36	1015	check for changes to an sql server table?	select checksum_agg(binary_checksum(*)) from sample_table with (nolock); 	0.0855151956754004
2120	11583	convert hashbytes to varchar	select substring(master.dbo.fn_varbintohexstr(hashbytes('md5', 'helloworld')), 3, 32) 	0.138579774571944
2702	29226	how do i use t-sql group by	select widgetcategory, count(*) from widgets group by widgetcategory having count(*) > 5 	0.696856292849772
3567	31247	sql to query a dbs scheme	selecttable_namefrominformation_schema.columnswherecolumn_name = 'desired_column_name'group bytable_name 	0.448296744835423
3682	2615	distribution of table in time	select * from (     select @rownum:=@rownum+1 as rownum, e.*     from (select @rownum := 0) r, entries e) as e2 where uid = ? and rownum % 150 = 0; 	0.00574217315942697
12533	24747	how do you convert the number you get from datepart to the name of the day?	select datename(weekday, getdate()); 	0
18413	26218	get a number from a sql string range	select substring(replace(interest , '<',''), patindex('%[0-9]%',replace(interest , '<','')), patindex('%[^0-9]%',replace(interest, '<',''))-1) from table1 	0
21489	10747	grouping runs of data	select n.name,      (select count(*)       from mytable n1      where n1.name = n.name and n1.id >= n.id and (n1.id <=         (         select isnull(min(nn.id), (select max(id) + 1 from mytable))         from mytable nn         where nn.id > n.id and nn.name <> n.name         )      )) from mytable n where not exists (    select 1    from mytable n3    where n3.name = n.name and n3.id < n.id and n3.id > (             select isnull(max(n4.id), (select min(id) - 1 from mytable))             from mytable n4             where n4.id < n.id and n4.name <> n.name             ) ) 	0.156215112999552
22474	40835	how do i display records containing specific information in sql	select * from table where table.title like '%lcs%'; 	6.94512772896077e-05
22935	9882	csv (or sheet in xls) to sql create (and insert) statements with .net?	select * into newtablennmehere from openrowset( 'microsoft.jet.oledb.4.0',  'excel 8.0;database=c:\testing.xls','select * from [sheet1$]') 	0.700393207956256
28196	19266	how to select posts with specific tags/categories in wordpress	select p.* from wp_posts p, wp_terms t, wp_term_taxonomy tt, wp_term_relationship tr, wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2 wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2 where p.id = tr.object_id and t.term_id = tt.term_id and tr.term_taxonomy_id = tt.term_taxonomy_id and p.id = tr2.object_id and t2.term_id = tt2.term_id and tr2.term_taxonomy_id = tt2.term_taxonomy_id and p.id = tr3.object_id and t3.term_id = tt3.term_id and tr3.term_taxonomy_id = tt3.term_taxonomy_id and (tt.taxonomy = 'category' and tt.term_id = t.term_id and t.name = 'category1') and (tt2.taxonomy = 'post_tag' and tt2.term_id = t2.term_id and t2.name = 'nuclear') and (tt3.taxonomy = 'post_tag' and tt3.term_id = t3.term_id and t3.name = 'deals') 	0.00523794734671501
29847	8249	get last item in a table - sql	select *  from historytable join (    select         max(id) as id.        batchref,        itemcount    from hsitorytable    where        bacthref = @batchref    group by        batchref,        itemcount  ) as latest on    historytable.id = latest.id 	0
35076	30957	strategy for identifying unused tables in sql server 2000?	select * from ... 	0.444310057428835
37275	12487	sql query for logins	select * from master..syslogins 	0.261711767693215
37743	29808	sql query to get the top "n" scores out of a list	select * from users where points in (select distinct top 3 points from users order by points desc) 	0
44046	663	truncate (not round) decimal places in sql server	select round(123.456, 2, 1) 	0.125263167127188
44181	13094	sql: select like column from two tables	select columna from table1 union select columnb from table2 order by 1 	0.00414925236680526
45535	16711	get month and year from a datetime in sql server 2005	select    convert(char(4), date_of_birth, 100) + convert(char(4), date_of_birth, 120)  from customers 	0
47762	31939	how-to: ranking search results	select * from `entries`  where token like "%x%" union all      select * from `entries`      where token like "%y%" union all          select * from `entries`          where token like "%z%" order by score ect... 	0.284338225809207
51969	38296	how to detect read_committed_snapshot is enabled?	select is_read_committed_snapshot_on from sys.databases where name= 'yourdatabase' 	0.5057676427293
52430	17288	sql server best way to calculate datediff between current row and next row?	select curr.*, datediff(minute, prev.eventdatetime,curr.eventdatetime) duration from dwlog curr join dwlog prev on prev.eventid = curr.eventid - 1 	0
54334	22215	how do i concatenate text in a query in sql server?	select cast(notes as nvarchar(4000)) + 'sometext' from notestable a 	0.104516248702961
54482	8002	how do i list user defined types in a sql server database?	select * from sys.types where is_user_defined = 1 	0.0163145959413066
56895	13836	proving sql query equivalency	select c1,c2,c3,         count(src1) cnt1,         count(src2) cnt2   from (select a.*,                 1 src1,                 to_number(null) src2            from a         union all         select b.*,                 to_number(null) src1,                 2 src2            from b        ) group by c1,c2,c3 having count(src1) <> count(src2); 	0.709763087011678
57243	8173	finding missing emails in sql server	select j.email  from jobseeker j where j.email not in (select email from aspnet_membership                       where email is not null) 	0.119957498346333
59425	27480	how do i find records added to my database table in the past 24 hours?	select * from messages where date_sub(curdate(),interval 1 day) <= messagetime 	0
60877	848	sql select bottom records	select t1.*  from (select top x id, title, comments, createddate from mytable where createddate > @olderthandate order by createddate) t1 order by createddate desc 	0.00545698909288963
66164	24946	how to write an sql query to find out which logins have been granted which rights in sql server 2005?	select dbrole = g.name, membername = u.name   from @name.sys.database_principals u, @name.sys.database_principals g, @name.sys.database_role_members m   where   g.principal_id = m.role_principal_id     and u.principal_id = m.member_principal_id     and g.name in (''db_ddladmin'', ''db_owner'', ''db_securityadmin'')      and u.name not in (''dbo'')   order by 1, 2 	0.0111888846235868
70455	28541	cross-server sql	select * from servername.dbname.schemaname.tablename 	0.462853915547349
71022	40309	sql max of multiple columns?	select     case         when date1 >= date2 and date1 >= date3 then date1         when date2 >= date1 and date2 >= date3 then date2         when date3 >= date1 and date3 >= date2 then date3         else                                        date1     end as mostrecentdate 	0.00504417624485145
73751	2296	what is the dual table in oracle?	select sysdate from dual; 	0.673238509335027
76680	10930	fetch unread messages, by user	select id, message from messages left join messages_read     on messages_read.message_id = messages.id     and messages_read.[user_id] = @user_id where     messages_read.message_id is null 	0.00829841395474284
80706	7853	query to find nth max value of a column	select dob from (select dob from users order by dob desc) where rowid = 6 	0
82929	15818	sort with one option forced to top of list	select name   from locations  order by case when name = 'montreal'               then 0              else 1            end         , name 	0.00124272136432124
85978	15647	query a table's foreign key relationships	select table_name from all_constraints where constraint_type='r' and r_constraint_name in    (select constraint_name   from all_constraints   where constraint_type in ('p','u')   and table_name='<your table here>'); 	0.00262347053322761
87747	35784	how do you determine what sql tables have an identity column programatically	select column_name, table_name from information_schema.columns where table_schema = 'dbo' and columnproperty(object_id(table_name), column_name, 'isidentity') = 1 order by table_name 	0.0269349450974473
92093	9199	removing leading zeroes from a field in a sql statement	select substring(columnname, patindex('%[^0]%',columnname), 10) 	0.036192819738667
95183	2441	how does one create an index on the date part of datetime field in mysql	select * from transactionlist  where trandatetime between '2008-08-17' and '2008-08-18'; 	0.000476904640630635
96952	36187	how to trim leading zeros from alphanumeric text in mysql function	select trim(leading '0' from myfield) from table 	0.0902102403006365
102591	16646	sql strip text and convert to integer	select substring(column, patindex('%[0-9]%', column), 999) from table 	0.080051742288507
102881	1506	how can i get datetime to display in military time in oracle?	select to_char(sysdate,'dd/mm/yyyy hh24:mi:ss') from dual; 	0.000565319525163615
103829	32452	t-sql: how do i get the rows from one table whose values completely match up with values in another table?	select a.pkid,b.otherid from  (select a.pkid,checksum_agg(distinct a.value) as 'valuehash' from @a a group by a.pkid) a  inner join (select b.otherid,checksum_agg(distinct b.value) as 'valuehash' from @b b group by b.otherid) b on a.valuehash = b.valuehash 	0
108281	38060	can i refactor my mysql queries into one query based on number of results?	select b from y where a=if(@value in (select a from y group by a),@value,0); 	0.000527434438242659
112892	28635	monthly birthday sql query	select c.name from cust c where (     month(c.birthdate) = month(@supplieddate)     and day(c.birthdate) = day(@supplieddate) ) or (     month(c.birthdate) = 2 and day(c.birthdate) = 29     and month(@supplieddate) = 3 and day(@supplieddate) = 1     and (year(@supplieddate) % 4 = 0) and ((year(@supplieddate) % 100 != 0) or (year(@supplieddate) % 400 = 0)) ) 	0.0364624954459043
113901	10615	how do i perform a case-sensitive search and replace in sql 2000/2005?	select testcolumn from testtable       where testcolumn collate latin1_general_cs_as = 'example'  select testcolumn from testtable     where testcolumn collate latin1_general_cs_as = 'example'  select testcolumn from testtable      where testcolumn collate latin1_general_cs_as = 'example' 	0.766182053127743
116163	6410	delphi: paradox db field name issue (spaces in field name)	select customers."street 1" from customers where ... 	0.466512543487739
117962	17330	simplest/efficient way to find rows with time-interval overlaps in sql	select *  from table1,table2  where table2.start <= table1.end  and (table2.end is null or table2.end >= table1.start) 	0.0121491805241152
118144	17469	what's the most efficient way to select the last n rows in a table without changing the table's structure?	select * from table_name order by auto_incremented_id desc limit n 	0
118443	443	selecting values grouped to a specific identifer	select user_id, max(score) from user_scores  group by user_id  order by max(score) desc  limit 5 	0.000120631902233645
119308	18903	how do i get a list of tables affected by a set of stored procedures?	select     [name] from     sysobjects where     xtype = 'u' and      id in     (         select              sd.depid          from              sysobjects so,             sysdepends sd         where             so.name = 'nameofstoredprocedure' and              sd.id = so.id     ) 	8.78844334882088e-05
120900	39372	how to check if a trigger is invalid?	select * from   all_objects where  object_name = trigger_name and    object_type = 'trigger' and    status <> 'valid' 	0.627928151994071
121387	21652	fetch the row which has the max value for a column	select userid,        my_date,        ... from ( select userid,        my_date,        ...        max(my_date) over (partition by userid) max_my_date from   users ) where my_date = max_my_date 	0
121581	39649	simplest way to create a date that is the first day of the month, given another date	select dateadd(month, datediff(month, 0, getdate()), 0) 	0
122302	36418	as system in sqlplus, how do i query another user's table?	select * from some_user.the_table; 	0.0229176949442957
123557	40116	in ms-sql, how do i insert into a temp table, and have an identity field created, without first declaring the temp table?	select *, identity( int ) as idcol   into #newtable   from oldtable 	0
124205	398	how can i do the equivalent of "show tables" in t-sql?	select table_name as "table name" from information_schema.tables where table_type = 'base table' and objectproperty  (object_id(table_name), 'ismsshipped') = 0 	0.0818127915590827
125976	5365	how to tell using t-sql whether a sql server database has the trustworthy property set to on or off	select is_trustworthy_on from sys.databases  where name = 'dbname' 	0.00284146373420615
126794	20723	find two consecutive rows	select top 1 *  from  bills b1 inner join bills b2 on b1.id = b2.id - 1 where b1.isestimate = 1 and b2.isestimate = 1 order by b1.billdate desc 	0.000119453398737848
129248	27315	many to many table queries	select t1.eid   from t t1  where t1.fid  = 'b'    and not exists        (select 1           from t t2          where t2.eid = t1.eid            and t2.fid  = 'a') 	0.0660344398257453
129861	12781	how can i query the name of the current sql server database instance?	select serverproperty ('instancename') 	0.000283963433712201
131014	33575	what's the sql query to list all rows that have 2 column sub-rows as duplicates?	select t.* from table t left join ( select col1, col2, count(*) as count from table group by col1, col2 ) c on t.col1=c.col1 and t.col2=c.col2 where c.count > 1 	0
132070	11017	how do i check that i removed required data only?	select table_catalog,table_schema,table_name,column_name,rc.* from information_schema.constraint_column_usage ccu,  information_schema.referential_constraints rc  where ccu.constraint_name = rc.constraint_name 	0.010087050835025
134958	17522	get top results for each group (in oracle)	select e.name, e.occupation  from emp as e    left outer join emp as e2      on (e.occupation = e2.occupation and e.emp_id <= e2.emp_id)  group by e.emp_id  having count(*) <= 3  order by e.occupation; 	0.000169940548185662
137398	28299	sql null set to zero for adding	select column1, column2, iif(isnull(column3),0,column3) + iif(isnull(column4),0,column4) as [added values] from table 	0.136051783751673
137803	13338	sql server, select statement with auto generate row id	select newid() as colid, col1, col2, col3 from table1 	0.00132015827741793
138261	9290	select query in sql + all the values in columns	select * from yourtable where     column1 is not null and column2 is not null and column3 is not null and .... 	0.000475640203294702
138419	15008	sql compact select top 1	select top(1) id  from tbljob  where holder_id is null 	0.174087637286003
144167	2726	how to format oracle sql text-only select output	select substr(assigner_staff_id, 8) as staff_id,        active_flag as flag,        to_char(assign_date, 'dd/mm/yy'),       to_char(complete_date, 'dd/mm/yy'),        mod_date from work where assigner_staff_id = '2096'; 	0.267249324734619
146531	16963	delete all but the 50 newest rows	select unixtime from entries order by unixtime desc limit 49, 1; delete from entries where unixtime < $sqlresult; 	7.37235705871713e-05
149690	7900	search for text between delimiters in mysql	select    substr(column,      locate(':',column)+1,        (char_length(column) - locate(':',reverse(column)) - locate(':',column)))  from table 	0.237858490947031
152024	25529	how to select all users who made more than 10 submissions	select userid from submission    group by userid having count(submissionguid) > 10 	5.57723703599871e-05
153585	39422	sql sub-query problem with grouping, average	select avg(total), customer  from orders o1  where orderdate in    ( select top 2 date      from orders o2      where o2.customer = o1.customer      order by date desc ) group by customer 	0.615761934031711
156329	10681	unwanted leading blank space on oracle number format	select to_char(1011,'fm00000000') ope_no from dual; 	0.156986987070413
156954	15919	search for words in sql server index	select *   from dbo.tblbusinessnames  where businessname like '%[^a-z^0-9]break%'      or businessname like 'break%'             	0.677756678120121
157114	36675	how to output a boolean in t-sql based on the content of a column?	select case when columnname is null then 'false' else 'true' end from tablename; 	0.000118576846713246
157459	7050	problem joining on the highest value in mysql table	select p.*, r.* from products as p   join revisions as r using (product_id)   left outer join revisions as r2      on (r.product_id = r2.product_id and r.modified < r2.modified) where r2.revision_id is null; 	0.000498753274400425
159769	17315	oracle rownum pseudocolumn	select rownum, a.*    from (<<your complex query including group by and order by>>) a 	0.460522784249013
160374	13488	tsql: how do i do a self-join in xml to get a nested document?	select [categoryid] as "@categoryid"       ,[categorydescription] as "@categorydescription"       ,(select [categoryid]        ,[categorydescription]        from [dbo].[taxonomy] "category"        where parentcategoryid = rootquery.categoryid        for xml auto, type) from [dbo].[taxonomy] as rootquery where [parentcategoryid] is null for xml path('category'), root('taxonomy') 	0.0510257823024925
161093	25315	do this with a single sql	select min(clndr_date) from [table] where (effective_date is not null)   and (clndr_date > (     select max(clndr_date) from [table] where effective_date is null   )) 	0.62160014398583
162399	2494	sql count query	select halid, count(halid) as ch from outages.faultsinoutages group by halid having count(halid) > 3 	0.415973364692942
167067	26056	mysql limit with many to many relationship	select i.itemcontent, group_concat(t.tagname order by t.tagname) as taglist from item as i    inner join itemtag as it on i.id = it.itemid    inner join tag as t on t.id = it.tagid group by i.itemid; 	0.193754006343975
168672	17581	how do i get back a 2 digit representation of a number in sql 2000	select replace(str(mycolumn, 2), ' ', '0') 	5.01476934060982e-05
170556	27316	maintaining consistency when using temp backup tables	select * from faultytable  except  select * from backuptable 	0.796221032590429
174516	30654	selecting a maximum order number in sql	select a.user, a.data, a.sequence from table as a     inner join (         select user, max(sequence) as 'last'         from table          group by user) as b     on a.user = b.user and         a.sequence = b.last 	0.000332362388907914
175733	38986	how can i create a mysql join query for only selecting the rows in one table where a certain number of references to that row exist in another table?	select movies.id, movies.title, count(ratings.id) as num_ratings    from movies    left join ratings on ratings.movie_id=movies.id    group by movies.id    having num_ratings > 5; 	0
175962	30839	dynamic select top @var in sql server	select top (@count) * from sometable 	0.490128025646031
176673	29006	how to get records after a certain time using sql datetime field	select * from mytable where datepart(hh, mydatefield) > 17 	0
177323	23597	how to read the last row with sql server	select top 1 * from table_name order by unique_column desc 	0.00172319411750981
179625	7299	in a select statement(ms sql) how do you trim a string	select ltrim(rtrim(names)) as names from customer 	0.0998005726970727
182544	4091	sql to find duplicate entries (within a group)	select     a.* from     event as a inner join     (select groupid      from event      group by groupid      having count(*) <> 5) as b   on a.groupid = b.groupid 	0.00011722627541477
184592	248	minus in mysql?	select topics.id from topics   inner join topic_tags topic_ptags     on topics.id = topic_ptags.topicfk   inner join tags ptags     on topic_ptags.tagfk = ptags.id       and ptags.name in ('a','b','c')   left join topic_tags topic_ntags     on topics.id = topic_ntags.topicfk   left join tags ntags     on topic_ntags.tagfk = ntags.id       and ntags.name in ('d','e','f') group by topics.id having count(distinct ptags.id) = 3   and count(ntags.id) = 0 	0.619803953848511
185520	35329	convert month number to month name function in sql	select datename(month, dateadd(month, @mydate-1, cast('2008-01-01' as datetime))) 	9.09075532155779e-05
186443	38139	what options are available for connecting to a microsoft sql server database from an oracle database?	select * from mytable@my_ms_sql_server; 	0.0641587250105734
187137	16338	how to output data from tables with same column names in codeigniter?	select type_of_source.description as type_of_source_description, origin.descripotion as origin_descripotion from .... 	0
188828	31648	sql - table alias scope	select t.*  from table t  join othertable o on t.nameid = o.nameid      and o.otherdesc in ('somedesc','someotherdesc'); 	0.650489300555142
188967	27313	how do i determine if a column is an identity column in mssql 2000?	select columnproperty(object_id('mytable'),'mycolumn','isidentity') 	0.032031038566498
190251	9088	in mysql, can you divide one alias, by another?	select columns, count(table2.rev_id) as rev_count, sum(table2.rev_rating) as sum_rev_rating, sum(table2.rev_rating)/count(table2.rev_id) as avg_rev_rating from table1 left join table2 on table1.dom_id = table2.rev_domain_from  where dom_lastreview != 0 and rev_status = 1  group by dom_url  order by avg_rev_rating desc 	0.0159363315998483
192028	38626	from string to blob	select item.title, group_concat( cast(concat_ws(',', attachments.id,  attachments.type, attachments.name ) as char ) ) as attachments  from story as item  left outer join story_attachment as attachments  on item.id = attachments.item_id group by item.id 	0.0438283173520815
193780	10935	how to find all the tables in mysql with specific column names in them?	select distinct table_name      from information_schema.columns     where column_name in ('columna','columnb')         and table_schema='yourdatabase'; 	0
196480	37895	identify full vs half yearly datasets in sql	select  @avgmonths = avg(x.[count]) from    ( select    cast(count(distinct datepart(month,                                                  dateadd(month,                                                          datediff(month, 0, dscdate),                                                          0))) as float) as [count]           from      hospdscdate           group by  hosp          ) x if @avgmonths > 7      set @months = 12 else      set @months = 6 select  'submitter missing data for some months' as [warningtype],      t.id from    thetable t where   exists ( select 1                  from   thetable t1                  where  t.id = t1.id                  having count(distinct datepart(month,                        dateadd(month, datediff(month, 0, t1.date), 0))) < @months ) group by t.id 	0.587425961661179
197033	34590	where is the oracle event log located?	select value from v$parameter where name = 'background_dump_dest' 	0.500070272592789
197099	33539	select specific rows with sql server xml column type	select id, loggeddata from mytable where datatype = 29 and  loggeddata.exist('rootnode/ns1:childnode[@value=sql:variable("@searchterm")]')=1 	0.00411122053637579
197291	18208	grouping by intervals	select count(*), round(mynum/3.0) foo from mytable group by foo; 	0.0383068320200826
198343	4456	how can i get the size of the transaction log in sql 2005 programmatically?	select (size * 8.0)/1024.0 as size_in_mb      , case   when max_size                                 = -1    then 9999999                     else (max_size * 8.0)/1024.0                  end as max_size_in_mb   from yourdbnamehere.sys.database_files  where data_space_id                            = 0 	0.018755204192914
199508	12609	how do i show running processes in oracle db?	select sess.process, sess.status, sess.username, sess.schemaname, sql.sql_text   from v$session sess,        v$sql     sql  where sql.sql_id(+) = sess.sql_id    and sess.type     = 'user' 	0.251825099628455
199953	478	how do you join on the same table, twice, in mysql?	select tod.dom_url as tourl,      fromd.dom_url as fromurl,      rvw.* from reviews as rvw left join domain as tod      on tod.dom_id = rvw.rev_dom_for left join domain as fromd      on fromd.dom_id = rvw.rev_dom_from 	0.00328937047028884
200430	32110	update column from another table - mysql 3.5.2	select concat(    'update products set products_ordered = ',     sum(products_quantity),    ' where product_id = ', products_id, ';') as sql_statement from orders_products group by products_id; 	0.000516488321053572
202245	11308	pure-sql technique for auto-numbering rows in result set	select id, name     , (select count(*) from people p2 where name='spiewak' and p2.id <= p1.id) as rownumber from people p1 where name = 'spiewak' order by id 	0.0268565765172536
203118	13202	week() function in sql script	select (datepart(dd,'2008-10-08')-1) / 7 + 1 	0.247266859352758
205797	37706	how to convert a sqlserver datetime to universal time using sql	select toutc([mydatecolumn], [mytimezonecolumn]) from [mytable] 	0.0312984600352177
206062	36498	mysql: view with subquery in the from clause limitation	select u1.name as username from message m1, user u1    where u1.uid = m1.userfromid group by u1.name having count(m1.userfromid)>3 	0.594657360182678
207337	39183	oracle v$osstat	select (select value from v$osstat where stat_name = 'busy_ticks') / (    nvl((select value from v$osstat where stat_name = 'idle_ticks'),0) +    nvl((select value from v$osstat where stat_name = 'busy_ticks'),0) +    nvl((select value from v$osstat where stat_name = 'iowait_ticks'),0) ) from dual; 	0.450055969112385
208874	21705	how to write a sql statement which gets results via a relationship table? (many to many)	select s.*  from section s inner join archive_to_section ats on s.id = ats.section_id  where ats.archive_id = 1 	0.0162909756109694
209615	32113	query a single value from a column that pulls multiple values	select distinct       pe.prodtree_element_name_l,      (select top 1 rs2.resource_value     from resource_shortstrings rs2     where rs2.language_id = '5'       and rs2.resource_key = pe.prodtree_element_name_l_rk) as "resource_value" from prodtree_element pe left join resource_shortstrings rs     on pe.prodtree_element_name_l_rk = rs.resource_key where rs.language_id = '5'     and pe.prodtree_element_name_l is not null 	0
209963	4624	finding entries in one mysql table based on conditions on another table	select distinct(hardware_name)  from hardware,incidents  where hardware.id = incidents.hardware_id and incidents.resolved=0; 	0
219833	32289	where are seed_value and increment_value for identity columns?	select c.name, i.seed_value, i.increment_value from sys.identity_columns i join sys.columns c     on i.object_id = c.object_id    and i.column_id = c.column_id 	0.00981219762242003
222217	27212	how do i determine if a column is in the primary key of its table? (sql server)	select k.table_name, k.column_name, k.constraint_name from information_schema.table_constraints as c join information_schema.key_column_usage as k on c.table_name = k.table_name and c.constraint_catalog = k.constraint_catalog and c.constraint_schema = k.constraint_schema and c.constraint_name = k.constraint_name where c.constraint_type = 'primary key' and k.column_name = 'keycol'; 	8.14886185776131e-05
222526	17133	how to search multiple columns of a table in mysql?	select * from person where code like '%part_of_code%' 	0.00111456250615175
223433	29854	how can i compare two datetime fields but ignore the year?	select * from table where month(fielda) > month(fieldb) or( month(fielda) = month(fieldb) and day(fielda) >= day(fieldb)) 	0
227457	9073	group by when joining the same table twice	select    location   ,sum(case when type = 'x' then 1 else 0 end) as xcount   ,sum(case when type = 'y' then 1 else 0 end) as ycount   ,sum(case when type = 'x' then duration else 0 end) as xcountduration   ,sum(case when type = 'y' then duration else 0 end) as ycountduration from my.table where  location = @location   and date(some_tstamp) = @date group by location 	0.00358589169647051
230058	16370	paginated query using sorting on different columns using row_number() over () in sql server 2005	select   orderid, customerid, employeeid, orderdate, shippeddate,   @offset, @limit, @sortcolumn, @sortdirection from   orders where   row_number() over    (     order by   ) between (@pagenum - 1) * @pagesize + 1 and @pagenum * @pagesize  order by   case when @sortdirection = 'a' then     case @sortcolumn        when 'orderid'    then orderid       when 'customerid' then customerid     end   end,   case when @sortdirection = 'd' then     case @sortcolumn        when 'orderid'    then orderid       when 'customerid' then customerid     end    end desc 	0.385978917320385
230081	20119	data length in ntext column?	select * from yourtable where datalength(ntextfieldname) > 0 	0.111675617430483
237302	33833	how to count unique records and get number of these uniques in table using sql?	select shop_id, count(1) from table_name   group by shop_id 	0
238380	40852	updating referenced columns in postgres	select table_name,column_name,constraint_name, referenced_table_name,referenced_column_name from  information_schema.key_column_usage where referenced_table_name = '<table>' and referenced_column_name = '<column>' 	0.0363010334315988
240582	14080	how do you or two like statements?	select col from db.tbl where (col like 'str1' or col like 'str2') and col2 = num 	0.596153522635915
243277	25473	aggregate greatest in t-sql	select sum(case when column1 > column2                   then column1                   else column2 end)   from test 	0.572443953688935
248753	7576	how do i do boolean logic on two columns in mysql, one of which is a varchar?	select *,        (payment1_paid && ((payment2_paid || (payment_type is not null && payment_type="none")))           as paid_in_full  from payments 	0.000377304329715818
249253	30294	select from different tables via sql depending on flag	select case @flag when 1 then t.field1 when 2 then t.field2 when 3     then t.field3 end as field,    [a bunch of other fields],    @flag as flag from table t 	0
251033	17207	how can i convert a varchar field of the form: yyyymmdd to a datetime in t-sql?	select convert(datetime, '20081030') 	0.000777591229198402
251278	23417	select one column distinct sql	select distinct a.value, a.attribute_definition_id,    (select top 1 value_rk from attribute_values where value = a.value) as value_rk from attribute_values as a order by attribute_definition_id 	0.00624989769126198
251902	4169	is there a way to do full text search of all oracle packages and procedures?	select name, line, text   from dba_source  where upper(text) like upper('%<<your_phrase>>%') escape '\' 	0.208442676047933
253324	9440	how can i get sql server column definition with parentheses and everything?	select data_type +      case         when data_type like '%text' or data_type like 'image' or data_type like 'sql_variant' or data_type like 'xml'             then ''         when data_type = 'float'             then '(' + convert(varchar(10), isnull(numeric_precision, 18)) + ')'         when data_type = 'numeric' or data_type = 'decimal'             then '(' + convert(varchar(10), isnull(numeric_precision, 18)) + ',' + convert(varchar(10), isnull(numeric_scale, 0)) + ')'         when (data_type like '%char' or data_type like '%binary') and character_maximum_length = -1             then '(max)'         when character_maximum_length is not null             then '(' + convert(varchar(10), character_maximum_length) + ')'         else ''     end as condensed_type     , * from information_schema.columns 	0.179642576558117
255517	13653	mysql offset infinite rows	select * from tbl limit 95, 18446744073709551615; 	0.0580022507628349
256282	14635	what is the best way to calculate page hits per day in mysql	select *, avg(hits / datediff(now(), created)) as avg_hits from entries where is_published = 1 group by id order by avg_hits desc limit 10 	0
258807	39633	sql server query against two linked databases using different collations	select    p.id,   p.projectcode_vc,   p.name_vc,   v.*  from   [serverb].projects.dbo.projects_t p    left join [servera].socon.dbo.vw_project v on p.projectcode_vc      collate latin1_general_bin = v.proj_code 	0.288015488573774
259486	9342	how do i query for foreign keys that don't match their constraints?	select * from tableorder where userid not in (select userid from tableuser); 	0
259547	27500	how does mysql store enums?	select mycolumn + 0 	0.590242701546251
260010	28041	is it possible to get the matching string from an sql query?	select substring(column,                  charindex ('news',lower(column))-10,                  20) from table  where column like %news% 	0.00350088274574946
260679	40641	is there an easy way to clone the structure of a table in oracle?	select dbms_metadata.get_ddl('table', 'table_name', 'schema_name') from dual 	0.419969311102803
265850	15588	how to query range of data in db2 with highest performance?	select * from table limit 5 and 20 	0.00386458165335671
266556	19042	how can i join an xml column back onto the record it originates from?	select blahid, xmlitems.blahitem.value('@name', 'nvarchar(100)') as blahitem from blah cross apply blahitems.nodes('/root/item') as xmlitems(blahitem) 	0.00418857856450114
267721	38623	mysql strip time component from datetime	select date(my_date) 	0.00416510945966485
267808	196	sql (mysql): match first letter of any word in a string?	select * from `articles` where `body` regexp '[[:<:]][acgj]' 	0.000125600248177524
268079	3695	search multiple list for missing entries	select c.chr, n.num from chars c, nums n  where not exists (select 1                      from mix m                     where m.chr = c.chr and m.num = n.num) 	0.00192690602652935
270190	14913	finding unique table/column combinations across sql databases	select      d1.table_name,      d1.column_name from      database1.information_schema.columns d1 left outer join database2.information_schema.columns d2 on      d2.table_name = d1.table_name and      d2.column_name = d1.column_name left outer join database3.information_schema.columns d3 on      d3.table_name = d1.table_name and      d3.column_name = d1.column_name left outer join database4.information_schema.columns d4 on      d4.table_name = d1.table_name and      d4.column_name = d1.column_name where      d2.table_name is null and      d3.table_name is null and      d4.table_name is null 	0.001119788659287
273009	26711	ms sql: convert datetime column to nvarchar	select convert(nvarchar(10), getdate(), 103) 	0.124220180884816
278777	33576	t-sql : using { fn now() } in where	select {fn current_timestamp()} as "date & time",        {fn current_date()} as "date only",        {fn current_time()} as "time only" ; 	0.717464611618519
279431	13138	using sql to determine cidr value of a subnet mask	select concat(inet_ntoa(ip_addr),'/',32-log2((4294967296-ip_mask))) net  from subnets  order by ip_addr 	0.0135909169105377
285162	5308	how do i query for the state of a session variable in pl/sql?	select sys_context( 'userenv', 'current_schema' ) from dual; 	0.151263780112904
285394	18727	oracle sql: multiple sums dependent on code in one statement	select t.location,    l.city,    f.year,    f.customer,   sum( nvl( case when t.code ='c' then t.sale_quantity else 0 end, 0)) sale_quantity from loc t, location l, father_table f  where f.number = t.number(+)  and f.code = '0001'  and f.c_code = '01'  and t.location= l.code(+)  and t.code in ('c', 's')  and t.co_code in ('g', 'v', 'a', 'd')  and t.year = '2008'  group by t.location, l.city, f.year order by l.city, f.year 	0.231714242568402
285666	23200	how to set a default row for a query that returns no rows?	select val from mytable union all select 'default' from dual where not exists (select * from mytable) 	0.000184592061541538
286039	27795	get record counts for all tables in mysql database	select sum(table_rows)       from information_schema.tables       where table_schema = '{your_db}'; 	0
287105	36161	mysql strip non-numeric characters to compare	select * from foo where bar like = '%1%2%3%4%5%' 	0.0244565961781823
287333	16544	sql: select "until"	select d.id, d.size, d.date_created from documents d inner join documents d2 on d2.tag_id=d.tag_id and d2.date_created >= d.date_created where d.tag_id=26 group by d.id, d.size, d.date_created having sum(d2.size) <= 600 order by d.date_created desc 	0.0612640782081214
289680	26689	difference between 2 dates in sqlite	select julianday('now') - julianday(datecreated) from payment; 	0.000936367477021536
291574	23283	query to list sql server stored procedures along with lines of code for each procedure	select t.sp_name, sum(t.lines_of_code) - 1 as lines_ofcode, t.type_desc from (     select o.name as sp_name,      (len(c.text) - len(replace(c.text, char(10), ''))) as lines_of_code,     case when o.xtype = 'p' then 'stored procedure'     when o.xtype in ('fn', 'if', 'tf') then 'function'     end as type_desc     from sysobjects o     inner join syscomments c     on c.id = o.id     where o.xtype in ('p', 'fn', 'if', 'tf')     and o.category = 0     and o.name not in ('fn_diagramobjects', 'sp_alterdiagram', 'sp_creatediagram', 'sp_dropdiagram', 'sp_helpdiagramdefinition', 'sp_helpdiagrams', 'sp_renamediagram', 'sp_upgraddiagrams', 'sysdiagrams') ) t group by t.sp_name, t.type_desc order by 1 	0.000608388837381776
294705	20021	sql query to get greatest distinct date - kind of	select t.tag, max(a.date_time) as latest from articles a inner join articletags t on t.id = a.id group by t.tag 	0.00774518799323802
295232	35181	how to make a sql query "you are better than xx percent of other users" for mssql2000	select (count(*)/(select cast(count(*) as float) from users))*100 from users where score < (select score from users where user = 'john') 	0.000313789215060625
297465	28337	how do you programatically identify a stored procedure's dependencies?	select lvl      , u.object_id      , u.object_type      , lpad (' ', lvl) || object_name obj    from ( select level lvl, object_id             from sys.public_dependency s          start with s.object_id =                       ( select object_id                           from user_objects                          where object_name = upper ('&object_name')                            and object_type = upper ('&object_type'))          connect by s.object_id = prior referenced_object_id          group by level, object_id) tree       , user_objects u   where tree.object_id = u.object_id order by lvl / 	0.447738138119186
301817	1844	how to select a related group of items in oracle sql	select distinct key, id, link   from the_table   start with id = 'aa'   connect by id = 'master' and link = prior link and 'aa' = prior id 	0.00123343505195386
302452	31479	calculate the last day of the quarter	select dateadd(day, -1, dateadd(qq, datediff(qq, 0, @date), 0)) 	0
303404	20533	help with distinct rows and data ordering	select t1.* from table t1   join (select max(date), locationid         from table         group by date, locationid) t2 on t1.date = t2.date and t1.locationid = t2.locationid 	0.19134538912102
304129	27337	how do you return a constant from an sql statement?	select 'my message'; 	0.0385987022367753
304940	28725	how to choose returned column name in a select for xml query?	select( select col1  from table1  where col2 = 'x'  order by col3  for xml path('') ) as myname 	0.00276855128864727
306743	23966	how to detect duplicate rows in a sql server table?	select     col1,      col2,      col3,      col4,     col5,     col6,     col7,     col8,     col9,     col10 from     mytable group by     col1,     col2,     col3,     col4,     col5,     col6,     col7,     col8,     col9,     col10 having     count(*) > 1 	0.00159995658939199
306788	24882	sql date comparison	select (cast(floor(cast(getdate() as float)) as datetime)) 	0.298167042061746
307941	39956	how can i get the database name from a perl mysql dbi handle?	select database(); 	0.00659794852594407
309930	33105	select with ors including table joins	select    *  from    books    left outer join keywordslink on keywordslink.bookid = books.copyid    left outer join keywords on keywords.id = keywordslink.keywordid  where books.title like '%joel%'        or keywords.name like '%good%' 	0.677074268402275
314998	9831	sql server 2005 drop column with constraints	select      col.name,      col.column_id,      col.default_object_id,      objectproperty(col.default_object_id, n'isdefaultcnst') as is_defcnst,      dobj.name as def_name from sys.columns col      left outer join sys.objects dobj          on dobj.object_id = col.default_object_id and dobj.type = 'd'  where col.object_id = object_id(n'dbo.test')  and dobj.name is not null 	0.192501633106392
315196	36473	sql join to find inconsistencies between two data sources	select * from report_1 r1  full outer join report_2 r2      on r1.samaccountname = r2.samaccountname     or r1.netbiosname = r2.netbiosname     or r1.displayname = r2.displayname where r2.netbiosname is null or r1.netbiosname is null 	0.00302827692899935
315621	24513	mysql: how to select all rows from a table except the last one	select * from table where id != (select max(id) from table) 	0
316295	17142	need help joining table	select a.lname, a.fname,a. email, a.address1,a. address2, a.city,      a.state, a.zip, a.venue_id, a.dtelephone, a.etelephone, a.tshirt,     coalesce(b.venue_name,'') as venuename from volunteers_2009 a left join venues b on b.id=a.venue_id 	0.773013024240118
316916	32755	is it possible to use containstable to search for "word1" in column1 and "word2" in column2	select     sometable.*,         col1.rank + col2.rank from      sometable inner join containstable(sometable, column1, 'word1 or word2') as col1 on      col1.[key] = sometable.id inner join containstable(sometable, column2, 'word3 or word4') as col2 on      col2.[key] = sometable.id 	0.347675547687007
317576	11593	oracle - select where field has lowercase characters	select id, first, last from mytable where first != upper(first) or last != upper(last); 	0.0537650607240641
319262	34396	can sql calculate aggregate functions across multiple tables?	select owner, sum(num_dogs), sum(num_cats) from   (select owner, 1 as num_dogs, 0 as num_cats from dogs    union    select owner, 0 as num_dogs, 1 as num_cats from cats) group by owner 	0.160270775611973
323294	21451	datatype of sum result in mysql	select cast(sum(price) as signed) from cakes where ingredient = 'marshmallows'; 	0.0449900978668056
324949	15330	writing comments table in database	select * from comment c join commenteditem ci on c.commenteditemid = ci.commenteditemid join friend f on f.commenteditemid = ci.commenteditemid where f.friendid = @friendid 	0.077435921243457
327010	4807	using a vector of column names, to generate a sql statement	selectsql  = "select "; selectsql += columns[0]._name; for (z = 1; z < columns.size(); z++) {    selectsql += ", ";    selectsql += columns[z]._name; } selectsql += " from some-table"; 	0.00259815613002991
327366	2630	join two tables into one big table	select col1, col2, col3  into table1 from table2 	0.000748415052978336
329822	29084	mysql strict select of rows involving many to many tables	select b_id from ab where a_id in (1,2,3) group by b_id having count(distinct a_id) = 3; 	0.00257741870897135
330612	6432	sql find non-null columns	select      case when exists (select * from series where t_stamp between @x and @y and field1 is not null) then 1 else 0 end as field1,      case when exists (select * from series where t_stamp between @x and @y and field2 is not null) then 1 else 0 end as field2, ... 	0.00259008903555358
332558	31701	version control algorithm	select myobjects.id,value from myobjects inner join  (         select id, max(generationid) as lastgen   from myobjects   where generationid <= @targetgeneration   group by id ) t1 on myobjects.id = t1.id and myobjects.generationid = lastgen where deleteaction = 'false' 	0.506496258502459
332668	5720	is the table in use?	select spid     from master..sysprocesses     where dbid = db_id('works') and spid <> @@spid 	0.216303818674944
334108	35741	how do i check if a sql server string is null or empty	select    isnull(nullif(listing.offer_text, ''), company.offer_text) as offer_text from ... 	0.263607856562429
334698	12904	compare result of 'as' expression in 'where' statement	select (mytable.field1 + 10) as x from `mytable` where (mytable.field1 + 10) < 50; 	0.345230189063074
335805	40943	how can i synchronize views and stored procedures between sql server databases?	select * from sys.syscomments 	0.556331787798269
335951	40341	providing mysql users with just the minimum privileges	select * from mytable, mytable, mytable, mytable, mytable order by 1; 	0.0133355427066111
339100	55	how do i get rid of .. replace(replace(replace(replace(replace( …?	select substring(fieldname, patindex('%[0-9][0-9][0-9][0-9]%', fieldname), 4) from tablename 	0.506802049205698
340020	25247	mysql - how to use index in where x in (<subquery>)	select employees.* from   employees, clients where  employees.client_id = clients.id and    clients.name like 'a%'; 	0.717153570741328
343900	23889	selecting rows where first n-chars are equal (mysql)	select name from players p1 where exists (   select 1 from players p2 where      p2.name like concat( substring(p1.name, 1, 3), '%')      and p1.name <> p2.name ) 	9.80837447407551e-05
346568	15497	how to query for 10 most recent items or items from last month, whichever is more?	select * from posts order by timestamp desc limit 100 	0
346659	4370	what are the most common sql anti-patterns?	select     firstname + ' ' + lastname as "full name",     case userrole         when 2 then "admin"         when 1 then "moderator"         else "user"     end as "user's role",     case signedin         when 0 then "logged in"         else "logged out"     end as "user signed in?",     convert(varchar(100), lastsignon, 101) as "last sign on",     datediff('d', lastsignon, getdate()) as "days since last sign on",     addrline1 + ' ' + addrline2 + ' ' + addrline3 + ' ' +         city + ', ' + state + ' ' + zip as "address",     'xxx-xx-' + substring(         convert(varchar(9), ssn), 6, 4) as "social security #" from users 	0.002958939492325
349260	17338	mysql tool or query that suggests table structure	select * from `table_name` procedure analyse ( ) 	0.112668908684307
349559	36267	sql how to search a many to many relationship	select * from notes where note_id in ( select note_id from labels where label = 'one'   intersect   select note_id from labels where label = 'two' ) 	0.0725555802009143
352503	29370	sql query for master-detail	select m.personname, c.coursename from   master m join   detail d on d.masterid = m.id join   course c on c.id = d.courseid where  d.startdate = (select max(d2.startdate)                       from   detail d2                       where  d2.masterid = m.id                      ) 	0.555086068017054
353132	39912	how to check if not null constraint exists	select is_nullable  from   sys.columns where  object_id = object_id('tablename')   and    name = 'columnname'; 	0.0646364385679417
353948	21948	summary query from several fields in sql	select years, sum(1*(1-abs(sign(id1-56)))) as id1, sum(1*(1-abs(sign(id2-56)))) as id2, sum(1*(1-abs(sign(id3-56)))) as id3, sum(1*(1-abs(sign(id4-56)))) as id4, from mytable group by years 	0.0162416939764315
354224	25760	combining union all and order by in firebird	select c1, c2, c3 from (     select c1, c2, c3 from t1     union all      select c1, c2, c3 from t2 ) order by c3 	0.0484315179470598
355538	38830	utf 8 from oracle tables	select value from nls_database_parameters  where parameter='nls_characterset' 	0.192356143467811
357244	3890	sql server 2005 date time stamp query	select * from yourtable where dateregistered between '10/22/2008 18:00:00' and '10/22/2008 20:00:00' 	0.0740463098047901
360615	24058	mysql - embed count query within another query	select a.stage_name, count(b.id) from authors a   left outer join books b on (a.id = b.author_id) group by a.id; 	0.0792966876866083
360961	20559	mysql query, select greater than	select id,question from `questions`  where `sort_order` > sort_order_variable order by sort_order asc  limit 1 	0.0899935881836347
361135	34226	sql query advice - most recent item	select      t1.prodid,      t1.issue from      sales t1 left outer join dbo.sales t2 on      t2.custid = t1.custid and      t2.prodid = t1.prodid and      t2.datesold > t1.datesold where      t1.custid = @custid and      t2.custid is null 	0.00579385758170543
361477	38383	mysql: joining tables + finding records with an and style query, rather than or	select user_id from skills where skill_id in (51, 52, 53, 54, 55) group by user_id having count(*) = 5; 	0.0506143576244952
363838	15337	sql user defined function within select	select dbo.getbusinessdays(a.opendate,a.closedate) as businessdays from account a where... 	0.409190687603936
364292	31473	sql server 2005 - select top n plus "other"	select * from (     select top 5          columnb, columna      from          sometable t     order by         columna desc     union all     select       null, sum(columna)      from          sometable t     where primarykey not in   (      select top 5           primarykey      from           sometable t      order by          columna desc     )   ) a 	0.00307687210708853
368351	28925	what's the best way to select the minimum value from multiple columns?	select id,        case when col1 < col2 and col1 < col3 then col1             when col2 < col1 and col2 < col3 then col2              else col3             end as themin from   yourtablenamehere 	0
369151	33681	error in retrieving and binding to a datagridview from a mysql stored procedure with concat()	select concat(column1, column2) as concatenated from table1 	0.773636051688978
371372	12874	mysql full text search is empty	select * from notes where match(title, body) against('test' in boolean mode) 	0.773179848491185
372114	14858	serializing objects as blobs in oracle	select count(*) from hashmaps where mapid = ? and key = ? 	0.776991435568231
372399	3655	how do you do many to many table outer joins?	select * from foo   left outer join (foo2bar join bar on (foo2bar.bid = bar.bid and zid = 30))   using (fid); 	0.696983889377071
372934	23344	how do i join to a "fixed vector" in sql?	select data.period, p.profit from ( select 1 as period union select 2 ... union select 24) as data  left join projections p on data.period = p.period 	0.144557689047088
375262	21657	sql query for finding representative rows in a table	select * from payments p where not exists (     select *     from payments p2     where p2.customerid = p.customerid     and   p2.value > p.value ) 	0.00526932581989285
377023	8231	sql server replication - get last synchronization date from query	select * from msmerge_sessions 	0.00190002855348627
381323	11075	how to look for a certain pattern within a database field?	select * from table where field like 'c[0-9]%' 	0.000378500093921898
383634	3471	looking for advice on a "related videos" query on a tagged video system	select v2.video_id from videotags as v1   join videotags as v2   using (tag_id) where v1.video_id = ?   and v1.video_id <> v2.video_id group by v2.video_id  order by count(*) desc; 	0.788857810056002
385441	6946	sql a numbering column - mysql	select @rownum:=@rownum+1 rownum, t.*from (select @rownum:=0) r, mytable t; 	0.0537969242292767
386795	29308	select top 1000, but know how many rows are there?	select top 1000 x,y,z, count(*) over () as totalcount from dbo.table 	0.000685750798147827
388687	4405	sql query for product-tag relationship	select tags.id, tags.name, tags.sortorder, tags.parentid,        count(distinct producttags.productid) as productcount,         count(distinct childtags.id) as childtagcount from tags left outer join producttags on tags.id = producttags.tagid left outer join tags childtags on tags.id = childtags.parentid group by tags.id, tags.name, tags.sortorder, tags.parentid 	0.427405760201851
388763	36468	select on a nullable reference	select "authors"."id", "authors"."name", "styles"."name", "authors"."comments" from  "authors" , "styles" where "authors"."style" = "styles"."id" union select "authors"."id", "authors"."name", "", "authors"."comments" from  "authors" where "authors"."style" is null 	0.0434368541686945
390814	38134	mysql autogenerate statistics fram data	select     year(my_date) as my_year,      month(my_date) as my_month,      sum(distance) / sum(timefordistance) as velocity  from your_table  group by my_year, my_month order by my_year, my_month 	0.0861647824229856
391744	36247	retrieving data on separate sql servers	select * from myremoteserver.mydb.dbo.mytable 	0.00344391728208759
394041	19065	mysql: how to search multiple tables for a string existing in any column	select * from table1 where match(col1, col2, col3) against ('some string') union all select * from table2 where match(col1, col2) against ('some string') union all select * from table3 where match(col1, col2, col3, col4) against ('some string') ... 	0.00432180035164817
395973	18969	mysql schedule conflicts	select * from shifts s1 and shiftstart between  from_unixtime('$startday') and from_unixtime('$endday') and user_id not in ($busy_users)  and (time_to_sec(timediff(shiftend,shiftstart)) = '$swap_shift_length') and (select count(1) from shifts s2      where s2.user_id = $joes_user_id      and   s1.shiftstart < s2.shiftend      and   s2.shiftstart < s1.shiftend) = 0 order by shiftstart, lastname 	0.497801086828901
397384	38930	mysql finding subtotals	select    i1.id as id1,    null as id2,    null as id3,    i1.amount from    items i1 union all select    i1.id as id1,    i2.id as id2,    i3.id as id3,    i1.amount + i2.amount as total from    items i1,    items i2 where    i1.amount + i2.amount = 30 and    i1.id <> i2.id and    i1.id <> i3.id union all select    i1.id as id1,    i2.id as id2,    i3.id as id3,    i1.amount + i2.amount + i3.amount as total from    items i1,    items i2,    items i3 where    i1.amount + i2.amount + i3.amount = 30 and    i1.id <> i2.id and    i1.id <> i3.id and    i2.id <> i3.id 	0.120986964048844
399567	34747	how do i compare overlapping values within a row?	select * from appts  where timestart <='$timeend'  and timeend >='$timestart'  and dayappt='$boatdate' 	8.22764347022388e-05
402980	30726	how to find the next record after a specified one in sql?	select id from table where fruit > 'apples' order by fruit limit 1 	0
406351	14289	t-sql: convert '0110' to 6	select (8 * convert(int, substring(@x, 1, 1)))      + (4 * convert(int, substring(@x, 2, 1)))      + (2 * convert(int, substring(@x, 3, 1)))      + (1 * convert(int, substring(@x, 4, 1))) 	0.0713984553628202
411624	19476	summation of second table grouped by results of first table	select      table_a.id,      table_a.date,     sum( table_b.amount ) as amount from table_a inner join table_b  on table_b.id = table_a.id where table_a.table_c_id = 123 group by table_a.id,      table_a.date 	0
414222	35926	selecting most recent date between two columns	select id,        case when date1 > date2 then date1             else date2        end as mostrecentdate from table 	0
416368	37935	combine 2 counts with different where on the same table	select sum(if(status=0,1,0)) as zeros,         sum(if(status>0,1,0)) as greater  from tbl; 	0
420722	22659	how can i identify unused/redundant columns given a list of tables?	select t.tabschema, t.tabname, c.colname   from sysstat.tables t, sysstat.columns c   where ((t.tabschema = 'myschema1' and t.tabname='mytable1') or          (t.tabschema = 'myschema2' and t.tabname='mytable2') or          (...)) and        t.tabschema = c.tabschema and t.tabname = c.tabname and       t.card = c.numnulls 	0
421509	20728	sql help: how can i add quantities together?	select category.category_name, sum((equipment.total_stock-equipment.stock_out)) as current_stock, sum(equipment.stock_out) as stock_out from equipment, category  where equipment.category_id = category.category_id and category.category_name = 'power tools' group by category.category_name 	0.69323182488713
421973	18656	will oracle optimizer use multiple hints in the same select?	select     e1.first_name, e1.last_name, j.job_id, sum(e2.salary) total_sal   from employees e1, employees e2, job_history j where e1.employee_id = e2.manager_id   and e1.employee_id = j.employee_id   and e1.hire_date = j.start_date group by e1.first_name, e1.last_name, j.job_id   order by total_sal; 	0.348240450053122
425020	37707	sql distinct by id and latest by date	select * from workitems w join ( select     [system.id],max([system.reviseddate]) from workitems where ([system.workitemtype] = 'change request')  and ([system.createddate] >= '09/30/2008')  and ([system.teamproject] not like '%deleted%')  and ([system.teamproject] not like '%sandbox%') group by {system.id] ) x on w.[system.id] = x.[system.id] and w.[system.daterevised] = x.[system.daterevised] 	0.000138820197830719
427549	30828	best approach to sql server query using distinct	select * from tablea  join (select distinct ida from tableb where date = '20090110') a on a.ida = tablea.ida order by tablea.ida 	0.593356752242555
428458	2405	counting rows for all tables at once	select      [tablename] = so.name,      [rowcount] = max(si.rows)  from      sysobjects so,      sysindexes si  where      so.xtype = 'u'      and      si.id = object_id(so.name)  group by      so.name  order by      2 desc 	0
428960	5727	how do i return multiple datatables from a sql server stored procedured?	select * from foo select * from bla 	0.0474704221273305
429684	13201	using the results of a query in openquery	select sql.pidm,sql.field2 from sqltable as sql inner join (select pidm,field2 from oracledb..schema.table) as orcl on  sql.pidm = orcl.pidm 	0.168183539565444
429745	26776	what is the best way to check for the existence of a login in sql server 2005	select * from master.sys.syslogins where [name] ='loginname' 	0.0448108610563403
430000	6510	sql exclude like items from table	select fieldname from tablename left join tablename2 on upper(columnname) like tablename2.fieldname2 + '%' where tablename2.fieldname2 is null 	0.00159891937774616
430922	19853	how to calculate difference between tables in mysql?	select a.id from a left join b on a.id = b.id where b.id is null select b.id from b left join a on b.id = a.id where a.id is null 	0.000619268106581145
431511	9065	determine if table exists in sql server ce?	select * from information_schema.tables where table_name = 'tablename' 	0.4101110295921
431571	17543	concat in mysql with condition	select ifnull(company_name,concat(first_name,' ',last_name)) as name 	0.614874816656062
433903	11496	how many rows in mysql database table?	select count(*) from table 	0.00395817744893584
434374	39691	another sql tutorial question: field > 0?	select region, name, population   from bbc x  where population >= all     (select population        from bbc y       where y.region = x.region         and population is not null) 	0.441548252169665
437617	9784	joining 2 columns from table1 to table 2	select w.*, s1.stateid as wstate, s2.stateid as cstate from weddings as w inner join states as s1 on w.weddingstate = s1.stateid inner join states as s2 on w.contactstate = s2.stateid where w.weddingid="094829292"; 	0
438776	13395	simplest way to get the number of calls to an mssql2000 server	select cntr_value  from sysperfinfo  where object_name = 'sqlserver:sql statistics'  and counter_name = 'batch requests/sec' 	0.00801410895045808
443588	31493	count stored procedures in database?	select count(*) from sysobjects where xtype = 'p' 	0.296947463098527
444523	13926	sql server 2000 - query a table’s foreign key relationships	select o2.name from sysobjects o inner join sysforeignkeys fk on o.id = fk.rkeyid inner join sysobjects o2 on fk.fkeyid = o2.id where o.name = 'foo' 	0.0346314256204374
444544	36410	mysql date/time calculation	select col1, col2, col3  from records  where (records.startdate between now() and adddate(now(), interval 9 hour))  and (records.status = '0'); 	0.298168437394542
444673	29169	sql - use results of a query as basis for two other queries in one statement	select count(*) as totaloccurs, count(@conditions@) as suboccurs from (@total@ as t1) 	0.00167662237380813
444976	22789	sql/t-sql - how to get the max value from 1 of n columns?	select case when dt1 > dt2 and dt1 > dt3 then dt1              when dt2 > dt3 then dt2 else dt3 end  from tablename 	0
445481	27532	grouping sql data in mysql side, or php?	select r.registration_id, p.* from registration_people rp, registrations r, person p where and rp.registration_id = r.id and p.id = rp.person_id 	0.414649665822262
448401	36601	how can i use transactions that span procedures chained across multiple servers?	select linked.fieldname from server.database.dbo.table as linked 	0.179557387585976
450159	28793	query a database from a search with empty values	select * from mytable  where (@name is null or name = @name) and (@fruit is null or fruit = @fruit) 	0.00959652533377782
451922	10056	how do i grep through a mysql database?	select * from columns where table_name like '%tablename%' and column_name like '%columnname%' 	0.132848609461917
452472	35312	execute count(*) on a group-by result-set	select count(*) from     (select distinct(somecolumn)        from mytable       where something between 100 and 500       group by somecolumn) mytable 	0.223195256667476
455657	21155	how to make a query to a table generated by a select?	select count(subadd.address)  from (select name, address, phone, from user) as subadd; 	0.025552499637544
455924	28745	is using null to represent a value bad practice?	select m.id, r.id as relatedtableid,.... from mytable m inner join myrelated table r on r.mytableid = m.id union select m.id, r.id as relatedtableid,.... from mytable m, myrelatedtable r where r.relatedall = 1 	0.520222353408857
457257	33744	how to select a set number of random records where one column is unique?	select top 5 *  from    (       select row_number() over(partition by team order by team) as rn, *       from @t       ) t where rn = 1 order by newid() 	0
463295	8867	java - ibatis - mysql with dynamic query based on role	select *       from employee a <isnotempty property="role" >    inner join secure_list b on b.employeeid = a.employeeid </isnotempty> <dynamic prepend="where">       <isnotempty property="role" prepend="and">            b.role_id = #role#       </isnotempty> </dynamic> 	0.266210928856098
466856	39714	convert string to uniqueidentifier in vbscript	select top 1 convert(uniqueidentifier, opensession) from opensessions with (nolock) 	0.376091997237319
467329	26842	selecting the distinct values from three columns with the max of a fourth where there are duplicates	select max(n), a, b, c from mytable group by a, b, c 	0
468664	37371	how can i find if a column is auto_increment in mysql?	select * from columns where  table_schema='yourschema' and table_name='yourtable' and extra like '%auto_increment%' 	0.0275070031942774
469318	37666	t-sql, updating more than one variable in a single select	select @var1 = avg(somecolumn), @var2 = avg(othercolumn)  from thetable 	0.0180599535932114
469338	19415	get the latest row from another table in mysql	select news.*, comments.name, comments.posted, (select count(id) from comments where comments.parent = news.id) as numcomments from news left join comments on news.id = comments.parent and comments.id = (select max(id) from comments where parent = news.id) 	0
472443	33830	sqlserver function for single quotes	select quotename(fieldname, char(39)) 	0.63806325173515
472732	39538	how to group ranged values using sql server	select     max(t1.gapid) as gapid,     t2.gapid-max(t1.gapid)+t2.gapsize as gapsize from   (      select gapid     from gaps tbl1      where       not exists(         select *         from gaps tbl2          where tbl1.gapid = tbl2.gapid + tbl2.gapsize + 1       )   ) t1   inner join (      select gapid, gapsize     from gaps tbl1      where       not exists(         select * from gaps tbl2          where tbl2.gapid = tbl1.gapid + tbl1.gapsize + 1       )   ) t2 on t1.gapid <= t2.gapid  group by t2.gapid, t2.gapsize 	0.463312958933812
476016	21231	sql joining a few count(*) group by selections	select n, count(*) as freq from  (   select n1 as n from lottery   union all   select n2 from lottery   union all   select n3 from lottery   union all   select n4 from lottery   union all   select n5 from lottery   union all   select n6 from lottery ) as transposed group by n order by count(*) desc 	0.293997815155648
480742	10877	select parent record with all children in sql	select parent.parentid, count(*) from parent inner join childparent     on childparent.parentid = parent.parentid inner join child     on childparent.childid = child.childid where <childfiltercriteria> group by parent.parentid having count(*) = (     select count(child.childid)     from child where <childfiltercriteria> ) 	9.29573418594571e-05
482473	36140	sql latest record per foreign_key	select i.*, p1.* from ingredients i  join ingredient_prices p1 on (i.id = p1.ingredient_id)  left outer join ingredient_prices p2 on (i.id = p2.ingredient_id     and p1.created_at < p2.created_at) where p2.id is null; 	0.000232734034551704
486270	23100	what's the most efficient way to check the presence of a row in a table?	select count(1) from mytable where id = 5 	0
487515	29925	sql union and order by	select case                  when exists (select email from companies c where c.id = u.id and c.email = u.email) then 1                  else 2 end as sortmefirst,   *      from users u      where companyid = 1      order by sortmefirst 	0.529574952556768
488062	24990	merging results in t-sql statement	select     coalesce(p.id, c.id),     coalesce(p.name, c.name),     p.num as pending,     c.num as completed,     coalesce (p.num, 0) + coalesce (c.num, 0) as total from     pending p     full outer join     completed c on p.id = c.id 	0.247165465712659
489116	14164	how to sum columns from two result sets in mysql	select sum(case when rating_type = 'up' then 1 when rating_type = 'down' then -1 end case) from posts group by post_id 	0.00010725887173083
489904	18024	mysql add total column	select concat(u.firstname, ' ', u.lastname ) name, u.id,    s.description, s.shiftstart, s.shiftend,    sum( time_to_sec( timediff( shiftend, shiftstart ) ) ) /3600 total from shifts s inner join users u on ( s.id = u.id ) where s.id = ? and date( shiftstart ) between ? and ? group by u.id, s.shiftstart with rollup order by shiftstart; 	0.00136639988408582
491345	41134	sql produced by entity framework for string matching	select * from customer where emaildomain like 'abc%de%sss%' 	0.683425656502136
491454	33992	random numbers from database	select top 500     convert(int, convert(varbinary(16), newid())) from     dbo.mytable 	0.00186023006302012
491838	38911	serialize oracle row to xml	select dbms_xmlgen.getxmltype ('select * from &table_name where rowid = ''&rowid''' )   from dual 	0.139514162896619
492204	18389	how to locate rows in sql table where xpath	select * from table t where charindex('id="' + cast(t.id as varchar) + '"',t.xml) = 0 	0.133590829685593
492613	39249	dynamically changing what table to select from with sql case statement	select itemnumber, itemtype, description   from tablea  where itemnumber = @itemnumber and itemtype = 'a' union all select itemnumber, itemtype, description   from tableb  where partnumber = @itemnumber and itemtype <> 'a' 	0.513429472008034
495098	6872	retrieving a list of blog posts with related tags with less query	select   it.itemid,   it.title [itemtitle],   tg.tagid,   tg.title [tagtitle] from item it left outer join tag tg on it.itemid = tg.itemid 	0
495465	27350	describe via database link?	select column_name, data_type from all_tab_columns where table_name = 'table_name'; 	0.247312759750617
495988	6089	conditionally replacing values in select	select     totalcost =      case      when (totalhours * staffbaserate) < 105 then (totalhours * staffbaserate)      else (totalhours * staffbaserate) * 1.128     end from         newrotaraw where     staffref = @staffref 	0.0263566725188966
497241	6071	how do i perform a group by on an aliased column in ms-sql server?	select       lastname + ', ' + firstname as 'fullname' from         customers group by      lastname + ', ' + firstname 	0.694720500645392
497522	10172	boolean expressions in sql select list	select 'test name',      case when foo = 'result' then 1 else 0 end      from bar where baz = (some criteria) 	0.529909579504602
497535	31908	how do i join the most recent row in one table to another table?	select e.*, s1.score, s1.date_added  from entities e   inner join scores s1     on (e.id = s1.entity_id)   left outer join scores s2     on (e.id = s2.entity_id and s1.id < s2.id) where s2.id is null; 	0
501347	315	sql products/productsales	select p.[name]  from products p  where p.product_id in (select s.product_id      from productsales s      where s.[date] between @datestart and @dateend      group by s.product_id      having sum(s.quantity) > @x ) 	0.384917343063491
503673	36374	replace multiple strings in sql query	select     case when product in ('banana', 'apple', 'orange') then 'fruit'     else product end  from [table] 	0.504548169793192
504508	17701	using sql to search for a set in a one-to-many relationship	select r.roleid  from role r where not exists (select * from role_permissions rp where rp.roleid = r.roleid and rp.permissionid not in (1,2,3,4))     and (select count(*) from role_permissions rp where rp.roleid = r.roleid) = 4  	0.20529100541905
506279	14698	mysql query to get the count of each element in a column	select main_cat_id , count(*) as total from category where ( main_cat_id in (select categoryid from products)                         or         sub_cat_id in (select categoryid from products)        ) group by main_cat_id  order by total desc 	0
506471	24353	mysql getting count of each type of element in a cloumn	select category, count(*) from products group by category; 	0
507063	12722	mysql formatting a date	select     accessstarts,     date_format(str_to_date(accessstarts, '%d.%m.%y %k:%i:%s'), '%d %m %y' ) as shortdate from auctions  where upper( article_name ) like '%hardy%'  limit 0 , 10; 	0.325310471634531
507139	7828	oracle and sql dataset	select * from sqlservertable inner join linkedserver.oracletable     on whatever 	0.290978806589215
507646	18880	select max 5 integers from set of 20	select * from (     select *     from news     order by id desc     limit 0, 20 ) lasttwenty order by views desc limit 0, 5 	5.20084521741263e-05
508097	6575	conditional select of a column	select id, coalesce(price_brl, price_usd * tbl_2.value)  from tbl_1 inner join tbl2 	0.0647205452321617
508274	11695	getting distinct records with date field?	select     resource.description,     arq.datereferred as datereferred,     arq.assessmentresourceid from     resource inner join     assessmentxresource as arq          on arq.resourceid = resource.resourceid          and arq.datereferred = (                                 select                                     max(datereferred)                                 from                                     assessmentxresource                                 where                                     resourceid = resource.resourceid                                ) inner join     assessment as aq         on arq.assessmentid = aq.assessmentid inner join     [case] as cq         on aq.caseid = cq.caseid  inner join     [plan] as pq         on cq.caseid = pq.caseid where     (pq.planid = 22) order by     resource.description 	0.000621069725055182
508509	38090	finding unmatched records with sql	select     * from     table2 t2 where     not exists (select *         from            table1 t1         where            t1.state = t2.state and            t1.product = t2.product and            t1.distributor = 'x') 	0.0107095418837611
508692	8817	mysql query to return only duplicate entries with counts	select count(*), list_id, address_id from lnk_lists_addresses group by list_id, address_id having count(*)>1 order by count(*) desc 	6.1328447656598e-05
508707	26376	mysql count only for distinct values in joined query	select * from media m inner join      ( select uid      from users_tbl      limit 0,30) map   on map.uid = m.uid inner join users_tbl u   on u.uid = m.uid 	0.00140124390700203
510769	1002	sql query that numerates the returned result	select  (select count (1) from field_company fc2          where fc2.field_company_id <= fc.field_company_id) as row_num,         fc.field_company_name from    field_company fc 	0.055997964723185
511872	26016	sql syntax for calculating results of returned data	select    case when  power(isnull(val1x, 0), 2) + power(isnull(val1y, 0), 2)      > power(isnull(val2x, 0), 2) + power(isnull(val2y, 0), 2)   then power(isnull(val1x, 0), 2) + power(isnull(val1y, 0), 2)   else power(isnull(val2x, 0), 2) + power(isnull(val2y, 0), 2)   end from   mytable 	0.166891578541647
513065	7518	how to return a record when the sum reached a certain threshold	select min(a.transaction_date), a.account from (select sum(t1.points) as thesum, t2.transaction_date, t2.account  from table t1 inner join table t2 on t1.account = t2.account and t1.transaction_date <= t2.transaction_date group by t2.transaction_date, t2.account having thesum >= 100) a  group by a.account 	0
514444	38870	get info for multiple users in thread topic	select u.`name`, u.`signature`, u.`rank`, count(*) as numposts from `users` u inner join `posts` p on (u.`id` = p.`userid`) where u.`id` in (     select `userid` from `posts` where `threadid` = 5 ) group by u.`name`, u.`signature`, u.`rank` 	0.000301378021332832
515039	36717	use '=' or like to compare strings in sql?	select count(*) from master..sysobjects as a join tempdb..sysobjects as b on a.name = b.name select count(*) from master..sysobjects as a join tempdb..sysobjects as b on a.name like b.name 	0.646568209478239
516592	13479	reporting against a csv field in a sql server 2005 db	select * from   (select 1       as id,                '1,2,3' as members         union         select 2,                '2'         union         select 3,                '3,1'         union         select 4,                '2,1') users        left join (select '1' as member                   union                   select '2'                   union                   select '3'                   union                   select '4') groups          on charindex(',' + groups.member + ',',',' + users.members + ',') > 0 	0.382269346127484
516712	26916	sql generating a set of dates	select cast (s || ' seconds' as interval) + timestamp 'now' from generate_series(0, -60, -5) s 	0.0260552310920826
517989	31360	select top (all but 10) from ... in microsoft access	select ... from ... where pk not in (select top 10 pk from ...) order by ... 	0.00103769822178529
518122	22533	list active forum threads	select * from posts where post_content = 'thread' group by post_contentid order by max(post_date) desc limit 65 	0.0112472523694849
518790	2978	select users by total submissions	select username, sum(submissions)  from      (select username, count(picture_id) from               pictures group by username       union       select username, count(comment_id) from            comments group by username     )  group by username   order by sum(submissions) desc limit 10; 	0.00231456256013587
519010	35594	compare subselect value with value in master select	select       p.firstname,      p.lastname,      count(a.attendance_date) as countofattendance_date,      first(a.attendance_date) as firstofattendance_date,      c.total from (      tblpeople as p  inner join tbleventattendance as a on       a.people_id = p.id)  inner join (select people_id, count (attendance_date) as total             from (                 select distinct people_id,attendance_date                 from tbleventattendance)              group by people_id) as c on       p.id = c.people_id group by       p.id, c.total; 	0.001241110357125
520102	25421	how to search from all field in sql	select     name,     goal      activities,     result,     monname,     mongoal,     monactivities,     monresult,     totalfund from     tproject where     name like '%' + @search_string + '%' or     goal like '%' + @search_string + '%' or     activities like '%' + @search_string + '%' or     result like '%' + @search_string + '%' or     monname like '%' + @search_string + '%' or     mongoal like '%' + @search_string + '%' or     monactivities like '%' + @search_string + '%' or     monresult like '%' + @search_string + '%' or     totalfun like '%' + @search_string + '%' 	0.00132166908334848
531187	13525	clearing prioritized overlapping ranges in sql server	select start, cast(null as int) as finish, cast(null as int) as priority  into #processed   from #ranges union   select finish, null, null  from #ranges update p  set finish = (     select min(p1.start)      from #processed p1      where p1.start > p.start ) from #processed p  create clustered index idxstart on #processed(start, finish, priority)  create index idxfinish on #processed(finish, start, priority)  update p set priority =      (      select max(r.priority)       from #ranges r      where       (       (r.start <= p.start and r.finish > p.start) or        (r.start >= p.start and r.start < p.finish)        )     ) from #processed p delete from #processed where priority is null  select * from #processed 	0.0178358287824463
532694	10775	sql - select rows from two different tables	select itemid, itemtitle, deleted, userid from( select i.id_itemid, i.itemtitle, m.deleted, m.userid from     mylist m     right outer join items i on i.itemid= m.itemid ) as mytableitems where itemid = 3 or itemid is null 	0
537223	12020	mysql - control which row is returned by a group by	select * from (select id, max(version_id) as version_id from table group by id) t1 inner join table t2 on t2.id=t1.id and t1.version_id=t2.version_id 	0.0198116713927279
537258	29809	sql select convention	select id, name     from table1     join table2          on table2.fk1 = table2.fk1 	0.283111200516914
541472	1897	php and outputting one-to-many results	select url, group_concat(category) as categories from yourtable group by url 	0.400111565401026
544284	27335	writing a query ordered by the number of associations between objects	select blog_posts.*, count(replies.blog_post_id) as blog_replies  from blog_posts  left join replies on replies.blog_post_id = blog_posts.id  group by blog_posts.id  order by blog_replies desc 	0.00149575288895286
544329	32672	t-sql pattern matching	select a.* from users a join dbo.fn_split(@valuearraystring, '|') b on a.firstname = b.value 	0.0957908030868895
545163	18470	is there a data sizer tool available for sql server 2005?	select      t.name as tablename,     i.name as indexname,     sum(a.total_pages) as totalpages,      sum(a.used_pages) as usedpages,      sum(a.data_pages) as datapages,     (sum(a.total_pages) * 8) / 1024 as totalspacemb,      (sum(a.used_pages) * 8) / 1024 as usedspacemb,      (sum(a.data_pages) * 8) / 1024 as dataspacemb from      sys.tables t inner join           sys.indexes i on t.object_id = i.object_id inner join      sys.partitions p on i.object_id = p.object_id and i.index_id = p.index_id inner join      sys.allocation_units a on p.partition_id = a.container_id where      t.name not like 'dt%' and     i.object_id > 255 and        i.index_id <= 1 group by      t.name, i.object_id, i.index_id, i.name  order by      object_name(i.object_id) 	0.0696779500762171
546411	24715	assign unique id within groups of records	select orderid,        row_number() over(partition by orderid order by orderid) as linenum from order 	0
546804	26515	select distinct from multiple fields using sql	select distinct(ans) from (     select right as ans from answers     union     select wrong1 as ans from answers     union     select wrong2 as ans from answers     union     select wrong3 as ans from answers     union     select wrong4 as ans from answers ) as temp 	0.00756306584782181
547542	13759	how can i manipulate mysql fulltext search relevance to make one field more 'valuable' than another?	select  ... , case when keyword like '%' + @input + '%' then 1 else 0 end as keywordmatch , case when content like '%' + @input + '%' then 1 else 0 end as contentmatch from     ...     and here the rest of your usual matching query    ...  order by keywordmatch desc, contentmatch desc 	0.0298164870502412
548363	11359	retrieving all records - inner join	select distinct  dbo.tb_user.familyname,dbo.user_email.email  from dbo.tb_user  left outer join dbo.user_email  on (dbo.tb_user.id = dbo.user_email.userid) 	0.00520286647502102
548960	16026	mysql keyword search	select *, match(title) against ('quantum solace' in boolean mode) as rank  from films where match(title) against ('quantum solace' in boolean mode) order by rank desc 	0.700632129818373
556300	31897	sql "group by" question - i can't select every column	select id, url, xml from table1 where id in (     select min(id)     from table1     group by url) 	0.503300456058734
558667	38620	how to get a list of fields in a unique constraint	select column_name from information_schema.constraint_column_usage where constraint_name = 'your constraint' 	0
558719	25568	select variable number of random records from mysql	select * from site_info order by rand() limit n 	0
561384	12488	how do i join a select distinct to a select sum?	select     t.cd,     t.stdate,     t.enddate,     sum(t.pr) from     table t group by     t.cd,     t.stdate,     t.enddate 	0.0270324824233524
567655	987	sql query make columns results into rows	select c01 from table union all select c02 from table union all select c03 from table union all select c04 from table 	0.00466742330193433
571655	27584	select item, and select name of parent	select s.id, s.name, s.parent_id, p.name as parent_name from sections s left join sections p on s.parent_id = p.id 	0.000164115096630796
572745	2955	sql: searching grand child table for specifc items	select   c.id            customer_id,   c.name          customer_name,   i.id            item_id,   i.name          item_name,   count(i.id)     order_count,   sum(i.quantity) items_ordered from   customers c   inner join orders o on c.id = o.customer_id   inner join items  i on i.id = o.order_id where   i.name like 'la%'   and c.id = 1 group by   c.id,   c.name,   i.id,   i.name 	0.000787949493465803
574469	33494	selecting unique entries from a column	select distinct category from table 	0
574593	16563	another mysql minus question	select id, name from t_profiles  where id not in     (select p.id from t_profiles as p      left join t_skills as s on p.id = s.id_employee      where s.lvl>0 and s.id_task=1) 	0.629637383947378
577712	19815	change type of a column with numbers from varchar to int	select * into #tmp from bad_table truncate table bad_table alter bad_table alter column silly_column int insert bad_table select cast(silly_column as int), other_columns from #tmp drop table #tmp 	0.000186313701976926
578688	1455	sql sums in rows pulled out into columns?	select j.dtminvoicedon, j.strjobkey, c.strcustname, strtranstype,       sum(case when strtranstype='credit' then r.dbltransactionamount else 0 end) as sum_credit,      sum(case when strtranstype='debit' then r.dbltransactionamount else 0 end) as sum_debit from tbljobs as j      inner join tblreceivledger as r on j.strjobkey = r.strjobkey       inner join tblcustomers as c on j.intcustomerid = c.intcustomerid  where c.strcustomername = 'acme runners inc' group by j.strjobkey, c.strcustname order by dtminvoicedon, strjobkey; 	0.000268025389708676
579873	35109	convert date in tsql	select      right( '00' + convert(varchar(2), datepart( mm, @ddate)), 2) + '/' +     right( convert(varchar(4), datepart( yy, @ddate) ), 2 ) 	0.114341903853168
580670	12853	oracle query to get book-name?	select id.owner-name, b1.name "book1-name", b2.name "book2-name" from id left join book-name "b1" on b1.id = id.book-id1 left join book-name "b2" on b2.id = id.book-id2 	0.114884110970294
582657	626	how do i discover the structure of a postgresql database?	select table_name      from information_schema.tables  where table_type = 'base table'      and table_schema not in          ('pg_catalog', 'information_schema');  select column_name      from information_schema.columns  where table_name = 'yourtablesname'; 	0.0259260974077836
583072	444	sql select where repeating, but distinct on another column	select min(uid) as uid, key, email from keys k inner join      (select email from keys group by email having count(email) > 1 ) k2     on k.email = k2.email group by key, email having count(key) = 1 	0.00133731258530692
584232	33764	t-sql - how to swap rows and columns	select a.id, a.value as [response], b.value as [count] from your_table as a     inner join your_table as b         on a.id = b.id where a.name = 'response'     and b.name = 'count' 	0.00233485136443793
585355	23104	table details in sql anywhere?	select c.column_name from systabcol c     key join systab t on t.table_id=c.table_id     where t.table_name='tablename' 	0.212685481415498
585453	7035	postgresql - tree organization	select * from categories as child left join categories as parent on parent.id=child.parent left join categories as grandparent on grandparent.id=parent.parent where child.id=(id) or parent.id=(id) or grandparent.id=(id); 	0.326719809099641
586088	4395	oracle: pattern for to_char(number) to add additional ascii characters?	select concat(to_char(89.2244, '999g999g999g999g990d00'),'%') from dual 	0.391403866582269
588221	2514	forum structure get last post	select forums.*, max(comments.date) as last_comment from forums  left outer join threads on forums.forum_id = threads.forum_id left outer join comments on threads.thread_id = comments.comment_thread_id group by forums.forum_id order by forum_order asc 	0.000196518015073599
588913	3032	select data from two tables with identical columns	select * from a union select * from b 	0
589116	3005	is it possible in sql to match a like from a list of records in a subquery?	select distinct rc.* from registeredcodes rc, codevariations cv where rc.code like cv.code; 	0.00356759099881585
589652	22530	add 2 hours to current time in mysql?	select *  from courses  where date_add(now(), interval 2 hour) > start_time 	0
590028	21306	what's the preferred way to return an empty table in sql?	select top 0 * from table and select * from table where 1=0 	0.44877168029761
592209	38648	find closest numeric value in database	select top 1 * from [mytable]  where name = 'test' and size = 2 and ptype = 'p' order by abs( area - @input ) 	0.00141821930538169
592983	32920	how do i include empty rows in a single group by day(date_field) sql query?	select    count(incident_id) as "calls",   max(open_time),   days.open_day from (   select datepart(dd,dateadd(day,-6,getdate())) as open_day union   select datepart(dd,dateadd(day,-5,getdate())) as open_day union   select datepart(dd,dateadd(day,-4,getdate())) as open_day union   select datepart(dd,dateadd(day,-3,getdate())) as open_day union   select datepart(dd,dateadd(day,-2,getdate())) as open_day union   select datepart(dd,dateadd(day,-1,getdate())) as open_day union   select datepart(dd,dateadd(day, 0,getdate())) as open_day  ) days left join  (  select    incident_id,    opened_by,    open_time - (9.0/24) as open_time,    datepart(dd, (open_time-(9.0/24))) as open_day  from incidentsm1   where datediff(day, open_time-(9.0/24), getdate()) < 7 ) inc1 on days.open_day = incidents.open_day group by days.open_day 	0.00883398411311796
598355	28662	mysql statement combining a join and a count?	select  fol.*  ,      (       select  count(*)                 from    files           fil                 where   fil.folder      = fol.folder         )       as      "files" from    folders         fol where   fol.userid      = 16 	0.36118809550112
600136	6554	how can i get the value of a pkey for a record just inserted (autoincrement)?	select last_insert_id(); 	0
602836	17293	select distinct in dataview's rowfilter	select distinct parentid from myothertable 	0.103839989627201
603502	32800	copy table to a different database on a different sql server	select * into targettable  from [sourceserver].[sourcedatabase].[dbo].[sourcetable] 	0.000181777113753802
605217	27637	tsql - sum a union query	select     othercol1, othercol2,     sum(bar) from     (     select        othercol1, othercol2, bar     from        rt     union all     select        othercol1, othercol2, bar     from        fm     ) foo group by     othercol1, othercol2 	0.485863354449529
606234	17918	select count(*) from multiple tables	select  (         select count(*)         from   tab1         ) as count1,         (         select count(*)         from   tab2         ) as count2 from    dual 	0.00434445686771679
607027	9870	mysql php: check already made query for distinct field values?	select distinct product_field from (select * from table1 join ... where ...) oq 	0.00315363598643217
607292	7305	limiting results to a distinct column with sql	select o.*, i.* from items i, (select * from orders limit 0, 10) o where i.order_id = o.id 	0.0701301548908513
607410	38498	group by like row filtering	select t1.make, t1.model, t1.year, t1.other_cols from table t1 where year = (select max(year) from table t2               where t2.make = t1.make               and t2.model = t1.model              ); 	0.187101922630716
607817	8004	get dates from a week number in t-sql	select     convert(varchar(50), (dateadd(dd, @@datefirst - datepart(dw, datecol), datecol)), 101),    convert(varchar(50), (dateadd(dd, @@datefirst - datepart(dw, datecol) - 6, datecol)), 101) 	0
608451	37610	getting single records back from joined tables that may produce multiple records	select  student_name,         student_email,         (select count(*)           from enrollment e           where e.student_id = s.student_id         ) number_of_enrollments   from student e 	0
608992	37683	query against 250k rows taking 53 seconds	select * from  (     select top(10) id, categoryid, userid     from stories     order by stories.lastactivityat ) s inner join stories on stories.id = s.id inner join categories on categories.id = s.categoryid inner join users on users.id = s.userid 	0.031062116026897
610945	27280	how can i order entries in a union without order by?	select col from     (        select a col, 0 ordinal from a limit 1        union all        select b, 1 from b limit 1    ) t order by ordinal 	0.0117668868047894
611676	26148	oracle correlated subquery in from list	select ... from   (        select pid,               hdid,               obsdate               max(obsdate) over (partition by pid, hdid) maxdate        from   ml.obs        where  obsdate < {?enddate}        ) where  obsdate = maxdate / 	0.558953812776544
612231	899	how can i select rows with max(column value), distinct by another column in sql?	select tt.* from topten tt inner join     (select home, max(datetime) as maxdatetime     from topten     group by home) groupedtt  on tt.home = groupedtt.home  and tt.datetime = groupedtt.maxdatetime 	0
614423	15240	removing non-numeric characters in t-sql	select     sum(au.total_pages) / 128.0 as usedmb from     sys.allocation_units au 	0.462906729626935
616853	4513	getting the data out of one-many relation ship from same table	select hospital, doctor, max(patient) from table group by hospital, doctor order by hospital, doctor 	0
618187	3089	retrieving records that has both tag t1 and t2	select i.* from items i, itemtags it1, itemtags it2 where i.item_id=it1.item_id and it1.tag_id=t1 and i.item_id=it2.item_id and it2.tag_id=t2; 	0.000144687534347561
620272	15899	select all rows that correspond to a time	select *  from table where time < utc_timestamp() + interval(1) minute  - interval (extract(second from utc_timestamp())) second  and time >= utc_timestamp() - interval (extract(second from utc_timestamp())) second; 	6.75012132718612e-05
620285	2907	counting multiple entries in a mysql database?	select author, code, count(*) from   table where  country = @country group by        author, code 	0.000736971526537313
624797	2701	is it possible to pass db name as a parameter	select @dbname = quotename(dbname) select @sql = ' select ... from ' + @dbname + '.dbo.tablename where ...' exec sp_executesql @sql, @params, ... 	0.693187205666961
626788	33772	t-sql group by: best way to include other grouped columns	select e.empid, fname, lname, title, dept, projectidcount from (    select empid, count(projectid) as projectidcount    from employees e left join projects p on e.empid = p.projleader    group by empid ) idlist inner join employees e on idlist.empid = e.empid 	0.000976130930049245
628844	5171	mysql - finding duplicate tuples	select f1, f2, f3, count(*) from mytable group by f1, f2, f3 having count(*) > 1 	0.00497789393616891
629183	31573	sql query - join that returns the first two records of joining table	select      p.pkpatientid,      p.firstname,      p.lastname,      ps1.statuscode as firststatuscode,      ps1.startdate as firststatusstartdate,      ps1.enddate as firststatusenddate,      ps2.statuscode as secondstatuscode,      ps2.startdate as secondstatusstartdate,      ps2.enddate as secondstatusenddate from      patient p inner join patientstatus ps1 on      ps1.fkpatientid = p.pkpatientid inner join patientstatus ps2 on      ps2.fkpatientid = p.pkpatientid and      ps2.startdate > ps1.startdate left outer join patientstatus ps3 on      ps3.fkpatientid = p.pkpatientid and      ps3.startdate < ps1.startdate left outer join patientstatus ps4 on      ps4.fkpatientid = p.pkpatientid and      ps4.startdate > ps1.startdate and      ps4.startdate < ps2.startdate where      ps3.pkpatientstatusid is null and      ps4.pkpatientstatusid is null 	0
634568	33178	how to get difference between two rows for a column field?	select    [current].rowint,    [current].value,    isnull([next].value, 0) - [current].value from    sourcetable       as [current] left join    sourcetable       as [next]       on [next].rowint = (select min(rowint) from sourcetable where rowint > [current].rowint) 	0
635932	12407	select newest record matching session_id	select session_id, timestamp, file  from table t1 join (select session_id, max(timestamp) as timestamp)          from table group by session_id) as t2    on t1.session_id = t2.session_id      and t1.timestamp = t2.timestamp 	0.00109605157302267
637757	37876	sql query - search across multiple fields	select * from address where ((name like 'bill%') or (city like 'bill%') or (company like 'bill%')) and ((name like 'seattle%') or (city like 'seattle%') or (company like 'seattle%')) 	0.12765968436707
638093	7903	count and grouped by in t-sql	select   count(t.recordid) numberofrows,   t.portname,   t.eventhour,   max(t.eventdatetime) lastactivityinhour from   (     select       recordid,       portname,       coalesce(receivedevent, sentevent) eventdatetime,       datepart(hh, coalesce(receivedevent, sentevent)) eventhour,       dateadd(dd, 0, datediff(dd, 0, coalesce(receivedevent, sentevent))) eventdate     from       mytable   ) t where   t.eventdate = dateadd(dd, 0, datediff(dd, 0, @thedateinquestion)) group by   t.portname,   t.eventhour order by   t.portname,   t.eventhour 	0.0481352390717625
638332	32700	how do i join two tables on a column, that has the same name in both tables?	select  * from    table1         inner join         table2         on table1.columnname = table2.columnname 	0
638865	10863	mysql - how do i order the results randomly inside a column?	select orders.*  from orders  inner join (select userid, rand() as random from users) tmp on orders.userid = tmp.userid order by tmp.random, tmp.userid 	0.0176317828636799
639070	14599	sql query to calculate correct leadtime in table (ms access)	select t.id, t.status, t.sdatetime,      (select top 1 sdatetime       from t t1 where t1.status = 1       and t1.id=t.id       and t1.sdatetime<t.sdatetime       and t1.sdatetime>=          nz((select top 1 sdatetime               from t t2               where t2.status=3               and t2.id=t.id               and t2.sdatetime<t.sdatetime),0)) as datestart,  [sdatetime]-[datestart] as result from t where t.status=3 	0.454264379496722
639895	15040	find all database objects by name?	select * from database.sys.all_objects where upper(name) like upper('my prefix%')   	0.000806637277354515
640656	19843	sql query for summary by instances per day	select avg(`num`), ((`num` - 1) div 2) * 2 as `tier` from (     select date_format(`created`, '%y-%m-%d') as `day`, count(*) as `num`     from `yourtable`     group by 1 ) as `src` group by `tier` 	0.000118066602573078
642474	19639	mysql query with wildcard on number strings	select * from table where field like '9%'? 	0.219992701300824
642656	25199	how to find duplicates in 2 columns not 1	select   stone_id,          upcharge_title,          count(*) from     your_table group by stone_id,          upcharge_title having   count(*) > 1 	0.000574142033575084
643508	35581	mixing on and using within one join	select *     from (select *              from tbl1                   join tbl2 using (col1, col2, col3, col4)                   join tbl3 using (col2, col4, col6, col23)                   join tbl4 using (col2, col8, col3, col23)           ) as systematicnaming           join tbl5               on  systematicnaming.col1 = tbl5.col1               and systematicnaming.cola = tbl5.poorlynamedcola               and systematicnaming.colb = tbl5.poorlynamedcolb 	0.332557581678957
650282	38890	oledbexception: data type mismatch in criteria expression	select * from flats where flats.versionstamp <= ? and flats.flat=? 	0.731922281405932
651955	20812	fetch fields from a table that has the same relation to another table	select distinct `tags`.`tag` from `tags` left join `tags_topics` on `tags`.`id` = `tags_topics`.`tag_id` left join `topics` on `tags_topics`.`topic_id` = `topics`.`id` left join `tags_topics` as `tt1` on `tt1`.`topic_id` = `topics`.`id` left join `tags` as `t1` on `t1`.`id` = `tt1`.`tag_id` left join `tags_topics` as `tt2` on `tt2`.`topic_id` = `topics`.`id` left join `tags` as `t2` on `t2`.`id` = `tt2`.`tag_id` left join `tags_topics` as `tt3` on `tt3`.`topic_id` = `topics`.`id` left join `tags` as `t3` on `t3`.`id` = `tt3`.`tag_id` where `t1`.`tag` = 'tag1' and `t2`.`tag` = 'tag2' and `t3`.`tag` = 'tag3' and `tags`.`tag` not in ('tag1', 'tag2', 'tag3') 	0
653337	1797	sql - calculate percentage increase in values of a numeric column	select   concat(     format(       if(@prev and sum(orders) <> @prev,          -1 * 100 * (1 - sum(orders) / @prev),        0         )       , 2)   , '%') as variation,     @prev := sum(orders) as orders from     (select @prev := null) init,     product group by   id_product order by   month 	0.000195494190498185
654585	2564	mysql: get all tables in database that have a column called xyz	select c.table_name from  information_schema.columns c  where c.column_name = 'xyz' 	4.92930287136586e-05
657803	21660	where are java classes stored in oracle?	select   object_name,    object_type,    status,    timestamp from    user_objects where    (object_name not like 'sys_%' and     object_name not like 'create$%' and     object_name not like 'java$%' and     object_name not like 'loadlob%') and   object_type like 'java %' order by   object_type,    object_name; 	0.638304669433216
659906	15458	how to delete duplicate records in mysql database?	select distinct * into newtable from mytable 	0.000881189046676097
662207	8949	mysql results as comma separated list	select p.id, p.name, group_concat(s.name) as site_list from sites s inner join publications p on(s.id = p.site_id) group by p.id; 	0.000929929990515244
665830	29296	access sql many to many query	select a.* from author a left join authoroftitle t on a.aid = t.aid where t.id is null 	0.62283527887784
667459	23217	how to outer-join two tables (main and many-to-one sub-table) to get only one item from second table?	select *  from main_table m left outer join sub_table s  on s.main_table_id = m.id where s.id is null or s.id in (    select max(id) from sub_table group by main_table_id ) 	0
669092	31534	sqlite - getting number of rows in a database	select coalesce(max(id)+1, 0) from words 	0.000255516811816804
670327	3982	sql query - how to fetch non-read messages efficiently	select count(*) from unread where user = foo 	0.0308767671536866
673768	4371	how to find the *position* of a single record in a limited, arbitrarily ordered record set?	select @row := 0;  select max( position )    from ( select @row := @row + 1 as position            from photos           where photo_gallery_id = 43             and date_created_on <= 'the-date-time-your-photo-was'            order by date_created_on ) positions; 	0
675117	676	fetching linked list in mysql database	select * from mytable t1  left join mytable t2 on (t1.next_id = t2.id)  left join mytable t3 on (t2.next_id = t3.id)  left join mytable t4 on (t3.next_id = t4.id)  left join mytable t5 on (t4.next_id = t5.id)  left join mytable t6 on (t5.next_id = t6.id)  left join mytable t7 on (t6.next_id = t7.id)  left join mytable t8 on (t7.next_id = t8.id)  left join mytable t9 on (t8.next_id = t9.id)  left join mytable t10 on (t9.next_id = t10.id); 	0.036260160085016
677854	567	pagination in for searching	select * from ( select row_number() over (order by id) as resultnum, id from table_name) as numberresultswhere resultnum  between ? and ? 	0.609108017768651
681408	37627	mysql: multiple grouping	select  item_type, person_name, item_count from    (         select  item_type, person_name, item_count,                 @r := ifnull(@r, 0) + 1 as rc,                 case when @_item_type is null or @_item_type <> item_type then @r := 0 else 1 end,                 @_item_type := item_type,         from    (                 select  @r := 0,                         @_item_type := null                 ) vars,                 (                 select  item_type, person_name, count(*) as item_count                 from    items                 group by                         item_type, person_name                 order by                         item_type, person_name, item_count desc                 ) vo         ) voi where   rc < 3 	0.177196597247041
683842	5731	how can i perform an and on an unknown number of booleans in postgresql?	select bool_and(somebool)   from mytable   where somekey = $1   group by somekey; 	0.182046803252631
689912	18068	sql: retrieve only the records whose value has changed	select  r1.code, r1.date, r1.rate from    ratetable r1 where   r1.rate <> (select top 1 rate                    from    ratetable                    where   date < r1.date                    order by date desc) 	0
690474	27596	sql select distinct rows	select col1, max(col2) from some_table group by col1; 	0.0167129064068259
693327	38362	how do i join multible tables?	select u.username, a.name from user_activity ua inner join session s on ua.session_id = s.session_id inner join user u on s.user_id = u.user_id inner join activity a on ua.activity_id = a.activity_id 	0.26694127571019
695647	22626	creating xml using the from xml clause using sql 2000	select     '<?xml version="1.0" encoding="iso-8859-1" ?>' + char(13) + char(10) +    '<root>' + char(13) + char(10) +    '    <value>' + yourtable.yourfield + '</value>' + char(13) + char(10) +    '</root>' + char(13) + char(10) from yourtable where id = 1 	0.752161552071999
696669	14031	mysql - combining questions and answers from multiple transactions	select      s.storeid,      s.branchname,      a.questionid,      t.created,      a.* from      tblstore s inner join tbltransaction t on      t.storeid = s.storeid inner join tblanswer a on      a.transactionid = t.transactionid and      a.storeid = s.storeid where not exists           (           select                t2.storeid,                a2.questionid,                t2.transactionid,                t2.createddate           from                tbltransaction t2           inner join tblanswer a2 on                a2.transactionid = t2.transactionid and                a2.storeid = t2.storeid           where                t2.storeid = t.storeid and                a2.questionid = a.questionid and                t2.createddate > t.createddate           ) 	0.0389357831298823
697295	25533	conditionally branching in sql based on the type of a variable	select case      when isnumeric(t.value) then t.value       else someconversionfunction(t.value)  end as somealias 	0.00071777642668049
697367	13370	loop through columns sql	select     myname + " ->"   + case option1 when 1 then ' option1' else '' end   + case option2 when 1 then ' option2' else '' end   + ... from  table 	0.0989010246096378
697997	5397	sql query for generating given data	select sum([1]) as jan, sum([2]) as feb, sum([3]) as mar, sum([4]) as apr,        sum([5]) as may, sum([6]) as jun, sum([7]) as jul, sum([8]) as aug,        sum([9]) as sep, sum([10]) as oct, sum([11]) as nov, sum([12]) as dec from (select month(join_date) as mon from student) ps pivot     (count(mon) for mon in          ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])     ) as pvt group by [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12] 	0.1132446460064
698438	7217	ordering wordpress posts by most recent comment	select wp_posts.*,     coalesce(         (             select max(comment_date)             from $wpdb->comments wpc             where wpc.comment_post_id = wp_posts.id         ),         wp_posts.post_date     ) as mcomment_date     from $wpdb->posts wp_posts     where post_type = 'post'     and post_status = 'publish'      order by mcomment_date desc     limit 10 	0.000399145880496599
699318	37735	joining a table value function to a mssql query	select id_num, name, balance, sum(x.discount) from listofpeople     cross apply dbo.calculatepersonaldiscount(listofpeople.id_num) x 	0.0572400192780074
699368	31486	querying similar but disjoint datasets in a single sql query	select cast(unixtime/3600 as unsigned) as hour,     sum(iface1_in), sum(iface1_out) from (     select * from router1_20090330     union all     select * from router1_20090331 ) x group by hour order by hour 	0.0749389465118704
700950	6103	union two or more tables, when you don't know the number of tables you are merging	select      f.*  from      resultstable rt     cross apply dbo.subs(rt.id) f 	0
701161	39039	sql query with unique column value	select a.*, b.*, c.*   from c     join b on b.cid = c.cid     join a on a.bid = b.bid     join     (       select id = min(aid)         from c           join b on b.cid = c.cid           join a on a.bid = b.bid         group by col3     ) d on d.id = a.aid 	0.00999077022813703
702105	36578	data paging in sql server 2005 only returns 1 (one) row	select * from @products 	0.0179343761843161
702208	40629	comparing two fields in mysql -indexes?	select count(id) from table1 where date1 > date2; 	0.0453491917513227
702763	35288	how can i get maximum and minimum values in a single query?	select min(posx), min(posy), max(posx), max(posy) from table 	0
702968	34699	how do i expand comma separated values into separate rows using sql server 2005?	select pv.productid, colortable.items as color from product p   cross apply split(p.color, ',') as colortable 	0
706364	29466	postgresql - how to check if my data contains a backslash	select  count(*) from    table where   column ilike '%\\\\%'; 	0.164794040198139
706430	25540	get schema of proc's select output	select * into #temptable from openquery(servername, ‘exec databasename.dbo.storedprocedurename paramvalues1, paramvalues1′) 	0.018257964964307
706803	13850	how do i write an sql query which looks for a value in all columns and all tables in my database?	select 'select ''' + table_name + '.' + column_name +     ''' from ' + table_name + ' where ' +     column_name + ' = ''[your value here]''' from information_schema.columns  where data_type = 'varchar'; 	0.00014922094702103
707004	35403	how do i select rows from a mysql table grouped by one column with required values in another	select p.name, p.id from product p,  (select product_id from properties where value='red') colors, (select product_id from properties where value='small') sizes where p.id=colors.product_id and p.id=sizes.product_id 	0
707270	8610	how to prevent, counter or compensate for, an empty/null field (mysql) returning an empty set	select concat(c.fname, ' ', c.sname) as name, e.address as email from contacts c left join emails e on (c.contactid = e.contactid) 	0.173509330784098
711123	37944	mysql query: how to calculate the average of values in a row?	select (a.a + a.b) / 2 from a; 	0
712731	40417	using temp tables in if .. else statements	select colx into #temp1 from @tbl where (@checkvar is null) or (colx = @checkvar) 	0.688010192757966
714980	38521	how do you search for a & (ampersand) in the tsql contains function?	select * from t where contains(c, '"a&b"') 	0.535549373160979
714992	4313	determining oracle database instance	select ora_database_name from dual; select sys_context('userenv','db_name') from dual; select global_name from global_name; 	0.155852763476432
715804	23902	query to return 1 instance of a record with duplicates	select id, value, min(signal), min(read), min(firmware), min(date), min(time) from   ... group by   id, value 	0.000868487998570951
719226	30438	modelling different usertypes in a relational database	select   a.*, b.*, c.*,   case when b.id is not null then 1 else 0 end as is_usertype1,   case when c.id is not null then 1 else 0 end as is_usertype2, from authcredentials a   left outer join usertype1 b on (a.id = b.authcredential_id )  left outer join usertype2 c on (a.id = c.authcredential_id ); 	0.0705323137926094
723101	33162	get the last record of table in select query	select  b.*, m.*, t,*         (         select  count(*)         from    topics ti         where   ti.boardid = b.boardid         ) as topiccount,         (         select  count(*)         from    topics ti, messages mi         where   ti.boardid = b.boardid                 and mi.topicid = ti.topicid         ) as messagecount from    boards b left join         messages m on      m.messageid = (         select  mii.messageid         from    topics tii, messages mii         where   tii.boardid = b.boardid                 and mii.topicid = tii.topicid         order by                 mii.date desc         limit 1         ) left join         topics t on      t.topicid = m.topicid 	0
723703	31322	date format conversion in sql	select datename(mm, your_date_column) + ' ' + cast(year(your_date_column) as varchar(4)) as [month yyyy] 	0.184598538652807
724341	18676	how do i get all the rows in one table that are not in another in ms access?	select tableb.con_number from tableb where not exists (select 1                    from tablea                    where tablea.con_number = tableb.con_number); 	0
724902	21022	sql query with joins between four tables with millions of rows	select  e.employeename,         (         select  sum(amount)         from    moneytransactions m         where   m.employeeid = e.employeeid         ) as totalamount,         (         select  sum(amount)         from    budgettransactions m         where   m.employeeid = e.employeeid         ) as budgetamount,         (         select  sum(hours)         from    timetransactions m         where   m.employeeid = e.employeeid         ) as totalhours,         (         select  sum(hours)         from    timebudgettransactions m         where   m.employeeid = e.employeeid         ) as budgethours from    employees e 	0.164151096289522
725153	10372	most recent record in a left join	select a.state, count(c.customerid) from product p inner join customer c on c.customerid = p.customerid left join address a on a.customerid = c.customerid        and a.addressid =          (            select max(addressid)             from address z             where z.customerid = a.customerid         ) where p.productid = 101 group by a.state 	0.00181597421042411
727065	19164	finding correlated values from second table without resorting to pl/sql	select     rng.sensor_id,     rng.start_date,     rdg1.value as v1,     rng.end_date,     rdg2.value as v2,     rng.description from     ranges rng inner join readings rdg1 on     rdg1.sensor_id = rng.sensor_id and     rdg1.acquired => rng.start_date left outer join readings rdg1_ne on     rdg1_ne.sensor_id = rdg1.sensor_id and     rdg1_ne.acquired >= rng.start_date and     rdg1_ne.acquired < rdg1.acquired inner join readings rdg2 on     rdg2.sensor_id = rng.sensor_id and     rdg2.acquired => rng.end_date left outer join readings rdg1_ne on     rdg2_ne.sensor_id = rdg2.sensor_id and     rdg2_ne.acquired >= rng.end_date and     rdg2_ne.acquired < rdg2.acquired where     rdg1_ne.sensor_id is null and     rdg2_ne.sensor_id is null 	0.00256809304625444
731413	18202	how to get all tables that have fks to another table?	select owner,constraint_name,constraint_type,table_name,r_owner,r_constraint_name from all_constraints  where constraint_type='r' and r_constraint_name in (select constraint_name from all_constraints  where constraint_type in ('p','u') and table_name='table_name'); 	0
733652	26945	select a random sample of results from an oracle query	select  * from    (         select  *         from    mytable         order by                 dbms_random.value         ) where rownum <= 1000 	0.0153857621982425
736151	2545	sql server: displaying first line of grouped records	select case when _rank = 1 then name else '' end as name, amount from (     select name, amount,      row_number() over (partition by name order by amount asc) as _rank     from t1 ) q 	6.23759469246896e-05
737669	16816	postgres - how to check for an empty array	select      count(*) from      table where      datasets = '{}' 	0.0272527717092548
737844	33528	join via junction table with nullable field	select  d.*, c.* from    d join    junction j on      j.d_id = d.id left join         с on      c.id = j.c_id 	0.0323400895066187
739994	28122	sql find most recent date from 2 columns, and identify which column it was in	select top 1 alldates.intpk, alldates.datlastaction as datlastscan, alldates.operation, dbo.viwassets.strfriendlyname, tblassetsinuse_join.intassetid from (select top 1 intpk, intassetid, datcheckedout as datlastaction, 'out' as operation   from dbo.tblassetsinuse as tblassetsinuse_out   order by datcheckedout desc   union all   select top 1 intpk, intassetid, datcheckedin as datlastaction, 'in' as operation   from dbo.tblassetsinuse as tblassetsinuse_in   order by datcheckedin desc) as alldates  inner join   dbo.viwassets on alldates.intassetid = dbo.viwassets.intpk order by datlastscan desc 	0
740724	24092	query for summing up values present in different columns in sql server 2005	select     student_id,     course_id,     subject_id,         sum(theory_marks + practical_marks) as overall_mark from     table group by     student_id, course_id, subject_id 	0.00171085428287257
742226	186	how to get a value from previous result row of a select statement?	select followup.value,      ( select top 1 f1.value        from followup as f1        where f1.id<followup.id        order by f1.id desc     ) as prev_value from followup 	0
743456	35374	displaying rows with count 0 with mysql group by	select   c.cname,   count(w.ename) wcount  from   company c   left join works w on c.cname = w.cname group by   c.cname 	0.0368549230734863
743569	2738	mysql query - unknown column	select  id, sum(linevalue * quantity) as totalline from    mytable group by         id having  totalline between 10 and 500 	0.517821940182886
744366	11349	convert data in a table to a different view	select dt,  sum(case when tag=1 then value else 0 end) as tag1, sum(case when tag=2 then value else 0 end) as tag2, sum(case when tag=3 then value else 0 end) as tag3 from mytable group by dt 	0.00199857588354534
748542	37491	how to find duplicate field combo	select     id, a, b from your_table t join (select a, b from your_table group by a, b having count(1) > 1) dup on dup.a = t.a and dup.b = t.b 	0.00361189725415914
750934	325	time slot sql query	select     case         when startdate = bookeddate and starttime between timeslotstart and timeslotend             then 'true'         else 'false'     end from     ... 	0.203854970581637
751141	7344	how to get top "n'th maximum" value alone from a table in ms sql?	select top 1 employee.name, employee.salary from (     select top n employee.name, employee.salary     from employee     order by employee.salary desc ) 	0
751156	31089	max count together in an sql query	select modeldescription, count(modeldescription)  from products  group by modeldescription order by 2 desc 	0.294938500403856
752048	16477	sql help in access – looking for the absence of data	select * from families left join children on families.familyid = children.familyid and children.gender="m" where children.familyid is null 	0.668250936901095
753594	36119	how can i execute a udf on multiple rows?	select dbo.yourfunc(column) as result from table 	0.123869589858829
754490	28755	list top 5(most collected) species	select distinct species.spid  ,species.common_name  ,count(specimen.spid) as number_collected from species  ,field_location  ,specimen where species.spid = specimen.spid  and field_location.locid = specimen.locid  and field_location.location_name = 'karkato' order by number_collected desc limit 5 	0.0261650165730832
754512	25761	mysql: how do i find out which tables reference a specific table?	select table_name from information_schema.key_column_usage where table_schema = 'my_database' and referenced_table_name = 'my_table_here'; 	0.000132454690257305
756080	5579	how to retrieve field names from temporary table (sql server 2008)	select * from tempdb.sys.columns where object_id = object_id('tempdb..#mytemptable'); 	5.66786434982013e-05
756972	40450	dash in a field name in access database table	select * from test where test.[hd-test]='h' 	0.0097625462375988
757763	36185	top n problem with group by clause	select gp.pledgeid from giftpledge gp       inner join giftdetail gd on gp.pledgeid = gd.pledgeid       where gp.pledgestatus = 'a'       group by pledgeid       having count(pledgeid) >= 3  and gp.pledgeid in ( select pledgeid from ( select top 3 gp.pledgeid, gdi.amt  from giftdetail gdi       inner join giftheader ghi on gdi.giftref = ghi.giftref       where gdi.pledgeid = gp.pledgeid       order by ghi.gdate desc ) x_amt  group by pledgeid having sum(amt) ) x_sum = 0 	0.468753433653476
757957	3418	restricting a left join	select ... from .... left join ( a inner join b on .... ) on .... 	0.731768840780987
759292	38965	to change date format in sql	select (convert(varchar(10), yourfield, 103) + ' ' + convert(varchar(15), yourfield, 108)) as datetime 	0.0462499577125116
761014	27203	mysql: can you pull results that match like 3 out of 4 expressions?	select   *  from    my_table  where    case when name = "john doe"           then 1 else 0 end +   case when phone = "8183321234"        then 1 else 0 end +   case when email = "johndoe@yahoo.com" then 1 else 0 end +   case when address = "330 some lane"   then 1 else 0 end   >= 3; 	0.0210014413584544
761641	122	can postgresql select from an array returned by a function?	select (xpath('/my/xpath/expr', my_xml))[1] from my_table; 	0.0689833737356208
763454	13368	sql question .. how can i dynamically add columns to a sql query result set?	select <non-pivoted column>,             [first pivoted column] as <column name>,             [second pivoted column] as <column name>, ...     from table      pivot ( ... for  ... ) 	0.101604123553194
764899	24792	mysql max query	select teacher_name from teachers where teacher_id in (     select t.teacher_id     from teachers t inner join courses c on t.teacher_id = c.teacher_id     group by t.teacher_id     having count(*) =      (         select max(courses_per_teacher) from         (             select teacher_id, count(*) as courses_per_teacher             from teachers t inner join courses c on t.teacher_id = c.teacher_id             group by teacher_id         )     ) ) 	0.31528562757015
765176	24338	how to get all details about a mysql table using c#?	select   table_name        , column_name        , data_type        , character_maximum_length        , character_octet_length         , numeric_precision         , numeric_scale as scale        , column_default        , is_nullable from information_schema.columns 	0.00961583149940333
766096	27556	looking for sql query to display data from 2 tables that is not commone between the tables	select acct_id,name  from masterlist  where acct_id not in (select distinct acct_id from newmasterlist)  union  select acct_id,name  from newmasterlist  where acct_id not in (select distinct acct_id from masterlist) 	0
766530	23352	displaying random row from last 100 entries?	select * from   (select * from $db_table order by $timestamp desc limit 100) order by rand() limit 1 	0
767663	5312	returning query where field is null	select article_no, username, accessstarts, article_name, date_format(str_to_date(accessstarts, '%d.%m.%y %k:%i:%s'), '%d %m %y' ) as shortdate  from auctions where upper(article_name) like '%hardy%' and subcat is null order by str_to_date(accessstarts, '%d.%m.%y %k:%i:%s'), article_no limit 0, 10 	0.554628016154558
770579	20474	how to calculate percentage with a sql statement	select grade, (count(grade)* 100 / (select count(*) from mytable)) as score from mytable group by grade 	0.0367347711438327
772483	839	sql: finding double entries without losing the id	select min(id), product, color from table group by product, color; 	0.000398437338406758
773417	33969	aggregate sql function to grab only the first from each group	select     * from account a join (     select          account_id,          row_number() over (order by account_id, id) -              rank() over (order by account_id) as row_num from user      ) first on first.account_id = a.id and first.row_num = 0 	0
776123	39354	mysql: dot (".") in database name	select `select`, `some.field name`, `crazy()naming+here` from `my-=+table` 	0.0761028816517534
777495	24244	how to tell last update/insert activity on a table sql 2005	select object_name(object_id) as databasename, last_user_update,* from sys.dm_db_index_usage_stats where database_id = db_id( 'adventureworks') and object_id=object_id('test') 	0.00394132085936897
777693	38365	how to get total occurrence of a value within its own query?	select     t.id,     t.user_id,     (select count(*) from table where user_id = t.user_id) as `count` from table t; 	0
778239	2599	mysql subquery returns more than one row	select voterfile_county.name,    voterfile_precienct.prec_id,    voterfile_precienct.name,    count(voterfile_voter.id) from voterfile_county join voterfile_precienct    on voterfile_precienct.county_id = voterfile_county.id join voterfile_household    on voterfile_household.precnum = voterfile_precienct.prec_id join voterfile_voter    on voterfile_voter.house_id = voterfile_household.id  group by voterfile_county.name,    voterfile_precienct.prec_id,    voterfile_precienct.name 	0.0238291586313084
778307	30189	can i have an inner select inside of an sql update?	select top 1 id from foo where foo.name=? 	0.620366246146512
778353	38483	comparing two date ranges when one range has a range of starting dates	select * from periods p where p.range_start >= @min_start and   p.range_start <= @max_start and   date_add(p.range_start, interval @duration day) <= p.range_end 	0
779149	2725	how to do select top @param in a stored procedure?	select top (@numberofresultstoreturn) * 	0.158491096191155
782465	11672	lazy evaluation of oracle pl/sql statements in select clauses of sql queries	select a, b, expensive_procedure(c) from  ( select a, b, c   from example   where <the_where_clause>   order by d ) v; 	0.757196433242129
783070	5520	oracle - sum on a subquery?	select sum(ticket_type.price) as totalsales           , reservation.reservation_id           , cinema.location           , performance.performance_date        from reservation           , ticket           , ticket_type           , cinema           , performance       where ticket_type.ticket_type_id = ticket.ticket_type_id          and ticket.reservation_id = reservation.reservation_id          and reservation.performance_id = performance.performance_id          and cinema.location = 'sometown'          and performance.performance_date = to_date('01/03/2009','dd/mm/yyyy');      group by reservation.reservation_id 	0.386572621577883
783211	36308	calculating the difference between two dates	select isnull(count(*), 0) from calendar where [date] > dateone      and [date] < datetwo     and isweekday = 1     and isholiday = 0 	0.000100181484769439
785172	13745	selecting date intervals, doing it fast, and always returning the latest entry with the result	select      p.start_date,      p.end_date,      ab1.account_id,      ab1.balance from      periods p left outer join account_balances ab1 on      ab1.date <= p.end_date left outer join account_balances ab2 on      ab2.aid = ab1.aid and      ab2.date > ab1.date and      ab2.date <= p.end_date where      ab2.aid is null 	0
791279	27822	tsql query that would return me the earliest date and the latest date in a table	select         min(dateadded) as firstdate,        max(dateadded) as lastdate from        news; 	9.40248159011536e-05
792310	17191	tsql return guid that occurs the most in a column	select top 1 id, count(*) as countofrows from unknowntable group by id order by countofrows desc 	0.000212965539446846
794656	15776	convert tsql to ms-access sql	select ... from (((participant par     inner join individual ind          on par.apetsid = ind.apetsid)     inner join ethnicity eth          on ind.ethnicityid = eth.id)     inner join education edu          on ind.educationid = edu.id)     inner join marital mar          on ind.marital = mar.id 	0.74259123376407
796299	9805	can we get the data from five tables having a common id with one query?	select * from tbl_student st  join tbl_batch ba on ba.college_id=st.college_id join tbl_section se on se.college_id=st.college_id join tbl_level le on le.college_id=st.college_id join tbl_faculty fa on fa.college_id=st.college_id 	0
797069	3244	in mysql stored procedures check if a local variable is null	select coalesce(variable, 0) + coalesce(variable2, 0) 	0.669147893658048
798522	11134	generate a fire register report	select      t1.user from      some_table t1 left outer join some_table t2 on      t2.user = t1.user and      t2.success = 1 and      t2.date > t1.date where      t1.success = 1 and      t1.action = 'login' and      t2.id is null 	0.211198319200255
798779	13746	efficiently sorting data from db using java?	select t.* from text t     inner join friend f on f.friend_username = t.username     where f.username = 'myusername'     order by t.date desc     limit 10 	0.0768436814452952
799070	26156	counting records from a grouped query with additional criteria	select approved_flag, count(*) from    table t   inner join (     select user_id, submitted_date = max(submitted_date)     from table     group by user_id   ) latest on latest.user_id = t.user_id               and latest.submitted_date = t.submitted_date group by approved_flag 	0.000231531519493068
800467	21139	mysql - optimize a query and find a rank based on column sum	select world, count(*) as total  from highscores  group by world having total > $total order by total desc 	0.00151972292957066
801166	21456	sql script to find invalid email addresses	select * from people where email not like '%_@__%.__%' 	0.573471448120319
801661	29767	counting non-unique rows in table with additional criteria	select email, count(*) as occurs where provider = x and yearmonth(date) = y group by email having occurs > 1 	0.00166204368223626
802373	12653	how to count and limit record in a single query in mysql?	select sql_calc_found_rows   id, name from my_table where   name like '%prashant%' limit 0, 10; # find total rows select found_rows(); 	0.00342911526762601
802802	18132	checking sequence with sql query	select cur.* from orders cur left join orders prev      on cur.webordernumber = prev.webordernumber + 1     and cur.webstoreid = prev.webstoreid where cur.webordernumber <> 1 and prev.webordernumer is null 	0.589864010333347
804381	38085	mysql wildcard for "=" - is there one	select * from table where col like 'xyz'; select * from table where col='xyz'; 	0.458045428081486
804967	15835	mysql: getting count of comma separated values with like	select count(id) from messages where favs like 'userid,%' or favs like '%,userid,%' or favs like '%,userid' 	0.000457104391499364
808225	20690	how to determine if a field is set to not null?	select      is_nullable from      my_db.information_schema.columns where      table_schema = 'dbo' and      table_name = 'my_table' and      column_name = 'my_column' 	0.0331912492653415
808331	29106	access db loop - for each record in one table create array of records in another table	select m.num, t.modelnumber, m.modality, t.priceea into mynewtemptable from masters m  inner  join temp t on m.modality = t.modality order by m.num, t.modelnumber 	0
808475	15186	how do i get a count of associated rows in a left join in mysql?	select      `vehicle`.`id`,      `vehicle`.`stock`,      `vehicle`.`year`,      `vehicle`.`make`,      `vehicle`.`model`,      `images`.`name`,     (         select count(*)          from `images`          where `vehicle_id` = `vehicle`.`id`     ) as `image_count` from `vehicle` left join `images` on `images`.`vehicle_id` = `vehicle`.`id` where `images`.`default` 	0.000577716377204173
808611	5064	sql count for each date	select      count(created_date) as counted_leads,      created_date as count_date from      table group by      created_date 	0.000813788812137493
810958	26061	return parts of two different records from same table in one query	select a.job, a.status, a.opendate,         b.note as opennote, c.note as closenote  from job a      join note b on (a.job = b.job and b.type = 'open')      left outer join note c on (a.job = c.job and c.type = 'closed'); 	0
812681	3712	access db do line item calculation on total of a column before knowing the total	select   m.id,   t.priceeach,  ( t.priceeach - ( t.priceeach * m.margin )) as estcost,  (( t.priceeach - ( t.priceeach * m.margin )) * t.quantity ) as salessub,  ((( t.priceeach - ( t.priceeach * m.margin )) * t.quantity )      / (select sum(( t2.priceeach - ( t2.priceeach * m.margin )) * t2.quantity )         from financemasters as m2             inner join temp as t2 .....         where m2.groupnum = m.groupnum))      as salespercent into output from financemasters as m inner join temp as t ....... 	0
813300	34525	how do i convert a datetime field to a formatted string in sql server 2005?	select convert(varchar(20), getdate(), 120) 	0.00915477588278164
816671	23288	find rows whose date range contain a given date	select   ... from   yourgrouptable as y where   curdate() between y.arrivaldate and y.departuredate 	0
816851	37368	duplicate rows in oracle	select user1, name, type, trunc(date) date from table1 group by user1, name, type, trunc(date) order by user1 	0.0109554068606622
818551	23929	how do i list related blog posts ordered by the number of common tags?	select count(*) as numcommon, posts.pid, posts.post from posts                inner join p2t on p2t.pid = posts.pid                where p2t.tid in                (select p2t.tid from p2t                inner join posts on p2t.pid = posts.pid                where posts.pid = 1)                and posts.pid != 1                group by posts.pid                order by numcommon 	0
819589	32778	how to combine 2 bit columns	select col1 | col2 from mytable 	0.00174991739053927
820267	15286	how can i group by my columns in sql?	select        count(page) as visitingcount     , convert(varchar(5),date, 108) as [time]  from     scr_securistlog    where     date between '2009-05-04 00:00:00' and '2009-05-06 14:58'       and     [user] in (        select          username                     from         scr_customerauthorities         )   group by     convert(varchar(5),date, 108)  order by     [visitingcount] asc 	0.200061425403595
821370	8927	group by 'other', where groups with small contribution are included in 'other' field - mysql	select itemname, sum(percent) as pc from items group by itemtype having sum(percent) >= 0.05 union select 'other', sum(*) from   (select sum(percent) from items    group by itemtype    having sum(percent) < 0.05) 	0.0011730376214216
821506	30130	display large result set	select * from logs where ... order by ... limit offset, count 	0.0120976140805127
821650	13999	get the latest row inserted with the help of createddate field	select top 1 * from   testtable order by createddate desc 	0
821751	20961	sql selecting multiple sums?	select  sum(case when order_date >= '01/01/09' then quantity else 0 end) as items_sold_since_date,         sum(quantity) as items_sold_total,         product_id from    sales group by product_id 	0.0224043550635962
822540	7327	how do i select rows that have a column value equal to the value of the known row?	select * from table1 where user_id = (select user_id from table1 where id = 3) 	0
824048	5233	select something + an arbitrary number in mysql	select 2 as arbitrary_value, id from users; 	0.0264734326254112
825127	27278	change table cells in sql but how?	select case when date < '15:30' then '15:00 - 15:30'             when date < '16:00' then '15:30 - 16:00'             else 'after 16:00' end as category into #temp1 from table1 select count(*) as vistingcount, category as date from #temp1 group by category 	0.0170729246227345
826365	14109	how do i add two count(*) results together?	select (select count(*) from toys where little_kid_id = 900)+ (select count(*) from games where little_kid1 = 900                                or little_kid2 = 900                                or little_kid3 = 900) as sumcount 	0.00856387371730345
828650	1299	how do i get textual contents from blob in oracle sql	select utl_raw.cast_to_varchar2(dbms_lob.substr(blob_field)) from table_with_blob where id = '<row id>'; 	0.00347442638463162
832160	23608	sql: delete all the data from all available tables	select 'truncate table ' || table_name || ';' from user_tables 	0
832322	13957	question about joining two mysql tables	select * from artist     left join events         on artist.id = events.artist_id where artist.name = 'your search text' 	0.691279223600909
832584	32770	how to query many-to-many?	select movies.id, movies.name from movies inner join actors_movies on actors_movies.movie_id=movies.id where actors_movies.actor_id=$actor_id 	0.385699135342343
834912	8507	sql: search for a string in every varchar column in a database	select  'select distinct ''' + tab.name + '.' + col.name  + '''  from [' + tab.name  + '] where [' + col.name + '] like ''%misspelling here%'' union '  from sys.tables tab  join sys.columns col on (tab.object_id = col.object_id) join sys.types types on (col.system_type_id = types.system_type_id)  where tab.type_desc ='user_table'  and types.name in ('char', 'nchar', 'varchar', 'nvarchar'); 	0.00214497962784811
834962	40439	is using in (...) the most efficient way to randomly access a mysql table?	select id   from transaction_table a  where exists( select *                  from archive_table b                 where a.id = b.id ) 	0.0133420775132585
835105	13639	sql statement for evaluating multiple related tables	select * from projects left join roofing on (projectid) left join siding on (projectid) left join gutters on (projectid) left join misc on (projectid) where (roofing.status is null or roofing.status="completed") and (siding.status is null or siding.status="completed") and (gutters.status is null or gutters.status="completed") and (misc.status is null or misc.status="completed") 	0.247020678906835
835276	1643	mysql query ordering data two ways	select a.session_id, min(a.created) as start_time,  b.page_id as last_page, b.end_time from table a  inner join     (select b.session_id, max(b.created) as end_time, max(b.page_id)     from table b group by b.session_id)  on a.session_id = b.session_id group by a.session_id 	0.0870503657281511
837015	17349	many-to-one relationship to implement tags: how to count how many times a tag is used?	select t.tag_name, count(*) from tags as t     inner join comment_tags as c_t on c_t.tag_id = t.tag_id group by c_t.tag_id order by t.tag_name; 	0.00961512187162823
839313	18709	parse year from sql date	select distinct year(yourdatecolumn) from yourtable; 	0.00343702860958428
839596	22896	mysql: how to query a column whose type is bit?	select * from table where active = (1) 	0.0205858593342364
839704	22005	sum until certain point - mysql	select max(n) from ints where (select sum(money) from student order by xxx limit n) < 1000 	0.00149420615315777
840884	244	how do i create an sql query that groups by value ranges	select b.description, total = count(*) / convert(money, (select count(*) from target t2)) from target t join (     select  description = '0 to 10', lbound = 0, ubound = 10      union all      select description = '10 to 20', lbound = 10, ubound = 20 ) b on t.value >= lbound and t.value < b.ubound group by b.description 	0.000957556478652077
842224	22613	tying tables together in mysql	select u.*, c.companyname from users u  inner join companies c on u.companyid = c.companyid 	0.164197715168708
842798	29199	sql: using top 1 in union query with order by	select * from (     select top 1 *     from table     where effective_date <= '05/05/2009'     order by effective_date desc ) as current_rate union all select * from table where effective_date > '05/05/2009' 	0.418115958895426
843069	11301	what's the difference between just using multiple froms and joins?	select bugs.id, bug_color.name  from bugs inner join bug_color on bugs.id = bug_color.id where bugs.id = 1 	0.102493008674043
843642	22416	sql combining several select results	select    sum(case when casestartdate between '2009-01-01' and '2009-03-31' then 1 else 0 end) as [new cases],    sum(case when casecloseddate between '2009-01-01' and '2009-03-31' then 1 else 0 end) as [closed cases],    sum(case when casestartdate <= '2009-03-31' then 1 else 0 end) as [existing cases] from    dbo.clientcase 	0.0726639558096582
844011	14357	sqlite - query involving 2 tables	select statuses.word_id from statuses join lang1_words on statuses.word_id = lang1_words.word_id where statuses.status >= 0 order by lang1_words.word asc 	0.156816909549672
845766	17770	derby - constraints	select c.constraintname, t.tablename     from sysconstraints c, systables t     where c.tableid = t.tableid; 	0.209608125639
849348	21983	conditional column for query based on other columns in mysql	select user_id ,case      when (year(dob) < 1980 and job_title = "manager")   then 'old fart'     when (year(dob) < 1980 and job_title = "associate") then 'old timer'     when (year(dob) > 1980 and job_title = "manager")   then 'eager beaver'     when (year(dob) > 1980 and job_title = "associate") then 'slacker'     else 'nobody' end as real_title  from users 	0.00034206984432695
850827	7985	returning partially distinct/unique rows	select a.* from table as a join (    select productcode, serialnumber, max(datepurchased) as maxdate     from table    group by productcode, serialnumber ) as b on    a.productcode = b.productcode    and a.serialnumber = b.serialnumber    and a.datepurchased = b.maxdate where    a.customerid = 'xxx' 	0.0435651570009694
851324	19608	min effective and termdate for contiguous dates	select distinct e0.effdate,e0.id   from  dbo.datatable e0    left outer join dbo.datatable prev on               prev.id = e0.id   and  prev.termdate = dateadd(dy, -1, e0.effdate)           where prev.id is null 	0.0285090700981056
851642	666	count distinct and null value is eliminated by an aggregate	select a,count(distinct isnull(b,-1))-sum(distinct case when b is null then 1 else 0 end),sum(a) from   (select 1 a,1 b union all  select 2,2 union all  select 2,null union all  select 3,3 union all  select 3,null union all  select 3,null) a  group by a 	0.206387787580793
852206	16754	how can evaluate more than once data from a query?	select sum(visitingcount)as visitingcount, [time] from (   select sum(visitingcount)as visitingcount, [time]     from #temp group by [time]   union all     select count(page) as visitingcount,      (datepart(hour,date)*60+datepart(minute,date))/30 as [time]     from scr_securistlog     where date between '2009-05-04 10:30' and '2009-05-04 12:30'     group by (datepart(hour,date)*60+datepart(minute,date))/30   ) x group by [time] order by 2 asc 	0.00146351677204969
852330	11803	sum a subquery and group by customer info	select  addressstate, datepart(mm, openeddate), sum(amount) from    customer c inner join account a  on a.customerid = c.customerid inner join payments p on p.accountid = a.accountid group by   addressstate, datepart(mm, openeddate) 	0.00457909334078564
853547	21437	sql to search objects, including stored procedures, in oracle	select * from user_source 	0.582421284557548
854128	20792	find duplicate records in mysql	select firstname, lastname, list.address from list inner join (select address from list group by address having count(id) > 1) dup on list.address = dup.address 	0.000764266985051256
854626	8059	restricting results from a sql query	select a.* from table1 a where a.userid not in    (select b.userid from table1 b where b.entityid not in         (select c.entityid from table1 c where c.userid=1)); 	0.0621106035680943
855422	12271	oracle/sql: why does query "select * from records where rownum >= 5 and rownum <= 10" - return zero rows	select * from t where rownum > 1 	0.000763230985651319
855871	17371	how do i merge two partially overlapping lists in mysql?	select t1.td, t1.val as val1, t2.val as val2   from table1 as t1   left join table2 as t2   on t1.td = t2.td union select t2.td, t1.val as val1, t2.val as val2   from table2 as t2   left join table1 as t1   on t2.td = t1.td where t1.td is null 	0.00233923777789824
856770	1160	how can i get permutations of items from two subqueries in t-sql?	select a.id0, b.id1 from (select id as id0 from table0) a,       (select id as id1 from table1) b 	0.000290732294498997
858746	8883	how do you select every n-th row from mysql	select *  from (      select          @row := @row +1 as rownum, [column name]      from (          select @row :=0) r, [table name]      ) ranked  where rownum % [n] = 1 	0
859250	21800	tsql - best way to select data where a leave date falls in range of an invoice	select *  from dailyleaveledger dl where paid = 0 and       exists (select *               from invoice i               where dateadd(week,-i.numberofweekscovered,i.weekending) < dl.leavedate                and i.weekending > dl.leavedate               ) 	0.000175184329110476
859642	16728	making mysql return the table backwards	select * from news order by time desc limit 10 	0.0611011136181574
862460	26777	how to search for matches with optional special characters in sql?	select * from customers where  lastname like 'o%brien' and  replace(lastname,'''','') like 'o''brien' 	0.732526958531639
862726	27784	how can i join two queries?	select t1.tarih, t1.sira, visitingcount = isnull(t2.sira, 0) from #tmp t1 left join (  order by t1.sira 	0.196111457278089
864870	37847	how do you select latest entry per column1 and per column2?	select orders.* from orders inner join (   select emp, cat, max(date) date     from orders     group by emp, cat   ) criteria using (emp, cat, date) 	0
866465	24269	sql order by the 'in' value list	select c.* from comments c join (   values     (1,1),     (3,2),     (2,3),     (4,4) ) as x (id, ordering) on c.id = x.id order by x.ordering 	0.00768955510068371
866548	13033	combining multiple sql queries	select * from (     select *      from mytable ) subquery 	0.240822056971676
867965	34146	can sql sub-query return two/more values but still compare against one of them?	select top 10     items.*,     recommended.*,     stock.* from items  inner join recommended      on items.productcode = recommended.productcode     and recommended.type = 'topical' inner join stock      on recomended.productcode = stock.productcode     and stock.statuscode = 1 order by checksum(newid()) 	0.000194238940651606
870204	26472	using datediff in t-sql	select initialsave from  (select datediff(ss, begtime, endtime) as initialsave from mytable) atable where initialsave <= 10 	0.685532780670356
874327	23127	identifying missing matches in a mysql db	select animals.id from animals left join animals_food on animals.id = animals_food.animals_id where animals_food.food_id is null; 	0.048663023488499
876820	18519	continuous sequences in sql	select group  from thetable  group by group  having max(sequence) - min(sequence) &lt> (count(*) - 1); 	0.40735021146027
878473	17043	how do i calculate a moving average using mysql?	select      value_column1,      (      select           avg(value_column1) as moving_average      from           table1 t2      where           (                select                     count(*)                from                     table1 t3                where                     date_column1 between t2.date_column1 and t1.date_column1           ) between 1 and 20      ) from      table1 t1 	0.00129615970725445
880456	17286	how to match two email fields where one contains friendly email address	select * from table1 join table2 on (locate(table2.real_email, table1.friend_email) > 0) 	7.98782895207711e-05
881900	4772	sql server 2008 - go from select to edit quickly	select top(200) ..... 	0.548949255438998
882628	9766	sql select from a group	select t.id, t.parent, t.stage  from    t,     (       select parent, max( stage) max_stage        from t       where submitted = 1       group by parent     ) m where     t.stage = m.max_stage     and t.parent = m.parent 	0.0406315173530783
883917	14218	import dbf files into sql server	select * into sometable from openrowset('msdasql', 'driver=microsoft visual foxpro driver; sourcedb=\\someserver\somepath\; sourcetype=dbf', 'select * from somedbf') 	0.115610270796224
884393	33171	how can i select only one record per “person”, per date with an inner join in an ms access query?	select readings_miu_id, reading, readdate, readtime, miuwindow, sn,  noise, rssi, origincol, colid, ownage  from analyzed  inner join  (select [whatever the id common to all like records is] as likeid, max(analyzed.readtime) as latestdate  from analyzed   group by likeid) as maxdate on analyzed.likeid=maxdate.likeid and analyzed.latestdate = maxdate.latestdate where readdate between #4/21/2009# and #4/29/2009# 	0
885728	16573	how to verify whether two sql server databases contain equal data?	select count('x') from tabley 	0.000564210150321421
887370	31455	sql server: extract table meta-data (description, fields and their data types)	select   u.name + '.' + t.name as [table],             td.value as [table_desc],       c.name as [column],       cd.value as [column_desc] from     sysobjects t inner join  sysusers u     on  u.uid = t.uid left outer join sys.extended_properties td     on  td.major_id = t.id     and  td.minor_id = 0     and  td.name = 'ms_description' inner join  syscolumns c     on  c.id = t.id left outer join sys.extended_properties cd     on  cd.major_id = c.id     and  cd.minor_id = c.colid     and  cd.name = 'ms_description' where t.type = 'u' order by    t.name, c.colorder 	0.000255548494649558
887870	39856	single sql select returning multiple rows from one table row	select id, 'value' || n as name,        case n when 1 then value1 when 2 then value2 when 3 then value3 end as value from (select rownum n       from (select 1 from dual connect by level <= 3)) ofs, t 	0
889179	10778	fetch only first match in a query where there is an order precedents?	select * from (     select * from table where name1 like "bob" limit 1     union select * from table where name2 like "bob" limit 1     union select * from table where nicknames rlike "[,]bob[,]|[,]bob$" limit 1 ) as t1 limit 1; 	0.00193722575568081
890035	7308	oracle query to get data from table inserted in last 10 mins	select * from mytable where lastupdateddate > sysdate - (10/1440) 	0
893209	29021	getting list of cities and countries from a sql table	select distinct country, city from <table> order by country, city; 	0.000218634759263982
893655	39096	sql query to return sum and # of rows that match query	select count(*), sum(sales), sum(credits) from userdata where transactiondate between @startdate and @enddate 	0.00103858808616954
893824	40994	using avg() with sql update	select readings_miu_id, avg(rssi) from analyzedcopy2  group by readings_miu_id 	0.732491330030868
894419	32641	count(*) in a subquery	select     ord.orderheaderid    , count(det.itemid) from    orderheader ord left outer join    orderdetail det on    det.orderheaderid = ord.orderheaderid group by    ord.orderheaderid 	0.388084238166325
894793	25564	orderheader.*,count(orderdetail) from a subquery	select     orderheader.*,      orderdetailcount.countoforderdetail from orderheader join (     select         oh.orderheaderid,        count(od.orderheaderid) as countoforderdetail         from orderheader oh         left join orderdetail od on         od.orderheaderid = oh.orderheaderid         group by oh.orderheaderid ) as orderdetailcount on     orderheader.orderheaderid = orderdetailcount.orderheaderid 	0.246068144677378
895980	37772	mysql sum by qty's and values	select sum(qty) as qty, sum(qty * price) as total from cartcontents group by cart_id 	0.0477021969006225
896274	28426	select multiple ids from a postgresql sequence	select nextval('mytable_seq') from generate_series(1,3); 	0.000556233765383323
896423	38808	compare results with another table in php/mysql	select * from table1 where id not in   (select * from table2 where accountid = '1') 	0.00161264224586377
897185	32368	sql magic - query shouldn't take 15 hours, but it does	select cur.source_prefix,         cur.source_name,         cur.category,         cur.element_id,        max(cur.date_updated) as dateupdated,         avg(cur.value) as avgvalue,        sum(cur.value * cur.weight) / sum(cur.weight) as rating from eev0 cur left join eev0 next     on next.date_updated < '2009-05-01'     and next.source_prefix = cur.source_prefix      and next.source_name = cur.source_name     and next.element_id = cur.element_id     and next.date_updated > cur.date_updated where cur.date_updated < '2009-05-01' and next.category is null group by cur.source_prefix, cur.source_name,      cur.category, cur.element_id 	0.0640053280397655
898818	22922	get total amount of rows from different table with matching id	select questions.qid, question, date, sum(comments.qid)  from questions  left outer join comments on questions.qid = comments.qid group by questions.qid, question, date order by questions.date 	0
899313	17523	select values from xml field in sql server 2008	select  [xmlfield].value('(/person [xmlfield].value('(/person from [mytable] 	0.00864641757047417
901156	10936	how to calculate the smallest period of time between consecutive events?	select min(timediff(t1.`time`, t2.`time`)) as delta_t,     from temperatures t1 join temperatures t2 on t1.`time` < t2.`time` 	0
906102	14940	mysql: collect records from multiple queries into one result	select refcode from (     select pd.refcode     from pd      inner join p on pd.prdfk = p.prdid     inner join pr on pr.childcatfk = p.childcatfk     where pr.parentcatfk = 6     union all     select pd.refcode     from pr      inner join pd on pr.prddetfk = pd.prddetid     where pr.childcatfk = 14 ) subquery order by rand()  limit 10 	5.15917126647195e-05
907023	7642	how can i sum the last 15 rows in my database table?	select     sum (amount) from     (select top 15 amount from sales order by [date] desc) foo 	0
908424	8939	sql sort with limit? (non trivial)	select * from   (select * from table where id<7868 order by id desc limit 2) as foo order by id asc 	0.349698874908726
908472	23716	sql server query grouped by max value in column	select slotnumber, fileid, rank from (     select slotnumber, fileid, schedules.rank, rank() over (partition by slotnumber order by schedules.rank desc) as rankfunc     from schedules     inner join playlistslots on schedules.playlistid = playlistslots.playlistid ) tmp where rankfunc = 1 	0.00552075271642208
909059	38318	sql filtering by average	select p.name, avg(r.rating) as average from products p inner join reviews r on p.id = r.product_id group by p.name having avg(r.rating) > 3 	0.0313604921218176
909923	19184	more elegant sql?	select username   from    (select username      from table      order by userid desc) where rownum <= 50 	0.787988135686082
911942	36484	are subqueries in linqtosql guaranteed to be in the same order as their parent?	select * from tblsometable s where s.name = 'hello world' and s.id == @p1 order by s.signupdate 	0.0171659081402681
912515	35910	mysql: query the top n aggregations	select object_id, count(object_id) as action_count  from `actions`  group by object_id  order by action_count desc limit 10; 	0.00701691018807203
913112	19660	writing sql query where a value maps to all possible values	select a.name, b.marks from a, b where a.num = 0 or a.num = b.num 	0.0341554021317198
913732	31032	efficient sql procedure to get data from name value pair table into dataset?	select fff.firstname, lll.lastname from (   select ff.value as firstname   from pairtable as ff   where ff.param = 'fname'     and ff.userid = 32 ) fff, (   select ll.value as lastname   from pairtable as ll   where ll.param = 'lname'     and ll.userid = 32 ) lll 	0
915260	35469	sql; only count the values specified in each column	select      month(`date`),      year(`date`),     sum(case when `answer` = 1 then 1 else 0 end) as yes,     sum(case when `answer` = 2 then 1 else 0 end) as nope,     count(*) as total from results group by year(`date`), month(`date`) 	0
915814	9133	sql for parsing multi-line data?	select q1.issueid, q1.issuekey, d1.dockey, d1.docid from issues as q1, documents as d1 where q1.issueid in    (select  q2.issueid from issues as q2 where q2.references like ("*" & d1.docid & "*")); 	0.472173833183071
916825	19629	how do i sort by a column name that's reserved in that context?	select item, [desc] from blah order by [desc] 	0.0137180273354413
917106	18179	how to optimize m:n relation query on 3 tables	select listsid from listhasnames a where namesid in (1, 2, 3) and not exists (select * from listhasnames b  where b.listsid = a.listsid  and b.namesid not in (1, 2, 3)) group by listsid having count(*) = 3; 	0.386081543778472
917233	21133	how to query without defining table initial name?	select a.name from actors as a inner join movies as m on a.actor_id = m.actor_id where m.genre_id = 3; 	0.0184265450561005
918317	5374	sql string manipulation	select right(replicate('0', 9) + '123456789', 9)     select right(replicate('0', 9) + '255', 9)           select right(replicate('0', 9) + '12', 9)            select right(replicate('0', 9) + '1', 9)             	0.430845124479963
919136	3861	subtracting one row of data from another in sql	select a.id, a.length,  coalesce(a.length -      (select b.length from foo b where b.id = a.id + 1), a.length) as diff from foo a 	0
923721	33671	remove double join results from query	select * from tbltagglass ttg inner join tbltagglass ttgc on ttg.jobid = ttgc.jobid and ttg.partcode = ttgc.partcode where (ttg.tagheight != ttgc.tagheight or ttg.tagwidth != ttgc.tagwidth) and ((ttg.tagheight >= ttgc.tagheight and ttg.tagwidth >= ttgc.tagwidth)      or (ttg.tagheight > ttgc.tagheight and ttg.tagwidth < ttgc.tagwidth)) order by ttg.partcode 	0.216538238654977
923776	25521	sql 2005 - compress rows with nulls and duplicates into single rows	select    id,    assndate,    assntxt,    max(isnull(sally,0)) as sally,    max(isnull(ted, 0)) as ted,    max(isnull(bob, 0)) as bob from vwgrades group by   id,   assndate,   assntxt 	0.000644664068233568
924494	40631	mysql group by ordering	select * from `table` where `id` = (     select `id`     from `table` as `alt`     where `alt`.`otheridentifier` = `table`.`otheridentifier`     order by `time` desc     limit 1 ) order by `time` desc limit 3 	0.432670452905648
924698	32556	applying table-valued function to every value of some column in source table	select * from sourcetable      cross apply f(column) 	0.00129529738706349
925195	2379	select all records don't meet certain conditions in a joined table	select * from posts p where not exists(     select 1     from comments c     where c.comment_date >= 'deadline'     and p.post_id = c.post_id ) 	0
925738	23541	how to find foreign key dependencies in sql server?	select     k_table = fk.table_name,     fk_column = cu.column_name,     pk_table = pk.table_name,     pk_column = pt.column_name,     constraint_name = c.constraint_name from     information_schema.referential_constraints c inner join information_schema.table_constraints fk     on c.constraint_name = fk.constraint_name inner join information_schema.table_constraints pk     on c.unique_constraint_name = pk.constraint_name inner join information_schema.key_column_usage cu     on c.constraint_name = cu.constraint_name inner join (             select                 i1.table_name,                 i2.column_name             from                 information_schema.table_constraints i1             inner join information_schema.key_column_usage i2                 on i1.constraint_name = i2.constraint_name             where                 i1.constraint_type = 'primary key'            ) pt     on pt.table_name = pk.table_name 	0.00243657281862208
926744	15817	get the sum of time datatypes (mssql08) from a table	select      dateadd(ms, sum(datediff(ms, '00:00:00.000', my_time)), '00:00:00.000') from      dbo.my_table 	0.000107958886002571
926781	28916	how to only display a treeview expand sign [+] if children exist	select  tp.*,          (         select  1         from    table tc         where   tc.parent = tp.id         limit 1         ) as has_children from    table tp 	5.71531489962337e-05
926967	34035	find all mysql stored procedure calls?	select * from information_schema.routines where routine_definition like "%someproc%"; 	0.109191076061751
927724	36741	what is a sql statement to select an item that has several attributes in an item/attribute list?	select  item.name  from    item  where   item.attribute in ('4 legs', 'green')  group by item.name  having  count(distinct item.attribute) = 2 	0.00258623352985831
929440	41179	get string representation of a sql datetime day	select datename(weekday, '1 may 2009') 	0
932986	40021	select many fields applying distinct to only one particular field	select id, user, action, insertdate from useractions where id in (select max(id)                  from useractions                  where user ='john'                  group by action) 	0
933565	7714	most efficient way to get table row count	select table_rows from information_schema.tables  where table_name='the_table_you_want'    and table_schema = database();       	0.000212656053509351
933769	13540	postgresql data analysis / aggregates	select     distinct on (question)     question, answer, responses from     mytable order by     question, responses desc; 	0.798030229940022
934371	8050	how to encode string in oracle?	select  utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.bit_xor(utl_raw.cast_to_raw('text'), utl_raw.cast_to_raw('mask')))) from    dual 	0.190225784309238
934885	9316	mysql: select distinct names for each date?	select date,name from table group by date,name 	0
935139	3938	how can i combine these queries?	select transactioncode, tenantid,  sum(case when amount > 0 then amount else 0 end) as paid, sum(case when amount < 0 and transactiondate > dateadd("dd", -30, getdate()) then amount else 0 end) as chargedcurrent,   sum(case when amount < 0 and transactiondate > dateadd("dd", -60, getdate()) and transactiondate <= dateadd("dd", -30, getdate()) then amount else 0 end) as chargedover30 sum(case when amount < 0 and transactiondate > dateadd("dd", -90, getdate()) and transactiondate <= dateadd("dd", -60, getdate()) then amount else 0 end) as chargedover60, sum(case when amount < 0 and transactiondate <= dateadd("dd", -90, getdate()) then amount else 0 end) as chargedover90  from tbltransaction group by transactioncode, tenantid 	0.177999033676723
936322	7151	sql select counter by group	select   dense_rank() over (order by empgroupid) as counter,   empid,   empgroupid from emp order by empgroupid,empid 	0.369389821341871
937042	6646	how to make comment reply query in mysql?	select * from comments order by if(parentid = 0, id, parentid), id 	0.793960586476254
937652	16726	mysql select sum group by date	select monthname(o_date), sum(total)  from thetable group by year(o_date), month(o_date) 	0.0383176293608943
938259	3837	how to display user databases only in sqlserver?	select * from sysdatabases where name not in('master', 'tempdb', 'model', 'msdb') 	0.000339686919038287
938904	36754	mysql select of rows involving csv	select * from txn where pid like '%,11,%' or pid like '%,11'; 	0.00752119827902961
939370	38325	select forum topic with most different participants	select  poster.*, count(distinct odgovori.author) as different from    poster join    odgovori on      odgovori.na = poster.id_poster group by         poster.id order by         different desc limit 1 	0.00650973474898721
940065	4790	using results from one mysql for a second query	select  posts.* from    listen join    posts on      posts.userid = listen.listenid where   listen.userid = @current_user 	0.000935307429211531
942160	19464	extract unique pairs from table containing reciprocal relationships	select distinct     case when person1 > person2 then person2 else person1 end as person1,     case when person1 > person2 then person1 else person2 end as person2 from     couples where     relationshiptype = 'married' 	6.51108336737781e-05
944134	14195	mysql sort by 2 columns	select id, season, episode  from table  order by season asc, epsisode asc 	0.00444231912924025
944720	28698	merged sql table names	select       name,      'users' as type  from users  where name like '%alex%' union select       name,       'admins' as type  from admins  where name like'%alex%' 	0.00527250045535403
945325	26205	syncing stored procedures between two databases?	select routine_name, last_altered from information_schema.routines where routine_type='procedure' and specific_catalog='database_name' order by last_altered 	0.058384975700079
946438	16696	oracle calculation involving results of another calculation	select  cost, total, per, sum(per) over (order by cost) from    (         select  cost, sum(cost) over() as total, cost / sum(cost) over() as per         from    my_table         ) order by         cost desc 	0.114918930252915
949435	26645	list which columns have a full-text index in sql server 2005	select distinct     object_name(fic.[object_id]) table_name,     [name] column_name from     sys.fulltext_index_columns fic     inner join sys.columns c      on c.[object_id] = fic.[object_id]      and c.[column_id] = fic.[column_id] 	0.076749201814572
949465	1950	performing a query on a result from another query?	select count(*), sum(subquery.age) from ( select availables.bookdate as date, datediff(now(),availables.updated_at) as age from availables inner join rooms on availables.room_id=rooms.id where availables.bookdate between '2009-06-25' and date_add('2009-06-25', interval 4 day) and rooms.hostel_id = 5094 group by availables.bookdate ) as subquery 	0.00765117063705026
949533	36501	determine sql server version of linked server	select * from openquery(mylinkedserver,'select serverproperty(''productversion'')') 	0.324906660069342
949605	17035	sql server 2005 - select records from tbl a contained within a text field of tbl b	select     a.keywordcolumn from     tablea a     join     tableb b on b.bigtextcolumn like '%' + a.keywordcolumn+ '%' where     b.byid = @id  	0.00242643321292778
952493	27033	how do i convert an interval into a number of hours with postgres?	select extract(epoch from my_interval)/3600 	0
954422	21248	simple sql select sum and values of same column	select top 5 a.amount, b.sum from table a cross join (select sum(amount) sum from table) b order by amount desc 	0.00254269053539998
955101	4055	sql column merge and aggregate functions	select keyword, sideinfo from (     select         distint city as keyword, country as sideinfo     from table     union     select          distinct country, 'country'     from table ) as innerquery where keyword like '%blah%' 	0.399770786528854
956913	23004	sql: find rows where field value differs	select r.* from rankings r     inner join     (         select alternative_id, indicator_id         from rankings         group by alternative_id, indicator_id         having count(distinct rank) > 1     ) differ on r.alternative_id = differ.alternative_id     and r.indicator_id = differ.indicator_id     order by r.alternative_id, r.indicator_id, r.analysis_id, r.rank 	0.000337334835354803
957527	20312	can you do a count query inside another query and use the results?	select id, count(id) from tablea a where id < 5 group by id having a.value < a.id 	0.237408592544374
958627	37555	mysql - order by values within in()	select id, name from mytable where name in ('b', 'a', 'd', 'e', 'c') order by field(name, 'b', 'a', 'd', 'e', 'c') 	0.0633694160885069
964378	9822	2 sql queries in one line - how?	select * from tblproducts where productid ='$scid'                                    or (cat ='$cattype' and type ='$typetype') 	0.00737358323098026
972877	39136	calculate frequency using sql	select  a.col1, a.col2, a.count1 * 1.0 / b.count2 as freq from    (      select col1, col2, count(*) as count1      from   yourtablename      group by col1, col2      ) as a         inner join (       select col1, count(*) as count2       from   yourtablename       group by col1       ) as b             on a.col1 = b.col1 	0.0246300607043406
974133	7243	how can i change datetime format in sql?	select cast(datepart(year, mydatecolumn)  as char(4)) + '-'     + datename(month, mydatecolumn) from mytable 	0.107925718155417
977916	33673	how to get entries of current date portion from column with datetime as datatype (tsql)	select attemptdate  from dbo.changeattempt where attemptdate >= cast(floor(cast(getdate() as float)) as datetime) 	0
979927	20520	how can i join a table to itself in t-sql?	select a.[applicationtitle],     a.visits,     a.newvisists,     b.visits as pvisits,     b.newvisits as pnewvisits     from (     select [applicationtitle] as "applicationtitle",       sum([visits]) as "visits",      sum([newvisits]) as "newvisits"      from [headlinefigures]       where [datadate] >= '01/06/2009'      and [datadate] < '08/06/2009'      group by [applicationtitle]     ) as a join (     select [applicationtitle] as "applicationtitle",       sum([visits]) as "visits",      sum([newvisits]) as "newvisits"      from [headlinefigures]       where [datadate] >= '01/05/2009'      and [datadate] < '08/05/2009'      group by [applicationtitle]     ) as b on a.[applicationtitle] = b.[applicationtitle]      order by [applicationtitle] 	0.152207439388907
982932	14294	sql query to return one single record for each unique value in a column	select t.name, t.street, t.city, t.state from table t  inner join (      select m.name, min(m.street + ';' + m.city  + ';' + m.state) as comb      from table m      group by m.name ) x    on  x.name = t.name    and x.comb = t.street + ';' + t.city  + ';' + t.state 	0
983202	39449	oracle 11g sql to get unique values in one column of a multi-column query	select * from tablea where rowid in ( select max(rowid) from tablea group by language ) 	5.71367837842897e-05
984493	3026	mysql query: get all album covers	select * from album, photos  where album_id=albums.id   and albums.user_id='user_id' and photos.id = (select id from photos where  album_id = album.id order by position limit 1) 	0.0126141315132801
991246	20187	does today's date intersect existing ranges in database php/mysql	select * from thetable where curdate() between date_from and date_to 	0.00603407802246094
991756	24126	select same customer name but that has different customer address	select distinct t1.*  from [table] t1 inner join [table] t2 on t1.name=t2.name and t1.address<>t2.address 	0
993660	27118	relational database	select user.id, post.title   from user left join post on (post.user = user.id)   where (post.title like '%monkeys%')     and (user.id > 3)     and (user.id < 20) 	0.299595896915288
996708	39314	access sql, select all but last x char of a field	select left(field1, len(field1) -1) from [table] 	0
997041	36733	mysql-php querying a list to build a table	select  tasks.*, students.*,         (         select  grade         from    grades         where   grades.task_id = tasks.task_id                 and grades.username = students.username         order by                 date desc         limit 1         ) as lastgrade from    assignments a join    assignment_tasks at on      at.assignmentid = a.assignmentid join    assignment_students ast on      ast.assignmentid = a.assignmentid join    tasks on      tasks.task_id = at.task_id join    students on      students.username = ast.username 	0.0337665710903105
997195	27564	joining by datetimefield sql server	select * from table_a, table_b where table_a.sku = table_b.sku and abs(datediff(second,table_a.datetime,table_b.datetime))<=3 	0.494283315561819
997514	32811	how to convert datetime to a number with a precision greater than days in t-sql?	select datediff(minute,'1990-1-1',datetime) 	0
1001638	18134	what is the best practice to count equal values in a database?	select count(distinct country) from table 	0.0158240646547532
1002639	3042	how to query multiple sums of the same item using sql in ireport	select   sum(case when $p{onedayago} <= datetime then count else 0 end) as 'today',   sum(case when $p{oneweekago} <= datetime then count else 0 end) as 'thisweek',   sum(count) as 'thismonth' from   statistics where    name = "test"   and $p{onemonthago} <= datetime   and datetime <= $p{now} 	0.000200240144777313
1002728	19416	mysql: select emails from one table only if not in another table?	select email.address from email left outer join donotmail on email.address = donotmail.address where donotmail.address is null 	0
1003381	18157	difference between like and = in mysql?	select foo from bar where foobar like "foo%" 	0.101305791772644
1004293	30047	tsql order-by with a union of disparate datasets	select id, cat, price, name, abbrv from (select t1.id, t1.cat, t1.price, t1.price as sortprice, null as name, null as abbrv  from t1 union select t2.id, null as cat, null as price, t1.price as sortprice, t2.name, t2.abbrv     from t2    inner join t1 on t2.id = t1.id ) t3 order by sortprice desc, abbrv asc 	0.673282857051811
1012870	27876	sql to check if database is empty (no tables)	select count(distinct `table_name`) from `information_schema`.`columns` where `table_schema` = 'your_db_name' 	0.0177572920347277
1014689	15928	wordpress: generate array of tags from posts in a particular category	select tag_terms.name, count(wp_posts.id) from wp_posts  inner join wp_term_relationships as cat_term_relationships on wp_posts.id= cat_term_relationships.object_id  inner join wp_term_taxonomy as cat_term_taxonomy on cat_term_relationships.term_taxonomy_id= cat_term_taxonomy.term_taxonomy_id  inner join wp_terms as cat_terms on cat_term_taxonomy.term_id= cat_terms.term_id  inner join wp_term_relationships as tag_term_relationships on wp_posts.id= tag_term_relationships.object_id  inner join wp_term_taxonomy as tag_term_taxonomy on tag_term_relationships.term_taxonomy_id= tag_term_taxonomy.term_taxonomy_id  inner join wp_terms as tag_terms on tag_term_taxonomy.term_id= tag_terms.term_id  where cat_term_taxonomy.taxonomy='category' and cat_terms.name='apple' and tag_term_taxonomy.taxonomy='post_tag' group by tag_terms.name 	0
1016419	3142	how to find sum(field) in condition ie "select * from table where sum(field) < 150"	select * from `users` u where (select sum(size) from `users` where size <= u.size order by size) < 150 order by userid 	0.00104336490835615
1018469	4000	sql (db2) return multiple conditional counts in a single query	select sum(case when t1.a = 1 then 1 else 0 end) as a_count      , sum(case when t1.b = 2 then 1 else 0 end) as b_count   from t1  where t1.a = 1     or t1.b = 2 	0.099425171369569
1021319	26651	how to optimize mysql views	select [stuff] from orders as ord  left join (   create view calc_order_status as   select ord.id as order_id,   (sum(itm.items * itm.item_price) + ord.delivery_cost) as total_total   from orders ord    left join order_items itm on itm.order_id = ord.id   group by ord.id ) as ors on (ors.order_id = ord.id) 	0.698805763041805
1021947	15576	how can i make an average of dates in mysql?	select     from_unixtime(         avg(             unix_timestamp(date_one)-unix_timestamp(date_two)         )     ) from     some_table where     some-restriction-applies 	0.00262995683253158
1023704	40295	sql grouping: most recent record between users	select message.* from message where message.messageid in (select max(messageid) from message      group by          case when receivinguserid > sendinguserid              then receivinguserid else sendinguserid end,         case when receivinguserid > sendinguserid             then sendinguserid else receivinguserid end ) 	0
1032975	15854	selecting distinct same column values from non related tables	select month, year   from table1 union select month, year   from table2 	0
1033201	30073	mysql match brand of item that you don't know brand of?	select * from mytable where brand = (select brand from mytable where id = 300 ); 	7.72401173296399e-05
1034063	31684	import error on dates (import from oracle 10g to sql server 2005)	select isdate('15000101'), isdate('17530101'),isdate('20080101') 	0.357009954788781
1038113	34651	how to find current transaction level?	select case transaction_isolation_level  when 0 then 'unspecified'  when 1 then 'readuncommitted'  when 2 then 'readcommitted'  when 3 then 'repeatable'  when 4 then 'serializable'  when 5 then 'snapshot' end as transaction_isolation_level  from sys.dm_exec_sessions  where session_id = @@spid 	0.001331413666347
1041282	30886	t-sql looping to create a recordset	select a.name_last,         a.name_first,         ca.status,         scores.averagescore,        scores.countscore from   application a        inner join committee_applications ca           on a.application_id = ca.application_id        left join (          select application_id,                  avg(score) as averagescore,                  count(*) as countscore          from   reviews           group by application_id          ) as scores          on a.application_id = scores.application_id 	0.0752599891434568
1041536	31142	how can i select where there is a specific link in a linking table or there is no link?	select distinct v.videogroupid from videos v      left join videotags vt on v.videoid = vt.videoid where     v.creatoruserid in (1, 2, 3)      and (         vt.tagid is null          or vt.tagid in (10, 11, 12)     ) 	0.00418020027195638
1041789	12273	can i combine my two sqlite select statements into one?	select substr(date, 0,7) "month",        total(case when a > 0 then a else 0 end) "income",        total(case when a < 0 then a else 0 end) "expenses" from posts group by month 	0.00656584711086645
1042011	884	how build a select statement with dates disconsidering time?	select *  from mytable  where cast(floor(cast(mydate as float))+1 as datetime) > getdate() 	0.135777462848546
1042481	13305	mysql join with limit?	select a.* from t a where 10 >  (    select count(*) from t b     where b.category=a.category     and b.count<a.count ) 	0.708076556551274
1043162	7229	string manipulation in mysql	select   substring_index('string1::string2', '::', -1) 	0.365530888032578
1046911	18775	how to show decimal zeroes for a number in sql server	select cast(value as decimal(5,2)) from table 	0.00280949331298346
1047256	951	get results from my own and "friends" posts	select      u.username,      u.email,      m.title,      m.text  from microblog m      inner join user u on m.user_id = u.id where  m.user_id = {$user_id}      or m.user_id in (select                           following_id                       from relations r                       where follower_id = {$user_id}                     ); 	6.66875779636164e-05
1048035	16548	selecting items from one column based on values in another.	select id1,count(id2) from tbtest  where id2 in(3,10,11)  group by id1  having count(id2)=3 	0
1049702	6609	create a sql query to retrieve most recent records	select date, user, status, notes      from [sometable]     inner join      (         select max(date) as latestdate, [user]         from [sometable]         group by user     ) submax      on [sometable].date = submax.latestdate     and [sometable].user = submax.user 	0
1051544	41243	sql query for information *not* in database	select emailaddress from temp_table where emailaddress not in (select emailaddress from table) 	0.41728625203313
1054016	11211	maximum number of databases in sql server 2008	select @@max_connections as 'max connections' 	0.00257420609390182
1054984	26054	get columns of a table sql server	select * from northwind.information_schema.columns where table_name = n'customers' 	0.000630130184589426
1058609	33954	need to find out of a table has certain columns before running alter table	select 1 from information_schema.columns where column_name = 'column_name' and table_name = 'table_name' and table_schema = 'database_name' limit 1 	0
1058881	10388	pl/sql: retrieve names of procedures and functions within a package	select owner,         object_name as package_name,         procedure_name as method_name   from dba_procedures  where object_type = 'package' 	0.00836730117609774
1058934	28004	is it possible to use mysql foreign keys in innodb tables for inverse lookup?	select   referenced_table_name parent,   table_name child, from   information_schema.key_column_usage where   referenced_table_name is not null 	0.204571945162531
1059026	39295	how do i make a select which always returns zero rows	select * from tablename where 'you' = 'smart' 	0.0142827301738793
1059253	29831	searching across multiple tables (best practices)	select id, table_name, ts_rank_cd(body, query) as rank     from search_view, to_tsquery('search&words') query     where query @@ body     order by rank desc     limit 10; 	0.041396047670951
1059409	39592	retrieving the latest note (by timestamp) in a single query from a 1:n table	select users.name, notes.subject, notes.heading, notes.body  from users, notes  where users.id = notes.user_id  and notes.timestamp = (select max(timestamp) from notes where user_id = users.id) 	0
1059613	38199	extending sql query to include records beyond a given date	select *  from mytable where id in (select id from mytable where                completiondate >= to_date('29/06/08','dd/mm/yy')                   completiondate <= to_date('29/06/09','dd/mm/yy') ) 	0.00156491750450016
1060458	9932	sparse dot product in sql	select sum(v1.value * v2.value) from vectors v1 inner join vectors v2 on v1.dimension = v2.dimension where v1.vector_id = ... and v2.vector_id = ... 	0.544705987744712
1061214	10550	group sum from two tables according to date in mysql	select commission_date, sum(click_commission), sum(lead_commission), sum(total_commission) from (select date(click.time) as commission_date, click.commission as click_commission,              0 as lead_commission, click.commission as total_commission       from click       union all       select date(lead.time) as commission_date, 0 as click_commission,              lead.commission as lead_commission, lead.commission as total_commission       from lead) as foo group by commission_date order by commission_date 	5.28644038566412e-05
1061404	8425	syntax for date range sql query in openoffice base	select *  from ordertbl where orddate between '2007-01-01' and '2007-01-31' 	0.0822047988538839
1061733	18221	group by, order by, sub queries - performance problem for getting the previous row value	select    seq = identity(int, 1, 1),    cardno,    cardeventdate into #cardseq from tmp_cardevent order by cardno, cardeventdate select    t1.personid,    t1.cardeventdate,    t1.cardeventtime,    t2.personid,    t2.cardeventdate,    t2.cardeventtime from    tmp_cardevent t1    inner join #cardseq s1 on t1.cardno = s.cardno    left join #cardseq s2 on t1.cardno = t2.cardno and t1.seq - 1 = t2.seq    left join tmp_cardevent t2 on t1.cardno = t2.cardno drop table #cardseq 	0.127802006008111
1062112	9632	a sql query to form data	select a.id, a.name, b_width.value as width, b_height.value as height, b_color.value as color from table_a as a join table_b as b_width    on b_width.a_id = a.id and b_width.type = 'width' join table_b as b_height    on b_height.a_id = a.id and b_height.type = 'height' join table_b as b_color    on b_color.a_id = a.id and b_color.type = 'color' 	0.123525244884383
1062158	23927	converting mysql select to postgresql	select c.id, c.name, sum(abs(v.vote)) as score from categories c,items i, votes v   where c.id = i.category_id   and i.id = v.voteable_id   and v.created_at > '#{1.week.ago}' group by c.id, c.name order by score desc limit 8; 	0.478955612182851
1062257	34781	date is displaying again and again, how can i make group by	select distinct a.personid, a.cardeventdate as newday,... 	0.55770420672899
1062495	5087	getting non-distinct results from a distinct mysql query	select date_format(`when`, '%e_%c_%y')date, count(distinct `ip`) addresscount from `metrics` where `id` = '1' group by date 	0.00921755747002153
1062876	17778	using min on a datepart with group by not working, returns different dates	select model, make, min(datepart(year,[registration])) as yearregistered, min(saleprice) from [vehiclesales] group by model, make 	0.322395760258102
1063260	30160	get earliest timestamps for user's cards in a mysql data table	select  `username`, `card_id`, min(`timestamp`) from    `usercardinfo`  where   `timestamp` between '2009-04-01' and '2009-06-01' group by         `username`, `card_id` 	0
1067315	20150	sql group by week (monday 07:00:00 to monday 06:59:59)	select to_char(wid_date - 7/24,'iyyy'), to_char(wid_date - 7/24,'iw'), tonnes from production where to_char(wid_date - 7/24,'iyyy') = '2009'  group by to_char(wid_date - 7/24,'iyyy'), to_char(wid_date - 7/24,'iw') 	0.00374134051248866
1067410	33183	existence confirmation method of the table of mysql	select * from information_schema.tables where table_name = 'mytable'; 	0.00914074719394442
1071254	40522	database design with many type of users	select users.name, users.email, users.typeid, usertypes.type from users left join usertypes on (usertypes.id = users.typeid) where (users.id = 1) 	0.0241086922307288
1075120	24678	mysql - using data from another table.field to determine results in a query	select date_format(m.`when`, '%e/%c/%y')date      , count(`ip`) addresscount      , o.`userid`   from `metrics` m   left join `other_table` o     on m.`userid` = o.`userid`   where `projid` = '$projid'    and o.`userid` = [value]   group by date(`when`) 	0.00152885238533354
1075550	8588	how do you add an edit button to each row in a report in oracle apex?	select '' edit_link,      ... 	0.000642056120988222
1076011	20160	how can multiple rows be concatenated into one in oracle without creating a stored procedure?	select questionid,        ltrim(max(sys_connect_by_path(elementid,','))        keep (dense_rank last order by curr),',') as elements from   (select questionid,                elementid,                row_number() over (partition by questionid order by elementid) as curr,                row_number() over (partition by questionid order by elementid) -1 as prev         from   emp) group by questionid connect by prev = prior curr and questionid = prior questionid start with curr = 1; 	0.00567553407408694
1079068	39834	sorting certain values to the top	select * from stores order by country = "us" desc,  storeid 	0.000141210379677773
1082199	27722	postgresql: unknown date output format. how can you convert date output format?	select extract(epoch from date_uploaded) from files where id = 1; 	0.0740127467524997
1083866	12588	how to get number of rows affected, while executing mysql query from bash?	select row_count(); 	7.75810743006684e-05
1084229	20340	how do i create an if-then-else in t-sql	select     case when [value] < 0 then 0 else [value] end from      example 	0.644215596689012
1084506	4304	how to store articles or other large texts in a database	select.. where fulltextfield like '%cookies%'. 	0.00492826546133947
1085485	17898	optimally querying a database of ratings?	select     sum(case when score = 1 then 1 else 0 end) 'positive' ,   sum(case when score = -1 then 1 else 0 end) 'negative' ,   objectid from     ratings where     objectid = @objectid ... group by     objectid 	0.0229119189113953
1087997	15526	how do i do a 'group by' for a datetime when i want to group by just the date?	select  cast(ps.date_scheduled as date), count(*) from    payments_schedule ps left join         invoices i on      i.invoice_id = ps.invoice_id left join         orders o on      o.order_id = i.order_id where   ps.date_scheduled > '2009-06-01 00:00:00' group by         cast(ps.date_scheduled as date) 	0.00702037252961936
1090809	8499	sqlserver2000 constraints	select  'alter table ' + object_name(parent_obj) + ' drop constraint ' + object_name(id),* from sysobjects where xtype in ('f', 'pk') 	0.156219756645688
1091170	16593	sql select - return as one	select * from temp2 union all select * from temp1 where not exists (select * from temp2) 	0.01786513601644
1092477	22652	keyword search, multiple tables, php and mysql, which join to use?	select   * from   event as e   left join event_location as el on el.event_id = e.event_id   left join location       as  l on l.location_id = el.location_id where   e.keywords like '%hello%'    or e.keywords like '%world%' 	0.531368934294109
1093566	18062	combining xml with reverse paths	select     convert(xml,      (select cust_id, fname, lname from customer for xml path('customer'))),     convert(xml,      (select order_id, cust_id, shipped from purchase_order for xml path('purchase_order'))),     convert(xml,      (select line_id, order_id, quantity from line_item for xml path('line_item'))) for xml path('collection') 	0.520351662154826
1094622	24741	mysql concat with trim	select trim(both ', ' from concat(ifnull(address,''), ', ', ifnull(city,''))) from locals; 	0.710613628459543
1094996	780	select a dummy column with a dummy value in sql?	select col1, col2, 'abc' as col3 from table1 where col1 = 0; 	0.0149519840082202
1096478	32944	how to fetch unmatching records from two sql tables?	select a.id, a.name from table1 a left outer join table2 b on a.name = b.name where b.id is null union all select a.id, a.name from table2 a left outer join table1 b on a.name = b.name where b.id is null 	0
1099120	12986	sql min / max group by question	select     category,     min(startdatetime) [minstartdatetime],     max(enddatetime) [maxdatetime] from mytable group by     category order by     category,     minstartdatetime,     maxdatetime 	0.671957391710174
1100044	39567	how do i use t-sql group by with multiple tables?	select     supplier.supplierid,     count(distinct computers.computerid) as computers,     count(distinct displays.displayid) as displays,     count(distinct foos.fooid) as foos,     count(distinct bars.barid) as bars from supplier left outer join computers      on supplier.supplierid = computers.supplierid left outer join displays      on supplier.supplierid = displays.supplierid left outer join foos      on supplier.supplierid = foos.supplierid left outer join bars      on supplier.supplierid = bars.supplierid group by     supplier.supplierid 	0.439272338957093
1100099	28187	mysql, given a list, selecting the missing rows from a table	select letter from table_alphabet where letter not in ( select letter from exclude_table ) 	0
1102406	35845	avg in sql - float number problem	select     avg(cast(variable as float)),     sum(variable) from     table 	0.383101761604241
1102438	36230	how to select a computed column	select     col1,     col2,     os,     osresult = case when os < 5.1 then 'bad' else 'good' end from     table 	0.00598909642263253
1105298	19974	how can i optmize a max date query relating to a other table entity	select  e.idprotocol, e.idequip, max(t.readdate) over (partition by e.idequip) maxreaddate from    equip e join    totalizer t on      t.idequip = e.idequip 	0.00579427331499323
1106297	8395	mysql: get how many entrys for each id on each date?	select date, associate_id, count(*) as per_date from tracking group by assoicate_id, date order by date 	0
1108340	18987	mysql user defined variable	select  @r := 1   1 select  @r := @r + 1   2 	0.220133670243878
1108727	550	difference between condition in where and condition in join	select     o.* from     customer c left join      [order] o on o.customerid = c.customerid where     c.country = 'usa' and     (o.ordertype = 'cash' or o.ordertype is null) 	0.1152012411472
1109113	28012	mysql table -> can you return the same row multiple times, in the same query?	select * from menu inner join order_items on menu.item_id = order_items.item_id where order_id = 123; 	0
1109306	23933	identifying indentity column?	select *  from information_schema.columns  where table_name='tablename_here'  and columnproperty(object_id('tablename_here'),column_name,'isidentity') = 1 	0.0877932736192654
1110115	11961	pull an xml schema from a sql 2005 database	select xml_schema_namespace(n'',n'ourxmlschemanameondatabase') 	0.02795588479464
1110643	25495	can i depend on order of output when using row_number()	select orderid, customerid, orderdatetime     , row_number() over (partition by customerid order by orderdatetime) rn     , row_number() over (partition by orderdatetime order by customerid) antirn from #order 	0.763024893913847
1110832	37867	can i use mysql to join two tables based on relationships with a third table?	select `item`.*, `seat`.`face_value` from `item` join `event` on `event`.`id` = `item`.`event_id` join `seat` using (`venue_id`, `configuration`) where `seat`.`section` = `item`.`section` 	0.000438760234473635
1113517	18321	finding all nullable columns in sql 2000 database	select * from information_schema.columns where is_nullable = 'yes' 	0.000962325249033042
1114029	5227	select x posts, regardless of number of inner joined category rows	select s.*,c.*   from story s   left outer join categories c        on c.story_id=s.story_id   where story_id in (select story_id from story order by pub_date desc limit 10) 	0
1117761	14121	sql query to return rows in random order	select * from table order by newid() 	0.0114251308526627
1117827	14798	sql fallback row?	select *   from table1    where id="a" union all select *    from table1   where id="b"   and no exists (     select *        from table1       where id="a"); 	0.181601159320769
1119019	32874	finding a missing index	select * from table t1 where not exists (select * from table t2 where t2.id = t1.id - 1) 	0.12960726525253
1119525	24216	merging two tables with same column in meaning into one	select title, publisherid from books union all select name, publisherid from articles 	0
1120210	25768	selecting indexes based on column/table names	select     i.name 'index name',     object_name(i.object_id) 'table name',     c.name 'column name' from      sys.indexes i  inner join     sys.index_columns ic on i.index_id = ic.index_id and i.object_id = ic.object_id inner join    sys.columns c on ic.column_id = c.column_id and ic.object_id = c.object_id where    c.name = 'index column name'       	0.000455682287879476
1121645	4816	get last log line per unique host from table	select lt.host, lt.last_run, lt.results  from logtable lt   inner join (select host, max(last_run) last_run                from logtable                group by host) mostrecent    on mostrecent.host = lt.host     and mostrecent.last_run = lt.last_run 	0
1123727	14709	sql count years on fromdate to todate fields	select    sum((datediff(d, fromdate, todate)) / 365.25) as 'years-count' from    mytableofdates 	0.0551266742375891
1124603	35369	grouped limit in postgresql: show the first n rows for each group?	select   * from   xxx a where (   select     count(*)   from     xxx   where     section_id = a.section_id   and     name <= a.name ) <= 2 	0
1124635	6412	mysql - 'seeing' other rows	select  i.*,         qty * amount * 0.15 *         coalesce(         (         select  1 - cast(substring(substring_index(description, '%)', 1), position('(' in description) + 1) as decimal) * 0.01         from    invoice ii         where   ii.invoice = i.invoice                 and ii.description rlike 'discount[^(]*\\([0-9]+\\%\\)'         limit 1         ), 1) as vat from    invoice i 	0.0130410738999939
1126261	34176	in sql, how do i fetch a row with a specific column value if available, otherwise any other row	select * from product order by case when featured = 'y' then 0 else 1 end limit 1 	0
1127088	23802	mysql like in()?	select * from fiberbox where field regexp '1740|1938|1940'; 	0.690346793585936
1128355	19333	sql creating a column of alternating values based on a condition	select  name,          period,          value,          '1' as category from    tablea union all select  name,          period,          value,          '2' as category from    tableb 	0.000164528511895305
1128573	4907	mysql query - query to show itens that are from actual date to the max of 15 days ago	select t.*  from   table1 t where  date(t.mydate) <= date_add(current_date(), interval 15 day)  order by t.mydate desc; 	0
1129659	9141	merge 2 tables for a select query?	select p.id, count(p.id), sum(p.points) from (select userh_userid as id, userh_points as points       from users_history1       union select userl_userid, userl_points       from users_ladders1) as p group by p.id 	0.00559887405671412
1131085	19405	removing duplicate records	select  ss.sightseeingid, ss.sightseeingname, ss.displayprice,  max(sst.fromdate) from      tblsightseeings ss inner join                tblsightseeingtours sst on ss.sightseeingid =  sst.sightseeingid where    ss.isactive = 1 and ss.isdisplayonmainpage = 1 group by ss.sightseeingid, ss.sightseeingname, ss.displayprice 	0.00456250903479061
1132603	37187	mysql range and average	select avg(value), max(value), min(value) from tablename 	0.00191392232277482
1133109	16665	sql query for calculating total no. of orders per day?	select date(order_placed_date)      , count(id) as num_orders      , sum(order_total) as daily_total   from [table]  group by date(order_placed_date) 	0
1133944	17369	how to limit rows in postgresql select	select * from users limit 5; 	0.0211586940204175
1134131	13721	mysql query: displaying counts for many groups with many records	select jurasdiction_id, quarter, count(*) as num from inspections group by jurasdiction_id, quarter 	0.00369643781942501
1134272	22766	sql question: getting records based on datediff from record to record	select distinct t1.* from table1 t1 inner join table1 t2      on abs(cast(t1.date_created - t2.date_created as float)) between 1 and 2 	0
1135144	22796	mysql views: sub-joins	select whatevercolumnsyouwant   from client   join profile using (profile_id)   join email on client.profile_id = email.profile_id             and email.primary = 1   join phone on client.profile_id = phone.profile_id             and phone.primary = 1 where client.id = :whateverclientid 	0.553658166361787
1135878	17208	how do i best get the top 2 unique rows when a join is involved?	select top (2)     pm.property_id,     pm.property_name,     (select top 1 image_file      from image_master      where property_id_ref = pm.property_id) as image_file from     property_master pm where     exists (select * from image_master             where property_id_ref = pm.property_id) 	0
1138259	23603	mediawiki: how to get the last n edited articles by a user?	select distinct p.page_title from revision r, page p where r.rev_page = p.page_id and p.page_namespace = 0 and rev_user = {$userid} group by p.page_title order by max(r.rev_id) desc limit 3 	0
1138292	6599	mysql query to calculate previous week	select sum(goods_total) as total_amount, "previous week" as week from orders where order_placed_date >= date_sub(current_date, interval 14 day)  and order_placed_date < date_sub(current_date, interval 7 day) union select sum(goods_total) as total_amount, "this week" as week from orders where order_placed_date >= date_sub(current_date, interval 7 day) 	0.000391979807983664
1138748	27456	how to find the small and big id in mysql	select min(id_field),max(id_field) from table; 	0.00306909070749501
1139283	15815	create an auto-incrementing result column in oracle	select  emp_no,         row_number() over (partition by emp_no order by book_id) as book_no,         book_id from    books 	0.211397103077049
1140064	31091	sql query to get most recent row for each instance of a given key	select u.[username]       ,u.[ip]       ,q.[time_stamp] from [users] as u inner join (     select [username]           ,max(time_stamp) as [time_stamp]     from [users]     group by [username]) as [q] on u.username = q.username and u.time_stamp = q.time_stamp 	0
1140664	26978	count total rows with a group by	select count(*) from (    select tracking_num    from orders    group by tracking_num    having count(distinct order_num) = 4) as agg 	0.000773064595058806
1141603	5022	how to combine two tables in a query?	select s.query, u.username from search s inner join users u on s.userid = u.userid 	0.00468590170009885
1143313	3917	why would sqlserver select statement select rows which match and rows which match and have trailing spaces	select * from testfeature1 where id like '1' 	0.00361082857695832
1143546	5633	sql select excluding some ranges	select *  from #stock_data sd left join #exclude_ranges er     on sd.symbol=er.symbol and sd.asof between er.asof_start and er.asof_end where er.symbol is null 	0.0053512233905037
1143574	894	convert nchar column to nvarchar and trim whitespace	select rtrim(cast([myncharcolumn] as nvarchar)) 	0.291206865521575
1144172	11787	how to count the number of times a character appears in a sql column?	select len(requestedreportparams) - len(replace(requestedreportparams, ',', '')) from yourtable where ..... 	0
1144897	2235	select statement gets byte[] and string but not xml	select convert(varchar(30), getdate(), 126) 	0.758516660686358
1145152	15624	concat and sql	select  col1 || col2 as mycol1 where concat(rtrim(col1),(rtrim(col2)) = 'searchvalue' 	0.50252121537394
1148059	18205	linking tables when grouping	select x.col1, x.col2, x.col3, x.col4, patient_names.patient from table x join (select col3, min(col4) as mcol4 from table group by col3) as y     on x.col3=y.col3 and x.col4=y.mcol4 inner join patient_names on x.col1 = patient_names.patient_no where x.col2='xxx'; 	0.0422497619221369
1148930	5100	empty set returned from query	select nurse, (max(nopats) - min(nopats)) as growth   from hospital  where year between 2000 and 2002  group by nurse  order by growth desc limit 1; 	0.0251658921840035
1150251	4099	first day of this week and last week	select dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) as lastweekstart select dateadd(wk, datediff(wk, 0, getdate()), 0) as thisweekstart select dateadd(wk, datediff(wk, 0, getdate()) + 1, 0) as nextweekstart 	0
1150715	54	how can i use max and limit together in mysql	select     max(id) from     (           select id           from yourtable          order by id          limit 5     ) as t1 	0.44141682227567
1151819	19807	sql join multiple values from column into one cell	select memberid, membername, group_concat(fruitname) from a left join b on a.membername = b.membername group by a.membername; 	0
1152322	39830	eliminating duplicate rows in postgres	select distinct on (upper(name)) name from names order by upper(name); 	0.0143521096944019
1152404	38463	select all items in a table that do not appear in a foreign key of another table	select * from   groups g  where not exists      (       select 1        from users_groups ug        where g.groupid = ug.groupid     ); 	0
1154091	24686	mysql - need help counting id's that correspond to certain in other tables	select players.player_id, (select count(*) from tries where player_id = players.player_id) tries, (select count(*) from penalties where player_id = players.player_id) penalties from players; 	0
1154536	31113	mysql joins to display categories, subcategories and subsubcategories	select  * from    (         select  distinct                 c.name as c_name,                 sc.name as sc_name,                 ssc.name as ssc_name         from    categories c         left join                 subcategories sc         on      c.id = sc.category_id         left join                 subsubcategories ssc         on      sc.id = ssc.subcategory_id         group by                 c.name, sc.name, ssc.name with rollup         having  c_name is not null         ) q order by         c_name, sc_name, ssc_name 	0.023647668524808
1159754	25555	sql latest date	select  customerid, max(date) from    purchase group by customerid, year(date), month(date) 	0.00434064307269705
1160337	33523	sql query to count and list the different counties per zip code	select  zipcode,  count(distinct county) from  zipcode group by  zipcode having  count(distinct county) > 1 	0.000664619302790869
1163059	24528	how to sort mysql results based on a specific foreign value?	select order.*, orderfield.value   from order   left outer join orderfield on order.`order id` = orderfield.`order id`  where orderfield.`field id` = :firstnamefieldid  order by orderfield.value 	0
1164350	29620	retrieving a row, with data from key-value pair table in mysql	select `customer`.*, `ca1`.`value1` as `wedding_date`, `ca2`.`value1` as `test`  from `customer`  left join `customer_attributes` as `ca1` on customer.customerid = ca1.customerid  and ca1.key1='wedding_date' left join `customer_attributes` as `ca2` on customer.customerid = ca2.customerid and ca2.key1='test' where (customer.customerid = '58029') 	0
1165928	31862	convert postgis table to sql server 2008	select  st_askml(the_geom) from the_spatial_table where .... 	0.426752785457344
1168992	33245	how to access multiple users' database via jdbc	select * from some_other_user.their_table; 	0.0755821045250611
1169280	34424	sql - query help: finding a local maximum	select b.index from   points as a, points as b, points as c where  a.index = b.index-1 and c.index = b.index+1    and a.value < b.value   and c.value < b.value 	0.243982888218616
1171019	1865	sql server table creation date query	select         [name]        ,create_date        ,modify_date from         sys.tables 	0.120244147193355
1174518	32433	grouping/aggregating sql results into 1-hour buckets	select slot_hour, sum(order_id) from     onehourslots     left join orders on datepart(hh, order_date) = slot_hour group by slot_hour 	0.152101144071836
1174571	20892	mysql join condition	select      s1.id, s1.name, s1.parent, s2.id as child, max(s2.mark) as mark, m.ranking  from      students s1     inner join students s2 on (s1.id = s2.parent and s2.mark >= 20)      left join marks m on (s1.name = m.name)  group by      s1.id, s1.name, s1.parent, child, ranking; 	0.596962156164781
1177495	25254	how to make result set from ('1','2','3')?	select items.extract('/l/text()').getstringval() item from table(xmlsequence(         extract(xmltype(''||         replace('aa,bb,cc',',','')||'')           ,'/all/l'))) items; 	0.0272100767855612
1181374	26779	mysql select statement distinct for multiple columns	select uniqueid, stringid, subject from data_table where uniqueid in  (   select max(uniqueid)    from data_table   group by stringid  ) order by uniqueid desc 	0.029222492706752
1182035	30664	mysql - get elements from a link table but only those elements	select * from `packages`  where 2 = (    select count(*) from `package_publications`     where `packages`.id = `package_publications`.package_id       and `package_publications`.publication_id in (11, 47)  ) 	0
1182533	16722	mysql query - show results that are not in another table	select lesson.id, p1.first_name, p1.surname, start_time, instrument.name  from  lesson l join person p1 on l.student = p1.id join person p2 on l.teacher = p2.id join instrument i on i.id = l.instrument_id left join invoice_lesson il on l.id = il.lesson_id where il.lesson_id is null order by surname 	0.000976486560908626
1186316	33766	sql/c# mvc: order over multiple fields	select case when iscompany = 1 then company     else lastname + ', ' + firstname end as displayname from mytable order by displayname 	0.147168460851595
1193581	31764	how do i obtain information about a nullable foreign key from information_schema views?	select     isnull(pk.table_name, object_name(i.[object_id])) as 'pk_table_name',     fk.table_name as 'fk_table_name',     c.constraint_name as 'constraint_name' from     information_schema.referential_constraints c     join     information_schema.table_constraints fk on c.constraint_name = fk.constraint_name     left join     information_schema.table_constraints pk on c.unique_constraint_name = pk.constraint_name     left join     sys.indexes i on c.unique_constraint_name = i.[name] 	0.00046289207103582
1195763	20184	is there any way to programmatically "move" an oracle table definition from one database to another?	select dbms_metadata.get_ddl('table','dept','scott') from dual; 	0.005164379287661
1196260	38726	retrieve most recently executed sql command (t-sql)	select dmexqrystats.last_execution_time as [executed at], dmexsqltxt.text as [query] from sys.dm_exec_query_stats as dmexqrystats cross apply sys.dm_exec_sql_text(dmexqrystats.sql_handle) as dmexsqltxt order by dmexqrystats.last_execution_time desc 	0.0184719458923069
1196363	30048	how can i create multiple columns from one db field in sql server?	select fn.propertyvalue firstname,        ln.propertyvalue lastname,        etc... from userprofile fn    join userprofile ln       on fn.propertyname = 'first name'           and ln.propertyname = 'last name'           and fn.user = ln.user    join userprofile em       on fn.propertyname = 'first name'           and em.propertyname = 'email'           and em.user = fn.user 	0.00017647222494539
1198116	37803	sql command for reading a particular sheet, column 	select [columnname] from [sheetname$] where [columnname] = 'somevalue' 	0.0570003313716712
1199131	24910	counting the rows of multiple distinct columns	select count(distinct(str(a) + ',' + str(b))) from @yourtable 	0
1199263	6973	sql query to eliminate rows	select * from mytable where id not in (select id from mytable where code = 'badcode') 	0.0544625550702876
1201128	31943	sql: populate single row(tbl 1) from multiple rows(tbl 2); cross db	select personid,         min(case                 when applicationid = 1                 then personapplicationid         end) as 'drimaster',         min(case                 when applicationid = 6                 then personapplicationid         end) as 'driclient' from tblapplicationassociation where applicationid in (1,6) group by personid 	0.00709935937147049
1201160	15946	how do i determine if a database role exists in sql server?	select database_principal_id('role') if database_principal_id('role') is null 	0.177428478304214
1201541	34652	converting sql server null date/time fields	select isnull(cast(somedatetime as varchar(20)), 'no') from sometable 	0.347765898010879
1202047	1152	pull back rows from multiple tables with a sub-select?	select distinct *   from articles t   join people p on p.spubid = t.spudid and p.slast ilike 'chow'  where t.skeywords_auto ilike'%pm2%'  limit 1; 	0.00109349766889885
1202668	7152	sql query that gives distinct results that match multiple columns	select document_id from table where tag = 'tag1' or tag = 'tag2' group by document_id having count(distinct tag) = 2 	0.00688344744739939
1202840	8905	is there cleaner syntax for where id != 1 and id != 2 and id != 7	select * from table where id not in (1,2,7) 	0.00260790766894765
1203171	6163	return identity in sqlserver compact	select @@identity as identity 	0.287350542589933
1207922	23806	how to find which unique table index a sql full text index uses	select      object_name(fti.object_id) as 'table name',     i.name as 'index name',     c.name as 'column name' from      sys.fulltext_indexes fti inner join      sys.index_columns ic on ic.object_id = fti.object_id and ic.index_id = fti.unique_index_id inner join      sys.columns c on c.object_id = ic.object_id and c.column_id = ic.column_id inner join     sys.indexes i on fti.unique_index_id = i.index_id and fti.object_id = i.object_id 	0.0359925868061798
1210430	29105	tips for deduping a list based on priority column	select a.*, b.priority  from tablea as a join tableb as b on b.sourceid = a.sourceid and b.priority = (select max(priority) from tableb where b.sourceid = a.sourceid) 	0.000290725791489708
1210686	37681	mysql date time query help?	select product_name from products where release_date > current_timestamp 	0.570380959999959
1211412	32348	netezza sql syntax to convert numeric yyyymmdd format into date	select  date(to_char(20090731,'99999999')) as number_as_date; 	0.405430397615182
1212073	6360	check constraint to make sure values in a character column are all digits	select 1 where 'foo' not like '%[^0-9]%' select 1 where '123' not like '%[^0-9]%' select 1 where 'aa1' not like '%[^0-9]%' select 1 where '1bb' not like '%[^0-9]%' select 1 where null not like '%[^0-9]%' select 1 where '   ' not like '%[^0-9]%' select 1 where '' not like '%[^0-9]%' 	6.32696273386836e-05
1213916	12113	mysql select where first character is	select if( left( myfield, 1) = 'a', 1, 0) from mytable; 	0.0636170649918379
1214035	226	mysql - if it starts with a number or special character	select *      from thread     where forumid not in (1,2,3)      and title not regexp '^[[:alpha:]]' order by title asc 	0.0825101870846968
1214576	32367	how do i get the primary key(s) of a table from postgres via plpgsql?	select                  pg_attribute.attname,    format_type(pg_attribute.atttypid, pg_attribute.atttypmod)  from pg_index, pg_class, pg_attribute, pg_namespace  where    pg_class.oid = 'foo'::regclass and    indrelid = pg_class.oid and    nspname = 'public' and    pg_class.relnamespace = pg_namespace.oid and    pg_attribute.attrelid = pg_class.oid and    pg_attribute.attnum = any(pg_index.indkey)  and indisprimary 	0
1216873	3888	sql select sum from other table as a column via junction table	select e.employeename, count(t.taskid) as [number of tasks], sum(t.duration) as [time spent] from employee e, employeetasks et, tasks t where et.employeeid = e.employeeid and et.taskid = t.taskid group by e.employeename 	0
1218064	20740	mysql join syntax for one to many relationship	select     t1.id     , t1.title     , t2.link_id as refid from     t1     left join t2         on t1.id = t2.title_id and t2.link_id = 123 group by t1.id; 	0.494884494595048
1227907	29032	return another value when row is inexistent	select  coalesce(t1.name, 'item nonexistent'), t2.intvalue from    table2 t2 left outer join         table1 t1 on      t1.id = t2.id 	0.000951555987994007
1227921	39532	portable sql to determine if a table exists or not?	select * from <table> 	0.418034481578822
1228856	31947	can i use oracle sql to plot actual dates from schedule information?	select distinct      t.schedid     ,level as paymentnum     ,add_months(t.startdate,level - 1) as duedate     ,(level * t.paymentamt) as runningtotal from schedtest t connect by level <= (t.term / t.frequency) order by t.schedid, level 	0.00923966727448783
1229437	22447	find a specific column in an unknown table in a database?	select table_name, column_name, data_type, is_nullable, column_default   from information_schema.columns  where column_name like '%watcher%' [and table_schema = 'database'] 	0.00107002508171724
1229968	33731	is it possible to list all foreign keys in a database?	select rc.constraint_name fk_name , kf.table_schema fk_schema , kf.table_name fk_table , kf.column_name fk_column , rc.unique_constraint_name pk_name , kp.table_schema pk_schema , kp.table_name pk_table , kp.column_name pk_column , rc.match_option matchoption , rc.update_rule updaterule , rc.delete_rule deleterule from information_schema.referential_constraints rc join information_schema.key_column_usage kf on rc.constraint_name = kf.constraint_name join information_schema.key_column_usage kp on rc.unique_constraint_name = kp.constraint_name 	0.000335979808589948
1230481	2447	printing out 25 most recently added tables	select table_name   from information_schema.tables  where table_schema='your_db_name`  order by create_time desc  limit 25 	0.00174075728466932
1232556	34329	listing categories with the latest comments/activities with mysql	select * from categories left join comments on categories.id = comments.category_id where comments.id is null or comments.id in ( select id from comments as a2 where categories.id = a2.category_id order by id desc limit 5 ) 	0.00429288356400141
1235449	21841	how to handle multiple one->many relationships?	select articlename, articlestatus, author, isbn_number  from articles    inner join status on articles.spubid = status.spubid      inner join people on articles.spubid = people.spubid    where people.saffil = 'abc'  union all  select papername, paperstatus, author, null from papers    inner join status on papers.spubid = status.spubid      inner join people on papers.spubid = people.spubid    where people.saffil = 'abc' 	0.123224854064426
1236394	40326	top 5 with most friends	select bandid, count(*) as fans from bandfriends order by fans desc group by bandid limit 5; 	0.00046991161731677
1239081	31181	split string in t-sql	select right('this is my text.',5) 	0.06707700280753
1239667	28305	t-sql datetimes substracting	select datediff(mi, start, end) 	0.0821476461032286
1239713	16901	sql server - selecting most recent record to generate a list of changes	select query.historyid     from     (select max(track.trackid) as maxtrackid, track.historyid     from rs_historytracker track     where track.trackdatetime <= '2009-08-06 23:59:59'       and track.action like 'status:%'     group by historyid) as query, rs_historytracker track     where track.historyid = query.historyid       and track.trackid = query.maxtrackid       and track.action like 'status:%:draft' 	0
1241758	10656	store data series in file or database if i want to do row level math operations?	select sum(), count() from fact join dimension where filter group by dimension attribute 	0.282878054846344
1242562	20751	how should i join these tables?	select distinct t.id, t.title   from threads t left join comments c on t.id = c.thread_id  order by c.date desc 	0.702156955549818
1242985	32100	access database query for using month from a date	select abs(sum(lunch)) as sumoflunch, abs(sum(snacks)) as sumofsnacks, abs(sum(tea)) as sumoftea from yourtable where eventdate >= #2009/08/01# and eventdate < #2009/09/01#; 	0.00201872697889729
1243975	35526	export query results into csv file issue in sql server	select    cast(personcode as varchar(50)) + '\t'   + cast(personreference as varchar(50))     from people 	0.542519508391734
1244500	32428	way to retrieve the objects quoted_identifier (and associated ansi) settings?	select      objectpropertyex (object_id('myproc'), 'execisquotedidenton')     objectpropertyex (object_id('myck'), 'isquotedidenton') 	0.032069805212459
1248903	26685	how do i join aggregations results from several sql selects?	select      year(joindate) year,               sum(case [level] when 1 then                      1 else 0 end) gold,              sum(case [level] when 2 then                      1 else 0 end) silver,              sum(case [level] when 3 then                      1 else 0 end) bronze,         count([level]) total from        members group by    year(joindate)  order by    year(joindate) 	0.0851917955607423
1249125	40691	aggregate function and other columns	select column_name, aggregate_function(column_name) from table_name where column_name operator value group by column_name 	0.0920558784215039
1249485	1835	replace part of string in mysql	select distinct stuff  from (   select rtrim(substr(data, 1, locate('(', data) - 1)) as stuff    from foo ) t; 	0.0701788418459904
1249513	2573	to select the newest 3 questions from postgresql by php	select title from questions order by was_sent_at_time desc limit 3; 	0.00100784248425736
1250156	2581	how do i return rows with a specific value first?	select * from `users` order by (`city` = 'new york') desc, `city` 	0
1252580	13794	sql selecting column names as values	select period, 'truck' as nameofvehicle, truck as value from vehicle union all select period, 'car', car from vehicle union all select period, 'boat', boat from vehicle 	0.000347011097586974
1255502	22528	mysql get distinct values and count how many of each?	select status, count(*) as c from table group by status; 	0
1255528	13174	sql join related question	select e.empid, e.firstname, e.lastname, e.email, e.phone, o.othername from employee e left outer join othername o on e.firstname = o.name 	0.773472680039439
1258469	16023	sql server 2005 syntax help - "select info based upon max value of sub query"	select a.*, b.*, c.jobid, c.value from  invoice as a inner join customer as b on a.customerid = b.customerid inner join (    select jobid, value, customerid,    row_number() over (partition by customerid order by value desc) as ordinal    from jobs    where year = 2008 ) as c on (a.customerid = c.customerid and c.ordinal = 1) 	0.132331763925141
1258592	35969	how to select in result set union all operation	select * from     (select foo.admward, bar.* from foo inner join bar on foo.an = bar.an          where foo.admward in (16,17)    ) t    unpivot     (diag for proptype in (diagnoses         , underlyingcause         , underlyingcause2         , underlyingcause3         , underlyingcause4         , underlyingcause5         , complications         , complications2         , complications3         , complications4         , complications5         , otherdiagnoses         , otherdiagnoses2         , otherdiagnoses3         , otherdiagnoses4         , otherdiagnoses5         )    ) u; 	0.0314809452532065
1258963	5355	sql: select n% with pictures, (100-n)% without pictures	select top @n * from (       select top 60 percent * from tbuser       order by haspicture desc       union       select top 40 percent * from tbluser       where haspicture = 0       and userid not in       (         select top 60 percent userid from tbuser         order by havepicture desc       )  ) 	0.0994227462908966
1259370	33674	how to sql return only all duplicated entries	select t1.day, t1.id from   test t1 inner join test t2 on t1.id <> t2.id and t1.day = t2.day 	0
1259536	11913	convert binary string to bigint in mysql?	select cast(conv(substring(md5(id), 1, 16), 16, 10) as unsigned integer) from sometable; 	0.14626546509494
1259663	20357	pgsql time diffrence?	select date_part('second',date1) - date_part('second',date2) 	0.530857555127585
1261189	11252	mysql: count entries without grouping?	select b.name, a.the_count from   some_table b,    (select name, count(*) as the_count   from some_table   group by name) as a where b.name = a.name 	0.0035951962801371
1262149	10362	optionally use a union from another table in t-sql without using temporary tables or dynamic sql?	select field1, field2, ... from table1 where cond union select field1, field2, ... from table2 where cond and param = 1 	0.0387647699248848
1262448	13908	using mysql, how do i select query result rank of one particular row?	select p1.id, p1.name, count( p2.name ) as rank     from people p1     join people p2      on p1.name < p2.name     or (          p1.name = p2.name          and p1.id = p2.id     ) group by p1.id, p1.name order by p1.name desc , p1.id desc limit 4,1 	0.000310655428996887
1263883	22984	using order and group with mysql to get the highest number for each group	select max(bid), *  from tblauctionbids  where username='$username'  group by auction_id  order by id desc  limit 10 	0
1264287	18055	group by and order with joining tables	select s.owner_id, s.owner_name, max(u.imag_id) as last_image_id from upload_tbl u inner join owner_tbl s on s.ownerid = u.owner_id group by s.owner_id, s.owner_name order by last_image_id desc limit 3 	0.128330196185206
1264450	17860	how to get the latest items distinctively in a row?	select latest.cardnumber, latest.max_trans_date, t2.balance   from     (       select t1.cardnumber, max(t1.trans_date) as max_trans_date       from transactions t1       group by t1.cardnumber     ) latest     join transactions t2 on (       latest.cardnumber = t2.cardnumber and        latest.max_trans_date = t2.trans_date     ) 	0
1265497	12265	string compare with 'strange chars' in sqlserver	select 1 where 'å' = 'a'     select 1 where 'å' collate latin1_general_ci_ai = 'a'    select 1 where 'é' = 'e'     select 1 where 'é' collate latin1_general_ci_ai = 'e'    	0.73130612008836
1266427	27755	sql join history table to active table ssrs report	select s.sbsb_id, m.meme_name, l.clcl_id as claim_id from cmc_sbsb_subsc s inner join cmc_meme_member m on s.sbsb_ck = m.sbsb_ck inner join cmc_cddl_cl_line l on l.meme_ck = m.meme_ck where  s.sbsb_id = '120943270' union select s.sbsb_id, m.meme_name, h.clcl_id as claim_id from cmc_sbsb_subsc s inner join cmc_meme_member m on s.sbsb_ck = m.sbsb_ck inner join cmc_cldh_den_hist h on h.meme_ck = m.meme_ck where  s.sbsb_id = '120943270' 	0.0233540439918519
1266717	30787	sql - two months from todays date in oracle	select * from table where date_column >= add_months(trunc(sysdate) + 1, 2); 	8.72328139884283e-05
1266767	41316	tsql get partial string of datetime value?	select right(convert(varchar, enddtfield - startdtfield, 121), 15) as duration from mytable; 	0.00022369876350705
1266960	30362	sql query to search schema of all tables	select * from information_schema.columns where column_name like '%create%' 	0.0195648090413602
1268403	37209	sql select and count all items that have occured before	select dt, count(q2.yourdate)     from (select distinct convert(varchar,yourdate,101) dt from yourtable) t1     join yourtable q2 on dateadd(d,-1,convert(varchar,yourdate,101)) < dt     group by dt 	8.1438971149492e-05
1270362	19139	how can i get all user created databases in sql server 2005?	select * from sys.databases where owner_sid != 1 	0.00459626721263025
1270895	11318	listing both null and not null in mysql query	select name, sum(isnull(ref)) as is_null, sum(not isnull(ref)) as is_not_null from table group by name; 	0.679532953712478
1272012	37724	find the amount of missing attributes in an eva design.... (remove the subquery from this sql join)	select    ob.objectid   ,count(at.attributeid) [total count of attributes]         ,count(oa.attributeid) [count of attributes for this object]   ,sum(case when oa.attributeid is null then 1 else 0 end) [count of missing attributes]  from @attributes at   cross join @objects ob   left outer join @objectattributes oa    on oa.objectid = ob.objectid     and oa.attributeid = at.attributeid  group by ob.objectid  having count(distinct oa.attributeid) > 0 	0.00300015771061659
1273007	21707	selecting records limited by only those with both criteria met	select * from employees where  employeeid in (select memberid from skilllist where skillname = 'nunchuck') and  employeeid in (select memberid from skilllist where skillname = 'bow staff') 	0
1273855	7965	y or n in an sql result	select case when col1 > 25 then 'y' else 'n' end as value1 from table1 	0.0373248469977973
1273871	7950	sql query: joining two fields from two separate rows	select d.uid, date, u.value + ' ' + u2.value as fullname from datedata as d  left join user as u on u.uid = d.uid and u.fid = 3 left join user as u2 on u2.uid = d.uid and u2.fid = 4 	0
1275381	39401	c# sql top as parameter	select top (@topparam) * from table1 	0.368876146201225
1275743	11292	retrieve data from remote server in sql server!	select * from opendatasource('sqlncli',     'data source=london\payroll;integrated security=sspi')     .adventureworks.humanresources.employee 	0.0205703279405537
1276133	40589	how to get the weight for a stored image in delphi 2009?	select octet_length(column) from table t; 	0.00339198329575659
1276157	38496	sql-time difference	select count(*) from table1 t1 inner join table2 t2 on t1.id = t2.id where      (t1.timestamp - t2.timestamp > 1000) or      (t2.timestamp - t1.timestamp > 1000) 	0.122120099430838
1276521	22937	how do i analyse time periods between records in sql data without cursors?	select theday, avg(timetaken) avgtimetaken from (   select      convert(date, logins.datetimestamp) theday     , datediff(ss, logins.datetimestamp,         (select top 1 datetimestamp          from auditdata userinfo          where userid=logins.userid          and userinfo.activitycode=2          and userinfo.datetimestamp > logins.datetimestamp )        )timetaken from auditdata logins where      logins.activitycode = 1 ) logintimes group by theday 	0.00163801951180761
1277762	11954	mysql: searching a single table multiple times?	select    distinct e1.entry_id  from   table e1  inner join   table e2 on e1.entry_id=e2.entry_id  where    e1.property='color' and    e1.value='blue' and    e2.property='shape' and    e2.value='circle' 	0.00206057924178381
1278109	12011	sql query to select at most one valid row by date w.r.t. foreign key	select dateranks.* from (     select     s1.stateid,     s1.vehicleid,     s1.validfromdate,     rank() over (partition by s1.vehicleid order by s1.validfromdate desc) as 'daterank'     from [state] s1     where     validfromdate <= '8/14/2009' ) dateranks where     dateranks.validfromdate <= '8/14/2009'     and daterank = 1 	0
1279569	27083	sql: combine select count(*) from multiple tables	select  (select count(*) from foo1 where id = '00123244552000258') + (select count(*) from foo2 where id = '00123244552000258') + (select count(*) from foo3 where id = '00123244552000258') 	0.001894708685654
1283016	25549	longest distance between lat/longs in a list	select coor1.longitude as lon1,        coor1.latitude as lat1,        coor2.longitude as lon2,        coor2.latitude as lat2,        (acos(          cos(radians(coor1.latitude))  *           cos(radians(coor1.longitude)) *          cos(radians(coor2.latitude))  *          cos(radians(coor2.longitude)) +           cos(radians(coor1.latitude))  *          sin(radians(coor1.longitude)) *          cos(radians(coor2.latitude))  *          sin(radians(coor2.longitude)) +          sin(radians(coor1.latitude))  *           sin(radians(coor2.latitude))          ) * 6378                                )  as distancekm from coordinates coor1,      coordinates coor2 where not (coor1.longitude = coor2.longitude and coor1.latitude = coor2.latitude) order by distancekm desc limit 1;                                  	0.00408212375905451
1283955	24928	determine varchar content in nvarchar columns	select * from tablename where columnname <> cast(cast(columnname as varchar(200)) as nvarchar(200)) 	0.00870690427120726
1283997	18547	mysql query for all search terms in index	select emp_name,count(distinct date) as daycount  from employee  where date in ('08-01-2009', '08-02-2009') group by emp_name having daycount=2 	0.357362555797829
1284463	19591	c# sql parent child table select query help	select parent.id, parent.name from parent  left outer join select child.id as childid, child.name as childname from child on child.parentid = parent.id order by parent.name 	0.1252209733131
1285743	30323	top x results per day with sql in access	select t1.date, t1.symbol, t1.mpr from table1 t1 where t1.mpr in (   select top 2 t2.mpr from table1 t2   where   t2.date = t1.date   order by t2.mpr desc ) 	0.000103752038856062
1286366	12811	how to exclude duplicate rows when joining a table with itself	select * from test t1 left outer join test t2 on t1.siteid = t2.siteid and t1.id < t2.id 	0.000115789445000256
1287583	5590	how do i join this sql query to another table?	select  * from    (         select  top 40                  tbrm_tagmap.tagid, count(*) as cnt         from    tbrm_tagmap         group by                 tbrm_tagmap.tagid         order by                 count(*) desc         ) q join    tags on      tags.id = q.tagid order by         cnt desc 	0.366657172089329
1288058	41156	conditional count on a field	select      jobid, jobname,     sum(case when priority = 1 then 1 else 0 end) as priority1,     sum(case when priority = 2 then 1 else 0 end) as priority2,     sum(case when priority = 3 then 1 else 0 end) as priority3,     sum(case when priority = 4 then 1 else 0 end) as priority4,     sum(case when priority = 5 then 1 else 0 end) as priority5 from     jobs group by      jobid, jobname 	0.0918146042749802
1289288	27791	to use other table as a where criteria in sql	select q.question_id, q.title     from questions      q         inner join tags t on q.question_id=t.question_id     where tag = $1      order by q.was_sent_at_time     desc limit 50 	0.0216159077598824
1289997	307	mysql query exclude a certain entry	select name from table where type = $type and name not in (select entry from t where id = $id ); 	0.000240117978828309
1291208	2482	case in order by few columns	select * from table order by   case when @flag = 0 then r.status else null end,   r.[date] desc 	0.205217808798806
1292221	15684	grouping consecutive "wins" in a row	select  symbol_id,         coalesce(avg(if(res, cnt, null)), 0) as avgwin,         coalesce(max(if(res, cnt, null)), 0) as maxwin,         coalesce(avg(if(not res, cnt, null)), 0) as avglose,         coalesce(max(if(not res, cnt, null)), 0) as maxlose from    (         select  symbol_id, streak, count(*) as cnt, res         from    (                 select  g.*,                         @streak := @streak + ((profit > 0) xor @result) as streak,                         @result := (profit > 0) as res                 from    (                         select  @streak := 0,                                 @result := false                         ) vars,                         t_game g                 order by                         symbol_id, date                 ) q         group by                 symbol_id, streak         ) q2 group by         symbol_id 	0.00277460692623473
1292254	14501	list of all tables in database, and number of rows in each one?	select table_name,table_rows from  information_schema.tables where table_schema = 'yourdatabase' 	0
1292755	22232	mysql: min() and max() against a string value	select productreference, min(sizeorder) as minsizeid, max(sizeorder) as maxsizeid,  (select sizename from size where sizeorder = min(products.sizeorder)) as minsizetext,  (select sizename from size where sizeorder = max(products.sizeorder)) as maxsizetext from (products inner join size on products.sizefk = stonesize.sizeid)  where id = 132 group by productreference; 	0.00566264097123935
1296785	39859	how to group data into buckets in microsoft sql	select name,  case when [base/day] <= 325 then '300 <= 325'      when [base/day] <= 350 then '325 <= 350'      when [base/day] <= 400 then '350 <= 400' end as bucket, [base/day] from (     select name, round([dr# base]/days_worked,0) as 'base/day' from mytable ) t order by 1, 2, 3 	0.0934641097297083
1299916	6855	sql 2005 - query to find tables with most rows	select      [tablename] = so.name,      [rowcount] = max(si.rows)  from      sysobjects so,      sysindexes si  where      so.xtype = 'u'      and      si.id = object_id(so.name)  group by      so.name  order by      2 desc 	0.00158117726846367
1302702	17263	sql returning 0 records / date problem?	select convert(char(23),yourdate,121) from yourtable 	0.157274643208084
1303125	3007	sub queries and sorting? (order by)	select * from articles_view where    ((articles_view.skeywords_auto ilike '%ice%') or (articles_view.skeywords_manual ilike '%ice%'))    order by (articles_view.authors[1]).slast 	0.704901330570195
1304530	8981	describe in a from subquery	select * from information_schema.columns where table_schema = 'database name' and table_name = 'table name' and any condition you want...; 	0.319508044221055
1305056	14836	selecting all corresponding fields using max and group by	select * from deal_status inner join   (select deal_id as did, max(timestamp) as ts   from deal_status group by deal_id) as ds   on deal_status.deal_id = ds.did and deal_status.timestamp = ds.ts 	0.000152822945538771
1305473	3403	find row with maximum value of id in mysql	select a.id, a.version from articles a where a.version = (     select max(version)     from articles b     where b.articleid = a.articleid ) 	0
1307298	26966	deleting a stored procedure in sql server	select     object_name(object_id) from     sys.sql_modules where     definition like '%' + 'mysp' + '%' 	0.690129848078579
1308861	3421	how do i form an sql query using date_sub to check for yesterday's data or if it's monday, to check for friday's data?	select * from daily_records and date = date_sub(curdate(), interval if(date_format(now(), '%w') = 1, 3, 1) day) 	0.00446656398411985
1310143	15459	sql query: data with comma	select @groupedtext = coalesce(@groupedtext, '') + [text] + ','      from requirement      where campaignid = @campaignid      order by [text] 	0.143553182722805
1312689	10620	how do i query for a max value and return date found	select     yourtable.*     from yourtable         inner join (select                         max(yourvalue) as yourvalue                         from yourtable                         where yourdate>=_startdatetime                              and yourdate<=_enddatetime_                    ) dt on yourtable.yourvalue=dt.yourvalue 	0.00126433695616289
1313212	38807	oracle get stored procedure last modified date	select  last_ddl_time, timestamp from    dba_objects where   object_type = 'procedure'         and object_name = 'prc_mine' 	0.00044141603134691
1314133	18819	how to select a row where one of several columns equals a certain value?	select * from mytable where columna=myvalue or columnb=myvalue or columnc=myvalue 	0
1315124	34501	how to select dates greater than current using date_format	select * from table where mytime > now() 	0.00072403594112186
1316159	29944	should i move columns on a wide mysql table to the left if they are used often?	select * 	0.0158859833693246
1317554	11826	search mysql query	select * from table where match(message) against ('hello*'  in boolean mode) 	0.599931941508723
1318640	28906	how can i make a mysql sum query return zero instead of null if there are no records?	select coalesce(sum(rating),0) as this_week from table_name    where unix_timestamp(created_at) >= unix_timestamp() - 604800) 	0.000380322004063377
1320790	1501	need to get data from a table which contains unique id with different category in mysql	select artist_id, category, count(*) as total from table group by artist_id, category 	0
1321096	3988	how to union queries from the same table in mysql	select name      , sum( case results when '1' then 1 else 0 end ) as counta       , sum( case results when '2' then 1 else 0 end ) as countb   from table   where results in ( '1', '2' )  group by        name 	0.000822567164812725
1321250	24252	creating breadcrumbs structure from sql query	select     c.name + ' >> ' + b.name + '>>' + a.name as breadcrumb from         tblorganisation as a left outer join                       tblsubgroup as sg on a.subgroupid = sg.subgroupid left outer join                       tblorganisation as b on sg.raoid = b.raoid left outer join                       tblrao as rao on rao.raoid = b.raoid left outer join                       tblorganisation as c on c.raogid = rao.raogid where     (sg.raoid is not null) and (a.orgid = @orgid) union select     c.name + ' >> ' + a.name as breadcrumb from         tblorganisation as a left outer join                       tblrao as rao on rao.raoid = a.raoid left outer join                       tblorganisation as c on c.raogid = rao.raogid where     (rao.raoid is not null) and (a.orgid = @orgid) union select     name as breadcrumb from         tblorganisation as a where     (raogid is not null) and (orgid = @orgid) 	0.506314035858779
1321402	38926	how do i get all of the latest "versions" from my table with one mysql query?	select * from table t      inner join (             select original, max(version) as version        from tabel        group by original      ) tmax on tmax.original = t.original and tmax.version = t.version 	0
1321946	12915	t-sql, remove space in string	select unicode(substring('18 286.74', 3, 1)) 	0.144415029688887
1322001	12249	sql left outer join with only some rows from the right?	select table_a.empno from   table_a left outer join table_b on table_a.empno = table_b.empno  where table_b.status<>'d' 	0.325340165748167
1322877	29417	retrieve roots with nodes in a hierarchy with pl/sql	select myid       ,connect_by_root myid root from myview  start with myid in ('targetid1', 'targetid2', 'targetid3')  connect by prior myid = myparentid 	0.0392877035200392
1323494	8369	get current connection protocol in sql 2000	select net_library from sysprocesses where spid = @@spid 	0.0169536817761757
1327332	8217	time difference between two times in the same table	select  date as current_date, next_date - date as difference from    mytable mo cross apply         (         select  top 1 date as next_date         from    mytable mi         where   mi.date > mo.date         order by                 date         ) q 	0
1327474	41010	subquery returns more than one row sql	select   case b.on_loan       when 'y' then 'in lib'       when 'n' then c.duedate end   as availability,   a1.isbn,   a.class_number  from book_copy b join book a1     on a1.isbn = b.isbn  join (select min(c.duedate), c.isbn  from loan c     join  book a     on a.a.isbn = c.isbn          where a.isbn = 123456 and datereturned is null   group by  c.isbn    ) c   on a1.isbn =  c.isbn  where a.isbn = 123456 	0.030470100562494
1329774	33390	multi-query sql condensed to one result	select     count(case when e.genepresentid = c.geneid then c.libraryid else null end) as 'gpcount',     count(case when e.geneabsentid = c.geneid then c.libraryid else null end) as 'gacount' from     as_event e, as_choicesupport c where e.as_id = c.as_id and c.libraryid = ? <sql:param value="${libraryid}"/> group by     c.as_id order by     e.as_id 	0.0658756735090312
1330846	14856	sql two tables, one result with extras	select t.id,         t.class_id,         t.pupil_id,         c.class_id as expr1,         c.class_name,         c.class_day,         c.class_orderview  from classes as c left outer join timetable as t         on (c.class_id = t.class_id) and (t.pupil_id = mypupil) 	0.00744238075150668
1330998	30837	sql server enumerate current session variables	select * from sys.dm_exec_sessions where session_id = @@spid 	0.035566243875418
1333340	233	date fields in mysql, finding all rows that don't overlap and returning only the difference	select *    from schedule as s1 where   s1.user = 'ondra' and not exists (    select * from schedule as s2    where     s2.user = 'zizka'     and (       s2.start between s1.start and s1.end        or       s2.end between s1.start and s1.end        or        s1.start > s2.start and s1.end < s2.end      ) ) 	0
1333623	35931	sql how to find non null column?	select     case         when a is not null then 'a'         when b is not null then 'b'         when c is not null then 'c'         when d is not null then 'd'     end from     mytable 	0.00635732198541295
1337216	10138	analyzing data from same tables in diferent db instances	select distinct(  a.rolein ) , a.activityin, b.activityin  from      taskperformance@dm_prod a,     taskperformance b,      activities@dm_prod c,     activities d where b.rolein = 0     and b.activityin = d.activityin      and d.activityid = c.activityid     and c.activityin = a.activityin order by b.activityin , a.activityin 	0
1339624	22106	sql - select unique rows from a group of results	select  r.registration, r.recent, t.id, t.unittype from    (      select registration, max([date]) recent     from @tmp      group by       registration     ) r left outer join      @tmp t  on  r.recent = t.[date] and r.registration = t.registration 	0.00011619152903303
1340775	2078	sql select multi-columns into multi-variable	select @variable1 = col1, @variable2 = col2 from table1 	0.124462414959201
1342898	15888	function to calculate median in sql server	select    customerid,    avg(totaldue) from (    select       customerid,       totaldue,       row_number() over (          partition by customerid           order by totaldue asc, salesorderid asc) as rowasc,       row_number() over (          partition by customerid           order by totaldue desc, salesorderid desc) as rowdesc    from sales.salesorderheader soh ) x where     rowasc in (rowdesc, rowdesc - 1, rowdesc + 1) group by customerid order by customerid; 	0.231392229448897
1345931	24180	sql - select rows based on a hierarchy of conditions	select * from ( select id, type, row_number() over (partition by id order by type desc) rn from #temp ) a where rn = 1 	0.000138472112868653
1346345	15578	mysql: count occurrences of distinct values	select name,count(*) as count from tablename group by name order by count desc; 	0.000411848919932072
1347894	7402	order by null first, then order by other variable	select id, number from media where user = 10 order by (case when number is null then 0 else 1 end), id 	0.00244576845092926
1348046	24416	oracle: using pseudo column value in the same select statement	select calculated_output process, calculated_output || '-output2' name from (     select 'output1' calculated_output from dual ) 	0.0101538208531306
1352090	32600	counting matches in sql	select     departments.departmentname,            count(surveys.departmentid) as [survey count] from         departments left join               surveys on departments.departmentid =  surveys.departmentid  group by departments.departmentname 	0.0528423350711379
1356658	39274	how do i find which database uses a file	select * from sys.master_files 	0.0207464191731178
1360695	16440	finding the latest post by author	select a.id,  (select count(*)  from posts  where a.id = posts.post_author  and posts.post_type = 'post'  and posts.post_status = 'publish') as post_count,  (select posts.id  from posts  where a.id = posts.post_author  and posts.post_type = 'post'  and posts.post_status = 'publish'  order by posts.post_date desc limit 1) as latest_post_id  from users as a  order by post_count desc 	0
1360737	12672	mysql selecting linked rows	select a.item_id     from table_a a     join table_b b on b.item_id = a.item_id    where b.user_id in (1, 2) group by a.item_id   having count(*) = 2 	0.00658021396126692
1361532	16220	sql joining 2 similar tables	select columns from t1 union select columns from t2 	0.0194687575078152
1363780	39456	in sql in a "group by" expression: how to get the string that occurs most often in a group?	select a, b from (   select a, b, row_number() over (partition by a order by c_b desc) as rn   from (      select a, count (b) as c_b, b      from table      group by a, b   ) count_table ) order_table where rn = 1; 	0.000254129397672849
1364319	16656	ssms and sqlcmd displays only the first 8000 characters	select replicate(convert(varchar(max), 'a'), 9000) 	0.0108290199109748
1365389	38077	select latest entry per day and corresponding data	select t.timestamp,        t.npass,        t.nfails   from test_results t   join (select max(tt.timestamp) 'maxtimestamp'          from test_results tt      group by date(tt.timestamp)) m on m.maxtimestamp = t.timestamp 	0
1365918	39266	find a result from a .doc type that store in a varbinary(max) column	select id, (other fields), documentcolumn from dbo.yourtable where contains(*, 'microsoft word') 	0.000696634399782525
1366039	13919	selecting rows from sql server where a casting issue occurs	select * from thistable t where isdate(t.value) = 1  	0.00994817336824682
1366511	39556	how to sort sql result using a pre defined series of rows	select ids.id, ids.name from ids_table ids left outer join sequences_table seq where ids.id = seq.id order by seq.sequ_no, seq.pos, ids.name, ids.id 	0.000938141899649544
1367156	38354	merging two sql select statements	select a.source, a.destination, b.destination from [table b] as a inner join [table b] as b on a.destination = b.source 	0.0297818224746278
1367394	10470	unque numbering rows in sql server for duplicate values	select   row_number() over (partition by uname order by u.uname) as rownumber           ,u.uname  from  (  select 'ferriec' as uname union all           select 'ferriec' as uname union all           select 'ferriec' as uname union all           select 'timneya' as uname union all           select 'timneya' as uname union all           select 'grayd' as uname ) as u 	0.00143424554018511
1368084	28730	can i re-use an expression in a mysql query as a variable for another field?	select variable1      , complex_function(variable1, other_column) as variable2      , yet_another column   from (select complex_operation as variable1              , other_column              , yet_another_column           from whatever) dt 	0.0963158394437763
1368087	20717	multiple criteria search	select    c.*     from customertable c         inner join (select                         customerid                         from table1                         where columna =filter1                     union                     select                         customerid                         from table2                         where columnb =filter2                     union                     select                         customerid                         from table3                         where columnc =filter3                    ) dt on c.customerid=dt.customerid 	0.116736829206263
1368331	22216	show only most recent date from joined mysql table	select d.docid, doctitle, c.dateadded, c.content from document d left join content c on c.docid = d.docid where dateadded is null     or dateadded = (         select max(dateadded)         from content c2         where c2.docid = d.docid     ) 	0
1368527	16013	how do i select a column based on condition?	select ordr_num as num, ordr_date as date,      case when @status<>'cancelled' then ordr_ship_with else null end as shipwith  from order  where ordr_num = @ordrnum 	0.000933318252460263
1368632	19309	how to return a failure if a table is empty	select cast(count(*) as integer) as row_count from mytable 	0.0277376817736585
1368702	8527	selecting time ranges from date time fields in access	select          sum(iif(format(s.studystartdatetime,'hh:mm:ss')                  between "08:00:00" and "08:09:59",1,0)) as "8:00 - 8:10",         sum(iif(format(s.studystartdatetime,'hh:mm:ss')                  between "08:10:00" and "08:19:59",1,0)) as "8:10 - 8:20",         ...     from dbo_study_viewx211_rpt as s 	0
1369483	37154	is it possible to remove the union between these 2 query and how to create this constrain?	select t.id from table1 as t     join table1 as a on a.fromid = t.fromid    join table2 as o on o.othertableid = t.fromothertableid where  54 in (a.person, o.person) 	0.482116285559192
1369938	13671	using a sql ranking function with a derived column	select      row_number() over (order by sub.points) as 'row number',     sub.firstname,     sub.lastname,     sub.points from (     select          table.firstname,          table.lastname,          calculatedvalue(table.number) as points     from          table     ) sub order by     sub.points 	0.673109837690168
1371192	26629	oracle: find index creation date from systables/information_schema?	select dbms_metadata.get_ddl('index','dept_idx','scott') from dual; 	0.012647937238408
1372864	16643	mysql 'in' clause and the returned record set order	select * from t where t.id in(4,78,12,45) order by find_in_set(t.id,'4,78,12,45'); 	0.0280216490702392
1373559	23559	mysql join based on max(timestamp)	select ratecode, rate, id, ratetypeid, date, entrytimestamp  from ratedefinitions,  (select ratetypeid, max(entrytimestamp) as max_timestamp from rates  group by ratetypeid) as inner_table where inner_table.ratetypeid = ratetypeid and innertable.max_timestamp = timestamp 	0.0372037005908407
1373693	366	sql server sp optimal way to get multiple cursors with related data	select * from [master] m where exists (         select * from [details] d where d.[columna] = 'α' and d.masterid = m.id) select * from [detail] d where d.[columna] = 'α' 	0.723601934090281
1373833	32135	how do i 'subtract' sql tables?	select ...   except   select ... 	0.0244832946932272
1374197	13680	retrieving data from mysql in one sql statement	select branches.br_field1, branches.name as br_name, branches.br_field3,   businesses.field1 ad bu_field2, businesses.name as bu_name from   ... 	0.00228415450072962
1374487	10771	how do i query for "per day" results for a given date range in ms sql?	select count(*),        datepart(year,created) as [year],        datepart(month,created) as [month],        datepart(day,created) as [day] from table where created >= '8/1/2009'       and created < '9/1/2009'       and datepart(hour,created) >= 8       and datepart(hour,created) <= 17 group by datepart(year,created), datepart(month,created), datepart(day,created) 	0
1375520	10828	mysql: joining 3 tables, limit results by first table?	select pd.prod_drop_id, pd.prod_drop_name, pd.prod_drop_available,        min(pp.product_id), min(cp.product_image_sm) from prod_drop pd     left join prod_drop_products pp         on pp.prod_drop_id = pd.prod_drop_id     left join cart_product cp        on cp.product_id = pp.product_id  group by pd.prod_drop_id, pd.prod_drop_name, pd.prod_drop_available order by prod_drop_id desc 	0.000759279757261137
1375826	12305	mysql view - value from one column where some other column is max	select t1.*, t2a.* from table1 t1 left join table2 t2a  on (t1.table1_id = t2a.table1_id) left join table2 t2b  on (t1.table1_id = t2b.table1_id and t2a.table2_id < t2b.table2_id) where t2b.table2_id is null  and t1.table1_id = ?; 	0
1378291	26953	sql query to return an item within range or nearest range	select top 1 d.id   from (         select id, case when (@weight >= lowerbound)                              and (@weight <= upperbound) then 0                         when (@weight < lowerbound) then lowerbound-@weight                         when (@weight > upperbound) then @weight-upperbound                    end as distance           from weightrange        ) d   where d.distance is not null   order by d.distance asc 	0.000183638007219545
1380855	5271	search for accentuated char in mysql	select 'lél' like '%é%' collate utf8_bin; 1 select 'lél' like '%e%' collate utf8_bin; 0 	0.591363922610381
1381131	32073	how to write sql query for these 5 tables?	select   b.bookid        , b.name        , b.author        , b.publisher        , c.condition        , c.comments   from book b        inner join copy_book cb on b.bookid = cb.bookid        inner join user_copy uc on uc.copyid = cb.copyid        inner join copy c on c.copyid = uc.copyid   where uc.userid = <the user id that you want> 	0.222592786014991
1382812	3388	how can i select records in mysql when a foreign key doesn't return anything?	select v.id, v.game_id, v.xbox360, v.ps3, v.pc, v.wii, v.other, v.thumbnail, v.vid_info, v.sdvid, v.hdvid, unix_timestamp(v.date_added), gd.name, avg(vg.rating) from videos v left join game_data gd on gd.id = v.game_id left join video_ratings vr on v.id = vr.video_id group by videos.id, video_ratings.video_id order by videos.date_added desc limit 10 	0.00275733853599106
1383259	31584	database query to get 10 most records by date field	select top 10 eventname, eventdate from eventstable order by eventdate desc 	0
1383516	16432	date difference in mysql to calculate age	select date_format(from_days(datediff(now(), dob)), "%y")+0 as age from sometable 	0.000363071859603362
1386610	18641	mysql: retrieve latest unique records	select *  from table t join ( select max( id ) as id, sum( item_qt ) as sum_item_qt from table where `timestamp` >= date_sub( now( ) , interval 5 minute ) group by member_id )t2 on t2.id = t.id order by t.id desc limit 10 	0
1388175	37865	mysql - finding out balancing figure from 2 tables	select tunion.product_id, (   (ifnull((select sum(s.qty) from stock s where s.product_id=tunion.product_id),0))-   (ifnull((select sum(p.qty) from sales p where p.product_id=tunion.product_id),0)))   as quantity    from (select distinct s.product_id from stock s   union all select distinct p.product_id from  sales p)   as tunion group by tunion.product_id 	0.00891924420413796
1389952	4965	sql table query setting	select     t1.uid,     t2.limit as a,     t3.limit as b,     t4.limit as c from     tbl t1     inner join tbl t2 on         t1.uid = t2.uid         and t2.type = 'a'     inner join tbl t3 on         t1.uid = t3.uid         and t3.type = 'b'     inner join tbl t4 on         t1.uid = t4.uid         and t4.type = 'c' 	0.686307608318433
1390400	36534	selecting by datetime field in sql server	select col1 from mytable where validuntil > '7/9/2009 8:45:30 pm' 	0.0141295907378182
1392012	38314	showing all duplicates, side by side, in mysql	select event_date, user from eventlog group by event_date, user having count(*) > 1 order by event_date, user 	0.0399193195490199
1392654	15184	sql comparing 2 tables with a link table	select *  from user u inner join hierarchyset h on h.clientid = u.clientid left outer join linktable l on      l.hierarchsetid = h.hierarchsetid  and u.userid = l.userid) where l.hierarchsetid is null and l.userid isnull 	0.00293506301211252
1393250	25599	getting multiple records from xml column with value() in sql server	select t.c.value('.', 'varchar(100)') as activity from @mydoc.nodes('(/root/activities/activity)') as t(c) 	0.000198386145993864
1394249	13489	simple sql question about getting rows and associated counts	select    a.id,    a.title,    count(distinct c.id) as numcomments,    count(distinct v.id) as numvotes from    articles           a   left join comments c on c.parentid = a.id   left join votes    v on v.parentid = a.id group by    a.id,    a.title 	0.733834239945348
1394603	38967	getting an average from subquery values or another aggregate function in sql server	select  avg(pagecount) from (  select    count(actionname) as pagecount  from   tbl_22_benchmark ) mytable 	0.0187626402083564
1395619	38978	sql: return percentage without decimal place	select round((t1.f_count / (select count(*) from utb where user_id = 1))*100) as ratio 	0.0210272319981445
1395641	24236	query to find a partial match	select * from schedule_items where start like 'some-date%' 	0.00687860838794821
1397178	38249	sql max() question	select m1.* from messages m1 left outer join messages m2    on (m1.location_id = m2.location_id and m1.revision < m2.revision) where m2.location_id is null  order by date, revision; 	0.752379552150922
1398333	24150	sql server combining two columns as one column if a conditions happens	select plus - minus as new_column from accounting 	0.000814632002702212
1399471	23356	how do i find a related record matching a date range using ms sql query	select id, merchantid, name from priceplan pp inner join (     select merchantid, max(validfrom) as validfrom     from priceplan     where validfrom <= '7-sep-09'      and validupto >= '9-sep-09'     group by merchantid ) pp2 on pp.merchantid = pp2.merchantid     and pp.validfrom = pp2.validfrom 	0
1400451	40969	sql to find articles with all of a set of tags	select article_id from  applied_tags  where tag_id in (<input tag set here>) group by article_id having count(*) = <count of input tags> 	0
1402869	35785	joining to a limited subquery?	select   apps.name,   releases.release_id,   releases.release_date  from apps inner join releases  on apps.app_id = releases.app_id where not exists (   select * from releases as r   where r.app_id = apps.app_id   and r.release_data > releases.release_data ) 	0.26421472446937
1403456	37104	how to sort by custom count with postgresql?	select   (select count(*) from workers w where w.company_id=c.id and w.country='usa') as mycount,   c.id,   c.company_name from   companies c order by mycount desc 	0.236196301773321
1406230	30464	sql aggregrates without a group by	select task.*,   (select sum (act_cost) from projcost where task_id = task.task_id) as act_cost,   (select sum (target_cost) from projcost where task_id = task.task_id) as target_cost from task 	0.536973500572787
1406663	31177	how can i aggregate two classes of values in a sql query?	select user_id, sum(case billable when 1 then (end - start) end) as can_bill,   sum(case billable when 0 then (end - start) end) as unbillable 	0.0163122102286417
1409822	9959	sql get char at position in field	select substring('hello',3,1) 	0.0011454074391068
1410820	5446	how to split a really long mysql result set into two lines?	select substring(col, 1, 50) from foo union all select substring(col, 51) from foo 	0.00681681741080882
1411666	6339	comparison query to compare two sql server tables	select 'table1' as tablename, name, lastname from     table1 outer join table2 on table1.name = table2.name2                               and table1.lastname = table2.lastname where table2.name2 is null union select 'table2' as tablename, name2 as name, lastname2 as lastname from     table2 outer join table1 on table2.name2 = table1.name                               and table2.lastname2 = table1.lastname where table1.name is null 	0.0405610023007199
1412195	18125	determine which part(s) of where statement failed	select   if(mem_username='test@example.com','true','error: bad username') as mem_username,   if(mem_password ='abc123','true','error: bad password') as mem_password' from members where mem_username='test@example.com' and mem_password='abc123' 	0.102642060016861
1412665	10008	selecting a single row in mysql	select * from tbl where id = 123 or colname4 = 'x' or colname8 = 'y' limit 1 	0.000983439356482647
1412734	24602	find what table a specific index belongs to	select object_name(object_id) from sys.indexes where name = '...' 	0.00596037206876204
1415438	4515	how to find rows in one table that have no corresponding row in another table	select tablea.id from tablea left outer join tableb on (tablea.id = tableb.id) where tableb.id is null order by tablea.id desc 	0
1415636	28378	sql, how to query with multiple foreign keys in a table?	select        projects.project_id     , projects.title     , projects.start_time     , projects.description     , projects.user_id     , projects.winner_user_id     , users.username as owner     , winneruser.username as winner from projects inner      join users     on projects.user_id=users.user_id inner      join users winneruser     on projects.winner_user_id=winneruser.user_id 	0.00252557269958719
1416003	21356	sql select from multiple tables	select p.pid, p.cid, p.pname, c1.name1, c2.name2 from product p left join customer1 c1 on p.cid = c1.cid left join customer2 c2 on p.cid = c2.cid 	0.0117359662455527
1417889	38170	get product onhand quantity	select t.pid,           t.txt,           t.price,           t.qty - ifnull(qs.qty_sold, 0) 'onhand_qty'      from products t left join (select o.pid,                   sum(o.qty) 'qty_sold'              from orders o) qs on qs."o.pid" = t.pid     where t.pid = ? 	0.00954451965162918
1418728	17564	sql statement to include rows that have no matches in a correlated subquery	select t.fkid,           ifnull(nu.num_users, 0)      from table_2 t left join (select t.fkid,                   count(distinct t.username) 'num_users'              from table_2 t              join table_1 a on a.id = t.fkid                            and subtime(a.endtime, sec_to_time( 60*60 )) = t.time          group by t.fkid) nu on nu.fkid = t.fkid    where t.fkid in (147, 148, 149) group by t.fkid, nu.num_users 	0.0662272209786951
1419737	29929	sql query that throws away rows that are older & satisfy a condition?	select a.seq      , a.buddyid      , a.mode      , a.type      , a.dtcreated from mim as [a] join (select max(dtcreated) from min group by buddyid) as [b]      on a.dtcreated = b.dtcreated      and a.userid = b.userid where userid='ali' order by dtcreated desc; 	0.000903410215844978
1419915	33641	how to merge rows in ms access?	select a.id,      a.field2,      a.field3 + iif(isnull(b.field3),'',b.field3),      b.field4,      b.field5 from table1 a left join table1 b on b.id = a.id + 1 where a.field2 is not null 	0.025628894633961
1420139	34867	how do i detect oracle xe?	select * from v$version  select * from product_component_version 	0.72027487743819
1420308	25269	is this the correct way to sort rows which have the same insert datetime?	select name, species, birth from pet order by species, birth desc 	0.000672539995296304
1421842	7782	how to match/compare values in two resultsets in sql server 2008?	select  * from    users u where   not exists         (         select  null         from    projectskill ps         where   ps.pk_project = @someid                 and not exists                 (                 select  null                 from    userskills us                 where   us.fk_user = u.id                         and us.fk_skill = ps.fk_skill                 )         ) 	0.104293544920051
1422405	22918	can i join a table based on an sql if-statement?	select * from songs s where    accesstype='public'    or (accesstype='whitelist'        and exists (select null from whitelist wl where            wl.songid = s.id and wl.userid=s.userid))    or (accesstype='blacklist'        and not exists (select null from blacklist bl where            bl.songid = s.id and bl.userid= s.userid)) 	0.0107231509994221
1422506	28482	vacuum postgresql db from php	select age(datfrozenxid) as age from pg_database where datname='your_db'; 	0.10708565095007
1422726	21203	mysql return rows matching year month	select * from table where extract(year_month from timestamp_field) = extract(year_month from now()) 	0
1423059	30166	generating php/mysql reference id	select last_insert_id() 	0.0715653777019069
1423907	28650	how do you join tables from two different sql server instances in one sql query	select * from server1table     inner join server2.database.dbo.server2table on ..... 	8.94820878135167e-05
1424999	30680	get the records of last month in sql server	select *  from member where datepart(m, date_created) = datepart(m, dateadd(m, -1, getdate())) and datepart(yyyy, date_created) = datepart(yyyy, dateadd(m, -1, getdate())) 	0
1425173	16856	how to give string value in the query?	select temp.* into  ” & stroutput & “  from temp 	0.0133082854410916
1425894	16116	mysql: how to inner join a table but limit join to 1 result with the highest vote or count?	select a.*, b.*   from items a        left join votes b on a.item_id = b.item_id                          and b.total_yes = (select max(total_yes)                                                from votes v                           where v.item_id = a.item_id) order by a.post_date desc, b.total_yes desc 	0.00302817748815571
1427061	26230	how do i get mysql results of todays date?	select x,y,z from t where date(added)=curdate() 	0.000287842195743189
1428864	18852	sql - using group by and count to collect the total of unique two-field combinations	select count(*), project.pname from project group by project.pname 	0
1429930	27636	sql query need to get names where count(id) = 2	select     (select name from participants where id=p.participantid) as name from    programparticipants as p where    .... (the part where you find count(name)>1) 	0.0112578448723285
1430562	34795	sql selecting rows that are in both tables	select * from productosa intersect select * from productosb ; 	0.000180972411168318
1430978	17580	how to get a total time?	select     id     , lunch_intime      , lunch_outtime      , format(cdate(lunch_outtime) - cdate(lunch_intime),                  "hh:nn:ss") as total_lunch_time  from     table; 	0.000151788306700537
1431809	33693	sql select subquery	select     c.companyname,    c1.ctctypid, c1.contactname,    c2.ctctypid, c2.contactname,    c3.ctctypid, c3.contactname,    c4.ctctypid, c4.contactname from    companytable c left outer join    contacttable c1 on c.enqid = c1.enqid and c1.ctctypid = 1 left outer join    contacttable c2 on c.enqid = c2.enqid and c2.ctctypid = 2 left outer join    contacttable c3 on c.enqid = c3.enqid and c3.ctctypid = 3 left outer join    contacttable c4 on c.enqid = c4.enqid and c4.ctctypid = 4 	0.623435579725008
1433978	37457	array variable in mysql	select 2 from dual union all select 34 from dual union all  select 24 from dual 	0.259004360502492
1434621	35908	exclude set from left outer join	select i.id,            i.location,            area.description       from incident_vw i  left join area_vw area         on area.code = i.area_code      where (i.area_code not in ('t20', 'v20b', 'v20o', 'v20p')             or i.area_code is null) 	0.500595127747799
1435238	33385	selecting 2 counts in 1 query	select  projects.* , (select count(*) from tasks where project_id = projects.project_id and assigned_user_id = 1) as task_assigned_count, , (select count(*) from tasks where project_id = projects.project_id and created_user_id = 1) as task_created_count from projects 	0.00503887305630351
1435935	40163	how to get the logical name of the transaction log in sql server 2005	select name from sys.master_files where database_id = db_id()   and type = 1 	0.0103968604345364
1437413	35080	mysql statement: spliting rows values into new columns	select t1.uid, t21.field_value first_name, t22.field_value last_name from table1 t1, table2 t21, table2 t22 where t1.uid=t21.uid and t1.uid=t22.uid and t21.fid=1 and t22.fid=2 	0.000196113742297586
1438280	14340	count with date intervals	select a.userid, count(a.userid) as [count] from table1 as a     inner join     (         select userid, min([date]) as mindate         from table1         group by userid     ) as b         on a.userid = b.userid where [date] between mindate and dateadd(day, 30, mindate) group by a.userid 	0.0121916202567561
1439021	18555	rightmost occurrence string match in mysql	select substring_index(filename, '.', -1) from mytable 	0.00771668878692839
1439279	31191	sql - beginning of hour, month etc	select dateadd(month, datediff(month, 0, getdate()),0)  select dateadd(hour, datediff(hour, 0, getdate()),0) 	0.00015977345520545
1439965	4374	sort by name, but ignore quotes?	select * from yourtable order by trim(both '"' from title); 	0.107665885465894
1441675	29990	sql server - top 1 post per member ordered by createddate	select p.*   from post p   join (select memberid,                max(createddate) as maxd          from post      group by memberid) as p2 on p.member_id=p2.member_id                              and p.createddate=p2.maxd  order by p.createddate desc 	0
1442202	39472	show records that contain a certain value first in mysql	select *  from thetable order by case lower(featured)            when 'yes' then 0             else 1           end           asc,          someothercolumnnameforaminorkeysort asc 	0
1446791	11594	use each row in one table by joining it to another table	select      *  from  (     select          top 10 row_number() over(order by employeeid) as join_id,*      from          humanresources.employee ) t1 inner join (     select          top 10 row_number() over(order by departmentid) as join_id,*      from          humanresources.department ) t2 on t1.join_id = t2.join_id 	0
1448131	18917	is it possible in mysql to order something by popularity with a timestamp and the number of hits?	select table.*, (table.hits / timestampdiff(day, now(), from_unixtime(table.created))) as popularity from table ... order by popularity desc 	0.00264638155388811
1448267	28065	determine file path of database	select      name as 'file name',      physical_name as 'physical name',      size/128 as 'total size(mb)',     size/128.0 - cast(fileproperty(name, 'spaceused') as int)/128.0 as          'available space(mb)' from      sys.database_files; 	0.0364107528609944
1449495	5343	can i test for the existence of a table in a sqlite database?	select name    from sqlite_master  where type = 'table'    and name like '%your_table_name%' 	0.00322294051206618
1450603	26699	sql server - select top 5 rows for each fk	select     * from     shops s  cross apply (     select top 5         *     from         products p     where         p.shopid = s.shopid and p.productname like '%christmas%'     order by          ??? ) x 	0
1453984	14556	conditional columns in or-constrained sql statements	select o.value * coalesce(m.multiplier,1) from orders o left outer join managed_orders m on m.order = o.pkey left outer join clients c on (o.client = c.pkey or m.client = c.pkey) where c.name = ? 	0.799916830474167
1454963	10316	mysql: grab one row from each category, but remove duplicate rows posted in multiple categories	select t.categoryname, tr.headline, tr.reviewtext from (     select tc.categoryname, max(tr1.reviewid) reviewid     from tblreview tr1 join tblwebsitecontent twc on tr1.reviewid = twc.reviewid                       join tblcategory tc on tc.categoryid = twc.categoryid     group by tc.categoryname) t join     tblreview.tr on tr.reviewid = t.reviewid 	0
1455054	34830	sql group by day, with count	select    convert(char(8), logdate, 112),   count(distinct refundid) from refundprocessing group by convert(char(8), logdate, 112) 	0.0143991132795452
1456475	27940	mysql error when comparing date (php)	select count(user) from my_table where ... 	0.657120600803292
1456524	14765	retrieve rows grouped by hour with mysql	select hour(mydatetimecolumn) as h, count(*) from mytable group by h; 	5.5294422807287e-05
1457234	3897	sql: how do i select an xml element from within a larger variable of type xml?	select @xml.query(' 	0.00177896831001339
1457246	23496	what is the most efficient way to write query to get latest item from collection?	select c.*, o.* from (     select customerid, max(createdon) as maxcreatedon     from order     group by customerid ) mo inner join order o on mo.customerid = o.customerid and mo.maxcreatedon = o.createdon inner join customer c on o.customerid = c.id 	7.39996724292095e-05
1457929	38596	generating tag cloud count given these 3 tables	select dbo.albumtags.tag_name,         count(dbo.albumtagbridge.tag_id) as cnt from dbo.albumtagbridge  inner join dbo.albumtags on dbo.albumtagbridge.tag_id = dbo.albumtags.tag_id group by dbo.albumtags.tag_name 	0.0231361051960695
1459584	26707	mysql datetime operation	select now() + interval 3 day select now() + interval 5 week select now() + interval 6 month select now() + interval 2 year 	0.466401423369633
1464678	20142	left join on the same table	select     a.value v_a,      b.value v_b from (select proc, value from tab where kind = 'a') a left join  (select proc, value from tab where kind = 'b') b   on a.proc = b.proc where a.proc = '1' union select     a.value v_a,      b.value v_b from (select proc, value from tab where kind = 'b') b left join  (select proc, value from tab where kind = 'a') a   on a.proc = b.proc where b.proc = '1' 	0.0308961057497383
1465160	24737	how to find count of transaction of type1 and type2 for each customer in mysql	select c.id as customer_id    , c.name as customer_name    , sum(case when t.`type` = 'type1' then 1 else 0 end) as count_of_type1    , sum(case when t.`type` = 'type2' then 1 else 0 end) as count_of_type2 from customer c    left join `transaction` t    on c.id = t.customer group by c.id, c.name 	0
1467589	34049	finding all caps in columns?	select * from my_table where my_column collate latin1_bin = upper(my_column); 	0.000544230135460973
1471833	18172	select query with no duplicate "first letter" in sqlite	select distinct substr(title_raw, 1, 1) from songs 	0.000691146562601504
1472483	36923	group by and where?	select sum(klick) from svar where pollid = 1234 	0.414325231195118
1472528	20415	matching only one specific row in a join where many exist	select ... from service s inner join provider p on p.provid = s.provid and (coalesce(p.enddate, '2037-01-01') = (    select max(coalesce(enddate, '2037-01-01')) from    provider lu where lu.provid = s.provid) ) 	0
1473272	2815	how to pivot in sql	select      custid,      sum(isnull(admin,0)) as admin,      sum(isnull(manager,0)) as manager,      sum(isnull(support,0)) as support,      sum(isnull(assistant,0)) as assistant from (     select cr.custid, cr.roleid, role, 1 as a     from custromerroles cr     inner join roles r on cr.roleid = r.roleid ) up pivot (max(a) for role in (admin, manager, support, assistant)) as pvt group by custid 	0.471075124680332
1473515	11690	how would you build one select stored procedure to handle any request from a table?	select *  from locationservicetype where locationserviceid = isnull(@locationserviceid,locationserviceid)   and locationid = isnull(@locationid,locationid)   and locationservicetypeid = isnull(@locationservicetypeid,locationservicetypeid)   and servicename = isnull(@servicename,servicename)   and servicecode = isnull(@servicecode,servicecode)   and flagactive = isnull(@flagactive,flagactive) 	0.0878008471962249
1473923	20025	sql pivot min( count (	select  * from    (         select  distinct clients.clientid, clients.serviceid         from    clients         ) e  pivot   (         count(serviceid)         for serviceid in ([1],[2])         ) p 	0.774497284287713
1474753	35506	sql query (like) trying to find titles with and	select name from table where name like '% and %' 	0.461965980496773
1475754	18680	how can i write a sql query that finds all entries in the database where a particular column occurs twice or more?	select hd,count(hd) from laptop group by hd having count(hd) > 1 	0
1477253	10806	sql select unique value in a column	select min(id), filename from yourtable group by filename 	0.00128160879901333
1477629	30999	sql query list those that are higher than average	select    dept.name, count(emp.id) as employeecount from         emp inner join dept on emp.deptid = dept.id group by dept.name having      (count(emp.id) > (select  count(*) from emp) / (select     count(*) from dept)) 	0
1478542	16640	oracle: get part string from a string	select col1      , regexp_substr(col1, '^[^;]') as part1      , replace(regexp_substr(col1, ';[^;]+;'), ';') as part2      , replace(regext_substr(col1, ';[^;]+$'), ';') as part3 	0.00132138160698361
1478853	11552	summary report grouped on multiple date ranges	select agentname,  sum (case when saledate.mydate between @mindate1 and @maxdate1 then sales.amount else 0 end) as gross1,  sum (case when saledate.mydate between @mindate1 and @maxdate1 then sales.commission else 0 end) as commission1,    sum (case when saledate.mydate between @mindate2 and @maxdate2 then sales.amount else 0 end) as gross2,  sum (case when saledate.mydate between @mindate2 and @maxdate2 then sales.commission else 0 end) as commission2 from agent inner join sales on agent.agentid = sales.agentid group by agentname 	0.000446415515179526
1482624	16164	mysql - using union with limit	select u.* from (     (select s1.title, s1.relavency, 'search1' as source from search1 as s1     order by s1.relavency desc     limit 10)         union      (select s2.title, s2.relavency, 'search2' as source from search2 as s2     order by s2.relavency desc     limit 10) ) as u order by u.relavency desc  limit 10 	0.723744532659789
1482763	5469	sql three table join and sort	select c.name, r.name, g.name  from groups g inner join regions r on(r.rid=g.rid)      inner join countries c on(c.cid=r.cid)  order by c.name, r.name, g.name; 	0.0906625040414394
1485201	34140	selecting products sold to a given set of customers	select distinct s1.product_id   from sold_record as s1, sold_record as s2  where s1.customer_id = "customer a"    and s2.customer_id = "customer b"    and s1.product_id = s2.product_id; 	0
1485391	28161	how to get first and last record from a sql query?	select <some columns> from mytable <maybe some joins here> where <various conditions> order by date desc limit 1 union all select <some columns> from mytable <maybe some joins here> where <various conditions> order by date asc     limit 1 	0
1490073	9589	sql query find max row from the aggregated averages	select t1.* from  (select b.bid, avg(s.age) as avg_age from sailor s, boat b   where b.sid = s.sid   group by b.bid) t1 left outer join  (select b.bid, avg(s.age) as avg_age from sailor s, boat b   where b.sid = s.sid   group by b.bid) t2  on (t1.avg_age < t2.avg_age) where t2.avg_age is null; 	0
1490290	8566	merge duplicates into one row and sum up values using php	select track, artist, sum(hits) as hits, sum(hits_this_week) as hits_this_week   from atable  group by track, artist; 	0
1490566	21432	how to display all the dates between two given dates in sql	select dateadd(d, y.i * 10000 + x.i * 1000 + h.i * 100 + t .i * 10 + u.i, '" & dtpfrom.value & "') as dates  from integers h  cross join integers t  cross join integers u  cross join integers x  cross join integers y  order by dates 	0
1492297	616	how to get all rows starting from row x in mysql	select * from tbl limit 95, 18446744073709551615; 	0
1493510	26311	next log backup - will it contain any transactions?	select max(backup_start_date) from msdb..backupset where type = 'l' and database_name = db_name(); select max(last_user_update) from sys.dm_db_index_usage_stats where database_id = db_id() and last_user_update is not null; 	0.279765764049614
1494353	1943	how do i select one parent row and additional rows for its children without a union?	select     p2.name parent_name,     c.name child_name from [parent table] p1     full outer join [child table] c      on 1=0     inner join [parent table] p2      on isnull(p1.id,c.parentid) = p2.id where p2.id = *id here* 	0
1496559	2539	mysql myisam how to join 2 statement select + select count	select     postid,     userid,     post,     replyto,     (select         count(*) as total     from table     where replyto=12) as totalreplies from table where postid=12 	0.41642593455031
1498648	22879	sql how to make null values come last when sorting ascending	select mydate from mytable order by case when mydate is null then 1 else 0 end, mydate 	0.000228480440894663
1500043	16620	combining 2 different but fairly similar tables	select activitycategory, activitytype, nationality, language, null as employment from table1 union select activitycategory, activitytype, nationality, null as language, employment from table1 	0.0078239549843281
1500781	1918	mysql select problem	select * from `business` where (  `category` like ('$_get[search]%')  or `location` like ('$_get[search]%')  or `name` like ('$_get[search]%')  or `address` like ('$_get[search]%') ) and `apv`='yes' 	0.754494815618043
1503745	31527	getting rid of duplicate results in mysql query when using union	select * from (     select items.*, reaction.timestamp as date from items     left join reactions on reactions.item_id = items.id     where reactions.timestamp > 1251806994     group by items.id     union     select items.*, wishlists.timestamp as date from items     left join wishlist on wishlists.item_id = items.id     where wishlists.timestamp > 1251806994     group by items.id     order by date desc limit 5 ) as items group by items.id order by date desc limit 5 	0.236236546310522
1503815	25512	sql server dynamic order by in query, different data types	select  distinct          a.column1,          b.column2  from    tablea a,          tableb b  where   a.key_id = b.fk_id order by          case @order_name when 'col1' then column1 else null end,         case @order_name when 'col2' then column2 else null end 	0.174047775303131
1504830	12705	how to return additional columns with values generated in stored procedures on the 'fly'?	select top 10 *,dbo.calculatedistance(@longitude, @latitude, locationlongitude, locationlatitude) as 'calculated distance' from   location where  locationlongitude between @minlongitude and @maxlongitude        and locationlatitude between @minlatitude and @maxlatitude        and dbo.calculatedistance(@longitude, @latitude, locationlongitude, locationlatitude) <= @withinmiles order by dbo.calculatedistance(@longitude, @latitude, locationlongitude, locationlatitude) 	0.000378489668325341
1506082	14217	find all references to view	select     object_name(m.object_id), m.* from     sys.sql_modules m where     m.definition like n'%my_view_name%' 	0.00252106073960612
1506276	15200	oracle date subtraction	select trunc(5.3574585) days,         trunc(mod((5.3574585) * 24, 24)) hours,         trunc(mod((5.3574585) * 24 * 60, 60)) minutes,         trunc(mod((5.3574585) * 24 * 60 * 60, 60)) seconds    from dual; 	0.189575705172247
1508515	31670	mysql - selecting records based on maximum secondary id	select * from mytable t where log_id = (select max(log_id) from mytable where team_id = t.team_id) 	0
1509732	22230	select only max 3 rows from the same user - mysql	select u.username, p1.* from photos as p1  inner join users as u on u.id=p1.user_id  left outer join photos as p2 on p2.user_id=p1.user_id and p2.id <= p1.id  group by p1.id  having count(p2.id) <= 3  limit 30; 	0
1510286	1311	excluding some columns in a select statement	select col1, col2, col3, col4, col5, col6, col7, col8, col9 from mytable 	0.00945258317823899
1510460	6097	need latest event of certain type where several events may exist for that date	select studentid, [date], max(event) as [event] from   mytable group by studentid, [date] 	0
1510824	1604	single query for all records having no key in a join table and those having a matching key	select * from `trips` where    (not exists (select id from residencies where trips.id = residencies.trip_id))   or   (exists (select id from residencies where trips.id = residencies.trip_id             and other_criteria_for_specific_residency)   ) 	0
1510851	20181	string functions in sql	select case when colname like 'lj%'                  then substring([colname], 2, len(colname) - 2)                 else colname end    from ... 	0.644131397264649
1511567	11477	date query and display	select * from requests where  start_date between <first_day_of_week> and <last_day_of_week> or end_date between <first_day_of_week> and <last_day_of_week> or <day_of_week_monday> between start_date and end_date or <day_of_week_tuesday> between start_date and end_date or <day_of_week_wedenesday> between start_date and end_date or <day_of_week_thursday> between start_date and end_date or <day_of_week_friday> between start_date and end_date group by id order by start_date asc, date asc 	0.00801475732705893
1512542	38866	select random rows but without duplicates of values from one column	select p.pid, p.pname    from (        select (            select pid from products            where pcategory=p.pcategory and pdisplay=1 and pfeatured=1            order by rand() limit 1            ) as pid        from products p        where pdisplay=1 and pfeatured=1        group by pcategory        order by rand() limit 4        ) c    join products p on c.pid = p.pid 	0
1513687	19354	picking info using junction table(sql server 2005) [ set based]	select pur.purchaserid, car.carid    from tblpurchaser pur, tblcar car   where not exists (select 1 from tblinformation  where purchaserid = pur. purchaserid and carid = car. carid)   order by pur.purchaserid; 	0.00202952626345152
1519272	31643	mysql "not in" query	select * from table1 where table1.principal not in (select principal from table2) 	0.742523793395372
1519578	26759	can't see bit(1) fields in mysql	select ignored+0 from table; 	0.712757753495046
1520789	22303	how can i select the first day of a month in sql?	select dateadd(month, datediff(month, 0, @mydate), 0) as startofmonth 	0
1521605	15534	sql server query - selecting count(*) with distinct	select count(distinct program_name) as count,   program_type as [type]  from cm_production  where push_number=@push_number  group by program_type 	0.108081084889019
1522057	11287	what is the fastest way to delete massive numbers of records in sql?	select * into #keep from bar where foo <> 3 truncate table bar insert bar select * from #keep 	0.00492407559586515
1524867	36998	how to display time in hh:mm format?	select left(time, len(time)-3) 	0.000518322440661326
1525672	24294	determine a table's primary key using tsql	select *     from information_schema.table_constraints tc         join information_schema.constraint_column_usage ccu on tc.constraint_name = ccu.constraint_name     where tc.constraint_type = 'primary key' 	0.0147918476705152
1525705	38026	compare with dates and id?	select table1.id     ,table1.date     ,coalesce(table3.timein, table2.timein) as timein     ,coalesce(table3.timeout, table2.timeout) as timeout from table1 inner join table2      on table1.id = table2.id left join table3      on table3.id = table1.id     and table3.date = table1.date 	0.00108755555253635
1526204	14689	selecting from a table where field = this and value = that	select * from visitor_fields inner join visitor_inputs on (visitor_inputs.input_id = visitor_fields.input_id) inner join visitor_fields as filter_0  on (filter_0.input_id=visitor_inputs.input_id  and filter_0.field_name = 'province' and filter_0.field_value != 'alberta') inner join visitor_fields as filter_1  on (filter_1.input_id=visitor_inputs.input_id  and filter_1.field_name = 'country' and filter_1.field_value = 'canada') inner join visitor_fields as filter_2  on (filter_2.input_id=visitor_inputs.input_id  and filter_2.field_name = 'first_name' and filter_2.field_value like '%jim%') 	0.000288012291775071
1526288	1339	how can i get the date of the first second of the year with sql?	select cast('01 jan' + cast((datepart(year, getdate())-1) as varchar) as datetime); 	0
1526776	20613	getting common nodes between two tags	select t1.nid from table t1 join table t2 on t1.nid=t2.nid where t1.tid='mysql' and t2.tid='ajax' 	7.26499917881415e-05
1529854	38766	retrieve duplicate row value and count	select x.pname, sum(x.countofpage) as total, sum(x.countofpage-1) as repeats from ( select tablex.pname, tablex.page, count(tablex.page) as countofpage from tablex group by tablex.pname, tablex.page ) as x group by  x.pname 	0
1530021	9239	query returns too few rows	select ifnull(sum(s.qty),0) as stock, product_name from product as p left join product_stock as s on p.product_id=s.product_id group by product_name order by product_name; 	0.432905900124783
1530396	13700	query did not return all rows	select ifnull(sum(s.qty),0) as stock,            product_name     from product_stock s      right join product p on s.product_id=p.product_id and branch_id=1     group by product_name     order by product_name; 	0.004036127248892
1531086	25703	problem with distinct, select and sort in tsql	select  datename(month, dateadd(month, b_month - 1, 0)) + ' ' + substring(cast(b_year as varchar), 3, 4) from    (         select  distinct year([begin]) as b_year, month([begin]) as b_month         from    records         ) q order by         b_year, b_month 	0.54727410304129
1532226	34586	merge result of two queries in sql server	select     pb_bank_code,    pb_bank_name,    isnull(sum(pc_amount),0) from glas_pdc_banks inner join glas_pdc_cheques      on glas_pdc_banks.pb_bank_code = glas_pdc_cheques.pc_bank_from where  pb_comp_code='1'     and pb_bank_code='025'     and isnull(pc_discd,'x') != 'c'    and pc_due_datetime between '05/05/2008' and '05/06/2008' 	0.00974800775812233
1533240	21153	oracle analytic function for min value in grouping	select dept,        emp,        salary from        (        select dept,                emp,               salary,               min(salary) over (partition by dept) min_salary        from   mytable        ) where salary = min_salary / 	0.793597340860589
1533362	10974	iterating 1 row at a time with massive amounts of links/joins	select a.field1, b.field2, c.field3, identity (int, 1,1)  as tablerownumber into #temp from table1 a  join table2 b on a.table1id = b.table1id join table3 c on b.table2id = c.table2id select * from #temp where ... 	0.00295472822541345
1537527	4423	merging 2 sql queries	select a.year, a.month, b.sameday, a.total from ( select  datepart(yy,dateclosed)as 'year',     datepart(mm,dateclosed) as 'month',     count(*)as 'total'  from bug  where projectid = 44  and ifclosed = 1 and isnull(createdbyperson,1) <> '-1111111110' and datepart(yy,dateclosed) > '2000' group by datepart(yy,dateclosed), datepart(mm,dateclosed) ) a inner join ( select  datepart(yy,dateclosed)as 'year',     datepart(mm,dateclosed) as 'month',     count(*)as 'sameday'  from bug  where   projectid = 44          and ifclosed = 1         and isnull(createdbyperson,1) <> '-1111111110'         and datepart(yy,dateclosed) > '2000'          and convert(varchar(10), dateclosed, 101) = convert(varchar(10), datecreated, 101)  group by datepart(yy,dateclosed),datepart(mm,dateclosed) ) b on a.year = b.year and a.month = b.month order by 1,2 	0.0319388679415368
1537638	35146	can i include the table name in the result of an sql query?	select id, 'actor' as career, name from actor union all select id, 'singer' as career, name from singer 	0.00461874793300289
1537945	39279	sql query group a range of numbers with low's and high's	select  street_id,  min(address_number) as address_low_range, max(address_number) as address_high_range, address_direction,  address_street,  address_type from table_name group by street_id, address_direction, address_street, address_type 	0.0097837550418503
1538578	20629	sql - trying to get customers who ordered a product for the first time during a month and	select count(c.customerid), sum(price), sum((price-cost))  from   (   select customerid, min(orderdate) as firstdate   from customerorder a   inner join customerorderitem b   on a.orderid = b.orderid   where sku='esk-1mvv'   group by customerid ) as firstsale inner join customerorder c on firstsale.customerid = c.customerid inner join customerorderitem d on c.orderid = d.orderid where month(firstsale.firstdate) = 1 and year(firstsale.firstdate) = 2009 and d.sku='esk-1mvv' 	0
1539121	10680	mysql select that returns a dummy column?	select column1, column2, 'waiting for table' as dummy_column, column4 from your_table 	0.0373471275841321
1539690	41274	how do i make a set of results become my select statement?	select pay_type      , sum(pay_amt) as pay_amt   from transaction_payments group     by pay_type 	0.186630959816429
1540201	28353	in oracle, how do i determine the fields that compose the primary keys of tables or views?	select  l.column_name, l.position from    all_constraints n join    all_cons_columns l on      l.owner = n.owner         and l.table_name = n.table_name         and l.constraint_name = n.constraint_name where   n.constraint_type = 'p'         and n.table_name = 'mytable'         and n.owner = 'scott' 	0.000395547368781464
1542181	29097	finding most specific prefix with sql	select id ,      sla_id ,      leng ,      group_id ,      (row_number() over (partition by id order by leng desc)) rn  from  ( select a.id, a.sla_id, max(length(ag.area_prefix)) leng, ag.group_id from areas a inner join areas_groups ag     on (substr(a.sla_id, 0, length(ag.area_prefix)) = ag.area_prefix) where a.sla_id is not null group by a.id, a.sla_id, ag.group_id ) where rn = 1 	0.00884723109795202
1545436	12635	mysql - query all users without an appointment	select * from users  left join appointments on users.userid=appointments.userid where appointments.userid is null 	0.0126766914606988
1546014	15556	sql query to retrieve results from two equally designed tables	select * from table_a union select * from table_b 	0.000982863038480767
1547666	14618	how do i get a list of locked users in an oracle database?	select username,         account_status   from dba_users; 	0.0002573643317038
1548882	35843	sql query for the given table	select supervisorname,    supervisoremail,    (select count(*)      from phd_student s      where s.supervisor_id = r.supervisor_id) as tot_stud from phd_supervisor r 	0.012040428431502
1549705	26741	implementing most recent comment - sql server	select c.* from blogcomments c join #tempentries t on c.entryid = t.entryid join (     select m.entryid, max(m.commentid) as commentid     from blogcomments m     group by m.entryid     ) m           on  m.entryid = c.entryid         and m.commentid = c.commentid 	0.0404991457594789
1550129	23619	sql with 0 counts	select date(procedures.start) date, name, count(procedure_types.id) count from `procedure_types` left outer join procedures on procedure_types.id = procedures.procedure_type_id     and date(procedures.start) = '2009-10-24' group by date(procedures.start), procedure_types.id order by date(procedures.start), procedure_types.id 	0.285733089922654
1551422	20989	how to look up language id of messages?	select * from syslanguages 	0.0102968785350473
1552231	35700	mysql function which takes a set of strings?	select * from mytbl where name in ('bob', 'jane', 'sally') 	0.284229276322424
1553746	24209	searching sql server	select     msgs.recordid,     msgs.title,     msgs.body from     [messages] as msgs     inner join freetexttable([messages],title,@searchtext) as titleranks on msgs.recordid = titleranks.[key]   order by     titleranks.[key] desc 	0.539753418755512
1555474	22708	cross-database queries with numbered database name	select    * from    granddatabase.user  inner join    [100].dbo.userinfo u    on granddatabase.user.userid = u.userid 	0.663432433646212
1556966	40132	distinct route pairs	select city1, city2 from yourtable where city1 < city2      union select city2, city1 from yourtable t1 where city1 > city2 	0.0452979904003897
1557209	12155	tsql group by including all columns	select sum(isnull(s.amount,0)) as totalsales, p.productname from sales s  right join product p on s.productid = p.id group by p.productname 	0.00352508460780776
1558623	36798	how can i query from two tables but get results only from one?	select * from contacts as c where c.id not in (select id from blockedcontacts) 	0
1560531	8439	in oracle, what is the sql to query for occurences of line feed?	select * from [table] where [column] like '%'||chr(10)||'%' 	0.418474851076222
1561821	11656	joining against derived table	select      events.id, events.name, periods.periodid from        periods inner join  events on          periods.id between events.startperiodid and events.endperiodid 	0.071559918821026
1563148	33536	one-to-many query selecting all parents and single top child for each parent	select p.id, p.text, c.id, c.parent, c.feature from parents p left join (select c1.id, c1.parent, c1.feature              from childs c1              join (select p1.id, max(c2.feature) maxfeature                      from parents p1                 left join childs c2 on p1.id = c2.parent             group by p1.id) cf on c1.parent = cf.id                                and c1.feature = cf.maxfeature) c on p.id = c.parent 	0
1563632	8240	oracle sql loop (between 2 dates) and counting	select 'there is no location' from reserve r where exists (select *               from disponibilidad                       join estadia                          on disponibilidad.identificador_estadia = estadia.identificador                where estadia.identificador = r.id                    and disponibilidad.numero_reservas > 500                     and disponibilidad.date between r.startdate and r.enddate) and r.id = 1 	0.00481041923025832
1564541	7635	how to convert records in a table to xml format using t-sql?	select * from table1 for xml auto 	0.0027179388195987
1567683	18299	mysql: grouping a grouped statement possible?	select employeeid, sum(short) from (    <your sql here> ) sub group by employeeid 	0.181512213652656
1571579	6547	sql server : how to get rownumber for each common set of values?	select row_number() over (partition by [tenancy number]                           order by [tenant number]                          ) as myrownum        ,[tenancy number]        ,[tenant number]        ,tenant from <table> 	0
1575419	3277	how can i truncate multiple tables in mysql?	select concat('truncate table `', table_name, '`;') from information_schema.tables where table_name like 'inventory%' 	0.042788820517883
1576370	29647	getting a percentage from mysql with a group by condition, and precision	select count(*) from agents into @agentcount; select user_agent_parsed      , user_agent_original      , count( user_agent_parsed )  as thecount      , count( * ) / ( @agentcount) as percentage  from agents group by user_agent_parsed order by thecount desc limit 50; 	0.00240175332484553
1579557	38396	how to join a one-to-many relationship to ensure that only 1 row from the left comes back?	select     pe.col_name,     (select top (1)           ph.col_phonenbr      from table_phone ph      where pe.col_name = ph.col_name      order by          case col_phoneid              when 4 then 1              when 2 then 2              when 1 then 3              when 3 then 4              when 5 then 5              when 6 then 6          end     ) as col_phonenbr from table_person pe 	0.00013722509569332
1579998	29886	tsql rollup -return not null	select        case when grouping(groupid) = 1 then '#all' else groupid end as         groupid,                         case when grouping(subgroupid) = 1 then '#all' else subgroupid end as subgroupid,                sum(value) from          table group by      groupid,               subgroupid with rollup 	0.770573861440804
1581052	39526	how to loop through all rows in an oracle table?	select * from tbl where <range> 	0.00202610149458042
1584704	10820	select different field in mysql if a field is set to null?	select coalesce(username, dispalyname) from users where ... 	0.000956722249870667
1585505	4358	compare mysql "time" field with string in php	select *     from data d     join users u on u.user_id = d.user_id    where not exists (select null                         from data t                       where t.id = d.id                         and convert('10:00:00', time) between t.start_time and t.end_time) group by u.usrid 	0.00479878800378521
1587425	4143	mysql counting results between two datetime	select count(*) from widgets where in < $$newcheckouttime$$ and out > $$newcheckintime$$ 	0.00244709165419083
1588464	3880	mysql dot-traversal... possible?	select    house.* from    house    join town on town.id = house.town    join state on state.id = town.state where state.name = 'alaska' 	0.777006407519636
1590223	30743	mysql ordering query	select * from (select * from table order by id desc limit 5) as tmp order by id asc 	0.598692295423122
1590685	8257	sort postgres table data in php through array	select     visitdate from     public.statistics where     visitdate          between date '2009-10-19' and date '2009-10-20' order by     visitdate offset 2 limit 3; 	0.00708192280198329
1594092	17008	sql: how to select single record for multiple id's on the basis of max datetime?	select        a.id, a.windspeed, a.datetime from          yourtable as a inner join      (     select    id, max(datetime) as datetime     from      yourtable     group by  id ) as b on            a.id = b.id and           a.datetime = b.datetime 	0
1595405	22675	sql between for daysofweek	select item_id, dayofweek(bookdate) as date, bookdate, avg(price) as price  from `availables` where (item_id = 16 and dayofweek(bookdate) in (7,1,2))  group by dayofweek(bookdate) 	0.257347830278121
1595574	6061	postgresql select the last order per customer per date range	select customernum, max(ordernum) from table where orderdate between '...' and '...' group by customernum 	0
1595659	16050	how to eliminate duplicate calculation in sql?	select *, locate( column, :keyword ) as somelabel  from table  having somelabel > 0  order by somelabel 	0.0492060463658194
1595804	12584	selecting transactions as a single row	select v.*   from (select proj.*, actual_date,                 max(actual_date) over(partition by ms.product_id) last_milestone,                lag(actual_date) over(partition by ms.product_id                                       order by actual_date) previous_milestone            from zsof_projects proj            left join zsof_milestones ms on ms.product_id = proj.id) v  where last_milestone = actual_date     or (actual_date is null and last_milestone is null) 	0.00156879118720695
1597055	3602	how to count rows that have the same values in two columns (sql)?	select a,b,count(*) from the-table group by a,b 	0
1598700	5622	mysql sum group by	select sum(g.points)      from grades g    where g.date < 'thedate'  group by g.assignmentid order by g.date desc 	0.211410956053924
1600934	34765	how to export 20 000 contacts from mysql database via php for import into an desktop address book?	select * into outfile 'result.csv' fields terminated by ',' optionally enclosed by '"' lines terminated by '\n' from my_table; 	4.89946107482456e-05
1601151	2426	how do i check in sqlite whether a table exists?	select name from sqlite_master where type='table' and name='table_name'; 	0.00367641276183387
1601509	4950	how can i select 16 records at random from a range of rows in mysql?	select *      from (select from table order by download_no desc limit 50) as new_table     order by rand()      limit 16 	0
1601727	18070	how do i return the sql data types from my query?	select * from information_schema.columns 	0.0149967063299772
1601840	34307	randomly selecting a limited number of records with two conditions in mysql	select t1.*   from table t1  where priority = 'high'  order by rand() limit 8 union all select t1.*   from table t1  where priority = 'low'  order by rand() limit 2 	0
1604323	16742	sql comparing set of information in a column	select   t2.actorname,           count(t2.seriesname)  from    mytable t1  join    mytable t2  on      t1.seriesname=t2.seriesname and t1.actorname='smith' and t2.actorname <> 'smith' group by t2.actorname  having  count(t2.seriesname)=(select count(seriesname) from mytable where actorname='smith') 	0.00217796426959561
1604367	40665	mysql - display rows of names and addresses grouped by name, where name occures more than once	select t.name_id,        t.last_name,        a.street_address   from name t   join address a on a.name_id = t.name_id   join (select n.last_name           from name n       group by n.last_name         having count(*) > 1) nn on nn.last_name = t.last_name 	0
1604786	7027	sql to return unique list of userid's based on 2 tables	select distinct u.userid from users u left join oldusers o on o.userid = u.userid where o.userid is null 	0
1604951	175	how to implement posting limit of a user?	select * from whatever where date(datefield) = curdate(); 	0.157918559788905
1605886	15124	counting instances of unique value in field	select prices, count(*) from thetable group by prices 	0
1606062	12724	count instances in table1 and link to table2	select t1.prices, count(t1.id) as thecount, t2.genre  from table1 as t1      inner join table2 as t2          on t1.id = t2.id  group by t1.prices, t2.genre 	0.000960807859555857
1606580	12946	distinct item with latest timestamp and multiple (or all) columns returned	select * from delivery_history a where id = (   select top 1 id    from delivery_history b   where a.delivery_number = b.delivery_number   order by b.timestamp desc [, tie breaking col1, col2, ... coln]   ) 	0
1607143	18410	mysql group by intervals in a date range	select from_unixtime(stime), bytes  from argustable_2009_10_22  where stime > (unix_timestamp()-600) group by floor(stime /10) 	0.000950196686897913
1608845	34614	mysql: export single row, but with all dependencies	select * from table1 t1  inner join table2 t2 on t1.pk = t2.fk inner join table3 t3 on t2.pk = t3.fk ....... where t1.pk = {pk id number} limit 0,1 	0.00120562341419268
1609391	35772	selecting with preference in sql server	select    referencenumber , referencevalue = isnull(max(nullif(referencevalue,'not assigned')),'not assigned') into table1_clean from table1 group by   referencenumber 	0.258966362863011
1611574	17244	select only integers from char column using sql server	select * from powder where isnumeric(name) = 1 	0.00193795134046174
1612590	6344	mysql: get multiple-keyed rows matching several where conditions (probably simple)	select *, group_concat(categoryid) as ids from tblwebsiteuserstats group by userid having ids like '%888%' and ids like '%999%' 	0.122374243560159
1614673	38590	query oracle db for timestamps when you know milliseconds	select * from a_table where to_char(a_timestamp_col) < '1252944840000' 	0.0811273800231515
1616969	27189	how to write a query returning non-chosen records	select w.name from words w where not exists    (select 1     from choices c      where c.class = 1 and c.wid = w.id) 	0.192972410472389
1623437	14792	displaying mysql data into html table (clearly explained)	select    u.email,    group_concat(d.domain separator ', ') from    domains d    join user_domain ud on d.domain=ud.domain and d.owner_id=ud.owner_id and d.owner_id!=ud.user_id    join users u on ud.user_id=u.user_id where d.owner_id='user_1' group by u.email 	0.0110429475638449
1623531	11859	query is slow while doing a not in on a nested select from another table	select p.*, u.*  from problems p join users u  on p.user_id = u.id  join problems_attempted pa on pa.problem_id = p.id  where not (pa.user_id = 1  and total_questions = ( attempted_right + attempted_wrong + skipped )) 	0.684131582778157
1623562	39536	mysql set a flag for each match	select users_extra.first_name, users_extra.last_name,     case users_extra.userid     when branches.manager_id then 'manager'     when branches.sales_manager_id  then 'sales manager'     ...     end as position from ... 	0.000483078501719975
1624632	18532	how to find the days compare with date?	select column from table where datename(dw, column) <> 'sunday' 	0
1624923	33184	sql get all children of a parent	select * from areas where path like '%/1/%' 	0
1625508	29165	counting rows in mysql	select count(*),sid from days_attend where absent = 'yes' group by sid having count(*) = 5 	0.0128871519964421
1626829	26822	mysql using calculated return values to calculate other values	select concat( (malefriendreferrals/totalfriendreferrals) *100 , '%') as malepercentreferrals from   (select     sum(st.tafpoints/200) as totalfriendreferrals,     sum(case when st.gender = "m" then st.tafpoints/200 else 0 end) as malefriendreferrals,     sum(case when st.gender = "f" then st.tafpoints/200 else 0 end) as femalefriendreferrals   from st) as subquery 	0
1627205	12513	select latest records by datetime field	select * from mytable where currenttime >= dateadd(n, -2,  getdate()) order by currenttime desc 	6.01685806030798e-05
1629196	40940	oracle date function	select br_data.upd_time from bankrec.br_data where to_char(br_data.upd_time, 'dd-mon-yy') = '12-mar-08'; 	0.528291259235554
1630715	37590	access 2007: determine maximum value per row across multiple columns	select   employeecolumn,   iff(iif(date1 > date2, date1, date2) > date3, iif(date1 > date2, date1, date2), date3) from yourtable 	0
1631723	39970	maintaining order in mysql "in" query	select * from foo f where f.id in (2, 3, 1) order by field(f.id, 2, 3, 1); 	0.797029287886355
1632606	35680	sql server 2005 - check for null datetime value	select count(*) from person where birthdate is null 	0.0615344700000298
1633498	12758	searching multiple tables with subquery	select     companies.company_id, companies.company_name, companies.company_description from       companies inner join tag_relation on         companies.company_id = tag_relation.company_id inner join tags on         tags.tag_id = tag_relation.tag_id where      companies.company_name like '%something%' or         companies.company_description like '%something%' or         tag.tag like '%something%' group by   companies.company_id, companies.company_name, companies.company_description order by   companies.company_name 	0.382879772840568
1633872	12746	how to get the item count for sub-categories on each parent?	select      h.receiptfolderid, count(h.receiptfolderid) from     tbl_receiptfolderlnk h     join tbl_receipt d on h.receiptid = d.receiptid where receiptfolderid=@folderid group by     h.receiptfolderid 	0
1635404	38823	choosing latest string when aggregating results in mysql	select d1.ticket_num, d1.date, q.name as queuename,    cf.name as cf, cfv.value as cfvalue, d1.closed from dayscf dcf inner join daily_snapshots d1 on (dcf.day_id = d1.id) inner join queues q on (d1.queue_id = q.id) inner join customfieldvalues cfv on (dcf.cfv_id = cfv.id) inner join customfields cf on (cf.id = cfv.field_id) left outer join daily_snapshots d2 on (d1.ticket_num = d2.ticket_num and d1.date < d2.date) where d2.id is null and cf.name = 'department' order by d1.ticket_num, d1.date; 	0.00803830301186572
1637094	3914	out of range value for integer	select cast('2123456789012345678' as int(11)) select cast('21234567890123456789' as int(11)) 	0.000554710296143286
1638738	31934	eliminate group of nulls from result set	select     quarter, count from     mytable m where     exists (select *         from mytable m2         where m2.count is not null and m.quarter = m2.quarter) 	0.00923292419904178
1639583	9534	get the next xx:30 time (the next half-past hour) after a specified time	select from_unixtime( floor((unix_timestamp(my_date)+(30*60))/(60*60))*(60*60) + (30*60) ) 	0
1641491	24497	mysql table design: multiple tables vs. multiple columns	select ifnull(sum(t.value), 0)      from players p      join item_stat_relation itr on itr.player_id = t.player_id left join stats s on s.stat_id = itr.stat_id     where p.player_id = ?       and ... 	0.024544727172899
1641988	11123	how do i select min/max dates from table 2 based on date in table 1?	select m.date as m1,                       min(d.date) as m2,                                  max(d.date) as m3 from monthly m join daily d on month(d.date) = month(m.date) and year(d.date) = year(m.date)  where  group by m.date order by m.date  	0
1644664	32618	ignoring spaces between words - an sql question	select * from table where lower(name) like 'john%doe%' 	0.540362783201084
1646001	31634	how can i get the number of days between 2 dates in oracle 11g?	select extract(day from sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) from dual 	0
1646609	18838	sql question regarding searching for data from multiple tables	select distinct d.* from ticket_data d  left outer join ticket_comment c on c.tid = d.id where   (    d.subject like '%test%' or    d.message like '%test%' or    c.comment like '%test%'   ) 	0.384288814579703
1647946	10995	merge and add values from two tables	select coalesce(t1.id, t2.id) as id, (coalesce(t1.value, 0) + coalesce(t2.value, 0)) as value  from table1 t1 full outer join table2 t2 on t1.id = t2.id 	0
1648190	31933	what is the query to get "related tags" like in stack overflow	select t.tagname     from tags t     join tags_bridge tb on tb.tagid = t.id     join (select li.id             from links li             join tags_bridge tb on tb.linkid = li.id             join tags t on t.id = tb.tagid            where t.tagname = 'xyz') x on x.id = tb.linkid group by t.tagname 	0.451236432070843
1649608	22169	querying a view that's not located on the same server (sql server 2005)	select   * from      opendatasource(          'sqloledb',          'data source=servername;user id=myuid;password=mypass'          ).northwind.dbo.categories 	0.365129473741806
1650636	11002	casting in mysql	select  str_to_date('fri, 30 oct 2009 06:30:00 edt', '%a, %d %b %y %h:%i:%s edt') 	0.445806239905613
1651602	29514	sqlite expression to count rows grouped by week	select (completiondate - min) / (60*60*24*7) as week,        count(*) as count from task, (select min(completiondate) as min from task) group by week having completiondate not null; 	0.000821512603074665
1651608	34508	sql joining question	select ndc,        max(decode(rn, 1, rx_num, null)) rx1,        max(decode(rn, 2, rx_num, null)) rx2,        max(decode(rn, 3, rx_num, null)) rx3,        max(decode(rn, 4, rx_num, null)) rx4   from (select *           from (select claims_list.ndc,                        claims_list.rx_num,                        row_number() over (partition by claims_list.ndc order by claims_list.date desc) rn                   from claims_list,                        (select *                            from (select *                                   from drug_list                                  where type = 'generic'                                 order by qty desc                                )                          where rownum < 51                        ) drug_list                  where drug_list.ndc = claims_list.ndc                )          where rn < 5         order by ndc, rn        ) group by ndc; 	0.785533944609638
1652251	34686	mysql count values based on multiple columns	select u.grade      , count(distinct l.userid)   from userlist u   join login l     on l.userid = u.userid group     by u.grade 	5.78924064907284e-05
1652714	1350	how to remove spaces in and of text field	select trim(column_name) from ....... ; 	0.00574731971260514
1653280	25106	getting count of related tags	select t2.tagname, count(distinct tb2.linkid) as relatedlinkcount from tags t2 join tags_bridge tb2 on t2.tagid = tb2.tagid join tags_bridge tb1 on tb2.linkid = tb1.linkid join tags t on t.id = tb1.tagid where t.tagname = 'tag3' group by t2.tagname 	0.00106817771095247
1655581	34333	select last (first) rows of a table in stored procedure using parameter (sql 2008)	select top (@param) * from tblrecords .... 	9.33345988920464e-05
1655761	39947	two foreign keys of the same table. how do i write this select statement?	select u.username, i1.path as thumb, i2.path as full   from users as u     join images as i1 on u.thumb_id = i1.image_id     join images as i2 on u.fullimage_id = i2.image_id 	0.000325060693793656
1656882	18100	sql question: how to select arbitrary numbers of records in each record group?	select * from (     select         row_number() over (partition by uid order by updatedt desc)          as rn     ,   *     from yourtable ) sub where rn <= 3 	0
1657876	24460	mysql order by math	select *  from yourtable  order by fieldx * fieldy 	0.700104995695374
1658103	13949	asking for everything "up to" a value [mysql]	select * from   students where  age >= 0 and age <= 20 	0.0248601795412494
1658761	36854	query to pull sum from 2 different tables, is this possible in one query?	select employeeid, year(created), month(created), day(created), case   when sum(commission) > 100 then 100   else sum(commission) end from (   select employeeid, created, commission from productsales   union all   select employeeid, created, commission from referrals ) commissions group by employeeid, year(created), month(created), day(created) 	0.000733381558897632
1659191	32858	doesn't equal in sql	select * from sometitle where somelabel <> 'something' 	0.479129320317613
1665149	17808	many to many tables and querying on the same variable with arrays	select boxid from table1 where fruitid in ($fruitid1, $fruitid2, ...) group by boxid having count(*) = $selectedfruitcount; 	0.000770629902534736
1666661	6286	retrieving mysql join values from php	select    s.id as storyid,    s.name as storyname,   a.id as authorid,    a.name as athorname, from stories s join authors a on a.id = s.authorid 	0.00398717463702323
1666827	22830	sql server select where value like(temporary table value)	select * from users,newtable where vlastname like values + '%' 	0.0102070268487979
1669857	40752	sql query - some kind of select distinct?	select distinct c1.cs from customers c1  inner join customers c2 on c2.cs=c1.cs where c2.day='tue' and c1.day='wed' 	0.271540830793631
1670148	11280	last item in mysql count(*) result?	select count(*) as repetitions, max(id) from users group by name, phone, state having repetitions > 1 order by id desc 	0.000133071634081853
1671084	32301	stored proc return all rows when parameters are null	select *   from apples  where 1 = case             when @color is null then 1             else               case                 when apple.color = @color then 1                 else 0               end             end    and 1 = case              when @time is null then 1              else                case                  when apple.time = @time then 1                  else 0                end            end 	0.0316093848088021
1671825	13069	how to load large xml file (> 100 mb) to an xmltype column in oracle	select count(*) from xdb.path_view p, table(xmlsequence(extract(p.res,'/*/*'))) y where p.path= '/sys'; 	0.167341647168865
1673672	37292	how to round with no trailing zeros in sql server 2005?	select cast(round(100.5555, 2) as decimal(8,2)) 	0.242842121391613
1674541	33793	how to join 2 tables based on a like in mysql	select * from employee e join company_employee ce     on e.id = ce.employee_id where e.firstname like '%john%' 	0.00299296929379212
1676346	33221	compare oracle table columns in sql	select column_name from all_tab_columns where table_name='a' and owner='yourschema' minus select column_name from all_tab_columns where table_name='b' and owner='yourschema' 	0.00507064687527406
1682321	22981	find unused stored procedures in code?	select * from sys.procedures; 	0.318195185815239
1682689	26233	join after processing select	select players.name, trials.player, trials.timestamp, trials.score from     (select player, score, timestamp from     trials order by score desc, timestamp asc limit 10) trials, players where players.id = trials.player 	0.740461749557121
1688937	19795	set all empty strings to null in all records of all tables in postgresql	select *  from information_schema.columns where is_nullable = 'yes'; 	0
1691447	31572	getting the index of set bits from an int column in mysql	select     make_set( val, '1', '2', '3', '4', '5', '6', '7', '8', '9' ) from     example 	0.0017264332015515
1692782	2627	sql select at least x rows that are in a given time	select distinct * from      (select top 100 *     from mytable     order by datecolumn desc) a union     (select *     from mytable     where datecolumn > '20090101') 	0
1693158	11933	get data from table, using rows as columns	select productid from mytable  where productid in (select productid from mytable where fieldid = 50 and fieldvalue = '1.0')    and productid in (select productid from mytable where fieldid = 55 and fieldvalue = 'y')     and productid in (select productid from mytable where fieldid = 60 and fieldvalue = 'n') 	0
1693689	21987	how retrieve category name?	select p.*, c.name as catname   from products p left join categories c on c.id = p.category_id 	0.000585334824633004
1693754	8132	how to select first 10 elements from database using sql?	select * from clients order by id limit 10; 	0
1694796	39777	select 2 count()'s from mysql query	select username, sum(outcome) as wins, count(*) - sum(outcome) as losses   from tblbattlehistory    where battle_type = '0'   group by username    order by wins desc, losses 	0.00788670439073901
1697255	8460	how to calculate sum of hours?	select worker_id,        sum(hrs)   from (select worker_id,                 (to_date(hr_stop, 'hh24:mi:ss') - to_date(hr_start, 'hh24:mi:ss')) * 24 hrs           from days d,                hours h          where d.id = h.day_id            and trunc(event_date, 'mm') = trunc(sysdate, 'mm')        ) group by worker_id 	0.000139805595216322
1698312	429	adding up values from a sql query	select sum(meta_value) from (table) where meta_key = 'views' 	0.0218343954243356
1698805	25766	how to separate positive and negative numbers into their own columns?	select activity_dt, sum(case when activity_amt < 0 then activity_amt else 0 end) as debits, sum(case when activity_amt > 0 then activity_amt else 0 end) as credits from the_table group by activity_dt order by activity_dt 	0
1699888	14924	can you select where something's like and in at the same time?	select   * from   table1 t1     inner join table2 t2 on (t1.name like t2.name + '%') 	0.0112798774026113
1699955	40627	sql to have one specific record at the top, all others below	select *  from the_table  order by (case id when 999 then 0 else 1 end), date_added desc 	0
1700303	3953	sql 2008 - foreign key constraints in the information_schema view	select  fk_table  = fk.table_name,  fk_column = cu.column_name,  pk_table  = pk.table_name,  pk_column = pt.column_name,  constraint_name = c.constraint_name  from  information_schema.referential_constraints c  inner join  information_schema.table_constraints fk      on c.constraint_name = fk.constraint_name  inner join  information_schema.table_constraints pk      on c.unique_constraint_name = pk.constraint_name  inner join  information_schema.key_column_usage cu      on c.constraint_name = cu.constraint_name  inner join  (      select          i1.table_name, i2.column_name      from          information_schema.table_constraints i1          inner join          information_schema.key_column_usage i2          on i1.constraint_name = i2.constraint_name          where i1.constraint_type = 'primary key'  ) pt  on pt.table_name = pk.table_name 	0.00528921845086662
1701124	24331	for each row in query select top 20 from other query	select thename, hour, cnt from ( select thename, hour, cnt,          rank() over (partition by thename order by cnt desc) rnk   from   ( select   thename, trunc (thetimestamp, 'hh24') hour, count (theid) cnt      from mytable     group by thename,trunc(thetimestamp,'hh24')   ) ) where rnk <= :x 	0
1701148	5017	grab only the last post from all topics in a category from phpbb	select  * from    phpbb_forums f join    phpbb_topics t on      t.forum_id = f.forum_id join    phpbb_posts p on      p.post_id =          (         select  pi.post_id         from    phpbb_posts pi         where   pi.topic_id = t.topic_id         order by                 pi.date desc         limit 1         ) where   f.parent_id in (…) 	0
1701850	19683	sql server date formats -- ddd	select left(datename(dw, getdate()), 3) 	0.29250162249644
1702420	15951	sql query not between two dates	select * from 'test_table' where end_date < cast('2009-12-15' as date) or start_date > cast('2010-01-02' as date) 	0.0245905981314859
1703097	12615	group by named column	select timestampdiff( year, birthdate, curdate( ) ) as age, count( timestampdiff( year, birthdate, curdate( ) )) from  person group by timestampdiff( year, birthdate, curdate( ) ) 	0.0656425996845447
1703119	4016	getting number of rows in a group by query with microsoft access	select count(*) as expr2   from (         select distinct [key1] & "-" & [key2] & "-" & [key3] as expr1           from table1        ) as sub; 	0.0203572257608094
1703244	9598	mysql: query to find row with max with tie breaker	select      t1.user from      myunnamedtable t1 left outer join myunnamedtable t2 on      t2.region = t1.region and      (           t2.points > t1.points or           (t2.points = t1.points and t2.last_updated > t1.last_updated)      ) where      t2.user is null and      t1.region between x and y 	0.0494575767661757
1703297	25756	selecting records in sql based on another table's contents	select      users.*  from      users,      properties  where      users.id = properties.userid      and properties.property = (whatnot); 	0
1704260	28582	access sql query: find the row with the most recent date for each distinct entry in a table	select id, value,as_of  from yourtable a inner join            (select id, max(as_of) as as_of            from yourtable group by id) b  on a.id=b.id and a.as_of = b.as_of 	0
1707506	12497	are the results deterministic, if i partition sql select query without order by?	select     * from     (     select         *     from         mytable     order by somecol     ) foo 	0.395528108356518
1708097	930	mysql date_add() how to use month into this?	select concat_ws('-', '2009', month(now()), '01') - interval 1 month 	0.129500971703683
1710218	31471	sql query return true/false	select 'true' union select 'false'; 	0.18041461972343
1710375	40344	tossing out certain result rows in a left join	select a.deptno, a.deptname, min(b.empno) from #dept a left join #emp b on a.deptno = b.workdept group by a.deptno, a.deptname 	0.00686567986639279
1714800	34753	is there any reason not to join foreign key to foreign key?	select class.classname from class where exists      (select * from financial      where (financial.fk_schoolid = class.fk_schoolid) and (...)) 	0.00476173775606783
1717126	12545	using select top from one column, then sorting on a different column	select revenue, vendorname from (select top 15                  sum(po.pototal) as revenue,          v.vendorname as vendorname         from purchaseorders po           join vendors v            on po.vendor_id = v.vendor_id        where ...        group by v.vendorname         order by revenue desc) z order by vendorname asc 	0
1717740	34130	modelling country adjacency in sql	select      border.country from      countries as c left outer join node_adjacency na1 on      na1.node_id_1 = c.country_id or      na1.node_id_2 = c.country_id inner join countries as border on      (      border.country_id = na1.node_id_1 or      border.country_id = na1.node_id_2      ) and      border.country_id <> c.country_id  where      c.country = 'croatia' 	0.333979569763383
1718194	30393	only list jobs if current time > expiry time (php mysqli)	select * from jobs where active = 1 and closingdate >= now() 	9.66399074682509e-05
1718867	34844	mysql count problem	select count(*), prerequisite from course group by prerequisite; 	0.728942343722663
1720425	19174	select (* - some_columns) from table in sql	select * from mytable 	0.0207912112849327
1721683	11438	sql query split by a date range	select      student,      date_format(applicationdate,'%m/%y') as month     count(id) as applications from yourtable group by applicationdate 	0.00295112887494814
1723925	28559	how can i know which values are numeric in oracle 9i	select my_column from my_table where my_column not like '%1%' and my_column not like '%2%' and my_column not like '%3%' and my_column not like '%4%' and my_column not like '%5%' and my_column not like '%6%' and my_column not like '%7%' and my_column not like '%8%' and my_column not like '%9%' and my_column not like '%0%' 	0.0539703895202413
1726458	32442	mysql: get list of all column names in a table that do not have null as their default value?	select * from information_schema.columns  where table_name = 'my_table'    and column_default is [not] null; 	0
1727319	37422	sql subquery getting particular column	select username  from (select username, company, position      from table1 where username in          (select username          from members_network          where xscore <= 18 and xscore >= 15)) t 	0.0572965457781956
1728246	26210	appending columns from two tables in ms access	select tablea.num from tablea union all select tableb.num from tableb 	0.00260461218395281
1728698	8720	access query to filter and combine count	select distinct tablea.num, [tablea].[val]+[tableb].[val] as expr1 from tablea inner join tableb on tablea.num = tableb.num where (((tablea.val)>=6) and ((tableb.val)>=6)); 	0.171792927094972
1729622	37828	select from sql	select name, gdp / population as [per capita gdp] from yourtable 	0.0523145535845028
1729870	14369	how to sum multiple sql queries together?	select sum(individual_counts) from (   select count(*) as individual_counts from tablea where x = 1     union all   select count(*) from tableb where x = 2 .... ) x 	0.118569603669749
1729973	1134	filter sql queries on the xml column using xpath/xquery	select id, xml.query('data(/xml/info/@name)') as value from table1 where xml.exist('/xml/info/[@name=sql:variable("@match")]') = 1 	0.079360094998775
1731786	40014	how to search for a value being in a known range in mysql	select * from table_name where venue in (1, 12, 23, ... 150) 	0.000570044319015233
1733197	28596	how to find missing value between two mysql tables	select userid from cw_users where userid not in(select userid from cw_users_data) 	8.74747064893431e-05
1733507	30566	how to get size of mysql database?	select table_schema                                        "db name",     round(sum(data_length + index_length) / 1024 / 1024, 1) "db size in mb"  from   information_schema.tables  group  by table_schema; 	0.00246843956359835
1733825	25070	how to count rows in mysqldatareader?	select * from purchaseorders  where purchasedt > '2009-01-01' and isdeleted = 0 	0.0143441236382311
1735791	18635	remove and split data into multiple columns in select statement	select substring(@ourname, 1, charindex(' ', @ourname)) as [first], substring(@ourname, charindex(' ', @ourname) + 2, len(@ourname)) as[last] 	0.000276324408907723
1737254	5295	check on overlapping dates (vb.net)	select   count(1) from     yourtable where    (@start < end and @end > start) 	0.0046535054670478
1740199	34894	select the newest record with a non null value in one column	select `keyword`, `count` , `date` from `keywords`  where keyword = "ipod" and `count` is not null  order by date desc  limit 1 	0
1740952	38893	extending a stored procedure (adding a single part to it) by using a parameter in sql server	select  a.*  from    (       select *        from table1      ) a left join       (       select *        from table2      ) b on @prmt = 'a'       and a.id= b.id 	0.590475578287533
1740959	38942	fix ora-02273: this unique/primary key is referenced by some foreign keys	select * from all_constraints  where constraint_type='r' and r_constraint_name='your_constraint'; 	0.596402195762054
1741205	33064	how do i use a select query to get the least of one value for each unique second value?	select user_id, min(seq_id) as seq_id, name from table group by user_id, name order by user_id; 	0
1743014	22557	sql anywhere table length	select db_property('pagesize')*(stab.table_page_count+stab.ext_page_count)     from sys.systab stab join sys.sysuser suser on stab.creator=suser.user_id     where stab.table_name='table_name' and suser.user_name='user_name' 	0.187215863214893
1743768	10247	sql for cases with 2 or more hits	select bookid, count(bookid) as keywordmatches from keywordstobooks where bookid <> @booktomatchid and keyword in (     select keyword     from keywordstobooks     where bookid = @booktomatchid) group by bookid having count(bookid) >= 2 	0.219773118682615
1746109	5153	retrieve available day from date rante	select employees.uid, name, date from users left join storelocation on employees.uid = storelocation.uid left join schedule on emplyees.uid = schedule.uid where slid =9308 and date between '2009-11-10' and '2009-12-20' and employees.uid not in (     select uid     from schedule     where date = '2009-11-11' ) 	0
1747750	21596	select column, if blank select from another	select coalesce(nullif(somecolumn,''), replacementcolumn) from sometable 	0.000318637982395308
1750458	71	mysql before insert trigger select into multiple variables?	select count(*), eodid, open, high, low, close, volume, mtime  into _rowsmatching, _eodid, _open, _high, _low, _close, _volume, _mtime ... 	0.0484861782234015
1750932	9248	select from multiple tables matching multiple criteria	select distinct(ccyname), oid from companies as c inner join notes as n on c.cid = n.cid inner join opportunities as o on c.cid = o.cid  where n.ntype in ('order','order2') and o.iactive = 1; 	0.00026713611895814
1751075	21689	convert timestamp/date time from utc to est oracle sql	select from_tz(to_timestamp('2009-11-17 18:40:05','yyyy-mm-dd hh24:mi:ss'), 'utc')  at time zone 'america/new_york' from dual 	0.159771064612365
1751290	22977	selecting a row of data in sql for comparison	select     count(a.*) from     tablea a,     tableb b where     a.col1 = b.col1 and     b.col2 = b.col2 	0.00171082658210234
1751491	605	sql query to get all the data in specific range	select price as price_lower, (price + 1) as price_upper, (select count(*) from offer where price between o.price and (o.price + 0.99)) from offer o group by price; 	0
1751649	40467	use select or pl sql to transpose	select 'current' as timeperiod, sum(case when cpt_originated > subdate(date(now()),30) then 1 else 0     end) as countofthings, from `cpt-prod` where cpt_state <> 'closed' union all select 'past1' as timeperiod, sum(case when cpt_originated > subdate(date(now()),60) and cpt_originated < subdate(date(now()),30) then 1 else     0     end) as countofthings, from `cpt-prod` where cpt_state <> 'closed' 	0.664386869004068
1751856	2202	how do you select all columns, plus the result of a case statement in oracle 11g?	select t.*, (case when pri_val = 1 then 'high'                 when pri_val = 2 then 'med'                 when pri_val = 3 then 'low'           end) as priority from mytable t; 	0.00560475129313264
1753562	32859	mysql inner join with 2 on clauses	select    u.*,    res.street residential_street,   res.suburb residential_suburb,   pos.street postal_street,   pos.suburb postal_suburb from users u     left join address res on u.id=res.id and res.addresstype='r'     left join address pos on u.id=pos.id and pos.addresstype='p' 	0.6553864885504
1755685	4526	how can i do this query in sql? count number of category	select category, count(*) from table group by category 	0.0185734702321054
1756350	20658	ignoring time stamp for a count in sql server 2005	select count (message), convert(datetime, convert(char(10), entrydatetime, 101))   from dbname.dbo.tablename   where message = 'loginfailed'   group by convert(datetime, convert(char(10), entrydatetime, 101)) 	0.0459443588718072
1758129	33620	counting values in columns	select   name,   sum( case type when 1 then 1 else 0 end) as type1,   sum( case type when 2 then 1 else 0 end) as type2 from   mytable group by   name 	0.00199274514948716
1758409	16686	sql "join" on null values	select *  from t1 join t2  on t1.somecol = t2.somecol or (t1.somecol is null and t2.somecol is null) 	0.143506183281769
1758987	41192	sql conflicted with the foreign key constraint	select   * from     [dbo].[upsell_data] u left join [dbo].[affiliate_mktg_ref] m on       u.amrno = m.amrno where    m.amrno is null 	0.00304773863501422
1760817	34965	mysql: returning multiple columns from an in-line subquery	select  date_format(orderdate,'%m %y') as ordermonth, count(orderid) as totalorders, sum(ordertotal) as totalamount,  z.ordercustomerfk, z.customername, z.ordertotal as customertotal      from orders        inner join (select date_format(orderdate,'%m %y') as mon, ordercustomerfk, customername, sum(ordertotal) as ordertotal                  from orders                 group by  date_format(orderdate,'%m %y'), ordercustomerfk, customername order by sum(ordertotal) desc limit 1) z           on z.mon = date_format(orderdate,'%m %y')     group by date_format(orderdate,'%m%y'), z.ordercustomerfk, z.customername     order by date_format(orderdate,'%y%m') desc 	0.34105849106988
1763013	40817	using joins in mysql	select     * from       customer c inner join custappointments ca on ca.cxid = c.customerid inner join clinicrooms cr on cr.approomid = ca.approomid inner join appclinics ac on ac.clinid = cr.clinid where      ap.clindate between '20090101' and '20091119' and        saccode in (select sc.saccode                         from saccode sc                         where sc.resellercorporateid = 392) 	0.796869795183602
1763031	34443	how best to do a partial text match in sql server 2008	select  top x id from    table where   id between 1 and 100000 and     textcolumn like('%blah%') 	0.0936145763375921
1763456	31034	nested set model, count items in categories	select parent.name, count(product.item_id),         (select count(*) from category parent2           where parent.lft > parent2.lft            and parent.rgt < parent2.rgt) as depth   from category parent   left outer join category node      on node.lft between parent.lft and parent.rgt   left outer join item_category product     on node.category_id = product.category_id  group by parent.name  order by node.lft 	0.0427429701999016
1763721	339	regexp mysql- only strings containing two words	select * from yourtable where field regexp('^[[:alnum:]]+[[:blank:]]+[[:alnum:]]+$'); 	0.0054753178395511
1764373	36926	how to write query for select statment where column in	select * from students  where class='10' and names in ('kiran', 'manju', 'ram' , 'peter') and language = 'english' 	0.5722544580769
1765861	25065	how to get last 10 records form sql table in asc order	select *  from (select top 10 * from customer order by customer_id desc) a order by  customer_id 	0
1766050	6693	how can i join in data from a key : value meta table in mysql?	select p.post_id, p.content from users u  inner join users_meta um      on (u.user_id = um.user_id) and um.key = 'age' inner join posts p      on (p.user_id = u.user_id) order by um.value limit 10 	0.0002487499689108
1766309	34230	max on columns generated by sum and group by	select sum(video_plays) as total_video_plays from `video_statistics` v_stat group by v_stat.`video_id`  order by total_video_plays desc  limit 1 	0.00374172654072677
1767437	23443	subgroup count in sql	select c.[name], c.description, c.id, cd.startdatetime,         row_number() over(partition by c.id order by cd.startdatetime)   from classroom.dbo.class as c   left join classroom.dbo.course as co     on co.id = c.courseid   left join classroom.dbo.classdate as cd     on cd.classid = c.id  where co.publicindicator = 1 	0.2912915998416
1767882	16048	sort flat list, group by parents	select *,     coalesce(         tabindex,         (select p2.tabindex from page as p2 where p2.id = p.parent_id limit 1),         0     ) as ti from page as p order by coalesce(ti, p.tabindex) ; 	0.0220572942659227
1768547	327	sort the "rollup" in group by	select *   from   (      select country, sum(id) as cnt       from mygroup group by country with rollup  ) t   order by cnt; 	0.212427322771168
1768569	6518	can i execute a single query on 2 database?	select * from database1.table1 t1, database2.table2 t2 where t1.id = t2.id 	0.0414124390360929
1768817	13785	how to connect 2 databases in php and mysql?	select * from db.table, db2.table 	0.061559621025546
1769970	572	t-sql, how to get these results?	select  pa.refpatient_id,      pa.datee,      pr.temporary,      pa.statue from    patientclinicacts as pa inner join      (       select pa.refpatient_id,         max(pa.datee) as datee       from patientclinicacts as pa       where pa.refclinic_id = 25                 group by pa.refpatient_id,pa.statue,pa.datee,      ) as maxdates on pa.refpatient_id = maxdates.refpatient_id and pa.datee = maxdates.datee inner join      patientstatuereasons as pr on pa.refreason_id = pr.reason_id 	0.0387869162521329
1771473	17640	trouble creating a sql statement select statement reference same table twice	select  q.id, owner.fullname, creator.fullname from    quotes q left join         users owner on      owner.uid = q.qid left join         users creator on      creator.uid = q.createdby 	0.52127428085813
1771872	29505	mysql: get all records that have an id for one year but not another	select   host_id from   table_name where   contractyear = 2009   and host_id not in (select host_id from table_name where contractyear = 2008) 	0
1772282	34370	fetch recently watched videos?	select v.videoid,          v.title,          v.description     from videos v     join (select wv.videoid,                  max(wv.date) 'max_date'                  count(*) 'count'             from watchedvideos wv         group by wv.videoid         order by count desc            limit 2) x on x.videoid = t.videoid order by x.max_date desc 	0.0115796462791995
1773790	14440	sum total amount returned from query	select partno4pt,orders.orderdate,orders.processdate,orderdetails.qty,orderdetails.extprice,      sum(orderdetails.extprice) as sumprice from orderdetails      inner join orders on orderdetails.order_id = orders.order_id      where orderdate > '2009.01.17 09:00:00'      and partnumber like '%m9150%' and orders.processdate is not null          group by partno4pt,orders.orderdate,orders.processdate,orderdetails.qty,orderdetails.extprice 	7.67073685862093e-05
1775168	18752	multiple select statements in single query	select  (     select count(*)     from   user_table     ) as tot_user,     (     select count(*)     from   cat_table     ) as tot_cat,     (     select count(*)     from   course_table     ) as tot_course 	0.158467417087371
1777327	27529	database design - do i need one of two database fields for this?	select   count(*) as totalapplications,   count(database_id) as usesdatabase,   count(bugtracking_id) as usesbugtracking from   applications 	0.0252122064682817
1779084	24388	sql: looking up the same field in one table for multiple values in another table?	select f.bar_id1,      (select bar_desc from bar b where (f.bar_id1 = b.bar_id)),     f.bar_id2,      (select bar_desc from bar b where (f.bar_id2 = b.bar_id)),     f.other_val from foo f; 	0
1780660	34657	how to create a empty temporary table from another tables schema?	select * into x_temp from tbl where 1 = 0 	0.000137186181499398
1781683	24381	sql compute the price of cart in one request	select product_id, price from products where product_id in (1,2,3,4); 	0.00672077597351642
1781946	11094	getting only month and year from sql date	select    dateadd(month, datediff(month, 0, <datefield>), 0) as [year_month_date_field] from    <your_table> 	0
1783806	15067	if statement within sql query	select  coalesce(salesheader.[ship-to name], poheader.[ship-to name]) as deliveryname 	0.722405685817858
1784110	39688	exclude row if one of 2 flattened columns didn't return	select   th.dateperformed ,        th.measurement as tireheight ,        tw.measurement as tirewidth from (     select dateperformed, measurement     from   measurements     where  measurementtype = 'tireheight' ) th inner join (     select dateperformed, measurement     from   measurements     where  measurementtype = 'tirewidth' ) tw on tw.dateperformed = th.dateperformed 	0
1785501	1834	sql select distinct values, but order by a different value	select [orderid], max([datetime]) from [table] group by [orderid] order by max([datetime]) desc 	0.00030192014112284
1785634	1966	select distinct on one column, return multiple other columns (sql server)	select * from gpsreport as g1 join (select device_serial, max(datetime) as mostrecent        from gpsreport group by device_serial) as g2 on g2.device_serial = g1.device_serial and g2.mostrecent = g1.datetime order by g1.device_serial 	0
1785799	26268	basic mysql question: how to get rows from one table that are not in another table?	select username from users where username not in (select username from recentusers) 	0
1786147	18575	sql "group by" varchar field with max date or all results of the same date	select t.id,        t.date,        t.groupname,        t.result,        t.info1,        t.info2   from table t   join (select t.groupname,                max(t.date) 'maxd'           from table t       group by t.groupname) x on x.groupname = t.groupname                              and x.maxd = t.date order by t.groupname 	0
1786350	36724	is it possible to create mutiple mysql queries within the same table?	select t1.description,         t1.min_price,        t1.max_price,        t2.user_id_2_price  from   (select description, min(price) as min_price, max(price) as max_price from t group by description) t1  left join   (select price, description as user_id_2_price from t where userid = '2') t2 on   (t1.description = t2.description) 	0.0129443184252574
1787344	24304	orderby in sql query	select   foo,   bar from   bortz order by   case foo      when 'e' then 1     when 'c' then 2      when 't' then 3      else 4    end 	0.778753746431635
1789197	33095	mysql query, select 2 databases with 4 tables + nested select?	select      `db1t1`.`userid`, `db1t1`.`customer_id`, `db2t1`.`customers_id`,     `db2t1`.`orders_id`, `db2t2`.`products_price` from `database1`.`table1` as `db1t1`     left join `database2`.`table1` as `db2t1`       using (`customers_id`)     left join `database2`.`table2` as `db2t2`      using (`orders_id`)   where `db1t1`.`userid` in (     select `l`.`userid`     from `database1`.`table3` as `l`      left join `database2`.`table4` as `r`       using (`username`)     where `r`.`cus_id` = 1234 ) 	0.116579286638257
1789418	7128	different record count values in one query	select   code, (select count (*) as total1   from tablea a1 where a.id in (select id from tableb     where type = 'xyz')     and a1.code = tablea.code) as total1,   (select count (*) as total2   from tablea a2 where a.id in (select id from tableb     where type = 'abc')     and a2.code = tablea.code) as total2) from tablea group by code 	0.000106794060227026
1790900	25026	how to manage null values with numeric fields in cursor?	select isnull(fieldname, 0) 	0.101051195028365
1791834	31522	referencing mysql alias of aggregate column	select x.company_id,        x.non_billable,        x.billable,        x.non_billable/x.billable as ratio   from (select t.company_id               sum(case when status in (0, 1) then 1 else 0 end) as non_billable,               sum(case when status in (2, 3) then 1 else 0 end) as billable          from transactions      group by t.company_id) x 	0.671554186506654
1792736	7054	sql retrieving the last record in a sql query	select * from my_table order by something (desc) limit 1 	7.73573523205894e-05
1792922	23810	sql query - get most recent revision	select * from projectrevisions inner join (   select projectid     , max(datecreated) as datecreated   from  projectrevisions   group by projectid   ) as currentrevision   on currentrevision.projectid = projectrevisions.projectid   and currentrevision.datecreated = projectrevisions.datecreated 	0.000446377169925768
1794012	36081	counts for lots of boolean fields in one sql query?	select sum(automatic) as automatic, sum(smelly) as smelly, sum(american) as japanese from ... 	0.0366358027236386
1794563	22425	sql date format	select datename(dw,getdate()) + ', ' + datename(mm, getdate()) + ', ' + cast(day(getdate()) as varchar(2)) + ' ' + cast(year(getdate()) as varchar(4)) 	0.0881045694880775
1794697	27708	find last sunday	select  dateadd(day,datediff(day,'19000107',dateadd(month,datediff(month,0,getdate() ),30))/7*7,'19000107') 	0.000317072904896416
1797785	37290	sql join two tables without keys/relations	select * from table1 cross join table2 	0.134364253677179
1799205	617	how to create mysql query for this criteria?	select * from `table`  where `title` like (select column from tableb where id=case) 	0.571999336388962
1799355	35884	mysql group by to return a the min value and get the corresponding row data	select merchant.product, merchant.name, merchant.price from a_table as merchant join ( select product, min(price) as minprice from a_table group by product ) as price on merchant.product = price.product and merchant.price = price.minprice 	0
1801590	34005	mysql join query	select     sum(case when t2.status is 'a' then 1 else 0 end) as acount,     sum(case when t2.status is 'b' then 1 else 0 end) as bcount,     ...     sum(case when t2.code is null then 1 else 0 end) as notpresentcount from       t1 cross join t3 left join  t2  on         t2.code = t1.code and t2.period = t3.period group by   t3.period 	0.724110026477687
1803160	10234	ms sql: how to separate out records which have no childs in the same table?	select a.* from theview a     left join theview b on (a.a = b.parentid and b.id <> b.parentid) where b.id is null 	0
1803905	19711	counting all the posts belonging to a category and its subcategories	select c.name, count(distinct p.pid) as postcount  from categories as c  left join categories as c2     on c2.parent = c.catid left join categories as c3     on c3.parent = c2.catid left join posts as p      on c.catid = p.category     or c2.catid = p.category     or c3.catid = p.category where c.parent = '0'  group by c.catid, c.name order by c.name asc 	0
1804469	18031	checking if a string is found in one of multiple columns in mysql	select * from tblclients where (name like '%john%') or (surname like '%john%') 	0.000311545781611679
1805600	12144	sql order by a column from another table	select   m.*  from    "memberships" as m   join "people" as p on p.personid = m.personid where   m.groupid = 32 order by    p.name 	0.000477117282374332
1806484	28383	generate many rows with mysql	select @rownum:=@rownum+1 n, t.* from tbl t, (select @rownum:=0) r order by somefield 	0.0197637770932323
1807971	34509	mysql query fetching siblings	select min(routeid) from routes where routeid>::p0:: and assetkmid<>'0'  union  select max(routeid) from routes where routeid<::p0:: and assetkmid<>'0' 	0.718143163522571
1808535	31884	distinct of date	select distinct dateadd(dd, datediff(dd, 0, mydatefield),0) from mytable 	0.0117822920589999
1810067	10970	select count(distinct name), id, adress from users	select count(distinct name), null, null from users group by name  union select name, id, address from users  	0.000499844287224971
1810978	39603	sqlite - how to wite a correct join?	select history.id, task.name     from history     inner join task     where history.task = task.id 	0.782169588398896
1813175	23377	select all table entries which have a fully capitalized string in a specific column?	select id from table where name = upper(name); 	0
1814831	40982	selecting specific values in a db (sorta...)	select * from table order by `id` desc limit 1, 5 	0.00114220447127884
1814907	7020	sql query between 3 tables	select rt.*  from roomtype rt where rt.typename not in (    select rm.typename     from room rm ) 	0.0612131880081084
1818122	12583	cumulative average number of records created for specific day of week or date range	select   dayofweek , count(*)/count(distinct(weeknumber)) as average from   mycompaniontable group by   dayofweek 	0
1820650	40941	sql script to create insert script	select coalesce(name, '') from... 	0.643323944498128
1822302	35018	sql server 2008: how to get the start date and end date of my data?	select      transaction,      min([date]) as [first date],      max([date]) as [last date] from      my_table group by      transaction 	0.000115919306890025
1822854	7145	mysql: how to get records with count > 1?	select *, count(*) as cc  from manytomany  group by aid, bid having 1 < count(*) order by cc desc 	0.000855668376780866
1823599	29679	calculating percentage within a group	select t1.sex, employed, count(*) as `count`, count(*) / t2.total as percent   from my_table as t1   join (     select sex, count(*) as total        from my_table       group by sex   ) as t2   on t1.sex = t2.sex   group by t1.sex, employed; 	0.0291381600980308
1824336	29227	mysql sort by calculated value of 2 rows	select posts.id,        (retail.meta_value - price.meta_value) * 1.0 / retail.meta_value as savings   from posts,        (select * from postmeta where meta_key = 'price') as price,        (select * from postmeta where meta_key = 'retail') as retail  where posts.id = price.post_id    and posts.id = retail.post_id    and posts.post_type = 'post'  order by savings; + | id | savings | + |  1 | 0.50000 | |  2 | 0.33333 | + 	8.67714985296086e-05
1826097	37016	sql server complex query - fetch data and search on multiple tables	select t2.*, t1.name from t2     join t1 on t2.category = t1.id where t2.name like '%keyword%'      or t1.name like '%keyword%' 	0.144779734451699
1826287	31650	how can i expand a postgresql row into multiple rows for updating "custom fields"?	select      u.id,      uf.id as field_id,      case uf.id           when 10 then u.first_name           when 11 then u.country           when 12 then u.company_name           else null      end as field_value from      users u cross join user_fields uf 	0.000656440399675824
1827025	37083	split string returning a record	select substring(fieldname,0,charindex('|',fieldname,0)) as city,    substring(fieldname,charindex('|',fieldname,0)+1,( charindex('|',fieldname,(charindex('|',fieldname,0)+1)) - charindex('|',fieldname,0) - 1)) as country,   right(fieldname, charindex('|',reverse(fieldname),0)-1) as coordinates 	0.003903306136037
1827122	11727	converting an integer to enum in postgresql	select (enum_range(null::bnfunctionstype))[s] from   generate_series(1, 5) s 	0.327404355288614
1827147	10788	sql select statement to find id's that occur the most	select userid, count(userid) from myusers group by userid order by count(userid) desc 	0
1827776	26049	adding an array to a mysql column in select	select  id, elt(field(id, 4, 3, 5, 1), 129, 87, 13, 20) as karma from    (         select  4 as id         union all         select  3 as id         union all         select  5 as id         union all         select  1 as id         ) q where   id in (4, 3, 5, 1) order by         karma 	0.0216437560452307
1830653	8533	searching content of mysql fields	select * from tablename where find_in_set('44444', invites); 	0.0186131084252172
1831166	1171	sql help (for each)	select  avg(salary),      assigned->name from edu_ucla_cs241_termproj_schema.instructorimpl group by assigned->name 	0.0933591228187729
1831417	1853	count top 10 most occuring values in a column in mysql	select col, count(*)     from tablethingie     group by col     order by count(*) desc     limit 10 	0
1831466	8757	drop 0 value in decimal places	select cast(cast([percent] as decimal(9,2)) as float) as [percent] 	0.00614377515697365
1836275	15169	mysql: pulling the current user's vote on a query of links	select links.*,         sum(votes.karma_delta) as karma,        sum(            if(votes.user_id = current_user_id,                votes.karma_delta,                0)           ) as user_vote from links, votes where links.id = votes.link_id group by votes.link_id order by (sum(votes.karma_delta) - 1) /           pow(               timestampdiff(hour, links.created, now()) + 2,                1.5             ) desc limit 0, 100 	0
1836502	25740	how do i show unique constraints of a table in mysql?	select distinct constraint_name from information_schema.table_constraints where constraint_schema = 'mysql' 	0.000104028401685278
1838197	25408	need an sql query to count unique combinations of strings	select year, month, count(*) from your_table group by year, month 	0.00603838309499993
1839024	37673	mysql join with limit 1 from two tables	select      * from        properties p left join   images i  on          p.p_id = i.p_id  and         i.main = 1 	0.0101694755773511
1839453	24637	how to convert result of an select sql query into a new table in ms access	select a,b,c into newtable  from (select a,b,c from thetable where a is null) 	0.00606699319413772
1840302	21760	ordering and grouping in php/mysql	select l2.id,        l1.user_id,        l1.lap_time   from lap l1   inner join lap l2      on l1.id = l2.id   where l1.lap_time < 57370   group by l1.user_id   having min(l1.lap_time); 	0.241325354919761
1841135	8504	select all udfs from database?	select *      from sys.objects      where type in ('tf','fn','if') 	0.00291480158560959
1842354	26447	match a query to a regular expression in sql?	select * from table where "dog" rlike(`column 1`) 	0.789250433195893
1842502	32307	how to change every nvarchar column to varchar?	select 'alter table [' + table_schema + '].[' + table_name + '] alter column [' + column_name + '] varchar(' + cast(character_maximum_length as varchar) + ')' from information_schema.columns where data_type = 'nvarchar' 	0.00229669738246226
1844954	20078	how to "default" a column in a select query	select     a, b, c, d    from t   where a = :in_a     and b = :in_b     and c in (:in_c,'  ')  order by     case c when '  ' then 2 else 1 end  fetch first 1 row only 	0.0175205867115356
1845068	36520	how to check if the log-in exists in sql server?	select name from master..syslogins 	0.0531653196111975
1845112	20321	select distinct of a date along with other fields from a table	select distinct mydates.joindate,      (select top 1 employeename from employee e2 where e2.joindate=mydates.joindate order by employeename)  from employee mydates 	0
1845394	31740	sql question - how to put into table?	select distinct h.customercode, h.billname, h.billaddress1 into newtable from hist2 h where not exists    (select customercode from tblcustomer c where c.customercode = h.customercode) 	0.0516852674287808
1846941	19420	most efficient way of getting record counts from a related table?	select isnull(x.readcount, 0) as readcount, f.* from faq f     left join     (         select faqid, count(faqid) as readcount         from faq_read_stats         group by faqid     ) x on f.id = x.faqid where f.show = 1 and f.active = 1 	0
1847902	27187	sql latest date	select  yourtabel.* from    yourtabel inner join      (       select prestatiecode,         max(uitvoerdatum) maxdates       from yourtabel       where yourcondition       group by prestatiecode       ) yourtablemaxdates on yourtabel.prestatiecode = yourtablemaxdates.prestatiecode           and yourtabel.uitvoerdatum = yourtablemaxdates.maxdates 	0.00434064307269705
1848321	23121	sql - find missing data / negative search	select distinct t.traveleventid   from table t   where not exists(select * from table t2 where t.traveleventid = t2.traveleventid and t2.text = 'lowcost booking') 	0.016582661956629
1849535	8598	t-sql - how to write query to get records that match all records in a many to many join	select person_id, count(*) from groupmembership where group_id in ([your list of group ids]) group by person_id having count(*) = [size of your list of group ids] 	0
1851226	35363	sqlplus - count function across several tables	select count(riders) as rider_count, eventname, description   from erp_report   group by eventname, description; 	0.172031814535103
1851507	4929	php & mysql - how to count the number of times data was entered for a specific user?	select t.tag,           count(q.tag_id) 'num'      from questions_tags q      join tags t on t.id = q.tag_id     where q.users_questions_id = 1  group by t.tag  order by num desc 	0
1851672	9609	select from hundreds of tables at once (.mdb)	select 'lesson1' as table_name, slide_id, name, ... from lesson1  union all select 'lesson2', slide_id, name, ... from lesson2  union all select 'lesson3', slide_id, name, ... from lesson3  union all select 'lesson4', slide_id, name, ... from lesson4  union all select 'lesson5', slide_id, name, ... from lesson5 	0.000245294666224519
1851869	36472	what's the best practise to write sql to get data as follow?	select  c.status,      sum(case when u.gender = 0 then 1 else 0 end) male,       sum(case when u.gender = 1 then 1 else 0 end) female  from    competitors c inner join      userinfomration u on c.userid = u.id group by c.status 	0.173352547301789
1851896	35760	sql select statement string concatenation	select   stuff(     (     select       ' ' + description     from dbo.brands     for xml path('')     ), 1, 1, ''   ) as concatenated_string 	0.578062675238115
1852936	11305	sql grouping... thing	select min(id),     country,     city,     sum(qty) as qty,     min(somedate) as somedate,     min(somedate1) as somedate1,     min(somedate2) as somedate2 from sourcetable group by country, city; 	0.595892152143484
1853510	20482	sql query's organisation, transforming url into title from db	select `title` from `articles` where `article_id` = (x); 	0.0821047604125476
1854383	28766	select average from mysql table with limit	select avg(x.price)   from (select t.price           from table t          where t.price > '0'             and t.item_id = '$id'       order by t.price          limit 5) x 	0.00120153844860252
1854544	6221	how to select the latest version of answers given by each answerer in mysql?	select *  from (     select * from `answers`     where questionid='$questionid'     order by answerer_id desc ) as `dyn_answers`  group by answerer_id 	0
1858024	671	how can i join the query below?	select b.pb_bank_code,          b.pb_bank_name,          x.total_amount     from glas_pdc_banks b     join (select c.pc_bank_from,                  sum(c.pc_amount) as total_amount             from glas_pdc_cheques c            where c.pc_due_datetime between :block01.date_from and :block01.date_to               and c.pc_discd = 'r'         group by c.pc_bank_from) x on x.pc_bank_from = b.pb_bank_code    where b.pb_comp_code = :parameter.comp_code  order by b.pb_bank_code 	0.536820261284144
1858867	149	how to get only numeric column values?	select column1 from table where isnumeric(column1) = 1 	0.000110940581919985
1859482	21615	sql query to add column datediff calculated in months	select datediff("m",[collumna],#2009/12/01#) as nomonth from sometable 	0.00870684095412029
1859616	30162	select most popular tags from database?	select t.* from tags as t left join thread_tag_map as ttm on t.id = ttm.tags_id group by t.id order by count(t.id) desc limit 30 	0.000103104069109846
1859774	3838	mysql: get records from database and add a count() column to the rows	select b.*, count(c.chapter_nr) as chapters  from books as b  left join chapters as c on (c.book_id = b.id) group by b.id 	0
1859791	6373	get random code not exists mysql	select concat(   char(97+ rand()*26),   char(97+ rand()*26),   floor(100+rand()*900),   char(97+ rand()*26))  as randomcode from dual   where not exists (select * from table where code_felt = randomcode ); 	0.163843634939502
1859990	6416	how to retrieve all of the records which dont have any reference in another table?	select   tablea.* from   tablea   left join     tableb    on     tableb.tablea_id = tablea.id where   tableb.id is null 	0
1863879	40832	checking to ensure all values in a field are integers in mysql	select * from yourtable where col % 1 != 0; 	5.21528044319154e-05
1867430	35188	sql merge table and group by	select id, sum(minutes) from mytable group by id 	0.0316629936749699
1868037	313	joining int column to comma separated list of ints	select     l.* from mylogs l (nolock),     details d (nolock)  where d.id in fn_whateveryoucallyoursplitfunction(l.searchvalue, ',') 	0
1868302	4800	mysql dynamic var	select  *,          'video' as category from    table 	0.751936865607239
1869063	11980	customised ordering in sql	select column1,column2  from table1  where column1 in('q3','q1','q2') order by sortorder 	0.756626082687345
1873519	34989	asp.net and sql server time difference in days, hours, minutes	select  case           when datevalue-getdate() >= 1 then cast(datepart(dy, datevalue-getdate()) as varchar) + ' day(s) remaining'           when datevalue-getdate() >= 0 then cast(datepart(hh, datevalue-getdate()) as varchar) + ' hour(s) remaining'           when getdate()-datevalue <= '00:59' then cast(datepart(mi, getdate()-datevalue) as varchar) + ' minutes(s) overdue'           when getdate()-datevalue <= 1 then cast(datepart(hh, getdate()-datevalue) as varchar) + ' hours(s) overdue'         else           convert(varchar, datevalue-getdate(), 121)         end as time_scale 	0
1875459	12210	homework: no subquery in getting a value indirectly	select i1.name, i1.color from items i1 inner join items i2    on (i2.type = 'detergent'       and i2.color = 'grey'       and i1.cost > i2.cost) 	0.105836855575687
1876496	3545	display a leading item then follow with addtional items alphabetical	select client_name from clients order by client_name != 'harold', client_name 	7.128958585095e-05
1876724	37551	how can i query the list of full table names in sql server database	select * from sys.tables 	0.00222606581486419
1878379	35286	aggregating data by timespan in mysql	select     date_format( time, "%h:%i" ),     sum( bytesin ),     sum( butesout ) from     stats where     time between <start> and <end> group by     date_format( time, "%h:%i" ) 	0.113131739096291
1880188	15315	viewing pending changes that are set in the spfile	select name, value from v$spparameter where isspecified = 'true'   minus select name, value from v$parameter; 	0.00900181829695523
1880597	12280	sorting by weighted rating in sql?	select * from event where id in (    select top 3 eventid    from ratings    group by eventid having count(*)>100 order by avg(rating) desc ) 	0.191093373852782
1881217	4610	sql server unpivoting table	select opration        , ...other columns ...        ,avalue        ,bvalue        ,cvalue from     mytable unpivot ( [avalue] for xx in (a1,a2,a3,...,a30)) as upv1 unpivot ( [bvalue] for yy in (b1,b2,b3,...,b30)) as upv2 unpivot ( [cvalue] for zz in (c1,c2,c3,...,c30)) as upv3 where right(xx, 2) = right(yy, 2)   and right(xx, 2) = right(zz, 2) 	0.435587600716079
1883071	15520	how do i find the data directory for a sql server instance?	select substring(physical_name, 1, charindex(n'master.mdf', lower(physical_name)) - 1)                   from master.sys.master_files                   where database_id = 1 and file_id = 1 	0.00716462836727033
1883362	20738	duplicate a row depending on some column value?	select      u.user_id,      u.name,      u.multiplier from      users as u inner join numbers as n on      n.number between 1 and u.multiplier 	0
1883375	8148	group by sku with count	select substring(sku, 1, 3) as mfg, count(*) as count     from parts     group by substring(sku, 1, 3) 	0.543904133551962
1883474	5762	renaming tags in xml output	select prsn_id "personid".... from 	0.0645322598450479
1883507	25668	select the x "closest" ids?	select * from (   select * from thetable where table_id >= 16 order by table_id limit 3 ) x union all select * from (   select * from thetable where table_id < 16 order by table_id desc limit 2 ) y order by table_id 	0.000157998575788936
1884299	41121	how to search a numeric value in a database	select * from yourtable where yourfield like '%0912%' 	0.010554242683679
1884461	620	sql join that displays left table even if right table doesn't match where	select p.pid, name, price, dprice, qty from product p  left join discount d on p.pid = d.pid and d.sdate<now() and d.edate>now() 	0.768187142509918
1888544	6877	how to select records from last 24 hours using sql?	select *  from table_name where table_name.the_date > date_sub(curdate(), interval 1 day) 	0
1889658	26159	how to select a row based on a max count? (using standard sql)	select main.* from (select computerid, userid, count(1) as cnt     from logtable     group by computerid, userid) as main     inner join (select computerid, max(cnt) maxcnt        from (select computerid, userid, count(1) as cnt         from logtable         group by computerid, userid) as counts)         as maxes on main.computerid = maxes.computerid and main.cnt = maxes.maxcnt 	0.000137253004010167
1890411	8907	comparing sql table to itself (self-join)	select t1.id from test t1 inner join test t2 on ((t1.test1 = t2.test2) or (t1.test2 = t2.test1)) where t1.id <> t2.id 	0.0293343952404478
1891016	40810	getting a distinct value across 2 union sql server tables	select count(distinct tmp.columna) from ( (select columna from tablex where x=y)  union (select columna from tabley where y=z) ) as tmp 	0.00123082218579995
1892354	18681	order by in sql after subtracting column values	select t.id,        t.start,        t.end,        t.start - t.end as difference   from table t order by difference desc 	0.00357477034784569
1893292	15282	mysql - select specific rows and only then randomize them	select * from    (       select *        from table        limit 50      ) sub order by rand() 	0
1893424	35851	mysql count table rows	select count(*) from footable; 	0.0070345775256276
1893593	2491	mysql - select, order by times a column value appears in a string	select      w.word ,   (length(title) - length(replace(title, w.word, ''))) / length(word) from (select 'lollipop lollipop oh la le la le lollipop' as title) t cross join (     select 'la' as word     union all select 'le'     union all select 'lollipop'     union all select 'shooby' ) w la          2.0000 le          2.0000 lollipop    3.0000 shooby      0.0000 	0.000145769981015879
1895110	8127	row_number() in mysql	select t0.col3 from table as t0 left join table as t1 on t0.col1=t1.col1 and t0.col2=t1.col2 and t1.col3>t0.col3 where t1.col1 is null; 	0.691059915859971
1895754	15696	sql server 2000 - view list of sprocs with grant execute for a particular role exclusively?	select     object_name(p1.id) from     syspermissions p1 where     user_name(p1.grantee) = 'myrole'     and     object_name(p1.id) = 'myproc'     and     not exists (select *         from             syspermissions p2         where             p1.grantee <> p2.grantee             and             p1.id = p2.id) 	0.622189362581143
1896213	27282	determine if one coordinate is in radius of another	select ((acos(sin($lat * pi() / 180) * sin(lat * pi() / 180) +           cos($lat * pi() / 180) * cos(lat * pi() / 180) * cos(($lon - lon) *           pi() / 180)) * 180 / pi()) * 60 * 1.1515) as distance  from members  having distance<='10' order by distance asc 	0.00358225878085334
1897352	21382	sqlite group_concat ordering	select id, group_concat(val) from (    select id, val    from yourtable    order by id, val    ) group by id; 	0.761420496384585
1900981	23940	joining all columns of two tables in mysql conditionaly	select * from tablea inner join tableb on tablea.sim1 = tableb.sim2 	0
1901925	34214	sql return rows where count of children does not equal column value	select *   from item   where expectedsubtems <> (     select count(*)       from subitem       where subitem.itemid = item.itemid     ) 	0.000130649156083078
1902072	25146	mysql: set limit for duplicate column	select      t1.id,      t1.style_number,      t1.col1,      t1.col2,      ... from      my_table t1 where      (           select                count(*)           from                my_table t2           where                t2.style_number = t1.style_number and                t2.id < t1.id      ) < 3 	0.0130426618519833
1902964	31488	mysql version of 'with' clause	select * from (   select long_string   from longstring   where hash = 'searchhash' ) as dataset where long_string = 'searchstring' 	0.653872182401485
1903197	11020	combining two t-sql pivot queries in one	select      case sq.total_type           when 1 then 'total special'           when 2 then 'total expensive'           else 'total'      end as total_type,      sum(case when month(r.createdate) = 1 then 1 else 0 end) as january,      sum(case when month(r.createdate) = 2 then 1 else 0 end) as february,      sum(case when month(r.createdate) = 3 then 1 else 0 end) as march,      ... from      dbo.records r inner join      (           select 0 as total_type union all              select 1 union all                            select 2                                 ) as sq on      (r.isspecial | (r.isexpensive * 2)) & sq.total_type = sq.total_type group by      sq.total_type order by      sq.total_type desc 	0.0389399075732418
1904314	33424	only one expression can be specified in the select list when the subquery is not introduced with exists	select count(distinct dnum)  from mydb.dbo.aq  where a_id in     (select distinct top (0.1) percent a_id     from mydb.dbo.aq      where m > 1 and b = 0     group by a_id      order by count(distinct dnum) desc) 	0.698205986774604
1904437	2638	displaying scheduled events	select * from events where start <= '2009-12-01 00:00:00'   and end >= '2009-12-01 23:59:59' 	0.0796315851905077
1904469	29340	fetching 3 tables at a time, retrieve only the table which matches the condition (sql)	select a, b, c, d, e, f from (     select a, b, null as c, null as d, null as e, null as f from water_tender     union all     select null as a, null as b, c, d, null as e, null as f from engine     union all     select null as a, null as b, null as c, null as d, e, f from trailer) as t1 where _id = @id 	0
1905630	17030	finding the rank or index of some name in an array returned by query	select t.*,         @rownum := @rownum + 1 as rank   from table t, (select @rownum := 0) r 	0.00502686792071496
1906621	37068	mysql select unique records	select members.* from members join (    select    members.memberid, count(*)    from members join subscriptions on (members.memberid = subscriptions.memberid)    where subscriptions.year = 2009    and subscriptions.untildate between '2009-01-01' and '2009-12-31'    group by members.memberid     having count(*) >= 1 ) v on ( members.memberid = v.memberid) where members.asscid = 15 	0.00323742536547873
1908166	18986	how to count diffrent rows in mysql ? (three columns as a whole)	select  count(distinct col1, col2, col3) from    mytable 	0.000200211337295837
1910855	28085	tsql: retreiving a value where a set of values in one table match a set of value in another	select o.orderid, t.testcode  from (     select o.orderid, t.testcode, count(*) as intcount     from orders o          inner join testcodes t on t.test = o.test     group by o.orderid, t.testcode ) as ot     inner join (         select orderid, count(*) as intcount         from orders         group by orderid     ) as o on o.orderid = ot.orderid     inner join (         select testcode, count(*) as intcount         from testcodes         group by testcode     ) as t on ot.testcode = t.testcode where o.intcount = ot.intcount     and t.intcount = ot.intcount 	0
1912362	24253	sql issue,challenge	select t.teacher_id, s.student_id,      case when t2.count > 10 then 'true' else 'false' end from     (select top 5 *      from teachers      order by teacher_id) t  join      (select top 10 *      from students s1 join teachers t1 on s1.teacher_id = t1.teacher_id      order by student_id) s  on t.teacher_id = s.teacher_id join     (select teacher_id, count(*) as count      from teachers t join students s on t.teacher_id = s.teacher_id      group by teacher_id)  t2  on t2.teacher_id = t.teacher_id 	0.688949553253353
1913388	24434	how to hide the date and id from the table	select id,date from table1 where convert(varchar,date)+'~'+convert(varchar,id) not in      (select convert(varchar,date)+'~'+convert(varchar,id) from table2      where holiday=1) 	0
1914063	14069	how to get the top n values of each column in mysql	select column1 from table order by column1 desc limit 5 select column2 from table order by column2 desc limit 5 etc 	0
1915238	3541	join results from tables with same name from different databases	select * from schema1.mytable as t1 join schema2.mytable as t2 on t1.something = t2.somethingelse 	0
1915573	31948	artist-tag database: getting tags	select t.tagid   from tagid t   where t.artistid in (select t1.artistid                           from tagid t1,                                tagid t2,                           where t1.tagid = x and                                 t2.artistid = t1.artistid and                                 t2.tagid = y) 	0.031330220969074
1917089	39959	oracle: check if rows exist in other table	select o.id     , case when n.ref_id is not null then 1 else 0 end as ref_exists from old_table o left outer join (select distinct ref_id from new_table) n    on o.id = n.ref_id 	0.000497384224907004
1917516	24116	sql count() with group by not returning 0/zero records	select division, isnull(ct,0) as ct from divisiontable left join (select division, count(id) as ct from test where role >=101 group by division) countquery on divisiontable.division = countquery.division where divisiontable.division in (1,2,4) 	0.355404969956095
1918711	40805	sql query in mysql using group by	select count(a), b, (count(a) / (select count(*) from foo)) * 100 from foo group by b 	0.71115077125802
1919293	19273	mysql query: select lastest where another row with n doesn't exist	select a.q_id        from user_q_answers a           join (select b.user_id,                    b.popling_id,               b.q_id,                    max(b.a_id) as a_id               from user_q_answers b                where b.correct = 1            group by b.q_id, b.user_id) c on a.q_id = c.q_id                                        and a.user_id = c.user_id                                        and a.a_id > c.a_id      where a.correct = 0         and a.user_id = 101        and a.popling_id = 170       order by a.a_id desc     limit 1 	0.00157723444002348
1920204	13927	minimum price selection	select min(price)   from products   where product_number = :my_product 	0.010931102331806
1920456	14051	finding any rows where the latest event time is over a specified period	select nodeid, max(eventtime) from your_table group by nodeid having max(eventtime) < now() - '24 hours'::interval 	0
1923613	37870	sql query to select bottom 2 from each category	select * from (   select c.*,         (select count(*)          from user_category c2          where c2.category = c.category          and c2.value < c.value) cnt   from user_category c ) uc where cnt < 2 	0
1924362	8563	select datetime data from sql server colum	select next_update_time from bgrex_updatequeue   where next_update_time < '2009-12-18'; 	0.00351409450604903
1925187	15845	how do i select the last child row of a parent/child relationship using sql	select i.*,it.*  from invoices i inner join (  select invoice_id, max(invoice_item_timestamp)   from invoice_items  group by invoice_id ) it on (i.invoice_id=it.invoice_id) 	0
1928104	31732	find a string within the source code (ddl) of a stored procedure in oracle	select distinct name from   user_source where  type = 'procedure' and    lower(text) like lower('%the_text_you_want%'); 	0.0131011297267007
1929917	12075	query to select intervals from a table	select d.id, d.description, min(d.start_date), min(d2.start_date) - interval 1 day as end_date from start_dates d left outer join start_dates d2 on ( d2.start_date > d.start_date or d.start_date is null ) group by d.id, d.description order by d.start_date asc 	0.00147022918495309
1930411	19341	list enumeration in sql?	select p.name,          group_concat(ls.language_name, ',')     from person p     join languagesspoken ls on ls.personid = p.personid group by p.name 	0.169937592760277
1931224	33694	how to represent a set of entities from separate tables?	select    * from      geolocation g left join cities c on        g.id = c.geolocation_id left join zipcodes z on        g.id = z.geolocation_id .... 	0.000395056222249884
1934342	2771	return only unique table id's from mysql join	select   rentals.status, movies.* from movies left outer join (   select     movie_id,     kiosk_id,     min(status) as status   from rentals   group by movie_id, kiosk_id) rentals on movies.id = rentals.movie_id and movies.kiosk_id = rentals.kiosk_id where movies.kiosk_id = 1 and (rentals.id is null or rentals.status != 'checked out'); 	0
1934352	37843	how to test date and datetime with mysql	select * from table where date(date) = '2009-12-19' 	0.0529741684502125
1935383	31464	is there a way to get the fields names of a table created in a function / stored procedure?	select column_name from tempdb.information_schema.columns  where table_name like '#t|_%' escape '|' 	0.000807744369194739
1936276	38678	get max from table where sum required	select min(difficultylevel) as difficltylevel from  (     select difficltylevel, (select sum(numberofquestions) from yourtable sub where sub.difficultylevel <= yt.difficultylevel ) as questiontotal     from yourtable yt ) as innersql where innersql.questiontotal >= @displayorder 	0.00155386984583987
1936496	33612	sql: how do i use parameter for top like in select top @amount?	select top (@param1) ... 	0.0534688095926659
1937974	9329	mysql selecting rows from multiple tables	select *   from (select c.category_id as row_id, c.category_title as row_title, 1 as is_category           from product_categories as c          where c.parent_category_id='20'         union          select p.product_id as row_id, p.product_title as row_title, 0 as is_category           from products as p           join products_categories as pc on p.product_id=pc.product_id) x limit x, y 	0.000185612400043561
1938686	4075	mysql query with random and desc	select * from yourtable order by wt desc, rand() 	0.434742507749616
1938888	24932	search in multiple tables with full-text	select mem.member_id,      mem.contact_name,      edu.member_id,      edu.school_name from members mem     inner join education edu on edu.member_id = mem.member_id where contains((mem.contact_name,edu.school_name),'*keyword*') order by mem.member_id desc 	0.630492844189836
1940893	13399	get top rows out of child table with inner join	select p.parentid from parent p  where exists (select 1  from child c  where c.parentid = p.parentid  and c.isactive = 1) 	0.000115137387240971
1941030	20455	in mysql, can i select all columns from one table and one from another?	select foo.*, bar.whatever from ... 	0
1941513	36619	query result organization	select item_id, sum(quantity), sum(sale) from item join purchase on item.item_id=purchase.item_id join transaction on purchase.transaction_id=transaction.transaction_id where client_id = $clientid and transaction.timestamp>= $start and transaction.timestamp <= $end group by item_id order by sum(quantity), sum(sale) desc 	0.391239802757662
1942994	35704	how to format "time with time zone" in postgres?	select to_char(date '2001-09-28' +time, 'hh24:mi:ss') 	0.00898279722673447
1944350	39937	select distinct values after a join	select person_id, vehicles.*  from vehicles  left outer join owners on vehicles.vehicle_id = owners.vehicle_id  and person_id = 1 	0.0227925623439013
1945757	30693	copy one table into another fails - "column names in each table must be unique"	select db1.dbo.customerorderlines.*  into db2.dbo.customerorderlines from db1.dbo.customerorderlines  inner join db1.dbo.customerorders on db1.dbo.customerorders.order_display_ref = db1.dbo.customerorderlines.order_display_ref where db1.dbo.customerorders.delivered_date between '2009-09-23' and '2009-09-24' 	0
1947523	261	show sum of all for every record	select itemname, (select sum(price) from items) as allprices from items 	0
1950054	21931	how do i import a date like 2009-12-05 11:40:00 into sql via csv?	select convert ( varchar(100), getdate(), 126 ) 	0.0299563863536467
1950439	5172	how to you weight returned values by a group by value	select sum(categoryscore * percentoftotal) as rawscore   from ( .....subquery here..... ) 	0.000287450603896998
1950697	35264	there are two columns in the new table(table1 join table2) which have the same column name, how to get the values of both respectively	select table_1.id as table_1_id, table_2.id as table_2_id 	0
1950794	13477	joining two sql tables with group by not achieving desired results	select     od.orderid,      od.orderitems,      os.status,      os.assigneduser from orders as od inner join orderstatus as os on od.orderid = os.orderid inner join (     select         max(statusid) as statusid,         orderid     from orderstatus     group by orderid ) as maxos on maxos.statusid = os.statusid group by os.orderid order by os.orderid asc 	0.544146864544708
1952123	37752	sql: finding user with most number of comments	select top 1  u.displayname,  count(c.id) as commentcount from  users as u  inner join comments as c on u.id = c.userid group by  u.displayname order by  count(c.id) desc 	0
1953997	38522	aggregrate all a single column in a grouped resultset in one query: is it possible?	select count(*) 'count',           v.value,          group_concat(distinct v.entity_id order by v.entityid asc separator ',') 'entities'     from client_entity_int as v      join client_entity as e on e.id = v.entity_id     where v.attribute_id = '1'      and e.deleted = 0 group by v.value 	0.000475007229844129
1955936	21302	how to create multiple mysql counts / group by / subqueries?	select @season:=left(matchnumber,4) as season,   count(*) as p,   (select count(*) from match_results where manager = 13 and result = "w" and left(matchnumber,4)=@season) as w,   (select count(*) from match_results where manager = 13 and result = "d" and left(matchnumber,4)=@season) as d,   (select count(*) from match_results where manager = 13 and result = "l" and left(matchnumber,4)=@season) as l,   sum(goalsfor) as f,   sum(goalsag) as a,   round((select sum((((select count(*) from match_results where manager = 13 and result = "w") * 2) +(select count(*) from match_results where manager = 13 and result = "d")))/((select count(*) from match_results where manager = 13)*2)*100),2) as pct   from match_results where manager = 13   group by season; 	0.207477632981554
1956057	30459	mysql: removing duplicate columns on left join, 3 tables	select  *  from  recipes left join recipe_prep_texts using (id_prep_text) left join recipe_pictures using (id_picture) left join mp_references using (id_reference) 	0.00943318908941819
1957064	39734	sql azure table size	select           sum(reserved_page_count) * 8.0 / 1024 from           sys.dm_db_partition_stats go select           sys.objects.name, sum(reserved_page_count) * 8.0 / 1024 from           sys.dm_db_partition_stats, sys.objects where           sys.dm_db_partition_stats.object_id = sys.objects.object_id group by sys.objects.name 	0.135671277384134
1959414	10911	mysql - how do i order results by alternating (1,2,3, 1, 2, 3, 1, 2, 3,) rows, is it possible?	select x.client_id,         x.project_id,        x.project_name   from (select t.client_id,                t.project_id,                t.project_name,                case                  when @client_id != t.client_id then @rownum := 0                  when @client_id = t.client_id then @rownum := @rownum + 1                  else @rownum                 end as rank,                @client_id := t.client_id           from table t,                (select @rownum := 0, @client_id       order by t.client_id) r) x order by x.rank, x.client_id 	0.00054297376621775
1959895	37429	view data of a table in sql server 2008	select * from <table name here> 	0.0743666847564659
1962026	1127	sql statement to retrieve a list of results (from other table) for a given record?	select bands.band_id, track_id from bands left join tracks on tracks.band_id = bands.band_id where bands.property1 = xyz; 	0
1964736	35048	select the newest entry based on other entries with the same values?	select distinct        x.id,        x.text,        x.otherid   from table x   join (select t.otherid,                max(t.id) 'max_id'           from table t       group by t.otherid) y on y.otherid = x.otherid                            and y.max_id = x.id 	0
1967100	19366	need mysql query	select jobtitle, count(*) as count from table2 where articleid = 4 group by jobtitle 	0.765194437860413
1968789	5965	sql query to find out some of three fields from three different table	select  ids.id,          ifnull(tablea.a,0) + ifnull(tableb.b,0) + ifnull(tablec.c,0) sumval from    (             select  id             from    tablea             union             select  id             from    tableb             union             select  id             from    tablec         ) ids left join         tablea on ids.id = tablea.id left join         tableb on ids.id = tableb.id left join         tablec on ids.id = tablec.id 	0
1968993	13577	need mysql query ( thread changed)	select jobtitle, count(*) as total from table1 join table2 on ( table1.userid = table2.userid ) where articleid = <your articleid> group by table2.jobtitle 	0.431718247297884
1969108	16583	mysql query taking user's participation place with quantity of all other participants	select p.place_id, p.place_name, c.city, placecount.cnt from places p inner join user_place up on p.place_id = up.place_id inner join fa_user u on up.user_id = u.id inner join city c on p.city_id = c.id left join ( select place_id, count( distinct user_id ) cnt from user_place where user_id <>53 group by place_id )placecount on p.place_id = placecount.place_id where up.user_id =53 limit 0 , 30 	0.000691621640624659
1970376	18189	is there a way to change permissions for all the tables in sql-server database at once?	select     'grant select on ' + object_name(o.object_id) + ' to myrole' from     sys.objects o where     objectproperty(o.object_id, 'ismsshipped') = 0     and     objectproperty(o.object_id, 'istable') = 1 order by     object_name(o.object_id) 	0.000126180689606285
1970602	22870	how to select from joined mysql tables?	select a.id, a.name, a.info, group_concat(b.item separator ' ') as items    from a    left outer join b on (a.id=b.id)    group by 1,2,3    having items regexp '[[:<:]]o'; 	0.00203005604924217
1971669	10471	sql query to return specified test numbers and date	select *  from testtable  where testnumber in ('1', '2')      and testdate between #01/01/2008# and #01/01/2009# 	0.0114334095564706
1971826	24719	how can i have a primary key in a view (a key that doesn't depend on source tables)	select @rownum:=@rownum+1 as id, mytable.* from (select @rownum:=0) r, mytable; 	0.000299801696000778
1974357	14154	sql select aggregate values in column	select  name,         coalesce(sum(case when availability = 'available' then 1 else 0 end), 0) as available,         coalesce(sum(case when availability = 'available' then 0 else 1 end), 0) as not_available from    mytable group by         name 	0.0622782382505036
1976750	34070	query table names based on the column information	select table_schema, table_name from   information_schema.columns where  column_name = 'id'        and data_type = 'uniqueidentifier' or     column_name = 'message'   and data_type = 'nvarchar' or     column_name = 'enteredon' and data_type = 'datetime' group by table_schema, table_name having count(column_name) = 3 	0
1976917	11824	how to reverse mysql table	select * from table order by column asc; 	0.0775728661380498
1977400	27586	percentage of results that have a column in sql	select reason,         count(reason) as number,         cast(count(reason) as float) / cast(t.total as float) as percentage from deletedclients,      (select count(*) as total from deletedclients) t group by reason, total 	0.000681539249467638
1978586	11962	how to specify psycopg2 parameter for an array for timestamps (datetimes)	select somestuff from mytable where thetimestamp = any (%(times)s::timestamp[]) 	0.00882419821217757
1981480	14580	mysql query to return most recent entry regardless of date entered	select  i.* from    (             select  store,                     product,                     max(date) maxdate             from    inventory             group by    store,                         product         ) maxdates inner join         inventory i on maxdates.store = i.store                         and maxdates.product = i.store                         and maxdates.maxdate = i.date 	0
1982854	34811	sql to identify missing week	select t1.* from table1 t1 left join table1 t2 on t2.week_end = dateadd(week, 1, t1.week_end) where t2.week_end is null and t1.week_end <> (select max(week_end) from table1) 	0.0106809927398429
1982892	37342	join two tables where all child records of first table match all child records of second table	select   matches.name,   matches.limit from (     select       c.name,       c.customerid,       l.limit,       l.limitid,       count(*) over(partition by cc.customerid, lc.limitid) as matchcount     from tblcustomer c     join tblcustomercategory cc on c.customerid = cc.customerid     join tbllimitcategory lc on cc.categoryid = lc.categoryid     join tbllimit l on lc.limitid = l.limitid ) as matches join (     select        cc.customerid,        count(*) as categorycount      from tblcustomercategory cc      group by cc.customerid ) as customercategories on matches.customerid = customercategories.customerid join (     select       lc.limitid,       count(*) as categorycount     from tbllimitcategory lc     group by lc.limitid ) as limitcategories on matches.limitid = limitcategories.limitid where matches.matchcount = customercategories.categorycount and matches.matchcount = limitcategories.categorycount 	0
1985390	28914	interval of one month back not working on the 31st?	select add_months(sysdate,-1) from dual 	0.00285729768442704
1987552	29858	return all results from a mysql row seperated by commas matching a value	select id from news_data where cat_id regexp '(^|[^0-9])2([^0-9]|$)'; 	0
1988189	28506	sql count(*) on multiple tables	select `horse number`, count(*) as `total winners` from (   select * from `races`.`2009`   union all   select * from `races`.`2010` ) all_races where `win $`>0  group by `horse number` order by count(*) desc; 	0.0373975552991694
1990353	20763	i used "from" and "to" as column titles in my database table, how do i select them?	select `from` from mytable; 	0.00111669032980869
1990371	26836	how to write mysql regexp?	select 'hello world!' regexp 'h[[:alnum:]]+rld!' 0 select 'hello world!' regexp 'w[[:alnum:]]+rld!' 1 	0.659292866846155
1991103	22427	mysql daily count grouped by one column	select  dayname(sip_date) as day,         count(distinct sip_callid) from    request_line where dayname(sip_date) = 'saturday'  group by dayname(sip_date) 	0.000137244004745045
1995143	14717	sql server 2005 import a csv file , rows in correct order	select * from mytable order by somecolumn 	0.107019876088236
1995289	17149	get last record of a table	select max(id)+1 from table 	0
1995983	30341	random results. which way is faster sql-query or a flat file?	select * from table where id = $r 	0.797598645654367
1997307	2334	retrieving records fulfilling a condition using group by 	select count( * ) as `number` , gi . * from `generalinformation` as gi group by `firstname` , `surname`  having count(*)>1 	0.026369457129523
1999211	41017	query on sql joins	select     l.linkname, g.groupname,      isnull(sg.subgroupname, 'notexist') as subgroupname from     link l .... 	0.778037672723014
2000105	3260	how to analayze/display a raw web analytics data?	select count(requestid) as numberofhits,    year(loggeddate) as eventyear,    month(loggeddate) as eventmonth,    day(loggeddate) as eventday from mytable group by year(loggeddate), month(loggeddate), day(loggeddate) order by year(loggeddate), month(loggeddate), day(loggeddate) 	0.776192751844469
2000744	6566	mysql limit results per category	select x.*   from (select cm.id,                cm.title as cmtitle,                cm.sectionid,                cm.type as cmtype,                cd.id as cd_id,                cd.time,                cd.link,                cd.title,                cd.description,                cd.sectionid as cd_sectionid,                case                  when @sectionid != cm.sectionid then @rownum := 1                   else @rownum := @rownum + 1                end as rank,                @sectionid := cm.sectionid           from c_main cm,                c_data cd,                (select @rownum := 0, @sectionid := null) r          where cm.sectionid = cd.sectionid       order by cm.sectionid) x  where x.rank <= 20 order by id 	0.00257732209321071
2001238	18169	postgresql - combining two tables	select u.id, u.firstname || ' ' || u.lastname || ' ' || u.email, u.registrationdate as dateval from user u union all select g.id, g.name || ' ' || g.desc, g.createdate from group g order by 3 	0.0220688998733108
2002988	21747	how to make a drop down list (list box)in an ms acess query with values from two different tables	select tblclasssession.sessionid, tblclasssession.date, tblsessiontype.classtypedesc   from tblclasssession inner join tblsessiontype      on tblclasssession.sessiontypeid = tblsessiontype.sessiontypeid; 	0
2003032	26154	select id_field where max(date_field) < 'some date'	select id_field    from tbl   group by id_field  having max(date_field) < 'some date' 	0.197182042817556
2007655	36085	maximum issued book in a one day	select bookname from book  where bookid = (select bookid from issue where issuedate = @yourdate  and qty = (select max(qty) from  issue)) 	0
2016480	38159	queries within queries counting rows to make a score based on categories chosen	select    master.id ,         sum(if(s.category='1',1,0))   cat1 ,         sum(if(s.category='2',1,0))   cat2 ,         sum(1)                        total from      master m left join scores s on        m.id = s.id group by  master.id 	0
2016801	9333	how do i efficiently group data in a hierarchical format in t-sql?	select     main_task,     sum(hours) from     (     select               task,         case              when                  len(task) + 1 - charindex('.', reverse(task)) = charindex ('.', task) then task                 else left(task, len(task) + 1 - charindex('.', reverse(task)) - 1)             end main_task,         hours     from          #temp     ) sub group by        main_task 	0.204546496997807
2018354	25803	mysql: is it possible to "insert if number of rows with a specific value is less than x"?	select top 1 id from gifts where (select count(*) from gifts where gift_giver_id = senderidvalue order by gift_date asc) > 9; {if result.row_count then} insert into gifts (gift_giver_id, gift_receiver_id,gift_date) values val1,val2,val3 {else} update gifts set gift_giver_id = 'val1', gift_receiver_id = 'val2',gift_date = 'val3' where {id = result.first_row.id} 	0
2020667	12907	given a column name how can i find which tables in database contain that column?	select * from information_schema.columns where column_name = 'mycolumn' 	0
2021944	25440	get list of products in stock at any given date	select productfk, sum(if(m.direction='in'))-sum(if(m.direction='out')) as stock from move m where m.date < '20090101' and stock > 0 	0
2022821	3433	[mysql]: select unique w/ join	select sum(tt.transaction_amount) from itemtracker_dbo.transaction_type tt where tt.transaction_id in  (select t.transaction_id from         itemtracker_dbo.transaction t     join         itemtracker_dbo.purchase p        on         p.transaction_id = t.transaction_id     join         itemtracker_dbo.item i        on         i.item_id = p.item_id     where         t.timestamp >= $start and t.timestamp <= $end        and         tt.transaction_format in ('cash', 'credit')        and         i.client_id = $client_id) 	0.271921843906098
2023467	11183	sql query solution - day by day balance	select   a.traid,   b.catname,   c.grouptype,   a.tradate,   a.traamt,   sum(d.traamt) as balance from transactiontbl a inner join transactioncategory b     on a.categoryid=b.categoryid inner join categorygroup c     on b.catgroupid=c.catgroupid inner join (         select           a.tradate,           case when c.grouptype = 'income' then a.traamt else -a.traamt end as traamt         from transactiontbl a         inner join transactioncategory b             on a.categoryid=b.categoryid         inner join categorygroup c             on b.catgroupid=c.catgroupid) d     on a.tradate >= d.tradate group by   a.traid,   b.catname,   c.grouptype,   a.tradate,   a.traamt order by   a.tradate,   a.traid; 	0.00973705492149893
2024007	34717	query the highest latest userid	select name, max(userid) as max_userid from users group by name order by max(userid) asc 	0.000213132725177947
2029152	12989	count unique records in 2 tables	select count(ts) from (  select _timestamp as ts  from table1  where temperature is not null  union    select _timestamp   from table2  where temperature is not null )innersql 	0.000185311032405158
2029355	29279	query tfs database to fetch last 10 check-in details	select top 10 c.changesetid,  v.fullpath,  v.parentpath,  replace(v.childitem,'\','') as [filename],  c.creationdate,  i.displayname, c.comment from tbl_version(nolock) v inner join tbl_file (nolock) f on v.itemid = f.itemid inner join tbl_changeset (nolock) c on v.versionto = c.changesetid inner join tbl_identity (nolock) i on c.committerid = i.identityid where v.parentpath like '$\' + (select name from [tfsworkitemtracking].[dbo].[treenodes] where parentid=0 and fdeleted=0 and id=524) + '\%' order by c.creationdate desc 	7.50213539494703e-05
2032082	21781	sql selection over two rows	select a.object  from mytable a, mytable b  where a.object = b.object    and a.key = 'a' and a.value = 'a'   and b.key = 'b' and b.value = 'b' 	0.016390185663482
2033535	38088	creating view from complicated select	select s.obraz, s.noisetype, s.avg as c3, fs.bayes, fs.sure, fs.visu, fs.fstd from  ( select  obraz, noisetype, avg(q.c3), count(q.c3), q.std from    (         select  obraz, noisetype, std, c3, row_number() over (partition by obraz, noisetype, std order by id) as rn         from    ssims         where   data>'2009-12-23' and maska = 9         ) q where   rn <= 15 group by         obraz, noisetype, std         ) s ,( select  obraz, noisetype, avg(f.bayes) as bayes, avg(f.sure) as sure, avg(f.visu) as visu, count(f.bayes) as fcount, f.std as fstd from    (         select  obraz, noisetype, std, bayes, sure, visu, row_number() over (partition by obraz, noisetype, std order by id) as rn         from    falki_ssim         ) f where   rn <= 15 group by         obraz, noisetype, std         ) fs where s.std = fs.fstd and s.obraz = fs.obraz and s.noisetype = fs.noisetype 	0.672007578634361
2033725	22819	delete all procedures except those which contain a string in their name	select 'drop procedure ' + name from    sysobjects where xtype = 'u' and         name like 'usp_%'    	0
2036435	5395	looping through data from multiple tables php/mysql	select w.* from (     (select          'w' as type,          wall_id as id,         wall_owner_id as owner_id,         wall_user_id as user_id,         wall_post_date as post_date,         null as title,         wall_post_content as content      from wall      where wall_owner_id = x # user id of owner     )     union     (select          'a' as type,          action_id as id,          action_user_id as owner_id,          null as user_id,          action_post_date as post_date,          action_title as title,          action_body as content       from actions       where action_user_id = x # user id of owner      ) ) w  order by w.post_date desc 	0.00266770558157013
2037598	7563	sql multiply discrepancy	select @a*@b    	0.397296425876832
2038109	35309	how to find the usage of constant in sql server database	select * from sys.objects where object_definition(object_id) like '%115%' 	0.0089316800034527
2038301	16790	sql server 2005 - how to know if a field is a primary key?	select       t.table_name from       information_schema.table_constraints t      inner join          information_schema.key_column_usage k          on t.constraint_name = k.constraint_name   where      t.constraint_type = 'primary key'       and k.column_name = @column_name 	0.02104337462419
2040556	9256	how to select data depending on multple row's field	select distinct t1.name from tab t1, tab t2  where t1.name = t2.name and  t1.value='a' and t2.value='b'; 	5.72472196403383e-05
2042372	4917	mysql joining multiple queries based on condition	select  x.* from    x left join         y on      y.userid = x.userid group by         x.id having  coalesce(max(y.enddate), x.enddate) between curdate() and curdate() + interval 7 day 	0.00548641922304366
2042414	26018	how to add together the results of several subqueries?	select  *,         bookreviews + recipereviews as totalreviews from    (         select  users.*,                 (select count(*) from bookshelf where bookshelf.user_id = users.id) as titles,                 (select count(*) from book_reviews where book_reviews.user_id = users.id) as bookreviews,                 (select count(*) from recipe_reviews where recipe_reviews.user_id = users.id) as recipereviews         from    users            ) q 	0.0127459036983686
2043098	1822	view in oracle to display rows from last weekday	select  * from    table_1 where   mydate >= sysdate - case when to_char(sysdate, 'd') > 6 then 3 else 1 end         and mydate < sysdate - case when to_char(sysdate, 'd') > 6 then 3 else 1 end + 1 	0
2044073	35399	sql query - join that return only last row	select  nom,prenom,oedp.num_emp,n_a_s,sit_statut,permis,date_embauche,adresse1,ville1,province1,code_postal1,tel_residence from    ods_employe_dossier_personnel as oedp cross apply          (         select  top 1 *         from    ods_situation_poste as osp         where   oedp.num_emp = osp.num_emp         order by                 sit_date_chg desc         ) osp order by         oedp.num_emp 	7.75075830533961e-05
2044752	5885	sql mapping between multiple tables	select a.name from a where a.id in     (select ab.a_id from atob ab where b_id =        (select b.id from b where b.name = 'zoo name')) union select i.name from imaginary_creatures i i.id in     (select ic.imaginary_creatures_id from imaginary_creatures_to_c ic      where ic.b_id = (select b.id from b where b.name = 'zoo name')) 	0.0692265921691996
2045463	33724	sql query to conditionally sum based on moving date window	select  count(created_at) as registered,         sum(case when verified_at <= created_at + '60 day'::interval then 1 else 0 end) as verified from    generate_series(1, 20) s left join         users on      created_at >= '2009-01-01'::datetime + (s || ' month')::interval         and created_at < '2009-01-01'::datetime + (s + 1 || ' month')::interval group by         s 	0.00342059426640658
2046037	22141	sql server: can i comma delimit multiple rows into one column?	select t.ticketid,        stuff(isnull((select ', ' + x.person                 from @tickets x                where x.ticketid = t.ticketid             group by x.person              for xml path (''), type).value('.','varchar(max)'), ''), 1, 2, '') [no preceeding comma],        isnull((select ', ' + x.person                 from @tickets x                where x.ticketid = t.ticketid             group by x.person              for xml path (''), type).value('.','varchar(max)'), '') [preceeding comma if not empty]   from @tickets t group by t.ticketid 	0.000192803619046152
2046194	26286	mysql: last 10 entries per user?	select x.user_id,          avg(x.score)     from (select t.user_id,                  t.score             from transactions t            where t.user_id = ?         order by t.date            limit 10) x group by x.user_id 	0
2046784	2304	sort search results from mysql by the position of the search query in the string using php	select  title,locate('banana',title)  from mytable     where  locate('banana',title) > 0  order by locate('banana',title) 	0.000515993648305554
2049622	36556	sql subqueries to try to get maximum difference of the same column in two tables	select id, `date`, sums from (   select id, `date`, sums,   case     when @d != `date` then @rownum := 1      else @rownum := @rownum + 1   end as rank,   @d := `date` from (   select t1.`date`, t1.id, t1.sums t1_sums, t2.sums t2_sums, (t1.sums - t2.sums) sums   from     (select `date`, id, sum(val) sums      from foo      group by `date`, id) as t1,     (select `date`, id, sum(val) sums      from bar      group by `date`, id) as t2,      (select @rownum := 0, @d := null) r   where t1.`date` = t2.`date` and t1.id = t2.id   group by t1.`date`, t1.id, t2.`date`, t2.id   order by t1.`date`, (t1.sums - t2.sums) desc, t1.id   ) x ) y where rank = 1 	0
2050065	32325	help in forming mysql query to find free(available) venues/resources for a give date range	select  * from    venue v where   not exists         (         select  null         from    event_dates ed         where   ed.venue_id = v.id                 and '2009-12-06 00:00:00' between ed.event_from_datetime and ed.event_to_datetime         ) 	0.201584361041655
2050922	40530	return all xml nodes import into sql server	select tab.col.value('./hotel_ref[1]','varchar(100)') as 'hotel_ref',  fac.value('(.)[1]','varchar(100)') as 'hotelfacilityid',  rowid=identity(int,1,1)  into #facilitiesid  from @details.nodes('/hotels/hotel') as tab(col)  cross apply col.nodes('. select tab.col.value('../hotel_ref[1]','varchar(100)') as 'hotel_ref',  fac.value('(.)[1]','varchar(100)') as 'hotelfacilityname',  rowid=identity(int,1,1)  into #facilitiesnames  from @details.nodes(' cross apply col.nodes('. select i.hotel_ref, hotelfacilityid, hotelfacilityname  from #facilitiesid i  inner join #facilitiesnames n      on i.rowid = n.rowid 	0.00160131270205891
2051023	32620	hashbytes comparison in stored proceduring not matching record	select hashbytes('md5','lorem ipsum'), hashbytes('md5',n'lorem ipsum') 	0.152188721560932
2052158	6694	ordered sql select columnwise distinct but return of all columns	select categoryid, downloadid, createdate, url from (   select     categoryid, downloadid, createdate, url,     row_number() over(partition by categoryid order by createdate desc) rownum   from download ) d where d.rownum <= 5 	0
2052216	4324	mysql orderby a number, empty strings (or 0's) last	select *  from tablename  where visible=1  order by      case when position in('', '0') then 1 else 0 end,     position asc,      id desc 	0.00187056888234234
2052333	5276	single sql query on many to many relationship	select p.*, group_concat(distinct c.title order by c.title desc separator ', ') from posts p inner join postcategories pc on p.id = pc.id_post inner join categories c on pc.id_category = c.id group by p.id, p.title, p.content 	0.0366406119126228
2053569	10036	is it possible for sql to find records with duplicates?	select name from people group by name having count(*)>1; 	0.0274920071809159
2054334	13178	getting the latest entries for grouped by the foreign key in mysql	select ... group by ... having max(modified) 	0
2054482	25715	oracle substr date duration	select extract (day from (time_b-time_a)),         extract (hour from (time_b-time_a)),         extract (minute from (time_b-time_a)),         extract (second from (time_b-time_a))  from ....; 	0.400408890870412
2054511	40944	including initial value in a select statement	select      0,     'select' union all <your query> 	0.0156532260163367
2054869	3281	how to check the range and number of records in that range without using cursor?	select lowrange, highrange, count(*), sum(amount) from ranges r left join infodetails d on d.range between r.lowrange and r.highrange group by lowrange, highrange; 	0
2055556	19632	how to improve time performance for retrieving huge data from the database?	select * from stuff limit 1000 offset 2000 	0.136973460982932
2058583	37963	mysql - selecting "everyone who booked last january, but hasn't booked this january"	select c.title,             c.initial,             c.surname,             c.labelno,            c.email     from         client c     where exists (select * from booking_record where labelno=c.labelno         and bookingdate between @start1 and @end1)     and not exists (select * from booking_record where labelno=c.labelno         and bookingdate between @start2 and @end2) 	0.000333166951550225
2058901	34126	how to nest select statements in sql?	select distinct u1.userid  from   userclicks u1 inner join (    select        userid     from       userclicks     where       (date > :monthbeforestartdate and date < :startdate) ) u2 on u1.userid = u2.userid where   (u1.date > :startdate and u1.date < :enddate) 	0.680390727230426
2059327	2842	sql example: retrieve musicianid with no gigs played?	select musicianid from musicians m left join gigs g on g.musicianid = m.musicianid where g.musicianid is null 	0.49047660964702
2059499	30796	sqlerror.number descriptions	select description from master..sysmessages 	0.790445279032414
2059666	36691	cursor to return multiple rows	select  trunc(v.date, 'month'), sum(field1) from    view1 v where   v.date between begindate and enddate group by         trunc(v.date, 'month') 	0.0203013808465979
2060718	8174	how do i efficiently do the intersection of joins in sql?	select books.id, books.title, books.author from books inner join taggings on ( taggings.book_id = books.book_id ) inner join tags on ( tags.tag_id = taggings.tag_id ) where tags.name in ( @tag1, @tag2, @tag3 ) group by books.id, books.title, books.author having count(*) = @number_of_tags 	0.184404014594245
2061225	5814	sql server: how to select second-highest parentid?	select l2.* from table t join table l1 on t.parent_id = l1.pageid join table l2 on l1.parent_id = l2.pageid where t.pageid = 6; 	0.244117192043091
2063771	32332	sql query to get rows where values in a column do not exist in another table	select  m.* from    mytable m left join         categories c on      find_in_set(c.id, replace(m.categories, ' ', ',')) where   c.id is null 	0
2063901	111	include admin role in users table from roles table	select u.id, u.username, if (id_role is null,  'n', 'y') as is_admin   from users u   left outer join user_roles r     on u.id = r.id_user and r.id_role = 1 	0.000318951024814596
2064037	11528	getting data from different tables and databinding same repeater	select es.recid,es.othercolumn, es.estatetype, es.othercolumn from estatetypes es,record rec where es.id = rec.estatypeid 	0
2067433	28204	convert mysql timestamp to time_t	select unix_timestamp(date_entered) from foo; 	0.0453735554724802
2069657	32704	check if user got new message in the background?	select * from messages where date > $last_message_date 	0.0446879409042451
2069963	38577	how to search between columns in mysql	select * from mytable where 25 between col1 and col2; 	0.010125951151931
2072587	28233	can an sql stored procedure simply return its inputs, concatenated?	select @param1 + ',' + @param2 + ',' + @param3 	0.13565094486476
2072679	3075	how do i use "group by" with three columns of data?	select s.x, s.mz, stuff.y  from (select x, max(z) as mz from stuff group by x) s    left join stuff on stuff.x = s.x and stuff.z = s.mz; 	0.0132575657954101
2072776	791	remove array values in pgsql	select array (  select unnest(yourarray) limit (   select array_upper(yourarray, 1) - 1  ) ) 	0.0564349055397803
2073830	38237	get roles which are still not assigned to member query	select * from roles r where not exists (    select 1    from user_roles ur    where ur.role_id = r.id    and ur.user_id = 1 ) 	0.00122185673714023
2076422	1154	access get all tables	select msysobjects.*, msysobjects.type from msysobjects where (((msysobjects.type)=1)) or (((msysobjects.type)=6)); 	0.00413096821076457
2077219	1828	optimizing mysql query for fetching data using time range	select sum(op.qty) as qty, date_format(o.created, '%y-%m-%d') as day from ... where ... o.created >= subdate(now(), interval 1 year) and o.created <= now() group by day order by day 	0.0816437232354234
2077355	32127	mysql & php - not unique table/alias	select count(*)  from grades  join grades on grades.id = articles_grades.grade_id where articles_grades.users_articles_id = '$page'" 	0.253390587527796
2078942	16018	should i quote numbers in sql?	select 10 as x 	0.517902379825511
2079260	29699	most common value for multiple fields	select language from mytable where series_id = 18 group by language order by count(*) desc limit 1 select quality from mytable where series_id = 18 group by quality order by count(*) desc limit 1 select type from mytable where series_id = 18 group by type order by count(*) desc limit 1 	0.000103119679648083
2081075	39957	mysql group by and unique values	select * from `test` where (did,dateof) in (     select did,max(dateof) from `test` group by did ) group by did order by dateof  desc 	0.00969275331764423
2081522	3487	mysql scenario - get all tasks even if there is no entry?	select final.taskid,         final.taskname,         tmp.hoursspent as totalhours,         tmp.workeddate     from (         select a.taskid, b.taskname, a.empnum         from taskallocations a                  inner join                   tasks b              on ( a.taskid = b.taskid )          where a.empnum = "333"         )final     left outer join (             select new.taskid, new.empnum, new.workeddate, new.hoursspent         from taskentries new         where new.workeddate         in                ('2010-01-17','2010-01-18','2010-01-19',               '2010-01-20','2010-01-21','2010-01-22','2010-01-23' )         or new.workeddate is null          and new.empnum = "333"         )tmp      on tmp.taskid = final.taskid and tmp.empnum = final.empnum     order by final.taskid, tmp.workeddate asc ; 	0.000786250509389743
2082507	10532	normalizing data on a table	select frequency_1 +        (frequency_2 * 2) +        (frequency_3 * 3) +        (frequency_4 * 4) as frequency 	0.0530501441560464
2084893	18895	sql query with limit on rows from one table, not the result set	select t3.a, t2.b from (select * from t1 limit 5) t3 left join t2 on ... 	0.000284828940515073
2086169	29659	joining tables in mysql question (php)	select similar.name, count(*) as commontags from artists current,    artisttags curtags,   artisttags simtags,   artists similar where current.id=curtags.artist_id   and curtags.tag_id=simtags.tag_id   and simtags.artist_id=similar.id order by count(*) desc; 	0.506302157914199
2086577	14221	want the data of upline and downline for particular id	select top 3 id, name from table where id =< @id  order by id desc union  select top 2 id, name from table where id > @id  order by id acs 	0.00044423191438851
2087825	25224	selecting latest rows per disctinct foreign key value	select u.text, u.typeid, u.created, t.name from  (     select typeid, max(created) as maxcreated     from updates     group by typeid ) mu inner join updates u on mu.typeid = u.typeid and mu.maxcreated = u.created left outer join type t on u.typeid = t.typeid 	0
2089546	30032	selecting count(*) sometimes returns 0, and sometimes returns nothing	select count(case when approved = '0' then 1 end) as cnt,       first_name , last_name , email from images group by first_name , last_name , email; 	0.172904244475803
2090221	4489	mysql: query to get all rows from previous month	select * from table where year(date_created) = year(current_date - interval 1 month) and month(date_created) = month(current_date - interval 1 month) 	0
2093949	16213	how to find out if select grant is obtained directly or through a role	select grantee from all_tab_privs  where table_schema = 'scott' and table_name='emp' and privilege = 'select'; 	0.333146431850826
2094307	20715	sql value which isn't for the needed date but first available	select top 1 kurs_sredni from yourtable where (your comparison here) order by date 	0.000379182492673288
2094843	12813	possible to link to another database link?	select * from myview@db1 	0.00655571245829722
2095496	27016	how to approach this specific query	select  *,         case              when td.t_id is null                 then it.price             when td.t_id is not null and d.type = 'p'                 then id.price - (id.price * d.value)             else id.price - d.value         end pricediscounted from    transaction t left join         purchase p on t.t_id = p.t_id left join         item it on p.item_id = it.item_id left join         transaction_discount td on t.t_id = td.t_id left join         discount d on td.d_id = d.d_id left join         item id on d.item_id = id.item_id 	0.543036472933244
2096695	27198	tsql - use a derived select column in the where clause	select a,b,c from( select a,b,c, case    when a=1 then 5   when a=2 then 6 end as d from some_table ) as t where d=6 	0.614720454210228
2099198	33103	sql transpose rows as columns	select r.user_id,          max(case when r.question_id = 1 then r.body else null end) as "do you like apples?",          max(case when r.question_id = 2 then r.body else null end) as "do you like oranges?",          max(case when r.question_id = 3 then r.body else null end) as "do you like carrots?"     from responses r     join questions q on q.id = r.question_id group by r.user_id 	0.00371627436004287
2099388	2682	comment trees in sql and html	select row_number() over(order by lineage) as rownum 	0.68510868281618
2099826	34294	check field1 and field2 from single table	select case when (field1 = 1 and date_sub(curdate(),interval 7 day) <= field2)                  then   count(*)             else 0         end   from sometable 	0.0167817074219368
2099923	23838	how do i order by multiple columns in a select query?	select * from your_table order by int_category_id, int_order 	0.0213123761771569
2100074	18866	finding one record from table having unique pk and duplicate fk	select fk, count(*)  from table1 group by fk having count(*) > 1 	0
2100219	1915	join three tables in sql server 2005	select o.orderid,o.custid,o.ordertotal,c.name, oc.orderamount from orders as o  inner join customers as c    on o.custid=c.custid  inner join orderitems as oc   on o.orderid=oc.orderid 	0.563094776005906
2101970	20431	create two separate tables for entities separated by one attribute?	select blah from mytable where type="orange" 	0
2102373	27247	referring to dynamic columns in a postgres query?	select t.*  from (     select sum(points) as total_points     from sometable     group by username ) t where total_points > 25 	0.158344532723674
2104175	10496	run two queries on two tables to get one list of results with mysql/php	select widgetid from table1 where find_in_set('$serial', items) union select widgetid from table2 where find_in_set('$serial', items) 	0
2104527	41207	ssis: oracle multiple rows to one column output without stragg	select x.id,        ltrim(max(sys_connect_by_path(x.language,','))        keep (dense_rank last order by curr),',') as employees   from (select a.id,                b.language,                row_number() over (partition by a.id order by b.language) as curr,                row_number() over (partition by a.id order by b.language) -1 as prev           from table_1 a           join table_2 b on b.id = a.langid) x group by x.id connect by prev = prior curr and x.id = prior x.id start with curr = 1; 	0.0109988319295839
2104872	20296	write a query to see the "date" in table is still to come or has passed by?	select summary, startdate   from c7_events and startdate > now() where users_id = $users_id; 	0.00997147239548543
2105079	24132	sql - join up two separate sql queries	select 1.page_name, count(*) as exitpagecount from weblog l inner join (     select http_session_id, max(page_hit_timestamp)     from weblog     group by session ) lm on l.http_session_id = lm.http_session_id and l.page_hit_timestamp = lm.page_hit_timestamp group by 1.page_name 	0.136906857286039
2109775	19563	t sql convert a row to a string	select  cast(id as varchar(10)) + ' ' + [first name] + ' ' + [last name] + ' ' + color  from    mytable 	0.00890350831649758
2110216	40307	local time zone offset in postgresql	select  current_setting('timezone') 	0.236995754813753
2111523	40975	how would i perform math within a sql query to calculate percent difference?	select choice,        (count(*) / (select count(*)                     from answers                     where answers.question_id = qid)) * 100 as percentage from choices      inner join answers        on choices.choice_id = answers.choice_id        and choices.question_id and choices.question_id where choices.question_id = qid group by choice_id; 	0.104111279914618
2112093	6332	join tables sql server	select lt.value from lefttable lt left outer join righttable rt on lt.leftid = rt.leftid where rt.leftid is null 	0.507740402843832
2112611	36570	sqlite3 2 level join with aggreation on middle level	select grandfathers.*, group_concat(sons.name)  from grandfathers left join fathers on grandfathers.id = fathers.grandfather_id  left join sons on fathers.id = sons.father_id group by grandfathers.id; 	0.793889226467382
2112618	36615	finding duplicate rows in sql server	select o.orgname, oc.dupecount, o.id from organizations o inner join (     select orgname, count(*) as dupecount     from organizations     group by orgname     having count(*) > 1 ) oc on o.orgname = oc.orgname 	0.0026498960811696
2114194	15850	sql query disregarding all rows that have all null columns	select count(id) from [some data] where not (column1 is null and column2 is null and column3 is null ...) 	0
2115367	39596	calculate sum based on column name	select st, sum(amt) from ( (  select s.state_cd_1 as st, a.state_amt_1 as amt  from states as s join amount as a on s.state_id = a.amt_id  where s.state_cd_1 is not null and a.state_amt_1 is not null ) union all (  select s.state_cd_2 as st, a.state_amt_2 as amt  from states as s join amount as a on s.state_id = a.amt_id  where s.state_cd_2 is not null and a.state_amt_2 is not null ) union all (  select s.state_cd_3 as st, a.state_amt_3 as amt  from states as s join amount as a on s.state_id = a.amt_id  where s.state_cd_3 is not null and a.state_amt_3 is not null ) union all (  select s.state_cd_4 as st, a.state_amt_4 as amt  from states as s join amount as a on s.state_id = a.amt_id   where s.state_cd_4 is not null and a.state_amt_4 is not null ) union all (  select s.state_cd_5 as st, a.state_amt_5 as amt   from states as s join amount as a on s.state_id = a.amt_id   where s.state_cd_5 is not null and a.state_amt_5 is not null )) as joined group by st; 	5.65650524581626e-05
2118511	14133	mysql "rank in highscore"-query	select count(*) + 1 from  (     select sum( p.points ) as sum_points     from user u     left join points p on p.user_id = u.id     group by u.id         ) x where sum_points > (select sum(points) from points where user_id = @this_user) 	0.527662332215913
2121740	39462	how to return sql server 2005/2008 columns as identical child nodes using for xml query?	select 'person.contact' as "@name", (select      (select * from (select 'firstname' as [@name], [firstname] as [*]     union all     select 'lastname' as [@name], [lastname] as [*]) y     for xml path('field'), type) from person.contact for xml path, type) for xml path('entity'), root('querydata') 	0.00152665956045573
2122138	23836	selecting the items associated with a tag along with the tags associated with these items	select i.*,         t.tag_id   from items i   join tags t on t.item_id = i.item_id  where i.item_id in (select x.item_id                        from tags x                        where x.tag_id = ?) 	0
2122340	13917	pqgetisnull : not not return true even value is empty in db	select coalesce(<field_name>,'null'), count(*) from <table_name> where <field_name> = ''    or <field_name> is null group by 1 	0.148324292041165
2126864	1178	is there any difference between these two select statements?	select table1.col1 from table1 inner join table2 on (table1.id = table2.ref_id); 	0.0259654068426244
2127062	26096	returning rows that has matching record in another table	select * from students s where exists  (select *                      from events e                     where e.studentid = s.studentid) 	0
2127533	18492	mysql ordering results by the order of where clause matched	select ..., match(col_name) against ('my pharse') as score from tbl_name where match(col_name) against('my pharse') order by score desc; 	0.180524613699457
2131168	40111	the fastest way to check if some records in a database table?	select 'y' from dual where exists (select 1 from mytable where parent_id = :id) 	0.000187991892525449
2132654	39127	querying multiple databases at once	select option_value  from `database1`.`wp_options`   where option_name="active_plugins" union select option_value  from `database2`.`wp_options`   where option_name="active_plugins" 	0.00352225315570794
2132673	2709	select row which has all five under it in the "tree"	select p.article_id from article a inner join structure s on s.article_above_id = article_id inner join article p on p.article_id = s.article_id where a.article_number in (3,7,45,186,203) group by p.article_id having count(*) = 5 	0
2132701	24997	t-sql : how to count empty tables in database?	select * from (  select    [tablename] = so.name,    [rowcount] = max(si.rows)   from    sysobjects so,    sysindexes si   where    so.xtype = 'u'    and    si.id = object_id(so.name)   group by    so.name  ) sub where sub.[rowcount] = 0 	0.0302051845216823
2134199	32251	performing string concatenation from rows of data in a tsql view (pivot?)	select  id,         (         select  text as [text()]         from    mytable mi         where   mi.id = md.id         order by                 mi.col         for xml path(''), type         ).value('/', 'nvarchar(max)') from    (         select  distinct id         from    mytable         ) md 	0.006049116907274
2136480	14892	returns zeros for dates that dont exist mysql group by	select avg(data) as data, vt.valdate from valtabledates vt left join  table t on t.datereg = vt.valdate where vt.valdate > [some start date] and vt < [some end date] group by year(datereg), month(datereg), day(datereg)  order by datereg 	0.00291244707005126
2136674	17036	get rows where timestamp column is 2 days old	select * from test where timestamp < date('now', '-2 days') 	0
2136734	23876	sql query source code	select   * from [xerex_test].[dbo].[xrxpat] inner join [xerex_test].[dbo].[xrxins]     on [xrxpat].[patid] = [xrxins].[patid] inner join [xerex_test].[dbo].[xrxpatins]     on [xrxins].[recno] = [xrxpatins].[insid]     and [xrxpatins].[instype] = 1 left join [xerex_test].[dbo].[xrxpatins] as ins2     on [xrxins].[recno] = ins2.[patid]     and ins2.[instype] = 2 left join [xerex_test].[dbo].[xrxpatins] as ins3     on [xrxins].[recno] = ins3.[patid]     and ins3.[instype] = 3; 	0.756733123449538
2137740	32049	in a select statement in sql server 2005	select intime.mat_id, intime.measurementid, measurment.measurementname from intime left join measurment on intime.measurementid = measurment.measurementid 	0.771201928021292
2137835	9707	concat two column in a select statement sql server 2005	select firstname + isnull(' ' + secondname, '') from table 	0.223736915449797
2137855	22375	how to join multiple tabels in the query scripts	select courseinfo.cname as coursename, mst.tname as mastername,          mst.tage as masterage,  mstloc.ldesc as masterlocation,          ass.tname as assistname, ass.tage as assistage,  assloc.ldesc as  assistlocation  from courseinfo      join teacherinfo mst on masterteacherid = mst.tid      join locationinfo mstloc on mst.tlocationid = mstloc.lid      join teacherinfo ass on assistteacherid = ass.tid      join locationinfo assloc on ass.tlocationid = assloc.lid 	0.526476199041291
2139809	30256	combining two resources php	select   * from     mytable1 where    ... union all select   * from     mytable2 where    ... 	0.0811858248815887
2141146	33136	display all the stored procedures in a database	select *  from information_schema.routines where routine_type = 'procedure' 	0.000824539742539352
2142005	20955	sql view. select count... where	select col1, col2,    sum(case when result=1 then 1 else 0 end) result1,    sum(case when result=2 then 1 else 0 end) result2    from yourtable   group by col1, col2 	0.368574095616279
2143116	32569	how to get number of specific rows from a different table in a subquery	select t1.*,           coalesce(x.num_rows, 0) as entries      from `table 1` t1 left join (select t3.v_id,                   count(*) 'num_rows'              from `table_3` t3          group by t3.v_id) x on x.v_id = t1.v_id 	0
2144687	6371	collapsing two columns in one in sql?	select '(' + convert(varchar, x1) + ',' + convert(varchar, y1) + ')' as "col" 	0.00133285620661479
2149272	39371	count number of entries in whole sql server database	select sum(rows) from sys.partitions; 	0.000122182465135778
2149892	23090	sum values by year with mysql/php	select a.year , sum( f.amountraised ) , a.target from annualtarget a inner join  fundraisingtotal f on (a.year = year( f.date )) group by a.year 	0.00668237293454989
2149922	30879	tsql to know database role members	select     user_name(memberuid), user_name(groupuid) from     sys.sysmembers where     user_name(groupuid) in ('db_owner', 'db_accessadmin') 	0.134002269073342
2149945	33388	sql query ; i want to get enquiry_no which has not been updated since last 7 days	select      <add columns here> from      tblenquiry where      not exists      (           select *           from tblhistory h           where h.enquiry_no = e.enquiry_no             and h.history_createdon between dateadd(dy, -7, getdate()) and getdate()      ) 	0
2150312	6288	pdo: check tags presence in db and then insert	select 1 as found from tags where tag_name = :tag_name limit 1 	0.00760348877657954
2153410	619	how to limit an sql result set to not too common items	select  personname,         address from    (             select  *,                     (select count(1) from addresses where address = a.address and personname < a.personname) countless             from    addresses a         ) sub where   sub.countless <= 2 	0.0268706954652895
2154677	15656	help with mysql query to select only records with specific value in column	select   * from table t left join (   select     min(stat) as stat,     id   from table   group by id ) minstat on t.id = minstat.id where minstat.stat = 1; 	0.00123552234492893
2156403	23065	cannot see table in object explorer, sql server 2005/2008	select type, type_desc from sys.objects where name = 'my_table_name' 	0.758693275120171
2156425	26556	mysql - search between dates where all dates appear	select id, sum(price) from (     select id, date, min(price) as price     from table1     group by id, date) as t1 where `date` between '2010-08-05' and '2010-08-07' group by id having count(*) = datediff('2010-08-07','2010-08-05') + 1 	0.000461936573048771
2156775	36635	oracle query to find priveleges on a stored procedure	select grantee, table_name, privilege      from dba_tab_privs      where        table_name = 'my_stored_proc'         and         owner = 'ownerofobject'        and        (grantee = 'usera'          or          grantee in           (select granted_role         from dba_role_privs         where grantee = 'usera'            )         ) 	0.411242476412171
2159698	13767	select to pick users who both viewed a page	select u1.user_id, u2.user_id, count(distinct u1.page_id) as numpages from logtable u1   join   logtable u2   on u1.page_id = u2.page_id   and u1.user_id < u2.user_id group by u1.user_id, u2.user_id; 	5.05220940447738e-05
2161153	292	complex combine sql	select userbase.username         , count(*) as total  from userbase      join extrauserinfofromhrms on userbase.username = extrauserinfofromhrms.useremail      right join logevent on userbase.username = logevent.useremail      join eachworkflow on logevent.workflowid= eachworkflow.workflowid  where logevent.actionname ='complete'   and logevent.useremail like 'email@test.com'  group by userbase.username  / 	0.66971648040903
2162789	21852	get the formatted output	select itemcode,  sum(case when pricinglevel = 'barons' then salesprice else 0 end) as barons, sum(case when pricinglevel = 'guild' then salesprice else 0 end) as guild from mytable group by itemcode 	0.00822024538217784
2163345	41098	how to find recursively self-joined records from a table	select * from jointablex a inner join jointablex b on a.recordaid = b.recordbid      and a.recordbid = b.recordaid 	5.00480817983224e-05
2163532	39490	select, where id = multiple from other select	select * from content where mi in (select id from menu where nr=10) 	0.000271288952101874
2164842	9	simpilify query for sql table with 12 columns for month	select sum(case when @month = 1 then jan         when @month = 2 then feb         when @month = 3 then mar         when @month = 4 then apr         when @month = 5 then may         when @month = 6 then jun         when @month = 7 then jul         when @month = 8 then aug         when @month = 9 then sep         when @month = 10 then oct         when @month = 11 then nov         when @month = 12 then [dec] end)          from mytable         where productid = @id and customer = @cust 	0.00158645537501276
2165571	7333	what's an efficient way to find rows where the timestamp and identity are not in sequence?	select   * from (         select           t1.*,           rank() over (order by trans_id) as trans_id_rank,           rank() over (order by crt_dttm, trans_id) as crt_dttm_rank         from v_trans t1) t where trans_id_rank <> crt_dttm_rank 	0.00206543795357227
2165962	27343	how to loop through array of database rows, and select the first with desired value?	select * from yourtable where criteria-for-property order by whatever-ordering-you-want limit 1 	0
2166008	28488	is it possible to compare a mysql timestamp to a millisecond?	select * from mytable where time_stamp_column > from_unixtime(1264665600000/1000); 	0.0273880286712878
2168068	3918	mysql return table name	select id, 'articles' as tablename where content like '%string to search for%' union select id, 'news' as tablename where news like '%string to search for%' 	0.0151899299568017
2172110	33321	computed column in sql view	select product1, product2, product1 + ' ' + product2 as [computed]   from my_table 	0.0604645411714414
2172267	13216	select from null?	select ... from blah as dummy on dummy.id = new.id 	0.0427625992425478
2173108	25646	php sql counting number of matches for query	select count(*) from (     select username, count(*) as c_comments     from users         join comments on username = comment_username     where referral = 'referral'     group by username ) t where t.c_comments > 10; 	0.00297027204185927
2173716	21313	what's the most efficient way to get the horizontal average in a mysql query?	select id, (ifnull(one,0) + ifnull(two,0) + ifnull(three,0))/   ((one is not null) + (two is not null) + (three is not null)) as average from table 	0.000183736125546606
2174203	36184	selecting from a mysql db based on parts of a timestamp	select * from table where year(timestamp) = '1999' 	0
2174566	19291	my sql isn't limiting my list to just the instance i want	select `teams`.*,      `markets`.`title` as `market`,      `markets`.`short_name`,      `market_countries`.*,      `countries`.`title` as `country`,      `languages`.`title` as `language`,      `languages`.`short_code`,      `status`.`title` as `status`,      `team_types`.`title` as `type`,      `market_languages`.*  from `teams`  inner join `markets` on teams.market_id = markets.id  left join `market_countries` on markets.id = market_countries.market_id  left join `countries` on countries.id = market_countries.country_id  left join `languages` on languages.id = teams.language_id  left join `status` on teams.status_id = status.id  inner join `team_types` on team_types.id = teams.type_id  inner join `market_languages` on ( teams.language_id = market_languages.language_id  and teams.market_id = market_languages.market_id)  where (market_languages.is_default = 1)  and (teams.status_id = 3)  group by `teams`.`id`  order by `teams`.`order_id` asc, `teams`.`status_id` asc 	0.409213685371639
2174905	22629	is there any tool available by which one can calculate (a)the size or a single row in sqlserver (b)the amount of traffic hitting the sqlserver	select sum(length) from syscolumns where id = object_id('mytable') 	0
2175922	33740	sql server conditional comparing	select     day     , name     , hoursworked     , hoursinday from (     select         p.day         , p.name         , count(*) hoursworked         , (select count(*) from #hours h2 where h2.day = p.day) hoursinday     from         #persons p inner join #hours h              on p.day = h.day and p.hour = h.hour     group by         p.day, p.name      ) data where     hoursworked + 2 >= hoursinday 	0.703238192796237
2176598	6489	how to search in 5 different fields with all possible choices in no particular order in mysql using like	select * from users where (firstname like "%persons%" or lastname like "%persons%" or address like "%persons%") and (firstname like "%name%" or lastname like "%name%" or address like "%name%") and (firstname like "%fake%" or lastname like "%fake%" or address like "%fake%") and (firstname like "%street%" or lastname like "%street%" or address like "%street%") 	0.00117842788125701
2179648	29852	add column while copying data in sql	select *, getdate() as currentdate from dbo.source 	0.0194686039532803
2181417	24070	sql server group by which counts occurrences of a score	select top 2 i.itemname  from items i left outer join (     select itemid,          sum(case when score = 10 then 1 end) as score10,         sum(case when score = 9 then 1 end) as score9,         sum(case when score = 8 then 1 end) as score8,         sum(case when score = 7 then 1 end) as score7,         sum(case when score = 6 then 1 end) as score6,         sum(case when score = 5 then 1 end) as score5,         sum(case when score = 4 then 1 end) as score4,         sum(case when score = 3 then 1 end) as score3,         sum(case when score = 2 then 1 end) as score2,         sum(case when score = 1 then 1 end) as score1     from votes     group by itemid ) v on i.id = v.itemid order by i.score,      v.score10,     v.score9,     v.score8,     v.score7,     v.score6,     v.score5,     v.score4,     v.score3,     v.score2,     v.score1 	0.000647273096366068
2182677	24755	merge data for same id	select itemcode,     (select attributevalue from table x where x.itemcode = t.itemcode and x.attributecode = 'buttons') as [buttons],    (select attributevalue from table x where x.itemcode = t.itemcode and x.attributecode = 'color') as [color],    ..... repeat for all ..... from table t group by itemcode 	0.000292180463054326
2183768	6763	how to search in sql for hour/minutes?	select  * from    tab where   datepart( hour, date_col )  in (17,18) and     datepart( minute, date_col ) = 0 and     datepart( second, date_col ) = 0 	0.550148932876077
2185029	35753	sort by order of values in a select statement "in" clause in mysql	select * from your_table where id in (5,2,6,8,12,1) order by field(id,5,2,6,8,12,1); 	0.0745061446557908
2185209	17836	sql finding the maximum of all averaged results	select top 1 id, name, avg (salary) from instructor group by id, name order by avg (salary) desc 	0
2185289	32740	mysql split to use in "select where in" statement	select  * from    mytable where   find_in_set( parametertype, 'a,b,c,d' ) != 0 	0.475608077395942
2185844	30685	find records that do not have related records in sql	select * from     orders o     left outer join orderitems i     on i.orderid = o.id where     i.id is null 	0
2187112	21068	write a t-sql query that filters records containing nchar(2028)	select *  from tablename where columnname collate latin1_general_bin like '%' + nchar(2028) + '%' 	0.14519424586468
2187548	38171	stored procedure column value determined by value of another column	select  date,          amount,          price,          case when amount > 0 then 'positive'               when amount < 0 then 'negative'          end as positive_or_negative from #table 	0.00013645183144444
2187575	56	sql query, select top 2 by foreign key order by date	select planid, clientid, plandate from (     select row_number() over (partition by clientid order by plandate desc) rn, *     from [dbo].[tblplan] ) as t1 where rn <=2 	0.000192135890958218
2188504	12327	mysql - selecting based on an if-statement	select t.one,        t.two,        t.three,        case when 1 = 1 then t.four else null end as four   from table t 	0.00161652297020606
2190112	25799	mysql optimization - display 10 most recent records, but also identify duplicate rows	select sql_no_cache count(*) as multiple, a.*,b.*    from announcements as a    inner join  (   select username, count(username) as multiple from stores   where username is not null and state = 'nc'   group by username  )  as s  on a.username=s.username  order by a.dt desc limit 10 	0
2190889	10968	mysql filter results	select * from actions inner join users on actions.user_id = users.id  where users.username != "admin"; 	0.236797899476826
2193093	18957	finding the sum of values of a column of all records in sql 2005	select     sum(weight)     from mytable     where name=2 and type in ('a','b','c') 	0
2195699	39273	sql if "something" select count	select    sum(       case           when col1 = 'cake' then col3           when col2 = 'cake' then col4           else 0 end     ) as mysum from theview 	0.241723349738181
2196017	32464	how to compare two tables fields name with another value in mysql?	select college_open_time, college_close_time, school_open_time, school_close_time from dbo.tbl_college as tc     left join dbo.tbl_school as ts on ts.owner_id = tc.owner_id      and ts.school_day = tc.college_day where tc.owner_id = 1      and college_day = 'tuesday' 	0
2197449	13380	joining multiple unrelated tables in mysql	select 'isfoo', a, b, c, null, null, null from foo union all select 'isbar',null, null, null, d, e, f from bar 	0.00994646193942775
2198712	19129	dynamicly labeling users by score	select  users.*,grade.* ,iif(users.score>grade.high,"a",iif(users.score>grade.average,"b",iif(users.score>grade.low,"c","d"))) as label from (select round(avg(users.score)-stdev(users.score),1) as low ,round(avg(users.score),1) as average ,round(avg(users.score)+stdev(users.score),1) as high from users)  as grade, users; 	0.0249258580037116
2199825	32077	how can i check if a binary string is utf-8 in mysql?	select (          convert(            convert(               potentially_broken_column             using latin1)           using utf8))        !=         potentially_broken_column) as invalid .... 	0.16882890128554
2200357	5832	sql - return limited number of rows, but full row count	select top 10 field1, field2, (select count(*) from table) as totalrows from table 	5.37338193110716e-05
2200368	6338	mysql selecting and grouping rows if one after another	select  user_id, auction_id, count(*) from    (         select  @r := @r + case when @user_id = user_id and @auction_id = auction_id then 0 else 1 end as _g,                 user_id, auction_id,                 @user_id := user_id,                 @auction_id := auction_id         from    (                 select  @r := 0,                         @user_id := null,                         @auction_id := null                 ) vars,                 mytable         order by                 auction_id desc, placed_at desc         ) q group by         user_id, auction_id, _g order by         _g 	0
2202497	30176	[mysql]: inserting values into an intermediate table	select last_insert_id() 	0.0064004416327618
2206284	29663	selecting records from the past three months	select dbo_lu_user.username, count(*) as no_of_sessions  from dbo_sdb_session  inner join dbo_lu_user  on dbo_sdb_session.fk_userid = dbo_lu_user.pk_userid  where [dbo_sdb_session].[sessionstart] between now() and dateadd("d",-90,now()) group by dbo_lu_user.username; 	0
2209338	33503	another mysql join question	select cat_id, classified_id, option_id, option_name, value   from option_values, category_options  where category_options.option_id = option_values.option_id    and classified_id = <?> and cat_id = <?> 	0.565445348851807
2211492	18565	sql server-- join tables and sum columns for each distinct row	select    p.institutionid,    p.accountnumberkey,    total = c.value1 + c.value2 from    parent p    inner join (       select distinct accountnumberkey, value1, value2       from child    ) c on p.accountnumberkey = c.accountnumberkey 	0
2211871	8039	sql group select query	select t1.* from(select password, ipaddress  from yourtable group by password, ipaddress having count(*) > 1) t2 join yourtable t1 on t1.ipaddress = t2.ipaddress and t1.password= t2.password 	0.481872852200982
2214058	39200	sql- how to extract forum topics that are not repeats?	select p.id, p.message, o.subject from ((select t.id   from posts as p left join topics as t on p.topic_id = t.id   group by t.id   having p.posted = max(p.posted) ) ids left join topics as t on ids.id = t.id) o                                         left join posts as p on o.id = posts.topic_id order by p.posted desc limit '0,10' 	0.0157595263969825
2214728	5387	sql to calculate daily totals minues the previous day's totals	select o.report_date, o.tech, o.total_cpe,  o.total_cpe -  (     select  iif(sum(oos.total_cpe) is null, 0,sum(oos.total_cpe)) as total_cpe      from oos      where (((oos.tech)=o.tech) and ((oos.report_date)<o.report_date)) ) as total from oos o; 	0
2215261	36208	advanced sql query. top 12 from each category (mysql)	select * from (     select        games.*,        @rn := case when @category=category then @rn + 1 else 1 end as rn,        @category := category     from games, (select @rn := 0, @category := null) as vars     where status = 'game_published' and featured = '1'     order by category ) as t1 where rn <= 12 	0.000147358242175843
2216522	37976	how to insert a time between the two dates	select isnull(max(t2.date)+1,t1.fromdate)  from table1 t1 inner join table2 t2 on t1.[name] = t2.[name] where t1.[name] = 'sched1' 	9.0914432720684e-05
2218378	423	use mysql to determine whether today is a user's birthday	select *        from users       where           date_format(from_unixtime(birthdate),'%m-%d') = date_format(now(),'%m-%d') 	0.000340856432711453
2220453	25800	sql query adding column values	select int_id, int_test_one + int_test_two as sum from table 	0.0465185988959221
2220889	19579	getting last insert id in excel adodb connection to mysql database	select last_insert_id(); 	0.000507166485202526
2221982	39031	easy way to find out how many rows in total are stored within sql server database?	select sum(row_count)     from sys.dm_db_partition_stats     where index_id in (0,1)     and objectproperty([object_id], 'ismsshipped') = 0; 	0.000220301117515501
2222592	33332	selecting rows - unique field as criteria	select    t1.* from      mytable t1           inner join (             select    pos, outdata, mismatch = min(mismatch)             from      mytable             group by  pos, outdata           ) t2 on t2.pos = t1.pos                   and t2.outdata = t1.outdata                   and t2.mismatch = t1.mismatch 	5.9444411356791e-05
2222995	1269	sql query with multiple checkboxlist selected	select name from tablea where id in (select aid from tableb where cid = 1              intersect              select aid from tableb where cid = 2) 	0.587694917738626
2224951	30642	return the nth record from mysql query	select * from table order by id limit n,1 	0.000175766647374738
2225690	33365	how to get unique set of rows from sql where uniqueness is defined by 2 columns?	select t1.* from table1 t1 left join table1 t2 on t1.id != t2.id and t1.name = t2.name and t1.parent = t2.parent where t2.id is null 	0
2225729	19094	grouping items from mysql by the day they were posted	select * from mypoststable order by postingdate  	0
2227805	21250	sql query to show most ordered product	select p.`product_id`, p.`name`, sum(o.`quantity`) as quantity from `order_detail` as o     inner join `product` as p     on o.`product_id` = p.`product_id` group by o.`product_id` order by sum(o.`quantity`) desc, p.`name` asc limit 3 	0.00134005082620896
2228307	31166	how to use sum() within a group_concat()?	select state,group_concat(cast(total as char)) from (     select state,sum(i.quantity) total     from shops s     left join items i on i.shop=s.shopid     where state=5     group by item ) s 	0.434919730290795
2228332	18180	two tables in mysql: select from first, sort by second	select prod.id, prod.title, min(price.price) as minprice from product prod left join price on price.productid = prod.id group by prod.id order by minprice desc 	0
2228519	1367	formatting dates in sqlserver to use as comparison	select * from tablea where as_of_date = convert(datetime, '01/01/2010', 101) 	0.7791775793429
2229070	40258	using ".." in sql (insert into x..y (a) values ('1')	select * from master..sysobjects select * from master.dbo.sysobjects 	0.0110736414735811
2230319	35508	select query with max	select *  from orders    , orders_history where orders.orders_id = orders_history.orders_id and orders.orders_id in (   select orders_id      from orders_history    group by orders_id    having max(order_status_id) = 1 ) 	0.282813857341838
2230447	16774	sql query to return columns and values which match part of a where condition	select a.*, b.*, mycond1, mycond2, mycond3 from a     inner join b on a.pk = b.pk     … rest of normal query …     left outer join (select 1 as matched where mycondition1) mycond1     left outer join (select 1 as matched where mycondition2) mycond2     left outer join (select 1 as matched where mycondition3) mycond3 where (mycond1.matched is not null or mycond2.matched is not null) and mycond3 is not null 	0.000133745608256159
2231717	32868	single sql query to check if either table contains a row with column=x	select c.*, a.*, b.* from c.id     left outer join a on a.id  = c.id     left outer join b on b.id = c.id where c.id = @somevalue and (a.id is not null or b.id is not null) 	0.00171171930679525
2231801	20479	sql to extract matlab date from postgres db	select extract(epoch from (timestamp '2010-10-02 12:00:01'         - timestamp '0000-01-01 00:00'         + interval '1 day'))/(3600.0*24.0) 	0.00252672260887823
2232672	40839	sort mysql table based on number of rows in another table	select      users.user_id, count(comments.id) as total_messages from      users inner join      comments on comments.link_id = users.id group by      user_id order by      count(comments.id) desc 	0
2232937	2234	sql server 2005: which one is faster? condition over 2 columns or over 2 rows?	select * from table1 where idcolumn1 = x union all  select * from table1 where idcolumn2 = x; 	0.0049443166546507
2234481	6798	mysql - how can i find common values in one table column based on another column using and?	select distinct location from cross_reference_table where attendee =6 or attendee = 7 or attendee=8 group by attendee, location having count(*)=3 	0
2236913	30545	how to join tables to get the result	select distinct t2.itemcode, t1.attr1, t2.attr2 from       (        select attr1        from table1     ) as t1     cross join     (         select itemcode, attr2        from table2     ) as t2 order by 1, 2, 3 	0.0036722965531414
2237159	14616	get average time between times in sql	select  avg(period) from    (         select  time_to_sec(timediff(@date_posted, date_posted)) as period,                 @date_posted := date_posted         from    (                 select @date_posted := null                 ) vars,                 messages         order by                 date_posted         ) q 	5.48154392816666e-05
2237467	37	sql server trigger - connection info	select *  from sys.dm_exec_connections  where session_id = @@spid 	0.386845719022308
2238269	40123	php+mysql join statement arrange multiple values as row in mysql_fetch array	select  cl.*, group_concat( distinct dep.dept_name separator '|' ) as dept_name  from epapers.clientelle  cl  inner join  epapers.dept_staff_users depu  on depu.user_id=cl.user_id  inner join epapers.dept dep  on dep.dept_id=depu.dept_id  group by cl.user_id  order by cl.user_name asc foreach( ....     $departments = explode( '|', $row['dept_name'] ); ...     if( isset( $departments[0] ) ) {         echo "<td>{$departments[0]}</td>";     } else {         echo "<td></td>";     }     echo "<td>{$departments[1]}</td>";     echo "<td>{$departments[2]}</td>"; 	0.00893409627588168
2238598	20295	mysql query to find a user with all of the given permissions	select userid, group_concat(distinct permissions order by permissions desc) as permissions_grouped from permissions where permissions in ('view', 'delete', 'add', 'edit') group by userid having permissions_grouped = "view,edit,delete,add"; 	0
2240902	19818	sql-query to find articles with at least one of the listed tags	select articles.article_id, count(tags.tag_id) as num_tags, group_concat(distinct tag_name separator ',') as tags from articles, article_tag, tags where articles.tag_id = article_tag.tag_id   and article_tag.tag_id = tags.tag_id   and tags.tag_name in ( 'jazz', 'funk', 'soul', 'britney spears' ) group by articles.article_id order by count(tags.tag_id) desc 	0
2241512	37451	how to get data from 2 mysql tables	select t1.idno, t1.lname from t1 left join t2.religion on ( t2.idno = t1.idno ) 	0.000102353614067758
2242893	28931	i am displaying a list of categories in asc order."others" is also one of the category. i need to display all categories in asc order and "others" in last 	select  * from    categories order by    case                  when categorie = 'others' then 2                  else 1              end,              categorie 	0
2246268	14692	how can i recover unicode data which displays in sql server as?	select convert(varbinary(max), 'some text') 	0.7284422405059
2246462	18911	mysql select not in () -- disjoint set?	select distinct a, b, c from t1 where not exists (select null from t2 where t1.a = t2.a and t1.b = t2.b and t1.c = t2.c) 	0.476243155153153
2246677	37620	mysql - fetch rows where a field value is less than 5 chars	select * from users where length(zip_code) < 5 	6.92538519582083e-05
2247266	34549	mysql - valid unique e-mail	select `email` from `users` where `email` regexp '[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}' group by `email` 	0.0933798636544501
2248901	2211	msaccess: ranking rows based upon column criteria	select a.account, a.[cost centre], a.transno, (select count(*)     from table4  b    where b.account=a.account     and b.[cost centre]=a.[cost centre]     and b.transno<=a.transno) as accountno from table4 as a order by a.account, a.[cost centre], a.transno; 	0.00049556404641302
2249905	2816	is there an alternative to top in mysql?	select field1, field2 from mytable order by field1 asc limit 10 	0.598049730525458
2253103	37053	tsql - latest entry	select id, max(index_id) as latest_index from [table] group by id 	0.00161198470299331
2254192	7237	how do you limit compound records in mysql?	select * from (select * from authors limit 5) as authors, books where books.author = authors.id 	0.0651342861741444
2254622	13078	sql server - selecting data where not exists	select f.*  from farm f  left outer join (     select farmid      from animal      where name = 'pig'     ) a on f.id = a.farmid  where a.id is null 	0.267817294516654
2255783	475	find duplicate records in mysql using like	select     t1.id from mytable t1 left outer join mytable t2 on t1.name like concat('%', t2.name, '%') group by t1.id having count(*) > 1 	0.00563876581163029
2256199	33868	mysql how to do this?	select * from table1 inner join table2 on table1.id = table2.id2 	0.72558754507595
2256488	32052	get mysql result and count specific field	select t1.*, t2.typecount from table1 t1 inner join (     select type, count(*) as typecount     from table1     group by type ) t2 on t1.type = t2.type 	0.000702001515039073
2256497	28936	sql - select inside select	select tablea.[name] as firstname, tableb.lastname from tablea    inner join tableb on tablea.lastnameid = tableb.lastnameid 	0.500251827305935
2257815	34170	select one record for conditions	select     player_id, player_action from     games where     player_action = 'move' group by     player_id 	0.00318068960221655
2258376	32924	mysql conditional order by	select *      from my_table      where 1       order by        case price when 0 then 1        else -1       end asc, price asc, id asc 	0.749087491993078
2258617	9595	mysql concate check not null	select concat(     ifnull(mp.chospital, ''),     ',',     ifnull(mp.chospital1,''),     ',',     ifnull(mp.chospital2,'')) as hospital from tbl 	0.541281089893244
2258735	22640	how to create a query to list all combinations possibilities	select    ccy1, ccy2, cer.exchange_rate from     (      select         c1.rec_id as rec_id1, c1.currency as ccy1,         c2.rec_id as rec_id2, c2.currency as ccy2     from         currency c1         cross join          currency c2     where         c1.rec_id <> c2rec_id      ) foo     left join      currencyexchangerate cer on foo.rec_id1 = cer.[from] and foo.rec_id2 = cer.[to] 	0.000508267940701108
2259160	14064	force mysql to return duplicates from where in clause without using join/union?	select table1.* from table1 join (select 1 as id       union all select 2       union all select 3       union all select 4       union all select 5       union all select 1       union all select 2       union all select 5       union all select 5) as t1 on table1.id = t1.id 	0.400327859325913
2259446	32714	need to export fields containing linebreaks as a csv from sql server	select '"' + replace (replace (html, char(10), ''), char(13), '') + '"' 	0.0189179095436696
2260816	22371	how to find out my result table in multiple table search?	select 'download' as source, download.title from download where download.title like '%$search%'  union all select 'news', news.title from news where news.title like '%$search%' or news.text like '%$search%'; 	0.00358568459044458
2263970	14020	employee database with varing salary over time	select   sum(h.num_hours * s.per_hour) as cost from projects p inner join hours h   on p.project_id = h.project_id inner join (     select       s1.employee_id,       s1.date as start_date,       min(s2.date) as end_date     from salary s1     inner join salary s2       on s1.employee_id = s2.employee_id       and s1.date < s2.date     group by       s1.employee_id,       s1.date) s   on h.employee_id = s.employee_id   and h.date >= s.start_date   and h.date < s.end_date 	0.00536661683427697
2268860	4893	trim whitespaces (new line and tab space) in a string in oracle	select translate(            translate(                translate(string1, chr(10), '')            , chr(13), '')        , chr(09), '') as massaged from blah; 	0.685939152491304
2271473	33210	search big database	select     yourfieldshere from     theurltable as tu join     thepatterntable as tp on tu.link like concat('%', tp.pattern, '%'); 	0.380685704122085
2272086	10791	join; only one record please!	select bl.`blog_id`, count(distinct concant(bc.`blog_id`,bc.`author`,bc.`timestamp`) as 'comment_count',... 	0.053346494857611
2272541	8571	to count or not to count, that is the question	select  item, number, sum(number) over (partition by item) from    products order by         item, number 	0.559976885311947
2272884	32615	mysql column's row starts with value of another row	select      mt1.a, mt2.a, mt2.b from      mytable mt1, mytable mt2 where     mt1.b <> mt2.b and      mt2.b like concat(mt1.b, '%') and      mt2.status = 0 	0
2272906	9612	sql server, choosing from two tables using if statement inside where statement depending on the parameter	select * from my_table where my_id in (   select allids as myids from atable where @local = 'true'   union   select teamids as myids from teamtable where @local <> 'true' ) 	0.0203299081141077
2273417	12377	differentiate rows in a union table	select * from  (select s.shout_id, s.user_id, s.time, 1 as fromshouts from shouts s union all select v.post_id, v.sender_user_id, v.time, 0 as fromshouts from  void_post v)  as derived_table order by time desc; 	0.0119388776562246
2273959	34654	trying to get mysql sub string search working	select postal_district from postcodes where  match(postal_district) against('sa1 1eg' in boolean mode); 	0.674616455260877
2275006	19064	sql server: how to check database has catalog or not	select is_fulltext_enabled from sys.databases 	0.367831558816151
2276123	12879	ordering by total number of rows	select director_id, count(*) as totalmovies from movies   group by director_id   order by count(*) desc 	0
2280906	23080	i have table returned by select,how to calculate sum of field2,where f1 is simillar?	select f1, sum(f2) from your_table group by f1 	0.00162676962782854
2281293	18712	how to do this in a mysql query	select city, count(*) as nbpercity from tablename group by city having nbpercity > 10; 	0.781921583127123
2281493	9023	can we pass null to sql parameter to query all?	select * from table where col1 = @param1 and col2 = isnull(@parm2, col2) 	0.620428588906669
2282136	10617	mysql get last date in each month from column of dates	select max(datecol) from sometable group by year(datecol), month(datecol); 	0
2286513	20843	mysql database join based on a mapping	select  * from    countries c inner join         country_mappings cm on c.country = cm.country inner join         your_other_table yot on cm.country_code = yot.country_code 	0.020868699668794
2288040	15897	how to filter a table by t_sql in sql server 2005, using a specific time for a column of "datetime" datatype	select *  from yourtable  where convert(varchar(5), datefield, 114) between '09:00' and '11:00' 	0.000400816929421124
2290180	14695	mysql date query which selects multiple dates	select  datetime from    (         select  datetime         from    blog         where   datetime < from_unixtime($date)         order by                 datetime desc         limit 1         ) p union all select  datetime from    blog where   datetime = from_unixtime($date) union all select  datetime from    (         select  datetime         from    blog         where   datetime > from_unixtime($date)         order by                 datetime         limit 1         ) n 	0.0118413949563817
2290753	39764	doing a join across two databases with different collations on sql server and getting an error	select sone_field collate sql_latin1_general_cp850_ci_ai   from table_1     inner join table_2       on (table_1.field collate sql_latin1_general_cp850_ci_ai = table_2.field)   where whatever 	0.770009687106314
2290932	27048	get weeks in sql	select datepart(wk, datefield) as weeknumber, count(*) as hitsforweek from sometable where datefield >= '20090101' and datefield < '20100101' group by datepart(wk, datefield) 	0.00804109467639368
2291193	31481	mysql: difference between `... add index(a); ... add index(b);` and `... add index(a,b);`?	select * from x1 where b = 'something'; 	0.00267196257333512
2293092	35702	fastest way to identify differences between two tables?	select term, crn, fee, level_code from live_data minus select term, crn, fee, level_code from historical_data 	0.000347638721005079
2294653	30843	sql server - top saleperson per region	select * from (      select region,              person,              rank() over(partition by region order by sum(dollars) desc) as ranking      from sales       group by region,                person  ) temp where ranking = 1 	0.0158409701237991
2295495	13710	sql join to only 1 row - sql server 2005	select tpnb, sum(allocatedqty) as 'qty'     from (select distinct tpnd, tpnb from integration.productlookup) as pl      inner join  dbo.allocatedstock as astock     on pl.tpnd = astock.tpnd     group by tpnb 	0.046186428601283
2295864	3809	php & mysql: selecting multiple books and showing their info in next screen	select  (select count(*) from books_stock where books_stock.book_id = books.book_id ) as  books_in_stock,             books.book_id, books.description, books.book_price, books.book_name             from books              inner join books_stock  on books.book_id = books_stock.book_id             where book_id in (21, 23, 30) 	0
2296296	11853	string formatting in t-sql	select right( '0000' + cast( 1 as varchar),4) 	0.704798958564445
2296824	26397	php mysql compare long and lat, return ones under 10 miles	select *, ((acos(sin($lat * pi() / 180) * sin(lat * pi() / 180) + cos($lat * pi() / 180) * cos(lat * pi() / 180) * cos(($lon - lon) * pi() / 180)) * 180 / pi()) * 60 * 1.1515) as distance from locations having distance<='10' order by distance asc 	0.0408176425927022
2297133	26740	count the number of times a string occours in a row with the type set	select one,count(*) from db group by one select two,count(*) from db group by two etc 	0
2300020	9702	mysql multiple counts in single query	select tm.*,            x.listcount,            y.uploadcount       from $tbl_members tm  left join (select tl.username,                   count(tl.listname) as listcount              from $tbl_list tl          group by tl.username) x on x.username = tm.username left join (select tu.username,                   count(tu.id) as uploadcount              from $tbl_uploads tu          group by tu.username) y on y.username = tm.username  group by tm.username   order by tm.lastname, tm.firstname 	0.0504678068666942
2301583	11255	select * from table with where and order by clause problem	select count(name) as totalcomments   from tablename where comment <> ''   order by id 	0.633603709022186
2302429	29398	select database rows in range	select * from (    select *, row_number() over (order by your_ordered_field) as row from your_table  ) a where row > 5 and row <= 10 	0.001267773453084
2305146	15356	select statement for one-to-many all details in one row	select          (select descriptions from products d where d.productid = p.productid )            description,          max(if(month=1,qty, null)) m1,          max(if(month=2, qty,null)) m2,          max(if(month=3, qty, null)) m3           from planned p           group by productid  ; 	0.00129236275386148
2305441	17180	sql query to concatenate strings or add default value	select    codproy,    descproy,    user,    codproy + ' - ' + coalesce(user,'not available') + ' - ' + descproy as expr  from dbo.proy 	0.00345059220811108
2308063	37383	tsql to find if logins have password same as loginname?	select * from syslogins where pwdcompare (name,password)=1 	0.00386192624848027
2308964	9683	adodb: postgresql select from two tables but return one set of results	select x_ast.name from x_ast inner join x_ast_tree   on x_ast.somefield=x_ast_tree.somefield where x_ast_tree.parent='$parent_id' 	0
2309891	40582	script to add an index on each foreign key?	select 'create index ix_'+c.name+'_'+p.name+' on '+c.name+'('+cf.name+');' from sysforeignkeys fk join sysobjects c on fk.fkeyid=c.id join sysobjects p on fk.rkeyid=p.id join syscolumns cf on c.id=cf.id and cf.colid = fk.fkey left join sysindexkeys k on k.id = cf.id and k.colid = cf.colid where k.id is null order by c.name 	9.3745760456884e-05
2310062	9736	how to force an index on inner joined tables?	select foo.*, bar.* from foo force index (a) inner join bar force index (b) on foo.rel_id = bar.rel_id where foo.status = 1   and bar.status = 1 	0.342350389839175
2311671	36287	filter based on an aliased column name	select id, myalias from (     select id, case when <snip extensive column definition> end as myalias     from mytable ) data where myalias is not null 	0.00361013281469869
2314295	26490	taking only 1 row from a group of rows sharing the same field value	select t1.*  from yourtable t1     join      (select min(col1) as firstid       from yourtable group by col2) x on t1.col1 = x.firstid 	0
2315041	37864	sql - find records with similar value	select     * from     tasks where typeid in     (select typeid from tasks      group by typeid having count(*) > 1) 	0.00111528382904448
2315045	10048	help me find blocks of data	select id, employeeid from ( select r.id, r.employeeid,  (select count(1) from recs r1 where (r1.employeeid = r.employeeid and r1.id = r.id-1) as c1, (select count(1) from recs r2 where (r2.employeeid = r.employeeid and r2.id = r.id-2) as c2, (select count(1) from recs r3 where (r3.employeeid = r.employeeid and r3.id = r.id-3) as c3 from recs r1) tab1 where (tab1.c1+tab1.c2+tab1.c3 =3); 	0.783651292559199
2316004	32926	sql query to only exclude data of last 24 hours?	select * from node where date < (unix_timestamp(now()) - 24*60*60) 	0
2316398	2173	get names from values in a select statement + sql server 2005	select case when gender=1 then 'male' else 'female' end gender  from table 	0.000751450504543931
2317377	135	postgresql order by	select * from channel_table  order by nullif(number, 0) nulls last 	0.418609287342913
2317686	5747	joining 2 sql select result sets into one	select t1.col_a, t1.col_b, t2.col_c from (select col_a, col_b, ...etc...) as t1 join (select col_a, col_c, ...etc...) as t2 on t1.col_a = t2.col_a 	0.000444077228783319
2318398	16466	how can i limit number of results by a specific column in postgresql?	select user_name, count_item, item_name  from (select user_name, count(item_name) as "count_item", item_name      row_number() over (partition by user_name order by count_item desc)     from my_table) where row_number < 4 group by user_name, item_name  order by user_name, count_item desc; 	0.000399579579879896
2321131	34773	display the table name in the select statement	select 'table1', * from table1  union select 'table2',* from table2 	0.000552933640695552
2323659	39382	how can i query two different databases in a single query using mysql?	select schemaa.table.column from schemaa.table union select schemab.table.column from schemab.table 	0.00633973124581693
2323817	16311	can i use the sub-query in the from in t-sql?	select *  from  ( select * from tablea where fielda=1 ) sub where fieldb > 10 	0.237372122048477
2324255	7606	how to find which task is atpresent going on based on the today date	select distinct projectname from projectplan where username=@username and getdate() between startdate and enddate 	0
2324522	15463	how to get the hour difference between 2 datetimestamp on derby db?	select {fn timestampdiff(sql_tsi_frac_second, startdate, enddate)} as diff 	0
2325074	12593	can sqlcommand parameters provide the names of database columns?	select * from line where ( @foo = 'montotal' and montotal is null)     or (@foo = 'monunitprice' and monunitprice is null) 	0.0117832587435847
2326183	3067	how can i reference a single table multiple times in the same query?	select     a.id,     a.name,     b.id as spouseid,     b.name as spousename from     people a     join people b on a.spouse = b.id 	0.00010020180818235
2326740	33646	shorten and compact this small sql snippet (count and most recent date)	select max(datecreated) as [viewedlast], count(*) as viewcount from userviewhistory uvh1 where (userid = @userid) and (viewedbyuserid = @requestinguserid) 	0.525846831222259
2328521	26350	sql: select from many-many through, joined on conditions in through table	select     cl.*, u.*  from     (     select         computer_id, max(numberoflogins) as numberoflogins     from        computerlogins     group by        computer_id     ) maxc     join     computerlogins cl on maxc.computer_id = cl.computer_id and maxc.numberoflogins = cl.numberoflogins     join     users u on cl.user_id = u.id 	0.00304808521252994
2328534	26751	agregate sql query with maximun number of rows to take into account	select yr, doy, team_id, sum(if nbvote < 10, nbvote, 10) as filteredvotecount from (   select year(date_voted) as yr, dayofyear(date_voted) as doy,      team_id,      ip_address,     count(*) as nbvotes   from mytable   group by year(date_voted), dayofyear(date_voted), team_id, ip_address ) group by yr, doy, team_id order by yr, doy, team_id    	5.88180889175523e-05
2330702	24926	how to do a join on the latest record? sql	select     a.*, curr.* from       a inner join b         curr on         a.aid   = curr.aid and        a.adate > curr.bdate where      curr.bdate = (                select max(b.bdate)                from   b                where  b.aid   =  curr.aid                and    b.bdate <= curr.bdate             ) 	0.000289137659729281
2331177	3850	preventing duplicate row insertion in php/mysql	select * from users where users.name = :name or users.email = :email 	0.00994198105155798
2332178	34774	mysql query for getting all items and removing one item based on a criteria	select id from sometable where email=:email2 	0
2334535	23456	selecting consecutive numbers using sql query	select seat, status from seats where seat >= (    select a.seat    from seats a       left join seats b on           a.seat < b.seat and          b.seat < a.seat + 4 and          b.status = 'available'    where a.status = 'available'    group by a.seat    having count(b.seat)+1 = 4    ) limit 4 	0.00541572218776528
2337156	33997	sql: quickly getting the value of column b wherever column a is minimum	select x.objuid,        y.time,        y.frame,        z.time,        z.frame   from (select m.objuid,                min(m.time) as min_time,                max(m.time) as max_time           from motion m       group by m.objuid) x   join motion y on y.objuid = x.objuid                and y.time = x.min_time   join motion z on z.objuid = x.objuid                and z.time = x.max_time 	5.02562321969312e-05
2337236	13276	list stored procedures that can be called by each user	select     suser_sname(u.sid), object_name(p.major_id) from     sys.database_permissions p     join     sys.database_principals u on p.grantee_principal_id = u.principal_id 	0.00364043515498656
2343056	16167	oracle :compare dates only by the hour	select d  from my_table where to_char(d,'hh24') > '16'; 	6.45974806001892e-05
2343155	22294	generating order statistics grouped by order total	select    count(case when total < 1 then 1 end) tunder1,   count(case when total >= 1 and total < 3 then 1 end) t1to3,   count(case when total >= 3 and total < 5 then 1 end) t3to5,   ... from (   select sum(quantity * price) as total   from orderitems group by orderid ); 	0.00415845363021419
2343401	6235	oracle db view/system table to check if given part of a package is a procedure or a function	select case (select count(*) from all_arguments aa                         where aa.object_name=ap.procedure_name                          and aa.object_id = ap.object_id                           and argument_name is null)          when 1 then 'function'          when 0 then 'procedure'          else ''        end as is_function, ap.*   from all_procedures ap  where ap.object_name like '<package name>' 	0.0299593745377988
2343549	40191	mysql - order by number of chars	select * from words order by length(word) desc 	0.0253010854988425
2344467	17116	how do you get the last access (and/or write) time of a mysql database?	select update_time from   information_schema.tables where  table_schema = 'dbname' and    table_name = 'tabname'` 	0.000169860478757185
2345879	17645	sql query to pull multiple entries with same user_id	select user_id  from task where created >= '" . date("y-m-d", strtotime("-1 week", strtotime($date))) . " 00:00:00'   and created <= '" . $date . " 23:59:99'  group by user_id  having count(*) > 1 	0.000310652060857714
2347446	37382	sql server - finding the highest priority item using bitwise operators	select  * from    primarydata pd cross apply         (         select  top 1 *         from    exception e         where   e.mask & pd.exceptions <> 0         order by                 e.priority         ) q 	0.00196324603218363
2348922	19588	mysql - using avg() and distinct together	select col2,           avg(col1)      from table  group by col2 	0.335528580172215
2349500	4120	group by sql statement	select b.medication_name,        b.patient_history_date_bio as med_date,        b.medication_dose   from biological b   join (select y.medication_name,                max(y.patient_history_date_bio) as max_date           from biological y       group by y.medication_name) x on x.medication_name = b.medication_name                                    and x.max_date = b.patient_history_date_bio  where b.patient_id = ? 	0.691318188644685
2349593	1301	retrieve records in a range using year and month fields in mysql	select... from ... where ( year = <startyear> and month >= <startmonth> )     or ( year > <startyear> and year < <endyear> )     or ( year = <endyear> and month <= <endmonth> ) 	0
2350492	28481	how to remove opposite rows from sql table	select      t.a,             t.b from        my_table t left join   my_table t2         on  t.a = t2.b         and t.b = t2.a         and t.a < t.b where       t2.a is null 	0.000544032904788697
2350716	31917	php: search in more tables at once?	select username from table1 where username = '$username' union select username from table2 where username = '$username' union select username from table3 where username = '$username' 	0.00570060884409464
2352497	510	mysql: value based on conditions	select case when columnz <> 0 then 4             when columny <> 0 then 3             when columnx <> 0 then 2             when columnw <> 0 then 1             else 0        end as your_alias_name from ... 	0.00147782121752696
2354717	5048	how to write a postgresql query for getting only the date part of timestamp field, from a table	select date(my_field) from my_table; 	0
2354832	25796	storing regular expressions in mysql database table and maching against them	select * from table where $your_string rlike regexp 	0.178548700977021
2355373	28435	getting random and last value from group in sql	select     traintablea.trainnumber     ,traintablea.departuretime     ,arrivalstation from     (select         trainnumber         ,departuretime         ,arrivaltime         ,arrivalstation     from         schedule     where departurestation = givenstation     ) as traintablea     inner join      (select         trainnumber         ,departuretime         ,max(arrivaltime) as a     from         schedule     group by           trainnumber           ,departuretime     ) as traintableb     on     traintablea.trainnumber = traintableb.trainnumber     and traintablea.departuretime = traintableb.departuretime     and traintablea.arrivaltime = traintableb.a 	0
2355662	28682	how to find unused tables in sql server	select * from sys.dm_db_index_usage_stats where [database_id] = db_id()      and [object_id] = object_id('tablename') 	0.0201353445991812
2358054	37415	valid record in sql query	select case when  cast(isnumeric(left(@str,5)) as int) + case when substring(@str,6,1)= '-' then 1 else 0 end +case when substring(@str,10,1) like '[a-z]' then 1 else 0 end =3 then 'matched' else 'notmatched' end 	0.242118747525971
2358409	33660	sql server 2005 - stripping only alpha values from string	select left(yourstringcolumn, patindex('%[0-9]%',yourstringcolumn)-1)    from dbo.yourtable 	0.00844017284187719
2358673	8272	count number of 'overlapping' rows in sql server	select c.day, max(c.concurrency) as mostconcurrentusersbyday from  (    select convert(varchar(10),l1.starttime,101) as day, count(*) as concurrency    from login_table l1    inner join login_table l2        on (l2.starttime>=l1.starttime and l2.starttime<=l1.endtime) or          (l2.endtime>=l1.starttime and l2.endtime<=l1.endtime)     where (l1.endtime is not null) and l2.endtime is not null)  and (l1.id<>l2.id)     group by convert(varchar(10),l1.starttime,101) ) as c     group by c.day 	0.000264453418038105
2359458	13635	running a query with php/mysql then reordering the results by another column	select * from (   select *   from post   inner join account on post.account_id = account.account_id   where post_id > neww   order by post_date asc limit 10; ) order by post_id 	0.00498709214063959
2360714	20612	what's the best way to retrieve this data?	select      formx.* from      orderitems join     formx on     orderitems.formxid = formx.formxid where     orderitems.orderid = @orderid 	0.0941186307894437
2362968	28803	mysql: find highest average score	select player_id, avg(score) from batsmen where batsmen.inning_no=4 group by player_id order by 2 desc limit 1; 	0
2363210	20552	which oracle table uses a sequence?	select type, name, line, text from all_source where owner = 'myschema' and upper(text) like '%myseq.nextval%'; 	0.136955764094177
2363319	11991	photos from last gallery	select * from fotos where gallery_fk = (select max(id) from gallery); 	0.000381054687106177
2363370	37906	mysql query to find all rows that are outside join	select  * from    classes c where   class_id not in         (         select  class_id         from    child_classes cc         where   cc.parent_id = 2         )         and class_id <> 2 	0.000250539254186879
2363578	40781	mysql find count query	select  sum(case when recommend = 'y' then 1 else 0 end) yescount,         sum(case when recommend = 'n' then 1 else 0 end) nocount,         count(*) totalcount from    stats 	0.0721998893511681
2364268	9970	replace id with string in sql view	select t1.groupid, t1.membership_list, t2.username from table1 t1 inner join table2 t2 on t1.managerid = t2.userid 	0.120047294041196
2365634	39620	unable to search using timestamp in mysql	select  * from    results where   starttime = timestamp(str_to_date('02/03/2010 21:30:00', '%d/%m/%y %h:%i:%s')); 	0.311261187173026
2367651	10552	inner joining two tables based on all "key/value" pairs matching exactly	select  * from    persons p where   not exists         (         select  null         from    (                 select  key, value                 from    clothing_attributes                 where   clothing_id = 99                 ) ca         full join                 (                 select  key, value                 from    person_attributes                 where   person_id = p.id                 ) pa         on      ca.key = pa.key                 and ca.value = pa.value         where   ca.key is null or pa.key is null         ) 	0
2370108	7071	selecting a null columns with conditons	select id, date, day,    isnull(status, case when day not in ('saturday', 'sunday') then 'holiday' end) from table1 	0.00715215841234211
2370808	33478	t-sql: omit/ignore repetitive data from a specific column	select  * from    (         select  *, row_number() over (partition by productname order by price) as rn         from    mytable         ) q where   rn = 1 	0.0033892596340921
2372047	6006	joining two tables	select  u.*, 'developer' from    users u         inner join developer d on d.user_id = u.user_id union all  select  u.*, 'manager' from    users u         inner join manager m on m.user_id = u.user_id 	0.0136778241814812
2375575	8688	can i concatenate a virtual column in a view?	select x.passwordsalt,         hashbytes('sha1', x.passwordsalt + x.password) as passwordhash from ( select  cast(cast(32768 * rand() as int) as nvarchar) as passwordsalt,         password         from dbo.users) x 	0.0031342930310234
2375781	9817	sql count for a date column	select  count(date)  , trunc(date,'mon') from table group by trunc(date,'mon') having count(date) > 3 	0.0142195194841424
2376535	852	last x posts in a database	select * from wp_posts where post_type = 'post' order by post_date desc limit 10 	0
2377697	8232	mysql getting max of previous where condition	select a.* from table a left join table b on (   b.date=date(from_unixtime($date)) and b.date=a.date and b.id=a.id ) where a.id='$id' order by b.date desc, a.date desc limit 1 	0.00676792246327567
2378246	18849	how to club the results of two sql queries?	select              count(distinct recepient_id) as noofusers,             to_char(actn_take_data_tm,'yyyy-mm-dd') as accdate          from              alrt_platform_alrt_hstry           where              appl_cd like 'ebp' and              alrt_rspns_from_client_id like 'bb'              group by to_char(actn_take_data_tm,'yyyy-mm-dd') union all        select              count(distinct recepient_id) as noofusers,              to_char(actn_take_data_tm,'yyyy-mm-dd') as accdate          from              alrt_platform_alrt          where              appl_cd like 'ebp' and              alrt_rspns_from_client_id like 'bb'              group by to_char(actn_take_data_tm,'yyyy-mm-dd') 	0.00544246586385461
2379357	24512	what is the best way to select multiple rows by id in sql?	select * from `table` where id in (5263, 5625, 5628, 5621) 	0.00543531116051846
2379481	8942	fetch last record in mysql	select col1, col2, ... from yourtable order by xyz desc limit 1 	6.44627052217556e-05
2379557	12984	create a new user oracle with full access to an specific schema	select 'grant select on '||table_name||' to b' from   user_tables / 	0.161965742837158
2379628	10773	mysql: delete empty cells	select  max(col1), max(col2), max(col3) from    mytable group by         (id - 1) div 3 	0.052683955083178
2381053	14025	how to apply a sum operation without grouping the results in sql?	select a.id, sum(b.value) as `sum` from test as a join test as b on a.`group` = b.`group` group by a.id, b.`group`; 	0.144059124666563
2381437	28020	like and where in the same mysql query	select city from cities where city like '%d%' and country_id = '12' 	0.217625536795187
2382931	1365	mysql many to many relation query	select key1  from table  where key1 not in (   select key1   from table   where key2 = 'k2_a' ); 	0.308734416288293
2383787	20388	is it possible to define a single sql query that draws a set of permissible foreign_keys from one table and then uses them to filter another?	select top 100 c.commentid, c.commenttext, c.postdate, u.name from friendships f inner join users u on u.userid = f.frienduserid inner join comments c on c.userid = u.userid where f.userid = 42 order by c.postdate desc 	0
2384067	12523	sqlite: trouble selecting by real values	select * from log where somenumber = 61.0; 	0.146848208646053
2384208	13409	paginate rows from sql	select     * from     (         select             row_number() over(order by news_id desc) as row_number,             *         from             news         where             news_cat = 'pizza'     ) as t where     row_number between @start and @start + 10 	0.0448896752014564
2385426	39650	select longest common timerange	select  max(mindates) maximummindate,         min(maxdates) minimummaxdate from    (             select  location_id,                     min([datetime]) mindates,                     max([datetime]) maxdates             from    table             where   location_id in (200333, 200768)             group by location_id         ) sub 	0.00602283165032176
2385931	9559	how to add new column in ms access table with this criteria	select tblfoob.textb, nz([numa],0) as expr1 into tblfooc from tblfoob left join tblfooa on tblfoob.textb = tblfooa.texta; 	0.0628436662718327
2387016	21882	getting value from array in a select statement	select case mytable.state    when 0 then 'first'   when 1 then 'second'   when 2 then 'third'    end    from mytable  where mytable.id = 1 	0.00267772725810196
2387235	10875	select an array per row?	select products.*, group_concat(category_id separator ' ') from products left join product_categories                 on product_categories.product_id = products.product_id group by product_id; 	0.000957542391158072
2387708	24646	how to get data 3 tables?	select *  from table1 t1 inner join table2 t2   on t1.key2 = t2.key2 inner join table3 t3   on t1.key3 = t3.key3 	0.00144546985410425
2387712	15740	find distinct count of group by user	select ip, count(id) as count, group_concat(cast(id as char)) as ids from table  group by ip 	0.00145298697214383
2387734	24550	a simple way to sum a result from union in mysql	select id, sum(amount) from (     select id,amount from table_1 union all     select id,amount from table_2 union all     select id,amount from table_3 ) x group by id 	0.208793656284718
2390449	4529	sql - isnull record value	select  firstname,  lastname,  case when r.birthdate is null then false  else true end  as hasrecord from  person p left join birthrecords r on p.ssn = r.ssn 	0.0495788932345744
2391911	17060	what's the proper way of joining tables in mysql	select  student.lastname,          student.firstname,          student.idno,          student.year,          parents.p_address  from    student right join parents  on  student.idno=parents.idno                                      and p_address="ambagat, santol, lu" 	0.201010231767872
2391962	16987	mysql - matching 2 rows (or more!) within a sub-query/table	select t1.user_id from table1 t1 join table1 t2 on t1.user_id = t2.user_id where t1.field_id = 1 and t1.value = 'gandalf' and t2.field_id = 2 and t2.value = 'glamdring' 	0.00276420821364198
2392306	20797	selection of rows related to a set of other rows	select entity.*      , count(*) as relevance    from entities      , tags      , entity_tags  where entities.id=entity_tags.entity_id     and tags.id=entity_tags.tag_id    and tags.name in ('fruit', 'organic', 'item') group by entity.id  having count(entities.id) > 1 order by relevance 	0
2392413	25584	convert datetime value into string in mysql	select   date_format(now(), '%d %m %y') as your_date; 	0.00240400003340895
2396695	13401	how to combine two result sets from one table sorted independently using one sql query?	select name, flag from  'table' order by     flag desc,     case when flag = 1 then name else '' end,     case when flag = 0 then name else '' end desc 	0
2397847	21369	conversion of if sql from mysql to postgresql	select    albums.id,    albums.albumname,    sum(    case when ((albums.id=allalbums.albumid) and (allalbums.photoid=$photoid)) then 1      else 0    end   ) as inalbum  from albums,allalbums  group by albums.id  order by albums.createdate desc 	0.0529884812188887
2400832	9162	merge queries into one query	select objectid, l1.setid, frequency, l1.date as startdate, l2.date as enddate  from `logs` l1 inner join `stats` s on (s.startid=l1.id) inner join `logs` l2 on (l2.id=s.endid) inner join  (    select setid, max(date) as date    from `logs` l    inner join `stats` s on (s.startid=l.id)     group by setid  ) d on (d.setid=l1.setid and d.date=l1.date) order by objectid 	0.00625350229759087
2401439	606	sql query - selecting rows where user can be both friend and user	select u.user_id, f1.status, f2.status from user u left outer join friend f1 on f1.user_id = u.user_id and f1.user_friend_id = 1             left outer join friend f2 on f2.user_friend_id = u.user_id and f2.user_id = 1 where u.name like '%' 	0.00610037449040288
2407230	12431	is there is any way to get the select random records using query from table in mysql	select * from `table` order by rand() limit 0,1; 	0.000218938861225768
2409434	28257	condense logic down to one sql query	select  cityname,  count(*) as citylistings from  yourtable group by  cityname order by  cityname 	0.50171021463113
2410994	13899	mysql displaying results in same order no matter "array-order"	select mt.*, $sql_tbl.* from classified mt  left join $sql_tbl   on $sql_tbl.classified_id = mt.classified_id  where mt.ad_id in ('$solr_id_arr_imploded')  order by field(mt.ad_id,'$solr_id_arr_imploded') 	0.0206039280329118
2411559	24049	how do i query sql for a latest record date for each user	select t.username, t.date, t.value from mytable t inner join (     select username, max(date) as maxdate     from mytable     group by username ) tm on t.username = tm.username and t.date = tm.maxdate 	0
2411794	97	storing annually repeatable values in a mysql database	select * from (   select * from mytable    where      repeatable = false     and      eff_dt <= '2007-06-20' < xpir_dt   union all   select * from mytable   where     repeatable = true     and eff_dt <= str_to_date(concat("2007", "-", month(eff_dt), "-", day(eff_dt)), "%y-%m-%d") < xpir_dt ) order by eff_dt desc limit 1 	0.0516004815493157
2411866	12128	creating a query to retrieve certain rows in mysql	select o.* from (     select customer_id, max(order_date) as maxorderdate     from orders     group by customer_id ) om inner join order o on om.customer_id = o.customer_id and om.maxorderdate = m.order_date 	0.000215045938398426
2413042	20376	mysql date time issue	select * from table where current_date() between start_date and end_date; 	0.425545702991877
2413553	30514	single mysql query with count and sum	select sum(article_user_rating) as total_rating, count(article_visited_user_id) as hits from article_visited where article_visited_article_id =1 and article_user_rating > 0 group by article_visited_user_id 	0.0812912667684128
2416522	22679	how to use a calculated column in where condition?	select calcdate from ( select startdate, enddate,        decode (:pvalue,1,                select sysdate from dual,                select activation_date from account where acno = 1234) as calcdate ) where calcdate between startdate and enddate; 	0.135500867645519
2417478	30009	find adjacent rows without stored procedure	select b.* from (select @continue:=2) init, (  select *   from agetable   where agestart=16 and         ageend=25   and         datestart=76533 ) a    inner join (    select *    from agetable    order by datestart   ) b on (     b.agestart=a.agestart and     b.ageend=a.ageend     and     b.datestart>=a.datestart   )    left join agetable c on (     c.datestart=b.dateend+1 and     c.agestart=b.agestart   and      c.ageend=b.ageend   ) where   case   when @continue=2 then    case     when c.someid is null then      @continue:=1     else      @continue    end   when @continue=1 then    @continue:=0   else    @continue  end 	0.0198539230417345
2418528	13950	is there a way to rename a similarly named column from two tables when performing a join?	select p.*, om.memberid, etc.. 	0.00144966388529029
2420078	30599	sql query to retrieve from three inter related tables	select g.groupname, u1.username as groupcreator u2.username as groupmember from groups as g inner join users as u1     on g.creator = u1.id left join association as a     on a.groupid = g.id left join users as u2     on u2.id = a.userid 	0.000437215748212581
2421503	34907	how to determine the maximum id of a set of tables in my database	select max(maxid) as maxid from (     select max(id) as maxid from table1     union all     select max(id) as maxid from table2 ) as t1 	0
2421660	2676	sql query to retrieve highest item up to a point in a group	select p.* from person p inner join (     select surname, max(age) as maxage     from person      where age < 30     group by surname ) pm on p.surname = pm.surname and p.age = pm.maxage 	4.61638232284316e-05
2422688	10051	sql count of count	select    times,    count(1) from ( select            id,           count(distinct value) as times        from table        group by id ) a group by times 	0.0490253084592872
2423422	875	find the most recent shipment for a product (sql subselect?)	select  * from    (             select  coi.product_id,                     max(s.shipping_date) maxdate             from    company_order_item coi inner join                     company_order co on coi.company_order_id = co.company_order_id inner join                     shipment s on co.shipment_id =s.shipment_id             group by coi.product_id         ) sub inner join         company_order_item coi on sub.product_id = coi.product_id inner join         company_order co on coi.company_order_id = co.company_order_id inner join         shipment s on   co.shipment_id = s.shipment_id                     and s.shipping_date = sub.maxdate 	0.0003960883471174
2423538	29090	sql: query 2 columns; if one is valid then ignore the other	select a.id,         case                 when a.over_80 = 'y' then 'over80'             when a.over_60 = 'y' then 'over60'         end from    my_table where   a.over_60 = 'y' 	0.000228729068859604
2423574	38836	sql server determine physical size of table columns	select sum(datalength(yourfield)) from yourtable 	0.00388802939700491
2424110	34731	how do i add months to a current_timestamp in sql?	select dateadd(month,1,current_timestamp) 	0.00341533708170823
2424550	20352	how to get number of selected node	select  rownumber from    (             select                     c.id_listparizm,                 row_number() over(order by c.num) rownumber             from                    @cfglistparizm c              where                   c.id_listgroupparizm = @id_listgroupparizm and                   c.visibleontab=1         ) sub where   id_listparizm = @id_listparizm 	0.000117909407566555
2424793	33328	how to get the table of missing rows in mysql	select t1.* from tablea t1 left join      tableb t2 on t1.id = t2.id where t2.id is null 	7.54578416270904e-05
2426862	20591	can a query be used in place of a table in sql server	select *   from (      select *       from mytable ) m 	0.411218962697359
2427333	34289	sql to get list of dates as well as days before and after without duplicates	select mydate, min(datetype) from (   select mydate + t1.recordtype as mydate, t1.datetype   from   (     select 1 as recordtype, 2 as datetype     union all     select 0 as recordtype, 1 as datetype     union all     select -1 as recordtype, 2 as datetype   ) as t1   cross join mytable   where mytable.fkid = @myfkid ) as combinedtable group by mydate 	0
2428345	8790	select a list of elements and 5 tags for each one	select bulding_name, tag from   buldings b   left join (select tag, building_id               from   tags                 inner join buildings_tags                   on tags.id = buildings_tags.tag_id               where  building_id = b.id               limit  5) t     on b.id = t.building_id order by bulding_name 	0
2429434	20369	tsql: grouping customer orders by week	select count(orderid), weekstart from  (  select *,    dateadd(week, datediff(day,'20000107',yourdate) / 7, '20000107') as weekstart    from orders ) o group by weekstart; 	7.50893172085508e-05
2430005	5572	display last 200 mysql entries no dupes	select distinct * from table order by id desc limit 200 	0
2432574	4924	sql to select from multiple tables	select       (fields) from      dbo.emptable1 e1 inner join     dbo.emptable2 e2 on e1.empid = e2.empid where      e1.status = 0     and e2.week = 7 	0.00858915667702939
2435388	2260	query a column and a calculation of columns at the same time postgresql	select name, description, price from (     select name, description, price from products     union     select bundle_products.name, bundle_products.description, sum(products.price)     from bundle_products     join products on (<your join condition)     group by bundle_products.name, bundle_products.description ) as combined order by price 	0
2435480	849	sql joining on a one-to-many relationship	select       n.id,       n.name,       max( iif( c.color = "red", "y", " " )) red,       max( iif( c.color = "blue", "y", " " )) blue,       max( iif( c.color = "green", "y", " " )) green,       max( iif( c.color = "black", "y", " " )) black    from       c_names n,       colors c    where       n.id = c.id    group by        n.id,       n.name 	0.101232123169875
2436028	3389	making a combined sum of two columns	select cid, sum(case when date_pm = 1 then 1 else 0 end) + sum(case when date_am = 1 then 1 else 0 end) from apples group by cid 	0.00115447089063726
2436992	27587	select sum returns a row when there are no records	select my_sum from (select sum(dummy) as my_sum from dual where 1=2) where my_sum is not null 	0.000482432985857866
2439829	6767	how to count all rows when using select with limit in mysql query?	select sql_calc_found_rows a.id, a.name, b.id, b.name from table1 a join table2 b on ( a.id = b.table1_id ) where   cond1, cond2, ..., condn limit 10 select found_rows(); 	0.00868993854080361
2441316	29453	how to know the names of other users in oracle10g?	select username from all_users / 	0
2443955	31223	how to get the trending tags using php and mysql?	select `tagname`, count(*) as `cnt` from `tags` where `stamp` >= unix_timestamp(date(now())) group by `tagname` order by `cnt` desc limit 10 	0.00258451869105512
2443992	39300	pl/sql - how to pull data from 3 tables based on latest created date	select   o.unique_doc_name,   u.biz_unit_object_name,   v.vendor_object_name,   o.created_at  from   ( select       v.vendor_object_name, max(o.created_at) as created_at      from       udef_vendor as v      inner join       biz_doc2 as o      on       v.parent_object_id=o.objectid      group by       v.vendor_object_name   ) as vo     inner join   udef_vendor as v  on   v.vendor_object_name=vo.vendor_object_name  inner join   biz_doc2 as o  on            o.objectid=v.parent_object_id and   o.created_at=vo.created_at  inner join   biz_unit as u  on   u.parent_object_id=o.objectid 	0
2445982	37621	replace char with varchar2	select 'alter table "' || owner || '"."' || table_name || '" modify ("' || column_name || '" varchar2(' || data_length || '));' from all_tab_columns tc where data_type = 'char' and owner = :schemaname and exists (     select 1     from all_tables t     where tc.owner = t.owner     and tc.table_name = t.table_name ); 	0.34897150275556
2446040	29936	how to select the records whose several fields' combination will equal to a specific value	select * from table where (col1 = "ab" or col2 = "ab" or col3 = "ab")  and (col1 = "bc" or col2 = "bc" or col3 = "bc") 	0
2447894	2708	how to virtually delete data from multiple tables that are linked by a foreign key?	select tbl_subject.*, tbl_domain.isdeleted from tbl_subject inner join tbl_domain on ... 	0
2447983	12738	sql column length query	select max(len(columnname)) as columnmame from dbo.amu_datastaging 	0.174362727931736
2448263	3439	mysql query to find customers who have made the most orders	select tbl_order.customer_id, count(*)     from tbl_order      group by customer_id      having count(*) > 4 	0
2448714	6425	getting average from 3 columns in sql server	select (ratin1 + ratin2 + ratin3) /  ((case when ratin1 = 0 then 0 else 1 end) +  (case when ratin2 = 0 then 0 else 1 end) +  (case when ratin3 = 0 then 0 else 1 end) + (case when ratin1 = 0 and ratin2 = 0 and ratin3 = 0 then 1 else 0 end) as average 	0.000217059589001584
2448772	6059	sql last day in moth select	select a.datecreated,a.sale          from salesummary a  inner join calendar c on a.datecreated = c.fulldatekey  and c.islastdayofmonth = 1 group by a.datecreated,a.sale 	0.000184690196804416
2450054	7099	how to control order of assignment for new identity column in sql server?	select     id, createdate into     mynewtable from     (     select         createdate,         row_number() over (order by createdate asc) as id     from         mytable     ) foo 	0.0718353626268473
2450143	1075	how to add condition on multiple-join table	select client.id, client.name from client inner join client_category cat1 on client.id = cat1.client_id and cat1.category = 1 inner join client_category cat2 on client.id = cat2.client_id and cat2.category = 2 	0.0155431350237695
2450341	36246	multiple column subselect in mysql 5 (5.1.42)	select   p.id,   p.title,   p_aut.aut_name,   p_adv.adv_name from papers p left join (   select pp_aut.paper_id,          group_concat(concat(p_aut.firstname, ' ', p_aut.lastname)) aut_name   from paper_person_roles pp_aut   join persons p_aut on (p_aut.id = pp_aut.person_id)   where pp_aut.act_role='author'   group by pp_aut.paper_id ) p_aut on ( p_aut.paper_id = p.id ) left join (   select pp_adv.paper_id,          group_concat(concat(p_adv.firstname, ' ', p_adv.lastname)) adv_name   from paper_person_roles pp_adv   join persons p_adv on (p_adv.id = pp_adv.person_id)   where pp_adv.act_role='adviser'   group by pp_adv.paper_id ) p_adv on ( p_adv.paper_id = p.id ) group by p.id, p.title 	0.14450799062916
2450528	38692	select highest rated, oldest track	select top 1 t.id, sum(r.rating) as rating, max(datetime) as lastplayed from tracks t inner join trackhistory h on t.id = h.track_id inner join ratings r on t.id = r.track_id where h.track_id not in (     select track_id      from trackhistory      where datetime > dateadd(hour, -2, getdate()) ) group by t.id order by rating desc, lastplayed 	0.00114005930600538
2450529	37549	mysql: selecting multiple fields into multiple variables in a stored procedure	select id, datecreated into iid, dcreate from products where pname = iname 	0.00739276252155433
2451579	26060	sql - select all when filter value is empty	select * from [records]  where @title is null or len(@title) = 0 or ([title] like '%' + @title + '%') 	0.0107403951032615
2455736	12789	display field from another table in sql	select cast((distanceasmeters * 0.001) as decimal(8,1)) distanceaskm, bold_id, created, addressfrom.addressname, addressto.addressname from addrdistance join address as addressfrom on addrdistance.fromaddress = addressfrom.addressid join address as addressto on addrdistance.toaddress = addressto.addressid where  distanceasmeters = 0 and pseudodistanceascostkm = 0        and not addrdistance.bold_id in (select bold_id from distancequerytask) order by created desc 	0
2455750	15213	replace duplicate spaces with a single space in t-sql	select string = replace(replace(replace(' select   single       spaces',' ','<>'),'><',''),'<>',' ') 	0.0604103830024149
2456747	10456	sqlite get records with same column value	select      firstname,lastname,count(*)     from mytable      group by firstname,lastname      having count(*)>1 	0
2456934	22423	sql select statement with a group by	select avg(b.grade), a.tableaid, a.name  from tablea a       join tableb b        on b.tableaid = a.tableaid group by a.tableaid, a.name 	0.600534116897126
2457142	28272	if i use a mysql function in a where clause that returns a static value does it get re-evaluated every row?	select column from table order by rand() limit 1 	0.0603014223459975
2458359	23275	how do i get the sum of the 4th column	select sum(results.amount) from ( select -price*quantity as amount      from product join shipped on (product.id = shipped.product)  union    select amount    from   ... ) results 	0.000371973888444479
2459328	33201	how do i get 5 records before and after a record with a specific id?	select *      from scores     where score >= n order by score asc    limit 6  union   select *      from scores     where score < n order by score desc    limit 5 	0
2459334	9603	query to find all the nodes that are two steps away from a particular node	select step2.tonode from   graph step1 join   graph step2 on step2.fromnode = step1.tonode where  step1.fromnode = 1 	0
2460118	24561	how can i use two or more count()s in one select statament?	select employeeid, employeename,     (select count(*)      from newtimeattendance      where newtimeattendance.employeeid = newemployee.employeeid          and totaltime is null          and (note = '' or note is null)          and month between 1 and 3) as attenddays,     (select count(*)      from newtimeattendance      where newtimeattendance.employeeid = newemployee.employeeid          and totaltime is null          and (note = '' or note is null)          and month between 1 and 3) as absentdays from newemployee order by employeeid 	0.0173386349785971
2460697	10542	how to get some randomized concats based on 2 columns from 1 table?	select concat(u1.first_name, ul.last_name) as full_name from users where mykey = floor(1 + (rand() * 13000)) 	0
2461801	37478	mysql search for user and their roles	select * from (   (select user_id from users where firstname like '%jenkz%')    union    (select user_id from users where lastname like '%jenkz%') ) as dt join ( select 'writer' as role, link_writers.user_id, link_writers.publication_id        from link_writers        union        select 'editor' as role, link_editors.user_id, link_editors.publication_id        from link_editors        union        select 'publisher' as role, lp.user_id, lpg.publication_id        from link_publishers lp        join link_publisher_groups lpg on lpg.publisher_group_id = lp.publisher_group_id      ) roles on roles.user_id = dt.user_id 	0.00563975831447859
2461884	2242	how to select non-consecutive rows in mysql?	select * from your_table as a     left join your_table as b         on a.key_column = b.key_column - 1 where b.key_column is null 	0.0191872301785938
2462502	25640	sql joining 3 tables when 1 table is emty	select  f.*,         v.total,         v.votes,         v.festivalid,         ifnull(r.reviewcount,0) as count     from festivals f inner     join vote v         on f.festivalid = v.festivalid left outer      join (select festivalid,                  count(*) as reviewcount             from reviews)             group by festivalid) as r         on r.festivalid = v.festivalid 	0.0712285070576607
2462749	4959	mysql select top users problem	select count(1) cnt, u.user_id  from users u  left join posts p on p.author_id=u.user_id group by u.user_id order by cnt desc limit 20 	0.103682987896856
2466101	3019	how i can change prefixes in all tables in my mysql db?	select    group_concat('rename table `', table_schema, '`.`', table_name, '` to `', table_schema, '`.`prefix_', table_name, '`;' separator ' ') from    `tables` where `table_schema` = "test"; 	0.0438864740691422
2467460	40407	problem reading from 3 tables in mysql	select * from father  inner join mother on father.idno = mother.idno inner join parents on mother.idno = parents.idno where father.idno = '03a45' 	0.0445158929468983
2468428	13822	how to convert the time difference to hours(with 2 decimal place) in derby?	select {fn timestampdiff(sql_tsi_minute, startdate, enddate)}/60 as diff 	0.000990756307987021
2468528	6207	need to read data from oracle database with many conditions	select  b.os      , c.package_version      , count(a.employee_name) from b   join a  on (b.id=a.id)   join c  on (b.id=c.id) group by b.os,c.package_version 	0.236153792519654
2469097	27409	user sumbitted top 5 and sort by popularity	select type, sum(score) from ( (select first as type, count(*)*5 as score  from top_fives  group by first ) union (select second as type, count(*)*4 as score  from top_fives  group by second ) union (select third as type, count(*)*3 as score  from top_fives  group by third ) union (select fourth as type, count(*)*2 as score  from top_fives  group by fourth ) union (select fifith as type, count(*) as score  from top_fives  group by fifth )  ) group by type order by sum(score) desc; 	0.00519223555173442
2469228	9257	multiple select statement in stored procedure	select a.[appointmentid]    ,a.[contactid]    ,a.[date]    ,a.[bookedby]    ,a.[details]    ,a.[status]    ,a.[time]    ,a.[type]    ,a.[jobid]    ,a.[appointmentfor]    ,p1.personfirstname as userfirstname    ,p1.personlastname as userlastname    ,p2.personfirstname as contactfirstname          ,p2.personlastname  as contactlastname              from [dbo].[appointments] a     inner join person p1 on p1.person_id = a.[appointmentfor]     inner join person p2 on p2.person_id = a.[contactid] 	0.738080805733548
2470356	622	mysql show create constraint?	select b.table_name, b.column_name, b.constraint_name,        b.referenced_table_name, b.referenced_column_name from information_schema.table_constraints a join information_schema.key_column_usage b on a.table_schema = b.table_schema and a.constraint_name = b.constraint_name where a.table_schema=database() and a.constraint_type='foreign key' order by b.table_name, b.constraint_name; 	0.0167617991593847
2470818	38283	database design query	select *   from table_illness  where table_illness.pet_id = <value>    and date between table_illness.start_date and table_illness.finish_date 	0.510301009386371
2472604	9211	comparing values from a string in a mysql query	select * from products where cast(substring_index(volume, ';', -1) as unsigned) >= 50 	0.00205640460507759
2473466	8382	how can an oracle number have a scale larger than the precision?	select cast(0.0001 as number(2,5)) num,         to_char(cast(0.0001 as number(2,5))) cnum,        dump(cast(0.0001 as number(2,5))) dmp   from dual 	0.000717779930281992
2474336	38181	the "first past the post election" query problem	select districthnd, partyhnd, candidatename, totalvotes from electionresults as er where totalvotes = (                     select max(er1.totalvotes)                     from electionresults as er1                     where er1.districthnd = er.districthnd                     ) 	0.00160082159413434
2474678	16748	date calculating (sql, oracle 10g)	select round((months_between(current_date,date1)/12),1) as years  from table1 where date1 > add_months(current_date,-60) 	0.254543483450218
2474975	2388	rows in their own columns depending on their date and symbolized by 'x'	select d.doctorname,          t.teamname,          max(case when ca.visitdate = 1 then 'x' else null end) as 1,          max(case when ca.visitdate = 2 then 'x' else null end) as 2,          max(case when ca.visitdate = 3 then 'x' else null end) as 3,          ...          max(case when ca.visitdate = 31 then 'x' else null end) as 31,          count(*) as visited     from cactivity ca     join doctor d on d.id = ca.doctorid      join team t on t.id = ca.teamid    where ca.visitdate between '1/1/2010' and '1/31/2010' group by d.doctorname, t.teamname 	0
2475178	19623	how to get total number of hours between two dates in sql server?	select datediff(hh, @date1, @date2) as hours_difference,        datediff(mi,dateadd(hh,datediff(hh, @date1, @date2),@date1),@date2) as minutes_difference 	0
2475275	33590	querying two tables at once	select l.username, l.loginid, s.loginid, s.submissionid,   s.title, s.url, s.datesubmitted, s.displayurl from submission as s inner join login as l   on s.loginid = l.loginid where l.username = '$profile' order by s.datesubmitted desc 	0.00050766353589256
2476594	32299	put today + 3 working days (as default value) in a sql datetime field	select (dateadd(day,(3),getdate())) select (dateadd(day,(3),cast(floor(cast(getdate() as float)) as datetime))) 	0
2476648	30225	sql check constraint to prevent date overlap	select for update 	0.00619910852451711
2477561	2191	mysql: check if first character is _not_ a-z	select  * from    mytable where   title not rlike '^[a-z]' 	0.0851908785177631
2477893	8254	method to sort mysql results by an arbitriary letter (ie, show all rows starting with f first)	select id, state from sometable order by if(state = 'hi', 0, 1) asc, id desc; 	0
2480214	9522	sql: connecting tables that have no relation	select a.column, b.column from tablea a, tableb b 	0.0129922994190446
2480758	35204	group by and sum distinct date across 2 tables	select created, sum(status) as totalactive, sum(transactionamount) as totaldeposit from ( (   select   created,   status,   0 as transactionamount   from users ) union (   select   created,   0 as status,   transactionamount   from billing ) ) as x group by created 	0.000656287418840802
2481259	14513	is there any way to modify a column before it is ordered in mysql?	select value from unnamed_table order by expression_returning_decimal(value) 	0.109912330634577
2482658	22894	i have a kvp key value pair table, need sql to make it relational structure...!	select stat.id as id, status, age_group, travel from  (select id, value as status from kvp where key = 'status') as stat join (select id, value as age_group from kvp where key = 'age group') as age on stat.id = age.id join (select id, value as travel from kvp where key = 'travel') as trav on stat.id = trav.id; 	0.0207996967199904
2483368	38239	select mysql data using max	select distinct testcase from select_pass  where testcase not in (select testcase from select_pass where result = 'pass') 	0.0789099195074383
2484437	29305	displaying a group once in php mysql	select * from select_pass order by testcase 	0.0204962696711826
2485727	35063	how to search a mysql database for a specific string	select * from articles where article_title = '$searchquery' 	0.0089343454821017
2487503	948	mysql distinct query	select id,table1.name,table1.fid from table1 inner join  (select name,max(fid) as fid from table1 group by name) table2 on table1.fid=table2.fid and table1.name=table2.name 	0.310754602261566
2490021	8100	matching day in datetime field from sqlite	select * from thetable where date(thefield) = '2010-02-12'; 	0
2490344	9085	mysql - get all unique values of a column, check if has a specific value	select plf.filename, max(if(plf2.filename = plf.filename, 1, 0)) as inplaylist, max(plf2.fileindex) from playlistfiles plf left join playlistfiles plf2 on plf.filename = plf2.filename and plf2.playlistname = @playlistname group by plf.filename 	0
2494624	10173	counting consecutive items within sql server	select personid, count(*) from table t1 where active = 0 and emaildate >     (select max(emaildate) from table t2         where t2.personid = t1.personid and active = 1) group by personid 	0.00257833150115701
2495471	33546	a query for date within a year	select * from fis_historico_receita where data between now() - interval '1 year' and now() 	0.00511081154893575
2496502	36763	how can i sort one table by a column in another in mysql?	select items.id, items.tag, tags.name from items left join tags on items.id = tags.id order by tags.name 	0.000107734277961224
2497270	22252	how to create mysql query to find related posts from multiple tables?	select article_id, count(*) as common_term_count from        (       select article_id from tags where tag in           (select tag from tags where article_id = :yourarticle)       union all        select article_id from categories where category in          (select category from categories where article_id = :yourarticle)        ) as accumulator_table   group by article_id order common_term_count desc 	0
2497737	39676	get past data from sqlite3 database	select * from table where id > ((select max(id) from table) - 30) 	0.000240584805444912
2497738	38225	how to get date from week and day of the week in oracle	select to_char(        trunc(sysdate,'yyyy')        + ((20-1) * 7)        + (to_char(trunc(sysdate,'yyyy')           + ((20-1) * 7),'d')           - 5)        ,'"wk"ww dy dd-mon-yyyy') from dual; wk20 fri 21-may-2010 	0
2497746	6178	mysql - selecting how many "days old" a field is	select datediff(now(), ts.dateadded) as daysold   from tbl_stuff ts 	0.00013881984296384
2497776	28872	how to link a table to a field a in mysql server	select w.word, w.meaning, t.language, t.word    from word as w   join translation as t      on (w.id = t.word_id) 	0.0030557899692059
2499014	37882	how to calculate end and start week?	select columnname - (datepart(weekday, columnname) - 1) as week_start from table1 	8.95354164197153e-05
2499910	34835	how to find the worst performing queries in sql server 2008?	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_cpu_time desc 	0.277791894675418
2500568	40952	in mysql, how do i return a list of grouped items limited to a certain number of groups + unique items	select a.item_id, case when a.group_id <= 0 then null else a.group_id end group_id  from (     select distinct group_id, item_id from test.so_test where group_id is not null      union     (select  -item_id, item_id from test.so_test where group_id is null) )  a inner join (     select distinct group_id from test.so_test where group_id is not null      union     (select  -item_id from test.so_test where group_id is null)     order by group_id limit 0, 5 ) b on a.group_id = b.group_id order by case when a.group_id <= 0 then null else a.group_id end, a.item_id; 	0
2500572	39310	determining whether a month contains entries	select distinct     case         when extract(month from logdate) is  null then false         else true     end,     y as month from     mytable          right join          (select generate_series(1,12)) as x(y) on ((extract(month from logdate)) = y and extract(year from logdate) = '2009') order by      month asc; 	0
2501515	36821	sql server: how can i select from table to other format?	select  tablea.[effective date],  tablea.[employee name],  tablea.fieldvalue as title,a2.fieldvalue as department from tablea inner join  tablea as a2 on tablea.[employeename] = a2.[employeename] and  tablea.[effectivedate] = (select max([effectivedate]) from tablea as a3 where a3.[employeename] = tablea.[employeename] and a3.fieldtype = 'title') and  tablea.fieldtype = 'title' and  a2.fieldtype = 'department' 	0.00136535905146432
2501625	16837	how to join mysql tables	select user.name, user.address, user.comment from user union all select user_alias.alias, user.address, user.comment     from user inner join user_alias on user.name = user_alias.name order by name 	0.176041562492293
2502583	17206	tsql - how to join 1..* from multiple tables in one resultset?	select     l.*,     maddress1 = m.address1,     maddress2 = m.address2,     mcity = m.city,     mstate = m.state,     mzip = m.zip,     mcountry = m.country     baddress1 = b.address1,     baddress2 = b.address2,     bcity = b.city,     bstate = b.state,     bzip = b.zip,     bcountry = b.country from     tbl_location l     inner join tbl_address m         on l.mailingaddressid = m.mailingaddressid     inner join tbl_address b         on l.billingaddressid = b.billingaddressid where     l.locationid = @locationid 	0.000754701529931672
2503712	20399	mysql ignores the not null constraint	select @@global.sql_mode; select @@session.sql_mode; 	0.577684162496542
2504847	9227	returning a recordcount from a subquery in a result set	select     recordid,     groupidentifier,     count() as total,     sum(intactingasboolean = 1) as approved  from table where date_format(datevalue, '%y%m%d') between 'startdate' and 'enddate' group by groupidentifier 	0.076828598802531
2505951	39768	using sql to get the last reply on a post	select discussion_id, user_id, pubdate from tablename where discussion_id in (   select max(discussion_id)   from tablename   group by parent_id ) 	6.68689874053765e-05
2506463	687	group / user based security. table / sql question	select     * from     users u         left join     group_user_mappings g         on             u.user_id = g.user_id         inner join     acl         on             (acl.user_id = u.user_id or              acl.group_id = g.group_id) 	0.0802319162056821
2507299	4564	integer comparison as string	select * from table where checkvar like '''' + to_char(<num>,'999') + '%' 	0.295017148586421
2508338	10516	getting the sum of a datediff result	select     anothercolumn, sum(datediff(day, startdate, enddate)+1) as mytotal from         mytable where      (reason = '77000005471247') group by   anothercolumn 	0.00957606633213575
2509161	2689	difference between dates when grouping in sql	select distinct user_id  from mytable t1 inner join mytable t2 on t1.user_id = t2.user_id  where t1.date_of_purchase - t2.date_of_purchase <= 365 	0.00685581318692364
2509387	10323	mysql - union tables by unique field	select  @r := @r + 1 as id, name from    (         select  @r := 0         ) vars,         (         select  name         from    table1         union         select  name         from    table2         ) q 	0.00862042149229334
2510246	15470	"select 1 from (select 1 from table) q" does not working on local machine	select 1 from (select 1) q; 	0.65810381656641
2510705	37711	how to create conditions in mysql (use of 'if')?	select  * from    room join    room_types on      typeid = fk1_typeid where   double_bed = 1         and single_bed = 0         and roomno not in         (         select  fk1_roomno         from    room_booking         where   check_out >= '2010-04-02'                 and check_in <= '2010-04-03'                 and not canceled         ) 	0.123691884952629
2511230	15178	sql one table aggregation	select      company,             sum(coalesce(prod1, 0)) as total_prod1,             sum(coalesce(prod2, 0)) as total_prod2,             sum(coalesce(prod3, 0)) as total_prod3 from        sales   where       gendate = '2010-03-24'  group by    company 	0.0452777461471571
2513382	36024	php - disconnecting and connecting to multiple databases	select * from main_database.a_table.... update alternate_db.a_table set... replace into third_db.a_table... 	0.192089822417974
2515916	33619	make a range in postgres	select  * from    generate_series(1, 6) num 	0.0414496586974553
2516173	25226	sql statement to grab table names, views, and stored procs, order by schema	select      s.name as [schema],      o.type_desc as [type],     o.name as [name]  from     sys.all_objects o     inner join sys.schemas s on s.schema_id = o.schema_id  where     o.type in ('u', 'v', 'p')  order by     s.name 	0.0143628254290831
2516434	15261	sql: daily average of logins per hour	select concat(date_format(t.event_datetime, '%y-%m-%d %h'), ':00:00.000') as hr,          count(*) as cnt,          avg(*) as avg     from events_all_rpt_v1 t    where t.event_name = 'login'      and t.event_datetime between '2010-03-24' and '2010-03-17' group by concat(date_format(t.event_datetime, '%y-%m-%d %h'), ':00:00.000') order by hr 	0
2516545	21767	mysql group_concat	select  user_id, group_concat(class_name) from    users join    classes on      find_in_set(class_id, user_class) group by         user_id 	0.654312036496098
2518083	39987	in mysql set something similar to a limit based on a percentage	select  material from    (         select  material, @r := @r + 1 as rn,                 (                 select  count(*)                 from    tab                 ) as cnt         from    (                 select  @r := 0                 ) vars,                 tab         order by                 quantity desc         ) q where   rn < cnt div 2 	0.000838172946518039
2519940	16497	is it possible to "merge" the values of multiple records into a single field without using a stored procedure?	select key, group_concat(value) from table_name group by key 	0
2520531	3125	why would a sql query join on the same table twice with the same condition?	select *  from main_table  inner join secondary_table as sec on main_table.id = sec.fk 	0.0488132068881618
2521438	9443	postgresql table for storing automation test results	select cola, colb, colc from table... insert into table(cola, colb, colc) values ('x', 'y', 'z') 	0.174510885008347
2523125	35915	how to give default values for the sum, count if no data exist in mysql query which uses group by?	select f.period as month,        ifnull(sum(p.revenue * ((100-q.rate)/100)),0) as revenue,        count(distinct q.label) as tot_stmt    from files f         left join reports p on f.id = p.file_id        left join rates q on f.period = q.period        left join albums a on q.album_id = a.id and p.upc = a.upc  where f.period in ('2010-06-01','2010-05-01','2010-04-01','2010-03-01')         and f.period_closed = true  group by month order by month desc 	0.000983531603187741
2523563	7253	conditions on count in a select	select     missioneid,     sum(case when [type]=1 then 1 else 0 end) as count1,     sum(case when [type]=2 then 1 else 0 end) as count2,     sum(case when [type]=3 then 1 else 0 end) as count3 from     [table] group by     missioneid 	0.0510170855166867
2524894	24337	assign table values to multiple variables using a single select statement and case?	select          @variablethefirst =          case             when descriptor = 'alpha' then tbl.systemid             else @variablethefirst         end,     @variablethesecond =          case             when descriptor = 'beta' then tbl.systemid             else @variablethesecond         end,     @variablethethird =          case             when descriptor = 'epsilon' then tbl.systemid             else @variablethethird         end from greekalphabetastic tbl 	0.00698972749545488
2525049	39903	show last 4 table entries mysql php	select * from 'movielist' order by 'dateadded' desc limit 4; 	0
2528591	17824	how to number the datas from mysql	select dbcountry, (select count(*) from tablecountry t2 where t2.dbcountry <= t1.dbcountry)  as rownum from tablecountry t1 order by dbcountry 	0.000368187305364997
2528669	6343	php mysql search	select * from newchap where (company like '%$company%' and company != '') or category like '%$cat%' 	0.433265625733797
2529334	30551	sql count() query for tables	select t1.fid,        count(t2.fid),        t1.fage from   table1 t1 inner join        table2 t2 on t1.fid = t2.fid group by t1.fid, t1.fage 	0.197029629686208
2529551	39044	mysql join 3 tables and count	select    t3.uid,    t3.industry,    count(t2.fid)  from    table3 t3  inner join    table2 t2 on t3.uid = t2.uid  group by    t3.uid 	0.10060044434235
2529659	8407	mysql count(*) left join group by - the number of files in a folder	select folders.directoryname,         count(files.fileid)  from folders left outer join       files on folders.directoryid = files.folder  group by folders.directoryid 	0.0686910776843115
2532173	18032	query to add a column depending of outcome of there columns	select  u.id,         u.first_name,         u.last_name,         case              when r.user_accepted = 1 and r.friend_accepted = 0                 then 'request sent'             else 'not sure'         end from    users u left join         relationships r on u.id = r.user_id 	0
2532404	38551	mysql query to get all entries with specific time, from php?	select * from something where timestamp > date_sub(utc_timestamp(), interval 1 day) 	0
2532960	26612	how add column order in careers table?	select *, case when job_order is null then 1 else 0 end as rank from job order by rank, job_order, job_id 	0.0113040391693943
2533310	20249	remove duplicates from left outer join	select s.no, l.key  from shop s  left outer join locatn l  on s.no = l.shop group by s.no, l.key 	0.693775081328203
2533890	28493	how to get an age from a d.o.b field in mysql?	select datediff(customer.dob, '2010-01-01') / 365.25 as age select date_format(from_days(datediff(customer.dob,'2010-01-01')), ‘%y’)+0 as age 	5.34943554158062e-05
2534253	40416	sql query - group by more than one column, but distinct	select b.cusid, b2.latestbidtime, b.amount  from bid b     join (         select cusid, max(bidtime) as latestbidtime         from bid         where sellid = 10         group by cusid) b2 on b.cusid = b2.cusid and b.bidtime = b2.latestbidtime where b.sellid = 10 	0.00943060523028303
2535191	33337	sql query - how to count values in a row separately?	select sum(case when secondperson='' then 1 else 2 end) from thetable; 	0.00932233347179559
2536159	4872	cannot sort a row of size 8130, which is greater than the allowable maximum of 8094	select distinct jr.jobreqid, jr.jobstatusid,    tbljobclass.jobclassid, tbljobclass.title,   jr.jobclasssubtitle, ja.jobclassdesc, ja.enddate, ja.agencymktgverbage,       ja.specinfo, ja.benefits,   s.minratesal, s.maxratesal, s.minratehour, s.maxratehour,   tbljobclass.statementeval,    jr.approvaldate, jr.recruiterid, jr.agencyid  from ( (tbljobreq as jr   left join tbljobannouncement as ja on jr.jobreqid = ja.jobreqid)  inner join tbljobclass on tbljobreq.jobclassid = tbljobclass.jobclassid) left join tblsalary as s on tbljobclass.salarycode = s.salarycode where (jr.jobclassid in  (select jobclassid from tbljobclass  where tbljobclass.title like '%family therapist%')) 	0
2537817	16566	fetch fourth maximum record from the table field	select min(salary) from    (select salary from empsalary order by salary desc limit 4) tmp; 	0
2538963	4827	sql top + count() confusion	select name from patients where diagnosis_id in ( select top(5) diagnosis_id from patients group by diagnosis_id order by count(diagnosis_id) desc ) 	0.553565625199079
2539858	17214	list all tables that are currently published for replication ms-sql	select * from sys.tables where is_replicated = 1 	0.000949174378836859
2540397	40622	regex for mysql query to match html entities	select body from email where body regexp '\&[a-z0-9a-z]+\;' 	0.45963085185967
2540846	39235	fill data gaps - union, partition by, or join?	select  count(r.incident_id),         crsjn.severity_cd,         crsjn.incident_typ_cd from    (             select  severity_cd,                     incident_typ_cd             from    severity_vw,                     incident_type_vw         ) crsjn left join         report_vw r     on  crsjn.severity_cd = r.severity_cd                          and crsjn.incident_typ_cd = r.incident_typ_cd group by crsjn.severity_cd,         crsjn.incident_typ_cd order by crsjn.severity_cd,         crsjn.incident_typ_cd 	0.321913590234637
2541043	18652	how to count each record in each table in a sql server 2005 database?	select   so.name, max(si.rows)  from     sysobjects so join     sysindexes si on so.xtype = 'u'  and      si.id = object_id(so.name)  group by so.name  order by 2 desc 	0
2543838	31748	best way to sort mysql results based on two columns and show results using pagination?	select * from data sort by first_column asc, second_column desc limit 20, 10 	0
2546053	40093	mysql difference between two timestamps in days?	select datediff('2010-10-08 18:23:13', '2010-09-21 21:40:36') as days; + | days | + |   17 | + 	0
2546503	3867	calculating multiple column average in sqlite3	select  (sum(q7)+sum(q33)+sum(q38)+sum(q40)+..+sum(q119))/ (count(q7)+count(q33)+count(q38)+count(q40)+..+count(q119)) as domain_score1  from survey 	0.00304543044416702
2547275	35716	mysql : using between in table?	select     time_id,     lesson_time from     mydb.clock where     lesson_time <= time(now()) order by     lesson_time desc limit 0, 1 	0.0554515553650719
2549316	13241	query design in sql - order by sum() of field in rows which meet a certain condition	select project.name from service left join project on project.id = service.project_id group by project_id order by sum(time_stop - time_start) limit 100 	0
2550174	28802	mysql query to return rows that are not in a set	select c.name       from contact c left join link l on l.contact_id = c.id                 and l.source_id = 8     where l.contact_id is null 	0.00278258689318836
2551573	31940	mysql nested set hierarchy with foreign table	select     sub.`name` as product,     group_concat(parent.`name` separator ' > ') as name from     categories as parent,     categories as node,     (select         p.`name` as name,         p.`categoryid` as category     from         categories as node,         categories as parent,         products as p     where         parent.`id`=4         and         node.`lft` between parent.`lft` and parent.`rgt`         and         p.`categoryid`=node.`id`) as sub where     node.`lft` between parent.`lft` and parent.`rgt`     and     node.`id`=sub.`category` group by     sub.`category` 	0.0516383060848849
2551644	15245	date problem in mysql query	select sum(transaction_amount) where year(transaction_date) = '2008' group by year(transaction_date) 	0.698455672146476
2551845	7407	aggregating mysql rows by day	select date(date), sum(payment) from payments group by date(date) order by date(date) desc 	0.00102717334087792
2552407	25497	sql server 2008: how to find trailing spaces	select col from tbl where col like '% ' 	0.250906229570303
2552862	8628	mysql query help in selecting top votes	select     posts.*,     pv.votes from     posts join     (         select post_id, count(*) as votes from posts_votes group by post_id     ) as pv on posts.id=pv.post_id where     posts.post_date >= unix_timestamp()-86400 order by     pv.votes desc; 	0.206061634870302
2555392	30506	oracle get previous day records	select field,datetime_field  from database where datetime_field > (sysdate-1) 	0
2556138	25957	selecting data from sql server table according to month	select * from whatevertable where convert(char(7),datahorainicio,120) = '2002-10' 	0
2556817	1090	how to find missing alpha values in sets of data within same table in sql	select distinct m1.wonumber from mytable m1 where     not exists (select 1/0                    from mytable m2                   where m2.resourceid = 'rw' and m1.wonumber = m2.wonumber) 	0
2558201	34220	sql query to get the sql server 2005	select     actors from     dbo.mytable m1 where     exists (select * from              dbo.mytable m2         where              m2.actors = 'bradpitt' and m1.filmname. = m2.filmname)     and     exists (select * from              dbo.mytable m3         where              m3.actors = 'rusellcrowe' and m1.filmname. = m3.filmname) 	0.182357628192656
2565599	19548	sql - joining multiple records to one record	select c.clientname, i.description, p.price,     stuff((select ', ' + a.agentname      from salesagent sa join purchasesalesagent psa on psa.agentid = sa.agentid     where psa.purchaseid = p.purchaseid     for xml path('')),1,2,'') as agents from client c  join purchase p on p.clientid = c.clientid join item i on i.itemid = p.itemid ; 	0.000140672770167827
2567460	25857	inner or left joining multiple table records into a single row	select   concat(f_first_name, ' ', f_last_name) as client_name,   group_concat(if(phone_type='work',f_phone_number, null)) as work_numbers,   group_concat(if(phone_type='home',f_phone_number, null)) as home_numbers from clients join phone   using (f_id) where phone_type in ('home', 'work') group by f_id; 	0.00061025686299158
2567708	6349	querying same lookup table with multiple columns	select   d1.val as column1,   d2.val as column2 from table1 t join data d1 on ( d1.dataid = t.col1 ) join data d2 on ( d2.dataid = t.col2 ) 	0.000915753916599603
2568668	20026	base 36 to base 10 conversion using sql only	select sum(position_value) from (   select power(36,position-1) * case when digit between '0' and '9'                                       then to_number(digit)                                      else 10 + ascii(digit) - ascii('a')                                 end           as position_value     from (           select substr(input_string,length(input_string)+1-level,1) digit,                   level position             from (select '01z' input_string from dual)             connect by level <= length(input_string)          ) ) 	0.00199842577370853
2569458	9953	can i do this in one mysql query?	select sum(if(columna=1, 1, 0) + if(columnb=1, 1, 0)) as ones,     sum(if(columna=2, 1, 0) + if(columnb=2, 1, 0)) as twos from mytable; 	0.676484352739049
2571888	10005	counting the most tagged tag with mysql	select t.*, count(tag_id) as code_count       from code_tags ct  left join tags t on ct.tag_id = t.id   group by tag_id   order by code_count desc      limit 1 	0.00663698419532529
2572496	37080	select top n records ordered by x, but have results in reverse order	select * from     (select top 10 * from footable order by x desc) as myalias  order by x asc 	0
2575286	30085	mysql group by with three tables	select `p`.*      , count(distinct comments.comment_id) as cmts      , posts_categories.*      , comments.*    from `posts` as `p`    left join `posts_categories`      on `p`.post_id = `posts_categories`.post_id    left join `comments`      on `p`.post_id = `comments`.post_id  group by `p`.`post_id` 	0.143093547356663
2575574	5244	sql get top 10 records by date	select top(10) count(bugtitle) as bugcount, bugtitle, errline from bugs where bugdate >= dateadd(day, -30, datediff(day, 0, getdate())) group by bugtitle, errline order by count(bugtitle) desc 	0
2576770	27555	how can join a query result set with an existing table?	select product_name, total from producttable x left outer join (select sum(qty) as total, productid from inventorytable      group by productid) y on x.productid = y.productid 	0.130404421840493
2577140	30826	mysql result set joining existing table	select products.*, sum(product.qty)  from products left outer join product  on product.id = products.pid group by pid 	0.0160941129240927
2577353	28715	grouping records with the same value	select messages.*, messages_conversations.subject from messages, messages_conversations where messages.to_user_id = '".$userid."' and messages_conversations.id = messages.conversation_id group by messages.conversation_id 	0.000193947498888316
2577500	17374	how understand one result set is subset of another in twomysql select result set?	select count( case when a.id = b.id then a.id end ) = count(b.id)      as is_a_containing_all_b from b left join a using(id) 	0.000340806911906075
2577510	4231	select proper columns from join statement	select t1.*, t2.my_col from table1 as t1 inner join table2 as t2 on t1.id = t2.id 	0.164347984926811
2577757	32878	selecting financial values from db stored as text	select   case when left(val, 1) = '('        then -1 * cast( replace((val, '(', ''), ')', '') as decimal(10,4))        else cast( val as decimal(10,4) )   end as num_val from   val_table 	0.000958894895440642
2579107	21132	mysql - join as zero if record not in	select a.foo, coalesce(b.bar, 0) as bar from a left outer join b on a.id = b.aid 	0.12382728252357
2579318	9582	group by as a way to pick the first row from a group of similar rows, is this correct, is there any alternative?	select user, max(score), time from test_results tr left outer join test_results tr2 on tr2.user = tr.user and tr2.time > tr.time where tr2.user is null group by user order by max(score) desc, time 	0.000371474306311703
2580014	13374	mysql - join matches and non-matches	select  *  from    interests i  left join  userinterests ui on i.interestid = ui.interestid  left join  users u on ui.userid = u.uiserid  and u.userid = ? 	0.645812822362451
2580036	5801	retrieving description item from sql server table column	select       [table name] = object_name(c.object_id),      [column name] = c.name,      [description] = ex.value   from       sys.columns c   left outer join       sys.extended_properties ex   on       ex.major_id = c.object_id      and ex.minor_id = c.column_id       and ex.name = 'ms_description'   where       objectproperty(c.object_id, 'ismsshipped')=0   order       by object_name(c.object_id), c.column_id 	0
2580298	29850	use a select to print a bunch of insert intos	select 'insert into attendancecodes (code, description, absent) values (''' + code + ''',''' + description  + ''',''' + absent''')'    from attendancecodes 	0.0932541187894086
2581795	1851	selecting the most common value from relation - sql statement	select top 1 software  from your_table  group by software order by count(*) desc 	0
2583742	26974	average of average in one row	select avg( col1 + col2 + col3)/3.0 from tbl 	0
2585462	13859	sql query: how to translate in() into a join?	select o.id, o.attrib1, o.attrib2 from table1 o join (   select distinct id from table1, table2, table3 where ... ) t1 on o.id = t1.id 	0.553039869297152
2588536	18432	sql query - get sums from two different levels of hierarchy	select p.projectid, t.plannedhourssum, a.assignedhourssum from projects p inner join (     select projectid, sum(plannedhours) as plannedhourssum     from tasks     group by projectid ) t on p.projectid = t.projectid inner join (     select t.projectid, sum(assignedhours) as assignedhourssum     from tasks t     inner join assignments a on t.taskid = a.taskid     group by t.projectid ) a on p.projectid = a.projectid 	5.69271447952014e-05
2589168	36530	retrieve sequence of data from different columns	select *  from table where 4 in (t0, t1, t2)    and 5 in (t0, t1, t2)    and 6 in (t0, t1, t2) 	0
2590169	24651	how to select a limited amount of rows for each foreign key?	select x.feedid   from (select t.feedid,                case when @feed != t.feedid then @rownum := 1 else @rownum := @rownum + 1 end as rank,                @feed := t.feedid           from table t           join (select @rownum := null, @feed := 0) r       order by t.feedid) x  where x.rank <= 3  order by x.feedid  limit 50 	0
2590498	24616	want to calculate the sum of the count rendered by group by option	select count( distinct id, companyid ) from transaction ; 	0.00123764655732473
2590621	6123	how to select distinct rows without having the order by field selected	select s.pid from students s join mentors m on s.pid = m.pid    where m.tags like '%a%' group by s.pid order by max(s.sid) desc 	0.000240358880258989
2590637	36248	mysql character mapping	select     replace(replace(         replace(replace(             replace(replace(                 replace(replace(                     replace(replace(                         replace(replace(                             name,                         'i', 'i'), 'ı' 'i'),                     'ö', 'o'), 'ö', 'o'),                 'ü', 'u'), 'ü', 'u'),             'ç', 'c'), 'ç', 'c'),         'ğ', 'g'), 'ğ', 'g'),     'ş', 's'), 'ş', 's')     as name from users where id=1 	0.50331898841653
2591073	3169	sum of times in sql	select personel_code, sum(datediff(minute, '0:00:00', convert(time, time, 8))) as totaltime from thistable group by personel_code 	0.0140687114149815
2591077	10103	sql server : get default value of a column	select * from information_schema.columns where.... 	0.000459726665063982
2593921	32275	db2 sql pattern matching	select     * from     mytable z where     left(myid, locate('.', myid)) = myname + '.' 	0.108129397282817
2594829	12347	finding duplicate values in a sql table	select     name, email, count(*) from     users group by     name, email having      count(*) > 1 	0.000460464551820271
2595978	3719	asp.net sql server select top n values but skip m results	select top 10        [id],        [itemdate],        [title],        [description],        [photo]      from [announcements]     where id <> (select top 1 id from announcements order by itemdate desc)     order by itemdate desc 	0.00132557944723365
2596914	20182	finding values from a table that are *not* in a grouping of another table and what group that value is missing from?	select ... from requireddocs as rd     cross join people as p where not exists(                 select 1                 from peoplesdocs as pd1                 where pd1.personid = p.personid                     and pd1.docid = rd.docid                 ) 	0
2597751	39106	designing a tag table that tells how many times it's used	select     tagid,count(*)     from yourtable     group by tagid 	0.00304012287375847
2598338	20605	sql count records in table 2 joins away	select t.name templatename, count(distict b.projectid) projectcount from templates t left outer join batches b on t.id = b.templateid group by t.id, t.name order by t.id 	0.00658252062801319
2598777	28846	excluding records based upon a one to many sql join	select * from details d where not exists (    select *    from items i   where i.detailid == d.id      and i.item = 'a') 	0
2601663	25318	sql join to only the maximum row puzzle	select u.networkidentifier, u.firstname, u.lastname,        h.hardwarename, h.serialnumber   from (select userid, max(assignedon) lastassignment           from hardwareassignments          group by userid) as t   join hardwareassignments as ha        on ha.userid = t.userid and ha.assignedon = t.lastassignment   join users as u on u.id = ha.userid   join hardware as h on h.id = ha.hardwareid  order by u.networkidentifier; 	0.00169899593382871
2602531	902	union on two tables with a where clause in the one	select recno, name from temp where signup='n' 	0.0129839571149935
2602774	41268	verify two columns of two different tables match exactly	select max(x.t1_missing_count) as t1_missing_count,         max(x.t2_missing_count) as t2_missing_count   from ( select count(distinct t1.col1) as t1_missing_count,        null as t2_missing_count   from table_1 t1  where t1.col1 not in (select distinct t2.col1                           from table_2 t2) union all select null,        count(distinct t2.col1),              from table_2 t2  where t2.col1 not in (select distinct t1.col1                           from table_1 t1)) x 	0
2602819	5037	mysql get data from another table with duplicate id/data	select table_1.id from table_1 left join table_2 on table_2.id = table_1.id where table_2.id is null 	0
2606323	28806	how to merge two tables based on common column and sort the results by date	select * from reply left join comment on reply.rev_id = comment.rev_id order by reply.post_date, comment.date_created 	0
2607478	32653	selecting data from table based on date 	select * from table where month(date) = 3 	0
2607778	6232	sql where clause conditional assignment based on another parameter	select * from myview where @viewallrecords or isclosed = @viewclosedrecords 	0.480032016718314
2612037	7055	mysql date range problem	select id, idnumber, thedatestart, thedateend  from clients  where idnumber = 'nb010203'  and '2010-04-09' between thedatestart and thedateend; 	0.087216477070965
2614674	13414	rails active record mysql find query having clause	select ifnull(sum(x), 0) as a from table 	0.072301622935869
2614969	36581	mysql gurus: how to pull a complex grid of data from mysql database with one query?	select jobtitle, companyname, employeename    from employee as e     right join company as c on e.companyid = c.companyid     right join job as j on e.jobid = j.jobid   where ...   order by j.jobtitle, c.companyname 	0.00170781974358229
2615432	18050	mysql one to many order by number found in joined table	select count(table_b.table_a_id) as count  from table_a  join table_b on table_b.table_a_id = table_a.id  group by table_b.table_a_id  order_by count desc 	0.00017683635586136
2616616	39125	effective retrieve for a voting system in php and mysql	select vote_comment_id, vote_type from vote where vote_user_id = 34513   and vote_comment_id in (3443145, 3443256, 3443983) 	0.0390179689532478
2617559	15584	mysql one-to-many query	select     u.user_id as user_id,     u.user_name as user_name,     i.info_id as info_id,     i.rate as rate,     c.contact_id as contact_id,     c.contact_data as contact_data from users as u left join info as i on i.user_id = u.user_id left join contacts as c on c.user_id = u.user_id 	0.611934960156432
2619126	3746	"date_part('epoch', now() at time zone 'utc')" not the same time as "now() at time zone 'utc'" in postgresql	select ((now() at time zone 'utc') at time zone '<your_time_zone>') at time zone 'utc'; 	9.40677175591122e-05
2619237	33168	get storage engine in mysql	select engine    from information_schema.tables   where table_schema = 'test'     and table_name = 'q'; + | engine | + | myisam | + 1 row in set (0.01 sec) 	0.182956716255579
2619682	2713	top 10 collection completion - a monster in-query formula in mysql?	select  userid,         us.totaluserscenario / gbd.total_scenarios collection_completion from    (             select  userid,                     game,                     count(scenario) totaluserscenario             from    userrecordedplays urp             group by    userid,                         game         ) userscenarios us inner join         gamebasicdata gbd on us.game = gbd.game order by collection_completion desc limit 10 	0.0613057704631134
2620153	20318	how do i do a where on the count(name) produced by a group by clause?	select topic, count(name) as counter from blah group by topic having count(name) <> 1 	0.673206642133771
2622272	29425	shred xml with variable number of nodes	select      authorlist.value('(forename/text())[1]', 'varchar(max)') as forename,     authorlist.value('(lastname/text())[1]', 'varchar(max)') as lastname,     authorlist.value('(initials/text())[1]', 'varchar(max)') as initials from      xmls cross apply        xml.nodes(' 	0.014222483890146
2625212	7615	mysql count() multiple columns	select tag, count(*) from (     select tag_1 as tag     union all     select tag_2 as tag     union all     select tag_3 as tag ) as x (tag) group by tag order by count(*) desc 	0.0172116279897036
2626105	9698	mysql: is it possible to compute max( avg (field) )?	select user_id, cat_id, max(avg_rate) from (     select entry_id, user_id, cat_id, avg( rating ) as avg_rate     from entry_rate     group by entry_id, user_id, cat_id) t group by user_id, cat_id 	0.743966857736921
2626477	18271	generating mysql update statements containing blob image data	select concat( 'update `image` set thumbnail = ',                 0xc9cbbbccceb9c8cabcccceb9c9cbbb....,                 ' where id = ', id, ';' ) as update_statement   from image; 	0.509839646944245
2626760	13041	would this prevent the row from being read during the transaction?	select * from tbl with updlock where id=@id 	0.0677164622336287
2627083	40367	php fetch rows from multiple mysql tables	select * from thread t inner join post_display pd on pd.threadid = t.threadid      where t.threadid = 2    order by t.threadid desc 	0.000167309279217853
2628159	3314	sql - add up all row-values of one column in a singletable	select sum(size) as overallsize from table where bla = 5; 	0.000303503850973482
2629211	36265	can we list all tables in msaccess database using sql?	select * from msysobjects where type=1 and flags=0 	0.0602390577328678
2629534	14961	getting the 'date' out of a datetime field in sql server	select convert(date, getdate()) 	0.00065329780948223
2629574	28946	linqpad / sqlite version info and foreign key support	select distinct sqlite_version() from sqlite_master; 	0.0247400075018276
2630433	11152	how do i return count and not count in a sql query?	select  team, sum(decode(isnew, 'n', 1, 0)), sum(decode(isnew, 'y', 1, 0)) from    mytable group by         team 	0.15618907496074
2630711	7116	help reading binary image data from sql server into php	select hex(image) from table; 	0.020280081618818
2631230	26827	how to select the record contains max(some_field) within group(group by)	select a.* from table_a a inner join (     select another_field, max(some_field) as maxsomefield     from table_a      group by another_field ) am on a.another_field = am.another_field and a.some_field = am.maxsomefield 	0.00227857392053615
2632793	27648	mysql - retrieve results by date proximity	select * from `calendar_table` where `date_column` = (select `date_column` from `calendar_table` order by abs(`date_column` - unix_timestamp()) asc limit 1) 	0.00459304841082423
2633111	31114	sql group by and join	select * from (     select t.*, (       select top 1 id        from message        where parentthreadid = t.id        order by datecreated desc      ) as messageid     from messagethread t   ) tm   left join message m on tm.messageid = m.id 	0.605152658784124
2633224	23370	sql query on table that has 2 columns with a foreign id on the same table	select m.id, away.name, home.name from match m inner join team away on away.id = m.awayteam_id inner join team home on home.id = m.hometeam_id 	0
2640575	19837	mysql: 4 table "has-many-through" join?	select a.*  from trucks t inner join boxes b on t.id = b.truck_id inner join apples a on b.id = a.box_id where t.owner_id = 34 	0.344519675976778
2642326	21073	group by, order by, with join	select * from (   select     topic.topic_title, comments.id, comments.topic_id, comments.message   from comments   join topic on topic.topic_id=comments.topic_id   where topic.creator='admin'   order by comments.time desc) derived_table group by topic_id 	0.673887753291298
2642504	2130	scd2 + merge statement + sql server	select (list of fields) from (merge dm.data_error.error_dimension ed        using @dataerrorobject obj       on(ed.error_code = obj.error_code and ed.data_stream_id = obj.data_stream_id)    ....... 	0.746568440821884
2643729	24992	how to combine specific column values in an sql statement	select ep,    case     when ob is null and b2b_ob is null then a     when ob is not null or b2b_ob is not null then b     else null   end as type from table; 	0.00286771680077145
2644851	33887	"select distinct" ignores different cases	select distinct col1 collate sql_latin1_general_cp1_cs_as from dbo.mytable 	0.165695504035714
2645733	11247	how can i get the total from the four different table in single query	select sum(val) from (     select sum(col1) as val from table1 where criteria1 = 'x'     union all     select sum(col2) from table2 where criteria2 = 'y'     union all     select sum(col3) from table3 where criteria3 = 'z'     union all     select sum(col4) from table4 where criteria4 = 'w' ) newtbl 	0
2645948	27272	walking through an sqlite table	select * from products order by name limit 10000 offset 10000; 	0.267649509738632
2647111	22200	order keywords by frequency in php mysql	select keyword, count(*) freq  from keywordtable  group by keyword  order by freq desc 	0.106662817412191
2649134	33046	mysql union query from one table + order by	select `text` from (     select `text`, `is_new_fr` as `is_new`     from `comments`     where user_fr = '".$user."'     and archive = '1'     union     select `text`, `is_new_to` as `is_new`     from `message`     where user_to = '".$user."'     and archive = '1' ) order by `is_new` desc 	0.0102309165545472
2649179	140	sql - multiple joins to one table - two values from two keys	select     games.game_id,     games.game_date,     pa.player_name as 'player_a_name',     games.player_a_score,     pb.player_name as 'player_b_name',     games.player_b_score from games inner join players pa on (games.player_a_id = pa.player_id) inner join players pb on (games.player_b_id = pb.player_id) 	0
2649471	28398	possible to sort via two time stamps and display same row twice	select * from ((select area, item, starttime as eventtime from tasks) union (select area, item, endtime from tasks)) as t order by eventtime 	0
2650154	15373	how can i allow null values in mysql	select *   from users   where (username ='$username' or username is null)  and user_id <> '$user_id' 	0.220901533014763
2650638	6255	sql query to get this result	select  coalesce(homephone, mobilephone, workphone) contactphone from    users 	0.419205831611691
2650718	26116	how to get this done in mysql?	select pref.*,group_concat(preflocation.name)  from pref, preflocationid, preflocation  where pref.locationid=preflocationid.pref and preflocation.id=preflocationid.location group by pref.id 	0.594123436372173
2653441	36693	having a number in	select * from table where find_in_set('4',hidden); 	0.0391794426931091
2656505	38373	max value amongst 4 columns in a row	select id, greatest(score1, score3, score3, score4) as col_value,        case greatest(score1, score3, score3, score4)           when score1 then 'score1'          when score2 then 'score2'          when score3 then 'score3'          when score4 then 'score4'        end as col_name from test_scores please let me know if there is a better solution. 	8.35136176724334e-05
2656701	12691	get 10 most entered entries	select value, count(value) as times from table  group by value order by times desc limit 0,10; 	0
2659114	16224	mysql query query	select hostname, linkedhost_id from rels, hostlist where host_id = id; 	0.673719300560482
2659253	7979	how to select the last record from mysql table using sql syntax	select *  from table_name order by id desc limit 1 	0.000109241560651624
2659720	30720	how do i select the most recent entry in mysql?	select * from posting where .... order by date_added desc limit 1; 	0
2662137	19738	sql query to show what has been paid each month	select p.name, d.year, d.month, p.paid/(datediff(m, p.startdate, p.enddate) + 1) from (     select year(date) as year, month(date) as month, min(date) as monthbegin, max(date) as monthend     from datestable     group by year(date), month(date) ) d left join payment_detail p on d.monthbegin<p.enddate and d.monthend>p.startdate 	0
2663459	37871	how does one concatenate database values into a string?	select   c.firstname,   c.lastname,   concat(c.firstname, ' ', c.lastname) as fullname  from   customer c  where   c.cust_id = 1; 	0.000115565351332496
2663692	35218	what command is used in mysql to look at the table and give tips?	select  * from `table` procedure analyse ( ) 	0.44494869898374
2666129	33948	how to combine two sql queries?	select a.item_id, a.stock_balance, b.pcs_ordered, b.number_of_orders from     (select stock.item_id, sum(stock.pcs) as stock_balance      from stock      group by stock.item_id) a left outer join     (select stock.item_id, sum(stock.pcs) as pcs_ordered,              count(stock.item_id) as number_of_orders      from stock     where stock.operation = "order"     group by stock.item_id) b on a.item_id = b.item_id 	0.0203538541708872
2666241	5843	tricky sql - select non-adjacent numbers	select * from mytable a where not exists   (select *   from mytable b   where a.name = b.name   and a.sectionid = b.sectionid + 1) 	0.740184474958903
2667520	34318	mysql - extracting time in correct format	select     time_format(`time`, '%h:%i') as time from     ... 	0.0507114550905326
2668924	11852	storing dates i train schedule mysql	select ... where month(deptime) = 4 and day(deptime) = 19; 	0.0999904047366898
2669180	13514	sql view creation	select    foouniqueid, year, name, worth from   foo join   bar on foo.year = bar.value where   bar.name = 'year' 	0.45541338886259
2670195	608	tsql: finding unique entries in a single table	select    name from    mysetobject group by    name having    min(num) <> max(num) 	0
2670254	26127	select from table and function	select (select store_id from table(user2.f_get_store(city_id, transaction_id))) store_id, city_id, transaction_id from table_name; 	0.0496656523866396
2672147	34528	identifying which value of a multi-row inserts fails foreign key constraint	select id from referencedtable where id not in (1, 4, 7) 	0.000118946205953184
2672321	39994	designing a game database	select  u.displayname opponentsname,         gsyours.score myscore,         gs.score opponenetsscore from    gamescores gs inner join         (             select  gs.gid,                     gs.uid,                     gs.score             from    gamescores gs              where   gs.uid = youruserid         ) gsyours   on  gs.gid = gsyours.gid                     and gs.uid <> gsyours.uid inner join         users u on gs.uid = u.uid inner join               gamehistories gh on gs.gid = gh.gid and gh.pubid = whatyourequirehere 	0.240873094863337
2674823	16666	select fields containing at least one non-space alphanumeric character	select * from  tbl_loyalty_card  where trim(customer_id) != ''; 	0.000636244107326114
2676626	17722	find out how much storage a row is taking up in the database	select [raportid]                       ,datalength([raportplik]) as 'filesize'                       ,[raportopis]                       ,[raportdataod]                       ,[raportdatado] from [database] 	0.00707209825021508
2676741	24226	oracle - return shortest string value in a set of rows	select columna from (   select columna   from tablea   order by length(columna) asc ) where rownum = 1 	9.59732381563262e-05
2678441	13852	efficient sql to count an occurrence in the latest x rows	select count(*) as cnt from a where     rowid > (select max(rowid)-20 from a)     and i=0; 	0
2678869	38595	truncate date to fiscal year	select add_months(trunc(add_months(sysdate,-3),'yyyy'),3) from dual; 	0.00115415925899359
2679344	28236	list hits per hour from a mysql table	select * from visitors where timestamp between unix_timestamp()-3600*1 and unix_timestamp()-3600*0; select * from visitors where timestamp between unix_timestamp()-3600*2 and unix_timestamp()-3600*1; select * from visitors where timestamp between unix_timestamp()-3600*3 and unix_timestamp()-3600*2; select * from visitors where timestamp between unix_timestamp()-3600*4 and unix_timestamp()-3600*3; select * from visitors where timestamp between unix_timestamp()-3600*5 and unix_timestamp()-3600*4; select * from visitors where timestamp between unix_timestamp()-3600*6 and unix_timestamp()-3600*5; 	0
2679865	4920	return a value if no rows are found sql	select case when count(1) > 0 then 1 else 0 end as [value] from sites s where s.id = @siteid and s.status = 1 and        (s.webuserid = @webuserid or s.allowuploads = 1) 	0.00012336981201535
2679932	9381	ordering by multiple columns in mysql with subquery	select topic_title, topic_id       from comments       join topic on topic.topic_id = comments.topic_id       where comments.user = '$user' and comments.timestamp > $week       group by topic_id order by max(timestamp) desc 	0.220808922168542
2683681	29872	query takes time on comparing non numeric data of two tables, how to optimize it?	select <specify fields here> from callsrecords r inner join contact c on r.callfrom = c.phonenumber   union all select <specify fields here>     from callsrecords r inner join contact c on r.callto = c.phonenumber  union all select <specify fields here>  from callsrecords r inner join contact c on r.pickup = c.phonenumber 	0.00931362345241232
2684043	22253	mysql - combine two fields to create a unix timestamp?	select unix_timestamp(concat(startdate, ' ', starttime)) as start; 	7.43934657275792e-05
2686254	9578	how to select all records from one table that do not exist in another table?	select t1.name from table1 t1 left join table2 t2 on t2.name = t1.name where t2.name is null 	0
2686353	477	how to see contents of check constraint on oracle	select constraint_name,search_condition  from all_constraints where table_name='name_of_your_table' and constraint_type='c'; 	0.000592083690797287
2687051	22414	outer select column value in joined subquery?	select table1.id,         (select count(*) from table2 where table2.lt > table1.lt and table2.rt < table1.rt) as cnt from table1; 	0.119115669793892
2687248	2571	how to get last 12 digits from a string in mysql?	select right(field, 12); 	0
2687715	5424	how to construct this query? (ordering by count() and joining with users table)	select u.user, count(s.score) as wins from users u inner join scores s      on u.user_id = s.user_id  where s.score = 1 group by u.user_id (and any other columns you need from the user table) order by wins 	0.343758536726629
2688589	13307	resultset comparison utilities	select count(*) from      ( select * from q1       intersect       select * from q2 ) / 	0.595884531979931
2689013	15705	how to format a date in sql server 2008	select convert(char(10), getdate(), 126) 	0.123652119705834
2689297	13	mysql query different group by	select * from `products`  group by case `configurable` when 'yes' then `id_configuration` else `id` end 	0.11648156239712
2689766	6710	how do you check if a certain index exists in a table?	select *  from sys.indexes  where name='yourindexname' and object_id = object_id('yourtablename') 	0.000835801564741815
2691262	24562	combining in and not in in sql as single result	select u.user_id, the_matches.matches, the_nonmatches.nonmatches from user u  left join  (         select ug.user_id, count(distinct goal_id) as matches     from user_goal ug     where ug.user_id!=@userid     and goal_id in (select iug.goal_id from user_goal iug where user_id=@userid)     group by user_id      order by matches desc limit 4 ) as the_matches on the_matches.user_id = u.user_id left join (     select ug.user_id, count(distinct goal_id) as nonmatches     from user_goal ug     where ug.user_id!=@userid     and goal_id not in(select uggg.goal_id from user_goal uggg where user_id=@userid)      group by user_id  ) as the_nonmatches on the_nonmatches.user_id = u.user_id 	0.123906941480268
2691408	9891	sql query count on column information	select sum(betrag / (  4-case when wal = 2 then 1 else 0 end   -case when jon = 2 then 1 else 0 end   -case when al  = 2 then 1 else 0 end   -case when ben = 2 then 1 else 0 end )) as "w->a" from abrechnung 	0.0306595212426121
2691441	579	sql server copy all rows from one table into another i.e duplicate table	select * into archivetable from mytable delete * from mytable 	0
2692090	18563	anyway to get a value similar to @@rowcount when top is used?	select top 5  *  from person  where name like 'sm%' order by id desc declare @r int select @r=count(*) from person  where name like 'sm%' select @r 	0.0113966161483827
2692340	14028	mysql count all rows per table for in one query	select table_name, table_rows from `information_schema`.`tables` where `table_schema` = 'your_db_name'; 	0
2694581	29695	retrieve input and output parameters for sql stored procs and functions?	select parameter_name, data_type, character_maximum_length, parameter_mode, numeric_precision, numeric_scale from information_schema.parameters where specific_name = @chvprocname order by ordinal_position 	0.537262366489496
2696094	1409	using or in mysql and merging columns	select f.friend_userid as userid from friends f where f.userid = 1  union select f.userid as userid from friends f where f.friend_userid = 1; 	0.0286683428851752
2698546	33696	how to create a sql function using temp sequences and a select on postgresql8	select case when i=1 then nombre_apellidos end as nomapeacc1, ... from pit_people p cross join generate_series(1,5) s(i) 	0.349294901582641
2700354	33318	left join not returning all rows	select pr.*, pr7.value as `room_price_high`   from `jos_hp_properties` pr        left join `jos_hp_properties2` pr7         on pr7.property=pr.id    and         pr7.field=23 	0.198128741077755
2700611	40033	display a ranking grid for game : optimization of left outer join and find a player	select p.nickname as nickname , sum(if(key = "for", value,0)) as `for` , sum(if(key = "int", value,0)) as `int` , sum(if(key = "agi", value,0)) as `agi` , sum(if(key = "lvl", value,0)) as `lvl` from player p left outer join simplevalue v1 on p.id=v1.playerid group by p.nickname order by v1.value 	0.428530970529118
2701394	28922	what is a sql statement that can tally up the counts even including the zeros? (all in 1 statement)	select g.gift_id, count(v.gift_id) as given_count from gifts as g left outer join gifts_given as v using (gift_id) group by g.gift_id; 	0.00674834283875836
2701652	7477	can't figure out how to list all the people that don't live in same city as	select person.firstname, person.lastname, person.city, person.state from person left join location on (person.city = location.city and person.state = location.state) where location.city is null order by person.lastname 	0
2703060	1901	matching an ip address with an ip range?	select * from ranges where inet_aton(ipaddress_s)<inet_aton('4.100.159.0') and inet_aton(ipaddress_e)>inet_aton('4.100.159.5') 	0.00337158576339771
2703828	17406	sql: optimize insensive selects on datetime fields	select i.id, i.name, s.execute_at from items i inner join scheduled_items s on s.item_id = i.id left join reviewed_items r on r.scheduled_items_id = s.id where r.id is null 	0.793111208590446
2706116	6816	in sql, we can use "union" to merge two tables. what are different ways to do "intersection"?	select t1.number from t1 inner join t2 on t1.number = t2.number 	0.0134792973053187
2709013	39708	calculation of derived field in sql	select namelast, namefirst, (height/12) as heightininches  from master  order by namelast, namefirst, height 	0.0881757487873347
2709519	21702	sql 2005: select top n, group by id with joins	select * from (select  d.name, u.name, u.dateadded, row_number() over (partition by d.depid order by u.dateadded desc) as rowid from department as d join depusers as du on du.depid = d.depid join users as u on u.userid = du.userid) as t where t.rowid <= 3 	0.014824952564077
2709890	3382	mysql join with a "bounce" off a third table	select n.product_name, c.company_name  from names n left outer join products p on n.product_id = p.product_id left outer join companies c on p.company_id = c.company_id where n.product_id = '12345' 	0.0753617664049464
2709929	26471	query that ignore the spaces	select * from mytable      where replace(username, ' ', '') = replace("john bob jones", ' ', '') 	0.126076512130258
2711040	39509	using a temp table in a view	select  temp.*,          temp1.areaattimeofincident  from    (             select *              from vwincidents         ) temp  left outer join          (             select  vwincidents.incidentcode,                      employeecode,                      empos.pos_l4_cda as areaattimeofincident              from    vwincidents  inner join                      empos   on vwincidents.employeecode = empos.det_numbera               where   empos.pos_startc <  vwincidents.incidentdate              and     (                            empos.pos_endd > vwincidents.incidentdate                          or empos.pos_endd is null                     )         ) temp1     on  temp.incidentcode = temp1.incidentcode                   and temp.employeecode = temp1.employeecode  order by incidentcode 	0.115771700752582
2712282	7117	sql join to grab data from same table via intermediate table	select  sc.*, sp.* from    sites sc join    site_h h on      h.parentof = sc.page_id join    sites sp on      sp.page_id = h.page_id where   sc.page_id = @mypage 	8.90002818405648e-05
2712852	25223	get all or part result from sql using one tsql commnd	select   *  from     table  where    coalesce(col1, '') like coalesce ('%'+@col1val+'%', [col1]) 	0.000415306928149313
2713352	17689	mysql order by offset	select    *  from   mytable  order by   case when name > 'f' then 0 else 1 end,   name 	0.42219384332488
2714446	6580	complex sql query... 3 tables and need the most popular in the last 24 hours using timestamps!	select  id, count(*) as cnt from    (         select  id         from    table1         where   time >= now() - interval 1 day         union all         select  id         from    table2         where   time >= now() - interval 1 day         union all         select  id         from    table3         where   time >= now() - interval 1 day         ) q group by         id order by         cnt desc limit 5 	0
2714787	21736	mysql setting default value to be items auto increment key	select id, coalesce(position, id) as position ... 	0.000327146639791295
2715576	19888	fetch last item in a category that fits specific criteria	select *       from categories as c left join (select * from articles order by id desc) as a        on c.id = a.id_category       and /criterias about joining/     where /more criterias/  group by c.id 	0
2718151	28790	creating sql server index on a nvarchar column	select collation_name from information_schema.columns where table_name = 'wordsindex'     and column_name = 'words' 	0.521768545181528
2719242	2954	sql default value	select id, 0 as value_default from mytable 	0.0475012939860811
2720422	35678	sql server trimming float data type	select @final = convert(varchar(80), cast(@lon as decimal(30,15))) 	0.307741023929558
2721280	39008	generate several sql insert from an sql select sentence	select  'insert table (col1, col2)         values (''' + stringcolumn + ''', ' + cast(intcolumn as varchar) + ')' from    sourcetable 	0.0221507192726369
2721307	20350	get the avg of two sql access queries	select avg(fev1_act) from     (select top 2 fev1_act from sheet1 order by fev1_act desc) 	0.00773763864652252
2722214	30552	mysql: get average of time differences?	select  date(start) as startdate, avg(time_to_sec(timediff(end,start))) as timediff from    sessions group by         startdate 	0
2722942	36823	help with two sql queries	select  * from    candidate c where   exists         (         select  null         from    qualification q1         join    qualification q2         on      q2.candidateid = q1.candidateid                 and q2.datestarted = q1.datestarted                 and q2.dateended = q1.dateended                 and q2.instituteid <> q1.instituteid         where   q2.candidateid = c.candidateid         ) 	0.795981854781346
2723168	13322	find all the varchar() fields in sql server?	select * from information_schema.columns where data_type = 'varchar' 	0.00109792465276033
2723213	25901	how to check the existence of multiple ids with a single query	select firstname   from people p    where not exists (select 1 from otherpeople op where op.firstname = p.firstname) 	0
2725807	33342	how to find n consecutive records in a table using sql	select distinct o1.customer, o1.product, o1.datum, o1.sale   from one o1, one o2   where (o1.datum = o2.datum-1 or o1.datum = o2.datum +1)   and o1.sale = 'no'    and o2.sale = 'no';   customer | product |   datum    | sale   x        | a       | 2010-01-03 | no  x        | a       | 2010-01-04 | no  x        | a       | 2010-01-06 | no  x        | a       | 2010-01-07 | no  x        | a       | 2010-01-08 | no 	0
2730913	15095	postgesql select from 2 tables. joins?	select  list_id, phone, email from    (         select  list_id, null as phone, email, 1 as set_id         from    email_lists         union all         select  list_id, phone, null as email, 2 as set_id         from    phone_lists         ) q order by         list_id, set_id 	0.0208704332292982
2731135	11456	sql query to find duplicates not returning any results	select [card number],[customer name],[acct nbr 1],[acct nbr 2], numoccurences from debitcarddata.dbo.['atm checking accts - active$'] as accmailtbl inner join  (select [acct nbr 1],count([acct nbr 1]) as numoccurences from debitcarddata.dbo.['atm checking accts - active$'] group by [acct nbr 1]  having (count([acct nbr 1])>1)) acctbl on acctbl.[acct nbr 1]=accmailtbl.[acct nbr 1] 	0.254488606290802
2732356	38355	list of all tables with a relationship to a given table or view	select     name, object_name(parent_object_id) 'table' from      sys.foreign_keys where      referenced_object_id = object_id('your-referenced-table-name-here') 	0
2733372	34611	conditionally summing the same column multiple times in a single select statement?	select date,      sum(case when deploymenttype_id = 1 then numemployees else null end) as "total permanent",      sum(case when deploymenttype_id = 2 then numemployees else null end) as "total temp",      sum(case when deploymenttype_id = 3 then numemployees else null end) as "total supp" from tbldeployment group by date 	0
2733830	11590	table rows with identifying parameter in each row sql server 2008 into single row	select a.pageid, a.value as title, b.value as description, c.value as author from table a     left outer join table b on a.pageid = b.pageid and b.key = 'description'     left outer join table c on a.pageid = c.pageid and c.key = 'author' where a.key = 'title' 	0
2734134	10012	postgres query optmization	select userid, 'ismaster' as name, 'false' as propvalue from user  where not exists   (select * from userprop   where userpop.userid = user.userid     and name = 'ismaster'); 	0.725841969578097
2734366	11773	mysql top count({column}) with a limit	select ip, count(*) from table group by ip order by count(*) desc limit 5 	0.445989228957174
2734812	469	how to convert the datetime value to hour	select right(convert(varchar(7), myvalue, 100), 7) 	0.000236047802649486
2735619	7716	getting a sorted distinct list from mysql	select t1.fid, t1.cd from (   select fid, max(changedate) as cd   from sorted   group by fid ) as t1  where 1  order by t1.cd desc 	0.000164999662536961
2735628	17272	time calculations with mysql timediff	select id, timediff( stop1, start1 ) , timediff( stop2, start2 ) , addtime( timediff( stop1, start1 ) , timediff( stop2, start2 ) ) , time_format( addtime( timediff( stop1, start1 ) , timediff( stop2, start2 ) ) , '%h:%i' ) as totaltime from times group by id 	0.168403351270984
2736319	33444	how to check group for containing certain elements in sql?	select `id` from `table` where `num` in (4, 5, 7) group by `id` having count(*) = 3 	0.000181796132655854
2736426	8020	difference in select for update of ... in oracle database 10g and 11g	select b.ename into   v_ename from   bonus b, emp e, dept d where  b.ename = 'scott' and    b.ename = e.ename and    d.deptno = e.deptno for update of b.ename; 	0.0575719334037505
2736769	31185	sql query number of occurance	select c.* from cars c     join     (         select carcode          from articles         where accepted = 1         group by carcode         having count(carcode) > 1     ) a on c.code = a.carcode 	0.0145708812946081
2737793	22542	group by with value of another column	select a.idarticle from (   select idcar , max(createddate) as max_date   from articles   group by idcar  ) max inner join articles a on a.idcar = max.idcar and a.createddate = max.max_date 	0.000669126195175261
2739324	37235	sql server > query > column names	select a, b, c, (c*2)+d as d from (select a.a, a.b, a.a+a.b as c, a.d as d from table a) table_alias_for_view 	0.0542205560892334
2739482	15329	query for props list with or without values	select *  from table_materials as m inner join table_props as p  left join table_material_props as mp  on p.prop_id = mp.prop_id  and  m.material_id = mp.material_id; order by p.prop_name 	0.145075144446186
2740413	411	mysql query the latest date	select        sh.dts,       cast( if( preagg1.totalpercatsort = 1, sh.status, ' ' ) as char(20))           as singlestatus,       sh.category,       sh.sort_by,        u.initials as initals     from        database1.table1 as sh,       database2.user as u,       ( select                t1.category,                t1.sort_by,                max(dts) maxdts,               count(*) totalpercatsort            from                database1 t1            group by                t1.category,                t1.sort_by ) preagg1    where          sh.userid = u.userid       and sh.sort_by = preagg1.sort_by      and sh.category = preagg1.category      and sh.dts = preagg1.maxdts      and id = 123456  ?? should this actually be the userid column ??   order by       sort_by,       category 	0.00266988651737784
2740785	15742	mysql select multiple rows in join	select * from user_table where userid = @userid; select * from photos_table where userid = @userid; 	0.0442224536894426
2742073	28920	sql select statement with increment	select      avg(listingprice),      avg(sellingprice),     count(listingdate),     month(sellingdate) as month,     year(sellingdate) as year from `rets_property_resi`  where area = '5030'     and status = 's'     and sellingdate <= now() group by year, month order by year desc, month desc limit 0,12 	0.320663507134498
2742736	4476	how do i combine 3 date columns from 3 tables in foxpro sql?	select         "purchase   " as transtype,       t1.adate as transdate    from       yourtablea t1    where        t1.idkey = ?somevaluesuchasaccount    order by       transdate union all select       "adjustments" as transtype,       t2.bdate as transdate    from        yourtableb t2    where        t2.idkey = ?somevaluesuchasaccount union all select       "sales      " as transtype,       t3.cdate as transdate    from        yourtableb t3    where        t3.idkey = ?somevaluesuchasaccount 	6.86348439826807e-05
2743580	22928	mysql combining multiple rows into one row dependant upon a single field?	select ppf.page_id, prv.`name`, prv.surname, prv.email, prv.mobile, ppf.email, ppf.sms, group_concat(page_profile_noticetypes.noticetype) from page_registration_value as prv inner join page_profile_value as ppf on prv.page_id = ppf.user inner join page_profile_noticetypes on page_profile_noticetypes.page_id = ppf.page_id where ppf.sms = 1 or ppf.email = 1 group by prv.email 	0
2745573	38869	sql partial max	select  h, max(cnt) from    (         select  h, sum(q) as cnt         from    mytable         group by                 h, t         ) sq group by         h 	0.0844229574551546
2745651	38096	saving blob data from sqlite database to a file	select hex( receiver_data ) from cfurl_cache_blob_data where entry_id = 3501; 	0.0256910666979199
2749744	29313	how to search mulitple value seperated by commas in mysql	select * from searchtest where keyword like '%test2%' 	0.00238086993738326
2750706	473	creating a mysql view to select coloumns from different tables	select er.id, er.empid, er.custid, er.status, er.datereported, er.report, eb.name, cr.custname, cr.locid, cl.locname, di.deptname  from emp_report er  join emp_bio eb on eb.empid = er.empid join cust_record cr on cr.custid = er.custid join cust_loc cl on cl.locid = cr.locid join dept_id di on di.deptid = eb.deptid 	0.00350272510299405
2751780	36870	use a sql select statement to get parameters for 2nd select statement	select [storetransactionid],[transactiondate],[storeid] from storetransactions where storeid in (select storeid from store) 	0.148825959541544
2756370	7523	get me the latest change from select query in below given condition	select j1.* from jos_audittrail j1 left outer join jos_audittrail j2   on (j1.trackid = j2.trackid and j1.field = j2.field    and j1.changedonetime < j2.changedonetime) where j2.id is null; 	0.000129164447653692
2757895	26302	get column of a mysql entry	select @m := greatest(col1, col2),   case @m        when col1 then 'col1'        when col2 then 'col2'   end   from my_table 	0.00018646721296774
2758110	340	selecting two field in mysql with php	select username, power from table where upper(username) = upper('%s') and password='%s'"... 	0.00416737778498087
2758486	25915	mysql compare date string with string from datetime field	select * from `calendar` where date_format(starttime, "%y-%m-%d") = '2010-04-29'" 	0.000109959192344052
2759756	32662	is it possible to select exists directly as a bit?	select cast(    case when exists(select * from thetable where thecolumn like 'thevalue%')         then 1     else          0     end  as bit) 	0.697296470426048
2759806	17637	parse multiple filters in sql	select      cast(idx as varchar(100)) 'idx'     ,   value      ,   substring(value, 1, charindex('=', value)-1)  'first'     ,   substring(value, charindex('=', value)+1, len(value)-charindex('=',value)) 'second'     from common.splittotable(@s, ',')      where len(value) > 0 	0.533934149859966
2759938	23645	select subset from two tables and left join results	select *  from tablea   left join tableb on tablea.key = tableb.key      and tableb.key3 = "yyyy"  where tablea.key2 = "xxxx" 	0.00681612301089298
2760399	10765	replace always replacing null values	select isnull(nullif(charindex(' ',field),0),len(field)) 	0.194282514769708
2760559	224	exporting ms sql schema and data	select * from information_schema.tables 	0.489779411887324
2761150	28627	select using count in mysql	select tag, url, count(tag) from table group by tag, url 	0.208161262811159
2761468	25684	merging mysql row entries into a single row	select l.id, group_concat( t.title )     from listings l, tags t     where concat( '-', l.tags )  like concat( '%-', t.id, '-%' ) group by l.id ; 	0
2761719	39198	joining two tables using a count	select     a.email_id,     e.subject,     e.body,     coalesce(count(a.id),0) as num_attachments from     emails e     left outer join attachments a     on e.id = a.email_id group by      a.email_id, e.subject, e.body 	0.00807849933167078
2763379	30946	getting the primary key back from a sql insert with sqlite	select last_insert_rowid() 	0.00181267264047707
2764231	8276	sql query: sum values up to the current record	select t1.id, t1.transactiondatetime, amount, (  select sum(amount)   from dbo.table1 as t1   where t1.transactiondatetime <= t0.transactiondatetime ) as balance from dbo.table1 as t0 	9.58867678560662e-05
2766116	16327	mysql select records greater than 3 months	select  * from    users where   user_datecreated >= now() - interval 3 month 	0.000184350593659281
2768497	4864	mysql select statment to return 2 columns into 1	select teama_id as 'teams' from teams union select teamb_id as 'teams' from teams 	0.000512995768353164
2769827	40557	how to order by a known id value in mysql	select id, name, date      from tbl  order by case when id = 10 then 0 else 1 end, id desc 	0.000408924960303649
2771179	2885	select a distinct record, filtering is not working	select * from #temp  select * from (select max(c1) as nr from  (select convert(varchar(10), c3,104) as date, max(c3) as max_date  from #temp  where   convert(varchar(10),c3,104) >=  '02.02.2010' and  convert(varchar(10),c3,104) <= '23.02.2010' group by convert(varchar(10), c3,104))  as t2 inner join #temp as t1 on (t2.max_date = t1.c3 and  convert(varchar(10), c3,104) = date)   group by convert(varchar(10),max_date,104)) as t3 inner join #temp as t4 on (t3.nr = t4.c1 ) 	0.356728556694151
2772548	23604	convert function from access sql to t-sql 2005	select     case          when isnull([selling price],0) = 0 then 0         else ([selling price] - isnull([cost],0))/[selling price]     end as fieldname from tablename 	0.758193414504614
2773050	27035	need to find differences between 2 identically structured sql tables	select b.*, 'added' from tableb b    left outer join tablea a on b.issueid = a.issueid where a.issueid is null select a.*, 'deleted' from tablea a     left outer join tableb b on a.issueid = b.issueid where b.issueid is null select a.*, 'updated' from tablea a     join tableb b on a.issueid = b.issueid where a.status <> b.status or a.who <> b.who 	0.00195883926649948
2776108	28349	what is the sql statement that removes duplicates but keep additional column's data?	select customer_id, vehicle_id, dealer_id, event_type_id,      max(event_initiated_date) from mytable  group by customer_id, vehicle_id, dealer_id, event_type_id 	0.0771504450884374
2776223	13885	pl/sql time segment calculation	select extract(hour from numtodsinterval(to_date('14:00:00','hh24:mi:ss') - to_date('13:15:00','hh24:mi:ss'),'day')) ||':'|| extract(minute from numtodsinterval(to_date('14:00:00','hh24:mi:ss') - to_date('13:15:00','hh24:mi:ss'),'day')) diff from dual / diff 0:45 	0.394855392737885
2778470	38397	query mysql table and fetch rows posted in 3 days	select t.id   from pages t  where t.date between date_sub(now(), interval 3 day) and now() 	0
2778618	13050	how to select a random record from a mysql database?	select * from tablename order by rand() limit 1 	0.000159382370832761
2778866	22389	eliminate subquery for average numeric value	select    name from    (select      round((min(latitude) + max(latitude)) / 2) as latitude,     round((min(longitude) + max(longitude)) / 2) as longitude    from station     where district_id = '110'       and name like 'vancouver%') as center   inner join station s where   s.district_id = '110'    and s.name like 'vancouver%'   and s.latitude between center.latitude - 5 and center.latitude + 5   and s.longitude between center.longitude - 5 and center.longitude + 5 	0.0076077858479141
2778926	16721	how to retreive the last updated data from mulitple categories using php and mysql	select p.id, c.id, p.productname, p.datetime from category c, product p where c.id = p.categoryid and p.id = (select id from product where categoryid = c.id order by datetime desc limit 1) 	0
2787908	33362	mysql select statment with modification to tuple values	select (subscription_id_fk * 2) as double_sif from table where sub_name = 'gold' 	0.315220792655614
2788571	37253	converting a date string which is before 1970 into a timestamp in mysql	select datediff( str_to_date('04-07-1988','%d-%m-%y'),from_unixtime(0))*24*3600 -> 583977600 select datediff( str_to_date('04-07-1968','%d-%m-%y'),from_unixtime(0))*24*3600 -> -47174400 	0.000619346581894946
2791308	34172	i have 2 mysql tables. how to get not all data from them in 1 sql query?	select a.username, b.streamid from names a, streams b where a.userid = b.userid; 	0
2791415	25184	tsql - top x in from subquery?	select  column_names  from  table_a a left join (select top 8 column_names from table_b) as b on a.id=b.id 	0.0141510569509067
2793994	25018	group mysql query by 15 min intervals	select   round(unix_timestamp(timestamp)/(15 * 60)) as timekey from     table group by timekey; 	0.0292875324602338
2794639	3879	how to make an sql for this: an integral field and it's last four must be zero	select column where column % 1000 = 0 	0.012934186811562
2797099	31657	mysql: just select something happen in the weekend	select * from events where dayofweek(start_time) = 7                       or dayofweek(start_time) = 1                       ... 	0.0808203892211255
2797286	12610	how to have multiple tables with multiple joins	select  * from staff, mobilerights left outer join staffmobilerights on staffmobilerights.staffid = staff.id 	0.0617827472402713
2797583	6481	is there a better way to find the max count in a table	select top(1) phg, count(*) as count from nhanvien group by phg order by count(*) desc 	0.00866930192858573
2798317	32791	performing inner join for multiple columns in the same table	select   a.answer_id   ,c1.color_name as favorite_color_name   ,c2.color_name as least_favorite_color_name   ,c3.color_name as color_im_allergic_to_name from tbanswers as a inner join tbcolors as c1   on a.favorite_color = c1.color_code inner join tbcolors as c2   on a.least_favorite_color = c2.color_code inner join tbcolors as c3   on a.color_im_allergic_to = c3.color_code 	0.00693930546423873
2798355	8844	mysql : avg of avg impossible?	select avg(avg_) as superavg from (     select category, avg(val) as avg_     from foo_table     group by category ) as avgs; 	0.53487204052723
2802185	2155	how do i format a date column in mysql?	select date_format(your_date_column, '%c/%d/%y') from table 	0.0108133849649882
2802609	29231	last results submitted in mysql db	select * from that_table order by auto_increment_primary_key desc limit 0, 20 	0.00387990697523407
2804176	25852	sql server 2008 - get latest record from joined table	select c.id, c.firstname, c.lastname, o.id as orderid, o.date, o.description from customer c  left outer join (     select customerid, max(date) as maxdate     from order     group by customerid ) om on c.id = om.customerid  left outer join order o on om.customerid = o.customerid and om.maxdate = o.date 	0
2804332	29945	mysql select into outfile to a different server?	select into outfile 	0.0253683298303804
2804341	35300	left join on associative table	select         pj.*,        cjp.value     from         (   select                     p.id prospectid,                    p.name,                    p.projectid,                    cj.title,                    cj.id conjointid                from                     prospect p,                    conjoint cj                where                         p.projectid = 1                    and p.projectid = cj.projectid                order by                     1, 4          ) pj          left join conjointprospect cjp               on pj.prospectid = cjp.prospectid              and pj.conjointid = cjp.conjointid      order by          pj.prospectid,         pj.conjointid 	0.51539360185412
2804452	2332	database per application vs one big database for all applications	select * from schemaname.tablename 	0.01673350503205
2804836	39436	what is the most effective and flexible way to generate combinations in tsql?	select     cast(t1.number as varchar) + ' ' + cast(t2.number as varchar) as numbers,     cast(t1.lottery as varchar) + ' ' + cast(t2.lottery as varchar) as lottery from table1 t1 cross join table1 t2 order by numbers 	0.0134825072113104
2807219	24714	reorganizing mysql table to multiple rows by timestamp	select     time,     sum(case when probe_id = '00a' then position else 0 end) `00a`,     sum(case when probe_id = '00b' then position else 0 end) `00b`,     sum(case when probe_id = '00c' then position else 0 end) `00c`,     sum(case when probe_id = '01a' then position else 0 end) `01a`,     sum(case when probe_id = '01b' then position else 0 end) `01b`,     sum(case when probe_id = '01c' then position else 0 end) `01c` from mg41 group by time limit 10; 	0.00132152749243553
2807361	17215	how to order by column with non-null values first in sql	select *     from @temp     order by case when lastname is null then 1 else 0 end, lastname 	0.00041052188371596
2808373	26006	how can i get the rank of rows relative to total number of rows based on a field?	select s.score, s.created_at, u.name    , u.location, u.icon_id, u.photo    , (select count(*) + 1         from scores s2         where s2.score > s.score             or (s2.score = s.score and s2.created_at > s.created_at)         ) as rank from scores s     left join users u          on u.uid = s.user_id order by s.score desc, s.created_at desc limit 15 	0
2809918	38138	mysql query to return most proposed books in a month	select  proposal_book, count(*) as cnt from    proposals where   proposal_date >= $first_day_of_month         and proposal_date < $first_day_of_month + interval 1 month group by         proposal_book order by         cnt desc limit 10 	0.000649934161747416
2813424	40113	sql query to return all rows that contain duplicate data from one field	select * from cardtable where cardid in ( select cardid from cardtable group by cardid having count(cardid) > 1) 	0
2814735	8680	selecting two specific mysql table rows in a single query	select x.*   from (select a.*,                @rownum := @rownum + 1 as rank           from mytable a            join (select @rownum := 0) r          where a.col1 = "zzz"        order by a.date desc) x  where x.rank in (1, 15) 	0
2815856	39588	sql: including data from multiple columns	select     practice, stuff1 as stuff, count(*) from table group by practice, stuff1 union select     practice, stuff2 as stuff, count(*) from table group by practice, stuff2 union select     practice, stuff3 as stuff, count(*) from table group by practice, stuff3 	0.00101866826122611
2823423	18282	sql algorithm question to convert a table	select * from (   select id, field1, null, null from table where not (field1 is null)   union   select id, null, field2, null from table where not (field2 is null)   union   select id, null, null, field3 from table where not (field3 is null) ) mysubquery order by id 	0.349694886883234
2824033	40558	mysql to get depth of record, count parent and ancestor records	select t1.node  from mytable as t1 join mytable as t2 on t1.parent = t2.node join mytable as t3 on t2.parent = t3.node where t3.parent is null; 	0
2826053	30129	want to avoid the particular rows from select join query... see description	select j1. * from jos_audittrail j1 left outer join jos_audittrail j2 on ( j1.trackid != j2.trackid and j1.field = j2.field and j1.changedone < j2.changedone ) where j1.operation = 'update' and j2.id is null and j1.field != 'lastvisitdate' and j1.field != 'hits' 	0.000758946838970428
2826976	4373	alias some columns names as one field in oracle's join select query	select fo.leader_type, us.name from follow_up fo join users us   on (fo.leader_id = us.id and fo.leader_type = 'user') where follower_id = 83 union all select fo.leader_type, co.name from follow_up fo join companies co   on (fo.leader_id = co.user_id and fo.leader_type = 'company') where follower_id = 83 union all select fo.leader_type, ch.title as name from follow_up fo join channels ch   on (fo.leader_id = ch.id and fo.leader_type = 'channel') where follower_id = 83 union all select fo.leader_type, gr.name from follow_up fo join groups gr   on (fo.leader_id = gr.id and fo.leader_type = 'group') where follower_id = 83 union all select fo.leader_type, tt.name from follow_up fo join talent_teams tt   on (fo.leader_id = tt.id and fo.leader_type = 'team') where follower_id = 83 	0.00830020012545105
2827645	11297	sql: joining multiples tables into one	select 'insert r (ttablename, rid, rname)         select ''' + t.table_name + ''', rid, rname         from ' + t.table_name from information_schema.tables t where table_type = 'base table' and table_name like 'r[0-9]%' and 2 = (select count(*)          from information_schema.columns c          where c.table_name = t.table_name          and c.column_name in ('rid', 'rname')) 	0.00105938648755573
2827871	30600	select distinct on a field not appearing in recordset?	select my, interesting, columns from (     select distinct guid, ...     from ... ) 	0.00436431898089623
2828153	31788	tsql sum data and include default values for missing data	select tl.type_lookup_id, tl.name, sum(da.type_lookup_id) how_much  from type_lookup tl   left outer join data da    on da.type_lookup_id = tl.type_lookup_id  group by tl.type_lookup_id, tl.name  order by tl.type_lookup_id 	0.00399920116433515
2828905	22668	sql help - find the table that has 'somefieldid' as the primary key?	select so.name as tablename,        si.name as indexname,        sc.name as columnname   from sys.indexes si   join sys.index_columns sic     on si.object_id = sic.object_id    and si.index_id = sic.index_id   join sys.columns sc     on si.object_id = sc.object_id    and sic.column_id = sc.column_id   join sys.objects so     on si.object_id = so.object_id  where sc.name like '%columnname%'    and si.is_primary_key = 1 	0.000918133647867225
2828973	28795	how do i display list of urls say maximum 50 per web page from mysql database?	select url_column_name  from my_table  order by url_column_name asc 	0
2829950	5299	consecutive absences in mysql	select a.id_student, a.date, dayname(a.date) from absences a join absences a2 on a2.id_student = a.id_student and (a2.date = date_add(a.date, interval 1 day) or (dayname(a.date) = 'friday' and a2.date = date_add(a.date, interval 3 day))) join absences a3 on a3.id_student = a.id_student and (a3.date = date_add(a2.date, interval 1 day) or (dayname(a3.date) = 'friday' and a3.date = date_add(a2.date, interval 3 day))) left join absences a4 on a4.id_student = a.id_student and (a4.date = date_add(a.date, interval -1 day) or (dayname(a4.date) = 'monday' and a4.date = date_add(a.date, interval -3 day))) where a4.id_student is null 	0.085345527740806
2831001	737	a select statement for mysql	select * from mytable where find_in_set(tagid,itagid) order by bookmarkid asc limit n; 	0.407711304597284
2831617	10338	sub-total and total columns	select ;        tbl.yourcolumns,;        peritem.totalperitem,;        rpttotal.totalperall;    from ;        yourothertables tbl,;        ( select yoursalestable.itemid,;                 sum( calculatedsales ) as totalperitem;              from;                 yoursalestable;              group by ;                 itemid ) peritem,;        ( select sum( calculatedsales ) as totalperall;              from ;                 yourtalestable ) rpttotal;    where ;        yourotherjoinconditions;       and yourothertables.itemid = peritem.itemid;    order by ;        whatever;    into ;        cursor yourreportresults 	0.00108285116279224
2831761	27591	mysql : count posts and group by date	select from_unixtime(post_date, '%y %d %m') as post_date,          count(post_id) as post_count     from posts group by post_date 	0.00492720475607331
2832305	13965	mysql query to get count of unique values?	select lid, count(distinct ip) as uhits from hits group by lid 	0.000247663869225579
2832637	16970	how can we fetch top 3 data value from database	select * from mytable order by salary desc limit 3; 	5.31995405201498e-05
2833672	9520	best way to add a column in mysql query	select `col1`, 'ok' as `col2`, `col3` from `table1` 	0.0501870717247579
2838467	28530	aggregate functions on subsets of data based on current row values with sql	select e.id      , e.name      , e.title      , e.salary      , g.posavg   from employee e      , (select e.title              , avg(salary) posavg           from employee e        group by e.title) g    where e.title = g.title 	0
2842423	6813	3-clique counting in a graph	select t1.v1, t2.v1, t3.v1 from tablename t1, tablename t2, tablename t3 where t1.v1 < t1.v2 and t2.v1 < t2.v2 and t3.v1 < t3.v2 and t1.v1 = t3.v1 and t1.v2 = t2.v1 and t2.v2 = t3.v2 	0.185964249699219
2843103	31832	how to limit date?	select [list] from mytable mt1 where mt1.date = (      select max(mt2.date)      from mytable mt2   ) 	0.0534813195838253
2843470	14414	mysql count elements in a database based on how many unique values there are in a field	select date, count(uid) from users group by date; 	0
2844077	37624	access: passing variables from vba to sql	select * from [some_table] where [occurrence number]=forms!someopenform!somecontrol 	0.771644612678832
2845145	41169	sql join everything from one table with one feild from another table?	select tablea.*, tableb.somefield 	0
2845857	9579	how to query by recent date and value in sql?	select tbl.* from le_table tbl inner join (     select patient_id, max(obs_date) obs_date     from le_table     group by patient_id ) t2 on tbl.patient_id = t2.patient_id     and tbl.obs_date = t2.obs_date where tbl.weight_val > 120 	0.000833609242913059
2847968	38094	sql most popular	select itemid, sum(qtyordered) as total from testdata group by itemid order by total desc; 	0.0155481304869459
2851073	34708	sql server 2005, relational tables to hierarchical xml	select id as [@id], name as [@name],     (select child.id as [@id], child.name as [@name]      from child      where child.parentid = parent.id      for xml path('child'), type) as [*] from parent for xml path ('parent'), root('output') 	0.732215528023281
2851651	40895	tv guide script - getting current date programmes to show	select now(), airdate from mediumonair where episode = 'episode' 	0.00199318397116585
2852144	28002	sql query with computed column	select ... from dbo.users as u     join    (             select t.userid, avg( datediff(s, t.starttime, t.endtime) ) as avgtimespan             from dbo.transactions as t             group by t.userid             ) as z         on z.userid = u.id order by z.timespan desc 	0.127100960374806
2852708	19205	converting mysql resultset from rows to columns	select id     , min( case when name = 'make' then attribute_value end ) as make     , min( case when name = 'year' then attribute_value end ) as year     , min( case when name = 'type' then attribute_value end ) as type     , min( case when name = 'axles' then attribute_value end ) as axles     , min( case when name = 'size' then attribute_value end ) as size     , min( case when name = 'frame' then attribute_value end ) as frame     , ... from attributes where name in('make','year','type','axles','size','frame',....) group by id 	0.000570345551576057
2853981	29248	mysql command-line tool: how to find out number of rows affected by a delete?	select row_count(); 	0
2854518	14613	counting twice in a query, once using restrictions	select     class,     count(distinct table1.child),     sum(if(table2.glasses='yes', 1, 0)) from table1 left join table2 on table1.child=table2.child 	0.0381477428075077
2855373	29866	sql server select distinct	select cola, colb, colc, cold from (     select          cola, colb, colc, cold,          row_number(partition by colb, colc order by cold) as rn     from table1 ) t1 where rn = 1 	0.242053509388645
2855526	9497	specify which row to return on sqlite group by	select t.*    from docs t        inner join ( select id, max(version) as ver from docs group by id ) as t2           where t2.id = t.id and t2.ver = t.version 	0.0037964337188945
2856881	26285	tsql: dates that lie between (intersect) from and to date?	select  * from    empc where   datefrom <= p_todate         and dateto >= p_fromdate 	0.000701806288272678
2857977	18028	select distinct values from multiple columns	select min(a),b   from table  group by b 	0.000173386008900736
2858197	15926	can i insert an image in a mysql db table?	select * 	0.0475337452423234
2861643	18525	long to timestamp for historic data (pre-1900s)	select to_timestamp('1-jan-1970 00:00:00', 'dd-mon-yyyy hh24:mi:ss') +          numtodsinterval(val /(1000*60*60*24),'day' ) +          numtodsinterval(            ((val /(1000*60*60*24)) - (trunc(val /(1000*60*60*24))) ) * 60*60*24,'second') from (select -2177452812340 val from dual); 	0.368159710886489
2862208	11201	mysql select two tables at the same time	select tablea.team1, tablea.team2, tableb.team, tableb.image, tb.image from tablea  left join tableb on tablea.team1=tableb.team left join tableb tb on tablea.team2=tb.team 	6.57446385889581e-05
2862344	3648	multi pivoting on single source data	select nk     , min( case when dc = 10 then gev end ) as [10]     , min( case when dc = 11 then gev end ) as [11]     , min( case when dc = 12 then gev end ) as [12]     , min( case when dc = 18 and version = 2006 then gev end ) as [2006]     , min( case when dc = 18 and version = 2007 then gev end ) as [2007]     , min( case when dc = 18 and version = 2008 then gev end ) as [2008]     , min( case when dc = 18 and version = 2009 then gev end ) as [2009] from multipivot group by nk 	0.0119573815247047
2862704	1216	php mysql - select unique value that not being used from dirrefent table	select name, u_country, u_postcode from user  where u_postcode not in (select d_postcode from data) 	0.00143239625886639
2862778	39609	mysql select results from 1 table, but exclude results depending on another table?	select * from messages where ((m_to=$user_id)      or (m_to=0 and (m_to_state='' or m_to_state='$state')      and (m_to_city='' or m_to_city='$city'))) and not exists (     select *     from messages_view     where messages.message = messages_view.id         and messages.deleted = 1          and messages_view.user = $somephpvariable ) 	0
2863632	19306	best way to change the date format in mysql select?	select date_format(datefield, "%d/%m/%y %h:%i") from <tablename> where <clause> 	0.0110489172967367
2865684	32330	select last row of table	select top 1 * from table  order by somecolumn desc 	0
2866764	11193	how to count number of occurences for all different values in database column?	select column5, count(*) from table1 group by column5 	0
2866795	38180	sql: without a cursor, how to select records making a unique integer id (identity like) for dups?	select distinct dbo.dateasint(dateentered) * 100 as pk,                   row_number() over (partition by dateentered order by recorddescription) as rowid,                  recorddescription as data from mytable 	0.000851498012088766
2867054	1442	sql: join within same table with different 'where' clause	select t.id,          max(case when t.key = 1 then t.value else null end) as "1",          max(case when t.key = 2 then t.value else null end) as "2"     from table t group by t.id 	0.0678697565398801
2867594	16972	sql joins "going up" two tables	select `history`.`id`            , `parts`.`type_id`          , `part_list`.`name`          , `serialized_parts`.`serial`          , `history_actions`.`action`           , `history`.`date_added`       from `history_actions` inner join `history` on `history`.`action_id` = `history_actions`.`id`  left join `parts` on `parts`.`id` = `history`.`part_id`       left join `serialized_parts` on `serialized_parts`.`parts_id` = `history`.`part_id`  left join `part_list` on `part_list`.`id` = `parts`.`type_id`      where `history`.`unit_id` = '1'    order by `history`.`id` desc 	0.465781757681455
2868343	24378	optimizing a mysql query that finds duplicate data	select  * from    people po where   exists         (         select  null         from    people pi         where   pi.col1 = po.col1         limit 1, 1         ) 	0.0708889763336946
2868786	18869	mysql comparisons between multiple rows	select  l1.id, l2.id from    ledger l1 join    ledger l2 on      addtime(cast(cast(l2.date as date) as datetime), l2.starttime) <= addtime(cast(cast(l1.date as date) as datetime), l1.endtime)         and addtime(cast(cast(l2.date as date) as datetime), l2.endtime) <= addtime(cast(cast(l1.date as date) as datetime), l1.starttime)         and l1.id < l2.id 	0.0316951468136006
2869376	14468	mysql: order results by number of matching rows in second table	select a.*          , b.cnt       from tablea a    left outer join (select a_id                          , count(*) cnt                       from tableb b                    group by a_id) b    on a.id = b.a_id      order by b.cnt 	0
2871194	13995	how can i get a distinct list of elements in a hierarchical query?	select  distinct * from    jobs start   with ( city, title ) in       ( select city, title        from   people        where  name in ( 'bill', 'jim', 'jane' )      ) connect by prior parent_title = title; 	0.000218181674672339
2873432	22040	two sql queries in one place	select  * from    tbl_sub_results ts left join         tbl_friendly tf on      tf.id = ts.ccompid where   ts.user_submitted != '$_session[username]'         and ts.home_user = '$_session[username]' or ts.away_user = '$_session[username]' 	0.0162747982906655
2874168	28987	limit the number of rows returned on the server side (forced limit)	select top x * from offendingtable 	0.00023942300789317
2874772	34807	finding if an anniversary is coming up in n days in mysql	select birthdate  from anniversaries  where dayofyear(birthdate) - dayofyear(curdate()) between 0 and 10  or dayofyear(birthdate) + 365 - dayofyear(curdate()) between 0 and 10; 	0.000420246724853924
2875835	25825	php sql: matching corresponding data between 2 tables, without filtering out data in 1st table	select userid, d.name from u left outer join division d on u.divisionid = d.divisionid order by userid 	0
2878356	25377	select ... where id = any value. is it possible?	select `id` from `table` where `name` = 'something' and `order` = `order` 	0.0406057661680518
2879710	30507	mysql counting question	select count(*) as coun, user_id  from users_articles group by user_id order by coun desc limit 1 	0.595429717709977
2882647	8274	mysql order by rand(), name asc	select * from  (     select * from users order by rand() limit 20 ) t1 order by name 	0.308708820536924
2882688	32421	adding a character to a foreign_key in select statement	select * from table_1 inner join table_2 on concat('fk',cast(table_1.id as char))=table_2.fk_id) 	0.420605664797555
2882981	21338	how do i deconstruct count()?	select column1, count(*) from view group by column1     select column2, count(*) from view group by column2     select column3, count(*) from view group by column3     select column1, column2, count(*) from view group by column1, column2 select column2, column3, count(*) from view group by column2, column3 select column1, column3, count(*) from view group by column1, column3 	0.276819618401181
2884689	14115	can you define values in a sql statement that you can join/union, but are not stored in a table outside of the statement?	select * from table1 t1 join (     select titles, stuff      from table2     union all     select 'foo' as titles, 'foostuff' as stuff     union all     select 'bar' as titles, 'barstuff' as stuff ) t2 on t1.id = t2.titles 	0.020808474054232
2884804	41173	make select @@identity; a long?	select cast(scope_identity() as bigint) 	0.681476935682908
2884996	29649	simple check for select query empty result	select * from service s where s.service_id = ?; if @@rowcount > 0  	0.54514249622237
2885662	15652	mysql: check whether two fields on a model are always the same?	select grid from mytable group by grid having count(distinct vill) > 1 	0
2885709	37949	sql concatenate rows query	select status, group_concat(title) from posts group by status 	0.0100862231610545
2885747	12703	how can i optimize retrieving lowest edit distance from a large table in sql?	select top 1     @resultid = id,     @result = [name],     @resultdist = distorig,     @resulttrimmed = disttrimmed from (     select         id, [name],          dbo.levenshtein(@source, [name]) as distorig,         dbo.levenshtein(@sourcetrimmed, [name])) as disttrimmed,         frequency     from mytable ) as t order by     case when distorig > disttrimmed then distorig else disttrimmed end,      case when distorig > disttrimmed then 1 else 0 end,                       frequency                                                             	0.00421663940747819
2886030	1560	assign the results of a stored procedure into a variable in another stored procedure	select @ssql = 'select @xcount = count(id) from authors'  exec sp_executesql @ssql, n'@xcount int output', @count = @xcount output 	0.00201936686969604
2886064	24750	how do i select a fixed number of rows for each group?	select x.a,        x.b,        x.distance   from (select t.a,                t.b,                t.distance                case                   when @distance != t.distance then @rownum := 1                   else @rownum := @rownum + 1                 end as rank,                @distance := t.distance           from table t           join (select @rownum := 0, @distance := '') r       order by t.distance   where x.rank <= 2 order by x.distance, x.a 	0
2887096	3149	finding rank of the student -sql compact	select a1.name, a1.total, count(a2.total) rank   from stmarks a1, stmarks a2  where a1.total < a2.total or (a1.total=a2.total and a1.name = a2.name) group by a1.name, a1.total order by a1.total desc, a1.name desc; 	0.0229470594427823
2887679	13119	count problem in sql when i want results from diffrent tabels	select  (select count(*) from tblreview where tblreview.groupid = product.groupid) as reviewcount,          (select count(*) from tblcomment where tblcomment.groupid = product.groupid) as commentcount,         product.groupid,         max(product.productid) as productid,         avg(product.price) as price,         max (product.year) as year,         max (product.name) as name,         (select avg(tblreview.grade) from tblreview where tblreview.groupid = product.groupid) as grade         from product where   (product.categoryid = @categoryid) group by product.groupid having count(distinct product.groupid) = 1 	0.474478104742038
2889647	31622	sort mysql data by number of entries	select p.product_id,          count(*) as num_orders     from products p group by p.product_id order by num_orders desc     limit 10  	0
2894832	17162	mysql query help, take total sum from a table, and based on discount value on another table calculate the gross_total	select sum( iv.inv_total - iv.inv_discount + iv.taxes ) from  ( select          (select sum(ii.total) from si_invoice_items ii             where ii.invoice_id = v.id) as inv_total ,         (             select                 case v.discount_type                     when 1 then v.discount                     when 2 then (v.discount / 100) * ( select inv_total )                      else 0                 end         ) as inv_discount,         (select              case t.type                 when '$' then t.tax_percentage                 when '%' then ( t.tax_percentage / 100 ) * (select inv_total - inv_discount)                 else 0             end         from si_tax as t         where t.tax_id = inv_tax_id         ) as taxes     from          si_invoices v     ) iv 	0
2895493	22140	query for find nth maximum value in mysql	select column from table order by column desc limit n, 1 	0.000115058406066358
2899771	32590	using mysql, is there any way to dump the count of records in each of all 200 tables in a database?	select table_name,        table_rows   from `information_schema`.`tables`  where table_schema = '<your database name>'  order by table_rows desc 	0
2900113	17885	combine sql statement	select *      from follows      join postings on follows.following_id = postings.profile_id      inner join users on postings.profile_id = users.profile_id    where follows.profile_id = 1  order by tweets.modified desc 	0.380923058603139
2901497	12799	t-sql picking up active ids from a comma seperated ids list	select productcode from     productallowed pa     join     (     select cast(id as varchar(10)) as productid     from product where     issaletypea = 'y' or      issaletypeb = 'y' or     issaletypec = 'y'     ) p on            pa.productids like '"p.productid,%' or             pa.productids like '%,p.productid"' or             pa.productids like '%,p.productid,%' 	0
2902629	6811	how can i get all the database names in a sql server instance using tsql?	select * from sys.databases 	0.000228532126446662
2903262	16195	sql query to list all views in an sql server 2005 database	select * from sys.views 	0.06920587592132
2903750	8120	t-sql right joins to all entries inc selected column	select  u.userid,         u.adusername,         al.accesslevelid,         al.accesslevelname,         case when ar.accesslevelid is null then 'false' else 'true' end as access from    tblusers u cross join         tblaccesslevels al left join         tblaccessrights ar on      ar.accesslevelid = al.accesslevelid         and ar.userid = u.userid 	0.00414718192145442
2905421	24941	how do i find out in sql what db name i'm connected to	select db_name() as dbname 	0.11798566896897
2905968	26929	how to pivot rows to columns	select collectionid     , min( case when question = 75098 then answer end ) as answerfor75098     , min( case when question = 75110 then answer end ) as answerfor75110     , min( case when question = 75115 then answer end ) as answerfor75115     , min( case when question = 75315 then answer end ) as answerfor75315 from #temp group by collectionid 	0.00446096448604115
2906950	19433	how do i select and group by a portion of a string?	select rtrim(version, '0123456789') ||'xx', sum(users)  from table group by rtrim(version, '0123456789') 	0.00310688368094338
2907813	31698	count of sums possibly using group_by	select count(*) as `number of users`, `sum of items`  from (     select u.userid, sum(itemcount) as `sum of items`     from user u     inner join order o on u.userid = o.userid     group by u.userid ) g group by `sum of items` 	0.217029178503947
2910531	25231	mysql> selecting from more tables (with same columns) without union	select col1, col2 from a union all select col1, col2 from b 	7.82030019288147e-05
2911739	30248	treat mysql longtext as integer in query	select  * from    mytable order by         myfield + 0 	0.628272794359094
2912062	11740	xquery get value from attribute	select <xmlfield>.value('(/xml/fields/field/@name)[1]', 'varchar(60)') from <table> where <xmlfield>.value('(/xml/fields/field/value/)[1], 'int') = 1 	0.0001279157744843
2912292	2192	date comparison in oracle database	select * from my_table where doj < "to_date" and dol > from_date; 	0.25197783069379
2913632	35465	how to decrease queries in php/mysql array selection loop	select stories.storyid,        stories.storyname,         group_concat( tags.tagname )    from stories, tags  where concat( ' ', stories.tags, ' ' ) like concat( '%', tags.tagid, '%' )   group by stories.storyid, stories.storyname 	0.350564211269572
2914346	21769	stored procedure: reducing table data	select batch, [length], width, thickness from ( select @batch as batch, @count as qty, pd.location, cast(pd.gl as decimal(10,3)) as [length], cast(pd.gw as decimal(10,3)) as width, cast(pd.gt as decimal(10,3)) as thickness  from propertydata pd group by pd.location, pd.gl, pd.gw, pd.gt) 	0.636183300535588
2914526	16804	summarize data with sql statement	select   datepart(hh,cms_starttime)  as hourofday,   count(*)              as nummsgs,   sum(datediff(mi,cms_starttime,cms_stoptime)) as totaltimeinminutes,  avg(datediff(mi,cms_starttime,cms_stoptime)) as avgtimebetweeninminutes from        mytable    where cms_starttime       between 'may 1 2010' and 'may 2 2010' group by       datepart(hh,cms_starttime) 	0.614970746635926
2915355	9735	selecting fields in sql select statements (dumbest sql question)	select tablename.*, tochar(dtfield) ... 	0.699479719588285
2917786	37577	sql - get the latest date of two columns	select date1, date2,   case    when date1 > cast(isnull(date2,'1900-01-01') as datetime) then       date1    else      cast(date2 as datetime)  end  as latestdate  from table1 	0
2918498	27746	how to perform count() or count(*)	select count(distinct `tag_name`) from `hashtag` 	0.360351269517536
2921046	40501	sql server: order by xml column's node	select id, data from t   order by data.value('(/data/simpleorderedvalue)[1]', 'int') 	0.0865695609656428
2921535	28115	querying tables based on other column values	select case when a.id = 1 then a.attr_value_int             when a.id > 1 then b.some_other_col             else null end as whatever from first_table a      left outer join other_table b      on ( a.attr_val_ext = b.id ) / 	0
2922637	24444	mysql selecting default value if there are no results?	select     m.member_id,     m.user_id,     m.avatar,     coalesce(sum(c.vote_value), 0) as vote_value_sum,     coalesce(sum(c.best), 0) as best_sum,     coalesce(sum(c.vote_value), 0) + sum(c.best) * 10 as total_value from     members m left outer join comments c on     c.author_id = m.member_id group by     m.member_id order by     total_value desc limit 0, 20 	0.000618476958878511
2922950	40011	how do stop form posting to mysql if database contains a specific id?	select customerid from content where customerid = @id 	0.00188092679290312
2922973	26706	sql select statement - returning records starting with variable length string	select     name,     i_will,     never_use,     select_star from     my_table mt where    replace(replace(replace(name, '.', ''), ' ', ''), '-', '') like @prefix + '%' 	0.0148034389979163
2925165	7530	join two results sets to make one result set in t-sql	select   sum(case when t.col3 is not null then 1 else 0 end) 'number of responses',   count(t.col1) as 'total number of participants',     t.col2 as 'department' from table t   group by t.col1   order by t.col1 	0.0116316737790732
2926814	10279	mysql select multiple colomn from non related tables	select rootpath.root, savecatogoroy.brandid, savecatogory.categoryid from rootpath, savecatogoroy 	0.00116527353033801
2927475	39376	sql server - select top and bottom rows	select * from (select top(5) * from logins order by username asc) a union select * from (select top(5) * from logins order by username desc) b 	0.00234098951332889
2927937	35835	mysql fast insert dependent on flag from a seperate table	select `x`, `y` from `locations` where `alwaysignore` = 1; 	0.00191809583355221
2930708	14964	is it necessary to have an id column if a table has a unique column in mysql?	select * from photos where 2 < id and id < 10 	7.73571923947907e-05
2931540	30011	mysql: get all rows into 1 column	select p.id_post          group_concat(distinct t.name separator ' ')     from post p     join post_tag pt on pt.id_post = p.id_post     join tag t on t.id_tag = pt.id_post_tag group by p.id_post 	0
2934924	14870	sql query by passing te values in one table	select tablea.employeeid, skillsetcode,certid, lastname, firstname, middleinitial  from tablea, tableb where tablea.employeeid = tableb.employeeid  and tableb.key_user='249' 	0.0184097613458493
2937129	1077	querying with foreign key	select      b.*  from      tableb as b      join tablea as a          on b.tablea_id=a.id  where      a1='foo' 	0.00966425668703792
2938681	8428	sql server convert string to datetime	select convert(smalldatetime,'30/05/2010',103) 	0.133008304232894
2938792	23958	specific query in mysql	select date,        activity,        hours,        '' as holiday_name from   reports where  date >= '2008-12-1'        and date < '2009-1-4' union (select holiday_date,         '',         '',         holiday_name  from   holidays  where  holiday_date >= '2008-12-1'         and holiday_date < '2009-1-4') order  by date 	0.148061369323475
2940759	16965	find column that contains a given value in mysql	select col from (    select "column_1" as col, column_1 as value from yourtable    union all select "column_2", column_2 from yourtable    union all select "column_3", column_3 from yourtable ) allvalues where value=8; 	0
2941455	10239	sql server combining 2 rows into 1 from the same table	select j1.jobid, j1.employeeid, j1.enddate,  (     select top 1 j2.startdate        from job j2      where j2.employeeid = j1.employeeid        and j2.startdate > j1.enddate      order by j2.startdate ) as nextstartdate from job j1 	0
2941474	13287	create chart using php-mysql	select count(type) from request_events      where      datetime > date_sub(curdate(),interval 30 day)      group by type; 	0.508357535573449
2943320	26949	sql: simultaneous aggregate from two tables	select type, count(*) as filecount, sum(pc.count) as [prop count] from files f left outer join (     select file_id, count(*) as count     from properties p     group by file_id ) pc on f.id = pc.file_id group by type 	0.0295684005076655
2943429	15342	how to find top three highest salary in emp table in oracle?	select  *from      (     select *from emp      order by salary desc     ) where rownum <= 3 order by salary ; 	0
2946144	33797	how to return one db row from two that have the same values in opposite columns using the max function?	select z.id,          max(z.col)     from (select x.id,                  x.column1 as col             from table x           union            select y.id,                  y.column2             from table y) z group by z.id 	0
2946170	2465	get top 'n' records by report_id	select * from (select *,          row_number() over(partition by report_id order by (select 0)) as rn          from top_keywords          where ym between '2010-05' and '2010-05') tk where rn <= 10 	9.5103242706446e-05
2946754	31589	exclude records matching subquery	select * from reports as r join reportvalues as rv on rv.report_id = r.report_id join metrics as m on m.metric_id = rv.metric_id where not exists (select 1          from exclude_report e          where e.report_id = r.report_id) 	0.00374601799646031
2947466	26433	how do i show number of fetching of a data in a mysql data base?	select * from mytable where id=$field_id; update mytable set count_field=count_field+1 where id=$field_id; 	0
2948457	27927	how to distinguish between the first and rest for duplicate records using sql?	select id, name,   decode(row_number() over (partition by id order by id,name),1,'first','rest') ord from input_table; 	0
2949281	6725	t-sql multiple criteria on where clause	select * from tblbooks where bookid in (select bookid from tblauthors where genre = 'fiction') 	0.463444202844327
2949920	7578	get age of a person in mysql	select year(now())*12+month(now()) - (member.year*12+member.month) +1; 	0.000360225936131094
2950669	14604	find units with zero categories	select u.id, u.name from unit as u left join unitcategoryindex as uci on u.id = uci.unitid where uci.id is null 	0.0166833379762511
2951019	18984	mysql retrieve data from same table	select t1.id, t1.name as pname,      t2.parentid, t2.name as child, t2.id as childid from mytbl t1 inner join mytbl t2 on t1.id = t2.parentid 	0
2951135	32562	how to combine 12 tables with some different and some same fields	select id, name, max(jan) jan, max(feb) feb, max(dec) dec   from (select id, name, jan jan, null feb, null dec            from table1          union all          select id, name, null jan, feb feb, null dec            from table2          union all          select id, name, null jan, null feb, dec dec             from table12)  group by id, name 	0
2951819	6987	single sql server result set from query	select   account.id as accountid,    account.accountname as accountname,    s1.id as primarysettlementid,    s1.name as primarysettlementname,    s2.id as alternatesettlementid,    s2.name as alternatesettlementname from account      left join settlementinstruction s1 on s1.id = account.primarysettlementid      left join settlementinstruction s2 on s2.id = account.secondarysettlementid where 	0.0277074757480476
2953120	36551	sql server 2008 - get geography from record	select geography :: point (latitude,  longtitude, 4326) from location.location 	0.00828953598948138
2953447	13004	getting the last entry of a user from a mysql table ordered by datetime	select data from table where username = 'jhon' order by datetime desc limit 1 	0
2954122	36344	relating categories with tags using sql	select tag_id from images_tags where image_id in (select image_id from images where cateory_id = 11 ) 	0.10914908786036
2954325	20196	need some sort of "conditional grouping" in mysql	select date     , sum(case when type ='a' then 1 else 0 end) as count_type_a      , sum(case when type ='b' then 1 else 0 end) as count_type_b     , sum(case when type ='c' then 1 else 0 end) as count_type_c  from article group by date 	0.307988667704442
2954648	38243	php mysql join table	select logs.full_name, logout.status from logs     left join logout on (logs.employee_id = logout.employee_id); 	0.269686173986544
2955341	18048	php mysql select multiple tables	select e.*, l.time, l.date, lo.time, lo.date    from employee e   left join logs l      on l.employee_id = e.employee_id   left join logout lo     on lo.employee_id = e.employee_id   where e.employee_id = {your id here} 	0.0648405858848367
2956309	39550	uids for data objects in mysql	select last_insert_id() 	0.194044942568083
2957351	19430	finding efficient overlapped entries in a sql table	select * from demo a where not exists( select 1 from demo b  where a.demo_id!=b.demo_id and a.s < b.e and b.s < a.e) 	0.00146641246764496
2959312	11605	sql - getting most recent date from multiple columns	select max(case when (datedeleted is null or datemodified > datedeleted)                 then datemodified else datedeleted end) as maxdate from table 	0
2959702	14572	how to get count of another table in a left join	select post.id, post.title, user.id as uid, username, coalesce(x.cnt,0) as comment_count from `post` left join post_user on post.id = post_user.post_id left join user on user.id = post_user.user_id left outer join (select post_id, count(*) cnt from post_comments group by post_id) x on post.id = x.post_id order by post_date desc 	0.000779150723351618
2959721	12608	ms sql/php truncating result text	select convert(text,fld_name) from table_name 	0.385599243455796
2959892	2452	how to intersect two "selects" and then put another condition for the result	select *   from ( select *            from table_a          intersect          select *            from table_b        ) where <conditions> 	0.000572560733550305
2960481	18666	get the previous date in mysql	select... where date <= now() && date >= ( now() - 90000 ) 	0.000498765943886489
2965471	39817	select log lines from today in mysql	select * from log where eventtime >= date_sub(curdate(), interval 1 day); 	0.00112346345866131
2965489	13233	sql: add counters in select	select name, row_number() over(partition by name order by name) as [rank] from mytable 	0.172614474980068
2967044	4674	mysql eliminate user based on conditions	select c.* from lessons_slots l join class_roll c on l.id=c.classid where concat(firstname,lastname) not in (select concat(firstname,lastname) from  lessons_slots l join class_roll c on l.id=c.classid where name='advanced') 	0.00241488355927466
2968042	40911	sql query for finding rows with special characters only	select     templateid,     body from     #template where     body like '%[^0-9a-za-z ]%' 	0.00789258302870183
2969894	30959	looping over some selected values in a stored procedure	select grp, code, srt_ordr from  ( select     grp = stat_cd,     code = reasn_cd,     srt_ordr from dbo.status_table with (nolock) union  select distinct stat_cd, ' from dbo.status_table with (nolock) ) raw order by grp, srt_ordr 	0.0414375652863305
2974608	40666	different results on the basis of different foreign key value using a falg in where clause	select  distinct t1.suppliervenueproductid, [...] from    table t1         left join                 table t2                 on t1.suppliervenueproductid = t2.suppliervenueproductid                 and t2.iscustomcost = 1 where   t2.suppliervenueproductid is null or      t1.iscustomcost = 1 	0
2974729	30366	simple mysql query (i think) - select multiple rows into 1 field	select p.id, group_concat(pi.values separator ' ') as allprofileinformation from profiles p   inner join profileinformation pi on (pi.id = p.id) group by pi.id 	0.0897473865331561
2977055	34371	can't create a mysql query that generates 4 rows for each row in the table it references	select ... from table     cross join  (                 select '12 am'                 union all select '6 am'                 union all select '12 pm'                 union all select '6 pm'                 ) as times 	0
2978499	4585	sql alias field	select (select ...) as `005` from table1 group by ... having `005` > 0 	0.436948605189605
2978726	19085	limit results from joined table to one row	select p.*,        pp.*   from products p   join product_photos pp on pp.product_id = p.product_id   join (select x.product_id,                min(x.photo_order) as default_photo           from product_photos x       group by x.product_id) y on y.product_id = pp.product_id                               and y.default_photo  = pp.photo_order 	0
2980220	37136	best way to fetch last 4 rows from a result set using mysql	select x.value     from (select y.value             from table y         order by y.value desc            limit 4) x order by x.value 	0
2980260	21485	how do i get the 2 most recent records	select  a1.accountno,  a1.dateoforder,  a1.orderid from accounts a1 left outer join accounts a2   on a2.accountno = a1.accountno and a1.dateoforder < a2.dateoforder group by a1.accountno,  a1.dateoforder,  a1.orderid having count(*) < 2 	0
2981151	10308	oracle replacing text between first and last spaces	select regexp_replace(column_value,' .* ',            ' '||rpad('*',length(regexp_substr(column_value,' .* '))-2,'*')||' ') from table(sys.dbms_debug_vc2coll(        'duke of north','prince of wales','baltic','what if two spaces')); duke ** north prince ** wales baltic what ****** spaces 	0.000261655860758878
2982495	29412	find overdrawn accounts in sql	select t1.username from (     select username, sum(amount) as amount     from withdraw     group by username ) t1 left join (     select username, sum(amount) as amount     from deposit     group by username ) t2 on t1.username = t2.username where t1.amount > coalesce(t2.amount, 0) 	0.0445719994375542
2984844	6714	mysql: joining three tables - how?	select `manufacturers`.*, `languages`.*, count(`products`.`id`) as numberofproducts from (`manufacturers`) join `languages` on `manufacturers`.`lang` = `languages`.`id` left outer join `products` on        `products`.`manufacturerid` =  `manufacturers`.`manufacturerid` group by <column list for manufacturers and languages here> order by `languages`.`id` asc, `manufacturers`.`id` asc 	0.0351304663893809
2985745	16572	mysql: combining multiple where conditions	select * from menu  where alias='filename' and  parent = (select node_id from menu           where alias='folder2' and           parent = (select node_id from menu                     where alias='folder1'                    )          ) 	0.257112119571666
2988159	3656	better ways to print out column names when using cx_oracle	select table_name from all_tables where nvl(tablespace_name, 'no tablespace') not in ('system', 'sysaux') and owner = :owner and iot_name is null 	0.0495811106036099
2988371	26373	using full-text search in sql server 2005 across multiple tables, columns	select u.id from users u where freetext(*,'"bpi"') union  select c.aid from certification c where freetext(*,'"bpi"') union  select ad.aid from applicantdetails ad where freetext(*,'"bpi"') union  select eb.aid from educationalbackground eb where freetext(*,'"bpi"') union  select ed.aid from employmentdetails ed where freetext(*,'"bpi"') union  select e.aid from expertise e where freetext(*,'"bpi"') union  select ge.aid from geographicalexperience ge where freetext(*,'"bpi"') union  select pd.aid from projectdetails pd where freetext(*,'"bpi"') union  select r.aid from [references] r where freetext(*,'"bpi"') union  select t.aid from training t where freetext(*,'"bpi"') 	0.293475471876351
2989141	33122	merging exists and not exists into one query - oracle magic	select distinct st.*  from sometable st       left outer join tab t      on st.a in (t.a,t.b) where t.c is null 	0.0534331766602817
2989725	26808	is it possible to query against these tables?	select distinct v.dataid1value, d1.description,                  v.dataid2value, d2.description,                  v.dataid3value, d3.description   from values v   inner join description d1 on d1.descriptionid = v.dataid1   inner join description d2 on d2.descriptionid = v.dataid2   inner join description d3 on d3.descriptionid = v.dataid3 	0.622718875989873
2990547	31453	sql query help - finding rows with no relationships	select * from client  where person_id not in (select person_id from client_books) 	0.158520725091017
2991710	19161	getting values by time difference in sql	select max(datavalue) - min(datavalue) from table where ([timestamp] < getdate()-0 and ([timestamp] > getdate()-31) 	0.00304479808579861
2992062	20215	mysql - multiple count statments	select sex,   sum(if(datediff(now(),last_login) < 1,1,0)),   sum(if(datediff(now(),last_login) between 1 and 7,1,0)),   sum(if(datediff(now(),last_login) between 7 and 30,1,0)) from player_account_demo  group by sex 	0.493298350022601
2993468	34275	from now() to current_timestamp in postgresql	select * from table where auth_user.lastactivity > current_timestamp - interval '100 days' 	0.014040900977157
2995539	11950	replace bit values with some text	select case gender when 0 then 'man' when 1 then 'woman' end as gender from yourtableorview 	0.161724672435064
2996104	11197	finding a identity specification using sql	select o.name, c.name, c.is_identity from sys.objects o inner join sys.columns c on o.object_id = c.object_id where o.type='u' and c.is_identity = 1 	0.155857707435525
2996210	13232	mysql, get the last created table name	select table_name from information_schema.tables where table_schema = 'some_database' order by create_time desc limit 1; 	0
2997364	4765	select by month of a field	select * from project where month(duedate) = 1 and year(duedate) = 2010 	0.000387654938924293
2999416	37696	find records produced in the last hour	select  * from    whatever where   mytime > dateadd(hour, -1, getdate()) 	0
3000933	36215	getting the max(price) for each item ordered, given multiple different prices for any ordered item	select item, max(price) from items_ordered group by item; 	0
3001681	10772	convert military time to string representation	select substring(convert(nvarchar, dateadd    (hh, hourmil / 100, dateadd(mi, hourmil % 100, '1900-01-01')), 8), 0, 6) 	0.0259328385314332
3003197	29828	select query related problem	select min(rate), sum(amount) from interest group by floor(rate / 0.25); 	0.516854547366196
3004288	31004	join two oracle queries	select pt.id, pt.promorow, pt.promocolumn, pt.type, pt.image, pt.style, pt.quota_allowed, ptc.text, pq.quota_left  from promotables pt, promogroups pg, promotablecontents ptc, promoquotas pq  where pt.id_promogroup = 1 and ptc.country ='049'  and ptc.id_promotable = pt.id and pt.id_promogroup = pg.id and pq.id_promotable = pt.id  union select pt.id, pt.promorow, pt.promocolumn, pt.type, pt.image, pt.style, pt.quota_allowed, null, null from promotables pt  where pt.type='heading' order by 2, 3 	0.339124325832849
3005671	34173	odp.net sql query retrieve set of rows from two input arrays	select id1, id2 from t, (select rownum rn1, a1.* from table(:1) a1) a1, (select rownum rn2, a2.* from table(:2) t2) t2 where (id1, id2) in ((a1.column_value, a2.column_value)) and rn1 = rn2 	0
3006160	9275	is there any optimizations i can do with this statement to get the count of used rows?	select @totalused = count(distinct i.productinfoid)  from productinfo i with (nolock)  join productorderinfo oi with (nolock)      on io.productinfoid = i.productinfoid 	0.244951151958308
3006605	16702	sqlplus remove \r \n \t from spool	select translate(l,'a'||chr(10)||chr(9)||chr(13),'a') from test; 	0.00523903366395917
3009896	28076	get the first and last date of next month in mysql	select date_sub(last_day(date_add(now(), interval 1 month)),                  interval day(last_day(date_add(now(), interval 1 month)))-1 day) as firstofnextmonth,        last_day(date_add(now(),                  interval 1 month)) as lastofnextmonth 	0
3012045	2240	skip first letters of all values returned from a sql server database	select right(companyname, len(companyname)-2) as companyname 	0
3012148	38211	mysql select column from view problem	select `account manager` , .. from `viewmanager` 	0.145095516317456
3012286	1052	mysql search number in table	select * from product where name regexp '^[0-9]' 	0.0175677257276326
3012723	16534	how to change srid of geometry column?	select addgeometrycolumn('table','the_geom4258',4258, 'polygon', 2); update table set the_geom4258 = st_transform(the_geom,4258); 	0.0229016925190388
3014541	15906	t-sql how to: compare and list duplicate entries in a table	select t1.* from table t1 join( select username from table group by username having count(username) >1) t2 on t1.username = t2.username 	0
3015305	8892	how to reuse subquery result in mysql	select id,  count(*) as sum,  sum( if( condition1 , 1, 0 ) ) cond1,  sum( if( condition2, 1, 0 ) ) cond2    from table1 group by id 	0.246049442794165
3018018	33486	convert a date to a string in sqlite	select min(date('your-date-here')) as mindate from tablename 	0.0167434523568663
3019073	10698	how to select first entry of the day grouped by user in sql	select [time sub].client_id,         [time sub].code,         [time sub].minutes,         firstday.minentry from [time sub]       inner join [         select          [time sub].client_id,          min([time sub].[date_entered]) as minentry         from          [time sub]         where           [time sub].code not in ("t", "l")        group by           [time sub].client_id,           datevalue([time sub].[date_entered])  ].as firstday   on firstday.minentry = [time sub].[date_entered]  order by firstday.minentry, [time sub].client_id; 	0
3019773	30496	advice on how to complete specific mysql join	select j.id, b.first_name, a.first_name from jobs j join meta b on j.booked_user_id = b.user_id join meta a on j.assigned_user_id = a.user_id 	0.742668242756998
3020653	19225	check if table exists in c#	select * from <table> where 1 = 0 	0.0524913218067133
3021839	22818	getting a date array from a mysql database?	select distinct substring(date, 1, 11) as date_string from table 	0.00106142164939795
3022509	3006	find records in between date range	select   m.eventid from     majorevents as m where   (                    ((m.locationid = @locationid) or (@locationid is null))             or  (m.locationid is null)         )     and (                 (dateadd(day, datediff(day, 0, m.eventdatefrom), 0) <= dateadd(day, datediff(day, 0, m.@datetimeto), 0))             and (dateadd(day, datediff(day, 0, m.eventdateto), 0) >= dateadd(day, datediff(day, 0, m.@datetimefrom), 0))         ) 	0
3024670	37283	how can i add a column to this union result?	select id as in_id, out_id, recipient, sender, read_flag , 'received' as source   from received where recipient=1 union all  select in_id, id as out_id, recipient, sender, read_flag , 'sent' as source    from sent where sender=1 	0.181689082998326
3028477	40373	how to select rows from table	select c.* from category c    join parent_category pc on c.parent_category_id = pc.id where pc.category_name = 'some name' 	0.000464338242642866
3029454	6860	sql query through an intermediate table	select r.id, r.name from recipes r where not exists (select * from ingredients i                   where name in ('chocolate', 'cream')                   and not exists                       (select * from recipeingredients ri                        where ri.recipe_id = r.id                        and ri.ingredient_id = i.id)) 	0.435505831263873
3030756	18320	selecting from 2 tables in a single query	select * from table2  where t2_id in (select t1_field3 from table1 where t1_field2=43 ) 	0.000177007126430993
3031256	13251	sql query help - return row in table which relates to another table row with max(column)	select       schools.schoolname,       grades.reading  from       schools inner join grades on schools.id = grades.id_schools where       grades.reading = (select max(reading) from grades) 	5.0020029228176e-05
3032401	5741	finding the 20 most commented 20 news	select top 20 news.*, count(news_comment.id) as no_of_comment from news inner join news_comment on news.id = news_comment.newsid order by no_of_comment desc 	0.000122326391459153
3032708	38493	how to compare dates in php and sql?	select * from table where date_column + interval 1 month >= now() 	0.00540327615230925
3034543	1989	how do i select a column with the latest "datetime" data type?	select top 1 ... from mytable where user = @theuser order by datecolumn desc 	0.000106839350870567
3035906	10575	group by sql with count	select a.id as id, a.name as name, a.product as product, isnull(b.cnt,0) as cnt from mytable a left join (select name, count(*) as cnt from mytable group by name) b on a.name = b.name 	0.36580573038398
3037615	34505	sql: 2 counts using joins?	select count(distinct unitid) as units, count(*) as pieces from piece where category = 'a' 	0.316783428321743
3038067	5012	get non-overlapping dates ranges for prices history data	select     sd.product,     sd.price,     sd.startdate,     max(ed.enddate) as enddate from     dbo.priceshist sd left outer join dbo.priceshist ed on     ed.product = sd.product and     ed.price = sd.price left outer join dbo.priceshist ld on     ld.product = sd.product and     ld.price <> sd.price and     ld.enddate < sd.startdate left outer join dbo.priceshist lmd on     lmd.product = sd.product and     lmd.price = sd.price and     lmd.startdate > isnull(ld.enddate, '1900-01-01') and     lmd.startdate < sd.startdate where     not exists (select * from dbo.priceshist md where md.product = sd.product and md.price <> sd.price and md.startdate between sd.startdate and ed.enddate) and     lmd.product is null group by     sd.product,     sd.price,     sd.startdate order by     sd.startdate 	4.62651327004668e-05
3038635	3538	i need to do a view in sql that returns the latest invoice date for each company	select         substring('000000', 1, 6 - len(cast(dbo.companies.companyid as varchar(10)))) +            cast(dbo.companies.companyid as varchar(10)) as client_id      , b.mxdate maxinvoicedate   from dbo.companies c      , (select dbo.invoices.invoicecompanyid companyid              , max(dbo.invoices.invoicedate) mxdate           from dbo.invoices         group by dbo.invoices.invoicecompanyid ) b  where c.companyid = b.companyid  order by 1 	0
3040680	4809	side-by-side comparison of data by year in sql	select product,      max(case when year = 2006 then value end) as [2006 value],      max(case when year = 2007 then value end) as [2007 value]  from mytable group by product order by product 	0.0115085398362561
3043124	2846	getting data from the next row in oracle cursor	select deptno, empno, sal, lead(sal, 1, 0) over (partition by dept order by sal desc) next_low_sal, lag(sal, 1, 0) over (partition by dept order by sal desc) prev_high_sal from emp where deptno in (10, 20) order by deptno, sal desc;  deptno  empno   sal next_lower_sal prev_higher_sal      10   7839  5000           2450               0      10   7782  2450           1300            5000      10   7934  1300              0            2450      20   7788  3000           3000               0      20   7902  3000           2975            3000      20   7566  2975           1100            3000      20   7876  1100            800            2975      20   7369   800              0            1100 8 rows selected. 	0.000236674882219202
3043221	10353	how to get a list of unrepeatable date from my db in php?	select distinct list_date from table 	0.000117526507704596
3044554	5877	get a db result with a value between two column values	select   * from   table_profiles as profiles,   table_users as users where   users.age between profiles.start_age_rage and profiles.stop_age_range 	0
3045041	3020	mysql select where count = 0	select * from table1 left join table2 on(table1.id = table2.table1_id) where table2.table1_id is null 	0.234560665815996
3045823	21239	design pattern for creating an xml document from a database query that has a 1:many relationship	select     bi.isbn,     bi.title,     bi.author,     bi.price,     br.review from     book_info bi     left outer join book_reviews br on br.isbn = bi.isbn where     bi.title like '%learn to%' order by     bi.isbn 	0.00867775300497612
3047789	6276	how to enumerate returned rows in sql?	select     row_number() over(order by age) as rownumber         ,count(*) as usercount      from users      group by age 	0.0129421157322163
3047798	9650	retrieve names by ratio of their occurance	select name, count(name)/(select count(1) from names) from names group by name; 	0
3048068	22129	a logical problem with two tables	select f.date from tbl_fixtures f where f.compname = '$comp_name' union select r.date from tbl_conf_results r where r.compid = '$_get[id]' and r.type2 = '2' group by date 	0.556372425221389
3048398	39256	find groups with both validated, unvalidated users	select users u1 left join groups_users g1 on id=user_id left join groups_users g2 on group_id=group_id left join users u2 on user_id=id where u1.validated=1 and u2.validated=0; 	0.00274691478588378
3051157	11315	how to search dob in db is in the yyyy-mm-dd strucuture. but i have to compare only with yyyy of the field using mysql	select * from table where year(dob) = '2010'; 	0
3051268	6345	how to list out all triggers in a particular table or database?	select * from sys.triggers 	0.000119196365114648
3051631	1813	tsql, how to get smalldatetime's time between two smalldatetime's times?	select value1       from tablea      where convert(varchar, getdate(), 108)     between convert(varchar, table_1.startdate, 108)         and convert(varchar, table_1.enddate, 108); 	0.000190810137737943
3053575	23096	how to order by last name on a full name column?	select * from users order by ltrim(reverse(left(reverse(fullname), charindex(' ', reverse(fullname))))) asc, fullname asc  	0.00010640002425026
3054943	15268	calculate sum time with mysql	select sec_to_time(sum(time_to_sec(timespent))) from yourtable; 	0.0184232618866204
3055493	40616	sorting nested set by name while keep depth integrity	select     n1.name from     dbo.departments n1 order by     (     select         count(distinct n2.lft)     from         dbo.departments n2     inner join (                 select                     n.name,                     n.lft,                     n.rgt,                     (select count(*) from dbo.departments where lft < n.lft and rgt > n.lft) as depth                 from                     dbo.departments n) sq1 on         sq1.lft <= n2.lft and sq1.rgt >= n2.lft     inner join (                 select                     n3.name,                     n3.lft,                     n3.rgt,                     (select count(*) from dbo.departments where lft < n3.lft and rgt > n3.lft) as depth                 from                     dbo.departments n3) sq2 on         sq2.lft <= n1.lft and sq2.rgt >= n1.lft and         sq2.depth = sq1.depth and         sq2.name > sq1.name     ) 	0.297005141230611
3056081	23784	subquery with multiple results combined into a single field?	select i.name as itemname,          group_concat(s.id order by s.id) as salesids,          group_concat(s.date order by s.date) as salesdates,          group_concat(s.containerid order by s.containerid) as containerids,          group_concat(c.name order by c.name) as containertypes     from items i     join sale s on s.id = i.salesid     join containers c on c.id = s.containerid group by i.name 	0.00572819088936153
3056826	29501	how to search for obtaining the "best" result	select * from mytable where match(field) against('nicole kidman films') 	0.0285459965891019
3057746	9734	how to count null values in mysql?	select     count(*) as num from     users where     user_id = '$user_id' and     average is null 	0.0240532750640019
3058646	11694	c# and sql - sub select from a table parameter	select custid  from @custids 	0.10897519478493
3058762	19471	unable to convert from julian int date to regular tsql datetime	select        org_id,  case when date_applied = 0 or date_applied < 639906 then convert(datetime, '1753-01-01') else dateadd(day,date_applied-729960,convert(datetime, '07-25-99')) end as date_applied, case when date_posted = 0 or date_applied < 639906 then convert(datetime, '1753-01-01') else dateadd(day,date_posted-729960,convert(datetime, '07-25-99')) end as date_posted from general_vw 	0.0576434312043842
3060952	35456	find invalid dates in sql server 2008	select     * from    mytable where     isdate(mydate) = 0 	0.38306734761066
3061655	17370	getting percentage of "count(*)" to the number of all items in "group by"	select category, count(*) as total , (count(*) / (select count(*) from item where department='popular')) * 100 as 'percentage to all items',  from item where department='popular' group by category; 	0
3061802	25983	how to get unique values when using a union mysql query	select   * from   (     select        contractno,        dsignoff      from        campaigns      where        clientid = 20010490 and contractno != ''      group by        contractno,dsignoff     union     select        id as contractno,       signoffdate as dsignoff     from        contract_details      where clientid = 20010490)    ) as tmp group by   tmp.contractno 	0.00411417922652251
3062653	8114	select dynamic string has a different value when referenced in where clause	select      ...     , x.thestring     ,...     from table1 join table2 on table1pkey=table2fkey        , (select            string1          ,left(             left((select top 1 strval from dbo.split(string1,' '))                  ,1)             + (select top 1 strval from dbo.split(string1,' ')              where strval not in (select top 1 strval from dbo.split(string1,' ')))             ,6) thestring          from table1        ) x     where x.thestring <> table2.someotherfield       and x.string1 = <whatever you need to join it to> 	0.0120921531206443
3063716	6777	how do i find the top n batters per year?	select b.playerid, b.yearid, b.hr from batting b  where hr >= (     select b2.hr      from batting b2      where b2.yearid=b1.yearid     order by b2.hr desc     limit 2, 1 ) order by b.yearid desc, b.hr desc; 	0
3063879	20635	in sql, how can i count the number of values in a column and then pivot it so the column becomes the row?	select     'quality' as question,     sum(case when quality = 1 then 1 else 0 end) as [1],     sum(case when quality = 2 then 1 else 0 end) as [2],     sum(case when quality = 3 then 1 else 0 end) as [3],     sum(quality) from     dbo.answers union all select     'speed' as question,     sum(case when speed = 1 then 1 else 0 end) as [1],     sum(case when speed = 2 then 1 else 0 end) as [2],     sum(case when speed = 3 then 1 else 0 end) as [3],     sum(speed) from     dbo.answers 	0
3064738	27226	how to search for a specific word in a row in mysql?	select information.data from users join user_keywords on user_keywords.user_id = users.id join information_keywords on information_keywords.keyword_id = user_keywords.keyword_id join information on information_keywords.information_id = information.id where users.id = <id> 	0.00140826627193729
3064997	10739	highlighting data values in a sql result set	select     (case field1         when (select max(field1) from data_table)         then concat('<b>',field1,'</b>')         else field1     end) as field1,     (case field2         when (select max(field2) from data_table)         then concat('<b>',field2,'</b>')         else field2     end) as field2 from data_table 	0.026725393093422
3065855	39147	select nth percentile from mysql	select m1.field, m1.otherfield, count(m2.field)    from mydata m1 inner join mydata m2 on m2.field<m1.field group by     m1.field,m1.otherfield order by     abs(0.4-(count(m2.field)/(select count(*) from mydata))) limit 1 	0.0017020007014398
3066124	11458	compare two table and find matching columns	select a.column_name  from information_schema.columns a  join information_schema.columns b  on a.column_name = b.column_name  and b.table_name = 'table2'  and b.table_schema = database()  where a.table_name = 'table1'  and a.table_schema = database(); 	0
3066700	33432	oracle aggregate function to return a random value for a group?	select deptno,max(sal),min(sal),max(rand_sal)  from( select deptno,sal,first_value(sal)       over(partition by deptno order by dbms_random.value) rand_sal from emp) group by deptno / 	0.0929056690620735
3068268	23635	getting highest results in a join	select a.id, a.title, ab.bid_points, u.display_name  from auction as a inner join (select auction_id, max(bid_points) as maxamount from auction_bids group by auction_id) as maxbids on maxbids.auction_id = a.id inner join auction_bids as ab on a.id = ab.auction_id inner join users as u on u.id = ab.user_id where ab.auction_id = maxbids.auction_id and ab.bid_amount = maxbids.maxamount 	0.00681408787650885
3068609	7079	how to find the difference between 2 times in mysql-like db in a single query	select timediff(max(time), min(time)) as visit_length from page_view group by(id) 	0
3070639	18566	sort mysql result set using comparison between 2 columns of same value type	select d.val, d.tstamp from (     (         select val as val, last_updated_1 as tstamp         from table_1         order by tstamp         limit 50     )     union     (         select val as val, last_updated_2 as tstamp         from table_2         order by tstamp         limit 50     ) ) as d order by d.tstamp limit 50; 	0
3075730	41016	disperse relational structure of mysql table	select user, min(case when number = 10 then myvalue end) as number10, min(case when number = 11 then myvalue end) as number11, min(case when number = 12 then myvalue end) as number12 from table where number in (10,11,12) group by user 	0.105011922977005
3076283	16867	sql count returning one value (and not the total)	select nid from bird_countries group by nid having count(*) = 1 	0.000315768299991436
3078370	1734	how to find least non-null column in one particular row in sql?	select if(col1 is null or col2 is null, coalesce(col1, col2), least(col1,col2)) 	0
3079802	2480	sql query to get new data across tables	select name, code  from new n where not exists(select * from current c                   where c.name = n.name or c.code = n.code) 	0.00178349552480974
3081601	27889	how to query multiple columns into more columns in oracle 10g	select a.col1, a.col2, b.col1, b.col2, c.col1, c.col2  from view a, view b, view c  where a.col3 = 1   and  b.col3 = 2   and  c.col3 = 3 	0.00260070029332452
3081647	24422	how do i select only rows that don't have a corresponding foreign key in another table in mysql?	select free_date from calendar c   where not exists (select * from listing                      where listing_id = c.listing_id); 	0
3081741	137	sql summing multiple joins	select col1, col2, sum(col_one) from      (select col1, col2, sum(col_one)            from table1            where <conditionset1>            group by col1, col2      union all      select col1, col2, sum(col_one)           from table1            where <conditionset2>            group by col1, col2) group by      col1, col2 	0.524544454068041
3081806	18110	how do you measure the number of open database connections	select spid,        status,        program_name,        loginame=rtrim(loginame),        hostname,        cmd from  master.dbo.sysprocesses where db_name(dbid) = 'test' and dbid != 0 	0.00144220183507898
3083749	7213	postgresql: is it possible to dynamically loop through a table's column	select      column_name  from      information_schema.columns  where      table_schema = tg_table_schema  and      table_name = tg_table_name; 	0.194691236042226
3085703	32524	is there a quick way to compare two equally formatted tables in sql?	select 'table1' as tblname, *  from   (select * from table1    except    select * from table2) x union all select 'table2' as tblname, *  from   (select * from table2    except select *     from table1) x 	0.0116881310526284
3085966	25527	sql selectl rows to colums without subquery	select max(decode(codigo, 190, info, '')) info_190,  max(decode(codigo, 130, info, '')) info_130,  max(decode(codigo, 140, info, '')) info_140 from t_test where grupo = 'vtos'; 	0.0604892451306332
3086299	35555	sql code to select to select unique column and match with row on another column	select secid, serviceid, userid from   (     select row_number() over (partition by serviceid order by secid) as row_number,     secid,     serviceid,     userid     from tblsecserviceusers  )   temptable  where row_number = 1 	0
3086817	30172	select distinct values from two columns	select t.itemid,        t.direction,        t.uid,        t.created   from table t   join (select a.itemid,                max(a.created) as max_created           from table a       group by a.itemid) b on b.itemid = t.itemid                           and b.max_created = t.created 	4.84525788084757e-05
3086889	35533	unable select unique values from a query	select c1.categorychild as cname1,c2.categorychild as cname2  from members as m, join categorychild as c1 on(m.categorychildid1 = c1.categorychildid) join categorychild as c2 on(m.categorychildid2 = c2.categorychildid) where m.memberid=50 	0.00331113663074713
3087020	17119	list number of rows per field value in sql	select employeeid,count(*) from yourtable group by employeeid 	0
3087836	4045	db2 how to get the last insert id from a table	select id from new table (insert into (val1, val2, ...) values ('lorem', 'ipsum', ...) 	0
3087941	7912	subtracting two columns in sql after join	select      a.purchaseid,      abs(a.purchaseid - b.purchaseid) as diff from      purchaseid a inner join purchaseid b on a.purchaseid=b.purchaseid where a.purchaseid=?      and a.purchasedate=?      and b.purchasedate=? 	0.00348817958178082
3088086	23023	how to get the constraints on a table	select object_name(object_id) as [constraint],schema_name(schema_id) as [schema], object_name(parent_object_id) as [table], type_desc as [type] from sys.objects  where 1=1   and object_name(parent_object_id)='yourtablename' and type_desc like '%constraint' 	0.000201733063402125
3088686	9690	how to make a "distinct" join with mysql	select p.upc,           p.name,           ph.price,           ph.date      from product p left join price_h ph on ph.product_id = p.id      join (select a.product_id,                    max(a.date) as max_date              from price_h a          group by a.product_id) x on x.product_id = ph.product_id                                  and x.max_date = ph.date 	0.401231260504043
3088904	41332	how to find all foreign keys?	select tab1.table_name from  information_schema.referential_constraints as ref inner join information_schema.table_constraints as prim on ref.unique_constraint_name=prim.constraint_name and ref.unique_constraint_catalog=prim.constraint_catalog and ref.unique_constraint_schema=prim.constraint_schema inner join information_schema.table_constraints tab1 on ref.constraint_name=tab1.constraint_name and ref.constraint_catalog=tab1.constraint_catalog and ref.constraint_schema=tab1.constraint_schema where prim.table_name='yourtablename' 	6.04881622516742e-05
3088920	35726	is there a way to optimize a mysql query that runs a function on every row?	select latitude, longitude from mytable where   offense = 'green' and   latitude between rect_left and rect_right and   longitude between rect_top and rect_bottom and   mywithin(     pointfromtext( concat( 'point(', latitude, ' ', longitude, ')' ) ),     polyfromtext( 'polygon(( ...bunch of lat longs...))' )) = 1; 	0.398251112596732
3089336	24863	include a blank row in query results	select -1, '(please choose one)' union select * from datstatus order by statusname 	0.0247318791677669
3090132	39486	one table, three column mysql query question	select       hostname,       group_concat(concat_ws("-", name, m_timestamp)) from      (select            hostname,            name,           cast(max(timestamp) as char(24)) as m_timestamp       from            comments       group by            hostname,           name) as a group by       hostname 	0.057278046410092
3091349	29903	using select distinct in mysql	select name, type, state, country from table group by name; 	0.176440667330737
3091515	20764	how to output the number of times data occurs using sql?	select acc.visitcount as total_visits,        count(acc.visitcount) as number_of_visitor_ids   from ( select visit_id,         count(visit_id) as visitcount   from visits   group by visit_id ) acc group by acc.visitcount 	5.45544426883964e-05
3092463	12621	t-sql query not bringing back a count of 0	select  storecharge.storeid,          count(distinct(isnull(wholesalerinvoice.wholesalerid,0))) as invoices  from    storecharge       left outer join      wholesalerinvoice on storecharge.storeid = wholesalerinvoice.storeid  and datediff(day,wholesalerinvoice.invoicedate,'20100627') > =0  and datediff(day,dateadd(day,-7,'20100627'),wholesalerinvoice.invoicedate) > 0  where   storecharge.companyid = 2  group by    storecharge.storeid 	0.407366870680785
3095135	5440	cumulative sum over days	select t1.date, sum(t2.count) from mytable t1 inner join mytable t2 on t2.date <= t1.date group by t1.date 	0.000948459762824907
3095474	26747	php/mysql pagination	select col from table limit  0,5;  select col from table limit  5,5;  select col from table limit 10,5;  	0.559118844182578
3096507	15414	how do i join on "most recent" records?	select t.* from articles as t         inner join  revision lasthis on t.id = lasthis.fk_id             left join revision his2 on lasthis.fk_id = his2.fk_id and lasthis.created_time < his2.created_time where his2.id is null 	0.000201133419672404
3097150	30217	add a temporary column with a value	select field1, field2, 'example' as tempfield from table1 	0.00304445488269246
3100877	35113	lookup table for oracle decodes?	select nvl((select state_desc from lookup where state_num=state),to_char(state)) from states_table 	0.340926880544332
3100921	31388	average of grouped rows in sql server	select column1, avg(column2) from table group by column1 	0.000237637853125302
3101851	23686	find high and low prices in sql	select p.id as productid,  nullif(sum(case when idx=1 then price else 0 end), 0) as highprice, nullif(sum(case when idx=2 then price else 0 end), 0) as lowprice  from (     select productid, price, row_number() over(partition by productid order by price desc) as idx from prices ) t right join products p on t.productid = p.id group by p.id 	0.0109080370562427
3104073	17856	mysql many to many query	select g.*, ht.name, ht.tid, at.name, at.tid, ht.league from games g join team_games htg on htg.gid = g.gid and htg.homeoraway = 1 join team ht on ht.tid = htg.tid join team_games atg on atg.gid = g.gid and atg.homeoraway = 0 join team at on at.tid = atg.tid 	0.306581723877029
3104714	15262	modifying a sql query within the select statement	select case    when recordupdated = true then 'yes'    when recordupdated = false then 'no'  end recordupdates ... 	0.760102432678321
3105031	23040	how to compare a datetime type in sql server	select *  from res  where datesubmit between '6/17/2010 5:01:26 pm' and '6/17/2010 5:01:27 pm' 	0.0198895625015882
3105052	27397	how do you merge rows from 2 sql tables without duplicating rows?	select  p.id, p.name, p.email_address, p.phone_number, group_concat(concat(job_title, ' for ', department, ' department')  separator '\n') as jobroles from people as p      inner join job_roles as r on p.id = r.person_id group by p.id, p.name, p.email_address, p.phone_number  order by p.name; 	0
3105053	11755	count query results on multi-join statements	select      cnt.loginid,      count(*) from contact cnt      right join grpmem list on cnt.contact_uuid = list.member      left join contact grp on grp.contact_uuid = list.group_id      join contact_acctyp cntacc on cnt.contact_uuid = cntacc.contact_uuid where cntacc.c_acctyp_id in (select id from acctyp_v2 where sym like 'cdn%') group by      cnt.loginid 	0.764246255642562
3107795	38163	query to collect data from previous rows	select [co.nr], (select top(1) employee from mytable b where b.[co.nr]=a.[co.nr]  and                          employee is not null order by nr desc) as employee, (select top(1) resp from mytable b where b.[co.nr]=a.[co.nr]  and                          resp is not null order by nr desc) as resp, (select top(1) description from mytable b where b.[co.nr]=a.[co.nr]  and                          description is not null order by nr desc) as description, (select max([date]) from mytable b  where b.[co.nr]=a.[co.nr]) as date from ( select distinct [co.nr]   from mytable ) as a 	0.00022345426322422
3107993	1605	row counting a joined column without affecting the returned rows?	select issues.*,        comments.author as commentauthor,        favorites.userid as favorited,        (            select count(favorites.id)            from favorites            where ticketid = issues.id        ) as numfavorites from issues left join comments     on comments.issue = issues.id     and comments.when_posted = issues.when_updated left join favorites     on favorites.ticketid = issues.id     and favorites.userid = ?uid 	0
3108262	20595	where all is not null	select * from schedule    where id is not null and foo is not null and bar is not null;  	0.307380673646871
3109190	8718	sql server xml column exist() query	select * from xmltest where data.exist('/data/item[type[@v=''3''] and value[@v=''debit'']]') = 1 	0.310321485006948
3110144	12260	sql - converting char to exact length varchar	select cast(rtrim(mycharcol) as varchar(8000)) from mytable 	0.132633245227454
3112747	6954	how to convert newlines (replace \r\n with \n) across all varchar and nvarchar fields in a database	select 'update ' + sc.name + '.' + t.name + ' set ' + c.name + ' = replace(' + c.name + ', char(13)+char(10), char(10))' from sys.columns c     inner join sys.systypes st         on c.system_type_id = st.xtype             and charindex('varchar', st.name) <> 0     inner join sys.tables t         on c.object_id = t.object_id     inner join sys.schemas sc         on t.schema_id = sc.schema_id 	0.000305802042047491
3112941	7753	convert from using 3 identical sql params to 1	select u.email, case when a.user_id is null then 'role_user' when a.auth_type = 's' then 'role_admin' when a.auth_type = 'l' then 'role_licensee' end as 'authority' from users u left join auth_sys a on u.user_id = a.user_id where u.email = **?** 	0.00982747409117546
3116383	24735	how to change the structure of a name field in mysql	select trim(substr(@name, locate(",", @name) + 1)) as prename, trim(substr(@name, 1, locate(",", @name) - 1)) as surename 	0.00108999152568422
3117088	1720	multiple count values on one column	select     c.title, count(cn.category_id) from       categories c left join  categories_news cn on         c.id = cn.category_id group by   c.title 	0.000419921567435844
3117718	9218	a join query for three tables!! for the given condtion below	select *  from orders o, customers c, orderstatus s where o.customerid = c.customerid and o.order_status_id = s.order_status_id and c.firstname = 'om' and c.lastname = 'the eternity' and o.orderid = 752 and ... 	0.0277006335604406
3118332	35187	adding table lock manually to specified table in sql server	select * from mytable with (lockname) 	0.544355931237265
3118714	14383	how to get latest id number in a table?	select id from table order by id desc limit 1 	0
3119840	36412	selecting an item matching multiple tags	select i.uid     from items i     join item_tags it on it.uid_local = i.uid                    and it.uid_foreign in (1, 2) group by i.uid   having count(distinct it.uid_foreign) = 2 	6.88139684698043e-05
3120166	32851	single sql query to find rows where a value is present for one key but not another given key	select a.p_id      from a_p a left join a_p b on b.p_id = a.p_id                and b.a_id = 2     where a.a_id = 1       and b.p_id is null 	0
3120263	36046	sql query, distinct rows needed	select id, name from departments o  where o.thedate=   (select max(i.thedate) from departments i where o.id=i.id) 	0.378632945412157
3120835	13112	how to pivot rows into columns (custom pivoting)	select     dy,     max(case when period = 1 then subj else null end) as p1,     max(case when period = 2 then subj else null end) as p2,     max(case when period = 3 then subj else null end) as p3,     max(case when period = 4 then subj else null end) as p4,     max(case when period = 5 then subj else null end) as p5,     max(case when period = 6 then subj else null end) as p6,     max(case when period = 7 then subj else null end) as p7 from     classes group by     dy order by     case dy         when 'mon' then 1         when 'tue' then 2         when 'wed' then 3         when 'thu' then 4         when 'fri' then 5         when 'sat' then 6         when 'sun' then 7         else 8     end 	0.00260910356566654
3122180	34923	display a random set of 10 questions and answers with mysql and php	select * from answers where an_quid in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 	9.42381916945945e-05
3122479	9505	how to find the lowest common denominator on one side of a many to many query	select ic.colorid, c.name from itemcolors as ic     join colors as c         on c.id = ic.colorid group by ic.colorid, c.name having count(*) =   (                     select count(*)                      from items as i2                      ) 	0
3125478	7807	how to select multiple results for a single row - mysql	select g.id, g.name, g.desc, group_concat(p.name) as platforms     from game g     join game_platform gp on gp.game_id = g.id     join platform p on gp.platform_id = p.id     group by g.id, g.name, g.desc 	0.00109519392973089
3126332	32175	sql syntax with more than one row	select topics.topic_id, topics.topic_subject, count(posts.post_topic) as comments from topics join posts on topics.topic_id = posts.post_topic group by topics.topic_id, topics.topic_subject limit 10 	0.118816815707449
3127074	3255	wordpress mysql query for post thumbnail	select a.post_title,max(c.guid) from wp_posts a left join (select post_parent, max(post_date_gmt) as latest_image_date from wp_posts where post_type='attachment' group by post_parent) b  on a.id=b.post_parent left join wp_posts c on c.post_parent=a.id  and c.post_type='attachment'  and b.latest_image_date = c.post_date_gmt group by a.post_title 	0.219154254737963
3128460	35543	how to select this in mysql?	select * from [tablename] where [fieldname] = 0 or [fieldname] is null 	0.605543184475843
3129858	20393	mysql:show all value of three fields	select nik, line, model from inspection_report     order by insp_datetime desc limit 0,30; 	0.000246192062635256
3130810	36507	update primary key from table in another database	select 2ndindent from table group by 2ndident having count(2ndindent) > 1 	0.000103942505735937
3130833	32318	sqlite: go to previous record in result set?	select f1, f2, f3 from tbl limit 50 offset 0 select f1, f2, f3 from tbl limit 50 offset 50 select f1, f2, f3 from tbl limit 50 offset 100 	0.00230182839365672
3132676	36337	part 2 - formate the double precisiont's as 0.00 in postgresql	select trim(to_char(00,'999999990d99')); 	0.73933376974192
3132734	15423	cannt get a record by the row number	select id from (select id, row_number() over(order by id) as rownum from t_task) dr where rownum = 5 	0
3132773	19343	days of last month inpl/sql	select  last_day(add_months(sysdate, -2)) + level from    dual connect by         level <= last_day(add_months(sysdate, -1)) - last_day(add_months(sysdate, -2)) 	0
3132782	7972	sql count distinct times with a 30 minute difference	select employeecode, starttime from schedule s1     where not exists (select * from schedule s2          where s2.employeecode = s1.employeecode and               s2.starttime > dateadd(mi, -29, s1.starttime) 	0.000659925150192097
3133785	21380	select exactly one row for each employee using unordered field as criteria	select distinct emplid, coalesce(   (select phone from employees where emplid = e1.emplid and phone_type = 'home'),   (select phone from employees where emplid = e1.emplid and phone_type = 'work'),   (select phone from employees where emplid = e1.emplid and phone_type = 'other') ) as phone from employees e1 	0
3134298	36107	display more than one row with the same result from a field	select     iditem from     some_table st inner join numbers n on     n.number > 0 and     n.number <= st.cantidad 	0
3134735	12822	database design: running totals of row counts	select ... group by ... 	0.00624223593982987
3135970	39899	mysql: retrieve more than 1 linked field in same table	select a.name, m.score_1, b.name, m.score_2 from matches as m inner join teams as a   on m.id_team_1 = a.id_team inner join teams as b   on m.id_team_2 = b.id_team 	5.21589544616559e-05
3136050	17447	specify data type with column alias in sql server 2008	select cast (case                 when lower(h.outofserv) = 'y' then 1                 else 0               end as bit) as oos   from history h 	0.749157285109657
3138631	31419	how to get all the tables and structure in a database in a printed format?	select  t.table_schema,         t.table_name,         c.column_name,         isnull(c.column_default, '') as 'column_default',         c.is_nullable,         c.data_type,         isnull(c.character_maximum_length, isnull(numeric_precision,'') + isnull(numeric_scale, isnull(datetime_precision,''))) as 'size' from information_schema.tables t join information_schema.columns c on    t.table_catalog = c.table_catalog                                 and     t.table_schema = c.table_schema                                 and     t.table_name = c.table_name where t.table_type = 'base table' order by t.table_schema, t.table_name, c.ordinal_position 	0
3139687	13754	usage of in clause in a database query	select   * from   khatapayment_track t     inner join khata_header h on (h.property_id = t.property_id) where   h.div_id = 2 	0.601411584886652
3139781	27126	mysql : group rows my multiple columns and return the count	select a.pathway_id, b.pathway_id, count(*) from t a inner join t b on a.ontology_term = b.ontology_term group by a.pathway_id, b.pathway_id 	0.000844167855575435
3140947	19208	mysql use group by column in where condition	select column1.....,sum(hits) as hitssum  from table  group by column1..... having hitssum > 100 	0.507424803512964
3141463	12243	inner join with count() on three tables	select     people.pe_name,     count(distinct orders.ord_id) as num_orders,     count(items.item_id) as num_items from     people     inner join orders on orders.pe_id = people.pe_id          inner join items on items.ord_id = orders.ord_id group by     people.pe_id; 	0.334694001047802
3141861	27103	can i select multiple columns depending on a select case?	select  person.firstname     , person.lastname     , case when substatus is not null then 'hassubstatus' end as [hassubstatus]     , case when substatus is null then 'doesnothavesubstatus' end as [doesnothavesubstatus] from person person 	0.00240293973660142
3143604	6120	select from two tables to find vat rate based on effective date	select rd.rate_id, r.name, rd.rate from (     select rate_id, max(effect_date) as maxeffectdate     from vat_rates_details     where effect_date < now()     group by rate_id ) rdm inner join  vat_rates_details rd on rdm.rate_id = rd.rate_id and rdm.maxeffectdate = rd.effect_date inner join vat_rates r on rd.rate_id = r.rate_id 	0
3144393	37575	querying a database or a datatable for duplicate records in one column	select     id,     my_data from     my_table where     my_data in     (         select             my_data         from             my_table         group by             my_data         having             count(*) > 1     ) 	9.75222613680968e-05
3145993	3726	joining tables: case statement for no matches?	select x.name, sum(index) from ( select p.text,se.name,s.sub_name,sum((p.volume / (select sum(p.volume)              from phrase p             where p.volume is not null) * if(sp.position is null,200,sp.position))) as `index` from phrase p left join `position` sp on sp.phrase_id = p.id left join `engines` se on se.id = sp.engine_id left join item s on s.id = sp.site_id where p.volume is not null and s.ignored = 0 group by se.name,s.sub_name order by se.name,s.sub_name  )x group by x.name 	0.254298931960329
3147119	3720	getting one to one result from one to many relationship	select *  from order where order_number in     (select order_number      from order_details      group by order_number      having count(*) = 1) 	0
3147720	37356	comparision of two table having same field?	select first.* from first left join second on(first.id = second.id) where second.id is null 	0.00019785688726514
3148238	32644	how to use nested select	select l1.id as select_id from location l1 where l1.id in (     select l2.id      from location l2, location l3      where l2.id = 1 or l2.parentlocation_id = 1 or (l2.parentlocation_id = l3.id and l3.parentlocation_id = 1) ) 	0.744042909114461
3150462	16118	how to get all rows that contain characters others than [a-za-z] in mysql	select *  from contact_info  where address not regexp '^[a-za-z0-9]*$'; 	0
3151369	39413	how to get two rows value	select concat(id, name) from mytable 	4.74902954337332e-05
3154368	7201	count occourances by hour in php	select count(*) as `cnt`, hour(`state_time`) as `hr` from nagios_statehistory where object_id='$tosearch' and output='critical - socket timeout after 10 seconds' group by `hr` order by state_time desc 	0.0267220064386364
3156098	11051	using a mysql table to access a lookup table?	select distinct sports.id, sportsarticles.data  from sportsarticles, sports where sports.id = (yourid)     and sports.id = sportarticles.sports 	0.0548819595246506
3156512	6217	how to implement select trim(string,','); for mysql?	select trim(both ',' from ',hi,test,') 	0.758820364944023
3157117	14778	how can we give multiple alias for a column in sql?	select name1, name1 as name2 from    (select myfunction(column1) as name1 from mytable) base; 	0.480422263663775
3157643	40271	how to select one text column, which string length >0?	select * from some_table where length(some_string) > 0; 	0.000575867483441622
3157671	19193	truncate all table in mysql database	select 'truncate table ' || table_name || ';'    from information_schema.tables; 	0.00351896897521639
3157990	23311	sql query get distinct records	select  distinct a.cid         , a.firstname         , a.lastname         , b.typeid         , b.email  from    tablea a         inner join (           select  cid, min(typeid), min(email)           from    tablea            group by                   cid         ) b on b.cid = a.cid 	0.00481608152366132
3158516	12658	string manipulation sql	select replace(my_column, 'order was assigned to ', '') 	0.430845124479963
3158780	34386	sql query to avoid duplicates and order by a row	select max(rvw_id), upc_cd, max(cmpl_date) from rvw_tsk group by upc_cd 	0.147821018389416
3159528	14671	query a union query	select [all].latd, [all].latm, [all].lats, [all].lond,  [all].lonm, [all].lons, [all].freq from [all] where latd =37 and latm=53 and lond=76 and lonm=37; 	0.679679244934273
3160176	6428	can i pass multiple rows from a stored procedure query into another query?	select * from dbo.aspnet_usersinroles  where userid in (      select userid from aspnet_users      where username = @username   ) 	0.00332740181724666
3162585	703	sql group by - select both columns	select * from users where userid not in ( select min(userid) from users group by age, experience_level having count(*) = 1 ) 	0.0272410198300239
3162623	41060	how do i get a list of unique values and the number of occurences from sql server 2008?	select   column1,   count(*) from   table group by column1 	0
3163503	13474	sorting union queries in mysql	select *, ((title like '%…%')*2 + (description like '%…%')) as rank     from jobs    where title like '%…%'       or description like '%…%' order by rank desc, time desc 	0.590690491568959
3165912	22868	mysql join a view table as a boolean	select users.user_id,name,age, view_table.user_id is not null as in_view from users  left join view_table using (user_id) where user_id = 555 	0.333576453063478
3167175	18442	how can i get the greatest string value that can be converted to an int from sql server?	select max(cast(wono as integer)) as wono from (     select wono       from yourtable     where isnumeric(wono) = 1 ) subtable 	0.000544985957588421
3168529	32362	sql access how to return between dates	select orders.*   from orders  where orders.orderdate between #3/1/96# and #6/30/96#; 	0.0110858288083479
3169193	4329	oracle query on string	select * from "my table" where field='xxxx/xxxx' 	0.319238698395439
3169933	33088	suggestion for finding similar rows in mysql	select *, match(project_title) against('sample project 55') as similarity     from projects     where status in(1, 2, 3, 4, 5, 6) and id != ? and match('sample project 55') against(?)     order by similarity desc 	0.019809722937786
3170616	6182	selecting counts of multiple items, grouped by date	select o.date, count(if(oi.type='tshirts', 1, null)) as tshirts, count(if(oi.type='mugs', 1, null)) as mugs from order_item oi left join order o on oi.order_id = o.id group by o.date 	0
3172860	16265	mysql query design for latest post per forum	select p.* from forums_posts p join forums_threads t on p.tid = t.tid where not exists (     select * from forums_posts p2 join forums_threads t2 on p2.tid = t2.tid     where t.fid = t2.fid and p.date < p2.date ); 	0.000819165196747887
3172970	16192	0 , null, empty string, default values - mysql questions	select if(0, 'true', 'false') 	0.0249397733824642
3173930	29335	how to divide data in multiple columns in tsql	select      salesid, [name], grandtotal as 'price' from      dbo.sales  where     (some condition) 	0.0038478247836416
3175409	372	getting metadata from another database in an sproc in sql server?	select  tbl.name as tablename, sch.name as schemaname, hasidentity = case when exists (select * from your_target_db.sys.columns as cols where tbl.object_id = cols.object_id and is_identity = 1) then 1 else 0 end  from your_target_db.sys.tables as tbl inner join  your_target_db.sys.schemas as sch on tbl.schema_id = sch.schema_id 	0.0165875577454635
3176922	31417	add information in mysql	select id_user, hour, nvl(medition,0) from `hours` as h left join `mytable`     on `hours`.`hour` = `mytable`.`hour` 	0.0480110136619285
3179053	913	improving query times a sql ip lookup database	select id, ipfrom, ipto, countrycode, countryname,region,city from ( select top 1 id, ipfrom, ipto, countrycode, countryname,region,city from tbl_ip  where @ip <= ipto order by ipto intersect select top 1 id, ipfrom, ipto, countrycode, countryname,region,city from tbl_ip  where ipfrom <= @ip order by ipfrom desc ) ip 	0.454180251929229
3179285	1726	joining a table on itself	select   *, columnb from   mytable where   columna = 'apple' 	0.0166595863956621
3180368	16718	sql - how to get the unique key's column name from table	select * from information_schema.table_constraints tc where tc.table_name = 'mytablename' and tc.constraint_type = 'unique' 	0
3180460	8549	mysql get rows, but for any matching get the latest version	select section, content from cms_content t1 where page in ('/', 'index.html')  and enabled = 1 and timestamp = (     select max(timestamp)     from cms_content t2     where page in ('/', 'index.html')      and enabled = 1     and t1.section = t2.section ) 	0
3180538	34136	determining whether to store xml data as xml or in normalized tables	select (columns) from dbo.table for xml..... 	0.0020353890903365
3180834	21847	retrieving xml element name using t-sql	select distinct r.value('fn:local-name(.)', 'nvarchar(50)') as t from     @xml.nodes(' 	0.0110113199846083
3181284	23441	inner join: limit 0,1 on the second table	select *  from products inner join images on products.id=images.prod_id  where products.cat='shoes' group by products.id 	0.0131168928316937
3182275	32577	how to group summed up columns from different tables?	select       u.id as user_id,       count(submitter_id) as tutorials_count,     ifnull(sum(rating_positive), 0) as pos,     ifnull(sum(rating_negative), 0) as neg from user u left join (     select submitter_id, rating_positive, rating_negative from trick     union all     select submitter_id, rating_positive, rating_negative from video     union all     select submitter_id, rating_positive, rating_negative from other ) t1 on u.id = t1.submitter_id group by u.id order by tutorials_count desc limit 10 	5.54910238171498e-05
3183673	6359	how can i limit the selection in mysql?	select * from tbl limit 95,18446744073709551615; 	0.205820437335895
3185299	19466	how to select two seperate non-overlapping tables in mysql	select t1.* , t2.* from table1 t1 right outer join table2 t2 on 1 = 0 union select t1.* , t2.* from table1 t1 left outer join table2 t2 on 1 = 0 	0.00227116425810776
3185803	864	find rows that has all the linked rows	select u.id, u.name ... from user u join userright r on u.id = r.user_id where right_id in (1,2,3) group by u.id, u.name ... having count distinct(right_id) = 3 	0
3188921	22983	mysql order by rand() grouped by day	select * from (select * from tbl order by rand()) as t group by date(md) 	0.00368765317917358
3190176	5674	joining one table multiple times with null fks	select g.id, p1.gender, p2.gender      from games g left join players p1 on p1.id = g.player1id left join players p2 on p2.id = g.player2id 	0.000566301462138243
3191555	13425	easier way to select max() based on conditions?	select top 1 id from table where date = '2010-01-01' order by value desc 	0.00826138376271984
3191860	8223	join two mysql queries based on parameters	select    q1.campaign_id as campaign_id,    q1.from_number as mobile,   q1.received_msg as join_txt,   q1.date_received as join_txt_date,   q2.received_msg as final_txt,   q2.date_received as final_txt_date from received_txts q1 join received_txts q2   on q2.msg_link_id = q1.id     and q2.campaign_id = q1.campaign_id     and q2.from_number = q1.from_number where q1.action_id = 4   and q2.action_id = 4   and q1.msg_link_id = q2.id   and q2.msg_complete_id = q2.id 	0.0165246308102074
3192155	3320	select a range of values in mysql	select * from comments where approved = 1 limit 3,some_huge_number 	0.000729761640431741
3192585	24716	restricting an sql query to certain fields in a table not used by the query	select month(saledate), sum(sales.cost) from sales, products where sales.productname=products.productname and category='food' group by month(saledate) union all select month(purchasedate), sum(purchases.cost) from purchases, products where purchases.productname=products.productname and category='food' group by month(purchasedate) 	0.00658323188265586
3193617	6090	returning multiple columns and grouping by month	select themonth, sum(sales) as sumsales, sum(purchases) as sumpurchases from  ( select date_format(thedate, "%y-%m") as themonth, cost as sales, 0 as purchases    from sales, products    where sales.productname=products.productname and category='food'   union all    select date_format(thedate, "%y-%m") as themonth, 0 as sales, cost as purchases    from purchases  ) as all_costs group by themonth; 	0.000980234849187103
3193795	1789	t-sql count rows with specific values (multiple in one query)	select igrp,      count(case when value1 > 1 then 1 else null end) as v1high,      count(case when value2 > 1 then 1 else null end) as v2high  from tbl group by igrp 	0.00028456653719312
3193886	41216	need help with a sql query selecting date ranges from a table of period quarters	select * from periods where  dateadd(qq,periodquarter-1,dateadd(yy,periodyear -1900,0))  between @startdate and @enddate 	0.000155599764652296
3193956	22041	how to get every attribute's name, value and parent element name in sqlxml?	select     elem.value('local-name(..)', 'nvarchar(10)') as 'parent name',     elem.value('local-name(.)', 'nvarchar(10)') as 'attribute name',     elem.value('.', 'nvarchar(10)') as 'attribute value' from     @content.nodes(' 	0
3195193	13564	select xml nodes as xml in t-sql	select     pref.query('.') as xmlextract from       @xml.nodes('/*/*') as extract(pref) where     pref.value('./*[1]', 'nvarchar(10)') is not null 	0.158378369837605
3195869	38309	how to merge lines in an sql query?	select foreign_id  from your_table where string in ('house', 'window') group by foreign_id having count(distinct string) = 2; 	0.0253541199780051
3196116	11573	a better way to return '1' if a left join returns any rows?	select a.a_id, a.col_2, col_3,      b.col_2, a.col_4,      case when exists (select * from c                       where a_id = a.a_id)          then 1 else 0 end as c_exists  from a join b       on (a.b_id = b.b_id)   where a.a_id = ?      order by case when a.col_2 = ?             then 0 else 1 end, col_3; 	0.230472430901748
3196851	20752	where clause on a column that's a result of a udf	select t.col1, t.col2, funcresult.x from table as t     cross apply ( select myudf(t.col1, t.col2) as x ) as funcresult where funcresult.x > 0 	0.234470537660883
3197322	14829	sql query at least one of something	select u.*   from users u  where exists(select null                 from posts p                where p.user_id = u.id                  and p.rating > 10) 	0.00726962584485569
3199154	30548	produce leading 0 in the minutes field	select datename(hh,dateadd(hh, -5, [time])) + ':' +      right('00' + datename(mi,[time]), 2) 	0.00812492227018239
3199157	19068	grouping fields by category and arranging by date, and calculating from another table	select s.productname, sum(s.quantity), sum(s.cost) from sales as s left join products as p on s.productname  = p.name  where month(s.saledate) = month(now()) and p.category = 'food' group by s.productname 	0
3200617	22131	which databases support encryption	select *, aes_decrypt(`field`, 'key') as `decrypted` from enc where aes_decrypt(`field`, 'key')='$input' 	0.76795685685409
3201359	425	joining the same table twice on different columns	select       complaint.complaint_text,       a.username,       b.username from       complaint       left join user a on a.user_id=complaint.opened_by       left join user b on b.user_id=complaint.closed_by 	0
3201432	34419	how to get time part from sql server 2005 datetime in hh:mm tt format	select ltrim(right(convert(varchar(20), getdate(), 100), 7)) 	0.000362391390627374
3204563	20627	getting the most recent records with 2 or more related entries with sql	select top 3     gt.id from     grouptable gt     inner join groupitem gi1 on gi1.groupid = gt.id where     gt.id in      (     select groupid     from         groupitem gi2     where         gi2.id = gt.id and         gi2.createdby = @user     ) group by      gt.id having      count(*) >= 2 order by     max(gi1.creationdate) desc 	0
3205790	30544	sql -- derive date difference column	select      e1.rowid,      e2.endtime as starttime,      e1.endtime, runningtime=convert(varchar(20), e1.endtime - e2.endtime, 114) from endtimetest e1     left join endtimetest e2 on e2.endtime =              (select max(endtime)                from endtimetest                where endtime < e1.endtime) 	0.00563284871303917
3206935	2777	sql same column in one row	select orders.id, lut1.name as orderstatus, lut2.name as servicetype from orders     inner join lut lut1 on  order.id = lut.statusid     inner join lut lut2 on order.serviceid = lut.statusid 	0.000226381591002816
3207157	21968	problem with count()	select       count(*) totalcount,       count(case when salary = 1000 then 1 else null end) specialcount from employees 	0.78492347513937
3211461	3048	how to find a time delta of a datatime row in mysql?	select      sensor_time,     time_diff,     time_to_sec(time_diff) > 30 as alarm from (     select         sensor_time,         timediff(sensor_time, @prev_sensor_time) as time_diff,         @prev_sensor_time := sensor_time as prev_sensor_time     from sensor_table,     (select @prev_sensor_time := null) as vars     order by sensor_time asc ) as tmp; + | sensor_time         | time_diff | alarm | + | 2009-09-28 07:08:12 | null      |  null | | 2009-09-28 07:08:40 | 00:00:28  |     0 | | 2009-09-28 07:09:10 | 00:00:30  |     0 | | 2009-09-28 07:09:40 | 00:00:30  |     0 | | 2009-09-28 07:10:10 | 00:00:30  |     0 | | 2009-09-28 07:10:40 | 00:00:30  |     0 | | 2009-09-28 07:41:10 | 00:30:30  |     1 | | 2009-09-28 07:41:40 | 00:00:30  |     0 | | 2009-09-28 07:42:10 | 00:00:30  |     0 | | 2009-09-28 07:42:40 | 00:00:30  |     0 | + 	0.000180413751210748
3212352	39022	how to order sql rows in order to create nice looking rollup?	select  id ,       parent from    yourtable order by         coalesce(parent, id) 	0.680154069042498
3213549	15530	mysql group by quantity	select      commentid,     sum(case when votevalue > 0 then 1 else 0 end) as plus,     sum(case when votevalue < 0 then 1 else 0 end) as minus from      mytable group by      commentid 	0.137233635881154
3214457	29283	sql query for finding row with same column values that was created most recently	select pp.id from people pp, (select name, max(created) from people group by name) p where pp.name = p.name and pp.created = p.created and id not in ( select person_id from hobbies ) 	0
3216219	12767	get list of tables but not include system tables (sql server 2k)?	select name from sysobjects where type='u' 	0.0112170139734569
3217141	35015	custom sort order - how to not duplicate the case statement	select row_number() over (order by                        case when @sortcolumnname = 'variety'          then              (case f.variety                 when 'fuji' then 1                 when 'gala' then 2                 else 3             end)          end     * (case when @sortdirection = 'asc' then 1 else -1 end)), * from   fruits f 	0.575919657688843
3219790	11045	sql query to get all the combinations of two columns	select flag1, flag2, count(geneid) as numgenes from genetable group by flag1, flag2 	0
3220977	2027	using sqlite3 on iphone to get midnight (this morning) as a unix timestamp	select * from table where strftime('%y-%m-%d', timestamp) = strftime('%y-%m-%d', 'now') 	0.0275311064131504
3221977	31334	mysql select/group by: how do i remove a group from the result based on a value of one of it's members?	select * from orderevents where processed = 0 group by orderid     having max(timeadded) < (now() - interval 15 minute); 	0
3221993	36647	mysql query with multiple id columns and php	select t1.id as id1, t2.id as id2, t1.*, t2.* from t1 join t2 on t1.fk_id=t2.id 	0.00897377111516419
3222060	27100	what's the best way to dump a mysql table to csv?	select ... into outfile ... 	0.131342414301282
3223109	16551	sql, join two tables	select x.author,        x.book_name   from (select case                   when @author != u.login then u.login                  else ''                end as author,                 b.name as book_name,                @author := u.login as set_variable             from user u      left join book b on b.author = u.login           join (select @author := '') r          where u.login = 'peter'       order by u.login) x 	0.0897065757232085
3225217	33943	mysql stored procedure: search for a variable number of strings	select *   from a as a   join b as b on b.id = a.b_id  where match (a.f1, a.f2, b.f3) against ('foo bar'); 	0.0598221904255021
3225320	18802	sql: group counts in individual result rows	select id, name,   (select count(name)     from markers im     where state like 'or'     group by name     having im.name=m.name) as count from markers m  where state like 'or'  group by name, id 	0.00411346481917346
3225558	39960	move child rows to new parent fk id?	select                  [parid]             ,   [name]     into    #redo     from    partable      where   datediff( hour , donewhen ,sysdatetimeoffset() ) > 23 begin transaction declare @rows int  = ( select count(*) from #redo ) declare @parid int  create clustered index redoix on #redo([parid]) with fillfactor = 100 while @rows > 0 begin     select top 1 @parid = [parid] from #redo order by parid asc         insert partable              (                 [name]             )         select                  [name]               from #redo          where parid = @parid         update chitable             set parid = scope_identity()             where   parid = @parid         delete from partable             where   parid = @parid     delete from #redo where [parid] = @parid      set @rows  = ( select count(*) from #redo ) end commit transaction 	0
3226491	11408	if clause in mysql	select *,        if (`date_last` is null,prev_date,last_date) as date  from `table_name`  where `id` = 2  order by `date` desc 	0.680977824558082
3228027	36382	how to get result from database by order the condition put in "in" clause?	select * from bfproduct where productid in (23,5,54,3132,32) order by    case productid       when   23 then 0       when    5 then 1       when   54 then 2       when 3132 then 3       when   32 then 4    end 	0.00112178174118359
3228799	13892	how to join two db tables and cross reference another	select * from `owners` join `records` on (`records`.`pa_no` = `owners`.`contact_no`) where email <> "" and not exists (select reg_no from `buyers`                  where `buyers`.reg_no = `records`.reg_no) 	0.00693089801095462
3230056	2144	mysql : how to get records are have non null values?	select id,        code,         comparewithfield    from `data`  where indexed = 0     and code = 142     and nullif(comparewithfield,2.26) is not null 	0
3230899	2118	using yql how can i select an item from a feed that contains a colon in its name?	select title, link, pubdate, encoded from rss where url='http: 	0.000483377565675869
3231912	2809	re-run the query of store the results in a table variable?	select * into #foo from bla where bla.column in (...) if @@rowcount = 0      select top 1 * from bla else     select * from #foo 	0.00919284768773624
3232861	38370	common table expression functionality in sqlite	select sum(t.time) as sum_of_series_of_averages from ( select avg(elapsedtime) as time from statisticstable where connectionid in ([lots of values]) and        updatetime > [starttime] and       updatetime < [endtime] group by connectionid ) as t 	0.433576203188063
3235189	10846	best way for join parent id	select t1.* , t2.name as parent_category    from categories t1    inner join categories t2 on t1.id = t2.parent_id 	0.0264654737680006
3236717	39998	how to select the same value only once in mysql?	select id, a, b from table  where id in (1,2,5) 	0
3236768	22678	how can i use sql to group and count the number of rows where the value for one column is <= x and the value for another column > x?	select  count(*)  as gamecount, n.number from numbers n         left outer join gametable on              minageinclusive <= n.number and n.number < maxageexclusive where n.number < 100 group by n.number 	0
3237499	19627	variable scope in sql `order`.id unknown column	select     sum(order_product.price * order_return_product.quantity) from order_return_product inner join order_product on (     order_product.product_id = order_return_product.product_id and     order_product.vehicle_id = order_return_product.vehicle_id ) where return_id in (     select         id     from order_return     where status_id != 3 and     order_return.order_id = `order`.id )  and order_product.order_id = `order`.id 	0.671764182927102
3238169	5498	sql report from 3 tables with sum of fields	select u.userid, u.username, d.dep_title     , coalesce(sum( case when t.tr_type = 'debit' then -1 else 1 end * t.amount )             ,0) as [balance (debit-credit)] from users as u     join department as d         on d.dep_id = u.dep_id     left join transactions as t         on t.userid = u.userid group by u.userid, u.username, d.dep_title 	0.00160614144225056
3238651	34799	retrieving i18n data with fallback language	select     e.key,coalesce(o.value,e.value)     from translation                e         left outer join translation o on e.key=o.key and o.language_code='nl'     where e.language_code='en' 	0.194541439654824
3240981	33556	in sql server 2008 how can i query for tables with foreign key references to a specific table column?	select k_table = fk.table_name, fk_column = cu.column_name, pk_table = pk.table_name, pk_column = pt.column_name, constraint_name = c.constraint_name from information_schema.referential_constraints c inner join information_schema.table_constraints fk on c.constraint_name = fk.constraint_name inner join information_schema.table_constraints pk on c.unique_constraint_name = pk.constraint_name inner join information_schema.key_column_usage cu on c.constraint_name = cu.constraint_name inner join ( select i1.table_name, i2.column_name from information_schema.table_constraints i1 inner join information_schema.key_column_usage i2 on i1.constraint_name = i2.constraint_name where i1.constraint_type = 'primary key' ) pt on pt.table_name = pk.table_name order by 1,2,3,4 where pk.table_name='something'where fk.table_name='something' where pk.table_name in ('one_thing', 'another') where fk.table_name in ('one_thing', 'another') 	0.000161178306837258
3241748	24973	using rmysql's dbgetquery in r, how do i coerce string data type on the result set?	select cast(foo as char), bar from sometable; 	0.0134363770535065
3241876	20754	comparison of html and plain text from sql	select * from yourtable where plaintext=udt_striphtml(htmltext) 	0.0345583573405475
3242069	12707	get us, uk in one table, cn and jp in the other, but not br in both	select   coalesce(c1, c2) countrycode from   (     select       t1.countrycode c1,       t2.countrycode c2     from       countrylanguage t1       full outer join countryname t2 on t1.countrycode = t2.countrycode     where       t1.countrycode is null or t2.countrycode is null   ) x 	0.000403453748200156
3242552	5823	aggregate sql function to grab only one from each grouping	select id, count(*) as idcounts, sum(rate) as total  into #temp group by id select total, idcounts, min(id) as someid into #uniques from #temp group by total, idcounts 	0
3246069	3144	filtering data in mysql	select * from users where id not in (1,2,3,4,5) 	0.161123118977313
3247052	13149	fetch record from a table on date difference	select distinct t1.customerid from table as t1 where exists    (                 select 1                 from table as t2                 where t2.customerid = t1.customerid                     and t2.enquiryid <> t1.enquiryid                     and abs(datediff(hh, t1.datecreated, t2.datecreated)) <= 2                ) 	0
3248448	12665	creating t-sql summary rows	select     tr1.serial_number,     case         when tr1.test_result like '%pass%' then 'pass'         when tr1.test_result like '%fail%' then 'fail'         else null     end as final_result from     test_results tr1 left outer join test_results tr2 on     tr2.serial_number = tr1.serial_number and     (         tr2.test_result like '%pass%' or         tr2.test_result like '%fail%'     ) and     tr2.test_date > tr1.test_date where     (         tr1.test_result like '%pass%' or         tr1.test_result like '%fail%'     ) and     tr2.serial_number is null 	0.121076131268598
3250616	6516	2 sql in one php while loop	select count(comment.id) as numcomments,     entry.id,entry.posted,entry.subject,entry.quicktext from `blog_comments` comment, `blog_entries` entry where comment.blog_id=entry.id group by entry.posted, entry.subject, entry.quicktext 	0.0369028010159682
3251417	21224	sql count function	select j.exempt_non_exempt_status, count(*) from employee e join job_title j on e.job_title = j.job_title group by j.exempt_non_exempt_status 	0.667558278759905
3251600	20310	how do i get first name and last name as whole name in a mysql query?	select concat_ws(" ", `first_name`, `last_name`) as `whole_name` from `users` 	0
3251947	10891	how to get certain numbers	select     substring(col, charindex('(', col) + 1, charindex(')', col) - charindex('(', col) - 1) from     some_table 	9.50210423614722e-05
3252190	36032	sql - select first in value set by priority?	select * from a where somefield in (5, 6, 9, 3)  order by field( somefield, 5, 6, 9, 3)  limit 1 	0.000765216933486332
3252751	28308	sql join table with two 'on' keyword?	select *from tbl_a join tbl_b on  (   tbl_a.a_c_id=tbl_b.b_c_id    and    tbl_a.a_d_id=tbl_b.b_d_id  ) where tbl_a.id>15; 	0.171401825477658
3253804	10948	need sql to get a record with two corresponding entries	select * from contacts_accounts where account_id = 12 and contact_id in (select contact_id from contacts_accounts where account_id = 13) 	0
3253834	40154	php/mysql pagination with one query	select sql_calc_found_rows something from table limit 30,10 	0.353262940649266
3254581	1124	i need to question my database about a word received from another aplication, my tables are related on a many to many relashionship	select m.name   from brand b   join market_brand mb on mb.fk_brand_id = b.id   join market m on m.id = mb.fk_market_id  where b.name = 'your_brand' 	0.0158182578402572
3257061	39780	optomizing a sql count query	select o.accountid, o.account_name,    count(*) as [number of tickets],    isnull(sum(case when statuscode in (1,2,3) then 1 else 0 end),0)                                                                  as [active tickets]  from opportunity o  left outer join ticket t on t.accountid = o.accountid     where o.accountid > @lowerbound and o.accountid < @upperbound     group by o.accountid, o.account_name 	0.607423663737464
3257064	13603	select most occurring value in mysql	select thread_id as tid,     (select user_id from thread_posts          where thread_id = tid          group by user_id         order by count(*) desc         limit 0,1) as topuser from thread_posts group by thread_id 	0.00255438885330385
3257475	10300	tying user ids in a table to meaningful values in another table in sql server	select c.name as customer,           s.name as shipper,           b.name as buyer      from people p left join user c on c.id = p.customer left join user s on s.id = p.shipper left join user b on b.id = p.buyer 	0
3257795	39507	combine subselect	select b, sum(e) as esum from b where h = 'foo' group by b; select sum(d) as dsum, count(*) as c from c where d = 'bar'; select count(*) as acount from a; 	0.362318736289428
3258554	14227	search for a specific value in a column in oracle	select substr (expr, instr (expr, '=') + 1) subdoctypeval   from (select regexp_substr ('doctype=1***subdoctype=2***minvalue=123',                               'subdoctype=[^*]+',                               1,                               1)                    expr           from dual) 	0.00339392373634929
3258884	15585	calculate min and max functions	select  min(case when j.exempt_non_exempt_status = 1 then e.wage end) ,       max(case when j.exempt_non_exempt_status = 0 then e.wage end) from    employee e join    job_title j on      j.job_title = e.job_title 	0.0758115858876151
3260980	29224	how to combine 2 different table?	select cat_name, sum(exp.exp_amount) from (select exp_cat_id, exp_amount from cash_expenses       union all       select exp_cat_id, exp_amount from cheque_expenses) as exp inner join exp_cat on exp.cat_id = exp_cat.cat_id group by cat_name; 	0.000441604783089712
3261834	19127	tsql to get data files growth type in sql 2000	select   name,   size,   growth,   status,   size * 8 as size_in_kb,   size * 8 / 1024. as size_in_mb,   case when status & 0x100000 > 0        then growth         else null end as growth_in_percent,   case when status & 0x100000 = 0         then growth * 8 / 1024. end as growth_in_mb   from sysfiles 	0.0258765110584297
3263465	1446	order by in sql	select      cast(substring(replace(title,'-',''),     patindex('%[0-9]%',replace(title,'-','')),     len(replace(title,'-','')))      as int) as [title number],* from [your table-name here]  order by [title number] 	0.410338791385693
3263497	35439	how does dotnet handle parameterised dates where programmatic date has no time but sql date has time	select * from table where floor(cast(table.date as float)) = floor(cast(@input as float)) 	0.0011528265097989
3265171	10740	count query filter	select count(distinct tmr_id) ,contract_id  from status_handling group by contract_id  having count(distinct tmr_id) = 2 / 	0.27619733628658
3265512	31784	mysql in array order?	select * from post  where flag='0' and id in(4,5,1) order by find_in_set(id, '4,5,1') 	0.223123469986264
3265760	30922	how to only select part of column value by regexp with mysql?	select trim(leading 'a' from (leading 'b' from `column`)) from my_table 	0.000354388077162328
3266968	2962	select inside a count	select a, count(*) as b,    sum( case when c = 'const' then 1 else 0 end ) as d,    from t group by a order by b desc 	0.281274288904036
3267609	11414	mysql join query for multiple "tags" (many-to-many relationship) that matches all tags?	select *      from objects o     join objectstags ot on ot.object_id = o.id     join tags t on t.id = ot.tag_id    where t.name in ('tag1','tag2') group by o.id   having count(distinct t.name) = 2 	0.000499500030030868
3268717	2609	ms access pass through query find duplicates using multiple tables	select       a.coverage_set_id,       count (a.benefit_id) as "count"   from       coverage_set_detail_view a   where       a.coverage_set_id in (         select b.coverage_set_id          from contracts_by_sub_group_view b         where b.valid_from_date between to_date('10/01/2010','mm/dd/yyyy') and to_date('12/01/2010','mm/dd/yyyy'))     and a.coverage_set_id in (         select b2.coverage_set_id         from contracts_by_sub_group_view b2         inner join request c on c.request_id=b2.request_id         where c.request_status = 1463)     and ?.summary_attribute = 2004687       and a.benefit_id <> 1092333   group by       a.coverage_set_id   having       count (a.benefit_id) > 1 	0.274645898013499
3269348	20510	mysql syntax problem in "select * from into file"	select *   from test_table   into outfile '/tmp/result.txt'    fields terminated by ','    optionally enclosed by '"'   lines terminated by '\n'; 	0.518807161318046
3271204	37233	find value between two data range in mysql	select * from table where 250 between maxvalue and minvalue 	0
3277757	18064	how can i convert a ole automation date value to a date in sql server	select cast(case when olefloat > 0 then                           olefloat-2.0                   else         2*cast(olefloat as int) - 2.0 +  abs(olefloat) end as datetime) 	0.0170479274718113
3278413	5306	sql server 2005: t-sql to query when a database was last restored?	select max(restore_date) from msdb.dbo.restorehistory where destination_database_name = 'somedb' 	0.114256713155078
3278597	26468	retreive one row from 1 to many relationship between three tables	select product_id,        (select min(price)              from price_by_supplier              where price_by_supplier.product_id = product.product_id) as min_price,        (select name              from product_images              where product_images.product_id = product.product_id              limit 1) as product_images,        (select count(*)              from price_by_supplier              where price_by_supplier.product_id = product.product_id) as supplier_count     from product_id; 	0
3279589	22272	aggregating multiple distributed mysql databases	select * from [table] where timestamp > last_backup_time 	0.139159007494976
3281145	35902	sql server - export in xml-like format without tags?	select 'start_file' as fieldname, '' as 'fieldvalue' union all  select 'date' as fieldname, getdate() as 'fieldvalue' union all select  fieldname, fieldvalue from     (     select     cast(column1name as varchar) as vendorcolumn1name,     cast(column2name as varchar) as vendorcolumn2name,     cast(column3name as varchar) as vendorcolumn3name     from mytable     ) c     unpivot     (     fieldvalue for fieldname in(vendorcolumn1name, vendorcolumn2name, vendorcolumn3name)     ) as p union all select 'end_file' as fieldname, '' as 'fieldvalue' 	0.0831302982845934
3281901	4553	sql: get a selected row index from a query	select *, (  select count(*) from participations as p2    where p2.tour_id = p1.tour_id and p2.rating > p1.rating  ) as rank  from participations as p1 left join tours on tours.id = p1.tour_id  where p1.player_id = 68 order by tours.date desc limit 10; 	0.000741890170485088
3283866	34789	should i create an index on the columns if their values are used in functions ? (sqlite)	select * from node  where lat >= $lat - $threshold and lat <= $lat + $threshold and lng >= $lng - $threshold and lng <= $lng + $threshold and distance( lat, lng, $lat, $lng )  < $threshold; 	0.00702102059846449
3284275	38084	concat tables with different content	select id, 'articles' as tablename, title, author,      preview, last_edited, category, '' as url from articles union select id, 'hyperlinks' as tablename, title, author,      '' as preview, '' as last_edited, '' as category, url from hyperlinks ... 	0.0225380490508159
3284373	39557	update mysql table based on row=column name	select 1 from compatible_products where product1 = 'a' and product2 = 'b' 	0.00269767770479047
3284885	13366	sql - getting the max effective date less than a date in another table	select   l.lawid from   law l   join (     select        a.lawsource,       a.lawstatue,       max(a.lawdate) lawdate     from        law a       join charge b on b.lawsource = a.lawsource                       and b.lawstatute = a.lawstatute                       and b.chargedate >= a.lawdate     group by       a.lawsource, a.lawstatue   ) d on l.lawsource = d.lawsource and l.lawstatue = d.lawstatue and l.lawdate = d.lawdate 	0
3285768	4198	sql updated since last visit column	select val1, val2,  case when lasttimestamp > '20100720' then 'true' else 'false' end as [true/false]  from table 	6.07556424989306e-05
3286849	9420	sql server remove milliseconds from datetime	select *  from table  where dateadd(ms, -datepart(ms, date), date) > '2010-07-20 03:21:52' 	0.0084664253942172
3288103	15422	how to select different columns from database each giving the sum(or similar) of another query result?	select      name,      (select sum(numbers) from mytable where cond='1' and cond2='2') as mysum1,      (select sum(numbers) from mytable where cond3='3' and cond4='4') as mysym2 from      mytable  where      userid='1' and status='1'; 	0
3289095	16292	order by maximum condition match	select *   from (select (case when cond1 then 1 else 0 end +                 case when cond2 then 1 else 0 end +                 case when cond2 then 1 else 0 end +                 ...                 case when cond10 then 1 else 0 end                ) as nummatches,                other_columns...           from mytable        ) xxx  where nummatches > 0  order by nummatches desc 	0.0107978220123611
3289900	9720	how to find rows in sql that start with the same string (similar rows)?	select *  from table where substring(column, 0, charindex('~', column)) in (     select substring(column, 0, charindex('~', column)) from table      group by substring(column, 0, charindex('~', column))     having count(*) > 1 ) 	0
3291252	9048	sql query join nearest date	select a.id, a.sales, a.date, (select top 1 goal                                 from tableb b where b.date < a.date                                order by b.date desc) as goal from tablea a 	0.33434279461801
3292544	5051	sql: best approach to select and insert from multiple tables	select ... from lookup l join table15 t on l.zipcode = t.zipcode where l.tableid = 15 	0.00717971853124546
3293790	10286	query to count words sqlite 3	select length(@string) - length(replace(@string, ' ', '')) + 1 	0.102286235194569
3294025	20978	sql server - need to gt back data based on nested rank	select name, address, city, state, zip  from customers c inner join (select top 100 customerid, territoryname,              rank() over partition by tid order by territoryname desc) as 'rank'             from territories             where nation = 'canada') t on c.customer_location = t.territoryname 	0.157214267957999
3294040	21105	2 sql queries from same table	select * from yourtable order by     id = (select id from yourtable order by date desc limit 1) desc,     last_name 	0.000730433759807889
3294306	16134	sql join on one-to-many relation where none of the many match a given value	select distinct u.* from user u left join user_prefs up on u.id = up.user_id and up.pref = 'email_opt_out' where up.user_id is null 	0.000645412565751006
3296430	7078	select query in sqlite	select distinct <column> from <table> order by <column> 	0.412256873013562
3297547	16768	"distinct" column in sql query	select id, empno, empno2 from employeestable left outer join (  select min([id]) as minid       ,[empno] empno2   from [employeestable] group by empno) etab2 on employeestable.id = etab2.minid 	0.132374617821727
3298607	40127	how to concatenate the output of a sql query into one string	select pv.id, bm.billno,      group_concat(bd.servicename)     from patientvisits pv inner join billmaster bm on bm.visitid = pv.id      inner join billdetail bd on bd.billno = bm.billno     where ..     group by pv.id,bm.billno 	7.34068947466399e-05
3299289	29423	table design for a matching system	select *     from products     where id <> <given product id>     order by (select count(*)                   from product_properties                   where product_properties.product_id = products.id and                         product_properties.property_id in                                 (select property_id                                      from product_property                                      where product_id = <given product id>))     limit 1; 	0.0591534784315308
3299433	8	problem with cast convert and view all in tsql	select      [cc_renal_support_days_1]         ,right(isnull(replicate('0',3)+convert(varchar, [cc_renal_support_days_1]),''),3) as [cc_renal_support_days_spc]     from vw_formattable1      group by [cc_renal_support_days_1] 	0.740914574646197
3299631	15701	t-sql distinct column problem when trying to filter duplicates out	select distinct col2 from mytable 	0.37889521567746
3301125	31753	select data from 8 tabels into one temp table	select * into #temptable from table1 insert into #temptable select * from table2 insert into #temptable select * from table3 	0.000217720546258782
3301302	39561	comparing dates in openoffice database with hsqldb	select sum((enddate-begindate) minute) as total_minutes from mytable 	0.014066843224023
3301397	35956	sql group by question - choosing which row gets grouped	select p.id, c.id as priorid, p.numusers-c.numusers as dif, p.date, c.date as priordate     from licenses p join licenses c on c.serial=p.serial   and c.date=(select max(date) from licenses ref where ref.serial=p.serial     and ref.date<p.date) order by p.serial 	0.0171168946525134
3301668	12503	providing additional data when selecting distinct rows	select ip, max(datetime) as datetime from eventstream where machine='$machine' group by ip 	0.00647596813168625
3301872	4053	get data origin after a union	select *  from (    (select name, 'man' as source from man)    union all   (select name, 'woman' from woman )  ) as my_table  order by name 	0.0140026441741097
3301979	24752	select results from the middle of a sorted list?	select *  from table order by somecolumn limit 10,40 	0
3303730	38041	t-sql combine column values	select t.id,         t.description        stuff(isnull(select ', ' + x.releateid                       from table x                      where x.id = t.id                        and x.description = t.description                    for xml path ('')), ''), 1, 2, '')   from table t 	0.00903457436541754
3306352	23831	sql to get rows where a date time is 5 or less days away	select `product_id`, `expiry` from `products_featured` where `notified_expiry` = false and `expiry` != 0 and date_add(now(), interval 5 day) >= `expiry` and now() <= `expiry` 	0
3313449	14929	xquery in linq to entities for sql server xml data type	select (list of fields) from dbo.changes c where c.content.value('(string-length(string((/content/opsnotes)[1])))', 'int') >= 2000 	0.695391021962822
3313982	23205	form a query to find duplicate zipcodes	select     count(zipcode_rid) as no_of_zipcodes     ,zipcode from     zipcodes group by     zipcode having     count(zipcode_rid) = 2 	0.00781732999303002
3315400	19955	how to get the last tuple from a table with sql server 2008 r2?	select top 1 (list of fields) from dbo.yourtable order by (some column) desc 	9.09206213745692e-05
3320306	24045	how do i write a function to compare and rank many sets of boolean (true/false) answers?	select     u2.userid,     sum(case             when a1.answer = a2.answer then 1             when a1.answer <> a2.answer then -1             when a1.answer is null or a2.answer is null then 0               else 0         end) as similarity_score from     questions q left outer join answers a1 on     a1.question_id = q.question_id and     a1.userid = @userid left outer join answers a2 on     a2.question_id = a1.question_id and     a2.userid <> a1.userid left outer join users u2 on     u2.userid = a2.userid group by     u2.userid order by     similarity_score desc 	0.0382902202659598
3321629	7535	how to find all table references from oracle 10g pl/sql functions and procedures?	select      owner              || '.'              || name              || ' ('              || decode (type,                         'materialized view', 'mv',                         'dimension', 'dim',                         'evaluation contxt', 'evalctxt',                         'package body', 'pkgbdy',                         'cube.dimension', 'cube.dim',                         type                        )              || ')' objdep,                 referenced_name              || ' ('              || decode (referenced_type,                         'evaluation contxt', 'evalctxt',                         'non-existent contxt', 'no-exist',                         'package body', 'pkgbdy',                         'cube.dimension', 'cube.dim',                         referenced_type                        )              || ')' refr         from dba_dependencies        where owner = :usn     order by objdep; 	0.0026787683879788
3325092	4121	get most active users by the amount of comments	select count(comment_author) as comment_comments, comment_author from table_name group by comment_author order by comment_comments desc limit 10 	0
3325516	21054	sqlite query: how to find out the average of last x records for every person	select id,        name,        (select avg(score)             from scores             where scores.player_id = players.id and                   scores.id in (select id                                     from scores sc                                     where sc.player_id = players.id                                     order by timestamp desc                                     limit 5))     from players; 	0
3327562	23500	sorting mysql results for diversity	select distinct course from classes where upper(course) like 'e' 	0.421858890627656
3330159	19446	query with multi tables	select c.guid          , c.name          , at.arenateamid          , at.name          , at.type          , ats.rating          , ats.wins          , ats.wins2           , ats.played       from characters c inner join arena_team_member atm on atm.guid = c.guid inner join arena_team at on at.arenateamid = atm.arenateamid inner join arena_team_stats ats on ats.arenateamid = at.arenateamid      where c.name like '%$q%'   order by ats.rating desc 	0.381471812393334
3331286	17217	joining multiple columns from table a to one on table b	select      forum_threads.id,      forum_threads.replies,      u1.username as author_username       u2.username as last_post_username  from forum_threads left join users u1 on forum_threads.author_id = u1.id left join users u2 on threads.lastpostid = u2.username  where forum_threads.forum_id=xxx 	0
3332922	18733	how to 'add' a column to a query result while the query contains aggregate function?	select     t2.course_id,     t2.attendance_time     t2.id from (     select         course_id,         max(attendance_time) as attendance_time     from attendance     group by course_id ) t1 join attendance t2 on t1.course_id = t2.course_id and t1.attendance_time = t2.attendance_time 	0.0636393477358343
3333357	39528	with index, returns different result	select topic_id, max(comment_id) as comment_id from comments where user_id=9384 and status in (0, 1) group by topic_id order by comment_id desc limit 15 	0.189660731615427
3333454	21005	join query with multiple tables invovled	select coursename,marks  from course c inner join examattend e on c.courseid = e.courseid  inner join semester s on s.studentid = e.studentid 	0.763541396946414
3333541	9363	aggregate functions return wrong values when joining more tables	select * from customer t1 left join (     select custid,            sum(total) as sum_total,            count(total) as count_total     from orders     group by custid ) t2 on t1.custid = t2.custid 	0.730802903541276
3336494	14464	mysql query add [something]_ infront of all table rows when grabbing multiple tables	select a.field as a_field, a.field2 as a_field2, ... 	6.31636101283547e-05
3337097	11928	sql server insert records from one table to another	select distinct url, feedurl, dateadded  from book3 t2  where not exists(select * from forms t1 where t1.url = t2.url  t2.feedurl = t1.feedurl and  t2.dateadded =t1.dateadded) 	0
3337328	1613	sql server 2008 select from table with and style conditions in related tables	select productid,     count(*) as facetcountbyproduct,     sum(case when facettypeid in (1, 2) then 1 else 0 end) as facetcountselectedfacets from productfacets group by productid having count(*) = 2     and sum(case when facettypeid in (1, 2) then 1 else 0 end) = 2 ; 	0.0524044466860613
3338391	9408	get percent of columns that completed by calculating null values	select    count(1) as totalall,    count(variable_value) as totalnotnull,    count(1) - count(variable_value) as totalnull,    100.0 * count(variable_value) / count(1) as percentnotnull from    games where    category_id = '10' 	0
3338546	29909	sql question: select cities distance without duplicates	select c1.city, c2.city, dbo.calcdistance(c1.x, c1.y, c2.x, c2.y) from cities c1, cities c2 where c1.cityid > c2.cityid 	0.488017993345502
3338710	38520	select a specific column based on another column's value	select case           when type = 0 then val0           when type = 1 then val1           .           .           when type = n then valn        end    from tbl 	0
3338770	25020	how to exclude rows that have duplicates in one field	select a.* from article a left join     article a2 on a.id<a2.id and a.cat_id=a2.cat_id where a2.id is null 	0
3339508	5587	ordering by two fields	select s.loginid, s.title, s.url, s.displayurl, s.datesubmitted, l.username,   s.submissionid, count(c.commentid) countcomments,    greatest(s.datesubmitted, coalesce(max(c.datecommented), s.datesubmitted)) as most_recent from submission s inner join login l on s.loginid = l.loginid left outer join comment c on s.submissionid = c.submissionid group by s.submissionid order by most_recent desc limit 10 	0.030012457475686
3340021	20760	mysql query - select (average of a category) as "category average"	select yt.qty,        x.cat_avg,        yt.sales/yt.qty as avg_price,        null as weighted_average    from your_table yt   join (select t.category,                avg(t.qty) as cat_avg           from your_table t       group by t.category) x on x.category = yt.category  where yt.seller = 'ash' 	0
3340061	18304	php mysql select random rows	select *      from friends     where member_id = '".$_session['userid']."'  order by rand()     limit 6 	0.0097763898120816
3340788	3667	sql server 2005 one query to calculation two table	select pf.id as patientfileid,     os.totalotherservices,     pd.totaldeposit from patientfiles pf     left join  (select patient_file_id as patientfileid, sum(os.quantum * os.price) as totalotherservices   from otherservices group by patient_file_id) os on pf.patientfileid = os.patientfileid     left join  (select patient_file_id as patientfileid, sum(deposit) as totalpatientdeposit   from patientsdeposits group by patient_file_id) pd on pf.patientfileid = pd.patientfileid 	0.0418459109260999
3341284	6377	count(*) with 0 for boolean field	select x.desc_value as result,                coalesce(count(t.field), 0) as num      from (select 1 as value, 'yes' as desc_value                 union all                 select 2, 'no') x left join table t on t.field = x.value    group by x.desc_value 	0.144359047117111
3341720	15112	how to check if a date is in a list of dates - tsql	select *  from table1 where field1 = value1   and date_start in      (select date_end from table2) 	0.000136969712430208
3342027	1751	how do i create index column in sql?	select rank() over (order by list of your columns) as id,  your_column_1, your_column_2 ... from your table 	0.217482545979396
3342308	5525	selecting columns as rows	select 'nett' as [desc], sum(pricen) as value from resources union all select 'gross' as [desc], sum(priceg) as value from resources 	0.000589421642881148
3342461	36087	mysql - group rows in 4's	select affiliateid, productcode   from (      select        affiliateid, productcode,        if( @prev <> id  @rownum := 1, @rownum := @rownum+1 ) as rank,        @prev := id      from your table   join (select @rownum := null, @prev := 0) as r   order by affiliateid, productcode   ) as tmp   where tmp.rank <= 4  order by affiliateid, productcode; 	0.0753684549968119
3342504	22011	effect of style/format on sql	select col  from a    inner join b      on a.id = b.id     inner join c      on b.id = c.id 	0.503303076563083
3343044	16858	sql table a left join table b and top of table b	select     dt.id, dt.outcomes,max(o.yourtimestampcolumn) as lastone     from (select                records.id, (isnull(count(outcomes.id),0)) as outcomes               from records                   left join outcomes on records.id = outcomes.id               group by records.id           ) dt         inner join outcomes o on dt.id = o.id     group by dt.id, dt.outcomes 	0.000321218096956124
3343721	40974	how to know how many or conditions are satisfied?	select      [title]      case [title] like '%value%' when true then 1 else 0 end as contains_value     case [title] like '%sql%' when true then 1 else 0 end as contains_sql from      [m_tips]  where      [title] like '%value%' or      [title] like '%sql%'; 	0.114951468350962
3344537	25310	sql query for getting the difference between a value from one row with a value another row	select     t1.itemno - 1 as itemno,     t1.date,     t1.value - t2.value as value from table1 t1 join table1 t2 on t1.date = t2.date and t1.itemno + 1 = t2.itemno 	0
3344863	30522	how can i get the row number in sql query?	select ....     , row_number() over ( order by t.somecolumn ) as num from table as t order by t.somecolumn 	0.000462754689256917
3345252	9846	mysql combine multiple rows	select t.category_id,          min(t.date) as first_date,          case             when max(t.date) = min(t.date) then null             else max(t.date)          end as last_date     from table t group by t.category_id, t.client_id 	0.00820023676032141
3345657	28	mysql: how do i sum non duplicates values when doing multiples joins	select p.id     , coalesce(detailtotals.total,0) as stock_bought_last_month     , coalesce(ordertotals.total,0) as stock_already_commanded from product as p     left join   (                 select o1.product_id, sum(o1.out_details_quantity) as total                 from out_details as o1                 group by o1.product_id                 ) as detailtotals         on detailtotals.product_id = p.id     left join   (                 select o2.product_id, sum(o2.order_quantity) as total                 from order_details as o2                 group by o2.product_id                 ) as ordertotals         on ordertotals.product_id = p.id where p.id = 9507 	0.116740694027918
3348043	32145	select top #chunksize# 	select top 10 	0.318918146530554
3348331	5262	how can i add other columns from a foreign table in the sql?	select e1.*, f1.titulo as feedtitulo, f1.url as feedurl   from feed_entries as e1 join feeds as f1 on e1.feed_id = f1.id  where f1.id in             (select e.id                from feed_entries            as e               inner join feeds              as f  on e.feed_id = f.id               inner join entries_categorias as ec on ec.entry_id = e.id               inner join categorias         as c  on ec.categoria_id = c.id               where e.deleted = 0                 and c.slug in ('manchete', 'google')               group by e.id              having count(distinct ec.id) = 2             )  order by `date` desc  limit 1 	0
3348705	16308	how to limit results of a left join	select ta.product_id, ta.product_name     , tb.transaction_date from tbl_product as ta     left join   (                 select tx1.product_id, tx1.transaction_id, tx1.transaction_date                     , (select count(*)                         from tbl_transaction as tx2                         where tx2.product_id = tx1.product_id                             and tx2.transaction_id < tx1.transaction_id) as [rank]                 from tbl_transaction as tx1                 ) as tb         on tb.product_id = ta.product_id             and tb.[rank] <= 4 limit 10 	0.327886599376546
3348905	10348	sqlite : finding a function's minimum values	select r.id, n1.lat, n1.lng, n2.lat, n2.lng from node n1, node n2 join route r on n1.route_id = r.id and n2.route_id = r.id where distance(n1.lat,n1.lng,$lat1,$lng1) = (                                              select min (distance(lat,lng,$lat1,$lng1))                                              from node c_n                                              where c_n.nid = n1.nid) and distance(n2.lat,n2.lng,$lat2,$lng2) = (                                              select min (distance(lat,lng,$lat1,$lng1))                                              from node c_n                                              where c_n.nid = n2.nid) 	0.00801054225772983
3350148	10197	where are numeric precision and scale for a field found in the pg_catalog tables?	select   case atttypid          when 21 then 16          when 23 then 32          when 20 then 64          when 1700 then               case when atttypmod = -1                    then null                    else ((atttypmod - 4) >> 16) & 65535                         end          when 700 then 24          when 701 then 53          else null   end   as numeric_precision,   case      when atttypid in (21, 23, 20) then 0     when atttypid in (1700) then                     case              when atttypmod = -1 then null                    else (atttypmod - 4) & 65535                     end        else null   end as numeric_scale,   * from      pg_attribute ; 	0.000778547481002529
3352057	24437	sql: is it possible to sum() fields of interval type?	select   sum(cast((date1 + 0) - (date2 + 0) as float) as sum_turnaround from my_beautiful_table group by your_chosen_column 	0.0431437941693539
3352086	22724	is it possible in sql to group by fields matching some pattern?	select 'b*' as mask, name from table where name like 'b%' union all select '*l*' as mask, name from table where name like '%l%' union all select 'mike' as mask, name from table where name like 'mike' 	0.0766268275791204
3352882	21405	ordering select clause result in specific way	select *   from tbl order by        case          when value = 5 then 8.5          else value        end 	0.296562997620987
3354154	17394	pivot a one row column t-sql	select dates from      (select * from yourtable) p unpivot     (dates for seq in          ([date1], [date2], [date3], [date4], [date5], [date6]) ) as unpvt 	0.00557570441677881
3354666	13282	mysql: hourly average value	select date(timestamp), avg(value) from table group by date(timestamp) 	0.000848880869055447
3356811	38668	query related to in clause	select    table1.fid from       table1    inner join       table2    on           table1.fid = table2.fid       and table1.field = table2.field where        table2.name = 'dell'    and table1.queryorder <> 1 	0.41534005455965
3359384	24340	php:count data from db then show at other page	select line, model, count(serial) as qty from table_name group by line, model 	0
3360068	17308	mysql:show date from datetime	select date(inspection_datetime) from inspection 	0.00578066232292356
3361639	21928	select name of a person with the most grandchildren	select  e1.first_name , e1.last_name , count(e3.first_name) as grandchilds from empnew e1 inner join empnew e2 on (e1.id = e2.father_id) inner join empnew e3 on (e2.id = e3.father_id) group by e1.first_name, e1.last_name having count(e3.first_name) = (select max (grandchilds) from ( select  e1.first_name , count(e3.first_name) as grandchilds from empnew e1 inner join empnew e2 on (e1.id = e2.father_id) inner join empnew e3 on (e2.id = e3.father_id) group by e1.first_name ) table_1); 	0.000180143531967284
3362688	32928	querying a database representation of a tree (mysql)	select    n.nodeid  from    node as n  left join    relationship as r on   n.nodeid = r.nodechild where   r.nodechild is null 	0.00853529007529374
3364224	3367	select first n records for each distinct id in sql server 2008	select * from ( select      row_number() over(partition by id order by id) as rownum,      id,      column1 from     table ) mydata where rownum < 10 	0
3364439	16406	whats the advantage or disadvantage of doing one of these way	select * from table1 inner join table 2 on table1_id = table2_id select * from table1 left join table 2 on table1_id = table2_id select * from table1 right join table 2 on table1_id = table2_id select * from table1 full outer join table 2 on table1_id = table2_id 	0.582096684903573
3364903	28416	process a repeatable subset of records in a sql server 2000 table	select id, requestor, status, created, queuetime from requests where status = 1     and id % 3 + 1 = 2 order by queuetime 	0.00339265940706948
3368785	29358	how to take sqrt in sqlite	select     *  from     (         select              temperature,             climate,             temperaturetime,             photourl,             (((latitude - 37.331689) * (latitude - 37.331689)) + (longitude - (-122.030731)) * (longitude - (-122.030731))) * (110 * 110) as dist          from              weather     )     as tab  where      tab.dist <= (1.0 * 1.0); 	0.0645130700412237
3369041	263	select rows where column is null	select column1, column2 from my_table where column1 = 'value' or column1 is null 	0.0256287277624058
3369797	2925	how do i get this 2 sql querys to be 1	select user_id, username  from user_table u, (select user_id, sum(votes) as sumvotes, vote_date                      from votes_table                      where vote_date > 1279749600                      order by sumvotes desc                     limit 10) t where u.user_id = t.user_id 	0.270439031002071
3370428	35909	how to get record in between time range	select *    from table    where convert(varchar(5),countrytime,108) between '15:00' and '16:00' 	0
3370639	17840	sql view where value appears in one of two tables or both of them	select      isnull(tbl2.timestamp, tbl1.timestamp) as timestamp,      isnull(tbl2.value,tbl1.value) as value from      @t1 tbl1 full outer join @t2 tbl2 on tbl1.timestamp=tbl2.timestamp 	0
3370843	21150	search in joint tables	select cuisine.id, cuisine.name   from cuisine   inner join recipe on recipe.cuisine_id = cuisine.id   inner join ingredients_recipes ir on ir.recipe_id = recipe.id   inner join ingredients on ingredients.id = ir.ingredient_id   where ingredients.name = 'tomatoe'   group by cuisine.id, cuisine.name 	0.163008712545582
3372000	1801	querying a mysql db representation of a tree	select node from table1 where type = 'type b' and nodeid not in (    select t2.childnodeid    from table1 t1    join table2 t2    on t2.parentnodeid = t1.nodeid    where t1.type = 'type c' ) 	0.0110114548013763
3373100	17486	t-sql - string concatenation	select  col1,         stuff(( select  ',' + cast((select col2                                         from table2                                         where table2.col1 = a.col1) as varchar(255)) as [text()]                 from    table1 a                 where   a.col1 = b.col1                 order by a.col2               for                 xml path('')               ), 1, 1, '') as col2concat from    table1 b group by col1 order by col1 	0.427187848180756
3373984	13542	how to select top 1 from each group after order by	select x.strid, a.unit   from (select unit, min(seq) as seq from mytable group by unit) a   join mytable x      on a.unit = x.unit and a.seq = x.seq 	0
3375314	21399	mysql query "one to many" question	select  contacts.full_name, [...] inner_phone.phones from contacts  left join (select group_concat(phone order by phone_type) as phones, contact_id from phone) inner_phone on contacts.id = inner_phone.contact_id [... etc. for other tables ...] 	0.442014137947347
3375436	32180	how do i limit a left join to the 1st result in sql server?	select userid, max(phonenumber) as homephone from [...] group by userid 	0.510876288672709
3377985	36982	why difference in performance between the two queries?	select t2.fact1 from     table1 as t1 join table2 as t2 on t2.fk=t1.pk 	0.478408268202555
3378049	24297	sql: any straightforward way to order results first, then group by another column?	select a,b from (select a,b from table order by b) as c group by a; 	0.000672382599669137
3378552	11990	"unknown column" because of subquery-in-subquery	select product_id as id,          group_concat (y.value order by y.`order`)      from slud_products t1      join (select sd.product_id,                   sd.value,                  sd.`order`             from slud_data sd         left join slud_types on slud_types.type_id = slud_data.type_id             where value! = ''               and display = 0) y on y.product_id = t1.product_id                                 and y.order <= 3    where now() < date_add(date,interval +ttl day)       and activated = 1 group by product_id order by t1.date desc 	0.744685826181319
3378743	33821	select join in same table on multiple rows	select c2.itemid from categories c1 join categories c2 on c1.catid = c2.catid where c1.itemid = :id and c2.itemid <> :id group by c2.itemid order by count(c2.itemid) desc; 	0.000559191614069843
3378775	40418	pictures & tags - database design question	select filestags.tag_name, count(*) as number_of_occurences from filestags group by filestags.tag_name; 	0.522127639228771
3380102	21650	sql/php: order by highest vote from different table	select c2.itemid from categories c1 join categories c2 on c1.catid = c2.catid join votes v on v.itemid=c1.itemid where c1.itemid = :id and c2.itemid <> :id group by c2.itemid order by count(c2.itemid), v.total_value desc; 	0
3380262	18646	sql: check to see which id's already exist	select c.id from checkids c left join mytable m on m.id = c.id where m.id is null 	0.000173191045057716
3381756	35444	date range sql query	select schedule_id  from tbl_schedule  where card_no = 1000058    and yourdate between fromdate and todate 	0.0246818896319059
3381760	25035	sql: list of points to rectangle	select region_id, min(x) as x1, min(y) as y1, max(x) as x2, max(y) as y2  from points  group by region_id. 	0.0164191976480257
3382733	23938	mysql query group by	select tbl.client, ytbl.price from (select client, min(price) as mpr from yourtable group by client) tbl join yourtable ytbl on ytbl.client=tbl.client order by tbl.mpr asc, tbl.client asc, ytbl.price asc 	0.513514763275716
3384380	10910	select n largest values from a table	select t.* from mtable t order by t.score desc limit 100 	0
3385102	14427	how to query two different fields from a table, and make it appear in the same row?	select table1.stuff, b.vales as value1, c.values as value2  from table1, table2 as b, table2 as c    where table1.foreing = b.id_table and table1.foreing2 = c.id_table 	0
3388662	5	how do i return all columns in one table and just a few in another using join?	select tablea.*, tableb.col1, tableb.col2, ... 	0
3389239	18480	advanced mysql query to fetch date specific records within the same table	select dr.day, p.discount from ( select a.date as day from (     select curdate() + interval (a.a + (10 * b.a) + (100 * c.a)) day as date     from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6  union all select 7 union all select 8 union all select 9) as a     cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all  select 6 union all select 7 union all select 8 union all select 9) as b     cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all  select 6 union all select 7 union all select 8 union all select 9) as c ) a where a.date >= '2010-08-12' and a.date < '2010-08-18') dr left join promotions as p on dr.day between p.startdate and p.enddate where p.category = 'a' 	0
3389845	29253	select a distinct row in left join	select id, date, opt from table2 as t2 where date = (             select max(date)             from table2 as t3             where t3.id = t.id             ) 	0.104985520994819
3390033	14267	sql query with specialized ordering of results	select * from routes where route = 'red' order by case when stop_order >= 3 then 0 else 1 end, stop_order ; 	0.712835189415565
3392956	19875	sql - how to transpose?	select t.userid          max(case when t.fieldname = 'username' then t.fieldvalue else null end) as username,          max(case when t.fieldname = 'password' then t.fieldvalue else null end) as password,          max(case when t.fieldname = 'email address' then t.fieldvalue else null end) as email     from table t group by t.userid 	0.143545736033218
3394072	7730	get the top row after order by in oracle subquery	select * from   (select id, name, department, age, score,   row_number() over (partition by department order by age desc, score asc) srlno    from student)  where srlno = 1; 	0.00253767519280653
3394221	953	challenge: sql check next record against previous	select street, startno, endno,  case  (select coalesce(min(s2.startno),-1) from stackchallenge s2         where s1.street = s2.street and               s1.startno <= s2.startno and               s1.endno < s2.endno)     when -1 then ' '     when endno then 'win!'     else 'fail!' end as validated, length from stackchallenge s1 order by 1,2,3 	0.00116240048651948
3394881	14163	how to convert second into datetime's 108 format hh:mm:ss in sql server without writing function	select convert(varchar               ,dateadd(minute                       , datediff(mi,v1.dateofchange,v2.dateofchange), '00:00:00')               , 108               ) 	0.00718075809918223
3394884	19726	how to merge 2 rows in mysql	select f1, f2, group_concat(f3 order by f3) as f3, f4 from t1 group by f1, f2 	0.000979966271989416
3395122	35140	index counter shared by multiple tables in mysql	select * from  ( select columna, columnb, inserttime from table1 union all select columna, columnb, inserttime from table2 )  order by inserttime limit 1, 50 	0.174617583110566
3395798	973	mysql, check if a column exists in a table with sql	select *  from information_schema.columns  where      table_schema = 'db_name'  and table_name = 'table_name'  and column_name = 'column_name' 	0.0121522222759941
3398075	18077	sql where clause with multiple keys in same table	select distinct * from   (     select * from table  where parent_id = @someid      union all     select * from table  where id = @someid                           or id = (select parent_id from table where id = @someid)      union all     select * from table where parent_id = (select parent_id                                             from table where id = @someid)                          and parent_id>0    ) f order by id 	0.0509848037408429
3399633	9488	how to construct the query	select distinct dp.id from restaurant_dp dp inner join restaurant_iw iw on dp.id = iw.id where dp.pcode = $pcode and iw.menu = $menu 	0.405224579021276
3401342	35477	how do i search "many like" in the database (mysql)?	select ...  from rooms  where dates like '%09/08/10%'    or dates like '%08/08/10%' 	0.337074234692355
3401562	35158	mysql unknown column	select y.*,        (select count(*)           from (select *,                         case type                          when 'advanced' then type                          else 'non-advanced'                        end as group_type                   from tester) x          where x.group_type = y.group_type            and (x.grade1 + x.grade2) >= (y.grade1 + y.grade2)) as rank   from (select t.name,                t.grade1,                t.grade2,                t.type,                case t.type                  when 'advanced' then t.type                  else 'non-advanced'                end as group_type           from tester t) y 	0.342560400037757
3404677	29402	question: how to use the current time in a where clause	select this, that from here where start >= now() 	0.163593124454539
3405025	37141	sql add tablename as field	select username, password, 'users' as mytable from users 	0.0325341843321724
3406412	12077	limit join query on specific table	select p.*, c.* from (select * from products limit 0,20) as p                  left join colors as c on c.colorproductid=p.productid          order by p.productid asc, c.colorid asc 	0.0645718499374829
3406782	6259	how do i calculate days since a record entry? android, sqlite, java	select (strftime('%s','now')-strftime('%s', data1))/86400.0 as days from table 	0
3407228	35377	extract directory from files field in sqlite table	select fullfilename from files where lower(fullfilename) like 'c:\folder\%' 	0.00062570737494633
3407680	1393	i'm in need of a sanity check on a sql query that will return a value if it exists in the table or return a default value if it doesn't	select coalesce(      (select mailbox from virtual_mailboxes where email = '%s'),      'all/' ); 	0.000661625394099561
3408126	32407	combine multiple rows in table into 1 resultset row	select t.name,          max(case when t.stat = 'stat1' then t.value else null end) as stat1,          max(case when t.stat = 'stat2' then t.value else null end) as stat2,          max(case when t.stat = 'stat3' then t.value else null end) as stat3,          max(case when t.stat = 'stat4' then t.value else null end) as stat4     from table t group by t.name 	0
3408589	6550	how do i remove overlapping lines in postgis	select y.id, z.id  from mytable y, mytable z where st_equals(y.the_geom,z.the_geom) 	0.00642113335011085
3408669	9079	sql direct way to get number of rows in table	select count(*) from gallery 	0
3409581	38196	how to combine aggregate functions in mysql?	select x.user,           avg(x.cnt)     from (select user, count(answer) as cnt             from surveyvalues             where study='a1'          group by user) x group by x.user 	0.593280677378948
3410583	38292	mysql search for 'no.' not 'no.' or 'no';	select * from <table> where <column> collate latin1_bin like '%no.%' 	0.392815930797035
3410687	37172	sql: group by on consecutive records	select min(weekenddate) as start_date, end_date, storecount from ( select s1.weekenddate      , (select max(weekenddate)           from store_stats s2          where s2.storecount = s1.storecount            and not exists (select null                              from store_stats s3                             where s3.weekenddate < s2.weekenddate                               and s3.weekenddate > s1.weekenddate                               and s3.storecount <> s1.storecount)        ) as end_date      , s1.storecount from store_stats s1 ) group by end_date, storecount order by 1 desc start_date end_date   storecount 2010-07-18 2010-07-25        359 2010-06-13 2010-07-11        358 2010-06-06 2010-06-06        359 2010-05-16 2010-05-30        360 	0.00337209747559412
3412973	37721	sql: how to get more information from a group by statement	select   invoice.customer_name,   invoice.customer_id,   sum(invoice.cost)  from invoice  group by  invoice.customer_name, invoice.customer_id 	0.00320501541747835
3413430	31996	how to make a random selection from database	select * from table order by random() limit 1; 	0.0106379038259628
3414600	9358	get values from all sub-divided child tables	select a.transactionid, isnull(b.receiveddate, c.receiveddate)  as receiveddate, a.value     from transactiontable as a          left outer join emailtable as b              on a.fileno = b.emailfileno                  and a.filetype='e'         left outer join documentstable as c              on a.fileno = c.docfileno                  and a.filetype = 'd'     where a.status = 'p' 	0
3414820	33124	sql query for nullable number greater than parameter	select * from items where (@itemswithpricetendollarsormore = 1 and price >=10) or (@itemswithpricetendollarsormore = 0 and price <10) or (@itemswithpricetendollarsormore is null) 	0.027458268222126
3415580	7025	get products from database	select     p.product_id as id,      p.product_name as name,      coalesce(pp.product_price, pp2.product_price) as price,      p.product_parent_id as parent,      coalesce(pp.mdate, pp2.mdate) as last_updated  from jos_vm_product p  left outer join jos_vm_product p2 on p.product_parent_id = p2.product_id left outer join (     select product_id, max(mdate) as maxmdate     from jos_vm_product_price     group by product_id ) ppm on p.product_id = ppm.product_id left outer join jos_vm_product_price pp on ppm.product_id = pp.product_id and ppm.maxmdate = pp.mdate  left outer join (     select product_id, max(mdate) as maxmdate     from jos_vm_product_price     group by product_id ) ppm2 on p2.product_id = ppm2.product_id left outer join jos_vm_product_price pp2 on ppm2.product_id = pp2.product_id and ppm2.maxmdate = pp2.mdate 	0.000673964492305249
3417390	27443	postgres query for sales projections	select sum(sub_total) as sales,          case when (sub_total<100) then '0-99'                when (sub_total>=100 and sub_total<200) then '100-199'                when (sub_total>=200 and sub_total<300) then '200-299'                when (sub_total>=300 and sub_total<400) then '300-399'                when (sub_total>=400 and sub_total<500) then '400-499'                else '500+'          end as product_sales_range,          sum(sub_total) * 1.1 as sales_increase_by_10percent,          sum(sub_total) * 1.2 as sales_increase_by_20percent     from order_item  group by sub_total 	0.275463274648625
3418154	29790	sql select from master - detail tables	select m.id,         m.brand,        x.detid,        x.parentid,        x.model   from t_master m   join t_detail x on x.parentid = m.id   join (select d.parentid,                max(d.detid) as max_detid           from t_detail d       group by d.parentid) y on y.max_detid = x.detid                             and y.parentid = x.parentid 	0.000945637904353847
3418568	11107	grab next row in sql	select personid, logondate, loggedontime        lead(loggedontime, 1, 0) over (partition by personid order by logondate, loggedontime) from agent_logout 	0.000648245181911042
3420352	14485	select where has pattern in text column. sql server 2005	select from table where column like '%[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]%' 	0.177762387447698
3420496	25935	writing sql queries from multiple tables	select [order details].* from [order details] inner join [orders] on [orders].orderid = [order details].orderid where [orders].shipcity = 'caracas' 	0.118300209763131
3422647	1008	mysql multiple tables link	select * from groupmembers g inner join users u on g.userid = u.userid where g.groupid = 15 and u.username like '%testquery%' order by u.userid 	0.0524780093368825
3424064	23516	treat null as max	select max(isnull(col1, 2147483647)) from <table> 	0.208727067186779
3426097	1684	sql query from 2 tables	select id from table1 where not exists     (select *     from table2     where table1.addressnumber between table2.addresslowrange and table2.addresshighrange         and table1.addressstreet = table2.addressstreet         and table1.addresszip = table2.addresszip     ) ; 	0.0138140039343864
3426897	37888	php + mysql (join?)	select distinct a.id2 from mytable a join (select id1, id2 from mytable where id1 = 1) b on a.id1 = b.id2 where not exists (select 1 from mytable where id1 = b.id1) 	0.572294770246878
3427353	321	sql statement question - how to retrieve records of a table where the primary key does not exist in another table as a foreign key	select a.* from tablea as a left join tableb as b on (a.id = b.tableaid) where b.tableaid is null 	0
3428400	16844	mysql count problem	select count(*)  from students_essays se where not exists(select * from                   essays_grades ge                  where se.id = eg.students_essays_id) 	0.728942343722663
3432701	25702	sql, checking if a value appears more then 2x in a table	select p.*   from peoples p  where not exists(select null                     from jobs j                    where j.personnumber = p.personnumber                   having count(distinct j.jobnumber) > 1) 	0.000727842469110152
3435957	9368	get last row per group	select m.conversationid,  max(case when m.datetime = x.firstrow then m.subject end) as subject, cast(coalesce(max(case when m.datetime = x.lastrowsentbyotheruser                         then m.datetime end),x.lastrow) as datetime)as lasttime, max(case when m.datetime = x.lastrow then m.message end) as message, max(case when fromid = 1 then toid else fromid end) as otherparticipantid from messages m join (     select conversationid, min(datetime) as firstrow, max(datetime) as lastrow,     max(case when fromid<>1 then datetime end) as lastrowsentbyotheruser     from messages     where fromid=1 or toid=1     group by conversationid ) x on x.conversationid = m.conversationid and (m.datetime in (x.firstrow, x.lastrow, x.lastrowsentbyotheruser)) group by m.conversationid having max(case when m.datetime = x.lastrowsentbyotheruser                     then m.datetime end) is not null 	0
3439886	16426	select distinct and order by	select productid, productname... from (        select distinct products.productid, productname... ) as orderproduct order by [your order code...] 	0.106405010702093
3440857	6759	sql count where clause	select        [l.leagueid] as leagueid, [l.leaguename] as name  from            (leagues l inner join                      lineups lp on l.leagueid = lp.leagueid)  group by [l.leagueid], [l.leaguename]  having        sum(case when lp.positionid = 1 then 1 else 0 end) > 2 or                      sum(case when lp.positionid = 3 then 1 else 0 end) > 6 or                      sum(case when lp.positionid = 2 then 1 else 0 end) > 3 	0.786726719035882
3441705	6157	pulling sql column names for a table	select * from information_schema.columns where table_name = 'foo' 	0.000773935924033777
3442931	34511	sql server select distinct rows using most recent value only	select t1.* from (select foreignkeyid,attributename, max(created) as maxcreated from  yourtable group by foreignkeyid,attributename) t2 join yourtable t1 on t2.foreignkeyid = t1.foreignkeyid and t2.attributename = t1.attributename and t2.maxcreated = t1.created 	0
3442970	37918	sql server 2008: select * into tmp from stored procedure	select * into #tmptbl      from openrowset ('sqloledb','server=(local);trusted_connection=yes;'    ,'set fmtonly off exec databasename.dbo.somesp') 	0.305260829305988
3443388	12920	reading from linked server and deleting on local db	select [uniquefield] from [remoteserver].[remotedb].[dbo].[tablea] 	0.0217581215864967
3443672	20718	integer division in sql server	select 151/cast(6 as decimal (9,2)) 	0.584302816090343
3445519	14447	return distinct and null records from a mysql join query	select x.order_id,        x.item_id,        x.name,        x.qty_ordered,        x.base_price,        x.row_total,        x.order_total   from (select case                    when @order = o.order_id then null                    else o.order_id                 end as order_id,                oi.item_id,                oi.name,                oi.qty_ordered,                oi.base_price,                oi.row_total,                o.order_total,                case                    when @order = o.order_id then null                    else o.order_total                 end as order_total,                @order := o.order_id           from order_items oi            join orders o on o.order_id = oi.order_id           join (select @order := -1) r       order by o.order_id, oi.item_id) x 	0.00313411017630471
3445718	4939	is there a way in mysql to choose an order for the beginning and end of rows returned?	select u.id     from users u order by case id            when 4 then 1            when 5 then 2            when 7 then 3            when 8 then 4            when 55 then 100000            when 56 then 100001            when 58 then 100002            else id          end asc 	0.000113127495073657
3446242	27105	convert datetime variable into string in sql server	select convert(varchar(100),getdate(),110) 	0.05727614435196
3447421	35708	how to select a record from a many to many table where one id exists in one but not another?	select product_id, category_id from   wp_wpsc_item_category_assoc winc where  winc.category_id in (5, 6) and    not exists     (select 0 from wp_wpsc_item_category_assoc wexc      where wexc.product_id = winc.product_id      and wexc.category_id in (7)) 	0
3447441	23930	how to group rows in sql with more than 2 columns are of the same value?	select column1, column2 from mytable group by column1, column2 	0
3447494	18769	how to write a sql to cascadingly accumulate rows of data?	select t1.team, t1.sprint,g.wh-sum(t2.workhours)  from tbl t1 join tbl t2 on t1.team = t2.team and t2.sprint <= t1.sprint  join     (select sum(workhours) as wh, team  from tbl group by team) g on t1.team=g.team  group by t1.team, t1.sprint,g.wh 	0.00419123066993498
3449757	18556	sql: group by records and then get last record from each group?	select a.*  from test a  where a.attendence = 1  and not exists (select 1 from test where name = a.name and id > a.id and attendence = 1) group by name 	0
3450144	721	sql merging two tables and updating referenced ids	select a.level_id alevelid, b.level_id blevelid,         case isnull(a.level_id, 0) when 0 then 'b' else 'a' end as type,        case isnull(a.level_id, 0) when 0 then b.level_id else a.level_id end as newlevel_id into dummy        from  a  full join  b on (a.level_id = b.level_id);  update c set c.level_id = dummy.newlevel_id from dummy, c where c.level_id = dummy.alevelid  and dummy.type = 'a'; update d set d.level_id = dummy.newlevel_id from dummy, d where d.level_id = dummy.blevelid  and dummy.type = 'b'; select dummy.newlevel_id, a.level, a.leveldesc as description into yournewtable from dummy join a on (dummy.alevelid = a.level_id) where dummy.type = 'a' union select newlevel_id, level, leveldesc as description from dummy join b on (dummy.blevelid = b.level_id) where dummy.type = 'b' drop table dummy; 	0.000198519529911319
3450965	19518	determine if oracle date is on a weekend?	select * from mytable where mod(to_char(my_date, 'j'), 7) + 1 in (6, 7); 	0.0322220784884189
3451567	13966	mysql regex at runtime	select telephone_number from table where telephone_number regexp '^1[() -]*999[() -]*999[() -]*9999$'; 	0.521641742911025
3451856	27491	multiple database in single query is possible?	select * from `databasename`.`tablename` ...   ... left join `databasename_2`.`tablename`.... 	0.178683984999277
3452597	22924	count is grouping rows unexpectedly	select i.item_type, i.item_name, count(j.id) from items i left outer join individual_items j on i.item_type = j.item_type group by i.item_type, i.item_name 	0.0396370915755201
3455201	12999	count based on condition in sql server	select     count(*),       sum(case when name = 'system' then 1 else 0 end)  from     mytable 	0.0143413385381393
3455739	18622	how to select records grouped by the hour of the day including hours that have no records	select h.hrs, nvl(quantity, 0) quantity from (select trim(to_char(level - 1, '00')) hrs        from dual        connect by level < 25) h left join (select to_char(event_date, 'hh24') as during_hour,                   count(*) quantity            from user_activity u            where event_date between                  to_date('15-jun-2010 14:00:00', 'dd-mon-yyyy hh24:mi:ss') and                  to_date('16-jun-2010 13:59:59', 'dd-mon-yyyy hh24:mi:ss')            and event = 'user.login'            group by to_char(event_date, 'hh24')) t on (h.hrs = t.during_hour) order by h.hrs; 	0
3456235	29645	how to replace leading null values with the first non-null value in a row?	select     id,     coalesce(sp1,sp2,sp3,sp4,sp5,sp6,sp7,sp8,0) as sp1,     coalesce(sp2,sp3,sp4,sp5,sp6,sp7,sp8,0) as sp2,     coalesce(sp3,sp4,sp5,sp6,sp7,sp8,0) as sp3,     coalesce(sp4,sp5,sp6,sp7,sp8,0) as sp4,     coalesce(sp5,sp6,sp7,sp8,0) as sp5,     coalesce(sp6,sp7,sp8,0) as sp6,     coalesce(sp7,sp8,0) as sp7,     coalesce(sp8,0) as sp8 from     (<your existing query>) t 	0
3456402	22603	storing geo data	select * from table where latitide<40; 	0.609005092227669
3457268	6445	sql query to get columns and records of that columns using like operator	select 'keyword' as keyword, 'part1_d1' as part1_d1, 'part1_d2' as part1_d2,    'part1_d3' as part1_d3, 'part1_d4' as part1_d4, 'part2_d5' as part2_d5, union select keyword, cast(part1_d1 as varchar(50), cast(part1_d2 as varchar(50),    cast(part1_d3 as varchar(50), cast(part1_d4 as varchar(50),    cast(part2_d5 as varchar(50) from sample 	0.000664510087316286
3458818	28128	finding similar records with sql	select s.id, s.locationid, s.name, a.id, a.line1, a.postalcode from (     select line1 + ', ' + postalcode as line1postalcode     from address a     inner join store s on a.id = s.locationid     group by line1+ ', ' + postalcode     having count(*) > 1 ) ag inner join address a on ag.line1postalcode = a.line1+ ', ' + a.postalcode inner join store s on a.id = s.locationid 	0.00998145301028632
3459391	29675	how to query for rows that have highest column value among rows that have same value for one of the columns	select id, userid, score   from userscores  where id in (select max(id)                 from userscores                group by userid              )   order by userid 	0
3459605	17969	sql-query: exists in subtable	select ... from tabdata as t1 where exists    (                 select 1                 from tabdatadetail as tdd1                 where tdd1.fidata = t1.iddata                     and tdd1.fiactioncode = 11                 )     and not exists    (                       select 1                       from tabdatadetail as tdd1                       where tdd1.fidata = t1.iddata                           and tdd1.fiactioncode not in(11,34)                     ) 	0.567140512625807
3459931	40063	how can i see the contents of an oracle index?	select        id, rowid    from a  where id is not null  order by id, rowid; 	0.0269473989713005
3460805	30766	postgresql: format interval as minutes	select extract(epoch from '2 months 3 days 12 hours 65 minutes'::interval)/60; 	0.0195207690837453
3462824	22539	joining new columns in mysql one-to-many	select c.first_name,          max(case when p.year = 2009 then c.amount_paid else null end) as 2009,          max(case when p.year = 2008 then c.amount_paid else null end) as 2008,          max(case when p.year = 2007 then c.amount_paid else null end) as 2007     from customer c     join payment p on p.customer_id = c.customer_id group by c.first_name 	0.0148776683370982
3463459	18576	sql query to retrieve data while excluding a set of rows	select distinct id, objectname  from objects  where id not in ( select distinct objectdetails.objectid  from objectdetails inner join components on objectdetails.componentid = components.id where components.componentname = 'a' or components.componentname = 'b' ) 	5.92446980760171e-05
3465212	23642	how to get field name what are the field have value?	select quesno, substring(answers, 1, length(answers) - 1) as answers from (     select quesno,            case             when a <> 0 then 'a,'             else ''            end +            case             when b <> 0 then 'b,'             else ''            end +            case             when c <> 0 then 'c,'             else ''            end +            case             when d <> 0 then 'd,'             else ''            end as answers from yourtable ) foo 	0
3465638	18976	hierarchical max	select *     from mytable     order by column_a desc, column_b desc     limit 1; 	0.351083521979685
3465848	8667	converting string (in eastern daylight time format) to date in sql	select     cast('fri jun 19 10:45:39 edt 2009' as date),        to_char(cast('fri jun 19 10:45:39 edt 2009' as date), 'dd-mm-yyyy')  	0.085233596803039
3466548	35663	php explode or unique mysql table for user's friends?	select id,foo,bar,group_concat(friend_id) as friends   from user   left join friends on(user.id=friends.user)  group by user.id; 	0.00212021593048371
3467039	28522	querying mysql table for times after the current one	select time from yourtable where time > now() 	0
3468184	16655	minus two tables based on 2 columns	select bt.controlnum, bt.carriername, bt.phonenum, bt.patientname, bt.subscriberid,  bt.subscribername, bt.chartnum, bt.dob, bt.subscriberemp, bt.visitid, bt.servicedate,  bt.providername, bt.cptcode, bt.billingdate, bt.agingdate, bt.balanceamt, bt.age,  bt.agecategory from billing_temp bt left join billing on  bt.controlnum=billing.controlnum and bt.cptcode=billing.cptcode 	0
3469591	32378	selecting a mysql row from one table based on select statement in another	select    submissions.name,   submissions.id,   submissions.uploader,   submissions.image_vote  from    submissions,votes   where    submissions.date_voted is not null and   submissions.id not in (select tee from votes where user='3')  limit 1 	0
3470690	39024	how to check if a list have any different value	select key, "there are duplicates" from (     select key,date1 from table     union all     select key,date2 from table     union all     select key,date3 from table     union all     select key,date4 from table     union all     select key,date5 from table ) as aa group by   key, date1 having    count(*) > 1 	4.60924938514373e-05
3470794	33416	how can i aggregate the # of seconds in a query result?	select count(*) * 15 from your_table 	0.0290811296142804
3470856	10907	match two keyword list columns against another column for matches	select * from interests i where      (i.accept = '' and i.reject = '')     or     (         exists (select * from split(',', i.accept) ia where ia.[value] in (productkeywords(@productid)))         and         not exists (select * from split(',', i.reject) ir where ir.[value] in (productkeywords(@productid)))     ) 	0
3471199	34393	mysql: get all characters before blank	select left(field1,locate(' ',field1)) 	0.00137791752983975
3471733	34315	ordering fulltext searches on relevance and other fields	select column_a, column_b, match(...) against (...) as score from ... order by score desc, column_a desc 	0.657908523238735
3472290	6931	how to create a view spliting one column to 2 or more using a regular expression?	select regexp_substr(text, '[:digit:]{5}', 1, 1) as first_refid,        regexp_substr(text, '[:digit:]{5}', 1, 2) as second_refid   from table 	0.0541855358980407
3472415	40164	trying to join tables and select by one distinct max value	select `p`.`id`, `o`.`id`, `o`.`email`, max(d.number)   from (`pets` as `p`, `owners` as `o`, `data_entries` as `d`)   where `p`.`owner_id` = `o`.`id`       and `p`.`id` = `d`.`pet_id`   group by `p`.`id`, `o`.`id`, `o`.`email`   order by `d`.`number` desc 	0.000757055922218473
3472476	6717	how can i get a list of tables in a database without a timestamp column?	select * from information_schema.tables t where not exists    (       select 1          from information_schema.columns         where table_catalog = t.table_catalog          and table_schema = t.table_schema          and table_name = t.table_name          and data_type = 'timestamp'    ) 	0
3479740	14223	pivot / crosstab query in oracle 10g (dynamic column number)	select t.username,          max(case when t.product = 'chair' then t.numberpurchases else null end) as chair,          max(case when t.product = 'table' then t.numberpurchases else null end) as tbl,          max(case when t.product = 'bed' then t.numberpurchases else null end) as bed     from table t group by t.username 	0.739862729373066
3479855	32504	sql select by a given time past the hour	select from table where extract(minute from timestamp field) = 30; 	0
3480247	7355	sql - how to find ytd amount?	select employee,          payperiod,         (select sum ([hours]) from @hours f2               where f2.payperiod <= f.payperiod and f2.employee=f.employee) as hh  from @hours as f  where  year(payperiod) = year(getdate())   group by employee, payperiod  order by payperiod 	0.00473478132997667
3480311	15806	mysql remove space before order by clause	select trim(title) as title, field2, field3 from products order by trim(title) 	0.433861111585485
3480803	1051	pivot/unpivot tables mysql	select table1.value as avalue, table2.value as bvalue from table1 join table2 on table1.grp = table2.grp and table2.type = 'b' where table1.type = 'a' 	0.227464547994965
3480947	7680	mysql select rows where timestamp column between now and 10 minutes ago	select *     from status    where code = 'mycode'      and `stamp_updated` between date_sub(now() , interval 10 minute)                            and now() order by stamp_updated desc    limit 1 	0
3482350	27300	how to sort within a group of data and sort the groups by max value within each group in a mysql query	select t1.id, t1.entry_id, t1.the_data from mytable t1 inner join (     select entry_id, max(id) as maxid     from mytable     group by entry_id ) maxs on maxs.entry_id = t1.entry_id where (     select count(t2.id) from mytable t2     where t2.entry_id = t1.entry_id and t2.id > t1.id ) <= 2 order by maxs.maxid desc, t1.entry_id desc, t1.id desc 	0
3485281	25087	check if a list of other strings is %like% another string	select * from books where match(fulltext_column) against('animal book a') 	0.000141431488800253
3486644	32906	sql many to many select	select m.name, cp.id_category from manufacturer as m inner join product as p     on m.id_manufacturer = p.id_manufacturer inner join category_product as cp     on p.id_product = cp.id_product where cp.id_category = 'some value' 	0.148418067766114
3488371	17260	multiple row sql where clause	select distinct leagueid    from lineups l    where exists (select * from lineups                  where leagueid = l.leagueid                     and positionid = 1                      and qty = 1)      and exists (select * from lineups                  where leagueid = l.leagueid                     and positionid = 3                      and qty = 2) 	0.304399471198127
3489728	11052	select distinct and count	select tag, count(*) from mytable group by tag 	0.0547664163854569
3489767	5186	mysql query joining table data	select m.left_players_id, l.name as left_player, m.right_players_id, r.name as right_player  from players r, payers l, matchups m  where m.left_players_id = l.id and m.right_players_id = r.id 	0.0555073516833397
3491329	20028	group by with max(date)	select t.train, t.dest, r.maxtime from (select train, max(time) as maxtime       from traintable       group by train) r inner join train t on t.train = r.train and t.time = r.maxtime 	0.429882387365272
3492539	922	mysql : multiple row as comma separated single row	select m.meal_id,          group_concat(dish_id) dish_ids,          group_concat(dish_name) dish_names  from dish_has_dishes m join dish d on (m.dish_id = d.dish_id)  group by meal_id 	0
3494273	32150	combine multiple sql fields into 1 output row	select u1.userid, u1.value, u2.value  from yourtable u1 inner join yourtable u2 on u2.userid=u1.userid where u1.attribute='username' and u2.attribute='password'; 	0.000555013972322233
3494990	26731	sql delete query --- more detail	select 'starting'  while @@rowcount <> 0     delete top (10000) tbl_transactions     where not exists (select *                          from tbl_socketconnections                        where tbl_transactions.transactionid = tbl_socketconnections.transactionid)       and not exists(select *                         from tbl_protocolcommands                       where tbl_transactions.transactionid = tbl_protocolcommands.transactionid)       and not exists(select *                         from tbl_eventrules                       where tbl_transactions.transactionid = tbl_eventrules.transactionid) 	0.122198605054072
3495444	40981	do all rdbms have a data dictionary comparable to the one oracle has?	select * from information_schema.columns 	0.000228272523658233
3495638	6245	trying to modify a monthly report to a weekly. aspen sql	select count(*)   from history h  where h.period = '0:00:15'        and h.request = '1'        and h.stepped = '1'        and h.ts between starttime and endtime        and (   (h.name = tag1name and h.value = tag1cond)              or (h.name = tag2name and h.value = tag2cond)); 	0.0274653258761024
3495876	39837	how can i select the database record with the most vote_points and ensure that it is displayed first? php / kohana 3	select *  from answers where question_id = x order by    (points = (select max(points) from answers where question_id = x)) desc,       created_at asc 	0
3498844	26537	sqlite string contains other string query	select *   from table  where column like '%cats%' 	0.0140599033807521
3499239	6027	sql server 2005 - removing table triggers?	select 'drop trigger ' + name from sysobjects where type = 'tr' 	0.366273061223572
3499295	36956	how do i check if a table exists in sqlite3 c++ api?	select count(type) from sqlite_master where type='table' and name='table_name_to_check'; 	0.312728730250375
3500839	21134	conditionally sql query	select * from users where name = 'user1' union all  select * from users where name = 'default'      and not exists (select 1 from users where name='user1') 	0.449209244132042
3501254	16017	find rows in table that fall under minimum and maximum range	select * from @temp where not (@maximum < minimum or @minimum > maximum) 	0
3501463	13037	intersect 2 tables in mysql	select b.visitid,  b.carriername, b.phonenum, b.patientname,   b.subscriberid, b.subscribername, b.chartnum, b.dob,   b.subscriberemp, b.servicedate, b.providername, b.cptcode,   b.agingdate, b.balanceamt,   f.followupnote, f.internalstatuscode from billing b left join followup f on b.visitid = f.visitid 	0.11310221124856
3502136	33474	sql time period query	select * from a_table where date_added between date_sub(curdate(), interval 6 week) and curdate() 	0.0779413411319029
3504012	27304	sql: how to find duplicates based on two fields?	select  * from    (         select  t.*, row_number() over (partition by station_id, obs_year order by entity_id) as rn         from    mytable t         ) where   rn > 1 	0
3505603	5317	setting up a default value of a column in select statement	select name, city, addr, 12345 as ph_no from table1 	0.0179721480497304
3505654	18287	select multiple distinct fields, and summing another field	select     sub_acct_no_paj,     customertype,     post_dte_paj,     ia_dateyear,     adj_rsn_paj,     sum(post_amt_paj) as post_amt_paj_total     count(*) as [acount] into temptable1 from all_adjustments group by     sub_acct_no_paj,     customertype,     post_dte_paj,     ia_dateyear,     adj_rsn_paj 	0.000251013865302557
3505676	30965	query to select subcategories of categories of destinations which are active?	select subcategories.name as subcategory_name, subcategories.slug as subcategory_slug, categories.name as category_name, categories.slug as category_slug from destination  inner join destinations_subcategories on destination.id = destinations_subcategories.destination_id and destination.active = 1 left join subcategories on destinations_subcategories.subcategory_id = subcategories.id left join categories on destinations_subcategories.category_id = categories.id where 1=1  and subcategories.is_active = 1  and categories.is_active = 1 	0.000108879259583029
3505752	20325	quickest way to identify most used stored procedure variation in sql server 2005	select top 50 * from(select coalesce(object_name(s2.objectid),'ad-hoc') as procname,   execution_count,s2.objectid,     (select top 1 substring(s2.text,statement_start_offset / 2+1 ,       ( (case when statement_end_offset = -1   then (len(convert(nvarchar(max),s2.text)) * 2) else statement_end_offset end)- statement_start_offset) / 2+1)) as sql_statement,        last_execution_time from sys.dm_exec_query_stats as s1 cross apply sys.dm_exec_sql_text(sql_handle) as s2 ) x where sql_statement not like 'select * from(select coalesce(object_name(s2.objectid)%' and objectpropertyex(x.objectid,'isprocedure') = 1 and exists (select 1 from sys.procedures s where s.is_ms_shipped = 0 and s.name = x.procname ) order by execution_count desc 	0.761845044394348
3505850	15765	combining columns from multiple sql queries	select      count(distinct case when jtprocess = 'verify-envprint' then jtbarcode else null end) as countevp ,      count(distinct case when jtprocess = 'envprint' then jtbarcode else null end) as countep  from jobtracker with(nolock) where jtprocess in ('verify-envprint', 'envprint')     and jtbarcode in(select lookupcode from data with(nolock) where clientid = 123 and batchid = 12345 and jobid = 1 and subjobid = 1 and entrytype<>'c' and entrytype<>'m') group by jtbatchid 	0.00468651121917243
3506808	28271	mysql - math queries	select sum((qty-mean)*square(qty-mean)        /(n*sigma*square(sigma))) as skew,        sum(square(square(qty-mean))        /(n*square(square(sigma))))-3 as excesskurtosis from pubs..sales, (   select     avg(qty) as mean,     stdev(qty) as sigma,     count(qty) as n   from pubs..sales ) s 	0.741452890510071
3507106	17290	selecting same column with different where conditions	select sum(price) as total, sum(case when closed = 1 then price else 0 end) as closed_total  from   dbo.sales  where  salesperson_id = @salesperson_id         and date_ordered between @start_date and @end_date  group by date_ordered 	0.000562269012784899
3507711	28533	query mysql: select from timestamp	select unix_timestamp("$timestamp 00:00:00"), unix_timestamp("$timestamp 23:59:59") 	0.0157277977739037
3508812	33031	php: how to change string data become numeric data	select `model`, if(`class`='s', 1, 0) as `s`, if(`class`='a', 1, 0) as `a`, if(`class`='b', 1, 0) as `b`, if(`class`='c', 1, 0) as `c` from `inspection_report` 	0.00445139751314062
3511845	10853	how to select from database with relations?	select *  from zamestnanci join lekaty on lekaty.zamestnanciid = zamestnanci.id join obsah on obsah.idletaku = lekaty.id join knihy on knihy.id = obsah.idknihy where letaky.id = 123 	0.0191895296759161
3512237	36710	mysql - find client with most transactions on a table	select count(client_id) as transaction_count, client_id      from transactions     group by client_id     order by count(client_id) desc     limit 1 	0.004373019979037
3514927	19256	filtering rows with datetime values that are within 1 minute	select yt.username ,           max(yt.logged) as logged     from your_table yt group by yt.username, dateadd(minute,datediff(minute,0,logged),0) 	9.78992514332207e-05
3515218	35210	using like to search for a name	select * from tablename where lower(sort_name) like '%name1%'   ...   and lower(sort_name) like '%namen%' 	0.435107691773027
3516873	22450	hql: fetch join collections from eager table	select distinct      rn from     rootnode rn left join fetch      rn.subnode sn left join fetch      sn.subnodechildren 	0.0783704808771614
3517062	6183	using if in a sql server view	select     case when newvalue > -1 then       newvalue     else       null   end as oldvalue from dbo.mytable 	0.568389133186048
3517447	4425	how can i get only one row per record in master table?	select fa.farm as farm_name,          max(case when fa.apple = 1 then fa.apple else null end as apple_1,          max(case when fa.apple = 2 then fa.apple else null end as apple_2,          max(case when fa.apple = 3 then fa.apple else null end as apple_3,     from farm_apples fa group by fa.farm 	0
3519742	1022	joining tables when certain one table has no values?	select u.uid, u.name, ifnull(c.nodecount,0) as `count` from user u left join (     select uid, `type` , count(nid) as nodecount     from node     where type = 'car'     group by uid, type ) as c on u.uid = c.uid 	0
3521124	27811	how to calculate maximum of two numbers in sql select	select total = case when number_of_items > 0                 then total/number_of_items                else total end from   xxx 	0
3521944	9315	simple sql query, combine results and divide	select (a.count_one / b.count_two) * 100 as final_count from  (select field_one, count(*) as count_one from table1 group by field_one) a, (select field_two, count(*) as count_two from table2 group by field_two) b where a.field_one = b.field_two 	0.595171339056951
3525086	5144	how can i add an additional field to an sql group by clause	select sm.name, sm.averagescore, sm.best_score, s.subject from (     select  name,  avg(score) as averagescore, max(score) as best_score      from scoretable      group by name  ) sm inner join scoretable s on sm.name = s.name      and sm.best_score  = s.score 	0.339971166350277
3525096	32843	displaying oracle table's column names	select column_name from user_tab_columns where table_name='table_name' 	0.00399789891621653
3525448	9644	check if table exists in the database - pl sql	select tname from tab where tname = 'table_name_to_search_for'; 	0.0178689676846107
3526604	21191	using pivot in sql server to display dates as days of the week	select bugno, [monday], [tuesday], [wednesday], [thursday], [friday], [saturday], [sunday] from (     select bugno, datename(dw, dateopened) as dayweek, timespent     from bugs     ) as src     pivot (         sum(timespent) for dayweek in ([monday], [tuesday], [wednesday], [thursday], [friday], [saturday], [sunday])     ) as pvt 	0
3528102	28014	finding data according to relevency and then take 2 result from diff domain	select x.url   from (select t.url,                t.teet,                t.html,                case                   when @domain = substring_index(t.url, '/', 1) then @rownum := @rownum + 1                  else @rownum := 1                end as rank,                @domain := substring_index(t.url, '/', 1)           from url2 t           join (select @rownum := 0, @domain := '') r       order by substring_index(t.url, '/', 1)) x  where x.rank <= 2 	0
3528754	2358	get results from mysql based on latitude longitude	select degrees(acos(sin(radians(clients.latitude)) * sin(radians(schools.latitude)) +                      cos(radians(clients.latitude)) * cos(radians(schools.latitude))                                                     * cos(radians(clients.longitude                                                                 – schools.longitude))))         * 60 * 1.1515 * 1.609344 as distance from clients, schools having distance < $radius 	0.000234517193845934
3529226	32032	mysql group integer column into groups of 100	select      truncate(pri/100,0)*100 as range_start,     count(*) from ... group by     truncate(pri/100,0)*100; 	0.000679582146796589
3530119	19360	pivoting for two columns	select  contact_id,     case when count(case when year(date_created) = 2006 then 1 end) > 0 then 1 else 0 end as gift_2006, sum(case when year(date_created) = 2006 then amount_exc_vat end) as [2006_excvat] , sum(case when year(date_created) = 2006 then amount_inc_vat end) as [2006_incvat] , case when count(case when year(date_created) = 2007 then 1 end) > 0 then 1 else 0 end as gift_2007, sum(case when year(date_created) = 2007 then amount_exc_vat end) as [2007_excvat] , sum(case when year(date_created) = 2007 then amount_inc_vat end) as [2007_incvat] , case when count(case when year(date_created) = 2008 then 1 end) > 0 then 1 else 0 end as gift_2008, sum(case when year(date_created) = 2008 then amount_exc_vat end) as [2008_excvat] , sum(case when year(date_created) = 2008 then amount_inc_vat end) as [2008_incvat]  from gifts  group by contact_id 	0.00538510987049409
3530133	41201	sql server transpose rows to column value	select project,   (select state + ''    from table t    where t.project = m.project    for xml path(''))  from table m  group by project 	0.00161403023493634
3532240	30909	sql min(date) issue with still getting all dates	select op.date, op.orderid, op.opid from (     select orderid, min(date) as mindate      from orderpermits       group by orderid  ) opm inner join orderpermits op on opm.orderid = op.orderid      and opm.mindate = op.date 	0.111567200026971
3532441	26616	mysql: how do i add up values if the occur on the same day?	select sum(t.value_column)   from table t group by date(t.datetime_column) 	0
3532588	7713	mysql: query to sort data based on the attribute of another column	select date(p.born_at),  sum(case when status = 1 then p.value end) as 'status = 1', sum(case when status = 2 then p.value end) as 'status = 2', sum(case when status = 3 then p.value end) as 'status = 3' from puppies as p where p.status in(1,2,3) group by date(p.born_at); 	0
3532909	8282	concatenating multiple result rows into a single result without using for xml path	select substring((   select ('; ' + rtrim(c.somefield))   from a (nolock)   inner join b (nolock) on a.aid = b.aid   inner join c (nolock) on b.cid = c.cid   where a.zid = z.zid   for xml path(''), root('xml'), type ).value('/xml[1]','varchar(max)'), 3, 1000) 	0.000261162820333223
3532942	21744	sql return all id's from 1 table and only ones that don't match from another	select * from '#tmptable1'  union all select * from  '#tmptable2' where      id not in (select id from #tmptable1 where id is not null) 	0
3533757	28376	how to execute all views in database through stored procedure	select quotename(table_schema) +'.' + quotename(table_name) as viewname,  identity(int,1,1) as id   into #test   from information_schema.tables  where table_type = 'view' declare @loopid int,@maxid int select @loopid =1,@maxid =max(id)  from #test declare @viewname varchar(100) while @loopid <= @maxid begin select @viewname = viewname  from #test where id = @loopid exec ('select top 1 * from ' + @viewname) set @loopid = @loopid + 1 end drop table #test 	0.137301259540345
3533989	15511	sql query to get single row value from an aggregate	select id from mytable where start_date = (select max(start_date) from mytable) 	0.000229198007363193
3534015	5216	oracle 10g - determine the date a trigger was last updated	select object_name, object_type, created, timestamp from user_objects where object_name = 'nameofyourtrigger' 	0.000337243908276693
3534282	21206	mysql custom select query	select tbl1.name,tbl1.id,tbl2.name,tbl2.id from mytable tbl1,mytable tbl2  where tbl1.id=1 and tbl2.id=2 	0.653612510748243
3534735	9934	how to create a table from the results of a sql query?	select a.name, b.id into employeedetail  from database1 a left join database2 b on a.id = b.id 	0.000678719959777279
3534848	18686	sql query for adding missing values for a field between two dates?	select             (select top (1) weight          from biouser as b          where (cast(datetested as date) <= k.date) and (userid= @userid)          order by datetested desc) as weight, date as datetested from     dimdate as k where     (date between @startdate and @enddate) 	0.000208700256533109
3534876	30066	transact-sql select with name only	select ... from fields as f     join values as v         on v.fieldid = f.fieldid where f.fieldname = @fieldname 	0.0588017235336829
3536283	38056	how to join two tables mysql?	select * from table1 left join table2 on table1.id = table2.id 	0.0353818444786988
3539659	40845	limit characters for mysql_query(select) lookup	select substring(text_column,1,4)  from random_table where something = something else 	0.533948499856476
3541865	14467	sql - get answer from query as a single number	select count(*) as numberofparticipants from  ( select pnr   from participates  group by pnr having count(activities)>3 ) t 	0.000227212039289698
3543149	11627	is it possible to perfom a fulltext search against a joined column?	select a.idad,           a.ads_in_cat,           a.title,           a.currency,           a.price,           a.in_dpt,           a.description,           d.*,            s.*       from ads a left join dept d on d.id_dept = a.in_dpt left join sub_cat_ad s on s.id_sub_cat = a.ads_in_cat                       and match (s.sub_cat_name) against(:searchterm)      where match(a.title, a.description) against(:searchterm) 	0.752364605866262
3544748	10053	i need a sql statement that returns the number rows in a table with a specific value	select t.teamid,           t.teamname,           coalesce(count(p.playerid), 0) as playercount,           t.rosterspots      from teams t left join players p on p.teamid = t.teamid  group by t.teamid, t.teamname, t.rosterspots 	4.93732697820059e-05
3546955	16550	mysql problem! needs to select unique value from one row only	select *              from (                 select * from actions                  as a                 where date(timestamp) = curdate()                  and timestamp = (                     select max(timestamp)                      from actions                      as b                     where a.kid_id = b.kid_id                     )                 )             as c 	0
3548825	28792	select rows with a set of values (in multiple rows in conjunction [and]) in sql server	select id  from mytable where value in (1, 2, 3)  group by id having count(distinct value) = 3 	0.000572702282929263
3548965	16892	how do i count two entries in one sql query in c#?	select count(id) as postcount, username where username = '@username' group by id, username select count(threadid) as threadcount, username where username = '@username' group by id, username 	0.000409278024737896
3549267	342	transact-sql query / how to combine multiple join statements?	select     values.value from     values inner join fields on         values.fieldid = fields.fieldid       inner join formfields on         fields.fieldid = formfields.fieldid       inner join forms on         formfields.formid = forms.formid     inner join datapools on         forms.formid = datapools.formid where     fields.fieldname = @fieldname     and     forms.formname = @formname     and     datapools.poolname = @poolname; 	0.63214758605457
3552574	1876	how to find range of a number where the ranges come dyamically from another table?	select personid, sizename from    (    select       personid,       (select max([lowerlimit]) from dbo.[size] where [lowerlimit] < [count]) as lowerlimit    from dbo.person    ) a    inner join dbo.[size] b on a.lowerlimit = b.lowerlimit 	0
3553202	15419	mysql: how to collect the array data?	select id, date(a.inspection_datetime) as date,                   a.model, count(a.serial_number) as qty,                   b.name                   from inspection_report as a                   left join employee as b                   on a.nik=b.nik                   group by date,b.name 	0.0105193175919015
3553457	4841	parsing a string into an table using oracle sql	select id, string   ,substr(string, instr(string, '<', 1, element_number)     ,instr(string, '>', 1, element_number) - instr(string, '<', 1, element_number) + 1) result from test cross join (   select level element_number from dual connect by level <=     (select max(length(string) - length(replace(string, '<', null))) max_elements from test) ) extra_rows where element_number <= length(string) - length(replace(string, '<', null)) order by id, element_number; 	0.0691810356935325
3553643	23866	counting some data array not work	select item, count(colour) as colour_qty from mytable group by item 	0.509508241011707
3554025	13016	retrieve current value of arithabort	select sessionproperty('arithabort') 	0
3554107	41064	sql search, search for a|b|c|d in a table and return results ordered by number of elements in the record	select      day_name, count(day_name) qty from     actions where      name in ('eat', 'sleep', 'write', 'drink') group by day_name order by qty desc 	0
3555782	24361	constructing a query for the following table	select *     from sales     where sales.date_of_sales = (select max(date_of_sales)                                      from sales s2                                      where s2.customerid = sales.customerid); 	0.519534033581742
3561881	7301	mysql: pivot + counting	select t.fk,          sum(case when t.status = 100 then 1 else 0 end) as count_100,          sum(case when t.status = 101 then 1 else 0 end) as count_101,          sum(case when t.status = 102 then 1 else 0 end) as count_102     from table t group by t.fk 	0.296911205893817
3561990	34364	how can i optimize a query that does an order by on a derived column in mysql?	select * from  (select `scrapesearchresult`.`creative_id`,          max(`scrapesearchresult`.`access_date`) as `latest_access_date`  from `scrape_search_results` as `scrapesearchresult`  where 1 = 1  group by `scrapesearchresult`.`creative_id`  ) as inner order by `latest_access_date` desc  limit 20; 	0.726229385803822
3562596	26112	how to get multiple columns in one variable in mysql query	select a.name as article_name,          group_concat(t.name) as types     from articles a     join article_type at on at.article_id = a.id     join type t on t.id = at.type_id group by a.name 	0.000626354867831805
3562787	31645	crosstab/pivot query in tsql on nvarchar columns	select t2.recordid,          max(case when t1.property = 'name' then t2.value end) as name,          max(case when t1.property = 'city' then t2.value end) as city,          max(case when t1.property = 'designation' then t2.value end) as designation     from table2 t2     join table1 t1 on t1.id = t2.table1id group by t2.recordid order by t2.recordid 	0.288561741449779
3566565	19407	query to find table relationship types	select p.table_name, 'is parent of ' rel, c.table_name from   user_constraints p join   user_constraints c on c.r_constraint_name = p.constraint_name                          and c.r_owner = p.owner where p.table_name = 'mytable'     union all select c.table_name, 'is child of ' rel, p.table_name from   user_constraints p join   user_constraints c on c.r_constraint_name = p.constraint_name                          and c.r_owner = p.owner where c.table_name = 'mytable' 	0.00760352327364322
3566691	11225	query help need in finding missing numbers	select distinct id from (     select id, group, lag(group, 1, -1) over (partition by id order by group) prevgroup  from table  )       where group -1 <> prevgroup 	0.592480724851098
3567323	7620	i need to improve my t-sql query so that i can return the sum of columns	select  patron_name,  federal_number,  hst_number,  average_bf_test,  statement_number,  period_ending,  sum(quota_payment) as quota_payment,  sum(total_deductions) as total_deductions,  sum(net_cheque_or_direct_deposit) as net_cheque_or_direct_deposit,  sum(interim_payment) as interim_payment,  sum(final_payment) as final_payment  from (quassnois query here) a  group by  patron_name,  federal_number,  hst_number,  average_bf_test,  statement_number,  period_ending 	0.438608805146944
3571367	26204	mysql: select maximum year value from my table?	select * from tbl order by year desc limit 1 	0
3572919	11262	mysql - select multiple maximum values	select user_id, max(price) from `order` group by user_id 	0.00164451079722489
3573472	57	sql select distinct rows from a table by multiple columns ignoring columns order (significance)	select firstname,lastname from people where firstname <= lastname union select lastname,firstname from people where lastname < firstname 	0
3574112	15558	selecting multiple values from 2 columns in mysql	select * from table where  (town in ( 'oxford' , 'abingdon' )) and (type in ( 'type1','type2')) 	0
3574403	38503	mysql select query - remove unwanted rows	select * from prods p1 where (date <= '2010-08-26')  and date in (select max(date) from prods p2 where p1.prodid = pr.prodid               and date <= '2010-08-26') order by activeuntil desc 	0.15233600901536
3574848	6223	copying a table in sql server	select * into newtable from oldtable where 1 =2  	0.145292413791685
3577314	12998	mysql like wildcard for table	select *  from feed, recipients  where feed.title like concat('%', recipients.suburb, '%') order by pubdate desc 	0.771081559572543
3578803	35539	getting data from 3 tables via a recurring id	select *      from `mailers`  left join `mailer_content` on `mailers`.`id` = `mailer_content`.`mailer_id`  left join `mailer_images` on `mailer_content`.`id` = `mailer_images`.`content_id`                          and `mailers`.`id` = `mailer_images`.`mailer_id`      where `mailers`.`id` = 47 	9.38400508476581e-05
3579092	26890	tsql: get last queries ran	select top 50 * from(select coalesce(object_name(s2.objectid),'ad-hoc') as procname,   execution_count,s2.objectid,     (select top 1 substring(s2.text,statement_start_offset / 2+1 ,       ( (case when statement_end_offset = -1   then (len(convert(nvarchar(max),s2.text)) * 2) else statement_end_offset end)- statement_start_offset) / 2+1)) as sql_statement,        last_execution_time from sys.dm_exec_query_stats as s1 cross apply sys.dm_exec_sql_text(sql_handle) as s2 ) x where sql_statement not like 'select top 50 * from(select %' order by last_execution_time desc 	0.00202511363801269
3579695	39399	selecting data between a certain date range where date range is a varchar	select rowid  from batchinfo  where convert(date, reporttime, 103)     between cast('2010-07-01' as datetime) and cast('2010-07-31' as datetime) 	0
3579844	26389	sql server: finding the bad data	select * from mytable where isdate(mycolumn) != 1 	0.172143862294437
3580357	40750	count of a column with different rows	select table2.jobcategoryid, table2.jobcategoryname, count(table2.jobcategoryid) from table1 inner join table2 on table1.jobcategoryid = table2.jobcategoryid where table1.contactid > 0 group by table2.jobcategoryid, table2.jobcategoryname 	0.000211674524988739
3580610	30830	how to return "row number" of first occurrence, sql?	select count(*) from tbl where letter < 'f' 	0
3580871	17886	sql query for most recent date and constrained by another column	select patient_id   from pat_procedure p   inner join (select procedure_id, max(procedure_date) as last_date               from pat_procedure               where procedure_id in (45, 66, 78)               group by procedure_id) mx   on p.procedure_id = mx.procedure_id and p.procedure_date = mx.last_date 	4.72588273023844e-05
3581554	17690	sql query on rownum	select instmax from    (select instmax ,rownum r    from      ( select instmax from pswlinstmax order by instmax desc nulls last      )   ) where r = 2; 	0.412838836557456
3581597	37123	mysql correctly compare 2 datetimes?	select * from `table`  where `new` != '1'  and `time` >= '2010-08-27 22:04:37'  and  (`name` like '%apple%'       or `name2` like '%apple%') 	0.0383816316768792
3582614	2941	how to insert some formula in mysql?	select     name,     black,     yellow,     white,     qty_job     (sum(black) + sum(yellow) + sum(white)*0.4) / qty_job as total from counter group by name; 	0.262028838308979
3583118	800	sql : return value in required format	select reverse(   insert(     insert(reverse(1234567890), 5, 0, '.'),       8, 0, '.')) as formatted; + | formatted    | + | 1234.56.7890 | + 	0.0371524641793664
3584028	26381	how to calc ranges in oracle	select * from table, (select level as id from dual connect by level <= (select max(end)      from table)) t  where  t.id between rr.start and rr.end  order by map, start, id 	0.0470543062077236
3584132	12106	finding the database name from tsql script	select db_name() 	0.00374599636194581
3585837	2231	single mysql query which checks another table for rows	select distinct username from users left outer join payments on users.userid = payments.userid where paymentcompleted is null or paymentcompleted != 1 	6.23541786837801e-05
3587941	2652	mysql query to use data from 2 tables	select username  from users inner join payments on (users.userid = payments.userid) where paymentstatus = 1 and groupid = 5 and timecompleted < 10 group by users.userid; 	0.0109039485111926
3588626	41026	char function on sql server is returning different values on different servers	select nchar(193) 	0.00866927128657881
3589461	7110	how can i combine join these two tables?	select t1.jobcategoryid, t1.jobcategoryname, t1.availablecategories, t2.allocatedjobs     from      (select job_category.jobcategoryid as jobcategoryid, job_category.jobcategoryname as jobcategoryname, count(job_position.jobcategoryid)  as availablecategories from job_position  right outer join job_category on job_position.jobcategoryid = job_category.jobcategoryid group by job_category.jobcategoryid, job_category.jobcategoryname) as t1  inner join  ((select job_category.jobcategoryid as  t2jobcategoryid, job_category.jobcategoryname as t2jobcategoryname, count(job_position.contactid) as allocatedjobs from job_position  right outer join job_category on job_position.jobcategoryid = job_category.jobcategoryid where job_position.contactid > 0 group by job_category.jobcategoryid, job_category.jobcategoryname)) as t2 on t1.jobcategoryid = t2.t2jobcategoryid 	0.0238756963792821
3589563	19371	getting the page a picture is on using its id	select count(*) where id < $id 	0.000446895850344426
3589956	23011	sql update query - can you not specify the column names?	select  column_name  from    information_schema.columns c  where   table_name = 'mytable' 	0.0587836429522925
3591203	22990	mysql: select on a table with tablename from a recordset	select   t.template_table_name from     templates    t,           documents    d where    d.template_id = t.template_id and      d.document_id = @param_document_id 	0.00116555987996368
3594663	33078	mysql select query	select * from table1 where id='$id_var'   union all   select * from table2 where id='$id_var' 	0.387336905290878
3594825	39327	urgent! need help selecting ids from a table if 2 conditions in other tables match	select    * from    tblquestions q where    exists (select *       from           tblanswers a           join           tblfeedback f on a.submission_id = f.submission_id       where           q.q_id = a.q_id and f.module_id = @moduleid) 	0
3599185	20875	how to drop all triggers in a firebird 1.5 database	select 'drop trigger ' || rdb$trigger_name || ';' from rdb$triggers   where (rdb$system_flag = 0 or rdb$system_flag is null) 	0.00233995470167265
3599548	18238	fetch only n rows at a time (mysql)	select * from table limit 0,20 	0
3601134	33775	return multiple rows on a single record	select   (select id from table x where x.something = 123) as row1id,  (select id from table x where x.something = 456) as row2id,  (select id from table x where x.something = 789) as row3id 	5.38765119783378e-05
3601140	32376	how can i use the table name in a column alias in access sql?	select e.id as 'examid',      e.name as 'examname'  from exam e 	0.172341907048044
3601257	5077	what is the best way to create all pairs of objects of two, from a huge list of objects (say a million strings)?	select t1.stringvalue, t2.stringvalue from stringstable t1     inner join stringstable t2         on t1.stringvalue <> t2.stringvalue 	0
3601258	24481	mysql custom order	select *  from your_table  order by (parent != 0) desc, parent asc; 	0.640998270348128
3601331	16504	sql if then for concatenating fields	select if(min_price=max_price,min_price,concat(min_price,' - ',max_price)) as price from your_table; 	0.022345538751064
3601365	27368	how to put flag on a column?	select case when isnull(price, 0) <= 0 then 0 else 1 end as validprice 	0.00404556916816209
3604568	14731	move one row to the end of a result set in mysql	select * from tablename order by symbol = 'cash', timestamp 	0
3604845	2461	how do i do 2 unique left joins on the same table cell?	select clientstable.clientname, n1.note as clientnote, n2.note as staffnote from clientstable  left join notes as n1 on clienttable.clientnotesid = n1.noteid left join notes as n2 on clienttable.staffnoteid = n2.noteid 	0.000182266940549783
3605010	7233	getting extra data from the join table	select p.product_id  ,        p.product_name,        pc.quantity from   `products` p        join `categorizations` pc        on     p.id = pc.`product_id`        join `categories` c        on     c.id = pc.category_id where  c.code      = 'something' 	0.0032804654793887
3605032	16912	creating date/time ranges with oracle timestamp with timezone datatype	select column_name, my_timestamp    from table_name    where my_timestamp >= sysdate - interval '3600' second   order by my_timestamp 	0.0592791878447258
3606229	21279	show and mark some records on top	select   users.*   , hr_orders.position_label   , hr_orders.is_boss   , deps.label as dep_label           , users.id  as show_on_top   from  where   and users.id in (?,?,?) 	0.000119817013420888
3606623	8810	substring to return all values after delimiter	select substring('abc@hotmail.com,xyz@yahoo.com,pqr@company.com',    instr('abc@hotmail.com,xyz@yahoo.com,pqr@company.com', ',') + 1) as first; 	0.000725430480579132
3606907	33320	sql query: order by length of characters?	select * from table order by char_length(field) 	0.158672011922123
3607062	22319	mysql sort question	select * from table order by length(column) - length(replace(column, ' ', '')) 	0.68447695315373
3607840	10978	mysql related articles	select distinct p . *  from projects p join projects_to_tags pt on pt.project_id = p.num join projects_to_tags x on x.tag_id = pt.tag_id and x.project_id = x  	0.0107243053963256
3608042	33844	how to remove matching rows from mysql join result and show non-matching rows?	select * from table1 t1 where not exists (select 1 from table2 t2                   where t1.pub_id = t2.pub_id                 and t1.post_id = t2.post_id) union all select * from table2 t1 where not exists (select 1 from table1 t2                   where t1.pub_id = t2.pub_id                 and t1.post_id = t2.post_id) 	0
3608880	13854	select * from table where field in (select id from table order by field2)	select ssi.id from     sub_subcategories_id ssi         inner join     subcategories_id si         on             ssi.subcategories_id = si.id         inner join     categories c         on            si.categories_id = c.id where     c.id = 'x' order by     c.position,     si.position,     ssi.position 	4.75903340051703e-05
3609222	22204	preventing overlapping appointment times	select * from appointments where  (time_from <= $from and time_to >= $to) or (time_from <= $from and $from < time_to and time_to <= $to) or (time_from >= $from and time_to >= $to and $to > time_from) or (time_from > $from and time_to < $to) 	0.00837245193025949
3609526	29344	need to connect to two different db from sqlplus	select *   from table_ondb2  where column_on_db2     in (select column_on_db1 from table_ondb1@db_link_name);                                              ^^^^^^^^^^^^^ 	0.00938000390783754
3609671	9138	sql - select next date query	select     mytable.id,     mytable.date,     (         select             min(mytablemin.date)         from mytable as mytablemin         where mytablemin.date > mytable.date             and mytable.id = mytablemin.id     ) as nextdate from mytable 	0.014987716496171
3610932	11404	sql 2005 get latest entry from a group of data	select clientid, body, max(datemodified) from activity group by clientid, body 	0
3611173	36571	query sql and get result for foreign key's value(not id)	select images.categoryid, category.category from images inner join category on category.categoryid = images.categoryid where image = exampleimage 	0.000242656256392164
3611229	5334	php/mysql join 2 tables	select t2.pdffile from t1 inner join t2  on t1.property = t2.documentcategory where t1.userid = $userid 	0.064858418535876
3611542	19492	sql - columns for different categories	select t.student,          max(case when t.test = 't1' then t.grade end) as t1,          max(case when t.test = 't2' then t.grade end) as t2,          max(case when t.test = 't3' then t.grade end) as t3     from table t group by t.student 	0.00207546394266468
3612269	4453	mysql query to count non-null values in a single row	select id, name, score_1, score_2, score_3 from table1 order by (score_1 = 0) + (score_2 = 0) + (score_3 = 0) 	0.000274842842923265
3613077	32974	date difference in mysql	select * from table where login_time >= subdate(curdate(),interval 60 day) 	0.0221665900854411
3613347	24484	sql query: how to count frequency over a many-to-many relation?	select t.name, count(*) as usecount from tag as t     join blogpost_tag as bpt         on bpt.tag_id = t.id     join blogpost as bp         on bp.id = bpt.blogpost_id where bp.title like '...' group by t.name 	0.0783292725924099
3613447	13181	how to search content of a routine/(sp-trigger-function)	select      object_name(object_id) from     sys.sql_modules where     definition like '%' + 'whatiwant' + '%' 	0.0331902540088946
3614631	33012	create columns from transaction type in table	select t.job,          sum(case when t.transaction_type = 'transtype1' then t.amount else null end) as transtype1amountsum,          sum(case when t.transaction_type = 'transtype2' then t.amount else null end) as transtype2amountsum,          sum(case when t.transaction_type = 'transtype3' then t.amount else null end) as transtype3amountsum     from jct_current_transaction t    where transaction_date between {?start date}                                and {?end date} group by t.job 	0.00101168500275665
3615266	22354	convert rows to columns allowing duplicates	select id, name, event as 'input event',         (select min(o.event)          from events o          where o.type = 'output' and                i.id = o.id and                i.name = o.name and                i.event < o.event) as 'output event'  from events i where i.type = 'input' group by id, name, event 	0.00195056869565023
3616210	20655	how to use max function on another column from a select	select      *  from  (select contactname, productname, count([order details].quantity) as numoftimecustomer     from orders, [order details], products, customers     where [order details].orderid = orders.orderid     and [order details].productid = products.productid     and orders.customerid = customers.customerid     group by contactname, productname)customer where customer.num = (select max(num) from (select contactname, productname, count([order details].quantity) as numoftimecustomer     from orders, [order details], products, customers     where [order details].orderid = orders.orderid     and [order details].productid = products.productid     and orders.customerid = customers.customerid     group by contactname, productname)customer2  where customer2.name = customer.name) 	0.00154712065416235
3616798	36555	sql change query to show orphans	select ...        isnull(tblproductcats.catname,'orphan') as  catname   ,        ... from   tblproducts        left outer join tblproductcats        on     tblproducts.categoryid = tblproductcats.id 	0.0953536342850167
3617003	41242	invalid column name, on select-statement created columns	select q.* from ( select     u.userid,    cast((case when exists(select * from tbluser u where u.disabled=1) then 1 else 0 end) as bit) as avar,  from tbluser u )q  where q.avar = 1 	0.0199746617663445
3618256	35217	how to send record(which is a weblink) from a table to the value of the variable in ssis package and send that weblink through an email?	select col1, col2 from table1 where <your condition to retrieve one row> 	0
3619542	39001	date table/dimension querying and indexes	select foo.orderdate    ,dte.fiscalyearname    ,dte.fiscalperiod    ,dte.fiscalyearperiod    ,dte.fiscalyearweekname    ,dte.fiscalweekname      from sometable foo   inner join     datedatabase.dbo.mydatetable dte   on foo.forderdate >= dte.date and foo.forderdate < dateadd(dd, 1, dte.date) 	0.437712105052365
3621440	20994	mysql - how to get exact difference of hours between two dates	select time_to_sec(timediff('2010-09-01 03:00:00', '2010-09-01 00:10:00' )) / 3600; + | time_to_sec(timediff('2010-09-01 03:00:00', '2010-09-01 00:10:00' )) / 3600 | + |                                                                      2.8333 |  + 	0
3623145	11873	split functionality in mysql	select substring_index(empname, ',', -1) as first_name,         substring_index(empname, ',', 1) as last_name    from table 	0.404347579603108
3623404	26757	filtering table and then joining results	select *    from  collections a    join users b on a.mid = b.user_id                and a.mid = 'value of $id' order by b.user_id 	0.0160296206265215
3625588	34155	tool for finding the database bottlenecks in sql server	select user_seeks * avg_total_user_cost * (avg_user_impact * 0.01) as index_advantage, migs.last_user_seek, mid.statement as 'database.schema.table',     mid.equality_columns, mid.inequality_columns, mid.included_columns,     migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact     from sys.dm_db_missing_index_group_stats as migs with (nolock)     inner join sys.dm_db_missing_index_groups as mig with (nolock)     on migs.group_handle = mig.index_group_handle     inner join sys.dm_db_missing_index_details as mid with (nolock)     on mig.index_handle = mid.index_handle     order by index_advantage desc; 	0.0261415507314183
3626645	30017	determining if mysql table index exists before creating	select index_name from information_schema.statistics where `table_catalog` = 'def' and `table_schema` = database() and `table_name` = thetable and `index_name` = theindexname 	0.243237810521201
3626991	6685	top ten count using mysql query	select referrersource,count(referrersource) as counts   from request_events    where referrersource!=''   and landingpage_collectionid=1   group by referrersource  order by 2 	0.0649192211731068
3628110	17585	mysql - multiple select and like method	select distinct wp_postmeta.meta_key, wp_postmeta.meta_value, wp_posts.id, wp_posts.guid, wp_postmeta.post_id, wp_posts.post_title from wp_postmeta inner join wp_posts on wp_postmeta.post_id=wp_posts.id where wp_postmeta.post_id in (     select post_id from wp_postmeta where str_to_date(meta_value, '%y-%m-%d') >= 2010-03-02' and post_id in (select post_id from wp_postmeta where meta_value = 'something') ); 	0.796381156863129
3628626	14270	getting unique values from a mysql table between a date range	select count( distinct( user_ip ) )  from table  where timestamp between y and z 	0
3630965	12351	sum until certain point from each group - mysql	select @i:=0, @type:='' ; select       id, type, x, y from (     select           id, type, x, y         , sqrt( pow(abs(5 - x),2) + pow(abs(3 - y),2) ) as distance         , if( type=@type, @i:=@i+1, @i:=0             ) as rank         , if( type=@type, @type,    @type:=type       ) as new_type     from         fruit_trees     order by           type         , distance     ) x where     rank < 3 	0
3631886	1360	sql 2005 - two tables join on some id,	select a.accountid     ,        a.name          ,        a.income        ,        a.primarycontact,        c.street        ,        c.city          ,        c.state         ,        c.country from   account a        join contact c        on     a.accountid      = c.parentaccountid        and    a.primarycontact = c.name 	0.00671359721326582
3632376	9922	finding rows with the maximum	select p.*   from palettes as p join        (select name, max("count") as max_count           from palette          group by name) as mc        on mc.name = p.name and p."count" = mc.max_count; 	0.000229555432128471
3633496	37564	sql server 2005/2008 finding nth highest salary	select salary from (     select dense_rank() over (order by salary desc) as rank, salary     from employee ) t2 where rank=2 	0.000128465837751525
3634300	36927	database design: where to place the total amount fields	select i.*, sum(wi.amount) total from invoice i join workitem wi on i.invoice_id = wi.invoice_id group by i.invoice_id 	0.000177031071666332
3634479	23835	select according to string ending	select to_number(substr(objname,instr(objname,'.',-1)+1,length(objname))) as last_version, objname from my_table order by last_version 	0.00903709697749664
3634542	5676	sqlite select * for last 7 days	select * from session where stop_time > (select datetime('now', '-7 day')) 	0
3635262	9405	mysql :how to select two different column values from a single table using two different values of another table	select table2.c, table2.d from table2 join table1 on table2.some_common_field = table1.other_common_field where (table1.a = xxx) and (table1.b = yyy) 	0
3636313	21606	select a string comparison as a boolean in tsql	select name, case when status = 'current' then 1 else 0 end as isvalid from items 	0.401041994159343
3637356	10271	trying to make a query that takes two tables into account	select lt.user, lt.team, lt.league,      l.game, l.type, l.name from tbl_leaguetables lt inner join tbl_leagues l on lt.league = l.id where l.format = 'yes' 	0.00999331774942609
3638551	10518	how to generate a tree view from this result set based on tree traversal algorithm?	select c . * , count( p.id ) as depth from `categories` c cross join categories p where ( c.lft between p.lft and p.rht ) and c.root_id = p.root_id group by c.id order by c.root_id, c.lft 	0.000452325810574336
3640729	15220	counting data and grouping by week in mysql	select   a.line,   week1.1stweek,   week2.2ndweek,   ...   ifnull(week1.1stweek,0) + ifnull(week2.2ndweek,0) + .... as total from    inspection_report as a left join (   select line, (sum(s) + sum(a) + sum(b)*0.4 + sum(c)*0.1)/count(serial_number) as 1stweek from inspection_report where day(inspection_datetime) between 1 and 7 group by line, week, year) as week1 using (line) left join (   select line, (sum(s) + sum(a) + sum(b)*0.4 + sum(c)*0.1)/count(serial_number) as 2ndweek from inspection_report where day(inspection_datetime) between 8 and 14 group by line, week, year) as week2 using (line) ... group by line 	0.00110671216810848
3649009	23519	combining union results	select count(emailid) as viewsthatmonth,           day(entry_date) as day,           month(entry_date) as month,           year(entry_date) as year from( select emailid, record_entry as entry_date      from email_views    where emailid = 110197 union all    select emailid, entry_date      from dbo.tblonlineemail_views    where emailid = 110197 ) as t group by day(entry_date), month(entry_date), year(entry_date) order by 4, 3, 2 	0.258701247385218
3650207	18348	a system that record and count user logged in	select time, sum(counter)  from youtlogtable  group by time 	0.000820940897870305
3650320	28862	convert from bigint to datetime value	select dateadd(s, convert(bigint, 1283174502729) / 1000, convert(datetime, '1-1-1970 00:00:00')) 	0.00467536503501425
3651985	26497	compare dates in mysql 	select * from players where      us_reg_date between '2000-07-05' and     date_add('2011-11-10',interval 1 day) 	0.0461695304410932
3652099	21563	how do i select records less than 1 year old	select * from mytable where mydate > dateadd(year, -1, getdate()) 	0.000210281526529183
3657540	1010	tsql searching rows in another table	select      pilot  from      pilotgroup pg      inner join     southoperation sop on (pg.plane = sop.plane) group by      pilot having      count(pg.plane) = (select count(*) from southoperation) 	0.00190130551291599
3660422	39537	most performant alternative to select count(*) using pdo and mysql	select count(*) from image where user_id=5 	0.205343208678455
3660606	3848	calculate rank in highscore from 2 tables	select     user_id,     score,     rank from (     select         tp.user_id,         (tp.correct * 10) + (count(tq.sender_id) * 30) as score,         @rank:=@rank + 1 as rank     from         trivia_players tp     left outer join trivia_questions tq on         tq.sender_id = tp.user_id     group by         tp.user_id,         tp.correct     order by         score desc ) as sq where     sq.user_id = $user_id 	0.000677622572296023
3662551	24329	performing select count across two tables sql	select c.*, cc.relativecount from client c inner join (     select clientid, count(*) as relativecount       from client_relative     group by clientid  ) cc on c.clientid = cc.clientid 	0.0101840026900675
3662685	27006	how to filter mysql duplicated id rows and retrieve the one with latest timestamp?	select m.* from (     select id, max(date) as maxdate     from mytable     group by id ) mm inner join mytable m on mm.id = m.id and mm.maxdate = m.date 	0
3662835	464	select multiple columns as a result of a case expression	select case      when p.residency_status = 0 then         dbo.fn_formataddress(r1.prm_name, p.py_hospital, p.py_address1, p.py_city, p.pyear_state)     when p.residency_status = 1 then         dbo.fn_formataddress(r1.prm_name, p.respgm_hospital, p.respgm_address1, p.respgm_city, p.respgm_state)     when p.residency_status = 2 then         dbo.fn_formataddress(r1.prm_name, p.curr_hospital, p.curr_address1, curr.city, p.curr_state) end from table p 	0.0816883107020835
3663743	22183	sql sub queries	select m.id,         m.subject,        m.date,        u.username   from mail m   join users u on u.id = m.id               and u.id = {0}  where m.date > some_date 	0.745584286849545
3664823	36584	it is possible to fetch with a single sql the minimum (maximum) row in the table when the compared value is combined of two separate fields?	select top 1      field1, field2,      dateadd(ms, millisecondsfield, datewithoutmillisecondsfield) timestamp from table order by timestamp desc 	0
3664975	18211	date range in pl/sql	select * from mytable   where created_date between v_fromdate                          and nvl(v_todate, to_date('31.12.9999','dd.mm.yyyy')); 	0.0133953895583539
3665223	27676	mysql time stamp queries	select * from table where date >= '2010-01-31' select * from table where date >= '2010-01-31 12:01:01' 	0.0437626127617576
3665507	15562	count of total groups required. group by cluased query in mysql	select count(*) from  ( select * from web_details  where redirected = false group by web_id ) as temp;enter code here 	0.00303940821835943
3665549	35919	how to get unique result in mysql	select name, max(marks) marks  from table  group by name 	0.00219544131566285
3665649	26817	querying multiple mysql tables simultaneously	select * from one join two on one.uid = two.uid join three on one.uid = three.uid where one.uid='1234567' 	0.0332639092342354
3665963	40924	how do i limit the result of a subquery in mysql?	select * from product p left join (     select product_id, min(price)     from supplierprices sp     group by product_id ) x on (p.product_id = x.product_id) 	0.0859733274732528
3666039	5547	how to count column values differently in a view?	select     count(*) as total,     sum(case when observation = 'positive' then 1 else 0 end) as positive,     sum(case when observation = 'negative' then 1 else 0 end) as negative,     someothercolumn from your_view group by someothercolumn 	0.00736234488016763
3666090	30118	database missing ! finding the root cause	select *  from fn_trace_gettable ('c:\program files\microsoft sql server\mssql.1\mssql\log\log_19.trc', default) 	0.0714459328650337
3666988	22666	how to write a sql query to figure out if a value falls within a range	select id   from tablea  where frompos <= x    and (topos >= x or topos is null); 	0.00611731573204489
3667043	5031	subdivide timestamps into 3 timeslots	select      case         when datepart(hh, dt) >= 5 and datepart(hh, dt) < 13 then 1         when datepart(hh, dt) >= 13 and datepart(hh, dt) < 21 then 2         when datepart(hh, dt) < 5 or datepart(hh, dt) >= 21 then 3     end from mytable 	0.0050505228814597
3667241	13022	getting more details out of a sql subquery	select ps.*  from periodscore ps inner join (     select periodid, itemid      from periodscore        group by periodid, itemid      having count(*) > 1 ) psm on ps.periodid = psm.periodid and ps.itemid = psm.itemid 	0.101707187447842
3667780	32680	tsql finding incomplete courses	select distinct a.sid, a.name, b.coursecompleted as `course not completed` from studentdetails a, (select distinct coursecompleted from studentdetails) b where not exists (select 1 from studentdetails where sid = a.sid and coursecompleted = b.coursecompleted) order by a.sid 	0.452187371605178
3668235	33143	select max date row from results	select     a.tp_no as clientnum,     c.name as company,     a.state as state,     max(b.eff_date) as date from "pr_tsuta" as a  left join cl_suta as b on a.tp_no = b.loc_no left join cl_mast as c on b.loc_no = c.loc_no where c.yn_17 = 'a' and a.er_rate != b.er_rate  group by a.tp_no, c.name, a.state 	0.000335955449477666
3668499	26382	sql: get a random entry iff condition is false	select first 1 t1.*  from table t1    left join table t2       on t2.pk = t1.pk          and t2.cond=1 order by case when t2.cond = 1                then 0 else rand() end 	0.00589060387310488
3669726	30370	left join with empty results when no match is found	select baskets.*, produce.fruitname as fruit, produce.veggiename as veggies  from baskets left join (select basketid, name as fruitname, null as veggiename            from fruit            union            select basketid, null, name            from veggies) produce       on baskets.id = produce.basketid where baskets.id = 2; 	0.690579620184609
3669735	26372	how do i know if a date is within the certain period	select  userid from    mytable where   '2010-09-09' between startdate and coalesce(enddate, startdate) 	0.000147276761679224
3670469	4838	query to get the max of the max records	select t.patient_id, max(t.visit_id)     from (select t.patient_id, max(t.visit_date) maxdate           from table t          group by t.patient_id) tt, table t where t.patient_id = tt.patient_id   and t.visit_date = tt.maxdate group by t.patient_id 	0
3671761	13842	how to search for a substring in sqlite?	select id from sometable where name like '%omm%' 	0.273635641156027
3673218	34738	counting subqueries	select     thistable.id,     title,     price,     other_count from (     select         id,         count(*) as other_count     from othertable     group by id ) othertablecount     inner join thistable         on thistable.id = othertable.id 	0.399260840292048
3673416	4992	counting subqueries	select tt.id, tt.title, count(ot.id) as count from thistable tt inner join othertable ot on ot.id = tt.id group by tt.id, tt.title 	0.399260840292048
3679148	6711	sql query to find sum of all rows and count of duplicates	select 'year ' + cast(sub.theyear as varchar(4)), count(sub.c),  (select sum(qtotal) from mytable where year(tdatetime)=sub.theyear) as total from (select year(tdatetime) as theyear, count(tdatetime) as c from mytable  group by tdatetime, year(tdatetime) having count(tdatetime)>2) as sub 	0
3679361	34973	how to join two tables from separate db's with timestamps that differ slightly with sql	select * from db1.dataset, db2.dataset where extract(year from db1.dataset.timestamp) = extract(year from db2.dataset.timestamp) and extract(day from db1.dataset.timestamp) = extract(day from db2.dataset.timestamp) and extract(month from db1.dataset.timestamp) = extract(month from db2.dataset.timestamp) and extract(hour from db1.dataset.timestamp) = extract(hour from db2.dataset.timestamp) and extract(minute from db1.dataset.timestamp) <= extract(minute from db2.dataset.timestamp)+5 and extract(minute from db1.dataset.timestamp) >= extract(minute from db2.dataset.timestamp)- 5 	0.000335786529492769
3679777	26737	how to have count on one to many relationship	select r.id, count(a.id) as count from reportertbl r left outer join attachmenttbl a on r.id = a.id group by r.id 	0.000767736252585847
3680660	22899	exclude results from a mysql union query	select a.* from  (    select ... from table_a    union    select ... from table_b )a  where a.x not in (...)  	0.0222511138909052
3681345	3500	mysql: fetching rows added last hour	select count(*) as cnt from  log where date >= date_sub(now(),interval 1 hour); 	0
3682956	27358	t-sql how to select rows without duplicate values from one column?	select max(id) as [id], id_proj_csr from my_table group by id_proj_csr 	0
3683117	3679	how to get total number of products in virtuemart?	select o.product_id,        sum(o.product_quantity) as total_sold   from jos_vm_order_item o  group by o.product_id 	0
3684409	26932	mysql sum query	select sum(distinct src.qnty) as qnty from tbl2 as src inner join tbl1 as pub   on src.xid=pub.xid inner join tbl2 as fno   on pub.xid=fno.xid where pub.pub=1   and src.ttype='a'   and fno.fno=0 	0.344013761484802
3685124	26179	how can i find all columns that contain a string and null those values	select 'update [' + s.name + '].[' + t.name + '] set [' +  c.name + '] = null'     from sys.columns c         inner join sys.tables t             on c.object_id = t.object_id         inner join sys.schemas s             on t.schema_id = s.schema_id     where c.name like '%qualifiers%'         and t.type = 'u' 	0
3686085	8919	how to find date difference when dates are places in different rows in same table?	select t.itemid,         t.versionno,         t.createddate, (           select top 1            createddate            from versions v            where v.itemid=t.itemid            and v.versionno<t.versionno            order by versionno desc) as lastdate,         datediff("h",[lastdate],[createddate]) as diffhrs,        datediff("d",[lastdate],[createddate]) as diffdays from versions t 	0
3687732	11768	mysql sum one field based on a second 'common' field	select repaymentday, sum(monthlyrepaymentamount) as monthlyrepaymentamount from yourtable group by repaymentday order by repaymentday 	0
3687809	33406	in a single mysql query, select multiple rows from one table, each containing multiple rows from a linking table	select     username,     group_concat(site order by site separator ', ') as sites from user_sites join users on user_sites.user_id = users.userid join sites on user_sites.site_id = sites.siteid group by username 	0
3689036	27143	mysql: limit a query to 10 rows where every index has 5 tags	select x.id,            x.house,            x.country,            x.id_tag       from (select h.id,                    h.house,                    h.country,                    ht.id_tag,                    case                       when @id = h.id then @rownum := @rownum + 1                      else @rownum := 1                    end as rank,                    @id := h.id,                    @house_count := @house_count + 1 as house_count               from house h          left join houses_tags ht on ht.id_house = h.id               join (select @rownum := 0, @id := -1, @house_count := 0) r           order by h.id, ht.id_tag) x    where x.house_count <= 10      and x.rank <= 4         order by x.id, x.id_tag 	0
3689190	4036	database table names: plural or singular	select idpost, name from posts inner join users on poster = iduser 	0.0215735053676286
3690745	34012	sql for a movie database search system	select actor.name from actor join movie_actor on movie_actor.actorid = actor.id where movie_actor.movieid = 153 	0.592569238163935
3695347	9149	mysql sum query	select sum(quantity) as total from   tbl1 where  pub=1 and    exists        (select *        from    tbl2        where   tbl2.ttype = 'a'        and     tbl2.fno   = 0        and     tbl1.xid   = tbl2.xid        ) 	0.344013761484802
3695711	7400	how to get a highest field value in a table in mysql?	select * from buddies where birthdate = (   select max(birthdate) from buddies ) limit 1; 	0
3699415	20956	sql stored procedure - count specific not null columns in a row	select case when data is null then 1 else 0 end +  case when structure is null then 1 else 0 end as null_columns_amount  from yourtable  where loadid = ? 	0.00846754727773534
3700806	20587	mysql select min for all time, but only return if between dates	select case count(*) when 0 then 'yes' else 'no' end as [wasfirsttransinthisperiod?] from (           select bb_member.member_id as [member_id], min(bb_transactions.trans_tran_date) as temp_first_time          from bb_business               right join bb_transactions on bb_transactions.trans_store_id = bb_business.store_id          left join bb_member on bb_member.member_id = bb_transactions.trans_member_id          where bb_business.id = '5651'          group by bb_member.member_id     ) t where t.temp_first_time between '2010-08-01' and '2010-09-13' order by t.member_id desc 	0
3702036	27425	modifying the group by column to get the newest result on top	select id, name, group_id  where id  in (select max(id) from test group by group_id)  order by id desc; 	6.7732929177445e-05
3702378	3373	pick column with default value or column with user defined value if not null?	select coalesce(the_field, "this literal") from your_table 	0.000374101975178639
3706074	38245	mysql count items in category	select     categories.field1,     categories.field2,     {etc.}     count(links.id) from categories left join links     on categories.id = links.category_id group by     categories.field1,     categories.field2,     {etc.} 	0.00226598213690984
3706145	22418	mysql - displaying results from a sub-query in a single row	select p.name,          p.desc,          group_concat(c.display_name) as categories     from product p     join product_category pc on pc.product_id = p.product_id     join category c on c.category_id = pc.category_id group by p.name, p.desc 	0.00130772827718331
3709463	8768	ssis merge join more than 2 data sets	select     custid,     max(case when fieldid = 3 then varchar_val else null end) as 'firstname',     max(case when fieldid = 5 then int_val else null end) as 'accountnumber',     max(case when fieldid = 1 then int_val else null end) as 'age',     max(case when fieldid = 4 then date_val else null end) as 'joindate',     max(case when fieldid = 2 then dec_val else null end) as 'balance' from     dbo.stagingtable group by     custid 	0.0127515093848535
3709560	22637	mysql join three tables	select s.name "student", c.name "course" from student s, bridge b, course c where b.sid = s.sid and b.cid = c.cid 	0.207671777364806
3710846	31539	sql join and aggregate several tables	select s.screenid, s.description , case max(case rf.status when 'e' then 2 when 'v' then 1 else 0 end)     when 2 then 'e'     when 1 then 'v'     else 'n' end as status from user_roles ur join role_functions rf on rf.roleid = ur.roleid join function_screens fs on fs.functionid = rf.functionid join screens s on s.screenid = fs.screenid where ur.userid = :theuser group by s.screenid, s.description order by s.screenid 	0.461539433024002
3711111	34143	t-sql union query to return items with highest and lowest rating from the same table	select * from (select top 5 *, 'bottom five' as ranking from call order by id ) a union all select * from (select top 5 *, 'top five' as ranking from call order by id desc ) b 	0
3711626	6925	select null as testdate into #temp_table	select id, cast(null as datetime) as testdate into #temp_table 	0.184769694517264
3711823	7002	select three rows when two of them need to be unique (sql)	select domain_name, index_path, min(collection_name) collection_name from tablenamehere group by domain_name, index_path; 	0.000423253148189209
3713107	34521	split column to multiple rows	select number, substr( site,  instr(','||site,',',1,seq), instr(','||site||',',',',1,seq+1) - instr(','||site,',',1,seq)-1)  site from sitetable,(select level seq from dual connect by level <= 100) seqgen where instr(','||site,',',1,seq) > 0 	0.000903708531514921
3713720	33732	how to pick table in query based on subtype?	select ... from orders o join transactions t on t.orders_id = o.orders_id left outer join site_orders so    on so.orders_id = o.orders_id and o.orders_type = 's'  left outer join product_orders po    on po.orders_id = o.orders_id and o.orders_type = 'p' 	0.00103780089255527
3713962	11785	distinct mixing rows values?	select wp.owner_id,        wp.date,        wp.title,        wp.revision,        u.name as updater   from wiki_pages wp   join users u on u.id = wp.owner_id   join (select t.title,                max(t.revision) as max_rev           from wiki_pages t       group by t.title) x on x.title = wp.title                          and x.max_rev = wp.revision 	0.0171520917942053
3714390	37748	how to get intro record from each group	select min(id) id, group, name from table1 group by group order by group 	0
3716240	27667	how do i write the following mysql query?	select ida, idb, stringvalue from table where ida = 'xyz' and idb = 12; 	0.715880619246308
3716423	7585	what's the best field type and data usage to accelerate searches?	select * from table where 'deleted' = 0 	0.592827352678861
3716451	38386	sql transform table query	select color, size from  ( select distinct  propertyvalue as color from yourtable where propertyname = 'color' ) t1 cross join  ( select distinct  propertyvalue as size from yourtable where propertyname = 'size' ) t2 	0.245619097287607
3716641	22151	select a distinct list of substrings from one of the fields in a mysql table	select distinct `match` from (select mid(title,instr(title,'[') + 1,instr(title,']') - instr(title,'[') -1) as 'new_title' from issues u where instr(title,'[') > 0 and instr(title,']') > instr((title),'[')) tbl 	0
3717714	6316	using single query to retrieve multivalued attribute by joining two tables without causing duplication of fields in mysql	select c.applicationno,         max(c.name) name,        max(p.phoneno) phoneno1,        case             when max(p.phoneno) = min(p.phoneno) then null             else min(p.phoneno)         end phoneno2 from client c left join phoneno p on c.applicationno = p.applicationno group by c.applicationno 	0
3718425	48	sql query to find temp tables in db	select name from tempdb.sys.tables 	0.0386263591004884
3719238	23483	sql except top 10 records in desc order	select comvid, vid, mid, ucomment, udateadded, memberid, username, avatar  from table.micomments  join table.mbrprofile2 on mid = memberid   where vid = @id and comvid not in (    select top 10 comvid    from table.micomments     join table.mbrprofile2 on mid = memberid      where vid = @id order by udateadded desc)   order by udateadded desc 	0.00112502930281846
3720958	3705	sqlce: find next available date	select dateadd(d, 1, min(t1.mydatefield)) from mytable t1 left join mytable t2 on datediff(d, t1.mydatefield, t2.mydatefield)=1 where t1.mydatefield>=getdate() and t2.mydatefield is null 	0.00016227823199903
3721646	36907	how to do outer join on >2 tables (oracle)	select a.a,                 b.b,                 c.c,                 d.d,                 e.e            from a full outer join b on b.a = a.a full outer join c on c.b = b.b full outer join f on f.c = c.c full outer join d on d.d = f.d full outer join e on e.e = f.e 	0.348056340611315
3723393	35652	cannot user "select top @count ..."	select top (@count)           t1.id as id,           t1.name as name,           t2.type as type     from sampletable1 as t1 with (noloack)     join sampletable2 as t2 with (noloack) on t2.id = t1.t2.id order by t1.name 	0.183639393395274
3724519	7887	is there a better way to extract the time of day?	select     cast(colname as time) from     tablename; 	0.000582643610606345
3725178	1843	mysql query help : show field appearance count and appearance percentage	select field, count(field) ,  count(field) / (select count(*) from table) as percentage from table  group by field; 	0.0167921560746843
3727629	21811	how do i find which tables have foreign keys on my table?	select dc.constraint_name, dc.constraint_type, dc.owner, dc.table_name from dba_cons_columns dcc  join dba_constraints dc on (dcc.constraint_name = dc.r_constraint_name and dc.owner = dcc.owner) where dcc.owner = 'owner_name' and dcc.table_name = 'table_name'; 	0
3732428	16829	mysql count rows with a specific column	select name, count(sr) from mytable group by name order by name asc; 	0.00129514403467697
3734052	37713	select elements of child tables with a given property	select id, prop1, prop2, isnull(t1.activecount, 0) as tab1cnt, isnull(t2.activecount, 0) as tab2cnt from meta m     left join     (         select metaid, count(*) as activecount         from table1         where active = 1         group by metaid     ) t1 on m.id = t1.metaid     left join     (         select metaid, count(*) as activecount         from table2         where active = 1         group by metaid     ) t2 on m.id = t2.metaid 	0
3735176	2113	compex mysql left join using multiple entries from meta tables	select     id, user_email, user_login,      first_name.meta_value as first_name,     last_name.meta_value as last_name,     phone_number.meta_value as phone_number,     wp_capabilities.meta_value as wp_capabilities  from wp_users     join wp_usermeta as wp_capabilities on wp_capabilities.user_id=id         and wp_capabilities.meta_key='wp_capabilities'     left join wp_usermeta as first_name on first_name.user_id=id         and first_name.meta_key='first_name'     left join wp_usermeta as last_name on last_name.user_id=id         and last_name.meta_key='last_name'     left join wp_usermeta as phone_number on phone_number.user_id=id         and phone_number.meta_key='phone_number' where     wp_capabilities.meta_value like '%administrator%' order by     first_name 	0.00584137758361707
3735591	29430	open source graph database	select from people where friends traverse(1,7) (name = 'ayende' and surname = 'rahien') 	0.175680753191809
3737696	6968	how to track which tables/views/etc depends from a table, in oracle	select name from user_dependencies where referenced_name = 'price' 	0.00239914063478974
3743447	30030	mysql: calculate visit frequency	select page,          count(*)     from hits    where agent like '%googlebot%' group by page 	0.00489358287858112
3744782	9328	multiple tag search in an associative table scheme	select i.item_id, i.item_name, t.tag_id, t.tag_name, m.tag_id, m.item_id  from item_table as i join tag_map as m on m.item_id = i.item_id join tag_table as t on t.tag_id = m.tag_id and t.tag_name in('tag1','tag2') where m.map_id not in (select m1.map_id from tag_map m1,item_table i1, tag_table t1 where m1.item_id = i1.item_id and m1.tag_id = t1.tag_id and t1.tag_name in('tag1','tag2') group by m1.item_id having count(m1.item_id) <2) 	0.0787228054379728
3744907	28108	calculate percentage applied sql server 2008	select *,      cast ((amount / totalpercentageamount - 1) * 100 as decimal (5, 2)) as pct,     cast (totalpercentageamount * 1.0572 as int) amt_calc from [salesreporttest] 	0.0567060066920775
3745751	24307	mysql - conditional select	select  * from    (         select  s2.store_id         from    store s2         join    items i2         on      s2.store_id = i2.store_id         group by                 s2.store_id         having                  count(*) > 1                  or max(i2.status) = 'unsold'          ) filter join    store s on      filter.store_id = s.store_id join    items i on      s.store_id = i.store_id 	0.62407098899859
3745812	33977	how do i make a cross table select in sql?	select sellerid from sales group by sellerid, goodsid having count(projectid) = select count(projectid) from projects 	0.344847977264313
3746866	41172	filtering results based on many to many relationships	select s.studentid  ,        s.studentname,        g.studentgrade from   students s        join grades g        on     g.studentid = s.studentid where  g.studentgrade     > 50 and    not exists        (select *        from    grades g2        where   g2.studentgrade <= 50        and     g.studentid   = g2.studentid) 	0.0021035309841419
3747013	38759	selecting columns in union	select ua.status, ua.date, 'dummy' as replyfrom, 'dummy' as viewed, 'status' as is_table from users_statuslog ua     where ua.uid = '{$showu[id]}' union all select us.message, us.date, us.isreplyfrom, us.viewed, 'wall' from users_wall us      where us.uid = '{$showu[id]}' order by `date` desc 	0.0101750073012162
3747820	24777	is there a view in sql server that lists just primary keys?	select object_schema_name(i.object_id), object_name(i.object_id), i.name from sys.indexes i where i.is_primary_key = 1 order by 1, 2, 3 	0.117810343523746
3750377	8327	t-sql: how to obtain the the exact length of a string in characters?	select      case when ((len ([t0].[product] + '#') - 1) = 8)        then [t0].[product] + 'test'        else stuff ([t0].[product], 8, 0, 'test')      end   from [orderitem] [t0] 	0.000319710962701087
3751704	33813	t-sql equivalent to oracle show all	select @@options 	0.251382109988499
3751782	8245	sql server 2005, calculating upcoming birthdays from date of birth	select * from customers c  where dateadd(year, 1900-year(dob), dob)      between dateadd(year, 1900-year(getdate()), getdate())     and dateadd(year, 1900-year(getdate()), getdate())+7 	0.000562687155753061
3751932	20367	how to find tables having foreign key to a table in oracle?	select d.table_name,        d.constraint_name "primary constraint name",        b.constraint_name "referenced constraint name" from user_constraints d,      (select c.constraint_name,              c.r_constraint_name,              c.table_name       from user_constraints c        where table_name='employees'        and constraint_type='r') b where d.constraint_name=b.r_constraint_name 	8.15766843655329e-05
3753346	22585	passing from form to query in access/sql/vb	select count(*) as countofcr1 from pdata where pdata.destid='cr1' and pdata.answertime between forms!myform!startdate + forms!myform!starttime                      and forms!myform!enddate + forms!myform!sendtime 	0.137093687168684
3753998	38558	t-sql how to get sum() from a subquery	select sum(time) as sumtime from table 	0.00754445823314881
3756576	34449	mysql select data from multiple rows	select * from table where keyword = 'guy' and name in (select name from table where keyword = 'developer') 	0.000965653690778571
3757768	6141	finding who is whose manager from the give table. i have given the reqired table and resultant table below. give query for sql server 2005	select sub.name , sup.name  from yourtab sub join yourtab sup on sup.id = sub.mgr 	0
3757908	34033	upload csv and replace data with foreign keys	select name, phone, city_id from temptable t, cities c where t.city = c.cityname 	0.0041449295135341
3758124	20124	database view for multiple one to many relationships	select a.id as aid, b.id as bid, c.id as cid from entitya a left join entityb b on a.id = b.aid left join entityc c on a.id = b.aid 	0.0113669099828827
3758366	32892	sql querying over multiple tables	select m.id from members m left join relations r on r.child = m.id left join members p on r.parent = p.id where m1.status = 0 and p.status <> 0 	0.116106154127258
3759054	22474	retrieve file list of an sql server database which is offline	select 'db_name' = db.name, 'file_name' = mf.name, 'file_type' = mf.type_desc, 'file_path' = mf.physical_name from sys.databases db inner join sys.master_files mf on db.database_id = mf.database_id where db.state = 6  	0.00190925869862404
3759743	33800	sql: select one record for each day nearest to a specific time	select values.value, values.datetime from values, ( select date(datetime) as date, min(abs(_wanted_time_ - time(datetime))) as timediff   from values   group by date(datetime) ) as besttimes where time(values.datetime) between _wanted_time_ - besttimes.timediff                                 and _wanted_time_ + besttimes.timediff and date(values.datetime) = besttimes.date 	0
3760559	16839	dealing with dates in mysql?	select u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt from relationships r, notes m, user u where m.user_id = r.leader and r.leader = u.user_id and r.listener ='".$_session['user_id']."' and m.dt < '".$lastmsg."' union  select username, picture, id, user_note, reply_id, reply_name, dt from user u, notes b where u.user_id = b.user_id and b.user_id = '".$_session['user_id']."' and dt < '".$lastmsg."' order by dt desc limit 10 	0.221702099302952
3760564	22387	mysql returning results from one table based on data in another table	select    user_id  from    users  inner join   groups   on groups.user_id = users.users_id     and groups.group_id = given_id where    firstname like '%foo' 	0
3760943	24598	include table name in sql query	select     id,     'table1' as tablename from     table1 union ... select     id,     'table4' as tablename from     table4 	0.0844820025000538
3761054	16717	what is an efficient way to check a word in a paragraph against the db?	select id, keyword from tbl_name where keyword in ('word1', 'word2', 'word3', 'wordn'); 	0.423506275316954
3761240	36483	count(*) from multiple tables in mysql	select   (select count(*) from table1 where somecondition) as table1count,    (select count(*) from table2 where somecondition) as table2count,   (select count(*) from table3 where somecondition) as table3count 	0.00784663505250816
3762022	34007	mysql number of rows per hour	select day(timestamp) as day, hour(timestamp) as hour, count(*) as count from mytable where timestamp between :date1 and :date2 group by day(timestamp), hour(timestamp) 	0
3762555	6961	display items by location. mysql select	select items.*, locations.* from items join locations on locations.id = items.location where items.display = 'true' order by locations.id; 	0.000419731617068739
3764498	14926	how to select specific changes using windowing functions in postgres	select "from", "to", timestamp from (     select         "from",         "to",         timestamp,         lag(("from", "to")) over (order by timestamp) as prev     from table1 ) t1 where ("from", "to") is distinct from prev 	0.458852273835996
3764683	20259	mysql intersection in subquery	select a.* from apartments a join apartments_features f1  on a.apartment_id = f1.apartment_id and f1.feature_id in (103,106)  where not exists (select null from apartments_features f2  where a.apartment_id = f2.apartment_id and f2.feature_id in (105,107) )  group by f1.apartment_id having count(*) = 2  	0.656074908415266
3765286	11601	mysql percentage (a bit complex?)	select x.movieid,          x.score,          count(x.userid) / y.score_count  as percentage     from your_table x     join (select t.movieid,                  count(t.score) as score_count             from your_table t         group by t.movieid) y on y.movieid = x.movieid group by x.movieid, x.score 	0.548964403055179
3765314	9037	sql pivot top n rows only	select x.col1, x.col2,          max(case when x.rk = 1 then x.col3 end) as res1,          max(case when x.rk = 2 then x.col3 end) as res2,          max(case when x.rk = 3 then x.col3 end) as res3     from (select yt.col1,                  yt.col2,                  yt.col3,                  row_number() over(partition by yt.col1, yt.col2                                        order by yt.col3) as rk             from your_table yt) x group by x.col1, x.col2 	0.000502944808252268
3766141	23521	mysql select query	select t1.f1,          t1.f2,          group_concat(t2.value) as values     from table_1 t1     join table_2 t2 on find_in_set(t2.color, t1.f2) group by t1.f1, t1.f2 	0.387336905290878
3766161	21624	getting view's column description	select view_column_name=c.name,view_catalog,view_schema,view_name,table_catalog,table_schema,table_name,column_name, ep.value as 'column_description' from sys.columns c inner join sys.views vw on c.object_id = vw.object_id inner join sys.schemas s on s.schema_id = vw.schema_id left join information_schema.view_column_usage vcu on vw.name = vcu.view_name and s.name = vcu.view_schema and c.name = vcu.column_name left join (     select distinct scm_name=scm.name,tbl_name=tbl.name,colname=col.name,col_object_id= col.object_id,col_column_id=col.column_id     from     sys.columns col     inner join sys.tables tbl on col.object_id = tbl.object_id     inner join sys.schemas scm on tbl.schema_id = scm.schema_id) temptbl on temptbl.tbl_name=vcu.table_name and temptbl.scm_name=table_schema and temptbl.colname = vcu.column_name left join sys.extended_properties ep on temptbl.col_object_id = ep.major_id and temptbl.col_column_id = ep.minor_id where vw.name = 'v_productinfo' 	0.0151292940347654
3767356	23827	have week number how to compute last day of the week?	select str_to_date('201038 sunday', '%x%v %w'); 	0
3767592	33067	php: filter mysql array	select browser, os, count(*) as c from table group by browser, os; 	0.167704389484119
3768148	27032	sql query - unique item with latest date of entry	select   usrs.name,   usrs.email,   (select case    when rsvp.answer = 1 then 'yes, see you there'    when rsvp.answer = 2 then 'cannot make it'    when rsvp.answer = 4 then 'cannot make it'    when rsvp.answer = 3 then 'maybe'   else 'no reply' end) as attendance,   (select case    when rsvp.answer = 1 then "1"    when rsvp.answer = 2 then "3"   when rsvp.answer = 4 then "4"   when rsvp.answer = 3 then "2"   else "5" end) as ordering   from jos_users usrs, jos_rsvp rsvp,   (select userid, max(answerid) as latest_answerid    from jos_rsvp    where userid not in (62,63,128)    group by userid   ) as latest_rsvp   where usrs.id = rsvp.userid   and rsvp.userid = latest_rsvp.userid   and rsvp.answerid = latest_rsvp.latest_answerid   order by ordering 	0
3769702	17763	how to create a new column in a select query	select a, b, 'c' as c from mytable 	0.00803433978982018
3771179	33077	is combining (result sets) of "two queries with aggregate and group by" possible?	select        id,       sum( case when x_factor = 1 then 1 else 0 end ) as x_count,        sum( case when y_factor = 1 then 1 else 0 end ) as y_count   from       yourtable   group by       id 	0.0938323242718407
3771423	20158	custom column on my select statement	select *, case when function(stamp)=1 then 'valid' else 'invalid' end 	0.593004850203415
3771452	41251	converting a text datatype field into a datetime	select  case when isdate(substring(fdelivery, 1,11)) = 1 then cast(substring(fdelivery, 1,11) as datetime) else cast('1/1/1900' as datetime) end as dateconvert from sorels 	0.0122796134538508
3772022	22763	how do i convert a hexadecimal varchar to a varbinary in sql server	select cast(dbo.hex2bin('7fe0') as varbinary(8000)) as bin; 	0.662812261245082
3772767	13766	eliminate duplicate data	select   ppc.personid,   ppc.category,   ppc.phonenumber,   ppc.createts from   person_phone_contacts as ppc   inner join (     select       personid,       category,       max(createts) as newest_createts     from       person_phone_contacts     where             current_timestamp between createts and endts       and current_date between effectivedate and enddate     group by       personid, category   ) as ppc2   on ppc.personid = ppc2.personid     and ppc.category = ppc2.category     and ppc.createts = ppc2.newest_createts 	0.0145540814184577
3773732	23351	find duplicate rows in database	select group_concat(first_name separator ' ') from table group by last_name having count(first_name) > 1 	0.000490335416454776
3774520	14936	sql finding multiple-line duplicates	select ot1.name name1, ot2.name name2 from oldtable ot1 join oldtable ot2 on ot1.name < ot2.name and                       ot1.state = ot2.state and                       ot1.strat = ot2.strat group by ot1.name, ot2.name  having count(*) = (select count(*) from oldtable tc1 where tc1.name = ot1.name)     and count(*) = (select count(*) from oldtable tc2 where tc2.name = ot2.name) 	0.0944704078081703
3775069	25999	ssis 2005 - ignore row insert failures	select 1 	0.417013728752787
3778006	34264	read-only committed data	select * from test with(readpast) 	0.6575422033425
3779180	11512	reverse the "natural order" of a mysql table without order by?	select @rownum:=@rownum+1 ‘rank’, p.* from player p, (select @rownum:=0) r order by score desc limit 10; 	0.0604317062628544
3779333	5183	stored procedure to query value of one column in first table to match any value in second table?	select  a.[col]  from    a           inner join b on a.col like '%' + b.col + '%' union all  select  distinct b.[col]  from    b         inner join a on b.col like '%' + a.col + '%' 	0
3779550	4580	two way joins mysql query	select m.id, m.user_id, m.message,     u.username  from message m inner join user_table u on m.user_id = u.id where m.id in (select message_id from message_tags where tags = 'happy') 	0.580927629980621
3779905	18051	sqlite - current_timestamp doesn't return the right hour?	select datetime(current_timestamp, 'localtime'); 	0.0540250679052255
3780787	19294	mysql - no result when joining tables using a null value	select location.id, location.city, state.name from     location left outer join     state on state.id = location.state_id; 	0.0113070758175149
3782094	1297	generate report using sum	select      m.serial,     o.name,     sum(o.value) from      main m     inner join order o on m.mainid = o.mainid group by     o.name,      m.serial 	0.150059836254017
3783010	25637	how to get mutiple results from group by in postgres	select id, type, timestamp from   (select id, type, timestamp,           rank() over (partition by type order by timestamp desc) as pos      from table   ) as t where pos < 5; 	0.00142267122170919
3783192	31315	help with querying a many to many table in mysql	select distinct product_id  from product   where product_id not in (select product_id from product_color where color_id in (4, 5, 6)); 	0.435287752035907
3783740	28655	get data for one semester in mysql	select * from dt_tb where (dt >= '2010-10-01') and (dt < '2011-05-01') 	0.00345102827662302
3784895	2761	how to check not equalto in mysql?	select * from users u  where not exists (      select 1 from active a where u.field  = a.field  ) 	0.344624895624547
3786398	35284	sql server 2008 - shredding xml to tables need to keep unknown date value as null	select tab.col.value('dinc[1][. != '''']','date') dinc, tab.col.value('ddis[1][. != '''']','date') lastard from xmlcompanydetail cross apply xmldata.nodes(' 	0.162060690748443
3788937	29568	reading the contents of a sql server job in vb.net	select [command] from msdb.dbo.sysjobs job join msdb.dbo.sysjobsteps steps on job.job_id = steps.job_id  where [name] = 'yourjobname' 	0.0340490947283517
3789638	2029	subtracting count of rows in subquery from current query	select x.id,             x.instancenumber - y.max_num as instancenumber,             x.isarchived       from @tbl x cross join (select max(instancenumber) as max_num                from @tbl               where isarchived = 1) y      where x.isarchived = 0 	0
3789868	24032	sql query that looks within the same table	select ft1.poster, ft1.title, count(ft2.id)     from forumtable ft1         left join forumtable ft2             on ft1.id = ft2.parentid                 and ft2.type = 1     where ft1.type = 0     group by ft1.poster, ft1.title 	0.00525299016756129
3789880	27537	splitting strings in postgres	select regexp_replace('fort worth tx', '\\s\\s+$', ''); 	0.0935460112567149
3791123	22372	mysql get table column names in alphabetical order	select c.column_name   from information_schema.columns c  where c.table_name = 'tbl_name' order by c.column_name 	0.000219290944250721
3791317	18037	mysql select from php	select email from members where username = 'admin'; 	0.0431110240008033
3791648	33687	how to select most frequent items from database?	select column_1, count(*) from records group by column_1 order by count(*) desc 	0
3792256	39146	sqlite3 group by using columns, not rows	select map,           sum(case when p.points > 0 then 1 else 0 end) as wins,          sum(case when p.points <= 0 then 1 else 0 end) as lose     from game g      join players p on g.game = p.game     where p.player='barrycarter' group by map 	0.0364434507903658
3793805	22553	sql server: how to query when the last transaction log backup has been taken?	select   d.name,          max(b.backup_finish_date) as backup_finish_date from     master.sys.sysdatabases d          left outer join msdb..backupset b          on       b.database_name = d.name          and      b.type          = 'l' group by d.name order by backup_finish_date desc 	0.00235943728772142
3795132	35223	mysql join with sum	select r.*,           coalesce(x.totalbet, 0) as totalbet,           coalesce(x.totalwins, 0) as totalwins      from results r left join (select t.resultid,                   sum(t.bet) as totalbet,                   sum(t.sum_won) as totalwins              from tickets t             where t.status != 0          group by t.resultid) x on x.resultid = r.resultid 	0.513617449504778
3796002	30686	display basic information from tables	select    cid as call_id,   a.username,    b.username   from calls   left join users a on calls.assigned_to = a.uid   left join users b on calls.caller_id = b.uid 	0.00242633539807532
3796186	8067	sql server query monthly totals	select cal.monthname, count(caseid) as total  from dbo.calendartable cal left outer join dbo.clientcase cc on month(cal.monthstartdate) = month(casestartdate) where  (casestartdate <= convert(datetime, cal.monthstartdate, 102)) and  (casecloseddate >= convert(datetime, cal.monthstartdate, 102)) or  (casecloseddate is null)  group by cal.monthname 	0.130928686221457
3797671	36502	php + mysql, order by name + starting at specific id	select id from (     select id from table_name      where id >= 3      order by id asc ) x    union select * from (     select id from table_name      where id < 3      order by id asc ) y 	0.000105789699187461
3798456	31346	mysql join count	select  l.type , count(ld.leavetype) as count from    leave as l left join leavedata as ld on ld.leavetype = l.id group by  ld.leavetype 	0.412872818257516
3799551	35717	postgresql function returns composite - how do i access composite values as separate columns?	select *    from myfunc() 	0.208254418171811
3799935	28474	mysql select where in given order	select * from table where id in (118,17,113,23,72)  order by field(id,118,17,113,23,72) 	0.0574789903950512
3801064	4327	mysql select conditional on existence of future records	select t.transactionid,        t.date,        t.alpha,        t.contractid   from mydb t  where t.date >= '2000-01-01'     and t.alpha < alphabound    and exists(select null                 from mydb x                where x.contractid = t.contractid                  and x.date > t.date) 	0.00216446847709274
3801413	20384	mysql not accessing parent in subquery?	select m.id from media m  join tag_name as n0 on n0.title = @a0      join media_tag as t0 on t0.media_id=m.id and t0.tag_id = n0.id where 1 and not (select 1 from tag_name as n1     join media_tag as t1 on t1.tag_id = n1.id     where t1.media_id=m.id and n1.title = @a1)  order by m.id desc; 	0.333446642280946
3801662	11049	how to get the value from mysql from table field like 'feildname-1'?	select `field-2` from users where useraccno = '1'; 	0
3801773	21245	how to check if a database exists in hsqldb/derby?	select schema_name from information_schema.schemata where schema_name = '<schema name>' 	0.0368128893993715
3802219	39058	transpose columns to rows	select 'one' as label,  curdate() as val union all select 'two' as label,  date_sub(curdate(), interval 15 day) as val union all select 'three' as label,  date_sub(curdate(), interval 30 day)  as val union all select 'four' as label,  date_sub(curdate(), interval 45 day) as val union all select 'five' as label,  date_sub(curdate(), interval 60 day) as val union all select 'six' as label,  date_sub(curdate(), interval 75 day)  as val union all select 'seven' as label,  date_sub(curdate(), interval 90 day) as val 	0.00172128560099206
3803151	26775	selecting 2 distinct rows mysql	select id, name, group_id from mytable where id in (     select min(id)     from mytable     group by group_id) union all select id, name, group_id from mytable where id in (     select min(id)     from mytable     where id not in (       select min(id)       from mytable       group by group_id       )     group by group_id) order by group_id 	0.000616152339138167
3804561	17086	mssql: only last entry in group by (with id)	select t.* from (     select *, row_number() over               (                   partition by [business_key]                   order by [date] desc               ) as [rownum]     from yourtable ) as t where t.[rownum] = 1 	0
3805153	23988	using not in for multiple tables	select count (visitorid) from company c where not exists (select * from userlog u where actionid = 2 and c.visitorid  = u.visitorid) and not exists (select * from supplies s where productid = 4 and s.visitorid  = u.visitorid) 	0.28666365746932
3805941	2401	add "datemodified" column with an update trigger to all tables that contain a "datecreated" column	select 'alter table ' + quotename(s.name) + '.' + quotename(t.name) + ' add [datemodified] datetime'     from sys.columns c         inner join sys.tables t             on c.object_id = t.object_id         inner join sys.schemas s             on t.schema_id = s.schema_id         left join sys.columns c2             on t.object_id = c2.object_id                 and c2.name = 'datemodified'     where c.name = 'datecreated'         and t.type = 'u'         and c2.column_id is null 	0.000293032562930476
3807103	21196	sql server script to find lob columns	select * from information_schema.columns where data_type in      ('text', 'ntext','image' ,'xml', 'varbinary')     or      (data_type = 'varchar' and character_maximum_length = -1)     or     (data_type = 'nvarchar' and character_maximum_length = -1) 	0.0222859411719138
3807950	20798	is it possible to execute a query for each database in mysql databases and sum or combine results using only mysql command environment?	select @query:=concat(       'select count(*) from ('     , group_concat( concat( y.prefix, x.table_schema, y.postfix ) separator ' union all ' )     , ') as total_count' ) from (     select  distinct table_schema     from    information_schema.tables     where   table_schema like '%dog%'     ) as x join (     select           'select * from '        as prefix         , '.log where insane = 1' as postfix      ) as y ; prepare stmt from @query; execute stmt; deallocate prepare stmt; 	0.0122244901528306
3808062	38514	counting mysql values	select tag_desc as 'description',           count(tag_desc) as 'occurances'      from table_name  group by tag_desc 	0.021910722438451
3808689	18741	mysql join on if()?	select t.*,         te.*   from templates t   join templates_email te on te.t_id = t.t_id  where t.t_type = 0 union select t.*,         ts.*   from templates t   join templates_sms ts on ts.t_id = t.t_id  where t.t_type = 1 union select t.*,         tf.*   from templates t   join templates_fax tf on tf.t_id = t.t_id  where t.t_type not in (0, 1) 	0.336786827593527
3809321	19783	how to select the five greatest number mysql	select * from bid_table order by bid desc limit 5; 	0.000797601637236183
3810105	6577	how do you get a sum() twice from one table with different where clause?	select      sum(case when pf = true then qty else 0 end) as accept,     sum(case when pf = false then qty else 0 end) as reject from pile; 	8.10448045418207e-05
3810165	18655	summarize the result of the table	select     "parent_id",     sum("count"),     bool_and("read") from     tablename group by     "parent_id"; 	0.00383812810133104
3810672	25826	mysql: show two separate fields become one field	select   concat(name,version) as model from   table 	0
3811750	13286	get the last entries using group by	select stamp_user, max(stamp_date), stamp_type from rws_stamps where stamp_date >= ? group by stamp_user, stamp_type 	0
3812165	3288	sql 2000/2005/2008 - find unique constraint name for a column	select     constraint_name  from     information_schema.constraint_column_usage  where     table_name = 'tablename'     and column_name = 'columnname' 	0.000296806602736051
3812316	4223	mysql grouping problem	select date1,date2,sc,cash,date from mytable  where id in (select id              from mytable group by date1,date2              having max(date)>=date1) 	0.778352263646342
3812864	40732	concat the output of the subquery?	select group_concat(id) as video_list from videos  where duration=0 	0.158833779853653
3813721	17316	non-trusted constraints	select *     from sys.check_constraints     where is_not_trusted = 1 select *      from sys.foreign_keys     where is_not_trusted = 1 	0.156219756645688
3814135	10436	using t-sql how do you calcualte a test grade percentage?	select round((cast(133 as numeric(20,8))/ cast(150 as numeric(20,8))) * 100, 2) 	0.212883959664756
3815045	32563	how to find the changes happened to the sql server since last migration	select     modify_date         ,type_desc         ,name     from sys.objects     where is_ms_shipped=0     order by 1 desc 	7.36658347144858e-05
3817028	14029	teradata - invalid date supplied for field	select * from mytable where value =  '2009-12-11' 	0.572577065919629
3817885	11296	sql server find out default value of a column with a query	select object_definition(default_object_id) as definition from   sys.columns where  name      ='colname' and    object_id = object_id('tablename') 	0.00094278343718158
3817913	3859	exporting table records as insert in mysql using mysql query browser?	select concat('insert into your_table (col1, col2) values(', t.col1,',', t.col2, ')')   from your_table t 	0.0681005046508819
3818560	448	count concatenate column in mysql	select x.insdate, sum(x.lot_qty), sum(x.accept), sum(x.reject) from     (select          date(inspection_datetime) as insdate,          model,         count(distinct(concat(range_sampling,model,line,lot_no))) as lot_qty,         if(status !='reject',1,0) as accept,         if(status ='reject',1,0) as reject     from inspection_report      group by date(inspection_datetime), model, line, range_sampling, lot_no) x group by x.insdate 	0.00579393544491804
3818977	32003	my sql field sum using another field to diffrentiate and then sort it	select sum(counter) as total_viewed, member_id, video_id from member_video_stat group by video_id order by total_viewed desc 	0.00265011429174676
3820347	9777	iphone, sqlite3, how can i determine is a table exists already in a few lines of code as possible?	select name from sqlite_master where type='table' and name='my_table_name'; 	0.00339503528430184
3821771	33748	select where column1 are equals	select column1, listagg(column2, ',') within group (order by column2) as concatedvalues from   table group by column1; 	0.0154331256204443
3821783	33340	mysql: how to select many results from linked table at one row to another?	select o.id_org, o.org_name, group_concat(concat(s.id_staff, ' ', s.staff_name) order by s.id_staff separator ' ')  from organizations o, staff s  where s.id_org = o.id_org  group by id_org, org_name; 	0
3822587	9369	sql server 2008: fill multiple t-sql variables from one select query?	select top (1) @targetid=id, @targetname=name  from @bigdataset  order by date desc 	0.0224710033975437
3822648	37071	how do i query between two dates using mysql?	select * from `objects` where (date_field between '2010-01-30 14:15:55' and '2010-09-29 10:15:55') 	0.0086383023936908
3822973	808	sql max and min in one column	select max.sizexlname as maxsize, min.sizexlname as minsize   from    (select max(tblsizexl.sizexlid) as maxsizexlid, min(tblsizexl.sizexlid) as minsizexlid      from product      join tblsizexl on product.sizexlid = tblsizexl.sizexlid     where product..groupid = @groupid) base   join tblsizexl max on max.sizexlid = base.maxsizexlid   join tblsizexl min on min.sizexlid = base.minsizexlid 	0.00562978142375897
3823419	33193	use like in t-sql to search for words seperated by an unkown number of spaces	select *  from table where  replace(column_name,' ','') like '%firstwordsecondwordthirdword%' 	0.0334496843685602
3823812	17431	sql: how to get a weighted count using group by?	select myvalue, sum(weight) as freq from mytable group by myvalue; 	0.0167324741822125
3824142	10435	join two mysql tables	select * from article_table right join meta_table on article_table.article_id = meta_table.article_id; 	0.0711018906807218
3824389	35431	mysql join of four tables with two key tables	select  tblb.bid,     tblb.name,     tblc.cid,     tblc.name from table e  right join table b on (table b.bid = table d.bid) right join table d using did right join table c using cid; 	0.00131630335607645
3824824	21240	join two mysql tables	select products.*, product_meta.meta_value from products left outer join product_meta  on products.id = product_meta.product_id where product_meta.product_id not is null 	0.0711018906807218
3825334	40748	compare monday's data to previous mondays in sql server	select cast (orderdate  as date) as [date], count(*) from orders where orderdate  > dateadd(year,-1, getdate())       and datepart(dw,orderdate ) = datepart(dw,getdate()) group by cast (orderdate  as date) 	0.00233343163111854
3826572	22208	mysql: include count of select query results as a column (without grouping)	select tabl.name, tabl.address, results.totals from databas.tabl left join (select count(*) as totals, 0 as bonus            from databas.tabl            where timelogged='noon'            group by null) results      on 0 = results.bonus where status='urgent'; 	0.00682623888298062
3830414	39434	sql select without sort	select    *,   case manufacid     when 2 then 1     when 1 then 2     when 4 then 3   end as sortorder from   items order by   sortorder 	0.128140687764899
3830596	39553	mysql query sum based on years	select `year`, sum(amount) from databasetable group by `year` 	0.000997653514791409
3833012	33426	sql. query for aggregating certain dependent fields	select sum(distance) from train_stops start with stop = 'middletown' connect by stop = prior  nextstop; 	0.0119384603835221
3833111	30610	simple sql query help - return rows where criteria matches all	select company  from table  where companyid in (     select companyid      from table     where fiscalyear in (2007,2008,2009)      group by companyid     having count(distinct fiscalyear) = 3 ) 	0.132056192797473
3834125	35467	how do you make an oracle sql query to	select      m.sup_email, r.sup_rating  from      (select substr(value, 1, length(value) - length('_email') as sup_name, info as sup_email from table where value like '%_email') as m  left join      (select substr(value, 1, length(value) - length('_rating') as sup_name), info as sub_rating from table where value like '%_rating') as r on m.sup_name = r.sup_name  order by     sup_rating desc  limit      1; 	0.790290091309814
3834273	40278	sql union issue when counting records	select count(a.code_id) as coded, a.code_desc from ( select     c.code_id,     c.code_desc from      code c     inner join assignedfoo af on af.code_id = c.code_id     inner join foo f on f.foo_id = af.foo_id where     f.foo_dt >= [start date] and      f.foo_dt <= [end date] union all    select     c.code_id,     c.code_desc from      code c     inner join assignedbar ab on ab.code_id = c.code_id     inner join bar b on b.bar_id = ab.bar_id where     b.bar_dt >= [start date] and      b.bar_dt <= [end date] ) a group by a.code_desc 	0.488422652005204
3834500	37191	mysql - count how many rows have a certain number?	select count(*)   from (select o.username,                 count(o.userid) as cnt           from orders o       group by o.userid         having cnt = ?) x 	0
3834572	19798	finding data that's missing from the database	select u.uid, u.mail, lu.id from users u left outer join legacy_users lu      on u.email = lu.mail where lu.id not in    (         select sourceid          from migrate_map_users     ); 	0.00178763506741064
3835646	11544	how to query the maximum value of two columns in two different tables?	select max(rec_id) from  (   (select rec_id from tablea)  union all   (select rec_id from tableb) ) combined 	0
3835678	25764	sql:getting count from many tables for a user record in user table.whats the best approach?	select u.userid,           u.username,           coalesce(f.numfiles, 0) as numfiles,           coalesce(p.numphotos, 0) as numfiles,           coalesce(g.numgroups, 0) as numgroups      from [user] u left join (select t.userid,                   count(*) as numfiles              from [files] t          group by t.userid)f on f.userid = u.userid left join (select t.userid,                   count(*) as numphotos              from [photos] t          group by t.userid) p on p.userid = u.userid left join (select t.userid,                   count(*) as numgroups              from [groups] t          group by t.userid) g on g.userid = u.userid     where u.userid = 2 	5.34490211123235e-05
3836649	7033	what is the best technique to search text for list of word	select     id from     mytable m     join     searchtable s on m.word like '%' + s.searchword + '%' 	0.0603781839664719
3839982	9109	row with minimum value of a column	select top 1 * from table where n_um = (select min(n_um) from table); 	6.59859548847639e-05
3840894	39824	how to trace back the exact create table statement that was used to create a table?	select dbms_metadata.get_ddl('table','<my_tab>') from dual; 	0.00446263242955718
3841226	9270	sql : group all	select sum(a) from tab where b > 0 	0.0623403451936973
3841811	16159	access 2003/2007 : query to find average of one text field grouped by another in table	select avg( c ) from      ( select producttype, count( itemname ) c     from mytable     group by producttype ) 	0
3842966	28247	building an index table from a mysql database with php	select distinct type, name, hour, day, month, year from table 	0.173154954613384
3844655	29364	how to get data from three tables by a join statement in mysql	select r.patient_id, s.sub_unit_name, p.patient_name, p.address  from reservation r, sub_unit s, patient p  where r.patient_id = p.patient_id and r.sub_unit_id = s.sub_unit_id 	0.00146185761573183
3845357	31857	inner join... how to get all fields from one table?	select stats.*, v.blog_id  from stats  inner join ( select distinct blog_id from visit_log where stats.blog_id = visit_log.blog_id ) as v 	0
3845503	31312	how to change 08:00:00 to 08:00 in php/mysql	select time_format(yourfield, '%h:%i') from table; 	0.251129327871375
3847163	10749	sql join two tables to access all of the data	select acl.datestarts, acl.dateexpires from sys_acl_levels_members acl left join profiles p on p.id = acl.idlevel 	0.000770354146468969
3847602	22004	using mysql, how do i order by date across several different tables?	select * from (     select * from     (         select chaptertitle, storyid, chaptercontent, newsfeed.article, newsfeed.title, newsfeed.release         from chapter         right join newsfeed         on releasedate=newsfeed.release     ) as derivedtable1     union     select * from      (         select chaptertitle, storyid, chaptercontent, newsfeed.article, newsfeed.title, releasedate         from chapter         left join newsfeed         on releasedate=newsfeed.release     ) as derivedtable2 ) as maintable order by maintable.release desc 	0.00122796643184618
3851702	2821	query for a column to be compared against two values	select *     from yourtable     where columna = 'aaaa' or columna = 'bbbb' 	0.0197366182541037
3852560	19590	adding selected attribute to group_concat output in codeigniter/mysql	select a.custom_field_name,            a.custom_field_id,            group_concat('<option name=\"',c.custom_field_value_id, '\" value=\"', c.custom_field_value_id, case when r.project_id is not null then 'selected' else '' end, '\">',c.custom_field_value_name , '</option>' order by c.custom_field_value_id asc separator ' ') as field_values      from projects_custom_fields a      join projects_custom_fields_values c on c.custom_field_id = a.custom_field_id left join projects_custom_fields_reg r on r.custom_field_value_id = c.custom_field_value_id                                       and r.custom_field_id = a.custom_field_id                                       and r.project_id = ?  group by a.custom_field_id  order by c.custom_field_id 	0.0688064324201841
3853867	14078	easier way to select row matching condition having maximum for a certain column	select id, name, rn   from (select id, name, rank() over(order by lvl desc) rn            from my_table           where name like 'a%')  where rn = 1 	0
3853953	17070	sql and mysql combined query	select      mysql.db.tbl_x.* left join      mssql.db.tbl_y  on     mysql.db.tbl_x.id=mssql.db.tbl_y=id 	0.462031892110058
3855169	27413	sql query - select data from table a based on two fields in table b	select b.name from a inner join b   on a.date = b.date   and a.step = b.step where a.status = '1' 	0
3855557	31459	left joining on multiple tables with timestamps	select distinct person_info.person_name      t2.value,      t3.value,      t4.value,      t5.value from person_info     left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table2 t) t2           on t2.person_name=person_info.person_name and t2.rowno=1     left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table3 t) t3          on t3.person_name=person_info.person_name and t3.rowno=1     left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table4 t) t4          on t4.person_name=person_info.person_name and t4.rowno=1     left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table5 t) t5          on t5.person_name=person_info.person_name and t5.rowno=1; 	0.0191169213220316
3857943	40012	primary foreign key display in html table	select * from product inner join warehouse on product.pid = warehouse.pid 	0
3859470	29906	generate report	select sum(b.total) from tableb as b inner join tablea as a on a.tablea_id = b.tablea_id where a.date between <start_date> and <end_date> 	0.175558846341034
3862304	31906	sql: how to refer subexpression from where in select?	select * from (  select complex_expression() ce from t ) where ce != ''; 	0.0700430034979007
3862624	37884	union all, text field and order by error	select * from  (     select     id, datetime, author, headline, intro, text, type, toppriority,             secondpriority, comments, companyid, '1' source      from     table1     union all     select     autoid as id, dato as datetime,             id collate sql_latin1_general_cp1_ci_as as author, null as headline,              null as intro, notat collate sql_latin1_general_cp1_ci_as as text,             cast(notattypeid as varchar) as type,             null as toppriority, null as secondpriority, null as comments,             selskabsnummer as companyid, '2' source      from     table2     where     (notattypeid = '5') or (notattypeid = '6') ) a order by datetime desc 	0.274960518786633
3863275	5716	sorting rows by count of a many-to-many associated record	select v.x, v.y, count(*) as keyword_count from "venues" v   inner join "check_ins"   c  on c."venue_id"     = v."id"   inner join "keywordings" ks on ks."check_in_id" = c."id"   inner join "keywords"    k  on ks."keyword_id"  = k."id" where (k."name" = 'foobar') group by v.x, v.y order by 3 	9.2775968153505e-05
3863430	12084	oracle select query	select '"' || last_name || ',' || first_name || '"' from table 	0.515601278408244
3863836	31503	mysql - order a query result in "some mode"	select        x.id,        x.name,        x.field from (       select id,               name,               field,               case field when 'defense' then 1                         when 'medium'  then 2                         when 'attack'  then 3              end as sortvalue       from mytable) as x order by x.sortvalue 	0.473481716263284
3864137	1042	7 day users stat sql query	select userid from tblq where datediff(now(),postdate) < 7 group by userid having count(distinct date(postdate)) = 7 	0.00244213145303127
3864432	1254	mysql select next row without knowing the id	select id from table where id >= (select id from table where name = '$name') order by id asc limit 2 	0
3865615	37006	getting number of rows from sqlite c interface in objective-c	select count(*) from coffee 	0.000374856795253068
3865680	40695	sql select where matching record exists and no matching record	select    tb1.booking_ref, tb1.investor, tb2.cost  from    tb1       left join tb2            on tb1.booking_ref = tb2.booking_ref               and tb1.investor = tb2.investor  where tb1.investor = ''12345'' 	7.32187377401112e-05
3865971	25748	how to make a sql query for an ordered list with sub-groups?	select whatever from mytable my1 left join mytable my2 on my1.id = my2.parent_id where whatever order by case when parent_id is null then id else parent_id end,  case when parent_id  is null then 0 else order_n end 	0.104953140166253
3869036	25276	how do i get mysql rows from 24-48 hours ago?	select *   from your_table t  where t.datetime_column < date_sub(now(), interval 24 hour)    and t.datetime_column > date_sub(now(), interval 48 hour) 	0
3871142	3037	convert string(integer) to date in sql	select convert(varchar,   convert(datetime,'20100731'), 103) 	0.112672428953079
3871229	30691	how do you order by a search phrase found in the beginning of a word and only afterwards the middle using sql	select * from users where [name] like '%al%' order by patindex('%al%',[name]) 	0.000145027924004175
3871978	20136	sql: select lowest value that doesn't already exist	select min(nt.id) from numbertable nt left outer join originaldata od on nt.id=od.id where od.id is null 	0.00127425452679608
3872173	15118	compare when value could be both null or text	select  *  from    material as m  where   mtrlcode = 826      and (exposlimit <> 'compareme'          or (exposlimit is null and compareme is not null)           or (exposlimi is not null and compareme is null)) 	0.358104804795641
3872403	17613	how do i find the row where a certain value is between 2 others?	select   val from   table where   table.range_min <= 9   and table.range_max >= 9 	0
3872632	19964	sql query for a report	select name,        sum(case when rating > 1 then 1 else 0 end) as cnt1,        sum(case when rating > 5 then 1 else 0 end) as cnt2     from myview     group by name 	0.553169250473267
3872788	27298	sql query is invalid in the select list	select          tblm.guidrid,      sum(dbo.tblch.curtotalcost) as curvalue from              tblch      inner join tblm on tblch.guidmid = tblm.guidmid      inner join viewlm on tblm.strnumber = viewlm.strnumber where       tblm.guidrid = '4d832bc8-1827-4054-9896-6111844b0f26' group by tblm.guidrid 	0.563300053847581
3873181	12617	is there a way to extract submatches from a regular expression in mysql?	select substr(`field`,1,instr(`field`,':')-1) as `field_a`,   substr(`field`,instr(`field`,':')+1) as `field_b`  from `table`  where `field` rlike '^(.+):(.+)$'; select left(`field`,instr(`field`,':')-1) as `field_a`,   right(`field`,length(`field`)-instr(`field`,':')) as `field_b`  from `table`  where `field` rlike '^(.+):(.+)$'; 	0.53901199324063
3875166	12730	mysql left outer join with count from joined table, show all records	select r.region_name, r.region_id, r.abbreviation, r.map_order,     (ifnull( count( p.property_id ) , 0 )) as propertycount from  `rmp_region` r left outer join  `rmp_property` p      on p.path like concat(  '%/', r.region_id,  '/%' ) and p.active =1 where r.parent_region_id =1 group by r.region_name, r.region_id, r.abbreviation, r.map_order order by r.map_order asc 	0.000884970686747462
3875323	14408	how can i select the latest of three value types in a mysql database?	select m.id, m.time, m.data, m.type from (     select type, max(time) as maxtime     from mytable     group by type ) mm inner join mytable on mm.type = m.type      and mm.maxtime = m.time 	0
3875765	16517	ms access sum of related records	select vendorpartnumber, sum(quantity) as totalallocations     from yourtable     group by vendorpartnumber 	0.0063330177348381
3876251	8182	need help with sql query to find things with most specified tags	select p.id, p.text, count(tg.id) as tagcount     from posts p          inner join taggings tg              on p.id = tg.post_id         inner join tags t              on tg.tag_id = t.id     where t.name in ('cheese', 'wine', 'paris', 'frace', 'city', 'scenic', 'art')     group by p.id, p.text     order by tagcount desc 	0.19494258580046
3876742	2902	sql make the joined tables as one table may be?	select    * from table3 t3 join  (select         *        from `databse1`.`table1`        join `database2`.`table2` on `table2`.`customerid` = `table1`.`customerid`        where        `table1`.`recordid` in (1,2,3,4)) t1 on t1.customerid = t3.customerid where t3.customerid = [your customer id] 	0.0207228009734669
3876894	12866	convert varchar to date	select cast((right('010110',2) + left('010110',4)) as datetime) 	0.0334256538749812
3877597	21583	mysql query to three tables, want to use join instead subquery	select p.id as a,           p.url as b,           t.id as c      from plug p      join trade t on t.id = p.trade_id                  and t.status = 1 left join trade_log tl on tl.trade_id = t.id                       and tl.ip = mysql_real_escape_string($ip)                       and tl.log_date = curdate()     where p.status = 1       and tl.ip is null  order by p.weight desc     limit 1 	0.746360646711195
3877705	38442	how to refer to a variable create in the course of executing a query in t-sql, in the where clause?	select * from  (     select [yourcolumn] as youralias, etc...    from whatever ) yoursubquery where youralias > 2 	0.192182335190937
3878499	277	finding the hash value of a row in postgresql	select     md5(cast((f.*)as text)) from     foo f; 	0.000341038923089724
3878753	31310	replace string in oracle procedure	select nama_akun, replace(nama_akun, 'dollar america', 'usd') as new_nama_akun   from mondes_mstr_chart_of_account   where instr(nama_akun, 'dollar america') > 0; 	0.677654232924829
3880196	32923	mysql get latest record by date from mutiple tables with values from lookup tables	select     s.mainnumber,     n.notes from numbers s join (     select         max(date) as date,         mainnumber     from numbers     where mainnumber = 2 ) as sx     on s.mainnumber = sx.mainnumber and s.date = sx.date left join notes n     on s.mainnumber = n.mainnumber left join (     select             max(date) as date,             coalesce(mainnumber,0) as mainnumber     from notes     where mainnumber = 2 ) as nx     on n.mainnumber = nx.mainnumber and n.date = nx.date 	0
3882178	21036	mysql latest records with condition	select tag, count(*)as tags_count from (   select post_n, tag from tags   order by post_n desc limit 20 ) as temp group by tag having tags_count>=2 order by post_n desc limit 5 	0.00208957357597019
3883307	13803	how to reverse values in a string in t-sql	select replace(replace(replace('abc.def.ghi/jkl','/','-'),'.','/'),'-','.') 	0.0246207824210391
3883365	20827	how to fetch data from oracle database in hourly basis	select to_char(t.time, 'yyyy-mm-dd hh24') as hourly,          count(*) as numperhour     from your_table t group by to_char(t.time, 'yyyy-mm-dd hh24') 	7.13352455514515e-05
3883674	14132	how will you keep a specific country on top in a drop down list?	select      countryname  from tableofcountries  order by      (case when countryname = 'us' then 0       else 1 end) asc, countryname asc 	0.000207991392551611
3883806	28736	how to search "tags" in mysql?	select    * from     product_tags p where    instr('yellow gold diamond band', p.tag_name) > 0 	0.0578552336631684
3886070	29883	how to change this sql so that i can get one post from each author?	select * from ( select `e` . * ,         `f`.`title` as `feedtitle` ,         `f`.`url` as `feedurl` ,         `a`.`id` as `authorid` ,         `a`.`name` as `authorname` ,         `a`.`about` as `authorabout` from `feed_entries` as `e` inner join `feeds` as `f` on e.feed_id = f.id inner join `entries_categories` as `ec` on ec.entry_id = e.id inner join `categories` as `c` on ec.category_id = c.id inner join `authors` as `a` on e.author_id = a.id group by `e`.`id` order by `e`.`date` desc ) t group by author_id order by date desc  limit 5 	0
3886490	7481	codeigniter: compare a mysql datetime with current date	select date_diff(curdate(),your_mysql_date_field) from your_table 	0.000319130312675317
3886897	19592	sql group by clause	select date,        riskcategory,        sum(point) as total  from risktrend  where date(date) >= (select max(date(date)) from risktrend)  group by date, riskcategory; 	0.794776946420377
3887063	21505	weighted average calculation in mysql?	select sum(x.num * x.gid) / sum(x.cou)   from (select i.gid,                count(i.gid) as num,                s.cou           from infor i      left join size s on s.gid = i.gid          where i.id = 4325       group by i.gid) x 	0.0404031926649077
3888412	8512	store open/close times and dst changes	select      case when (         (cast((current_timestamp at time zone s.timezone) as time) between h.opens and h.closes) and          h.day = extract(dow from current_timestamp at time zone s.timezone)) then 0 else 1 end     ) as closed  from store s  left join store_hours r on s.id = r.store_id  here h.day = extract(dow from current_timestamp at time zone s.timezone) 	0.108350190217091
3888439	5909	how to write sql query for aggregate total value for a particular condition	select sum(case [vote] when 1 then 1 else -1 end) as total_votes,        sum((case [vote] when 1 then 1 else -1 end) *              (case when [user_id] = @username then 1 else 0) as user_votes from [votetable] where [ob_type] = @obtype and [ob_id] = @obid 	0.00527579849081307
3888920	24672	select top record from group	select          min(name), code from           mytable  group by           code 	0.000807154048417615
3893539	9161	oracle query to extract distinct routes	select   distinct xmlserialize(content approver_path as varchar2(2000)) distinct_path from (   select     request_nbr,     xmlagg(xmlelement("approver",approver) order by sequence_nbr) approver_path   from     role_approvals   group by     request_nbr ) 	0.202762660178713
3894474	30174	sql "all" functionality?	select t1.id, max(number) as [max number] from table1 t1 left join table2 t2 on t1.fk=t2.id and t2.number is not null group by t1.id having count(distinct t1.fk) = count(distinct t2.id) 	0.305089616189862
3896077	17539	searching database php mysql	select * from table where match (columnname)       against ('+house +barn -sheep' in boolean mode); 	0.247903371031
3898589	21921	mysql calculate time online	select  sum(datediff(n, li.logtime, lo.logtime)) as totaltimeinminutes from    (             select  li.recordid, li.userid, li.logtype, li.logtime,                    (    select min(t.recordid) from  yourtable t                         where t.userid   = li.userid                         and   t.logtype  = li.logtype                         and   t.recordid > li.recordid                     ) as nextrecordid             from   yourtable li             where  li.userid = 123             and    li.logtype = 'login'         )          li inner join yourtable lo on lo.userid = li.userid              and lo.logtype = 'logout'              and lo.recordid between li.recordid and li.nextrecordid 	0.0267482049847996
3902335	25958	query based on sql	select * from people where year(now())-year(dob)>50 order by dob limit 1; 	0.0258335652263443
3905633	37189	passing a parameter into a subquery	select cataloguenumber, productname,  shipping.carriagecost as carriagecost  from products, shipping  where shipping.carriageweight = products.weight 	0.44250989569005
3907161	19067	why does oracle return specific sequence if 'orderby' values are identical?	select   date,   amount from mytable where date = '26-oct-2010' order by date, dbms_random.value; 	0.0961092564040883
3907173	30368	t-sql how to run a procedure/function within a select query?	select mytable.id_customer, myschema.myfunction(mytable.id_customer) as myalias from mytable group by mytable.id_customer 	0.440145704442172
3907879	27486	sql server: howto get foreign key reference from information_schema?	select        kcu1.constraint_name as fk_constraint_name      ,kcu1.table_name as fk_table_name      ,kcu1.column_name as fk_column_name      ,kcu1.ordinal_position as fk_ordinal_position      ,kcu2.constraint_name as referenced_constraint_name      ,kcu2.table_name as referenced_table_name      ,kcu2.column_name as referenced_column_name      ,kcu2.ordinal_position as referenced_ordinal_position  from information_schema.referential_constraints as rc  inner join information_schema.key_column_usage as kcu1      on kcu1.constraint_catalog = rc.constraint_catalog       and kcu1.constraint_schema = rc.constraint_schema      and kcu1.constraint_name = rc.constraint_name  inner join information_schema.key_column_usage as kcu2      on kcu2.constraint_catalog = rc.unique_constraint_catalog       and kcu2.constraint_schema = rc.unique_constraint_schema      and kcu2.constraint_name = rc.unique_constraint_name      and kcu2.ordinal_position = kcu1.ordinal_position 	0.0001819458341849
3908228	37111	incorrect key file with mysql	select posts.id, posts.post_title  from rss_posts as posts inner join rss_feeds as feeds on posts.blog_id=feeds.id  where feeds.blog_language=1  and posts.post_data_db > (now - interval 30 day); order by posts.post_date_db desc limit 10; 	0.622406507069656
3908366	8564	optimize a query that is using multiple left joins on the same tables	select ... from tickets t inner join ticket_text_fields f on t.id=f.ticket_id where f.textfield_id in (7, 8, 9, ...) union all select ... from tickets t inner join ticket_date_fields d on t.id=d.ticket_id where d.datafield_id in (434, 435, 436, ...) 	0.445905518246673
3909126	17222	mysql granting provileges on all databases, except a few	select concat(concat('grant all on ',schema_name), ' to some_user') as `database`   from information_schema.schemata where schema_name not in ('db1','db2') 	0.00430355570133099
3912315	34985	get id after an insert in sql server in a multithread enviromment?	select scope_identity() 	0.00977472782371129
3913563	22904	mysql: count data from a month until b month	select id, line, count( serial_number ) as qty,        sum(s), sum(a), sum(b), sum(c),        (sum( s ) + sum( a ) + sum( b ) * 0.4 + sum( c ) * 0.1) / count( serial_number ) as qp from `inspection_report` where `thedate` between '2010-01-01' and '2010-06-00' 	0
3913656	40991	multiple condition in join	select *  from t1 join t2  on t1.a = t2.b and t1.c = t2.d and t1.e = t2.f 	0.433066995757765
3914452	12344	how to select distinct from multiple columns	select t.users   from   (   select saved_by as users   from table   union    select deleted_by   from table   union    select accepted_by   from table   union    select published_by   from table   ) as t; 	0.000516556232405061
3914930	40481	how to select first 30 chars in a sql query?	select left(colname,20) as first20 from yourtable 	0.00780364987432837
3915421	27055	sql: expand 1 column into 3 on summarize table	select      product,     max(case when availability='store1' then 'yes' else 'no' end) as store1,     max(case when availability='store2' then 'yes' else 'no' end) as store2,     max(case when availability='store3' then 'yes' else 'no' end) as store3 from yourtable group by product 	0.000846912773733385
3915576	1295	how to reuse a dynamic column in another column calculation in mysql?	select (selloff1 / weekavg) as procent from (   select      selloff1, if(daycode=1,(select...),(select...)) as weekavg   from ... ) 	0.00315919925303935
3916422	24296	mysql join multiple table	select group_concat(kword) from news natural join keyword group by news.nid 	0.1775857297308
3917578	7604	grouping multiple counts with each row representing one id	select admin_id,        sum(case when activity = 1 then 1 else 0 end) as numactivated,        sum(case when activity = 2 then 1 else 0 end) as numcanceled,        sum(case when activity = 3 then 1 else 0 end) as numrenewed     from yourtable     group by admin_id 	0
3918174	16814	grouping by fiscal year (oracle)	select 'fy'||trunc(date + 83, 'yyyy') as fy, site, count(*) from mytable group by 'fy'||trunc(date + 83, 'yyyy'), site 	0.0184734219007345
3918349	19181	how to count multiple fields in sql	select ip, sum(clientcount) as clientcount, sum(servercount) as servercount from (     select client_ip as ip, count(*) as clientcount, null     from t_events     where start_time between '10/7/2010 08:00:00 am' and '10/7/2010 04:00:00 pm'     group by client_ip      union all     select server_ip as ip, null, count(*) as servercount     from t_events     where start_time between '10/7/2010 08:00:00 am' and '10/7/2010 04:00:00 pm'     group by server_ip  ) a group by ip 	0.0304669793315549
3922770	32059	ranking in mysql in a single sql statement	select count(id) + 1 as rank from student  where score > (select score from student where id = 3) 	0.328958688942271
3922819	23814	is there any way given a column, which table it belongs using sql query?	select [name], object_name(id) from sys.columns where [name] like '%columnname%' 	0.00932867463590637
3924097	13651	mysql join tables	select   t1.* , count(t2.food) as foods from   t1 left join t2 on (t1.cid = t2.cid) group by   t2.cid 	0.30836982525185
3925504	513	mysql select: get main record(s) by multiple attached records?	select p.*  from pages p join page_filters pf on p.pageid = pf.pageid     and pf.filtertypeid in (22,27) group by p.pageid having count(distinct pf.filtertypeid) = 2 	0.000107380717935948
3926162	32191	group different rows in one by combining strings	select column1, group_concat(column2) from table group by column1 	0.000275016206287587
3926166	31564	rails/mysql - find all with no association	select users.*  from users  left join shifts on users.id = shifts.user_id      and shifts.date = @somedate where shifts.user_id is null; 	0.00294694877805669
3927231	37650	how can you tell what tables are taking up the most space in a sql server 2005 database?	select   t.name as tablename,  i.name as indexname,  sum(p.rows) as rowcounts,  sum(a.total_pages) as totalpages,   sum(a.used_pages) as usedpages,   sum(a.data_pages) as datapages,  (sum(a.total_pages) * 8) / 1024 as totalspacemb,   (sum(a.used_pages) * 8) / 1024 as usedspacemb,   (sum(a.data_pages) * 8) / 1024 as dataspacemb from   sys.tables t inner join    sys.indexes i on t.object_id = i.object_id inner join   sys.partitions p on i.object_id = p.object_id and i.index_id = p.index_id inner join   sys.allocation_units a on p.partition_id = a.container_id where   t.name not like 'dt%' and  i.object_id > 255 and    i.index_id <= 1 group by   t.name, i.object_id, i.index_id, i.name  order by   object_name(i.object_id) 	0.10174518450291
3927646	229	in sql, how do i get all rows where a column's value is the lowest in the table?	select * from table where weight = (select min(weight) from table) 	0
3928484	22887	how to count results within results in mysql?	select `year`,           `manufacturer`,           count(id) as `total`,          sum(case when store = 'ebay' then 1 else 0 end) as ebay_count,          sum(case when store = 'amazon' then 1 else 0 end) as amazon_count     from `items`  group by `manufacturer`, `year`  order by `total` desc     limit 10; 	0.0580783942563667
3928575	7832	postgresql, checking date relative to "today"	select * from mytable where mydate > now()::date - 365; 	0.00766380629813052
3930213	11585	mysql - adding/concatenating text values within a select clause	select concat(vend_name, ' (', vend_country, ')') from vendors order by vend_name; 	0.266927611680365
3930338	2883	sql server: get table primary key using sql query	select ku.table_name as tablename,column_name as primarykeycolumn from information_schema.table_constraints as tc inner join information_schema.key_column_usage as ku on tc.constraint_type = 'primary key' and tc.constraint_name = ku.constraint_name and ku.table_name='yourtablename' order by ku.table_name, ku.ordinal_position; 	0.0164113835436427
3931338	35307	sybase iq - how to show stored procedure without wrapping text?	select proc_defn from sys.sysprocedure where proc_name='<procedurename>' 	0.308537057619931
3934093	19497	plsql return values	select max(ltrim(sys_connect_by_path(flow_run_id, ','), ','))    from    (     select flow_run_id, rownum rn     from table     where created_date < sysdate - 32     and rownum < 10     order by 1 desc    )    start with rn = 1    connect by prior rn = rn - 1 	0.036383322714495
3934627	29752	tsql, counting pairs of values in a table	select forename, surname, count(*) from yourtable group by forename, surname 	0.000192063578471333
3935569	15650	mysql: date as string	select str_to_date(datecolumnname,'%m/%d/%y'); 	0.0601119265482271
3935998	15655	sql sum with case and distinct?	select users.id, users.name,           subquery1.result_of_calculation1, subquery2.result_of_calculation2     from users          left join (          ) subquery1          on users.id = subquery1.user_id          left join (          ) subquery2          on users.id = subquery2.user_id group by users.id, users.name; 	0.621745424493868
3937202	41312	sql find holes in linear time-based table	select top 1      dateadd(second,-10,t1.yourdatecolumn)     from yourtable t1     where not exists (select 1                           from yourtable t2                            where dateadd(second,-10,t1.yourdatecolumn) = t2.yourdatecolumn)     order by t1.yourdatecolumn desc 	0.061613562482353
3938893	30028	how to join queries from one table?	select      batch,     shiplist_qty,     count(x.batch) as allocated,     (shiplist_qty - count(x.batch)) as variance,     (select count(batch) from dbo.fg_fillin where status='kitted' and batch = x.batch) as kitted from dbo.fg_fillin as x where x.status in('kitted','allocated') group by x.batch,x.shiplist_qty 	0.00369497091057554
3938918	17507	how to order or choose rows in mysql group by clause?	select id, number, otherfields from table    where id in (select min(id) from table group by number) 	0.139029323400205
3939125	23944	query to get all matches for a particular column	select t2.column4      from table1 t1 left join table2 t2 on t1.column1 = t2.column1     where column2 = 'mmm'  group by t2.column4    having count(t1.column1) = count(t2.column4) 	6.14194737807413e-05
3939386	24179	select top n with "for update skip locked" in oracle	select messageid from messages      where messageid in (        select messageid from(          select            messageid,            rank() over (order by messageid asc) as msg_rank            from messages        ) where msg_rank=1     )   for update skip locked; 	0.00562878024334976
3939714	23737	run a single query on multiple databases	select blah,blah,blah from localtable union select blah,blah,blah from federatedtable 	0.0668784321241373
3940984	26610	how to search data from oracle database which contains single quote	select * from my_table where name like '%''%' or address1 like '%''%' or address2 like '%''%'; 	0.000934242842633946
3941875	28433	how to search in mysql in a case-insensitive way	select * from user where upper(u.name) = 'steven' 	0.490430103283314
3942612	40266	new to dynamic sql statements	select *  from users u where   (@username is null or username like '%'+ @username + '%')     and (@gender is null or gender = @gender)     and (@age is null or age = @age)     and (@gname is null or gname = @gname)     and (@location is null or location = @location) 	0.569381979166399
3943474	10374	select that returns based off two columns as a key	select distinct a.fname, a.lname from address a     where not exists        (select * from addresslive b where b.fname = a.fname and b.lname = a.lname) 	0
3943795	18592	select all email addresses, implode by ;	select group_concat(`emailaddress` separator ';') as `emails` from table where id=4 group by id 	0.210739114132355
3946307	16250	in a many to many relationship, how can records collectively owned be selected	select b.* from books b inner join   (select book_id, count(*) as cnt    from user_has_book    where user_id in ('frank', 'joe')       group by book_id   having cnt=2)x on (x.book_id = b.book_id) 	0.0105486810452127
3946623	20806	how to check that at least one row complies to a condition (where clause) in mysql?	select case          when exists (             select *              from mytable              where mycolumn = 23         ) then 1          else 0      end as rowsexist 	0.000293009380448234
3946831	21503	mysql where problem with comma-separated list	select uid    from tbl   where find_in_set('401', artist_list) > 0 	0.765221949915297
3949181	40553	sql query for join two tables of different databases that are in two servers	select  * from    localdb.dbo.localtable as t1 full outer join         linkedserver.remotedb.dbo.remotetable as t2 on      t1.col1 = t2.col1 	8.1360337155249e-05
3950838	25788	trying to join data from two mysql tables in order to sort by it	select    t1.event from    t1    join t2 on t1.nid = t2.nid order by    t2.time 	0.0027410701506482
3952664	15838	mysql find crossovers in a table for different profiles for a same user	select   l.location_id,   l.location_name from   location l where   exists (       select 1          from profile p   inner join profile_location pl on pl.profile_id = p.profile_id              and pl.location_id = l.location_id        where p.user_id = <user_id_param>     group by pl.proloc_id       having count(*) > 1   ) 	0
3955631	41185	php / sql using data from previous query to query another table	select *  from supplier_areas join supplier_languages using (supplierid) join supplier_products using (supplierid) join supplier using (supplierid) where     supplier_areas.locationid=1  and supplier_languages.languageid in (1,2) and supplier_products.productid in (....) 	0.000507808301144715
3957535	36181	problem select specific column name using sql statement	select [select], [insert], [update] from dcparam 	0.259038887619303
3957718	25287	issue writing mysql query to find difference	select greatest(column1 - column2, 0)  from table 	0.667701655829001
3958366	36476	mysql query to select one specific row and another random row	select * from users order by (user_id = 5) desc, rand() limit 0,2 	0
3959692	8191	rownum in postgresql	select      row_number() over (order by col1) as i,      e.col1,      e.col2,      ...  from ... 	0.393366008775084
3960691	39810	using php, how would i convert all rows of a char field such as "11/19/10" to a date field?	select str_to_date(datearriving, '%m/%d/%y') from table 	5.13206782040243e-05
3961502	40200	how can i find matches in two sql tables?	select     us.* from userssample us inner join userssearching uss on uss.userid = us.userid 	0.00153532938364257
3963457	40771	how do i select a 1 as a bit in a sql-server view?	select id, name, convert(bit, 1) as active from users 	0.0749886793074981
3964322	34692	get maximum count of a value in a column	select name, count(name) from table group by name 	0
3964806	27388	making a query ordering condition dependent on the age of a variable	select s.loginid, s.title, s.url, s.displayurl, s.datesubmitted, l.username,            s.submissionid, s.subcheck, s.topten, count(c.commentid) countcomments,             greatest(s.datesubmitted, coalesce(max(c.datecommented), s.datesubmitted)) as most_recent       from submission s       join login l on s.loginid = l.loginid  left join comment c on s.submissionid = c.submissionid   group by s.submissionid   order by case               when s.datesubmitted > date_sub(now(), interval 1 day) and s.topten = 1 then 0               when s.datesubmitted > date_sub(now(), interval 1 day) and s.topten != 1 then 1              else 2             end, most_recent desc       limit $offset, $rowsperpage 	0.0243616907005151
3965790	4913	select query which returns exect no of rows as compare in values of sub query	select ... from student s     inner join (         select 'rajesh' as sname         union all         select 'rohit'         union all         select 'rajesh') t on s.sname = t.sname 	0.000235850573633101
3966516	33491	mysql join with 3 tables and empty rows	select    profiles.id,    profiles.company,    group_concat(distinct cast(rubrics.id as char) separator ', ') as rubric,    group_concat(distinct cast(rubrics.title as char) separator ', ') as rubric_title,    profiles.user_id  from    profiles left join   profiles_rubrics  on  profiles_rubrics.profile_id=profiles.id left join   rubrics   on  profiles_rubrics.rubric_id=rubrics.id left join   users on  users.id=profiles.user_id  where    users.profile_online is not null    and users.role_id!=1  group by    profiles.id 	0.0227707739567577
3966694	20212	change varchar data type to number in oracle	select to_number(replace('12345,6789123', ',', '.')) from dual; 	0.00775133914152209
3967665	8185	how can i copy a row into same table with sql server 2008	select *, -id 	0.00057637238778178
3968276	13052	column alias oracle 10g	select     user_id, name, role,     case when (select count(*) from usersprojects up #                where up.user_id = u.user_id) > 0           then 'true' else 'false' end assigned from users u 	0.748182338499101
3972007	39988	exclude results from join where duplicate keys match occur	select t1.firstkey, t1.secondkey, t1.thirdkey, t2.firstkey, t2.secondkey, t2.thirdkey, t1.additionalcolumns, t2.additionalcolumns, count(*) from ( select         t1.firstkey, t1.secondkey, t1.thirdkey,        t2.firstkey, t2.secondkey, t2.thirdkey,        t1.additionalcolumns, t2.additionalcolumns from         t1 join t2 on t1.firstkey = t2.firstkey            and t1.secondkey = t2.secondkey           and t1.secondkey is not null union select         t1.firstkey, t1.secondkey, t1.thirdkey,        t2.firstkey, t2.secondkey, t2.thirdkey,         t1.additionalcolumns, t2.additionalcolumns from         t1 join t2 on t1.firstkey = t2.firstkey            and t1.thirdkey = t2.thirdkey           and t1.secondkey is null ) group by t1.firstkey, t1.secondkey, t1.thirdkey, t2.firstkey, t2.secondkey, t2.thirdkey, t1.additionalcolumns, t2.additionalcolumns having count(*) = 1; 	0.000243022166863256
3975030	1755	can sqlbulkcopy create a table from a sql selection	select      1,      [columnname],     [columnname]... from tablename 	0.0178933935330886
3975803	33471	do not repeat (distinct) one column on a table with mysql	select    prod_list.id,    prod_list.prodname,   max(prod_pict.pict_file) as `pict_file`, from    prod_list inner join   prod_pict on   prod_list.id = prod_pict.prod_id group by   prod_list.id,   prod_list.prodname 	0.000948085395124281
3978124	38302	sql select query for a total and parts building the total	select    dbo.job.batchid,   count(dbo.job.oid) as total,   count(case when jobstatusid = 1 then 1 end) as [ready to book],   count(case when jobstatusid = 2 then 1 end) as [pending],   count(case when jobstatusid = 3 then 1 end) as [booked],   count(case when jobstatusid = 4 then 1 end) as [cancelled],   count(case when jobstatusid = 6 then 1 end) as [callback],   dbo.jobbatch.batchdate from   dbo.job   inner join dbo.jobbatch on dbo.job.batchid = dbo.jobbatch.oid group by   dbo.job.batchid,   dbo.jobbatch.batchdate having  (dbo.jobbatch.batchdate > convert(datetime, '2000-01-01 00:00:00', 102)) order by   dbo.jobbatch.batchdate,   total desc 	0.000324360483161103
3978670	27267	oracle 10g - flatten relational data dynamically	select b.* from b, a where b.a_id = a.id and a.enabled = 1 	0.59386730197255
3979428	15296	writing a sql query in mysql with subquery on the same table	select id,        count(distinct archdetails.compname) from svn1 s1,      svn3 s3,      archdetails a where s1.name='ant' and       s3.name='ant' and       a.name='ant' and       type='bug' and       s1.revno=s3.revno and       s3.compname = a.compname and       ( (startdate >= sdate and startdate<=edate) or         (sdate <= (select max(date)                      from svn1                      where type='bug' and                            id=s1.id and          edate>=(select max(date)                    from svn1                    where type='bug' and                    id=s1.id)) or         (sdate >= startdate and edate<=(select max(date)                                           from svn1                                           where type='bug' and                                           id=s1.id)) ) group by id limit 0,40; 	0.15410253241595
3980462	23153	how to compare two tables column by column in oracle	select * from  ( ( select * from tableinschema1   minus    select * from tableinschema2) union all ( select * from tableinschema2   minus   select * from tableinschema1) ) 	0.000221115587023681
3980622	33309	sql server 2008: i have 1000 tables, i need to know which tables have data	select  [name]      = o.name     ,     [rowcount]  = sum(p.row_count) from    sys.dm_db_partition_stats p inner join         sys.tables o     on p.[object_id] = o.[object_id] where   index_id    <= 1  group by o.name order   by 2 desc 	0.0107552489880061
3982860	5289	sql server database max row rowversion	select @@dbts 	0.0480424825516836
3983015	28445	sql list game database by most likes	select appinfo.title, appinfo.description, appinfo.username, appinfo.genre,      sum(appratings.rating) as totalscore from appinfo left join appratings  on appinfo.id=appratings.app_id  group by appinfo.title, appinfo.description, appinfo.username, appinfo.genre order by totalscore desc ; 	0.00283691108287303
3983325	38162	calculate distance between zip codes... and users	select zip from zipcode where geom && expand(transform(pointfromtext('point(-116.768347 33.911404)', 4269),32661), 16093) and distance(    transform(pointfromtext('point(-116.768347 33.911404)', 4269),32661),    geom) < 16093 	0.00147903254800303
3985918	18934	using t-sql to select a dataset with duplicate values removed	select tmp.* from (     select *, row_number() over (partition by [time] order by [time]) as rownum     from raw_data ) as tmp where tmp.rownum = 1 	0.0090750587134788
3986447	19516	mysql join, empty rows in junction table	select t2.b, t2.b_name, max(if(a=2, a, null)) as a from t2      left outer join t3           on t3.b = t2.b group by t2.b order by b asc; 	0.0153338379653518
3990527	35963	how to check which cache features are turned on? [php/mysql]	select count(*) from `users` 	0.00732990410436626
3991238	27106	sql - patient with an office visit one year before the most recent one	select * from patients p where      datediff(d,               (select min(appointmentdate) from appointments a where a.patientid = p.patientid),              (select max(appointmentdate) from appointments a where a.patientid = p.patientid)) >= 365 	0
3991377	25628	sql select master records and display number of detail records for each	select mt.id, mt.name, mt.age, count(d.masterid) as [#subjects] from mastertable mt left outer join detail d on mt.id = d.id group by mt.id, mt.name, mt.age order by mt.id 	0
3993262	13910	mysql check id whether is in another table	select table1.* from table1     left join table2         on table1.id = table2.tableone_id where table2.tableone_id is null 	7.87555030617804e-05
3994205	1224	sql query help: returning distinct values from count subquery	select number from notes  where result = 'na' group by number having count(result) > 25 	0.443745715833832
3995535	30147	what is the sql query to show the number of tables in a database?	select count(table_name) from information_schema.tables where table_schema = 'database_name' 	0.000600075149884638
3995862	26869	bulk add quotes to sql values	select ... where column in (?,?) 	0.0338448132607847
3996075	38011	sql query to find fifth record	select top 1 * from (select top 5 * from table t order by column asc) order by column desc 	0.0315736458720961
3996999	23895	sql query: for each value, determine the percentage of rows that contain the value?	select     notecount,     count(*) contactswiththisnotecount,     count(*) / (select count(*) from contacts) percentagecontactswiththisnotecount from      contacts group by     notecount 	0
3997287	38944	inserting sql data into linked (foreign key) tables in sqlite	select last_insert_rowid() 	0.000287947462257551
3997344	10941	select as problem	select *  from     (     select         t1.[user1], t1.[user2],(cast(t1.[total_event_duration] as decimal))/(cast (t2.[total_events_duration] as decimal)) as buddy_strength          from [cdrs].[dbo].[aggregate_monthly_events] as t1              inner join [cdrs].[dbo].[user_monthly_stats] as t2                  on t1.[user1] = t2.[user1]      ) foo         where foo.buddy_strength > 0.02 	0.734373993065996
3998379	33278	how to query for a value from the last month of each quarter?	select   year,   quarter,   (     select sum(cast(aum_assetvalue as money))        from assetundermanagement      where year(aum_timeperiod) = i.year            and month(aum_timeperiod) = i.lastmonthinquarter   ) as total_assetvalue from   (   select     year(aum.aum_timeperiod)        as year,     datepart(q, aum.aum_timeperiod) as quarter,     max(month(aum.aum_timeperiod))  as lastmonthinquarter   from     assetundermanagement as aum, lineofbusiness   where     aum.lob_id = lineofbusiness.lob_id     and lineofbusiness.lob_name = 'asset management'    group by     year(aum.aum_timeperiod),     datepart(q, aum.aum_timeperiod)   ) as i 	0
4000895	31912	flattening columns in a one-to-many relationship in oracle 10g	select a.prjid,          wm_concat(b.userid) as userids     from table_1 a     join table_2 b on b.prjid = a.prjid group by a.prjid 	0.191251583670213
4003056	2146	mysql 2 queries into 1	select id, issue,(select count(issueid) as count from sendbook where (issueid = issue)) as total  from issue where disabled='0'  group by issue  order by issue desc; 	0.0147039147911662
4003277	39374	getting top distinct records in mysql	select albumownerid, albumid, albumcsd from album where albumcsd in (select  max(album.albumcsd) as maxvonalbumcsd from album group by album.albumownerid); 	0.00182105400134343
4004104	29768	select data along with sum of a column	select name, supplier, amt from transact t group by name, supplier with rollup; 	0.000374840004178687
4004229	3355	how do i view the auto_increment value for a table	select `auto_increment`   from `information_schema`.`tables`  where `table_schema` = schema()    and `table_name` = 'tbl_name'; 	0.00898021405618179
4005310	2946	mysql multiple group bys, order by one group by item?	select product_id, min(auctions.id) auctions inner join products on auctions.product_id = products.id inner join product_groups on products.group_id = product_groups.id inner join product_images on products.id = product_images.product_id where products.group_id = '1' group by products.id order by auctions.id asc limit 10 	0.00522377001051553
4010311	7164	how to check if all fields are unique in oracle?	select mycolumn, count(*) from mytable group by mycolumn having count(*) > 1 	0.000116771374698253
4010766	2387	retrieving "likes" tied to users from a database	select  e.id, e.name, l.userid from entries e left join likes l on l.entryid = e.id where l.userid = 1  order by e.name 	9.61583105490672e-05
4011071	31433	php mysql query to get most popular from two different tables	select `p`.*, sum(`v`.`views`)+`p`.`views` as `totalviews` from `afrostarprofiles` `p`  left outer join `afrostarvideos` `v` on `p`.`id` = `v`.`artistid` group by `p`.`id` order by sum(`v`.`views`)+`p`.`views` desc 	0
4011944	2015	mysql select zipcodes within x km/miles within range of y	select zipcode from zipcodes where distanceformula(lat, long, 4.808855, 52.406332) < $range 	0.000423323791051102
4012353	19252	mysql join on record that might not exist	select <columns> from table1  inner join table2 on table1.id = table2.table1_id left join table3 on table1.id = table3.table1_id where coalesce(table3.column1, '') != 'foo' and <other_conditions> limit 1 	0.0558120311239831
4012525	31679	sql server count of	select     order.ordertypeid,     count(order.ordertypeid) as 'count1',     count(distinct order.productid) as 'count2' from      order group by order.ordertypeid 	0.143652738272214
4013136	22833	count multiple appearances in distinct statement with two parameters?	select company_id, count(distinct person_id) from mytable group by company_id having count(distinct person_id) > 1 	0.112781763058026
4014368	23617	the result of [datetime + 420./1440] (7 hours) is wrong (precision in ms is lost)	select dt, dateadd(hour, 7, dt) as dt_new from #t1 	0.0340403137611861
4016271	21422	sql union on 2 table variables where date is same but other data is not	select company, date, type, select from datatable  union all  select company, date, type, select from datetable     where exists (select * from datatable where company = datetable.company and date = datetable.date)     and not exists (select * from datatable where company = datetable.company and date = datetable.date and type = datetable.type) 	0.00067809208349923
4016477	38248	rows to field level in query?	select  orders.name,  orders.date, (select comment +', ' from ordercomments where ordercomments.orderid = orders.orderid for xml path('')) from orders 	0.0248338798190129
4017407	2956	sql - retrieve values in a single query with multiple where clauses	select sum(case when l.lastlogin >= date_sub(current_date, interval 3 day) then 1 else 0 end) as within_3,        sum(case when l.lastlogin >= date_sub(current_date, interval 7 day) then 1 else 0 end) as within_7,        sum(case when l.lastlogin >= date_sub(current_date, interval 21 day) then 1 else 0 end) as within_21   from login l 	0.00514923814716237
4017528	7709	how to get all tables name's in sqlce database?	select table_name from information_schema.tables where table_type <> 'view' 	4.82885887215036e-05
4017808	16990	multiple mysql queries and fatching min price from a table	select min(price) from product_prices p, product_categories c where p.product_id=c.product_id and c.category_id = $category_id 	0.00126433205638778
4018123	358	export a mysql table via join?	select      us.id,     concat_ws(' - ',cats_sic_us.sic,cats_sic_us.category) as sic_cat into outfile '/tmp/results.csv'     fields terminated by ',' optionally enclosed by '"'     lines terminated by '\n' from     us     inner join cats_sic_us on us.sic=cats_sic_us.id; 	0.0938302656372947
4018708	29807	select into using union query	select x.*    into [new_table]   from (select * from table1         union         select * from table2) x 	0.231770308896962
4019887	36171	adding values in a table in sql 2008	select i.user,           count(i.priority) as total,          sum(case when i.priority = 1 then 1 else 0 end) as 1,          sum(case when i.priority = 2 then 1 else 0 end) as 2,          sum(case when i.priority = 3 then 1 else 0 end) as 3,          sum(case when i.priority = 4 then 1 else 0 end) as 4,          sum(case when i.priority = 5 then 1 else 0 end) as 5     from issues i group by i.user 	0.0388967181183895
4020690	16410	how to make column to row without an aggregate function in sql server 2005/8?	select * from [studentscores] pivot (   min(score)   for [subject] in ([chinese],[maths],[english],[biology]) ) as p 	0.72642610654275
4021845	4996	sort a query based on omitting a word	select id, name from mytable order by trim(leading 'the ' from name) 	0.00195547374905624
4023841	41143	extract number from the date in pl sql	select to_char(sysdate,'dd') as day from dual 	0.000180971687088783
4025380	3360	transform a parent/child table to a fixed column dimentional table	select     l1.id as id     l1.name as level1     l2.name as level2     l3.name as level3     l4.name as level4 from     reltable as l1         inner join     reltable as l2         on l1.id = l2.parentid         inner join     reltable as l3         on l2.id = l3.parentid         inner join     reltable as l4         on l3.id = l4.parentid 	0.00220089376690499
4025718	7867	build a formatted string in oracle	select to_char (datecol, 'fmmm') from mytable; 	0.233106862252743
4025959	34273	tsql selecting distinct based on the highest date	select invoice, date, notes from table  inner join (select invoice, max(date) as date from table group by invoice) as max_date_table           on table.invoice = max_date_table.invoice and table.date = max_date_table.date 	0
4026381	16144	wordpress - sql query on two custom fields issue	select id ,      max(case when meta_key = 'property_region' then meta_value end) as property_region ,      max(case when meta_key = 'property_bedrooms' then meta_value end) as property_bedrooms from (your query) group by id having max(case when meta_key = 'property_region' then meta_value end) = 'east' and    max(case when meta_key = 'property_bedrooms' then meta_value end) = 4 	0.730828874574424
4026519	1460	how to combine two tables, one with 1 row and one with n rows?	select * from   games g        inner join participants p on p.gameid = g.gameid 	0
4029030	33963	mysql join query	select t1.id,           t1.`name`,           group_concat(t3.detail) as `meal_detail`      from t1 left join t2 on t2.`name` = t1.`name` left join t3 on t3.meal = t2.meal  group by t1.`name` 	0.724110026477687
4030476	37714	how to use select result with like in mysql	select id from ( select id,parent_id from units where ptitle like concat('%',(select ptitle from units where id='".$id."'), '%') ) sub_table 	0.725118913837022
4031717	35249	how to retrieve a set of table data in sql?	select name, phone from numbers where name in ('a','b','c','d','e') 	0.00019899419707687
4032256	22265	add years and move to last day	select add_months(trunc(sysdate, 'yyyy'), 12*11) - (1/86400) from dual 	0
4032778	11142	sql query for pairing terms from one table	select      a.seqid, a.tid, b.tid from        [table] a inner join  [table] b on a.seqid = b.seqid where       a.tid &lt; b.tid order by    a.seqid, a.tid 	0.013970653057878
4033272	1331	how can i delete pseudo-duplicates?	select rowid from( select t.*       ,rowid       ,row_number() over(partition by pkeycol1, pkeycol2                               order by othercol1,othercol2) rn   from tbstage t)   where rn=2 	0.304050675761143
4035157	12031	shifting mysql database values from a couple of columns to rows of entries	select des.response as name, val.response as value from mytable as des join mytable as val using (elementnumber) where des.elementtype = 'entrydes' and val.elementtype = 'entryval'; 	0
4035893	33165	how to write a report with multiple filters for the same field in ssrs	select   case when totallength <= 30 then '0-30'        when totallength > 30 and totallength <= 60 then '31-60'        when totallength > 60 and totallength <= 90 then '61-90'        else '>90'   end as lengthband,   category,   sum(itemcount) as sum_itemcount from   table where   date >= @date   and date <= @date2 	0.011229664085268
4037145	29674	mysql - how to select rows where value is in array?	select t.*   from your_table t  where find_in_set(3, t.ids) > 0 	0.00296680669371328
4038298	37842	using date of type char in where clause	select *  from caddb..incident  where convert(datetime, "date", 112) between convert(datetime, '100401', 112) and convert(datetime, '101001', 112) 	0.206292531416366
4043175	16840	how to 'select' the current identity value for a table?	select ident_current('mytable') 	0
4045609	6419	sql : using group by and max on multiple columns	select t2.catid, t2.attrib1, max(t2.attrib2) from (   select catid, max(attrib1) as attrib1   from test_table   group by catid ) t1 inner join test_table t2 on t2.catid = t1.catid and t2.attrib1 = t1.attrib1 group by t2.catid, t2.attrib1 	0.0143135251065232
4046278	22676	adding column contents in a sql union query	select x.code_desc,        sum(x.item_count)  from (select f.code_desc,               count(f.code_id) as item_count          from foo f          join foohistory fh on f.history_id = fh.history_id         where month(fh.create_dt) = 6           and year(fh.create_dr) = 2010      group by f.code_desc        union all        select b.code_desc,               count(b.code_id) as item_count              from bar b          join barhistory bh on b.history_id = bh.history_id         where month(bh.create_dt) = 6           and year(bh.create_dr) = 2010      group by b.code_desc) x group by x.code_desc 	0.056925174351988
4049797	35012	trouble in find child field from primary field in mysql	select * from students s lef tjoin countries c on s.country_id = c.id left join countries n on s.nationality_id = n.id 	0.000177272119178432
4055502	33251	sqlite -- sum over small sections of column based on index in other column	select date, symbol, sum(oi *  contract_settle) as oi_dollar   from add  group by date, symbol; 	7.46208617653525e-05
4055528	25438	ordering mysql rows from derived columns?	select id, post_text, votes_up, votes_down, date, sum(votes_up + votes_down) as 'votes' from posts order by sum(votes_up + votes_down) 	0.0013581562502274
4056478	435	duplicate results returned from query when distinct is used	select [item_id] from (       select [item_table].[item_id]             , row_number() over (order by [item_table].[pub_date] desc, [item_table].[item_id]) as [row_num]       from [item_table]             join [onetoonerelationship] on [onetoonerelationship].[other_id] = [item_table].[other_id]             left join [onetononeormanyrelationship] on [onetononeormanyrelationship].[item_id] = [item_table].[item_id]       where [item_table].[pub_item_web] = 1             and [item_table].[live_item] = 1             and [item_table].[item_id] in (1404309)       group by [item_table].[item_id], [item_table].[pub_date] ) as [items] where [items].[row_num] between 0 and 100 	0.0232053306396757
4057223	17529	sql query that relies on count from another table? - sqlalchemy	select * from person where personid in    (select personid from appointments    group by personid    having count(*) >= 5) and dob > 25 	0.00355725174994471
4057254	30874	how do you match multiple column in a table with sqlite fts3?	select * from table where table match 'a:cat or c:cat' 	0.0145244534757705
4061279	35232	query for new replies on a comment table?	select    comment from    comment.comment c    join posts using p (post_id)    join user_post_views u using (user_id) where    user_id = ?    and c.comment_time > u.post_last_viewed_by_user 	0.0171067371667959
4061359	10260	mysql select to file	select *   into outfile '/tmp/result.txt' fields terminated by ',' optionally enclosed by '"'  lines terminated by '\n'   from your_table; 	0.140848463650352
4063266	34414	count for each row	select *, (select count(*)     from words     where words.project=projects.id) as pcount  from projects 	0.000245273307904382
4064082	24961	mysql: take all records with meeting_id = x and it's parent is available but don't care if available itself?	select * from people outt   where meeting_id = x and   (parent_id is null or exists (select 1 from people inn where inn.id = outt.parent_id and available = 1)) 	0
4065313	16772	how to select 3 of each results for given catids in mysql	select x.id,        x.catid,        x.product_name   from (select t.id,                t.catid,                t.product_name,                case                   when @catid = t.catid then @rownum := @rownum + 1                  else @rownum := 1                end as rank,                @catid := t.catid           from your_table t           join (select @rownum := 0, @catid := -1) r       order by t.catid, t.product_name) x where x.rank <= 3 	0
4067222	21156	selecting unique records 	select  adrlat, adrlng,         round(3956 * 2 * asin(sqrt(power(sin((39.97780609 - abs(adrlat)) * pi() / 180 / 2), 2) + cos(39.97780609 * pi() / 180) * cos(abs(adrlat) * pi() / 180) * power(sin((-105.25861359 - adrlng) * pi() / 180 / 2), 2))), 2) as distance from    mytable where   adrlng between -105.2680699902 and -105.2491571898         and adrlat between 39.970559713188 and 39.985052466812 group by         adrlat, adrlng having  distance <= 0.30          and distance > 0.00 order by         distance 	0.00299170460329049
4068619	5475	execute mysql query in multiple databases at once	select concat( 'alter table ', a.table_name, ' add index `fields` (`field`);' ) from information_schema.tables a  where a.table_name like 'table_prefix_%'; 	0.0357308293582743
4071811	19564	how to transform vertical data into horizontal data with sql?	select rel_id, group_concat(name) from item group by rel_id 	0.00287513431997711
4073340	20933	using datediff to find duration in minutes	select datediff(minute, starttime, endtime) from exceptions2 	0.00582819864206603
4073824	28511	how to find if a particular timestamp with time zone is within daylight saving or not	select decode(to_char(from_tz(cast (sysdate as timestamp),'cet'),'tzr'), to_char(from_tz(cast (sysdate as timestamp),'cet'),'tzd'),'n','y') is_daylight  from dual 	0.00424549245474114
4075018	24322	sql - joining two tables and counting items	select companyname, count(productname)   from suppliers left join products     on suppliers.supplierid = products.supplierid  group by companyname; 	0.0004393490551819
4076098	25412	how to select rows with no matching entry in another table?	select t1.id from table1 t1     left join table2 t2 on t1.id = t2.id where t2.id is null 	0
4076336	15622	how to get sum from two different tables that are linked to third one	select user_id,        (select sum(point)           from points          where user_id = u.user_id        )        +        (select sum(earning)           from earnings          where user_id = u.user_id            and p.hit in ('yes', 'no')        ) as bb   from users 	0
4076542	9565	sql distinct query	select q.* from questionnaire q inner join (   select top 1 guid, creationdate   from questionnaire   order by creationdate desc ) q2 on q2.guid = q.guid and q2.creationdate = q.creationdate 	0.367273461457552
4077526	16422	how can i get last record from a table?	select * from mytable order by creation_date desc limit 1 	0
4080481	4691	return a sum of values common to an attribute in sql?	select name, sum(value) from mytable group by name 	0
4081651	9250	how to decode password from sys.syslogins table	select name from sys.syslogins where pwdcompare('somepassword', password) = 1 	0.712434562125426
4082635	21104	join 4 tables in db with stored procedure?	select t1.field1, t2.field2, t3.field3, t4.field4 from table t1     inner join table2 t2 on t1.id = t2.id     inner join table3 t3 on t1.id = t3.id     inner join table4 t4 on t1.id = t4.id 	0.606352569795042
4083659	16776	sql server 2005: how to create a tsql as per my business logic?	select * from table_01  join     (select max(transdate) as latestdate, testid, status from table_02             where testid not in                   (select testid from table_02 where status = 0)         group by testid, status) as latesttrans  on latesttrans.testid = table_01.testid order by latesttrans.latestdate desc 	0.584870425429852
4085784	30815	mysql, use two select and order by, new value	select a.id, a.name, a.ad, c.name, c.phone, c.email, (     select b.id_user     as f_user_id     from price_b b     where b.id = a.id     order by b.date desc     limit 1 ) from a_emtp a left join customer c on c.id = f_user_id where a.show = "1" 	0.00895289445378608
4086545	34622	sql display different data from the same table in different rows	select t1.resourceid,     t1.filename as 'ie',     t1.fileversion as 'ie ver',     t2.filename as 'sap',     t2.fileversion as 'sap ver' from v_gs_softwarefile as t1     inner join v_gs_softwarefile as t2 on t2.resourceid = t1.resourceid where     (t2.filename = 'saplogon.exe'     and     t2.fileversion = '7100.3.13.1045')     and      (t1.filename = 'iexplore.exe'     and t1.fileversion < '8') order by t1.resourceid 	0
4087638	29913	sql server 2008: can you have a query where you do a diff on a count from two tables and then output result	select ((select count(*) from business) - (select count(*) from shusiness)) as busminusshus 	0.000234252849640667
4090639	23085	selecting records based on current time falling between programstart and programend	select *     from programs     where clientid = 5         and dateadd(day, 0-datediff(day, 0, getdate()), getdate()) between programstart and programend 	0
4090729	17730	get average of query result	select min(mynumber) as minnumber, max(mynumber) as maxnumber, avg(mynumber) as avgnumber from (select userid, count(userid) as mynumber       from dbo.user2user       group by userid) tmp; 	0.000889736436199674
4090789	10032	sql how to select the most recent date item	select *  from test_table  where user_id = value  and date_added = (select max(date_added)     from test_table     where user_id = value) 	0
4090800	794	determine monthly values of timestamped records	select left(date,7) as the_month, min(price),max(price),avg(price) from fruit_price where fruit_id = 2 and date >= concat(left(date_sub(curdate(), interval 11 month),7),'-01') group by the_month; 	9.65359850538098e-05
4090957	32996	sql query for the following output?	select t.compname, min(t2.version) from test t inner join bugs b   on t.compname = b.compname inner join test t2   on t.compname = t2.compname where bugid = 1 and t.version='1.6' group by t.compname 	0.60875570292047
4093941	37807	remove results of 1 query that appear in another	select * from users left join friendships on friendships.friend_id = users.id where friendships.user_id = ? and users.id not in (   select user_id from active_users ) 	0.000871561274433722
4094073	11194	max() group by (aggregate) function problem with same column values	select isti.itemstockid, isti.date, isti.itemid, isti.currentstock from items_stock as isti join (select max(itemstockid) as itemstockid          from items_stock as ist             join (select max(date) as date, itemid from items_stock where date <= '2010-11-05' and active = 1 group by itemid) as sd on sd.date = ist.date and ist.itemid = sd.itemid         group by ist.itemid     ) as isto on isto.itemstockid = isti.itemstockid; 	0.238042250451772
4094733	14299	how to view a string or update a column on a database table depending on the values of other columns?	select  t.column1         , t.column2         , t.column3         , t.column4                 , t.column5         , t.column6         , coalesce(status1, status2, status3, status4, status5, status6) as dummycolumn from    (           select  *                   , case when column1 is not null then 'status1' else null end as status1                   , case when column2 is not null then 'status2' else null end as status2                   , case when column3 is not null then 'status3' else null end as status3                   , case when column1 is not null and column2 is not null then 'status4' else null end as status4                   , case when column2 is not null and column3 is null then 'status5' else null end as status5                   , case when column2 is not null or column3 is not null then 'status6' else null end as status6           from    table1         ) t 	0
4097384	37767	finding data from specific value in an array in sql	select *     from yourtable     where charindex(' 18,', ' ' + allowedsystems + ',') <> 0 	8.74057139569474e-05
4098012	36911	how to search for multiple values on inner join	select     p1.gameid  from     participants as p1, participants as p2  where    p1.name = 'team1' and p2.name='team2' and p1.gameid = p2.gameid 	0.163047219387752
4098800	38499	oracle sql return true if exists question	select case when max(user_id) is null then 'no' else 'yes' end user_exists   from user_id_table  where user_id = 'some_user'; 	0.749983926655393
4099453	20569	how do i find out what license has been applied to my sql server installation?	select serverproperty('licensetype'), serverproperty('numlicenses') 	0.249329911265103
4099511	722	having trouble tracking unique product views per day	select product_id, count(user_ip) as times, user_ip, date from `product_ip_tracking` group by product_id, user_ip, date order by times desc, product_id 	0.00114145043961871
4100245	14656	mysql like function only works on some tables	select name from table where name like '%' 	0.754114064694629
4106338	34034	distinct sql query	select min(id) as id, [name] from mytable group by [name] 	0.367273461457552
4106568	32013	mysql: get all results that has all this relations	select objects.id, objects.name  from `object_features` left join `objects` on ( objects.id=object_features.object_id) where term_id in ('1','3','4','10') group by objects.id,objects.name having count(objects.id) = 4 	0.000440308020962153
4107252	13894	include subselect only if there is one result using tsql	select    invoice.id,   invoice.totalamount,   oneorder.orderid from    invoice   left join (     select   invoiceid, min(orderid) orderid     from     invoicedetail      group by invoiceid     having   count(distinct orderid) = 1   ) oneorder on oneorder.invoiceid = invoice.id 	0.0829860781682796
4108056	15922	grabbing the matched context from mysql like query	select ...   services.service_name like ? as service_matched,   clients.client_name like ? as client_matched from    ... 	0.0187892875634787
4108166	22266	sql: ordering by how much greater than something is?	select actual_delivery, scheduled_delivery, actual_delivery - scheduled_delivery as difference from tablename order by difference 	0.419985002543026
4109435	16179	how to check for null/empty/whitespace values with a single test?	select column_name   from table_name  where trim(column_name) is null 	0.00567510750277029
4111798	38566	limit in php mssql_query?	select top 20         e.name,         e.id,         e.startdate    from events e 	0.633393158390426
4113246	7470	how to get the cartesian product in mysql for a single table	select   f.id,  f.tshirt,  color.option_id as color_option_id,  color.option_name as color_option_name,  color.value_id as color_value_id,  color.value_name as color_value_name,  size.option_id as size_option_id,  size.option_name as size_option_name,  size.value_id as size_value_id,  size.value_name as size_value_name from   foo f inner join foo color on f.id = color.id and f.value_id = color.value_id and color.option_id = 2  inner join foo size on f.id = size.id and size.option_id = 3 order by   f.id,   color.option_id, color.value_id,   size.value_id, size.value_id; 	0.000534094743611329
4113517	1250	what is the right way to organize communication of two clients with one table?	select for update 	0.0192116757554103
4114579	15552	how to use order by field with subquery in mysql?	select ua.* from user_actions ua inner join users u on ua.user_id = u.id order by u.name 	0.590456182602331
4114940	31469	select random row(s) in sqlite	select * from table order by random() limit x 	0.010317066344173
4115006	6414	sql child relation query help	select p.*   from parent p  where exists(select null                 from child c                where c.parentid = p.id                  and c.date <= '2010-10-13')    and not exists(select null                     from child c                    where c.parentid = p.id                      and c.date > '2010-10-13') 	0.71341370609884
4115977	13537	mysql: selecting foreign keys with fields matching all the same fields of another table	select from the_table where gid in ('g1','g2') group by pid having count(*) = 2 	0
4119241	5281	php/sql: select one per dialog_id	select * from users_pm_in where uid = '$user' group by dialog_id order by id desc 	0.00442609225891281
4121092	23494	join a cursor or record set in oracle	select c1.id,        c2.name   from (select * from emp where ename = 'king') c1,        (select * from dept where dname = 'accounting') c2  where c1.deptid = c2.deptid 	0.381924268842755
4122124	10883	mysql count problem	select count(contract.contract_notesid) + count(quotation.contract_notesid) from contract join quotation on contract.contract_notesid = quotation.contract_notesid where contract.contract_notesid = '48' 	0.728942343722663
4122149	13531	how to select a period of time in mysql?	select * from rapoarte where date(ziua) between "2010-01-12" and "2011-01-14" 	0.00170924353779
4122386	19044	convert hours to minutes, sql server 2005	select datediff(mi, convert(datetime, '10:20'),  convert(datetime, '17:00')) 	0.00524487930260858
4123268	20180	rows processed statistics information in sql server 2005	select      * from      sys.dm_exec_query_stats  qs     cross apply      sys.dm_exec_sql_text(sql_handle) st 	0.0426550001152548
4123369	12906	sql select - combine the data from the column into one and run distinct on it	select distinct coach from ( select coach1 as coach from tablex  union all  select coach2 as coach from tablex)  where coach <> 0 	0
4124018	41031	sql query max with sum	select id from table1  where ([field1]+[field2])=(     select max([field1]+[field2]) as expr1     from table1) 	0.32957770591608
4125121	33927	php mysql custom blog, listing categories	select *, count(*) as category_post_count from post_categories left join posts   on posts.category_id = post_categories.category_id group by category_name; 	0.392723067197433
4125868	29250	select sales by user pairs	select  ss1.userid, ss2.userid, sum(sales) from    session ss1 join    session ss2 on      ss2.sessionid = ss1.sessionid         and ss2.userid < ss1.userid join    sales s on      s.sessionid = ss1.sessionid group by         ss1.userid, ss2.userid 	0.00154766096810214
4126146	35366	how to select the first post using mysql	select user_id, min(post_id) as firstpostid from posts where user_id in (1, 2) group by user_id 	0.000901428937966642
4126225	37899	mysql average of 2 columns using where and group by year(), month()	select year(my_date) as year,     month(my_date) as month,     average(min_amount) as min_avg,     average(max_amount) as max_avg from table_1 where (my_date >= "$start_year-$start_month-01")     and (my_date <= "$end_year-$end_month-31")     and (name = $name) group by year, month 	0
4126771	34473	populating percentile data using a mysql query (pic)	select ... percentage as 100*occurrences/sum(occurrences) ... 	0.208936898532381
4127448	2093	how to do query with timestamp?	select date(`insert`) as day, count(*) as cnt from your_table group by day 	0.111474910626122
4127584	23937	how do i enforce sql join conditions across multiple joined rows?	select * from tournaments where id in ( select tournaments.id   from tournaments inner join games on tournaments.game_id = games.id   group by tournaments.id   having min(games.event_date) >= now() ) 	0.0132774927119504
4127649	273	selection of test's last attempt from students	select idstudent, idtest, max(attempt) from studenttable where idtest = @testnumber group by idstudent, idtest 	5.56099406876969e-05
4131644	40474	how can i get the last 10 records	select * from your_table order by your_timestamp desc limit 10 	0
4131707	18484	mysql, i have two large fields, which when records are looped and displayed make site slow	select left(somefield, 450) as somefield 	0.0135067798644873
4132631	8764	mysql how can i speed up with function field > x and field < y	select  padid  from    (         select  *         from    pads         where   removemedate = '2001-01-01 00:00:00'          ) as subquery where   catid >= 0 and catid <= 11  order by          versionadddate desc  limit   0, 20 	0.193266950323838
4133433	28315	trying to find an elegant way to split data into groups in sql server 2005 / ssrs	select 'q' + cast(ntile(5) over (order by customer_spend) as varchar(1)) as quintile 	0.0138337916124124
4134872	23648	postgres if statement fails	select    case status     when 'l' then edate      when 'c' then 'wrong date'    end as date  from    campaigns; 	0.732704351644155
4135860	4647	mysql select between an unknow number of date intervals	select `games`.* from games join rounds on (`games`.`date` < `rounds`.`end_date` and `games`.`date` > `rounds`.`start_date`); 	0.000129173246839512
4137030	22033	select from multiple rows	select     distinct a.* from     ad_values v,     ad a where     v.sid = a.id and     (           (v.m_value='bmw' and v.m_input='car') or         (v.m_input='year' and v.m_value='2010') or         (v.m_input='category' and v.m_value='1')     ) 	0.00215367643866542
4138229	18219	ordering a varchar column in mysql in an excel-like manner	select a from test order by a is null or a='', a<>'0' and a=0, a+0, a; 	0.229705123742023
4141000	7271	phpbb3 - get row from insert statement	select last_insert_id() 	0.00238239638868495
4141435	14758	retrieve a list of all tables in the database	select name from sqlite_master where type = 'table' 	0
4141651	2445	turn a list of single-column sql select results into a single line	select a.column1,b.column2,c.column3 from (select column1 from db where country ='usa' and commodity='pork') as a, (select column1 from db where country ='bra' and commodity='pork') as b, (select column1 from db where country ='chn' and commodity='pork') as c 	4.86467346968721e-05
4142102	37839	sql server 2008 - how to automatically drop and create and output table?	select    someint,    somevarchar,    somedate  into dbo.outputtable from sometable 	0.222282997247635
4142408	25227	how to multiply values using sql	select player_name, player_salary, player_salary*1.1 as newsalary from players order by player_salary desc 	0.0264392719874775
4142486	16318	sql: using case to select a field?	select lastname,      case firstname when 'ian' then jobno else -1 end from employees 	0.360097757158857
4143280	13861	mysql - how to insert data in a table which sort of holds the matrix of 3 other tables	select teacher_id, subject_id, class_id      from teacher join subject join class      order by teacher_id, subject_id, class_id 	0
4147110	12606	optimal way to join three tables in sqlite	select bookmarks.suid, title from bookmarks   inner join user using (suid)   where isfavorite = 1   and suid in (select suid from history order by lastused desc limit 15); 	0.479244925716275
4147482	30569	"people you may know" sql query	select u.id, u.email, u.name, u.etc from friendships as f1 inner join friendships as f2     on f1.friend_id = f2.user_id inner join users as u     on f2.friend_id = u.id where f1.user_id = @userid 	0.381296743723074
4147666	32459	how to filter a query to show only results where a column can't be converted to int	select mycolumn from mytable where isnumeric(mycolumn) = 0 	0.0279746201013435
4148001	39218	generate and combine for xml auto	select     ( select * from rp for xml auto, type) ,    ( select * from ind for xml auto, type)   for xml path('root') 	0.00339484428827852
4151077	31841	sql to pull data sorted by column then sort it another way	select sq.* from (     select loc.* from `location` as loc order by loc.usedby desc limit 0, 15 ) as sq order by sq.name 	0
4151572	18424	using different columns values twice in a single sql query?	select user.user_id,        node.name user_name,        user.birthday,        (select node.name from node where node_id = vote.node_id) as movie_name   from user   join node on user.user_id = node.user_id   join vote on vote.user_id = user.user_id 	0.000446463846285429
4153392	26260	mysql has all values	select x.* from article x inner join (select t.article_id, count(t.article_id)   from articletopics t   where t.topic_id in ([your_list_of_topics])   group by t.article_id   having count(t.article_id)>=[number of elements in [your_list_of_topics]]   order by count(t.article_id) desc   limit 0,100) as ilv on x.id=ilv.article_id 	0.00204528992653834
4154355	38274	mysql help - writing a query to show productsthat are in more than one category, as long as they are in a specific category	select distinct   pc.cat_id from  product_category pc inner join (  select prod_id from product_category where cat_id = 100 ) cards on cards.prod_id = pc.prod_id; 	0.000139713876283626
4154522	12532	dynamic order by select with multiple columns	select * from products order by  case when @sortindex = 1 then price end asc, case when @sortindex = 2 then price end desc,  case when @sortindex = 2 then title end asc 	0.0893646956972374
4155733	5826	t-sql query w/ grouping	select  distinct(t1.name),    t2.id,    t2.name from table1 t1 inner join table2 t2 on t1.id = t2.id 	0.790128392517537
4155827	38834	postgres query problem, need to select unique values	select  * from    clients where   id in         (         select  clientid         from    campaigns         where   status in ('l', 'p')         )         and id not in         (         select  clientid         from    campaigns         where   status not in ('l', 'p')         ) 	0.186392074369671
4156179	25998	php max number of days in a pool of dates	select date_format(`time_duration`, '%a') as `max_days`,     count(*) as `day_count` from `timeduration` group by `max_days` order by `day_count` desc limit 1 	0
4156300	333	selecting values from multiple tables	select          c.*, r.* from courses    c   left join     response r   on            r.userid = c.userid where           r.userresponse = null 	0.000267310106234321
4157797	39759	t sql conditional string concatenation	select case           when len(p.street_number) > 0 then p.street_number + ' '           else ''         end +        case           when p.street_ext = 50 then '1/2'          when len(p.street_ext) > 0 then ''          else p.street_ext        end + ' ' +        case           when len(p.street_direct) > 0 then p.street_direct + ' '          else ''        end +         case           when len(p.site_street) > 0 then p.site_street + ' '          else ''        end  +         case           when len(p.site_address) > 0 then p.site_address + ' '          else ''        end as full_address from parcel p 	0.776472494547116
4157836	35273	how to do joins with conditions?	select contest.user_id,         contest.pageviews,         roles.role_name,         locations.city,         locations.state from ((contest  inner join users  on contest.user_id = users.id)  inner join roles  on users.role_name = roles.role_name)  inner join locations  on users.location = locations.location_name where roles.type1="y" 	0.653552212442961
4158798	1173	how can i pull records from several different tables into a single view in sql server 2008 r2?	select (select count(thisfield) from thistable) as thiscnt, (select count(thatfield) from thattable) as thatcnt, [etc.] 	0
4160315	8330	join on other table with date range having count 0	select distinct id roomid from room r where isdouble = 1  and not exists    (select * from booking     where room_id = r.id       and date_from <= @enddaterange       and date_to >= @startdaterange) 	0.000491799947097734
4160339	31147	sql sum() with multiple level joins	select  subquery.avalue, sum(subquery.fvalue) from    (         select a.value as avalue, f.key, f.value as fvalue         from a         inner join b on b.key = a.key         inner join c on c.key = b.key         inner join d on d.key = c.key         inner join e on e.key = d.key         inner join f on f.key = e.key         group by a.value, f.key, f.value         ) as subquery group by subquery.avalue 	0.756612729552641
4160453	22077	sql query for getting top x 'distinct' values of one field when sorting by another?	select    id as mydistinctvalue,    min(intfld) as mysort from   mytable group by id order by mysort 	0
4161722	4279	mysql select statement from two tables	select  title,          category_title from    topics t inner join         categories c    on t.category_id = c.category_id 	0.00867810530824948
4162215	5047	generating a list of years/months in mysql	select    year(post_date) as yr, month(post_date) as mn, count(id) as count from      wp_posts where     post_status = 'publish' and     post_type = 'post' and     post_parent = '0'  group by year(post_date), month(post_date) 	0.0749421638632094
4162681	30439	how do you sort fields which have numbers in a mathematical order	select * from users order by cast(substr(name from 2) as unsigned) 	0.0011584638593716
4163047	10433	how to use case together with date interval?	select if (datetype  = 'h',             date_sub(date('2010-09-10'), interval 1 week),            date_sub(date('2010-09-10'), interval 1 year))         as wdt; 	0.478686556695471
4163697	6569	sql query for distinctive values (entries)	select distinct tags from mytable; 	0.00596852638719088
4163821	28604	joining one table to many using joins	select      a.name,      b.office,      c.firm,      d.status from      job a join depts b on a.office = b.ref join firms c on b.firm  = c.ref join statuses d on a.status = d.ref 	0.0377719531724336
4164580	31642	intersection in mysql	select     a.id as id from     (select id from wp_posts where post_type = 'post' and post_status = 'publish' and id in (select object_id from wp_term_relationships, wp_terms where wp_term_relationships.term_taxonomy_id =8 or wp_term_relationships.term_taxonomy_id =18)) as a,     (select id from wp_posts where post_type = 'post' and post_status = 'publish' and id in (select object_id from wp_term_relationships, wp_terms where wp_term_relationships.term_taxonomy_id =18 or wp_term_relationships.term_taxonomy_id =18)) as b where     a.id=b.id 	0.312730180384522
4164876	18350	select all rows that have the tag x and y for filter results	select product     from tags    where tag in ('x', 'y') group by product   having count(*) = 2 	0
4165490	22639	stored procedure to get the count using 2 tables	select merchantname, count(1) from merchants, emails where merchants.id = emails.id and emails.signedup = 'yes!' group by merchantname; 	0.00436102126911546
4166650	10499	how do you perform a search on a 1-to-many relationship when the criteria could be on either table?	select     salepersonid, firstname, lastname, ts1.datelastwent,   ts2.city, ts2.state  from         salesperson inner join  (select     salepersonid, max(datelastwent) as datelastwent  from tradeshow   group by salespersonid  ) as ts1 on (salesperson.salepersonid= tradeshow.salepersonid) inner join tradeshow ts2 on   (ts2.salepersonid = ts1.salepersonid and ts2.datelastwent = ts1.datelastwent) where ts2.city = 'cityname' 	0.358142740697595
4166676	37184	one to many relationship - returning only results where all rows in a linked table match a certain criterion without using a correlated subquery	select * from message where id not in (     select m.id     from message m     join order o on m.order_id = o.order_id     join review r on o.order_id = r.order_id     join user u on r.user_id = u.user_id                 and u.role_id is not null ) 	0
4171731	11986	sql query a word inside field	select * from table where willingness like '%shopping%' 	0.288349196677453
4171820	19090	retrieve only numbers using sql query	select column_name from table_name where column_name regexp '^[0-9]+$' 	0.00251716015494756
4172166	31052	is there something more efficient than joining tables in mysql?	select  a.entity,     a.located_in,     a.border from    my_table a where   a.border in (select b.entity from my_table b where b.entity = 'russia' ) and     a.located_in = 'asia' 	0.375104564257716
4172351	35491	divide two dates into periods	select  greatest(period_start, @vacation_start),         least(period_end, @vacation_end) from    mytable where   period_start <= @vacation_end         and period_end >= @vacation_start 	0.000142917243384896
4175603	6188	how to query 3 tables in a single query?	select       p.* from       posts p      inner join linker l on l.postid = p.id      inner join categories c on c.categoryid = l.categoryid where       c.name = 'entertainment' 	0.0212713886143187
4176385	40188	mysql select query based on another tables entries	select t1.*  from table1 t1 join table2 t2 on t1.product_id = t2.product_id where t2.active = 'y' 	0
4180320	15882	select the next/prev mysql	select * from items where created >= current_item_created and id >= current_item_id order by created asc, id asc limit 1,1 select * from items where created <= current_item_created and id <= current_item_id order by created desc, id desc limit 1,1 	0.173517411262291
4181125	4450	how do i concatenate the results from multiple join tables into a delimmited list using a single mysql query?	select d.title as doctitle,          group_concat(distinct f.title) as foldertitles,          group_concat(st.title) as searchtagtitles     from documents d     join docfolder df on df.docid = d.id     join folders f on f.id = dc.folderid     join docsearchtags dsc on dsc.docid = d.id     join searchtags st on st.id = dsc.searchtagid group by d.title 	0
4181766	16458	mysql select max in equation	select        * from          table1 t1 inner join    table2 t2     on        t1.join_field = t2.join_field where         t1.some_field = 1     and       t2.other_field <= (                   select (max(t22.third_field) - 5)                   from   table2 t22               ); 	0.380158990978663
4183348	20702	generating unique values	select top 1 * from sysobjects while @@rowcount > 0 begin     update top 1 keys set key = (select max(key) from keys)+1 where key is null end 	0.0252777612773646
4183967	36905	mysql sorting single field in multi orders	select    * from   users order by ( case status   when 'active'   then 1   when 'inactive' then 2   when 'merged'   then 3   when 'promo a'  then 4   when 'promo b'  then 5   when 'promo c'  then 6   when 'promo d'  then 7   when 'defunct'  then 8   else 9999 end ), ( case category   when 'traditional' then 1   when 'native'      then 2   when 'salvation'   then 3   when 'amm'         then 4   when 'nav'         then 5   else 9999 end ), state; 	0.00286838902433921
4184128	40462	mysql join on two rows	select    articles.article_id from    articles,    article_categories where    articles.article_id=article_categories.article_id and   article_categories.category_id in(3,5) group by   article_categories.article_id having count(*)>=2; 	0.0108083312845592
4184179	38574	mysql: select an extra column categorizing another column based on if statements	select     sessionid,     sessionlength,     if( sessionlength > 10, "big",         if( sessionlength < 1, "small", "medium")) as size from mytable; 	0.000116599254543841
4184770	4020	sorting database result object (array) according to months	select * from db order by month(date) as 'd' desc group by month(date) 	0.00109617795493486
4187978	13064	redirect users based on server traffic	select servercolumn from table order by numberofuserscolumn asc; 	0.00332369800226122
4188793	19848	firebird - select rows with date field having values within this week	select *   from mytable  where adate between          cast('now' as date) - extract(weekday from cast('now' as date))            and          cast('now' as date) - extract(weekday from cast('now' as date)) + 6            ; 	0.000214299600809565
4189256	16536	how to select photoalbums, count photo's, and select one photo per album?	select alb.id as album_id, alb.album_name, alb.album_created,         count(p.id) as pcount,         max(p.thumbnail) as thumbnail from photoalbums alb  left join pictures p on p.album_id=alb.id  group by alb.id, alb.album_name, alb.album_created order by alb.album_name asc 	0.000133728257221513
4189495	17465	sql server 2005: select one column if another column is null or contains a word	select whatever1, whatever2, case when originalemail is null then alternateemail when originalemail like '%domainname%' then alternateemail else originalemail end as email from... 	0.000756891958275126
4191513	39752	select where member only belongs to one customer	select distinct m.message_id as unique_id, m.phone_num, m.body, m.system_time from messages m join subscribers s on m.phone_num = s.phone_num join keywords k on s.keyword_id = k.keyword_id where m.phone_num not    in (       select s.phone_num       from subscribers s, keywords k       where k.client_id != 'xxxx'       and k.keyword_id = s.keyword_id   ) order by m.system_time desc 	0
4191993	7683	return column name where join condition is null	select emp.salary, emp.designation, emp.isactive, p.name  from employee emp left join person p  on p.id = emp.personid 	0.132470430058386
4192467	11898	sql query t find out maximum from name field	select top 1 name, count(*) from table group by name order by count(*) desc 	7.77730504493445e-05
4192659	35496	how can i create a table in sql server 2005 that is totally new for me..?	select * from information_schema.tables where table_type = 'base table' 	0.765060937055377
4195305	2936	summation of daily income possible without cursor?	select i1.asset_no,      sum(i1.amt * cast(isnull(i2.start_date, '2020-12-31') - i1.start_date as int)) as total_amt from @incomeschedule i1 left outer join @incomeschedule i2 on i1.asset_no = i2.asset_no      and i2.start_date = (         select min(start_date)          from @incomeschedule          where start_date > i1.start_date              and asset_no = i1.asset_no     ) group by i1.asset_no 	0.0645749400630361
4196959	19237	convert columns values into multiple records	select  t.date,         unpvt.name,         unpvt.color from     (select  name, colors, color1, color2, color3    from dbo.mytable) p unpivot    (color for [date] in        (colors, color1, color2, color3) )as unpvt join dbo.mytable t on t.[name] = unpvt.[name] where unpvt.color != '' 	5.20763055981347e-05
4197137	25503	sql array being returned as number, not string in coldfusion	select distinct      right('00000' + convert(varchar(5),stateusabb),5),      lkustate.statename          from lkustate inner join tblloc on lkustate.fips_state = tblloc.fips_state          where (lkustate.statename <> 'new brunswick')   union      select '' as stateusabb,      ' all' as statename           from lkustate           order by statename 	0.274551658290261
4197771	10491	picking query based on parameter in oracle pl/sql	select * from table_awesome where (? = 'all' or year = ?) 	0.0407758181832879
4198673	39464	mysql most recent time	select * from your_table order by str_to_date(your_time, '%h:%i%p') desc limit 1 	0.000898945305359536
4199331	5680	select min returns empty row	select min(price), min(year) from tblproduct where price <> '' 	0.0208489790804237
4200064	40828	sql multiple groups - it's possible?	select e.date,     sum(case when e.client = 0 then e.size else 0 end) as cli0-size,     sum(case when e.client = 1 then e.size else 0 end) as cli1-size,     sum(case when e.client = 2 then e.size else 0 end) as cli2-size,     sum(case when e.client = 3 then e.size else 0 end) as cli3-size from entries as e group by e.date 	0.0333665876968787
4201033	25707	mysql add text to a field	select  case when ( instr( your_field,  '(' ) > 0 ) then replace(your_field, '(', '2010 (') else concat (your_field, ' 2010') end  from your_table 	0.0206785556700841
4202828	26332	how to display date in a different format in oracle	select to_char(max(date), 'mm/dd/yyyy') from table; 	0.000219580286015368
4204116	34792	a more efficient mysql statement?	select u.username, count( c.username ) as intimagecount from users u left join content c on c.username = u.username group by u.username 	0.728613082338406
4206051	16494	return the last sub sorted row in a table (sql)	select y, max(x) from [table] group by y 	0
4206056	9410	mysql select distinct where clause	select user_id from mydata where event='aaaaaaaaaaa' union select user_id from mydata where event='xxxxxxxxxxx'; 	0.59572532926949
4206343	2989	mysql query most recent entry	select x.client_code,        time(x.time_date)        x.employee_name,        x.date_time,        x.time_stamp   from transaction x   join (select t.client_code,                max(t.time_date) as max_time_date           from transaction t          where t.date_time = current_date            and t.time_stamp != ''       group by t.client_code) y on y.client_code = x.client_code                                and y.max_time_date = x.time_date  where x.date_time = current_date    and x.time_stamp != '' 	0.000404945008707011
4206555	22490	problem with using count & sum to get data from 2 tables	select d.date, coalesce(a.count, 0) as applications, coalesce(b.count, 0) as clicks from  (     select date from applications     union     select date from leads ) d left outer join (     select date, count(*) as count     from applications      group by date ) a on d.date = a.date left outer join (     select date, count(*) as count     from leads     group by date ) b on d.date = b.date 	0.000969189549715718
4208548	25747	mysql search for names - seperated by space	select * from table where name like 's%' or name like '% s%' 	0.0111306737765237
4208808	3393	mysql: grouping question	select su.user_id, su.group_id, su.stream_update, su.timestamp     from stream_update su         inner join (select user_id, group_id, max(timestamp) as maxtime                         from stream_update                         group by user_id, group_id) m             on su.user_id = m.user_id                 and su.group_id = m.group_id                 and su.timestamp = m.maxtime 	0.787353068633141
4208904	6845	sql select multiple column values	select   p.product_id from   products p   inner join features f1 on p.product_id = f1.product_id   inner join featurenames fn1 on f1.feature_id = fn1.feature_id and fn1.name = 'sex'   inner join featurevalues fv1 on f1.value_id = fv1.value_id and fv1.value = 'male'   inner join features f2 on p.product_id = f2.product_id   inner join featurenames fn2 on f2.feature_id = fn2.feature_id and fn1.name = 'age'   inner join featurevalues fv2 on f2.value_id = fv2.value_id and fv1.value = 'children' 	0.0103575192322426
4209051	6145	sorting results on a mysql table along longitude and then latitude, not a circular radius	select *  from table where long > $the_long or ( long = $the_long and lat >= $the_lat) order by long asc, lat asc limit 34 	0.0373703979461047
4209871	3343	stored procedures - how to return multiple values after an insert	select last_insert_id(), the_column from the_table limit 1; 	0.0138319289213279
4211468	30329	finding the depth of a set of related tables for a given primary key	select coalesce(section4.secname                 ,section3.secname                 ,section2.secname                 ,section1.secname) as deepestsection from (select 'section1' as secname, * from section1) as section1 left join (select 'section2' as secname, * from section2) as section2     on section2.sect1id = section1.sectid left join (select 'section3' as secname, * from section3) as section3     on section3.sect2id = section2.sect2id left join (select 'section4' as secname, * from section4) as section4     on section4.sect3id = section3.sec3tid where section1.jobid = whatever 	0
4212080	29772	subquery returned more than 1 value how to handle it	select top 1 ((camount * cpercentage)/100)  from table1 	0.0438510439166674
4212690	16420	searching multiple tables in query	select  name as businessname        ,description as description from    business where   cityid = '$city'  and     status = 0 and (   categoryid in (select id from category where name like '%$name%')      or  subcategoryid in (select id from sub_categories where name like '%$name%') ) 	0.158719764136127
4214196	4665	sql server return only single row or null	select whatever from     (        select whatever, count(*) as numrecords        from mytable        where something = myquery        group by whatever        having numrecords = 1     ) 	0.00329118984838285
4214265	21271	how to query selection of cells in two columns alternatly hidden or replaced with character	select     id,     case (id % 2) when 1 then enlish else '***' end,     case (id % 2) when 0 then polish else '***' end from     translations 	0.00229263912911185
4214595	4558	select with a sum condition	select users.uid, sum( transactions.credits_earned ) as total from users inner join transactions on users.uid = transactions.uid  group by users.uid having sum(transactions.credits_earned) > 25 	0.145430358615285
4214746	32146	count number of articles in categories	select c.id, c.jcat_name,count(a.catid) as catid from jt_categories c  left join jt_articles a on c.id = a.catid group by c.id 	0.000159338812660779
4214986	14558	count number of comments in articles	select m.id,m.j_surname,a.j_user_id,a.id,a.jart_title, a.jart_description,      a.jart_createddate , count(a.id) as count_comments         from jt_articles a left join  jt_members m on m.id = a.j_user_id  left join  jt_article_comments c on c.artid = a.id                 group by a.id         order by a.jart_createddate desc 	0.000147378303385257
4216506	1874	rounding up in sql server?	select @totalpages = ceiling((select cast(count(*) as float) from #tempitems) / @recsperpage ) 	0.713962644078502
4217449	11380	returning average rating from a database (sql)	select     p.product_id,     p.name,     avg(pr.rating) as rating_average from products p inner join product_ratings pr on pr.product_id = p.product_id group by p.product_id order by rating_average desc limit 1 	0.00122939422999842
4219022	13804	how do i tally votes in mysql?	select voted_for, count(*) from votes v inner join (select voter, max(timestamp) as lasttime from votes group by voter) a  on a.voter = v.voter and a.lasttime = v.timestamp  where timestamp < {date and time of last vote allowed} group by voted_for 	0.150477540661245
4220587	6041	how to reuse a sub-query result in a select more than once	select    turnover,    cost,    turnover - cost as profit from (    (select sum(...) from ...) as turnover,    (select sum(...) from ...) as cost    ) as partial_sums 	0.00415034094538121
4221322	18685	sql select,get most recent entry for each car	select c.*, j.id, max(j.date) from cars c  inner join jobs j on j.car_id = c.id group by c.id 	0
4221921	35634	mysql order by "month" with unixtime	select month(from_unixtime(0)); 	0.0231634227858823
4222057	17190	counting distinct records using multiple criteria from another table in mysql	select  count(recipe.id) answer from    recipe inner join         ingredient olives on olives.recipeid=recipe.id inner join         ingredient mushrooms on mushrooms.recipeid=recipe.id  where   olives.name='olives' and     mushrooms.name='mushrooms' and     olives.amount = 1 and     mushrooms.amount = 2 	0
4222616	14968	mysql, need to select rows that has the most frequent values in another table	select *       from comment inner join (select comment.c_id,                    count(*) as cnt               from comment         inner join logs on comment.c_id=logs.c_id              where logs.daterate >= date_sub(curdate(), interval 8 day)                and logs.rated=1           group by comment.c_id) x on x.c_id = comment.c_id   order by x.cnt desc 	0
4222657	16039	query to get list of views that use a certain field in sql server	select * from     sys.sql_modules m     join     sys.views v on m.object_id = v.object_id where     m.definition like '%mytable%'  	5.0117808445408e-05
4223971	40502	mysql: how to convert varchar column containing dates to a date column?	select if(birthday_date rlike '[0-9]{2}/[0-9]{2}/[0-9]{4}',str_to_date(birthday_date,'%m/%d/%y'),str_to_date(birthday_date,'%m/%d')); 	8.82665289631718e-05
4224657	3592	mysql: selecting rows ordered by frequency of value	select    count(firstname) as countfn,    firstname  from people  group by firstname  order by countfn desc 	0
4225075	39921	fetch the top 5 records from 2 tables each using single query	select student.*, student_details.* from student, student_details where student.id = student_details.student_id order by id asc limit 5; 	0
4225528	1408	how to combine multiple true/false rows in mysql	select name, max(flag) from table1 left join table3 on table3.prod_id = table2.prod_id left join table2.loc_id=table1.loc_id group by name 	0.00198869739441821
4225932	29762	query with multiple joins will only return one of my left joins	select       o.order_id,        n.title,        c.first_name,       tdv5.tid,       tdv6.name,       tdv8.name as settlement_month  from orders o       join products p           on o.product_id = p.nid       join node n               on p.nid = n.nid       join customers c          on o.customer_email = c.customer_email       join term_node tn         on tn.nid = p.nid       join term_data tdv6       on tn.tid = tdv6.tid       left join term_data tdv5  on tn.tid = tdv5.tid       left join term_data tdv8  on tn.tid = tdv8.tid where       tdv6.vid = 6 and       tdv5.vid = 5 and       tdv8.vid = 8 	0.488322760486997
4226874	28371	how to sum up a field depending on an other field value?	select id         , name         , sum(case when answer = 1 then values else 0 end) as positive         , sum(case when answer = 0 then values else 0 end) as negative     from mytable     group by id         , name 	0
4226893	13151	mysql fulltext on multiple tables	select *,   match(books.title) against('$q') as tscore,  match(authors.authorname) against('$q') as ascore,  match(chapters.content) against('$q') as cscore from books  left join authors on books.authorid = authors.authorid  left join chapters on books.bookid = chapters.bookid  where   match(books.title) against('$q')  or match(authors.authorname) against('$q')  or match(chapters.content) against('$q') order by (tscore + ascore + cscore) desc 	0.30940168269122
4228843	6331	mysql php - adding three datas and order by	select *, mines + explodes + tags as kills from your_table order by kills desc 	0.0792161226735229
4229986	5776	how to run query through 2 database - sql server 2008	select fname, lname from aa..men intersect select fname, lname from bb..men 	0.486023815474577
4230747	18145	mysql union returning table name	select database() as source, 'collection' as tblname,title as main, id as id, date          from collection where userid = '1234'          union         select database() as source, 'blog' as tblname,body, id, date          from blog where posterid = '1234'          order by date desc 	0.117485905735552
4230782	12000	write a sql query that retrieves all distinct rows having the same value in a column where count of these rows is larger than 1	select   id,   name from test  group by id, name having count(distinct(name)) > 1 	0
4230839	33343	mysql query to get single item and latest associated item	select   t1.*,   t2.* from table1 t1 inner join table2 t2 on t2.table1_id = t1.id inner join (select max(time_added) as time_added, table1_id from table2 group by table1_id) t2a on      t2a.time_added = t2.time_added and t2a.table1_id = t2.table1_id 	0
4238209	17352	sql value is closest or equal to a certain value in a field	select *  from table where abs($postid-postids) = (select min( abs($postid-postids))       from table ) 	0
4238214	33684	sql insert newlines and formatting data	select case when video_title is not null then        video_title + '\n'        else        ''              end +         case when author is not null then        author + '\n'        else        ''           end +        case when url is not null then        url + '\n'        else        ''           end    from videos 	0.587348447434387
4238398	21236	full-text search indexing only on certain rows	select   * from   revisions r where   r.revisionid =      (select       max(mr.revisionid)      from       revisions mr      where mr.documentid = r.documentid) 	0.00551194133065003
4239708	3202	i try to select some rows in tables - and get error	select * from ( select    fname,lname,rollet, row_number() over(order by rollet) as rowid from backup2 ) xx where xx.rowid between 13 and 20 	0.0153833832538922
4239972	16053	using oracle sql to generate nested xml	select xmlelement("results",        xmlagg(xmlelement("row",                   xmlelement("empno", empno),                   xmlelement("ename", ename),                       (select xmlagg(xmlelement("subrows",  xmlelement("row",                                                  xmlelement("empno", empno),                                                  xmlelement("ename", ename)                                                                             )                                                        )                                            )                               from emp                                where empno <> 7839                               )                                                     )              )              )                  from emp  where empno = 7839 	0.748949118013016
4241022	24153	sql aggregate count = 0	select * from items i where not exists(select holdings.item_id               from holdings               where holdings.active = 't'                 and holdings.item_id = i.item_id) 	0.577852732906484
4241427	32281	grouping data in sql server	select name, min(code) from mytable group by name order by name 	0.233602068593276
4242990	30875	mysql: select rows with more than one occurrence	select en.id, fp.blogid, count(*) as occurrences from french.blog_pics fp, french.blog_news fn, english.blog_news en  where fp.blogid = fn.id  and en.title_fr = fn.title  and fp.title != '' group by en.id having count(*) > 1 	0.000277402828545942
4244660	22550	t-sql outer join across three tables	select  q.name, q.description, sum(q.duration) from    (           select  p.name, et.description, duration = 0           from    person p                   cross apply eventtype et           union all                   select  p.name, et.description, e.duration           from    person p                   inner join event e on e.person_id = p.id                   inner join eventtype et on et.id = e.eventtypeid                 ) q group by         q.name, q.description 	0.64934766007029
4246438	10335	in oracle, find number which is larger than 80% of a set of a numbers	select percentile_disc(0.8)  within group(order by integer_col asc)  from some_table 	0
4246615	32925	use a comma-separated string in an `in ()` in mysql	select * form t where c in ('1,2,3'); 	0.458970211972302
4252394	5952	in t-sql, how to reference to table variable in the subquery?	select x.*,        y.num   from @t x   join (select t.collateral_id,                t.m_il_no,                count(*) as num           from @t t       group by t.collateral_id, t.m_il_no) y on y.collateral_id = x.collateral_id                                             and y.m_il_no = x.m_il_no 	0.119621302122736
4254720	15798	mysql count same column multiple times	select  sum( case when w.invoicedate < date_sub(curdate(), interval 10 day) then 1 else 0 end) as '10 days',         sum( case when w.invoicedate < date_sub(curdate(), interval 20 day) then 1 else 0 end) as '20 days' from    tbl_invoice w  where   w.invoiceid not in(                              select  inv.invoiceid                              from    tbl_invoiceallocation inv)  and     w.invoicedate < date_sub(curdate(), interval 20 day) 	0.000712066466877047
4256843	14079	how do you get the index of a node in a left-right tree?	select count(treestructureid)  from treestructures s, (select leftvalue, rightvalue, treeid, parenttreestructureid from treestructures where treestructures.treestructureid = 204260) as data where s.leftvalue <= data.leftvalue and s.rightvalue <= data.rightvalue and s.treeid = data.treeid and s.parenttreestructureid = data.parenttreestructureid 	0.00287096468418013
4256867	15064	joining table variable and derived table	select        t.order   ,convert(nvarchar,temp.[datetime],101) as [datetime]    ,t.status   ,t.domain   ,t.media   ,t.approved        ,t.createdby         from @processtable t join (select max(id) as maxid,order, max([datetime]) as [datetime] from orderdetail od group by order)  temp   on temp.order = t.order  order by temp.[datetime] desc, approved asc 	0.0299809220392788
4256982	34486	2 left joins count in a query	select a.*, count(distinct b.parentid) as catscount, count(distinct c.id) as itemscount .... 	0.66009988983255
4258928	1627	postgressql with rails, using ilike to search a combined two fields?	select concat(fname, ' ', lname) as fullname from table 	0.452448119388641
4259830	12725	select empty dates for no data dates from oracle?	select   dummy_hours.hour,   log_aggregate.metric,   log_aggregate.minimum,   log_aggregate.maximum from (   select to_char(trunc(to_date('08-nov-10', 'dd-mon-yy'))+(level-1)/24, 'dd-mon-yy "-" hh24":00"') hour   from dual connect by level <= 48 ) dummy_hours, (   select to_char(day,'dd-mon-yy "-" hh24":00"') as hour,   round(avg(duration), 2) as metric,   round(min(duration), 2) as minimum,   round(max(duration), 2) as maximum   from log_events   where day between to_date('08-nov-10', 'dd-mon-yy') and to_date('08-nov-10', 'dd-mon-yy') + 2   and day > to_date('08-nov-10', 'dd-mon-yy')   and day < to_date('08-nov-10', 'dd-mon-yy') + 2   and company = 'company a'   and component = 'api layer'   and event_label = 'execution request'   group by to_char(day,'dd-mon-yy "-" hh24":00"') ) log_aggregate where dummy_hours.hour = log_aggregate.hour(+) order by dummy_hours.hour; 	0.000196011619034434
4266164	4424	select the table name as a column in a union select query in mysql	select 'table1' as tablename, text from table1 union select 'table2' as tablename, text from table2 order by date 	0.00317153066325482
4266386	30740	mysql specific query requirement	select date_format(salestime, '%y-%m') as salesmonthyear,        count(*) as salescount from sales group by date_format(salestime, '%y-%m') 	0.412556135419257
4267929	11036	what's the best way to join on the same table twice?	select t.phonenumber1, t.phonenumber2,     t1.someotherfieldforphone1, t2.someotherfieldforphone2 from table1 t join table2 t1 on t1.phonenumber = t.phonenumber1 join table2 t2 on t2.phonenumber = t.phonenumber2 	0.0043256134451487
4268139	34077	how does one do a sql select over multiple partitions?	select *   from transactions  where transaction_date in (date '2010-11-22',                              date '2010-11-23',                              date '2010-11-24') 	0.16104494498605
4269629	23409	swap fields inside an oracle record using couple separator * and elements separator |	select    cola,    regexp_replace(cola, '([^*|]*)\|([^*|]*)(\*|$)','\2|\1\3') as swapped_col from (   select '3456|abc*7890|def*9430|ghi*3534|jkl' cola from dual ) 	0.0940808264976774
4270967	20354	t-sql select sum of two integer column	select tot = isnull(val1, 0) + isnull(val2, 0) from table 	0.00186924391288236
4271170	23435	mysql join to return distinct ids linked from another table	select distinct e.employee_id  from locations l   inner join stores s on s.store_id = l.store_id    inner join employees e on s.manager_id = e.manager_id  where l.location_id = 999; 	0
4271960	35901	sql case statement to check for nulls and non-existent records	select      id = coalesce(a.id, b.id),     name = coalesce(a.name, b.name) from table1 a full outer join table2 b on a.id = b.id where a.id = @id 	0.32003367708015
4272087	5111	sql distinct count of duplicates	select id, firstname, lastname, count(friendid) as friends     from users group by id, firstname, lastname 	0.0245310525522242
4273811	21303	how can i round a date object to the end of the month in mysql?	select last_day(date_add('2010-11-24', interval 3 year)) 	0
4274376	31890	getting uncommited data in transaction in sql server 2005	select * from errorlog with (readpast); 	0.484497596514952
4274412	12211	select records older than latest 100 records from database	select  *     from    table      order by id desc      limit 101 , totalrecords 	0
4276626	32881	query to select all the table names that doesn't have their name in upper case	select * from sysobjects where    upper(name) collate latin1_general_bin <> name collate latin1_general_bin and objectproperty(id,n'istable')=1 and objectproperty(id,n'ismsshipped')=0 	0.000155078743396015
4277632	35527	mysql query data group	select data, count(*)  from   your_table  group by         data 	0.30515003744597
4277721	8766	non-existent tuples in a self-joined table	select a.id, a.fromnode from cpm as a left outer join cpm as b on a.fromnode = b.tonode  where b.fromnode is null 	0.0221763467171106
4277786	8839	get the closest record for every date	select the first record from skucompetition where creationdate is before (input date + one day) order by creationdate so most recent record comes first 	0
4278570	8259	get sum of sales for multiple years in columns	select c.name,     sum(case when o.year == 2008 then price else 0 end) cy2008,    sum(case when o.year == 2009 then price else 0 end) cy2009,    sum(case when o.year == 2010 then price else 0 end) cy2010 from customers c left outer join       orders o on o.customer_id = c.customer_id group by c.name 	0
4280984	5061	how do i search/query multiple tables to return a common result?	select id, name as title, left ([description], 100) as content, webuserid  from dbo.divesites where status = 1      and name like '%wre%' union all     select id, title, left ([description], 100), webuserid  from dbo.media where status = 1      and title like '%wre%' 	0.00102963308456182
4281526	12237	getting products from sql query	select      products.productid, product, descr,      coalesce(products.list_price, p.price) as price,      i.image_path ... 	0.015308413345594
4282729	23274	mysql return group_concat in function	select group_concat(mycolumn) from   mytable where  myid = myvar into @myretvar; return @myretvar; 	0.781811989321424
4282841	10079	how to form a sql query for a one to many relation?	select *  from house h join features f on h.house_id = f.house_id where feature in ('garden','garage'); 	0.0119105828829041
4284359	24729	how to select records close to one in sql?	select * from test order by abs(money - (     select money from test where id = 2 ))  limit 4; 	0.00282019223087882
4285354	34690	how to select with the length of the field / untrim using select	select id     || rpad(otyp, 3, ' ')     || rpad(fname, 8, ' ')     || age  from      myschema.test_table; 	0.00155426195826449
4286216	10402	oracle: how to “group by” over a datetime range?	select case       when extract(hour from tx.datetime) >= 5 then to_char(tx.datetime,'dd-mm-yyyy')      when extract(hour from tx.datetime) between 0 and 2 then to_char(tx.datetime-1,'dd-mm-yyyy')      when extract(hour from tx.datetime) between 2 and 5 then to_char(tx.datetime-1,'dd-mm-yyyy')    end as age,     nvl(sum(tx.amount),0) as sales from transaction tx where tx.datetime > to_date('20100801 08:59:59', 'yyyymmdd hh24:mi:ss')    and tx.datetime < to_date('20100901 09:00:00', 'yyyymmdd hh24:mi:ss') group by case       when extract(hour from tx.datetime) >= 5 then to_char(tx.datetime,'dd-mm-yyyy')      when extract(hour from tx.datetime) between 0 and 2 then to_char(tx.datetime-1,'dd-mm-yyyy')      when extract(hour from tx.datetime) between 2 and 5 then to_char(tx.datetime-1,'dd-mm-yyyy')    end  order by 1 	0.0134357266922738
4286817	40995	postgresql + date format convert yyyy-mm-dd to day, date month year	select    *  from    table_name  where    user_id=('11')  and    to_char(effective_date, 'dy, mon dd, yy') = trim('fri, nov 26, 10'); 	0
4288867	38141	recursive "on duplicate key update"	select date_add(min(a.`date`), interval '1' day) as `free_date` from `activity` a left join `activity` z on z.`date` = date_add(a.`date`, interval '1' day) where z.`date` is null  and a.`date` >= '2009-07-31' 	0.0467124409352236
4290549	21824	how do we know how many columns come from xml variable in sql server 2005	select count(1) from @xmldoc.nodes('row/@*') as t(c); 	0.0177719308854544
4290563	10839	how to count the number of common bidirectional connections in graph	select  t1.user1, t1.user2, 0 as calling_calling, 0 as calling_called, 0 as called_calling, 0 as called_called, count(*) as both_directions  from   (select monthly_connections_test.calling_party as user1, monthly_connections_test_1.calling_party as user2, monthly_connections_test.called_party as calleduser from         monthly_connections_test inner join                       monthly_connections_test as monthly_connections_test_1 on                        monthly_connections_test.called_party = monthly_connections_test_1.called_party and                        monthly_connections_test.calling_party < monthly_connections_test_1.calling_party) t1                        inner join monthly_connections_test as monthly_connections_test_2 on                       monthly_connections_test_2.called_party = t1.user1                       and monthly_connections_test_2.calling_party = t1.calleduser 	0.00016586788630391
4291352	18744	mysql limit 1 on second table with inner join	select tf_threads.*, tf_posts_tmp.* from tf_threads left join (select p1.*            from tf_posts as p1            left join tf_posts as p2            on p1.postid = p2.postid and p1.date < p2.date) as tf_posts_tmp on (tf_threads.thread_id=tf_posts_tmp.thread_id) 	0.0501498913038618
4295860	8675	count within a count	select  count(coursecount) as coursecount from    (     select  studentid, count(courseid) as coursecount             from enrollment             group by studentid             having  (count(courseid) >= 4)) as t 	0.0622407744081712
4296310	27672	query to count values	select p.id as personid,           count(a.personid) as `count`      from persons p left join activepages a on a.personid = p.id  group by p.id 	0.0526647738187515
4296462	10582	how to use sql join where table1 has rows not present in table2	select name, id from record r left join share s on r.id = s.id where s.id is null 	0.0109242932649812
4299007	21803	mysql - and query on joined table	select *, content.contentid as thisid from content left join link_keywords on content.contentid = link_keywords.contentid left join link_countries on content.contentid = link_countries.contentid left join link_sections on content.contentid = link_sections.contentid where status = '1' and typeid = '1' and       content.contentid in (select section3.contentid                             from link_sections as section3                             where sectionid = 3) and       content.contentid in (select section4.contentid                             from link_sections as section4                             where sectionid = 4) group by contentid order by creationdate desc 	0.0349819117564893
4301175	27260	delete mutiple rows with duplicate values	select id,depid,address, distinct name from ... 	0.000573794868933062
4301404	26301	how to export a view data from postgresql/phppgadmin	select      definition  from      pg_views  where      schemaname = 'public'  and     viewname = 'your_view'; 	0.00777008484470218
4301672	4995	find size of a database in oracle	select tablespace_name "tablspace",    file_name "filename",    bytes/1024/1024 "size mb",   maxbytes/1024/1024 "maximum size mb",   autoextensible "autoextensible" from sys.dba_data_files 	0.00757025071159144
4303248	27214	udf to display string as hexcode	select cast( @string as varbinary(max)) 	0.0559507488798712
4304850	31426	oracle - use table of number as filter in where clause	select count( o.pap_id)    into testvar   from pap_operator o  where o.pap_operator_id in (select * from table(activeiteitsac) ); 	0.150776300172086
4305162	9449	retreive a list of records based on time intervals (php/mysql)	select * from table      where current_timestamp >= datesub(startdate, interval 49 hour)     and current_timestamp < datesub(startdate, interval 48 hour); 	0
4305839	17750	mysql table inside join	select amount, sale, returnamount, returned, returndate        from        (        select amount, 1 as sale, 0 as returnamount, 0 as returned, '' as returndate        from sales where billtype='s'        union        select 0 as amount, 0 as sale, amount as returnamount, 1 as returned, date as returndate        from sales where billtype ='r'        ) 	0.58533763898712
4306847	35740	is it possible to use a mysql field value in the where clause?	select questiondescription from questionstable left join actionstable on questionstable.questionid=actionstable.action where actionstable.action is null 	0.396440294553837
4307243	26287	how to group sums by weekday in mysql?	select weekday(t.timestamp) as weekday,          sum(case when t.type = 'a' then 1 else 0 end) as a,          sum(case when t.type = 'b' then 1 else 0 end) as b,          sum(case when t.type = 'c' then 1 else 0 end) as c     from your_table t group by weekday(t.timestamp) 	0.0351603378025391
4307254	35940	how to call specific rows from a table in mysql ? (see the case)	select *  from updates u join accounts_courses_relationship r on u.courseid = r.courseid where r.account_id = {$account_id} 	0.000768839158354551
4310282	32395	sql single table with two columns	select m.memo,      (select top 1 x.id      from checking x      where x.memo = m.memo      order by x.id) as id from checking m group by m.memo 	0.0010831101762969
4310909	484	how can i give the order by in s3 database	select * from second where gibid = '54' and gibview = 'o' order by time_stamp 	0.177607175693663
4314728	11095	mysql select first then limit	select * from table order by id asc , time_stamp desc 	0.0082127614233958
4316676	19882	sqlite select minimum function value of grouped result	select *, distance('+lat+','+lon+', lat, lon) as minmiles from all_restaurants  where restaurant_id || minmiles in  (      select restaurant_id || min(miles) as fewmiles      from (          select restaurant_id, distance('+lat+','+lon+', lat, lon) as miles          from restaurant_master_combined          where lat between $lat and $lat2 and lon between $lon1 and $lon2 and miles < $miles     )      group by restaurant_id  ) order by round(minmiles) asc, company_name asc 	0.00112091417228819
4317037	3184	sql server 2005 - how to take a record from one table and loop through another table looking for match	select  [user]        ,[evaldate]        ,case when ( select  count(*)                     from    [userstartenddates] b                     where   [a].[user] = [b].[user]                             and [evaldate] between [startdate]                                                and coalese([enddate],[evaldate])                   ) > 0 then 1              else 0         end as [isvalid] from    [evaluations] a 	0
4319484	10768	simple sql select query between 2 tables	select u.userid, u.username, count(*) as ratingcount     from usertable u         inner join ratingtable r             on u.userid = r.userid                 and r.ratingvalue = 5     group by u.userid, u.username     order by ratingcount 	0.178521826041989
4319756	38450	mysql query search record in between and list if exits or not	select   coalesce(sum(o.price),0) as price from     (select 2004 as yr          union all          select 2005          union all          select 2006          union all          select 2007          union all          select 2008          union all          select 2009          )          y          left join orders o          on       y.yr = o.year group by y.yr 	0.0343816603437029
4323999	23490	how to do a count query that groups by distinct product	select   productid                            ,          productprice                         ,          count(*) * productprice as totalprice,          count(*)                as quantity from     configure_system where    estimateid='edb95py0z2' and      stepid    =1 group by productid,          productprice 	0.00270548829506377
4329396	24383	mysql select 10 random rows from 600k rows fast	select name   from random as r1 join        (select (rand() *                      (select max(id)                         from random)) as id)         as r2  where r1.id >= r2.id  order by r1.id asc  limit 1 	0
4331368	38291	parse and replace in oracle	select regexp_replace(regexp_replace(regexp_replace(            str,'[^,]*','constant',1,3),'[^,]*','constant',1,9),'[^,]*','constant',1,15) from    (select 'param,value1,str1,param,value2,str3,param,value3' str from dual); 	0.755657451861912
4332798	33243	inner join on 3 tables with sum()	select u.userid,        u.username,        u.realm,        u.cap_size as cap,        h.adhoc,        a.octetsused   from msi_adsl as u   join (select userid, sum(acctinputoctets + acctoutputoctets) as octetsused           from radact          where acctstarttime between '2010-11-01' and '2010-11-31'          group by userid        )    as a on a.userid = u.userid   join (select userid, sum(value) as adhoc           from adsl_adhoc          where time between '2010-11-01 00:00:00' and '2010-11-31 00:00:00'          group by userid        )    as h on h.userid = u.userid  where u.canceled = '0000-00-00'  limit 10 	0.29346880564448
4333659	29233	is it possible to find the repeating patterns in the text stored in mysql?	select   (length(abstract)-length(replace(lower(abstract), 'apple', '')))/5    as occurrences from   textanalysis where   match (abstract) against ('+apple' in boolean mode); 	0.186682855409698
4334514	36623	query transform and pivot	select id, name,       iif(option1_value<>"something","option1 dosn't match",         iif (option2_value<>"something","option2 dosn't match",            iif( option3_value<>"something","option3 dosn't match","no errors")))      as reason from table 	0.678570881273477
4334564	31682	how do i obtain for each distinct primary key occurrence in a table, the first of an ordered set of rows?	select datetime, id, state from table t1   where t1.datetime = (select max(t2.datetime) from table t2 where t2.id=t1.id) 	0
4335568	39028	how to merge unrelated tables, but sort on a common column type?	select * from ( select     `timestamp`,     cast(`value1` as char) as `value1`,     cast(`value2` as char) as `value2`,     cast(null as char) as `text1`,     cast(null as char) as `char1`,     cast(null as signed) as `int1`,     cast(null as signed) as `int2` from `table_a` union select     `timestamp`,     cast(null as char) as `value1`,     cast(null as char) as `value2`,     cast(`text1` as char) as `text1`,     cast(`char1` as char) as `char1`,     cast(null as signed) as `int1`,     cast(null as signed) as `int2` from `table_b` union select     `timestamp`,     cast(null as char) as `value1`,     cast(null as char) as `value2`,     cast(null as char) as `text1`,     cast(null as char) as `char1`,     cast(`int1` as signed) as `int1`,     cast(`int2` as signed) as `int2` from `table_c`) `table_all` order by `timestamp` 	0
4336148	40712	convert sql datetime format	select stuff(convert(varchar, getdate(), 105), 3, 1, '/') + ' ' + left(convert(varchar, getdate(), 8), 5) 	0.126030674240715
4336485	13221	how to extract an element from an xml file?	select cast(x.somexml as xml).value('(simplerulevalue/entityfriendlyname)[1]','nvarchar(1000)') as entityfriendlyname from xmlsource x 	0.00133839385106496
4338662	36067	finding total number of rows of tables across multiple databases	select sum(table_rows) from information_schema.tables where table_name = 'company' 	0
4339123	39091	kohana 3.x: sql-query for entities and all their members	select * from myentity join member on member.foreignkey = myentity.foreignkey where myentity.foreignkey = {$myforeignkey}; 	0.00296556789341606
4341259	34863	removing duplicate rows in 1 transaction id while retaining other transaction item	select  `trans_id`,  `item_name`,  concat(count(*), '/', `total_trans`) as value,  `total_trans`  from mytable  group by `item_name`, `trans_id`, `total_trans` 	0
4342283	19830	mysql: check if data exist inside query	select c.*,           if(v.competitionid is not null, 'voted', 'not voted') as `verdict`      from competition c left join vote v on v.competitionid = c.competitionid                 and v.userid_voter = $currentuserid 	0.245149847935026
4342470	11353	query either field with highest number	select if(a > b, a, b) as max_value   from (select max(up) as a,                max(down) as b           from table) x 	0.00127352679974449
4342708	23864	how to output enum/string when selecting from a int column in mysql	select elt(int_column, 'a', 'b', 'c') from table; 	0.00288594223877256
4343261	30652	join on tables with or (repeating data) - sql server 2005	select t1.guid from t1 join (t2 union all t3) as t on t1.guid=t.guid where t.maintitle like '%water%' 	0.395879371724009
4343270	21397	mysql get union, order by intersection?	select * from recipes  where lower(ingredients) like '%mayonnaise%'  or    lower(ingredients) like '%bacon%' or    lower(ingredients) like '%cheese%' order by lower(ingredients) like '%mayonnaise%' desc,          lower(ingredients) like '%bacon%' desc,          lower(ingredients) like '%cheese%' desc 	0.0903436583658965
4344197	14561	sql query for finding a value in multiple ranges	select case          when date '2010-12-05' between range1_from and range1_to then range1_rate         when date '2010-12-05' between range2_from and range2_to then range2_rate         when date '2010-12-05' between range3_from and range3_to then range3_rate        end as rate   from events  where date '2010-12-05' between range1_from and range1_to     or date '2010-12-05' between range2_from and range2_to     or date '2010-12-05' between range3_from and range3_to; 	0.00109450476773673
4347101	132	how to select an sql index	select column_list from table_name with (index (index_name) [, ...]); 	0.396365486378874
4347761	31671	isolate values based on format in mysql	select * from mytable where mydate not like '____-%__%__' and not like '____/__/__' 	0.00142253631222487
4348583	37476	extract elements in xml to rows in select statement	select col.value('.', 'varchar(20)')  from yourtable  cross apply xmlcolumn.nodes(' 	0.000829374677715752
4350360	5099	select * from table, replace fk's with their name	select pd.name, pc.price     from product as pd         inner join price as pc             on pd.id = pc.productid 	0.000280875410713578
4351043	27254	select only one record for each match	select min(date) as date, resid, med, time, emar from yourtable where date > date_min and date < date_max group by  resid, med, time, emar 	0
4351577	12469	mysql join - select table based on condition	select c.*, a.title from  table1 c  left outer join table2 a   on c.parent_id = a.id and c.parent_type = 0  left outer join table3 p   on c.parent_id = p.id and c.parent_type = 1 where a.id is not null or p.id is not null order by id desc limit 10 	0.0052756310323684
4352772	8224	how can i check if column does not have any values when left joint is used?	select   family.position          , food.meal  from     family left join           food on family.position = food.position where    food.meal is null 	0.506178286698906
4353944	4246	sql - finding transaction that contain 2 or more item using query	select * from transaction t  where t.trans_id in      (select t1.trans_id      from (select *            from transaction             where [name]="i1")  as t1       inner join            (select *            from transaction             where [name]="i2")  as t2       on t1.trans_id = t2.trans_id) and t.name in ("i1","i2") select * from transaction t  where t.trans_id in      (select t1.trans_id      from ((select *            from transaction             where [name]="i1")  as t1       inner join            (select *            from transaction             where [name]="i2")  as t2       on t1.trans_id = t2.trans_id)      inner join            (select *            from transaction             where [name]="i3")  as t3       on t1.trans_id = t3.trans_id ) and t.name in ("i1","i2","i3") 	0.00228301574096984
4354174	17686	mysql problem how to know the number of each color	select color, count(*) as total from images where classification='$request' group by color 	0.000370938312803488
4354367	13948	sql query - sum of data in transaction (for each transaction)	select sum(value)/count(*)  from table 	0.000569336483114873
4354634	21195	select entries bases on multiple entries in another table mysql	select a.carid   from cars        a   join car_names   b using(carname)   join car_attribs c using(nameid)  where c.attribute in('small', 'fast')  group      by a.carid having count(distinct c.attribute) = 2; 	0
4359550	15493	oracle sql find different values in two tables with same schema	select a.col1       ,a.col3   from new_table a  where exists(select 'x'                  from old_table b                 where a.col1 = b.col1                  and decode(a.col3, b.col3, 'same', 'diff') = 'diff'               ); 	5.11097193773778e-05
4363174	34797	adding row_number affects order of rows in rollup	select     foodtype,     foodname,     numitems,     row_number() over     (         partition by foodtype         order by             (case when foodtype is null then 1 else 0 end),             foodtype,             (case when foodname is null then 1 else 0 end),             foodname     ) as rank     from     (         select             foodtype,             foodname,             sum(numitems) as numitems             from food_delivery             group by foodtype, foodname with rollup     ) a     order by         (case when foodtype is null then 1 else 0 end),         foodtype,         (case when foodname is null then 1 else 0 end),         foodname 	0.499891303148342
4363831	18391	order by in sql server 2005	select * into #b1 from a where b = 1 select * into #b2 from a where b = 0 order by 1 desc select * from #b1 union all select * from #b2 order by b desc drop table #b1 drop table #b2 	0.73064412391652
4366793	18045	select only one distinct column	select id_x, min(name) as name from table group by id_x 	0.00053775948355535
4367588	29015	mysql query to find records not present in another table	select d.name  from drivers d where not exists(select * from cars c                   where d.licensenumber = c.licensenumber) 	0.000146415941576045
4367739	13818	advanced select	select * from prices left join (vendors, products)                  on (products.product_id=prices.product_id and vendors.vendor_id=prices.vendor_id) 	0.600778350271745
4369780	14209	sql table variable not existing after creation?	select c.custcode, c.custname   , n.promiseavg, n.shipdate   , d.promiseavg, d.shipdate   , j.promiseavg, j.shipdate   , f.promiseavg, f.shipdate   , m.promiseavg, m.shipdate   , a.promiseavg, a.shipdate   , mm.promiseavg, mm.shipdate   , jj.promiseavg, jj.shipdate   , jl.promiseavg, jl.shipdate   , ag.promiseavg, ag.shipdate   , s.promiseavg, s.shipdate   , o.promiseavg, o.shipdate from @customers c left join @nov n on  c.custcode = n.custcode left join @dec d on  c.custcode = d.custcode left join @jan j on  c.custcode = j.custcode left join @feb f on  c.custcode = f.custcode left join @mar m on  c.custcode = m.custcode left join @apr a on  c.custcode = a.custcode left join @may mm on  c.custcode = mm.custcode left join @jun jj on  c.custcode = jj.custcode left join @jul jl on  c.custcode = jl.custcode left join @aug ag on  c.custcode = ag.custcode left join @sep s on  c.custcode = s.custcode left join @oct o on  c.custcode = o.custcode 	0.207304657458764
4371193	11239	mysql query order by certain values before others	select * from highscores order by completiontime = 0, completiontime 	0.00089581355234344
4372070	27968	trouble combining two sql queries into one	select coalesce(next_due_missed, next_due) as effectivenextdue from table_name  where coalesce(next_due_missed, next_due) > curdate() group by coalesce(next_due_missed, next_due) 	0.0177077819864629
4373627	21221	query to get the list of tables and the number of columns	select t.table_name,          count(*)     from information_schema.tables t     join information_schema.columns c on c.table_name = t.table_name    where t.table_catalog = 'your_database'      and t.table_schema = 'your_schema' group by t.table_name 	0
4374594	26516	how to view all the created databases in a oracle dbms	select * from user_tablespaces; 	0.0304108104447447
4374936	11439	finding all records where a particular field has more than "n" number of characters in oracle	select * from employee where length(address_1) > 40; 	0
4376667	36576	how to get column metadata from a table synonym	select c.* from    sys.columns c    inner join sys.synonyms s on c.object_id = object_id(s.base_object_name) where    s.name = 'projectsyn' 	0.000331331546289571
4377767	4073	complex mysql-query: get name of object, and count and average-value of all grandchildren	select   rc4p.product_id,   rc.rating_category_id,   rc.name,   count(r.rating_id),   avg(r.value) from   rating_category_4_product rc4p,   rating_category rc,   rating_type rt,   rating r where   r.rating_type_id = rt.rating_type_id   and rt.rating_category_id = rc.rating_category_id   and rc.rating_category_id = rc4p.rating_category_id   and rc4p.product_id = {$productid} group by   rc4p.product_id,   rc.rating_category_id,   rc.name 	0.000645615441894669
4378415	12063	database connectivity using linked server. (numeric values)	select convert(int, yourfield ) as yourfield    from openquery (linkedserver,  'select to_char(yourfield ) as yourfield from remotetable'); 	0.169900846379336
4379743	40902	mysql query between two items	select `id`, `twitter_id`, `date`, `time` from `table_name` where `date` = '2009-03-17' and `time` >= '9:00' and `time` < '10:00' 	0.00400606417640403
4381568	5097	sql server version numbers	select serverproperty('productversion') 	0.219283348308111
4381579	34679	more sql headaches	select d.*,     case when di.totalcount = deliveredcount then 1 else 0 end as deliverycomplete from deliveries d inner join (     select deliveryid,          count(*) totalcount,          count(case when delivered = 2 then 1 end) as deliveredcount     from deliveryitems      group by deliveryid ) di on d.id = di.deliveryid 	0.699381327069321
4381745	29692	sql exclude and move columns on left outer join	select t1.name as emp,         coalesce(t2.name,t3.name) as mg1, coalesce(t2.title,t3.title) as title1,         case when t2.name is not null then coalesce(t3.name,'') else '' end as mg2,         case when t2.title is not null then coalesce(t3.title,'') else '' end as title2 from @table1 t1 left outer join @table2 t2 on t1.id = t2.fid and t2.etype = 123 left outer join @table2 t3 on t1.id = t3.fid and t3.etype = 234 	0.36193806699309
4382315	10525	getting first record from two tables	select c.[ename],c.[custno], o.[orderdate], o.[description]     from  cust  c   left join orders o      on c.custno = o.custno    left join          ( select   custno, min(orderdate) orderdate              from [orders]              group by custno)  mo      on mo.orderdate = o.orderdate          and mo.custno = o.custno 	0
4383480	27423	which stored proc(s) updating certain specific columns in a table	select name from sys.procedures where object_definition(object_id) like '%put text here%' 	7.54072441449588e-05
4384787	11316	based on a date range, how can i tell how many users were active 3-5 days a week?	select userid  from   (select userid,                 yearweek(timestamp)                  as year_week,                 count(distinct dayofweek(timestamp)) as check_in_days          from   checkins          where  1 = 1          group  by userid,                    yearweek(timestamp)          having check_in_days between 3 and 5) as user_weeks  group  by userid  having count(year_week) = (select count(*)                             from   year_week                             where  1 = 1                            ); 	0
4386301	35413	mysql selecting column via other table	select forum_section.section_level from forum_topic  left join forum_category on forum_topic.topic_category_id = forum_category.category_id left join forum_section on forum_category.category_section_id = forum_section.section_id where forum_topic = 'forum topic id'; 	0.000439521735258517
4386631	18679	is it possible to discover the column types from a postgres function?	select t.typname, attname, a.typname from pg_type t join pg_class on (reltype = t.oid) join pg_attribute on (attrelid = pg_class.oid) join pg_type a on (atttypid = a.oid) where t.typname = (     select t.typname     from pg_catalog.pg_proc p     left join pg_catalog.pg_namespace n on n.oid = p.pronamespace     inner join pg_type t on p.prorettype = t.oid     where n.nspname = 'public'     and proname = 'foo'     order by proname ); 	0.0416916358466182
4388635	2341	sql select rows that have (partially) duplicated data	select   productid,   component from   table group by   productid,   component having   count(*) > 1 	0.000231319169877846
4389329	3377	sql query on a condition	select top 1    translation.title    ,translation.summary from     translation where     translation.fklanguageid in (1, 3) order by     fklanguageid desc 	0.344874931455676
4391381	12278	return null columns if ids don't exist in the table	select x.id, y.name, y.designation from ( select row_number() over(order by id) as id from table1 ) x left join table1 y on x.id = y.id 	0
4392361	19714	mysql: getting the most recent action per row	select *     from table_users as users         left join (select user_id, max(date) as maxdate                        from table_special_actions                        group by user_id) s_actions             on s_actions.user_id = users.user_id         left join table_special_actions s2_actions             on s_actions.userid = s2_actions.id                 and s_actions.maxdate = s2_actions.date         left join table_actions as actions             on s2_actions.action_id = actions.id 	0
4394244	7257	sql to get listing from paging	select skip n limit m ... 	0.0767238208049572
4394434	12875	mysql (and php) single query, single table, multiple qualifiers	select a.type, … from marketfile as a, marketfile as b where (a.type = b.type) and (a.location = 102) and (b.location = 75) and … 	0.0111127756832571
4399436	14102	mysql query to get all combinations of elements in same table field	select t1.org as org1, t2.org as org2, teller as scrib_id, count(teller) as weight  from stories t1 join stories t2 where t1.teller=t2.teller and t1.org!=t2.org group by teller,t1.org 	0
4400706	37168	sql query - join	select * from student s left join attendance a on a.student_id = s.id where s.course_id = "eng" 	0.771641521025625
4400941	17132	how to return the miliseconds of a getdate() function of t-sql?	select        playerid, (select        convert(varchar(23), getdate(), 121) as expr1) as expr1 from            player 	0.0136582277514551
4404631	31749	add year to column before compare in sql query	select count(*) as count    from users u   where date_add(u.renewed, interval 1 year) < '2009-12-12' 	0.000468084832370803
4405154	16108	sql select depending on match in php and mysql	select     * from     your_table where     date_format(date_column, '%m %y') = '01 2010' 	0.00450040163122534
4405367	12520	mysql query optimize for searching records!	select m.movie_id,m.movie_name_cn  from movie as m, moviewh as mwh   where m.movie_id = mwh.movie_id       and date_format(mwh.watching_date,'%y-%m-%d') = '2010-11-01'        and mwh.user_id = 1 	0.482286815144896
4405540	13480	sql to get lastest node of hierarchy base table?	select max(id), parent from tree group by parent; 	0.000232078094780293
4409004	31033	3 table count query mysql	select p.productid as productid, p.name as name, count(s.salesid) as totalsales, count(l.linkid) as totallinkavailable from products as p left join sales as s on s.productid = p.productid left join links as l on l.productid = p.productid group by p.productid, p.name 	0.0725082724940918
4409465	8661	sql query - multiple keywords searching multi columns	select idn, firstname, lastname from employees  where 1=1 <cfloop list="#arguments.namesearchstring#" delimiters=" " index="word">     and ( firstname like <cfqueryparam cfsqltype="cf_sql_varchar" value="#word#%" />     or lastname like <cfqueryparam cfsqltype="cf_sql_varchar" value="#word#%" /> ) </cfloop> 	0.113226272644205
4409919	24933	how to create inner join multiple tables in sql	select pr.price_id, p.product_name v.vendor_name, pr.price from prices as pr left join products as p on p.product_id = pr.product_id left join vendors as v on v.vendor = pr.vendor_id 	0.384312074702065
4411456	15266	sql server strip string	select * from yourtable where charindex('yourstring', yourcolumn) > 0 	0.18999561512133
4412403	1149	sql - comparing substrings instead of entire string	select substring(datapath,1,5), count(*)      from batchinfo     where datapath like '%thc%'     group by substring(datapath,1,5)     having count(*)>1 	0.00136445982725219
4412643	6230	sql: select one column into a column in another table	select iso_2_letter_code into odbctest from #temptable 	0
4413960	16723	how do i select the first element in a the table returned by a sql function	select top 1 * from my_function('x','y'); 	0.00021717739267867
4415639	9523	getting projects which are have no feedback	select *   from projects p  where not exists(         select *           from feedbacks f          where p.id = f.project_id); 	0.00291450313498225
4416036	36169	can i select before join?	select a.id, b.name     from table as a    left join      (select name from table2) as b    on a.id = b.id 	0.343098628162088
4416109	27769	mysql join a table with with two other tables based on a flag column	select message_id, message_title, user.name, corp.name from group_messages left join users on    users.user_id = group_messages.user_id    and group_messages.usertype = "1" left join corp on    corp.user_id = group_messages.user_id    and group_messages.usertype = "0" ; 	0
4416880	7053	sorting multiple fields in mysql	select * from yourtable order by `date` desc, `importance` desc 	0.100894704151146
4418665	25622	sql join to return null rows from both left and right table	select     tbl1.id,     tbl1.count1,     tbl2.count2 from tbl1 left join tbl2 on tbl1.id = tbl2.id union all select     tbl2.id,     tbl1.count1,     tbl2.count2 from tbl2 left join tbl1 on tbl1.id = tbl2.id where tbl1.id is null order by id 	0.0351775678188878
4418919	36616	sql to find list of stores in city x that carry product y and order by the total num of orders in asc	select stores.name   from stores        inner join storesproducts          on stores.id = storesproduct.store_id        inner join products          on storesproduct.product_id = products.id        inner join orders          on stores.id = orders.id  where stores.city = 'new york'        and products.name = 'shampoo'  group by stores.name  order by count(*); 	0
4420048	33169	t-sql count items by adding and removing	select a.time,a.item, sum(case  when b.action='add' then 1 when b.action='remove' then -1  else 0 end) from table1 as a left join table1 as b on a.item=b.item and b.time<a.time where a.action='count' group by a.time,a.item,a.action order by 1 	0.0226089048512799
4420554	9539	use like %..% with field values in mysql	select t1.notes,         t2.name   from table1 t1   join table2 t2 on t1.notes like concat('%', t2.name ,'%') 	0.322474196178787
4422122	4923	join two tables with one common key in mysql	select table1.app_name, table1.app_id from table1 inner join table2 on table1.app_id = table2.app_id 	0.000373692708280125
4425388	5745	data from three tables	select m.name, m.zipcode, p.lat, p.lon, meta.meta_value from members as m inner join zipcodes as p on m.zipcode = p.zipcode  left outer join usermeta as meta on m.id = meta.id where m.zipcode = p.zipcode and coalesce(meta.meta_key,'image')='image' and m.country = 'usa' 	0.00457500629752495
4426083	6542	mysql date compare problem?	select * from shortleavedetails where employee_code='17' and  authorizeddate between '2010-5-1'and '2011-1-1' 	0.142007862012644
4426363	32983	mysql finding unique product ids from 2 tables	select count(1)  from (select distinct productid       from sales      union        select distinct productid       from links) products 	0
4431330	2463	mysql, select rows if column equals ? else select using default value	select t.optionname, t.optionvalue from (     select optionname, max(languageid) as maxlanguageid     from tbl_options        where optionname in ('opt1', 'opt2')          and languageid in (1, 2)       group by optionname ) tm inner join tbl_options t on tm.optionname = t.optionname     and tm.maxlanguageid = t.languageid order by t.optionname 	0.000826477560398546
4433927	15955	mysql retrieving data from 2 tables via a correlation table	select   artist_id,   album_id,   ... from   albums_artists join albums on albums.id = albums_artists.album_id join artists on artists.id = albums_artists.artist_id 	0.000110369669203732
4434118	1554	select statement to find duplicates on certain fields	select field1,field2,field3, count(*)   from table_name   group by field1,field2,field3   having count(*) > 1 	0.000252338354020677
4434622	33264	subtype reference in oracle	select p.gender, p.name.firstname, p.name.lastname,         treat(value(p) as fulltimeemployeetype).yearlysalary from person p / 	0.632694638853281
4435986	10823	mysql string contained within a search string	select *   from `table`   where '{$search}' like concat('%', `column`, '%') 	0.105747167533635
4436591	3563	how can i search within a table of comma-separated values?	select * from table where field like '3,%' or field like '%,3' or field like '%,3,%' or field = '3' 	0.00399983144718251
4437412	23884	transform sql table	select   tn.fieldvalue as valuename , tv.fieldvalue as valueage from dbo.table1 tn inner join dbo.table1 tv on tn.recordid = tv.recordid   and tn.fieldname = 'name'   and tv.fieldname = 'age' 	0.136421158534016
4437784	7072	add column values in sql server query	select id, sum(value) as value from (     select id, value from query1     uninon all     select id, value from query2 ) x group by id 	0.0317045389653124
4439129	36771	sql returning aggregated results from one table as a column in a query	select title,         (select group_concat(comment) from comments          where          comments.postid=posts.posts) as comments from posts 	0.000560859865936015
4439329	20835	how to know how many times its a value in the databes? and for all values?	select `name`, count(*) as `count` from `colors` group by `name` order by `count` desc 	0
4439369	6107	combining two ms access queries	select "i1" & "," & "i2" as item_set, round(sum([t1].fuzzy_value)/sum(ttrans.expr1),15) 	0.290598368530411
4442910	39659	combine tables related to each other by a linking table and not to worry if the linking table is missing some data	select p.alias, p.name, g.group from person as p left outer join group as s on p.alias=l.alias left outer join cglink as l on l.type=s.type order by p.alias, p.name; 	0
4443314	17571	join row with specified field value and highest value in other field	select id,lang,time from articles,article_versions where articles.id=<article_id_you_provide> and       articles.id=article_versions.article and       article_versions.time = (select max(time)                                from article_versions                                where article=<article_id_you_provide>); 	0
4443451	106	expression of non-boolean type	select min(q.rid)     from qvalues q         inner join batchinfo b             on q.rowid = b.rowid                 and b.instrument = 'tf1'     group by q.rowid, q.name, q.compound     having count(*) > 1 	0.718986532576091
4444237	14970	with sql server how to get the most recent date while summing on amount and the sum of the amount is greater than 0?	select  lastdate.personid, lastdate.transdate as lastpaymentdate, totalamount.totalamount   from    (select   personid, max(transdate) as transdate          from     trans          where    (transcode in ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'p2'))          group by personid          having   (sum(transamount) > 0)          order by personid, transdate) as lastdate inner join (select personid, transdate, sum(transamount) as totalamount           from     trans          where    (transcode in ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'p2'))          group by personid          having   (sum(transamount) > 0)          order by personid, transdate) as totalamount  on totalamount.personid = lastdate.personid and totalamount.transdate = lastdate.transdate order by lastdate.personid 	0
4445333	41264	filtering sql query by row and by date range	select oracle_time from t_ssv_soh_packets0 where oracle_time >= timestamp '2009-01-01 00:00:00' and oracle_time <= timestamp '2009-01-31 00:00:00' group by oracle_time, rownum having mod(rownum, 50)=0 	0.00213517987378302
4445698	21977	find difference between end dates by comparing rows	select u1.*, datediff(day, u2.enddate, u1.enddate) as days from     (     select userid, enddate, row_number() over(partition by userid order by userid, enddate) as rownumber     from [user]     ) u1     left join      (     select userid, enddate, row_number() over(partition by userid order by userid, enddate) as rownumber     from [user]     )u2     on u1.userid = u2.userid     and u1.rownumber = u2.rownumber + 1 	0
4445820	37967	find rownum from mysql result set for ranking	select t.*,        (select count(*)           from top100 t2          where t2.score > t.score) as rank   from top100 t  where id = last_insert_id() 	0.00556467232652391
4448058	36217	mysql query. select data from three tables	select  t.name,         t.surname,         group_concat(l.lang_name separator ", "),         t.phone,         t.email from    translators t inner join         trans_lang_rel tlr  on  t.id = tlr. trans_id inner join         language l  on  tlr.lang_id = l.id group by    t.name,             t.surname,             t.phone,             t.email 	0.00692983515409768
4448270	24262	convert nvarchar to money value	select convert(money, replace('4352,50', ',', '.')) 	0.0301915313157495
4448421	14946	oracle query needs to return the highest date from result	select * from ( select custid,reason,date from opt opt where opt.custid = 167043   order by date desc )  where rownum = 1; 	0.000171943065319653
4452628	38656	sql select to reference a lookup based on two columns	select mt.product,         lt1.description as debitdescription,         lt2.description as creditdescription     from mastertable mt         inner join lookuptable lt1             on mt.debitcode = lt1.code         inner join lookuptable lt2             on mt.creditcode = lt2.code 	6.27613051593545e-05
4453300	12402	sqlite, making a query based on dates	select contactname from shipment  where datecreated  between '11-15-2010'  and '12-25-2010' 	0.00533926344943139
4453342	12315	count maximum times record appears in database table	select max(c) from (   select     count(*) c   group by     .. whatever ...   ) x 	0
4453548	650	how to list duplicate entries in database	select email, category from tablename group by email, category having count(email) > 1 	7.81098217927039e-05
4453810	21860	convert date to null in sql sever	select  entered_date as date convert(datetime, null) as next_date from sometable 	0.128098122257349
4456656	25237	how can i get the size in bytes of a table returned by a sql query?	select sum(max_length) from sys.columns where object_id = object_id('mytable') 	0.00039204908722986
4457914	30373	t-sql combine multiple rows into single row	select case max(x.score1) when 0 then null else max(x.score1) end as score4        case max(x.score2) when 0 then null else max(x.score2) end as score4        case max(x.score3) when 0 then null else max(x.score3) end as score4        case max(x.score4) when 0 then null else max(x.score4) end as score4   from (select 3.00 as score1, 0 as score2, 0 as score3, 0 as score4         union all         select 0 as score1, 4.5 as score2, 1.5 as score3, 0 as score4) x 	5.66680502167533e-05
4458891	4355	fetching records with column value constraints	select     * from     <table> t          left join     <table> t2          on              t.name = t2.name and              t2.privilege <> 1 where     t2.name is null and     t.privilige = 1 	0.000279373485022673
4460520	16158	tricky sql to select distinct user	select distinct u1.username from users u1 inner join users u2 on u1.username = u2.username inner join users u3 on u1.username = u3.username where u1.value <> u2.value and u1.userid < u2.userid and u2.value <> u3.value and u2.userid < u3.userid 	0.33908525273347
4460881	29702	conditional select count(id) using count(id) as the condition?	select categoryid, count(articleid) as numarticles  from articles group by categoryid having count(articleid) > 3 	0.486943827989648
4461266	27877	sqlite query three tables	select monitors._id as _id,  monitors.monitor_name as monitor_name,  monitors.warning_threshold as warning_threshold,  monitors.alarm_threshold as alarm_threshold,  lastresults.test_info as test_info,  count(correctsteps._id) as correct_count from monitors left join   (select * from results as r1 where timestamp =    (select max(r2.timestamp) from results as r2 where r1.monitor_id=r2.monitor_id)) lastresults on monitors._id = lastresults.monitor_id left join   (select * from steps where correct = 'true') correctsteps on lastresults._id = correctsteps.result_id group by monitors._id; 	0.189286354468668
4462495	21201	joining 5 tables to obtain all comments made about goal where id = 2	select c.* from goal g  inner join objectives o on g.id = o.goal_id  inner join steps s on o.id = s.objective_id  inner join transaction t on s.id = t.step_id  inner join comments c on t.comment_id = c.id where g.id = 2 	0.000173049889744128
4463116	37060	use access sql to do a grouped ranking	select *, (select count(*) from tbl as tbl2 where tbl.customers > tbl2.customers and tbl.dept = tbl2.dept) + 1 as rank from tbl 	0.430617846215352
4464946	34149	how do i sum distinct rows?	select sum(popestimate2005), sum(estimatesbase2000) from(     select  distinct         zipcodes.countyid,          us_co_est2005_alldata.popestimate2005,          us_co_est2005_alldata.estimatesbase2000,          users_link_territory.userid      from          zipcodes inner join          users_link_territory on zipcodes.countyid = users_link_territory.countyid inner join          us_co_est2005_alldata on zipcodes.fips = us_co_est2005_alldata.state and zipcodes.code = us_co_est2005_alldata.county      where          (users_link_territory.userid = 4) ) as foo 	0.00768333801210222
4465664	22460	tsql translation	select * from mytable where @activestate is null or isactive = @activestate 	0.717261830845054
4467069	38080	apply certain condition on specific rows in sql statement	select name    from mytable  where mydate between  '2011-01-01' and '2011-04-01'    and addtime(mydate, endtime) > now() 	0.00128791242485621
4468173	14368	how to clone user in oracle	select dbms_metadata.get_ddl('user', '...') from dual; select dbms_metadata.get_granted_ddl('role_grant','...') from dual; select dbms_metadata.get_granted_ddl('system_grant','...') from dual; select dbms_metadata.get_granted_ddl('object_grant','...') from dual; select dbms_metadata.get_granted_ddl(‘tablespace_quota’, ‘...’) from dual; 	0.255012134271553
4469872	33235	multiple join view on the same table	select foo.datetime, max(foo.v1), max(foo.v2), max(foo.v3)     from      (      select acq.datetime, data.value as v1,0 as v2, 0 as v3      from acq inner join data on acq.id = data.id_acq      where acq.id_cu=1 and data.id_meas=100      union     select acq.datetime, 0 as v1, data.value as v2, 0 as v3     from acq inner join data on acq.id = data.id_acq     where acq.id_cu=2 and data.id_meas=200     union     select acq.datetime, 0 as v1, 0 v2, data.value as v3     from acq inner join data on acq.id = data.id_acq     where acq.id_cu=3 and data.id_meas=300     ) as foo     group by foo.datetime 	0.00531662499820251
4470164	32712	sql problem with formulating a query where combinations are defined in another table	select      loc1.name as loc1,     loc2.name as loc2 from     pressurebox pb     join location loc1 on loc1.id = pb.dd     join location loc2 on loc2.id = pb.cr 	0.149600362639952
4471230	20693	sql: select items with number of comments and latest comment date	select item.*,    count(comments.itemid) as commentcount,    max(comments.created) as commentcreated  from table_items as item  left join table_comments as comments on (comments.itemid = item.id)  where item.published=1  group by item.id  order by item.created desc 	0
4472168	2410	search for string with conditions	select name from table      where name like '/home/%' and name not like '/home/%/%' 	0.357711038273654
4472880	13582	sql query grouped parameter maximum	select col1 from table group by col1 having max(col2) <= 4 	0.0282474487637389
4474130	29785	how do i check an input against prohibited words in mysql database?	select *     from restrictions      where locate(prohibited, @username) <> 0 	0.0607536421028584
4474251	11085	how to get id of field based on the max of another field in same table	select a.aetid, a.aetproposaltype, a.aetdaystowait     from ae_types a         inner join (select aetproposaltype, max(aetdaystowait) as maxdays                     from ae_types                     group by aetproposaltype) sq             on a.aetproposaltype = sq.aetproposaltype                 and a.aetdaystowait = sq.maxdays 	0
4476407	27884	php mysql - compare datetime	select count(counterid) as count  from visitors_counter where timestamp > (now() - interval 15 minute) 	0.032708024981573
4480868	6194	jpql order by average from a second table	select p from product p left join p.votes v   group by p order by avg(v.score) desc 	0.000139292767785712
4481396	17186	mysql cartesian product between two select statements	select mytable1.col1, mytable2.col2 from mytable1 cross join mytable2 	0.0544625641390964
4482671	29978	select comparison operator on basis of parameter	select *   from mytable  where (p_stroperator = '=' and mycolumn = p_dtclosingdate)     or (p_stroperator = '>' and mycolumn > p_dtclosingdate)     or (p_stroperator = '<' and mycolumn < p_dtclosingdate); 	0.401830158670983
4483399	3539	selecting an int and dividing using mysql	select (field / 100) as divided   from table; 	0.0620936551025379
4483798	29626	can i use count() and distinct together?	select count(distinct column) from table; 	0.321118832573454
4484974	32673	how to check whether select exists returns a value or not?	select 1 from goals where goal_id='$obj_id' and user_id='$user_id' limit 1 	0.00578786426754459
4487533	19750	select rows where value changes	select j.job,     j.proj,     j.date,     j.amt,     (select top 1 amt       from jobs q       where q.job=j.job and q.proj=j.proj and q.date<j.date       order by [date] desc) as nextamt  from jobs as j  where ((select top 1 amt          from jobs q          where q.job=j.job and q.proj=j.proj and q.date<j.date          order by [date] desc)) <>[amt]  or ((select top 1 amt       from jobs q       where q.job=j.job and q.proj=j.proj and q.date<j.date       order by [date] desc)) is null 	0.00564211720861397
4489218	6529	parsing comma seperated values in ms-sql (no csv or such)	select *  from t1      join t2 on '%,' + t1.id + ',%' like ',' + t2.t1_ids + ',' 	0.00988530624077584
4490084	25741	select values out of xml column	select a.objectid,         a.cgpracticecode,         a.totalamt,         a.splitamt.value('(/values/row/practicecode)[1]', 'nvarchar(50)') as practicecode,         a.splitamt.value('(/values/row/value)[1]', 'int') as [value] from [dbo].[tablea] a 	0.00200532290129801
4490133	14987	sql: how to return any part that occurs more than once	select part from parts group by part having count(*) > 1 	0.000164860595385205
4491411	19926	sql server failover cluster - determine active node	select serverproperty('computernamephysicalnetbios') 	0.117640866279354
4491965	18582	query join condition	select  a.id from    account a left join         assignedgroup b on      b.assignedgorup like a.sourceaccount + '-%' 	0.72338594720267
4492913	4416	how to find all instances of a procedure (or function) in sql server 2005/2008	select     object_schema_name(m.object_id) + '.' + object_name(m.object_id)     from sys.sql_modules  m     where m.definition like '%whatever%' 	0.0083551387143584
4494602	20941	find an unused number in a bunch of numbers	select seq_num   from (select (lvl + &&v_from - 1) seq_num           from (select *                   from (    select level lvl                               from dual                         connect by level <= (&&v_to - &&v_from) + 1)))  where seq_num not in (select my_identifier from my_table); 	0.000588040832706963
4495242	7873	mysql: number of subsequent occurrences	select    count(*) as unreplied from   `convo` where   `convo`.`from` = 'bar' and   `convo`.`to` = 'foo' and   `convo`.`id` > (select                     id                   from                     `convo`                   where                     `convo`.`from` = 'foo' and                     `convo`.`to` = 'bar'                   order by                     `convo`.`id` desc                   limit 1) 	0.000942969144959389
4496829	8498	numbers in select statements	select * from yourtable yt where exists(     select 1     from someothertable sot     where yt.id = sot.id     ) 	0.0995085887968877
4499688	40633	join two tables, where one is not uniqe	select distinct * from table as p          join `table2` as ps on (p.id = ps.`id_table2`)          order by p.id 	0.166215783548939
4499763	6630	mysql lookup table schema	select `table_name`, `engine` from `information_schema`.`tables` where `table_schema` = 'your_db' order by `table_name` asc 	0.183190462544695
4500466	24625	mysql join table - selecting the newest row	select n.name_id ,  n.name , max(timestamp) as time from names n left join  status s on s.name_id = n.name_id group by n.name_id 	0.000214717984170443
4503030	9212	mysql multiple inner join	select       businessdetails.name as businessname,     (select count('x') from clientdetails where clientdetails.businessdetailsid = businessdetails.businessdetailsid) as totalclients,     count(records.businessdetailsid) as totalrecords from      `businessdetails`     inner join records on records.businessdetailsid = businessdetails.id group by      businessdetails.name order by     totalclients desc 	0.793157669370634
4504042	19154	how do i efficiently make use of the result of a function call in a mysql query multiple times without calling the function multiple times?	select blah from (     select          blah, field1, field2, field3,         functcall(otherfield1, otherfield2) as f     from your_table ) t1 where field1 % f = 0    or field2 % f = 0    or field3 % f = 0 	0.0886699527259739
4504379	831	convert date in sql to compare dates	select *   from tab  where submission_date between          to_date ( $begin_date, 'yyyymmdd') and          to_date ( $end_date, 'yyyymmdd'); 	0.00159834561922318
4504991	13544	sql select for multiple where clause	select count(distinct id) as totalcount,  count(distinct case type when 'a' then id else null end) as totala, count(distinct case type when 'b' then id else null end) as totalb  from mytable; 	0.718196189942533
4506286	6670	getting max(date) out of similar dates	select balance from mytable where timestamp = (select max(timestamp) as recenttime from mytable where recorddate = (select max(recorddate) from mytable)   group by recorddate 	0.00419636925382387
4506427	4109	get the count of a -> b and b->a without duplicates	select `from` as a, `to` as b, count(*) as `count` from your_table group by if (from<to, concat(from,to), concat(to,from)); 	0.000183978050066491
4507845	13354	mysql order results if a certain condition is met	select * from posts left join customfields        on post_id=posts.id and custom_key='featured'  order by custom_value=1 desc, id desc; 	0.00510129980284816
4509167	35341	select nth row from a table in oracle	select *    from ( select a.*, rownum rnum            from ( your_query_goes_here            where rownum <= n_rows )  where rnum >= n_rows / 	0.000158415050507069
4510479	36450	mysql select * from tbl1 where smth and a field from another table is something	select t.* from trips_all t inner join users on t.username = u.username     where u.active = 'member' 	0.000174367585491289
4511324	12451	mysql query to get most recent and cheapest items per classification	select * from data d1    where not exists       (select * from data d2 where d2.class = d1.class                              and (d2.date > d1.date                               or (d2.date = d1.date and d2.price < d1.price))) 	0
4511583	20115	mysql left join 3 tables include null sets	select  driver.driver, race.id, race.year, result.finish from    race cross join         driver left join         result on      result.race_id = race.id         and result.driver_id = driver.driver_id where   race.track_id = 1         and race.year > 2006         and race.complete = 1         and driver.driver_id = 1 order by         race.id asc 	0.371915796677975
4511597	7095	php: mysql table structure	select     lessons.*,     courses.title as course from     lessons inner join     courses         on     courses.id = lessons.cid group by     lessons.id order by     lessons.date 	0.146977645240265
4511945	14846	select values that begin with a number	select * from yourtable where yourcolumn regexp '^[0-9]+' 	0.0013989354051096
4511962	6362	sql subtract first row from all selected rows	select  v - first_value(v) over (order by t) from    mytable order by         t 	0
4512491	16824	how to select 2 fields from one table and compare it on 1 field of the another table	select categ_name, ... from invoices_account  join invoices_payable  on concat(invoices_account.categ, invoices_account.code) = invoices_payable.reference 	0
4513205	41182	sql latest record per group with an aggregated column	select   b.stock_id,   b.trade_time,   b.price,   a.sumvolume from (select         stock_id,          max(trade_time) as maxtime,         sum(volume) as sumvolume       from stocktable       group by stock_id) a inner join stocktable b   on b.stock_id = a.stock_id and b.trade_time = a.maxtime 	0
4514550	40966	cannot produce query to find multiple under same member record	select id, code  from table  group by id, code  having count(code) > 1; 	0.000544363376468419
4516616	21771	how to know in mysql that table is empty by writing query?	select count(1) from users 	0.275326854969906
4518560	5667	group by in subquery and base query sql server	select day,          sum(regular + extra + overtime) as [potential hours],         subsum as [billed hours] from    billable as billable1 left join         (             select  day,                     sum(extra + regular + overtime) as subsum             from    dbo.ticplus_effort_billable_only             where   (manager not like '%manager1%')             group by day         ) s on  billable1.day = s.day group by    day 	0.705238535545192
4519077	18758	select all data from the last 5 days	select name,date  from lineas where date >= date_sub(curdate(), interval 5 day) and date <= curdate() order by date desc 	0
4519266	3807	not exists in the same table	select test_name from tests  where version='ie7'  and test_name  not in (select test_name from tests where version='ie8'); 	0.0146325180746005
4519582	28711	how to select non "unique" rows	select t1.ida, t1.infos from xxx t1 join (     select ida     from xxx     group by ida     having count(*) >= 2 ) t2 on t1.ida = t2.ida 	0.000749424963466853
4519706	13569	how to select from many tables	select v.image,a.text from video as v join article as a on v.id=a.id where ... 	0.00477023774238438
4520065	13977	returning results from 2 mysql tables	select u.*, count(f.id) from users u left join files f on u.id = f.user_id group by u.id 	0.00667742381565125
4521182	12465	how to use join and multiple where condition?	select  h.same_date,         h.holiday,         hd2010.date,         hd2011.date,         hd2012.date from    countries c join    holiday_countries hc on      hc.country_id = c.id join    holidays h on      h.id = hc.holiday_id left join         holiday_dates hd2010 on      hd2010.holiday_id = hc.holiday_id         and hd2010.year = '2010' left join         holiday_dates hd2011 on      hd2011.holiday_id = hc.holiday_id         and hd2011.year = '2011' left join         holiday_dates hd2012 on      hd2012.holiday_id = hc.holiday_id         and hd2012.year = '2012' where   c.name = 'india' 	0.685610205660055
4521215	12241	finding the last duplicate row in (oracle) sql	select  * from    (         select  h.*,                  row_number() over (partition by workid order by date desc) as rn         from    history         ) where   rn = 1 	0
4523135	3646	distinct select on oracle	select * from (select *  from   (select e.node2 ,  max(e.weight * k.grade ) as maxde     from kuaisfast k, edges e     where k.id = 1 and k.course_id = e.node1 and e.node2 not in(         select k2.course_id         from kuaisfast k2         where k2.id = 1         )          group by e.node2 ) order by maxde desc) where rownum <= 40 	0.108305545162018
4524737	35686	getfulltext search result for maximum values	select   * from your_table  where    match(name,address,description) against ($search_string in boolean mode) order by   length(concat(name,address,description))-   length(replace(concat(name,address,description), $search_string, ''))   /length($search_string)   desc; 	0.00504897278648174
4525176	39551	getting list of maximum values in sql	select * from table order by colname desc limit 10; 	0.00014852599379219
4525761	32468	can i combine values from multiple rows in another table into multiple columns of one row using sql?	select t1.m_id, t2_1.a as p_1a, t2_1.b as p_1b, t2_2.a as p_2a, t2_2.b as p_2b, ... from t1, t2 t2_1, t2 t2_2 where t1.p_id1 = t2_1.p_id and t1.p_id2 = t2_2.p_id 	0
4526594	99	sql distinct [alternative using]	select city from (   select city,          row_number() over             (partition by city             order by city) rownumber     from persons          ) t    where rownumber = 1 	0.728990239941405
4527654	26267	mysql tag query - repeated values	select  content.name,         (         select  group_concat(cta.tag)         from    content_tags cta         where   cta.contentid = ct.contentid         ) from    content_tags ct join    content c on      c.contentid = ct.contentid where   ct.tag in ('grass', 'texture') group by         ct.contentid having  count(*) = 2 	0.0667029480498518
4527723	4064	db2: joining 2 tables with priority	select coalesce(seasonal.price,normal.price)  from normal left outer join seasonal  on normal.id= seasonal.id 	0.0151543833195529
4529091	8035	sql database query distinction and grouping	select a.name, b.*  from    your_table as a  inner join  (select     department, gender, min(age) as min_age  from your_table  group by department, gender) as b  on     a.department=b.department and    a.gender=b.gender and    a.age=b.min_age; 	0.623444811999621
4530804	23695	how do i change sql query output?	select customer_id, group_concat(domain_name separator ',') from customers_orders inner join orders on order_id = sub_id group by customer_id 	0.527883085893013
4530938	28761	how to select only some characters from mysql field?	select substring('cybernate', 2, 3) 	0.000308140719201493
4532314	39945	finding oracle_sid for database?	select instance from v$thread select distinct sid from v$mystat select * from global_name 	0.0625499060372331
4533426	18038	get the longest hierarchy	select id,  (if(t_definition_types_id_1>0, 1, 0) +    if(t_definition_types_id_2>0, 1, 0) +   if(t_definition_types_id_3>0, 1, 0) +   if(t_definition_types_id_4>0, 1, 0)  )  as level  from mytable order by level desc 	0.00419390507241
4533817	3617	mysql - joining tables together in one single query	select a.activity_id, a.activity, c.child_gender, count(*) from activity a  join [child activity] ca on a.activity_id = ca.activity_id   join child c on ca.child_id = c.child_id group by a.activity_id, a.activity, c.child_gender 	0.00543344712478749
4534314	38560	can i do this in only one query?	select u1.id, count(*) from user as u1, user as u2, friend as f1, friend as f2 where u1.id = f1.to and u2.id = f1.from and  u2.id = f2.to and f2.from = 1234  group by u1.id 	0.187198627960944
4535331	23657	do a query only if there are no results on previous query	select * from t1 where title like 'key%' limit 1 union select * from t1 where title like '%key%'    and not exists (select * from t1 where title like 'key%')  limit 1 	0.00112301081276439
4535782	2634	select count of rows in another table in a postgres select statement	select a.*, (select count(*) from b where b.a_id = a.id) as tot from a 	0.000114204966933783
4535818	41033	how can i select the required records?	select brand.name, count(awards.id) as awards from brand left join product on product.brand_id = brand.id and product.is_published = true left join productawards on productawards.product_id = product.id left join awards on awards.id = productawards.award_id where brand.is_published = true 	0.0153957035741277
4539783	13465	sql unite fields to one result	select [key], coalesce(f2, f3, f4), f5 from yourtable 	0.0357494830552358
4542565	13122	how to check if a specific id exists in multiple tables and which ones with oracle?	select p.pid       ,p.name       ,p.sex       ,case when a.pid = p.pid then 'yes' else 'no' end as in_a       ,case when b.pid = p.pid then 'yes' else 'no' end as in_b       ,case when c.pid = p.pid then 'yes' else 'no' end as in_c   from persons p   left outer join a on (a.pid = p.pid)   left outer join b on (b.pid = p.pid)   left outer join c on (c.pid = p.pid)  where p.pid = 5; 	5.62759985831867e-05
4543443	1274	mysql query current month	select *   from `table`  where date_format(from_unixtime(`date`), '%y%m') = '201012' 	0.00106047101179451
4548201	10584	left join that always includes null records	select  customer_id, null as location_id, address from    customers union all select  customer_id, location_id, address from    locations 	0.282118927544138
4548456	5176	join and count in sql server	select a.elementid, a.column1, a.column2, a.column3,         count(case when b.somecolumn > 0 then b.elementid else null end) q from tablea a left join tableb b on a.elementid = b.elementid group by a.elementid, a.column1, a.column2, a.column3 	0.585793696007075
4549595	14171	how can i take a union of two separate sql queries and get only distinct values	select distinct             g.name, g.hash, g.views                     from c7_groups g, c7_groups_affiliations ga                     where g.category >= 592 and g.category <= 622                         and ga.affiliated_groups_hash = g.hash                         and lower(g.name) like lower('%$school_name%') union select             g.name, g.hash, g.views                     from c7_groups g, c7_groups_affiliations ga, c7_affiliations a                     where ga.affiliations_id = a.id                         and ga.groups_hash = g.hash                         and lower(a.name) like lower('%$school_name%') 	0
4551654	1972	pivoting data using sql 2008	select * from (   select a.id, a.title, b.text   from dbo.sliders as a   left join dbo.slideritems b on b.sliderid = a.id ) as s pivot (   max(s.text)   for s.text in ([one],[two],[three],[four]) ) as p 	0.41540198643659
4551935	19626	2 results with 2 where in one select statement in sql-server	select  min (case when event_id = 4 then log_in_time else null end) as mintime, max (case when event_id = 5 then log_off_time else null end) as maxtime from tbl 	0.0156912365442587
4552769	24320	sql rownum how to return rows between a specific range	select * from  (  select m.*, rownum r  from maps006 m  )  where r > 49 and r < 101 	0
4554346	26453	mysql date function	select *, timestampdiff(year, child_dob, current_timestamp) as age  from child order by child_dob, child_sname, child_fname; 	0.399473425011358
4554765	30852	get the sum of a column in all rows mysql	select sum(grand_total) from order 	0
4555635	37715	use tsql to select value b if a is not found	select  distinct t1.id,coalesce (t2.addresstype, t3.addresstype)  from @tmp t1  left join @tmp t2 on t1.id = t2.id and  t2.addresstype = 's'  left join @tmp t3 on t1.id = t3.id and t3.addresstype = 'p'   where t1.addresstype  in ('p', 's') 	0.0568461087567431
4555988	12069	sql server pivot on key-value table	select    t1.objectid, t1.value as key1, t2.value as key2 from    objectattributes t1    join    objectattributes t2 on t1.objectid = t2.objectid where    t1.key = 'key 1'    and    t2.key = 'key 2' 	0.192169014800867
4556046	20423	sql problem - duplicate names, listing all fields	select * from [employee] where lname + ', ' + fname in  (select lname + ', ' + fname as fullname from [employee] where lname != ' ' and fname != ' ' group by lname + ', ' + fname having count(*) > 1) 	0.00215884621573495
4556397	23047	sql: is it possible to add a dummy column in a select statement?	select id, '~' as endofcol from main where id > 40 	0.220230246929451
4557871	35608	mysql fulltext search where category = something	select * from `posts` where match ( `title` , `description` , `location` )       against ( 'fayetteville' in boolean mode ) and `category` = 'search category' order by `id` desc limit 0 , 100 	0.683787499884138
4560471	23169	how to exclude rows that don't join with another table?	select <select_list>  from table_a a left join table_b b on a.key = b.key where b.key is null 	0
4560630	15117	mysql for update	select ... for update 	0.336856843650713
4562184	14707	sql query: multiple rows append to show in one row	select     stuff((select ' ' + employeename           from dbo.employee           for xml path('')), 1, 1, '') 	5.94991703209207e-05
4562923	3425	mysql two table query	select user as allfriends from friendlist inner join members on user = id where myid = 50624 and status = 1 union select myid as allfriends from friendlist inner join members on user = id where user = 50624 and status = 1` 	0.0453153073264867
4563940	3594	sql select statement	select studentid from table where      studentid in         (select studentid from table where ( period = 1 and class= "math" ) )  and      studentid in         (select studentid from table where ( period = 2 and class= "english" ) ) 	0.572900891335646
4566500	18011	multiple foreign keys from one table linking to single primary key in second table	select u1.strusername, u2.strusername from household h left join adult a1 on a1.id = h.iadult1id left join users u1 on u1.id = a1.iuserid left join adult a2 on a2.id = h.iadult2id left join users u2 on u2.id = a2.iuserid 	0
4568694	6741	mysql multi count() in one query	select u.userid, companyname,         count(distinct l.listid) as tlists, count(distinct i.items) as titems  from users u    left join lists l on u.userid=l.userid    left join items i on u.userid=i.userid  group by u.companyid 	0.084792052717416
4568723	22323	invalid column name	select ad.id, newspaper,      (select organization from joborganization where joborganization.id = ad.organizationid) as organization,     ad.publishdate, ad.lastdate,ad.url, job.id as jobid,     (select jobtitle from jobtitle where jobtitle.id = job.titleid) as jobtitle1,     qualificationid, expinyears, categoryid      from ad inner join job on ad.id = job.adid      where (select jobtitle from jobtitle where jobtitle.id = job.titleid)like @title or @title is null      order by  case when @sortcol='publishdate' and @sortdir='asc' then ad.publishdate end asc,  case when @sortcol='publishdate' and @sortdir='desc' then ad.publishdate end desc,  case when @sortcol='lastdate' and @sortdir='asc' then ad.lastdate end asc,  case when @sortcol='lastdate' and @sortdir='desc' then ad.lastdate end desc 	0.304013550411386
4569537	18089	select a distinct value in multiple tables (sql)	select colb from tab1 union   select colb from tab2 union   select colb from tab3; 	0.00344522790324376
4570872	34071	a specific value(only one) to be first in a query result. rest order by time stamp	select * from posts order by    if (userid=27, -1, any_timestamp_include_zero); 	0
4572228	13110	need method to seek next/previous records id without cycling through all records	select id as nextid from blogposts where pubdate > $thispubdate order by pubdate limit 1; select id as previd from blogposts where pubdate < $thispubdate order by pubdate desc limit 1; 	0.00177515103632991
4572307	7405	similar sql queries returning different results	select count(*) from comments where thread=1 and parent_id=0 and not exists (select 1 from users                 where users.user_id=comments.user_id) 	0.0927876154070481
4572687	6031	how do you compare strings in sql by aplhabetical order?	select stocka, stockb, correlation, lengthstr from mtcorrelations where stocka < stockb and    exists                     (select *     from industries     where industry = 'money center banks' and           symbol = stocka) and   exists                     (select *     from industries     where industry = 'money center banks' and           symbol = stockb)       order by correlation desc 	0.0661567534384476
4572828	37163	need to retrieve latest instances of a user from a table	select c.id, c.name, cu.user_id, cu.started_at from challenges as c  left join challenges_users as cu on cu.challenge_id=c.id    and cu.started_at=(     select max(cu2.started_at)      from challenges_user cu2      where cu2.challenge_id=c.challenge_id) 	0
4575226	40868	gridview column - only display first 20 characters of field	select left('columnname', 20) 	0
4576456	21695	mysql query to check for duplicate ips	select *  from accounts a where a.last_login_from in      ( select last_login_from        from accounts       group by last_login_from       having count(*)>1 ) 	0.0343955626920231
4576564	28274	select count(*) sql server	select count(distinct assignmentid)  from problemview 	0.281537529716375
4580593	36681	sql query for report - select min date	select     searchterm,     min(dateadded) as mindateadded,      max(dateadded) as maxdateadded,      count(*) as reccount from searchtable  group by searchterm 	0.149175847535754
4581329	29931	how to count tickets as datewise	select r.[date], r.count as received, c.count as closed, p.count as pending from    ( ) r full join     ( ) c on c.[date] = r.[date] full join    ( ) p on p.[date] = r.[date] 	0.368500340211576
4583517	37195	how can i add a serial number for the following query	select row_number() over(order by (select 1))  as 'row number',         ep.firstname,         ep.lastname,         [dbo].[getbookingrolename](es.userid, ep.bookingrole) as rolename  from   [3rdi_eventparticipants] as ep         inner join [3rdi_eventsignup] as es           on ep.signupid = es.signupid  where  ep.eventid = 13         and userid in (select distinct userid                        from   userroles                        where  roleid not in( 19, 20, 21, 22 )                               and roleid not in( 1, 2 )) 	0.00251164170848971
4583810	28449	sql server add count column near existing select columns	select id,         company,         total_money,         no_items,         sum(total_money) over(partition by company) count_total_money_for_company  from   company 	0.0155677064759199
4584241	15614	how to get position rank of specific row using just mysql query?	select users1.id, (users1.points+users1.extra_points) as total, count(*)+1 as rank from users users1 inner join users users2 on users1.points+users1.extra_points < users2.points+users2.extra_points where users1.id = $id 	7.630831366871e-05
4585172	13310	include null in each "details group" in ssrs	select name, number, cast(number as varchar(50)) as displayvalue from mytable  union all select m.name, m.number, 'null' as displayvalue from mytable m where exists(select 1 from mytable where name=m.name and number is null) group by name, number 	0.0045250508803209
4585604	1735	how to do a sql server select using a timestamp minus a certain number of hours	select account from mytable where create_date > dateadd(hh, -2, getdate()) 	0
4586014	39935	oracle date formating null date as 00/00/0000	select nvl(to_char(null, 'dd-mm-yyyy'), '00-00-0000') from dual 	0.180957793161052
4586040	34798	mysql sum elements of a column	select sum(a),sum(b),sum(c) from mytable where id in (1,2,3); 	0.000995043137932119
4586504	959	filtering for multiple values on one column based on values from another column	select fruit from table where color in ('green', 'yellow')     group by fruit having count(*) >= 2 	0
4587316	33438	boolean value from datetime field	select (case publisheddatetime is null then 0 else 1 end case) as is_published 	0.00173247140567803
4589203	28589	mysql : multiple column values as 1 comma-separated string?	select (select group_concat( cols.column_name) from (select column_name from information_schema.columns where table_name='test_table') as cols) from test_table 	0.00397685930396882
4589716	23626	mysql multiple row count?	select action         , count(*)      from table     where date between startdate and enddate  group by action 	0.0172800439404765
4590090	395	time comparison check against mysql datetime stamp	select date_sub(now(), interval 1 hour) 	0.0139466561048684
4590543	25722	mysql join two tables	select id, title, null as categories from a  union all select id, title, categories from b 	0.0711018906807218
4594486	28520	sql server - query on getting distinct records from a table	select max(createddate), businessdate, bookid, datatypeid, version, delflag from table group by businessdate, bookid, datatypeid, version, delflag 	0.000541784566594593
4594939	5928	sum time field values in jpa	select func('sec_to_time', sum(func('time_to_sec', w.timespent))) from workinghours w 	0.0126592391750499
4595700	12770	how to add decimal & zero's after number	select case      when myvarcharcolumn not like '%[^0-9]%' then convert(decimal(18,2), myvarcharcolumn)      else myvarcharcolumn  end as myvarcharcolumn from x 	0.000733726462405871
4596220	30498	how to verify oracle sequences	select (select last_number           from all_sequences          where sequence_name = 'account_code_definition_seq'            and sequence_owner = 'squiggly') max_sequence,        (select max(id_number)            from squiggly.account_code_definition) max_id_number   from dual 	0.165817161237358
4596815	34951	how do i retrieve table id inside mysql	select concat('<a href=\"available.php?id_timeslot=', id_timeslot, '\">available</a>') from table ..... 	0.002474572114889
4596853	13776	mysql not displaying shortest result first	select id,        name from   places where  name_bg like 'рим%'         or name like 'рим%' order  by length(name) 	0.0168433477244832
4598019	16270	sql script to modify column data types	select concat('alter table ',table_schema, '.',table_name, ' modify column ',column_name, ' int unsigned not null;') as sql_stmt  into outfile '/tmp/modify_columns.sql' from information_schema.columns  where table_name = 'user'  and column_name = 'change_me'; \. /tmp/modify_columns.sql 	0.0837989767441624
4598250	24836	count the # of distinct ids, but only when multiple records exist in a table	select count(campaignid) from (   select campaignid   from table   where tagid in (12, 13)           group by campaignid   having count(distinct tagid)=2    ) t 	0
4599322	40207	multiple top n queries	select team_id,        sum(points)   from (         select t.team_id,                 p.points                row_number() over(partition by team_id order by player_id, p.rowid) rn           from teams t, players p               where t.team_id = p.team_id                 and p.wassick = 0         )  where rn < 12  group by team_id 	0.00763631945193005
4600349	15107	how to give weight to full matches over partial matches (postgresql)	select   metrocode,   region,   postalcode,   region_full,   city,   (region = 'chicago'    or postalcode = 'chicago'    or city = 'chicago'    or region_full = 'chicago') as full_match from   dv_location where (   region ilike '%chicago%'  or   postalcode ilike '%chicago%'  or   city ilike '%chicago%'  or   region_full ilike'%chicago%' )  and metrocode is not null  order by full_match desc; 	0.00714249530572395
4602400	32610	limiting union result in oracle	select *   from ( select             ...           union          select             ...        )  where rownum <= 500 	0.613303515084297
4602425	28389	how to store category specific fields in mysql?	select table2.fieldname from table2 left join table1 on table1.category_id = table2.category_id where table1.lft <= [lft value for given level of hierarchy] 	0.00117246535990575
4602727	8561	database query involving username and count	select ref, count(ref) from tbl_users group by ref order by count(ref) desc 	0.351807662488906
4603297	36722	too many records, wamp gets hang, for exporting my customers with no orders to csv	select first_name, last_name, email  from your_table into outfile 'c:\customer.csv'; 	0.0155887108712594
4605376	13904	sql: select most voted items from each user	select id_b, max(votes), rating  from (select id_benefit, count( * ) as votes, rating         from `vote_benefits      group by id_benefit, rating)  group by id_b 	0
4605769	40059	more efficient way of using sql or?	select * from tablea where colour in ('red','greed','yellow'); 	0.710067671615743
4606482	4505	sql help - filter by user id	select     projectid, urlid, count(1) as totalclicks, projectpage,                           (select     count(1)                             from          tblstatsessionroutes, tblstatsessions                             where      tblstatsessionroutes.statsessionid = tblstatsessions.id and tblstatsessions.projectid = tbladclicks.projectid and                                                     (tblstatsessionroutes.leftpageid = tbladclicks.projectpage or                                                    tblstatsessionroutes.rightpageid = tbladclicks.projectpage)) as totalviews from         tbladclicks where projectid in (select projectid from tblprojects where userid = 5) group by projectid, urlid, projectpage order by projectid, urlid 	0.201078997028592
4608389	4163	group sql query	select votes_no, votes_yes, votes_yes-votes_no as votes_calc from (select sum(case when vote = 0 then 1 else 0 end) as votes_no,              sum(case when vote = 1 then 1 else 0 end) as votes_yes       from comments_votes       where id_comment = 1) a 	0.595756005863289
4609753	1142	mysql join with multiple values in one column	select user, group_concat(names separator ',') from table1 left join table2 on table1.id = table2.id group by user 	0.00686288978135809
4610340	7086	mysql group by and sort by with joins	select t.term_id, t.term_name, max(i.timestamp)  from items i   inner join items_terms it using(item_id)   inner join terms t using (term_id) group by t.term_id, t.term_name order by max(i.timestamp) desc limit 5 	0.593219375199589
4613015	7149	display records through sql in oracle	select id, name   from (        select id,name, row_number() over( order by name) r        from member         where name like 'a%'  )  where r between fromrownum and torownum; 	0.00392855673867238
4613631	39282	sql query: get first 20 and number of total items in one query	select sql_calc_found_rows item.* from #__gallery_items as item order by created desc limit 0,20 select found_rows() 	0
4613819	2640	sql query that returns static values into rows instead of columns	select 'foo1' as foo union all select 'foo2' as foo 	6.13306730321303e-05
4614316	34574	rows with null value for group_concat not returned	select  `a`.`id` , `a`.`name` , `b`.`id` as  `b_id` , `b`.`name` as  `b_name` ,    ifnull(group_concat(  `c`.`l_id` ), '') as  `c_ls` from  `a` inner join  `b` on  `a`.`b_id` =  `b`.`id` left outer join  `c` on  `a`.`id` = `c`.`a_id` group by `a`.`id` order by  `a`.`created` desc 	0.0536755317312134
4614337	9452	how to select a row by primary key in sqlite3?	select * from "soft drinks" where "drink name" = 'coke'; 	0.00154134506001053
4614783	32441	oracle sql query to display one row for each deptid	select distinct r_id     , first_value(d_id) over (partition by r_id order by d_id) d_id     , first_value(dept) over (partition by r_id order by d_id) dept from your_table order by r_id; 	0
4615249	30199	different result from select and from select inside a view	select person_id as p, currency_id as c, sum(case action_type_id when 1 then sum when 2 then -sum end) as sum from actions group by currency_id, person_id order by person_id, currency_id; 	0.000972097366027883
4615869	40926	excel & sql: how to convert string to double in select statement	select  *  from ["&strsheetname&"$]   where cint(testcaseid)  >= " & abs (strrow) 	0.521477599519985
4617558	38420	can i do i mysql query across 3 tables sharing multiple primary keys?	select requests.request_id,requests.user_id,requests.profile_id,requests.job_title,requests.date,requests.time,requests.info,requests.approval, profile.first_name, profile.last_name, othertable.other_field from requests  left join profile on requests.profile_id = profile.profile_id  left join othertable on requests.profile_id = othertable.profile_id  where request.user_id = '$user_id' order by approval as 	0.00293210799211677
4617739	13898	i get no results using like in mysql when names contain caps characters or not	select * from table_name where lower(column_name) like '%pescado%'; 	0.086882639436373
4618057	7028	last login joining two tables	select m.userid, max(l.login)     from members m left outer join login_history l    on m.userid = l.userid group by m.userid 	0.00016185314320567
4618756	24042	what is the best way of storing a geographical information in a relation db?	select *    from customer        left outer join city    on (customers.cityid = city.cityid)        left outer join state   on (city.stateid     = state.stateid)        left outer join country on (state.countryid  = country.countryid)  where customerid = 1234 	0.0355619503209348
4619090	30623	append results from two queries and output as a single table	select * from products where producttype=magazine union select * from products where producttype = book 	0.000316549437646769
4620040	15411	calculation in sql statement	select customerid, (case when channelid = 1 then 1 else 0 end) as chan1, (case when channelid = 2 then 1 else 0 end) as chan2 from .... 	0.798703123950077
4623993	19949	sql server: performant way of getting data from two tables	select parent.fields   from parent  where <filters on parent columns>    or exists(          select 'x'             from child            where child.parent_id = parent.parent_id             and <filters on child columns>); 	0.000656245593809002
4624363	16850	all months total of checklist	select * from (     select c.checklist_name,         b.branchname,         count(*) itemcount     from dbo.checklist_detail cd     join dbo.checklist_master c         on c.checklist_id = cd.checklist_id     join dbo.branch_master b         on b.branch_id = cd.branch_id ) a pivot (     min(itemcount) for branchname in     (         [br1], [br2], [br3], [br4], [br5], [br6],         [br7], [br8], [br9], [br10], [br11], [br12]     ) ) b 	0
4625190	6010	mysql union query	select     m1.id as myid,     m1.fname as myidname,     m1.pic as myidpic,     m2.id as user,     m2.fname as username,     m2.pic as userpic,     m1.status from     members m1         inner join friends f on m1.id = f.myid         inner join members m2 on f.user = m2.id 	0.641551068668689
4625229	16104	sql server t-sql get data into xml using for xml path	select  (     (select          'zoneid' as 'fieldname',     zoneid as 'fieldvalue'     from [dbo].[condition_t_zones]     where zoneid = [condition_t_zones].zoneid     for xml path('field'), type)  ) as 'insert', (                 (select          'zonename' as 'fieldname',     zonename as 'fieldvalue'     from [dbo].[condition_t_zones]     where zoneid = [condition_t_zones].zoneid     for xml path('field'), type)         )  as 'insert'      from [condition_t_zones] for xml path('record'), root('batch') 	0.0289810218858458
4626871	36166	what would mysql look for getting data from 2 tables if they do not match to table 3?	select u.email from users as u  left join table3 t3 on u.email = t3.email where t3.email is null union  select s.email from subscribers as s left join table3 t3 on s.email = t3.email where t3.email is null 	0.000470007096186172
4629128	22926	exlude duplicate data access query	select mytable.tid, mytable.date,         mytable.item, min(mytable.total) as minoftotal from mytable group by mytable.tid, mytable.date, mytable.item; 	0.204462952050918
4630757	28739	mysql different conditions in a single query	select (avg(t.rating1) + avg(t.rating2)) / 2 as total_rating         ,avg(t.rating1) as rating1       ,avg(t.rating2) as rating2       ,avg(case when cond = '1' then price end) as price_used       ,avg(case when cond = '2' then price end) as price_new   from t     where t.approved = '1' 	0.0189190577059044
4630856	37677	sql query to get the table names which use a particular column as a foreign key	select object_name(fkc.parent_object_id) as tablename     from sys.foreign_key_columns fkc         inner join sys.columns c             on fkc.referenced_object_id = c.object_id                 and fkc.referenced_column_id = c.column_id     where fkc.referenced_object_id = object_id('dbo.person_table')          and c.name = 'person_id' 	0
4634389	3517	mysql how do i join and select visible records from one table?	select old_table.padid, new_table.padid from `jules-fix-reasons`.`pads` as old_table join `jules`.`pads` as new_table on old_table.padid = `jules`.`pads`.`padid` where new_table.removemedate<>'2001-01-01 00:00:00' and  old_table.removemedate='2001-01-01 00:00:00' 	0.000217315041525919
4635063	31843	sql select statement	select * from users where username in ('chris', 'bob', 'bill'); 	0.572900891335646
4636837	34782	sql join only returning 1 row	select tl.*,         (tl.topic_total_rating/tl.topic_rates) as topic_rating,         count(pl.post_id) - 1 as reply_count,         min(pl.post_time) as topic_time,         max(pl.post_time) as topic_bump    from topic_list as tl    join post_list  as pl on tl.topic_id = pl.post_parent   where tl.topic_board_link = ?       and tl.topic_hidden != 1   group by tl.col1, ..., topic_rating  order by ?    	0.0178747138508971
4642050	9537	mysql find location of row	select @rownum:=@rownum+1 ‘rank’, p.* from player p, (select @rownum:=0) r order by score desc limit 10; 	0.000781860349524785
4643381	15377	how do i compare two tables data?	select table1.id from table1 left join table2 on table1.id = table2.id where table2.id is null 	0.00114235458898697
4643570	37561	custom ordering in sqlite	select _id, name, key      from my_table t  order by case when key = 'key' then 0                when key = 'named' then 1                when key = 'contributing' then 2 end, id; 	0.70560855602634
4643895	10915	sql and/or conditions for two tables	select  persons.* from    persons   join  person_characters   on    person_characters.person_id on persons.id     and       person_characters.character_id in (101,106)       person_characters.character_id in (         select characters.id         from   characters         where  characters.description in ('cheerful','firm')       ) 	0.0818702575523404
4645068	8849	join two counts in sql query	select  (select count(1) from binaryassets.binaryassetstags where tagid = 1731)  +  (select count(1) from planning.scheduletag where tagid = 1731)  as total_sum 	0.187269099763709
4645322	20664	how to group number of users by age bands in mysql	select   count(*),   case     when age >= 10 and age <= 20 then '10-20'     when age >=21 and age <=30 then '21-30'     when age >=31 and age <=40 then '31-40'     when age >=41 and age <= 50 then '31-40'     when age >=51 and age <=60 then '51-60'     when age >=61 then '61+'   end as ageband from   (      date_format(now(), '%y') - date_format(data_of_birth, '%y') - (date_format(now(), '00-%m-%d') < date_format(data_of_birth, '00-%m-%d')) as age,  .. ..   ) as tbl group by ageband 	0.000222806653105252
4646149	39323	select dept names who have more than 2 employees whose salary is greater than 1000	select d.deptname from department d where (select count(*)                      from employee e                      where e.deptid = d.deptid and                             e.salary > 1000) > 2 	0
4647775	39671	large in statement - data from spreadsheet	select email_address, created_date from people      where email_address in (select email_address from email_table) 	0.0905167137586778
4650420	7623	auto-suggest of airfields - how to order "best match first" across several columns?	select sum(     if(`name` = :input, 50, 0),     if(`iata` = :input, 50, 0),     if(`icao` = :input, 50, 0),     if(`name` like concat('%', :input, '%'), 25, 0),     ... ) from table; 	0
4650744	14636	mysql multiple row to single row	select     a.post_id,     a.organisation_id,     b.organisation_id from your_table a left join your_table b     on a.post_id = b.post_id and a.organisation_id < b.organisation_id 	0.000538144372042432
4651231	14696	conditional display	select.... case when active = 'active' then 'y' else 'n' end .... from table 	0.0921700997579407
4651594	27400	mysql search - return id only if it's present in all of the conditions	select memberid from services where serviceid in (...) group by memberid having count(*) = x; 	0
4654089	33614	joining multiple rows and summing them with mysql (and php)	select t.order_id, t.order_type, sum(t.order_amount) from (select order1_id as order_id, order1_type as order_type, order1_amount as order_amount       from orders       union all       select order2_id as order_id, order2_type as order_type, order2_amount as order_amount       from orders         union all               select order3_id as order_id, order3_type as order_type, order3_amount as order_amount       from orders        union all                select order4_id as order_id, order4_type as order_type, order4_amount as order_amount       from orders           union all             select order5_id as order_id, order5_type as order_type, order5_amount as order_amount       from orders) t group by t.order_id, t.order_type 	0.00186855721886387
4655433	31593	how to force mysql to return limited rows?	select * from mytable 	0.0119981131615687
4657973	36387	remove time from datetime sql server 2005	select convert(varchar(10),getdate(),105) 	0.0200753482997048
4658151	36068	loop through table, check name, and add total	select sum(col1) from table group by company; 	0.000217632256456545
4659089	34455	reading full rows in java resultset	select concat(a, b, c, d, e) as mysinglestringcolumn from table 	0.0546890095723433
4659107	21545	sql update (but only if its going to be unique)	select count(*)  from [knw].[dbo].[nop_productvariant]  where barcode = '" + item + "' and productvariantid <> '" + s + "'" 	0.0160190564481493
4659603	29444	mysql count multiple foreign keys	select s_id, s_name, s_main_url, numpages, numlinks from sites,  (select count(p_id) as numpages from pages where pages.site_id = sites.s_id) as cnt_pages, (select count(l_id) as numlink from links where links.site_id = sites.s_id) as cnt_links order by s_id asc 	0.00380827510798775
4660022	21577	make mysql ignore "the" from the start of a like condition?	select  * from    company where   (name like '?%' and not name like 'the %')         or name like 'the ?%' 	0.00783789638103386
4661137	2873	how do you format a number into a string with padded zeros?	select right('00000' + cast(number as nvarchar), 5) 	0.000346760478910127
4661373	16720	getting the avg of the top 10 students from each school	select sch_code,        schabbrev,        round( avg( totpct_stu ), 1 ) as top10 from   (select sch_code,                schabbrev,                totpct_stu,                @num := if(@group = sch_code, @num + 1, 1) as row_number,                @group := sch_code as dummy         from   test_table         order by sch_code, totpct_stu desc) as x where  row_number <= 10 group by sch_code,        schabbrev 	0
4663622	24666	match ... against on more field: give more importance to first field?	select * from  (select * from  where  match(title) against ('word1')  union select * from  where  match(text) against ('word1')  ) t limit 100 	0.000234577558686834
4664361	15387	order and group by date in mysql	select first(id), idcat, first(name), first(date) as d from mytable group by idcat order by d; 	0.1143024155928
4664797	4347	seperate sql queries per word for dynamic pages?	select page_title, page_text, page_footer, page_blah  from page_table where page_id = 123 and lang = 'fr' 	0.0140896277172454
4666042	26710	sql query to get total rows and total rows matching specific condition	select  count(*), count(case when type='a' then 1 end) as count_a, count(case when type='b' then 1 end) as count_b, count(case when type='c' then 1 end) as count_c, from table1; select type, count(*)  from table1  group by type with rollup 	0
4666380	8513	how can i do the following query to get needed information	select      cl.compid,     cl.mcid,     cl.station,     cl.slot,     cl.subslot,     bt.lineid,     bt.mcid     as bookingmcid,      bt.station  as bookingstation,      bt.slot     as bookingslot,      bt.subslot  as bookingsubslot from complist as cl join bookingtable as bt on bt.compid = cl.compid 	0.157741814490956
4669134	2252	php / mysql - how to get rankings of users?	select  count(*) + 1 from    users where   (rating, name) <         (         select  rating, name         from    users         where   name = 'john'         ) 	0.00146981913617637
4674040	16707	fetch views by (unique viewers and unique videos)	select user, video     from views     group by user, video 	0.000940458791811326
4675605	29190	speeding up a group by date query on a big table in postgres	select * from action_report 	0.17810558099239
4677287	28911	convert row to column	select t.inv,          max(case when t.description = 'charges' then t.amount else null end) as charges,          max(case when t.description = 'freight' then t.amount else null end) as freight,          max(case when t.description = 'insurance' then t.amount else null end) as insurance     from your_table t group by t.inv order by t.inv 	0.00661298346256092
4678317	18893	perform operation on return value	select measuremententry * 1000 as measuremententry    from log 	0.12899212144018
4680867	38020	group by date, confirm, pending	select date, sum(case confirm when 1 then 1 else 0 end) confirmed,   sum(case confirm when 0 then 1 else 0 end) pending,  from table group by date 	0.0553376762508312
4680882	36838	extracting xml (as xml type) using xpath query in sql	select cast(table.xmlcolumnname.query('/head/instance/tag1') as varchar(max)) 'col'; 	0.376914812250223
4681628	4797	sql how to write a query to retrieve latest post	select comment   from comment  order by date desc ,time desc limit 10 	0.000308260212386309
4681744	40468	android get list of tables	select * from sqlite_master where type='table' 	0.00229874502406076
4681918	37872	mysql statement that groups results, but also returns the lowest and the highest value of another column from within the group	select `page`, min(`timestamp`) as startdate, max(`timestamp`) as enddate     from `hypothetical_table`      where `visible` = 1          and `foo` = 'blargh'      group by `page`      having count(`page`) >= 1      order by `page` asc 	0
4682621	10366	sql: how to select rows from a table while ignoring the duplicate field values?	select distinct(user_id) from messages order by id desc limit 5 	0
4683177	2377	get latest exchange rate for all currencies	select      c.currency     c.exchange_rate  from         currencies  c        inner join          (select              max(datestamp) datestamp , currency         from              currencies           group by              currency) current_exchange         on c.datestamp  = current_exchange.datestamp          and       c.currency = current_exchange.currency 	0.000311985571307863
4686003	2841	count rows in joined table but display 0 if no rows exist - mysql	select date_format(launched_date,'<nobr>%e-%b-%y %h:%i:%s</nobr>'), survey.name, survey.iris_type, survey.launched_by, count(response_header_2010.survey_id) as response_count, survey.survey_id, survey.name  from survey left join response_header_2010     on survey.survey_id = response_header_2010.survey_id where survey.status='live'  and survey.iris_type!='recipient list' and client_id = '98' group by  survey.survey_id, survey.name order by response_count 	0
4687060	31110	sql query to find all tables in a database that have a column with a specific name	select      table_name  from      information_schema.columns  where     column_name = 'x' 	0
4687312	10803	querying within longitude and latitude in mysql	select id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) as distance from markers having distance < 25 order by distance limit 0 , 20; 	0.334160361881575
4687504	6080	is it possible to compare 2 sqlite files and update	select * from x.tab except  select * from y.tab union all select * from y.tab except select * from x.tab 	0.0473416256351839
4687748	38567	is it better to run 100 sql queries with a where clause that has one condition, or one query with a where clause that has 100 conditions?	select * from users where username in ('value1',...,'value100'); 	0.608958516211665
4688086	22823	cannot insert duplicate record in a table	select keycol1 {,keycol2 {,keycol3} ...}, count(*) from tablename having count(*) > 1 	0.00285443269233561
4688271	10913	mysql count from same table and data from the other table	select a.id, a.regname, count(1)   from reg_table a, details_table b,     details_table c  where b.replyid=10    and b.regid = a.id      and c.regid = a.id group   by a.id, a.regname 	0
4688359	34634	mysql:displaying of two rows in a single row	select a.employeename,            a.branch,            a.date, b.branch previousbranch,                    b.date previousdate     from       ( select date_format(max(a.effectivedate),'%d-%m-%y') as `date`,                concat(a.firstnm,' ',ifnull(a.miidlenm,' '),' ',ifnull(a.lastnm,' ')) as `employeename`,                `b`.`branchname` as `branch`        from `tbl_employeemaster` as `a`        inner join `tbl_branch` as `b` on a.brnnm = b.idbranch) a     left join       (select date_format(max(c.effectivedate),'%d-%m-%y') as `date`,               concat(c.firstnm,' ',ifnull(c.miidlenm,' '),' ',ifnull(c.lastnm,' ')) as `employeename `,               `d`.`branchname` as `branch`        from `tbl_employeehistory` as `c`        inner join `tbl_branch` as `d` on c.brnnm = d.idbranch) b    on a.employeename = b.employeename 	0
4688782	20385	use the if else condition for selecting the column in mysql?	select if(t1.accountno is null, t2.tempaccountno, t2.accountno) as optional_field      from table2 t2 left join t1 on t1.accountno = t2.accountno 	0.0331829785784695
4689484	13633	get the previous date and hour from a table in sqlite	select *   from ( select data, hour from commentstbl           where data < mydate              or ( data = mydate and hour < myhour )           order by data desc, hour desc           limit 1         )  union all select *   from ( select data, hour from commentstbl           where data > mydate              or ( data = mydate and hour > myhour )           order by data asc, hour asc           limit 1        ) 	0
4690687	17279	postgresql query - count column values matching on two columns	select    agency.city,   count(case when customer.status = 'new' then 1 else null end) as new_customers,   count(case when customer.status = 'regular' then 1 else null end) as regular_customers,   count(case when customer.status = 'gold' then 1 else null end) as gold_customers  from    agency, customer  where    agency.id = customer.agencyid  group by   agency.city; 	4.73183166470157e-05
4692604	16382	conditional sum t-sql	select col1      , sum(col3) as total      , sum(case when col2 is not null then col3 else null end) as valid   from mytable  group by col1 	0.674114384755531
4692884	9710	return null on condition in sub-table	select * from person p left join job j on p.job_id=j.j_id and j.j_active=1 	0.0972193142185167
4693018	21020	sql statement to get the most frequent hours and/or period for a user	select count(id) as count, hour(datetime) as hour from table group by hour order by count desc limit 1 	0
4694763	33006	printing out list of attribute descriptions based on boolean columns in sql	select     substring (        case when isproductionworker = 1 then ', production worker' else '' end +        case when ismaterialhandler= 1 then ', material handler' else '' end +        case when isshopsupervisor= 1 then ', shop supervisor' else '' end +        ... ,        3, 8000) from     mytable where      ... 	0
4694964	18193	mysql - joining a table to itself, but keeping original results	select t1.graph_id, t1.col1, t1.col2, t2.col1, ... from (     select graph_id, sum(...) as total     from ...     group by ... ) t1 join (     select graph_id, min(...) as minfoo, max(...) as maxfoo     from ...     group by ... ) t2 on t1.graph_id = t2.graph_id 	0.00808045904337238
4697792	24774	age range query in mysql based on two age fields	select *   from ages  where 32 between age_start and age_end 	0
4699871	25625	limit based on count	select id, pid, name from yourtable where pid = 0 union all (     select id, pid, name     from yourtable     where pid <> 0     limit 10 ) 	0.00565214091633159
4701144	26963	join two subquery in mysql	select * from table1, table2; select * from table1 inner join table2 on table1.id=table2.id; select * from table1 left join table2 on table1.id=table2.id; select * from table1 left join table2 using (id); 	0.47313847992017
4703306	7558	mysql select max multiple tables : foreach parent return eldest son's picture	select       prequery.parentid,       p.name parentsname,       c.childid,       c.age,       cp.imgurl    from        ( select                c.parentid,               max(c.age) oldestchildagewithpicture            from               children c,               childrenpictures cp            where               c.pictureid = cp.pictureid            group by                c.parentid ) prequery,       parent p,       children c,       childrenpictures cp    where           prequery.parentid = p.parentid       and prequery.parentid = c.parentid       and prequery.oldestchildagewithpicture = c.age       and c.pictureid = cp.pictureid 	0.0105850532755529
4706254	15769	filter away specific rows from php mysql fetch array result	select `sl`, `name`, `value` from `table` where `value` != 2 	0
4707312	11120	mysql left join on multiple tables	select year(calendar.date_field) as year,  monthname(calendar.date_field) as month,  sum(invoice_payments.paid_amount) as total  from calendar  left outer join invoice_payments on calendar.date_field = invoice_payments.date_paid  left outer join invoice on invoice_payments.invoice_id = invoice.invoice_id  left outer join (select * from client where registered_id = 1) as c on c.id = invoice.client_id group by year(calendar.date_field), month(calendar.date_field) 	0.435895183103954
4709755	40958	what's the best practise if i want to fetch data from two table?	select agent.id as id ,agent.name as name, shop.id as shop_id, shop.name as shop_name from agent inner join shop on agent.shop_id=shop.id where agent.id=$id; 	0.000111608282707716
4710406	38888	alternative to using group by without aggregates to retrieve distinct "best" result	select  s2.id ,       s2.title ,       s2.episode ,       s2.is_hidef ,       s2.is_verified from    (         select  distinct title         ,       episode         from    shows         where   title = 'the simpsons'          ) s1 join    shows s2 on      s2.id =          (         select  id         from    shows s3         where   s3.title = s1.title                 and s3.episode = s1.episode         order by                 s3.is_hidef desc         ,       s3.is_verified desc         limit   1         ) 	0.111482514700297
4710684	24275	row number only for matching rows by id?	select category, empname, row_number() over(partition by category) 	0
4710709	32840	using mysql syntax to select based on unique columns?	select distinct city, state from table_name; 	0.00183788664714826
4710919	11546	sql*plus: difference in number of rows in two tables	select ((select count(*) from dual44) - (select count(*) from dual)) from dual 	0
4711963	946	is there any difference between these three uses of dateadd?	select datepart(dayofyear,'20111231')  select datepart(day,'20111231')  select datepart(weekday,'20111231')  	0.118023275201239
4713071	28209	add a dynamic field to a mysql table based on a functions value	select * from products where  cost_price * 1.2 *   (select user_level * $some_coefficient from users where user_id = $uid)  between x and y 	0.00011444184670744
4713213	8960	how to conditional select table rows using sql	select * from mytable where change_key = 4 and (system_key = 1 or system_key = 2) 	0.0410566291562735
4713527	37479	easy way to copy rows between identical table schemas [visual studio 2010]	select * into <destination table> from <source table> example: select * into employee_backup from employee 	0.412907344238821
4713878	20199	fetch max from a date column grouped by a particular field	select distinct mytable.logid, mytable.entered from mytable inner join (select refid, max(entered) as entered from mytable group by refid) latest on mytable.refid = latest.refid and mytable.entered = latest.entered 	0
4713898	29293	show biggest margin between 1st and 2nd within group	select    first_place.name,    max_points-max(points) as max_margin  from the_table inner join    (select name, day, max(points) as max_points     from the_table group by day) as first_place  on the_table.day=first_place.day  where the_table.points<max_points  group by the_table.day  order by max_margin desc limit 1 ; 	0.000322761421807804
4715696	33548	parse xml string stored on oracle table	select   extractvalue(xmlcol, '/*/textbox[@name=''txtaddress11'']') txtaddress from yourtable 	0.21360692179604
4716016	40917	mysql joins tables creating missing dates	select m.date, from_unixtime(i.time, '%y-%m-%d'),`time`,`protocal`,(`octet`/1024) as `octet10243`,`percent`,`div`,from_unixtime(`time`, '%y-%m-%d') as `newtime3`      from makeupdate m         left join ipport i             on m.date = from_unixtime(ipport.time, '%y-%m-%d')                 and (`protocal` = 'echo' )                  and `div` = 'xdiv'     where m.date >= '2011-01-05' and m.date <= '2011-01-08' 	0.281765711259214
4716369	524	give priority to order by over a group by in mysql without subquery	select v.* from (     select program, max(id) id     from versions     group by program ) m inner join versions v on m.program=v.program and m.id=v.id 	0.390568275128666
4717093	28270	mysql find related articles	select fa.id, fa.title from    articles ba,    articles_tags bat,    articles_tags fat,    articles fa where     ba.title = 'some name'   and    ba.id = bat.article_id   and    bat.tag_id = fat.tag_id    and    fat.article_id = fa.id  and    fa.title != 'some name' group by      fa.id, fa.title having    count(*) >= 3 	0.00152254152041389
4717489	21863	how do i exclude outliers from an aggregate query?	select m.unit,         count(*) as count,         sum(m.timeinminutes) as totaltime from             (select              m.unit,              ntile(20) over (order by m.timeinminutes) as buckets          from              main_table m          where              m.unit <> '' and m.timeinminutes > 0         ) m where          buckets between 2 and 19 group by m.unit having  count(*) > 15 	0.128213195410087
4718548	14815	joining two sql tables in a query	select table2.title  from table2  cross join table1 where (table1.d0*table2.d0)+(table1.d1*table2.d1)+(table1.d2*table2.d2) < 0.5; 	0.0274843817881319
4718946	18874	sql trend over time	select  (case when date <= dateadd("d", -1, getdate) then score else 0 end) as sum1, (case when date <= dateadd("d", -2, getdate) then score else 0 end) as sum2, etc. 	0.313454487030785
4718985	16507	determine which or statement selected the record?	select ...     , case         when a = 525 and b = 324 and c = 4523 then criteria_row_1_pk         when d = 'asdf' and e = 3.43 then criteria_row_2_pk         ....         end as successclausepk 	0.00645628064577898
4721442	5211	query to search for maximum value in a row, rather than within a column - sql/mysql	select greatest(col1, col2, col3, col4, col5, col6, col7, col8) as max_date   from your_table 	0
4727786	39487	how to get the dataset to recognize the table names from stored procedure?	select 'products' as thistable, <fields> from products where productid = @productid 	0
4727906	31026	sql max(m.time) does not select the highest value	select m2.message,            m2.time as time,            m2.sender,            m2.receiver,            m.contact,            u.ufirstname from (     select         case when sender_uid = '$me' then receiver_uid else sender_uid end contact,         max(time) maxtime     from messages      where sender_uid = '$me' or receiver_uid = '$me'     group by case when sender_uid = '$me' then receiver_uid else sender_uid end ) as m inner join messages m2 on m.maxtime = m2.time     and ((m2.sender_uid = '$me' and m2.receiver_uid = m.contact)         or         (m2.receiver_uid = '$me' and m2.sender_uid = m.contact)) inner join users as u on m.contact = u.uid order by time desc; 	0.0116748088166878
4728577	19538	get some random and some specific records in a single query?	select random   union select choosed 	0
4728845	36152	table join full values	select d.id, d.name, cd.customer_id      from distributionlists d left outer join         (select customer_id, dl_id from customer_dl where customer_id = 2) cd      on d.id = cd.dl.id 	0.128668173314865
4730044	2579	select distinct field on join in mysql	select * from gr3_pracmath_jan11_d1 left join student_list_011811  using (studentid) 	0.0411118059081641
4730370	15566	mysql, count the number of "filled" fields in a table	select count(*) as `total`, sum(if(`text` <> "",1,0)) as `non_empty` from `table` 	0.000198442291245294
4732872	36078	mysql between query w/ between ? and?	select `foo` from `bar` where `datetime` between ? and ? 	0.196920477775491
4733619	18763	select random data with a nested query?	select * from  (   select * from your_table   where some_conditions   limit 1000 )  as some_aliases order by rand() limit 4; 	0.311016470708308
4735466	28979	mysql: select from table a, if id matches 2 (or arbitrary n) rows in table b	select  * from    a where   (         select  count(*)         from    b         where   b.id_a = a.id                 and b.tag in ('foo', 'bar', 'baz')         ) = 3 	0
4735648	24641	select sql query	select  case p1 when 0 then t2.status else t3.status end from    t1 left join         t2 on      t2.p1 = p1 left join         t3 on      t1.p1 = 0         and t3.p2 = t1.p2 	0.448716452127667
4736887	34578	how do i create a sql distinct query and add some additional fields	select  * from    (         select  *, count(*) over (partition by firstname, lastname) as cnt         from    contacts         where   contacttypeid = 1         ) q where   cnt > 1 order by         cnt desc 	0.021654300165234
4738187	19427	change results in mysql query	select        count(*) as totalrecs,       case status          when 1 then "initial order"          when 2 then "cancelled    "          when 3 then "whatever     "          else        "all others   "       end case as wordstatus    from       yourtable    group by        2 	0.353336038479043
4740489	40717	query to find an average weighted price	select part, sum(qty*price_per)/sum(qty)   from <your_table> group by part 	0.000797477074778204
4740612	15902	query to convert from datetime to date mysql	select cast(orders.date_purchased as date) as date_purchased 	0.00613259117383491
4741297	14185	tsql problem - link table	select u.username     , u.firstname + ' ' + u.lastname as full_name , case      when rd.related_uniqueid is not null then rd.relateddataid     when rd1.uniqueid is not null then rd1.relateddataid     else 0     end as relatedid from users as u     left join related_data as rd         on rd.uniqueid = u.uniqueid             and (                 rd.related_uniqueid = @uniqueid                 or rd.uniqueid = @uniqueid                 )     left join related_data as rd1         on rd1.related_uniqueid = u.uniqueid             and rd1.uniqueid = @uniqueid where u.deleted = '0'     and u.persontypeid = @persontypeid 	0.516757065194257
4743619	36736	ordering and randomizing a query at the same time	select * from products order by views desc, rand() limit 5; 	0.00271913664075089
4744198	29608	how to write this particular query?	select * from mytable where title not like 'test - %' 	0.743437119695295
4744278	37883	union two tables and order by a common field like name which is present in both the tables	select slug, name, 1 as mt    from tablea  union  select slug, name, 0 as mt    from tableb   order      by name; 	0
4747914	1635	find foreign key information using perl/dbi/mysql/innodb	select null as pktable_cat,    a.referenced_table_schema as pktable_schem,    a.referenced_table_name as pktable_name,    a.referenced_column_name as pkcolumn_name,    a.table_catalog as fktable_cat,    a.table_schema as fktable_schem,    a.table_name as fktable_name,    a.column_name as fkcolumn_name,    a.ordinal_position as key_seq,    null as update_rule,    null as delete_rule,    a.constraint_name as fk_name,    null as pk_name,    null as deferability,    null as unique_or_primary from information_schema.key_column_usage a,    information_schema.table_constraints b where a.table_schema = b.table_schema and a.table_name = b.table_name    and a.constraint_name = b.constraint_name and b.constraint_type is not null    and a.table_name = ? order by a.table_schema, a.table_name, a.ordinal_position 	0.000788326915257594
4749233	16564	nested group by	select group, sum(age) from people where group > '' group by group union select personname, age from people where group is null 	0.736681734013638
4749948	25936	sql specific question - get child that belong to all item of a collection	select cityname, count(distinct userid)  from  user u inner join person p on  u.personid = p.personid  inner join adresse a on  p.addressid = a.addressid inner join city c on a.cityid = p.cityid  group by cityname 	0
4751117	15874	mysql, order-by, check if and item is included in another table first	select itemid from table2 left join table1 using (itemid)  where id = '1' order by title desc, time desc 	0.000107187925272642
4751361	39889	using mysql in clause as all inclusive (and instead of or)	select i.moviename     from item i         inner join itemcategory ic             on i.item_id = ic.item_id     where i.item_id = 55         and ic.category_id in ('5','8','9')     group by i.moviename     having count(distinct ic.category_id) = 3 	0.0850387517811926
4753633	30240	how do i sort using two fields?	select      headline,             the_date,             day(the_date) as the_day from (     select      headline,                 pub_date as the_date     from        stories     union     select      headline,                 update_date as the_date     from        stories     where       update_date is not null ) as publishedandupdated order by    the_date desc; 	0.0122919283590456
4755392	1236	joining 2 tables indirectly through a relationship table	select * from bands b inner join band_genre bg on b.band_id = bg.bg_band inner join genres g on bg.bg_genre = g.genre_id 	0.00148844043917568
4755518	40071	postgresql select additional columns that aren't used in aggregate function	select users.*, a.num_deals from users, (     select deal.id as dealid, count(deals.id) as num_deals      from deals      group by deal.id ) a where users.id = a.dealid order by a.num_deals desc limit 5 	0.434329738392784
4758198	16090	datetime (timezones) in php web applications	select * from todos where convert_tz('2011-01-21', 'est', 'utc') between curdate() and date_add(curdate(), interval 1 day) 	0.734598978214939
4758387	24023	casting character varying field into a date	select...     from details d     join quesionnaires q on d.id=q.id order by least (decrypt_me(onsetdate), questdate::date) 	0.00492137285445747
4759718	25447	mysql php group by day and total for each day	select date(tstamp), sum(value)   from your_table  group by date(tstamp); 	0
4761517	15768	t-sql: select related column data for the max two other columns	select order_type      , po_num      , max(order_num)   from orders o1  where order_type = (          select max(order_type)            from orders o2           where o2.po_num = o1.po_num       )   group by po_num,order_type 	0
4762652	35562	join two tables, ignore records from first table if exists in second	select    isnull(a.column1, b.column1),      isnull(a.column2, b.column2)   from    tablea a    full outer join    tableb b on a.column1 = b.column1   	0
4764650	15208	sql query where all records in a join match a condition?	select u.*  from users as u where u.id not in (     select distinct user_id from tags where name not in ('word1', 'word2') ) and exists (select user_id from tags where user_id = u.id) 	0.00840145946902993
4765422	37556	sql query to calculate the difference of a number of fields and passing to asp script	select max(remainingcapacitybytes) - min(remainingcapacitybytes) diffcapacitybytes    from [check].[dbo].[tbl_backupchecks_mediainfo]     where company = 'company name' and modifieddatetime >= dateadd(d,-7,getdate()) 	6.85012286445044e-05
4767104	10270	how to filter duplicate rows with different value	select model, sum(qty), max(date) from yourtable group by model having sum(qty) <> 0 	6.03475236478035e-05
4770875	26940	mysql join from 3 relative tables	select rp.*, r.role, r.id as role_id, p.id as permission_id,p.name as permission from permission as p cross join  role as r left join role_permission as rp on p.id = rp.permission_id   and r.id = rp.role_id 	0.0205226789825605
4774146	5678	mysql - complex query including lookup columns from several tables	select  i.id, i.checkin,         concat('{\"date\":\"', i.checkin,'\",', group_concat('\"', attribute.key, '\":\"', convert(attribute.value,char), '\"'), '}') as attributes,         l.location, c.color from    (         select  itemid, ats.key, ats.value         from    attributestrings as ats         union all         select  itemid, ati.key, ati.value         from    attributeintegers as ati         ) attribute join    items i on      i.id = attribute.itemid left join         attributeintegers atli on      atli.itemid = i.id         and atli.key = 'location' left join         locations l on      l.id = atli.value left join         attributeintegers atci on      atci.itemid = i.id         and atci.key = 'color' left join         colors c on      c.id = atci.value group by         i.id desc 	0.0117726992948929
4774649	34086	mysql - join same rows with null entries	select name,          max(date1),          max(date2)     from tbl group by name 	0.000485766166180343
4775820	22049	sql - give me 3 hits for each type only	select id, title, type from   (select id, title, type,                @num := if(@group = type, @num + 1, 1) as row_number,                @group := type as dummy         from   your_table         order by type, title) as x where  row_number <= 3 	0.00166035597817668
4776636	4494	sql to get minimum of two different fields	select e.equip_id, min(case when h.install_date < e.install_date_at_location      then h.install_date      else e.install_date_at_location  end)  as first_install_date from equipment e  left join locationhistory h on h.equip_id = e.equip_id group by e.equip_id 	0
4777066	33814	mysql count(*) from multiple tables	select      sum(a.count) from     (select count(*) as count from table1      union all      select count(*) as count from table2) a 	0.00800683073528526
4777928	35395	ranking database entries in mysql	select laptop from table   group by laptop   order by count(laptop) desc 	0.00871608114463935
4780148	15323	how to check if a column is empty or null using sql query select statement?	select * from userprofile where propertydefinitionid in (40, 53)   and (    propertyvalue is null         or propertyvalue = '' ); 	0.289824761068126
4781002	4804	select on results of a select	select * from t1 where column1 = (select column1 from t2); 	0.0123084374275214
4782026	32657	sum on a left join sql	select a.id, sum(b.ach_sell)  from bookings a     left join pricing_line b  on b.bookings = a.id  group by a.id 	0.619110861661032
4782743	11831	sql excluding via join	select  * from    b where   itemid not in         (         select  itemid         from    a         where   a.parentnumber = @parentnumber         ) 	0.242550512443962
4783760	1979	oracle sql query to format number by comma	select  to_char(696585242087, '99g999g999g9999', 'nls_numeric_characters=",."') from    dual 	0.021263820880257
4784191	4823	sql statement to remove duplicates and get counts	select     state,    count(cr_id )    from    (        select  distinct         lkustate.statename as state,         tblmain.cr_id         from lkustate         inner join         (tblmain         inner join (loclink         inner join tblloc         on loclink.geometry_id = tblloc.geometry_id)         on tblmain.cr_id = loclink.cr_id)         on lkustate.fips_state = tblloc.fips_state         where tblmain.lost=false) t group by state 	0.0132966682392483
4784545	24494	sql - how to order using count from another table	select bloggers.*, count(post_id) as post_count     from bloggers left join blogger_posts      on bloggers.blogger_id = blogger_posts.blogger_id     group by bloggers.blogger_id     order by post_count 	0.00120310062727206
4784868	2606	select info from one mysql db if value exist in another db	select latitude, longitude, username, rank    from users inner join online_users on users.username = online_users.username select latitude, longitude, username, rank    from users where username in (select username from online_users) 	0
4785769	22282	sql two tables with different month values. getting one result set for all the months	select [month] from table1 union select [month] from table2 	0
4787205	6731	are sql execution plans based on schema or data or both?	selective 	0.186659241266084
4788644	27715	select latest record in table (datetime field)	select id, thread_id, user_id, subject, body, date_sent   from messages where date_sent in (     select max( date_sent )       from messages where user_id =6 group by thread_id   )   order by thread_id asc , date_sent desc; 	0
4789843	29267	a sql query that acquires the list of categories given a page title from wikipedia	select `categorylinks`.`cl_to` from `page` join `categorylinks` on `categorylinks`.`cl_from` = `page`.`page_id` where `page`.`page_namespace` = 0 and `page`.`page_title` = 'page_name_here' 	0
4790162	21772	sqlite select distinct values of a column without ordering	select distinct column   from table  order by min(rowid); 	0.00160168147047525
4790662	28594	how to send sql count data & array data together?	select studentid, classid, date count(*) from attendance_main where status = 'tardy' and classid like '%adv%'" left join student on student.rfid = attendance_main.studentid group by studentid having count(*) > 3; 	0.00670018488464366
4791099	16568	how to display records in php from stored procedure mysql	select 1 as type, area_id as id ,areaname as name from area union all  select 2 as type , loc_id as id ,locname as name from location; 	0.000625626285474631
4792577	8079	mysql full join (union) and ordering on multiple date columns	select     `newsid`,     `text`,     case         when `datetime` is null then `pdate`         else `datetime`     end as `datetime,     `pcount` ( select * from `news` as `n`     left outer join (                         select count(pictureid) as `pcount`, datetime as `pdate`                         from picture group by date(datetime)                     ) as p on date(n.datetime) = date(p.datetime)      union select *      from `news` as `n`     right outer join (                         select count(pictureid) as `pcount`, datetime as `pdate`                         from picture group by date(datetime)                     ) as p on date(n.datetime) = date(p.datetime)  ) 	0.0685823889009221
4793529	28253	join table query	select m1.id as reg, m1.name as name, f.registered as status  from phone f  inner join members m1 on m1.id=f.user_id  where   (m1.status='1' and f.registered='1') or  (m1.id in (014,01284,014829,075090) ) 	0.382908659365558
4795379	40604	selecting data from two tables	select a.name,a.date   from table1 a  where ...  union all select b.name,b.date   from table2 b  where ... order by 2 desc 	0.000178225842100761
4795386	38454	multiple joins to same table	select i.name as name, v1.value as value_1, v2.value as value_2    from item i        inner join item_value iv on iv.item = i.id        inner join property p on iv.property = p.id        left join value v1 on p.name = 'prop1' and v1.id = iv.value        left join value v2 on p.name = 'prop2' and v2.id = iv.value 	0.0255481958217029
4797800	38201	omitting wikipedia maintenance categories from sql query	select categorylinks.cl_to  from categorylinks  join page on categorylinks.cl_from = page.page_id  and page.page_namespace = 0  and cl_to not like '%article%'  and cl_to not like '%article%'  and cl_to not like '%wikipedia%'  and cl_to not like '%redirect%'  and cl_to not like '%page%'  and cl_to not like '%redirect%'  and page.page_title = "ice_hockey"; 	0.105196953448484
4798069	21425	convert one specific query from text field to date for arithmetic functions	select str_to_date(meta_value,'%m/%d/%y') as date_paid     from `drabble_postmeta`      where meta_key = 'date_paid' 	0.00384271262541922
4799187	17273	how do i transform table- see example?	select t1.a, min(t2.a), t1.b from table_1 t1     inner join table_1 t2 on t2.a > t1.a group by t1.a, t1.b 	0.164737304787028
4799381	33430	adding an column populated by an arbitrary value in sql	select 234 as consumer_id, action_log_id, communications_id    from consumer_action_log   where comm_type_id=4 	0.00579377076357491
4799389	30877	access sql query - group by date range (after midnight problem)	select     dateadd('h', -5, recordedondate) recordedondate,     count(recordedondate) as rowcount,     count(songid) as [total amount] from infotable where (recordedondate > dateadd('h', 5, #1/23/2011#)) and (recordedondate < dateadd('h', 5, #1/24/2011#)) group by dateadd('h', -5, recordedondate) order by recordedondate desc 	0.491120412344921
4801117	14962	is it possible to sort the results of a select query in 2 different ways based on a conditional?	select * from categories order by case when parent = '1'     then menu_order     else id end; 	0.000108201000392945
4801791	32256	do sqlite connections share temp tables in shared-cache mode?	select * from sqlite_temp_master 	0.129294664375554
4802578	15042	i need to join two tables to get all the records from the student_info table	select student_info.student_id, student_info.student_name, student_info.phone, student_info.age, isnull(t.coa, 0) coa   from   student_info   left   join (select student_id, count(*) coa from student_activities group by student_id) t   on     student_info.student_id = t.student_id 	0
4805560	4979	group by week, how to get empty weeks?	select date_format(date, 'y:%x - week:%v') as regweek, count(date) as number      from yourtable right outer join weeks on week(yourtable.date) = weeks.weekno 	7.5671086031408e-05
4806348	5960	how do i sum records by week using pl/sql?	select trunc (created_dt, 'iw') created_dt     ,  count ( * ) allclaims     ,  sum(case when filmth_cd in ('t', 'c') then 1 else 0 end ) ct     ,  sum(case when filmth_cd = 'w' then 1 else 0 end ) web      ,  sum(case when filmth_cd = 'i' then 1 else 0 end ) icon  from claims c where c.clsts_cd not in ('in', 'wd')    and  trunc (created_dt) between      to_date('1/1/2006', 'dd/mm/yyyy') and      to_date('1/1/2100', 'dd/mm/yyyy') group by trunc (created_dt, 'iw') order by trunc (created_dt, 'iw') desc; 	0.0012615169958867
4806717	18448	getting the last record in a top n percent query	select  top 1 time from    (             select  top 10 percent [time]          from    scores          where   lesson = 1          order by                  time         ) as top10  order by         time desc 	0
4808691	8220	how can i combine two count() statements into one and get the difference?	select  sum(votetypeid = @votetype1) - sum(votetypeid = @votetype2) from    votes where   userid = @userid         and votetypeid in (@votetype1, @votetype2) 	0
4809032	1810	group by problem with counting in sql	select     ir.[driverlicensenumber]     ,count(ir.[reportnumber]) as [totatreports]     ,ir.[lastname]     ,ir.[firstname] from [dbo].[interimreports] ir group by ir.[driverlicensenumber]     ,ir.[lastname],ir.[firstname] 	0.746132357543417
4809155	38338	mysql if condition in a calculated field	select ....   case when consumer_expert_id = 1 then 1 else -1 end as my   from consumer_expert_score  where consumer_expert_score_id in (2,1) 	0.0368114301123907
4809166	7723	counts with multiple joins	select  *, total_reviews + total_ratings as total_interactions from    (         select  id,                 (                 select  count(*)                 from    reviews                 where   item_id = i.id                 ) as total_reviews,                 (                 select  count(*)                 from    ratings                 where   item_id = i.id                 ) as total_ratings         from    items i         ) q order by         total_interactions desc limit 1 	0.460738311022824
4810568	15091	can i join two tables with only one match for each row of one table in mysql?	select    classes.class_id,    classes.name,    courses.room from classes    join courses       on classes.class_id=courses.class_id where courses.room=1 group by classes.class_id,classes.name,courses.room 	0
4810807	16698	summing up mysql calculated field where column value is the same	select communications_id, sum(fieldname)  from consumer_action_log where comm_type_id = 4 group by communications_id 	0.000209640307338447
4811241	14146	using count i'm only getting one row back	select user, item, count(*) count from tablename group by user, item order by item 	0.0014703921191743
4811271	17882	get current year and next form mysql	select    *  from    table  where    year(date) = year(curdate())  or    year(date) = year(curdate()) + 1 	0
4811533	3835	mysql combine row results into a new column	select m.date,          m.sponsor,          m.match_no,          group_concat(m.team, separator ' vs ')     from match_no m group by m.date, m.sponsor, m.match_no 	0.000144378935018505
4812460	20775	combine three select queries?	select homeupload, count(*) from link group by homeupload union  select mediatype, count(*) from link group by mediatype union  select emailsub, count(*) from link where emailsub='1' group by emailsub 	0.0586821020214301
4813863	40197	sql server: cte, how to get last row number	select database_name, max(backup_finish_date) from bckhist group by database_name 	0
4815163	32202	designing database	select rec.rec_id,         count(itn.item_id) as [nummatches] from recipe as rec join items_needed as itn on itn.rec_id = rec.rec_id where itn.item_id in (comma-delimited-list-of-itemids) group by rec.rec_id having count(itn.item_id) > 0 order by count(itn.item_id) desc 	0.342073742182517
4816323	9324	finding overlapping intervals using sql	select id, date_start, date_end  from thetable  where date_start <= p_date_end  and date_end >= p_date_start 	0.004587775202781
4817111	58	appending query based on condition in sql stored procedure	select * from tablea where (@param1 = 0 or id=@param1) and (@name = null or column2=name) 	0.14066879012798
4817579	21025	mysql - reference column in function call	select date_add('2011-01-02', interval some_table.column) as newdate from some_table 	0.724390624554572
4818596	7349	how do i group results based on information found (or not found) in another table?	select project, decode(sort, 1, 'lead', 2, 'editor', 'not assigned') role from ( select project, role, case when user_id = <current_user_id> and role = 'lead' then 1                            when user_id = <current_user_id> and role = 'editor' then 2                            else 3 end sort from userprojectrole ) order by sort, project; 	0.000144196307508562
4819358	15846	mysql many to one get as string	select person.id, person.name, group_concat(colour.colour separator ', ') from person join associations on associations.person_id = person.id join colours on colours.id = associations.colour_id group by person.id 	0.00213945865526786
4821192	22449	using (-) in fields	select * from `cool-table` where `cool-id` = 1 	0.169225397808193
4821289	11144	sql - get array of data ordered by occurrences	select code, count(code) from table group by code order by count(code) desc 	0
4822895	28615	combining query results of two different tables	select *  from table1 left join table2 on table1.id = table2.id 	0.000815890568785345
4823353	21609	exclude rows based on other rows (sql)	select *    from table a  where a.val in (1,2,3)    and not exists(select null                     from table b                    where b.id = a.id                      and b.val not in (1, 2, 3)) 	0
4823737	18367	in sql dividing a value by its mean	select tips_amount/communications_id/nullif(avg_tip,0) from consumer_action_log a   # return to table consumer_action_log inner join (     select avg(calc_tips) avg_tip, comm_type_id     from (         select tips_amount/communications_id as calc_tips, comm_type_id         from consumer_action_log) as cal     group by comm_type_id ) b on a.comm_type_id = b.comm_type_id 	0.0357590274206292
4829199	6461	sql: is there a way to get the average number of characters for a field?	select avg(datalength(yourtextfield)) as textfieldsize 	0
4829601	8101	row count mysql with three tables	select  s.name, count(distinct c.id) as classes, count(st.id) as students from    table_schools s left join         table_classes c on      c.school_id = s.id left join         table_students st on      st.class_id = c.id group by         s.id 	0.00924506226977925
4830500	12855	query to get "most recent" joining on other table with date	select eo.id, eo.eventdate, gc.grade     from #eventoccurrence eo         inner join #gradechange gc             on eo.id = gc.id                 and gc.effectivedate = (select max(gc.effectivedate)                                              from #gradechange gc                                              where gc.id = eo.id                                                  and gc.effectivedate <= eo.eventdate) 	0
4830677	40507	calculating commission	select client_id, sum(invoicecommision) as totalsum from tbl_statement_items where fk_rid = '1' and dt > date_sub(curdate(), interval 1 month) group by client_id having totalsum > 25; 	0.112488976788125
4833282	23363	get postgis version	select postgis_full_version(); 	0.101569663686707
4834085	26634	how can i replace a large amount of expressions with a variable or alias?	select long_case_expression, count(1)   from ( select     case          when ...         when ...         ...     end as long_case_expression from table ) a group by long_case_expression 	0.713275777548846
4834176	7189	mysql create table containing values from a column in another table	select distinct cityname from tilistings 	0
4834531	10955	compound sql join?	select *   from t3 inner join t2 on (t3.fkeyt2 = t2.key)           inner join t1 on (t2.fkeyt1 = t1.key)  where t1.name = 'foo' 	0.78738469001904
4834772	8576	get all records from mysql database that are within google maps .getbounds?	select * from tilistings where lat > a and lat < c and lng > b and lng < d 	0
4835208	32543	how to link the following 2 tables to get the result which is shown below in sql server?`	select staffname, tmstamp, noofqno, noofcontent   from (                 select staffname, tmstamp, trackno, count(1) noofqno                     from visit                 group by staffname, tmstamp, trackno              ) a left join              (                 select trackno, count(1) noofcontent                     from matter                  group by    trackno              ) b     on  b.trackno = a.trackno 	0.000355658061538932
4837062	6605	write a query in sql	select table1.name, table1.nmber, table2.check from table1 left outer join table2 on table1.nmber = table2.number 	0.759331639497897
4841260	2366	select a 'virtual' column computed from other existing columns	select `max` - `current` as `result` from table_data order by `result` asc 	0
4847181	32904	convert int values to datetime in sql server	select dateadd(month,(@year-1900)* 12 + @month - 1,0) + (@day-1) 	0.0401279502146
4850181	949	sql ordering with different date fields	select * from foo order by coalesce(created_at, scheduled_at) 	0.0135030348592588
4850408	35212	mysql joining empty rows?	select cities.city, city_date.date_avail from cities left outer join city_date on city_date.city_id = cities.id; 	0.0191817878139498
4850414	28659	mysql query to pull distinct id with multiple wheres	select detailid from (     select detailid, 1 as whichmatch     from tbl     where name like '%a%'     union all     select detailid, 2 as whichmatch     from tbl     where name like '%b%'     union all     select detailid, 3 as whichmatch     from tbl     where name like '%c%' ) sq group by detailid having count(distinct whichmatch) = 3 	0.00387825662165855
4851648	27114	find similar data from different columns in oracle	select * from mytable where substr(tc_no,1,10) = ver_no 	5.91265971444397e-05
4853771	36730	subquery selecting over a select	select  p.*, u.username, u.userimage from    users u join    posts p on      p.postuid = u.useruid 	0.112031441578338
4855276	12247	select rows based on number of duplicates, ordered alphabetically	select country      , count(*)   from thetable  group by country having count(*) > 1  order by country 	0
4858774	9169	oracle/sql - select specified range of sequential records	select *    from ( select a.*, rownum rnum            from ( your_query_goes_here            where rownum <= max_rows )  where rnum >= min_rows / 	0.000424543283414438
4860024	29071	how to get previous row value	select (id, value) from table as table1 join inner join table as table2 on table1.id = (table2.id -1) 	0
4862724	29289	query my block size oracle	select distinct bytes/blocks from user_segments; 	0.791785054208876
4863015	34915	returning table type in table union in sql	select id, name, 'table_1' as type from table1  union all  select id, name, 'table_2' as type from table2; 	0.10196356924938
4864942	25138	mysql query: getting the most recent forum post	select distinct c.name , c.id , t.title , t.id , p.id , p.post , u.id , u.username , from_unixtime(p.`timestamp`) as postdate from category c inner join thread t on t.category_id = c.id inner join post p on p.thread_id = t.id inner join users u on u.id = p.user_id inner join users u2 on u2.id = p.user_id where u2.id = userid_whose_threads_are_to_display and p.timestamp = (select max(`timestamp`) from post where post.thread_id = p.thread_id) order by postdate desc 	0.000270045879296456
4865958	36397	mysql select between time span query optimizing	select u.*, t4.user_id, t4.data, t4.a, t4.ucount, u.userid as ip from (     select user_id, data, a, ucount,         @r := case when @g = user_id then @r+1 else 1 end rownum,         @g := user_id     from     (select @g:=null) g     cross join     (     select t1.user_id, t1.data, addtime(t1.data,'24:00:00') a, count(*) ucount     from downloads t1     inner join downloads t2 on t1.user_id = t2.user_id                         and t1.data <= t2.data                         and addtime(t1.data,'24:00:00') >= t2.data     group by t1.user_id, t1.data     having count(*) > 100     order by t1.user_id, ucount desc     ) t3 ) t4 left join users u on u.id = t4.user_id where t4.rownum = 1 	0.216181691638865
4867410	4684	mysql - how do i get a list starting with a letter and continue with next letters?	select contact_id, last_name  from contacts where last_name > 'b'  order by last_name  limit 0, 250 	0
4872056	23469	mysql users table: find rows that have the same email address	select u.id from users as u inner join (    select email     from users     group by users.email     having count(id) > 1 ) as u2 on u2.email = u.email 	0
4873588	34385	what kind of sql join do i need to compress a one to many relationship into the same view row?	select    p.col1, p.col2,   c1.col1 as topic1,   c2.col1 as topic2,   c3.col1 as topic2,   c4.col1 as topic4 from   parent p   left join   child c1 on p.key = c1.fkey and c1.id = 1   left join   child c2 on p.key = c2.fkey and c2.id = 2   left join   child c3 on p.key = c3.fkey and c3.id = 3   left join   child c4 on p.key = c4.fkey and c4.id = 4 	0.00087452343106033
4874731	11448	how can i select the top 10 largest numbers from a database column using sql?	select column1, column2, hit_pages,... from yourtable order by hit_pages desc limit 5 	0
4876038	15822	is it possible to count the amount of letters in the alphabet that exists in mysql column?	select count(distinct substring(`name`, 1, 1)) from `users` 	6.89680698902868e-05
4876100	40209	mysql query order by multiple items	select some_cols from prefix_users where (some conditions) order by pic_set desc, last_activity; 	0.0547616460745878
4876767	33175	sorting out the dublettes in sql table	select article.article_id, comment.comment_text,comment.comment_date from article inner join (select min(comment_date) 'comment_date', article_id             from comment             where comment_date < '2010-02-02'             group by article_id) c         on c.article_id = article.article_id inner join comment on comment.article_id = c.article_id and c.comment_date = comment.comment_date 	0.0789676354954282
4878019	12041	sql query to limit number of rows having distinct values	select * from (select * from employee where rownum < some_number and some_id_filter), table2 where some_join_condition and some_other_condition; 	0.000314730773137096
4878183	37703	mysql distinct entries disregarding all repeats after order_by	select question_id,     answer_id,     foo,     bar,     sum(answer_score) as answer_score_summed from... <snip> ...group by question_id, answer_id, foo, bar 	0.000530161488943932
4878422	33117	join two columns with one table mysql	select admin_todo.*, au.username as creator, au2.username as completer from admin_todo  left join admin_users as au     on admin_todo.created_by = au.id left join admin_users as au2     on admin_todo.completed_by = au2.id 	0.00133710340125081
4878516	33860	sql grouping - show only 5 comments per post	select    * from    tblpost p    outer apply    (select top 5 * from tblcomment c         where p.id = c.postid       order by something) inline 	0
4879541	1081	top 5 comments from a specific post. how to write my sql	select * from memberactions inner join actions     on memberactions.actionid = actions.id inner join members     on memberactions.memberid = members.id outer apply (     select top(5) *     from actioncomments     inner join comments on actioncomments.commentid = comments.id     inner join members members_2 on members_2.id = actioncomments.memberid     where actions.id = actioncomments.actionid     order by comments.id desc) comments 	0.000154120723182589
4883636	19400	getting sum from two diffrent tables sql	select   (select sum(units) from stock_in where itemid = 7) -   (select sum(units) from stock_out where itemid = 7)   as difference; 	0.000807226812738339
4884421	27249	oracle 10g: extract data (select) from xml (clob type)	select xmltype(t.xml).extract(' 	0.006242666475653
4884422	13666	how to deduct the hours with condtion	select  id         , mintime         , totaltime         , breaktime         , case when totaltime < mintime then totaltime                when totaltime - breaktime < mintime then mintime                else totaltime           end as deducttime from    table1 	0.00769706753754901
4885035	10337	get paid cash amount grouped by day	select date(`date`), sum(if(pay_method=1,purchase_price,cash_paid))  from yourtable group by date(`date`) 	0
4886295	9471	mysql like another field	select id, url, modelid  where url like concat('%', modelid, '%') 	0.0484830143721729
4886910	24812	query to find all no associated entities	select *  from users  where and users.id not in ( select * from users_association as ua inner join usesr as u on ua.fk_assoc_id = u.id and ua.fk_id = 1); 	0.000935589312879998
4891143	32828	oracle - unique values from a single column, but returning other columns	select *   from (select person,                type,                color,                rank() over( partition by person                                 order by type asc ) rnk           from <<person_table>>)  where rnk = 1 	0
4891676	15475	removing duplicates from a sql query (not just "use distinct")	select u.name, min(p.pic_id)     from users u         inner join postings p1             on u.email_id = p1.email_id         inner join pictures p             on p1.pic_id = p.pic_id     where p.caption like '%car%'     group by u.name; 	0.15957556632867
4891847	27119	overwrite/join mysql table with another table on select	select     coalesce(b.nullablefield, a.nullablefield) as nullablefield,    if(b.intfield = 0, a.intfield, b.intfield) as intfield,    if(b.floatfield = 0, a.floatfield, b.floatfield) as floatfield,    ... etc ... from table_a a left join table_b b on a.uniqueid = b.uniqueid 	0.00261197295419396
4892532	35478	sql select first records of rows for specific column	select stvnst, max(stdesc) from my_table group by stvnst; 	0
4892556	33316	efficiently find mapping	select t.item1, concat(t.item2, ", ") from t group by t.item1 	0.0855033728070654
4892584	27923	select where another table is equal to	select *         from queue      join link      on queue.pid = link.id    where exists(select 1 from settings where process = 1)  order by timestamp desc 	0.00770812121914228
4894867	21058	how to get in between dates from table using mysql	select    *  from    tblname  where    startdate between '2011-02-05' and '2011-02-10'  and    expirydate between '2011-02-05' and '2011-02-10' 	5.70012891667694e-05
4894906	982	mysql select and order by with a limit that can change	select t.* from table t join (     select points     from table r     where r.gameid = 2     order by r.points desc     limit 3 ) tr on t.points = tr.points where t.gameid = 2 	0.109516281763573
4895861	10396	assign names to tables in an sql server result set	select 'tablename' select * from table where 1 = 1 	0.00233123546619749
4896042	23384	is there a command in postgresql that can find if a tuple "contains" a specific value?	select * from tab where col1 like '%help%' or col2 like '%hello%' 	0.000496213435826275
4898082	6135	selecting parent and children values of xml together	select  tbl.col.value('parent::*/@parentid', 'int') as parentid, tbl.col.value('parent::*/@parentname', 'varchar(50)') as parentname, tbl.col.value('@childid', 'int') as childid, tbl.col.value('@childname', 'varchar(50)') as childname from @x.nodes('/parent/child') as tbl(col); 	0
4899537	15375	can't figure out correct sql query for historical table records	select t.*  from table t join (select rid, max(revision) maxrevision from table group by rid) mt on t.rid = mt.rid and t.revision = mt.maxrevision 	0.724221254469183
4900896	17924	select max value of a column in table with no rows	select coalesce(max(route_id),0) ... 	0
4903396	30457	sort query result rows by index?	select * from `tabley` order by id desc; 	0.0548808543522897
4903527	11176	how to get the max row number per group/partition in sql server?	select a.*, case when totalpayments>1 then 'no' else 'yes' end isfirstpayment   from(                 select  p.payment_id,                                      p.user_id,                                      row_number() over (partition by p.user_id order by p.payment_date desc) as paymentnumber,                                 sum(1) over (partition by p.user_id) as totalpayments                     from payment p              ) a where   paymentnumber = 1 	0
4903760	34413	find out which column has a particular string and return the column number	select coalesce(if(col1='thestring',1,null), if(col2='thestring',2,null), if(col3='thestring',3,null) ....) from somewhere; 	0
4904416	1132	efficient sql to merge results or leave to client browser javascript?	select max(case when t.ani = 'cows' then t.num else null end) as cows,          max(case when t.ani = 'pigs' then t.num else null end) as pigs,          t.country     from your_table t group by t.country order by t.country 	0.785209571389141
4905300	28228	concatenate a varchar and int	select ('varvalue' + cast(32 as varchar)) 	0.0117549833163335
4907238	18647	mysql multiplication in select depending on value of column	select case when col2 > 0 then col1 * col2 else 0 end as `sum`... 	0.000143256562833427
4910790	25300	how do i find the largest value in a column in postgres sql?	select name from tbl where weight = (select max(weight) from tbl) 	7.11383290877814e-05
4911228	5668	how do i search this in mysql and get result?	select   t2.name from   table1 t1 inner join   table1 t2 on   t1.designation = t2.designation where   t1.name = 'john' and   t2.name != 'john' 	0.28593980953489
4914272	32447	mysql query complex relationship of one way linking	select post.post_id, website.website_id from test_posts post   join test_posts website on website.website_id not in (   select sl.website_id   from test_posts f     inner join test_smartlink_to_websites sl on f.post_id = sl.post_id   where f.post_id = post.post_id ) order by post_id 	0.0712207770735745
4915008	36470	how to show values from two different queries?	select u.name,           n.*      from db2.notes n left join db1.users u on n.id = u.id  order by u.name 	0
4915065	34663	dynamic user ranks	select r.id from ranks r where r.points <= {userscore} order by r.points desc limit 1 	0.645790577665169
4915469	1125	mysql getting each first unique row from sorted by a date column?	select   user_id,   created_at,   message from   status     join       (select user_id,max(created_at) as max         from status         group by user_id) max_created_at on       (max_created_at.user_id = user_id and max_created_at.max = created_at) 	0
4915790	788	mysql: finding users with similar interests	select * from users where id in ( select id from interests where interest_name in ( select interest_name from interests where id = :current_user_id )) 	0.023452904315961
4915844	34014	how to get the latest set of data available out of a mysql table (data sets are stored daily)?	select   day,   x,   y,   z  from   coords     join   (select max(tid) as max_tid from coords group by concat_ws('.', day, x, y)) sub on (sub.max_tid = coords.tid) where   pid = 1 	0
4916195	40592	mysql select query string matching	select * from customers where 'robert bob smith iii, phd.' like concat('%',name,'%') 	0.0509073374161899
4916930	20248	two inner joins mysql	select   columns from   invoice inner join   address on   join_condition inner join   client on   join_condition 	0.680182914756643
4918098	28401	how to group results from a query based on one-to-many association by some criterion in the "many"?	select x.*   from (select v.*,                t.*,                abs(t.latitude - 30) + abs(t.longitude - 30) as distance,                row_number() over(partition by v.id                                      order by abs(t.latitude - 30) + abs(t.longitude - 30)) as rank           from vendors v           join locations t on t.vendor_id = v.id          where t.latitude is not null             and t.longitude is not null) x   where x.rank = 1     and x.distance < 50 order by x.distance 	8.91346207698045e-05
4921297	1206	generalized query to find whether the database user owns a schema	select u.name, s.name       from sys.sysusers u inner join sys.schemas s         on s.principal_id = u.uid 	0.00158376404940076
4921354	38413	get events history from a table that holds events and their old versions at the same time	select * from events where id   in ( select max( id ) from events group by origin_id )   order by start asc 	0
4924080	40984	running queries on more than one table	select sp.name from simple_person as sp inner join individual_aggregate as ia on sp.grid = ia.grid where sp.ssc = {somenumber} 	0.0134272352790514
4924365	2621	sql to return first two columns of a table	select column_name,ordinal_position   from information_schema.columns  where table_schema = ...    and table_name = ...    and ordinal_position <= 2 	0
4925152	17792	sql query with order by	select   columnofinterest  from   thetable order by    case when columnofinterest is null then 1 else 0 end case , columnofinterest 	0.698693741841341
4925566	18288	php take id's from one table and pull data that corrispondes with those id's from another table	select post_title from wp_postmeta m, wp_posts p where m.wmeta_key = '_isevent' and m.meta_value ='yes' and m.post_id == p.post_idorder by m.post_id limit 0, 5 	0
4927404	35039	how can i select an entire row without selecting rows where a certain column value is duplicated?	select name, group_concat(score)     from yourtable     group by name 	0
4927490	3454	sql count returning count of items that use a specific property	select color.id_color, color.title, count(theme_color.id_theme)   from color inner join theme_color on color.id_color = theme_color.id_color group by color.id_color, color.title 	0.000611360400213017
4929720	19905	how to get all results where column is larger then zero in sqlite?	select * from record where online_recordid <> '' and online_recordid > 0; 	0.000278132061288305
4930361	9511	how do i search for a range of integers in postgresql?	select * from "table" where id::text like '19%' 	0.005938626524034
4934034	29899	select specific records with specific ordering without using a common condition	select studentid, studentname from (     select 1 as roworder, studentid, studentname from <table> where studentid = 4 union all     select 2, studentid, studentname from <table> where studentid = 2 union all     select 3, studentid, studentname from <table> where studentid = 3 union all     select 4, studentid, studentname from <table> where studentid = 5 union all     select 5, studentid, studentname from <table> where studentid = 7) as x order by roworder 	0.000152175566936009
4934300	25462	mysql attribute database	select upa1.value, upa2.value, up1.status, u1.status    from product p     inner join product_attribute pa1       on p.product_id = pa1.product_id         and pa1.attribute_name = 'username'     inner join user_product_attribute upa1       on pa1.product_attribute_id = upa1.product_attribute_id     inner join user_product up1       on upa1.user_product_id = up1.user_product_id     inner join user u1       on up1.user_id = u1.user_id      inner join user_product_attribute upa2        on upa1.user_product_id = upa2.user_product_id     inner join product_attribute pa2       on upa2.product_attribute_id = pa2.product_attribute_id                     and pa2.attribute_name = 'domain'   where p.product_name = 'email' 	0.0305425306484712
4935015	20725	how can i view the double entry of a field and show only one entry of the other fields?	select c.scode, c.sdesc, group_concat(g.grade), s.studno      from students s         inner join grade g              on s.studno = g.gstudno         inner join curriculum c             on g.gscode = c.scode     group by c.scode, c.sdesc, s.studno 	0
4935389	29778	select multiple counts from one database table in one sql command	select   itemscanpoint,          sum(case itemtype when 1 then 1 else 0 end) ,          sum(case itemtype when 2 then 1 else 0 end)    from     itemsscan  group by itemscanpoint 	0.000126470991531488
4935470	30287	select the n-1 rows of a query	select p.id, p.from_date, p.price     from (select id, from_date, price, row_number() over (order by id desc) as r from prices) p     where p.r <> 1     order by p.id, p.from_date 	0.00497838442689638
4935541	19196	determining if a leap day falls between two days with db2 sql	select    ( days(end_date + 1 year) - days(start_date + 1 year) ) -    ( days(end_date)          - days(start_date) ) from    sysibm.sysdummy1 	0
4936371	31797	find rows with duplicate/similar column values mysql	select * from   users where  id in        (select id        from    users t4                inner join                        (select  soundex(fname) as snd,                                 count(*)       as cnt                        from     users          as t5                        group by snd                        having   cnt > 1                        )                        as t6                on      soundex(t4.fname)=snd        ) and    id not in        (select  min(t2.id) as wanted        from     users t2                 inner join                          (select  soundex(fname) as snd,                                   count(*)       as cnt                          from     users          as t1                          group by snd                          having   cnt > 1                          )                          as t3                 on       soundex(t2.fname)=snd        group by snd        ); 	0.00061547214986955
4936436	39289	how to combine the rows of two different tables into the same column?	select blah_blah from table1 where <some condition> union select blah_blah from table2 where <some contition> 	0
4937702	38710	mysql: quering time-related rows grouped by century?	select whatever from yourtable where ... group by cast((year(datetimefield) / 100) as integer) 	0.0383663341986557
4937735	4216	mysql table joining with avg()	select  avg(ratings.rating),         thing.id     from things         left outer join ratings             on ratings.thingid = things.id     group by thing.id 	0.16200278251561
4938209	13993	how to create an "any word" search?	select  keyword  from    keywordtest a inner join         split('alpha, beta, charlie',',') b on a.keyword like '%'+value+'%' 	0.147854616853466
4938306	4884	mysql group by and order by	select id, content, vote_up, vote_down, month(timestamp) as themonth from posts order by vote_up desc group by themonth 	0.340233349317674
4939487	27022	how can i associate values in a table with ranges in another table?	select *  from entries as a left outer join ranges as b    on (a.v between b.x and b.y); 	8.36156829404404e-05
4941813	5596	mysql query where statement which is a query itself?	select   tagusers.* from   tagusers inner join   friendtable   on   tagusers.username = friendtable.usera and   friendtable.userb = '$username' 	0.799988670936137
4943494	40318	finding out the day	select dayofweek(date) as weekday from mytable 	0.000495348512815316
4946621	11286	how to retrieve an average from a specific data type from a column in sql	select avg(price) as priceaverage from products where mfr = 'particularmanufacter' 	0
4946758	18847	sql 2005 get data from file	select      substring(f1, 1, 19) col 1     ,substring(f1, 20, 19) col 2 from openrowset(''microsoft.jet.oledb.4.0'',         ''text;hdr=no;characterset=unicode;database='+@path+';      extended properties="excel 8.0;hdr=yes;imex=1" '',journey_plan#txt); 	0.00559400372901701
4949207	21403	oracle database, what is an easy way to find all active db sessions (for all users) log in time (since when) using sql or em?	select username, status, logon_time   from v$session  where status = 'active' 	0.00227366528473353
4950294	9097	convert mysql query from union to something more efficient	select sum(case when m.type in(0,2) then 1 else 0 end) as type_a_messagecount     , sum(case when m.type = 1 then 1 else 0 end) as type_b_messagecount from messages as m     join messagerecipients as r         on r.messageid = m.messageid where r.read = 0      and r.trashed = 0      and r.deleted = 0      and r.userid = 1      and r.authorid <> 1 	0.393494725784512
4952786	32741	mysql joins - getting all data from 3 tables	select h.house_id, s.seller_id, sd.details from houses h cross join sellers s left join selling_details sd     on sd.seller_id = s.seller_id     and sd.house_id = h.house_id order by h.house_id, s.seller_id 	0.00109636402289869
4953397	33000	join query in mysql	select count(*) from table1 t1 inner join table2 t2 on t1.pid = t2.pid where t2.uid=1 	0.720021750495743
4953477	11660	access unkown columns of a table and insert them into a new one	select name, colorder from syscolumns where id = (select id from sysobjects where name = [tablename]) 	0
4953650	26902	group by first letter of the string	select member.member_firstname, count(member.member_lastname) from dbo.member group by member.member_firstname, substring(member.member_lastname, 1,1) having count(member.member_lastname) > 1 	0.00020771709711737
4954067	6088	mysql subquery as criteria	select   t.id           as t__id,   t.state_code   as t__state_code,   t.number       as t__number,   t.meta         as t__meta,   t.date_created as t__date_created,   count(t2.id)   as t__0 from tbl_subscribers t join tbl_messages t2 on t2.subscriber = t.number  left join tbl_services t3 on t2.service_id = t3.id  where t2.inbound_time between "2011-01-31 16:00:00"         and "2011-02-28 15:59:59"          and t3.pool_id = 48 group by t.id, t.state_code, t.number, t.meta, t.date_created  having count(t2.id) > 0 order by t__0 desc limit 100 	0.424802945661316
4955791	3789	sql server: merging multiple colums into 1 column	select data1 from table1 union all select data2 from table1 union all ... select data3 from table2 	0.000812052843109902
4956277	15662	fetch records in specific order but keep some specific records in always top mysql	select * from table1 order by purchased desc, created desc 	0
4957224	10278	getting last day of previous month in oracle function	select last_day(add_months(yourdate,-1)) 	0
4958159	23766	variable as top value	select top (@num) a from table 	0.0195657346685117
4958627	31649	get 2 most recent items of all but from 2 different categories	select id, cat, datetime, ... from `table`   inner join (     select cat, max(datetime) as mdate      from `table`      group by cat      order by mdate desc     limit 2   ) as t   on `table`.cat = t.cat and `table`.datetime = t.mdate; 	0
4959595	1587	select id where table row count = 1	select person.id from person where ((select count(*) from person) = 1) 	0.000366798180224951
4961524	26721	mysql query: latest timestamp + unique value from the last 30 minutes	select max(timestamp) as timestamp, username      from bla      where timestamp > (now() - interval 30 minute)      group by username      order by timestamp desc 	0
4963028	35536	how do you list all the indexed views in sql server?	select o.name as view_name, i.name as index_name     from sysobjects o          inner join sysindexes i              on o.id = i.id      where o.xtype = 'v'  	0.0326473447697462
4967615	2066	taking script of filtered stored procedures	select     p.name,     p.create_date,     p.modify_date,     sm.definition from      sys.procedures as p inner join      sys.sql_modules as sm on p.object_id = sm.object_id where      p.is_ms_shipped = 0     and p.modify_date >= dateadd(day, -10, dateadd(day, -10, getdate()) 	0.620924747347285
4968516	28500	mysql how to create optimum query for these table	select b.*, f.favorite_writer_id from book_tittle b left outer join favorite_writer f on b.writer_id = f.writer_id and f.user_id = 10 where b.tittle like '%something%' order by f.favorite_writer_id asc 	0.130982543600463
4968570	11190	how to select the relative complement of a table b in a table a (a \ b) in an sql-query?	select * from subjects where id not in (select subject.id from categories ) 	0
4970162	14786	combine multiple room availability queries into one	select      room_availability_rid, count(*) n where room_availability_date in ('2011-02-13','2011-02-14','2011-02-15')   and room_availability_number > 0 group by room_availability_rid  having n=3 	0.00514916012281967
4971051	1848	php - select * from ... but view last element in database first	select * from comments order by id desc 	0
4972566	13145	mysql count query excluding records when joining	select i.item_id, i.item_name, i.item_sku, i.item_price,  (select count(*) from purchases where item_id=i.item_id and user_id='1') as purchase_count  from items i order by i.item_name asc 	0.0113292534312845
4972970	27686	tsql: convert columns into a xml column, one xml per row	select d=(select a.* for xml path('r'),type,elements absent) from mytable a 	0
4973268	9121	mysql date and datetime problem	select id, dt  from table1 where date(dt) = '2011-02-11' 	0.318275048234573
4973827	39543	select distinct first character based on the string column	select distinct lower(substr(last_name,1,1)) as last_initial from my_table; 	0
4976422	4635	how do i select from two tables, nearest timestamp and order by said timestamp?	select s.*,e.* from series s join (select serieskey, min(episodeairdate) mindate from episodes     where episodeairdate > now() group by serieskey) m     on m.serieskey = s.serieid join episodes e on e.serieskey = s.serieid and e.episodeairdate = m.mindate order by e.episodeairdate; 	0
4977375	22382	datediff getting the previous month	select dateadd(month, -1, getdate()) 	0.000625019549929955
4979483	32342	mysql hierarchical query on codeigniter	select * from (`categories` as l1) left join `categories` as l2 on `l2`.`parent` = `l1`.`id` left join `categories` as l3 on `l3`.`parent` = `l2`.`id` where `l1`.`slug` = 'animations' and `l2`.`slug` = 'flash' 	0.678227267151133
4980291	131	getting point based score using mysql	select player, (case when weight < 150 then 1 else 0) +                 (case when height >  67 then 1 else 0) +                (case when weight <  1.8*height then 1 else 0) +                (case when agility > 4  then 1 else 0)  from table 	0.00505482045151844
4981011	14197	mysql - joining tables and turning specific rows into "virtual" columns	select u.id     , min( case when m.meta_key = 'nickname' then m.meta_value end ) as nickname     , min( case when m.meta_key = 'description' then m.meta_value end ) as description     , min( case when m.meta_key = 'userphoto_thumb_file' then m.meta_value end ) as userphoto_thumb_file from users as u     join usermeta as m         on m.user_id = u.id group by u.id 	0
4982558	21510	php mysql check if a table has a primary key	select exists(   select 1   from information_schema.columns   where table_schema = 'db'      and table_name='table name'      and column_key = 'pri' ) as hasprimarykey 	0.000505890682756927
4984363	40615	sql return a comma separated value list	select ta.ida, ta.valuea, stuff((     select ', ' + cast(valueb as varchar(max))     from @tableb tb inner join @tablec tc on tc.fidb = tb.idb     where tc.fida = ta.ida     for xml path('')     ), 1, 2, '') as options from @tablea ta 	0
4986548	29310	mysql - combining columns into one big column	select concat(address, '  ', city, ', ', state, ' ', zip) from table; 	0.000339010882752754
4988906	40754	oracle sql - how do i repeat a character based on a value in a column	select rpad('$', round(salary/1000), '$') as "graphic" from employees 	6.20263367389943e-05
4989334	25292	how to get the rows from two table instead of one when their is sure that they exist in one	select col1, col2, col3 from table1 where id = 5 union all select col1, col2, col3 from table2 where id = 5 limit 1 	0
4989574	20476	sql query condition	select discount from mytable where days > xxxx limit 1 	0.600032316082923
4990052	2046	join without double values	select date ,         max(case when id=1 then value end) as val1,        max(case when id=2 then value end) as val2 from [archiveanalog] where id in (1,2) group by date 	0.309338493827621
4991507	3157	getting values across many tables including max and nulls	select   a.eid,   a.evalue,   t.pid,   t.pname,   t.rid,   t.rvalue from tblalert a   left join (     select       p.pid,       p.pname,       p.eid,       r.rid,       r.rvalue     from tblpatient p       inner join (         select pid, max(rid) as rid         from tblpatientrecords         group by pid       ) pr on p.pid = pr.pid       inner join tblrecords r on pr.rid = r.rid   ) t on a.eid = t.eid 	0.00131658730903254
4992329	5915	group_concat missing on of the group	select group_concat(distinct        `delegate`.`fldfirstname`, ' ', `delegate`.`fldsurname`        separator        ' and ')               as 'nameofpair',        sum(`data`.`fldscore`) as 'totalscore' from   `delegate`        left join `data`          on `data`.`flddelegateid` = `delegate`.`fldid` where  `delegate`.`fldcategory` > '0'        and `delegate`.`fldpairnum` > '0' group  by `delegate`.`fldpairnum` 	0.103134611784398
4992826	4359	mysql error : subquery returns more than 1 row	select `index`, `fundname`, count(*),      (select sum(`priceperweek`)      from `tbl_fundsubscriptions`      where date_sub(curdate(),interval 7 day) <= `subscribedt`             and `fundidsend` = `tbl_fundstatic`.`fundid`) from `tbl_fundstatic` where `userid` = '14' 	0.656922265200273
4995721	32601	sql self join query? how to get categories sub categories?	select l0.catid,     concat(       case when l5.catid is null then '' else concat(l5.category, '/') end     , case when l4.catid is null then '' else concat(l4.category, '/') end     , case when l3.catid is null then '' else concat(l3.category, '/') end     , case when l2.catid is null then '' else concat(l2.category, '/') end     , case when l1.catid is null then '' else concat(l1.category, '/') end     , l0.category) from catcat l0 left join catcat l1 on l0.parentid=l1.catid left join catcat l2 on l1.parentid=l2.catid left join catcat l3 on l2.parentid=l3.catid left join catcat l4 on l3.parentid=l4.catid left join catcat l5 on l4.parentid=l5.catid 	0.200554487806447
4996345	15371	ms- access query for total hours and time deduction	select empcode, datevalue(punchtime),     sum(iif(isinpunch='f',punchtime,0)) -     sum(iif(isinpunch='t',punchtime,0)) from timesheet group by empcode, datevalue(punchtime) 	0.00468408490723746
4998420	37709	sql select display row data as columns	select     sum(if(login_type = 'iphone', 1, 0) as iphone_login,     sum(if(login_type = 'browser', 1, 0) as browser_login from log_table 	8.11506555439597e-05
4998470	8270	storing day and month (without year)	select     adddate(     subdate(cast('0004-02-29' as date),         interval 4 year),         interval year(curdate()) year) result: 2011-02-28 	0
4999211	2221	merge values in mysql and sort	select username, sum(nr) as nrsum  from vote  group by username  order by nrsum desc 	0.00578009110099399
4999550	3745	how to eliminate duplicates from select query?	select distinct on (userid) userdid, name, yr from table_name 	0.0137080455203404
5000607	24214	multiple mysql cross reference tables, or one (by adding an extra field storing reference type)	select * from prx_sportsitems psi left join prx_tags_items pti on (pti.ownerid=psi.id) left join prx_tags pt on (pti.tagid=pt.id) where pt.tagname = 'aerobic' and pti.ownertype='sportsitems' order by psi.dateadded desc limit 0,30 	0.0165739814586196
5002457	13017	combining the results of two seperate sql queries with 'or'	select "outbreaks".* from "outbreaks" inner join "bacterial_agents" on bacterial_agents.outbreak_id = outbreaks.id inner join "bacteria" on "bacteria".id = "bacterial_agents".bacterium_id where (bacteria.name ilike e'%vtec o157%') union select "outbreaks".* from "outbreaks" inner join "viral_agents" on viral_agents.outbreak_id = outbreaks.id inner join "virus" on "virus".id = "viral_agents".virus_id where (virus.name ilike e'%norovirus%') 	0.00795633953130546
5002960	36538	list of table which has the column in sql server 2005	select * from  information_schema.tables t inner join information_schema.columns c on t.table_name = c.table_name where c.column_name='studentid' 	0.000381220940340503
5003425	12931	mysql :need to get unique field of two row on base of a column having two different value	select studentid  from students where examid in(23, 24)  group by studentid having count(*) > 1 	0
5004130	38818	unioning two tables and selection only top 'n' records	select post_id, comment_id, user_id, post, created from (     select top 10 post_id, null as comment_id, user_id, post, created     from posts     order by created desc     ) ss union select      posts.post_id     , comment_id     , comments.user_id     , comment as post     , comments.created from posts inner join comments on posts.post_id = comments.post_id where posts.post_id in (     select top 10 post_id     from posts     order by created desc     ) order by created desc 	0
5006694	24472	sql query to select all records from the last 5 years	select r.* from (     # the 5 most recent classes     select class     from recruits     group by class     order by class desc     limit 5 ) c inner join recruits r on r.class = c.class order by class desc, `first`, `last` 	0
5008877	25563	getting a sum in columns from different tables in a sqlserver-ce database and displaying the result in a label control	select sum(amount) from (   select amountreceived [amount] from a where date between (@param1) and (@param2)   union all   select amountcharged from b where dateofentry between (@param1) and (@param2)   union all   select amount from c where date between (@param1) and (@param2)   union all   select amountcharged from d where dateofrequest between (@param1) and (@param2)               union all   select -amountdue from e where date between (@param1) and (@param2) ) [subquery] 	0
5010745	417	how can i merge these two queries into one?	select count(this_1 = '1' or null) as count_1, count(this_2 = '1' or null) as count_2 	0.000674993393924151
5010796	9718	mysql get latest x rows, while ordering by column?	select * from (select * from `item` order by `date` desc limit x) order by y 	0
5014656	25049	query to merge multiple rows into into distinct rows with multiple columns	select name,[1] as animal, [2] as color from (select name,id,value     from table) as sourcetable pivot ( min(value) for id in ([1], [2]) ) as pivottable; 	0
5015279	22996	how to get the sum of all column values in the last row of a resultset?	select isnull(master_code, 'total') as master_code,        jan,        feb,        mar from (       select master_code,              sum(jan) as jan,              sum(feb) as feb,              sum(mar) as mar       from foobar       where participating_city = 'foofoo'       group by master_code with rollup      ) as dt 	0
5016292	16672	get data for each month from defined month up to current month	select year(radacct.acctstarttime), month(radacct.acctstarttime), ... from ... where radacct.acctstarttime > '2010-09-00' group by year(radacct.acctstarttime), month(radacct.acctstarttime) 	0
5016465	15141	case statement problem to show values without null in a row	select   max(case rtt.us_code when 's' then rtt.name end) as input_tax_name,   max(case rtt.us_code when 'r' then rtt.name end) as output_tax_name,   max(case rtt.us_code when 's' then rtt.acc_id end) as input_tax_rate,   max(case rtt.us_code when 'r' then rtt.acc_id end) as output_tax_rate from supplier_item si   inner join ret_tx_type rtt     on si.ret_tx_type_id = rtt.ret_tx_type_id group by ??? 	0.131592463262749
5019007	31690	comparing two tables with sql	select t1.col1, t1.col2, t2.col2, t1.col3     from table_1 t1         left join table_2 t2             on t1.col1 = t2.col1                 and t1.col3 = t2.col3 union select t2.col1, t2.col2, t1.col2, t2.col3     from table_2 t2         left join table_1 t1             on t2.col1 = t1.col1                 and t2.col3 = t1.col3 	0.0226775239096227
5019137	13362	return the first n letters of a column	select left(col, 10) from table; 	0
5021826	28777	mysql merge rows if id = the same	select  id,max(c1) as c1,max(c2) as c2,max(c3) as c3,... from    [table] group by id 	0
5023529	39722	doing two select query, with the second query dependant of the first, and the result of the second being concatenated in one	select tgathering.*, group_concat(people.cpeople separator ',') from tgathering inner join tgatheredpeople as people on `people`.cgatheringid=`tgathering`.cid group by people.cgatheringid 	0
5026275	28011	how to make mysql result set the same as specified?	select * from tablename  where id in (1,5,10)  order by find_in_set(id, '1,5,10') 	0.00586808795284358
5026377	33847	mysql - how to select a range of id's at set intervals	select * from categories where categoryid >= 100 and categoryid % 100 = 0; 	0
5027194	24503	query to find pairs of employees who have the same birthdate	select t1.empno,         t1.lastname,         t1.birthdate,         t2.empno,         t2.lastname,         t2.birthdate from employee t1, employee t2 where t1.birthdate = t2.birthdate and t1.empno <> t2.empno 	0
5027687	27042	selecting all records from one year ago till now	select *  from orders  where order_date >= date_sub(now(),interval 1 year); 	0
5030300	12050	limiting the null subqueries from result set	select [m].[name] as [mastername]     , max([c].[value]) as [cm]  from [master] as [m]  left outer join [child] as [c] on m.id = c.id group by [m].[name] 	0.0903167886644391
5030646	36594	sql if breaking number pattern, mark record?	select *  from   dbo.report r1      , dbo.report r2 where  r1.accountnumber = r2.accountnumber and    r2.rptperiod - r1.rptperiod > 1 and    not exists         (select 1 from dbo.report r3         where  r1.accountnumber = r3.accountnumber         and    r2.accountnumber = r3.accountnumber         and    r1.rptperiod < r3.rptperiod         and    r3.rptperiod < r2.rptperiod         ) 	0.00112954044757733
5031471	29101	optimizing select count to exists	select case          when exists (select *                       from   customer                       where  amount <> 0                              and customerid = 22) then 1          else 0        end  as non_zero_exists 	0.539151118343057
5032388	37614	selecting blob column from oracle database to sql server database over linked server	select * from openquery(linked_server_name ,  'select dbms_lob.substr(blobcolumn,4000,1) from table') as derivedtbl_1 	0.0152113956045231
5032995	22768	mysql select data from two tables and different structure	select  'events' as tbl,         datetime,         location,         organizer,         null as notes from    events union all select  'user_notes' as tbl,         datetime,         null,         null,         notes from    user_notes order by      datetime desc 	0.000133920848295568
5033618	30089	sql join 3 tables	select *     from users u         inner join relationship r             on u.user_id = r.user_id         left join relationship_block rb             on r.user_id = rb.user_id                 and r.member_id = rb.blocked_member_id     where rb.user_id is null 	0.227154333492206
5034172	16019	calculate bmi from height / weight tables	select w.personid,        w.entrydate,        (            select top 1 h.inches                from patientheight as h                where w.personid = h.personid                    and h.entrydate <= w.entrydate                order by h.entrydate desc        ) as inches        w.pounds     from patientweight as w 	0.00113186844772614
5034801	33802	return a boolean value if string matches one of list mysql	select s.sequence,     case          when (select count(*) from known_sequences k where k.sequence = s.sequence) > 0 then '1'         esle '0'     end      `known`, from sequences s; 	0
5035551	34987	sorting sql results from two tables	select tagid, count(*) as totaloccurrences from coupon_tags     group by tagid     order by totaloccurrences desc     limit 10 	0.00504553647566554
5036145	7092	weighted conditions in the where clause of a sql statement	select * from ( select *, 1 as preferred from employees where name like 'ar%' limit 10 union all select * from (     select *, 2     from employees     where name not like 'ar%' and name like '%ar%'     limit 10 ) x ) y order by preferred limit 10 	0.591694549223653
5038193	14398	reading only one column from sql output as a numerical array in php	select tagid             from coupon_tags group by tagid order by count(tagid) desc  limit 10 	7.05390422155336e-05
5040407	12242	how do i select employees most profitable case's?	select * from   employee e        inner join case c on c.employeeid = e.empid        inner join (          select employeeid, max(profit) as profit          from   case          group by                  employeeid        ) pmax on pmax.employeeid = c.employeeid                  and pmax.profit = c.profit 	0.00599638966509108
5040663	7406	sql join on not equal in mysql	select  t1.* from    table1 t1 left join         table2 t2   on  t1.questionid = t2.questionid where   t2.questionid is null 	0.576674380713614
5040818	28699	compare last to second last record for each contract	select a.contractid, a.date, a.value, (select top 1 b.[value]          from tbl b          where b.[date] < a.[date] and b.contractid=a.contractid         order by b.[date] desc) as old_value from tbl as a where a.date in         (select top 1 b.date          from tbl b          where b.contractid=a.contractid         and b.date < #2011/02/11#         order by b.date desc) 	0
5042874	17717	sql view: join tables without causing the data to duplicate on every row?	select a.name as account_name,         p.description as property_description,         p.address as property_address,         null as vehicles_description,        null as vehicles_make,         null as vehicles_model     from accounts a         inner join properties p             on a.accountid = p.accountid union all    select a.name as account_name,         null as property_description,         null as property_address,         v.description as vehicles_description,        v.make as vehicles_make,         v.model as vehicles_model     from accounts a         inner join vehicles v             on a.accountid = v.accountid 	0.000414553215797954
5044698	38322	search list of strings for string match	select     * from     inserted i, badwords b where     charindex(b.badword, i.body) > 0 	0.00464662281310057
5048457	15455	select from db by strlen	select * from table_name where char_length(column_name) < 5 	0.0380798321260765
5049010	10752	find duplicate entries in db	select count(*),  field_name from table_name group by field_name having count(*) > 1; 	0.000140377177402688
5050151	18719	using 2 while loops to get data from 2 tables	select distinct column_name from table 	0.000122226225956287
5050809	1884	mysql table problem?	select c.chat_text, u.username from chat_data c, users u where c.con_id =1   and u.id = c.user_id 	0.573378280723269
5051173	35549	how can i query for text containing asian-language characters in mysql?	select * from `mydata` where `words` regexp concat('[',unhex('e3'),'-',unhex('e9'),']') 	0.623599718613012
5052770	17173	counting occurences in second table compared to first	select sc.*,           coalesce(x.numphotos, 0) as numpht      from site_con sc left join (select sp.photter,                   count(*) as numphotos              from site_phts sp          group by sp.photter) x on x.photter = sc.con_code  order by ssc.surn 	0
5056178	25051	sql query , get data from table by 2 fields	select code from table where date > '2011-01-30 23:59:59' group by code having min(price) > 22 	0.00012984833255837
5059912	13510	how to count the number of rows in a table using a foreign key in the same query?	select name, count(itemid) as itemcount from table1 inner join table2 on table1.itemid = table2.id group by name 	0
5061300	6133	mysql how to get results based on the the order of parameters in the where clause	select idelm_na as id, nd.lat_nd as lat, nd.lon_nd as 'lon' , adr.road_adr as 'road'  from node_nd as nd     join node_address as na         on na.idelm_nd = nd.idelm_na     join address_adr as adr         on adr.id_adr = na.idadr_na     join    (             select 1 as rnk, 14.654733 as lat, 121.058403 as lon             union all select 2, 14.654791, 121.062386             union all select 3, 14.654791, 121.064343             union all select 4, 14.654754, 121.064403             union all select 5, 14.654648, 121.064450             union all select 6, 14.653869, 121.064798             union all select 7, 14.653865, 121.065399             union all select 8, 14.653880, 121.066532             ) as z         on round(lat_nd, 6) = z.lat             and round(lon_nd, 6) = z.lon order by z.rnk 	0.000210678800285136
5062234	24333	sql query condition	select date_format(date_col, '%m') as month from table order by month 	0.600032316082923
5062430	13881	datetime format	select convert(varchar, getdate(), 103) – dd/mm/yyyy 	0.111294596066748
5064521	6715	top comments,top users,top users and comments mysql	select * from comments x join (select comment_id, sum(rating)       from votes        group by comment_id       order by sum(rating) desc       limit 10 ) z on x.comment_id = z.comment_id 	0.00736781291469939
5064711	25092	sql match on letter and number arrangement without using regular expressions	select mycol  from mytable  where substring(mycol, 1 , 1) >= 'a'  and substring(mycol, 1 , 1) <= 'z'  and substring(mycol, 2 , 1) >= 'a'  and substring(mycol, 2 , 1) <= 'z'  and substring(mycol, 3 , 1) >= '0'  and substring(mycol, 3 , 1) <= '9' 	0.105856425182546
5065520	23208	sql query showing element more than once	select c.name, count(c.title) as numfilms from casting c group by c.name having count (c.title) > 1 order by numfilms 	0.012999120083836
5066269	6596	normalise/join sql server tables	select * from results where name = @bandname or       name in (select oldbandname                  from oldbands                 where bandid in (select bandid                                  from bands                                 where bandname = @bandname)) 	0.537912261519674
5066700	27961	display primary key related data	select a.row_id, customer_name, worker_name, vehicle_name, task_serial, subcontractor_name  from my_table as a inner join cusomer as b on a.customer_id = b.customer_id inner join worker as c on a.worker_id = c.worker_id ... 	0.000147395711105184
5067487	39240	complex sorting on mysql database	select nt.title   from news n    join news_translations nt on(n.id = nt.news_id)  where nt.title is not null    and nt.language = (           select max(x.language)             from news_translations x            where x.title is not null              and x.new_id = nt.news_id)  order      by nt.title; 	0.681583742123889
5067666	32589	how to connect tables on sql compact?	select showdate from shows inner join clubs on  shows.clubid = clubs.clubid where clubs.clubname='" + cmb_clubnameslist.selecteditem.tostring() + "'" 	0.348434830274589
5068293	22513	listing all friends and joining to the users table	select u.name     from friends f         inner join users u             on f.user_id = u.user_id     where f.friend_id = @yourid union select u.name     from friends f         inner join users u             on f.friend_id = u.user_id     where f.user_id = @yourid 	0
5068623	12644	erlang and sqlite	select user from users where user = 'spongebob'; 	0.612384478871865
5068706	39845	find non-integer values in a float field	select field from table where field like '%.%' 	0.00133841179996112
5072348	15038	how can i join two db tables and return lowest price from joined table	select pr.id, pr.title, pr.name, pr.description, min(p.price)   from products as pr      join prices as p on pr.id = p.product_id    where pr.live = 1 and p.live = 1   group by pr.id 	0
5072724	13802	run two queries on the same table at once?	select sum(`hits`) as `total_hits`, `ip`     from `ips` group by `ip` 	0
5073089	14075	select top 1 from a table for each id in another table	select a.*, m.* from fruit_allocation a cross apply (     select top 1 *     from measurement m     where m.fruit_allocation_id = a.id     order by m.measurement_date desc ) m where a.fruit_id = 10 	0
5073550	8874	sql query to find only unique strings from 2 columns	select [name] from (select name1 as [name] from [table] union all select name2 from [table]) group by [name] having count(*) = 1 	0
5074889	4538	sql: left join select statement to addd "daily sales total" column	select  tracking.id,         tracking.creationdate,         tracking.currentassigneddriverid,          tracking.totalcost,          tracking.customerid,          tracking.dfrom,          tracking.dto,         customers.company,         sum(tracking.totalcost) over(partition by cast(convert(char(10), tracking.creationdate, 101) as smalldatetime))         as totalsales   from  tracking inner join customers        on    customers.id = tracking.customerid 	0.00251926616155716
5074941	7342	how to ignore lines from tbl2 while main table is tbl1 in sql?	select service, count(qno) as [qno_served]   from visit  where not exists (     select * from matter where matter.trackno = visit.trackno and matter.code = 'a')  group by service 	0.00896018952082052
5075167	10545	grab all items from mysql table expired 1 day ago	select a.* from trial_list as a left join trial_list as b on a.product_id = b.product_id and a.id < b.id where b.product_id is null and a.expiry_date < curdate() 	0
5075909	3183	sql query how to count different value in single row	select a, b,        sum(if(c=3, d, null)) as c3,        sum(if(c=4, d, null)) as c4,        sum(if(c=5, d, null)) as c5   from yourtable group by a, b; 	0.00013303780987572
5077723	41168	t-sql: return range in which a given number falls	select case when value / 1000 < 1      then '0000-0999'      else cast(value / 1000 * 1000 as varchar(16)) + '-' + cast(value / 1000 * 1000 + 999 as varchar(16))  end 	0
5077748	2964	sql server: subtraction between 2 queries	select amounttable.amount-isnull(discounttable.discount, 0) from amounttable left join  on amounttable.car = discounttable.car 	0.106389842736414
5078916	36199	simple pivot of columns to rows in mysql	select 'a' as title1, a as title2 from table union all select 'b' as title1, b as title2 from table union all select 'c' as title1, c as title2 from table union all select 'd' as title1, d as title2 from table 	0.0340147370810392
5080716	16070	sql server 2005 - t-sql to increase field size based on parameters	select     'alter table ' +         object_schema_name(c.object_id) + '.' + object_name(c.object_id) +         ' alter column '+ c.name + ' ' + t.[name] + ' (1000) ' +         case when c.is_nullable = 0 then 'not' else '' end + ' null' from     sys.columns c     join     sys.types t on c.system_type_id = t.system_type_id where     t.[name] like '%varchar' and c.max_length < 1000     and     objectpropertyex(c.object_id, 'ismsshipped') = 0 	0.028400987672198
5083985	10167	search all stored procs for a literal or string	select quotename(s.name)+'.'+quotename(o.name) as object_name, o.type_desc     from sys.sql_modules m         inner join sys.objects o              on m.object_id = o.object_id                 and o.type = 'p'         inner join sys.schemas s              on o.schema_id = s.schema_id     where m.definition like '%yoursearchtext%' 	0.204841815869649
5085474	34199	help with sql totals and sums	select   a.acct_no, m.cmcl_forecast_cleared, b.name,   count(*) as totalchecks,   sum(m.check_amount) as totalamount from ap_master m    join accounts a on a.acct_id=m.account_tag   join banks b on b.bank_id=a.bank_id   where m.cmcl_bank_cleared is null  group by a.acct_no, m.cmcl_forecast_cleared, b.name order by a.acct_no, m.cmcl_forecast_cleared, b.name 	0.753186348354474
5085905	16952	basic mysql count selecting	select col1, col2, (  select count(*)  from votetable vt   where vt.contenttable_id = ct.id ) as count from contenttable ct 	0.229655628565051
5087718	10720	selecting categories and articles	select c.title, a.title from articles a  left join  articles_category b on a.id=b.article_id left join categories c on c.id = b.category_id order by b.main, c.id, b.cposition 	0.00141146592767961
5088094	20691	text wrapping in oracle	select regexp_replace(column_name, '(.{40})', '\1' || chr(10) || chr(13)) from some_table; 	0.569634426455824
5088366	28694	how to create an inventory summary report from mysql database	select product_id, stock_balance from stock_card s join (     select max(stock_id) maxid     from stock_card     group by product_id   ) g on s.stock_id = g.maxid order by product_id, stock_balance 	0.0135144568463103
5089058	21332	how do i convert an access 2007 datetime to mysql datetime format?	select format(datetimefield, "yyyy.mm.dd hh:mm:ss") from tablename; 	0.407966253662941
5089430	41253	mysql listing from 2 tables	select * from ads a    join ads_packs p on p.id_ad = a.id order by p.id_pack <> 2, a.date; 	0.00464475267044655
5090591	36903	mysql - select ... where id in (..) - correct order	select * from table where id in (5,4,3,1,6) order by field(id, 5,4,3,1,6); 	0.17915689153817
5090601	9240	how to get unique number of rows from the secondary table	select count(distinct product_id) from pro_category 	0
5090652	25304	grab a certain amount of database entries from a table	select * from tablename order by totalvisits limit 20 	0
5092028	31418	need to see if a range of dates overlaps another range of dates in sql	select    room_id from    rooms r    left join bookings b on (       r.room_id = b.room_id       and b.check_in_date > '$max_date'       and b.check_out_date < '$min_date'    ) 	0
5092185	38062	merge two select queries into one	select sum(case when category = 'value_a' then 1 else 0 end) as group_a,        sum(case when category = 'value_b' then 1 else 0 end) as group_b     from tbl     where category in ('value_a', 'value_b') 	0.000330673012044345
5096887	31248	sql: detecting differences in sums between two tables?	select     totals_a.state,     totals_a.total_votes,     totals_b.total_votes from (     select state, sum(votes) as total_votes     from votes_a     group by state ) as totals_a join (     select state, sum(votes) as total_votes     from votes_b     group by state ) as totals_b on totals_a.state = totals_b.state where totals_a.total_votes <> totals_b.total_votes 	0.0014205549142221
5097188	21616	mysql - rename all tables and columns to lower case?	select concat('alter table ', table_name, ' change `', column_name, '` `', lower(column_name), '` ', column_type, ';') from information_schema.columns where table_schema = '{your schema name}' 	0.00936978084490132
5097515	4769	two queries to get information	select     c.userid,     c.comment,     u.username,     ...etc... from comments as c join user_database as u on c.user_id = u.user_id where post_id = '42' 	0.00242345178082101
5097703	28260	sql query to find all possible paths	select distinct c1, c2 from testtb connect by nocycle prior c1 = c1 or prior c2 = c2 start with c2 = 100 order by c1, c2; 	0.0472348276068878
5098352	14175	getting conditional counts on to the same row in mysql / sql	select males.team, count(males.id) as "males", sum(males.points) as "male points",         count(females.id) as "females", sum(females.points) as "female points"  from scores as males  left join scores as females on males.team=females.team and females.gender="female"  where males.gender="male"  group by team 	0.0011626995868768
5098476	27169	mysql count frequency of one-many links	select jobcount, count(peoplecount) from (   select person.id as peoplecount, count(jobs.id) as jobcount   from jobs   where person.id = jobs.person_id   group by person.id ) as frequency group by jobcount 	0.00310515708998917
5100291	30476	select a group of records based on one record in the group	select account, subnumber, count(*)   from orderdtl  where exists (    select *      from orderdtl as a     where a.account = orderdtl.account       and a.subnumber = orderdtl.subnumber       and a.pubstatus = 'a'       and a.renewalthere = 0 ) group by account, subnumber 	0
5102857	958	mysql query that requires subtraction of fields that cannot be referenced	select    sum(case when co.type = 1 then col.quantity else -col.quantity end) from   ... 	0.378348811371542
5103116	15917	mysql replace all whitespaces with -	select replace( table.field, ' ', '-' ) from table; 	0.606174853605621
5103809	19016	comparing matching column data from 2 different tables	select table1.[email address] into newtable from table2 inner join table1 on table2.[email address] = table1.[email address]; 	0
5105035	40614	get polygon points mysql	select astext(g) from geom; 	0.0798860535802507
5106260	33240	query between two related tables	select * from users left join friends f1 on (users.id = friends.uid) left join friends f2 on (users.id = friends.fid) where f1.uid is null and f2.uid is null 	0.00285971168606407
5107040	37615	get followers and following in one query using mysql	select (select count(buid) as count from social where buid = :uid) as followers   , (select count(auid) as count from social where auid = :uid) as following 	0.0391051947381888
5107562	23918	sql group dates by month	select month(cvu.expirationdate) as mnth, year(cvu.expirationdate) as yr,      count(*) as duetoexpire from clientvehicleunit cvu where cvu.expirationdate >= '20120101' and cvu.expirationdate < '20130101' group by month(cvu.expirationdate), year(cvu.expirationdate) 	0.00344152805400524
5108101	38719	merge two tables with common values by adding the count, append rest	select company, sum(views) from  (select company, views from first union all select company, views from second) as t group by company 	0
5109581	11726	granting execute permission on all stored procedures in a certain database	select 'grant execute on ' +      quotename(specific_schema) + '.' +     quotename(specific_name) + ' to someone' from information_schema.routines where routine_type='procedure' 	0.00250926935934798
5111396	4598	sql group by date (hour)	select to_char(date,'hh24') from table where date = to_date('20110224', 'yyyymmdd') group by to_char(date,'hh24') 	0.0134094747118738
5112571	34963	union 1 column and select additional	select p.post_id     , max( case when ur.unread_by is not null then 1 else 0 end ) as unread     , max( case when p2.pinned_by is not null then 1 else 0 end ) as pinned from posts as p     left join unread as ur         on ur.post_id = p.post_id     left join pinned as p2         on p2.post_id = p.post_id group by p.post_id 	0.0771244109625047
5112721	23974	how to detect if a certain amount of time has passed in php/mysql?	select * from table where timestampcol < date_sub(current_timestamp, interval 10 day) 	0
5113450	25037	last id value in a table. sql server	select max(id) from <tablename> 	0
5113767	2714	select specific column only in mysql	select t1.*,t2.user_name  from   table_checkout_bidpack as t1 inner join table_user_information  as t2 on t1.user_id=t2.user_id 	0.00183195827567535
5116057	38676	how can i get difference of two dates through mysql select query	select time_to_sec(timediff('2007-01-09 10:24:46','2007-01-09 10:23:46')); 	7.37592997022637e-05
5116819	15507	exclude both rows one of them doesn't match criteria - self join?	select c1.* from customers c1 where c1.tea_preference = 'yes please'  and c1.date between '2011-01-01' and '2011-01-03' and not exists      (select c2.* from customers c2      where c2.tea_preference = 'no thanks'     and c2.date between '2011-01-01' and '2011-01-03'      and c1.custom_id = c2.customer_id) 	0.000177564966546748
5116841	33806	how do i combine having and group by in the same sql?	select user_id, sum(...) as total from mytable group by user_id having sum(...) >= 10 	0.0083497886761815
5118134	22002	select multiple rows from joined table	select b.value  from a a  join b b on  concat(',',a.x,',') like concat('%,',b.uid,',%') 	0.000168401782105475
5120158	10069	sql code to list most common email suffixes from database	select   substr(useremail from locate('@', useremail) + 1),   count(*) from   email_user_testing group by   substr(useremail from locate('@', useremail) + 1) order by   count(*) desc 	0.000200445962982158
5120402	21321	how to get load time in milliseconds or microseconds in mysql	select last_query_execution_time() 	0.0211976703944084
5120817	24035	how do i store the select column in a variable?	select @empid = id from dbo.employee 	0.0190933080742585
5123585	31074	how to split a single column values to multiple column values?	select case          when name like '% %' then left(name, charindex(' ', name) - 1)          else name        end,        case          when name like '% %' then right(name, charindex(' ', reverse(name)) - 1)        end from   yourtable 	0
5123832	18671	pulling certain information from 2nd table but without a "where" constraint	select whatever from messages_questions as mq join accounts as a on mq.user_id = a.user_id 	0
5125609	6124	how to select date without time in sql	select convert(varchar(10), '2011-02-25 21:17:33.933', 120) 	0.0129933976189926
5126035	40668	is there a way to know the mysql server timezone using php?	select @@global.time_zone 	0.653495400646203
5126418	27458	single query with two condition	select      id, date     , case when t2.id is null then null else ‘leave’ end as status  from event table as t1  left outer join leave table as t2 on      t1.id = t2.id  where (t1.date between t2.startdate and t2.enddate) or (t2.enddate is null and (t1.date > t2.startdate)) 	0.0557277628862637
5126999	33610	mysql compare values in table	select u.nmb, sum(u.val) as total_val,r.p_val from inv u inner join bills r on r.nmb = u.nmb group by u.nmb having sum(u.val) < r.p_val 	0.00304055881191789
5128006	35075	how do i group columns in mysql and get rid of recurring ids?	select id1, count(distinct id2) ... 	0.000138381536589469
5130616	25335	comparing timestamps in mysql	select date(`yourtimestamp`) from thetablename where date(`yourtimestam`) < curdate() - interval 2 day; 	0.0160367860913034
5131043	2138	show random quote from database?	select id,user_who_posted,quote,year,author  from table order by rand() limit 1 	0.00279995068132189
5131528	16939	compare the date from other table	select    startdate,   [status]=case           when datediff(m,startdate,(select max(date) from table2))>6         then 'expired'          else 'valid'         end   from table1   where enddate is not null 	0
5131644	15878	selecting duplicate site_id's	select      deal.*,     site.name as site_name from (     select max(deal.id) as deal_id, site_id     from deal     inner join site on site.id = deal.site_id     where site.id in (2, 3, 4, 5, 6)     group by site.id ) last_deals inner join site on site.id = last_deals.site_id inner join deal on deal.id = last_deals.deal_id limit 5 	0.0110821235803498
5132784	9626	mysql three table join, find item's rating	select user_name, item_name, rating_value from user as u, item as i left join rating as r   on r.user_id = u.user_id  and r.item_id = i.item_id 	0.000951068906531663
5132822	3480	sql bit field filtering	select * from tbl_table  where (@deleted is null) or (deleted = @deleted) 	0.163985802549636
5135093	9339	is it possible to do a find function in sql?	select * from tablename where username like "%pie%" 	0.609496582071884
5135539	36258	if one table (a) relates to another (b), which relates to another (c), can i write a query to get table out of a from a join between b and c?	select price.* from portfolio   inner join price     on portfolio.portfolioid = price.portfolioid where portfolio.tradeid = 1 	0
5135864	3502	how work with foreign keys in hibernate?	select product, package  from product product join product.packages package where product.name = 'television' 	0.690215962289585
5137228	5353	php mysql counting results and if that is all of the results	select *,      (select count(*) from table) as `found`,      (select 10 - count(*) from table) as missing from table limit 10 	0.00038944432306305
5137304	21951	import table and add incremental primary id	select identity(int,1,1) as id, * into #newtable from dbo.oldtable; 	0.000242734542611061
5137667	25399	column a contains column b	select col1 where col1 regexp (col2) 	0.00175621330058605
5137930	28845	sql counting sums of rows	select f.id as fruit_id, count(1) as purchase_count   from fruits f left join customers c     on f.id = c.fruit group by f.id 	0.00207546993568701
5138547	5411	sql group by combination?	select chat.*,         (select screen_name          from usr          where chat.from_device_id=usr.device_id         limit 1        ) as from_screen_name,         (select screen_name          from usr          where chat.to_device_id=usr.device_id         limit 1        ) as to_screen_name from chat  where to_device_id="ffffffff-af28-3427-a2bc-83865900edbe" or        from_device_id="ffffffff-af28-3427-a2bc-83865900edbe"  group by from_device_id, to_device_id order by date desc limit 1; 	0.238353346462899
5140024	13744	mysql last 5 in reverse order?	select `name` from (select `id`, `name` from `table1` where id='0' order by `id` desc limit 5) tmp order by `id` asc 	0.00274437152311334
5141521	23129	how to insert data from excel sheet to sql server 2005	select * into #tmptable from openrowset('microsoft.jet.oledb.4.0', 'excel 8.0;database=c:\test\xltest.xls', [sheetname$]) 	0.0335027453564036
5142140	14462	mysql rows into columns, optimization query using if	select  group_concat( if( a.rank='mod', concat( m.prenom, ' ', m.nom ), '' ) ) as 'mod',  group_concat( if( a.rank='adm', concat( m.prenom, ' ', m.nom ), '' ) ) as 'adm' from `0_area` as a left join 0_member as m on a.user_id = m.id left join 0_depart as d on a.user_id = d.user_id where a.sec_id =2 and (a.rank = 'mod' or a.rank = 'adm' ) and d.department in ( 75, 92 ) group by a.sec_id 	0.0667765656705947
5143217	10817	sql server 2008 - query which matches both conditions	select  o.customerid from    orders o inner join         orderitems oi on o.orderid = oi.orderid  where   (oi.orderitemstatusid = 1) and (oi.remainingweeks in (1, 4))  group by o.customerid having count(distinct oi.remainingweeks) = 2 order by o.customerid 	0.311392549136007
5144137	9794	how do i convert sql getdate() function into a string in dd/mm/yyyy format?	select convert(varchar(10),getdate(),103) 	0.0316297756640222
5146097	14404	show the ten first contacts that i have recieved message	select m2.fromuser     , lastmessage.messagebody     , lastmessage.timestamp from    (         select m1.fromuser             , min(m1.timestamp) as firstmessage             , max(m1.messageid) as lastmessageid         from messages as m1         where m1.touser = 'my username'         group by m1.fromuser         order by min(m1.timestamp) asc         limit 10         ) as m2     join messages as lastmessage         on lastmessage.messageid = m2.lastmessageid 	0.000118646077696022
5146978	876	count number of records returned by group by	select     count(*) recordspergroup,     count(*) over () as totalrecords from temptable group by column_1, column_2, column_3, column_4 	0.00020713629616154
5148570	7657	related rows mysql query	select * from ad_table where title regexp '[[:<:]]android[[:>:]]|[[:<:]]smartphone[[:>:]]' 	0.0185390516018217
5149649	17538	mysql : writing a query where a column is the result of a boolean expression	select col1, col2,     (deposit_received     and paperwork_received      and preferred_physician is not null     and preferred_physician_phone is not null)   as result from tablename 	0.590953833083608
5150600	21618	creating unique hash code (string) in sql server from a combination of two or more columns (of different data types)	select substring(master.dbo.fn_varbintohexstr(hashbytes('md5', 'helloworld')), 3, 32) 	0
5155003	11189	mysql select tablex from all databases	select * from db1.plays, db2.plays, ...., db3.plays where <condition> 	0.00374674905735419
5157400	9758	how do i order query results by an associated model field with conditions?	select *         from keywords         as keyword         left join (select keyword_id,count(*) as click_count from clicks group by keyword_id)         as click         on keyword.id = click.keyword_id         where keyword.word_count > ".$keyword['keyword']['word_count']."         and upper(keyword.keyword) like '%".strtoupper($keyword['keyword']['keyword'])."%'         order by click.click_count desc 	0.113026204210661
5157536	7580	how can i join multiple polymorphic tables without pulling back blank records?	select * from users   inner join participations      on (users.id = participations.user_id)     and ( (participations.group_type = "club" and participations.group_id is in (12,20))        or (participations.group_type = "class" and participations.group_id is 10) ) 	0.00777752249280009
5157599	11651	using inner join to receive crossed data by date range	select theme.id_theme, theme.title, count(views.id_view) as view_count from theme left join views on (theme.id_theme = views.id_theme) group by theme.id_theme where views.date > date_sub(now() interval 30 day) order by view_count desc having view_count > 0 	0.0366656924085419
5157920	13256	sql: count number of columns in all tables, excluding views	select      t.name,     count(c.name) from      sys.tables t      inner join sys.columns c     on t.object_id = c.object_id group by t.name 	0
5158913	36365	tsql max in a range	select foo1, foo2, foo3, field_etc, max(score) maxscore  from (select foo1, foo2, foo3, field_etc, score1, score2, score3, score4, score5         from sometable) base   unpivot (score            for whichscore            in (score1, score2, score3, score4, score5)) upvt   group by foo1, foo2, foo3, field_etc 	0.0180623198983461
5161002	17169	many-to many query	select top 5 tag_id, count(*) cnt from taggins group by tag_id order by cnt desc 	0.711724562509751
5161297	19771	mysql regexp: a digit who is not followed by a digit	select * from `mes` where text regexp '#11^[:digit:]' 	0.0620072663384933
5163175	7014	sql join limit results to rows where specific value does not exist	select * from charter c inner join crew on (charter.char_trip = crew.char_trip) where crew.crew_job = 'pilot' and (select count(*) from charter                                    inner join crew on (charter.char_trip = crew.char_trip)                                    where crew.crew_job = 'copilot'                                           and charter.chart_trip = c.charttrip) = 0 	0.0572819990128702
5164614	13452	selection of column based on max value	select    (select max(count1)    from (     select count1 union all     select count2 union all     select count3 union all     select count4 union all     select count5) x) as maxcount from tbl 	4.94861691098886e-05
5169766	11031	sql query to find status of the last event of an order	select a.orderid, e.status from (    select o.orderid, max(e.eventdate) latestdate    from tblorders o    inner join tblevents e on o.orderid = e.orderid    group by o.orderid    ) a inner join tblevents e on e.orderid = a.orderid where e.eventdate = a.latestdate 	0
5169811	2119	"friend" relationships across two mysql tables	select u.u_name from friends f, user u where (f.u_id1 = '1' and u.u_id = f.u_id2)    or (f.u_id2 = '1' and u.u_id = f.u_id1) 	0.00473682146535557
5171385	19223	how do i display a field's hidden characters in the result of a query in h2?	select rawtohex('test' || char(13) || char(444)); > 0074006500730074000d01bc select stringencode('test' || char(13) || char(444)); > test\r\u01bc 	0.000301935769618715
5173217	23042	sum field using sql in php	select customers.name, sum(books.price) from customers, orders, order_items, books where customers.customerid = orders.customerid  and orders.orderid = order_items.orderid  and order_items.isbn = books.isbn group by customers.customerid; 	0.110062617484893
5173382	13455	selecting a max distinct value	select top 1 name, count(*) total     from phone where number = '555.1234'     group by name     order by total desc 	0.00105449247446045
5174473	27224	sql: selecting rows contained in a group	select b.claimid, b.claimdate, b.clientname, g.claimcount from (     select clientname, count(claimid) claimcount     from billings     where claimdate > '2010'     group by clientname     having count(claimid) > 1 ) g inner join billings b on b.clientname = g.clientname where b.claimdate > '2010' 	0.00652154478871627
5175345	24328	comparing fields and getting percentage	select t1.user_id     , count( t2.user_id ) / count( t1.user_id ) * 100.0 as percentmatch from user_artist_favorites as t1     left join user_artist_favorites as t2         on t2.artistname = t1.artistname             and t2.user_id = 'tester' where t1.user_id = 'moonwalker' group by t1.user_id union all select t1.user_id     , count( t2.user_id ) / count( t1.user_id ) * 100.0 from user_artist_favorites as t1     left join user_artist_favorites as t2         on t2.artistname = t1.artistname             and t2.user_id = 'moonwalker' where t1.user_id = 'tester' group by t1.user_id 	0.00566527919513062
5176257	29518	how to capture state of an entity in database during the course of business process?	select * from order     inner join activeorder        on     order.orderid = activeorder.activeorderid        where activeorder.status = 'l' 	0.00234099116526755
5177053	16334	find rows using nested count, join, or having	select distinct streetnum from atable as a1,atable as a2 where a1.streetnum=a2.streenum and a1.item is null and a2.item is not null; 	0.246207320549258
5177131	32029	mysql: select all items in common between two users	select i.item_id       from item_tb i inner join user_tb u on i.user_id = u.user_id      where i.user_id in (42, 43)   group by i.item_id     having count(*) = 2 	0
5177425	10332	calculate difference of value for consecutive days for all objects in sql	select t2.object,t2.index,t2.date,t2.value-t1.value from table t1, table t2     where t1.object=t2.object and t1.index=t2.index         and t2.date=date_add(t1.date, interval 1 day); 	0
5177471	18430	how to execute two quires in jdbc	select emp.name,        emp.salary,        count(*) over () as total_count from   employees emp; 	0.423617812138338
5178638	38631	how to make a sum with conditions?	select   employee.name, employee.surname, sum(timesheet.hours_par_day +              (case                 when contract.id_category = '206'                 then 15                 else 0             end             )         ) as hours_worked from contract join employee on contract.employee_id = employee.employee_id      join timesheet on contract.contrat_id = timesheet.contrat_id      left join contract_categories      on contract.contract_id = contract_categories.contract_id where contract.customer_id = '108538'  and contract.begin_date between '01/01/2008' and '01/03/2011'  and employee .employee_id in (             select employee_id             from contract             where contract.client_id = '108538'             and contract.end_date >= '01/01/2011') 	0.21545338730031
5178857	34353	how to list out top 10 salaries with out using top	select  salary from (   select  salary, row_number() over(order by salary desc) as 'salaries' from user2 )#emp    where  salaries <=10 order by salary desc 	0.000210996396145841
5179104	13526	get field from first table by foreign key from second	select c1.name, c2.name from relations as r left join categories as c1 on r.parent = c1.id left join categories as c2 on r.child = c2.id where c1.id = 1 	0
5179896	203	mysql - subquery with date and like	select * from mytable where month(date) = (select month(max(date)) from mytable) and year(date) = (select year(max(date)) from mytable) order by date asc 	0.759472089363005
5180962	2014	returning max values from two individual queries	select max (rownum)   from (select rownum from t_table1          union         select rownum from t_table2) 	0.000368469880627913
5184196	8247	convert date against where clause	select srno from dummy where name = 'mahesh' and date= convert(datetime,'12/04/2010',103) –- i have date in dd/mm/yyyy format and acid=3 	0.423154725889372
5184429	24545	querying a sql server 2008 table to find values in a column containing unicode characters	select * from your_table where your_column like n'%[^ -~]%' collate latin1_general_bin 	0.00340159014387413
5184736	30155	possible to delete everything after a 'space' in mysql field?	select substring_index('name sub _blah',' ',1) 	0.0257703127548657
5185065	22552	select x times for each row without union	select     id,     case when p.paydate > x.comparedate then 1 else 0 end,     (1 + cap) * (p.value + modf * p.premium),     @nextyear from products p cross join (     select @defcapup cap, cast(0 as datetime) comparedate, 1 modf union all     select -@defcapdown, 0, -1 union all     select -@defcapup, getdate(), -1 union all     select @defcapdown, getdate(), 1     ) x 	0
5185993	1698	sql help with omitting records	select id, year from table t where not exists (select * from table t2                    where thirdcolumn = 'a'                   and t2.id = t.id                   and t2.year = t.year) 	0.598861807833816
5186378	20336	how to: count widgets sold every 7 days for a period of a year	select       datepart(week, w.createts) as [soldweek]     ,count(*) as numberofwidgets     ,ft.formname from tblwidget w join tblformtype ft on (w.formtypeid = ft.formtypeid) where w.createts >= dateadd(year, -1, @rundate) group by datepart(week, w.createts), ft.formname 	0
5186575	1395	how do i retreive and display a timestamp from a mysql database using php?	select unix_timestamp(yourdatefield) from yourtable 	5.5840173315087e-05
5186967	11270	sql server 2000: how do i get a list of tables and the row counts?	select o.name, rows  from sysindexes i join sysobjects o on o.id=i.id where indid < 2 and type='u' 	4.81856984116839e-05
5188774	22738	counting records from table that appear is one but not other: mysql	select count(*) from users where not exists   (                     select 1                     from userpreference as up1                     where up1.id = users.id                         and up1.preferencevalue = 'shopping'                     ) 	0
5189976	31278	can i do an sql query on a table and its join table at the same time?	select book_name,         tag_name  from   books         left join books_tags           on books.book_id = books_tags.book_id         left join tags           on tags.tag_id = books_tags.tag_id  where  books.book_id = 283 	0.000131973333302126
5191494	7109	padding the beginning of a mysql int field with zeroes	select lpad(convert(`col`,varchar(3)),3,'0') 	0.00353951532839989
5191703	24532	using union and then arrange the data with order by from second row onwards	select *,1 as tab from items  where status = 'a' and staffid = '$var1' and workid = '$var2' union select *,2 from items  where status = 'a' and staffid = '$var1' and workid != '$var2' order by tab,seq 	0
5194675	1219	sql server join adds results?	select personid, actionx = count(distinct varname), actiony = sum(distint varname) from tblname1 a inner join tblname2 b on a.personid = b.personid where b.group_id = 'groupvar' 	0.777237498332337
5195263	799	sql - need to determine implicit end dates for supplied begin dates	select       m1.*     , min( m2.joindate ) - interval 1 day as leavedate from     members m1 left join     members m2 on    m2.memberid = m1.memberid and   m2.joindate > m1.joindate group by       m1.memberid     , m1.groupid     , m1.joindate order by       m1.memberid     , m1.joindate 	0.0486384757522486
5196822	17259	select the maximal and minimum dates in the last 3 months	select min(`date`) as date1,        max(`date`) as date2    from mytable  where `date` between now() - interval 3 month                    and now(); 	0
5198942	1702	the best way to add a concatenated string of multiple fields to a stored procedure	select    replace   (     convert(char(5), [dtmon_f],108) + ' - ' +      convert(char(5),[dtmon_t],108) + ' - ' +    convert(char(5),[dttues_f],108) + ' - ' +    convert(char(5),[dttues_t],108) + ' - ' +     ...      , ':', '') as whatever  from mytable 	0.000389799520883202
5199849	17834	split varchar into separate columns in oracle	select substr(t.column_one, 1, instr(t.column_one, ' ')-1) as col_one,        substr(t.column_one, instr(t.column_one, ' ')+1) as col_two   from your_table t 	0.000410730080332678
5202110	14098	mysql distinct with sum	select    t.username, sum(t.bytes) from ( select username, messageid, bytes    from my_table   group by username, messageid) as t group by t.username 	0.153546505584879
5204684	34540	query to check whether a column is nullable	select columnproperty(object_id('tablename', 'u'), 'columnname', 'allowsnull'); 	0.00437835416971458
5204750	22021	sql selecting from 3 tables returns syntax error	select a.column1, a.column2, a.column3, a.columnid, b.column1 from (table1 as a      inner join table2 as b          on a.columnid = b.columnid)      inner join table3 as c          on a.columnrelativeid = c.columnid where a.columnid = 16 	0.542907773236454
5204999	41309	how to getting number of records after union operation..?	select     count(*) from     (     select author1 from books_group where category='cse' union     select author2 from books_group where category='cse' union     select author3 from books_group where category='cse'     ) a 	0.000917605389585215
5205138	34006	select records only if another record contains a value from the first record in different field	select * from employees e  where e.first_name like '%<first_name_string>%'  and e.last_name like '%<last_name_string>%'  and (select count(*) from employees where employees.supervisor_id = e.user_id) > 0) 	0
5205507	24572	count only null values in two different columns and show in one select statement	select     (select count(*) from table1 where column1 is null) as 'column1count',     (select count(*) from table1 where column2 is null) as 'column2count'; 	0
5206577	7733	better query strategy to sort files by file hash frequency and file size	select filehash, group_concat(filename), filesize, count(*) as group_files     from files group by filehash order by group_files desc 	0.196449291634257
5206596	20447	mysql select rows where value in comma-delimited column	select * from table t  where if(find_in_set(column,(select "1,2,3" from othertable where 1))>=1,1,0)  	0.00110157804429842
5208610	27046	how do i write a standard sql group by that includes columns not in the group by clause	select c.departmentid, c.name, c.hired from customer c, (select departmentid, max(hired) as maxhired   from customer  group by departmentid) as sub where c.departmentid = sub.departmentid and c.hired = sub.maxhired 	0.454710553978692
5209184	34691	how to group by category and then find the percentage of the income?	select  (100*(select sum(amount) tot_inc from money.income ic where month(ic.date) = "02")/sum(amount)) as "result" from expenditure e  where month(ex.date) = "02" group by categoryid having result > 10 	0
5210817	28428	sql query to fetch data from the last 30 days?	select productid from product where purchase_date > sysdate-30 	0
5212530	21273	last 5 related records for multiple records	select reading,        date from   (select sensor_id,                reading,                date,                @num := if(@sensor_id = sensor_id, @num + 1, 1) as row_number,                @sensor_id := sensor_id                         as dummy         from   sensor_readings         order  by sensor_id,                   date desc) t where  row_number<=5 	0
5213475	18003	fastest way (and most optimized) to calculate and sort users by ascending order of zip code distance	select distinct zipcode from users where ... 	0.000191038493329619
5216761	8361	getting count of each item	select id, count(*) as totalcount from abc where id in (1,3,6) group by id 	0
5216762	568	how to put extra condition in select clause in sql server 2008	select  code ,         max(case patientcharts.chartstatusid             when 1 then dateadd(hour, seed_timezone.differencefromutc, completedon)             else convert(datetime, '1-jan-1900') end) 'lastcompletedon' ,         max(dateadd(hour, seed_timezone.differencefromutc,lastupdatedemographicsdate)) 'lastedaon' from    patientcharts with ( nolock )         inner join facilities with ( nolock ) on facilities.facilityid = patientcharts.facilityid         inner join seed_timezone with ( nolock ) on seed_timezone.timezoneid = facilities.timezoneid where   facilities.isactive = 1         and patientcharts.isdeleted = 0         and patientcharts.iserroneous = 0 group by code 	0.665791472337658
5217187	23618	querying 2 entries that are with the same value but with dates within 24 months	select    i1.customerid  from    dbo.icecreamorders i1    join    dbo.icecreamorders i2 on i1.customerid = i2.customerid and i1.flavor = i2.flavor and                         datediff(month, i1.dateordered, i2.dateordered) <= 24 where    i1.flavor = 'vanilla' group by    i1.customerid having    count(*) >= 2 	0
5217494	20351	doing a count on more than a column	select count(*) as [total products owned],     sum(p.views) as [total product views],     (select count(*)       from product p join reviews r on p.prodid = r.prodid       where p.prodowner = 'jake bill'     ) as [total reviews received on all products] from product p where p.prodowner = 'jake bill' 	0.0309314043858365
5218095	1461	mysql, join on same table?	select  parent.id,         child.name,         parent.name from    yourtable as parent left join          yourtable as child on parent.parentid = child.id 	0.0176585012178131
5221553	20453	sql 2008 retrieving attribute values from an xml column	select     metadata.value('(/root/class/int16_t/@value)[1]', 'int') as 'int16_value' from     dbo.yourtable 	0.000165280369576374
5222075	3271	sql datetime format to date only	select subject,         convert(varchar,deliverydate,101) as deliverydate from email_administration  where merchantid =@merchantid 	0.00414060232812551
5222212	301	select an xml type column in select query with group by sql server 2008	select ci.candidate_id, ci.firstname, convert(xml,convert(varchar(max),ci.detailxml)) detailxml from candidate_instance ci  where ci.candidate_instance_id=2 group by  ci.candidate_id, ci.firstname, convert(varchar(max),ci.detailxml) 	0.523849485879388
5223360	28824	sql multiple case statements return 0 instead of null	select           isnull(sum(case when type = 1 then amount else amount * - 1 end),0) as balance from         dbo.memberfinancials as mf inner join                       dbo.members as m on mf.memberid = m.memberid and datepart(yyyy, mf.date) = m.membercurrentyear inner join                       dbo.financialtypes as ft on mf.financialtypeid = ft.financialtypeid 	0.37956759520632
5224590	35168	count memberships of user in groups	select  is_types.name     , roles.name     , count(z.is_type_name)  from roles     cross join intern_structure_types as is_types     left join   (                 select is_types.name as is_type_name                     , roles.name as role_name                 from intern_structures as is_elements                      join intern_structure_types as is_types                         on is_types.id = is_elements.intern_structure_type_id                     join memberships                         on memberships.intern_structure_id = is_elements.id                     join roles                         on roles.id = memberships.role_id                 ) as z         on z.is_type_name = is_types.name             and z.role_name = roles.name group by is_types.name, roles.name 	0.00639516780680438
5224907	32814	joining tables with like (sql)	select *  from tableone     join tabletwo on tableone.pizzaone like ('%' || tabletwo.pizzatwo || '%') 	0.473742621281768
5225451	344	obtain the last inserted record of a group of same id's	select idsale, max(dateinserted) dateinserted from tablename group by idsale 	0
5227313	7009	how do i join 4 tables on mysql select statement?	select * from ads as a left join images as i on i.img_ads_id = a.ad_id and i.img_status = 1 left join users as u on u.id = a.ad_userid and u.user_status = 1 left join category as c on c.cat_slug = a.ad_category where a.ad_pic = 1 and a.ad_status = 1 order by a.ad_id desc limit 0,4 	0.203294033022333
5227398	37048	where to get oracle service_name?	select sys_context('userenv','service_name') from dual 	0.165986423029628
5228577	32838	get the minimum price of each product type with currency conversion	select a.id, a.price*isnull(s.to_aud,1) as minprice from (  select type_id, min((price+shipping)) as minprice  from products  group by type_id ) as b inner join products as a on a.type_id = b.type_id and (a.price+a.shipping) = b.minprice inner join sellers s on s.id = a.seller_id order by price 	0
5231336	38821	sql use grouped values to use in a subquery + "where column in())"	select  c.responsibleid         , count(distinct c.id)         , count(*) from    case c         left join action a on a.caseid = c.caseid group by         c.responsibleid 	0.165493577099125
5231461	22042	select row that is within start date	select * from promotions where '$current_date' between date_from and date_to 	0.00118465112952207
5233238	21542	query to get records matching another table?	select abc_id from abc inner join xyz1 on abc.xyz_id1=xyz1.xyzid inner join xyz2 on abc.xyz_id2=xyz2.xyzid where xyz1.location=xyz2.location 	0
5235232	25476	sql query using in but where all results have to have the same grouping id	select productsetid, count(*) as countofmatchingrows from mytable where attributeid in (14,17 ) group by productsetid having count(*) = 2 	0
5237301	36521	return all nodes in many-to-many hierarchal tree	select *  from tbl inner join closure on tbl.id=closure.desid  where closure.ancid = 2 	0.00842158879759261
5239847	18166	query datetime in sql without time	select count(*) from xyz where time between '2010-01-21' and '2010-01-22 	0.148779396815541
5240601	12590	php, mysql query	select     * from     `users` where     concat(',', `connections`, ',') like concat('%,', @x, ',%') 	0.512830742731512
5240791	13274	sql server stored procedure get count of people attending events	select top (100) percent dbo.tb_events.eventname, dbo.tb_events.eventdate, count(dbo.tb_eventattendance.willattend) as numattendees,  from  dbo.tb_eventattendance inner join dbo.tb_events on dbo.tb_eventattendance.eventid = dbo.tb_events.dbid where     (dbo.tb_eventattendance.willattend = 'y') group by dbo.tb_eventname, dbo.tb_events.eventdate order by dbo.tb_events.eventdate 	0.00397869637359332
5240954	2619	select all value from table only once if they're duplicated	select distinct adspot from your_table; 	0
5242034	23995	mysql query for both distinct and sum	select * from table group by url_id,time_spent 	0.115501400517448
5244142	23154	how to make the resultset returned from oracle keeps its column aliases characters case	select part_id "partid", part_num "partnumber" from tbl; 	0.0679812015215741
5244278	21152	finding out redundancy	select foriegn_column_name,count(foriegn_column_name) from table_name group by foriegn_column_name having count(foriegn_column_name) > 1 	0.0723524304977532
5244666	27718	avoiding a cross-join	select      installed.prefix,      quantityoflicensesinstalled,      purchased.prefix,      quantityoflicensespurchased,      (quantityoflicensesinstalled-quantityoflicensespurchased) as differencebetweenvalues from clientidprefixsuminstalled  full outer join clientidprefixsumpurchased on installed.prefix = purchased.prefix; 	0.749542766464971
5244837	41008	how to construct a sql query with different aggregation	select  dt.date ,       dt.type ,       sum(dt.cost) as daytypetotal ,       (select sum(cost) from @t d where d.date = dt.date) as daytotal ,       100.0 * sum(dt.cost) /               (select sum(cost) from @t d where d.date = dt.date) as percentage from    @t dt group by         dt.date ,       dt.type 	0.424708096227555
5246457	14240	in sql server how to get a column values with `<br>` separate	select     stuff(              (select                   '<br/>' + cast(citation_id as nvarchar(500))                   from tollplus.violated_trips                   for xml path(''), type              ).value('.','varchar(max)')              ,1,5, ''          ) as citation_id 	0.000466294700052029
5247483	1252	mysql query split by month	select distinct     month(accesstime) accesstimemonth,      devid,     username  from auth_log 	0.00660659964804245
5248012	27831	mysql query: selecting from two rows in the same field	select id, name from products where instock = 1 and (referer = 'google.com' or referer = 'google.ca'); 	0
5248192	12060	get number of users of different type	select count(*) as count ,type from users  group by type 	0
5248278	37190	mysql sum() on different group bys	select    stock_sums.item_id,    stock_sums.st_sum as stock_in_total,   coalesce(sold_sums.so_sum,0) as sold_total,   (stock_sums.st_sum - coalesce(sold_sums.so_sum,0)) as left_total from (   select stock.item_id as item_id, sum(stock.amount) as st_sum    from stock    group by item_id ) as stock_sums  left join (   select sold.item_id as item_id, sum(sold.amount) as so_sum    from sold   group by item_id ) as sold_sums on stock_sums.item_id = sold_sums.item_id 	0.0330280129384629
5248902	9906	sql server - view all foreign key dependencies	select object_name(parent_object_id), object_name(referenced_object_id)     from sys.foreign_keys     where referenced_object_id = object_id('schemaname.tablename') 	0.00503887490256053
5250489	25260	getting cumulative count	select count(*) as numcount,          t.column2                  from your_table t group by t.column2 order by numcount desc 	0.0210549827031465
5250599	36409	sql joining two tables	select e.id, e.name , s.salary from employees e  inner join salary s on e.id=s.id order by e.id asc 	0.0204158111533011
5252415	39936	compare data in two tables	select sum ( error_count ) as total_errors into num_errors from ( select count ( * ) as error_count from mprlib . v_tshoursumm a exception join mprlib . v_reqhoursumm b on a . em_number = b . em_number and a . timesheet_code = b . timesheet_code and a.hours_summary = b . hours_summary where a . em_number = employee_id or b . em_number = employee_id union select count ( * ) as error_count from mprlib . v_reqhoursumm a exception join mprlib . v_tshoursumm b on a . em_number = b . em_number and a . timesheet_code = b . timesheet_code and a . hours_summary = b . hours_summary where a . em_number = employee_id or b . em_number = employee_id ) table 	0.00135587615678377
5253896	41051	turn multiple (m) rows of (n) columns into one row with (m*n) columns in oracle	select min(decode(rownum, 1, a, null)) a,        min(decode(rownum, 1, b, null)) b,        min(decode(rownum, 1, c, null)) c,        min(decode(rownum, 1, d, null)) d,        min(decode(rownum, 2, a, null)) a2,        min(decode(rownum, 2, b, null)) b2,        min(decode(rownum, 2, c, null)) c2,        min(decode(rownum, 2, d, null)) d2 from <test_table> 	0
5255440	13228	joining two tables back on them selves together	select  parentlink.sourceworkitemid, parentlink.targetworkitemid,             childlink.sourceworkitemid, childlink.targetworkitemid,              childlink.workitemlinktypesk from    dbo.factworkitemlinkhistory parentlink         join dbo.dimworkitemlinktype parentlinktype (nolock)             on parentlink.workitemlinktypesk = parentlinktype.workitemlinktypesk         left join            (dbo.factworkitemlinkhistory childlink (nolock)             inner join dbo.dimworkitemlinktype childlinktype (nolock)               on childlink.workitemlinktypesk = childlinktype.workitemlinktypesk                 and childlinktype.linkname = 'child')           on parentlink.targetworkitemid = childlink.sourceworkitemid           and childlink.removedbypersonsk is null where   parentlink.sourceworkitemid = 1917         and parentlink.removedbypersonsk is null                 and parentlinktype.linkname = 'releases story' 	0.00160658588556119
5255866	15976	sql query: how can i get the corresponding employee id which are not allotted to department?	select empid, name from employee where empid not in (select empid from allocateddetails) 	0
5256709	39569	how to get max(colname) value where colname is of type timestamp in mysql	select     _id,     game_id,     inning_id,     scoretype,     oponentonescore,     oponenttwoscore,     currenttime,     latest from     game_scores join (     select         max(currenttime) as latest     from         game_scores     where         game_id = '2268' ) as latest_calculation where game_id = '2268'; 	0.000851000726370911
5257451	5781	sql logical compression of records	select     substring(t.digit,0,len(t.digit)-1)     (select top 1 source         from innertable i         where substring(i.digit,0,len(i.digit)-1)                 = substring(t.digit,0,len(t.digit)-1)         group by i.source         order by count(*) desc     ) from table t     group by substring(t.digit,0,len(t.digit)-1) having count(*) = 10 	0.0605776018729465
5259319	22396	wrap xml column values into outer for xml path query	select     'val' as [@att],      [col] as [*] from     @tab for xml path ('root'); 	0.303343301621422
5259351	1312	name already used by an existing object in vba	select t.coupon_upc, t.division from    (select lca.coupon_upc,lca.division from  lca where lca.campaign_id = campaign_id      minus      select mcr.coupon_upc,mcr.division from  mcr where mcr.campaign_id = campaign_id) t  where {clauses here...} 	0.246684107939695
5260153	6025	what is the fastest way to select a whole table in sql server?	select * from table_name 	0.159063792513079
5262354	12380	how can i compare tables in two different databases using sql?	select * from db.sys.columns where object_id = object_id('db.schemaname.table1') 	0.000668865610042767
5262611	24889	can you return different values for multiple rows on the same join?	select t.first, t.last, t.type, t.dob, t.address     from (select id, first, last, 'parent' as type, dob, address, 1 as sortkey              from parent           union all           select p.id, d.first, d.last, d.type, d.dob, p.address,                   case when d.type = 'spouse' then 2 else 3 end as sortkey               from dependents d                   inner join parent p                       on d.parentid = p.id) t     order by t.id, t.sortkey 	0
5264373	39644	how to retrieve a default row when a mysqli_stmt_fetch fails?	select col1, col2, col3 from table where id = :id union all  select col1, col2, col3 from table where id = 1 where not exist (select 1 from table where id = :id) 	0.00280089818624553
5264610	11312	convert int to truncated decimal	select round( 51501319 / 1000000.000, 1 ) 	0.289858797664952
5264838	18493	joining 2 tables in a database	select country, district, population from city inner join country on country.countryid = city.countryid where city.name = 'tulsa'; 	0.0072445999983768
5264843	25365	sqlserver - select bool if column begins with a string	select cast(case when name like 'foo%' then 1 else 0 end as bit) as isfoo from bar; 	0.0347132323525411
5264902	9730	counting distinct undirected edges in a directed graph in sql	select count(*) from (   select to_there from edges where from_here = 1   union   select from_here from edges where to_there = 1 ) as whatever 	0.12847584631862
5265684	38143	select tables that do not contain a certain column in mysql	select t.* from information_schema.tables as t     left join information_schema.columns as c     on c.table_name = t.table_name     and c.table_schema = t.table_schema     and c.column_name = 'unique' where c.column_name is null and t.table_schema = 'database' 	0.000416716385065441
5267715	36420	whats the correct query for getting the current number of connections in a postgresql db?	select sum(numbackends) from pg_stat_database; 	0.000156454338097842
5268088	32195	extra backslash \ when select ... into outfile ... in mysql	select * from business where id > 0 and id <= 20000 into outfile "business.csv" fields terminated by ',' optionally enclosed by '"' escaped by '"'  lines terminated by '\n'; 	0.751534949280455
5268640	4815	sql query to get the source of a stored procedure	select routinename, text from syscat.routines where definer not in ('sysibm') and routineschema='databasename' 	0.0250707536852739
5268972	8197	selecting two random rows in an sql table where the values of a column come very close	select top 1 id1, id2 from (   select c1.id as id1, c2.id as id2 from codesnippets c1, codesnippet c2   where c1.id <> c2.id and abs(c1.score-c2.score) < [threshold] ) order by rand() 	0
5269356	39171	sql union query	select     isnull(pv2.propertyid, jv2.propertyid),     isnull(pv2.initialvisit, 0),     isnull(jv2.jobvisit, 0) from     (     select pv.propertyid, count(pv.visitid) as initialvisit     from tblpropertyvisit pv     where pv.status = 0     group by pv.propertyid     ) pv2     full outer join     (     select jv.propertyid, count(jv.jobvistid) as jobvisit     from tbljobvisits jv     where jv.visitstatus = 1     group by jv.propertyid     ) jv2 on pv2.propertyid = jv2.propertyid 	0.697361477975413
5270623	8065	sql getting data with extra row	select  distinct column1, [column2] = 0 from    (           youroriginalquery         ) q union all          youroriginalquery 	0.0210968343462614
5274543	40037	mysql group by a field based on the maximum value of another field in the group (not in the table)	select      tbl_unit.un_id,     tbl_availability.avl_id,     tbl_availability.avl_date,      tbl_availability.avl_status from     tbl_unit inner join      (select un_id, max(avl_id) as max_avl_id from tbl_availability group by un_id) t     on tbl_unit.un_id = t.un_id inner join tbl_availability on      t.max_avl_id = tbl_availability.avl_id where     tbl_availability.avl_active='true' and     tbl_unit.un_active='true' and     tbl_availability.avl_date >= '2011-03-10' and     tbl_availability.avl_date 	0
5274592	7160	count unique records in database	select count( distinct( email ) ) from table 	0.00147405741897291
5277631	20280	mysql between query	select   * from     mytable where    date(timestamp) = curdate() 	0.220276168887517
5279079	6341	mysql convert timediff output to day, hour, minute, second format	select concat( floor(hour(timediff('2010-01-06 08:46', '2010-01-01 12:30')) / 24), ' days ', mod(hour(timediff('2010-01-06 08:46', '2010-01-01 12:30')), 24), ' hours ', minute(timediff('2010-01-06 08:46', '2010-01-01 12:30')), ' minutes') 	0
5279278	17246	left join variation based on dates	select answers.id, answers.answer_text, count(polls_results.id) as total   from answers    left join polls_results on answers.id = polls_results.answer_id                           and polls_results.date >= ".$startdate." and polls_results.date <= ".$enddate." where answers.poll_id = ?    and answers.activate = '0' group by answers.id 	0.0157467816392342
5279839	35172	mysql query; if greater than a value 'yes' else 'no'; grouping	select account, if(max(status)>2,'no','yes') as pending  from table  group by account 	0.0183871428479575
5281575	8970	change query to return the rows that don't match	select   t.clinic_code, c.dt, t.schedule_time, t.section_name,   t.section_content, cs.schedule_event_source_id from master_templates t   inner join calendar c     on  t.dw = c.dw     and t.mo = (c.d - 1) / 7 + 1     and c.y = '2014'     and c.m = '3'     and t.clinic_code = 'abc'   left outer join clinic_schedule cs     on  cs.schedule_date=convert(varchar, c.dt, 121)     and cs.clinic_code=t.clinic_code     and cs.schedule_time=t.schedule_time     and cs.section_name = t.section_name     and cs.schedule_event_source_id = 2   where cs.clinic_code is null 	0.000208244833093589
5283836	3220	display mysql table attributes via a foreign key relationship using php	select * from job as j, company as c where j.company == c.company 	0
5284923	25514	join two tables, then order by date, but combining both tables	select x.*   from ( select `id`,                 `userid`,                  'invoice' as ptype                  `amount`,                  `date`             from `invoices`            where {$userid} = userid             union           select `id`,                  `userid`,                  'payment' as ptype                  `amount`,                  `date`             from `payments`            where {$userid} = userid           ) x  order by x.`date` 	0.000643047930356925
5287032	21123	how do i connect to the default instance of sql if a "named instance" parameter is required?	select @@servername + '\' + @@servicename as instancename 	0.0409709100746624
5287064	39905	format integer to formatted date in an sqlite select statement	select strftime("%m-%d-%y", date_col, 'unixepoch') as date_col 	0.0336619221137479
5290050	3621	query for finding the tuple with other corresponding elements of value x	select n1, n2, n3 from data where n4 = 0 except select n1, n2, n3 from data where n4 <> 0 	0
5291116	3910	selecting with two references to same table	select     sp.*,     rp,*,     o.* from order o join person sp on sp.personid = o.sender_personid join person rp on rp.personid = o.receiver_personid 	0.000127996627472272
5292076	16976	how to treat null values as 0 from mysql	select tb1.id         from table_one tb1     left join table_two tb2 on tb2.user_id = tb1.user_id        where tb1.min_val <= ifnull(tb2.act_val,0)          and tb1.max_val >= ifnull(tb2.act_val,0)     group by tb1.id; 	0.00713148250874341
5293189	39483	select records from today, this week, this month php mysql	select * from jokes where date > date_sub(now(), interval 1 day) order by score desc;         select * from jokes where date > date_sub(now(), interval 1 week) order by score desc; select * from jokes where date > date_sub(now(), interval 1 month) order by score desc; 	6.15964585938558e-05
5296106	31985	copying a huge table data into another table in sql server	select into 	0.0012806053321828
5297320	14638	mysql, alternative to using in which will prioisties the first value?	select * from (     select 1 as prec, column-list from table-list     where keywords.word = '$search[0]'     limit 100) a union all select * from (     select 2 as prec, column-list from table-list     where keywords.word = '$search[1]'     limit 100) b union all select * from (     select 3 as prec, column-list from table-list     where keywords.word = '$search[2]'     limit 100) c order by prec limit 100; 	0.00721417319413108
5297372	35016	sql select & group by a period of time (timestamp)	select to_char(msg_date, 'x')       ,count(*)   from msg  group      by to_char(msg_date, 'x') 	0.000893601000218424
5301113	38667	how to get lowest value for 2 duplicate entries in php and mysql	select productid, productidentifier, productwholesaler, min(productprice)   from `products` group by productid, productidentifier, productwholesaler 	0
5301256	36053	select a value based on multiple rows in mysql	select docid     from yourtable     where tagid in (2,3)     group by docid     having count(distinct tagid) = 2 	0
5301632	40804	sql multiple count	select type,        sum(case when name like '% smith' then 1 else 0 end) as smithcount,        sum(case when name like '% anderson' then 1 else 0 end) as andersoncount     from mates     group by type 	0.175140867493932
5301842	13392	returning max value of multiple related rows and incorporate data from another table (sql server 2005)	select  customeraccountnumber, dollaramount from    (         select  *,                 row_number() over (partition by customeraccountnumber order by dollaramount desc) rn         from    tablea a         join    tableb b         on      b.requestnumber = a.requestnumber         ) q where   rn = 1 	0
5301853	19262	select data from three tables?	select * from table_1 join table_2 on (table_2.table_1_id = table_1.table_1_id) join table_3 on (table_3.table_1_id = table_1.table_1_id) 	0.00289198888375961
5302701	28046	filter sql query based on non-alpha first character	select *  from sometable  where somecolumn not like '[a-z]%' 	0.00203273577842305
5303066	14198	extract both counts and earliest instance from my dataset	select uname, count(uid), min(passdate) from userdetails inner join passdates on passdates.fkuser = uid group by uname, uid 	0.000460348377147755
5303152	40612	mysql rank (top ranked users)	select @rank := @rank + 1 as rank, overall, u.nick, u.user_id, ... from (select ... <your query including order by>) 	0.00961570250561352
5303548	41074	i need to select the value up to certain character	select substring_index('hello.  this value is from my mysql table.   	0.00109919913693188
5303694	15904	sql select all records where unique composite key	select    foo, bar, baz, min(gif), min(xyz) from    mytable group by    foo, bar, baz 	0.000420967268067541
5303793	5954	sql statement, always list 3 entries of a sort	select * from table as t1 where (select count(*) from table as t2        where t1.user_id = t2.user_id and t2.id < t1.id) <3 	0.000558399773410229
5304127	32477	sqlite substituting values where join doesn't find a match	select table_results._id        ,coalesce(table_names.name, 'no name') as [name]        ,table_results.score_1        ,table_results.score_2 from table_results left outer join table_names     on (table_reults.name_id = table_names._id); 	0.0624729396824486
5304426	41305	how to read parent and children data from sql?	select p.parentid as 'parentid', null as 'childid'     from parents p     union all     select c.parentid as 'parentid', c.childid as 'childid'     from children c     list<parent> result = new list<parent>();     parent current;     while (dr.read())     {       if (string.isnullorempty(dr['childid']))       {       }       else if (!string.isnullorempty(dr['childid'])                  && dr['parentid'].tostring().equals(current.parentid.tostring())       {       }     } 	0.000967623815371287
5304696	40027	sql: average of a dates	select customer, (max(bought) - min(bought)) / (count(bought)-1) from data group by customer; 	0.000831964089406948
5305450	21909	mysql: add an identifying field to union queries	select 'query1' as type, a, b, c, d from table1 union  select 'query2' as type, a, b, c, d from table2 	0.0466604228669405
5306687	21183	sql counting and joining	select s.allocated_to as branch, count(*) as num_ads, count(*)*100 as ad_cost  from advertisement as a inner join property as p on a.property_no = p.property_no inner join staff as s on p.overseen_by = s.staff_no group by s.allocated_to; 	0.0810300918082492
5308467	30841	date diff, including time	select time_to_sec(timediff('2011-02-14 13:05:06','2011-02-15 13:06:06'))/86400; 	0.00395437417567182
5308595	13889	sql query (can include pl/sql bits) based on conditional count	select a,b,c, sum(d) as d, sum(e) as e    from tablet    where (select count(*) from tablet) <= 3   group by a,b,c  union all select a,b,c,d,e    from tablet    where (select count(*) from tablet) > 3 ; 	0.111882925118102
5309507	1731	linq to sql: how to handle ambiguous column names when joining tables?	select new {t1a = t1.columna, t2a = t2.columna, t3a = t3.columna } 	0.0807950321442973
5311550	17959	total a value and return value in same column	select    sum(isnull(cast(a.odenen_anapara as float),0)+isnull(cast(a.faiz as float),0)+       isnull(cast(a.bsmv as float),0)+isnull(cast(a.gecikme_faiz as float),0)+       isnull(cast(a.gecikme_bsmv as float),0))     + dbo.fngcodeme(@hesap,@bas,@bit,@dov) from ... 	0
5315536	16835	select data and count comments in other mysql table	select videos.video_genre_id, videos.username, videos.title, videos.slugtitle, videos.link, videos.tags, videos.date_added, video_genre.video_genre_id, video_genre.video_genre, count(video_comments.videos_id) from videos inner join video_genre on videos.video_genre_id = video_genre.video_genre_id left join video_comments on video.id = video_comments.videos_id  where videos.accepted = 'y' group by videos.video_genre_id, videos.username, videos.title, videos.slugtitle, videos.link, videos.tags, videos.date_added, video_genre.video_genre_id, video_genre.video_genre order by  videos.date_added desc 	0.000410296581027267
5315836	24429	how to compare the length of fields in sql?	select * from mytable where char_length(name)> 3 and char_length(name) < 10 	0.000844609537265456
5316992	5246	sql syntax for retrieving from a different table?	select     user.firstname,     user.secondname,     user.aboutme,     user.dob,     picture.picturepath from user left join pictures on user.userid = pictures.userid where user.userid=1 	0.00468768894740692
5317489	4360	skip the first row if a condition is met	select * from posts where id >= (    select id    from posts    where username <> 'dummy'    order by id asc    limit 1)    order by id asc limit 10 	0.000190455928934957
5317816	36859	flex datefield and mysql default date value 0000-00-00	select coalesce(date_column,'0000-00-00') as formatted_date from your_table 	0.0107468454740573
5319064	37005	how could i have one column store an arbitrary number of "users"	select m.*, p.* from matches m join matchplayers mp on mp.matchid = m.matchid join players p on p.playerid = mp.playerid where m.teama_id = mp.teamid or m.teamb_id = mp.teamid 	0
5319239	7361	php consolidate inventory into table	select shoe_size, count(id) as count from table group by shoe_size order by shoe_size asc 	0.0104888043673869
5319305	28622	how to get an automatically incremented column value when inserting a row into a table in mysql using java?	select last_insert_id() 	0
5319643	26178	top n per group with multiple table joins	select     vendorid, productid, numsales from (     select         vendorid, productid, numsales,         @r := if(@g=vendorid,@r+1,1) rownum,         @g := vendorid     from (select @g:=null) initvars     cross join      (         select count(oi.price) as numsales,                 p.productid,                 p.vendorid         from products p         inner join vendors v on (p.vendorid = v.vendorid)         inner join orders_items oi on (p.productid = oi.productid)         inner join orders o on (oi.orderid = o.orderid)         where (p.approved = 1 and p.active = 1 and p.deleted = 0)         and (v.approved = 1 and v.active = 1 and v.deleted = 0)         and o.`status` = 'settled'         and o.deleted = 0         group by p.vendorid, p.productid         order by p.vendorid, numsales desc     ) t ) u where rownum <= 3 order by numsales desc limit 100; 	0.000767412267469127
5319717	25733	only join tables if a certain condition is met	select i2.id, i2.name from items i inner join items i2 on     (i.super = 0 and i2.id = i.id)     or     (i.super = 1 and i.subcategory_id = i2.subcategory_id) where i.id = ? 	0.000530658169796577
5324321	5798	how do i get today's transaction from sql server table	select * from rm07transaction  where      rm07tran_startdate >= '03/16/2011 00:00:00 am' and      rm07tran_enddate < '03/17/2011 00:00:00 am' 	0.000463980926893531
5324342	197	how to extract my table_names+descriptions from my "database navigator" from ibm?	select table_schema, name, table_text    from qsys2.systables 	0.084870048326332
5324366	11919	mysql select count	select count(distinct c.id) from company c join product p on c.id = product.company_id where p.is_deleted = 0 and c.is_customer = 1 and c.company_type_id = 5 	0.144851831043468
5325261	15283	how can i run queries like "within five days" on time series data?	select  top 10         a.event as 'first event',          b.event as 'second event',         abs(cast((a.timefield - b.timefield) as int)) as 'time apart' from mytable a inner join mytable b     on a.idfield <> b.idfield where (abs(cast((a.timefield - b.timefield) as int)) <= 5 	0.00102036353006374
5325664	28171	oracle query need to compare and get result in the same query	select id, date, iscomplete     from sourcedb.test   where id = '1'      and date = '2011-03-15'      and not exists (select 1 from sourcedb.test where id = '1'                     and date = '2011-03-15' and iscomplete <> 1); 	0.00278844288678617
5325816	35089	time apart in postgresql	select abs(extract(epoch from (a.timefield - b.timefield))) as "time apart" from a inner join b on (a.id = b.id); 	0.118567223363691
5326680	32525	how to do a join query for huge tables?	select      t.* from      ngr_titles t  inner join  ngr_monitordata m     on  t.id = m.titleid      and  m.when_posted = (select max(when_posted) from ngr_monitordata where titleid = t.id) 	0.498273270888567
5327288	8782	max date problem on joined table	select   * from   record inner join   record_change_log     on record_change_log.change_log_id = (       select         change_log_id       from         record_change_log       where         record_id = record.record_id       order by         record_change_date desc       limit         1     ) 	0.0180838237463008
5327519	15019	query to retrieve the name of an specific table in database and retrive primary key of that table	select * from     information_schema.table_constraints tc         inner join     information_schema.key_column_usage kcu         on             tc.constraint_catalog = kcu.constraint_catalog and             tc.constraint_schema = kcu.constraint_schema and             tc.constraint_name = kcu.constraint_name where     tc.constraint_type='primary key' and     tc.table_name like '%location%' order by     tc.constraint_catalog,     tc.constraint_schema,     tc.constraint_name,     kcu.ordinal_position 	0
5327625	11288	sql server count datasets in different results without subselect	select count(sb1.nodeid) as all, count(case when year(sb1.date)=2010 then sb1.nodeid else null end)as y2010, sb1.nodeid from stat_bc sb1  group by sb1.nodeid 	0.122684355907376
5327784	7531	mysql: order by absolute value of user-defined columns	select user_id, pref_percent, all_percent, abs(all_percent - pref_percent) as deviation     from (select user_id,           (select count(*) from responses where option_id = 1 and poll_id = 1 and pref = 1) /           (select count(*) from responses where poll_id = 1 and pref = 1) as pref_percent,           (select count(*) from responses where option_id = 1 and poll_id = 1 ) /           (select count(*) from responses where poll_id = 1) as all_percent           from responses           group by user_id          ) t     order by deviation desc 	0.00676718269795161
5329991	40039	store array in sql query	select a.catname, group_concat(b.productname) productnames from category a inner join product b on a.catid=b.catid group by a.catname 	0.354043164330775
5331363	40541	geting values by timestamp to find percent change. mysql	select t1.time, (sum(t1.value) - sum(t2.value)) from table t1, table t2 where t1.time>t2.time and t1.time = t2.time + (60 * 60 * 24) group by date(from_unixtime(t1.time) 	0.000215488611183953
5332099	2659	how can i find all the stored procedures that a certain user has execute rights to	select u.name, o.id, o.name from sysobjects o cross join sysusers u  left join syspermissions p on p.id = o.id and u.uid = p.grantee where o.xtype='p' and  (u.roles & 1 = 1 or p.actadd = 32) 	0
5333079	38511	how to get the default xmlnamespace from an xml datatype using tsql?	select  x.value('namespace-uri(.)', 'varchar(100)') from    @xml.nodes('*[1]') x(x); 	0.00312792246997897
5334861	30728	sql to match number in string	select * from table where activitiesids regexp '[[:<:]][0-9]+[[:>:]]'; 	0.00784076663631619
5334882	4488	how to get list of all the tables in sqlite database in my application	select * from sqlite_master where type='table' 	0.000351362135172476
5335120	33019	how to query the column description of a table?	select     k_table = fk.table_name,     fk_column = cu.column_name,     pk_table = pk.table_name,     pk_column = pt.column_name,     constraint_name = c.constraint_name from     information_schema.referential_constraints c inner join information_schema.table_constraints fk     on c.constraint_name = fk.constraint_name inner join information_schema.table_constraints pk     on c.unique_constraint_name = pk.constraint_name inner join information_schema.key_column_usage cu     on c.constraint_name = cu.constraint_name inner join (     select         i1.table_name,         i2.column_name     from         information_schema.table_constraints i1     inner join information_schema.key_column_usage i2         on i1.constraint_name = i2.constraint_name     where i1.constraint_type = 'primary key' ) pt     on pt.table_name = pk.table_name 	0.000689814943076586
5335735	37369	selecting distinct dates from datetime column in a table	select distinct year(date_posted), month(date_posted) from table 	0
5337970	9576	select and sums from another table. whats wrong with this sql?	select id, sumvalue, getdate() from (     select id, (select sum(value) from table) as sumvalue     from mytable ) x where sumvalue > 0 	0.307112111361012
5337984	8864	refactor sql query to return results into rows instead of columns	select c.customer_name      , p.product_type from customers c   join orders o     on o.customer_id=c.customer_id   join products p     on o.product_id=p.product_id where c.id = 111 	0.000608829564268819
5338539	23041	scoring database entries by multiple columns	select * from (     select *,       case when location = 'berlin' then 5 else 0 end +       case when royality >= 100 then 1 else 0 end +       case when familylaw = null then 1 else 0 end +       case when criminallaw = true then 1 else 0 end as score     from tbl ) scored order by score desc 	0.00108436415656403
5340328	31805	join first valid row from another table in innodb	select table.*, ht1.* from table inner join historical_table ht1      on table.id = ht1.id      left join historical table ht2      on ht1.id = ht2.id and ht1.timestamp < ht2.timestamp where ht2.timestamp is null 	0.000162026807892197
5340697	26896	how do i find percentage in sql server 2005?	select region, product, count(*)*100.0/(select count(*) from yourtable) as percentage     from yourtable     where product in ('apple','orange')     group by region, product 	0.0669717848410418
5340780	10023	counting voucher value total since the beginning of the month	select sum(voucher_value)   from vouchers  where month(from_unixtime(redeemed_at)) = month(curdate())    and year(from_unixtime(redeemed_at)) = year(curdate()) 	0
5342386	12869	mysql - -838 hours?	select    datediff(now(),'2009-12-12 13:13:13') * 24     + extract(hour from now())     - extract(hour from '2009-12-12 13:13:13') as hour_diff 	0.0247323274252863
5344711	4690	3 table join with addition inside of it	select p.ideatitle, f.feedback, f.contact, p2.yescount, p2.nocount from ideas p left join feedback f on f.ideaslug = p.ideaslug left join (     select         p.ideaslug,         sum(case when v.vote = '1' then 1 else 0 end) as yescount,         sum(case when v.vote = '0' then 1 else 0 end) as nocount     from ideas p     left join votes v on v.ideaslug = p.ideaslug     group by p.ideaslug ) p2 on p.ideaslug = p2.ideaslug 	0.492333465869629
5346057	9693	how to get newest/latest record from sql server database c#?	select    max(history.changedatetime) from  monitoringjob inner join history on monitoringjob.id=history.jobid group by monitoringjob.id 	0.000889886528334535
5346865	30414	sql query to retrieve all employees in descending order of total bonus plus commission	select   ... from     employee order by bonus+comm desc 	0
5347050	22551	sql to list all the tables that reference a particular column in a table	select r.table_name from information_schema.constraint_column_usage u inner join information_schema.referential_constraints fk     on u.constraint_catalog = fk.unique_constraint_catalog     and u.constraint_schema = fk.unique_constraint_schema     and u.constraint_name = fk.unique_constraint_name inner join information_schema.key_column_usage r     on r.constraint_catalog = fk.constraint_catalog     and r.constraint_schema = fk.constraint_schema     and r.constraint_name = fk.constraint_name where u.column_name = 'a'   and u.table_catalog = 'b'   and u.table_schema = 'c'   and u.table_name = 'd' 	0
5348179	27903	how to query on another query result	select emp_code, min(emp_name) as emp_name, sum(hours) from (   <your original query here> ) as e group by emp_code order by emp_name; 	0.0284028457063106
5348834	40644	mysql query from log table	select f1.* from filelog f1 where f1.action = 'upload' and f1.date_time =           select max(f2.date_time)           from filelog f2           where f2.file = f1.file 	0.053993184531558
5349181	25117	getting a date value in a postgres table column and check if it's bigger than todays date	select id,substring(name,'[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}'),name from clients where substring(name,'[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}') > '2011-03-18'; 	0
5351472	4475	mysql select from 3 or more tables	select  t1.*         coalesce(t2.phone,t3.phone) phone from    table1 t1 left join         table2 t2 on t1.reference = t2.id left join         table3 t3 on t1.reference = t3.id 	0.0175798121895851
5352022	27023	sqlserver: how to drop corrupted foreign key constraint	select fk.[name] from sys.foreign_keys fk inner join sys.objects o    on fk.[referenced_object_id] = o.[object_id] where lower(o.[name]) = lower('your table here') 	0.00119008381118148
5352106	2830	how to write mysql query to search database?	select * from ( select 1 as relevance, * from wallpapers  where tags like '%new york%' or name like '%new york%' union select 10 as relevance, * from wallpapers  where (tags like '%new%' or name like '%new%')  and (tags like '%york%' or name like '%york%') union select 100 as relevance, * from wallpapers  where tags like '%new%' or name like '%new%'  union select 100 as relevance, * from wallpapers  where tags like '%york%' or name like '%york%' ) order by relevance asc 	0.546721097438662
5352353	3714	find all tables not referenced in stored procedures	select  o.name , indexname=i.name , i.index_id    , reads=user_seeks + user_scans + user_lookups    , writes =  user_updates    , rows = (select sum(p.rows) from sys.partitions p where p.index_id = s.index_id and s.object_id = p.object_id) , case     when s.user_updates < 1 then 100     else 1.00 * (s.user_seeks + s.user_scans + s.user_lookups) / s.user_updates   end as reads_per_write , 'drop index ' + quotename(i.name)  + ' on ' + quotename(c.name) + '.' + quotename(object_name(s.object_id)) as 'drop statement' from sys.dm_db_index_usage_stats s   inner join sys.indexes i on i.index_id = s.index_id and s.object_id = i.object_id    inner join sys.objects o on s.object_id = o.object_id inner join sys.schemas c on o.schema_id = c.schema_id where objectproperty(s.object_id,'isusertable') = 1 and s.database_id = db_id()    order by reads 	0.00670213639281751
5352461	430	find a way to query a list of items that meet all of a criteria using sql	select i.firstname, i.lastname, count(1) from (     select u.id, uw.widgetid from [db].[dbo].[widgets] w inner join      userwidgets uw on w.id = uw.widgetid                      and uw.widgetid in ('29017318-fd89-4952-a3a2-8405bd5c5c44',                             'bdb7d25c-0794-4965-842d-e6d03a250418',                           'cb4553ac-a47b-4aa6-9231-5c59c8f97655')      inner join users u on uw.userid = u.id      left join userwidgets uw2 on uw2.userid = u.id                     and uw2.widgetid not in ('29017318-fd89-4952-a3a2-8405bd5c5c44',                             'bdb7d25c-0794-4965-842d-e6d03a250418',                           'cb4553ac-a47b-4aa6-9231-5c59c8f97655')      where uw2.widgetid is null      group by u.id, uw.widgetid      ) a  inner join [db2].[dbo].[identities] i on a.id = i.identityid  group by i.lastname, i.firstname  having count(1) = 3  order by i.lastname, i.firstname 	0
5355207	39578	sql - find all related tags?	select tag_id, count(*) as tagcount from relation where tag_id <> 1 group by tag_id order by count(*) desc 	0.000289975882840794
5355428	40412	how to concatenate strings and commas in sql server?	select vri.street_number_and_modifier      + case when vri.street_number_and_modifier <> '' then ', ' else '' end        + vri.street_direction     + case when vri.street_direction <> '' then ', ' else '' end        + vri.street_name     + case when vri.street_name <> '' then ', ' else '' end        + vri.street_direction     + case when vri.street_direction <> '' then ', ' else '' end        + vri.street_suffix     + case when vri.street_suffix <> '' then ', ' else '' end        + vri.street_post_direction     + case when vri.street_post_direction <> '' then ', ' else '' end        + vri.unit     + case when vri.unit<> '' then ', ' else '' end from view_report_information_tables vri 	0.00723301586727695
5356330	4402	complex 3 way sql join (where table 3 has to join table 2 before joining table 1)	select t.team_id, t.team_name, t.captains_id, sum(m.miles) as total_miles from teams t inner join riders r on r.team_id = t.team_id inner join miles m on m.rider_id = r.rider_id group by t.team_id, t.team_name, t.captains_id 	0.00505029078949478
5356396	33593	how can a specify header is in which table?	select column_name,table_name  from information_schema.columns where table_schema = 'your_db' and table_name in ('broker','man','coach') and column_name = 'name' 	0.0357562222886827
5356777	40049	how to use "in" for more than one column	select e.emp_id  from employee e where exists     (     select *     from employee_other eo     where e.emp_id = eo.emp_id         and e.emp_org = eo.emp_org     ) 	0.0132408369179878
5356938	2795	return 5 newest articles for each category in ms sql server	select  * from    (         select  *,                 row_number() over (partition by catid order by posted desc) as rn         from    articles         ) q where   rn <= 5 	0
5357497	31778	how to display weekdays from below two days (monday and friday)?	select        t1.date_from,         t1.date_to,        case when datename(dw,t1.date_to) in ('friday','monday') then datename(dw,t1.date_to) else null end     from table t1 	0
5358097	12867	how to take weekdays using sql query?	select datename(dw, getdate()) 	0.120556433596113
5358798	37875	mysql php help with return a dataset	select * from table where key = 'image' and value in (1,2) 	0.527646561101217
5360849	3053	how select that where =list	select namecompany from [participatefairlist]  where idfair in (select id from [tmpfair] where parent_fk=88) 	0.0237886356588941
5361499	4206	get position of a row in a table, when ordered by name asc	select count(*) from tbl where name <= 'john' order by name asc 	0
5362125	20514	how to get multiple max column value mysql	select t1.user_id,         sum(week1score) as week1score,         sum(week2score) as week2score  from   (select user_id          from   `table`          group  by user_id) as t1         join (select user_id,                      max(if(`week` = 1, score, 0)) as week1score,                      max(if(`week` = 2, score, 0)) as week2score               from   `table`               group  by user_id,                         `week`) t2           on t2.user_id = t1.user_id  group  by user_id  order  by ( sum(week1score) + sum(week2score) ) desc 	0.000255734440515348
5364283	15980	how to select on strange column name in sqlite terminal?	select "data_text:1" from questions; 	0.265738657965758
5364429	4546	group by ignoring an attribute	select t1.itemgroup, t1.description, t1.price from table t1,      (select itemgroup, max( price ) as price      from table      group by itemgroup) t2 where t1.itemgroup = t2.itemgroup and t1.price = t2.price 	0.0466955736603938
5367435	24125	mysql - how to select entries from one table based on whether or not i subscribe to them from another table?	select e.publisherid, e.entry from entries e join subscriptions s on s.friendid = e.publisherid where s.myid = 1234 	0
5367899	15385	mysql - select user only once when subscribed to multiple categories	select categorie_id       ,count(*)   from (select user_id               ,min(categorie_id) as categorie_id           from xs2_media_users_categories          group              by user_id        ) u   group      by categorie_id; 	0.000279185340599727
5369667	31961	limit user in sql plus to a single record in a table	select * from employee t where sys_context('userenv','session_user') = t.empname`enter code here 	0.000361276494804338
5370216	1580	mysql selects with joins with foreign keys when using a supplied id	select chat.message, chat.timesent from chat left join chat_private on chat.id=chat_private.message_id where chat.timesent>='$timestamp' and chat_private.target_id=$target_id 	0.105126444959301
5370685	13464	mysql query to match similar words/sentences	select id from papers  where match (title,booktitle,journal) against ('nfoil: integrating naïve bayes and foil' in natural language mode with query expansion); 	0.294895005750074
5374563	14429	detect (find) string in another string ( nvarchar (max) )	select t2.* from t1 cross join t2 where patindex('%' + t1.stringcol + '%', t2.stringcol) > 0 	0.00600194625842889
5379144	33369	how do i search titles in mysql?	select title from table where match (title) against ('national geography'); 	0.292348235803909
5380735	21572	select random item where item occurs more than three times in table mysql	select userid from breadscores group by userid having count(*) > 3 order by rand() limit 1 	0
5380929	12036	joining empty table to return all rows	select * from table1 t1 left join table2 t2 on t1.id = t2.fk 	0.000104270103501563
5381757	39519	mysql cross join, but without duplicated pair?	select r1.id, r2,id  from rows r1  cross join rows r2  where r1.id < r2.id 	0.332974107490644
5383272	27695	mysql spatial extensions: getting records that fall with in a certain area	select *, aswkt(location) as geomwkt from mytable where intersects(location,geomfromtext('point(1.9845 49.8543)')) 	0.000170143148260417
5383502	16326	what's the most efficient way to pull the data from mysql so that it is formatted as follows:	select patients.first_name, patients.last_name, group_concat(prescriptions.medication separator ", ") as meds from patients left join prescriptions on prescriptions.patient_id = patients.id group by patients.id; 	0.00133880352802266
5384516	12143	gathering multiple statistics about a table in a single query	select type,     sum(case when status = 'open' then 1 else 0 end) as [open],     sum(case when status = 'closed' then 1 else 0 end) as [closed] from table group by type 	0.0681998146769391
5384618	6418	sql amount consumed query?	select     purchases.id, purchases.productid, purchases.qty, purchases.date,      case when coalesce (previouspurchases.previousused, 0) + qty < consumedsummaryview.qtyused then qty     else case when consumedsummaryview.qtyused - coalesce (previouspurchases.previousused, 0) < 0 then 0      else consumedsummaryview.qtyused - coalesce (previouspurchases.previousused, 0) end end as used from         purchases inner join                   consumedsummaryview on purchases.productid = consumedsummaryview.productid left outer join                       (select     sum(purchases_2.qty) as previousused, purchases_1.id                         from          purchases as purchases_2 inner join                                                purchases as purchases_1 on purchases_2.id < purchases_1.id and purchases_2.productid = purchases_1.productid                         group by purchases_1.id) as previouspurchases on purchases.id = previouspurchases.id 	0.0978069862296185
5384649	25002	restrict competition entry to once per day	select count(*) from competition_entries where ce_c_id = '$c_id'      and ce_sub_id = '$user_id'      and cte_date = current_date() 	0
5385827	36517	how can i have different where condition using case statement?	select * from stagetable map where id = 1 and (   (@historymsbtype = 'utilization other' and map.columnid = 4)   or   (@historymsbtype = 'cost other' and map.columnid = 6)   or   (isnull(@historymsbtype,'') not in ('utilization other','cost other')    and map.columnname = @historymsbtype)   ) 	0.570562401116906
5387764	9832	subquery returns more than 1 row in mysql	select pkticketid,ticketreplydateadded,        timestampdiff(day, ticketreplydateadded,now()) as numberofdays  from   tickets as t         left join ticket_replies as tr        on t.fkticketreplyid=tr.pkticketreplyid  where  1  and    t.fkemployeeid = '4'  and    (select timestampdiff(day, ticketreplydateadded, now()) as numberofdays          from tickets as t left join ticket_replies as tr          on t.fkticketreplyid=tr.pkticketreplyid         limit 1) = 7  and     t.ticketstatus = 'replied'  order   by pkticketreplyid desc 	0.0837509958916336
5388739	18817	select value that is not "*username*"	select * from group where group_id not in (     select group_id     from group_hide     where user_id = 'testuser'     and hide = true) and active =1 order by `group`.`group_id` asc limit 0 , 500 	0.0637441943970388
5388789	35354	how to invoke the neweset one week recored in mysql?	select * from threads where dateline > date_sub(now(), interval 1 week) order by dateline desc; 	0.00108516717743544
5390731	28156	ordering by multiple columns in mysql	select t1.* from products as t1 inner join ( select area_id,min(price) as price from products where price > 0 group by area_id) as t2 on t1.area_id = t2.area_id and t1.price = t2.price alter table products add index i (area_id,price); 	0.0409240805896944
5390947	29409	order by the sum of the count of two fields	select   count(case when v.vote = 1 then 'up' else null end) as up,   count(case when v.vote = 0 then 'down' else null end) as down,   (count(case when v.vote = 1 then 'up' else null end)-count(case when v.vote = 0 then 'down' else null end)) as rating,   t.*   from tips t   left join votes v   on t.tip_id = v.tip_id   where t.challenge_id = 10   group by t.tip_id   order by rating desc 	7.93654659265653e-05
5392419	26831	query for selecting different recent records with different categoryid	select *   from categories   where (categoryid, date) in         (         select categoryid, max(date)           from categories           group by categoryid        ) 	0
5393440	9306	what is the proper way to get the last entry for each foreign key of a history table?	select   * from   thistory where   timestamp = (     select       max(timestamp)     from       thistory latest     where       fk_user = thistory.fk_user   ) 	0
5394920	26508	unable to get the right output from oracle sql	select field1, field2, field3,  from mytable where trunc(date)  = tp_date(‘03/22/2011’,’mm/dd/yyyy’) and field1 in     (select field1     from mytable     group by field1     having count(field1)  <  7); 	0.134236654190706
5395078	9623	mysql - getting distinct records	select ua.*  from user_actions ua join (select max(id) as max_id,user_id,action_type from user_action group by user_id,user_action) ua_max on ua.id=ua_max.max_id and ua.user_id=ua_max.user_id and ua.action_type=ua_max.action_type 	0.00832863435335803
5395412	22480	how can i remove duplicate records in access only if all fields match?	select name,location from table_name group by name,location 	0
5395871	31932	mysql detect capitalization?	select lastname from tbl where concat( upper( substring( lastname, 1, 1 ) ) ,               lower( substring( lastname from 2 ) ) ) != lastname collate latin1_german2_cs; 	0.484441880632751
5400349	19147	mysql: count children and get parent rows	select a.pg_title as parentname,              a.pg_id as parentid,              b.totalcout   from root_pages a inner join          (         select parent_id, count(1) as totalcout           from root_pages            where parent_id <> pg_id         group by parent_id          ) b       on a.pg_id = b.parent_id      and b.totalcout>0 	0
5401848	6985	how to obtain list of tables names from a mysql database in a c#?	select table_name from information_schema.tables where table_type = 'base table' 	0
5402195	28429	sql to display number of unread messages... including unread replies	select m.*      , count(*) as num_replies      , max(r.datetime) as max_datetime      , (m.viewed like '%,$user_id,%')           as message_viewed          , sum(r.viewed not like '%,$user_id,%')          as unread_replies     from directus_messages as m   left join directus_messages as r     on m.id = r.reply where m.active = '1'    and m.removed not like '%,$user_id,%'  group by m.id having m.reply = '0'  order by m.datetime desc        , max_datetime desc ; 	6.68407854255015e-05
5403179	1631	problem in getting the datetime variable from the database	select min(startdatetime) from agentlog  where activity='logon' and   user = 'username' group by datepart(day, startdatetime),     datepart(month, startdatetime),     datepart(year, startdatetime) 	0.0170681773783071
5405951	37890	select count from second table based on initial select	select t1.accountid, t1.referenceid, count(t2.accountid) from table1 t1 left join table2 t2 on t1.accountid = t2.accountid and                        t1.referenceid = t2.referenceid group by t1.accountid, t1.referenceid 	0
5406500	23652	mysql join with count(*)	select domains.*, count(s1.<column_name>) as total from subpages s1, domains left join subpages s2 on s2.domainid = domains.id where domains.id = 293 and s2.seitenart = 'startseite' and s1.statussub = '1' and s1.domainid = domains.id 	0.526962283404201
5407208	41290	how to return varchar string instead of null with rollup?	select  case when grouping_id(first_name) = 1 then 'total' else first_name end,         sum(a),         sum(b),         sum(c) from    data group by         first_name with rollup 	0.0302116867389008
5407322	31317	mysql- group and count by date	select count(*), trip_date , shop_id  from trips  group by trip_date , shop_id 	0.0557986790934508
5407637	12803	join table on itself	select  t2.cat_id from    mytable t1 join    mytable t2 on      t2.entry_id = t1.entry_id         and t2.cat_id <> t1.cat_id where   t1.cat_id = 234 	0.106588364853709
5409003	39692	need sql-regexp help: find lowercase char before uppercase char	select * from table where binary(your_field) regexp '^[a-z]{2,}[a-z]+' 	0.740335456115674
5409018	23669	sql query creating start and end dates	select tb1.date as startdate,dateadd(d,-1,tb2.date) as enddate from the_table tb1 join the_table tb2 on tb2.date>tb1.date left join the_table tb3 on tb1.date<tb3.date and tb3.date<tb2.date where tb3.date is null 	0.0438638153928536
5409547	39298	oracle - how to obtain information on index fields etc	select * from all_ind_columns where table_name = 'your_table' 	0.0265877159557661
5409582	9715	any way to join these two queries without subquery?	select group_concat(l2.friend_id) as friends from friends_friends l1   join friends_friends l2     on l2.user_id = l1.friend_id where l1.user_id = 503695576; 	0.633929573470071
5411834	27258	for xml subquery to append attributes to parent	select     uniqueid        as [@uniqueid],     x.id            as [@id],     x.name          as [@name],     x.latitude      as [@latitude],     x.longitude     as [@longitude],     (select         column1     from @vehicle1     where uniqueid = t1.uniqueid     for xml raw ('row'), type, root ('vehicle1')),     (select         column1     from @vehicle2     where uniqueid = t1.uniqueid     for xml raw ('row'), type, root ('vehicle2')) from (     select         uniqueid,         max(t1.id) as maxid     from         @event as t1     group by         t1.uniqueid ) as t1 cross apply     (         select             id,             name,             latitude,             longitude         from             @event          where             uniqueid = t1.uniqueid and             id = t1.maxid     ) as x order by     t1.uniqueid     for xml path('event'), type, root ('events'); 	0.0389808078975582
5412224	69	filter out with join	select distinct(b.friend_id) as possible_id from friends_friends a     join friends_friends b        on b.user_id = a.friend_id     left join friends_friends c       on c.user_id = a.user_id      and b.family_id = c.friend_id where a.user_id = 123456789 and c.friend_id is null 	0.494055913740279
5415438	15321	retrieve daily competition entries grouped by member	select count(ce_sub_id) from competition_entries  where ce_c_id = '$competition_id'  group by ce_sub_id 	0
5416139	2380	my sql sum the count values	select sum(campaign_pid != 0 +            sms_pid != 0 +            survey_pid != 0) as total, ... 	0.0417128633660931
5416146	28475	counting distinct field in table2 from distinct ids in table1 in sql (mysql)	select reference,count(distinct(concat(shop_id,'_',customer_id))) as count  from table1 join table2 using(shop_id,customer_id) group by reference; 	0
5416864	40229	find all categories that have some specific features	select * from `categories`  where category_id in (select category_id from categories_features where feature_id = 3)  and category_id in (select category_id from categories_features where feature_id = 10) 	0
5417526	21629	sqlite: get day	select strftime('%d', `date`) from sessiondate 	0.00146825721717632
5417784	30381	sql - invalid column name	select i.* from (   select o.outcode as lead_postcode, v.outcode as venue_postcode, 6 * o.lat as distance    from venue_postcodes v, uk_postcodes o    where o.outcode = 'cf3'  ) i group by i.outcode  having sum(i.distance)>100 order by i.distance 	0.39630876704739
5418248	27885	get max one result of each value in a column	select t.* from (     select col2, min(pk_id) pk_id     from tbl     group by col2 ) x, tbl t where t.col2=x.col2 and t.pk_id=x.pk_id 	0
5418682	6309	calculate previous sum value	select n.name,        s1.scoreid,         s1.nameid,         s1.scorevalue,        sum(s2.scorevalue) prevmonths from   names n        inner join scores s1 on n.nameid = s1.nameid        left  join scores s2           on  s1.nameid = s2.nameid           and s1.scoredate >= s2.scoredate  group by n.name,        s1.scoreid,         s1.nameid,         s1.scorevalue 	0.00044801242210457
5419199	41284	how to format money in postgresql	select to_char(0,'99999999999999990d99'); select to_char (1234567890999999.8,'99 999 999 999 999 990d99'); 	0.12134353363914
5421467	27129	how to find out sqlce column's length	select character_maximum_length from information_schema.columns where table_name = 'docentry' and column_name = 'filename' 	0.00160676409186982
5422485	32940	select from same column (possible different row) in one select statement using joins	select pro.name as product, un.name as unit, pvu.timesbaseunit as 'times base unit',    baseunit.name as 'base unit', pvu.cost from prodvsunit pvu   inner join units un on pvu.idunit = un.idunit   inner join products pro on pvu.idproduct = pro.idproduct   inner join units baseunit on pro.idbaseunit = baseunit.idunit 	5.19652657744662e-05
5422488	89	select first 10 distinct rows in mysql	select  distinct * from    people where   names = 'smith' order by         names limit 10 	7.52378508050319e-05
5423138	38886	cross-checking a list of users with users on a db - bad idea?	select * from users where name in ( <generated list of your 500 user name candidates>) 	0.02325797244853
5423751	15151	how do the sql "is" and "=" operators differ?	select * from foo where (@param is null and bar is null) or (bar = @param) 	0.68434280691183
5424874	8401	can't nail a mysql query where i require multiple records from a table	select  data.entry_id, data.date, data.body,   titles.entry_id, titles.title as biz_name, from data join titles on data.entry_id = titles.entry_id inner join categories cat1 on data.entry_id = cat1.entry_id and cat1.cat_id=17 inner join categories cat2 on data.entry_id = cat2.entry_id and cat2.cat_id=24 where ((cat1.cat_id) = (17)) and ((cat2.cat_id) = (24)) 	0.0835135578814712
5425441	11480	sql comparing two attributes as 1 combination	select distinct mine.name, ore.name from oreproduction inner join mine on mine.mineid = oreproduction.mine inner join ore on ore.oreid = oreproduction.ore left join contractdetail on oreproduction.mine = contractdetail.mine and oreproduction.ore = contractdetail.ore where contract.mine is null 	0.00441304883348109
5425997	11182	grouped results with sql server stored procedures	select vendor,        category,        sub_category,        product,        price,        vendor_name   from ( select          vendor as id,                 null as vendor,                 category,                 sub_category,                 product,                 price,                 vendor_name   from table union all select distinct vendor as id,                 vendor,                 null as category,                 null as sub_category,                 null as product,                 null as price,                 null as vendor_name   from table ) t order by id, category 	0.400952413435395
5426064	13589	mysql left join not returning null values for joined table	select * from a left join b  on a.sid = b.sid  and (ryear = 2011 or ryear is null) where (rcode = 1 or rcode = 2 or rcode = 3 or rcode = 5) 	0.327532725942994
5426104	37507	how do you input multiple select outputs into a from clause in mysql?	select five, six from (select 5 as five) as a, ( select 6 as six) as b 	0.0204839334770903
5430841	24884	sql: how compare cells from different tables?	select b2.* from band2 b2 where b2.kampas not in (select b1.kampas                         from band b1                          where b1.kampas is not null)   and b2.kampas is not null 	9.98709918298764e-05
5431819	27886	grouped query (pivot style?)	select  department, staff,         sum(if(job = 'holiday', 0, hours)) as work_hours,         sum(if(job = 'holiday', hours, 0)) as holiday_hours from    mytable group by         department, staff with rollup 	0.756896039879596
5435134	11446	return a list from different rows into a single field	select animal, group_concat(name) from your_table group by animal 	0
5435176	22359	php/mysql latest photos friends	select p.id from photos as p, friends as f where p.uid = f.uid2 and f.uid1 = ${userx.id} order by p.date desc limit 1; 	0.000412624435058712
5435240	15860	sql server - get count and column value from two tables for a report	select      clientid,     sum(case when t.clientid is not null then 1 else 0 end ) as total1      sum(case when w.clientid is not null then 1 else 0 end ) as total1      from tfeed t full outer join wfeed w      where w.dateadded = getdate() or t.dateadded = getdate() 	0
5435786	4705	aggregate function checking 'if contains'	select code, max(case when page = '999' then 1 else 0 end) as has999 from table group by code 	0.738731528787715
5437052	27541	mysql. select years range	select make, model,      case       when min(year) = max(year)          then min(year)       else concat(min(year), '-', max(year))     end as year,     othercolumns from tablename group by make, model, othercolumns 	0.00236125487221286
5438367	5494	how do i exclude or negate two queries?	select userid from users   where userid not in (select userid from user_groups where groupid = ?) 	0.0489049084512948
5439458	27813	retrieving data from multiples tables	select     t.*,     e.name as employee_name,     u.name as user_name,     s.name as service_name, s.description from tasks as t inner join employees as e on e.employee_id = t.employee_id inner join users as u on u.user_id = t.user_id inner join services as s on s.service_id = t.service_id 	0.000349959358829019
5441211	32120	sql server substring query	select tt.id,substring((     select ','+cn.documenttitle     from contractnewdocs cn     where tt.id = cn.contractid     order by cn.contractid for xml path('')),2,200) as csv from  tblcontract tt inner join contractnewdocs cn on tt.id = cn.contractid where tt.jobid = 8 group by tt.id 	0.773569248892092
5441587	35914	sql count distinct?	select tag_id, count(*) from mytable group by tag_id order by count(*) desc 	0.134589483711289
5442971	12531	how to get the data i want in mysql in one query or in php?	select user_id, group_concat(file_id) from yourtable group by user_id 	0.00270593414611097
5444532	4138	fetching data from the inner join query	select user.name as username, employee.name as employeename 	0.113221429164535
5445291	4299	how to join two tables together in sql?	select c.name, count(n.category) as count_in_name_table from categories c left join name n on n.category = c.name group by c.name 	0.0442424951608891
5446797	29601	if and else to turn decimal values into string	select      case when a > 20 then 'abc'           else 'def'      end  from a 	0.00270837423570995
5448368	37276	mysql count cannot show 0 values	select c.name, count(m.mailid) from employee     left join mailingsubscriptions as m on c.name = m.employeename group by c.name; 	0.0248894080753254
5449496	10933	date difference between two records in same table	select j1.job_id as job_id, (j2.created_at - j1.created_at) as time_run from job_logs j1 inner join job_logs j2 on (j1.job_id = j2.job_id) where j1.status = 'started' and j2.status = 'completed' 	0
5452233	15339	where statement after a union in sql?	select *   from (select * from tablea         union         select * from tableb        ) as u  where u.col1 = ... 	0.759972449829109
5453138	17744	two queries and two inner joins together	select * from (select * from listings inner join category on listings.category = category.categoryid where link = '3') as t1 inner join accounts on t1.account_id=accounts.account_id; 	0.279047553645854
5457471	23216	mysql in list only validates first id in list. maybe a blob issue	select * from mytable where find_in_set(25,category) 	0.00310046605076548
5460740	5570	how can i filter a mysql result by the amount of words in a column?	select * from table where length(field) - length(replace(field, ' ', '')) + 1 < 100 	0.000112016208886002
5461269	17138	mysql join on 3 tables	select t1.*, t3.* from  table1 t1  inner join table2 t2   on t1.idsp = t2.idsp inner join table3 t3   on t2.did = t3.did 	0.106590073206659
5462303	23756	sql - different sum levels in one select with where clause	select   id,   amountusedsincelastweek = sum(case when applydate > '4/21/2011' then amountused end)   amountusedtodate = sum(amountused) from transtable group by id 	0.066484130601487
5462668	5177	select with grouping in mysql	select  id_tax, sum(value * rate) from    pay p join    rate r on      r.id_currency = p.id_currency group by         id_tax 	0.255583292225858
5464633	22202	mysql: how to select values from one table and order by calculated values from a different table?	select c.id, c.target_item_id, c.comments,        sum(case when v.`like`=1 then 1 when v.`like`=0 then -1 end) popularity from comments c left join votes v on v.comment_id = c.id where c.target_item_id = 643 group by c.id, c.target_item_id, c.comments order by popularity desc 	0
5465505	17377	sliding window average for multiple time periods - sql server	select     dateadd(month, -n.number, getdate()) onemonthfromthisdate,     avg(datediff(dd, acquisitiontime, createdate)) averageinthismonth from users join master..spt_values n on n.type='p' and n.number between 1 and 24 where createdate >  dateadd(month, -n.number, getdate())   and createdate <= dateadd(month, 1-n.number, getdate())   and acquisitionmedium = 'cpc'   and acquisitionsource = 'google'   and acquisitiontime is not null group by n.number, dateadd(month, -n.number, getdate()) order by n.number 	0.0204158654403195
5466125	9494	oracle: query against value of user defined type	select count(1) from table_of_my_messages m      where m.user_data.relatedid = 'abcdefgh'; 	0.0188379316812582
5467475	18479	which method is better to display large result from database?	select * from students join marks on students.student_id = marks.student_id 	0.0178428523265266
5470404	39542	top record per each foreign key in mysql	select r.business_id, t.c as 'number of reviews',      r.title, r.description, t.max_useful_count  from reviews r join (select business_id, count(business_id) as c,          max(useful_count) as max_useful_count       from reviews       where r.business_id in (...)       group by business_id) as t   on r.business_id = t.business_id   and r.useful_count = t.max_useful_count 	0
5471089	6842	access query: find highest rank product in each category	select category, first(product) as bestproduct from (   select category, product, rank   from qryevalprod   order by category, rank desc ) as ordered group by category; 	0
5471339	1939	grouping records from mysql	select s.name, s.secondname, concat(dayofmonth(f.date),', ',year(f.date)),  sum  (f.hoursworked), sum(f.fee) from staff s join fee f on f.staffid = s.id group by s.id, year(f.date), month(f.date) 	0.00385758169811416
5471399	15164	mysql force order of results found to match order of in clause	select * from (     select  session_id, group_concat(concat('|',progress,'/') order by datetime) list     from    formation_page_hits     where   progress in (2, 4, 7)             and datetime >= '2011-03-23'             and datetime < '2011-03-24'     group by session_id     having  count(distinct progress) = 3 ) x where list like '%|2/%|4/%|7/%' 	0.106681568513896
5471623	15540	how do i pivot this dataset into columns for each question	select [eligible project costs],[date],[cash costs £],[in kind costs £],[total costs] from (     select  qr.*,       grp = row_number() over (partition by qr.questionid order by qr.id),       value,       question     from questionrecord qr     inner join      questionrecord p     on p.id = qr.parentquestionrecordid     join questions q on q.id = qr.questionid     )pvt pivot (     min(value)     for question in     ([eligible project costs],[date],[cash costs £],[in kind costs £],[total costs]) )pivottable 	0.00914355490818544
5471732	2013	custom order by + group by	select * from t3   where t3.lang in ('dk','uk')   and t3.id not in   (select t1.id   from t1,t2   where t1.header_name = t2.header_name   and t2.lang = 'dk'   and t1.lang = 'uk'   ) 	0.5977585935961
5472860	10115	mysql search based search	select o.id  from   orders o, customers c  where  o.customer_id = c.id and         o.price > 60         and        c.name = 'anna'; 	0.041085305858861
5472949	26292	finding rows in the same table which have the same many-to-many relationships as given other row	select m.title  from tbl_movie_master m join tbl_movie_genre allgenres    on m.movie_id= allgenres.movie_id join    (select genre_id from tbl_movie_genre where movie_id=45) somegenres   on somegenres.genre_id=allgenres.genre_id; 	0
5475550	6866	postgres searching in a column splitted by regexp_split_to_table	select *  from (    select        cs_id,       regexp_split_to_table(cs_values, '* , *') as splitted_value ) t where    splitted_value = 'a' 	0.211512805602203
5475744	31375	select from one mysql table where ids match results from select of another mysql table	select m.*     from s_matters m         inner join s_links l             on m.id = l.mid     where l.uid = '0007' 	0
5476234	10600	how to retreive max date from a left outer join?	select client_headquarter.id, max(clients.tscreated) from client_headquarter  left outer join clients on clients.headquarterid = client_headquarter.id group by client_headquarter.id order by max(clients.tscreated) asc 	0.0927366261359454
5476297	14863	tally/count mysql results per day	select  date(signup_date) as `date`         , count(*) as signups  from    `signups`  group by          date(signup_date) 	0.000720121841752162
5476299	4293	select 1 day / week / month from sql server timedate	select [time], [temp]  from [test2]  where      month([time]) = month(getdate()) and      datediff(day, [time], getdate() <= 7 and     day([time])  = day(getdate()) 	0
5476920	19047	mysql user signup counts between groups	select date, sum(case when subscriber = 1 and s2member_level2 = 0 then 1 else 0 end) subscriber,            sum(case when s2member_level2 = 1 then 1 else 0 end) s2member_level2 from (   select  date(user_registered) date,              id,             sum(case when b.meta_key = "wp_capabilities" then 1 else 0 end) as subscriber,             sum(case when b.meta_key = "wp_s2member_subscr_id" then 1 else 0 end) as s2member_level2     from wp_users a left join wp_usermeta b on a.id = b.user_id                 group by date(user_registered), id ) c group by date 	0.00389410546430662
5477561	3814	mysql query search using multiple rows	select *  from  item i inner join item_data country on i.itemid = country.itemid   and fieldid = 2 inner join item_data address on i.itemid = country.itemid   and fieldid = 1 where     country.fieldvalue= 'united kingdom'     and address.fieldvalue= 'whatever' 	0.122473308679656
5479341	6752	mysql - check db record for 5 days after member's birthday	select *,  current_date() - interval 5 day as then from members where month(dob) = month(then) and dayofmonth(dob) = dayofmonth(then) 	0
5480423	40334	how to use the mysql between operator?	select bdate from table where bdate between '2001-01-01' and '2010-01-01' 	0.511957821999308
5481002	13175	sql server select rows between two values	select top 40 * from (select top 60 * from table order by xx asc) t order by xx desc 	0.000527982503802621
5482036	38814	getting the period of dates for each employee	select a.id, b.begindate, b.enddate from employeemaster as a left join employeedates as b  on a.id = b.id 	0
5483950	20589	my where condition isn't returning every row in a table, how to make it return the rows?	select category.name, count(name.category) as availability from     category left join name on name.category = category.name and     time > now()     group by category.name 	0.000554332882204353
5484669	28043	sql select latest value	select top(1) [motor] ,[time]  from [logger].[dbo].[motor]  where day([time]) = day(getdate())  order by [time] desc 	0.00160288467693403
5487543	21452	query that retrieves combinations from two sequential rows	select a.type_id, b.type_id     from time_period a     left join time_period b     on a.billing_id = b.billing_id     and a.sequence_number = b.sequence_number - 1     where a.billing_id = 4356 	6.6958455694151e-05
5488060	27808	get distinct value with last row value of other column	select id, max(name) name from yourtable group by id 	0
5489895	3942	combine two mysql count queries	select      date_format(change_date, '%y-%m') as date,     count(distinct change_id) as change_count,     name from      change_table, (select        name as name,          count(distinct change_id) as changes     from change_table     where date(change_date) > date(now() - interval 1 month)     group by name     order by changes desc ) subq where change_date > curdate() - interval 10 month and change_table.name = subq.name group by date, name 	0.0182574629840729
5490479	29061	sql query that finds the position of an empty column in an array of 4 columns	select case     when a is null then 1     when b is null then 2     when c is null then 3     when d is null then 4     else 0 end as firstnull from sometable 	0
5490821	5372	finding album title of longest album	select a.title, sum(t.length)         from album a, track t         where a.id = t.album_id group by a.title         order by sum(t.length) desc limit 1; 	0.00128196631750642
5491846	8339	how do i join two table with group by order by	select *  from (     select count(*) as rows, ad_userid     from ads     group by ad_userid     order by rows desc     limit 5  ) as t1 left join users as t2 on t2.user_id = t1.ad_userid 	0.0747656339518519
5492589	33988	sql select ordering columns with null values	select     columna,     columnb from yourtable order by     case when columnb is null then 1 else 0 end asc,    columnb 	0.0189788413864276
5493685	23787	oracle: select * from (select table_name from ... )?	select        table_name,        to_number(          extractvalue(            xmltype(              dbms_xmlgen.getxml('select count(*) c ' ||                                 ' from '||owner||'.'||table_name))            ,'/rowset/row/c')) count    from all_tables   where table_name like 'my_table_%' 	0.0211208666753255
5494687	32593	is there an sql function which generates a given range of sequential numbers?	select element from series where element not in (select pk_id                       from tbl) 	0.00225562608103603
5494970	39190	select grouped by column only, not the aggregate	select idclient, business_name from client where idclient in (   select idclient    from payment    group by idclient   having sum(amount) > 100 ) 	0.00582863433233845
5495913	13621	can i use aggregation function (last) in mysql?	select f.user_id, f.value from (    select  max(value) as maxval    from my_table group by user_id ) as x inner join my_table as f on f.value = x.maxval 	0.288752294426132
5496272	37358	how can we get trigger names for particular table?	select trigger_name from information_schema.triggers where event_object_table = 'my_table'; 	0.000982351145907999
5497394	16219	select sum of values: grouped by sign	select    year(date),    sum(case when value > 0 then value else 0 end) as positives_sum,   sum(case when value < 0 then value else 0 end) as negatives_sum from    table  group by   year(date) 	0.0016402106584724
5498655	24902	how can i replace all zeroes returned with blank space	select replace(column_name,'0',' ') "column name" from your_table_name; 	0.0441294749279602
5499436	16845	how to return all values of a column as null except one column value in sql script?	select column, cast(null as int) as intcolumnexample, cast(null as nvarchar) as stringcolumnexample from tbl 	0
5500187	24894	recordset for todays date using current_timestamp	select columns from fields where table.record_date > curdate(); 	0.0035751195021731
5501961	23549	query by slug or query by id?	select tid from `forum_threads` where subject = "new bmw x5"; showing rows 0 - 0 (1 total, query took 0.0230 sec)  select tid from `forum_threads` where tid = 19906; showing rows 0 - 0 (1 total, query took 0.0001 sec) 	0.287480634217354
5502079	5699	does join change the sorting of original table?	select * from x 	0.070403609973681
5502139	33242	sort sql query by values in another table	select distinct a.artist from            artists a      inner join paintings p      on         a.artistid = p.artistid order by        p.date_created desc 	0.00210882522569388
5503692	35453	sql select distinct top 2	select distinct top 2 partid, idnumber, lenght from (   select partid, idnumber, lenght, row_number() over(partition by idnumber order by lenght) orden     from [ayuda] ) a where a.orden = 1 order by lenght 	0.0086674059228577
5504166	885	mysql query - 2 foreign keys	select   flight.idflight,   flight.idairline,   flight.from_airport,   flight.to_airport,   flight.number,   airport_from.name as origin   airport_to.name as destination from flight   inner join airports airport_from on flight.from_airport = airport_from.idairports   inner join airports airport_to on flight.to_airport = airport_to.idairports 	0.00512663224033663
5504489	29007	how does one perform math on multiple select results?	select bccount, totalcount, bccount/totalcount as percentage     from (select sum(case when flagb=true and flagc=true then 1 else 0 end) as bccount,                  count(*) as totalcount               from playertrial               where playerid = _) t 	0.340607280920885
5505244	7859	selecting matching/mutual records in mysql	select distinct a.user_id   from <your_table> a inner join <your_table> b     on a.matches = b.users_id    and b.matches = a.users_id  where a.matches = 54 	0.00691820536576245
5505452	30673	sql query to find trends	select count(time), blote.name, number_of_votes, score  from `vote` inner join `blote` on vote.name=blote.name where unix_timestamp(now()) - `time` < 60*60*24*7 group by vote.name order by count(time) desc limit 25 	0.189450815342189
5507060	25015	distinct results in ora-01791: not a selected expression	select full_name from (  select distinct a.fname||' '||a.lname as full_name, a.lname  from author a, books b, bookauthor ba, customers c, orders  where c.firstname='becca'    and c.lastname='nelson'    and a.authorid=ba.authorid    and b.isbn=ba.isbn  ) order by a.lname 	0.714150915801249
5507455	36935	constraining returned value decimal places in mysql	select round( avg(`readingvalue`), 4 ) as `readingvalue` from table 	0.00536613678328516
5509787	32850	how to declare variables in select statement	select name , dept from name_table nt, dept_table dt    where nt.name = dt.name 	0.573900406521863
5509958	15787	mysql query on timestamp ignore seconds	select * from locations  where timestamp between "2011-03-25 07:20:00" and "2011-03-25 07:20:59" 	0.0183917836811982
5510989	13291	sql select, match one column but not another	select a.* from dbo.a inner join dbo.b on a.b_guid = b.guid where     a.value <> b.value 	0.00117086643705699
5511097	16329	query for matching comma seperated values from two tables	select s.studentid, jp.mandskills from jobposts jp cross apply split(jp.mandskills, ',') jps inner join (     select s.studentid, s.mandskills, ss.items     from students s     cross apply split(s.mandskills, ',') ss) s on s.items = jps.items where jp.jobpostid=36 group by s.studentid, jp.mandskills having len(jp.mandskills)-len(replace(jp.mandskills,',',''))+1 = count(distinct s.items) 	0
5511878	32018	mysql join query	select c.id,c.email,c.phone,concat(c.year,c.id) as customer_id,p.name from table_customer c join table_product p on p.id=c.product_id 	0.724110026477687
5512699	29458	getting data from mssql table based on startdate and enddate	select * from contest where dtbegin <= getdate() and getdate() <= dtend 	0
5514560	742	items in multiple categories show multiple times	select  equip.* from    equip e where   equipid in         (         select  equipid         from    equip_equipcat ec         join    equipcat c         on      c.equipcatid = ee.equipcatid         where   equipcat like '%rake%'                  or                 equipcatkeywords like '%rake%'         )         and         (         equipdesc like '%rake%'         or         keywords like '%rake%'         )         and hideyn  = 0 order by         equipdesc 	8.18510720889296e-05
5514605	15502	joining several tables at once:	select reply.id, reply.content, author.username from thread inner join thread_reply on thread.id = thread_reply.thread_id inner join reply on thread_reply.reply_id = reply.id inner join author_reply on thread.id = author_reply.thread_id inner join author on author_reply.author_id = author.id where thread.id = '40' 	0.000911728462852706
5515508	19013	obtain all the players born in a particular month in sqlite	select p.name, p.birth_date     from player p         where p.birth_date > '1986-04-30'             and p.birth_date < '1986-06-01'; 	0
5516110	29277	get top count in a table?	select  userid, count(distinct hwid) as cnt from    logs group by         userid order by         cnt desc limit 10 	0.00097535401636356
5517084	16649	find missing row using sql	select a.receiptnumber       from transactions  a  where a.transactiontypekey = 50      and  not exists                 (                     select 1                        from transactions b                      where b.receiptnumber = a.receiptnumber                         and b.transactiontypekey = 1                 ) 	0.016753117001493
5517175	10790	sql server - database with stored procedures using all of memory on server	select * from sys.sysprocesses where open_tran > 0 	0.148553796723775
5517180	30298	retrieve data from 2 tables using conditions	select e.id,            e.name,           case              when he.id_center is not null then 1              else 0           end as has      from t_equipment e left join t_has_equipment he on he.id_equip = e.id                             and he.id_center = 3     where e.approved = 1  order by e.id 	0.000176053542489776
5517304	1961	querying a xml document in sql	select     feed.product.value('@id[1]', 'int') as productid,     step3.data.value('externalid[1]', 'varchar(50)') as externalid,     step2.data.value('averagerating[1]', 'decimal(10,1)') as averating,     step3.data.value('ratingrange[1]', 'int') as ratingrange from     @xmldata.nodes('/feed/product') feed ( product ) cross apply     feed.product.nodes('nativereviewstatistics/averageratingvalues/averageratingvalue') step2(data) cross apply         step2.data.nodes('ratingdimension')  step3(data) 	0.129532596424345
5518195	12542	mysql: return only last message in flat/conversation message table	select max(message_id) from messages group by greatest(to_id, from_id), least(to_id, from_id); 	0.000211228122667287
5518612	14410	sql: nested select with multiple values in a single field	select w1.warranty_id as "no.",        w1.created as "register date"         w1.full_name as "name",         w1.purchase_date as "purchased",         (            select p1.product_name            from warrdbo.products p1 with(nolock)            where p1.product_id = i1.product_id        ) as "product purchased",        stuff(          (            select               ', ' + a.name            from [table-valued-function](i1.accessories) acc_list               inner join accessories a on acc_list.id = a.id            for xml path('')          ), 1, 1, ''        ) as [accessories] from warrdbo.warranty w1   left outer join warrdbo.warranty_info i1     on i1.warranty_id = w1.warranty_id order by w1.warranty_id asc 	0.0128823648882261
5520030	17621	sql - return an entire recordset x times (where x is the number of rows in another table)	select * from tablea cross join tableb 	0
5520666	5021	c# sqldatareader only returns values > 0	select        a, coalesce(sum(b),0) as total from          table group by      a 	0.125428064151762
5520744	12788	taking n random elements from a table with a constraint	select * from <table> where <constrain> order by rand() limit 0,<n> 	0
5522433	12558	convert sql server query to mysql	select * from (     select tbl.*, @counter := @counter +1 counter     from (select @counter:=0) initvar, tbl     order by ordcolumn ) x where counter <= (50/100 * @counter); order by ordcolumn 	0.60195425179603
5522607	24905	how can i do a count distinct in sqlite?	select type, count(type) from table group by type; 	0.0821898612597674
5525970	15273	mysql: show columns but exclude everything except the field names	select column_name from information_schema.columns where table_name = 'your_table' 	0
5529204	1780	how to retrieve views creation time?	select view_definition from information_schema.views where table_schema = 'test' and table_name = 'v'; 	0.00319096438499833
5529217	19930	i need to select all rows from user table where row does not have value in join table	select `user`.* from `users` as `user` where `user`.id not in (    select `user2`.id    from `users` as `user2`, `groupsusers` as `groupsuser`    where         ( `groupuser`.`user_id` = `user2`.`id` )        and         ( `groupuser`.`group_id` = 102 ) ) 	0
5530748	20923	mysql group concat	select group_concat(`cnt` order by `date`)  from (     select t.`date`, count(*) as `cnt`     from `table1` t     group by t.`date` ) d 	0.502594740722672
5532186	18704	mysql: finding repeated names in my user table	select u.* from cpnc_user u join (     select firstname, lastname     from cpnc_user     group by firstname, lastname     having count(*) > 1 ) x on x.firstname = u.firstname and x.lastname = u.lastname order by u.firstname, u.lastname 	0.00194754704383175
5532224	515	stock and cart mixed query	select s.type, count(*) - (   select count(*)   from cart c   where c.type=s.type   # and c.userid = x   ) as counter from stock s group by s.type having counter > 0 	0.621488541351674
5532597	30125	top n query - sql server 2008	select top 6 empno, ename, job, mgr, hiredate, sal from emp order by nullif(sal, 0) desc; 	0.114180946991504
5534527	5521	mysql count distinct join on two columns	select fruit_name, count(*)  from (    select fruit0 as fruit_name    from table1    union all    select fruit1 as fruit_name    from table1 )aaa group by fruit_name 	0.00300601498362769
5535119	9855	android sqlite numeric filter	select *,lower(engword) as letter from tantable where letter >= 'a' and letter < '{'; 	0.525179318112358
5535311	39448	query to select maximum of all minimum	select id, val from table where val < 23 order by val desc limit 1 	7.56825335167615e-05
5535990	40371	oracle get foreign keys	select a.table_name, a.column_name, uc.table_name, uc.column_name                  from all_cons_columns a                 join all_constraints c on a.owner = c.owner                     and a.constraint_name = c.constraint_name                 join all_constraints c_pk on c.r_owner = c_pk.owner                        and c.r_constraint_name = c_pk.constraint_name                 join user_cons_columns uc on uc.constraint_name = c.r_constraint_name                 where  c.r_owner = 'myschema' 	0.0019969008186935
5536727	11681	how to generate sequence id without procedure?	select row_number() over (order by sender) as id, 'blabla' as sender from a 	0.0107611356570511
5537151	21694	sql - replace nulls with 0 in custom table	select  so.name,          sc.name as varname ,         st.name as typename ,         sc.max_length ,         sc.[precision] ,         sc.scale ,         sc.collation_name from    sys.columns sc         join sys.types st on sc.system_type_id = st.system_type_id                              and sc.user_type_id = st.user_type_id         join sys.objects so on so.object_id = sc.object_id 	0.752970334719077
5538471	25870	minimum values from the table	select  top 1 name, val as min from (     select  name, val1 as val     from    table     union     select  name, val2 as val     from    table     union     select  name, val3 as val     from    table ) as sub_query order by val asc 	0.000138977704175875
5539517	34316	sql server: calculating date ranges	select  'anything' as label         ,dateadd(month, datediff(month, 0, getdate()), 0) as firstdaythismonth         ,dateadd(day, datediff(day, 0, getdate()), 0) as today         ,dateadd(year, -1, dateadd(month, datediff(month, 0, getdate()), 0)) as firstdaythismonth_lastyear         ,dateadd(year, -1, dateadd(day, datediff(day, 0, getdate()), 0)) as today_lastyear 	0.0108790515112877
5539645	37854	select rows between an specified row to some row with particular condition	select version, compatible     from yourtable     where version >= '0.1.3'         and version < (select version                            from yourtable                            where version > '0.1.3'                                and compatible = 'false'                            order by version                            limit 1)     order by version 	0
5540416	31415	how to ignore a condition in where clause	select field1 from table1 where field1 >= 4006    and (field1 < (     select field1      from table     where field1 > 4006           and field2 = false     order by field1      limit 1     )     or     not exists (     select field1      from table     where field1 > 4006           and field2 = false     order by field1      ) ) 	0.615160369659618
5541088	25686	using subquery to pull random value reveals same value every time	select column1,     (select top 1 column1 as c2 from table2 where table1.column1 is not null order by newid()) from table1 	0
5541434	5025	sql get date month from query	select     convert(varchar(2), month(dbo.tblinvoices.invoicedate))     + '/' + convert(varchar(4), year(dbo.tblinvoices.invoicedate)) as date from     dbo.tblinvoices select     convert(varchar(6), dbo.tblinvoices.invoicedate, 112) as invoiceyearmonth from     dbo.tblinvoices 	0.000170660901854761
5544523	12358	alter table in stored procedure	select 'a' as cola     ,'b' as colb     ,cast(null as char(5)) as colc     ,cast(null as char(5)) as cold     ,cast(null as char(5)) as cole into #tmp update #tmp set colc = 'c',     cold = 'd',     cole = 'e' from #tmp select * from #tmp 	0.308491063163146
5545908	29013	combining 1 column of mysql table with every other column (cols a,b,c,d becomes a-b, a-c, a-d)	select time,   max(case when host='hosta' then var1 end) `hosta-var1`,   max(case when host='hosta' then var2 end) `hosta-var2`,   max(case when host='hosta' then var3 end) `hosta-var3`,   max(case when host='hostb' then var1 end) `hostb-var1`,   max(case when host='hostb' then var2 end) `hostb-var2`,   max(case when host='hostb' then var3 end) `hostb-var3`,   ..... from tbl group by time 	0.000240734531027681
5547098	29325	need help to sum data in mysql	select  line,model,lot_no, lot_quantity, sum(merchandise) from (                 select a.line, a.model,                        a.lot_no,b.lot_quantity,                        if(right(a.range_sampling,4)='0000',10000,                        right(a.range_sampling,4))-mid(range_sampling,5,4)+1                         as merchandise                 from inspection_report a                 left join prod_sch b                 on a.line= b.line_name and a.model = b.model_code                  and a.lot_no= concat(lpad(cast(b.lot_no_ as char),3,'0'),'a')           )           group by line,model,lot_no, lot_quantity 	0.788683843519098
5548388	19300	mysql: count certain values	select     reporting.station, count(reporting.station) from     reporting left join     channel on     md5(igmpurl)=reporting.station where     reporting.station!="n/a" group by reporting.station order by     name; 	0.00120479475927795
5548446	6664	sql server: number of disk blocks used by index or table	select      t.name as tablename,     p.rows as rowcounts,     sum(a.total_pages) as totalspace,      sum(a.used_pages) as usedspace from      sys.tables t inner join           sys.indexes i on t.object_id = i.object_id inner join      sys.partitions p on i.object_id = p.object_id and i.index_id = p.index_id inner join      sys.allocation_units a on p.partition_id = a.container_id where      t.name = 'yourtablenamehere' group by      t.name, p.rows order by      t.name 	0.286339500012945
5551272	27919	to remove a character from a string in mysql	select employee_id,emp_email,substring_index(user_name, '\\', -1)  from employee_master 	0.00472166524924301
5551451	31854	mysql query pulls data from another row than specified	select t1.* from table t1    join (select companyid, min(listnumber) min_listnumber from table     where addedwhen >= '2011-04-05 00:00:00' and searchid='26'     group by companyid) t2   on t1.companyid = t2.companyid and t1.listnumber = t2.min_listnumber where t1.addedwhen >= '2011-04-05 00:00:00' and t1.searchid='26'; 	0.000200790343706006
5552338	34784	how to check if i can remove index from db in sql server	select 'drop index ' + name + ' on ' + object_name(object_id) from sys.indexes where is_primary_key = 0 and is_unique_constraint = 0 and objectproperty(object_id, 'ismsshipped') = 0      and name is not null 	0.0227352863187941
5553430	38378	sql optimization: four statements into one	select     sum(case when foo_timstamp < date_sub(now(), interval 1 week) then 1 else 0 end) as oneweek,     sum(case when foo_timstamp < date_sub(now(), interval 2 week) then 1 else 0 end) as twoweek,     sum(case when foo_timstamp < date_sub(now(), interval 3 week) then 1 else 0 end) as threeweek,     sum(case when foo_timstamp < date_sub(now(), interval 4 week) then 1 else 0 end) as fourweek from foo where      foo_timstamp < date_sub(now(), interval 1 week) 	0.358656154118615
5553577	38393	count first occurence in a table not duplicates	select student,      count(crit1) > 0 as crit1,      count(crit2) > 0 as crit2  from submission group by student order by student ; 	0.00144899637060802
5554075	2658	mysql: get last distinct set of records	select *   from [tablename]   where id in (select max(id) from [tablename] group by code) 	0
5554346	33450	sql query multiple fields from a single form input	select city, state, min(zip) as min_zip, max(zip) as max_zip from zips where city = $foo or concat_ws(', ',city, state) = $foo or zip = $foo group by city, state order by state; 	0.00255228835211756
5554677	39950	better way to demand, in sql, that a column contains every specified value	select p.name     from person p         inner join homes h             on p.id = h.pid                 and h.type in ('spaceport', 'cottage')     group by p.name     having count(distinct h.type) = 2 	0.00104783184268798
5555321	3265	oracle date difference with case	select    case        when sysdate-tablea.start_date < 120 then 1       else 0   end myflag from tablea, tableb  where tablea.id(+) = 9999 and tableb.project_id(+) = tablea.project_id 	0.328629854600615
5555441	31451	postgresql, php - how to design a database search?	select uri from ads where fts @@ plainto_tsquery('cereal'); 	0.280493547712879
5556138	28754	getting the maxium count of comments in terms of users using mysql?	select users.user_id, count(*) as nb_comments from posts     inner join tag_posts on tag_posts.post_id = posts.id     inner join comment on comment.post_id = posts.id     inner join users on users.user_id = comment.user_id where tag_posts.tag_id = 39 group by users.user_id order by count(*) desc limit 5 	0.000242661286355488
5556161	20749	how to convert "" to null in postgresql	select *   from single_occurrences  where case when age="" then null else age::int4 end > 29 	0.168408191683828
5556992	23949	can i use join to get two usernames for say, createdbyuserid, and assignedtouserid in a single mysql query	select    createdbyuser.username as createdbyusername,    assignedtouser.username as assignedtousername from     nxt_act_dev_hist       join nxt_user as createdbyuser           on nxt_act_dev_hist.createdbyuserid = createdbyuser.userid       join nxt_user as assignedtouser          on nxt_act_dev_hist.createdbyuserid = assignedtouser.userid 	0.01387194639754
5560130	5811	having a problem pulling a max() value in mysql	select thread_id, p2.post_id as post_id, subject, user_id, username, dateline  from posts  join (      select max(post_id) as post_id       from posts       group by thread_id      order by  dateline desc       limit 10 ) as p2 on p2.post_id = posts.post_id order by  dateline desc 	0.0575580942262648
5561051	17111	php 5 connecting to oracle 9.2	select userid, userhost, terminal, returncode, ntimestamp# from sys.aud$ order by ntimestamp# desc; 	0.262097607322816
5561394	16531	how to identify the column name of a data table	select    ft.id firsttable_id,   st.id secondtable_id from firsttable ft, secondtable st where ft.id = st.fs_id 	7.8447879530849e-05
5563141	20470	convert text to date format	select cast(      substring('thursday, 1 january 2009',         charindex(',', 'thursday, 1 january 2009')+1, len('thursday, 1 january 2009'))       as datetime) 	0.0395474328747577
5565360	8221	mysql get nearest records to specific date grouped by type	select type, amount from table as t where dat = (     select max(dat)     from table     where type=t.type         and dat <= '2011-03-01' ) 	0
5565769	5632	mysql group by x where y = a and b and c	select p.id, count(p.id) from products p   left join discounts d on p.id = d.product_id where   (d.quantity = 1 and d.amount = 5)   or (d.quantity = 2 and d.amount = 10)   or (d.quantity = 3 and d.amount = 20) group by p.id having count(p.id) = 3 	0.00753016319390419
5566422	19373	select all rows from table 1 and mark rows that exist in table 2	select t1.*, if(count(`t2`.`customer_id`) > 0, 'yes', null) as customer_link from `suppliers` as `t1` left join `accredited_suppliers` as `t2` on `t2`.`supplier_id` = `t1`.`id` 	0
5569816	7521	view of multiple tables. need to remove "doubles" defined by 1 table	select * from instellingen as i cross apply (        select top (1) * from instellinglogin as il     where i.inst_loc_ref = il.inst_loc_ref      and i.inst_locnr=il.inst_loc_nr      and i.inst_ref=il.inst_instellingikon_ref      and i.inst_type=il.inst_instellingikontype     order by il.datum_tot ) la 	0.00702278809595185
5570269	3398	mysql query: select the pages of the first generation only?	select *   from root_pages   where parent_id in (      select pg_id       from root_pages       where parent_id = pg_id  ) and  parent_id != pg_id 	0.000453598500325826
5571632	33174	circular reference probelm in joining tables	select      convert(varchar,dateadd(mi,tz.offset,cal.caldate),101) as caldate,     s.[off],     s.aban,     s.ans,     case when s.[off]  - s.abn_in = 0 then 0 else 1 end as sla,     g.slgo from      calend cal      cross join zone tz      left join summ s on cal.caldate = dateadd(mi,tz.offset,s.arrdate) and tz.id = s.arrdate     inner join gol g on g.id = cal.id 	0.505644175931162
5573424	37008	sql left join doubling value of summed columns	select a.tranname,a.trandate,a.trancode from ( select tranname,trandate,trancode, sum(tranqty) as t1qty table1  group by tranname,trandate,trancode) a left join ( select tranname,trandate,trancode, sum(tranqty) as t1qty table2  group by tranname,trandate,trancode) b on (a.tranname = b.tranname and a.trandate = b.trandate and      a.trancode = b.trancode) where a.t1qty != b.t1qty 	0.00929704129098495
5574248	38116	querying random 10 percent for each record in sql server 2008	select clients_id, loans.loan_no from clients as c     cross apply (                 select top 10 percent b.loan_no                 from borrower as b                 where b.clients_id = c.clients_id                     and b.funded >= '20110401'                     and b.dba in( 'abc company' )                 order by newid()                 ) as loans 	0
5574535	1871	sql - return top 3 records per field	select t1.sub_ticker, t1.value1, t2.sub_ticker, t2.value2   from (select case when tickera = 'aaww' then tickera else tickerb end ticker,         case when tickera = 'aaww' then tickerb else tickera end sub_ticker,         value1,         @rownum:=@rownum+1 ‘rank’   from data_table d, (select @rownum:=0) r  where tickera = 'aaww' or tickerb = 'aaww'  order by value1 desc  limit 3) t1 join (select case when tickera = 'aaww' then tickera else tickerb end ticker,         case when tickera = 'aaww' then tickerb else tickera end sub_ticker,         value2,         @rownum:=@rownum+1 ‘rank’   from data_table d, (select @rownum:=0) r  where tickera = 'aaww' or tickerb = 'aaww'  order by value2 desc  limit 3) t2 on t1.rank = t2.rank 	0
5574775	34332	trying to get top 20 mysql	select sum(award) as totalawards, pi, org  from iis  group by pi, org order by sum(award) desc limit 20; 	0.00162948777376888
5575019	19674	lookup from multiple tables	select so.[group name], o.[organisation name] from organisations as o left join [sub-organisations] as so     so.[organisation name] = o.[organisation name] 	0.0128277903165344
5575682	17375	how to merge data from multiple tables in sql	select enrollment.*, student.*, course.* from enrollment    inner join student on enrollment.studentid = student.studentid    inner join course on enrollment.courseid = course.courseid 	0.000686052032783933
5576759	18964	how to write sql query	select t3.enumid as enumid, t1.enumname as country, t2.enumname as state, t3.enumname as city from table t1 inner join table t2 on (t1.enumid=t2.enumparentid)   inner join table t3 on (t2.enumid=t3.enumparentid) where t1.enumtypeid=1 and t2.enumtypeid=2 and t3.enumtypeid=3 	0.696786723662829
5578068	5029	select max similar rows by numeric field for all users	select point from user group by point having count(*)=(select count(distinct user) from user) order by point desc 	0
5578425	15226	can we make multiple rows as comma seperated in sql query?	select name+','+phone_no+','+address from <table_name> 	0.0197327299815838
5578451	14594	using the value of a column to select another column in sql	select   [datecolumn]=case step when 1 then date1  when 2 then date2 when 3 then date3 else date4 end from <table> 	0
5578591	13393	check if exactly one variable is not null	select case when count(c) =1 then 'y' else 'n' end from  (values (cast(@string as sql_variant)),(@float),(@bit),(@int)) t (c) 	0.0703622123543569
5578727	40057	mysql: group by `topic_id`, if `topic_id` > 0	select * from (         select topic_id,count(*),sum(`score`) as sum     from `entries`     where `topic_id` > 0     group by `topic_id` union     select topic_id, 1,1 as sum     from `entries`     where `topic_id` = 0 ) order by sum desc limit 30 	0.799797396717316
5578911	11805	find identity columns from another database	select o.name + '.' + c.name, o.name from test1.sys.columns c join test1.sys.objects o on c.object_id = o.object_id join test1.sys.schemas s on s.schema_id = o.schema_id where s.name = 'dbo'   and o.is_ms_shipped = 0 and o.type = 'u'   and c.is_identity = 1 order by o.name 	0
5579633	37137	how list out all tables in mssql?	select table_catalog ,         table_schema ,         table_name ,         table_type from information_schema.tables 	0.00227274518243359
5580697	39974	mysql limit number of rows returned by union all statement	select column1, column2 from (    select column1, column2    from table1   union all    select column1, column2    from table2 ) as resutl_table  limit 100; 	0.000341075190057745
5582528	17296	getting all unique values between two columns in mysql	select distinct * from (   select distinct field1 as n from table     union    select distinct field2 as n from table) as t; 	0
5583881	9463	is 1 single query statement possible	select couples.id, husband.person, wife.person   from couples     inner join persons as husband on couples.husband=husband.id     inner join persons as wife on couples.wife=wife.id 	0.499990619668828
5584754	35485	how to query column names dynamically using postgres/npgsql	select column_name from information_schema.columns where table_schema='public' and table_name='youtablename' 	0.0187791041102369
5585125	2481	select statement that selects distinct based on rownumber	select premiumyear, lastname, firstname, booking, claimtype, departuredate, [plan], incident, reserveamount, finalstatus, age, total     from (select premiumyear, lastname, firstname, booking, claimtype, departuredate, [plan], incident, reserveamount, finalstatus, age, total,                  row_number() over(partition by booking order by total desc) as rownum               from dbo.[table]) t     where t.rownum = 1 	0.0239845017514621
5587642	20073	how to retrieve the details of the student whose name starts with s	select sname  from student where sname like 's%' 	0
5587992	25541	how to run sql query for multiple meta keys as columns, and their values as rows?	select meta1.meta_value as address, meta2.meta_value as latitude, meta3.meta_value as longitude from wp_posts posts, wp_postmeta meta1, wp_postmeta meta2, wp_postmeta meta3 where posts.post_id = meta1.post_id and posts.post_type = ‘dealers’ and meta1.meta_key = ‘_dealer_address’ and posts.post_id = meta2.post_id and posts.post_type = ‘dealers’ and meta1.meta_key = ‘_dealer_latitude’ and posts.post_id = meta3.post_id and posts.post_type = ‘dealers’ and meta1.meta_key = ‘_dealer_longitude’ 	0
5590585	9021	getting the smaller index for each duplicate in sql	select id from atable except select min(id) from atable group by name 	0.000576364174869132
5591582	24290	how to get age using birthdate column by mysql query?	select * from your_table where year(curdate())-year(birthdate) between 10 and 20; 	0.00220613250992439
5591727	25209	how can i count the number of data that match the string text i have from this query?	select lo_category, count(*) from questions where question_text=<choice> group by lo_category order by lo_category 	0
5592199	22006	search person table for a given name	select * from table where concat_ws(' ',name,surname) like 'john d%' 	0.000872718881651362
5593511	22381	sql query for distinct count	select      fld1,      date,      fld4,      count(fld4) as count from     table group by     fld1, date, fld4 	0.239773766008791
5593684	32786	mysql select statment to get last records of duplicate entries	select max(id) id, name from tbl group by name having count(*) > 1 select tbl.* from tbl left join (     select max(id) id     from tbl     group by name     having count(*) > 1) x on x.id = tbl.id where x.id is null 	0
5593784	9663	mysql: get a list of tables that references a deleted row	select c.table_schema,u.table_name,u.column_name,u.referenced_column_name from information_schema.table_constraints as c inner join information_schema.key_column_usage as u using( constraint_schema, constraint_name ) where c.constraint_type = 'foreign key' and u.referenced_table_schema='your_db_name' and u.referenced_table_name = 'your_table_name' order by c.table_schema,u.table_name; 	0
5595062	40327	how to order results of a query randomly & select random rows. (mysql)	select * from item_bank_tb where item_type in(1,3,4) order by rand() limit 10 	0.000271304441038086
5595409	41043	join query on date range	select   p.startdate,   p.enddate,   h.personid from periods p   left join history h     on h.[from] between p.startdate and p.enddate or        p.startdate between h.[from] and isnull(h.[to], '30000101') 	0.022534462410714
5595650	24947	using sys.dm_sql_referenced_entities to show on dependencies that are views	select referenced_entity_name, re.* from sys.dm_sql_referenced_entities ('dbo.web_analyser', 'object') as re   inner join sys.views as sv     on sv.name = re.referenced_entity_name 	0.00817569179896499
5596702	39055	how to select only the int values in a column that is nvarchar	select *     from yourtable     where isnumeric(yourcolumn + '.0e0') = 1 	0.000144846365672194
5598377	14687	sql select and delete help	select * from table where id in(1,2,3,4,5) 	0.759122576602448
5598447	26439	mysql subquery with between	select distinct foreign_key from acos join     (         select lft, rght         from acos         where             id in (                  select aco_id                 from                     aros_acos a,                     (                         select parent_id, id                         from aros                         where foreign_key = 48 && model =  'user'                     ) x                 where                     a.aro_id = x.id                     or a.aro_id = x.parent_id             )     ) interval on     acos.lft>=interval.lft     and acos.rght<=interval.rght 	0.476520381687685
5598842	26734	searching mutliple tables using mysql?	select 'user' as hit_type, id from users where username like '%" . $_get['term'] . "%'" union all select 'topic' as hit_type, id from topics where tag like '%" . $_get['term'] . "%'" 	0.164489308820124
5598843	23484	how to search for a string in multiple stored procedure queries	select object_name(m.object_id), m.* from sys.sql_modules m join sys.procedures p on m.object_id = p.object_id where m.definition like '%yourtable%' 	0.316043742414628
5600028	3784	how to get single result in from sql select query! sql	select bt.source, bt.destination,        fmt.flight_name,        fct.flight_cost, fct.flight_seat, fct.flight_type,        ft.flight_time     from flight_main_table fmt         inner join base_table bt             on fmt.base_id = bt.base_id         inner join flight_cost_table fct             on fmt.flight_id = fct.flight_id         inner join flight_timing_table ft             on fmt.flight_id = ft.flight_id     where fmt.base_id = 109 	0.00125445619078604
5600867	38563	how to show fields from most recently added detail in a view?	select t.name, t.note, t.id     from (select f.name, n.note, n.id,                  row_number() over(partition by f.id order by n.id desc) as rownum               from #foot f                    left outer join #note n                        on n.foot_id=f.id) t     where t.rownum = 1 	0
5601054	4389	comparing 2 mysql tables	select * from `tablea` left join `customers` on `tablea`.`id`=`customers`.`id` where `customers`.`id` is null 	0.0144921962543878
5601096	12129	how to compare based on date with datetime field of mysql?	select subtitle,count(alertid) as cnt,date(alertdate) from alertmaster a,subscriptionmaster s where s.subid=a.subid group by a.subid,date(alertdate) 	0
5601299	29948	problem with multiple order by that must respect the first clause	select * from(     select top 50         e.id, e.name , e.total_score, e.(yourfield)     from          entry e      order by          e.total_score desc ) x order by x.(yourfield) 	0.175754823645642
5604165	21434	how to get row id of a sqlite fts3 table?	select rowid,* from person 	0
5605565	39027	adding a column that doesn't exist in a query	select a, b, 3 as c from table_test 	0.0744922740733369
5606892	37363	problem getting most recent record from sqlite db table	select _id, datetime_column from table1 where datetime_column in (select max(datetime_column)                            from table1) 	0
5607221	6493	mysql select from two tables	select can_call - (select count(id) from players where ...) as free   where match=match_id and id=partner_id 	0.00257067263629356
5607261	4427	avg() value to a default value 0 for non existent records in foreign table	select a.alertid     , min( a.alerttitle ) as alerttitle     , min( a.alertdetails ) as alertdetails     , min( a.alertdate ) as alertdate     , min( a.alerturl ) as alerturl     , min( s.subtitle ) as subtitle     , coalesce( avg( d.avgvote ), 0 ) as avgvote from alertmaster as a     join subscriptionmaster as s         on s.subid = a.subid     left join alertdetails as d         on d.alertid = a.alertid where a.subid=1  group by a.alertid order by alertdate desc  limit 0,10; 	0
5609327	6094	help me write the sql to get distinct members	select distinct(from_member_id) from messages_received order by id desc 	0.687353903935676
5611178	38853	search age range in mysql, php	select * from users where dob > min_dob and dob <= max_dob; 	0.00997146308924827
5611960	10932	mysql fulltext search on multi tables	select product_info.name from product_info  left join product_detail_info  on product_info.id = product_detail_info.product_info_id where match ( content ) against ( your_search_string ) 	0.585770271841137
5612597	14338	sql selecting a single record by comparing the different fields	select distinct prp_hist_id from tbl_proposal_workload where prp_hist_id not in ( select prp_hist_id from tbl_proposal_workload where prp_response = 1 ) 	0
5614196	36858	group by 2 columns and count	select count(distinct user_id)      , date_format(timestamp, '%y-%m-%d')    from table   group by date_format(timestamp, '%y-%m-%d') 	0.00503957969770137
5614627	35934	getting the last 15 dated items -- any way to optimize?	select * 	0.00037470475450552
5615225	165	hotel reservation system sql: identify any room available in date range	select r.*  from rooms r   left join availability a on (r.id = a.room_id   and a.date_occupied between :start_date and :end_date) where a.id is null 	0.003433221507499
5617467	40094	sql: how to replace one with two?	select id,freq,parity,line,type,gain,obdim from [first] where type&lt&gt'mm' union select id,freq,parity,line,'hh' as type,gain,obdim from [first] where type='mm' union select id,freq,parity,line,'vv' as type,gain,obdim from [first] where type='mm' 	0.0201449874912389
5618497	2786	sql - multiple table join and select first record on conditions	select  p.name, isnull(u.name, firstdelegate.name) as projmanager from    projects p left outer join         users u on p.manageruser_id = u.id and u.active = 1 left outer join         (             select * from             (                 select d.projectid,                         us.name,                         row_number() over (partition by projectid order by orderno) as seqno                 from  delegates d inner join                       users us on d.userid = us.id                 where us.active = 1             ) as del             where del.seqno = 1         ) as firstdelegate on p.id = firstdelegate.projectid 	0.000493490089053096
5619167	4554	mysql limit/offset: get all records except the first x	select * from tbl limit 95,18446744073709551615; 	0
5621247	5904	sql server order max values	select userid, max(point)  from [table]  group by userid  order by max(point) desc 	0.0927868430147228
5621842	35438	get last record of each month in mysql....?	select * from table  where created_on in  (select distinct max(created_on) from table  group by year(created_on), month(created_on)) 	0
5625495	38672	getting those records that have a match of all records in another table	select pl.positionid  from positionlicense pl   left outer join (                    select licenseid                     from userlicense                     where userid = @userid                      and @rangefrom <= validfrom                      and @rangeto >= validto) li    on li.licenseid = pl.licenseid  group by pl.positionid   having count(pl.licenseid) = count(li.licenseid) 	0
5627333	9197	selecting not joined data from several tables in mysql	select 'table1' as name, mydate from table1  union (select 'table2' as name, mydate from table2) as tmp ...  order by mydate 	0.000417101602869051
5627988	5532	how to add a row to the result of a sql query with inner join?	select      (t1.cola, t1.colb from my_table       union       select 'foo' as cola, 'bar' as colb) as t1  inner join      my_other_table t2 on . . . 	0.0103116642297708
5628539	8656	how to select the latest rows where each contains one value of all possible values found in a domain table?	select u.username from   users u,        domain d where  d.id = u.cityid        and u.registeryear = (select max(u2.registeryear)                              from   users u2                              where  u2.cityid = u.cityid); 	0
5631909	25932	retrieve records based on date	select * from mytable where filterdate like "%2010-08-01 %" 	0
5632134	25327	how to do a sql join that returns the rows that are not present in my table 2	select * from table1           left join table2           on table1.id=table2.id           where table2.id is null 	0.000200266617731297
5632285	3108	mysql using inner join to select multiple tables?	select @prod:= concat_ws(',',prod_product.field1,prod_product.field2,...)   ,@comment:= concat_ws(' ',pub_comment.field1,pub_comment.field2,....)  from prod_product  inner join pub_comment on (prod_product.id = pub_comment.itemid)  where prod_product.id = 7744 	0.494699209430968
5633619	11780	select 2 products from each category in mysql	select id, name, category  from (   select *,           if( @prev <> category,               @rownum := 1,               @rownum := @rownum+1           ) as rank,           @prev := category,           @rownum     from (     select * from products      order by category, rand()   ) random_prodcts ) products_ranked  where rank <= 2; 	0
5633821	31039	how to calculate difference between two dates in months in mysql	select 12 * (year(dateofservice)                - year(birthdate))         + (month(dateofservice)             - month(birthdate)) as months  from table 	0
5633895	34404	mysql select ids from one table which are not found in another table under certain conditions	select  distinct t1.session_id  from     id_table1 t1  inner join      id_table2 t2  on      t1.session_id = t2.session_id  where     t1.flag = 'yes' and     t2.progress not in(11) 	0
5634655	3663	php/mysql - multiple selects for query	select *  from instruments  where '$search' in (instrument, instrument2, instrument3, instrument4, instrument5) 	0.422450512775095
5634746	37062	joining one table to the latest row in another table using mysql	select          devices.*,         datalog.time_stamp,         datalog.fuellevel,         datalog.voltage     from         ( select deviceid,                  max( id ) lastactionid               from                  datalog               group by                   1 ) lastinstance         join datalog             on lastinstance.lastactionid = datalog.id         join devices              on lastinstance.deviceid = devices.deviceid    order by         devices.devicename 	0
5637284	23829	mysql fetch x colums for each category_id	select  l.* from    (         select  category,                 coalesce(                 (                 select  id                 from    writings li                 where   li.category= dlo.category                  order by                         li.category, li.id                 limit 15, 1                 ), cast(0xffffffff as decimal)) as mid         from    (                 select  id as category                 from    cats dl                  ) dlo         ) lo, writings l where   l.category>= lo.category         and l.category<= lo.category         and l.id <= lo.mid 	0
5637459	27812	selecting only the latest version of a field	select mytable.title, max(mytable.date) from mytable group by mytable.title 	0
5641274	12917	mysql counting the number of records that are associated	select catherder.*, count(cat.id) as cats_count from catherder join cat      on catherder.id = cat.catherder_id 	0
5642762	22647	mysql query for counting number of books	select branch_id, sum(num_copies) totcopies from book_copies group by branch_id 	0.00514005962285695
5643464	7954	mysql return single row of multiple invoice due for notification	select distinctrow name from table where duedate (<=> meets your criteria of when it's "due") 	0.00180088560306269
5643641	40409	sql count overflow	select count_big(*) from similarities where t1similarity = 0 or t2similarity = 0 	0.784961498228838
5646359	1021	getting referenced tables in mysql	select * from tableb where id in (select field2 from tablea); select * from tablec where id in (select field3 from tablea); 	0.0318220388093737
5647058	3871	how to trim results from a substring-with-regex match?	select regexp_replace(name,e'\(\\w\)_\\d+_\\d+_\\d+$',e'\\1') from logs; 	0.0131574590645648
5648420	41093	get all columns from all mysql tables	select * from information_schema.columns where table_schema = 'your_db' order by table_name,ordinal_position 	0
5648524	31615	mysql merging columns	select        car as product,       car_qty as qty   from       orders union all select       speakers as product,       speakers_qty as qty    from       orders; 	0.00871973277125539
5648658	7390	mysql left join multiple tables with one-to-many relation	select * from t1 left join t2 on (t1.id = t2.id1); union all select * from t1 left join t3 on (t1.id = t3.id1); 	0.788329851807124
5649937	33966	sql server multiple order?	select userid, max(skor) as 'skor', min(sure) as 'sure' from mytable group by userid 	0.459554690323477
5654132	28985	how to make mysqli_query compare a variable identicly?	select * from accounts where binary username = '$qrystring'"; 	0.110549696982973
5654568	13219	join with sum and group by	select   name,    sum( isnull(time, 0) ) sumoftime from   tasks    left join report on tasks.id = report.taskid                          group by   tasks.name 	0.458187330248136
5654735	19893	time in mysql and php on two different servers	select unix_timestamp() 	0.00170985760580663
5655498	31079	get distinct max date using sql	select t.pc_tmppl_attach, t.pc_tmppl_val1, t.pc_tmppl_crtdt from pc_temppl_tbl as t     join    (             select pc_tmppl_val1, max( t1.pc_tmppl_crtdt ) as maxdatetime             from pc_temppl_tbl as t1             group by t1.pc_tmppl_val1             ) as z         on z.pc_tmppl_val1 = t.pc_tmppl_val1             and z.maxdatetime = t.pc_tmppl_crtdt 	0.00506745839906263
5656407	12420	mysql query, most recent values from a historical table of values	select value from your_table group by request_id order by modifier; 	0
5657010	15380	database query on a non-dense index	select count(*) from employee where salary < 10,000 	0.613830456692877
5658948	36191	limit result in progress 10.1c	select top 5 from pub.customer order by balance desc; 	0.355079337433181
5659695	22442	picking data from database that appeard just once in a month	select *  from transactions group by card_number, month having count(card_number) = 1 	0
5661635	30429	what is the most efficient way to always make a database query that i know will only return a result very occasionally?	select * from uploads where group = $groupid and downloadable != 0 	0.13555303165978
5662133	15823	sql - group by id and a time interval from variable starting point	select  id, diff, min(dt_event), max(dt_event) from    (         select  t.*,                 trunc((dt_event - first_value(dt_event) over (partition by id order by dt_event)) * 86400 / 1200) as diff         from    mytable t         ) group by         id, diff 	0.000165223158593277
5665175	24147	count records that start with specific letters	select count(*),substring(column_name,1,2) from table_name group by substring(column_name,1,2) 	0.000141191826803937
5666986	11641	how can i determine if a string is numeric in sql?	select 1 from dual where regexp_like('23.9', '^\d+(\.\d+)?$', '') 	0.122251061939793
5667446	13389	in sql server 2008 how can i get the list of stored procedures which are inserting data in a given table?	select object_name(s.object_id) storedprocedure from sys.sql_modules s join sys.procedures p on s.object_id = p.object_id where definition like '%insert into mytable%'  or definition like '%insert mytable%' 	0
5667881	17053	only returning records when s.id = u.summary_id	select from    summary s  inner join year y1 on  s.current_year_id = y1.id inner join  year y2 on  s.previous_year_id = y2.id inner join  strategic_goal_entries sge  on   s.id = sge.summary_id inner join goal g on  sge.goal_id = g.id inner join  department d  on  s.department_id = d.id left join  uploads u on  s.id = u.summary_id  where  s.department_id = '4' group by  s.id 	0.0149489193172271
5668713	24510	select statement across a join table	select p.* from persontable p   inner join persontypecompositetable ptc     on p.person.id = ptc.person.id   inner join persontypetable pt     on ptc.persontype.id = pt.persontype.id where pt.persontype.category = 'a' 	0.144999440155116
5669473	34613	sqlite select date for a specific month	select * from `table name` where strftime('%m', `date column`) = '04' 	0.000364519766922698
5670675	32245	how to strip querystring from a field in t-sql?	select left(url, charindex('?', url + '?')-1) from   @temp 	0.00402788061149109
5671278	5879	mysql multi count with where	select sum(sold) as sold_count, sum(refunded) as refund_count from store 	0.50031246167739
5672337	3716	select the nearest value before and after	select   min(case when different > 0 then different else null end) as minpositive,   max(case when different < 0 then different else null end) as maxnegative from show_date 	0.00287668716940256
5672707	23703	inner join unknown column in 'field list'	select courses.name, sections.section_name, professors.first_name, professors.last_name, classrooms.room  from courses, course_section, sections, professors, professor_course, classrooms where sections.id = course_section.section_id and professors.id = professor_course.professor_id  and  and courses.id = 1; 	0.215451782955424
5674354	11155	sql select query - which merges 2 identical tables?	select  e.empid         , coalesce(e.name, de.name) as name         , coalesce(e.something1, de.something1) as something1         , coalesce(e.something2, de.something2) as something2 from    employee e         inner join draft_employee de on de.empid = e.empid 	0.00851802572814514
5675395	36509	how not to display records that are in both tables?	select a.*  from a left join b using (signup)   where b.id is null and *signup thingie*; 	4.75347216935941e-05
5675594	33279	how to query total when i have a join table	select  * from    (         select  a.amount, b.refid,                 rank() over (partition by a.refid order by b.id desc) as ranking,                 sum(amount) over (partition by a.refid) as asum         from    tablea a         left join                 tableb b         on      b.refid = a.refid         ) where   ranking = 1 	0.00444762414880302
5678010	39126	finding the nearest numeric match in a database to what a user has inputted in php	select * from `table_test1` where `price` > 80 order by `price` asc limit 1 	0.000524173378220824
5680337	20151	mysql query that can get distinct ids for logins and how many there were	select user_id, count(*) from users group by user_id 	0
5681320	30570	add list<int> to a mysql parameter	select * from table where find_in_set(id, @parameter) != 0 ... intarray = new list<int>(){1,2,3,4}; conn.command.parameters.addwithvalue("parameter", string.join(",", intarray)); 	0.303171586793749
5681332	11233	how do i concat grouped rows as a single row in mysql?	select group_concat(count seperator ',') from  (select concat(manufacturer, ':', count(*)) as count  from cars group by manufacturer) as a 	0.000174845288383548
5681819	4432	sql: combine value into one result when null or empty	select  case when coalesce([title],'') = '' then 'blank'               else [title]          end as [title],         count([value]) as [count] from .... where .... group by case when coalesce([title],'') = '' then 'blank'                else [title]           end 	0.00197488169963217
5682443	26138	sql server views - simulating a table from a normalized source	select value     , min( case when deductible = '0' then cost end ) as [no deductible]     , min( case when deductible = '100' then cost end ) as [$100]     , min( case when deductible = '250' then cost end ) as [$250]     , min( case when deductible = '500' then cost end ) as [$500] from valuation group by value 	0.00567506031871156
5682513	34305	select query with multiple tables in sql server	select "article"                  as type      , crossarticle_article.id    as id      , crossarticle_article.title as title_subject from crossarticle_article  where title like "%userinput%" union all select "blog entry"               as type      , blogs_entries.id           as id           , blogs_entries.title        as title_subject from blogs_entries where title like "%userinput%" union all  select "forum post"               as type      , forums_posts.id            as id      , forums_posts.subject       as title_subject from forums_posts where subject like "%userinput%" 	0.328127940946438
5682755	31824	mysql intersect via joins table?	select urls.id from urls inner join tags_urls tu1 on tu1.url_id = urls.id inner join tags t1 on tu1.tag_id = t1.id and t1.tag = 'sample' inner join tag_urls tu2 on tu2.url_id = urls.id inner join tags t2 on t2.id = tu2.tag_id and t2.tag = 'list' 	0.664323878540037
5682886	20884	retrieve rank from sqlite table	select  p1.* ,       (         select  count(*)          from    people as p2         where   p2.age > p1.age         ) as agerank from    people as p1 where   p1.name = 'juju bear' 	0.00102897554693682
5684430	39763	getting both id's from inner join	select     m.id as meal_id,     m.price as meal_price,     r.id as restaurant_id,     r.name as restaurant_name,     r.location as restaurant_location from meals as m inner join restaurants as r on r.id = m.restaurant_id 	0.00757253187726181
5686376	40715	sql query to display records from multiple tables	select     t.thread_id     ,t.thread_title     ,t.description     ,t.posted_time     ,t.subject     ,count(r.reply_id) as no_of_replies from     thread t     inner join reply r on t.thread_id = r.thread_id group by     t.thread_id     ,t.thread_title     ,t.description     ,t.posted_time     ,t.subject 	0.000100750444451496
5687064	32815	how to query two column of same table with two condition with groupby	select      cast(dateofregistration as date),     count(distinct id),       sum(         case registrationstate when '0' then 1 else 0 end     ) from tbl_user     group by cast(dateofregistration as date)     order by 1 2011-06-03  3   2 2011-07-03  2   0 	0.000173573553294371
5690306	24074	sql join by date range	select s.customer_id      , s.sales_location      , s.visit_date      , g.customer_id      , g.order_date from sales_location s   full join                       <     ( select o.customer_id            , max(s.visit_date) as last_visit_date            , o.order_date       from order o          left join sales_location s           on  s.customer_id = o.customer_id           and s.visit_date <= o.order_date       group by o.customer_id              , o.order_date     ) as g     on  g.customer_id = s.customer_id     and g.last_visit_date = s.visit_date 	0.0288075724528477
5690748	30353	get distinct result	select name from student where (select count(*) from grade where grade = 'f'          and id = student.id) = 0 	0.0133063904739979
5693749	1158	how to category in select statement	select distinct case     when department in ('programmer', 'network admin', 'system support') then 'it'     else department end from yourtable 	0.0418117140396868
5693764	4459	how to effectively join 3 tables m:n	select      a.name appname,      a.id appid,     d.id devid,     d.url_key url,     d.name devname,     cast(agg.dev_count - 1 as varchar) + ' more' from      (     select          max(ada.developer_id) first_dev_id,          count(ada.developer_id) dev_count,          app_id     from         apps_developers_assignment ada      where          d.id != @excludedevid     group by         app_id     ) agg     inner join apps a on a.id = agg.app_id     left join developers d on agg.developer_id = d.id 	0.352822317968523
5696002	39473	select from table given day	select * from dbo.tblmessages   where   mydatetimecol >= dateadd(day, datediff(day, 0, @mydatetimeparameter), 0)   and   mydatetimecol < dateadd(day, datediff(day, 0, @mydatetimeparameter), 1) 	0
5696123	3831	sql server 2000 row numbering	select l.seq, l.mn_no as mn_no, l.sb_no as sb_no, l.dp_no as dp_no, sum(costprice) as amt into #foo from dbo.mac_pur_tempdetail d inner join dbo.mac_pur_tempheader h on d.header_id = h.header_id and h.ref = 'sah1fihc' inner join dbo.mac_actlocmap l on l.loc_main = d.loc_id and l.description = 'pur' group by  l.seq,l.mn_no,l.sb_no,l.dp_no select (select count(seq) from #foo s where s.seq <= a.seq and a.mn_no = s.mn_no) as new_seq, * from #foo a 	0.114439079794136
5697442	16492	mysql group by get title column with smallest date value	select t1.* from `table` as t1 inner join ( select sid,min(datestart) as elder from `table` group by sid order by elder desc limit 10) as t2 on t1.sid = t2.sid and t1.datestart = t2.elder 	4.74621407958364e-05
5698378	39765	mysql -- join between tables in 2 different databases?	select <...> from a.table1 t1 join b.table2 t2 on t2.column2 = t1.column1; 	0.00231909435324534
5701451	40415	return null value as '0' in group by clause, postgresql	select  s.created_at, count(o.subsription_id) from    subscriptions s left join         orders o on      o.subcription_id = s.id group by         s.created_at 	0.182676328316351
5701750	33140	sql where subquery on id	select *  from table_1 t1 where t1.mymonth = (select max (t2.mymonth) from table2 t2 where t1.id = t2.id) 	0.189445094249304
5701757	19858	joining tables with anonymous foreign keys	select b.rec_id,'blog' as type from tblblogs b inner join tbltaganchors ta on ta.anchor = b.anchor where ta.tagid = 5 union select t.rec_id,'tutorials' as type from tbltutorials t inner join tbltaganchors ta on ta.anchor = t.anchor where ta.tagid = 5 	0.0057161865496778
5703167	7155	category post count	select c.name, count(p.id) from blgcategories c  inner join blgpostcategories pc on c.id = pc.categoryid inner join blgpost p on pc.postid = p.id group by c.id 	0.00371451701962256
5705184	27312	getting name from phone number from multiple tables?	select i.sendernumber,        coalesce(c.name, d.spvname, sd.spvname, v.spvname) as name,        case when c.name is not null then 'contact'             when d.spvname is not null then 'district'             when sd.spvname is not null then 'sub_district'             when v.spvname is not null then 'village'               else ''        end as type,        i.message     from inbox i         left join contact c             on i.sendernumber = c.number         left join district d             on i.sendernumber = d.number         left join sub_district sd             on i.sendernumber = sd.number            left join village v             on i.sendernumber = v.number 	0
5705316	40663	how to get the size of a varchar[n] field in one sql statement?	select column_name, data_type, character_maximum_length       from information_schema.columns    where table_name = 'mytable' 	0.000185592747948829
5705448	40820	sql select certain value first	select     assetvalue from         assets where     (assettype = 'country') order by case assetvalue            when 'us' then 1            when 'canada' then 2 else 3 end, assetvalue 	9.84113677196767e-05
5705630	13496	mysql - getting a row from latest non-null values in each column	select @a:=null, @b:=null, @c:=null; select a,b,c from (     select @a:=coalesce(a,@a) as a, @b:=coalesce(b,@b) as b, @c:=coalesce(c,@) as c time     from yourtable     order by time asc ) as y order by time desc limit 1; 	0
5706067	12442	how many records have a column value longer than 400 characters?	select * from mytable where len(myfield) > 400 	0.000122049134486165
5706724	3682	mysql query dependant on another query vs. join	select p.player_name from players as p inner join team_players as t on (t.player_id = p.player_id) where t.team_id = $tid 	0.632517676504533
5706740	32308	adding column to all tables in a mysql database (unknown table names)	select concat('alter table ', table_schema, '.', table_name, ' add column id int auto_increment not null primary key first;') as ddl into outfile '/tmp/alter_table.sql' from information_schema.tables where table_schema = 'db_name'  and table_type = 'base table'; \. /tmp/alter_table.sql 	0.000112424952650216
5707107	10604	order by column names	select * 	0.0115542597509204
5707198	30711	select from multiple tables group by id with time	select 'v' as type, v.userid, v.time from votes v where v.userid = '1234' union select 'c' as type, c.userid, c.time from comments c where c.userid = '1234' 	0.000423165777490734
5707614	37528	how to concatenate/join strings from a grouped column in sqlite?	select company.name, group_concat(employee.id) from company inner join employee on company.id = employee.company  group by company.id 	0.000962344793690122
5708466	30194	android querying many to many relationships	select name from places where exists( select * from routingtable_placestags where routingtable_placestags.places_id = places._id and exists ( select * from tags where tags._id = routingtable_placestags.tag_id and tags.name = 'searched for tag name here' )) 	0.197058391430053
5709777	33734	how to write a if condition within a select statement?	select name,salary, case     when  salary <= 2000 then 'low' when  salary > 2000 and salary <= 3000 then 'average' when  salary > 3000 then 'high' end as salary_level from employees order by salary asc 	0.331261041320307
5709989	39850	android sqlite inserting and ordering by time	select * from table where .... order by updatetime 	0.279313166932778
5711826	23945	getting concatenated rows in ascending order	select c.id     , stuff(         (         select ', ' + c1.errormessage         from category as c1         where c1.id = c.id         order by c1.errormessage         for xml path('')         ), 1, 2, '') as categories from category as c group by c.id 	0.000686288745034256
5716342	32323	mysql group by products	select s.p_name, sum(s.p_price)  from    (select left(p_name, 7) as p_name,     p_price from products) s group by s.p_name; 	0.0833384868463187
5716608	10758	sqlite column names without table name	select a._id as _id, name, email from people as a, emails 	0.00114324547658253
5717205	15609	how do i count every hour with epoch and mysql?	select from_unixtime(visittime,'%h') as h,count(*) as total from table where from_unixtime(visittime) >= now() - interval 1 day group by h 	0.00803109127663606
5717387	7295	how to reference multiple columns in a 1:n relationship chain	select   case grouping(d.name)     when 1 then 'all:'     else d.name   end as dept,   count(*) as total_manager,   sum(p.salary) as wages from dept d   inner join office o on d.id = o.dept_id   inner join personnel p on o.id = p.office_id group by d.name with rollup 	0.00336233285445899
5718413	1130	mysql summing value across date range	select  sum(hour_count)  from `work_entries`  group by    year(work_date - interval 15 day),    month(work_date - interval 15 day); 	0.000282972169949015
5718881	21100	adding a row value more than once to stdev()	select stdev(amount) from yourtable join numbers on n  <= yourtable.[count] 	0.000189144195827176
5720716	25455	how to properly join two mysql tables with conditions?	select b.*, ev.*    from blocks b  left outer join element_values ev      on ev.b_id = b.id     and e_id = 1  where t_id = 1; 	0.565379553385968
5721712	14372	query checking too many rows, how can i reduce?	select             sob_datas.id,             sob_datas.sob_field_name,             sob_datas.sob_field_value     from sob_datas sd          join sob_datas ssd on sd.sob_field_name = ssd.sob_field_name     where sd.sob_form_id = '.$proof['sobform']['id'].'          and sd.sob_field_value != ssd.sob_datas.sob_field_value 	0.679698927538578
5721922	8586	filter out string column	select tests.release, tests.result from tests where tests.testcaseid = 104209 and tests.release <='a1b2c2' order by tests.release 	0.03248758365336
5722458	26375	sql - suppressing duplicate columns (not rows) for a query	select (case when effective_date = prior_effective_date               then null              else effective_date          end) effective_date,        (case when end_date = prior_end_date               then null              else end_date          end) end_date,        description ,        subpart   from     (select effective_date,             lag(effective_date) over                  (order by effective_date desc, description asc) prior_effective_date,             end_date,             lag(end_date) over                  (order by effective_date desc, description asc) prior_end_date,             desc,             subpart        from <<your query>>) 	0.0100502026035297
5724035	5234	show more button: with php and mysql	select cities.id, cities.country, cities.city, count(*)     from cities     group by cities.country 	0.128788753327454
5724716	20403	php mysqli ranking position	select * from (select *, @rownum := @rownum + 1 as rank from `points_table` `p`  join `accounts_table` `a` on a.id = p.uid, (select @rownum:=0) r order by `p`.`points` desc) mytable where rank = 4 	0.369192395818085
5736820	27461	sql: how to select earliest row	select company, workflow, min(date) from workflowtable group by company, workflow 	0.00464147008030699
5737628	25115	mysql count distinct	select      count(distinct user_id) as countusers    , count(site_id) as countvisits    , site_id as site  from cp_visits  where ts >= date_sub(now(), interval 1 day)  group by site_id 	0.107778434640739
5737719	11430	selecting columns based on value in single column	select firstname, email from users where `group` = "test" 	0
5738257	22540	how to add an array of ints to stored procedure in sql server 2000	select * from order where orderid in (1, 2, 100) 	0.19866793426536
5742066	11489	create 24hour top table by pageview	select          pageview.id as pageview_id   ,movie.title as move_title   ,count(movie.id) as moviecount24 from pageview inner join movie on (pageview.movie = movie.id) where pageview.vieweddate between date_sub(now(), interval 1 day) and now() order by moviecount24 desc limit 30; 	0.0369143907597761
5745339	1050	mysql statement	select u2.id, u2.country_id, u2.city_id, u2.surname      from users u1         inner join users u2             on u1.country_id = u2.country_id                 and u1.city_id = u2.city_id                 and u1.id <> u2.id     where u1.id = 'current_id' 	0.622785314457111
5747463	5385	mysql select query condition	select * from table where a = 'x' or (a is null and b = 'y') 	0.4237457382348
5747648	25069	find the max value of an aggregate query in sql server 2008:  select the u.s. state with the most cities	select top 1     s.name, count(c.stateid) as citycount from     tblstates as s inner join     tblcities as c on     s.stateid = c.stateid group by     s.name order by     count(c.stateid) desc 	0.000985489895335576
5748229	16506	find number of joins by a reference table	select b.code as code, count(a.id) as a_count from b left join (j join a on j.a_id = a.id) on j.b_id = b.id group by b.code asc 	0.00106476626460675
5748620	3551	sql server - not in	select  *   from table1 t1  where not exists (     select *      from table2 t2      where t1.make = t2.make     and   t1.model = t2.model     and   t1.[serial number] = t2.[serial number]); 	0.763979158595551
5749037	17435	how to handle one-to-many join without repeat rows	select   dbo.product_img.p_id , dbo.products.name , max(dbo.product_img.path) , min(dbo.product_img.path)  from dbo.product_img  inner join dbo.products      on dbo.product_img.p_id = dbo.products.p_id  group by dbo.product_img.p_id , dbo.products.name 	0.0274597292869154
5749051	17617	generating a 2-d table of results in sql	select [date],        count(case when pb.band = 1 then l.id end) as band1,        count(case when pb.band = 2 then l.id end) as band2,        count(case when pb.band = 3 then l.id end) as band3,        count(case when pb.band = 4 then l.id end) as band4 from listitem l join priceband pb on l.price >= pb.loprice and l.price <= pb.hiprice where listid = 1  and ranking <= 100 and band >= 1 and band <= 4 group by date order by date asc 	0.101403239488502
5749279	28578	sql - getting next number in line from a recordset with gaps in numbers	select  top 1         load_no + 1 from    loads mo where   not exists         (         select  null         from    loads mi          where   mi.load_no = mo.load_no + 1         ) order by         id 	0
5750471	18054	selecting duplicate values based on distinct values in another column	select i.itemid,        i.description from   items i        join useritemrelationship r          on i.itemid = r.itemid        join users u          on u.userid = r.userid where  u.name in ( 'ruth', 'bob' ) group  by i.itemid having count(distinct r.userid) = 2 	0
5755005	38167	want to know if a table exists or not	select count() from sqlite_master where name ='name_of_your_table'; 	0.310165225217137
5755213	35359	grouping data in one table based on links in another table	select * from table2 where id in (select table2_id from table3); 	0
5755951	37874	find duplicate ids for each timestamp	select  timestamp, badge_id from    mytable group by         timestamp, badge_id having  count(*) > 1 	0
5756133	36359	aggregate/group table rows in sql if a column has a specific value	select <columns> where description not in('insurance','pickup') group by  <some columns) union all select <columns> where description in('insurance','pickup') 	0
5756732	29981	how to make string longer then 15 chars appeared with ".." in mysql?	select if(char_length(thefield) > 15, concat(substr(thefield, 1, 13), '..'), thefield) 	0.0563755644681614
5757746	37544	mysql count two groups from a joined table	select t.name,             count(a.id),             sum(case when a.status = '1' then 1 else 0 end)       from tickets t       left join articles a          on t.id = a.ticket_id       group by t.id,            t.name 	7.30482845566798e-05
5758416	2749	my mysql query is resulting in 1 for number of rows regardless if value is there or not	select count(*) ... 	0.0013945495007467
5759529	12061	php/mysql search for multiple values	select * from homes  where published = 1  and (  lower(country) like '$search%'   or   lower(city) like '$search%'  or  lower(area) like '$search%' ) 	0.0472383530399008
5759868	35234	generate 6 numbers between 1 and 2 in a 2:1 ratio in sql or pl/sql	select r from   (select case                when rownum <=4 then 1                else 2                end as r         from dual         connect by level <= 6) order by dbms_random.value; r                       2                       1                       1                       2                       1                       1 	9.88626088200652e-05
5760335	18791	sql: select rows with a column value that occurs at least n times?	select fname, lname from celebrities  where lname in   (select lname from celebrities    group by lname having count (lname) >1) 	0
5760820	4792	how to retrieve records from first table that don't have a reference in the second table?	select * from table1 where table1.id not in (select distinct referenced_id from table2) 	0
5765385	3935	mysql: how to get rows repeated x times	select fruit_name from `table` group by fruit_name having count(fruit_name)>=3; 	0
5767479	31444	mysql limit range	select name from mydb order by score desc limit 10,10; 	0.0464279798114893
5768133	35213	single sql query for multiple tables	select d.domain_name, k.keyword from pages p, keywords k, domains d where p.id_domain  = d.id  and p.id_keyword = k.id group by d.domain_name, k.keyword order by d.domain_name 	0.0560257971276657
5771077	25534	how to automatically set the sno of the row in ms sql server 2005?	select row_number() over(order by sno asc), sno, customername, age from customer 	0.00892676728171371
5772418	5230	how could i go by storing items from my database into an array, but only if that item is not already in the array?	select distinct categoryname from categorytable 	0
5772713	23242	structuring a sql statement to display by two levels depth not one upwards	select parent1.name from categories as node, categories as parent, categories as parent1 where node.left_node > parent.left_node and node.right_node < parent.right_node   and parent.left_node > parent1.left_node and parent.right_node < parent1.right_node   and node.name = '{$node_name}' order by parent.right_node desc 	0.0158178293624218
5772866	29701	how to create dates from date components in sql (t-sql)?	select   mydate = cast([year] + right('0' + [month], 2) + '01' as datetime) from (   select [month] = '2',  [year] = '2011' union all   select [month] = '03', [year] = '2011' union all   select [month] = '5',  [year] = '2011' union all   select [month] = '12', [year] = '2011' union all   select [month] = '8',  [year] = '2084' union all   select [month] = '1',  [year] = '1940' ) x; 	0.00236321316469424
5773169	24775	t-sql custom sort/orderby on a calculated value as a stored procedure or table function	select   calendareventid,   dbo.getlatestdate(     fromdate, todate, monday, tuesday,     wednesday, thursday, friday, saturday, sunday,      everynweeks, endafternoccurences) as latestdate from calendarevents order by 2 	0.793028326477314
5773366	8087	how do i query tables located in different database?	select * from database1.dbo.table1 t1 join database2.dbo.table2 t2 on   t1.field1 = t2.field2 	0.0326000674368161
5777759	18998	how to determine what foreign keys are defined in hsqldb?	select * from information_schema.constraint_column_usage select * from information_schema.constraint_table_usage 	0.00300505321884532
5779598	15092	mysql in substitute	select  * from    employee e where   not exists         (         select  null         from    employee ei         cross join                 project p         left join                 works_on wo         on      wo.pno = p.pnumber                 and wo.essn = ei.ssn         where   ei.ssn = e.ssn         ) 	0.469366488533685
5780138	9004	sql server: combine two values in the same row	select id, name, date, team, sum([total#1]) [total#1], sum([total#2]) [total#2] from yourunionresult group by id, name, date, team 	0
5781156	40674	combining records in a query	select * from (     select  studentid,             min(case when fieldid = 1 then response else null end) as name,              min(case when fieldid = 2 then response else null end) as lastname     from yourtable     group by studentid) as studentsnames where name = 'some value' and lastname = 'some value' 	0.0257304708575491
5781349	9874	mysql subquery to refer to field in parent query	select *  from   (select count(*),                 a2.page_title          from   ratings a2          where  date(timestamp) <= '2011-04-24'                 and date(timestamp) >= '2011-04-17'                 and rating >= 1                 and rating <= 2          group  by a2.page_title) current         join          (select a1.page_title,                      count(*)       as rvol,                      avg(a1.rating) as theavg               from   ratings a1               where  date(a1.timestamp) <= '2011-04-17'                      and date(a1.a_timestamp) >= '2011-04-11'               group  by a1.page_title               having count(*) > 20) morethan20           on current .page_title = morethan20.page_title 	0.105529598326623
5781662	34928	joining on 1 column across 4 tables - mysql	select a.adata, b.bdata, c.cdata, d.ddata  from taba as a     inner join tabb as b         on b.id = a.id     inner join tabc as c         on c.id = b.id     inner join tabd as d         on d.id = c.id 	0.00161191777441674
5782026	9071	sql query to find resource containing more than one tag	select t.md5, r.title, r.link, t.category from resource r inner join tags t on r.md5 = t.md5 where exists (select category from tags t1 where category = @tag and t1.md5 = r.md5) and exists (select category from tags t1 where category = @tag2 and t1.md5 = r.md5) 	0.00979946803137545
5782672	13709	mysql. numeric sort by string id	select cast( replace( id, 'k', '' ) as signed ) as sort from online order by `sort` desc 	0.00890274156911588
5785166	39831	mysql match text fields	select      group_concat(id separator ' '), "name" from proj  where      length(company_name_metaphone) < 9 and      length(company_name_metaphone) > 3 group by country, upper(company_name_text) having count(*) > 1 union select      group_concat(id separator ' '), "metaphone" from proj  where      length(company_name_metaphone) > 9 group by country, left(company_name_metaphone, 9) having count(*) > 1 	0.0602757636941281
5785685	3794	mysql exclusive records	select clientid from   clients group by   clientid having   count(*) = count(if(pageid = 3, pageid, null)); 	0.0357363707864422
5788164	23345	calculated field in sql server 2008	select r.roleid,        r.rolename,        cast(case               when lr.roleid is null then 0               else 1             end as bit) as isloginetrole from   aspnet_roles r        left join loginetroles lr          on r.roleid = lr.roleid 	0.276651933646659
5788586	8744	how to use distinct in ms access	select distinct task.priority, task.subject, task.status, task.duedate,  task.completed, categories.category from task, categories where (((categories.categoryid)=[task].[categoryid])); 	0.688715424957333
5788916	16066	how can i get a list of ordered rows from a list of ordered ids from a mysql table?	select * from table where id in (x,y,z) order by field(id,x,y,z) 	0
5789360	35977	select rows depending on field value	select     e.empid,     coalesce(oneappoint.appointmentid, zeroappoint.appointmentid) appointmentid from     employee e     left join appointment zeroappoint         inner join (         select             max(a.appointmentid) appointmentid ,         a.empid             from             appointment a         where             a.visibility =0              ) maxzeroappoint         on zeroappoint.appointmentid = maxzeroappoint.appointmentid     on e.empid = zeroappoint.empid     left join appointment oneappoint     on e.empid = oneappoint.empid          and oneappoint.visibility = 1 	0
5790042	40672	mysql query to calculate total cost	select           sum( pt.price ) as totalcosts     from          ( select                   @r:= date_add(@r, interval 1 day ) calendardate             from                   (select @r := str_to_date('2011/04/28', '%y/%m/%d')) vars,                 anytablewithatleast8ays limit 8 ) justdates,         pricestable pt     where         justdates.calendardate between pt.date_from and pt.date_to 	0.00232198068379081
5792066	16059	can a query use more than one nonclustered index for a table?	select top 1000 c.iid_company from dbo.company as c with(nolock) where  c.col_1 like 'something%' or c.col_1 like 'something2%' or c.col_1 like 'something3%' union all  select top 1000 c.iid_company from dbo.company as c with(nolock) where  c.col_2 like 'something%' or c.col_2 like 'something2%' or c.col_2 like 'something3%' 	0.271468558344297
5792236	17685	select users appearing at least once per week for several weeks	select user_id,  sum(if(activity_date between now() - interval 1 week and now(),1,0)) as this_week, sum(if(activity_date between now() - interval 2 week and now() - interval 1 week,1,0)) as last_week, sum(if(activity_date between now() - interval 3 week and now() - interval 2 week,1,0)) as two_week_ago, sum(if(activity_date between now() - interval 4 week and now() - interval 3 week,1,0)) as three_week_ago from activities where activity_date >= now() - interval 4 week  group by user_id having this_week > 0 and last_week > 0 and two_week_ago > 0 and three_week_ago > 0 	0
5792764	15672	mysql where or having	select    u.name,    u.type,    count(a.id) count from users u left join articles a on u.id = a.writer_id where    u.type='writer'    or    a.writer_id is not null   group by    u.name 	0.779015708245531
5793159	22628	"friends of friends" like sql query	select  case f2.id_user1 when case f1.id_user1 when $user then f1.id_user2 else f1.id_user1 end then f2.id_user2 else f2.id_user1 end from    friends f1 join    friends f2 on      f2.id_user1 = case f1.id_user1 when $user then f1.id_user2 else f1.id_user1 end         or f2.id_user2 = case f1.id_user1 when $user then f1.id_user2 else f1.id_user1 end where   (f1.id_user1 = $user or f1.id_user = $user)         and f1.is_accepted = 1         and f2.is_accepted = 1         and f1.is_blocked = 0         and f2.is_blocked = 0         and not (f1.id_user1, f1.id_user2) = (f2.id_user1, f2.id_user2) 	0.0221686373735179
5794331	11040	how to get parent name through mysql query	select ty.id, ty.type, ty.pid,    if(ty.pid = 0, '-', p.type) as parent,   ty.code, ty.description, ty.icon,   date_format(ty.adate, '%m-%d-%y %h:%i:%s') as adate,   date_format(ty.edate, '%m-%d-%y %h:%i:%s') as edate, ty.status from bid_type ty   left outer join bid_type p on p.id = ty.pid 	0.0035335333732266
5796340	9054	mysql string last index of	select substring_index('http: 	0.00253812966095389
5798217	18751	counting the number of non null or non zero columns in a table 	select *,  if(score_1<>0,1,0)+if(score_2<>0,1,0)+if(score_3<>0,1,0) as `count`  from table 	0
5798720	13154	sql query question, find max of result	select x.aname, x.quantity   from (select r.name, sum(r.rhowmuch + r.rhowoften) as quantity           from ration r       group by r.aname       order by quantity desc) x  where rownum = 1 	0.13968104730221
5799816	19199	join on date group	select from_unixtime(date,'%m-%d-%y') as d, sum(tb=1) as tb1, sum(tb=2) as tb2, sum(tb=3) as tb3 from ( select date,1 as tb from t1 union all select date,2 from t2 union all select date,3 from t3) as t group by d 	0.133008815857213
5800378	30177	mysql fetch data between two rows	select * from `table` limit 4,5; 	9.83522662124459e-05
5803212	38573	date index - long range search all rows, small not	select min(date), max(date) from dates; select count(*) from dates where date between '2011-04-27' and '2012-04-28'; 	0.0167950544924974
5803570	21391	sql select to find cyclic references in father-id-organized tree?	select  n.*, connect_by_root(id), level from    elements n start with         id in         (         select  min(id)         from    (                 select  id, connect_by_root(id) as root                 from    elements                 start with                         id in                         (                         select  id                         from    elements n                         where   connect_by_iscycle = 1                         connect by nocycle                                 father_id = prior id                         )                 connect by nocycle                         id = prior father_id                 )         group by                 root         ) connect by nocycle         id = prior father_id 	0.0234910691932371
5805222	897	left join bringing 2 different objects	select distinct n from novidade as n left outer join fetch n.comentariosnovidade 	0.162991739339581
5806715	31779	sum of cost spent on advertisments on specific magazine (month?, year?)	select sum(b.cost * a.num_issues) as total_cost   from dvd_ads a,         dvd_adv_cost b  where b.mag_id = a.mag_id    and b.page_size = a.page_size    and a.adv_id = 6    and a.mag_id = 1 	0
5808209	14919	sql return custom groups with 0 entries	select ranges.name     , count( z.somenonnullablecol ) from    (         select '1: less than 50'  as name, 0 as min, 49 as max         union all select '2: 50 - 100', 50, 99         union all select '3: 100 - 150', 100, 149         union all select '4: 150 - 200', 150, 199         union all select '5: 200 - 250', 200, 259          union all select '6: greater than 250', 250, 2147483647         union all select '7: unable to calculate', -2147483648, -1         ) as ranges     left join ( some subquery ) as z         on z.sc between ranges.min and ranges.max             or ( z.sc is null and ranges.max = -1 ) group by ranges.name 	0.00446556318184323
5808374	38513	how to order results from a table in mysql by the same order as when added to the table?	select * from table_name order by pk_column desc 	0
5808700	1556	select rows based on max values of a column	select * from attributes a where attribute_id := given_attribute_id and version_id = (  select max( version_id ) from attributes b where attribute_id := given_attibute_id  and b.id = a.id  ) 	0
5810015	27599	sql query for mutual visited places	select venue_id, count(distinct user_id) from activities where user_id in (116,227,229,613,879)  group by venue_id having count(distinct user_id) = 5 	0.0891285648237301
5810213	14697	sql server null value with inner join	select table1.id, table1.description, table2.name, table2.surname from table1 left join table2 on table1.empid = table2.empid; 	0.792665717499235
5814400	8521	grouping data and showing it	select p1.id as profileid      , p1.name as profilename      , group_concat(p2.productname)   from profiles as p1    left   join products as p2      on p1.id = p2.profileid   group      by p1.id      , p1.name   order      by profileid asc 	0.145175958468995
5814473	26412	how can i get these two suburbs with sql?	select jp.`id`,      concat(u.`first_name`, " ", u.`last_name`) as `name`,      jp.`departure_time`,      jp.`destination_time`,      s.`suburb` as `departure_suburb`      s2.`suburb` as `destination_suburb`  from `journey_planning` as `jp` join `users` as `u` on jp.`driver_id` = u.`id` join `suburbs` as s on jp.`departure_suburb_id` = s.`id` join `suburbs` as s2 on jp.`destination_suburb_id` = s2.`id` 	0.0324692888183506
5815669	23426	find invalid email address	select email from table where email not like '%_@_%._%' and email not like '%list of invalid char%' 	0.158353875889968
5820093	28328	how to get 2 maximum id from table in mysql	select from [table] where [condition] order by `id` desc limit 2 	0
5821277	1045	oracle/sql - select records on at specific sysdate times	select         *     from         tablename     where          to_char(sysdate,'hh24') = '08'; 	5.09418979641031e-05
5824722	16612	mysqli: how to get the type of a column in a table	select data_type from information_schema.columns where table_name = 'my_table' and column_name = 'my_column' 	0.000145246408718872
5824873	13733	every derived table must have its own alias error in mysql	select sum( cost )  from (   (   select s.cost   from sandwiches as s   where s.name =  "cheese steak"   ) as t1 union    (   select p.cost   from pizza as p   where type =  "plain"   and size =  "l"   ) as t2 ) as t 	0.0596661566186885
5826761	5367	get age from record in table: t-sql	select datediff(hour,timestamp,getdate()) as hours_old from mytable 	0
5826891	16964	subtract 1 from query result	select count(p.pid) - 1 as pid_count  from department d, professor p  where d.did = ? and p.did = d.did; 	0.00569380592835518
5826946	40212	convert xml data to tabular and xml form in sql server 2005	select       p.value('../@id', 'int'),     p.value('../@total', 'int'),     p.query('fid') from @xmldocument.nodes('roomtypes/roomtype/roomfacilities') n(p) 	0.167884619537708
5827363	19185	detecting changes within a dataset in mysql	select t.id, t.date, t.value, if( ( select td.value as last_value from tab td where td.date < t.date order by td.date desc limit 1 ) <> t.value, 'changed', 'unchanged' ) as cstatus from tab t order by date 	0.185602348202597
5827657	33608	mysql, to get rows in tbla that aren't in tblb for an item in tblb	select *    from batchtbl   where jobuuid     not      in (select jobuuid            from jobbatchstatustbl) 	0.000143636275069345
5828997	29352	count records in range group by date	select saledate, sum(iif(saletime >= 101 and saletime <= 159), 1, 0) as [101to159) sum(iif(saletime >= 200 and saletime <= 259), 1, 0) as [200to259) from mytable group by saledate 	0.000368001010575101
5831027	3790	mysql query on single table to find multiple rows	select distinct cr1.movie from credits as cr1 join credits as cr2 using (movie) where cr1.person = {person 1 goes here} and cr2.person = {person 2 goes here} 	0.000189368104724154
5832270	1449	select only the last inserted item related to another registry	select al.* from albums al inner join bands b on al.band_id=b.id where al.insertion_date=(     select max(insertion_date)     from albums     where band_id=b.id ) 	0
5835382	20233	how to impose conditions on a "group by" statement - mysql	select p.* from   ( select style,max(discount) as highest_discount      from products     where catalog = 1     group by style ) p1 join products p on p.id =   ( select pu.id      from products pu     where pu.catalog = 1       and pu.style = p1.style       and pu.discount = p1.highest_discount     limit 1 ) 	0.632586342670202
5836025	2886	how to count hits greater than x in access?	select     count([user]) from     [table] where     hits > 10 group by     [user] 	0.00216121215886215
5837429	6751	mysql sum multiple rows and rank handling ties	select @rownum := @rownum + 1 as row,     @rank := if(@prev_val!=score,@rownum,@rank) as rank,     userid,     @prev_val := score as score from (     select userid, sum(score+bonus) as score      from entries      group by userid  ) exodus_entries  order by score desc 	0.114411963044967
5837949	2959	sql: select * where attribute matches all items in array	select photos.id,max(othercolumn) from \"photos\"  inner join \"taggings\" on \"photos\".\"id\" = \"taggings\".\"photo_id\"  inner join \"tags\"  on \"tags\".\"id\" = \"taggings\".\"tag_id\"  where \"tags\".\"name\" in ('foo', 'bar') group by photos.id having count(*) = 2  	8.83333540753946e-05
5844384	22398	ip2nation - don't understand how the ip value is stored	select inet_ntoa( 687865856 ) >> 41.0.0.0 select inet_ntoa( 689963008 ) >> 41.32.0.0 	0.0642743314896503
5846862	38127	extracting information from datetime to input into a sql query	select     yt.* from     yourtable yt where     month(yt.datecreated) = 11     and year(yt.datecreated) = year(now()) ; 	0.000315074924362504
5853059	40360	hql: finding object where child objects include specific attribute values	select d from dog d join d.colors o where o.color in ("black","white") 	0.000175279648407354
5856844	12712	query to select all record and counts the same value?	select o.name "name",     (select count(*) from table_name i where i.name = o.name) "count" from table_name o; 	0
5857762	32621	join data with mysql and php	select u.* from friends f inner join `user` u on f.idfriends=u.id where f.iduser=1; 	0.419115442107892
5857990	5403	mysql unix_timestamp for postgresql	select extract(epoch from your_datetime_column) from your_table 	0.473759820794862
5858331	12686	mysql query for maximum value of all records from last 5 days	select max(`value`) from mytable  where `date` between date_sub(now(), interval 5 day) and now() 	0
5858453	3407	get schema name	select sequence_owner   from all_sequences  where sequence_name = '<your_sequence_name>' 	0.0238841763651448
5859096	36438	remove seconds from time field?	select   time_format(opentime, "%h:%i") as opentime,   time_format(closetime, "%h:%i") as closetime from hours; 	0.000356014099536248
5861002	10719	hql select from select problem	select count(*) from mytable t group by t.col1, t.col2 	0.568243763791937
5861852	27471	sort mysql results alphabetically, but with numbers last	select names from your_table order by names + 0 asc 	0.000369189374335982
5862576	32793	how to subtract two columns which are times in access sql query	select format(j.leaving_time - j.arrival_time, "hh:nn:ss") as time_difference from technicians as t, jobs as j, tech_allocation as ta where j.job_id = ta.job_id        and ta.technician_id = t.technician_id order by 1 asc; 	7.27289818118588e-05
5862822	28813	rounding milliseconds in t-sql	select cast('2009-12-07 10:40:21.893' as datetime2(0)),         cast('2009-12-07 10:42:18.173' as datetime2(0)) 	0.277196818520647
5863293	4074	calculate price with mysql query	select sum(x.totalcost) from (     select c.item_id, c.quantity * ip.price as totalcost     from cart c     join items_prices ip       on c.item_id = ip.item_id     left join items_prices ip2       on ip2.quantity > ip.quantity       and c.quantity >= ip2.quantity     where c.quantity >= ip.quantity       and ip2.quantity is null ) x 	0.0313387977481776
5863471	40565	select all rows of data but eliminate rows with duplicate data in single column	select * from tblusers where cdeviceregistrationid > '' group by cdeviceregistrationid 	0
5863677	39305	union select column mismatch	select     from_unixtime( date_added,  '%m-%d-%y' ) as formatted_date,     sum( tb =1 ) as sum_users,     sum( tb =2 ) as sum_links,     sum( tb =3 ) as sum_ads,     sum( tb =4 ) as sum_actions,     sum(total) as tot_rev from (     select date_added,'' as total, 1 as tb         from users_list where 1=1     union all      select date_added,'', 2         from users_links where 1=1     union all      select date_served,revenue, 3         from ads_served where 1=1     union all      select date_served,'', 4         from actions where 1=1 ) as t group by formatted_date order by formatted_date desc 	0.495501602622582
5863684	21973	case statment based on a count	select     case         when table1.field is not null             then table1alias1.column1         when table2.field is not null             then table1alias2.column1     end,     column2 from     table0     left outer join table1 on table0.id = table1.field and         table1.column1 like '%foo%' as table1alias1     left outer join tabl1 on table0.id = table1.field and         table1.column1 like '%fork%' as table1alias2 	0.0691425260292677
5865220	1153	how do i query by two columns with a self-referential relation with sql/activerecord?	select * from stories left outer join shares as s1 on s1.story_id=stories.id left outer join shares as s2 on s1.parent_id=s2.id order by greatest(s2.updated_at,s1.updated_at,stories.updated_at) 	0.029691481152721
5865421	6083	combining sql query results into one table	select sku.idsku, amaterial.material, amcolor.color, atype.type  from sku sku  inner join amaterial on sku.idsku = amaterial.sku_idsku  inner join amcolor on sku.idsku = amcolor.sku_idsku  inner join atype on sku.idsku = atype.sku_idsku  limit 0 , 30 	0.00431784551112063
5867320	9099	index on which tablespace	select tablespace_name from all_indexes where owner = 'myschema' and index_name = 'myindex'; 	0.554119970130035
5869805	7264	help with sql statement (select users who have product a, but not product b, c or d)	select email, first_name  from users where id in (select user_id from resources where product_id=22) and id not in (select user_id from resources where product_id in (1,3,35)) 	0.198440839924059
5871369	39478	oracle - how do i get the actual size of a specific row?	select vsize(col1) + vsize(col2) + vsize(col3) +  long_raw_length_function(long_col) + dbms_lob.getlength(blob_col)  from table  where id_col = id_val; 	0
5872211	28603	is it possible to select records range from n to n+10 in mysql?	select * from table <where clause if required> limit 10,20 	0.000117786087072564
5872357	20874	mysql select * but place array of ids to the bottom of the result	select * from table where id not in (3,6,9) union all select * from table where id in (3,6,9) 	0
5872431	28988	microsoft sql querying hours in timestamp	select *     from yourtable     where datepart(hh, yourcolumn) between 18 and 20 	0.020030631573576
5876885	23086	retrieving the most recent entry in a database table with a certain value	select couponid from users_coupons where userid = ? order by id desc limit 1 	0
5878163	9849	sql result sorted twice on same column	select ... from mytable order by case when col = 0 then 1 else 0 end asc, col asc 	0.000328858532094493
5878585	9681	return mysql thread_id	select connection_id(); 	0.245114058679393
5880492	9251	how to filter xmltable using data from existing table?	select t.nam   from xmltable('/документ/план/строкиплана/строка'         passing xml columns nam varchar2(256) path '@дис') t  where t.nam not in (select d.name                         from disciplines_ d                        where d.name is not null) 	0.00556679073536625
5883017	34398	trying to assign something to a "rule" using logic in php and mysql	select * from rules where ((pickup_type = 'city' && pickup_city_id = '$pickup_city_id') or (pickup_type = 'state' && pickup_state_id = '$pickup_state_id') or (pickup_type = 'country' && pickup_country_id = '$pickup_country_id') or (pickup_type = 'region' && pickup_region_id = '$pickup_region_id')) and ((drop_type = 'city' && drop_city_id = '$drop_city_id') or (drop_type = 'state' && drop_state_id = '$drop_state_id') or (drop_type = 'country' && drop_country_id = '$drop_country_id') or (drop_type = 'region' && drop_region_id = '$drop_region_id')) order by type asc 	0.672702312382949
5884781	29967	sql datetime format	select convert(datetime, '23/02/2008 00:00:00') 	0.158397992520556
5885094	11813	sql server: print generated sql query	select     count(eo.equal_opps_id) as 'age 40 - 49'    ,dateadd(yy,-49,getdate()) as lesserdate   ,dateadd(yy,-39,getdate()) as greaterdate from    dbo.app_equal_opps eo, dbo.app_status s  where    eo.date_of_birth > dateadd(yy,-49,getdate())    and eo.date_of_birth < dateadd(yy,-39,getdate())    and eo.application_id = s.status_id    and s.job_reference_number = '33211016'    and s.submitted = 1 	0.413058718438015
5887439	933	using max function on the resultset of count	select tid, count(tid) as count from klb_log_food_maps group by tid order by count desc limit 1; 	0.0216690419664189
5894508	35100	how to get the max version records?	select distinct t2.fid, t2.uid, t2.version from (     select fid, max(version) as "version"     from mytable     group by fid ) t1 inner join mytable t2 on (t1.fid = t2.fid and t1.version = t2.version) order by t2.fid, t2.uid 	0.000453250839555842
5896671	853	mysql - join a table twice with a main table	select `tbl_campaign`.id,  count(u.id) as num_all_campaign_users sum(u.cu_status) as num_sentcampaign_users,  count(u.id) - sum(u.cu_status) as num_unsent_campaign_users    from `tbl_campaign` c  left join tbl_campaign_user as u on (u.cu_campaign_id = c.campaign_id) where `tbl_campaign`.`campaign_id` = '19'   group by `tbl_campaign`.id 	0.0871935267937255
5898504	33496	what does insert(), delete(), select() and update() of the mybatis sqlsession interface return?	select() 	0.728750619374708
5899562	28547	merging multiple oracle queries to produce one result	select * from (select count(*) from tablea), (select count(*) from tableb), (select count(*) from tablec), (select count(*) from tabled); 	0.0141473810894285
5901205	29781	grouping mysql data	select url, group_concat(link_id)    from table1   group      by url; 	0.11852984227452
5903925	9951	mysql select based on two criteria	select t.max_id, t.product, pcl.date, pcl.change     from (select product, max(id) as max_id               from productchangelog                where change = 'price changed'               group by product) t         inner join productchangelog pcl             on t.max_id = pcl.id 	0.000373529997598496
5904372	5020	selecting from a table that contains: for each row in a different table call a table returning function	select *     from yourtable yt         cross apply dbo.yourtablefunction(yt.id) 	0
5909817	13131	how to convert two nvarchar rows into one when one of the row is null	select rtrim(ltrim(isnull(firstname ,'') + ' ' + isnull(lastname,''))) as name  from tablea 	0
5911625	39397	fetch count based on 2 different values in same table	select race,         count(case                 when outcome = 'win' then 1               end) as win,         count(case                 when outcome = 'loss' then 1               end) as loss  from   games  where  userid = x         and race in ( 'a', 'b', 'c' )  group  by race 	0
5912770	35067	select last 20 order by ascending - php/mysql	select * from (     select * from your_table order by id desc limit 20 ) tmp order by tmp.id asc 	8.09794745987834e-05
5914080	14180	postgresql: timestamp in the future	select now() + '30 days'::interval 	0.0146515758602099
5915318	32192	passing the result from one subquery to an in clause in another subquery in mysql	select *    from (@var:=group_concat(bar.id) as results                  from pivot_table                 where foo.id = x) t1          join (select count(*) c1, bar.id                  from table                 where bar.id in (@var)                 group by bar.id) t2 on t1.id = t2.id          join (select count(*) c2, bar.id                  from another_table                 where bar.id in (@var)                 group by bar.id) t3 on t1.id = t3.id 	0.0389270359566299
5916890	10459	composite primary key/foreign key headaches	select   count(*) as ticketcount,   ticketid from   ticket_instances as ti group by   ticketid 	0.550672263176476
5916972	12125	mysql: returning a count of objects matching all tags	select count(o.*) as numobjects     from objects o    where exists (select null                    from objectstags ot                     join tags t on t.id = ot.tag_id                               and t.name in ('tag1','tag2')                   where ot.object_id = o.id) 	0.000156581135566353
5917277	179	utility to create sql statements	select * from information_schema.columns where table_catalog = <my-db-name>   and table_schema  = <table-owner-schema>   and table_name    = <table-name> order by ordinal_position 	0.787887005945266
5920374	29156	count the "ratio?" for wins and losses	select `gamedate`,    sum(case `p2param`          when 'a' then case p1outcome when 'win' then 1 else -1 end          else 0        end) as a_ratio,    sum(case `p2param`          when 'b' then case p1outcome when 'win' then 1 else -1 end          else 0        end) as b_ratio from games where `p2param` in ( 'a', 'b', 'c' )  group by gamedate 	0.0257042302650146
5920917	14117	mysql group by subkey but if new read if not 1 show 0	select tod.username as touser, fromd.username as fromuser, msg.* from         ( select distinct touserid, subkey        from usermessages        where touserid = 'insert_your_id_here'        and deleted=0 ) msgg join usermessages msg on msg.id = ( select msgu.id               from usermessages msgu               where msgu.touserid = msgg.touserid               and msgu.subkey = msgg.subkey               and deleted=0               order by msgu.read asc, msgu.created desc               limit 1 ) join users fromd on msg.fromuserid = fromd.id join users tod on msg.touserid = tod.id 	0.104655547721962
5922867	6268	finding similarity between users in telecomunication network	select c1.userid as user1, c2.userid as user2   from callinglist as c1   join callinglist as c2 on c1.phonenumber = c2.phonenumber  where c1.userid < c2.userid  group by c1.userid, c2.userid having count(*) >= 3 	0.011567750340487
5925338	15824	sql: how to return an non-existing row?	select * from (select color_id, parent_id, language_id, name, 1 as order_rank  from some_table  where parent_id = %parent_id% and language_id = %language_id%  union  select null, %parent_id%, %language_id%, null, 2 as order_rank ) order by order_rank limit 1 	0.00640056322393453
5925804	19461	retrieving records from design containing multiple hierarchy	select types.id, coalesce(subtype1.name, type2.name, type3.name) as name,   coalesce(subtype2.description, type1.description, type2.description) as description,   ... from types   left join subtype1 on (types.id = subtype1.id)   left join subtype2 on (types.id = subtype2.id)   ...  where ... order by types.insert_date; 	0.00046273319300218
5926364	38140	count multiple in one statement	select   a.trigger_type_code,   c.trigger_name,   count(month(b.created_date) < 5 or null) as before_the_month,   count(month(b.created_date) = 5 or null) as in_the_month from issue_trigger a    inner join cs_issue b     on b.issue_id = a.issue_id   inner join ref_trigger_type c     on c.trigger_type_code = a.trigger_type_code where year(b.created_date) = 2011 group by a.trigger_type_code, c.trigger_name 	0.0584037086683842
5926500	18063	search mysql database for a html link using php	select mytable.item_id from mytable where mytable.link not like '%</a>%' 	0.140944220731572
5932147	1896	how to concat columns in android sqlite	select columna || columnb as columnc from table 	0.115891451944014
5933905	11062	problem in setstring method.in retrieving data from the table	select * from course where course_id = (select course_id from table1  where user_name=?); 	0.00592732626943829
5933931	35656	database friends list structure and query	select p.display_pic, f.*  from friends f inner join profiles p on p.user_id = f.user_id  where f.friend_id = 1     union select p.display_pic, f.*  from friends f inner join profiles p on p.user_id = f.friend_id  where f.user_id = 1 	0.0141413974667
5937523	32935	how do i return a field in mysql from a sub-query linked to the main query results?	select wp1.*, wp2.*  from wp_postmeta wp1, wp_postmeta wp2  where wp2.post_id in (1,2,3)  and wp1.meta_value = wp2.post_id and wp2.meta_key = '_wp_attached_file'; 	0.0074878903601427
5939079	5967	returning distinct rows from database query	select max(a.group_leader), b.forum_name       from flightuser_group a     inner join flightacl_groups c on a.group_id = c.group_id       join flightforums b on c.forum_id = b.forum_id         where a.user_id = '60'      group by  b.forum_name       order by a.group_leader desc 	0.00510609547603005
5939559	2082	mysql-query to get articles with only the chosen language	select a.* from (select article_id,language_id,count(article_id) as languages_count from article_languages group by article_id) as al left join articles as a on al.article_id = a.id where al.languages_count = 1; 	0.000261877551054335
5939940	35966	using "not in" statement in sql for a duplicated key	select distinct room_type_id, room_id from room r where not exists (         select *         from hotel_reservation h         where     (     @datestart between h.bookingstart and h.bookingend     or @dateend between h.bookingstart and h.bookingend     or h.bookingstart between @datestart and @dateend       or h.bookingend between @datestart and @dateend     )     and       h.hotel_id = r.hotel_id and h.room_id = r.room_id )  and  r.hotel_id = @hotel_id 	0.329456288025558
5940839	1119	sql return first day of last month and current month @ 00:00:00	select    dateadd(month, datediff(month, 0, getdate())-1, 0),    dateadd(month, datediff(month, 0, getdate()), 0) 	0
5941809	22220	include headers when using select into outfile?	select 'colname1', 'colname2', 'colname3' union all select colname1, colname2, colname3     from yourtable     into outfile '/path/outfile' 	0.128405247596626
5942117	302	how to take the top 10 results of a union in sql?	select top 10 * from ( select a_object_id as [id],      a_object_name as [name],     'a_object' as [type] from [database].[dbo].[table_a] where a_object_name like @search + '%' union all select b_object_id as [id],      b_object_name as [name],     'b_object' as [type] from [database].[dbo].[table_b] where b_object_name like @search + '%' ) x order by [name] 	0.000102057357728717
5942206	23116	get last record of each record group	select m.user_id, m.username     , n... from members as m     join    (             select user_id, max( notification_id ) as notification_id             from notifications              group by user_id             ) as userlastnotification         on userlastnotification.user_id = m.user_id     join notifications as n         on n.notification_id = userlastnotification.notification_id where n.private_message = 1     and n.reply_id = 0 order by n.has_replied, n.notification_date desc 	0
5942210	16216	sql server query to group records	select feed, sum(count) as total from posttable where cast(dateinserted as date) = cast(getdate()-1 as date) and feed in ('box1', 'box3', 'box4') group by feed 	0.132472776559925
5942774	40112	mysql query: selecting rows of linked tables and catching a "bigger" dataset	select a2.name, b.title     from a         inner join linktable lt             on a.id = lt.a_id         inner join b             on lt.b_id = b.id         inner join linktable lt2             on lt.b_id = lt2.b_id         inner join a a2             on lt2.a_id = a2.id     where a.name = 'douglas adams'     order by b.title,              case when a2.name = 'douglas adams' then 1 else 2 end,              a2.name 	0.000584889210542722
5942974	34524	returning count from database table joined with another table	select t.name,        (select count(*)from comments c where c.titleid=t.id)as numcomments   from titles t 	0.000105425027398519
5943265	4454	generate get next unique number from mysql id	select (a.extention + 1) as avail  from admin_users a left join admin_users b on ( (a.extention + 1) = b.extention ) where a.extention >= 105 and b.extention is null order by avail asc  limit 1 	0
5944681	15317	in an sql xquery result set, is there a way to make the "value" operator return null on missing elements?	select n.value('stringvalue[1]', 'varchar(100)') as stringvalue,        n.value('intvalue[1]', 'int') as intvalue,        n.value('@attrval', 'varchar(100)') as attrval from @val.nodes(' 	0.0231245211935969
5945460	27983	how to get one common value from database using union	select line_item_id,sid,price_1,part_number from ( (select line_item_id,sid,price_1,part_number from table where sid = 2)  union  (select line_item_id,sid,price_1,part_number from table  sid = 1 and line_item_id not in (select line_item_id,sid,price_1,part_number from table  sid = 2))) 	0
5945604	39900	sql query to fetch 3rd lowest value	select emp_salary from emp_salary group by emp_salary order by emp_salary limit 1 offset 2; 	0.000908722780243473
5945735	32540	retrieving n'th record	select top 1 salary from ( select distinct top n salary from employee order by salary desc) a order by salary where n > 1 (n is always greater than one) 	0.000545271465518227
5945843	31716	are any permissions required to backup a mysql table through php script	select * from tablename into outfile 'backupfile.sql'; 	0.194249632612784
5947025	21057	how can i alter a field from bigint to character varying in postgresql?	select 1::bigint::text::varchar; 	0.0153030441148099
5947765	14027	mysql natural sorting	select id,name,ip,convert(substring(name from 4),unsigned integer) num order by num; 	0.716842210908129
5948741	37516	get numerical value as a percentage of total of all rows	select pageviews * 100 / (select sum(pageviews) from table) from table where page_id = 42 	0
5949402	19054	sql-query: see relationship between array of users and groups	select g.groupname,     case         when count(ug.userid) = (select count(*) from users) then 'yes'         when count(ug.userid) = 0 then 'no'         else 'someare'     end as howmany from groups g join usergroups ug on g.id = ug.groupid group by g.groupname 	0.000443458218550059
5949995	31581	how can i access last record's previous record im mysql?	select *     from table order by contractid desc    limit 1,1 	6.37923887024744e-05
5951466	460	select contracts that are only in the notification period or are expired	select *  from contracts  where getdate() > dateadd(day,-1*daysinadvance,expirationdate)  or expirationdate < getdate() 	0.000145198186357189
5952309	11100	ordering a top ten query	select  u.*, count(vote_id) as votes_count from    users u left join         votes v on      v.receiver_user_id = u.user_id group by         u.user_id order by         votes_count desc 	0.0636613214516648
5953330	40970	how do i map the id in sys.extended_properties to an object name	select object_name([major_id]), [name], [value] from sys.extended_properties 	0.00696854590976691
5953469	38647	how to join counts of 3  different tables and grouping them with a common column name in all 3 tables	select      list.packname,      isnull(a.acnt, 0) as tblacount,      isnull(b.bcnt, 0) as tblbcount,      isnull(c.ccnt, 0) as tblccount from     (     select packname from tbla     union     select packname from tblb     union     select packname from tblc     ) list     left join     (     select tbla.packname as ptype, count(*) as acnt from tbla     group by tbla.packname     ) a on list.packname = a.ptype     left join     (     select tblb.packname as ptype, count(*) as bcnt from tblb     group by tblb.packname     ) b on list.packname = b.ptype     left join     (     select tblc.packname as ptype, count(*) as ccnt from tblc     group by tblc.packname     ) c on list.packname = c.ptype 	0
5954565	18618	single query to get data from 3 separate tables based on provided timestamp	select t1.data, t2.data, t3.data from table1 t1, table2 t2, table3 t3 where t1.pid = t2.pid and t1.link1 = t3.link1 and greatest(t1.created,t2.created,t3.created) < 'your-formatted-time' order by greatest(t1.created,t2.created,t3.created) desc; 	0
5954772	20531	number of rows returned in mysql/codeigniter (not affected by limit clause)	select sql_calc_found_rows * from table .... limit x; select found_rows(); 	0.00730072752271604
5955373	13198	t-sql if statements in order by clauses	select     * from     table order by     case when @sorttype = id then table.id end asc,     case when @sorttype != id then table.date end asc 	0.73192960010848
5957831	1951	oracle range and subquery	select a.* from schedule a where user_id = 0   and not exists (     select null       from schedule b       where b.user_id = 123456         and b.start_date <= a.end_date         and b.end_date >= a.start_date   ) 	0.20228805447962
5958602	33529	sql - select the most frequency item	select name from table_name group by name order by count(*) desc limit 1; 	0.000159808732488955
5959345	22804	join two identical tables on rows with different values	select n.item_id   from new_items n  where exists (select null                  from old_items o                 where o.item_id = n.item_id                   and (o.price <> n.price                    or o.description <> n.description                     or o.description_long <> n.description_long                     or o.image_small <> n.image_small                     or o.image_large <> n.image_large                     or o.image_logo1 <> n.image_logo1)) 	0
5960620	38066	convert text into number in mysql query	select field,convert(substring_index(field,'-',-1),unsigned integer) as num from table order by num; 	0.0151858078519052
5962612	11	do table hints apply to all tables or only the preceding table?	select * from tablea with (nolock), tableb with (nolock) 	0.000263081103636317
5963494	35826	php sql check inactive users	select username from users where datediff(now(),last_access)>90 	0.110504158911405
5964705	12434	mysql sum query	select * from ( select type as type,  count(*) as cnt  from $tbl_name  group by type with rollup) as inner_table order by cnt desc; 	0.344013761484802
5964780	2540	access query: group get latest	select field1, max(instance) 	0.00879794367217019
5965575	38429	check whether the schedule overlaps between days	select  * from intervals where  ( ( dbo.timeonly(last) > dbo.timeonly(first) and not (dbo.timeonly(last) < @start or  @end < dbo.timeonly(first)) ) or ( dbo.timeonly(last) < dbo.timeonly(first) and ( @start >= dbo.timeonly(first) or @end <= dbo.timeonly(last) or (@start < dbo.timeonly(first) and @end > dbo.timeonly(last)) ) ) ) 	0
5965713	32445	selecting count(id) and total in one sql query	select user_id, count(id) n_items from items group by user_id with rollup 	0.00058447390887245
5967130	7959	mysql select one column distinct, with corresponding other columns	select id, firstname, lastname from table group by(firstname) 	0
5967426	15126	select day of week from date	select * from mytable where month(event_date) = 5 and dayofweek(event_date) = 7; 	0
5968349	28316	how can i compare the trimmed and untrimmed lengths of fields without retyping the field name?	select     'select * from ' + o.name + ' where datalength(' + c.name + ') > datalength(rtrim(' + c.name + '))' from     sys.objects o inner join sys.columns c on     c.object_id = o.object_id and     c.system_type_id = 167 where     o.name = 'tablename' 	6.80555323458175e-05
5969663	2532	get earliest date for each id	select t1.id,         min(tbls.date)  from   table1 t1         inner join (select id,                            date                     from   tableprt                     union all                    select id,                            date                     from   tableonl                     union all                    select id,                            date                     from   tablesrv) tbls           on t1.id = tbls.id  group  by t1.id 	0
5970058	29644	first child in xml document using sqlxml	select @x.query('(/a/*[1])') 	0.00159946604266753
5971267	37649	sql how to do a conditional sum by distinct id?	select date, sum(cost) from    (select distinct date, id, cost from yourtable) group by date 	0.0231024014427746
5971434	6154	limit query results to two rows per group	select date(from_unixtime(mytimestamp)) as fordate, * from   mypoststable where  2 >= (     select count(*)     from   mypoststable as lookup     where  date(from_unixtime(lookup.mytimestamp)) = date(from_unixtime(mypoststable.mytimestamp))     and    lookup.mytimestamp >= mypoststable.mytimestamp ) 	0.000599307258428241
5972389	27432	joining two tables and overwriting one colum	select a.id, a.name, a.desc, case b.isempty                 when 1 then 1                 else a.isempty                 end case as isempty  from table2 a left join table1 b on a.id=b.id 	0.000451678491670516
5973214	11416	negation with match against	select    * from    member where    not match (state) against ('+rajasthan' in boolean mode) 	0.514977565947751
5973521	40323	how to extract latest record	select   a.item, a.location, a.code, size = b1.att_value, grade = b2.att_value from   [table a] a   inner join (select max(atr_no) from [table b] group by item) i on i.item = a.item   inner join [table b] b1 on b1.atr_no = i.atr_no and b1.att_id = 'size'   inner join [table b] b2 on b2.atr_no = i.atr_no and b2.att_id = 'grade' order by   a.item 	9.45622178291551e-05
5974086	27992	sql query sort by in groups	select ... from products_description a     join products b         on a.products_id=b.products_id where b.products_status >0     and a.products_name like '%".$q."%' order by case when products_quantity = 0 then 1 else 0 end asc     ,  a.products_name asc limit 10 	0.0963019102218815
5974636	32889	count query in sql	select a.category_name, count(b.incident_id) number_of_faults from maincategory a join incident b on a.category_id = b.category_id group by a.category_name 	0.411032898746839
5974931	21746	players current rank	select * from     (select @rownum:=@rownum+1 ‘rank’, your_query from your_table, (select @rownum:=0) r) e  where user_id = 1; 	0.00327286710890968
5976686	3671	organizing query results into groups using the group by clause	select pub_id, type, max(price) from mytable group by pub_id, type 	0.186222029693442
5978678	31850	select number groups in query	select t.range as score, count(*) as total_users from  (        select case when score between 12 and 15 then '12 to 15'                      when score between 8 and 11 then '8 to 11'                  when score between 5 and 7 then '5 to 7'                     when score < 5 then 'less than 5'             end as range        from scores) t  group by t.range 	0.0103314597951989
5979098	21200	how to multiple join the same table?	select isnull(l1.locationname,'') as locationfrom, isnull(l2.locationname,'') as locationto, c.duration  from connection c  left outer join location l1 on l1.locationid= c.locationidfrom left outer join location l2 on l2.locationid= c.locationidto 	0.00331673907375199
5979779	33047	how can i count the number of items that where inserted at given time intervall to the db?	select hour(timestamp) as interval, count(*) from data group by interval; 	0
5980116	18674	mysql 5 table select query	select g.*, b.* from users u  left join band_users bu on u.id = bu.uid  left join bands b on bu.bid = b.id  left join bands_gigs bg on b.id = bg.bid  left join gigs g on bg.gid = g.id where u.id = 1 	0.0437531986461661
5981162	19191	list of users and roles that have permissions to an object (table) in sql	select permission_name, state_desc, type_desc, u.name, object_name(major_id)  from sys.database_permissions p  join sys.tables t on p.major_id = t.object_id  join sysusers u on u.uid = p.grantee_principal_id 	5.58740779781773e-05
5982174	41289	postgresql: select returning array	select array[$1, friend_id] from tbl_temp where id = any($2) 	0.239609917684365
5983138	14648	list of all tables in database	select [name] from sys.tables 	0.000468800548767334
5985784	8895	gridview with multiple tables?	select [subid], [custname], [broname], [entity]  from [customer]  join [broker] on <join condition>  join [submission] on <join condition> 	0.11040229558986
5987042	9779	how do you efficiently trim an sqlite database down to a given file size?	select count(*) from log_message 	0.0104822119795209
5987529	2330	mysql: get one row for each item in the in clause efficiently	select  `books`.`id`,  `books`.`name`  from `books`   inner join (     select max(book_id), author_id     from `books_authors`     group by author_id) ba on `books`.`id` = ba.`book_id` where ba.author_id in (8, 12) 	0
5988179	32536	mysql group by date - how to return results when no rows	select date(d.`thedate`), count(`id`) from `datetable` d left join `blogs` b on b.`posted` = d.`thedate` where `status` = 'active'      && d.`thedate` between `2011-01-01` and `2011-05-01`      group by date(d.`thedate`) 	0.0014548776253401
5989387	37403	set variable to null if nested query returns no results	select @sampleid = [sampleid] from [sample] where [identifyingnumber] = @sample_identifyingnumber 	0.671879058055746
5990439	15399	query for counting column with datatype bit	select      count(field) as tot_true,      count(*)-count(field) as tot_false from table where field=1 	0.119575206972183
5990586	3878	mulitply 2 values from 2 different tables	select total_amount * exchange_rate as value  from transactions, rates  where rates.currency_name = 'sek' and transaction_id = 001 	0
5992673	7022	get current record for a subquery in t-sql	select  dbo.table_1.*,     case when count(dbo.table_2.id) = 0 then         0     else         1     end     as hasexception from         dbo.table_1 left outer join                       dbo.table_2 on dbo.table_1.id = dbo.table_2.id group by dbo.table_1.id 	0.000504337750535592
5994324	36979	how to get available space in tablespace for a user (oracle)	select   ts.tablespace_name,   to_char(sum(nvl(fs.bytes,0))/1024/1024, '99,999,990.99') as mb_free from   user_free_space fs,   user_tablespaces ts,   user_users us where   fs.tablespace_name(+)   = ts.tablespace_name and ts.tablespace_name(+) = us.default_tablespace group by   ts.tablespace_name; 	0.00781371957858998
5994478	15360	cannot add or update a child row: a foreign key constraint fails	select *  from ninikske_bioldb.experiment where probe_genomicpos = ?   and samplename = '?'   and probeid = ? 	0.000139576708353417
5994485	4696	is it possible to rename a joined column during an inner join?	select d.name as dogname, o.name from dog d inner join owner o on d.ownerid = o.ownerid 	0.0938492705834563
5994660	21004	oracle permissions	select atp.grantor, atp.privilege,        case when nvl(rtp.role,'null') <> atp.grantee then atp.grantee             else atp.grantee||' (role)'        end grantee, atp.table_name   from all_tab_privs atp left join role_tab_privs rtp                           on (atp.table_name = rtp.table_name and                               atp.table_schema = rtp.owner)  where grantor <> 'sys' union all select owner, 'select' , null, view_name||' (view)'   from all_views  where owner <> 'sys' order by 1,3; 	0.431267119225455
5995198	34667	sql join to only one record in one to many relationship	select c.[clientid], max(u.[accessid])      from [tblclient] c          inner join [tbluser] u              on u.[id] = c.[userid]     group by c.[clientid] 	7.59689223933612e-05
5995256	22451	casting a double to a datetime type is off by 2 days?	select cast(0 as datetime) 	0.000870619269824985
5995438	34741	mysql query for crosstable select	select distinct t.* from   packages p        left join transactions t          on p.user_id = t.user_id        left join transactions t2          on t.user_id = t2.user_id where  ( t.package_id is null           or t.package_id = 0 )        and t2.package_id > 0 	0.685937760815648
5995781	18670	how to get each day's information using group by keyword in mysql	select activity_id, dayofweek(datetime) as day, avg(duration) as average from table_name  where datetime between start_date and end_date group by activity_id,dayofweek(datetime) 	0
5997684	35892	php mysql query out all the words, but not repeat	select item from cxt_20110105 union select item from cxt_20110106 	0.00771701038812848
5997690	26992	get lastest version of a content group sql	select c1.* from content c1   left join content c2 on c1.document_id = c2.document_id and c1.version < c2.version  where c2.document_id is null    and c1.id_project = 8 	0.00326472284082199
5999063	12154	sql query to find matches for multiple criteria	select person from permissions  where permission in (select permission from things where thing='eggplant') group by person having count(person) = (select count(permission)  from things where thing='eggplant') 	0.00869040051025016
6001030	611	select max id from current id mysql	select * from tablename where manager = 'y' and item_order = (select max(item_order) as parent                   from tablename                    where item_order < 5                    and manager =  'y') as t 	0
6001436	27031	joining 3 tables	select a.email,a.username,g.name from cs_accounts a inner join cs_permissions p on p.user_id = a.id inner join cs_groups g on g.id = p.group_id where g.low_limit > 70 and g.high_limt < 120 	0.0397175620179167
6001992	41136	sql/mysql: common design of row number/index/offest for pagination	select count(*) from table where create_date <= (select create_date from table where id = 45); select table.* from table order by create_date limit 5 offset :offset; 	0.00760228662975539
6004872	9019	filtering a selected column in sql	select userid1 as relateduserid from user_user where userid2 = xid     union select userid2 from user_user where userid1 = xid 	0.0342119767385085
6007774	24075	make blank row appear 0 in ms sql	select remarksdisplay = case remarks when '' then '0' else remarks end from tablename; 	0.149077962900602
6009403	33308	select from the same table for two different values (mysql)	select      forum_topics.primkey,     forum_topics.title,     forum_topics.creatorid,      forum_topics.last_reply_poster,      users.username,     users.avatar,     u2.username,     u2.avatar,     forum_tracks.lastmark  from      users,     users as u2,     forum_topics      left join forum_tracks          on forum_tracks.userid='".$_session['loggeduserkey']."'          and forum_tracks.topic_id=forum_topics.primkey  where      forum_topics.cat_id='".$forum_id."'      and users.userkey=forum_topics.creatorid     and u2.userkey=forum_topics.last_reply_poster order by ...; 	0
6011161	24977	mysql, how to find last id of inserted row before the given id for a specific query	select * from table where rowid < (select rowid from table where userid=24) order by rowid desc limit 1 	0
6012659	20640	how do i return results from multiple queries (that have been looped) in one table?	select * into temporary resulttbl from locations where 1 = 2 ... loop     insert into resulttbl select ... end loop ... return query select * from resulttbl 	0
6015636	15615	extract selective records	select     customer,      invoiceno,      type,      decode(type, 'misc', 0, 1) * amount as sales_amt,      decode(type, 'misc', 1, 0) * amount as misc from     tablea ; 	0.00325582609311916
6016132	11272	check if column exists when there are multiple tables with same name in different schemas (psql 8.2)	select *  from information_schema.columns where table_catalog = 'sandbox' and table_schema = 'public' and table_name = 'calendar' and column_name = 'iso_year'; 	0.000311020063336894
6016525	1215	query in sqlite with dates	select * from tablename where strftime('%y', datecreated) = '2011'                            and strftime('%m', datecreated) = '5'; 	0.194839507816109
6017091	19265	return a string from a sub query	select      case          when committed_date >= '01/04/2011' then 'y'          else 'n'      end as current_ytd from yourtable 	0.0311364808727613
6017456	19319	how to display data from a db when rows and columns are inverted	select    id,   group_concat(if(fieldname='name', field_value, null)) as 'name',    group_concat(if(fieldname='lat', field_value, null)) as 'lat',    group_concat(if(fieldname='long', field_value, null)) as 'long'  from table  group by id; 	0
6019170	16315	count and avg the number of records in mysql	select user, domain, count(page),     sum(if(page=1, 1, 0)) as page1,     sum(if(page=2, 1, 0)) as page2,     sum(if(page=3, 1, 0)) as page3 from table group by user, domain 	0.000285127215650372
6019185	29619	how to create a query to get all records from one table and fill in field information from a second table with a where statement?	select prem.meter_miu_id, jimsquerybycoll.*, prem.longitude, prem.latitude from prem left join jimsquerybycoll  on (prem.meter_miu_id = jimsquerybycoll.[miu id]  and jimsquerybycoll.collector="frederick road") 	0
6019360	11977	searching multiple rows in select with left join	select straight_join       p.*    from       ( select pt.product_id            from products_tags pt                    join tags on pt.tag_id = tags.id            where tags.name in ('test1', 'test2' )            group by pt.product_id            having count(*) = 2       ) prequery       join products on prequery.product_id = products.id 	0.261148377607302
6020391	37366	fastest way to find quotient by dividing two number	select ... whatever ... from table1 join table2 using (someid) where (table1.q / table2.d) % 10 = 4 	0.000533921503660333
6021115	35177	how can i display the most common value sequence in mysql?	select a, b, count(*) as freq from mytable group by a, b order by count(*) desc limit 1 	0
6021210	32011	filtering a select query to return only records that don't have a corresponding record in a joined table	select * from users where user_id not in(select user_id from group) 	0
6023831	37490	sql select rows that have higher timestamp value	select         t.code,        t.kind,        t.timestamp  from   table t         left join table t2           on t.code = t2.code              and t.kind = 'i'              and t2.kind = 'o'  where  t2.code is null 	0
6023918	16343	mysql query structure for searching two tables	select * from posts, meta m1, meta m2 where posts.id=m1.post_id and posts.id=m2.post_id and m1.name="date" and m1.content="2011-5-5" and m2.name="heading" and m2.content="my heading" 	0.070234291908522
6025149	21413	how do i create an array of data for 30 days from database table where some dates are not entered?	select timespan."day",           coalesce(num_uniq_ips, 0) as num_uniq_ips,           coalesce(num_records, 0) as num_records      from (select date_sub(current_date, interval i day) as "day"              from integers             where i < 30) timespan left join (select date(created_date) as "day",                   count(distinct ip) as num_uniq_ips,                   count(1) as num_records              from so6025149          group by 1) tallies           on timespan."day" = tallies."day"  order by timespan."day" asc; 	0
6025422	5717	how do i calculate the difference	select customer_balance, credit_limit, customer_balance - credit_limit as overage from your_table where customer_balance > credit_limit 	0.00361203805183081
6025705	20118	grouping sql results from a union	select followerid as reference_user, followeduserid as connection   from follows  where followerid = 1 union select followeduserid as reference_user, followerid as connection   from follows  where followeduserid = 1 group by reference_user; 	0.0565906846662272
6025768	29845	sql -- create column in select to test equality	select  staffid         , starttime         , endtime         , case           when starttime = endtime then 1           else  0         end as areequal from    tblschedule where   staffid = xxx 	0.169538365215589
6025968	21610	sql group by with limit and distinct - mysql	select sid,        (select text        from shouts        where shouts.sid = shoutbox_follower.sid        order by shouts.sid desc limit 1        ) as shout_text from shoutbox_follower where uid=5 	0.36923857105872
6027294	18568	sql query to check if a select operation returns rows	select count(*) from error_repository_bkp partition(part_maxval); 	0.0597537173460907
6027672	33571	mysql - conditionally add values from different tables?	select sum(case (select flag from table3)             when onlytable1 then t1.col            when onlytable2 then t2.col            else t1.col+t2.col end) from table1 as t1 join table2 as t2 	0.000100971341554424
6030275	20545	sql server get row closest (in the future) to today	select min(startdate) from itemstable where datediff(d, getdate(), startdate)>0     and datediff(d, startdate, @datetocheck)>=0 	0
6031063	8608	what is the most efficient / best practise to upsert 5000+ rows without merge in sql server?	select .. into #temp from (shredxml) begin tran update ... from where (matches using #temp) insert ... select ... from #temp where not exists commit 	0.0359722415779014
6031115	39180	locking a table within a transaction	select count(*) from table 	0.0809016300440251
6032691	7218	sql select from three tables	select mt.*, ut.name, ct.title from      map_table mt inner join      user_table ut on mt.from_user_id = ut.id left join       content_table ct on mt.content_id = ct.id where       mt.to_user_id = 1 	0.0112343282243883
6033622	12140	how can i count the number of rows returned by a mysql query?	select count(*) from (<your complete query here>) 	0.00013773226385703
6034488	2928	current executing procedure name	select object_name(@@procid) 	0.0489597618466
6034827	31231	count frequency of all items in tsql	select userid, count(*) from ninjatable group by userid order by count(*) desc 	0.000154064302987248
6037027	32808	mysql select qualification expiry dates	select u.username, max(case when testid = 1 then datetaken else null end) as a, max(case when testid = 2 then datetaken else null end) as b, max(case when testid = 3 then datetaken else null end) as c, max(case when testid = 4 then datetaken else null end) as d, max(case when testid = 5 then datetaken else null end) as e from users as u left join passes as p on u.userid = p.userid group by u.userid 	0.0433085823561326
6037755	33045	sql create a datetime value from year and quarter	select dateadd(day, -1,                         dateadd(year, @year-1900,                                           dateadd(quarter, @qq, 0)                                      )              ) 	5.47663331598755e-05
6037982	25927	db2 date conversion	select case month             when '1' then 'january'             when '2' then 'february'             when '3' then 'march'             when '4' then 'april'             ...       end+'-'+year from table 	0.238475785428775
6041347	33435	query construction combining union and least	select i.email, min(i.date_creation) from (select email, date_creation from emailcapture union all select email, date_creation from cpnc_user) as innertable i group by i.email 	0.745860288039946
6042160	6513	combine columns of sqlite3 select-statement	select (name || ', ' || firstname) as test from person; 	0.00597956669294967
6042347	30343	how to sort sql by other sql table?	select field1, field2, field3, etc...  from wp_posts inner join wp_term_relationships on wp_posts.id = wp_term.object_id where term_taxonomy_id=".$cat_id." order by menu_order 	0.00538670355335253
6044652	705	find mysql databases/tables, which are stored in innodb engine	select engine from information_schema.tables 	0.128853846253915
6044822	5478	can i check that two sub query return the same result without using stored procedure?	select otherobjid, active from mytable where objid = 1 except select otherobjid, active from mytable where objid = 54 	0.00571478323263129
6045873	18061	mysql join 2 tables - show all rows from one table	select a.id as stock, coalesce(b.quanitity,0), b.product_id, a.name as stock_fullname from a left join b   on a.id = b.stock_id   and b.product_id = 13 	0
6047675	18138	how to extract number which is of variable length from a string using substring?	select     substring(filepath, 1, charindex('_', filepath) - 1) from    tblfileinfo 	5.93901103072538e-05
6049131	30334	count unique users from db	select count(distinct user_id) from mytable where project_id = $myproject     and user_id != 3 	0.00058473687573965
6049359	23699	how to order recordset by no of occurences of a field value and sort by it	select t.* from transactions t order by (     select count(1) from transactions t2 where t2.ppno = t.ppno ) desc, t.ppno desc 	0
6050483	5423	what is the simplest way to enumerable tables, views and sps of a database	select * from information_schema.tables select * from information_schema.views select * from information_schema.routines 	0.602321958579104
6051213	30709	sql query for finding a column name where matching text is in column	select lexemeid,        case when lexeme.lexeme like '%apani%' then 'lexeme'             when lexeme.variant like '%apani%' then 'variant'             ...             when sense.example like '%apani%' then 'example'        end as columnname     from ... 	0.00212184730267632
6052881	15587	archiving large amounts of old data in sql server	select * into anewarchivetable from currenttable where somedatecolumn <= dateadd(year, -2, getdate()) 	0.123122999460879
6054829	27240	how to compare heights values	select *  from tbl_member  where     concat(format(left(height, 1), 0), lpad(format(substr(height,3,2), 0 ), 2, '0'))     between 308  and 700 	0.00639401643538416
6055405	22808	sql 2 table query problem	select  u.id, u.ad, count(b.id) as 'total'  from tblproducts u  left join tblbasvurular b on b.urunid=u.id  group by u.id,u.ad 	0.441768704514528
6055505	1209	blank spaces in column names with mysql	select * from `area one` 	0.0155048403048084
6055791	6821	how to show sequential number in mysql query result	select @rownum:=@rownum+1 no, foo, bar from table, (select @rownum:=0) r; 	0.00372386190276592
6056563	4401	order column by keyword	select * from tbldishes where foodanddrinks = 'e' order by case field_name when 'rabbit' then smth1 when 'apple' then smth2 ... else smth666  end 	0.289656770674713
6057066	25673	date format date-month-year	select convert(varchar,datecolumn,103) from yourtable 	0.0901825676094143
6057625	18153	if condition in select query	select case unsub when true then null else email end as email,.... from ... 	0.320182121647027
6062328	1368	mysql to php array grouping duplicate values	select   date,   sum(case answer when 'y' then count else 0 end) as totaly,   sum(case answer when 'n' then count else 0 end) as totaln,   sum(case category when 'cat1' then count else 0 end) as totalcat1,   sum(case category when 'cat2' then count else 0 end) as totalcat2,   sum(count) as totaloverall from subquery group by date 	0.00304817656044809
6064431	23575	how can i prevent duplicate rows being selected in a select query?	select      bbp.subcar "treadwell",       bbp.batch_id "batch id",       bcs.silicon "si",       bcs.sulphur "s",      bcs.manganese "mn",       bcs.phosphorus "p",       to_char(bcs.sample_time,'dd-mon-yy hh24:mi') "sample time",       to_char(bbp.start_pour, 'dd-mon-yy hh24:mi') "start pour time",      to_char(bbp.end_pour, 'dd-mon-yy hh24:mi') "end pour time",       bofcs.temperature "temperature" from       bof_chem_sample bcs,  inner join       bof_batch_pour bbp, on      bbp.batch_id=bcs.batch_id inner join      bof_celox_sample bofcs on      ** where       bcs.sample_code= to_char('d1') and       bcs.sample_time>=to_date('01-jan-10') 	0.00241484715520043
6065538	21862	mysql find all persons who have not had an appointment in six months or more	select clients.firstname, clients.lastname, groomappointments.gapmtdate from clients join groomappointments on clients.clientid = groomappointments.gapmtclient where clients.clientid in (   select gapmtclient from groomappointments   group by gapmtclient   where date_sub(curdate(), interval 6 month) > gapmtdate ) 	0
6065754	26458	sql statement order by maximum of entries	select * from (     select user_id, report_post, count(*) as cnt     from reports     group by report_post ) c order by cnt desc 	0.000749062592419977
6065884	17450	what query do i run to select the highest value for each group of values in an sql table?	select bid_for_auction, max(bid_price) as bid_price from bids group by bid_for_auction; 	0
6065972	18581	how to select part of the string with t-sql?	select id,         substring(items,0,charindex(',',items)),        values  from mytable 	0.0110041971946517
6066097	3857	when selecting everything from mysql can i rename specific fields and still select everything else as is with the *	select *, prof.id as youth_id from time time, profiles prof 	0.00222593926885891
6067083	8777	oracle/sql - grouping items by action by day over time	select widget, to_char(timestamp_,'yyyy-mm-dd'), count(widget) from widget where timestamp_ between to_date('yyyy-mm-dd hh24:mi:ss','%date1%') and to_date('yyyy-mm-dd hh24:mi:ss','%date2%') and action like 'reject' group by widget, to_char(timestamp_,'yyyy-mm-dd') having count(widget) > 1; 	0.000219928504469575
6069933	9917	search query - postcode, company name or location	select distinct c.* from company c join postcode_areas p on p.company_id = c.company_id where c.name like <input> or c.location like <input> or p.postcode like <input> 	0.147687686119815
6070525	17850	mysql query. extracting sum(total) and sum(total) with a condition	select  users.full_name         ,sum(total)         ,sum(case when service < 49 then total else 0 end) as productive from    time_report         , users where   time_report.user = users.user_id         and date between '2011-0502' and '2011-05-11' group by          user 	0.382636448838188
6071816	3986	sqlite - return sorted list	select *   from table  where id in (478,278,190,890,123)  order by case id when 478 then 0                   when 278 then 1                   when 190 then 2                   when 890 then 3                   when 123 then 4           end 	0.00301898257085113
6073577	6784	sorting and calculating by dates in joined query	select     r.resource_id,     r.resource_url,     count(*) from     visitor_resources vr inner join resources r on r.resource_id = vr.resource_id inner join resource_tags rt on rt.resource_id = r.resource_id inner join tags t on     t.tag_id = rt.tag_id and     t.tag_name = '42' where     vr.last_visited between <start of month> and <end of month> group by     r.resource_id,     r.resource_url order by     count(*) desc limit 5 	0.0149479160193894
6074480	16515	year, month, and day parameters describe an un-representable datetime how to ignore	select case convert([updated date], sql_char)  when '0000-00-00' then null  else [updated date] end  as [updated date] from fingerscans 	7.96505106659715e-05
6074888	30116	find all records until this time - mysql	select * from table where datetimecolumn between date(now()) and current_timestamp() 	0.000302787204681
6075888	24446	trying to join tables using datetime fields	select distinct a.tripid as 'id',        a.currdate,        a.groupid,        a.useremail as 'user',        a.routeid as route',        b.patternnum from sometable a join tblmoehistory b on a.groupid = b.groupid      and b.timestamp = (select min(timestamp)                          from tblmoehistory                          where groupid = a.groupid                          and timestamp > a.currdate) 	0.0822549856617421
6077998	28695	problem in php when joining tables having columns with the same name	select table1.name as name1 	0.00590539942596908
6078169	12784	mysql retrieve count of pairs	select count(*) from mytable a   join mytable b     on a.id_to = b.id_from     and a.id_from = b.id_to where a.id_from = 1000 ; 	0.000501606466776403
6078429	10878	use columns from a previously referenced table in a query as parameter values for a udf...? doesn't work?	select     * from     mtfirsttable t cross apply     myudf(t.somesolumn, t.someothercolumn) u where     t.somecolumn = u.somecolumn and      t.someothercolumn = u.someothercolumn 	0.241006557488197
6078738	25369	sql query to count ids with exactly 91 duplicates	select userid from mytable group by userid having count(*) = 91 	0.00807842734033725
6080534	8738	how to select multiple values from single column with multiple tables in mysql?	select table1.name from table1  join table2 t1_link on table1.id = t1_link.table1_id join table3 t1_data on t1_link.table3_id = t1_data.id and t1_data.title in ('blue', 'orange') join table2 t2_link on table1.id = t2_link.table1_id join table3 t2_data on t2_link.table3_id = t2_data.id and t2_data.title in ('green', 'black') 	0
6080662	26278	strip last two characters of a column in mysql	select  that_column, substring(that_column, 1, char_length(that_column) - 2) as that_column_trimmed from that_table 	0
6080935	41158	how to fetch rows by descending order by appears number?	select t1.col from table as t1 inner join ( select col,count(col) as num from table  group by col) as t2 on t1.col = t2.col order by t2.num desc 	0
6081316	11264	math in mysql/php	select userid, (upvoteds - downvoteds) / (aposts - aselecteds) as result from table     order by result desc 	0.755077299575017
6081436	17318	how to use alias as field in mysql	select col1 ,      col1 + field3 as col3  from   (        select  field1 + field2 as col1        ,       field3        from    core        ) as subqueryalias 	0.518298043300212
6084192	40423	perform operation on generic list	selectedlist.where(m=>m.startswith("as"));  selectedlist.orderby(m=>m.firstname); 	0.748438225192438
6085258	23497	mysql - i don't want multiple records on a join	select count(e.event_id) as count_events,        sum(num_attendees) as sum_attentees,        sum(tickets_sold) as sum_tickets_sold  from events e  where e.event_id in       (select distinct event_id from singers where singer in ("bob", "jane")); 	0.00713838269688355
6085443	17408	can i resuse a calculated field in a select query?	select      @total_sale := s.f1 + s.f2 as total_sale,      s.f1 / @total_sale as f1_percent from sales s 	0.0678447490346975
6085750	1296	subquery returning multiple columns - or a close approximation	select   user_id   max(add_posts) as add_posts,   max(remove_posts) as remove_posts,   max(modify_users) as modify_users,   max(add_users) as add_users,   max(delete_users) as delete_users from ( select    ug.user_id   max(g.add_posts) as add_posts,   max(g.remove_posts) as remove_posts,   max(g.modify_users) as modify_users,   max(g.add_users) as add_users,   max(g.delete_users) as delete_users from   groups g inner join   users_groups ug on g.group_id = ug.group_id group by       ug.user_id union select   user_id     max(add_posts) as add_posts,   max(remove_posts) as remove_posts,   max(modify_users) as modify_users,   max(add_users) as add_users,   max(delete_users) as delete_users from    user_rights group by   user_id ) as combined_user_groups group by   user_id 	0.784526134694652
6087140	11940	sql query for finding checkins from friends	select   l.id,   l.name,   c.name as cat,   c.icon as caticon,   count(case u.gender when 'm' then 1 end) as male,   count(case u.gender when 'f' then 1 end) as female,   count(f.user_id) as friends from locations l   inner join categories c on c.id = l.category_id   inner join checkins ch on ch.location_id = l.id   inner join users u on u.id = ch.user_id   left join friendships f on f.user_id = @user_id and f.friend_id = ch.user_id                           or f.user_id = ch.user_id and f.friend_id = @user_id where l.id = @location_id group by l.id, l.name, c.name, c.icon 	0.00336295452198419
6089960	10534	mysql query to select data from last week?	select id from tbl where date >= curdate() - interval dayofweek(curdate())+6 day and date < curdate() - interval dayofweek(curdate())-1 day 	0
6092588	3692	convert varchar to float if isnumeric	select case isnumeric(qty) when 1 then cast(qty as float) else null end 	0.248580340091669
6092955	23887	retrieving data from joined mysql tables using an avg in the where clause?	select metrics.*,companies.company_name,companies.permalink from (select company_id,avg(company_unique_visitors) as met_avg       from company_metrics      where `date` between date_sub(now(), interval 4 month) and now()   group by company_id having met_avg>2000) as metrics left join companies on companies.company_id=metrics.company_id 	0.00465030759244271
6093282	40340	how to seperate last name and first names into two new columns in mysql?	select replace('john & anna smith', substring_index('john & anna smith', ' ', -1),'') as first_name, substring_index('john & anna smith', ' ', -1) as last_name; 	0
6094504	20096	sql query to get count of each fileid entry in table	select fieldid, count(id) as count from tag group by fieldid 	0
6096654	13118	selecting most recent row, per user	select max(time_stamp), user_id from table group by user_id; 	0
6097806	34375	sql-function to get lines including a certain date	select * from table where getdate() between begin-date and end-date 	0
6098559	38791	sql - where condition for each column	select "user",     sum(case when type='credit' then amount end) as credit,     sum(case when type='debit' then amount end) as debit from     "table" group by     "user" 	0.00353849463197361
6098900	12739	sql statement to get the date next 2 days from now	select *  from guest g inner join reservation r on g.nric = r.guestnric  where arrivaldate = date(date_add(now(), interval +2 day)) 	0
6099112	37244	need a nested sql query which takes the count from the first query and calculate a new count	select numberoftags, count( fileid ) as numberoffiles from (   select `fileid` as fileid, count( fileid ) as numberoftags   from `tag`   group by `fileid`   ) as rows group by numberoftags 	0.000795668523544677
6099565	12769	computed columns or store	select * 	0.0247086019637433
6100794	36987	accessing child nodes in sqlxml columns with xquery	select  distinct  cref.value('(text())[1]', 'varchar(50)') as cat from          sgis cross apply        data.nodes('/test/result') as results(rref) cross apply       rref.nodes('data[@elementname = ''cat'']') as categories(cref) 	0.00139987953953026
6100921	8837	numeric result blank for t-sql union	select product, price from tablea union all select '', sum(price) from tableb union all select 'space', null from tablec 	0.366346401688066
6101832	31903	pull smallest value	select id, min(price) from t where price > 0 group by id; 	0.00243336187703355
6102198	28680	what formula is used for building a list of related items in a tag-based system?	select pt.widgetid, count(*) as commontags, ps.otherorderingcriteria1, ps.otherorderingcriteria2, ps.otherorderingcriteria3, ps.date from widgettags pt inner join widgetstatistics ps on pt.widgetid = ps.widgetid     where pt.tagid in (select ptinner.tagid from widgettags ptinner where ptinner.widgetid = @widgetid)     and pt.widgetid != @widgetid group by pt.widgetid, ps.otherorderingcriteria1, ps.otherorderingcriteria2, ps.otherorderingcriteria3, ps.date order by commontags desc, ps.otherorderingcriteria1 desc, ps.otherorderingcriteria2 desc, ps.otherorderingcriteria3 desc, ps.date desc, pt.widgetid desc 	0.180271085258942
6103741	3620	sum of calculated field	select t1.a, t2.d*t2.f as m, sum(t2.d*t2.f) from table1 as t1, table2 as t2  where t1.a=t2.a group by t1.b 	0.0078664460731151
6104727	16212	oracle sql - problem displaying using the foreign key	select p.prod_id, p.product_name, s.date_of_sale from  products p    ,  sales    s where s.prod_id(+) = p.prod_id   ; 	0.0762625938817592
6105047	9968	how to limit a join to one result per record, in order for mysql	select title, url, media_file from ".px."objects left join     ( select m1.media_id, m1.media_ref_id, m1.media_file, m1.media_order     from ".px."media as m1     left join ".px."media as m2 on m1.media_ref_id = m2.media_ref_id and m1.media_order    > m2.media_order     where m2.media_ref_id is null             ) maxmedia on ndxz_objects.id = maxmedia.media_ref_id where `status` = 1 and `section_id` = 2 order by `ord` 	0.000178457632385617
6105128	3420	how can i query only ids 3, 4, 5 and 1?	select id, name from categ where email_activated='1' and id in (1, 3, 4, 5) order by id desc 	0.000127107652909466
6105151	10062	calculating distance between 2 points with sql	select <replace with your select>, 3963.0 * acos (     sin(substring(x, 1, 2)/57.2958) * sin(" + axisx + "/57.2958) + cos(substring(x, 1, 2)/57.2958) * cos(" + axisx + "/57.2958) * cos(" + axisy + "/57.2958 - substring(y, 1, 2)/57.2958)) as distance  from house order by distance 	0.0128451422919047
6105514	36316	a counting problem	select count(distinct t.user_id)     from your_table t    where t.time_stamp = 0 group by t.activity 	0.445338543545143
6105767	25354	mysql group by sum	select cat_name, sum(amount) as total_amount from table group by cat_name 	0.211410956053924
6107099	33567	mysql how do i get a sum of the checkins?	select promotions.`sms_promo_id`, places.`id`, places.`name`, sum(insights.`checkins`), insights.`likes`, insights.`place_id` from promotions inner join places inner join insights on promotions.`id` = places.`promotion_id` and places.`id` = insights.`place_id` group by promotions.`sms_promo_id`, places.`id`, places.`name`, insights.`likes`, insights.`place_id` 	0.00142236620434749
6108992	35988	chaning the view/style of sql xml auto	select (select cast(narrative as varchar(max)) from officeclientledger where ptmatter=$matter$ and pttrans = 4 as disbursments for xml path(''), true) 	0.0115550925653271
6110464	35541	multiple queries: multi variables or one query	select    cards.card_id,    concat(cards.title, ' by amy') as titleconcat,    cards.description,    cards.meta_description,   cards.seo_keywords,   concat('http:   card_cheapest.price,   card_import.author,   min(card_lookup_values.card_price) from   cards   join card_cheapest on cards.card_id = card_cheapest.card_id   left join card_import on card_import.card_id = cards.card_id   join card_lookup_values on card_lookup_values.card_id = cards.card_id where card_lookup_values.card_price > 0 group by   cards.card_id order by   cards.card_id 	0.304115578224102
6113070	18091	executing a client query exactly the same in ssms	select session_id, blocking_session_id, command, cpu_time, reads, writes, logical_reads, row_count, total_elapsed_time, granted_query_memory, db_name(database_id),  last_wait_type, wait_resource, start_time, open_transaction_count, query_plan, text from master.sys.dm_exec_requests (nolock) cross apply sys.dm_exec_query_plan(plan_handle) cross apply sys.dm_exec_sql_text(sql_handle) where session_id <> @@spid 	0.296248981450557
6114873	11892	get the newest entry before a group by query	select t.package_name, p.price, t.maxdate     from (select package_name, max(date) as maxdate               from products               group by package_name) t         inner join products p             on t.package_name = p.package_name                 and t.maxdate = p.date 	0.000110188866513096
6115607	26007	sql - getting category name from sql table	select distinct categoryname  from yourtable 	0.000634185215760423
6118803	22848	t-sql query to get # of something for a given category, via lookup table	select *  from categories  where catid in  (     select catid       from placecats     group by catid     having count(*) < 5 ) 	8.81739673148344e-05
6119350	27433	sort mysql data by count and timestamp	select searchstring  from trending  where    timestamp > date_sub(now(), interval 1 day) order by count desc  limit 5 	0.00639470935875551
6120185	4116	how to see the table structure in the query analyzer ms sql server	select *  from   information_schema.columns where  table_name = 'yourtable' 	0.128806943624128
6121370	5339	how can i get the name of a logged in user from a database?	select user, uid from dual 	0
6122440	20458	mysql query: using union and getting row number as part of select	select  @rownum := @rownum + 1 rownum         , t.* from    (             (select t.id                     , t.name                     , c.company as owner                     , t.creation_date as date                     , t.notes              from    tool t                     , client c              where   t.id_customer = '15'                      and t.trash_flag = '1'              ) union (             select  f.id                     , f.name                     , concat(m.first_name, ' ', m.last_name) as owner                     , f.date                     , f.notes              from    file f                     , meta m              where   ((f.acl = 0) or (f.acl = 1 and '1' = true) or (f.acl = 2 and f.id = '7')) and f.id = '15' and f.trash_flag = '1' and m.user_id = f.id_user)              )         ) t         , (select @rownum := 0) r order by          'name' asc limit   0, 20 	0.00122152812397446
6125259	32823	how to limit the total number of form submissions per day	select count(*) from mytable where mydatecolumn >= curdate(); 	0
6127366	18127	join with same table in mysql?	select e1.emid, e1.name, coalesce(e2.name, e1.name) as managername     from employee e1         left join employee e2             on e1.managerid = e2.emid 	0.0506857796958172
6127655	31357	combining two (or more) sql results dynamically with php?	select p.* from posts p   join friendrequests fr     on fr.from = p.authorid where fr.accepted = 1   and fr.to =  @myid order by p.postdate desc 	0.140947848070524
6128351	27472	access join on first record	select tblproducts.intid , tblproducts.strtitle , (select top 1 intgroup     from tblproductgroups     where intproduct=tblproducts.intid     order by intgroup asc) as intgroup from tblproducts  where tblproducts.blnactive  order by tblproducts.intsort asc, tblproducts.curprice asc 	0.00923029824548862
6128522	23685	sql - return all rows, however non-unique rows are merged into one (arithmetic performed)?	select b, c, d, sum(e*f) / sum(f), sum(f), sum(g), sum(h), sum(i) from mytable group by b, c, d 	0
6129664	35620	get maximum with other data	select brand_id, count(*) as top_deliverer, deliverer_id, deliverer.etc. from some stuff group by brand_id, deliverer_id, deliverere.etc order by top_deliverer desc 	0.000162147905971126
6129782	34453	how will i join this two query in one single query?	select item.id, item.name, item.description,         item.tnurl, item.spec_id, item.item_type,         item.sub_category  from item left join fb_item_promo on fb_item_promo.item_id=item.id where fb_item_promo.item_id is not null   or item.description like '%package%' 	0.195589467056772
6130400	28731	sql syntax to always get one	select  c.description, r.isread, r.userid from    dbo.calls c left join dbo.ticketread r     on c.callid = r.ticketid     and r.userid = 1 	0.144622843389178
6130450	36002	making a query on 2 columns as if they were one	select z.name, count(*) as total from    (         select col_a as name         from total         union all         select col_b         from total         ) as z group by z.name 	5.21258713830992e-05
6131263	1020	how can i select distinct data based on a date field?	select color.*  from colortable as color inner join  ( select objid, max(date) as date from colortable group by objid ) as maxdatebycolor on color.objid = maxdatebycolor.objid and color.date = maxdatebycolor.date 	0
6132025	18133	combine rows adding specific columns	select employee_id, sum(totalworkhours) as actualworkhours from   yourtablename group by employee_id order by employee_id 	0.00019002399660692
6132065	7603	closest matching for mysql datetime fields	select `timestampcolumn` from `thetable` order by abs(`timestampcolumn` - givenvalue) limit 1 	0.00336498152613518
6134736	20523	sql script ordering	select a.*,        1 as sort   from users a  where a.description like 'query' union all select b.*,        2 as sort   from users b  where b.description like '%query%' order by sort 	0.705528679316837
6135205	32981	sql query group by	select . . . sum(case mg_disp_status=0 and mig_disp_code =3 then 1 else 0 end) cnt1, sum(case mg_disp_status=1 and mig_disp_code <> 2 then 1 else 0 end) cnt2, 	0.576087973847006
6137024	26722	mysql: how to group data per hour and get the latest hour	select  f.* from    (         select  max(unix_timestamp(date_created)) as mts         from  user_accounts          group by hour(date_created)         ) s join    user_accounts  f on      unix_timestamp(date_created) = s.mts where  date(date_created) = '2009-10-27' 	0
6137433	34016	where does the practice "exists (select 1 from ...)" come from?	select * 	0.00443512232886291
6137655	19644	creating views - with check option	select * from view update view set id = id + 3 select * from view 	0.534267545656266
6138257	28556	need to order mysql table and return specific subset	select foo from bar order by baz limit 0,10; 	0.00635476669971854
6138960	35578	does mysql have the concept of "this" database?	select database() 	0.602165193570706
6139467	7789	80% rule estimation value in pl/sql	select percentile_disc(0.8) within group (order by the_value) from my_table 	0.541071213319608
6139733	20475	comparing dates in sql	select restrictions, restrictions_adddate  from restrictions  where id = '555555'   and restrictions_adddate between date '2011-01-01' and date '2011-12-31'; 	0.0317715425359091
6140009	16125	selecting data within a row of a column	select substring(name,length('quantity for pricing'))           from lookup where name like 'quantity for pricing%'; 	5.75310776349924e-05
6140529	28135	how can i get the id of the last inserted row using pdo with sql server?	select @@identity - return the last id created by actions of the current connection, regardless of table/scope select scope_identity() - last id produced by the current connection, in scope, regardless of table select ident_current('name_of_table'); - last id produced on that table, regardless of table/scope/connection 	0
6143082	16682	rolling 30 day uniques in sql	select distinct `activity_date` as `day`, ( select count(distinct `user_id`) from `user_activity` where `activity_date` = `day` ) as `num_uniques` from `user_activity`  where `activity_date` > now() - interval 30 day; 	0.00238062834764167
6144442	39243	how to return row count of mysql sub query	select games.id, games.gametitle  from games  where (     select count(filename)     from banners     where banners.keyvalue = games.id and banners.filename like '%front%' ) > 1 	0.00845606597130813
6144533	6462	is it possible to have distinct + concat within group_concat?	select group_concat(distinct concat(id,nombre)) from pre_departamento; 	0.576993610085381
6149523	19342	how to retrieve the number of rows in a table	select count(*) num_rows from allpacks; 	0
6154487	9661	mysql - use group_concat values in a calculation?	select p.price,        p.price - coalesce(sum(d.amount), 0) as discounted_price,        group_concat(d.amount) as discounts from products p left outer join discounts d on d.product_id = p.id group by p.id 	0.580003489450838
6154973	27669	sql server 2008: select name of column with greatest recurring value	select name, count(*) from exployeetreats where  donut = "yes" and amounteaten >= 10 group by name having count(*) >= all ( select count(*)                          from employeetreats                          where donut = "yes" and amounteaten >= 30                          group by name ) 	0.00435054432018667
6155895	10746	mysql select one row, join multiple to it	select e.code from events e inner join sessions s     on s.session = e.session where s.set = <whatever set you want> and s.timestamp = (select max(timestamp) from sessions where set = s.set) 	0.00956909762517788
6156726	27764	mysql return static strings	select 'option one' as value union select 'option two' as value 	0.131995266641382
6159153	39704	sql count number of values given compound condition on row	select count(*) from userservice where      serviceid = 3 and     userid in (select userid from userservice where serviceid != 3) 	0
6159832	17218	how to find the column name of a table from its column value in sql server 2005?	select * from ( select d1 as value, d1_code as code from view union all select d2, d2_code from view union all select d3, d3_code from view ) as myinfo where code='length' 	0
6159873	14103	how can i fetch the data of specific month from sqlite database	select column_name from table_name where strftime('%y-%m', column_name) = '2011-05'; 	0
6160307	22525	sqlite - highest 60 second average in a time series?	select max((select avg(watts)              from tblworkoutdata d2             where d2.workoutsummaryid = d1.workoutsummaryid                and d2.ticks between d1.ticks and d1.ticks + 60)) as themax  from tblworkoutdata d1 where workoutsummaryid = 198 	0
6160850	281	consistent random ordering in a mysql query	select something from somewhere order by rand(123) 	0.462246911676339
6162527	32199	shortest string within same path (branch)	select t1.* from atable t1   left join atable t2     on t2.assigned_user_id = t1.assigned_user_id and        t2.path = left(t1.path, char_length(t2.path)) and        t2.id <> t1.id where t1.assigned_user_id = 2   and t2.id is null 	0.0176756745784878
6166268	28913	how to show the last entry on first in php?	select * from mytable order by id desc limit 1 	0
6166783	3773	summary function on a subquery	select a.x, select(mean(b.y) where b.x<a.x from data2 b) as m_y from data1 a 	0.713893085298236
6168396	35830	sql/c# windows app - several counts from one dataset?	select @return = count(party) where party = 'dem' 	0.00374155109580918
6169834	22124	ms access relationship between 2 tables	select tblinfo.username, tblinfo.address, tblroomnames.room_name from tblroomnames inner join tblinfo on tblroomnames.id = tblinfo.room_name_id; 	0.0359289960403165
6172880	19183	select more than one count in mysql	select count(*),         sum(case when foo is null then 1 else 0 end) as count_conditional   from baz 	0.0117804138138193
6175397	4754	how to use three conditions in where clause of mysql query?	select * from posts where userid = $userid and postby = '{$postby}' and posttype = 'unread' 	0.756729605767434
6176670	27435	sql sum question	select   sum ( table_one.field + table_two.field ) as total_field,   sum ( table_one.field + table_two.field + table_one.anotherfield ) from   table_one join  table_two on table_one.id = table_two.id where   table_one = 1 	0.775809079047407
6178068	22057	do i need to have a multicolumn index?	select * from (   select * from (            select *            from phppos_items            where name like 'ab10la2%' and deleted = 0            order by `name` limit 16            ) t   union   select * from (            select *            from phppos_items            where item_number like 'ab10la2%' and deleted = 0            order by `name` limit 16            ) t   union   select * from (            select *            from phppos_items            where category like 'ab10la2%' and deleted = 0            order by `name` limit 16            ) t   ) as top rows order by `name` limit 16 	0.483004164033913
6179175	13604	getting maximum from two columns of two tables	select max(maxid) from (     select max(id) as maxid from delt1     union all     select max(id) as maxid from t1 ) maxes; 	0
6179623	22409	efficient mysql search	select * from table where soundex(myc) = soundex('asda'); 	0.64843130936415
6180853	7790	ms-access selecting the problematic data	select col1, col2 from mytable where col1 not in (     select col1      from mytable      where col2 = 'ok' ) 	0.054085625146764
6181705	34366	mysql select differences between two tables in different databases	select * from olddatabase.commenttable where comment not in (select comment from newdatabase.commenttable) 	4.90613473662696e-05
6182536	34069	sql order by query	select *    from `rcarddet`   where `rdate` = '2011-05-25'     and `rcno` = '1'     and `place` = 'h'  order by   `sdno` = 0,   `sdno`; 	0.594121400670141
6184775	10557	get another column from sum-sub-select	select to_char(a.pow * f_unit_converter(a.base_unit, '[w]'), '000.00')  from (     select sum (time_value) as pow, t_mp.base_unit     from v_value_quarter_hour         inner join t_mp on (v_value_quarter_hour.mp_id = t_mp.mp_id)     where         t_mp.mp_name = 'ac' and         (now() - time_stamp < '5 day')      group by time_stamp, base_unit     order by time_stamp desc  ) a  limit 1 	0.000219379997420957
6186457	40484	sql: what's the state of id x on date y (is there a more efficient way?)	select t.id,       '2000-01-01'::date + (m.mon || ' months')::interval as month,       t.state from generate_series(0, 11) as m (mon) left join info_table t on '2000-01-15'::date + (m.mon || ' months')::interval    between t.start and t.end 	0.00111940594791055
6186594	2626	select limited rows and columns from database table	select top 50  col1, col2 from mytable 	0
6186966	20696	get the parent xml node based on an inner node's value in sql server	select   a.b.value('id[1]','nvarchar(max)') id, a.b.value('enddate[1]','datetime') enddate  from    @xmlval.nodes('  for xml path('token') 	5.62818298586667e-05
6190939	23246	display data based on timeframe with sum	select sum(table1.vote) as votes, table2.* from table2                 left join table1 on table1.itemid=table2.itemid                     where table1.`time`>=date_sub(table1.`time`, interval 24 hour)  group by table1.itemid                                              order by table1.votes desc 	5.32804174748019e-05
6191704	12843	how to pass the value for datetime field in where clause in sql server	select * from tablename where convert(varchar(10), publishdate, 103) = '03/10/2011' 	0.0682918685391429
6192499	36167	select records based on what a field begins with? 	select person.spineinjuryadmit, tblcomorbidity.comorbidityexplanation, count(tblcomorbidity.comorbidityexplanation) as countofcomorbidityexplanation from tblkentuckycounties inner join (tblcomorbidity inner join (person inner join tblcomorbidityperson on person.personid = tblcomorbidityperson.personid) on tblcomorbidity.id = tblcomorbidityperson.comorbidityfk) on tblkentuckycounties.id = person.county group by person.spineinjuryadmit, tblcomorbidity.comorbidityexplanation having (person.spineinjuryadmit like "c*"); 	0.00117367018738581
6194081	3803	how to join three degrees in mysql	select posts.id, posts.text, users.id, users.name, comments.text as commenttext, commenters.id, commenters.name from posts     join users         on posts.userid = users.id     left join comments         on posts.id = comments.postid              left join users as commenters                 on comments.userid = commenters.id 	0.513675053205979
6195597	36588	insert with static elements | dynamic | select | random | & top for good measure	select top(1000) * from (     select top 50000 [lname] as 'last'       , [fname] as 'first'       , [phone]       , [wphone]       , [fax]       , [cellphone]       , [email]       , [state]       , [zip]       , [state_w]       , [zip_w]       , [employer]       , convert(char, [datebirth], 101)       , rand() as priority     from [rt2dbsql_review].[dbo].[respondent]     where (education = '5' )       and (race = 'h' )       and (hours = '1' )       and (',' + cc5 like '%,2,%' or ',' + cc5 like '%,26,%' or ',' + cc5 like '%,12,%')       and (',' + cc6 like '%,9,%' or ',' + cc6 like '%,23,%')       and (',' + cc4 like '%,nintendo ds,%') and (gender = 'm')       and pro_resp is null   ) full_sample order by priority 	0.123166071465091
6196247	18971	how to display data from table where data is filled in sql server 2005 	select e.details from dbo.employee e where e.details is not null  and e.details <> '' 	0.00656437477181697
6197762	36696	how do i have just the date and not the time displayed along with it in a mysql table?	select name, address, date(dateofbirth) from myfriends 	0
6198239	7880	mysql join empty rows	select * from wp_sb_users u  left outer join wp_sb_usermeta m on (u.id=m.user_id and m.meta_key = "autostatus")  left outer join wp_sb_usermeta mm on (u.id=mm.user_id and mm.meta_key = "first_name")  left outer join wp_sb_usermeta mmm on (u.id=mmm.user_id and mmm.meta_key = "last_name") 	0.0846462150346083
6198320	15536	how to use "partition by" or "max"?	select year, x,y from (       select year, x, y, max(year) over(partition by x) max_year       from my data       ) where  year = max_year 	0.746298382244296
6198731	31263	selecting rows from a table by one a field from other table	select i.prof_image  from profile_images i  where cat_id = (select max(cat_id) from images_cat) 	0
6198962	24770	how to get distance <500?	select mm.mem_id, mm.profilenam, mm.photo_thumb, mm.city, mm.zip, mm.country, mm.state, ( 3956 *2 * asin( sqrt( power( sin( ( 34.1012181 - abs( latitude ) ) * pi( ) /180 /2 ) , 2 ) + cos( 34.1012181 * pi( ) /180 ) * cos( abs( latitude ) * pi( ) /180 ) * power( sin( ( abs( - 118.325739 ) - abs( longitude ) ) * pi( ) /180 /2 ) , 2 ) ) ) ) as distance from members as mm where mm.profile_type =  'c' having distance<500 	0.0128404536439501
6199583	5614	using group by and maximum	select      p.[postid],     pc.[description] from     [post] as p inner join     [postcontent] as pc     on p.postid = pc.postid  where     pc.[version] = (select max([version]) from postcontent where postid = p.postid) 	0.0324263764843901
6200650	31264	query gives different output on different os	select date_format(curdate(), '%d/%m/%y %hh%mm%ss') 	0.134598412823392
6202049	40590	compare table with a table variable in a stored procedure in sql server 2005	select *  from table a  where not exists(     select *      from @item sub      where table a.id = sub.id ) 	0.126190230757505
6203719	29200	left join only for specific rows in sql?	select e.*, s.name, isnull(s.name,'predefined value') from [event] as e left join [source] as s on (s.id = e.sourceid)                        and (e.eventtype in ('app_close','app_start')) 	0.0182344090138585
6204688	8975	sql - select between 3 tables	select h.* from hosts h  inner join hosts_hostgroup hg on hg.host_id = h.host_id inner join hostgroup g on g.hostgroup_id = hg.hostgroup_id where g.name = 'mygroupname' 	0.0195736821845872
6207486	8980	will an in clause always return the same order in mysql	select price from product where product_id in (49, 50, 51) order by field(product_id,49,50,51) 	0.0977310458471612
6207972	26485	sql query to pull out form entries where each value is a separate row	select ffe.form_entry_id     , min( case when ff.name = 'foo' then ffe.value end ) as `foo`     , min( case when ff.name = 'bar' then ffe.value end ) as `bar`     , ... from formfieldentry as ffe     join formfield as ff         on ff.id = ffe.form_field_id group by ffe.form_entry_id 	0
6209443	12321	problem with selecting data in 2 tables	select `e`.`employee_id` ,        `e`.`employee_name` ,        `e`.`title` ,        `e`.`file_date` ,        `e`.`status` ,        `e`.`confirmation` as "status" from `gmdc_employee` `e`   join `gmdc_user` `u` on ( `u`.`company_id` = `e`.`company_id` ) where `u`.`company_name` like "dlsu" 	0.0249931516158628
6209658	2674	transact-sql: how do i tokenize a string?	select t.* from atable t   inner join dbo.split(@userinput, ' ') s on t.name like '%' + s.data + '%' 	0.515150234192595
6210260	4217	what is the correct sql (mysql) for finding the value that occurs the most?	select `column` from `table` group by `column` order by count(`column`) desc limit 1 	0.000134788976489894
6210333	17638	mysql return multiple results with group by	select ticker from company order by industry, ticker 	0.116136700242095
6210621	17992	sql for finding a value having rows of closest to half of all unique occurrences of another value?	select top 1     facts.factid   , facts.segids   , segs.total_segids from (     select factid       , count(distinct segid) as segids     from my_table     group by factid   ) facts,   (     select count(distinct segid) as total_segids     from my_table   ) segs order by abs(facts.segids - (segs.total_segids / 2)) 	0
6211363	15293	replace characters in all tables in database postgres	select 'update ' || table_schema || '.' || table_name ||        ' set ' || column_name || ' = replace(' ||         column_name || ', ''from'', ''to'')' from information_schema.columns where data_type like '%char%' 	0.00983457121343892
6211392	1690	mysql: variable limit	select ... from table where somecolumn >=     ( select somecolumn        from table        order by somecolumn desc        limit 4, 1                      <     ) order by somecolumn desc 	0.466777892387762
6211695	35269	how to remove null rows from sql query result?	select    c.id, c.firstname, dbo.getclientstaffcontacts(c.id, '27,31') as staff  from    client c  where   dbo.getclientstaffcontacts(c.id, '27,31') is not null order    by c.id 	0.00261691091903003
6211892	16540	problem comparing two dates in mysql	select * from tblconcertdetail where date(concert_date) >= "+datetime.now.tostring("yyyy-mm-dd")+"; 	0.0419983454304046
6212447	24874	sql server: how to check if a windows user exists in the database but under a different user name	select * from sys.database_principals where sid = suser_sid(n'mydomain\myuser') 	9.10178085867069e-05
6215459	15344	t-sql query to show table definition?	select ordinal_position, column_name, data_type, character_maximum_length        , is_nullable from information_schema.columns where table_name = 'customers' select constraint_name from information_schema.constraint_table_usage where table_name = 'customers' select name, type_desc, is_unique, is_primary_key from sys.indexes where [object_id] = object_id('dbo.customers') 	0.0995361076787878
6215735	23180	how to check that the to which table the view is currently pointing to in oracle?	select referenced_name from all_dependencies where name = 'myview' and owner = 'myschema' and referenced_type = 'table'; 	0.00147480860995478
6216236	16390	php/mysql many-to-many relationship - the next step here	select * from projects p left join users_projects up on p.projects_id = up.projects_id where up.users_id = [insert userid here] 	0.0315713451629793
6216311	15476	get comma separted string from mysql	select *      from table      where ustaffid='$ustaffid'          and find_in_set('$a', groupid) > 0 	0.0011229718889006
6220309	28212	how to assign the max value across mulptiple fields to a single column in a select statement using ms-access-2010 sql?	select max(v) as maggiore from ( select id,d1 as v from table union all select id,d2 from table union all select id,d3 from table union all select id,d4 from table ) as t group by id 	0
6221821	9419	extract a search string in context	select     id,     title,     substring(body,           case              when locate('mysql', lower(body)) <= 20 then 1              else locate('mysql', lower(body)) - 20         end,         case             when locate('mysql', lower(body)) + 20 > length(body) then length(body)             else locate('mysql', lower(body)) + 20         end) from content where lower(body) like '%mysql%'     or title like '%mysql%' limit 8; 	0.0383388219836669
6222147	28255	sql to answer: which customers were active in a given month, based on activate/deactivate records	select t2.custid from ( select custid, date, action  from cust_table t1  where date = (select max(date)      from cust_table where custid = t1.custid) ) as t2 where t2.date < '2011-06-01' and (date > '2011-05-01' or [action] = 'activate') 	0
6222401	35983	getting only 1 record from each category for each page in pagination	select id, name, catid from     (select id, name, catid from t where catid=1 limit 2,1) as t1     union (select id, name, catid from t where catid=2 limit 2,1)    order by catid 	0
6222880	29884	mysql join two tables based on a time field returning the largest previous time	select   e.name,   v.video,   to_seconds(v.starttime) - to_seconds(e.eventtime) as secsintovideo from eventtable e   left join videotable v     on e.eventtime between v.starttime and v.starttime + interval (v.durationsecs) 	0
6223838	22348	how to convert rows values into column in sql server 2005	select userid, vendorname, [abc1], [abc2], [abc3] from questions pivot (max(answertext)     for questiontext in ([abc1], [abc2], [abc3]) ) as pvt 	0.000712115675977831
6225524	16448	hirarchy id, find parent by child	select tablep1.id, tablep1.p1   from tablep1   join tablep2 on tablep1.p2.tostring() like '/'+tablep2.id+'%'               and tablep2.id in (1600, 1300) 	0.000178620675333952
6226103	41295	select multiple static values	select 'jan' as qtr1, 'apr' as qtr2 union all select 'feb' as qtr1, 'may' as qtr2 union all select 'mar' as qtr1, 'jun' as qtr2 	0.0343680077412682
6226447	15093	passing sql "in" parameter list in jasperreport	select * from customer where $x{in,customer_role,roles} 	0.692629407896067
6226933	7710	how do i join a table and change the names of the returned columns?	select f.name as fruit_name, c.category_name as fruit_category_name from fruits as f inner join categories as c on c.id = f.category_id 	0
6227481	37318	mysql: how do i order the results depending on if they are also present in other tables?	select table_1.id,    (case   when max(table_2.id) is not null and max(table_3.id) is not null then 0   when max(table_2.id) is not null or max(table_3.id) is not null then 1   else 2   end) rank from table_1 left outer join table_2 on    table_1.id = table_2.id left outer join table_3 on    table_1.id = table_3.id group by table_1.id order by rank 	0
6228325	34245	looking up missing keys	select distinct p.zipcode, p.place from p left join zipcodes as z on (p.place = z.place) and (p.zipcode = z.zipcode) where (((z.zipcode) is null)); 	0.329002525576886
6229869	31855	conditional joining	select a.accountid, oq.somefield, oq.someotherfield from        (select coalesce (o.accountid, q.accountid) as accountid,             q.somefield, o.someotherfield     from opportunity o      full join quote q          on q.opportunityid = a.opportunityid) oq left join accounts a     on oq.accountid = a.accountid 	0.55527398183336
6230362	31794	oracle query cast attribute	select to_char(0.1234, '00000000.00') from dual 	0.323379653295047
6230779	23049	trying to find amount of null values for a column returning 0?	select count(*) from table where age is null; 	7.31578231507965e-05
6233060	40262	sql server 2005 find all columns in database for a certain datatype	select a.name    from syscolumns a inner join systypes b     on a.xtype = b.xtype    and b.name = 'ntext'  	0
6236339	3340	oracle sql query question(grouping by 2 columns)	select i, j, count(*) as jini from atable group by i, j 	0.0808879877069644
6237166	11019	get rate of rise from mysql order table but tooooo slow	select thismonth.productcode,        (thismonth.ordercount-lastmonth.ordercount)/lastmonth.ordercount as riserate      from ( (select productcode,                  sum(quantity) as ordercount             from `order`             where order_date between '01-12-2010' and '31-12-2010'                   group by productcode) as thismonth,          (select productcode,                  sum(quantity) as ordercount             from `order`             where order_date between '01-11-2010' and '30-11-2010'             group by productcode) as lastmonth)   where thismonth.productcode = lastmonth.productcode   order by riserate; 	0.0148169155222195
6237472	31158	mysql compare two tables	select id from members left join votes on userid=id where votes.userid is null 	0.00419854547811881
6238230	11905	sql integer query, find integer within +/- 1	select integername  from tblintegerlist  where (integername-<variable>) between -1 and 1 	0.0269810820686184
6242671	24751	mysql sum on matching set of data	select     g.inputdate,     g.invoiceno,     g.bookno,     j.accountname,     j.debit,     j.credit,     1 as recordtype from     gjournal_main g     inner join general_journal j on j.tid = g.invoiceno union all select     null,     null,     g.invoiceno,     '** total',     sum(j.debit),     sum(j.credit),     2 as recordtype from     gjournal_main g     inner join general_journal j on j.tid = g.invoiceno group by     g.invoiceno order by     bookno,     invoiceno,     recordtype having     bookno = 600 	0.00130173940776816
6243175	39330	difference in columns. returning variable top duplicate results	select max(column1 - column2) as result from table where othercolumn = somecondition group by id having result =    (select max(column1 - column2) from table where othercolumn = somecondition) order by id; 	0.000534517315489243
6243678	34064	specific ordering sql command	select * from mytable  order by case when name like 'test%' then 0 else 1 end asc, name asc 	0.342643945592258
6244701	22589	mysql using if statements	select contracttype, paymentreceivedon, if (contracttype = 'abo3', adddate(paymentreceivedon, interval 3 month), null)   as expirydate from payments where id=21 	0.60948896485246
6245650	24962	oracle select highest date per record	select count(a.agency_name) as number_of_visits,     a.agency_name,     (a.street||', '||a.city) as "location",      max(n.call_date),     round(trunc(sysdate - max(call_date))) as days_since_visit from notes n, agency a where (sysdate - n.call_date) > 120     and n.agency_gp_id = a.agency_id     and not exists (select 1 from notes n2                      where n2.agency_gp_id = a.agency_id                      and (sysdate - n2.call_date) <= 120) group by a.agency_name,a.street, a.city order by a.agency_name asc, max(n.call_date) desc; 	0
6246024	4067	calculate total value of products	select sum(price*quantity) as yoursum from yourtable 	0
6247145	27318	how to query a first name and last name string in mysql	select id, firstname, middlename, lastname where firstname like '%searchterm%' or middlename like '%searchterm%' or lastname like '%searchterm%' 	0
6247626	35932	joining two tables twice in mysql. possible or not???	select id, s.name, r.name from messages     inner join users as s on (message.sender = s.id)     inner join users as r on (merssage.receiver = r.id) 	0.126127517412569
6249996	9458	how to use two sql requests (mysql) to calculate an average number	select (nbissuereopenbyproject / totalticketbyproj)   from (select project.pname, count(jiraissue.id) as totalticketbyproj           from jiraissue, project          where jiraissue.project = project.id          group by project.pname) ttbp,        (select project.pname, count(changeitem.id) as nbissuereopenbyproject           from changeitem, changegroup, jiraissue, project          where changeitem.groupid = changegroup.id            and changegroup.issueid = jiraissue.id            and jiraissue.project = project.id            and changeitem.oldstring = "resolved"            and changeitem.newstring = "closed"          group by project.pname) nbirbp  where ttbp.pname = nbirbp.pname 	0.000227571243952044
6254457	22305	drop all logins where loginname like 	select 'drop login [' + name + '];' from sys.server_principals  where name like 'foo%' 	0.238278249916349
6254897	15249	how to combine two sql queries	select * from unithd where ( driver1medical between '1/1/1990' and getdate()+29 )    or ( driver2medical between '1/1/1990' and getdate()+29 ) order by driver1medical 	0.0203538541708872
6255206	40702	town report (number of orders)	select s.city,          sum          (         case              when isnull(o.status) then 0             else 1         end           ) as numoforders          from shop as s  left join orders o        on o.shopid = s.shopid   where ifnull(o.status, 4) = 4      group by s.city 	0.00155836291280459
6257580	40306	count all duplicates of each value	select   col,          count(dupe_col) as dupe_cnt from     table group by col having   count(dupe_col) > 1 order by count(dupe_col) desc 	0
6258750	20024	combining multiple mysql queries into one	select count(distinct user_id),year(created_at), quarter(created_at) from transactions  group by year(created_at), quarter(created_at) 	0.00635784228317133
6259236	23588	how to get related items without select each id	select       u.name  from       friends f       join users s on (u.id = f.user_id_2)  where       f.user_id_2 = 1234 	0
6259647	5672	mysql match() against() - order by relevance and column?	select pages.*,        match (head, body) against ('some words') as relevance,        match (head) against ('some words') as title_relevance from pages where match (head, body) against ('some words') order by title_relevance desc, relevance desc order by title_relevance + relevance desc 	0.0906194362450204
6259998	3795	mysql selecting reciprocating data?	select a.userid, a.following   from follow a inner join follow b     on a.userid = b.following    and b.userid = a.following 	0.034745534990135
6262244	40310	dynamic column in where clause	select id, name, distance from (         select id,name,distance=dbo.calculatedistance(lat,lon,@lat,@lon)         from requests) derived          where distance < 2          order by distance desc 	0.788115975890835
6262993	19895	write a query to get an array and use that array in a subquey	select *  from videos  where video_id in (     select v2.video_id      from videotags as v1      join videotags as v2 using ( tag_id )      where v1.video_id =1 and v1.video_id <> v2.video_id      group by v2.video_id order by count( * ) desc ) 	0.064748605414787
6263817	33386	reports by month with php and mysql?	select      month(to.orderdate),      year(to.orderdate),      sum(to.total),      to.*  from tbl_order as to inner join tbl_shop as ts on ts.shopid = to.shopid group by to.shopid, month(to.orderdate), year(to.orderdate) 	0.0257959803198656
6264512	370	i want to convert rows 2 rows as 2 columns in sql 2000 without using pivot	select 'a' as projects, a as my_count from mytab union all select 'b' as projects, b as my_count from mytab union all select 'c' as projects, c as my_count from mytab 	0.000208066330232377
6265136	10089	all rows where at least one child has all of its own children pass a condition	select   prizeid from   (   select     prizerule_map.prizeid,     prizerule_map.ruleid   from     prizerule_map   inner join     rule       on rule.ruleid = prizerule_map.ruleid   inner join     conditional       on conditional.ruleid = rule.ruleid   left join     input       on input.inputid = conditional.inputid   group by     prizerule_map.prizeid,     prizerule_map.ruleid   having     count(*) = sum(case conditional.expectedvalue                      when 1 then case when input.inputid is null then 0 else 1 end                      when 0 then case when input.inputid is null then 1 else 0 end                    end                    )   )     as map group by   prizeid 	0
6267564	23746	convert unix timestamp into human readable date using mysql	select   from_unixtime(timestamp)  from    your_table 	0.022066347150815
6267878	11763	mysql left join for right table max value	select       p.*,       tbc.comment    from       tb_photos p          left join ( select c.photos_id,                              max( c.id ) lastcommentperphoto                         from                            tb_comments c                         group by                            c.photos_id                         order by                            c.photos_id ) lastphotocomment             on p.id = lastphotocomment.photos_id             left join tb_comments tbc                on lastphotocomment.lastcommentperphoto = tbc.id 	0.442497985709691
6268895	25238	data order by which table its in sql	select p.firstname, p.lastname,     p.location, p.uid,     case when f.a is null then 1    else 2        end as type from profile as p left join favorites as f  on p.uid = f.b and f.a = 'myid' where p.firstname like 'mich%' or p.lastname like 'mich%' 	0.00598097372430088
6269665	2177	is there a way to find all distinct values for multiple columns in one query?	select documentid as documentid, 'filename' as attributetype, filename as distinctvalue  from tablename union select documentid, 'added date', added_date from tablename union select documentid, 'created by', created_by from tablename union .... 	0
6270734	19316	sql query to count number of days, excluding holidays/weekends	select   days = datediff(day, workdate, receiveddate)   - (select count(*) from tblholidays where holidaydate >= workdate and holidaydate < receiveddate) from   tblexceptions 	7.34119936792229e-05
6273048	22602	what's the syntax for selecting several ids into a variable, and then using that in an in	select table_b.*  from table_b join (select id from table_a limit 1,10) as table_a   on table_b.table_a_id = table_a.id 	0.000689082619354078
6273208	27550	mysql single row with multiple records	select `resortid`    where `amenoptionid`          in (1, 4)  group by `resortid`   having count(*) = 2 	0.000865995641309946
6273822	18711	sql query to retrieve data	select `name`   from `business` where id in ( select business_id from bill  where id in ( select bill_id from bill_schedule where show_bill = 1 ) 	0.0210170460057735
6273890	9983	mysql select and json_encode	select ... where the_json_field like '%"var":"value"%'; 	0.259783202515907
6273928	32021	sql union returns duplicate results	select count(trade_sid), shortcode  from (     select trade_sid, shortcode      from  trade      where          trade.trade_date <= sysdate and          trade.trade_date>= add_months(sysdate, -11)      union all     select trade_sid, shortcode      from trade_archive      where          trade_archive.trade_date <= sysdate and          trade_archive.trade_date>= add_months(sysdate, -11)  ) tt group by shortcode order by shortcode 	0.166848735670626
6273978	7961	how to do a join in mysql based on partial matches?	select a.column1, a.column2,        b.column1, b.column2   from table_a a   join table_b b on find_in_set(a.column2, b.column2) > 0 	0.000893828758604481
6274433	34762	efficient datawarehousing algorithm for counting rolling quarter value	select sum(month)         over(rows between 2 preceding and current rows) from database.table 	0.0045955840517003
6275500	12079	how do i get the top 1 of a linked table?	select    q.questionid, q.questionname,    a.answerdescription, a.createddate from     question q     cross apply     (      select top 1 a2.answerdescription, a2.createddate      from answer a2      where q.questionid = a2.questionid      order by a2.createddate desc     ) a 	8.34602982915073e-05
6276683	33472	how to do : "between today and today-7"?	select * from `account`  where date(created_at) > (now() - interval 7 day) 	0.00818558896185549
6277718	10227	mysql select value before max	select max_name.name,before_max.count from  (select type,max(count) as max from `test`  group by type) as type_max join (select type,name,count from test  ) as max_name on (type_max.type = max_name.type and count = type_max.max ) left join (select type,count from test as t1 where count != (select max(count) from test as t2 where t1.type = t2.type) group by type order by count desc) as before_max on(type_max.type = before_max .type) 	0.010228976600954
6280732	40830	how can i see the list of all the triggers defined on a db?	select b.name as tablename,a.name as triggername from sysobjects a,sysobjects b where a.xtype='tr' and a.parent_obj = b.id 	4.98998721154748e-05
6282784	3206	oracle debugging technique for row difference	select list_of_columns   from some_table  where some_criteria minus select list_of_columns   from some_table@db_link_to_dev  where some_criteria 	0.0699559715849215
6283995	38905	next lowest number in mysql	select min(step_number) from system_step_product where step_number > 1 	0.000448000374849155
6286832	38732	doubles in mysql query	select users.full_name from users inner join profiles on profiles.user_id = users.id where profiles.zipcode = '$zipcode'  order by users.full_name asc 	0.60230866840056
6286888	36527	vlookup-style range lookup in t-sql	select v.value, p.profession from tblvalues v cross apply    (select top(1) pr.profession     from tblprofessionranges pr     where pr.range <= v.value order by pr.[range] desc) p 	0.0882674654363024
6287364	1060	what is the best way to have a sql that only looks at max of a date field	select *   from order  where dateupdated = (select max(dateupdated)                         from order ) 	0
6289251	13137	sql - finding maximum date in set of rows along with all other data	select     (select max(startdate) from mytable where phname = "name") as maxdate,     id, name , phname , startdate, enddate from mytable where phname = "name" 	0
6289709	2107	get all duplicates rows in sql	select * from your_table where organization_no in     (select organization_no     from your_table    group by organization_no    having count(*) > 1) 	0.000344133090441898
6290879	9977	how to get xml attribute with plsql?	select x.col1.extract(' 	0.0055083288491407
6291060	1164	mysql query order the results in group by 3 tables count	select * from   zoo_leads        left join votes          on lists.id = votes.listid        left join comments          on lists.id = comments.listid group  by lists.id order  by count(votes.id) desc,           count(comments.id) desc limit  10 	0.0369052728927088
6291783	21562	using field values from joined query as columns	select pm.page_id as id   , p.name   , max(if(pm.key = 'picture', pm.value, null)) as picture   , max(if(pm.key = 'video', pm.value, null)) as video   , max(if(pm.key = 'sound', pm.value, null)) as sound from page p inner join page_metadata pm on (p.id = pm.page_id) group by p.id 	0.000222990260006229
6292378	16083	counting number of sales from two tables	select         d.username,         sum(case when d.type = 'yes' then 1 else 0 end) as yes,         sum(case when d.type = 'no' then 1 else 0 end) as no,         sum(case when d.type = '' then 1 else 0 end) as other,         sum(case when s.mobile is null then 0 else 1 end) as sales,         count(*) as total  from dairy as d  left join (select distinct mobile from sales) as s on d.mobileno = s.mobile where source = 'company' and unix_timestamp(checkdate) >= 1293840000 and unix_timestamp(checkdate) <= 1322697600  group by d.username order by total desc 	0
6292847	32724	how to get a field with a certain amount of sub-field in sql?	select * from group_members group by groupid having count(*) >6 	0
6293072	33277	obtain average no-null fields in query	select    100.0 *     (       count(name) + count(surname) + count(email)    )    /    (        3 * count(*)    ) from    table where id = 1 	0.00570976889740127
6295837	35990	postgresql join across 2 databases	select from_user, created_at, text from twitter where q = '#postgresql'; 	0.0894836854334665
6296084	12183	select all rows in two tables without a foreign key property	select     isnull(bikes.bikename, cars.carname) as name,     bikes.bikeid,     cars.carid from bikes     full outer join cars on bikes.bikename = cars.carname order by isnull(bikes.bikename, cars.carname) 	0
6296347	25835	jpa select latest instance for each item	select m from meeting m      where m.meetingdate =          (select max(m1.meetingdate)              from meeting m1              where m1.attendee = m.attendee )     and not exists          (select m2 from meeting m2              where m2.attendee = m.attendee              and m2.meetingdate > m.meetingdate) 	0
6296464	10538	join two queries with count from the same table in mysql	select id,        sum(case when up = 1 then 1 else 0 end) as upcount,        sum(case when down = 2 then 1 else 0 end) as downcount     from comentarios     group by id 	0.000378215350043712
6296515	19347	returning column valuses and sum() of column valuses in one mysql query	select     id,     cust#,     (select          sum(payment)      from          mytable      group by          cust#     ) as totalpayments,      date  from     mytable 	0.00367361684999684
6297254	17417	date query between two dates	select *     from yourtable     where startdate >= '2005-01-01'         and enddate <= '2005-10-01' 	0.00134296946407898
6299090	14131	how to find if a date fits an interval in either php or mysql?	select * from test where datetimefield > '2011-06-16 07:00:00' and mod(timestampdiff(second,'2011-06-16 07:00:00',datetimefield),7200) = 0 	0.00557803311800188
6299241	24709	sql: how do i count the number of clients that have already bought the same product?	select t_current.featureid, count(distinct t_prior.clientid) from table_name t_current left join table_name t_prior on t_current.featuredate > t_prior.featuredate and t_current.clientid = t_prior.clientid and t_current.productid = t_prior.productid group by t_current.featureid 	0
6299375	28764	mysql:relational database , a how to?	select c.id,l1.value car,l2.value engine,l3.value gear from cardb c left outer join labels l1 on c.car=l1.label left outer join labels l2 on c.engine=l2.label left outer join labels l3 on c.gear=l3.label; 	0.117904065993846
6300117	31603	how can i return a record based on only a partial match of that record?	select name from list where name like '%ed%'; 	0
6300678	14309	split row in mysql check for values in between	select value from table where 245  between  substring_index(zip,'-',1) and substring_index(zip,'-',-1) 	0.000149350031495618
6303007	34334	how to get sum() from alise column in sql	select sum(totalvisitedtime) from (             select 1234 as totalvisitedtime      ) as outertable 	0.000837980731219255
6303839	16170	create an sql query that checks the column name for a select string of words	select company, hc_version, max(av_version) as av_version from  (     select company, av_version, '8.5.0' as hc_version     from avcom     where av_version like '8.5.0%' ) group by company, hc_version 	0.000161170240033913
6303854	37306	how to find out where reference to primary key is used in sql server?	select * from information_schema.key_column_usage 	0.0235876803874812
6305161	23009	how to call a udf with a parameter which is known only at "execution time"?	select table1.column1  from table1 table1    cross apply udf1(table1.column2) as udf1 where table1.id=100 	0.0928782521105506
6305266	14624	how to execute more than one query at the same time in mssql	select     inspectionprocedurename as inspection, count(*) as total from         unitdata_vehicle where     (datediff(day, inspectiondatetime, getdate()) = 1) group by inspectionprocedurename union all select     inspectionprocedurename as inspection, count(*) as total from         anothertable where     (datediff(day, inspectiondatetime, getdate()) = 1) group by inspectionprocedurename union all 	0.000613764521514816
6306961	17358	left join 3 columns to get username	select u.username, u.user_id, r.record_id, u2.username as contributorname, u2.user_id as contributorid     from records r         inner join members u             on r.user_id = u.user_id         left join contributions c             inner join members u2                 on c.contributor_user_id = u2.user_id             on r.record_id = c.record_id     where r.record_id = 1 	0.0237733991435876
6307207	13303	mysql count not returning zero	select count( tbl_workstation.workstation_id ) as available, tbl_lab.room_no, tbl_lab.capacity from tbl_lab left outer join tbl_workstation on tbl_workstation.logged_on =0    and tbl_workstation.startup =1    and tbl_workstation.lab_name = tbl_lab.lab_name group by tbl_lab.lab_name 	0.412446800855609
6308524	7627	mysql - return all results from table a and selectively join with table b	select a.colour, b.customcolour  from default a  left join custom b on a.id = b.linkid and (b.ownerid is null or b.ownerid = 1) group by a.id order by a.colur 	5.0953228060763e-05
6308924	11015	modifying a mysql query that removes duplicates	select * from      (select * from persons order by deleted asc, date desc) as p group by first_name,last_name,work_phone 	0.54442257429825
6309608	2993	query to exclude row based on another row's filter	select id from table_a group by id having count(*) = count(case when substr(code,3,1) = '6' then 1 end) 	0
6310338	2258	regex for mysql query?	select substring_index(thefield,'-',-1) as buildnumber,        substring_index(substring_index(thefield,'-',-2),'-',1) as versionnumber from thetable 	0.777756573612772
6310977	15608	combine multiple queries on same mysql table	select questions.postid, questions.title, answers.postid, answers.title,   from table as questions  inner join table as answers on (questions.postid = answers.parent_postid); 	0.00169849083936739
6311303	8666	sql cross searching two tables	select category_code  from   product_import_queue         left join catalog_category_reference           on product_import_queue.category_code =              catalog_category_reference.class_id  where  catalog_category_reference.class_id is null 	0.132021282960679
6312086	12340	sqlite joining two columns together in select results	select firstname || lastname from person 	0.00271885178821157
6313485	33581	compare two strings in mysql	select url    from table   where instr('http: 	0.00803273309851976
6314128	13557	sqlite3, match and or	select * from mytable where name match 'andrew or bill' 	0.375006712175142
6316097	17881	mysql performance: query if an indexed column has a given value	select exists (select 1 from t where c = x) 	0.0842755531694273
6317966	2010	can alter table engine = innodb be run on multiple tables at the same time?	select concat('alter table ',table_name, ' engine = innodb;') from information_schema.tables where table_schema in ('db1','db2',....,'dbn') 	0.00291951619790715
6323847	33900	pulling multiple tables with mysql	select    c.setid   , s.setname   , b.bname    , count(*) as totalcards   , sum(if(c.rarity = 1,1,0) as total_of_rarity_1   , sum(if(c.rarity = 2,1,0) as total_of_rarity_2 from card c inner join `set` s on (s.setid = c.setid) inner join b on (b.bid = s.bid) group by c.setid 	0.0434802245360115
6328682	9226	create email list from sql developer data	select user_email,';' from user_list where other = 'y' 	0.00716205808291933
6331898	20720	mysql - limit inside a range	select * from table where id <'$1' and id >='$min' order by id desc limit 3 	0.116071243187802
6336711	5166	show unique (differentiating) data in a duplicate search in access?	select t1.col1, t1.col2,        t1.col3, t1.col4,        count(*)                     from   tbl t1 inner join tbl t2 on t2.col1 = t1.col1                   and t2.col2 = t1.col2                   and t2.id <> t1.id     group by t1.col1, t1.col2,          t1.col3, t1.col4           	0.00121535374686095
6337665	33761	alternating column value based on datetime column in t-sql query	select *,      (dense_rank() over (order by dateadd(hh,datediff(hh,0,dt),0))) % 2 as [band] from @test 	0.000102308725796275
6338253	25095	perform matrix-like calculation on a master table	select     m1.city as icity ,   m2.city as jcity ,   m1.month ,   m1.temperature - m2.temperature as final_temperature from     master m1     cross apply     master m2     on m2.month = m1.month 	0.0995644640984736
6338631	39116	sql query to get the record what has the max id number for each type	select * from (        select *,               row_number() over(partition by deviceid order by pid desc) as rn        from thetable      ) as t where rn = 1 	0
6339785	31366	how to convert timestamp format to 2011-05-10t06:58:00?	select date_format( date( from_unixtime( `timestamp` ) ), '%y-%m-%dt%h.%i.%s'); 	0.018347098721704
6340886	25758	get db data at jquery onchange textfield	select model,line, date from detail_model where model like 'cat' and startnumber <= '098x0003' and endnumber >= '098x0003' 	0.0427601266745208
6343224	28719	sql columns adding	select concat(member_firstname,'',member_lastname) as name from members; 	0.0550682833916836
6345810	18951	merging two mysql tables with unique fields	select a.user_id, a.firstname, a.lastname, b.address_city, b.address_state, b.address_country, b.address_zip, a.username, a.username_clean, a.password, a.email, a.activationtoken, a.lastactivationrequest, a.lostpasswordrequest, a.active, a.group_id, a.signupdate, a.lastsignin from users a left join deals_users_assoc b   on a.user_id = b.user_id group by a.user_id; 	0.000332960702906944
6346483	38204	t-sql - getting most recent date and most recent future date	select id, name, appointmentdate  from (select            id           ,name           ,appointmentdate           ,row_number() over (partition by id order by abs(datediff(dd, appointmentdate, getdate()))) ranking          from mytable) xx  where ranking = 1 	0
6347313	10120	sql query on link table where results must contain certain value	select distinct p.productid  from product p inner join productattributelink pa1 on pa1.productid = p.productid inner join productattributelink pa2 on pa2.productid = p.productid where pa1.attributeid in(25,5,44,46) and pa2.attributeid = 10 	0.000450078149428336
6347545	25978	duplicating and replacing field values on rows in mysql table	select col_1, col_2, col_3 from tablename union select 'ddd' as 'col_1', col_2, '0' as col_3 from tablename where col_1 = 'aaa'; 	0.000230839127800708
6347839	25809	small modification to a sql query to show only the unique and non empty recprds	select distinct comment_author_email from  `wp_comments` where comment_author_email != '' 	0.00140602162061529
6349239	39079	calculate sum from three tables	select sum(c.price), cl.name from client cl inner join client_courses clc on cl.client_id=clc.client_id inner join courses cs on clc.course_id=cs.course_id group by cl.name 	0.000852588527205619
6352448	11589	grouping in statement sql	select * from table1 t1, table1 t2 where t1.col1=t2.col1 and t1.col2=t2.col2 and t1.col3<4 	0.600292605773051
6353624	29507	how do i count total of row in mysql without get fatal error : allowed memory	select count(*) as `rows_count` from `table`; 	0.0117283267062996
6354753	37349	get the member id from database 	select member_id from members where concat(member_firstname,'',member_lastname) = 's thwaites' 	0.000196489777233317
6354830	12151	postgis: calculating minimum distance between a point and 2 fks: origin and destination	select least(    st_distance(st_geographyfromtext('srid=4326; point(-3 40)'), sorigin.point),     st_distance(st_geographyfromtext('srid=4326; point(-3 40)'), sdestination.point) ) from transport t left outer join spot sorigin on t.origin = sorigin.id  left outer join spot sdestination on t.destination = sdestination.id; 	0.00177665790308692
6355542	25439	search those records which has column value contains % sign in mysql	select * from table where column like '%\%%'; 	0
6357904	1497	mysql max count without order by	select age,     count(*),     (select max(c) from          (select count(*) as c from pacient where age between 20 and 40 group by age) as x) as t  from pacient  where age between 20 and 40  group by age  order by age; 	0.109795109060231
6359834	10328	select data from query without column names	select id as "", name as "", job as "" from table 	0.000632461417051566
6360764	20597	sqlite where condition on julian dates?	select * from products where juliandatecolumn > julianday('now') -1 	0.110109227623586
6360947	4004	select statement	select tc.line_item_id              item_id,        tc.fromval              cost_fromval,        tq.fromval               qty_fromval,        (tc.fromval*tq.fromval) prod_fromval,        tc.toval                  cost_toval,        tq.toval                   qty_toval,        (tc.toval*tq.toval)       prod_toval,   from (select line_item_id,         fromval,         toval,    from table   where fieldname = 'cost') tc join (select line_item_id,              fromval,              toval,         from table        where fieldname = 'quantity') tq   on tc.line_item_id = tq.line_item_id 	0.471607569159542
6362132	23058	mysql select dummy record when join condition not met	select date_format(a.timestamp, '%y-%m-%d') date, count(a.*) hits, a.user_id,   coalesce( b.username, 'guest') from hits a left join users b on a.user_id = b.id 	0.175800382120568
6363189	17229	mysql - reusing calculated values	select label, entry, back, round(entry/back*100,2) as 'rate' from (     select sum(t1.totalevents) as entry, sum(t2.totalevents) as back, t1.label as label     from trackreports_daily t1      .... rest of query ...  ) as temp; 	0.132470631458393
6363205	35720	how do i find the oldest record in a group using postgresql?	select group_id, title, check_out_date from book b1         where        check_out_date =         (select min(check_out_date)         from book b2 where b2.group_id =  b1.group_id) 	0.000864079393854217
6365978	21065	sql query to find number of users who are in two specific groups	select    u.userid from   usergroup u where   u.groupid in (27, 714) group by   u.userid having    count(u.userid) > 1 	0
6366946	24102	distinct key word only for one column	select    nid,    max(date_start),    max(date_end)  from    table_1 group by    nid 	0.00011068148569702
6368621	23904	mysql - search in longtext	select postid,content from posts where content like '%keyword%'; 	0.634446358603947
6370326	34904	select rows from key-list in a single column	select a.* from foo a where a.id in    (select a.id from bar b     where instr(','||b.concatkeyfield||',', ','||a.id||`,', 1, 1) > 0) 	0.000185601422651928
6371021	38610	select on multiple tables	select 'product' as type, product_id as id, name, model from product where ... union all select 'tire' as type, tire_id as id, name, model from tire where ... 	0.0286939145661848
6371148	29731	how to export data from an ancient sql anywhere?	select * from #{table}; output to "c:\export\#{table}.csv" format ascii delimited by ',' quote '"' all; select * from #{table}; output to "c:\export\#{table}.txt" format text; 	0.0336583679995486
6372906	17681	mysql: multiple condition with sub-query	select a.* from a     left outer join b         on (a.cityid = b.id or a.regionid = b.id or a.countryid = b.id)  where b.id is not null 	0.697608156620956
6375410	37840	create temporary table where concat groups are placed into their own columns?	select `al`.`id`,     (     select `ft`.`name`     from `format_types` `ft`     inner join `album_occurrences` `ao` on `ft`.`id` = `ao`.`format_type_id`     where `ao`.`album_id` = `al`.`id`     and `ft`.`id` = 1     ) `format_name_1`,     (     select `ft`.`name`     from `format_types` `ft`     inner join `album_occurrences` `ao` on `ft`.`id` = `ao`.`format_type_id`     where `ao`.`album_id` = `al`.`id`     and `ft`.`id` = 2     ) `format_name_2`,     (     select `ft`.`name`     from `format_types` `ft`     inner join `album_occurrences` `ao` on `ft`.`id` = `ao`.`format_type_id`     where `ao`.`album_id` = `al`.`id`     and `ft`.`id` = 3     ) `format_name_3`,     (     select `ft`.`name`     from `format_types` `ft`     inner join `album_occurrences` `ao` on `ft`.`id` = `ao`.`format_type_id`     where `ao`.`album_id` = `al`.`id`     and `ft`.`id` = 4     ) `format_name_4` from `albums` `al`; 	0
6375900	4810	sql: retrieve unique structure	select group_id from my_table oq where domain_id  in (2124, 2125) group by group_id having count(group_id)=2 and  count(group_id) = (select count(iq.domain_id)  from my_table iq where iq.group_id=oq.group_id) 	0.00605740984178219
6377104	6950	sql update only if relationship exists	select id from batches left join tasks on batches.id = tasks.id where tasks.id is null 	0.0438486863443377
6377507	7742	sql server - combine single ids into range	select      min(itemid)     ,max(itemid) from     (         select itemid, rank() over (order by itemid) r from items     ) tmp group by     itemid - r 	0
6378509	7833	what is the most efficient way to search rows in a table based on metadata stored in another table?	select * from movies  where exists(   select null    from movie_attributes   where movies.id = movie_attributes.movie_id and         key = 'genre' and value in ('comedy', 'adventure') ) and  exists(   select null    from movie_attributes   where movies.id = movie_attributes.movie_id and         key = 'actor' and value = 'harrison ford' ) 	0
6379807	38342	select max(column) from table (column is varchar)	select max(cast(substring(my_id, 1, 6) as int)) from my_table 	0.00140823271336465
6380237	16959	sql query counting entries in 3 tables	select a.user_id,         coalesce(b.cnt_b, 0) posts_count,         coalesce(c.cnt_c, 0) messages_count   from user a left join              (                 select user_id, count(1) cnt_b                     from posts b                   group by user_id             ) b      on a.user_id = b.user_id left join             (                 select user_id, count(1) cnt_c                     from messages c                   group by user_id             ) c     on a.user_id = c.user_id 	0.00137238363469797
6381071	3070	sql and distinct	select month(birthday), count(*) as birthdaycount from user group by month(birthday) 	0.199920213876311
6381304	2994	mysql convert minutes to seconds	select foo.min*60 as sec from foo 	0.00578846873555657
6383830	29545	sql with specific limit	select *   from table     where user_id in      (select distinct(user_id) from table order by user_id limit 3); 	0.174259598132764
6383911	6856	sql query to sort data on one column only but not change the others columns	select t2.id, t1.name from     (select row_number() over(order by id desc) as rownumber,            name     from mytable) as t1     inner join         (select row_number() over(order by id asc) as rownumber,                 id          from mytable) as t2 on t1.rownumber = t2.rownumber 	0
6385131	26548	sqlite - select count(*how many times a value is stored*)	select answer, count(*) from yourtable group by answer; 	0.0204442261447286
6388035	19385	merging fields in t-sql	select limit as val1,    lower as val2,    upper as val3 from tablename union all select select deviation as val1,    lower as val2,    upper as val3 from tablename 	0.0370099023827885
6389392	18078	mysql query two table join	select rsamecompany.resid, rsamecompany.firstname, rsamecompany.lastname from resource r     inner join resource rsamecompany         on r.companyid = rsamecompany.companyid      inner join account a         on r.resourceid = a.resourceid          and a.accid='7' 	0.110599934936932
6389873	17602	how to count unique occurences of data in sql	select     q.treatment,     count(*) as [total letters sent] from     [select distinct         treatment,         client_id     from         research     ]. as q group by     q.treatment; 	0.000359938870532656
6390388	28941	how to query the permissions on an oracle directory?	select *    from all_tab_privs   where table_name = 'your_directory';   	0.16708863009244
6390590	29985	add a comma at the end of each returned value	select regemail + ',' as regemail from [db182324492].[dbo182324492].[tblxuduserregistration] 	0
6391703	32268	sql select not a string doesn't return null value	select * from #temps where isnull(name, '') <> 'foo' 	0.0680585115297153
6393120	25403	how to handle overlapping dates in mysql?	select count(*)<1 as available from `table` where (`startdate`>checking_start_time and `startdate`<checking_end_time) or (`enddate`>checking_start_time and `enddate`<checking_end_time) or (`startdate`<checking_start_time and `enddate`>checking_end_time) 	0.00917695986360408
6393477	28842	mysql - select # of rows as well as other data at same time w/o considering limit	select sql_calc_found_rows * from tbl_name where id > 100 limit 10; select found_rows(); 	0
6393989	19449	conditional max in sql	select employeeid, sum(totalsales), sum(case when maxmonth = 1 then totalsales else 0 end) recentmonthsales from  (     select *, rank() over(order by monthnumber desc) maxmonth     from     (         select employeeid, monthnumber, sum(totalsales) totalsales         from vwsales         group by employeeid, monthnumber     ) tt ) tt group by employeeid 	0.603998046317701
6395034	16542	sqlite - select the newest row with a certain field value	select * from tbl where id in (select max(id) from tbl group by key); 	0
6395273	37375	mysql - join the same table's data	select   q.id as q_id,q.message as q_message ,a.message as q_answer   from comments q left outer join comments a on (a.parent_id = q.id and a.is_answer=1 and q.is_answer=0) 	0.00638067917692763
6402425	26185	removing duplicates and sort results emulating group_concat	select  id_exam,  method = replace ((select distinct method as [data()]                    from methods                    where id_exam = a.id_exam                                          order by method for xml path('')), ' ', ',') from  methods a where id_exam is not null group by id_exam 	0.571312265811702
6403213	30901	optimize 2 mysql queries into one	select *  from banners  where section = 1  and pageid = if(     (select count(*) from banners where section = 1 and pageid = 2) = 0,      0, 2 ); 	0.0428497798215213
6403896	13269	retrieve 10 records from mysql?	select * from table order by id desc limit 0, 10 	0
6404588	24208	mysql query for maximum duplicate value	select b_id, count(b_id)  from books  group by b_id  order by count(b_id) desc limit 1; 	0.0010625741287851
6405780	19640	sql subqueries - which order do you perform the select statements?	select ethnicity, count(referral) from demographics, marketing where demographics.id = marketing.source_id and referral = 'website' and gender = 'female' order by ethnicity 	0.791491635710472
6406287	17425	how to trace the foreign keys?	select      fk.table_name as child_table,      cu.column_name as child_column,      pk.table_name  as parent_table,      pt.column_name as parent_column,     c.constraint_name  from  information_schema.referential_constraints c  inner join  information_schema.table_constraints fk      on c.constraint_name = fk.constraint_name  inner join  information_schema.table_constraints pk      on c.unique_constraint_name = pk.constraint_name  inner join  information_schema.key_column_usage cu      on c.constraint_name = cu.constraint_name  inner join  (      select          i1.table_name, i2.column_name      from          information_schema.table_constraints i1          inner join          information_schema.key_column_usage i2          on i1.constraint_name = i2.constraint_name          where i1.constraint_type = 'primary key'  ) pt  on pt.table_name = pk.table_name  order by  1,2,3,4 	0.00315871319435325
6406405	18239	php & mysql: how to narrow down the tag search result?	select * from  ( select root_mm_tagged_pages.tag_id as atag_id, root_mm_tagged_pages.pg_id as apg_id, at.tag_name as atag_name from root_mm_tagged_pages left join root_tags as at on at.tag_id = root_mm_tagged_pages.tag_id ) as aat join ( select root_mm_tagged_pages.tag_id as btag_id, root_mm_tagged_pages.pg_id as bpg_id,  bt.tag_name as btag_name from root_mm_tagged_pages left join root_tags as bt on bt.tag_id = root_mm_tagged_pages.tag_id ) as bbt on aat.apg_id = bbt.bpg_id where aat.atag_name = 'a' and bbt.btag_name = 'b' 	0.117220031227988
6406789	38344	how to join two tables with one mandatory condition and an optional one	select m.* from media m   inner join (     select id_media     from tag_media     group by id_media     having count(id_tag in (required1, required2) or null) = 2        and count(id_tag in (option1, option2, option3) or null) >= 1   ) t on m.id_media = t.id_media 	0.0132324961478236
6408843	3544	influencing how mysql-cli-client displays results from select queries	select * from table\g 	0.086312604102187
6409068	38894	sql query to find articles which belong to all selected tags	select at.article_id from article_tags at where at.tags_id in (2,3,4) group by at.article_id having count(*) = 3 	0
6410134	275	how to select sql results group by weeks	select  productname, weeknumber, sum(sale) from (     select      productname,     datediff(week, '2011-05-30', date) as weeknumber,     sale     from table ) group by productname, weeknumber 	0.0194263643876741
6410811	8557	`count` of subqueries	select l.listing_id, count(e.enquiry_id) as num_enquiries  from listings as l join enquiries as e on l.listing_id = e.enquiry_itemid and    e.enquiry_itemtype='listing' and enquiry_datesent >= '2011-01-1 0:01' and enquiry_datesent <= '2011-12-31 23:59'  group by l.listing_id order by listing_title_e 	0.257009670386189
6410823	30924	help with select distinct	select distinct null, monthly_cost from plans where tariff not like 'cat extra' union select tariff, monthly_cost from plans where tariff like 'cat extra' 	0.754926523693137
6411249	5412	count of orders by city	select count(sfoa.city) as count_of_city, sfoa.city  from sales_flat_order as sfo  left join sales_flat_order_address as sfoa on sfo.entity_id=sfoa.parent_id  where sfoa.address_type="shipping"  group by sfoa.city; 	0.000883901506854858
6411916	11073	sql incremenet and reset variable insert	select id, datefield, fielda,      row_number() over(partition by id order by datefield asc) as counter from yourtable order by id, datefield 	0.32003290321883
6412182	16601	how to get minutes from two different date in mysql	select * from user where timestamp >= now() - interval 5 minute 	0
6412757	26738	select distinct first row from database	select number, min(time) from table group by number order by number desc limit 2 	7.07545867716397e-05
6414274	35734	how to retrieve all rows thats co-ords are within a specifc radius in mysql database	select * from table where pow((_lat_-lat1),2) + pow((_lng_-lng1),2) < 1 	6.12225305607234e-05
6414678	8085	mysql - need to get latest of table a when referenced from table b	select * from     (select `action`.`id_action`, max(`action`.`revision`),          (select id           from action as a           where a.id_action = action.id_action           order by revision desc           limit 1) as id_with_max_revision     from `action`     where     action.department = 1     group by `action`.`id_action`     ) as action_max_revision join action on action_max_revision.id_with_max_revision = action.id left join action_status on       `action_status`.`id_action` = `action`.`id_action` join `priority` on       `action`.`id_priority` = `priority`.`id` order by `id_priority` asc, `id_parent` asc, `sort_order` asc 	0
6414945	28892	select * from table where col has at least 3 identical	select * from table where col in (     select col from table group by col having count(*) > 3 ) 	5.24259595549619e-05
6415516	7667	searching sql db table for japanese terms	select * from jtable where searchterm = n'ろくでなし' 	0.505605933171737
6415526	3107	how to select records from a table that has a certain number of rows in a related table in sql server?	select    b.foreignkey,    count(b.foreignkey) as bidcount  from     b where     b.foreignkey in (select a.id from a)  group by     b.foreignkey  having     count(b.foreignkey) < 3 	0
6417511	17830	mysql query: merge rows in three tables and output as one	select    t1.user,    t1.pid,    count(t3.spec) as countround from table1 t1   left join table2 t2 on t1.pid = t2.pid    left join table3 t3 on t2.lid = t3.lid and t3.spec = 'round' group by   t1.user,   t1.pid 	0.000718996420472789
6418842	20780	select multiple sums with mysql query and display them in separate columns	select sum(case when name='bob' then points end) as bob,        sum(case when name='mike' then points end) as mike   from score_table 	0
6421978	32417	eliminate row that has null value using cte	select      id,     dense_rank() over(order by substring(data,2,len(data))*1) as rowid,     position,     data  from      @t  where      data is not null group by      id,rowid,position,data 	0.00187259800338678
6422324	30938	sql join queries with multiple tables	select w.person_name from works w      inner join manages m         on m.person_name = w.person_name             inner join works wmanager                 on wmanager.person_name = m.manager_name where w.salary > wmanager.salary 	0.437863647837509
6422489	18578	joining multiple rows	select distinct   a.id, a.name from jobs as a inner join logs b on b.job_id = a.id inner join logs c on c.job_id = a.id where   b.event = 'initialized'   and   c.event = 'failed' 	0.0133751686150849
6424132	28200	count by day, count by week, in a grouped select statement	select dbo.clients.town as town,  count(*) as wktotal,  sum(case when datepart(dayofyear, status_date) = datepart(dayofyear, getdate()) then 1 else 0 end) as daytotal from dbo.clients  where dbo.clients.status like 'status 1%' and  datepart(week, getdate()) = datepart(week, dbo.clients.status_date) and year(getdate())= year(dbo.clients.status_date) group by dbo.clients.town  order by dbo.clients.town 	0
6424443	4369	month start in sql server 2005	select dateadd(mm, datediff(mm, 0, getdate()), 0) as firstdayofmonth 	0.0313816013633954
6425353	16383	ms sql - find relational tables in database	select k_table = fk.table_name, fk_column = cu.column_name, pk_table = pk.table_name, pk_column = pt.column_name, constraint_name = c.constraint_name from information_schema.referential_constraints c inner join information_schema.table_constraints fk on c.constraint_name = fk.constraint_name inner join information_schema.table_constraints pk on c.unique_constraint_name = pk.constraint_name inner join information_schema.key_column_usage cu on c.constraint_name = cu.constraint_name inner join ( select i1.table_name, i2.column_name from information_schema.table_constraints i1 inner join information_schema.key_column_usage i2 on i1.constraint_name = i2.constraint_name where i1.constraint_type = 'primary key' ) pt on pt.table_name = pk.table_name 	0.069138010627229
6426476	6467	how to interpret a column as having a different character set per query?	select upper(convert(binary(filename.name) using utf8)) from filename; 	0.000497564930459759
6427265	2205	sql - group session log entries and order the groups by session start time	select  yt.item_id ,       yt.item_datetime ,       yt.app ,       yt.action ,       yt.session_id from    (         select  session_id         ,       min(item_datetime) as mindate         from    yourtable         group by                 session_id         ) sessions left join         yourtable yt on      yt.session_id = sessions.session_id order by         session.mindate ,       yt.item_datetime 	0.00016279770556397
6427352	28133	a column called status in mysql	select `t`.`status`. from `t` 	0.0395662372364486
6428429	9394	multi count in single query - oracle	select count( case                   when click_date='2011-06-20' then 1                   else null               end ) as thisdaycount      , count(*) as todaycount from mytable where click_date between '2011-05-01' and '2011-06-20' ; 	0.2044873465773
6429483	32051	single sql query that returns list of "most commented" relative to past 7 days, but the list always has to contain something	select   articleid,   count(commentid) as number_of_comments,   datediff(current_date, created) div 7 as weeks_old from   comment group by   articleid,   weeks_old order by   weeks_old asc,   number_of_comments desc limit 10; 	0
6431472	19334	how to dynamically add to the tsql where clause in a stored procedure	select count(*) from   mytable where  shipdate >= @firstdayofmonth and    shipdate <  @lastdayofmonth and    ordertype = 1 and    (@excludephoneorders = false or (not ordercode like '%3' and not ordercode like '%4')); 	0.503165581044534
6431564	34290	alter every double fields of a table	select 'alter table ' + table_name + ' alter column ' + column_name + 'type numeric(15,3)'     from information_schema.columns   where data_type = 'double precision'         and table_name = 'your_table_name' 	0.00138961040565941
6431714	31370	design question: how to determine distance between multiple lat/long points?	select haversine(lat1,lng1,lat2,lng2,units); 	0.182819029415308
6431892	34745	mysql query, fetching avg results	select       dc.*,        coalesce( s.avgscore, 0 ) finalavg    from        dog_clinic dc          left join ( select dcs.input_id,                             avg(dcs.score) as avgscore                         from                             dog_clinic_score dcs                         group by                             dcs.input_id) s              on dc.id = s.input_id    order by        coalesce( s.avgscore, 0 ) desc,       dc.visited desc     limit        0,10; 	0.423480951775109
6434474	8129	select first word - mysql query	select substring_index(field, " ", 1) .... 	0.0202195739843033
6434896	14711	find a string within a string - sql takes too much time	select           e.* from    customeremails e  where   exists          (             select  email              from    customeremailids c              where   ( isnull(e.[from],'') + '/' + isnull(e.[to],'') ) like  '%'+c.email+'%'          ) 	0.262264948732437
6436858	19965	how to do a sql inner join between 2 tables when using a partial key?	select * from table1  inner join table2 on table1.studentid = concat('student',table2.id) 	0.0106379292337649
6436897	26690	php mysql, joining more than two tables together with similar ids?	select products.title, product_lines.pl_title, manufacturers.man_title  from products inner join product_lines on products.pl_id = product_lines.pl_id inner join manufacturers on product_lines.man_id = manufacturers.man_id 	0.000358664215081556
6437380	10977	merge two queries into one	select    t.name,   t.score,   (select      count(t.team_id) as rank    from      team as t    where     t.score > (select t.score from team as t where t.team_id = '$id')   ) as rank,   count(m.user_id) as membercount from    team as t, team_member as m where    t.team_id = '$id' and m.team_id = '$id' 	0.000523894141564517
6438137	2007	change output style of while loop	select lnid,lnline,lntitle,group_concat(clongname) from table group by lnid,lnline,lntitle; 	0.647436043991886
6439196	40030	sql/sqlite: adding a column in a select statement based on a value of another column	select word,definition from (   select word, definition, position, count from words    where position = 5000 and count < 5 and length <= 6   and definition is not null union all   select word, "" as definition, position, count from words   where not (position = 5000 and count < 5 and length <= 6              and definition is not null) ) order by position asc, count desc 	0
6439716	13063	need to generate n rows based on a value in a column	select * into #tablea from  (     select  1 as id, 3 as quantity, 'myref' as refcolumn     union all     select 2, 2, 'anotherref' ) t ;with nbrs ( number ) as (     select 1 union all     select 1 + number from nbrs where number < 99 ) select    a.id, a.refcolumn + cast(n.number as varchar(10)) from    #tablea a    join    nbrs n on n.number <= a.quantity 	0
6440604	18981	sqlite select x-th row	select * from table limit 2,1 	0.0526213270791142
6445573	2554	sql find the same column in different tables	select name from syscolumns sc1 where id = object_id('table1') and exists(select 1 from syscolumns sc2 where sc2.name = sc1.name and sc2.id = object_id('table2')) 	0
6445690	13277	tsql dbo.split including a key	select    sv.rowid,   sv.[value],   valueid  from dbo.product as p   cross apply dbo.split2value('deli?', p.notes, p.p_c_id) as sv 	0.0860960923494729
6446377	39033	help in performing date arithmetic with timestamp values in oracle	select * from table where to_date(year||'/'||month||'/'||day, 'yyyy/mm/dd') >= trunc(sysdate) - 2 	0.669892375223115
6446742	7562	casting a geography type in postgis	select st_covers(     boundary,      st_geographyfromtext('point(2 2)') )  from source_imagery 	0.60003709232528
6446889	39065	sql: how to exclude maximum if another column doesn't match	select * from t where enrolldate= (select max(enrolldate) from t as t1   where t.id=t1.id)   and t.code='wheat' 	6.38814656448905e-05
6447353	41149	how to scroll through a count query in mysql/php	select count(*) as count, ( 3959 * acos( cos( radians( 34.469994 ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( -118.196739 ) ) + sin( radians( 34.469994 ) ) * sin( radians( lat ) ) ) ) as distance from users having distance < 150 	0.229646386263364
6447635	13752	count query returning unexpected results	select count(*) as count from users where ( 3959 * acos( cos( radians( 37.774929 ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( -122.419418 ) ) + sin( radians( 37.774929 ) ) * sin( radians( lat ) ) ) ) < 150 	0.688507977021502
6447931	3457	best practice for loading non-existent data	select row_number() over(order by t1.[number]), 'custom data 1', 'custom data 2' from   master..spt_values as t1   cross join (select [number] from master..spt_values where [type] = 'p' and [number] between 1 and 50) as t2 where   [type] = 'p' and t1.[number] between 1 and 1000 	0.17778292883088
6448223	1969	xml input getting truncated	select     inputxml     from tablea     where somekey = '<somekey>' 	0.369933295577925
6449243	13408	calculating the number of records after doing a group by in sql	select count(*)  from (     select (sum(wins) * 2) + sum(ties) as rank     from scores     group by userid ) tt where rank > 35 	0.00042357819655326
6449694	827	query for converting rows in columns	select hopper_close_time  new_column_name from table1 where your_condition_here union all select  hopper_open_time  new_column_name from table1 where your_condition_here union all select  sr_no             new_column_name from table1 where your_condition_here union all select cal_done           new_column_name from table1 where your_conidtion_here union all selectnpartial_calc_done_time new_column_name from table1 where your_condition_here 	0.0221522453130894
6450156	38628	sybase: composing a where for a timestamp datatype	select * from dev.conf where last_update < '2011-06-16 04:17:29.463114' 	0.142651676505856
6452254	6376	plsql - count "n" max values	select cause,        work,        cnt as "count" from (   select cause,           work,           count(work) as cnt,          row_number() over (partition by cause order by count(work) desc, work desc) as rown   from your_table group by cause, work ) where rown <= 2; 	0.00279693508527647
6453986	27677	select values from database based on cases	select     case         when x.testcase > 1 then "string_literal"         else tb1.field_p     end as somecol from    tb1    cross join    (    select count (distinct tb1.field_k) as testcase    from tb1    ) x 	0.000146711749685138
6454191	3780	select top (outerquery.amount) * from 	select * from x inner join (     select row_number() over (order by someval) as rn, *     from y ) as z on x.id = z.x_id where    z.rn <= x.integeramount) 	0.0552758405673359
6455924	32160	select rows based on value between 2 fields	select * from valuedb where min_price < 250 and max_price > 250 	0
6456011	968	get only nonunique rows from table	select a,b from tablea group by a,b having count(*)>1 	0
6457581	38740	sql get users within range	select * from usertable where datediff(day, datejoined, dateunsub) <= 30 	0.000726292212184375
6459406	35548	multiple sql counts	select     billinglawyer,     sum(case when itemsent is not null then 1 else 0 end) as sent,     sum(case when itemreceived is not null then 1 else 0 end) as received from     tbl_matteritem mi join tbl_matter m on     mi.matterid = m.matterid group by billinglawyer order by billinglawyer 	0.134848415530906
6459694	28796	mysql select where column like column1%column2	select * from family_watchdog_offender where name  like concat(firstname, '%', lastname); 	0.728985740748947
6459781	27207	sql join on two columns	select message, uf.email as fromemail, ut.email as toemail from messages join users uf on messages.fromuser = uf.id join users ut on messages.touser = ut.id 	0.0153795035620054
6460176	5805	stuck on sql query to count rows	select count(*) as totaluservotes   from tblarticlevotes as v inner join   tblarticles as a on v.articleid = a.id   where a.authorid = 13405 	0.170903415273438
6460362	37859	subquery, temporary table, mysql variables, or procedure to get pos and neg search terms from a column in one table to query another	select d.biz_id,         temp.adventure_id,         d.id as deal_id  from   daily_deals d         join (select adv.activity,                      st.adventure_id,                      group_concat(st.term separator '|') as `match`               from   search_terms st                      join adventures adv                        on adv.id = st.adventure_id               group  by adv.id) temp           on d.title regexp temp.match; 	0.000165754475757389
6461336	20907	another sql 'rows to columns' question	select id, max(case when seq = 1 then model end) as model1, max(case when seq = 1 then year end) as year1, max(case when seq = 2 then model end) as model2, max(case when seq = 2 then year end) as year2, max(case when seq = 3 then model end) as model3, max(case when seq = 3 then year end) as year3, max(case when seq = 4 then model end) as model4, max(case when seq = 4 then year end) as year4 group by id 	0.00471524506968366
6461738	22206	how to export data for a manual read?	select 'col1:' + char(13) + char(10) + col1 + char(13) + char(10)      + 'col2:' + char(13) + char(10) + col2 + char(13) + char(10)      + 'col3:' + char(13) + char(10) + col3 + char(13) + char(10)      + char(13) + char(10) from table 	0.145685637300583
6462123	7951	php: merging arrays with mysql results and sorting them by an array key	select * from (         select p.page_url as url,         count(*) as occurrences     from page p, word w, occurrence o     where p.page_id = o.page_id         and w.page_word_id = o.page_word_id         and w.word_word like '' '" . $stemmed_string . "' '%'     group by p.page_id     union     select f.file_url as url,         count(*) as occurrences     from files f, filenames fn, fileoccurrence fo     where f.file_id = fo.file_id         and fn.file_word_id = fo.file_word_id         and fn.file_word like '' '" . $stemmed_string . "' '%'     group by f.file_id ) t order by occurrences desc 	0.00113780486128839
6462277	27900	sql server 2008: many to many tables with relational tables ordering field + grouping	select     p.id,     p.baseurl,     ts.*,     tc.*,     ta.*,     pts.ordernumber as suitesorder,     tstc.ordernumber as casesorder,     tcta.ordernumber as actionsorder from     projects p join     projecttotestsuites pts     on pts.projects_id = p.id join     testsuites ts     on ts.id = pts.testsuites_id join     testsuitestotestcases tstc     on tstc.testsuites_id = ts.id join     testcases tc     on tc.id = tstc.testcases_id join     testcasestotestactions tcta     on tcta.testcases_id = tc.id join     testactions ta     on ta.id = tcta.testactions_id where     p.id = @id order by     pts.ordernumber,     tstc.ordernumber,     tcta.ordernumber 	0.0929937271513645
6463233	20040	finding total and unique hits for each product	select productid, count(*) totalhits,      count(distinct          concat(ip,             date_format(hittime, '%y%m%d%h'),             round(date_format(hittime, '%i') / 5) * 5)         ) uniquehits from table group by productid 	0
6464656	23502	find mininum not used value in mysql table	select t1.id+1 as missing  from tbl as t1  left join tbl as t2 on t1.id+1 = t2.id  where t2.id is null  order by t1.id limit 1;  + | missing |  + |       3 |  + 	0.0237421251228117
6467254	20471	mysql count distinct query	select post_id from postextras group by post_id, comment_type having count(comment_type) > 1 	0.19934166805221
6468813	32278	assign a login to a user created without login (sql server)	select suser_sname(0x0105000000000009030000001139f53436663a4ca5b9d5d067a02390) 	0.0123771214092824
6469934	4306	parsing data rows in plsql	select max(id) result   from (   select 1 id from dual   union all   select 0 id from dual )     result          1   1  select max(id)   2    from (   3    select 0 id from dual   4    union all   5    select 0 id from dual   6    union all   7    select 0 id from dual   8* ) sql> /    max(id)          0 	0.0368764685575058
6470648	8437	mysql: joining a table with itself without using distinct 	select f1.fuid, f1.fname from friends f1, friends f2 where f1.uid = x1       and f2.uid = x2       and f1.fuid = f2.fuid 	0.161712387802012
6472436	32232	mysql match with multiple keywords	select id, manuf, model, type,        @m := match(manuf) against('bmw') as score_manuf,        @t := match(type) against('car') as score_type,        @m + @t as score   from items; 	0.162544455483524
6472970	20962	mysql query for multiple tables being secondary tables multiple items?	select g.name, group_concat(c.command) as commands from site_access b      join groups g          on b.group_id = g.id      join groups_commands gc         on g.id = gc.group_id     join commands c         on gc.command_id = c.id where b.site_id = 1  group by g.name order by g.status asc 	0.00262189925306369
6473130	2279	query sql server system tables for character data type sizes	select  * from  information_schema.columns where character_maximum_length > 450 	0.605312938216579
6473279	23069	selecting 1 word out of a field using sql	select 'srn='+left(stuff(@s, 1, charindex('srn=', @s)+3, ''), patindex('%[^0-9]%', stuff(@s, 1, charindex('srn=', @s)+3, '')+' ')-1) 	0.000983026361626991
6476595	6310	query mysql and compare entries?	select b1.tid as tid, min(datediff(b2.date,b1.date)) as responsetime from billing b1 inner join billing b2  on b1.tid = b2.tid where b1.action='new support ticket opened' and b2.action like 'new ticket response made by%' group by tid 	0.00270709447193405
6476688	3642	empty select result when dates are used	select nvl(max((case            when to_char(sysdate, 'dy') = 'sat' then 1            when to_char(sysdate, 'dy') = 'sun' then 1           else 0 end)), 1) status  from mytable where mycondition; 	0.0236976773384628
6481044	34251	are database queries for everyone in a user list too much?	select username,email,etc from user_table where userid in (1,15,36,105) 	0.100758611291587
6483276	4671	mysql query: one table, two levels of select. is there a better way?	select *  from double_select where orderid in      (select orderid       from double_select       where `status` = 'ready') 	0.0153572566868984
6483848	37194	select true if more then 0 in t-sql	select      id,      case          when count > 0 then 'true'         else 'false'     end as count from mytable 	0.0794322514190228
6484197	37291	how to combine multiple activity data like facebook with sql server?	select min(b.membername), count(*) as total from network_feed a join member b on a.memberid = b.memberid where a.feedtype = 1 	0.512925949061455
6487348	6304	how to count rows from multiple tables mysql	select sum(subcount) as totalcount      from ( select count(*) as subcount from table1 where approved = 0            union            select count(*) as subcount from table2 where approved = 0 ) 	0.000369761686634486
6487439	15225	storing multiple values in one field	select students.id,        organizations.name from students  inner join studentsmajors on students.id = studentsmajors.studentid inner join organizationsmajors on studentsmajors.majorid = organizationsmajors.majorid inner join oranizations on organizationsmajors.orgid = organizations.id where students.id = 1 	0.000990186751806634
6489417	11716	how can i only select the newest entries from a table	select j_id, j_name, j_readdate, j_i_id from (   select j_id, j_name, j_readdate, j_i_id,          row_number() over (partition by j_name order by j_readdate desc) as rn   from jobs ) j where j.rn = 1 order by j_readdate desc 	0
6489848	9865	percent to total in postgresql without subquery	select      country_id,      count(*) over (country_id)      ((count(*) over (country_id)) * 100) / count(*) over () )::decimal) as percent from      users where     cond1 = true and cond2 = true and cond3 = true 	0.00863207192310877
6490348	34091	need to show time in hh:mm format only	select      cast(datepart(hour, '2007-06-01 12:15:22') as nvarchar)+':'+     cast(datepart(minute, '2007-06-01 12:15:22') as nvarchar); 	0.00111949978918766
6492562	25376	mysql query sorting	select * from assigned order by field(id,3,1,2) 	0.549307876757786
6493153	21292	select one line of each code	select mytable.* from mytable join (select min(codmsg) as codmsg, anothercod from mytable group by 2) x         on mytable.codmsg = x.codmsg 	0.000146176184120437
6494872	15548	access sql: top 1 of a subcategory (or max())	select ac, max(hours), max(cycles) from flights where flight_date <= cdate(asked_date) group by ac 	0.0589532441758624
6496866	13236	best way to do a weighted search over multiple fields in mysql?	select *,     if(             `name` like "searchterm%",  20,           if(`name` like "%searchterm%", 10, 0)       )       + if(`description` like "%searchterm%", 5,  0)       + if(`url`         like "%searchterm%", 1,  0)     as `weight` from `mytable` where (     `name` like "%searchterm%"      or `description` like "%searchterm%"     or `url`         like "%searchterm%" ) order by `weight` desc limit 20 	0.0897185784645495
6497532	18894	joining 2 tables with where clause	select t1.user_id from `table 1` t1 inner join `table 2` t2 on t1.user_id=t2.user_id where t2.status=1 	0.232600863546616
6497773	3374	mysql query to return count of rows of multiple user-input parameters	select u.realname as reporter, count(b.id) as bugs  from profiles u inner join bugs b on u.userid = b.reporter   where u.userid in (1,4)  group by u.userid, u.realname 	0.00144356713652774
6498072	32852	information schema and primary keys	select  c.table_name, c.column_name,c.data_type, c.column_default, c.character_maximum_length, c.numeric_precision, c.is_nullable              ,case when pk.column_name is not null then 'primary key' else '' end as keytype from information_schema.columns c left join (             select ku.table_catalog,ku.table_schema,ku.table_name,ku.column_name             from information_schema.table_constraints as tc             inner join information_schema.key_column_usage as ku                 on tc.constraint_type = 'primary key'                  and tc.constraint_name = ku.constraint_name          )   pk  on  c.table_catalog = pk.table_catalog             and c.table_schema = pk.table_schema             and c.table_name = pk.table_name             and c.column_name = pk.column_name order by c.table_schema,c.table_name, c.ordinal_position 	0.0227851884359993
6501355	12685	filtering sql results	select * from mytable where `category` = '1' and id % 3 = 1 order by `id`  desc limit 0 , 10 	0.34275184235203
6502375	30840	query for an exact match for a string in to a column having text fields(more then one strings)	select ... where description like '% diamond %'; 	0.000694647959514613
6502414	3262	sql server conditional select depending on input parameter	select  ...     from    ...     where   [a] = @a and          (@b = 0 or [b] = @b) 	0.205233269025117
6503872	14466	sybase sql union of two different tables	select  intcolumn as col1 ,       charcolumn as col2 ,       decimalcolumn as col3 from    table1 union all select  null ,       'halelujah' ,       doublecolumn from    table2 	0.00348735687267751
6504502	35079	sql custom limit	select *     from events     where startdate in (select distinct startdate from events order by startdate desc limit 0,7)    and startdate >= date     order by startdate asc, title as 	0.69190393267109
6505166	36061	pull latest version of content for all languages in a revisions system	select * from `news_articles_languages` where id in(select max(id) from `news_articles_languages` where article_id = 1 group by language_id) 	0.00010949471580046
6505484	18705	getting status name corresponding to the member_id	select st.membershipstatus_name from memberstable m left join membertomshiptable sh on m.member_id = sh.member_id left join membershipstatustable st on sh.memberstatustype_id = st.membershipstatustype_id where m.member_id = [member_id_here] 	0.00101131599407012
6506418	36743	sql searching multiple words in a string	select * from table where    columnname like'%david%' and    columnname like '%moses%' and columnname like'%robi%' 	0.0639721290358089
6506709	39929	mysql query to receive random combinations from two tables	select *  from ( select firstname from firstnames order by rand( )  limit 10 ) as tb1 join ( select lastname from lastnames order by rand( )  limit 10 ) as tb2 on 1=1 	0.00013277049795567
6507755	21370	how do i list (or export) the code for all triggers in a database?	select      o.[name],             c.[text] from        sys.objects as o inner join  sys.syscomments as c on      o.object_id = c.id where   o.[type] = 'tr' 	0.00405815182613098
6508107	26702	sql statement to return elements from a column only if no elements from a different column match	select document_id from signoffs_table as t1 where signers_list like "%bob%" and not exists (     select 1 from signoffs_table as t2     where (t2.user_id = $bobsid) and t2.document_id = t1.document_id ) 	0
6508443	34484	getting the maximum value from interrelated mysql tables	select a.id, max(c.myfield) as cfield from a     left outer join b         on a.id = b.a_id             left outer join c                 on b.id = c.b_id group by a.id 	4.55951230630137e-05
6509159	10423	how do i search for names with apostrophe in sql server?	select *   from header  where userid like '%''%' 	0.74951945901445
6509779	19805	select column based on maximum value in another column	select id from test group by id having max(time) <= 'x' 	0
6510475	20132	how to get the records which is not equal to 1 in my query	select * from  ( select td.productaccumrule_id,td.product_id,td.variable_id,td.accum_code,ordinal = row_number() over( partition by td.product_id,td.variable_id,td.accum_code order by td.product_id,td.variable_id,td.accum_code) from testdata td join ( select product_id,variable_id,accum_code from testdata where  isactive = 1 group by product_id,variable_id,accum_code having count(*) > 1 ) temp on td.product_id = temp.product_id and td.variable_id = temp.variable_id and td.accum_code = temp.accum_code where td.isactive = 1 ) myinnerquery where ordinal  <> 1 	0.00158158767953859
6511217	33537	table types in db2	select * from syscat.columns where tabname= (select base_tabname from syscat.tables where tabname = 'table') 	0.07457540885153
6512367	35692	date based nth record in mysql query	select * from weather where mod(unix_timestamp(time), divisor) = 0 	8.95191968447554e-05
6515597	19954	grouping between consecutive rows in a table without cursor	select cast(a.col1 as varchar(10))+ '-' + cast(b.col1 as varchar(10)), coalesce(a.col2,0)+coalesce(b.col2,0) from table a join table b a.col1 = b.col1 + 1 	0.000561451063555623
6516472	23758	mysql query result that use value of other fields	select concat('some text ', field1, ', ', field2, ' some text.') from table; 	0.00118897838382431
6517058	7772	multiplying values from two access tables	select  townname ,       flatcount ,       flatcount * (select pcost from cost where prop = 'flat') as flatcost ,       detachedcount ,       detachedcount * (select pcost from cost where prop = 'detached')              as detachedcost ,       ...  from    town 	0.000481213345777414
6517170	10221	how to get count in this query?	select listid, sum(if(status="yes",1,0))  from yourtable group by `listid` 	0.200112575192412
6518241	36613	how to add a column based on certain date range	select st.*, ft.rate from second_table st left join first_table ft on (month(acct_date) = month(eff_date) and year(acct_date) = year(eff_date) ) 	0
6520036	35235	using max and returning whole row with max column value	select     id,            date,            version from       yourtable inner join  (     select    id,               max(version)     from      yourtable     group by  id ) as x on         yourtable.id = x.id and        yourtable.version = x.version 	0.000771768048275995
6520397	37486	having a bit of trouble with mysql query to receive random combinations from 3 tables	select       first10.firstname,       last10.lastname,       ( select status from status order by rand( ) limit 1) as status    from        ( select fn.firstname,                @fns := @fns + 1 as sequence            from              ( select firsname,                   from firstnames                   order by rand()                    limit 10 ) fn,              (select @fns := 0 ) vars       ) first10       join       ( select ln.lastname,                @lns := @lns + 1 as sequence            from               ( select lastname,                    from lastnames                    order by rand()                     limit 10 ) ln,               (select @lns := 0 ) vars        ) last10       on first10.sequence = last10.sequence 	0.00187647942276678
6521997	21636	join same table to multiple fields	select task.taskid       ,project.project       ,task.task       ,task.description       ,submitted.username       ,owner.username       ,task.isvisible   from task   inner join project on task.projectid = project.projectid   inner join login submitted on task.submitterid = submitted.loginid   inner join login owner on task.ownerloginid = owner.loginid   where isvisible = 1 	0.00414605052739346
6522042	8910	mysql relationship query	select *    from users u join skills s on u.id=s.user_id     where skill_level=2     group by id     having count(*)>2 	0.370764777351167
6522944	39911	sql: order results by (optional) relationship	select p.id, ..., creationdate     from post p         left join post_has_post php             on p.id = php.child_id     order by coalesce(php.parent_id, p.id),              creationdate 	0.693311803748807
6523658	10376	find an available time frame in mysql	select  if(max(end) >= $end, max(end), $end) -          if(min(start) <= $start, min(start), $start) -          if(sum(end - start) is null, 0, sum(end - start))  as freetime where end > $start and start < $end 	0.00304140364373086
6525894	2695	can i select a field from data type?	select column_name from information_schema.columns where table_schema='your_schema' and table_name='tbl_name' and data_type='timestamp without time zone' order by ordinal_position; 	0.00268694064209027
6526606	1767	vanilla sql that selects multiple values in single column	select customer from mytable group by customer having count(distinct timezone) > 1 	0.00308904055627627
6527184	21967	can i make a query which orders things by two columns?	select    distance,   eventtime, from table1 order by distance desc, eventtime asc 	0.000883983086141122
6527241	34805	sql - select row id based on two column values in same row as id	select [id]  from tbl  where a = @a and b = @b 	0
6528700	7251	fastest way to find non-matching ids from two tables	select a.* from secondtbl a left join firsttbl b on a.guid = b.guid where b.guid is null 	0
6528749	34746	mysql group by & count... can i do a nested grouping?	select count(distinct logindate) as numlogins,        date_format( max(logindate), '%m%d%y' ) as lastlogdate,         loginid, department from activity  where ismgr='1' and logindate > '2011-01-01 00:00:00'  group by loginid, department order by loginid, department desc 	0.569501695371421
6530458	1347	sql query to find rating?	select restaurantid , sum(foodquality+service+atmosphere+value) rating1  , avg(foodquality+service+atmosphere+value) rating2  , avg((foodquality+service+atmosphere+value)/4) rating3  from table group by restaurantid 	0.049684950959407
6532252	2326	finding total sales and total products from 2 tables, includes a little concatenation	select p.catid as catid,         group_concat(distinct p.productid separator ',') as productids,         count(distinct p.productid) as totalproducts,         count(s.salesid) as totalsales from products p     left outer join sales s         on s.productid = p.productid         and s.paymentstatus = 'completed' where p.deleted = 'n' group by p.catid 	0
6533140	4009	rows that are similar in all but one column	select name, age, group_concat(favorite separator ',') from mytable group by name, age 	0
6534649	32692	how to do select substr(column1, 1, 3), * from table1 in db2	select column1, table1.*  from table1 	0.00348739140905977
6536761	35811	sql..sum two rows	select `location`, `name`, `label1`, `label2`, sum(`time`)   from `mytable`  where `service` = "car" or `service` = "house"  group by `location`, `name`, `label1`, `label2` 	0.00948783837377423
6536793	19411	how can i connect these two tables in sql?	select    cf.id,   sfd.data_txt,   sfd.itemid,   sfd.fieldid from #__community_fields cf inner join #__community_fields_values cfv on cf.id=cfv.field_id inner join #__sobi2_fields_data sfd on cfv.value=sfd.data_txt inner join #__sobi2_item si on sfd.itemid=si.itemid where cf.fieldcode='field_country' and cfv.user_id=$userid and sfd.fieldid=6 and si.published=1 and (si.publish_down > '{$now}' or si.publish_down = '{$config->nulldate}') order by si.last_update desc limit 0, 30 	0.0883610391012315
6537778	34877	mysql: creating a dataset with multiple where clauses	select    geo,    total,    sum(unique) as unique from    (select       geo,       count(total) as total,       0 unique,     from     where     group by        geo)   union     (select       geo,       0 total,       count(unique) as unique,        from      where       group by        geo) ) as tmptable group by     geo 	0.503359567005347
6538357	9664	merge two queries into one	select a.field_1, a.field_2, b.field_3, b.field_4 from tbl_a as a, tbl_b as b where a.field_1 = b.field_3 and ( case when a.field_1 in (1,2,3,4) then       case when a.field_date = now() then 1 else 0       end else 1 end) = 1 	0.000523894141564517
6539618	17253	declare a table variable based on select statement	select * into #people from persons; 	0.0113382091428989
6539757	34193	string breaking/stripping using a mysql query	select substr(style_number, instr(style_number, '-') +1 ) from table1 	0.651512602444519
6540080	1027	mysql count occurences of failure codes	select count(b.id), f.name from builds b  join failureareas f on b.failurearea = f.id where date(b.submittime) >=  date_sub(curdate(), interval 30 day) and b.buildstatus != 2 group by f.name 	0.0602016199480439
6540111	470	get active rows between from and to date range inclusive of boundary	select * from testtable tt where (tt.started >= fromdate and tt.started < dateadd(day, 1, todate)    and tt.ended >= fromdate and tt.ended < dateadd(day, 1, todate))    or sessionisrunning = true order by tt.sessionid 	0
6543369	34825	include partial matches in sqlite fts3 search	select name from (       select name, 1 as matched       from nametable       where name match 'fast'     union all       select name, 1 as matched       from nametable       where name match 'food'     union all       select name, 1 as matched       from nametable       where name match 'restaurant'   ) group by name order by sum(matched) desc, name 	0.124789298915153
6543738	15259	extracting member's first name from member table using results from another table	select *  from course inner join course_member on course.id = course_member.course_id inner join member on member.id = course_member.member_id 	0
6545405	30984	mysql ignore any distinct values	select col1 as d from tb_col group by col1 having count(*) = 1             	0.0382103500270343
6548678	10233	how to select * (all) which date start from the last day of last month to the first day of next month	select * from `table_name` where date(`date_post`) >= date_format(curdate() - interval 1 month, concat('%y-%m-', day(last_day(curdate() - interval 1 month)))) and date(`date_post`) <= date_format(curdate() + interval 1 month, '%y-%m-01'); 	0
6551585	37435	mysql: convert date from jan 01, 2000 to 2000-01-01 	select date_format( str_to_date( thedate, '%m %d, %y' ) , '%y-%m-%d' )  newdate, thedate  from donor where `thedate` like '%,%' 	0.222123508816185
6553531	7040	mysql - get sum() grouped max() of group	select person, sum(best) from     (select person, max(score) as best     from tabgames     where month(`date`) >= 1 and month(`date`) <= 6      group by person, month(`date`)) as bests group by person 	0.000595344788501821
6553677	22807	enforcing unique columns	select 1  from mytable_with_unique_column  where my_unique_column = mynewvalue 	0.00820268594561516
6553847	23360	mysql reference row in sub query	select  messages.user_id ,       count(*) as count  from    messages  where   messages.created_at >         (         select  min(created_at)         from    photos         where   photos.user_id = messages.user_id         ) group by          messages.user_id 	0.226742381553457
6557071	36959	mysql query, select from a determined point on	select *      from (select *           from ladder_rankings           where ladder_points > (select ladder_points                              from ladder_rankings                              where player_id = %current_player%)           order by ladder_points asc           limit 5) as next_5  order by ladder_points desc 	0.0700653929362959
6557086	17692	mysql query to pull items, but always show a certain one at the top	select distinct section from merch      order by field(section, 'books', 'posters') desc; 	0
6558771	28282	condition as a coulumn named using as "name" in mysql	select distinct   idlogin, count(idlogin ) as cou  from   `products`  group by idlogin having cou > 2 	0.198217753624165
6561438	28737	mysql select within same table	select a.id as problem_id from table_a as a join table_a as b on a.type = b.type where a.value1 <> b.value1 or a.value2 <> b.value2 group by problem_id; 	0.00640872925979783
6562113	7637	combine multiple select statements from different tables	select      ( select sum(amount) as credittotal       from x.card1       where user_id = userid and card_type=1     )     , ( select sum(amount) as debittotal       from x.card2       where user_id = userid and card_type=2     ) 	0.00075841002575602
6562470	19718	how to select rows every record+100 value?	select * from mytable where col1 % 100 =     (select col1 % 100 from mytable order by col1 limit 1) 	0.000220430815214995
6562836	23115	mysql query: using joins to get data not results good	select t1.empid, t2.itemid, t2.items    from itemsinfo t2 left join employeeinfo t1 on t1.itemid=t2.itemid and empid=201; 	0.790546817796676
6563330	15114	merging two select queries	select `date`    from `tasks` where `user_id`=1 union select `t1`.`date`    from `tasks` `t1`    inner join `urls` `u1` on `u1`.`id` = `t1`.`url_id`    where `u1`.user_id`=1; 	0.0106043845448616
6563616	14505	need to have a grid grouped into logical groups based on date	select new {                 luke.jobid,                 luke.job.jobdate,                 clientid = luke.job.branch.clientid,                 clientname = string.format("{0} ({1})", luke.job.branch.client.name, luke.job.branch.client.number),                 branchid = luke.job.branchid,                 branchname = string.format("{0} ({1})", luke.job.branch.number, luke.job.branch.number),                 jobbookingstatusname = luke.jobbookingstatus.name,                 groupname = getgroupnamebydate(luke.job.jobdate)             }; string getgroupnamebydate(datetime date) {     var today = datetime.today;     if ( date < today ) { return "past"; }     else if ( date >= today && date <= today.addmonths( 1 ) ) { return "current"; }     else { return "future"; } } 	0
6563623	30562	getting affected row in trigger	select * from deleted 	0.0286535343875754
6565228	952	mysql order year field by closest match	select * from `table` order by abs(1992-`year`) asc 	0.0010500422592737
6569479	14882	in firebird, how to return the ids of the deleted rows?	select id from category where name = 'haló' 	0
6569573	37259	select highest ranked group only	select user_id, μιν(user_group_id) as min_group_id from users where user_group_id >= 5 && user_group_id <= 12 group by user_id 	0.000623005249385849
6571246	24451	sql server 2008 - picking all records from a table that match smallest date	select *  from table   where  datemodifiedvalue = (select min(datemodifiedvalue)                              from table1 ) 	0
6571575	24797	what's the created date-time for table row in oracle?	select    scn_to_timestamp(ora_rowscn) from    mytable 	0.0106637205814655
6571732	28368	select into with desc and rownum	select dactionmillis, dactiondate into wf_dactionmillis, wf_dactiondate  from (     select dactionmillis, dactiondate, wf_dactiondate      from workflowhistory      where ddocname=? and lower(daction)=?     and lower(dwfstepname)=?     and lower(duser)=?      order by dactiondate desc ) where rownum = 1 	0.114520807306365
6572951	39822	quering the most recent columns and summing the others in mysql	select        id,        id2,        sum(profit) profit,        sum(expense) expense,        (select status from tbl t1 where t1.id=tbl.id and t1.id2=tbl.id2 order by date desc limit 1)      from        tbl      group by        id,        id2 	0
6575624	8594	group by name order by name returns all letters	select  left( name, 1 ) as fl  from   ... group by  fl 	0.00183078708490022
6575669	28999	doing a count in mysql	select u.id as userid, count(v.uploaded_by_id) as videoscount from userprofile_userprofile u     left outer join userprofile_videoinfo v         on v.uploaded_by_id = u.id group by u.id order by count(v.uploaded_by_id) desc 	0.416002675887981
6577298	39470	mysql group by null and empty	select case     when table_name.text_field is null or table_name.text_field = ''     then null     else table.text_field end as new_field_name, other_field, another_field, ...rest of query... 	0.295592284637616
6579066	26491	pattern matching in db2 sql	select * from marks_table where upper(mark_desc) like '%test%' 	0.106180428006338
6579082	25943	how to sum based on field value (mysql)	select sum(case when flag = 'y' then last_amount else amount end) as total from tb_stock 	7.97586760276281e-05
6579860	8469	crystal reports: data in records is stored in columns in a row, how can i transpose those columns or choose maximum from them?	select id, 1 as idx, a1 as a, b1 as b, c1 as c union  select id, 2 as idx, a2 as a, b2 as b, c2 as c ... union select id, 20 as idx, a20 as a, b20 as b, c20 as c 	0
6580237	427	detailsview with sqldatasource, display two tables	select orders.orderid, users.username from orders inner join users on orders.userid_relat = users.userid where userid = @userid 	0.00437609724631305
6581250	39197	order a sql query by number of results	select manufacturer, count(*) as matches from     from shop_articles where ( manufacturer like '".$searchparams[0]."%' or manufacturer like '".$searchparams[1]."%' or  ... manufacturer like '".$searchparams[n]."%' or )     group by manufacturer     order by matches 	0.018772530440335
6581796	31793	sql aggregation query for sum, but only allow positive sums (otherwise 0)	select customer_id,   case      when sum(order_total) < 0 then 0     else sum(order_total)   end   from orders    group by customer_id; 	0.0103973294415969
6582354	10322	change gridview columns header	select [itemtitle] as header1  from orders 	0.019215860081933
6584527	15215	how to implement a mapped keyword match with multiple keywords and preference based on number of hits?	select rec_id, count(keyword) as matches from index_tbl where keyword = 'key1' ... group by rec_id; 	0.000265493831701219
6585904	337	how to select a column in with a clob datatype	select restriction, person, start_date, end_date, comments from restrictions  where id in (select distinct id from restrictions where <original where clause>) 	0.0143703910899781
6586263	3217	sum of time in sql	select totalseconds / 3600 as [hours], (totalseconds % 3600) / 60 as [minutes], (totalseconds % 3600) % 60 as [seconds] from (     select sum(datepart(hour, dt) * 3600) + sum(datepart(minute, dt) * 60) + sum(datepart(second, dt)) as totalseconds     from test ) t 	0.0288177429603871
6587972	2370	how i do a select a limited number of rows with the same attribute?	select url,row_number from(      select url,row_number() over (partition by domain) from website      where domain in     (select distinct domain from link)   ) as links  where row_number <= 10 limit 25 	0
6588738	14888	create list of dates, a month apart, starting from current date	select getdate() 'date' union select dateadd(month, 1, getdate()) 'date' union select dateadd(month, 2, getdate()) 'date' union select dateadd(month, 3, getdate()) 'date' union select dateadd(month, 4, getdate()) 'date' 	0
6588972	16862	sql: how to only use dynamic column for order, not as part of result set	select id, lat, lng from locations order by <haversine calc> 	0.0273248251246063
6591067	17676	invalid column name when using t-sql column alias	select firstname as nick from [dev].[dbo].[name] where firstname like '%et%'  order by 1 desc 	0.776535219975121
6591075	15800	multiple count in mysql/php	select  cat, sum(if(item = 0,1,0)) as items0,  sum(if(item = 1,1,0)) as items1 from table group by cat 	0.198186123949255
6591157	25590	mysql group by day with timestamp column	select ... group by date(`datetimecolumn`) 	0.000995735090697642
6593275	283	addition in sqlite where	select col1 + col2 as xx from my_table order by xx asc 	0.652894243419097
6593564	10876	select min and max dates between two columns from different tables	select min(mydate) mindate, max(mydate) maxdate from( select expensedate as mydate from tablea union all select invoicedate as mydate from tableb ) as table 	0
6594309	3675	how to query for a built string select	select ('reword#' || reword) || reword_faq as foo from me_review_entries re where ('reword#' || reword) || reword_faq = 'reword#2#some_faq' 	0.129264238927507
6594313	28703	php / mysql create a new array using values from an existing array, help?	select p.name as productname, m.name as materialname, p.price     from products p, materials m     where p.productid=1 and materialid=12 	0.00891826915423891
6594536	12137	group by with 2 distinct columns in sql server	select t1.id, t1.stat, t1.date from testtable t1 join (select stat, max(date) date from testtable group by stat) t2 on t1.stat = t2.stat and t1.date = t2.date group by stat 	0.0191292561199295
6595881	23033	using sql to get distinct rows, but also the whole row for those	select * from mytable main where bidamount = (     select min(bidamount)     from mytable     where contractid = main.contractid) 	0
6596335	36229	mysql want to fetch title_en if title_es is empty	select   case when title_es is null then title_en     else title_es end as title from product 	0.0958528263194264
6597712	35405	sql query to calculate monthly growth percentage	select product, this_month.units_sold,     (this_month.sales-last_month.sales)*100/last_month.sales,     (this_month.sales-last_year.sales)*100/last_year.sales     from (select product, sum(units_sold) as units_sold, sum(sales) as sales             from product where month = 146 group by product) as this_month,          (select product, sum(units_sold) as units_sold, sum(sales) as sales             from product where month = 145 group by product) as last_month,          (select product, sum(units_sold) as units_sold, sum(sales) as sales             from product where month = 134 group by product) as this_year     where this_month.product = last_month.product       and this_month.product = last_year.product 	0.00257914914571967
6599198	37954	sql server group by, count, compute	select purchased_profileid, count(*) as 'noofpurchases', sum(final_paidprice)  from mmbmembership mmb, mmb_businessprofiles mmbprofiles, basic_details bd, orderdetails_purchasedprofiles odpp where mmb.mmb_id = mmbprofiles.mmb_id and mmb.profile_id = ltrim(bd.profile_id) and odpp.purchased_profileid = bd.profile_id and mmb.mmb_id = 1 and ispublished='true' group by  purchased_profileid 	0.500779064119981
6600139	3590	specific group by query in sql server	select col1, col2, sum(col3) from dbo.yourtable group by col1, col2 	0.297562450938704
6600480	12004	ssrs - determine report permissions via reportserver database tables?	select c.username, d.rolename, d.description, e.path, e.name  from dbo.policyuserrole a    inner join dbo.policies b on a.policyid = b.policyid    inner join dbo.users c on a.userid = c.userid    inner join dbo.roles d on a.roleid = d.roleid    inner join dbo.catalog e on a.policyid = e.policyid order by c.username 	0.10579869954649
6600698	7147	how can i count how much each different values occur in each column independently?	select 'letter' as type, letter as item, count(letter)     from mytable group by letter union all   select 'num', cast(num as varchar(100)), count(num)     from mytable group by num; 	0
6600863	22139	sql add new timestamp if date is between (kinda static date) condition	select to_date(     textcat(         textcat(             textcat(                 date_part('years', current_date - interval '3 months'),             '-'),         date_part('months', current_date - interval '3 months')),     '-10'),'yyyy-mm-dd') as previous_date, to_date(     textcat(         textcat(             textcat(                 date_part('years', current_date - interval '3 months'),             '-'),         date_part('months', current_date - interval '3 months')),     '-10'),'yyyy-mm-dd') + interval '1 month' + interval '1 day' as next_previous_date 	0.00060096886492728
6602032	15203	adding strings in mysql	select concat(  'data', cast( curdate( ) as char ) ,  '.txt' ) 	0.222786353467318
6602229	10141	ms sql: how to select from 2 tables?	select t2.[product name in spanish], t1.price     from table1 t1          inner join table2 t2              on t1.productid = t2.productid 	0.00489649753392057
6603300	35633	how to join two tables in mysql via select	select roomname, usercount, userlimit, topic, extra from tablea union all select roomname, usercount, userlimit, topic, extra from tableb where roomname not in     ( select roomname from tablea ) 	0.0183277845728606
6607073	33179	what's the right way of joning two tables, group by a column, and select only one row for each record?	select * from (     select      *,     row_number() over (partition by c.crew_id order by l.sim_time desc) as rnum     from crew as c     inner join tilelog as l (on c.crew_id = l.crew_id) ) as t where rnum = 1 	0
6607262	30721	how to use aggregate function on column cotainining string values?	select sum( dividend ) || '/' || sum( divisor )        as fractionofsums      , avg( dividend / divisor )                as averageoffractions from   ( select cast(substr(result, 1, position('/' in result)-1 ) as int)            as dividend          , cast(substr(result, position('/' in result)+1 ) as int)            as divisor     from rows   ) as division 	0.290869363652001
6607565	13086	how to insert data into two table, while one depends of primary key of other	select scope_identity() 	0
6608153	30418	sql query which deletes an attribute in xml	select deletexml(xmltype.createxml('<items>                                        <item type="xxx">a</item>                                        <item type="xxx">b</item>                                    </items>'),                                    '/items/item[@type="xxx"]/@type') from dual   <items>    <item>a</item>    <item>b</item> </items> 	0.148883457884368
6610474	12422	fast way to find the row associated with a given guid across many sql databases and tables	select kc2.table_name as fk_table_name, kc2.column_name as fk_column_name,         kc1.table_name as ref_table_name, kc1.column_name as ref_column_name from information_schema.referential_constraints rc inner join information_schema.key_column_usage kc1          on rc.constraint_catalog = kc1.constraint_catalog        and rc.constraint_schema = kc1.constraint_schema        and rc.unique_constraint_name = kc1.constraint_name inner join information_schema.key_column_usage kc2          on rc.constraint_catalog = kc1.constraint_catalog        and rc.constraint_schema = kc1.constraint_schema        and rc.constraint_name = kc2.constraint_name order by kc2.table_name, kc2.column_name 	0
6611103	33700	calculate age of a person in sql	select case when  (dateadd(year,datediff(year, @datestart  ,@dateend) , @datestart) > @dateend) then datediff(year, @datestart  ,@dateend) -1 else datediff(year, @datestart  ,@dateend) end 	0.000598137771730204
6611978	12827	how to get the root id of a parent child structure	select categories.name  from categories, productcategories  where productcategories.parentcategory = categories.id    and productcategories.productid = 50   and categories.parentid is null 	0
6612919	18308	sql count days till first of the month	select (date_trunc('month', current_date) + interval '1 month') - current_date 	0
6613156	14104	how to select count as a percentage over the total in oracle using any oracle function?	select sum(case when p.end_dt is null then 1 else 0 end) / count(*) * 100   from packages p 	0.00780698813035752
6614867	17237	sql join 2 rows in the same table	select      address.name,     address.value as address,     phone.value as phone from     yourtable as address left join     yourtable as phone on address.name = phone.name where address.type = 'address' and       (phone.type is null or phone.type = 'phone') 	0.000353086541992424
6615527	4836	how do i add the first of the week for every week from 2011-01-02 until 2100-01-01 to a mysql table via a while loop?	select a.date  from (     select date('2011-12-31') - interval (a.a + (10 * b.a) + (100 * c.a)) day as date     from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a     cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b     cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c ) a where dayofweek(a.date)=1 and a.date between '2011-01-01' and '2011-12-31' 	0
6616804	28964	only returning rows when there is a certain count of a given column	select t.*   from your_table t having count(distinct t.my_column) = 1 	0
6617702	1246	mysql many to many relationship matching	select d.drink_name from tbl_drink d inner join tbl_receipe r on r.drink_id=d.drink_id inner join tbl_ingredient i on i.ingredient_id = r.ingredient_id where `given id` in (i.ingredient_id) 	0.0197237066049474
6617996	38675	simulating regex capture groups in mysql	select     if(cast(right(substring_index(left(version,char_length(version) - char_length(substring_index(version, '.', -3)) - 1), '.', -1),2) as decimal) > 0,          cast(right(substring_index(left(version,char_length(version) - char_length(substring_index(version, '.', -3)) - 1), '.', -1),2) as decimal),          cast(right(substring_index(left(version,char_length(version) - char_length(substring_index(version, '.', -3)) - 1), '.', -1),1) as decimal)) as version1,     substring_index(left(version,char_length(version) - char_length(substring_index(version, '.', -2)) - 1), '.', -1) as version2,     substring_index(left(version,char_length(version) - char_length(substring_index(version, '.', -1)) - 1), '.', -1) as version3,     substring_index(version, '.', -1) as version4 from version having version1 >= 5 ; 	0.234415248248963
6618346	1646	how to do recursive queries on two tables using web sql database?	select * from products where id in (select * from prices where product_id = ?) 	0.218739583031113
6618437	40214	how do i get just one result when running a sql query?	select distinct user_ids from items 	0.0170867535550973
6619770	73	comparing a column against an entire table of ranges?	select *   from tablea a     where exists     (         select 1            from tableb b             where  a.id between b.id1 and b.id2     ) 	0
6619810	19508	how to split strings in sql server	select substring(data, 1, charindex(',',data)-1) col1, substring(data, charindex(',',data)+1, len(data)) col2 from table 	0.0640626203390063
6622335	19235	mysql sort query	select *, count(tbl_comments.id) as comments_count from tbl_articles join tbl_comments on (tbl_comments.article_id = tbl_articles.id) group by tbl_comments.article_id order by comments_count; 	0.297385074355432
6622726	28054	better schema for a database	select user_id, count(*) as misses from user_missed_date where date>[last two months] group by user_id 	0.55391644681888
6628330	2655	need mysql query manytomany mapping count records	select g.name, count(mg.idmovie) from moviegenre mg inner join genre g on mg.idgenre = g.id group by g.name 	0.298468648500435
6628691	30793	subquery on single table	select taskid as parenttaskid, childof ,   (select count(t2.taskid)    from tasks t2   where t2.childof = t.taskid) as countchildren from tasks t  where t.childof = 0 	0.0518908434425049
6628942	3948	showing only the year portion of a date	select     orderid, year(orderdate) as date from         dbo.orders 	0
6629936	16616	postgresql: how do you select distinct relations and order by different fields depending on where clause?	select     case         when p.id in(2,4,6) then p.updated_at         when t.id in(1,3,5) then p.created_at     end as position,     distinct a.* from people as p join accounts as a on a.people_id = p.id join type_account as t on t.type_id = a.id where t.id in(1,3,5) or p.id in(2,4,6) order by 1 desc limit 1; 	0.00172808320697758
6630595	19447	return columns as comma seperated, for more than one condition on key or more than one row	select t1.key1, t1.key2,         stuff((select ', ' + columnkey                   from table1 t2                   where t2.key1 = t1.key1                       and t2.key2 = t1.key2                   order by columnkey                   for xml path('') ),1,2,'') as tcolumnkey     from table1 t1     group by t1.key1, t1.key2; 	0
6630748	27309	multiple sum for row	select    cat,    sum(if(item = 0,data,0)) as data0,     sum(if(item = 1,data,0)) as data1  from table group by cat; 	0.0138552716149287
6631166	28799	in oracle, how do i convert a number such as 1 to a string such as "1st"?	select case         when initial_extent is null then null        when substr(initial_extent,-2,1) = '1'              then initial_extent || 'th'        else case substr(initial_extent,-1,1)             when '1' then initial_extent || 'st'             when '2' then initial_extent || 'nd'             when '3' then initial_extent || 'rd'             else initial_extent || 'th'             end        end as formatted_number from user_tables 	0.0212531114686782
6632598	38535	how to search for exact string in mysql	select userid from sys_users where binary userid='nrew' 	0.0776937960297968
6637058	5922	using mysql how do you count the number of successfull ors?	select id, name, description, (     if(keywords like '%video%', 1, 0)   + if(keywords like '%keyword2%', 1, 0)   + if(keywords like '%keyword3%', 1, 0) ) score from table having score > 0 	0.0286665084451443
6638036	17151	sql / sqlite, need query to check all of the strings in a column	select itemdate, itemid, itemspecialid from mytable where itemspecialid is not null 	0.00167905747632297
6639417	32153	mysql get the columns names from search results	select *, concat_ws(',',(if(a = 'foo','a',null)) ,(if( b = 'foo','b',null)) ,(if(c = 'foo','c',null))) as wherefound from my_table where a = 'foo' or b = 'foo' or c = 'foo' 	0
6642130	40322	group by ratio and seniority list in sql	select c.courseid        s.studentname from course as c     join asks as a         on a.courseid = c.courseid     join student as s         on s.studentname = a.studentname     join asks as a2         on a2.courseid = c.courseid     join student as s2         on s2.studentname = a2.studentname         and s2.seniority <= s.seniority group by c.courseid        , c.ratio        , s.studentname having c.ratio >= count(*) order by c.courseid        , s.seniority 	0.0374100162529965
6643229	8868	how to select * into [tmp table] without declare table?	select * into #tmp from mytable; 	0.0061939856501513
6644324	2852	get an average vote rating for males/females/all in one mysql query	select   q.id,   avg(t.rating) as avgtotal,   avg(m.rating) as avgmale,   avg(f.rating) as avgfemale from questions as q left join ratings as t on q.id = t.question_id left join ratings as m on q.id = m.question_id and m.gender = 'male' left join ratings as f on q.id = f.question_id and f.gender = 'female' group by q.id 	0.000215073843888112
6644343	18777	mysql query order by if null	select *  from tbl_product  order by ifnull(wholesale_price, retail_price); 	0.513420554956174
6645065	9893	sql inner join with two conditions on same field	select a.*        from table_a a inner join             (             select table_a_id                from table_b             where table_c_id in(1,4)                 group by  table_a_id                 having count(distinct table_c_id) > 1         ) b  on a.id = b.table_a_id 	0.0271273953244507
6645871	9719	get grouped data from a table as columns instead of rows	select date    , sum(case status when 'active'     then cnt else 0 end) as a    , sum(case status when 'processing' then cnt else 0 end) as p    , sum(case status when 'closed'     then cnt else 0 end) as c from    ( select date, status, count(distinct name) as cnt     from accounts     group by date, status   ) grp group by date order by date 	0
6646061	14147	rank in mysql table	select count(*) from mytable where score > (select score from mytable where user = 'joe'); 	0.0968417492451251
6648193	6553	get random selection of rows equal number per grouping	select top 1000    * from    (    select        *,        row_number() over (partition by call_calt_code order by newid()) as rn     from        mytable       ) foo where     rn <= 1100 / (select count(distinct call_calt_code) from mytable) order by     rn 	0
6649607	27689	how to select data between date ranges from 2 tables	select sum(vat)'vat',itemvat,sum(productvalue)'productvalue' from ( select  t.vat, t.value,    isnull(t.value *      (select top 1 value from #tmp x where x.ttid=t.vat  and   convert(varchar,cast(x.effectivedate as datetime),3)>convert(varchar,cast(t.date as datetime),3) and convert(varchar,cast(x.mdate as datetime),3)<=convert(varchar,cast(t.date as datetime),3) )/100,'5')  as 'vat' from products t   )  as t where vat<>'5' group by itemvat 	0
6650307	12809	how do i do a group by with a random aggregation function in sql server?	select username,      count(distinct m.message) as "count",      avg(m.wordcount) as "average",     foo.message from     messages m     cross apply     (select top 1 message, username        from messages m2         where m2.username = m.username        order by newid()     ) foo group by m.username, foo.message order by "count" desc 	0.738477238153609
6650897	29590	want to exclude from the query some records, but i do not know how	select * from messages m inner join users u on m.user_id = u.id left outer join blacklists b on u.id = b.user_id where b.user_id is null 	0.000700094338195697
6651001	33268	tsql compare 2 select's result and return result with most recent date	select top 1 * from ( union all ) t order by yourdatecolumn1 desc 	0
6651097	3939	displaying multiple columns from a single column select statement	select recordid as records,    case when valueid=5 then value else null end [join date],    case when valueid=3 then value else null end [vehicle type],    case when valueid=4 then value else null end [speaker type]  from table where valueid in (5,3,4)    recordid   |   join date   |   vehicle type    | speaker type    1          |   2011-03-24  |   null            | null    2          |   2011-03-25  |   null            | null    3          |   null        |   bobcat          | null    4          |   null        |   backloader      | null    etc.... 	0.000180478835956933
6651249	15563	how to get the average from 3 values on a table on sql server?	select id, avg(value) from mytable group by id 	0
6651323	26083	multiple counts in a multi table query sql	select      tablea.subjectvalue,     sum(case when somecol='request1' then 1 else 0 end) as request1,     sum(case when somecol='request2' then 1 else 0 end) as request2,     . tableb inner join                        tablea on tableb.id = tablea.request_id inner join                        table c on tableb.details_id = tablec.id group by     tablea.subjectvalue 	0.070264319203849
6651790	13335	is it possible to have "null rows" in sql?	select a.id as a, b.id as b, null as c from tablea a inner join tableb on a.id = b.fid union select a.id as a, null as b, c.id as c from tablea a inner join tablec on a.id = c.fid order by 1 	0.0860347954647888
6651888	35802	mysql query use of and	select fusers.fuser_id, fusers.name, contest.contest_id, contest.name from fusers left join participants on fusers.fuser_id = participants.participants_id left join contest on contest.contest_id = participants.contest_id where (contest.launched = 1) 	0.465044357539414
6652060	4122	calculating time differences in mysql	select timediff(last_logout_time, last_login_time) as last_duration from... 	0.00853853590633792
6653847	40061	mysql query -- multiple possible specific values	select point_id  from v_ak47_test_point  where ak47_testsection_id= $secid and result_text != 'obsolete' and fieldname = 'expected_result_up' and resultsfields_value in (240, 846, 1000) 	0.0301359578810684
6653863	40699	ssis package to execute a stored procedure for each xml document is a specific directory	select getdate() as currentdatetime 	0.0186604342988807
6655821	36105	select row based on column	select top 1 * from table1 where id = @id order by      case primary_mfgr          when 'p' then 1         when ''  then 2         else 3     end 	0.000154497137494608
6657633	2824	sql - select distinct rows and join them with another table to get data	select p.person_id as person_id, p.name as name from person p, cars c     where p.person_id = c.person_id     group by b.brand_id 	0
6657854	4685	mysql ifnull on 4 or 5 columns	select ....   from .... order by coalesce(rrp, wholesale, column3, column4) 	0.096125868612603
6661884	18520	selecting specific rows from database in sql	select * from (   select     row_number() over (order by dayrangeid asc) as rownumber,     dayrangeid   from dayrangetable )  as temptablename where rownumber = 4 	0.000119253431796482
6662486	10340	mysql merge rows based on occurence	select * from table where paygrp='a'; select * from table where paygrp='b'; 	5.89655144066917e-05
6663587	1483	max (sum(votes)) | get only winners	select grp.local_unit_id, grp.mayor_id, grp.value from       ( select  local_unit_id, mayor_id, sum( votes ) as value        from mayorresults        group by local_unit_id, mayor_id     ) as grp   join     ( select local_unit_id, max(value) as value       from          ( select  local_unit_id, mayor_id, sum( votes ) as value            from mayorresults            group by local_unit_id, mayor_id         ) as grp       group by local_unit_id     ) as grp2     on  grp2.local_unit_id = grp.local_unit_id     and grp2.value = grp.value order by local_unit asc 	0.00497359938457088
6663610	29962	sql select all but nulls	select t1.id, t1.name, t2.color  from tablea t1 left outer join tableb t2  on t1.id_tableb = t2.id; 	0.0560818454899996
6663714	9896	max() on count() subquery that returns multiple rows	select rec.record_id,     rec.record_title,     usr.user_id,     usr.username,     (             select max(count) from (                 select count(distinct rec.record_id) as count                 from records rec                 where rec.record_title like '%random%'                 group by rec.record_id             ) as x     ) as total_records from (     records rec     inner join members usr ) where rec.record_title like '%random%' group by rec.record_id limit 0, 25 	0.00776650470904
6664491	15603	problem while seleting distinct item in t-sql	select c.companyname  from tbl_company as c   inner join (                select distinct companyid                from tbl_company_category_map              ) as m     on c.companyid = m.companyid 	0.305802738714634
6665700	33005	mysql query - getting people out that arent in another table?	select * from name n     left join classesbooked c on n.nameno = c.classesbooked_nameno where c.classesbooked_nameno is null 	0.000319466054232807
6665807	11591	how to transform rows into columns having no column with unique values?	select d.user_id, group_concat(     d.value separator ','   ) as val from details d group by d.user_id; 	0
6665852	6477	resolving hours and minutes from total minutes in t-sql	select   *,   cast(totaltime/60 as varchar) + ' hours ' +   cast(totaltime%60 as varchar) + ' minutes' as [converted] from (   select     pu.projectid,     c.clientname,     p.projecttitle,     sum(timetoadd) as totaltime   from dbo.projectusers pu     left join dbo.projects p on pu.projectid = p.projectid     left join dbo.projecttime pt on p.projectid = pt.projectid     inner join dbo.clients c on p.clientid = c.clientid   where pu.staffid = 3   group by     pu.projectid,     c.clientname,     p.projecttitle ) s 	0
6666152	18026	mysql order by where?	select * from members where memberid = "6" or memberid="3" or memberid="5" order by memberid = "6" desc, memberid="3" desc, memberid="5" desc; 	0.50063670572883
6667410	24960	t-sql select and count from different table?	select      t.threadid,     (select count(*) from dbo.posts p where p.threadid = t.threadid) from     dbo.threads t 	0.00108658499940915
6669101	20191	i want to combine two columns into a new column, but only if one isn't blank, and then sort by that new column. (mysql)	select trim(both ' - ' from concat(coalesce(city, ''), ' - ', coalesce(sitename, ''))) as citysite from my_table order by citysite 	0
6669261	33378	count users in table	select username, fan, count(*) as count from table_name  group by username, fan 	0.0104465989281001
6669730	12127	sql query that groups different items into buckets	select       case when price >= 0 and price <= 10    then "  0 - 10"            when price > 10 and price <= 50   then " 10+ - 50"            when price > 50 and price <= 100  then " 50+ - 100"            else "over 100"       end pricerange,       count(*) as totalwithinrange    from       yourtable    group by 1 	0.000127733475501915
6670346	41036	joining two tables based off of parsed column content	select * from #tempinvoices i inner join #tempexpenses e on cast(num as varchar(10)) + ' ' + substring(memo,1,9-len(cast(num as varchar(10)))) = substring(fmemo,1,10) 	0
6670724	17606	mysql count total songs for the artist	select concat(artist_name, '( ',  count(song_id), ' )') from artist         join song_artist on artist.id = song_artist.artist_id         group by artist.id, artist_name 	0.00596693926081753
6670801	795	sql results in rows not columns	select      storeid,      deposit,      row_number() over(partition by storeid) as depositnumber from (<< your query above>>) 	0.014295577454678
6672050	40885	calculate time difference in sql server?	select t1.tid, min(t1.starttime) as starttime, max(t2.starttime) as endtime,     max(datediff(mi, t1.starttime, t2.starttime)) as [timediff(min],     t1.uid, sum(t2.wid) as wid from mytable t1 join mytable t2 on datediff(mi, t1.starttime, t2.starttime) between 0 and 60 group by t1.tid, t1.uid order by t1.tid 	0.0102621427113189
6673156	9384	sql grouping and running total of open items for a date range	select count(case when d.checkdate = i.startdate then 1 else null end)          as itemsopened      , count(i.startdate)          as itemsopenedcumulative from dates as d   left join items as i     on d.checkdate between i.startdate and i.enddate group by d.checkdate 	0
6674202	12180	must match both columns in boolean mode	select htext,  match(htext) against('+genomics' in boolean mode) as relevance from paragraphs  where match(htext) against('+genomics' in boolean mode)  and match(keywords) against('+genomics' in boolean mode) order by relevance desc 	0.0586742271209351
6677177	20921	php - help with checking time was within past 24 hours	select count(*) from 'referrals' where `referrer_uid`=? and created_on > unix_timestamp(date_sub(now(), interval 1 day)) 	0.00134471661973508
6680395	7524	selecting next n rows from a table, based on a given row and column value	select  * from    mytable m where   (ts, id) <         (         select  ts, id         from    mytable mi         where   mi.id = :myid         ) order by         ts desc, id desc limit 50 	0
6683333	18546	query help - joining two tables with subset based on column values	select a.id, a.name, b.date, b.value   from people a inner join piesbaked b     on a.name = b.name    and b.date between a.firstdate and a.lastdate 	0.000206304055606591
6684938	15015	how to add two sums	select coalesce(sum(startuserthreads.newforstartuser),0)+coalesce(sum(enduserthreads.newforenduser),0) as numnew ... 	0.00511288985600761
6685124	3113	sql case statement if data exists for same id is in both tables output data	select t1.car, t2.status as result     from table1 t1         inner join table2 t2             on t1.id = t2.id     where t1.car = 'green' 	0.0116078448391871
6686171	3434	freetext search - ordering results according to how close they match	select     t.tableid     , t.textdata     , ft.rank from     table t     inner join freetexttable ( table , * , 'car park' ) ft on ( t.tableid = ft.[key] ) order by     ft.rank desc 	0.0114007668978492
6688885	30409	eliminate first numeric from string	select   coalesce(ltrim(substring(address, firstpos, 2147483647)), '') as address from (   select     address,     nullif(patindex('%[^0-9]%', address), 0) as firstpos   from atable ) s 	0.00122087910387989
6688952	26467	join based on the same column	select     itemname,     d0.uomname,     d1.uomname as d1_uomname,     d2.uomname as d2_uomname,     d3.uomname as d3_uomname from tableb tb join tablea d0 on d0.uomid = tb.uomid join tablea d1 on d1.uomid = tb.d1_uomid join tablea d2 on d2.uomid = tb.d2_uomid join tablea d3 on d3.uomid = tb.d3_uomid; 	0.000225826746264951
6689873	23034	i want to pass in 1 inplace of 4 and that result set should return in reverse order	select _id, parentid, level from (  select  convert(@r, decimal) as _id,          (          select  @r := parentid          from    people          where   peopleid = _id          ) as parentid,          @l := @l + 1 as level  from    (          select  @r := 4,                  @l := 0,                  @cl := 0          ) vars,          people h  where    @r  0 ) as initialq order by level desc 	0.0393750427716894
6689962	36781	sql server format date dd.mm.yyyy hh:mm:ss	select convert(varchar(10), getdate(), 104) + ' ' + convert(varchar(8), getdate(), 108) 	0.014577830633767
6690069	1470	than replace the function locate in sqlite, how to compare strings?	select * from contacts where 'yoursearchstring' like '%' || address || '%' 	0.205054349990333
6690514	24712	mysql count all outside limit	select sum(projects.hours) as total_hours, (select sum(projects.hours) from projects) as all_hours from  projects group by  projects.companyid order by total_hours desc limit 5 	0.0291062331480408
6692620	7551	how to do a special order clause in postgresql?	select  value from    mytable order by         case value when 'a' then 1 when 'c' then 2 when 'b' then 3 end 	0.784155711380588
6693373	28040	querying table with an ampersand in the name	select * from `cats&dogs` 	0.0595038562507009
6693796	31316	mysql group by a certain type and select the latest row?	select      `type`,      max(`date`) as `max_date`,      (select `t2`.`message` from `table` as `t2` where `t2`.`type` = `t1`.`type` order by `t2`.`date` desc limit 1) from `table` as `t1` group by `type` 	0
6694024	27513	return row when one of many conditions is not met	select  q.id, m.status from    (         select  4567 as id         from    dual         union all         select  7777 as id         from    dual         ) q left join         mytable m on      m.id = q.id 	0.00167313460834527
6694084	26493	mysql one to many, pulling only selected record from many table	select distinct m.* from music m inner join reviews r on m.uid = r.uid where r.thumbsup > 0 	0
6694414	25639	c# checking if record exists in sql error	selectstring = "select guid " + "from trafficscotland" + " where guid = '" + guid1 +"'" 	0.593763416185817
6694681	6317	how to select multi row values without querying database using 1 line of sql?	select 1 as 'primary', 'peter@email.com' as 'email' union select 2, 'dave@email.com' 	0.000169676595386394
6695428	14562	how to split an ip address string in db2 sql (for converting to ip number)?	select     lo.ipaddress     16777216 * cast(left(lo.ipaddress, locate('.', lo.ipaddress, 1)-1) as bigint)     +  65536 * cast(substr(lo.ipaddress, locate('.', lo.ipaddress, 1) + 1, locate('.', lo.ipaddress,locate('.', lo.ipaddress, 1) +1) - locate('.', lo.ipaddress, 1) - 1) as bigint)     +    256 * cast(substr(lo.ipaddress, locate('.', lo.ipaddress,locate('.', lo.ipaddress, 1) +1) + 1, locate('.', lo.ipaddress, locate('.', lo.ipaddress,locate('.', lo.ipaddress, 1) +1) +1) - locate('.', lo.ipaddress,locate('.', lo.ipaddress, 1) +1) - 1) as bigint)      +          cast(right(lo.ipaddress, length(lo.ipaddress) - locate('.', lo.ipaddress, locate('.', lo.ipaddress,locate('.', lo.ipaddress, 1) +1) +1)) as bigint)     as ipnumber from login lo 	0.00204959680199916
6696218	6536	mysql help regexp trying to shorten zipcodes from 9 to 5 digits	select * from mytable where zipcode regexp "[[:digit:]]{5}-[[:digit:]]{4}"; 	0.786971991396848
6696260	29457	get current year's birthday in sql	select userid,        date_of_birth,        dateadd(yy, datepart(yyyy, getdate()) - datepart(yyyy,date_of_birth), date_of_birth) as current_bday from users 	0
6696611	32352	is there a find sql statement behind a view	select object_definition (object_id(n'your view')); 	0.347326716643871
6697461	4508	check if two table rows are equal	select * from table1 except select * from table2 	6.91030253678771e-05
6698015	3062	how do i retain carriage returns while moving data from a web service into sql server 2005?	select [columnname] from [tablename] 	0.12264383348269
6698612	10568	sql select a row conditionally	select t1.*,     coalesce(t2.id,t2a.id) id,    coalesce(...   from table1 t1   left join (table2 t2      inner join table3 t3 on t1.id = t3.id              and  t3.status = 'a' )    on t1.id = t2.id   inner join (select id, max(timestamp) as timestamp            from table2        group by id) t2a on t2.id = t2a.id                        and t2.timestamp = t2a.timestamp  where t1.id in (select id                     from listofids) 	0.0175631945658916
6699153	21773	calculate value based on 2 fields in sql database	select      cast((case             when tableavalue < tableb.maxrange and tableavalue > tableb.minrange                then 1             else                0            end) as bit)  from tablea   inner join tableb     on tablea.id = tableb.tableaid where tablea.id = @yourid 	0
6699516	27205	efficient way to obtain ddl from entire oracle db	select dbms_metadata.get_ddl('table', table_name)   from user_tables; 	0.00492788160210167
6700619	17647	get latest rates for each distinct rate name	select a.* from yourtable a inner join (    select ratename, max(effectivedate) as maxdate                 from yourtable                 group by ratename) b on a.ratename = b.ratename and a.effectivedate = b.maxdate 	0
6700705	26440	mysql multiple or statements	select * from `table` where `id` not in (21474, 26243, 78634) and `checked` = 5 	0.659097717443779
6701090	23954	sql query for mutual friends	select user.uid from user where exists(     select top 1 1      from friends      where friends.fuid = @friend1 and friends.fapproved = 1        and friends.fuid2 = user.uid   )   and exists(     select top 1 1      from friends      where friends.fuid = @friend2 and friends.fapproved = 1        and friends.fuid2 = user.uid   ) 	0.0872368466826317
6701305	10035	mysql: comparing multiple rows from a joint table to the primary table using not in?	select sql_calc_found_rows e.* from exercises e where not exists (     select 1       from  exercise_targetedmuscles em         where  em.exerciseid = e.exerciseid                 and   em.targetedmuscleid in(15,16,17,14,3,12,9,8,7,18,4,2)         and em.isprimary = 1 ) group by e.exerciseid order by e.name asc 	0
6701448	23228	mysql distinct select exclude it self query	select distinct replace(column, 'aaa/bbb/', '') as column from table  where column like 'aaa/bbb/%'; 	0.38467598901944
6702033	7721	joining against a csv column in sql server	select [desc], count(b.cc6) from dbo.tbl_custom_code_6 a inner join dbo.respondent b on charindex(',' + a.code + ',', ',' + b.cc6) > 0 group by [desc] 	0.0435853033421634
6702480	8723	select numbers not present in multiple number series in oracle	select sequence_number from myvalues m where not exists  ( select 1 from myseries s where m.sequence_number between s.start_sequence    and s.end_sequence ) 	0.00151816903368702
6703726	36652	order by a field which is a navigation property to an entity - linq to entity	select `extent1`.`username`,  `extent1`.`name`,  `extent1`.`surname`, `extent1`.`countryid` from `users` as `extent1` inner join `countries` as `extent2` on `extent1`.`countryid` = `extent2`.`countryid` order by `name` asc 	0.28282238074172
6704304	26865	how to write the sql command?	select tableone.fieldone, tableone.fieldtwo, b.sortfield from tableone inner join  (select fieldone, min(fieldtwo) as sortfield from tableone group by fieldone) b on (b.fieldone = tableone.fieldone) order by b.sortfield, tableone.fieldone, tableone.fieldtwo 	0.574675270293473
6704438	4254	problem while fetching values using foreign key	select      t.id,     t.a_name,     s.title as s_title,     r.r_name from     t_atc_list t         inner join t_s_list s on t.s_title = s.s_id         inner join t_r_list r on t.r_name = r.r_id where     t.a_name = '$album' 	0.0130035633147402
6709615	39700	tsql - selecting data for a record when it does not exist	select distinct     subq.sku,     (         select sum(d.received) as numreceived         from data d             join period p on d.fulldate = p.fulldate         where d.yearmonth = subq.yearmonth           and d.sku = subq.sku           and p.weekofmonth = subq.weekofmonth         ) as received,     subq.yearmonth,     subq.weekofmonth from (         select distinct             d.sku,             p.yearmonth,             p.weekofmonth         from             period p,             data d       ) subq order by     subq.sku 	0.0927511147939696
6709876	1494	select items from table where timestamps are within an hour of eachother	select      t0.id, t1.id as matchid,      t0.ts as origtime, t1.ts as matchtime from t t0 inner join t t1 on      t1.ts between          t0.ts - interval '1 hour'         and          t0.ts + interval '1 hour'     and t0.id != t1.id ; 	0
6710144	19000	conditions (where) mysql	select product.* from product   join product_features as buttons     on buttons.id_product = product.id   join product_features as color     on color.id_product = product.id where buttons.feature_value = '1'   and buttons.feature = 'count_of_buttons'   and color.feature_value = 'white'   and color.feature = 'color'; 	0.487674378812513
6710862	733	sql query help - join on second table, possible?	select * from user inner join report re   on re.id = (select id                from report                where user_id=user.id                order by report.date desc               limit 1) where user.id='4' 	0.46467858304559
6712835	1033	checking multiple values in a sql array	select replace(concat(",", "1, 7, 8", ",")," ", "")        regexp concat(",", replace(replace("1 ,2 , 3 , 4 ,5 " ," ", ""),",", ",|,"), ",") from dual 	0.0189358329698982
6712964	1598	sql server 2008 group by	select aba.name, aba.surname, aba.whatisdoing,     b.id, b.title, b.photolink from books b join     (     select ba.bookid, ba.whatisdoing, a.name, a.surname,       row_number() over (partition by ba.bookid order by ba.whatisdoing) as sequence     from book_authors ba     join authors a on ba.authorid = a.id     where a.active = 1     ) as aba on b.id = aba.bookid where b.title like '%' + @textstring + '%'     and b.active = 1     and aba.sequence = 1 	0.753346811640638
6713408	17923	how do you select data from postgresql database, but if no data is present for a given day, then return 0?	select d.created_at, count(m.messageid) from possibledates d left join messages m     on d.created_at = m.created_at group by d.created_at 	0
6715226	19163	how to read null value in ado	select coalesce(att0, -1) as att0 from [dbo].[mytable] 	0.362929954883383
6716986	40097	mysql count rows for each id in a table	select killer, count(killer) as total_kills from kills where killed='player' and killed_by not in (<list of environment ids>) group by killer order by total_kills desc, killer 	0
6719068	3429	mysql select query	select i.id, i.title from interviews i inner join interview_keywords ik1     on ik1.interview.id = i.id     and ik.keyword_id = 39     and ik1.sort = 1 inner join interview_keywords ik2     on ik2.interview.id = i.id     and ik2.keyword_id = 33     and ik2.sort = 2 inner join interview_keywords ik3     on ik3.interview.id = i.id     and ik3.keyword_id = 51     and ik3.sort = 3 inner join interview_keywords ik4     on ik4.interview.id = i.id     and ik4.keyword_id = 96     and ik4.sort = 4 inner join interview_keywords ik5     on ik5.interview.id = i.id     and ik5.keyword_id = 97     and ik5.sort = 5 where i.cat_id = 1 	0.387336905290878
6720827	14284	returning null instead of empty rows for a particular column in an sql query	select  c.location as "location",  b.c2 as 'priceofpizza'  from from datatable a  inner join datatable b on (b.rowno = 'r2')  left join locationtranslation c  on (c.rawlocation = a.c1) where a.rowno = 'r1' 	0.00137940301482827
6721053	20104	sort problem with first position	select *, if(`id`=3,0,1) as `sticky` from `test` order by `sticky` asc, `timestamp` desc 	0.068007620461442
6721439	22740	mysql query already grouped and ordered : how to order inside the groups?	select    p.id_user,   ap.post as last_post,   count(*) as count from    posts p   join posts ap on (     p.id_user = ap.id_user     and ap.post_id = (       select max(post_id) from posts ip where p.id_user = ip.id_user     ) group by    p.id_user,   ap.post order by    count(*) desc 	0.000967669786244043
6722221	2566	extract the highest value of each day	select    t1.`date`,   t1.transactionid,   t2.balance from   (     select       `date`,       max(transactionid) as `transactionid`     from       table     group by       date(`date`)   ) t1 inner join   table t2 on   t2.transactionid = t1.transactionid order by   t1.`date` 	0
6723608	21910	how to count number of rows in related table	select s.sec_id,s.category,s.slug,s.description,count(a.id) from sections s      left join articale a on s.sec_id = a.section_id  where 1  group by s.sec_id  order by s.category asc 	0
6724338	3647	howto realise a query which makes a second query to count the sum?	select first.name, (  select count(*)   from second  where second.first_id=first.id ) as entries from first 	0.00538165819271065
6726271	24114	mysql query that orders data by timestamps contained in two tables	select a.`date`      , a.`time`      , l.loc_name as l_name      , a.rating      , a.comment      , u.user_name from table_a as a   left join loc as l      on l.loc_id = a.loc_id   left join `user` as u     on u.user_id = a.user_id union all select b.`date`      , b.`time`      , l.loc_name as l_name      , null as rating      , b.comment      , u.user_name from table_b as b   left join table_a as a     on a.id = b.parent_id   left join loc as l      on l.loc_id = a.loc_id   left join `user` as u     on u.user_id = b.user_id order by `date`        , l_name        , `time` 	5.64254780047369e-05
6727697	31922	combining two group by queries grouped by the same column	select tg.name,           case when tx.type = "actual" then sum(amount) end as actualtotal,          case when tx.type = "budget" then sum(amount) end as budgettotal   from....   where  tx.type in ("actual", "budget")   and   ....   group by tg.name 	9.02706503799647e-05
6728297	15590	mysql - if table a is left joined to table b, how do i order by a field in table b?	select  pts.pts_id,              pts.pts_name,              meds.*     from    pts             left join meds             on pts.pts_id = meds.pts_id_fk     where   pts.id_fk = $id       and   pts_current = 1 order by pts.pts_id, meds.time 	7.10706574156811e-05
6728905	8671	sql express database size limit via query	select @@version 	0.760834664404549
6729441	5623	mysql natural sort	select data from example order by     cast(substring_index(data, '.', 1) as binary) asc,     cast(substring_index(substring_index(data , '.', 2), '.', -1) as binary) asc,     cast(substring_index(substring_index(data , '.', -1), '.', 1) as binary) asc; 	0.467843366382607
6730530	24212	what is the best way to segregate the data alphabetically using sql?	select * from your_table where your_column between 'a' and 'g'; 	0.525023462345523
6730728	1700	how do i delete records in mysql and keep the lastest date	select max(updatedate) from table_1 into @tempupdatedate delete from table_1 where updatedate < @tempupdatedate 	0.000400076437400444
6730742	2059	sql distinct question	select distinct review.user_id, review.id, user.*, account.*    from reviews as review    inner join users as user on review.user_id = user.id    left join accounts as account on user.id = account.user_id    group by review.user_id 	0.748433080798436
6731114	549	sql table search	select col1 from table_foo where  col1 not in (   select col1   from table_foo   where col2 = 3 ) 	0.205410623909326
6731854	19801	mysql select all from table where month?	select create_date from table where month(create_date) = 5 	7.619913816039e-05
6733812	10642	search in sql database	select *     from yourtable     where (yourcolumn = @param or @param is null) 	0.3622267151857
6734246	15255	mysql date result split by date	select * from mydb.mytable group by thedatevalue order by thedatevalue asc; 	0.00319393444725758
6737715	14865	sql funky time duration query	select      case          when extract(day from date_field) <= 25          then date_trunc('month', date_field + interval '3 months')         else date_trunc('month', date_field + interval '4 months')     end from t 	0.272219007600246
6738510	20203	how to improve site title search results	select * from blah where soundex(column) like concat('%', soundex($search_string), '%') 	0.774525774513778
6739169	38368	need to add the number of completes per interviewer in two union'ed queries	select interviewer, sum(num_completes) from (     select interviewer as interviewer, count(completes) as num_completes         from tableone_projectone, interviewertable_mainsystemdb         where survey_result = '01' and interviewertablekey=interviewernumber         group by survey_result, interviewer     union all     select interviewer as interviewer, count(completes) as num_completes         from tableone_projecttwo, interviewertable_mainsystemdb         where survey_result = '01' and interviewertablekey=interviewernumber         group by survey_result, interviewer ) as unions  group by interviewer  order by interviewer desc 	9.85068954738028e-05
6739461	32028	merge two sql tables with condition	select    id, title, multiplayer, id_product  from  products_groups left join product_category   on product_category.id_category = products_groups.id    and product_category.id_product = '45' where products_groups.type = 'game'; 	0.0138429429099277
6740456	10757	selecting data with multi table sql statement returns unexpected result	select product.name, group_concat(features.text) from products join product_features on(products.id = product_features.product_id) group by products.id; 	0.193415286555618
6740564	12701	t-sql include column if condition exists	select call_id, title, description, due_date,  case when due_date < getdate() then cast(1 as bit) else 0 end overdue from calls 	0.137216458886563
6741358	12227	perform sql join on tables	select xyz.columna from xyz join xde on xyz.columna=xde.columna 	0.532673103442642
6744367	10354	most efficient way to calculate the first day of the current financial year?	select dateadd(year,datediff(month,'19010701','20110630')/12,'19010701') 	0
6744759	34352	mysql select distinct values in two columns	select distinct     least(foo, bar) as value1   , greatest(foo, bar) as value2 from table 	0.00039633484145056
6744803	21061	sqlite count, group and order by count	select foo, count(bar) from mytable group by bar order by count(bar) desc; 	0.161844436823346
6745790	21103	select distinct rows that contain a given set of data	select t1.bid from table_1 t1 inner join table_1 t2 on t1.bid = t2.bid where t1.data = 'a' and t2.data = 'c' 	0
6747000	33662	how to display all variable with/without a null value?	select * from course inner join category on course.category_id = category.category_id outer join tutor on course.tutor_id = tutor.tutor_id  order by course.course_name asc limit $offset, $rowsperpage 	0.000129262729190936
6748889	33706	mysql call for additional filtering for certain rows, only if another table is populated	select  c.* from    content           c ,          program_users     pu  where   pu.useridnum      = 1 and     pu.programidnum   = c.programidnum and not exists (     select *     from content_criteria cc     where cc.contentidnum = c.contentidnum ) union  select  c.* from content_criteria cc, users_criteria uc, content c where cc.contentidnum = c.contentidnum and cc.criteriaidnum = uc.criteriaidnum and uc.useridnum = 1 	0
6750021	11129	casting scientific notation (from varchar -> numeric) in a view	select     ltrim(rtrim(case          when @d like '%e-%' then cast(cast(@d as float) as decimal(18,18))         when @d like '%e+%' then cast(cast(@d as float) as decimal)         else @d     end)) 	0.111129509206619
6752169	4144	how to obtain column comments from sql	select     column_comment from     information_schema.columns where     table_schema = 'db-name' and     table_name = 'table-name' and     column_name = 'column-name' 	0.000773953108146178
6752230	841	mysql need a query using group by column_a to also ignore duplicates of column_b	select count(*) as player_qty, prize as prize_qty from   (select distinct prize, player from prizes) as t1 group by prize 	0.0436586803209142
6752985	27690	analyzing survey data with mysql	select    sum(      case when q1 = 'y' then 1 else 0 end +      case when q2 = 'y' then 1 else 0 end +      ...      case when q20 = 'y' then 1 else 0 end      )    /    sum(      case when q1 in ('y', 'n') then 1 else 0 end +      case when q2 in ('y', 'n') then 1 else 0 end +      ...      case when q20 in ('y', 'n') then 1 else 0 end      ),    person from    mytable group by    person 	0.284875918442622
6753119	8645	collapsing data given groups	select left(name, 5) as name, sum(value) as totalvalue     from datatable     group by left(name, 5) 	0.00288882511959102
6753541	21294	mysql: order by a count of rows from another table?	select e.*, tm.*, count(tm.targetedmuscleid) as coveredmuscles from exercises as e join exercise_targetedmuscles as tm on tm.exerciseid = e.exerciseid where tm.isprimary = 1 and tm.targetedmuscleid in (4, 11) group by e.exerciseid order by coveredmuscles; 	0
6756332	36528	best way to join multiple foreign keys to same table	select bio.text, sig.text from user u join content bio on u.bio       = bio.id join content sig on u.signature = sig.id where u.id = 4 	0.00027362901242545
6756451	36779	sql join on enum column returns all possible values	select t. * , o.amount as discount, p.status from transactions t     left join offer o on o.id = t.offerid     left join payments p on p.offerid = t.offerid and p.memberid = t.memberid where t.companyid = '10' order by date asc 	0.00464303801849274
6757468	37785	how to join two tables on three conditions?	select fieldsites.*, precipitation.* from fieldsites inner join gpcp_precipitation2 as precipitation on precipitation.siteid = fieldsites.siteid where     fieldsites.d_year = precipitation.year and     fieldsites.d_lat = precipitation.lat and     fieldsites.d_lon = precipitation.lon 	0.0102945468612373
6757616	19694	sql query to join two columns of a table with other tables	select  * from    account_txns txns inner join         account_master fromacc  on  txns.fromaccid = fromacc.accid inner join         account_group fromaccgrp    on  fromacc.groupid = fromaccgrp.groupid inner join         account_master toacc    on  txns.toaccid = toacc.accid inner join         account_group toaccgrp  on  toacc.groupid = toaccgrp.groupid 	0.000139454958008372
6758103	5673	sql server query for count sold item in certain dates	select t1.item_name,       (select sum(sold) from table1 t2 where t2.date <= t1.date              and t2.item_name = t1.item_name ) as sold,        t1.date from table1 t1 	5.13812642669632e-05
6758765	27137	sql query to check combinations and match it to the given combination	select userid from user where userid not in    (select distinct userid from useritemcombinations where itemid in                   (select itemid from item where itemid not in (2,3)); 	0.000277061333256132
6760553	30876	how to write mysql5 query for finding duplicate rows from a table?	select username, count(username) as count from tablename group by username having count(username) > 1; 	0.000165583882859274
6760665	11877	trying to get the word with starting upper case on first letter using mysql	select concat(upper(substring(visit_status, 1, 1)),        lower(substring(visit_status from 2))) as status ...... 	0.000617314120231049
6760892	18342	converting a number to datetime sql	select  convert(datetime, cast(20110331 as varchar(8)), 112) 	0.0333137156567735
6762538	43	log sql server stored procedure start and end time 	select      [procedure] = quotename(object_schema_name([object_id]))         + '.' + quotename(object_name([object_id])),     last_execution_time,     avg_execution_time = convert(decimal(30,2), total_worker_time * 1.0 / execution_count),     max_worker_time from sys.dm_exec_procedure_stats where database_id = db_id() order by avg_execution_time desc; 	0.584132322114602
6762649	38872	averaging rows with same id	select id, avg(number) from table group by id 	0.000237064602851078
6765308	5728	mysql: a sum from 3 different tables	select sum(rev) as trev from (     select sum( revenue) as rev from table1     union all     select sum( revenue) as rev from table2      union all      select sum( revenue) as rev from table3  ) as tmp 	0.000534453847497671
6765886	33415	retrieve same column data from two different rows with one sqlite3 query?	select m.*, p1.*, p2.*   from msgs m inner join profiles p1 on m.src = p1.login_hash inner join profiles p2 on m.dest = p2.login_hash 	0
6766616	29463	inexact searching for nearest time value	select id, min(abs(time(time) - time("4:04:35"))) from table 	0.0176154415378264
6766658	40179	select statement that skips certain rows	select     talbe1.a,     table1.b,     table1.c,     table2.d,     table2.e,     table2.f,     table2.g,     from table1 inner join      table2 on table1.b = table2.e         where (table2.f != 'no' and table2.g != 'no') does not return if  f = no and g = no f = no and g = yes f = yes and g = no does return if f = yes and g = yes 	0.00120918729896051
6767487	26245	problem with grouping on european standard week and year	select   week  = datepart(isowk, thethursday),   year  = datepart(year, thethursday),   count = count(*) from (   select     thethursday = dateadd(       day,       3 - (datepart(dw, col1) + @@datefirst - 2) % 7,       col1     )   from @t ) s group by   thethursday 	0.00825169843149363
6767940	13848	mysql: counting column from different tables on a certain timeframe	select sum(counted) as tcounted      from (select counted from `clicks`.`t1` where somedatecol between somedate and somedate           union all           select counted from `clicks`.`t2` where somedatecol between somedate and somedate           union all           select counted from `clicks`.`t3` where somedatecol between somedate and somedate          ) as tmp` 	0
6769563	33735	mysql join query to sum a field in one table based on its corresponding login id in another table	select s2.loginid, sum(points) as total  from submission s2 inner join comment c2 on s2.submissionid = c2.submissionid group by s2.loginid 	0
6774533	35379	how to get database name of sqlserver	select db_name() 	0.00152444739792528
6776365	17760	how to find out client process id in sql server profiler?	select host_name() 	0.0479352448388243
6777978	32288	sql/php: counting average male/females	select count(males.id) / (count(males.id) + count(females.id)) * 100 as male_percentage from discos_events join discos_events_guests on discos_events_guests.eid = discos_events.id left join users males on males.sex = 'male' and males.id = discos_events_guests.uid left join users females on females.sex = 'female' and females.id = discos_events_guests.uid where discos_events.did = :id 	0.00494858173100728
6778435	2251	how to create sql query to calculate the difference between two values in same column based on dates	select t2.date, t2.value-t1.value from table1 as t1, table1 as t2 where t2.date=dateadd("d",1,t1.date); 	0
6779166	8473	omit all result if one row is equal to a certain value	select * from table1 t1 where not exists   (select 1    from table1 t2    where t1.user = t2.user    and wrong = 'yes'); 	0
6779607	26793	sql query to find the duplicate records	select    title from     (     select        title, count(*) over (partition by title) as cnt     from       kmovies     ) t order by    cnt desc 	0.000579287276128736
6780284	26329	can i select the data of a given row and column while executing a sql statement	select * from dbo.evnt_hstry hstry where evnt_hstry_cd like '3' and not exists (select 1 from evnt_hstry where hstry.evnt_id = evnt_id and hstry.adt_trl_dt_tm > adt_trl_dt_tm) 	0.000443559664914486
6780529	14395	i'm using mybb, how can i find the top 5 threads that has the most readers currently?	select count(*) as count, subject as title from `mybb_sessions`,`mybb_threads` where location1 = tid group by `location1` order by count(*) desc limit 10 	4.77390074874256e-05
6781083	29829	query to get all those names of employees,who have 'a' as their middle character in their name	select `ename` from  `employees` where substr(`ename`, length(`ename`)/2+1, 1) =  'a' 	0
6781311	16313	counting the most amount of items assigned to a user using greatest	select a.actorid, a.name     from request r         inner join actor a             on r.actorid = a.actorid     group by a.actorid, a.name     order by count(distinct r.itemid) desc     limit 5 	0
6782643	10009	excel - converting datasource into data dictionary	select table_name from information_schema.tables where table_type = 'base table' declare @tablename sysname declare table_cursor cursor fast_forward  for  select table_name from information_schema.tables where table_type = 'base table' open table_cursor fetch next from table_cursor  into @tablename while @@fetch_status = 0 begin     select table_name,             column_name,             data_type + coalesce('(' + cast(character_maximum_length as varchar) + ')' ,'') datatype,              is_nullable     from information_schema.columns      where     table_name = @tablename     fetch next from table_cursor      into @tablename end close table_cursor deallocate table_cursor 	0.500181697018202
6784299	7926	calculating the 95th percentile value?	select min(value) 	0.00495851322420355
6784604	16209	mysql self-referencing id and selects	select u1.username, if(u1.oppponent = -2, "bye", u2.username) as username from users as u1 left join users as u2 on u1.opponent = u2.id join starcraft2brackets as sc2a on u1.id = sc2a.uid where u1.uid = ?; 	0.0825854808973018
6784895	41334	doctrine2 - 3 tables relation - select	select c from entity\user u inner join u.hosts h inner join h.category c where u.id = :user 	0.134955831619246
6785100	5045	how to put the sum of all rows in each row	select     clientes.nombre as [nombrecliente], venta.usuario as [nombrevendedor],             venta.fecha, venta.id as [idventa], idproducto as [clave],             producto.descripcion, listaventa.precio as [preciounitario],             sum(listaventa.cantidad) as [cantidad],             sum(listaventa.total) as [lineatotal],             (select sum(listaventa.total) from listaventa where idventa = '36')             as [ventatotal] from       venta  inner join clientes on venta.idcliente = clientes.id  inner join listaventa on listaventa.idventa = venta.id  inner join producto on listaventa.idproducto = producto.id   where      venta.id ='36' group by   clientes.nombre, venta.usuario, venta.fecha, venta.id,             listaventa.idproducto, producto.descripcion, listaventa.precio 	0
6785786	18489	where cast column name equals	select * from (    select id,       col1 as [description],       col2 as [date1],       col3 as [image],       col4 as [date2],       col5 as [link],       col6 as [location],       col7 as [price],       col8 as [title]    from tablename ) as subquery where [title] = 'lemons' 	0.0702211579317484
6786687	31991	extracting sum of data from xml in sql	select     b.name,     sum(b.totalcode) from  (     select         t1.c.value('name[1]', 'varchar(100)') as name,        t1.c.value('code[1]', 'numeric(10,5)') as totalcode     from tablename     cross apply xmlfield.nodes('root') as t1(c) ) as b group by name 	0.000627753473341973
6786874	33831	sql server cast string to datetime	select cast(right(s, 2) + left(s,4) as datetime) from (select '010910' s) a 	0.351354319602094
6788548	24250	custom database query with sql for a specified user_id	select distinct x.*  from master x  inner join detail y on x.id=y.master_id  where y.user_id=? 	0.603602549884835
6788647	18825	sql retrieval from tables	select *     from table    where employee_id = ?? and dtl_id = ?? union   select *     from table    where employee_id = ?? and dtl_id = 0      and not exists (select *                        from table                       where employee_id = ?? and dtl_id = ??) 	0.0547178825613089
6790479	5512	select separate rows from two tables, order by date	select * from (     (select foo.id, null as title, null as body, foo.downloads, foo.views, foo.created from foo)     union all     (select null as id, bar.title, bar.body, null as downloads, null as views, bar.created from bar) ) results order by created asc 	0
6790753	17077	comparing two large sql queries	select  * from  ( query a goes here  ) as a left join ( query b goes here  ) as b on a.col1=b.col1 and a.col2=b.col2 .... where b.col1 is null 	0.0859956498662453
6791202	37116	mysql: adding and multiplying	select sum(price * items_purchased)   from mytable 	0.100373822341397
6791320	23845	mysql error...#1305	select cos    (0.4)  select cos(0.4)  	0.610911624309268
6791840	7204	mysql, similar topics	select  tr.* from    topic t join    topic_tag tt on      tt.topic_id = t.id join    topic_tag ttr on      ttr.tag_id = tt.tag_id join    topic tr on      tr.id = ttr.topic_id where   t.id = $topicid group by         tr.id order by         count(*) desc 	0.151328406748846
6792431	29297	how to calculate sum of count(*) in mysql	select sum(cnt) from (     select count(*) as cnt from tbl_events     union all     select count(*) as cnt from tbl_events2 ) as x 	0.00241925257433122
6793168	14965	summation of results in mysql and then dividing the result by 2	select (sum(sales_today) + sum(sales_yesterday)) / 2 from table1 	0.00192471027392256
6793604	12979	mysql / sql 'exclude' or 'except'	select * from ... 	0.144909225795419
6795176	28978	display only best result out of one-to-many select	select bookmarks.url, comments.title, comments.comment, comments.rating       from bookmarks inner join booksncomms on bookmarks.bid=booksncomms.bid inner join comments on comments.cid=booksncomms.cid       join (            select bookmarks.bid               from bookmarks           order by bookmarks.datecreated desc              limit 10       ) as a on a.bid=bookmarks.bid       join (           select comments.cid, max(comments.rating)                as maxrating             from comments       inner join booksncomms on comments.cid=booksncomms.cid         group by booksncomms.bid       ) as b on b.cid=comments.cid      where comments.title is not null   order by bookmarks.datecreated desc; 	0.000244960948138446
6795219	6650	refine sql result set by average	select g.gametitle,            p.name,            g.id,            b.filename     from   games as g,            banners as b,            platforms as p,            ratings as r     where  r.itemid = b.id            and g.id = b.keyvalue            and r.itemtype = 'banner'            and b.keytype = 'fanart'            and g.platform = p.id     group by g.gametitle,              p.name,              g.id,              b.filename     having avg(r.rating) = 10 	0.00914792117097807
6795280	124	selecting the most recent entry subject to a condition	select id, max(date) as date, grocery_item from table where date < 201103 group by grocery_item 	0
6795558	7060	could these two selects be crushed into one?	select users.user as user,        users.budget as budget,        sum(spendings.cost) as spent from users left outer join spendings on spendings.user = users.user group by users.user, users.budget 	0.105087546891809
6796183	28525	sql statement - select * with max()	select tn.*     from table_name tn    where tn.version =           (select max(sq.version)              from table_name sq             where sq.equipid = tn.equipid); 	0.494099508806959
6797993	9963	sql select latest post by postid	select * from table where postid = (select max(postid) from table) 	0.00231292497659104
6800929	34008	help with an sql query to sum of the number of rows depending on an option in another table	select           mark_notifications_options.grouptogether,          count(mark_notifications.threadid) as ungrouped,           sum(mark_notifications.threadid = 0) as total_zero,           count(distinct mark_notifications.threadid) as grouped      from mark_notifications mark_notifications     left join mark_notifications_options mark_notifications_options on mark_notifications_options.userid = mark_notifications.userid    where mark_notifications.userid = $userid group by mark_notifications_options.grouptogether 	0
6801004	7891	how to get count of rows returned from nested and where in used query in mysql?	select kullanicinick,        kullaniciadi,        kullanicisoyadi,        count(*)  from panelkullanicilari where id in     (select user_id      from proje_ekip      where proje_id=11) group by 1,2,3  order by kullanicisoyadi 	0.00108753140836272
6801946	32718	sql combine select statements into two columns	select orders.ticker, t1.enter, t2.exit from orders inner join trend t1 on orders.enter = t1.number inner join trend t2 on orders.exit = t2.number 	0.00108879933051424
6802218	2412	boolean logic on multiple rows of an sql table	select unique id from table as t1 where (t1.source = 'a' or t1.source='f')   and exists     (select * from table as t2     where t2.id = t1.id and (t2.source = 'c' or t2.source='g')     ) 	0.0186428815976348
6802230	17436	sql server: how to get current date time in yyyymmddhhmissmss	select replace(        replace(        replace(        replace(convert(varchar(23), getdate(), 121),        '-',''),        '.',''),        ' ',''),        ':','') 	0.000171846602242524
6803690	11871	in mysql, how do i join and only get the first of a set	select e.event_id, min(ep.product_id), p.product_name from `events` e left outer join event_products ep on ep.event_id = e.event_id left outer join products p on p.product_id = ep.product_id group by e.event_id, p.product_name ; 	0
6805944	17942	how to distinguish if a database object (in oracle) is a table or view	select c.table_name  from user_tab_columns c, user_tables t where c.table_name = t.table_name and c.column_name='studentid'; 	0.162386807884826
6806761	35535	group by age from date field	select     case         when age < 20 then 'under 20'         when age between 20 and 29 then '20 - 29'         when age between 30 and 39 then '30 - 39'         when age between 40 and 49 then '40 - 49'         when age between 50 and 59 then '50 - 59'         when age between 60 and 69 then '60 - 69'         when age between 70 and 79 then '70 - 79'         when age >= 80 then 'over 80'         when age is null then 'not filled in (null)'     end as age_range,     count(*) as count         from (select timestampdiff(year, dob, curdate()) as age from gamers) as derived         group by age_range         order by age_range 	0.000539400265078303
6807854	13631	get other columns that correspond with max value of one column?	select    s.video_id    ,s.video_category    ,s.video_url    ,s.video_date    ,s.video_title    ,short_description from videos s    join (select max(video_id) as id from videos group by video_category) max       on s.video_id = max.id 	0
6810877	9341	select only albums with photos in them	select albums.aid, albums.defaultpic  from albums join photos on (albums.aid = photos.aid and photos.deleted = 0) where $privacychecksql and albums.uid='$userid'  group by aid limit $start , $limit 	0.00273944179383183
6811397	39963	check if matching record exists within 28 days of current record	select id, uid, date from orders current where exists  (     select * from orders future      where future.date < dateadd(days, 28, current.date)     and future.date > getdate()     and future.uid = current.uid ) 	0
6813144	32609	how to display last three rows of a database table in android?	select * from yourtable order by date desc limit 3 	0
6814113	35392	sql query mysql	select longitude, latitude, firstname, surname, profile_pic, facebook_id, distance  from    (select longitude, latitude, firstname, surname, profile_pic, facebook_id, 6371 * acos( cos( radians( users.latitude ) ) * cos( radians( 23 ) ) * cos( radians( 23 ) - radians( users.longitude ) ) + sin( radians( users.latitude ) ) * sin( radians( 23 ) ) ) as distance    from users   ) as u1   where distance >=1000   order by distance   limit 20 	0.600901146971297
6814937	36363	usage of group by clause in the below criteria?	select   id,   data,   max([date]) as maxdate from   tablename group by   id,   data 	0.26510170780596
6818265	7112	return a count each row instead of a sum or single row in postgres	select  sum(active::boolean::int) as active,          sum((not active::boolean)::int) as inactive,          entry_id_ref from    sooper_entry group by         entry_id_ref 	0
6821246	34452	html check boxes to add/remove entries on a many-to-many look up table (php/mysql)	select employee.*, (select count(id) from employee_project     where project_id=<project_id> and employee_id=employee.id)     as in_project     from employee 	0.000452308475920819
6822087	25661	sql procedure to return the result in one row	select memberid, userid, group_concat(role) as roles from mytable group by memberid, userid 	0.00140984223712435
6822606	40788	create a report show specific stats for each day between a start and end date	select 'created' as src, count(*) as cnt, date(question_created_date) as created ... union select 'answered' as src, count(*) as cnt, etc... 	0
6822636	7276	single query to get the messages and count their answers	select m.message, count(ma.answer_id) as answercount     from messages m         left join message_answers ma             on m.id = ma.message_id     group by m.message 	0.000105517320898244
6822666	14344	how can i replace null category titles in mysql rollup function?	select  ifnull(name, 'maintotal') as name,  ifnull(location, 'subtotal') as location,  sum(if(division='oem',totalhours,null)) as oem, sum(if(division='a/m',totalhours,null)) as am, sum(if(division='skf',totalhours,null)) as skf, sum(if(division='re',totalhours,null)) as re, location as location from $databasetable group by location, name  with rollup 	0.629789120845667
6825078	21336	selecting and formatting by type 1 or 2 after join operation	select   m.member_id,  m.login,   p.type,  case p.type     when 1 then '<div id=1>'     when 2 then '<div id=2>'  end as mydiv from   permissions p inner join members m on p.member_id = m.member_id where   k_id = '$kid'  order by p.type desc 	0.323832962705445
6825279	13975	mysql query & the php - how to do this?	select avg(q1) as accommodation, avg(q2) as scenery, avg(q3) as food from my_table group by sid 	0.687154585542419
6826342	33071	mysql - specific columns on join?	select user.firstname, provider.* from user left outer join provider on user.providerid = provider.id 	0.0123570092422771
6827178	30539	complex sort and grouping with mysql	select t1.*, t1.hitcount as maxhit from chapter as t1 where t1.hitcount = (select max(hitcount) from chapter where chapterno = t1.chapterno) order by t1.chapterno desc 	0.699671167323655
6828915	21493	calculating time length, through php or mysql?	select procedure_id, subtime(events_max.start, events_min.start) as duration from procedure join ( select procedure_id, select max(time) as start from procedure_events group by procedure_id ) as events_max using ( procedure_id ) join ( select procedure_id, select min(time) as start from procedure_events group by procedure_id ) as events_min using ( procedure_id ) group by procedure_id 	0.100281068898542
6832508	4021	month/year sql to correct format	select   * from   members where   signupdate between @param and dateadd(month, 1, @param) - 1 	0.340830301752761
6832954	28058	need help creating a select query to select unique rows	select     tddate,     case tdtype         when 'login' then min(tdtime)         when 'logoff' then max(tdtime)         else null     end as tdtime,     tdtype,     tdusername from timedata group by tddate, tdtype, tdusername order by tddate, tdtime 	0.244053396728701
6833569	9519	extracting strings from mysql field	select substring_index(substring_index(column_name, '<! 	0.00155707500157146
6835035	27193	t-sql datetime question	select *   from tablename   where orderno = 'ab103' and senddate between '4/1/2010' and '4/30/2011' 	0.779677698527383
6836249	14663	joining four tables	select a.member_id, b.date, d.title, c.content from members as a join permissions as b on b.member_id = a.member_id join kcontent as c on c.k_id = b.k_id join ktitle as d on d.k_id = b.k_id where a.member_id = {inputmemberid} order by b.date, d.k_id, d.title 	0.0341850661855078
6836676	3984	how do i write a sql query to check if a many-to-many relationship on one table is a subset of a many-to-many relationship on another table?	select  * from    promo p where   id not in         (         select  pp.promo_id         from    promoproduct pp         where   pp.product_id not in                 (                 select  product_id                 from    orderproduct op                 where   op.order_id = $order                 )         ) 	0
6837177	3310	select distinct field, but avoid some values	select capital_id  from tablename where capital_id <> $capital_id group by 1 having sum(value = $value) = 0 	0.0097055636553497
6837266	8534	how do i get the sum of those three counts()?	select (select count(`id`) from `table1` where `id` = '1') +        (select count(`id`) from `table2` where `id` = '1') +        (select count(`id`) from `table3` where `id` = '1') as `sum` ... 	0
6837674	1992	sql parent child table interview question	select id,name,parentid from table where parentid = 1 union select id,name,parentid from table where parentid in (select id from table where parentid = 1) 	0.0678701208696155
6840450	1829	mysql counting records in a single table, help needed	select t1.id, t1.cdate,  (select count(*) from ytable as t2 where t1.cdate > t2.date)  as createdbefore from ytable as t1 	0.0727460061875269
6841230	23592	get all unique years from a date column using sql (mysql)	select distinct year(created) from table 	0
6841250	10701	is it possible to find out dependent tables for a view?	select object_definition(object_id(n'myview')) 	0.0650612412200795
6841496	3018	mysql selecting something with array information	select * from tablename where find_in_set('1', x) 	0.0295089792374092
6843200	35291	trying to get a result based on grouping in sql	select billid, sum(value)  from      (select billid, sum(value) as value, count(type) as typecount       from bills group by billid, type) as innergroup group by billid, typecount having count(typecount) > 1 	0.0004498384379137
6843203	30653	sql select id where other columns are identical	select distinct t1.owner  from tablename t1  where t1.owner not in  (     select distinct t2.owner from tablename t2     where t2.wallcolor != t2.roofcolor  ) 	6.33092978361541e-05
6843699	26663	how to build next and previous links with php?	select id,title from videos where id < $local_id order by id desc limit 1  select id,title from videos where id > $local_id order by id asc limit 1 	0.00177030960446738
6845082	27398	mysql retrieve 2 values from different tables	select lines.*, poems.* from lines  inner join poems on(poems.pid = lines.pid) where lines.text = 'some value' 	0
6845140	7545	results from mysql database based, not one, but on results from a few tables	select t.name, count(te.expansion) as numberofexpansions     from toy t         left join toy_expansions te             on t.id = te.toy_id         left join owned_toy ot             on t.id = ot.toy_id     where ot.toy_id is null     group by t.name 	0
6845297	22549	sql count distinct absence periods of students	select '111111' as stuid,'2011-01-10' as start_date,'2011-01-15' as end_date into #data union all select '222222','2011-02-01','2011-02-05' union all select '222222','2011-02-06','2011-02-08' union all select '333333','2011-04-07','2011-04-14' union all select '444444','2011-04-20','2011-04-25' union all select '444444','2011-04-23','2011-04-28' union all select '111111','2011-05-01','2011-05-03'  ;with periods as ( select  stuid ,start_date ,end_date ,row_number() over (partition by stuid order by end_date asc) as period_number from #data ) ,periods2 as ( select  p1.stuid ,p1.start_date ,p1.end_date ,p1.period_number ,isnull(datediff(dd,p1.end_date,p2.start_date),1) as period_gap from periods p1 left outer join periods p2 on p2.stuid = p1.stuid and p2.period_number = p1.period_number + 1 ) select  stuid ,count(period_gap) as number_discrete_absences from periods2 where period_gap > 0 group by stuid 	0.00101013620705948
6845307	23193	fetch column if row exists using mysql?	select p.*, s.status       from photo p left join sale s         on p.id = s.photoid 	0.00228376623179122
6846094	26901	customize order by for mysql select query	select *, case when id = 5 then -1 else id end as ordering  from table  order by ordering asc 	0.583128864932043
6846967	9651	mysql - how to count number of rows from primary query, ignore subquery rows?	select  *,    (select count(*) from forum_qa where forum_qa_parent_id  = $forum_qa_id) cnt     from    forum_qa             join user_profiles               on user_id = forum_qa_author_id             left join (select forum_cm_id,                               forum_cm_author_id,                               forum_qa_id_fk,                               forum_cm_text,                         from  forum_cm                         join  user_profiles                           on  user_id = forum_cm_author_id) as c               on forum_qa_id = c.forum_qa_id_fk     where   forum_qa_parent_id  = $forum_qa_id 	0
6847478	12495	how can i find out the date of the last change on a table in teradata?	select tablename, lastaltertimestamp  from dbc.tables where databasename = 'my db name'  order by lastaltertimestamp desc 	0
6848107	8399	mysql question order by `user_id` in (1,2,3) and `name`	select *          from    `user`      order by          case              when `user_id` in (1,4,5) then 1             else `user_id`         end,         `name` 	0.625367994872867
6849332	15803	sql compute average of two fields	select *, cast(total_score as float) / cast(total_nodes as float) as average_score from yourtable order by cast(total_score as float) / cast(total_nodes as float) desc 	0.000748082863856503
6849678	8305	how do i build a summary by joining to a single table with sql server?	select       filename,       sum(case when status = 1 then 1 else 0 end) as countof1,       sum(case when status = 2 then 1 else 0 end) as countof2,       sum(case when status = 3 then 1 else 0 end) as countof3 from       mytable group by filename order by filename 	0.0324407061710267
6850055	30186	sql server string to date conversion	select  o.ordernumber,     convert(varchar(25),cast(o.dateordered as datetime), 101),     cast(oi.category as varchar(max))  from   orders o     left outer join orderitems oi on oi.orderid = o.uid     left outer join orderaddresses oa on oa.orderid = o.uid  where o.dateordered like '6%2011%' and (oa.type = '4') and (oa.country = 'us')  group by cast(oi.category as varchar(max)), convert(varchar(25),cast(o.dateordered as datetime), 101), o.ordernumber 	0.197305113356101
6850612	17419	how can i create this sql query that has to join four tables to allow me extract the data i need?	select jvp.product_id, product_desc, product_full_image, product_name, product_price, category_name    from jos_vm_product jvp   join jos_vm_product_price jvpp   on jvp.product_id = jvpp.product_id   join jos_vm_product_category_xref jvpcx   on jvpcx.product_id = jvp.product_id   join jos_vm_category jvc   on jvc.category_id = jvpcx.category_id 	0.504115513868081
6851764	14249	select based on field in another table	select   table1.user,   table1.city from   table1 inner join   table2 on   table1.user = table2.friends where   table2.friends = '$user' union select   user,   city from   table1 where   user = '$user' 	0
6852201	34713	which example is best at using indexes	select * from table1 t1    inner join table2 t3 on t1.id = t3.t1_id where not exists (   select top 1 1    from table2 t2    where t1.id = t2.t1_id     and not t2.txt like 'blue%'     and not t2.txt like 'green%') 	0.617269570804858
6852311	11903	multiple where selection (high number of params) in sqlite	select * from tables where id in (2, 5, 7, 32, ...) 	0.0396813012179896
6852593	2572	how to group by several days in postgresql?	select ts, count(distinct(user_id)) from  ( select current_date + s.ts from generate_series(-20,0,1) as s(ts) ) as series(ts) left join messages on messages.created_at::date between ts - 1 and ts  group by ts order by ts 	0.00233239603796405
6853327	1019	keep table downtime to a minimum by renaming old table, then filling a new version?	select base_object_name from sys.synonyms where name = 'client' 	0
6853433	4227	mysql - how to group by a column that has conditions	select fi,count(*) from  (   select   case     when content like '%bank of america%' then "bofa"     when content like '%usaa%' then "usaa"     else "other"   end as fi   from topics ) group by fi 	0.00491616493180715
6853897	10830	is there a way to convert the time format in the mysql	select from_unixtime(`updatetime`, '%m-%d') as `updatetime`    from `node_software` 	0.0219750365502864
6854609	2237	what is the difference between clob and nclob?	select parameter, value   from v$nls_parameters  where parameter like '%characterset' 	0.055503895144128
6854833	18778	tsql pivot transformation row fields -> column	select id ,max(case when key = 'name' then string end) as name ,max(case when key = 'age' then number end) as age ,max(case when key = 'sex' then string end) as sex from table group by id 	0.0549115047049028
6855605	11039	php-mysql: like query with modified table column	select column as colmn_find  from cer  where replace(column, ' ', '') like '%yourterm%'; 	0.104502704018525
6856400	10774	join in search results	select     `groups`.`id`,     `groups`.`name`,     `groups`.`description`,     `groups`.`members`,     `groups`.`image`, from     `groups` left join group_members on `groups`.`id` =  group_members.group_id where     `groups`.`name` like '%a%'     or     `groups`.`description` like '%b%'    and group_members.status  = xxx 	0.55915481878808
6856923	7433	select all distinct and get all rows of each distinct values from the same table	select date, count(banner_action) from table where banner_id = 1 group by date 	0
6857004	2104	find from database table based on field value of another table?	select   pages.id,   page_revisions.title,   page_revisions.content from   pages left join   page_revisions     on page_revisions.id = (select top 1 id from page_revisions where page_id = pages.id order by created desc) where   <conditions> 	0
6857380	40655	.net data base access: newest technology, comparison (2011)	select new mydto... 	0.22256993567259
6857461	31303	android sqlite data aceess of a null value attribute	select * from person where phone is null 	0.00242740578704304
6857702	24727	sql query ( sql server) date & time difference	select startdate from table where year(startdate)=year(getdate()) and month(startdate)=month(getdate()) and day(startdate)=day(getdate()) and (datediff(minute, startdate, getdate()) >= 5      or      datediff(minute, startdate, getdate()) <= 5) 	0.0536869148700939
6859016	14165	query to pull document categories (with their parent), only when the category actually contains documents?	select     cat.name, parent.name from     documentcategories cat     inner join documentcategories parent         on  parent.catid = case when cat.parentid = 0 then cat.catid else cat.parentid end where     exists (         select 1         from              doccats dc         where             dc.catid = cat.catid) 	0
6859221	20971	how to get columns data which are having different values after comparing with other table?	select      a.id         ,   a.rollno as [rollno_a]         ,   b.rollno as [rollno_b]         ,   a.status as [status_a]         ,   b.status as [status_b] from        dbo.tablea  a inner join  dbo.tableb  b on          a.id        =  b.id where       a.rollno    <> b.rollno or          a.status    <> b.status 	0
6859377	16389	multiple queries in sqlite for ios	select category, count(drinkid) as drinksinthiscategory            from drinks            group by category 	0.520527560559092
6860746	40662	sql selecting multiple columns based on max value in one column	select t.orderfileid, t.itemnumber, t.itemcost, t.warehouse     from yourtable t         inner join (select itemnumber, max(orderfileid) as maxorderid                         from yourtable                         group by itemnumber) q             on t.itemnumber = q.itemnumber                 and t.orderfileid = q.maxorderid 	0
6861313	17292	get the highest-n values including duplicates in sql	select s1.id, s1.series from seriesscores s1  inner join      (select distinct series from seriesscores order by series desc limit 0, n) as s2      on s1.series = s2.series 	0.00153263244094264
6861749	26075	sqlexception because subquery returned more than 1 value	select * from orders where customer_id =    (select customer_id from customer where name ='bob') 	0.353351159651339
6862181	40491	last 24 hours updated records from table using oracle sql?	select distinct c.constit_id as constitid,                replace (c.in_labelname, 'none', '') as fullname,                c.firstname as firstname, c.lastname as lastname,                c.indiv_title as title, e.e_addr as email,               'inactive' as status                                          from tbl_constit cn, tbl_email e,tbl_catcod s          where c.constit_id = e.constit_id            and c.constit_id = s.constit_id(+)            and e.e_type = 'email'            and e.e_default = '1'            and s.cat_code in ('spemu', 'spenm')            and ((cn.chgd_dt > (sysdate - 1)) or (e.chgd_dt > (sysdate - 1)))       order by c.constit_id; 	0
6862798	171	mysql three table join while concanting a column?	select movies.*, group_concat(categories.name) from movies left join movies_categories on (movies.id = movies_categories.movie_id) left join categories on (movies_categories.category_id = categories.id) group by movies.id 	0.0609779367587674
6864123	25907	how do i get the earliest date and latest date from 5differnt table in sql and populate them into a dropdown form?	select min(somedate) from table1 union select min(somedate) from table2 union select min(somedate) from table3 	0
6864417	30604	comparing fields in sql server 2008 r2 where there is both letters and numbers	select transaction, equiptype, serialnum from table1 where  (serialnum  collate sql_latin1_general_cp1_ci_as           not in (select serial_num  collate sql_latin1_general_cp1_ci_as from table2 )      and transaction = @transaction) 	0.104640841375371
6864747	7319	3 table sql join	select      vendor = v.name,     staff = vs.vendorstaff,     region = t.[type] from     dbo.vendor as v inner join     dbo.vendor_staff as vs     on v.pkvendorid = fkvendorid inner join     dbo.type_zone as t     on v.fktype_zoneid = t.pktype_zoneid where     v.active = 1 order by     t.type,     v.name; 	0.188098219045125
6864799	8532	how to reuse calculated columns avoiding duplicating the sql statement?	select      a.val as a,      b.val as b,      c.val as c  from mytable   cross apply(select 1 + 2) as a(val)   cross apply(select a.val + 3) as b(val)   cross apply(select b.val * 7) as c(val) 	0.0427094893340211
6865821	28557	update a field with different information	select clientlastname__c,    clientfirstname__c,    clientid__c,    category_id__c,    id as incident__c,    '95939439uuxx' as ownerid,    systemtypedesc as taskdescription__c  from process.dbo.vw_newhireprocess  where system_type__c is not null 	0.00429040762247486
6866105	26040	mysql query and pivot tables	select ifnull(typeofwork, 'total') as typeofwork, sum(if(month='jan',totalhours,null)) as jan,     ... sum(if(month='dec',totalhours,null)) as `dec` from $databasetable group by typeofwork 	0.485414992030182
6866545	655	mysql select any department that has had transactions in every month in the last year	select deptid, count(distinct month(`date`)) as month_count from transactions where `date` >= curdate() - interval 1 year group by deptid having month_count = 12; 	0
6868422	37035	oracle/sql query for some calculation!	select    value - prev_value as diff,   '(' || to_char(value) || ' - ' || to_char(prev_value) || ')' as expression from (   select value, idx,    lag(value) over (order by idx) as next_value,   lead(value) over (order by idx) as prev_value from(           select 25 as value, 1 as idx from dual union all select 20 as value, 2 as idx from dual union all select 15 as value, 3 as idx from dual union all select 12 as value, 4 as idx from dual union all select 11 as value, 5 as idx from dual union all select 10 as value, 6 as idx from dual ) ) where prev_value is not null 	0.619001717602232
6868517	5493	oracle sql convert hex to char	select asciistr(chr(to_number('0a','xx'))) from dual 	0.456407582699097
6869974	37237	how do i select a value whose id don't exist as parent to others, in mysql?	select * from `nestmenu` where `id` not in (select `parent_id` as `id` from `nestmenu`) 	0
6870524	16136	sql query to get sum of amounts based on the taxtype code	select fedtaxid, sum(tx02t) as tx02_tot , sum(tx03t) as tx03tot , sum(txallt) as txnntot   from (select case when  taxtypecode = 'tx02' then amount else 0 end as tx02t,                case when  taxtypecode = 'tx03' then amount else 0 end as tx03t,                amount as txallt         from tbltest         where fedtaxid = '888888888'        )  group by fedtaxid 	0.000204577267968575
6870846	33993	unix time to date in mysql	select * from visits where from_unixtime(visit_time, '%y-%m-%d') = curdate() 	0.00400054432969836
6873376	4334	using php and mysql to populate html select isnt sorting	select category from category order by category 	0.323391434059732
6873985	1662	how to inspect sql server database during a transaction?	select * from dbo.table with (nolock) 	0.0892137137747035
6875495	38505	sql date question	select thedate from datetable where thedate >= (select max(thedate) from datetable where thedate < getdate()) 	0.608906831536642
6875832	35171	mysql find data in one table based on conditions of two other tables	select bunch_of_columns from items i  inner join items_to_groups ig on i.id=ig.item_id inner join items_to_regions ir on i.id=ir.item_d where ir.region_id=y and ig.group_id=x 	0
6877668	27830	finding possible duplicates in database	select distinct t.name, t.surname, t.phone from table t  left outer join table t2 on t.name = t2.name and t.surname = t2.surname and t.phone <> t2.phone where t2.name is not null 	0.0446890476219012
6877823	33270	sql query getting datetime range	select comment.adddate, event.starttime   from comment   join users on users.users_id = comment.userid   join event on users.users_id = event.userid  where eventid = 5630    and comment.adddate between dateadd(minute, -30, event.starttime)        and dateadd(hour, 2, event.starttime) 	0.0233857254050064
6877859	14934	sql limit total vs limit column	select event from table group by year order by id limit 5 	0.0493269044698508
6879073	29793	mysql outer join - determine if the joined row exists	select a.id,not isnull(b.id) as exists from a left outer join b   on a.id=b.id; 	0.079037140816889
6880150	28686	mysql : is it possible to select those values	select distinct     substring_index(field, ':', 1) as strippedfield from tablex 	0.0134007251375089
6880249	23194	sql server table with different user profiles	select       u.*,      c.*,      m.*      from users u         left join consumers c on c.user_id = u.id         left join marketers m on m.user_id = u.id      where         u.id = @userid 	0.0149107167292182
6880801	749	simple way to concatenate bit and nvarchar columns	select id,         item + (case hidden when 1 then ' (hidden)' else '' end) as conct from items 	0.073337792112725
6881272	9935	how query can i use to get a best seller?	select   title,   sum(quantity) as total_sales from   books group by   title order by   total_sales desc 	0.167228369944892
6881424	20735	how can i select the row with the highest id in mysql?	select * from permlog order by id desc limit 0, 1 	0
6881629	19831	mysql select with exceptions	select id from dates where user = 'x' and id not in (select id from exceptions where user = 'x')) 	0.52059325091662
6885054	18643	fetch data from two tables?	select table-a.id, table-a.article-name, table-a.date, (select count(id) from table-b where article-id=table-a.id) as numberofcomments from table-a; 	0.000152893313354648
6887234	11131	when joining a table to itself to identfy duplicate date in a column, how do you keep it from returning the inverse in the results?	select t1.rowid, t1.column1, t2.rowid, t2.column1 from test t1 inner join test t2 on t1.column1 = t2.column1 and t1.rowid < t2.rowid 	0
6887679	17586	sql server set based division among sets?	select     a.keycol as a_keycol,     a.countcol as a_countcol,     b.keycol as b_keycol,     b.countcol as b_countcol,     c.keycol as c_keycol,     c.countcol as c_countcol from b cross join c inner join a on a.countcol = b.countcol * c.countcol 	0.00649590024490464
6887781	27167	php mysql joins	select one.* from one, two where one.type='7' and two.live='1' and one.c_id = two.id order by one.id desc limit 5 	0.726478175136389
6888381	18808	return output parameter from a stored procedure that includes several derived tables	select  rownumber,newsid,innercount from  (     select row_number() over (order by firstvisit) as 'rownumber', newsid       , count(*) over () as innercount     from         (         select distinct newsid,firstvisit,publishdate from vwnewspack      ) as t ) as tt          where newsid between 10 and 20 	0.0239475527765075
6888466	26420	how i can delete repeated rows from database?	select distinct * into   #tempgood from   good_ truncate table good_ insert good_ select * from   #tempgood drop table #tempgood 	0.00118351136797215
6888910	16217	return a single row with the maximum value	select trackid, artist, countview from tracklist  order by countview desc limit 1 	0
6889083	6034	sql server order by different values	select top x * from mytable order by   case        when status = 'gold' then 4        when status = 'silver' then 3        when status = 'active'  then 2        when status = 'inactive' then 1   end desc 	0.024988180218909
6890688	8673	is it possible to create and use "virtual" table in mysql query?	select 1 as product_id, 1 as quantity union all select 2, 1 union all select 3, 100 ... 	0.517625971632051
6890830	8055	assigning each like statement a value that is returned on matching	select case when wordtext like 'alpha%' then 0 when wordtext like 'beta%' then 1 when 'gamma%' then 2 else -1 end as match from words where match <> -1 	0.000678911643919341
6891169	33457	select sum in sql server using one query	select sum(cal1+cal2) as total   from cat 	0.135501231088698
6891388	39576	allow duplicate matches for a case statement	select `word`, 12 as matchid from `words` where `word` like 'a%' union select `word`, 13 as matchid from `words` where `word` like 'b%' union select `word`, 14 as matchid from `words` where `word` like 'a%' 	0.525474343658403
6892392	38188	select number of times result of one query occurs in another table	select     customer, count(*) as orders  from         orders  right outer join                       users on users.user_id = orders.customer group by users.user_id order by count(*) desc 	0
6893075	22579	counting items or incrementing a number?	select count(*) from mytable 	0.000686966893562895
6893170	23591	mysql like match, but need to filter by username	select *  from prices  where (itemnum like '%$findit%'    or  itemdesc like '%$findit%')   and username = '$username' order by price 	0.53911936358472
6895579	13574	getting multiple values from a query	select      tblcustomer.companyname,     tblcustomerdetail.fedtaxid,     tblcustomerdetail.emailaddress,     tblcustomerdetail.phonenumber  from tbluserlogindetail, tblcustomer, tblcustomerdetail where      tbluserlogindetail.loginid = tblcustomer.customerid     and tblcustomer.fedtaxid = tblcustomerdetail.fedtaxid     and tbluserlogindetail.username like 'pa%'     and tbluserlogindetail.roletypeid = '20' 	0.00385060282848442
6897494	33511	mysql join to get available photos	select photos.id, photos.user_id, photos.s3_thumb, photos.`name`, photos.`date`, photos.`caption` from photos where(photos.user_id = 4)and(not exists(select 1 from users_homepage_photos where users_homepage_photos.`photo_id` = photos.id)) 	0.00398692856596182
6898454	40999	mysql: i want to sum my employees cost and group it by employee and by day	select date, name, sum(amount) as total from mytable group by 1,2 order by 1,2; 	0.000364813690962793
6900123	25666	problem making 1 big query from lots of small ones	select something from topic left join friendship on friendship.user_id = topic.user_id && friendship.friend_id == watch_id left join access on access.topic_id = topic.id && access.user_id == watch_id where   watch_id == topic.user_id or   topic.visibility == 3 or   (topic.visiblity == 2 and friendship.user_id is not null) or   (visibility == 1 && access.topic_id is not null) 	0.606872131713008
6900875	40896	mysql average of column where there are greater than 5 rows	select round(avg(points),1) as a from points where user_id=x having count(*) >5 	0
6901591	5010	how to search a image/varbinary field for records that start with a binary pattern	select [cpclid]  from [cp] where cast(cpphoto as varbinary(4)) <> 0xffd8ffe0 	0.000332613949176591
6902636	25076	performant check for existence of values	select item from table as t1 where user = x   and exists ( select * from table as t2 where user <> x and t1.item = t2.item ) group by item 	0.00191377296111073
6903015	21193	modified preorder tree transversal child roll up	select c.name, sum(s.amount) from companies_table c     join companies_table c2 on c2.lft between c.lft and c.rght     join spend_table s on c2.id = s.company_id where parent_id = (select id from companies_table where name = 'parent a') group by c.name 	0.0206933080134108
6903456	21431	query parents without children	select m1.cod_menu     from menu m1     where not exists(select null                           from menu m2                           where m1.cod_menu = m2.cod_menu_parent)         and m1.issubmenu = 't' 	0.0296695113827959
6903963	38131	selecting 1 instance of a client's family in mysql	select f.headofhouseholdid 'hohid',     concat( c.lastname, ', ', c.firstname ) as 'head of household',     c.phonenumber as 'hoh phone',     f.relativeid,     concat( c2.lastname, ', ', c2.firstname ) as 'relative',     relationship.description as 'relation',     c2.phonenumber as 'relative phone', c2.dob,     (             (             date_format( now( ) , '%y' ) - date_format( c2.dob, '%y' )             ) -             ( date_format( now( ) , '00-%m-%d' ) < date_format( c2.dob, '00-%m-%d' ) )     ) as age     from client c     inner join clientfamily f on c.clientid = f.headofhouseholdid     join (             select clientid, max( datevisited ) as 'datevisited'             from visits             group by clientid     ) v on c.clientid = v.clientid     join client c2 on c2.clientid = f.relativeid     join relationship on f.relationshipid = relationship.relationshipid     where v.datevisited             between curdate( ) - interval 1 year             and curdate( ) 	0.00183081011161278
6905775	25649	apply scalar function to each row	select comparestrings(@string1, tablestring) from yourtable 	0.0297678870827302
6908809	39471	sorting mysql result datas	select `date`, group_concat(`id`) from `example` group by `date` 	0.115762465832153
6908895	37768	how do i return a boolean value from a query during condition evaluation?	select (case when len(somelongtextcolumn) = 0 then 1 else 0 end) as isemtpy 	0.00818129510168699
6909314	9531	is it possible to replace values in sql query?	select case [accepted]  when 0 then 'not_accepted'  when 1 then 'accepted ' else 'not_available' end as accepted , count(*)  from my_table  group by case [accepted]  when 0 then 'not_accepted'  when 1 then 'accepted ' else 'not_available' end 	0.628394133394446
6913040	37764	comparing values in sql	select @count = count(id) from @mytable  where id = @id     and (isnull(value1,0) <> @value1 or isnull(value2,0) <> @value2) 	0.0369719941298796
6913460	15642	trying to generate a subset from an in statement	select *   from (select regexp_substr(&x, '[^,]+', 1, level) phone_number            from dual          connect by level <= length(&x) - length(replace(&x, ',', '')) + 1)  where phone_number not in (select phone_table.phone_number                                from phone_table) 	0.0187525546353337
6914241	27288	ordering a group_concat column (mysql)	select `users`.*, group_concat(distinct `majors`.name order by `users_majors`.order) as major, group_concat(distinct `users_majors`.order) as major_order from `users` left join users_majors on (users_majors.user_id = users.id) left join majors on (majors.id = users_majors.major_id) group by users.id 	0.336733030876865
6914292	5091	mysql: 24 hour interval with joins	select * from winners      join profiles on winners.subscriber_id = profiles.subscriber_id     left join comments on (comments.profile_id = profiles.vanity and comments.created_at > date_sub( now(), interval 24 hour))     left join videos on (winners.subscriber_id = videos.subscriber_id and videos.created_at > date_sub( now(), interval 24 hour))     left join photos on (winners.subscriber_id = photos.subscriber_id and photos.created_at > date_sub( now(), interval 24 hour)) where winners.round_id >= 4 and winners.active = true  and comments.parent_id = 0; 	0.0182355565644415
6914752	40907	mysql query for multiple rows	select column1, column2, count(*) from tablename group by column1, column2 having count(*) > 1 	0.0547525915474562
6915305	37986	sql server -- loop through each column in every table?	select s.name schemaname, t.name tablename, c.name columnname from sys.columns c inner join      sys.tables t on c.object_id = t.object_id inner join      sys.schemas s on t.schema_id = s.schema_id ; 	0.000132491200625397
6917423	37452	how can i set multiple t-sql variables in a single select query?	select    @sampleid = [sample].sampleid,     @clientid = [client].clientid from dbo.[test]     ... the rest of your code above 	0.0619260270378815
6917556	10572	mysql select a column by month	select * from table where month(col_name) = 8 	0.0019378894851773
6918553	8961	how to get most recent row in a table?	select * from blog order by date desc,blog_id desc limit 5 	0
6919666	31821	get linked info from mysql in one request	select ip, firstname, lastname from applications where pin = '2232' or  ip in (select ip from applications where pin = '2232') 	0.000249648445962984
6922107	35750	merging records based on a time difference?	select distinct a.id,a.name,a.startdate,a.enddate from temp a   left join temp b on a.name = b.name and a.id < b.id and datediff(s,a.startdate,b.startdate)<=60   left join temp c on c.name = a.name and c.id < a.id and datediff(s,c.startdate,a.startdate)<=60 where (b.id is not null or c.id is null) and a.id <= coalesce(c.id,a.id) 	0
6922675	8906	how to select unique rows from one to many relationed tables in mysql?	select groceries.product, person.name, location.name from person left join groceries on person.id = groceries.person_id left join location on person.id = location.person_id where person.id in ( select person.id from person left join groceries on person.id = groceries.person_id left join location on person.id = location.person_id group by person.id having count( person.id ) =1 ) 	0
6923038	5039	mysql - join 2 tables and group values	select   c.companyname,   group_concat(concat(r.resourcename, ' ', r.resourcefirstname, ' ', r.resourcelastname) separator '\r\n') from   company c join   resources r     on c.companyid = r.companyid group by   c.companyid; 	0.0158712428242555
6923610	29026	pl sql - convert a numerical value into varchar (percent)	select cast(round(10.75, 2) as varchar(10)) || '%' as result from   dual select to_char(round(1234567890.29, 2),'9g999g999g999d99' ) || '%' as result from   dual 	0.00108319024130977
6924079	17227	how can i pad a number with zeros in mysql?	select '00005' 	0.0126185022141778
6924180	27010	is there a statistical function in mysql to find the most popular value in a column?	select r.supply_fk, s.name, count(*) from resource r inner join supply s on s.supply_pk = r.supply_fk group by r.supply_fk, s.name order by count(*) desc limit 1 	0.000235514916267759
6925949	18059	how to do "show tables as col" alike stuff?	select   table_name as c  from   information_schema.tables where   table_schema = database() 	0.0390785226508243
6927615	14443	php unix time stamp in the past	select * from mytable where time < unix_timestamp(date_sub(now(), interval 30 day)) 	0.00014414230637598
6928053	40426	grab one for each id	select de.id, d.name, de.title  from discos_events de inner join places d on (de.did = d.id)  where de.date = (select max(t.date)                  from disco_events t                  where t.did = de.did                        and unix_timestamp(now()) > t.date) limit 10; 	0
6928483	9464	mysql: i need to pull the same column name from multiple rows into single query based on same conditions	select resource.val from   ( (select "all" as name) union (select "your") union (select "base") ) as facets   left join resource on( resource.facet  = facets.name and resource.urlid = "1234" ) 	0
6929223	11086	reading items with like in a function that splits	select   distinct(pr.myid)  from   myproducts pr   left join pcategory pc on pr.productid = pc.productid   left join category ca on ca.categoryid = pc.categoryid   left join snumber zs on zs.productid=pr.productid   cross apply sc_splitter(@keyword,' ') as sentance  where                    pr.activated = 1                  and pr.portalid = @portalid                   and (pr.name like '%' + @keyword + '%'         or pr.name like '%' + sentance.value + '%')   or pr.mytitle like '%' + @keyword + '%'        or pr.prnum like '%' + @keyword + '%'          or zs.snum like   '%' + @keyword + '%' 	0.131917199007074
6930355	31022	mysql multi group query with count	select pcl.*,    (select count(*) from products_list pl         where pcl.id_cat_unique = pl.id_cat_unique           and pcl.lang = pl.lang) as counter from products_categories_list pcl order by pcl.name_cat asc 	0.56473169587403
6935983	10997	all columns in a table to string sql	select stuff(                     (                         select  ',' + cast([col] as varchar)                         from                         (                             select col1 as col from [dbtest].[dbo].[table] union                             select col2 as col from [dbtest].[dbo].[table] union                             select col3 as col from [dbtest].[dbo].[table]                          ) alldata                         for xml path('')                     )                 ,   1                 ,   1                 ,   ''             ) 	0.00043524214109746
6937164	21594	in postgres is it possible to retrieve distinct date data if the table only contains the datetime field?	select distinct     col_name::date from     table_name 	0
6937556	4749	concatenate values in sql stored procedure	select ltrim(rtrim(field_one)) + ltrim(rtrim(field_two)) + ltrim(rtrim(field_three)) from copyfrom 	0.0409602591515902
6938260	28210	sql select fields with a value of 'y' and order by date descending, then select all others and order by another field ascending	select * from todolist  where ws_status <> 'completed'  and (user_id= 'testusr' or ww_cover='testusr'  or (ws_status = 'orphan' and wwt_workgroupid in (108)))  order by case when wi_urgent = 'y' then 0 else 1 end asc ,psc_alt_code 	0
6938597	8258	only one expression can be specified in the select list when the subquery is not introduced with exists	select firstname, lastname, ei.started,            ((ei.totalcorrect*100)/@examquestioncount) as percentage,            passed_ = case passed                 when '1' then 'yes'                 else 'no'            end,      ei.instanceid  from ea e ei, invite i, osttable ost, ef e  where ei.finished is not null        and ei.inviteid = i.inviteid 	0.698205986774604
6939178	29149	sql: key-value: values in columns?	select    key , max( case value-name when 'color' then value else null end)      as color , max( case value-name when 'heght' then value else null end)      as height , max( case value-name when 'whatever' then value else null end)   as whatever from    table group by key 	0.00504086806564507
6939913	15357	5 minute bars using mysql	select      date_format(          date_sub(             tick_time,              interval (extract(minute from tick_time) % 5) minute         ),          "%m-%d%y %h:%i"     ) as  bar_time,      max(bid) as high,     min(bid) as low from ticks group by bar_time 	0.144355224462955
6940315	3326	writing a sql to calculate datediff	select *, datediff(year,now()) / -365 as date_value_table from hotel 	0.290979082892655
6941145	1557	sql query: how to make the tags without children to become parents?	select parents.tag_id as parentid,        parents.tag_name as parentname,        count(childs.tag_id) as totalchildren from root_tags as parents     left outer join root_tags as childs         on parents.tag_id = childs.parent_id where parents.parent_id is null group by parents.tag_id, parents.tag_name order by parents.tag_id 	0.00103580646684011
6943533	21315	count passed logins and failed logins in same query?	select uid, count(uid) as cnt, count( if( passed = 0, 1, null ) ) as failed from logins group by uid order by cnt desc  limit 5 	0.0097880151476335
6944170	35512	sql - get highest utilization by member by provider	select * from member where member.utilizationcounts =            (select max(utilizationcounts)             from member m2             where m2.memberid = member.memberid) 	0.00203501975785082
6944418	33086	duplicate column names in query	select * 	0.00299551007197746
6944657	12178	how to join three different tables in mysql with no common field amongst them all	select foo from table1     join table2 on table2.groupid = table1.groupid     join table3 on table3.branchid = table1.branchid 	0
6945784	18980	return random 5 records from last 20 records	select * from (   select * from your_table    order by id desc limit 20 ) as lastest_results order by rand() limit 5; 	0
6948796	2817	only select row with later expiry date	select t.serial_number, t.contract_type, t.expiry_date     from yourtable t         inner join (select serial_number, max(expiry_date) as maxdate                         from yourtable                         where contract_type in ('sprt', 'homd')                         group by serial_number) q             on t.serial_number = q.serial_number                 and t.expiry_date = q.maxdate     where t.contract_type in ('sprt', 'homd') 	0.000249671270822623
6949020	28751	returning bit for each row in sql which exist in joined table	select pid, pname, cast(case when b.fkpid is null then 0 else 1 end as bit) existsothertable from part a left join (select distinct fkpid from [joined part]) b on a.pid = b.fkpid 	0
6949307	37156	is there a more elegant way of calculating the median of a group of numbers using ruby-dbi and connection to a database	select median(birthd.decade.members, measures.[%count]) on 0 from patients 	0.00137385587732299
6949369	30916	prepend a digit to the beginning of a field	select concat( '0', int_col ) from .... 	0.000263173527082653
6949575	24691	auto detect db instances	select name from sys.databases 	0.00410572084669479
6949649	24579	inserting missing entries when doing a group by?	select fw.year as 'ayear',        fk.week as 'aweek',        sum(case when t.startdate is not null then 1 else 0 end) from fakeweeks fw left outer join #temp t on datepart(year,startdate) = fw.year and datepart(wk,startdate) = fw.week group by datepart(year,startdate),datepart(wk,startdate) order by 1,2 	0.0356426830926415
6950794	20130	how to display unassigned rows while using crosstab in sqlserver	select     productid,      departmentid,     isnull(aud, 0) as aud,     isnull(usd, 0) as usd,     isnull(euro, 0) as euro,     isnull(gbp, 0) as gbp from (     select departmentid from @tbldepartment     cross join     select distinct productid from @tblsale ) a left join     (         select productid, departmentid,         sum(case currencyid when 1 then value else 0 end) as aud,         sum(case currencyid when 2 then value else 0 end) as usd,         sum(case currencyid when 3 then value else 0 end) as euro,         sum(case currencyid when 4 then value else 0 end) as gbp         from              @tblsale         group by              productid, departmentid     ) b on      a.departmentid = b.departmentid and a.productid = b.productid order by      a.productid, a.departmentid 	0.0149973444893581
6951741	31463	how select only one record in mysql?	select * from table limit 0, 1 	0.000290624649451765
6952106	10599	time difference among end dates of first records to next record first dates	select  sourceid,recordid,startdate,enddate    , datediff(mi,a.enddate,b.startdate) diffmin from table a left join table b on a.no = b.no+1 	0
6952344	35713	mysql select all, group by orderid	select * from #__users_orders where userid = 22  order by orderid desc 	0.0301142624730586
6952665	1564	what is the query to select a table row , matching two column constraints in sqlite	select name from employee where userid=? and passwd=? 	5.95638317006274e-05
6953557	40803	tsql contains weighed columns	select id,searchkeywords, ptitle, pdescription, presentation, category, manufacturerid, sum(srank) ranked  from ( select id,searchkeywords, ptitle, pdescription, presentation, category, manufacturerid, 5 srank from v_productforsearch   where contains ((searchkeywords), @keywords)  union all select id,searchkeywords, ptitle, pdescription, presentation, category, manufacturerid, 4 srank from v_productforsearch   where contains ((ptitle), @keywords)  union all select id,searchkeywords, ptitle, pdescription, presentation, category, manufacturerid , 3 srank from v_productforsearch   where contains ((pdescription), @keywords)  union all select id,searchkeywords, ptitle, pdescription, presentation, category, manufacturerid, 2 srank  from v_productforsearch   where contains ((presentation), @keywords) ) a group by id,searchkeywords, ptitle, pdescription, presentation, category, manufacturerid order by sum(srank) 	0.0434860366650774
6953979	40411	queries separated by union	select a.name, a.age, b.addr, d.group, d.project  from a, b, d  where a.rid=b.tib  and d.uon=a.von  union  select a.name, a.age, c.addr, d.group, d.project  from a, c, d  where a.uiroll=c.piroll  and d.uon=a.von 	0.0464402583013112
6955814	26224	how to grant user privilege on specific schema?	select 'grant select on a.'||table_name||' to b'  from dba_tables  where owner = 'a'; 	0.146575653972268
6957097	9988	selecting with random date ranges	select *  from      my_table     cross join (select from_unixtime(rand() * 2147483647) random_date) rd where      timestamp between (rd.random_date - interval 1 day) and rd.random_date 	0.000587938010295959
6957453	7428	how to sort this query	select x.* from (   select     id, name, level as lvl, leader as par3, timeacceptinvite   from road   where road.id like '180'    union all   select     id, name, lvl, lastonline, dnd, null, raceid, currenthp, dressed_hp as hp, timeacceptinvite    from users    where rid like '180'     and id not like (select leader from road where id like '180')   union all    select    users.id as id, users.name, lvl, lastonline, dnd, currentlocid, location.name as locname, currenthp, dressed_hp as hp, timeacceptinvite    from users left join location on (location.id = currentlocid)    where users.id like(select leader from road where id like '180') ) as x  order by x.timeacceptinvite 	0.649359158600467
6957465	39334	checking a string value	select iif(answer = """""", "no response", answer) from tblanswers 	0.0194139109860949
6960890	36776	getting normalized values from two foreign key fields, sql, double join?	select   move.id,   [from] = fromlocation.name,   [to] = tolocation.name from   move   inner join location as fromlocation on move.[from] = fromlocation.id   inner join location as tolocation on move.[to] = tolocation.id 	0
6961601	8647	include third table in left join query	select     availability.shop_id,     shops.name,      shop_activity.status from availability left join shops on availability.shop_id=shops.id  left join shop_activity on shop_activity.shop_id = availability.shop_id    and shop_activity.user_id = 1 where fruit_id = 2 	0.486755089822974
6962384	6660	underlying rows in group by	select original.id from original inner join temptable on    temptable.fielda = original.fielda and    temptable.fieldb = original.fieldb and    temptable.fieldc = original.fieldc 	0.0589777801741876
6965565	35677	data from two tables and one show	select *   from news1 n1 union all select *   from news2 n2 	0
6969315	30483	mysql query to return rows that contain whitespace	select ...    ...   where username like '% %' 	0.00967936542024408
6969749	37718	sql match against or some other method to search two tables	select * from  (  select question, answer, status, match(title,category) against ('keyword') as rank  from questions   where match(question,answer) against ('keyword')  union   select question, answer, status, match(tag) against ('keyword')  from questions q   inner join question_tags qt         on q.id_question = qt.id_question  inner join tags t      on qt.id_tag = t.id_tag   where match(tag) against ('keyword') ) r order by rank 	0.0119043145454341
6970029	16945	mysql select with condition on left join table returns incomplete result set	select e.id, e.name, min(s.date_start) as range_start, max(s.date_finish) as range_finish from `event` as e left join `session` as s on e.id = s.event_id  where (s.hidden != 1) or s.hidden is null 	0.729875861025811
6970245	38516	android sqlite: select no duplicates in sql query	select origin, max(_id) from items group by origin 	0.453872814595399
6974380	6046	how do i replace one column in a table with multiple columns from another table	select    c.id, c.name as accountname, c.joindate, c.accountstatus, c.companyname,   ma.street1 as mailstreet1, ma.street2 as mailstreet2, ma.city as mailcity, ma state as mailstate,   ma.county as mailcounty, ma.country as mailcountry, ma.postalcode mailpostalcode,   ba.street1 as mailstreet1, ba.street2 as mailstreet2, ba.city as mailcity, ba state as mailstate,   ba.county as mailcounty, ba.country as mailcountry, ba.postalcode mailpostalcode, from   customer c   inner join address ma on ma.id = c.mailaddress   inner join address ba on ba.id = c.billingaddress 	0
6974492	40875	fetch records one by one from each category in the table	select item_id, item_name, dealer_id from mytable order by item_name, dealer_id 	0
6975127	40733	how can i display differently from the database a field from a record, after the execution of a select statement?	select (case [columnname] when 1 then 'cheque' else 'duplicata' end) as [aliasname] from [tablename] 	0
6975446	32458	sql: multiple matches towards same table?	select e.*, r.*, s1.s_name, s2.s_name   from tt_events e   inner join tt_run r on e.e_id = r.e_id   inner join tt_staff s1 on r.e_bandproducer1 = s1.s_id   inner join tt_staff s2 on r.e_bandproducer2 = s2.s_id 	0.00229902177920232
6975878	7777	mysql time difference	select count(*) from database where date_created> now() - interval 1 hour and user_id=17 	0.0325227635740152
6977270	16565	using max and count together in mysql query	select *, max(infodate), count(*) as count 	0.25940980960517
6978146	20111	select from two different tables	select   n1.name as `name1`,   n2.name as `name2`,   n3.name as `name3`,   n4.name as `name4` from   r inner join   n n1 on   n1.id = r.id1 inner join   n n2 on   n2.id = r.id2 inner join   n n3 on   n3.id = r.id3 inner join   n n4 on   n4.id = r.id4 	0.000275680691348939
6978211	17668	concatenate field with plain text in case used in select?	select     case when unityreq = 1 then concat(table, ' (unity)') else table end as type   from ... 	0.115947325178208
6980167	26572	last 10 items from table from last added item	select * from (select *      from messages      where chat_room=5      order by your_date_column desc      limit 10) ilv order by your_date_column asc 	0
6980403	39441	using like query to get the desired output across two tables	select *    from  bw_tempclientdetails bw_temp   left join bw_clientallocation bw_client     on bw_temp.companyname = bw_client.companyname    where bw_client.company like '%fff%'    and (bw_temp.companyname like '%fff%' and bw_client.company like '%fff%'); 	0.0245635298988062
6981224	9617	getting not paid members	select distinct member_firstname   from member m    join paymentscedules p on p.member_id = m.member_id  where date_add(paymentschedule_actualdatetobepaid, interval 7 day)< now()    and paymentschedule_amountdue > paymentschedule_amonutpaid 	0.0862350575244917
6981450	35644	sqlite query compare distance within rows	select a.* from station a inner join station b on distance(a.station_id, b.station_id) < 30; 	0.00800218754790501
6981659	24470	sort by log_time but into group section?	select logid, groupid, log_output, log_time from table order by groupid, log_time desc 	0.225731768496124
6981973	40144	mysql : group records by datetime ignoring the "seconds"	select  date_format(actiontime,'%y-%m-%d %h:%i:00') as act_time, max(score) as greater from table group by act_time 	0.0011741589449177
6982247	471	tsearch2 word statistics	select * from ts_stat('select ts_vector_col from mytable')  order by nentry desc, ndoc desc, word ; 	0.15439490321338
6982898	18155	sqlite query between two set of elements	select * from stations where lines in  (select distinct [column_name] from a) and  lines in (select distinct [column_name] from b) 	0.00070733433148164
6982964	15780	mysql query to calculate cricket batsman average	select `name`,sum(`runs`) as 'total_runs', sum(`runs`)/sum(if(how_out <> 'not out',1,0)) from `batsman_stats` group by `name` order by 2 desc 	0.0102349863144926
6984341	41059	how can i get the date in "month year" format?	select datename(month, getdate()) + ' ' + datename(year, getdate()) 	0
6986461	22697	how can i use two sede (sql) queries as the inputs for a third query?	select   postid as [post link],   count(case votetypeid when 2 then v.postid end) as 'upvote count',   count(case votetypeid when 3 then v.postid end) as 'downvote count' from votes v inner join posts p on p.id=v.postid where posttypeid = 1   and votetypeid in (2, 3) group by v.postid having count(case votetypeid when 2 then v.postid end) > 150    and count(case votetypeid when 3 then v.postid end) > 10 	0.29360248963319
6987532	39582	possible to join a table on only one row	select    u.firstname, u.lastname, t.* from    #users as u    cross apply    (select top 1 *      from othertable as ot      where u.userid = ot.userid    order by something) t 	0.000247080823326004
6988220	37995	select from nested select t-sql	select count(x.cvs) from (   select    cvs,   (case citycode when 123 then 'test' else 'other' end) as cityname ,   (case productcode when '000' then 'test3' when 'ss' then 'xtr' else 'ddd' end) as cardname   from applications ) x 	0.205843210111306
6988887	14842	request a sql query	select t1.* from table as t1 inner join ( select max(id) as greater from table group by subcatid) as t2 on t1.id = t2.greater 	0.605838163602506
6988973	2666	exporting a mysql database to access?	select * into new_access_table from mysql_linked_table; 	0.333079372367518
6990030	305	using flex to implement a "next" or "prev" button from an sqlite database	selectstmt = new sqlstatement(); selectstmt.sqlconnection = conn; selectstmt.text = "select title, cast(picture as bytearray) as picture from data where id=@index limit 1"; selectstmt.parameters['@index'] = index++; selectstmt.execute(); 	0.0528833167546857
6992396	29671	postgres getting data where two column references same parent id	select      rm.rel_id,     r.rel_desc as relation,     n1.cust_name as cust_name1,     n2.cust_name as cust_name2 from tab_rel_map rm join tab_rel r on r.id = rm.rel_id left join tab_name n1 on n1.name_id = rm.name_id1 left join tab_name n2 on n2.name_id = rm.name_id2 where rm.rel_id = 1; 	0
6992622	39512	grouping result according to one column in sql	select column1, column2,column3, column4   from table1  order by column3 select *   from table1  order by column3 	0.00100017033104021
6992810	1280	mysql comparing intergers	select ... from ... where datefield between x - mynumber and y - mynumber 	0.179932725706033
6994478	18742	always select a row sql	select isnull((     select          case              when count(*) > 10 then 1             else 0         end     from      fldt_querydslam lastday     where accountid = @acc         and lastday.dsl = @dsl     group by lastday.dsl ), -99 ) 	0.0406445013326842
6998357	4249	mysql join to return three rows per type, regardless of how many rows there are	select t.labels, coalesce(d.data, 0)  from data d  left join types t on t.labels = d.labels; 	0
6998469	24740	postgresql nested select	select   p.pid,   g.gid,   p.val from   grid          as g inner join   points        as p     on  p.val < g.max_val     and p.val > g.min_val 	0.718553329094921
7000317	15825	group by statement as a column	select o.[orderid],         o.[productname],         o.[price],         [productid_fk],         p_counts.k  from   order o         inner join (select productid_fk,                            count(product_id) k                     from   products                     group  by productid_fk) p_counts           on o.productid_fk = p_counts.productid_fk 	0.219891988469083
7001259	24780	how to search on levelorder values un sql?	select *     from mytable     where levelorder like '0/8/_%' 	0.108902883251837
7002067	432	mysql - show unrelated results between two tables from table 1	select a.*     from a         left join b             on a.pid = b.pid     where b.pid is null 	0
7002196	25641	sqlite two columns from table joined on same other table	select   ta.name,   tb.name from t1   left join t2 ta on(t1.person1 = ta.id)   left join t2 tb on(t1.person2 = tb.id) 	0
7002707	14734	how to combine two column values into one column value?	select names + char(13) + description from emp 	0
7003221	36405	filtering null values in case statement	select    case when rt.role_type_cd = 'sa' then ap.appl_cd + ' ' + rt.role_type_cd        else rt.role_type_cd        end as dropdownname,      rt.role_type_sid as dropdownid,      rt.actv_ind as active,      'application role' as dropdowncatagory          from cdms_role_type rt     inner join cdms_application ap    on rt.appl_sid = ap.appl_sid  where role_type_cd != 'all role types'    and (rt.role_type_cd = 'sa' or ap.appl_sid = 1) 	0.693234314818315
7003610	3678	t-sql how do you filter by case	select * from address  where state <> 'mi' or (state = 'mi' and streetnum > 1000) 	0.745590616940577
7004302	4678	querying from multiple tables with different columns	select foo,biz,baz from table1 where vid = ? union select foo,biz,baz from table2 where vid = ? 	0.000199831702461694
7005822	30063	php mysql query based off the results of another	select user.*, club.* from user inner join club on user.email = club.created where user.verified 	0.000169449506797788
7009171	11687	sql query: order by in union	select ordnbr, prio    from orders order by   case prio      when 16 then 0      when 6 then 1     else 2 end,     prio desc 	0.719287036938109
7010498	14904	how can i query data from multi tables in a single query, including "like" data based on user login	select m.*, if(l.stream_like_id is not null, 1, 0) as stream_like from stream_master m left join stream_likes l on m.stream_id = l.stream_id and m.user_id = l.user_id 	0
7010744	252	mysql where value dosnt equal	select * from categories left join cat_meta on cat_meta.cat_id = categories.cat_id where cat_meta.meta_key = 'delete' and (cat_meta.meta_value <> 1 or cat_meta.meta_value is null) 	0.103815708539523
7011619	10000	aggregate sql query grouping by month	select year(transactiondate), month(transactiondate), sum(usage) from yourtable where (transactiondate between [some start date] and[some end date]) group by year(transactiondate), month(transactiondate) order by year(created), month(created) 	0.115090962533569
7012028	19439	order without duplicates	select t.ident_nr, t.proj_nr, t.start_time     from yourtable t         inner join (select proj_nr, max(start_time) as maxtime                         from yourtable                         group by proj_nr) q             on t.proj_nr = q.proj_nr                 and t.start_time = q.maxtime     order by t.proj_nr; 	0.212732947876251
7012983	22730	find items whitch has 2 associations (together) using mysql	select * from product left join product_option as po1 on product_option.product_id = product_id left join product_option as po2 on product_option.product_id = product_id where po1.option_id in (1,2,3)  and po2.option_id in (4) group by product.id 	0.00120701043381374
7015427	30824	filling a database with results from another?	select username, rattend, rtotal, 100 * (rattend / rtotal) as raverage from users order by raverage 	0.000720085150685657
7016128	1156	sqlite references keyword	select count(*) from tablename where fr = contactid; 	0.433326909638878
7016419	29956	postgresql: check if schema exists?	select schema_name from information_schema.schemata where schema_name = 'name'; 	0.249363135481056
7016499	20080	how to get percentiles?	select age      , first_name       , last_name       , sum(votes) as votes      , ( select count(distinct age)          from tablex as a          where a.age <= t.age        ) * 100 / distinct_age_count        as age_per      , ( select count(distinct first_name)          from tablex as f          where f.first_name <= t.first_name        ) * 100 / distinct_first_name_count        as first_name_per      , ( select count(distinct last_name)          from tablex as l          where l.last_name <= t.last_name        ) * 100 / distinct_last_name_count        as last_name_per from     tablex as t   cross join     ( select count(distinct age) as distinct_age_count       from tablex     ) as ad   cross join     ( select count(distinct first_name) as distinct_first_name_count       from tablex     ) as fd   cross join     ( select count(distinct last_name) as distinct_last_name_count       from tablex     ) as ld group by age        , first_name        , last_name 	0.0293066950712035
7018628	17376	postgresql sorting mixed alphanumeric data	select * from sort_test order by substring(text from '^(.*?)( \\d+)?$'),          coalesce(substring(text from ' (\\d+)$')::integer, 0); 	0.265203908453591
7019236	38615	sql select 3 random rows non-recurring in the last query	select t.* from table1 t, (     select id from table1 order by id desc limit 5,1 ) as x where t.id <= x.id order by rand() limit 3 	9.04163198673011e-05
7019838	14428	how do you join tables so that right table values depend on two different rows in left table	select  *  from    vals v  join    (select since               , lead(since) over (order by since) as "end"           from intervals) s           on ( v.val >= s.since               and ((v.val >= s."end") is not true)             ) ; 	0.000170471860106747
7020661	34142	mysql: how to convert to eav?	select id as fk_id, 'first_name' as attribute, first_name as value from one union all select id as fk_id, 'last_name', last_name from one order by fk_id, attribute 	0.198943228428651
7021281	13747	combining the results of two tables in one query	select id, category, name, dosage from medicationcombination cross join medication where medicationid = 2 	0.000324029888776845
7021723	39613	how to group records based on condition in mysql (group_by)	select   users.id,users.name, users.`value`, users.`updated_at` from   users inner join (  select name, max(updated_at) as `updated_at`  from   users  group by   name ) max_users on   users.name = max_users.name and   users.updated_at = max_users.updated_at 	0.00123403432512485
7021812	33030	between query [postgresql & php]	select * from ranks inner join (select unnest(array[224, 338, 800]) as n) tt     on n between rank_min and rank_max; 	0.279249855607569
7022075	11883	how to order by max(a,b) in sql?	select * from table order by greatest(a, b) desc 	0.465762057061565
7022077	26269	sql query where date between two times	select id, date  from mytable  where convert(varchar(8),date,108) between '09:00:00' and '11:00:00' 	0.00437890973490495
7022461	17033	mysql database primary key usage	select   class.class_id,   student.name as `student_name`,   faculty.name as `faculty_name`,   subject.name as `subject_name` from   class inner join   student on   student.student_id = class.student_id inner join   faculty on   faculty.faculty_id = class.faculty_id inner join   subject on   subject.subject_id = class.subject_id where   class.faculty_id = ? and   class.subject_id = ? 	0.0798666388405546
7023096	2449	i would like to use the result of a query in another query using php and mysql	select moves.idtechnic, moves.move  from moves inner join technic         on technic.idtechnic=moves.idtechnic where technic.idname='$technic'    and technic.setname='$set'    and technic.number='$number' order by moves.idmoves 	0.454444479861368
7023776	15862	how to fetch count of every classid from db table in mysql see below for detail	select classid, count(*) from table1 group by classid; 	0
7024778	24875	sql add comma seperators on an integer value	select format(sum(invoiceamount),2) from fact_salescount where year in ({year}) and month >= ({frommonth}) and month <= ({tomonth}) 	0.00240021054089483
7024854	35964	mysql custom order by and alphabetical order by:	select * from `$table[$a]`  order by    field(typeof,'pdf','swf','img','web'),    filename   	0.46280483885834
7025030	33778	php/mysql: in a voting system, how can i keep a user from seeing a profile he has already voted on?	select userid from users where userid not in (select touser from votes where fromuser = 'theuseridthatisvotingnow') order by rand() limit 1 	5.70892997358878e-05
7025420	40023	how to fetch the last inserted (datetime) records for each category in database table	select * from (   select row_number() over (partition by category order by creation_date desc) rn, *   from table   where condition1 ) t where t.rn = 1 	0
7026325	26003	mysql select of everything before @	select substring_index('somebody@somewhere.com', '@', 1); 	0.123975244415634
7026499	6169	numbering rows in a view	select top(5000) bcode, sapcode, 1 as groupno from dbo.db  union select top (10000) bcode, sapcode, 2 as groupno from dbo.db p  where id not in (select top(5000) id from dbo.db) 	0.0163996541169639
7027450	9028	how to do a like considering two columns?	select concat(first_name, ' ', last_name) as 'full_name'  from customer where concat(first_name, ' ', last_name) like 'john d%' 	0.00570632836103382
7029747	8901	sql query to get count of rows with more than one row in another table	select count(*) from (     select count(*) as c     from resources as r          inner join resourcefields as rf              on rf.resid = r.resid                  and rf.name = 'contactname'      where r.type = 1      group by rf.resid      having count(rf.value) > 1; ) s 	0
7029802	32377	count fields with a where clause in sql	select * from  (select messages.id as id,        messages.user_id,        messages.category_id,        messages.parent_id,        messages.message,        messages.create_date,        messages.update_date,        messages.status,        users.name as username,        users.id as userid,        users.email as useremail,        users.phone as userphone,        users.active as useractive,        users.role as userroel,        users.date as register_date,        (select count(*) from afo_messages where parent_id=messages.id) as `sub messages` from `afo_messages` as messages  inner join `key_users` as users on messages.user_id = users.id where messages.category_id=5 and messages.parent_id=0 order by messages.id desc limit 30) ilv  order by id asc 	0.547892906029902
7032596	21939	mysql table join with aggregates	select p.person_id, p.name, p.email, a.activity_id, a.activity_date, a.activity_name from person p left join activity a on p.person_id = a.person_id where a.activity_date = (select max(a1.activity_date)                from activity a1                where a.person_id = a1.person_id                group by person_id) or activity_date is null; 	0.711217689257041
7033789	32571	mysql - how to get non aggregate columns from a table based on an aggregate column	select al.id, al.activity, al.activity_id from activty_log join (select max(aa.activity_id) as ma from activity_log aa group by aa.id) as al2  on al2.ma = al2.activity_id; 	0
7033797	17031	how to eliminate repeating case or decode statement multiple times in select?	select  a, if (c = b then c else 0), if (d != b then d else 2), if (e = b then e else 5) from (select a, decode(b, "foo1", "bar1", "foo2", "bar2") b, c, d, e from x); 	0.65103179617557
7036946	36801	joining this query with sub query into one query	select ... from `posts` join `groups` on (`groups`.`id` = `posts`.`group_id`) join `users` on (`users`.`id` = `posts`.`user_id`) join `group_members` on (`groups`.`id` = `group_members`.`group_id`) where `group_members`.`user_id` = '33' and `posts`.`post_id` = 0 	0.748439751081777
7037182	21398	check if a value exists in a column in mysql table	select * from accountinfo where username = 'something' 	0.000695333785924129
7037336	32968	applying conditions to different sort than final one	select * from   ( select ...     from tablex     where created_at > @checkdate      order by created_at asc, id asc     limit 5   ) as tmp order by created_at desc, id desc 	0.00274650073329188
7038123	35671	how do i change the database values using php and mysql?	select concat(usrfirstname,'',usrsurname) as fullname,         usrnickname as nickname,         usremail as emailaddress,         case when usrgender = 0          then                   'm'                else                   'f'             end as gender,        date_format(usrdob,'%d%m%y') as dob,usrbelt as beltid       from user 	0.0156262825866592
7040282	5467	how to extract info from database to excel	select t1.sku sku, concat(t1.serialno, "  ", t1.grade) serialgrade from yourtable t1     join temptable t2 on t2.serialno = t1.serialno     orderby t1.serialno asc 	0.000659936935837357
7040918	31237	order by and top on grouped rows	select productid,        avg(price) as avgprice from ( select productid,               price,               row_number() over(partition by productid order by [date] desc) as rn        from orderproduct      ) as o where rn <= 20 group by productid 	0.000726266995819373
7041374	20618	mysql: select from all tables in a db	select content from img union all select content from flash union all select content from pdf 	0.00073444917689844
7042239	35874	sql: remove multiple row null values, concathenate into one row	select max(merge_table_parcel_1.txtfrequency1) as frequency1,        max(merge_table_parcel_1.sum_inst_n) as sum_inst_n1,        max(merge_table_parcel_1.sum_inst_d) as sum_inst_d1,        max(merge_table_parcel_1.sum_ctrn_d) as sum_ctrn_d1,        max(merge_table_parcel_1.sum_ctrn_n) as sum_ctrn_n1,        max(merge_table_parcel_1.sum_tran_n) as sum_tran_n1,        max(merge_table_parcel_1.sum_ppu) as sum_ppu1,        max(merge_table_parcel_1.sum_ppujobs) as sum_ppujobs1,        max(merge_table_parcel_1.sum_dayt) as sum_dayt1,        max(merge_table_parcel_1.sum_resd_d) as sum_resd_d1,        max(merge_table_parcel_1.sum_resd_n) as sum_resd_n1,        max(merge_table_parcel_1.sum_on_strn_d) as sum_on_strn_d1,        max(merge_table_parcel_1.sum_on_strn_n) as sum_on_strn_n1   from merge_table_parcel_1 	0
7043464	21438	mysql single query to populate alphabetical glossary	select left(name, 1) as namethatstartswith, count(*) as numofresults from your_table group by left(name, 1) 	0.107903115507342
7043939	2419	using php and calling values from mysql i am trying to call every 16 rows that contain the metal gold	select * from (      select          @row := @row +1 as rownum, time,metal     from (          select @row :=0) r, metal_price      where metal = 'gold' ) ranked  where rownum % 16 = 1 	0.00863299105384132
7044897	40018	how can i compare 2 columns in 2 tables to check for unequal values	select * from table1 as t1 left join table2 as t2 on t1.columna = t2.columnb where t2.t2id is null 	0
7044973	28053	how to filter nested query in t-sql	select g.gameuid, g.gamename, p.playeruid, p.playername from game g inner join (     select gameuid, min(finishedposition) as finishedposition     from gameplayer gp     group by gp.gameuid) as v on v.gameuid = g.gameuid inner join gameplayer gp2 on (gp2.finishedposition = v.finishedposition and gp2.gameuid = v.gameuid) inner join player p on (p.playeruid = gp2.playeruid) 	0.783930526846847
7045803	35305	postgres view showing todays orders	select * from table where date("created_date") = current_date(); 	0.00451272039541304
7046195	3175	oracle sql: add sum from another table to query results	select a.id, sum(b.price) totalprice from (  select *         from table1         where something) a left join table2 b on a.id = b.table1_id group by a.id 	0.000956349087820663
7048119	41194	mysql - relational databases and tagging	select * from posts where exists (select * from tags where tags.postid = posts.id and tags.tag = 'x') and not exists (select * from tags where tags.postid = posts.id and tags.tag = 'y') 	0.710636485172984
7049153	30559	count the number of rows in mysql?	select list_of_fields,@rn:=@rn+1 as row_num from table,(select @rn:=0) as r order by id 	0.000236832543412554
7050026	14017	mysql: getting columns by value priorities	selectr tblkeys.idkey, ifnull(de.translation, en.translation) from tblkeys left join  (select idkey, translation from tbltranslations where tbltranslations.dtlanguage = 'de') de  on de.idkey = tblkeys.idkey left join (select idkey, translation from tbltranslations where tbltranslations.dtlanguage = 'en') en on en.idkey = tblkeys.idkey 	0.00296185635749625
7052478	13595	order mysql-query alphabetically, a string is given for a number?	select * from table, sources where table.source = sources.id order by sources.name 	0.0015806484101917
7053052	30778	randomly (with weight bias) select row from database?	select * from table order by entries*rand() desc limit 1; 	0.000126205721059302
7053317	19744	mysql query - select a unique column comparing other column	select property_id from table where location_type in (1,2) group by property_id having count(distinct(location_type)) = 2 	0.000178075155134353
7053902	36938	sql: how to get the count of each distinct value in a column?	select   category,   count(*) as `num` from   posts group by   category 	0
7054839	20887	how can order the result , mysql	select *  from posts order by usercomments + visitorcomments desc 	0.110307442098054
7055698	27773	how to create correct sql query to get data from 2 tables	select p.* from posts p join posts_tags pt on pt.p_id = p.p_id join tags t on t.t_id = pt.t_id where t.t_name = 't1'; 	0.000527238004705887
7056418	17269	mysql online members in past 30 days	select  count(*) as users  from table  where from_unixtime(lastonline) >= now() - interval 30 day 	7.19678743042098e-05
7057772	15461	get row position in mysql query	select id, name, rank from      (     select t.id, t.name,         @rownum := @rownum + 1 as rank     from table t, (select @rownum := 0) r     order by name asc     ) `selection` where id=1 	0.00442717412466631
7058288	8574	how to select only the first line from an raw in mysql	select  substring(field_name,1,180) as begin_text, other_fields_list  from articol where id = '$artid' 	6.43741447469661e-05
7058603	38212	mysql left join multiple tables twice	select m.title_slug, m.title, m.release_date,        c.celeb_slug, c.celeb_name,         r.role_name,        s.char_name from b_movies m inner join b_starcast s on m.id = s.movie_id inner join b_mov_rol_celeb mrc on m.id = mrc.movie_id left join bb_celebs c on mrc.celeb_id = c.celeb_id or s.celeb_id = c.celeb_id  left join bb_roles r on mrc.role_id = r.role_id  where m.id = '14'; 	0.514542706013142
7060202	17803	mysql query to fetch most recent record	select   record.recordtype_id,   record.record_value from   record inner join   (   select     recordtype_id,     max(record_timestamp) as `record_timestamp`   from     record   group by     recordtype_id   ) max_values on   max_values.recordtype_id = record.recordtype_id  and    max_values.record_timestamp = record.record_timestamp inner join   user_recordtype on   userrecordtype.recordtype_id = recordtype.recordtype_id where   user_recordtype.user_id = ? 	0
7061166	31893	sql: calculate percentage in other table, and user percentage to filter?	select      u.username,      (         (select count(*) from posts where user=u.username and category=3)          / (select count(*) from posts where user=u.username)          * 100     ) as percentage  from users u  having percentage > 10 	0
7061569	26094	order the categorys after most threads	select     c.name,     count(*) as cnt from     cats c     left join threads t         on  c.idcats = t.category group by     c.name order by     cnt desc 	0.0122969783575059
7062038	40794	how to set a update warning for update too many rows	select count(*) from tbl where... 	0.272919907188971
7062653	37421	select rows where particular records are removed based on another table	select b.* from tableb b left join tablea a on b.cell2=a.cell1 and b.time2=a.time1 where a.cell1 is null 	0
7062708	30021	query in sql to get the months b/w the dates	select datediff ("m", [id date of issue], [date of travel]) from ... 	0.000171463901795205
7063339	30387	filtering table dynamically using the user details entered	select * from   user where  organisation in (select organisation                          from   user                          where  emailid = loggedon_emailid) 	0.00593578667710659
7066879	27939	mysql query - latest month/year	select month, year from posts where postid = 25 order by year desc, month desc limit 1 	0.0145759596189687
7066917	9548	limit number of occurances in output group-by sql query	select      rep, companyname, [count], commission from (     select          rep, companyname,count(companyname) as [count], commission,         count(1) over (partition by companyname) as [companycount]     from customers     group by repid,companyname,commission ) sub where companycount > 1 	0.0759606082666022
7067089	25624	using an sql statement select next 4 items	select  id, foo, bar from     (select  row_number() over (order by id asc) as row,           id, foo, bar from    sometable) tmp where   row >= @rowrangestart and row <= @rowrangeend 	0.0111594162019714
7068731	23748	mysql "non unique id"	select .... from mytable     join    (             select min( primarykeycolumn ) as pk                 , specialid             from mytable             group by specialid             ) as specialidvalues         on specialidvalues.pk = mytable.primarykeycolumn 	0.0028315297334959
7071447	7180	mysql group by return the first item - need to select the last item	select t1.* from tblusersprofile as t1 inner join ( select user_id,max(activity_ts) as rct from tblusersprofile group by user_id) as t2 on t1.user_id = t2.user_id and t1.activity_ts = t2.rct 	0
7073447	21661	difference when using rownum	select * from employees     where rownum > 1; 	0.217008619416508
7074513	30126	number of row that repeated	select   id,   name,   count(*) from   table group by   id, name 	0.000269757461430821
7075483	36322	is there a way to get a list of all current temporary tables in sql server?	select * from tempdb.sys.objects 	0
7075664	26621	how to add count of different query using a query in mysql5?	select ((select count(id) from employee where..) + (select count(id) from emplyer where..) + (select count(id) from users where..)) 	0.00960188371364474
7076766	27913	select rows having 2 columns equal value	select ta.c1       ,ta.c2       ,ta.c3       ,ta.c4 from [tablea] ta where (select count(*)        from [tablea] ta2        where ta.c2=ta2.c2        and ta.c3=ta2.c3        and ta.c4=ta2.c4)>1 	6.30596725580887e-05
7077545	18251	mysql - how to join two queries to omit elements found in the second query (or perhaps any better solution?)	select * from wp_posts, wp_postmeta where wp_posts.id = wp_postmeta.post_id and ((wp_postmeta.meta_key = 'start date' and wp_postmeta.meta_value > now()) or (wp_postmeta.meta_key = 'ongoing' and wp_postmeta.meta_value != 'yes')) 	0.0725426823512312
7078062	19977	creating summary report with selected summary	select     customertype,     count(*),     sum(case when status = 'c' then 1 else 0 end),     sum(case when status = 'a' then 1 else 0 end),     sum(amount) from     customers group by     customertype order by     customertype 	0.28792529226216
7080770	11203	check whether date is 12 hours before in php	select ... from yourtable where `date` <= date_sub(now(), interval 12 hour) 	6.74536816839702e-05
7080912	2165	t-sql - return right-most non-zero column	select    gl,    coalesce( nullif(q4,0), nullif(q3,0), nullif(q2,0), nullif(q1,0) ) as amount from    mytable 	0.0641326025629417
7081908	27507	how to get first login per day of users in a date range	select userid, min(login_date) as first_login_date from login where login_date between inputstartdate and inputenddate group by userid, year(login_date), month(login_date), day(login_date) 	0
7082218	5721	oracle appending string to a select statement	select column1, 'abc' || lic_num from table_one 	0.320714112530215
7082721	12028	counting rows in one table to check if they match value in another table	select t.company_id, t.ind_company_name, t.tickets attendee_tables_tickets, a.tickets attendees_tickets from attendee_tables t  left join (select company_id, count(*) tickets from attendees group by company_id) a       on t.company_id = a.company_id   where t.tickets <> isnull(a.tickets,0) or a.company_id is null 	0
7082871	40394	sql group by with a condition	select derived.*,        case when exists           (select top 1 1 from table_name as t2 where t2.username = derived.username and t2.directory=derived.directory and t2.access = 'allow') then 1 else 0 end as is_allowed,        case when exists           (select top 1 1 from table_name as t2 where t2.username = derived.username and t2.directory=derived.directory and t2.access = 'deny') then 1 else 0 end as is_denied, from (  select distinct t.username, t.firstname, t.lastname, t.directory   from table_name as t ) as derived 	0.449268009496024
7083568	5795	php sql server concat	select * from <tables> where (website like '%".$term."%' or (firstname +' '+ lastname) like '%".$term."%'; 	0.682498681690066
7084511	708	how to get same results without using distinct in query	select l.name, r.name from (select distinct id, name from a) as l inner join (select distinct id, name from b) as r on l.id = r.id 	0.00206658576956946
7087867	6073	how to order results by customer expression in hibernate/hql/jpql	select o    from cat o   order by case o.name when 'tom' then 0 else 1 end 	0.107779512004042
7088936	12557	sql (query) checking for duplicate record on duplicate columns	select field1, field2, field3, field4, count(*) from mytable group by 1,2,3,4 having count(*) > 1; 	0.000123535589778996
7089526	12740	mysql between query	select * from mytable where startdate > '5/30/2011' and  startdate < '6/30/2011' 	0.220276168887517
7089739	10015	ambiguous column error when joining 2 tables which have the same column name	select tb.id from a ta join b tb on ta.id = tb.fid order by ta.name; 	0.000432673355956549
7089777	21649	how to select top record of same group?	select t1.* from table as t1 inner join (     select min(id) as minid     from table     group by groupno) as t2 on t1.id = t2.minid 	7.32167081051924e-05
7090062	28974	sql query for specific data	select [user], min(logdatetime) as firstlogin from [archive table] group by [user] 	0.0793607139673809
7090713	27752	mysql select record if value exists in another record	select     * from     users where     concat(user_id, ":", scheme_id)         in             (                 select                     concat(user_id, ":", max(scheme_id))                 from                     users                 group by                     user_id             ) 	0
7091018	31647	mysql group by x characters on an id field	select * from tbl_item where substr(tbl_item.`product group code`, 1, 6) like ':shopprodid%' 	0.00091344864073002
7091822	5624	sql server: how to calculate median (group by)?	select    dst,    avg(sp) from (    select       dst,       cast(sp as decimal(5,2)) sp,       row_number() over (          partition by dst           order by sp asc, id asc) as rowasc,       row_number() over (          partition by dst           order by sp desc, id desc) as rowdesc    from dbo.cars soh ) x where     rowasc in (rowdesc, rowdesc - 1, rowdesc + 1) group by dst order by dst; 	0.0353019393175568
7092696	6718	doing a search for words out of order	select ... where title like '%finn%' and title '%huckleberry%' and title '%next%' implode(' and ',array_map(function($x){     return '`title` like "%'.$x.'%"'; },explode(' ',$str))); 	0.158757198121678
7092934	40219	mysql query - multiple where clause on 1 column	select     products.*, from products inner join  product_categories on product_category_pid = product_id inner join  categories on product_category_cid = category_id inner join  manufacturers on product_manufacturer = manufacturer_id inner join  product_specifications on product_specification_pid=product_id where product_active = 1   group by product_id having count(case when product_specification_sid in (3) then 1 end) > 0  and count(case when product_specification_sid in (8,9,6,7,10,11) then 1 end) > 0 	0.317110331747275
7094664	8711	how to find out what table's primary keys are using a select query	select cc.column_name from user_cons_columns cc join user_constraints c on c.constraint_name = cc.constraint_name where c.table_name = 'mytable' and c.constraint_type = 'p' order by cc.position 	0.00154008235830131
7094857	18505	problem with date field after migration from mysql to oracle	select to_char(created, 'dd-mon-yyyy hh24:mi:ss')   from jiraissue; 	0.101888554397844
7095573	37506	mysql select problem	select customerid from customers_location where customerid in(select distinct customerid from customers_location where locationname = 'sheffield') 	0.754494815618043
7098202	8434	mysql get all results but first	select distinct `memberid`  from `discuscomments`  where `topicid` = 4  order by `id`  desc limit 1,x 	0.000198065227241084
7098231	21666	finding a dll sql assembly with only the database in sql server	select      assembly = a.name,      path     = f.name from sys.assemblies as a inner join sys.assembly_files as f on a.assembly_id = f.assembly_id where a.is_user_defined = 1; 	0.0614188341136386
7098421	11370	get all members who haven't logged in, in past 30 days	select * from members where logged_in < unix_timestamp()-2592000 	0
7098437	31101	maximum sum in sql	select lastname, sum(a.netpaidamount) as totalpaid, (max)code1, ... group by lastname 	0.0171478724201933
7099070	21566	mysql: group by clause	select m.*, u.*   from users_medals u   left join medals m on u.medal_id = m.medal_id   where u.user_id in (1)   and u.earnedtime = (     select max(users_medals.earnedtime) from users_medals     left join medals on users_medals.medal_id = medals.medal_id     where users_medals.user_id = u.user_id     and medals.medal_type = m.medal_type   ) 	0.750503952031481
7100010	24800	mysql rank in the case of ties	select t1.name, (select count(*) from table_1 t2 where t2.score > t1.score) +1 as rnk from table_1 t1 	0.213230804499034
7100508	25613	sql group by value within substring of char(255) field	select   substring_index(substring_index(str,'/',4),'/',-1) as val,  count(*)  as `count`  from table  group by val 	0.00900607868687358
7101299	34892	can several join clauses in a mysql query exponentiate number of rows it has to check?	select count(*) as `total_num_resource_rows`  from `admin_site_resources` as `a`  where `a`.`post_status`='approved' and    ( `a`.`resource_name` like '%alpha%'   or `a`.`aliases` like '%alpha%'    or `a`.`short_desc` like '%alpha%'    or `a`.`resource_url` like '%alpha%'    or `a`.`other_resource_type` like '%alpha%'    or exists ( select *                from `admin_site_organization_resource` as `b`                  join `admin_site_organizations` as `c`                   on `b`.`org_id`=`c`.`id`               where `b`.`res_id`=`a`.`id`                 and `c`.`org_name` like '%alpha%'              )   or exists (               ...             )   or exists (               ...             )   ...     ) 	0.000660373975380478
7103809	30090	select with different conditions on multiple different fields of a single table	select   plan1.planname,   plan2.planname,   plan3.planname  from project    left join plan plan1 on project.id=plan1.projectid and plan1.period=1    left join plan plan2 on project.id=plan2.projectid and plan2.period=2    left join plan plan3 on project.id=plan3.projectid and plan3.period=3 	0
7104178	37727	mapkit: coordinates from sqlite database	select * from atms where lat > 51.4 and lat < 51.6 and lng > -0.165 and lng < -0.175 	0.332370254170826
7104790	2250	mssql stored procedure: compare parameter with column if isnumeric	select id, name from managers where [id] = case                when isnumeric(@search) = 1 and @search not like '%.%' then cast(@search as int)                else -1              end or contains([name], @search) 	0.675231084456008
7104833	4442	how to select every (1918/1000)th record from sql?	select    @rownum := @rownum + 1 as rownum,   data.*,   if( floor( @rownum % (1918.0/1000.0) ) = 0, '1', '2') as grp 	0.000305883964538298
7108284	13076	selecting a count into a variable in oracle	select count(*) into leadscount from leads_deleted 	0.00775736130939867
7108701	13343	sql server 2005 using count and distinct together	select sourcecode, count(*)  from [secureorders]  where datetime >= dateadd(day, datediff(day, 0, getdate()), 0)    and datetime < dateadd(day, datediff(day, 0, getdate()), 1)  group by sourcecode 	0.460124791624236
7109602	7940	query to return data from sql server table based on date criteria	select * rows where datevalue >= date1 and datevalue < date2 + 1 	0
7110451	10282	sql request : how to make a particular select with multi tables and calcul?	select t.teamname,   count(*) as teammembers,   c.membersname as teamcaptain from team t   inner join teammembers tm on tm.teamid = t.teamid   left join members m on m.membersid = tm.membersid   left join teammembers tmc on tmc.teamid = t.teamid and tmc.memberstatusid = "captain"   left join members c on c.membersid = tmc.membersid   group by t.teamname, c.membersname 	0.0858224628743915
7111220	30310	joining two separate columns while using count()	select leads.id, count(in_click_id)  from leads  inner join in_click on leads.in_click_id = in_clicks.id where create_date like '%2011-08-17%' group by leads.id order by count(in_click_id) desc 	0.000854735149829596
7111728	32383	comparing binary values in mysql	select bit_count( conv( '001011', 2, 10 ) ^ conv( '001111', 2, 10 ) ) 	0.0155090800157575
7112247	1438	find out a row number for a specific row, after ordering by a sum	select * from #ranktable where userid = 41 	0
7112849	39085	querying two tables with columns named the same	select isnull(c.date, d.date) date, isnull(c.name, d.name) name, sum(c.credit) credit, sum(d.debit) debit from table_1 c full join table2 d on d.date=c.date and d.name=c.name where isnull(c.date, d.date) between @date1 and @date2 group by c.date, d.date, c.name, d.name 	7.16820818581487e-05
7113174	10256	sql max and sum	select x.county, x.code x.totalpaid     ,rank() over      (partition by x.county order by x.totalpaid desc) as 'rank' from (select     county,    code,    sum(paidamount) as totalpaid from    counties group by    county,    code) x where rank = 1 	0.117843413441274
7114164	21508	cannot open database "test" requested by the login. the login failed	select      dp.name,      sp.name  from     sys.database_principals as dp full outer join     sys.server_principals as sp     on dp.[sid] = sp.[sid] where      dp.name = 'testuser'; 	0.183380229905119
7114296	19788	comparing two int values in tsql	select case when cmh.level > cons.level  then cmh.level else cons.level end from cmh inner join cons on cmh.[user] = cons.[user] where cons.[user] = 'blah' 	0.0070267476844396
7115570	24428	select only matching records from two tables	select * from class1 c1 join class2 c2 on c1.groupname = c2.groupname         and c1.subgroup = c2.subgroup where     (     select count(distinct ind)     from class2 c2a     where c2a.groupname = c1.groupname         and c2a.subgroup = c2a.subgroup     ) = 2   and     (     select count(distinct subgroup)     from class1 c1b     where c1b.groupname = c1.groupname     ) =     (     select count(distinct subgroup)     from class2 c2b     where c2b.groupname = c2.groupname     ) 	0
7116415	33547	optimal sql statement or algorithm for finding most popular category of items in a database	select count(*) as popularity from categories, views where views.category_id = categories.id group by views.category_id order by popularity desc 	4.68701854051885e-05
7116568	11146	performing math operation on temporary column in sql	select   t.t_id,   t.occurrences,   t.value / tm.occurrences as newvalue from table t   inner join (     select       tm_id,       count(*) as occurrences     from table_map     group by tm_id     having count(*) > 1   ) tm on t.t_id = tm.tm_id 	0.704346365486377
7116812	7888	select a subset of records from table a that match two columns in table b	select users.* from users inner join activejobs dep on users.department = dep.department and users.jobtitle = dep.jobtitle 	0
7117479	29272	microsoft access: how to sort text column by length of its text string?	select stringcolumn, len(stringcolumn) as length from yourtable order by len(stringcolumn) desc 	0.0107431036193614
7117722	40355	sql - sorting table with parent child relation	select id, parent_id, level from the_table  start with parent_id is null  connect by prior id = parent_id; 	0.00853476010874627
7118270	31518	need find the number of days by taking date differnce in sqlite android	select (julianday(date('now')) - julianday(confirmationdate)) from [table] 	6.80016745528137e-05
7120085	3371	mysql join based on sortorder field	select b.id, b.user_id, b.sortorder, b.title from books b join (     select b2.user_id, min(b2.sortorder) sortorder     from books b2     group by b2.user_id ) first_books using (user_id, sortorder); 	0.00561634294758261
7121221	7472	filtering in oracle based on a group of values contained in a list of values	select      id_person   , name from      person as p where exists         ( select *           from               personspecialization as ps           where ps.id_person = p.id_person             and ps.id_specialization = 5         )   and exists         ( select *           from               personspecialization as ps           where ps.id_person = p.id_person             and ps.id_specialization = 6         ) 	0
7122794	11273	select based on matching columns	select one.* from tableone as one   inner join tabletwo as two     on one.companyid = two.companyid and        one.someyear = two.someyear 	9.148283252821e-05
7124266	7765	sql server fulltext - getting keyterms out given a row and column	select * from sys.dm_fts_index_keywords_by_document (db_id('cardatabase'),object_id('cars')) where document_id = 2039468 	0.00671157710315357
7125200	25516	mysql query for unique user and minimum score value	select username, min(score) as mn from scores group by username order by mn 	0.000215128485559386
7125668	13498	sql query with a case when returning more than one row	select     sq.display_value from     surv_action_type_list satl inner join     (     select         'trigger severity' action_type,         cast(severity as varchar2(255)) display_value     from         surv_trigger_severity_list     union all     select         'host group' action_type,         cast(name as varchar2(255) display_value     from         surv_list.groups     union all     select         'host' action_type,         cast(name as varchar2(255) display_value     from         tn_tree     ) sq on     sq.action_type = satl.action_type where     satl.id = 0 	0.210656805287753
7125852	29794	php, mysql, how to compare two strings?	select t1.id, t1.word1, t2.price   from database1.table1 t1    join database2.table2 t2      on t1.word1 = t2.word2; 	0.00414400342070931
7126088	33743	mysql - select a random row from one table and join it to three rows in another	select userid, points from tbl_ranking where type = '1' and game = (select name      from tbl_game      where active = '1'      order by rand( )      limit 1      ) order by points desc limit 3 	0
7126989	19845	which is the most memory intensive sql query: select, update or insert?	select * from table 	0.202702880450058
7127708	35494	mysql query for all records not today	select * from your_table where date(timestamp_field) <> date(now()) 	0.00236573381708173
7128959	1710	sql: how to select a count of multiple records from one table, based on records in a different table?	select message, count(commentid)  from tablea left join tableb on tablea.messageid = tableb.messageid  group by message 	0
7129538	17857	trying to count number professors in dept order by desc	select p.pid from department d, professor p where d.did = p.did order by count(pid); 	0.0212538224619966
7129558	20426	mysql grouping problem	select     g.id, g.date,     t.name,     sum(s.kicks),     sum(s.goals),      sum(s.tackles) from stats s left join player_team_game ptg on ptg.id = s.player_team_game_id left join game g on g.id = ptg.game_id left join team t on t.id = ptg.team_id group by ptg.team_id order by g.id, t.id 	0.778352263646342
7132303	20358	select * distinct one column	select distinct pid,field1,field2 from tmp where city='test' 	0.0041673065447397
7133574	955	top n per group sql problem in mysql	select cat_id, prod, pos from (     select cat_id, pos, prod, if(@last_id = cat_id, @cnt := @cnt + 1, (@cnt := 0 || @last_id := cat_id)) cnt     from (         select p.cat_id, pseq.cnt pos, pseq.prod         from (             select prod, count(*) cnt from prods group by prod order by cnt desc         ) pseq         inner join prods p on p.prod = pseq.prod         order by cat_id, pseq.cnt desc     ) po ) plist where cnt <= 3; based on the above data, this will return: + | cat_id | prod      | pos | + |      1 | spl php   |   2 | |      1 |  kntrn    |   1 | |      1 | kntrn e   |   1 | |      2 | spl php   |   2 | |      2 |  zlv      |   1 | |      2 | zlv enter |   1 | + 	0.00937988154956926
7133994	3952	how to select rows which are today events?	select distinct n.number from phonebooks p inner join  numbers n on n.book_id = p.book_id inner join extradatas ed on ed.book_id = n.book_id inner join extrafields ef on ef.field_id = ed.field_id and ef.title = 'birthday' where p.book_id = :book_id     and p.username = :username     and ed.value between unix_timestamp(date(now()))         and unix_timestamp(date(now()) + interval 1 day); 	0
7135515	1629	union select with multiple distinct criteria where there is no real fk	select up.time, qm.value as title, u.username, u.id as id_user, q.id as id_quest, qm.key as tit from participation p inner join quests q  on p.id_quest = q.id inner join user u on p.id_user = u.id inner join quest_meta qm on q.id = qm.id_quest where p.time > '2011-08-19 00:00:00' and qm.key = 'quest_title' and qm.id_meta = -1 group by p.id_user union select a.time, a.type, a.title, a.username, a.id_user, a.id_quest, a.tit from ( select p.time, qm.value as title, u.username, u.id as id_user, q.id as id_quest, qm.tit from participation p inner join quests q  on p.id_quest = uq.id inner join users u on p.id_user = u.id inner join quests_meta qm on q.id = qm.id_quest where p.time > '2011-08-19 00:00:00' and q.id = 2 and p.vote = '1' and p.id_quest_meta = -7 ) as a where a.tit = 'quest_title' group by id_user  order by time desc; 	0.234251347338446
7136050	20154	mysql counting number of duplicate data in a table	select count(*) from table group by score having count(score) > 1 	0
7137793	40639	get recent threads that the user did not join in to	select t.*, jt.* from thread t  left join joined_threads jt on jt.thread_id = t.unique_id and jt.saved_by = '$user_id'  where t.owner <> '$user_id' and jt.thread_id is null group by t.unique_id 	0.00021115103753468
7139817	24129	join query, on same key	select t2a.name as one_name, t2b.name as two_name, ... from table1 as t1 join table2 as t2a (on t2a.id = t1.one_id)                   join table2 as t2b (on t2b.id = t1.two_id) 	0.0292778402844413
7140083	31057	mysql sum() returning top 10 values	select pubs.*, services.*, sum(temp.total) as final_total from pubs inner join services on pubs.shop_id=services.shop_id inner join ( select  sum(comfort + service + ambience + friendliness + spacious + experience + toilets)/(7) /count(shop_id) as total, shop_id from ratings group by shop_id ) as temp on pubs.shop_id=temp.shop_id group by shop_name order by final_total desc, shop_name asc 	0.00130447878889618
7140193	13351	oracle sql - repeating same column value within a group	select smalldate, mip_step_description      , error_code_en      , max("input") over (partition by smalldate, mip_step_description) "input"      , "defects"   from (select data.smalldate, mip.mip_step_description, error_code.error_code_en              , count(case when (error_code is null and quality_plan is null)                           then data.part_serial_number end) as "input"              , count(case when error_code is not null                            then data.part_serial_number end) as "defects"              , count(data.part_serial_number) sn_ct           from data left join mip on data.equipment = mip.equipment                     left join error_code on data.error_code = error_code.error_code_sn           group by data.smalldate, mip.mip_step_description, error_code.error_code_en) order by smalldate, mip_step_description, sn_ct desc; 	0.00100206138142523
7140670	15843	sql join problem joining same table	select g.subgroup as subgroup,      mg1.maingroup as g1,      mg2.maingroup as g2,      mg3.maingroup as g3 from (select distinct subgroup from groups) g left join groups mg1 on mg1.maingroup = 1 and mg1.subgroup = g.subgroup left join groups mg2 on mg2.maingroup = 2 and mg2.subgroup = g.subgroup left join groups mg3 on mg3.maingroup = 3 and mg3.subgroup = g.subgroup where g.subgroup in ('a','b','c'); 	0.197319938048718
7140673	14013	boolean variable always returning false	select invoice from m_invoiceinfotablewhere invoice=:invoice 	0.753777263393159
7145485	23989	tsql: values of all field in a row into one string	select t2.n.value('local-name(.)', 'nvarchar(128)')+': '+        t2.n.value('.', 'nvarchar(max)') from (select *       from yourtable       for xml path(''), type) as t1(x)   cross apply t1.x.nodes('/*') as t2(n) 	0
7146557	2973	how to get date difference between two dates in same year with one date is from an input date not from the year	select   daydiff = datediff(     day,     dateadd(year, case when lastocc > getdate() then -1 else 0 end, lastocc),     getdate()   ) from (   select lastocc = dateadd(year, year(getdate()) - year(@inputdate), @inputdate) ) s 	0
7147571	27208	mysql select having multiple n to n's	select     r.id, r.recipe, r.directions from       ingredients_tbl i            inner join recipe_to_ingredient ri on i.id = ri.id_ingredient             inner join recipes_tbl r on r.id = r.id_recipe   where      i.id in (1 ,2) group by   r.id, r.recipe, r.directions having     count(*) > 1 	0.0307837806189079
7149463	9113	how to show how many people wants a product in mysql?	select count(user_id) from reverse_relations group by product_id where product_id = $dealid 	0.00127070711193843
7150088	5654	multiple inner joins with multiple tables	select table4.company, table1.id, table1.value from table1     inner join table1         on table2.table1_id = table1.id     inner join table3         on table3.table2_id = table2.id     inner join table4         on table4.table3_id = table3.id 	0.689644500356726
7150321	4368	mysql select query conditions	select j1.job_id     from job_requires j1         inner join job_requires j2             on j1.job_id = j2.job_id                 and j1.group_index = j2.group_index     where j1.field_id = 11 and j1.field_value = 50       and j2.field_id = 14 and j2.field_value = 1 	0.405199896882779
7150769	22836	mysql returning lowest zip code	select loccity, min(loczipcode)  from exp_course_events  group by loccity order by loccity 	0.164334994312723
7152898	11329	mysql where in results are out of order	select * from `challenges` where id in (108, 208, 134, 142) order by field(id, 108,208,134,142) 	0.0436087817545484
7154747	14608	mysql use row from same table as condition?	select t1.*  from `table` t1     inner join `table` t2 on t1.`parent` = t2.`id`  and t2.`online` = 1 where t1.`online` = 1 	0.000864517317640754
7155286	17781	sql - how to count items from other tables?	select brands.brandid, count(*) from brands inner join models on brands.brandid=models.brandid group by brands.brandid 	7.51176646212014e-05
7156466	1093	sql server database master key	select d.is_master_key_encrypted_by_server from sys.databases as d where d.name = 'adventureworks'; 	0.0414766005111447
7156881	34852	mysql limit and group by with join	select items.*,subitems.* from (     select *     from items     limit 10 ) as items left outer join subitems on subitems.subitem_itemid = items.item_id group by subitem.subitem_id; 	0.693952167522985
7157646	11581	convert update statement to a select statement	select t.ptime, (      (          select              count(*)          from              (                  select                      *                  from                      test              )as t1          where              t1.slope < t.slope      )* 100 /(          select              count(*)          from              (                  select                      *                  from                      test              ) as tz      )  )  as slope_percentile  from test as t  	0.547196642142479
7157891	24516	sql inner join query returns two identical columns	select employee.empid, employee.name, ... from employee  inner join department on employee.empid=department.empid 	0.116140174339402
7158812	39520	how can i combine these 2 sql queries into one	select c.title # also c.id if you need it from categories c, products p  where c.id = p.categoryid  and p.seo_title = '{$url_title}' 	0.00187187184070218
7159394	35775	sql; how can i use where condition for only one column	select a.id, a.turq_id, a.unvan, a.tip, a.aktor,         a.gsm_alan, a.gsm_tel, a.is_alan, a.is_tel,         a.is_ext, a.ev_alan, a.ev_tel, a.adres,         a.stf_kontak,         (case when a.yaz_adres is null          then (b.is_adres1 +' '+b.is_adres2)           else a.yaz_adres end)         collate database_default as yaz_adres , a.sehir, a.ps, a.memo from prospect_master a left outer join yaz..mardata.s_musteri b on a.id in (b.tc_kim_no, b.vergi_no) 	0.0196386164826235
7162076	35297	sql - how to count yes and no items	select  b.brand,         b.brandid,         count(m.modelid) as totalmodels,         sum((case when m.isbestvalue = 1 then 1 else 0 end)) totalbestvalueyes,         sum((case when m.isbestvalue = 0 then 1 else 0 end)) totalbestvalueno,         sum((case when m.isbestvalue is null then 1 else 0 end)) totalbestvaluenull, from    brands b         left join models m on b.brandid = m.brandid group by b.brand,         b.brandid order by b.brand 	0.00655264957167504
7162614	18191	sql query which counts status of grouped by month w. revision system	select t1.*  from table as t1  join table as t2 on (t1.original = t2.id)  where t1.status != t2.status; 	0.000306283668506376
7162750	26358	get distinct rows from list of 'games'	select * from testtbl t where location = 'a' or   (location = 'n' and team1 <= team2) 	0
7163319	12764	joins on mysql many-to-many tables	select distinct cats.id, cats.name from cats join items_to_cats on items_to_cats.fk_cat_id=cats.id join items on items.id=items_to_cats.fk_item_id where items.type='report' 	0.41387412098892
7163712	24426	turn two tables and a link table into one big table	select * from     (select          practitioner_id,          practitioner_name,          insurance_name     from practitioner p     join insurancelink il on p.practitioner_id = il.practitioner_id     join insurance i on il.insurance_id = i.insurance_id    ) pivot (count(*) for insurance_name in ([insurancename1],[insurancename2], ..., [insurancename100])) 	0
7176555	15947	mysql multiply if?	select sum(ps_order_detail.product_weight) *    if( count(ps_order_detail.id_order_detail) > 50, 1.2, 1 ) as total_provision,    count(ps_order_detail.id_order_detail) as antal_ordrar, ... 	0.116522655330964
7177180	21278	get username/account name from email address	select firstname, lastname, email, department, organization, rank              from client              where email like '#casuser#@%' 	0.00083069759057349
7178555	31825	subquery returned more than 1 value	select     contact,     mystatus = case          when column1 = 1 or column2 = 1 then 'active'         when column3 = 1 or column4 = 1 then 'inactive'     end from     mytable 	0.0305077408918894
7180617	28688	order by one-to-many relation	select * from messages as m order by greatest(    m.created_at,     (select max( c.created_at ) from comment as c where c.message_id = m.id ) ) desc 	0.429018883643542
7182254	40819	oracle: get the closest date for each id efficiently	select   id, date,price from   (select     p.id,     p.date,     p.price,     dense_rank() over (partition by d.date, p.id order by p.date) as rank   from     date d     inner join price p on p.date > d.date) where   rank = 1 	0
7182861	18060	how to compare dates in php	select * from table where datetime_field > now() - interval 7 day 	0.00405766382360572
7183364	7150	join on multiple columns	select tablea.col1, tablea.col2, tableb.val     from table     inner join tableb          on tablea.col1 = tableb.col1 or tablea.col2 = tableb.col2           or tablea.col2 = tableb.col1 or tablea.col1 = tableb.col2 	0.0358622310648302
7186207	22340	how to return record count in postgresql	select * into tmp_tbl from tbl where [limitations]; select * from tmp_tbl offset 10 limit 10; select count(*) from tmp_tbl; select other_stuff from tmp_tbl; drop table tmp_tbl; 	0.0047261557758424
7186268	18353	adding string to a select statement to include in result set	select p.name as title,         p.meta_desc as description,         p.product_id as id,         'new' as `condition` from products as p 	0.0431907957501862
7188047	17807	how to add integers to char in oracle 11g sql?	select chr(ascii('a') + 1) from dual 	0.0728322641752318
7188969	23427	using join in place of this two seperate queries	select     uid, list_name from     mytable t1 where    uid = 2    or    ( uid = 0       and not exists              ( select *                 from mytable t2                 where t2.uid = 2                  and t2.list_name = t1.list_name              )    ) 	0.221498257576522
7189128	9430	average the data in sql table	select pk, projectid, machineid, avg(powervalue), powerdata from table group by (pk-1)/5 	0.00132734201585275
7189633	6398	accumulate data over several days in sql query	select     a.symbol,     a.value        + coalesce((select sum(value)          from t2 b          where             b.date < a.date and            b.symbol=a.symbol         ),0)       + c.value  from     t2 a join t1 c on (a.symbol = c.symbol) 	0.00259090688209131
7189940	10801	retrieving last 100 rows from a mysql database	select ... from t order by id desc limit 100; 	0
7191636	18996	how do i sort an alphabetical text field?	select      column1  from        dbo.table1  order by    len(column1)         ,   column1 	0.0254293453260616
7193916	8199	mysql join statement pulling items multiple times from the same field in a db	select d.item as dog, i1.image_name as im1, i2.image_name as im2 from dogs as d join images as i1 on (i1.image_id = d.image_1)                join images as i2 on (i2.image_id = d.image_2) 	0
7194555	26404	display one of two fields in every row	select isnull(nick, name) as result from table 	0
7194650	26189	getting the last record of a user in a table	select top 1 ... from ... left join ... order by datalastmodified desc 	0
7194978	37224	same query multiple tables mysql	select count(*) +  (select count(*) from multiple_email where emailid = $emailid) from registration where emailid = $emailid 	0.0206581156654488
7196083	24485	sql server 2008 - conversion from string to int fails	select cast('32.000' as float) 	0.515553209717763
7196271	20888	trouble comparing strings in mysql	select ... from ... where `datefield` > date_sub(now(), interval 1 week) 	0.499204678157874
7196512	17774	sql count union for multi-column queries	select     d.[os name] ,   sum(d.[computer count]) as [computer count] ,   d. ... from ( select [os name], (select count (distinct statement for total computers including a few joins and where)) (select count (distinct statement for installed including a few joins and where)) (select count (distinct statement for exempt including a few joins and where)) (select count (distinct statement for missing including a few joins and where and a subquery)) from table union all select [os name], (select count (distinct statement for total computers including a few joins and where)) (select count (distinct statement for installed including a few joins and where)) (select count (distinct statement for exempt including a few joins and where)) (select count (distinct statement for missing including a few joins and where and a subquery)) from table2 ) d group by     d.[os name] 	0.540515469577243
7197776	19297	tsql - transform addresses on different rows to one row for each customer	select     custid ,   d.address as deladdress ,   coalesce(b.address, d.address) as billaddress from     address d     left outer join         address b         on b.custid = d.custid         and b.addresstype = 'b' where     d.addresstype = 'd' 	0
7198130	36977	sort mysql data from separate columns	select * from ( select game_id, round1away as away_score order by round1away   limit 5 union  select game_id,  round2away as away_score order by round2away   limit 5 )a order by away_score limit 5 	0.00024049071599379
7198203	6882	in c# how to connect to fetch two tables without connecting to the database twice	select * from table1 as t1 left join table2 as t2 on t1.modelno = t2.modelno 	0.000350806811084362
7199245	26833	how do i select rows where a column contains	select * from `vendor` where `services` regexp '[[:<:]]5[[:>:]]'; 	0.00269093455846744
7203813	10517	how to fetch the last record from the table in mysql without order by	select * from [mytable] where [id] > (select max([id]) - 1 from [mytable]) 	0
7205018	40150	add null row only if there's no result for such pe_num	select pe_num, derived_class from base_table left join ( ** some complicated subquery involving union's as mentioned in op **) using (pe_num) 	0.000678778076218354
7205734	33925	sql: cross table with foreign keys to two different tables	select zip.*,loc.* from x_data xref join zip_code_data zip on zip.zipcodeid=xref.zipcodeid join location_data loc on loc.locationdataid=xref.locationdataid where zip.zipcode like '2322%' or loc.city like '%aaa%' 	0.000134652903368004
7206547	367	determine if table has consecutive primary id auto increment values	select (max(id) - min(id)) + 1,         count(id) from table 	0
7209867	35129	sql server database merging two columns?	select empid, empname, homephone, homeaddr from temptable union select empid, empname, workphone, workaddr from temptable union select empid, empname, extraphone, extraaddress from temptable 	0.00215719216506325
7210189	28972	how to set collation for a connection in sql server?	select * from orders where customerid = 3277  and projectname collate chinese_prc_ci_ai_ks_ws like n'學校' update quotes set iscompleted = 1 where quotename collate chinese_prc_ci_ai_ks_ws = n'學校的操場' 	0.745952414515499
7210317	30960	how can i find the record with the max value for a group?	select test.id, test.size, test.item from test inner join (     select id, max(size) as size     from test     group by id ) max_size on max_size.id = test.id and max_size.size = test.size 	5.2806735222785e-05
7212282	14095	is it possible to query a comma separated column for a specific value?	select    *  from   yourtable  where    ',' || commaseparatedvaluecolumn || ',' like '%,searchvalue,%' 	0.000117832255492957
7212681	1543	mysql - subqueries w/ counting items	select cc, cat_name, name from (    select count(deals.id) as cc, cat.name as cat_name, deals.name as name     from ddd_categories as cat    join ddd_deals as deals on deals.category_id=cat.id    group by deals.id ) order by xxx; 	0.182481136954956
7212793	21443	sql query to find maximum tax brackets	select   locationname,   maxtaxrate from   (select     max(tax_rate) as maxtaxrate,     locationname   from     mylocations   group by     locationname   ) as maxtable 	0.0274106859523467
7213670	33586	mysql join with many (fields) to one (secondary table) relationship	select p.provider_last_name, p...., t1.specialization as specialization1, t2.specialization as specialization2, t3.specialization as specialization3 from physicians p left join taxonomy_codes t1 on t1.taxonomy_codes = provider_taxonomy_code_1 left join taxonomy_codes t2 on t2.taxonomy_codes = provider_taxonomy_code_2 left join taxonomy_codes t3 on t3.taxonomy_codes = provider_taxonomy_code_3 	0.00291121230410499
7214125	22726	translation query	select coalesce( de_at.translation, de.translation, en.translation )   from (select 'greeting' as id) as id   left join translations as de_at on( de_at.lang = 'de_at' and id.id = de_at.id )   left join translations as de on( de.lang = 'de' and id.id = de.id )   left join translations as en on( en.lang = 'en' and id.id = en.id ) 	0.748850068969438
7216511	41162	mysql/php: consolidate results such as footnotes from multiple tables	select group_concat(agent.reference separator ','), agent_names.id, agent_names.name                      from agent_names, agent                      join actor_list on(agent.bw_actor_list = actor_list.id)                       join reports on(agent.reference = reports.id)                      where  agent_names.id = agent.agent_name and bw_actor_list =  '".mysql_real_escape_string($a)."' group by agent_names.id 	0.0544129524719022
7217071	32975	mysql subquery result array	select field_b from table_2 inner join table_1     on table_2.id_2 = table_1.id_1 where table_2.field_a=1234 	0.405187645493125
7217719	34058	sql: use table aliases across multiple select statements	select   * from   (select * from bla   union all   select * from blo) bli   inner join anothersometing a on bli.id = a.id 	0.561561648326342
7217887	25212	getting exact matches from full-text search returned first?	select *, case when wm = 'foot locker' then 1 else 0 end as score, match (`wm`, `locn`, `gns`) against('foot locker') as score2 from `example_table` where match (`wm`, `locn`, `gns`) against('foot locker')) order by score desc, score2 desc; 	0.00160592142487973
7219501	17913	query question: is there a better way to select all records from one table, along with unmatched records from another table?	select     c.customerid,     coalesce(m.address1, c.address1) as address1,     coalesce(m.city, c.city) as city,     coalesce(m.state, c.state) as state,     coalesce(m.zip, c.zip) as zip from customers c left join customermailingaddresses m on m.customerid = c.customerid 	0
7225574	37270	synchronize a select projection	select [id]       ,[name]       ,case when 'reptile' in        (select [type] from dbo.pets [s] where s.people_id = p.id)        then 1 else 0 end [hasreptile]   from people [p] 	0.432546983770909
7225804	23993	getting distinct users in a messages database table	select sender_id from   messages where  receiver_id = '$sess_id' union select receiver_id from   messages where  sender_id = '$sess_id' 	0.000963352625501039
7226123	16473	many to many relationship tag matching?	select      ai.art_id,      ai.title     count(distinct r2.tag_id) as relevance from art_tag_relationship r1  inner join art_tag_relationship r2 on (r1.tag_id = r2.tag_id                                     and r1.art_id <> r2.art_id)  inner join art_info ai on (r2.art_id = ai.art_id)  where r1.art_id = '1'    group by ai.art_id order by relevance desc 	0.0112343834507989
7226844	23668	convert varchar(8) values and use asc in t-sql	select      total  from table a order by cast(total as float) asc 	0.481952776548489
7226984	36102	how can i do the sumation of time in mysql query?	select sec_to_time(sum(time_to_sec(totalloginfinal))) from table_name; 	0.0483089337114735
7227551	4587	oracle - time and date format	select to_char ( mydatecolumn, 'yyyy-mm-dd' ) from mytable 	0.0369440808643955
7227679	29629	median values in t-sql	select avg(total) median from (select total,  rnasc = row_number() over(order by total), rndesc = row_number() over(order by total desc)  from [table]  ) b where rnasc between rndesc - 1 and rndesc + 1 	0.051675491751314
7227984	40701	t-sql string manipulation	select substring(yourcolumn, len(yourcolumn)-charindex('\', reverse(yourcolumn))+2, 1) from yourtable 	0.469005114982623
7228041	35219	t-sql: sql to get mutual records from a single table	select t1.* from table1 t1 join table1 t2 on (t1.col2 = t2.col1) and (t1.col1 = t2.col2) where t1.col1 = 1 	0
7228662	14851	how can i do a yearly report grouped by month?	select to_char(trunc(date,'yyyy'),'yyyy') as year, sum(number_of_transactions) from header where date < trunc(sysdate, 'mm') group by trunc(date,'yyyy') order by year 	0.00153233910978254
7229790	26264	sql query first rows with specific column values	select blah, blah from t where  ... union   select * from   (     select blah, blah from t where something else order by somecolumn limit 1   ) 	9.6806794460931e-05
7230174	15011	using two variables from php on the same where in mysql	select * from `poster` where mdr < '201106' and mdr > '201100' 	0.000967198317040061
7231375	2969	count(*) and having	select count(*) from ... where ... and   (6368 * sqrt(2*(1-cos(radians(loc_lat)) * cos(0.899945742869) *   (sin(radians(`loc_lon`)) * sin(0.14286767838) + cos(radians(`loc_lon`)) *    cos(0.14286767838)) - sin(radians(loc_lat)) * sin(0.899945742869)))   ) between 0 and 25 	0.25043340831379
7231746	12086	select everything, based on distinct user id in oracle	select distinct user_id, users.* from users; 	9.63680667679316e-05
7232570	31383	sql select where two particular items not sold on same date to same customer	select     ol1.* from     order_lines ol1 inner join product_types pt1 on     pt1.product_id = ol1.product_id and     pt1.product_type = 'kite' inner join customers c1 on     c1.customer_id = ol1.customer_id where     not exists (         select *         from order_lines ol2         inner join product_types pt2 on             pt2.product_id = ol2.product_id         inner join customers c2 on             c2.customer_id = order_lines.customer_id and             c2.first_name = c1.first_name and             c2.last_name = c1.last_name         where             ol2.order_date = ol1.order_date and             pt2.product_type = 'yo-yo') 	0
7232648	38669	how to get records based on date of birth	select ... from... where datediff(dd,              cast(cast(year(getdate()) as varchar) + '-' + cast(month(dateofbirth) as varchar) + '-' + cast(day(dateofbirth) as varchar) as datetime),              getdate()) <= 7 	0
7232704	38762	how to check if a given data exists in multiple tables (all of which has the same column)?	select 1  from (     select username as username from tbl1     union all     select username from tbl2     union all     select username from tbl3 ) a where username = 'someuser' 	0
7235118	14322	ip conflicts mysql	select login_ip, count(login_ip) as occurences from accounts group by login_ip having ( count(login_ip) > 1 ) 	0.371465466218983
7238029	34924	sql select when a grouped record has multiple matching strings	select masteritemid from itemsgrouptable where itemname regexp 'item [1234].*' 	0.000136146612149755
7239476	6270	geting value count from an oracle table	select name, surname, username, decode(count(*) over (partition by name, surname), 1, 'n', 'y') from your_table; 	0.00431050358341124
7239531	22455	how to get absolute last 7 days data, instead of last 7 records in sqlite iphones	select * from consumed where date between ? and ? 	0
7241322	40384	two level adjacency list using mysql and php	select * from `tasks`  where `parenttask_id` = 0 or `parenttask_id` in  (select `task_id` from `tasks` where `parenttask_id` = 0) 	0.0524982130128743
7243531	34712	t-sql query to output the values in csv format	select        t1.subscriptionid,       (select generationtimes + ', '        from tablename t2        where t1.subscriptionid = t2.subscriptionid        for xml path('')) as generationtimes from tablename t1 group by t1.subscriptionid 	0.0286386978713356
7243907	14499	how can you get the ram usage of processes in an oracle11g database?	select operation,         options,         object_name name,        trunc(bytes/1024/1024) "input(mb)",        trunc(last_memory_used/1024) last_mem,        trunc(estimated_optimal_size/1024) opt_mem,         trunc(estimated_onepass_size/1024) onepass_mem,         decode(optimal_executions, null, null,               optimal_executions||'/'||onepass_executions||'/'||              multipasses_executions) "o/1/m"   from v$sql_plan p      , v$sql_workarea w  where p.address=w.address(+)    and p.hash_value=w.hash_value(+)     and p.id=w.operation_id(+)     and p.address= ( select address                       from v$sql                      where sql_text like '%my_table%' ) 	0.0553385330138615
7244252	26631	how to design database table for working hours?	select datediff(hh,'2011-08-30 04:47','2011-08-30 05:48') as [hour(s) worked] hour(s) worked 1 	0.0341481744125252
7245423	23458	find all tables without a certain column name	select     table_name from     information_schema.tables t where     t.table_catalog = 'mydb' and     not exists (         select *         from information_schema.columns c         where             c.table_catalog = t.table_catalog and             c.table_schema = t.table_schema and             c.table_name = t.table_name and             c.column_name = 'enddate') 	0
7247166	30358	ordering a mysql query?	select * from linkpages inner join pages on pages.pageid = linkpages.pageid where linkmemberid='memberid' order by startdate desc limit 5 	0.500429606467104
7247238	20781	sql sum() in a month on month report	select     dbo.jm_job_type.job_type_desc,            dateadd(month,datediff(month,0, dbo.jm_invoice.yourdate),0) as monthyear,            sum(dbo.jm_invoice.invoice_amount) as 'inv tot' from         dbo.jm_invoice inner join                   dbo.jm_job on dbo.jm_invoice.job_no = dbo.jm_job.job_no inner join                   dbo.jm_job_type on dbo.jm_job.job_type_no = dbo.jm_job_type.job_type_no group by dbo.jm_job_type.job_type_desc,           dateadd(month,datediff(month,0, dbo.jm_invoice.yourdate),0) 	0.000237591015172391
7249146	36712	list results in mysql with join	select user_id   from wp_usermeta   where (meta_key = 'age' and meta_value = '19')     or (meta_key = 'gender' and meta_value = 'male')     or (meta_key = 'int' and meta_value ='male')   group by user_id   having count(*) = 3 	0.248686864467208
7250887	5445	sql count of data in many to one relationship where i want to find duplicate data	select a.patientid, a.apptid, count(e.encounterid) as numberofencounters from appointment a left join encounter e on e.apptid = a.apptid                             and exists (select * from encounter e2 where e.pkencounterid <> e2.pkencounterid and e.code = e2.code and e.dateofencounter = e2.dateofencounter and e.apptid = e2.apptid) group by a.patientid, a.apptid order by count(e.encounterid) desc 	0
7250995	15905	php mysql query	select * from images  where score in (select distinct score from images order by score desc limit 20) order by score desc; 	0.512830742731512
7252406	17947	how to extract info based on the latest row	select a.sku, a.code, a.bin, b.grade, b.size, b.color, b.finish  ,b.seqno from #tablea a left outer join (       select x.seqno,            x.sku as sku,            x.code as code,           max(case when id = 'grade' then [value] end) as grade,           max(case when id = 'size' then [value] end) as size,           max(case when id = 'color' then [value] end) as color,           max(case when id = 'finish' then [value] end) as finish       from #tableb x       inner join       (         select sku, code, max(seqno) as seqno         from #tableb         group by sku, code       )y on (x.seqno = y.seqno)       group by x.seqno, x.sku, x.code )b on (a.sku = b.sku and a.code = b.code) 	0
7252467	18339	sql query help - condition applies only for the newest record	select a.patientid from     some_table as a     inner join (         select patientid, max(date) as date         from some_table         where test = 'x'         group by patientid     ) as lr on a.patientid = lr.patientid and a.date = lr.date where a.test = 'x' and a.result > 10 	0.0216976554207456
7255671	33082	mysql select statement with min	select pr.id, pr.name, pr.image, min(pi.price) min_price from products pr inner join product_items pi on pr.product_id = pi.product_id group by pr.id 	0.513636163912173
7256270	24971	how to get the dates available in a mysql table	select distinct date(`column_with_date_and_time`) as `date`         from `table` order by `date` 	0
7257093	35044	sql - select all skills	select id_user from user_skills where id_skill in (1,2) group by id_user having count(*) = 2 	0.0387016607741097
7259101	34003	stored procedures and temp tables	select * into ##users from usertable 	0.302282696109082
7260485	39855	linq to nhibernate: select multiple sums at once	select() 	0.00863219919813218
7261613	20029	mysql how to order by?	select klass,id from klassid where klass!=''  order by klass+0 asc, klass asc 	0.209076028008595
7266262	37077	get certain record while sum of previous records greater than a pecentage in sql server	select top 1    t2.id,   sum(t1.value) as runningtotal from foodata t1  inner join foodata t2    on t1.id <= t2.id  group by t2.id having sum(t1.value) * 100. /    (select sum(value) from @foodata) > 90 order by sum(t1.value) 	0
7269080	17568	exporting mysql to csv with specific row names	select col1 as "user id", col2 as "first name" from table; 	0.00051743065520779
7269339	15777	get all months last days in mysql	select distinct(last_day(date)) from table; 	0
7270467	27899	is there a pl/sql pragma similar to deterministic, but for the scope of one single sql select?	select t.x, t.y, (select my_function(t.x) from dual) from t 	0.00702934585626619
7271588	20807	how to use the output of one sql statement in another	select distinct * from countries where region_id in (select region_id from regions where region_name = 'europe') 	0.00709560583216166
7272190	19649	sql query duplicate rows from union	select     me,     ope,     dd,     u11,     id3,     legal,     pai = (select tbluser.user from tbluser where tblmat.pai = tbluser.userid),     ial = (select tbluser.user from tbluser where tblmat.id3 = tbluser.userid),     isnull(tblcon.contactname,'') as outside,     dagal from     ttblmat left outer join     tblmatrelateditems on     tblmat.me = tblmatrelateditems.me and     tblmatterrelateditems.relateditem = 'contact' left outer join     tblcon on     tblmatrelateditems.relatedkey = tblcon.contactid and     tblcon.contacttype = 'managing partner'  where     mstatus = 'open' and     (mgroup = 'cas' or templategroup = 'sub' or tmattertemplate = 'ss') and     (opte <= convert (nchar (8), getdate (), 112) and     opte >= dateadd (mm, -6, getdate ())) and     lookup2 in('nol','nh','ne') 	0.00442966289093254
7272260	8485	combining two queries in mysql	select ehr.reservationid, ehr.day, h.name as hotelname,      ehr.totalrooms as requested_rooms, r.name as roomname,      egh.bookedrooms from event_hotel_reservation ehr  inner join hotel_room_type r on ehr.roomtypeid = r.roomtypeid  inner join hotel h on ehr.hotelid = h.hotelid     left outer join (     select hotelid, count(roomtypeid) as bookedrooms, day      from event_guest_hotel      where roomtypeid = 1      group by hotelid, day ) egh on h.hotelid = egh.hotelid and ehr.day = egh.day where totalrooms != 0      and reservationid = '1' 	0.0631937213253121
7274497	28852	sql query with date period and more	select a.name, f,r,t from(     select name, count(1) as f,2*count(1) as f_sum     from table1     where date >=current_date-30      and event='f'     group by name     )a join(     select name, ,count(1) as r,0.5*count(1) as r_sum     from table1     where date >=current_date-30      and event='r'     group by name     )b on a.name=b.name join(     select name, count(1) as t,4*count(1) as t_sum     from table1     where date >=current_date-30      and event='t'     group by name     )c on b.name=c.name order by f_sum+r_sum+t_sum desc; 	0.0724569576070707
7275000	22735	php/sql creating links to next row in a database	select     ( select id from <table-name> where id > $currentid order by id asc limit 1 )     as next_value,     ( select id from <table-name> where id < $currentid order by id asc limit 1 )     as prev_value from dual; 	0.00108534484187492
7276423	585	asp & sql server 2008 : calculated value from another calculated value	select *, c01 = (s00/constant)  from (  select s00 = sum(column1)   from table ) as x; 	0.00038257925800591
7276519	21033	how do i include my id with the id's from a select and join statement?	select *     from table.post p         left join table.follow f             on p.ownerid = f.userid         inner join table.users u             on p.ownerid = u.id     where p.ownerid = '$myid'         or f.ownerid = '$myid'     order by p.date desc 	0.000906027459146822
7276710	28373	full outer join on one criteria, inner join on another	select   coalesce(o.orderid, od.orderid) as orderid,   coalesce(o.currencyid, od.currencyid) as currencyid,   o.buyamount,   o.buyrate,   od.sellamount,   od.sellrate from   #orders as o   full outer join #orderdetails as od on o.orderid = od.orderid and o.currencyid = od.currencyid 	0.381769805353922
7276932	16635	mysql count rows where a=b and b=a	select count(*) from t t1 join t t2 on t1.b = t2.a where t1.a = ? and t2.b = ? 	0.0874748441321067
7277107	19593	add all the columns of a consult in sql	select a1, a2, a3, ... , an, (a1 + a2 + ... + an) as s from yourcolumn. 	0.000193915915620918
7277241	34826	how can i pull multiple user info from one query?	select    j.title,    tp.display_name as to_name, fp.display_name as from_name,    i.to_id, i.from_id,    i.amount from    invoice i   join jobs j on j.job_id = i.job_id    join profiles fp on i.from_id = fp.user_id    join profiles tp on i.to_id = tp.user_id  where    i.invoice_id= '3' 	8.38923914165469e-05
7278867	13827	mysql show duplicates	select * from tbl     where (b = x or b = y)     and a in (select a from tbl where b = y)     order by a asc 	0.0425953432909535
7280277	23302	join table rows by group_concat , failed! it's not working?	select id, group_concat(skill separator ', ') from resume_skills group by id 	0.706498347396533
7280781	21621	determine most recent 'vote type' for a record, returning 2 fields for hasvotedup/down?	select p.id,     case when vt.votetypeid = 1 then 1 else 0 end as hasvotedup,     case when vt.votetypeid = 2 then 1 else 0 end as hasvoteddown from posts p left outer join     (         select v.postid, v.votetypeid         from votes v inner join         (             select postid, userid, max(creationdate) as creationdate             from votes             group by postid, userid         ) newest on v.postid = newest.postid and v.userid = newest.userid and v.creationdate = newest.creationdate         where v.userid = 1     ) vt on p.id = vt.postid 	0
7280977	38983	multiple aggregates from same sub query in sql server	select     name,     er.dateeventstarts,     e.locationname, t.noofattendees, t.totaltickets, t.onlinepayfee, t.onlinepaytotalcost   from [event] e join eventrepetition er     on         er.eventrepetitionid = (select top 1 eventrepetitionid from eventrepetition er2 where er2.eventid = e.eventid) join     (select eventrepetitionid,count(*),sum(tickettotalcost),sum(onlinepayfee),sum(onlinepaytotalcost)     from ticket     where deleted = 0 and refunded = 0     group by eventrepetitionid) t (eventrepetitionid,noofattendees,totaltickets,onlinepayfee,onlinepaytotalcost)         on             er.eventrepetitionid = t.eventrepetitionid 	0.220973382617545
7281133	29191	increments of a date using oracle sql	select * from table where status = 'pending' and mod(sysdate-date_created, 3) = 0 	0.0278831065691311
7281652	32509	sqlce: how to count datepart	select datepart(week, createdate) as week, count(*)  from tblorders  where createdate>'12 april 2010' and createdate<'25 june 2011' group by datepart(week, createdate) 	0.186793537408003
7282248	32597	oracle sort substitution variables	select     least(:var1, :var2, :var3) as least_var,     case       when :var2 < :var1 and :var1 < :var3         or :var2 > :var1 and :var1 > :var3 then :var1       when :var1 < :var2 and :var2 < :var3         or :var1 > :var2 and :var2 > :var3 then :var2       else :var3     end as greater_var,     greatest(:var1, :var2, :var3) as greatest_var from dual 	0.675143017516761
7284156	18673	how to provide a download of a mysql database in php	select t1.a, t2.b  from table1 t1 inner join table2 t2 on (t1.id = t2.table1_id) where table2.somefield = 'something' into outfile 'outfile.csv'; 	0.0598015498865536
7285298	24258	counting the number of occurances of something in the database	select tags.tagid, count(articles.tagid) as occurances   from articles   join tags on articles.tagid   group by tags.tagid 	7.94880109587291e-05
7286031	27395	how can i exclude a certain row from an mysql query	select * from imdb where genres like 'adventure' and id <> 1 order by id desc limit 10 	5.8317313356942e-05
7287865	17627	getting time interval from datetime	select call_id,        start_time,        right(100+datepart(hour, start_time), 2)+        right(100+30*(datepart(minute, start_time)/30), 2) as interval from timezone 	0.00190198169504775
7288270	39187	get the column order of a query	select t2.pos, t1.id, t1.value  from test as t1 inner join (select id, value, @pos:=if(@pos is null, 0, @pos)+1 as pos   from test order by value desc) as t2 on t1.id=t2.id where t2.pos<=3 or t2.id={$ask_id} order by t2.pos; 	0.00207514880895627
7288667	39664	find duplicates in table plus join	select d.phone,         min(d.id) minid, max(d.id) maxid , count(*) count from   tablec c  join tabled d  on c.tableid = d.id  where  c.leadlistid = 81 group by d.phone having count(*)> 1 	0.0202329041049549
7288888	410	combining two time interval queries	select arr_date,        interval,        sum(case when han_time > 1800 then 1 else 0 end) as han_time_1800,        sum(case when sl_time > 300 then 1 else 0 end) as sl_time_300 from call_data where han_time > 1800 or        sl_time > 300 group by arr_date, interval order by arr_date, interval 	0.00858985982004434
7289048	7861	t-sql to determine lowest bit value in a result set	select top 1 *      from horriblesample  where code = 'hello'   order by istrue 	0.00173741202822912
7291177	35348	how to generate ten absolute random digit in sql server?	select floor(rand() * power(cast(10 as bigint), 10)) 	0.00520917201594385
7292438	9743	edit an sql query	select table1.id, table1.name,    case table1.event      when 'r' then 'very high'      when 't' then 'very low'      else (select table2.risk from table2 where table2.value <= table1.value            order by table2.value desc limit 1)    end as risk from table1 order by field( table1.event, 'r', 'f', 't' ), table1.value desc 	0.692979530522931
7292763	26428	mysql meta search using distinct	select user_id from wp_usermeta where ( meta_key='postcode' and meta_value= '3000') or       ( meta_key='state' and meta_value= 'vic') or       ( meta_key='maternitybg' and meta_value= 'no' ) group by user_id having count(distinct meta_key) = 3 	0.23975854045439
7292906	38151	how can i merge and count mysql rows that are identical except for an id column?	select col1, col2, count(col1) from mytable group by col1, col2 	0
7293912	9796	store objects with common base class in database	select cb.id, a.x, a.y, b.name   from commandbase cb    left outer join commanda a on a.id = cb.id    left outer join commandb b on b.id = cb.id 	0.01122087033105
7294595	19281	get the mysql record that has less child-records	select    count(s.id) from      wifi_spots s left join wifi_users u on u.spot_id = s.id where     u.status = 'active' group     by s.id order     by count(u.spot_id) limit     1 	0.000162449805351343
7295249	26830	filter null values from query	select table1.id, table1.name,    case       when table1.event = 'r' and table1.name = 'jones' then 'very high'      when table1.event = 't' and table1.name = 'smith' then 'very low'      else (select table2.risk from table2 where table2.value <= table1.value            order by table2.value desc limit 1)    end as risk from table1 # add this row: having risk is not null order by field( table1.event, 'r', 'f', 't' ), table1.value desc 	0.0185391693304222
7297651	30782	mysql order rank as a column	select [columns],    (      (case when [1st rank criteria] then 3 else 0 end) +      (case when [2nd rank criteria] then 2 else 0 end) +      (case when [3rd tank criteria] then 1 else 0 end)    ) as myrank from (     select *, count(*) as `matches`     from [table1]     join [table2] using (id)     join [table3] using (id)     where [criteria]     group by `id`     order by `matches` desc ) as `grouped` order by myrank desc limit 100; 	0.0845094930755878
7300905	950	duplicate attributes of table sql	select      a1, a2, a3, a4,      a1 + 1 as 'a5',      a2 + 1 as 'a6',      a3 + 1 as 'a7',      a4 + 1 as 'a8' from      dbo.yourtable 	0.00283375796459257
7304081	23693	replacing null from results of case query	select   sid,   coalesce([form1],'no') as [first],   coalesce([form2],'no') as [second],   coalesce([form3],'no') as [third],   coalesce([form4],'no') as [fourth],   coalesce([form5],'no') as [fifth],   coalesce([form6],'no') as [sixth] from (   select sid, formid, present from @qa1 ) s pivot (   min(present)   for formid in ([form1],[form2],[form3],[form4],[form5],[form6]) ) as p order by sid; 	0.204028316076296
7304528	19036	sql select multiple distinct column rows as one column	select name, homephone as phone from directory where homephone is not null union select name, fax as phone from directory where fax is not null union select name, mobile as phone from directory where mobile is not null 	0.000104095006300464
7306401	15047	sql group by and value	select * from (    select availbilitydate,            resort,           accomname,           price,           min_occupancy,           min(price) over (partition by availbilitydate, resort) as min_price    from deals_panel_view ) t where min_price = price; 	0.0744185174417859
7306658	20464	ordering rows by data from another table	select * from table1 t1  join table2 t2 on t1.id = t2.user_id  order by date desc, count desc 	7.82737990319596e-05
7306843	15621	limit results to last 10	select * from (select * from graphs where sid=2 order by id desc limit 10) g order by g.id 	0.00035511488148591
7307813	811	select data excluding a subset of records with linq with minimal overhead	select      d.itemid  from      documents d  where      d.itemid not in        (          select top 250 itemid           from documents           where categoryid = d.categoryid           order by d.itemid desc       ) 	0.000393393198619104
7310349	20344	creating tempory column in mysql	select (year(curdate())-year(birth)) as age from table_name; 	0.500025210411642
7310640	33036	mysql: counting two fields	select pizza, count( distinct topping) as cnt from your_pizza_table group by pizza order by cnt desc; 	0.0074828401345873
7311091	32933	mysql query question last time record found in database	select device, count(*) as cnt, max(time) <     from database.table  group by device   having cnt>1 order by device; 	0.00160539708175717
7318786	16756	how do find the mysqldump operation permission by that user	select * from mysql.user where select_priv and lock_tables_priv='y'; 	0.0217455056383844
7319046	3352	customers who bought this also bought this... help	select distinct l.id, l.name, count(l.id) as rank from lessons l join users_to_lessons ul on l.id = ul.lessons_id where l.id<>my_lesson_id and   ul.users_login in   (select distinct us.login from users us    join users_to_lessons ls on us.login = ls.users_login    where ls.lessons_id = my_lesson_id       and us.id<>my_user_id) group by l.id order by rank desc, l.name 	0.109735526869899
7319820	17603	geonames database: getting a full hierarchy (country -> admin1 -> admin2 -> city) with one only mysql query	select locgeoname.*, loc_countryinfo.name, loc_admin1codes.name, loc_admin2codes.name,  from loc_geoname  inner join loc_countryinfo  on loc_countryinfo.iso_alpha2=loc_geoname.country inner join loc_admin1codes  on code=loc_countryinfo.iso_alpha2+'.'+admin1   inner join loc_admin2codes  on code=loc_countryinfo.iso_alpha2+'.'+admin1+'.'+admin2 	0.00270089846835125
7321964	433	mysql, select all from table	select * from categories c inner join (select catparentid from categories where id = 4) a on c.catparentid = a.catparentid 	0.00109904558298634
7322025	10298	return descending list of products by total sold from line item table in mysql	select product_id, sum(qty) as qty_sum from table group by product_id order by qty_sum desc 	0
7322322	8973	using sql query to find details of customers who ordered > x types of products	select customer_name, count(distinct product_id) as products_count from customer_table inner join orders_table on customer_table.customer_id = orders_table.customer_id group by customer_table.customer_id, customer_name having count(distinct product_id) > 10 	0
7322455	20518	mysql combining multiple count queries	select sum(case when package = '2' then 1 else 0 end) as advanced_count,        sum(case when package = '1' then 1 else 0 end) as basic_count,        count(*) as total_count     from users     where site_url is not null         and package in ('1', '2'); 	0.119764698290864
7323802	66	convert column values to grouped comma-separated string	select id, (select itbl.name+','             from tblname itbl             where itbl.id=tbl.id             for xml path('')) name from tblname tbl group by id 	0.000918710826215148
7323883	1342	sql query that displays "time ago dates" like “one week ago”, “two weeks ago”, “one month ago”, “one year ago”, etc	select  column1,  column2,  thedate, case   when datediff(dd, thedate, getdate()) =< 7 then 'one week ago'   when datediff(dd, thedate, getdate()) > 7 and datediff(dd, thedate, getdate()) < 30 then 'one month ago'   end as timeago, column3, column4 from table1 	0
7324863	39020	database structure - two tables or one table?	select count(user_id) from user_login_sessions where user_id = ? 	0.00167672131474741
7327354	16004	get specific info from sql error message 547	select * from sys.messages where message_id=547 	0.00927176518706574
7327628	6587	mysql query but two differant group by	select ms.playerid, mp.name, sum(ms.runs_by_match) as runs_scored,     max(ms.runs_by_match) as highest_score from     matchplayer as mp     inner join (         select playerid, matchid, sum(runs) as runs_by_match         from matchplayer         group by playerid, matchid     ) as ms on mp.playerid = ms.playerid group by     ms.playerid, mp.name 	0.232633408127156
7328448	2164	sql: select users where relationship count == 1	select users.id, count(items.type) from users join items on items.user_id = user.id where items.type is not null group by users.id having count(items.type) = 1 	0.0195615241080607
7328485	13643	select datetime as varchar in sql server 2008	select convert(varchar(10), [mydatetimecolumn], 20),... 	0.352664018396713
7330535	38875	android sqlite no data from view	select * from view_all_sms_wcd where contact_id = '1' order by st_dte asc 	0.0541538927528574
7331757	29953	sql server: cumulative percentage with "group by" on many fields	select type_material, years, row_num, percentual_price, percentual_price_cumulative= ( select sum(percentual_price) from @mytable b where b.row_num<=a.row_num and b.years = a.years and b.type_material = a.type_material ) from @mytable a 	0.0118361627933974
7332344	6796	selecting data from two tables using mysql stored procedures	select o.id, o.itemname, o.companyname, o.quantity * ifnull(t.itemprice, 1) total      from one o left join two t         on o.id = t.id 	0.000997490497796441
7333001	25523	mysql select from three tables as one	select `table_two` . *  from  `table_one`  join ( `table_two` ) on `table_two`.`two_nid`=`table_one`.`t_one_id` where  `table_one`.`t_one_id`=1 union select `table_three` . *  from  `table_one`  join ( `table_three` ) on `table_three`.`three_nid`=`table_one`.`t_one_id` where  `table_one`.`t_one_id`=1 union select `table_four` . *  from  `table_one`  join ( `table_four` ) on `table_four`.`four_nid`=`table_one`.`t_one_id` where  `table_one`.`t_one_id`=1 	0.00122106175699776
7333300	2045	sql server datetime in query	select     * from t   where startdate < dateadd(hour, -1, '2011-08-24 17:30:00.000') 	0.510248896765793
7333465	14234	how to write a sql request that selects rows with a column value equal to one of multiple values?	select *  from jobstable j inner join jobidstable jt on j.jobid = jt.jobid 	0
7335658	30224	re-sorting the output of a select limit query	select *  from (   select *    from `stats`    where `projectid` = ?   order by `statsdate` desc   limit 6 ) s order by s.statsdate 	0.312830825573645
7336434	35419	how to retrive the mysql server timezone and then do a convertion in php	select convert_tz('2004-01-01 12:00:00','system','@user_timezone'); 	0.0354261903437893
7336971	27726	calculating a field from sql query selecting from multiple tables with union	select mtguid * 1.35 as calculatedmtguid, subsel.* from (   select bkretail.* from bkretail where bkretail.mkey='somekey'  union  select bkwholesale.* from bkwholesale where mkey='somekey') subsel order by   case status      when 'rt' then 1      when 'wh' then 2      when 'ol' then 3      when 'od' then 4      when null then 5      else 6   end; 	0.000147766037591301
7336994	26446	sql view without references	select   t1.value as t1value,   ...   t4.value as t4value,   t.fld1   ..   t.fld16 from   t inner join t1 on t.t1_id = t1.id ... inner join t4 on t.t4_id = t4.id 	0.25963388803392
7337691	10240	problem with result order on distinct select query	select group_id,max(date) as sortdate from table group by group_id order by sortdate 	0.629294161891237
7338418	19159	how to find stored procedures by name?	select schema_name(schema_id) as [schema],         name from sys.procedures where name like '%item%' 	0.0263983508700184
7339156	1907	is it possible to do a group by in sql server 2000 that returns the whole row?	select rh.rh_sp_number, rh.rh_end_date from dbo.readings_history as rh inner join (   select rh_sp_number, rh_end_date = max(rh_end_date)   from dbo.readings_history   group by rh_sp_number ) as sub on rh.rh_sp_number = sub.rh_sp_number and rh.rh_end_date = sub.rh_end_date; 	0.117026944325917
7340285	30442	find total duplicate entries on two columns	select sum(sub.counts) from (   select col_1, col_2, col_3, col_4, count(*) as counts   from mytable   group by col_1, col_2, col_3, col_4   having count(*) > 1 ) sub; 	0
7341127	4826	quick way to find usages of db objects in sql server 2008?	select referencing_schema_name,         referencing_entity_name,         referencing_id,         referencing_class_desc,         is_caller_dependent from sys.dm_sql_referencing_entities ('production.product', 'object'); 	0.418489241833064
7342185	33822	sql select problem	select tableb.id_box,tableb.boxname, sum(bc.boxcount) from tableb inner join    (select box1_id as boxid, box1count as boxcount    union     select box2_id as boxid, box2count as boxcount   ) bc  on (tableb.id_box=bc.boxid)  group by tableb.id_box, tableb.boxname 	0.798250004351207
7342638	11475	sql sum of 3 counts (different month clause) from same table	select count(*) from table1 where month in (1,2,3) 	0
7346127	22345	how do i count multiple columns in sql server?	select count(*), a, b, c, d  from dbo.yourtable  group by a, b, c, d 	0.0317251439580675
7346612	14761	use case is postgresql query to get record based on condition	select e.emp_name,        e.id,        coalesce(r.leavingdate, e.retiredate) as some_date  from tblemp e    left join tblresign r on e.id = r.emp_id 	0.0104796799222383
7348955	20450	ssrs - get group total within record scope	select field1, field2, value,         100.0 * value / sum(value) over(partition by 1)  from yourtable 	0.000308244620918804
7349538	40891	sql select statement for 3 tables	select distinct      p.productid,     p.productname from product p inner join marketing m on p.productid = m.productid inner join feature f on f.featureid = m.marketingdata where  f.featuretitle like '%@textyousearchfor%' order  by p.productname asc 	0.191343805693794
7349597	32845	how do i add a column with an auto-incremental name to a mysql table?	select '' as userid,       max(case when w.weekno = 1 then w.start_date end)) as 'w1',        max(case when w.weekno = 2 then w.start_date end)) as 'w2',        max(case when w.weekno = 3 then w.start_date end)) as 'w3',        ........ etc  from tbl_week w where w.start_date >= start and w.end_date <= enddate  union all select     userid,     sum(case when w.weekno = 1 and ww.weekid is not null then worked else 0 end)) as 'w1',    sum(case when w.weekno = 2 and ww.weekid is not null then worked else 0 end)) as 'w2',    sum(case when w.weekno = 3 and ww.weekid is not null then worked else 0 end)) as 'w3',    ........ etc  from tbl_week w left join tbl_weeks_worked ww on ww.weekid = w.weekid where w.start_date >= start and w.end_date <= enddate  group by userid; 	0.00322255310517384
7352966	6312	t-sql, select first row of a set	select t.id, t.hash, t.otherid     from (select id, hash, otherid, row_number() over(partition by hash order by id) as rownum               from yourtable) t     where t.rownum = 1 	0.000342797694223226
7354053	4605	concatenating a description together when using a group by clause	select      sum(b.amount_curr) amount,      group_concat(b.description) descr from acctg_invoice a inner join acctg_invoice_item b on a.acctg_invoice_id = b.acctg_invoice_id group by a.acctg_invoice_id 	0.347808479955275
7354466	26611	finding identity column in a table	select name    from sys.columns    where [object_id] = object_id('dbo.iv00101')    and is_identity = 1; 	0.0017529406916386
7355421	39860	subtract values from first and last row per employee in sql server 2000	select minmaxdate.emp_id,         last.miles - first.miles,         last.gallons - first.gallons  from   (select emp_id,                 min(datime) firstdate,                 max(datime) lastdate          from   emp_data          group  by emp_id) minmaxdate         inner join emp_data first           on first.emp_id = minmaxdate.emp_id              and first.datime = minmaxdate.firstdate         inner join emp_data last           on first.emp_id = minmaxdate.emp_id              and last.datime = minmaxdate.lastdate 	0
7356900	25509	getting data from two tables?	select dname, loc, (select count(ename) from emp where deptno = dept.deptno) as number_of_people  from dept; 	0.000651548814979783
7357313	9521	omitting primary key from php mysql result	select column1, column2, column3 from table 	0.00582944932039157
7357796	21960	count number of rows with distinct value in column in t-sql	select parentdeviceid, count(*) as [count] from controlsystemhierarchy group by parentdeviceid 	0
7358571	19594	mysql, set value of column "id"(auto increment ) as an default value for column b	select ifnull(message_reference_id, message_id) as message_reference_id from your_table 	0
7361109	30500	php - unix timestamp	select * from table where stamp > unix_timestamp() - 24*3600 	0.0112198404157301
7362144	23245	position of the column in the index	select c.relname, a.attname, a.attnum  from pg_attribute a inner join pg_class c on c.oid = a.attrelid  where c.relkind = 'i'   and c.relname = 'beds_pkey'   and a.attnum > 0 	0.00464251547983283
7362190	2295	returning a new row for each record	select'facebook' source, id from bla_facebook_accts where (user_id = 12) union select 'linkedin' source, id from bla_linked_in_accts where (user_id = 12) union select'twitter' source, id from bla_twitter_accts where (user_id = 12) 	0
7362312	27170	is there a function/feature in sql server to determine if a table has any (recent) activity?	select          last_user_seek,         last_user_scan,     from         sys.dm_db_index_usage_stats     where         database_id = db_id() and object_id = object_id('tablename') 	0.00422654895857311
7362439	23062	how to filter values from a query against a sql server database?	select      complist.compname,     complist.compid,     componenttrace.remark,     complist.mcid,     complist.station,     complist.slot,     complist.amount - complist.used - isnull(complist.correction,0)  from     complist inner join componenttrace on complist.compid = componenttrace.compid  where     complist.mcid = 1004     and upper(complist.station + '.' + complist.slot) like '%1.1%' order by     complist.compname, complist.compid 	0.00510231167725422
7363773	29986	sql - programmatically rename all table columns in a database	select 'exec sp_rename ''' + quotename(table_schema)    + '.' + quotename(table_name) + '.'    + quotename(column_name) + ''', '''    + table_name + '_' + column_name + ''', ''column'';' from information_schema.columns where column_name not like table_name + '[_]%'; 	0.000666302761303333
7364088	22881	renaming a result	select     case pizza       when 'cheese' then 'cheese'       when 'four cheese' then 'cheese'       when 'extra cheese' then 'cheese'       else pizza    end as pizzatype,    count(*) as pcount from pizzatable group by pizzatype 	0.113685014785463
7364308	3776	mysql query of one table that is a many to many relationship to another table	select t2.* from table1 t1 inner join table2 t2 on (t1.id = t2.tbl1_id) where t1.date = '2011-08-20' 	0
7365120	12361	converting sqlite to postgres	select count(*),     date_part('hour', sentdate ) as hour from latency l,     contacts me where l.lat < 1     and date_trunc ('day', sentdate) > date ( '2009-01-01' )     and date_trunc ('day', sentdate) < date ( '2011-02-01' )     and ( me.id = l.replyuid         or me.id = l.senduid ) group by date_part('hour', sentdate ) order by hour asc; 	0.472046430721462
7365724	27246	how to compare variable amount of days using unix timestamp (stored as int) 	select * from your_table where ftimestamp_column > unix_timestamp(date_sub(now(), interval 5 day)); 	0
7367240	4708	mysql select count by value	select date,        count(*),        count( if( value = 1, 1, null ) ),        count( if( value = 2, 1, null ) ) from my_table 	0.0210159879190671
7368360	15274	moving mysql columns to another table	select u_id, field_1 from table_1;    (while results)    {             select field_2 from table_2 where u_id = ?;               insert into table_new values (u_id, field_1, field_2);   } 	0.000420841831822287
7368568	4111	finding top scores over multiple columns	select * from (   select team, score1 from tbl   union all select team, score2 from tbl) a order by score1 desc limit 5; 	0.00151921283741879
7368672	13824	selecting all rows after a row with specific values without repeating the same subquery	select * from (   select row_number() over (order by c1, c3) myorder, c2, c3         ,case when c2 = "foo" and c3 = "bar"               then row_number() over (order by c1, c3)          end target_rn   from t1, t2   where condition   order by conditions ) where myorder > target_rn; 	0
7370165	16151	calculate the number of hours a ticket is open, using sql	select * from ( select datediff(hour,        convert(datetime,          convert(datetime,            convert(nvarchar, cast(complaintdate as datetime), 101)         ) + '' +         convert(varchar, complainttime, 114)       ),        dateadd(mi, 330, getutcdate())     ) as [open hours] from complaintregister ) t where t.[open hours]>500 	5.38909407989473e-05
7372998	23977	problem in reading data from multiple tables	select memberships.cust_id from memberships, bookings where    memberships.cust_id  = bookings.cust_id union memberships.cust_id from memberships where  not exists (select bookings.cust_id from bookings where memberships.cust_id  = bookings.cust_id) 	0.018041852541224
7373635	23589	mysql select based on the selects	select group_id, group_concat(user_id order by user_id) as user_id_list from group_user group by group_id having user_id_list = '3,7,100' 	0.0041501086800995
7374221	24658	effiecient way to pull post for many threads?	select * from post where thread in @ls 	0.00897901000917266
7375373	27286	select difference between row dates in mysql	select   id,   date,   datediff(     (select max(date) from atable where date < t.date),     date   ) as days_since_last from atable as t 	0.000250917593491752
7376072	38666	postgresql calculate sum of a resultset	select sum(b) from sample_table where a = 5; 	0.0034350357886255
7378338	19582	sql populating with distinct data and a sequence	select cr.plate, car_id_seq.nextval from (select distinct plate from cars_rentals) cr 	0.0706200825159932
7379423	1418	sorted difference between two columns	select (sale_price - buy_price) as profit     from table_name order by profit desc 	0
7380331	14705	getting the i-th to j-th rows within an ordered mysql query	select * from t where j = k order by l limit 20, 20 	0.00449774585667611
7381644	12263	get duration between records from separate tables by date	select avg(timediff(b.`date`, a.`date`)) from quotes a inner join (   select quote_id, min(`date`) as `date`    from responses   group by quote_id) b    on (b.quote_id = a.quote_id) 	0
7381737	26658	how to incorporate the next result of a query in the query in postgresql?	select *   from  (       select (select max(level) from students "inner" where "inner".level < "outer".level) as level            , sum(case when grade = 'pass' then 1.0 else 0.0 end) / count(*)                as percentage         from students "outer"     group by level     union all       select max(level) as level            , null       as percentage         from students ) mylevels  where level is not null 	0.00164659683170366
7382217	32879	sql query for retrieving records separated by seconds	select * from my_table as t1 inner join my_table as t2 on (     t1.recordid < t2.recordid     and     datediff(second, t1.datefield1, t2.datefield1) <= 30     and     t1.textfield1 = t2.textfield1     and     t2.textfield2 = t1.textfield2 ); 	0.000126526415741905
7382815	38873	extracting rows from a table which fit conditions referring to another table in oracle sql	select distinct tb2_id from table2 t2 left join table1 t1 on t1.tb1_id = t2.tb2_id and t1.condition = t2.condition where t1.tb1_id is null; 	0
7382816	16412	how can i select a category and the first picture associated with that category?	select    category.*,    (     select top 1 pictures.picturefilepath      from pictures      where category.categoryid = pictures.categoryid    ) from   category 	0
7383667	21077	how to immediately use the result of computation in another computation within mysql query	select s, s + 600 as y from (select sum(x) as s from table); 	0.039255320092558
7384096	7238	get latest 3 comments for a list of posts	select p.id, p.userid, c.id, c.userid   from posts p   join (     select c1.*, count(*) rank from comments c1     left join comments c2       on c2.relid = c1.relid and c2.id <= c1.id     group by c1.relid, c1.id     ) c   on p.id = c.relid where rank < 4 	0
7384142	1088	mysql selection	select x.userid from  (select userid, count(distinct color) c from colors where color in ( 'red', 'blue' ) group by userid) x  where x.c = 2 	0.380343588908658
7385066	18423	mysql how to "join" two queries	select uid, uri from table1, table2 where table1.fid = table2.fid 	0.127439191484723
7385213	12095	mysql choose to join table where record exists	select     ci.item_name, ci.item_id, if(c.catalog_name, c.catalog_name, cd.catalog_name) from catalog_items as ci    left join catalog as c    on c.catalog_id = ci.catalog_id    left join catalog_draft as cd    on cd.catalog_id = ci.catalog_id 	0.0189186789651535
7385622	23553	more efficent way to select number of occurences in a string	select sum(c) from (        select count(*) as c        from master..spt_values as n        where n.type = 'p' and              n.number between 1 and len(@number)        group by substring(@number, n.number, 1)        having count(*) > 1      ) as t 	0.00107215467294725
7386716	25314	sql server database and android	select * 	0.618463987354259
7390185	32065	mysql query for selecting time periods	select * from your_table where `time` between date_sub(now(), interval 1 day) and now(); 	0.00715612010208535
7390486	24473	mysql join results different in php?	select table_name.field, table_name.field2, other_table_name.field1 	0.114899885148254
7390690	27086	join two tables field based on the same id?	select t21.name, t22.name from table1 t1  inner join table2 t21 on t1.id_1 = t21.id inner join table2 t22 on t1.id_2 = t22.id 	0
7392149	12689	in php, how do i ask a mysql database to retrieve the most recent record that matches a certain value?	select * from yourtable order by date desc where name='steve' limit 1 	0
7392457	9241	get each 7th record	select *      from (           select "date", "read_count",                   row_number() over (order by "date" asc) as n             from "articles_stats"           ) x    where x.n % 7 = 0 order by x."date" asc 	0
7395571	30773	order by something, then random?	select photo.sort_order,         profile.description is not null as desc_order,         profile.description,         rand() as r  from         photo photo, profile profile order by          photo.sort_order desc,          desc_order desc,          r 	0.0911914594972021
7395596	37898	sql - count unique values of a column produced from a query	select file_name, count(*) from downloads_downloads group by file_name; 	8.11752308151325e-05
7397936	15444	how to set 2 decimal places in sqlite select statement	select _id, name, round(amount,2) from accounts 	0.00897902076727614
7400810	20493	mysql table name with string concate?	select t.table_schema , t.table_name from information_schema.tables t , otherdb.table o where t.table_name like concat('%',o.table_name_prefex) and .... 	0.0693918090686707
7403304	25280	mysql distinct while selecting other column	select id, sum(total_hits)  from (     select * from tbl1 union      select * from tbl2 union      select * from tbl3 union      select * from tbl4 ) as sumtbl group by id order by sum(total_hits) desc limit 50; 	0.000983788092203102
7403667	36278	mysql create function for range of values with equivalent numbers	select (         case           when pos < 2 then 10           when pos >= 2 && pos < 4 then 7           when pos >= 4 && pos < 11 then 5           when pos >= 11 && pos < 31 then 2           else 1         end ) 	0.0427460046966553
7404047	13998	sql - get rows where one column is a certain percentage greater than another	select inventorylevel,        inventoryalert   from yourtable where inventorylevel > 1.25 * inventoryalert  	0
7405432	18764	can you apply limit on mysql before left join another?	select * from     (select * from table_1 limit 5) as subq     left join table_2 as subq.id = table_2.id where 1 	0.360325444969635
7406108	15246	mysql subquery selection	select c.*, sub.*  from    connections c    inner join    (    select *,     open_hour_from - ((open_hour_day - 1) * 24 * 60) as timefrom,      open_hour_to - ((open_hour_day - 1) * 24 * 60) as timeto,     group_concat(open_hour_day) as days     from `open_hours` where open_hour_connect_id = 2     group by timefrom, timeto     order by days) sub  on c.days = sub.days 	0.720138186788619
7407864	34402	mysql select union for different columns?	select id, name, date, null as userid, 'a' as recordtype from table1 union all select id, name, null , userid, 'b' as recordtype from table2 	0.00710083022975579
7408269	15007	sql coalesce entire rows?	select id, name, email, etc from tbl_employees       where id in (select id from tbl_peopleinid)  union all  select id, name, email, etc from tbl_customers       where id in (select id from tbl_peopleinid) and             id not in (select id from tbl_employees) 	0.0401311894800741
7408658	10705	mysql multiple where conditions on same field in a join	select a.order_id, b.*, c.* from orders a  left outer join orders_requests b on b.order_id = a.order_id left outer join orders_requests c on c.order_id = a.order_id where b.requests = 'rush processing' and c.requests = 'free shipping' 	0.0117968226231271
7409472	21148	mysql python combine results	select * from urls, sites where urls.site_id = sites.id and sitename like ? 	0.213446372594906
7410196	7990	tips to make only one query?	select    s.username as sender,    r.username as recipient,    msg from    messages m join users s on (m.sender = s.id)    join users r on (m.recipient = r.id) 	0.0200564708998728
7410406	7911	working with dates in sql	select * from event order by abs(datediff(event_date, now())) limit 4 	0.663291706756261
7413130	985	need help using unique keys on several columns	select ... from languages where nid=1 and language="chinese" 	0.033469201706976
7413849	19867	select from 3 table	select t1.id as t1id, t1.name, t1.lastname,      t2.name as t2me, t2.value as t2ve, t3.name as t3me,      t3.value as t3ve from table1 t1  left join table2 t2 on t1.id = t2.idtable1  left join table3 on t3.idtable1 = t1.id 	0.00516366128863273
7414626	36009	how to look up the information using another table as a reference	select up.uid, sum(p.pointvalue) total_points      from userpoints up left join points p        on up.pid = p.id     where up.uid = 5; 	0.00118774854949756
7415426	32242	how do i join two tables to get statistics	select a.name, count(distinct b.city_id)  from cities a join members b  on b.city_id = a.id   group by b.city_id 	0.0021013280874512
7415698	2632	skip-lock-tables and mysqldump	select sql_no_cache * from my_large_table 	0.763817035491173
7416929	22968	count all items in a "trash bin" with a mysql query	select sum(albums_and_items.cnt) from (   select   case a.status     when -2     then (       select count(*)       from gallery_item as i       where i.fk_album = a.id     ) + 1     else (       select count(*)       from gallery_item as i       where (i.fk_album = a.id) && (i.status = -2)     )   end as cnt   from gallery_album as a   group by a.id ) as albums_and_items 	0.0113073084349344
7417873	2783	select all users with one role and one role only - many 2 many relationship	select users.*, count(*) as role_count,         sum(case roles.name when 'user' then 1 else 0 end) as isuser from users join roles_users  on users.id = roles_users.user_id join roles  on roles_users.role_id = roles.id group by users.id having count(*) = 1 and sum(case roles.name when 'user' then 1 else 0 end) = 1 	0
7419243	13601	multiple subqueries and conditions	select      s_date     ,case col3 when 'doit' then col1 else col2 end as selection from (     select         sdate        , col1        , col2        , col3     from foo     where s_date > getdate()  ) as sub 	0.576640249914359
7419773	17852	sql query from 3 tables	select     * from     primarysta a inner join     typecodes b on     a.tid = b.tid inner join     mutualaid c on      a.tid = c.tid     and c.tid = b.tid where      a.id = %s  	0.0313101408121014
7420463	36489	mysql query with table that may or may not have data	select *     from transactions t         left join bill b             on t.userid = b.userid     where month(date) = '09'         and year(date) = 2011     (...)     order by t.id_transaction 	0.46778283852829
7420995	18170	latest time of a date in sql	select * from table where rec_create_timestamp in (       select        max(rec_create_timestamp) as rec_create_timestamp     from        table     where        to_char(rec_create_timestamp, 'yyyymmdd') = '20110831' ) 	0.00026508693582808
7421860	8285	converting from integer to binary and back in sql server	select convert(bigint, convert(binary(30), convert(bigint, 2691485888))) 	0.0800157248004153
7422748	38063	select the biggest value	select department_name from          ( select department_name, count(*) number_of_employees             from department d, employee e            where d.department_id = e.department_id            group by department_name            order by 2 desc )    where rownum = 1 	0.00351581980569932
7424514	28623	how to query a table with cardinality one to display all the pk while also displaying the matching elements in a table with fk	select ..... from a left outer join b on (a.apkcolumn=b.afkcolumn) 	0
7424651	23567	trimming characters from data in mysql	select game_id, substring(game_id, 4, 4) as year_id from your_table 	0.0339227760128623
7426456	6548	best way to get most relevant data from table mysql	select * from entry where correct_answers = 5 	0
7426589	10547	seek row in sql server	select t.*,      (select count(w.*)       from dbo.getwordlist(t.text) w      where w.word like '%criteria%') as count  from mytable t  where t.text like '%criteria%' 	0.206301741791332
7428174	24611	sqlite3 select from empty table = no select?	select ifnull((select _id from empty_table limit 1), 1) 	0.00442548101408247
7429715	11602	removing padded zeroes in hexadecimal column	select  replace(rtrim(replace('c700dbbf000000','0',' ')),' ','0'); 	0.256877817367354
7431708	1484	select specific columns, along with the rest	select t.*, unix_timestamp(t.start) as start, unix_timestamp(t.end) as end ... 	0
7432178	9676	mysql sum columns accros multiple tables	select sum(t.qty) as total_qty     from (select qty from mc           union all           select qty from amex) t 	0.00807126646993826
7432784	18999	mysql: how to select top 10 users of the last 24 hours for a ranking list (and avoid multiple user entries)	select t1.*, users.username from (select results.* from results where results.user_id != 0 and results.created >= date_sub(now(),interval 24 hour) order by wpm desc) t1 join users on (t1.user_id = users.id) group by t1.user_id order by wpm desc limit 10 	0
7433009	24557	"secondary" query	select      `num_code`,      `name`,      (         select count(*)          from `answers`          where `num_code` = `people`.`num_code`     ) as `answercount` from     `people` order by     `name` 	0.244908874981264
7436547	28339	mysql query and php: how to know how many results per each "where" condition	select *,        sum(case when xxx like '999' and yyy rlike '[0-9]88[0-9]' then 1 else 0 end) as count999,        sum(case when xxx like '111' and yyy rlike '[0-9]23[0-9]' then 1 else 0 end) as count111     from numbers     where      ( xxx like '999' and yyy rlike '[0-9]88[0-9]')      or      ( xxx like '111' and yyy rlike '[0-9]23[0-9]') 	0.000262687002682489
7436973	25393	use group by in mysql and return identity of the row	select id from ( select id, type        from table        order by price desc) as h group by type 	0.00292811978039362
7437619	31490	counting how many times a value appeared	select name, count(1) from table group by name; 	0.000385766818370795
7438022	32706	oracle combine multiple rows into one with distinct title	select  courses_id,  rtrim ( xmlagg (xmlelement (c, requisite_type_title || '' || reqtexts || ''  ) order by   mino).extract (' from ( select  courses_id, requisite_type_title, min (order_num) mino,  rtrim ( xmlagg (xmlelement (c, condition_title || '' || req_text || ''  ) order by   order_num).extract (' from cos_requisites where courses_id = '1175' and requisite_type_title !=  'corequisite' group by courses_id, requisite_type_title )  group by courses_id; 	7.1731968181642e-05
7438699	7061	select values from a column into a pipe-delimited row	select result = stuff((select '|' + columna     from dbo.[table]     for xml path('')), 1, 1, ''); 	0
7438992	38550	what is the most efficient way to pull parent and child items (ordered) from the same table in mysql?	select post_id,parent_id from table      where coalesce(parent_id, post_id) in (         select post_id from table              where parent_id = ''              order by date desc limit n         )     order by coalesce(parent_id, post_id), parent_id desc, date desc; 	0
7440180	11761	select query sort problem	select m.studno, m.studname from mastertable m left join transacttable s on m.studno = s.studnoo  and  m.studname = s.studname  order by s.studno 	0.696273092370088
7442212	10200	get the closest date if it doesn't exist in the inputted date range	select * from tbl where date between (select date from tbl where date < lower_range limit 1 ) and upper_range 	0
7442961	5605	how do i ask my table columns to be printed in a alphabetical manner	select column_name, data_type, is_nullable, column_default   from information_schema.columns   where table_name = 'foo'   and table_schema = 'foo_schema'   order by column_name; 	0.148880587503754
7447675	1641	duplicates removing	select           min(a) as a         , b     from      (         select a = 1, b = 30         union all          select a = 2, b = 50         union all          select a = 3, b = 50         union all          select a = 4, b = 50         union all          select a = 5, b = 60     ) t group by b     order by a 	0.193745419823937
7452501	2618	postgresql turn null into zero	select coalesce(max(column), 0) from mytable; 	0.0278368774882728
7456450	3689	selecting rows that fail to match this join's criteria	select      asi.`street name`,      asi.`street number`,      asi.evaluation from    `asindex` asi ledt join   `tblevaluations` ev on asi.`streetname` = ev.`street name`       and asi.`streetnumber` = ev.`street number` where asi.`evaluation` = 'blue'    and ev.`street name` is null; 	0.0545854117090442
7457868	8601	how can i join these 3 tables?	select a.* from   table_a a        left join (select c.table_a_id, b.category                   from   table_b b,                          table_c c                   where  c.table_b_id = b.id) d                   on     a.id = d.table_a_id where d.category = '$_get[term]' or    match(a.title) against('$_get[term]' in boolean mode)  limit 0,5 	0.201286357301408
7458524	17148	using count and max in sql query	select top 1 a.coursecode, count(*) from course a inner join enrollment b on (a.coursecode=b.coursecode)  group by a.coursecode order by count(*) desc 	0.310710302755681
7459156	32087	sqlite query: selecting the newest row for each distinct contact	select * from (select * from messages order by messagetime) group by contactid 	0
7460969	15050	mysql query to find top items	select item_id, sum(count) from order_list group by item_id order by sum(count) desc limit 0,10 	0.00188660473487231
7461295	3484	find how many (googlemap) polygons near x distance of a point	select user_id,latitude,longitude,    contains(           polyfromtext( 'polygon((-26.167918065075458 28.10680389404297, -26.187020810321858 28.091354370117188, -26.199805575765794 28.125,-26.181937320958628  28.150405883789062, -26.160676690299308 28.13220977783203, -26.167918065075458 28.10680389404297))' ),           pointfromtext(concat("point(",latitude," ",longitude,")"))    ) as contains from user_location 	0.00612710623050377
7461967	37958	getting first 5 digits of a database stored number in the query	select * from table where from_unixtime(unix_timestamp_field,'%y-%m-%d') = curdate() 	0
7462677	19421	adding a restriction to mysql count() to only consider a maximum of 3 rows per day?	select 5*sum(if(num_content>3,3,num_content))  from ( select date(content_timestamp) as dt, count(id) as num_content from content      where author = 'newbtophp' group by date(content_timestamp) )a 	0
7463942	18317	with mysql can i have a column generated with an autoincrement value	select   @rownum:=@rownum+1 rownum,           id,          application_id,          3rd_column_to_generate  from     semesterapplication,          (select @rownum:=0) r where    semesterapplication.semester.id = 1  order by semesterapplication.modified 	0.0241725719263113
7464484	36395	how to get count for each type of record in a result set	select venue, count(*) from (your_query_here) t group by t.venue; 	0
7464713	29342	mysql query to display everything from a table but not a certain word	select replace (m.title, 'the', '') movietitlefordisplay, m.* from movie m 	0
7465759	7417	sql query involving specific counts	select p.id, p.name, m.loaner, count(*) from person p     inner join loan l on p.id = l.id    inner join money m on l.acct = m.acct    group by id, name, lower    having count(*) > 4 	0.16341954425812
7466289	18615	apply where after group by	select thread_id from table group by thread_id having max(date) < 1555 	0.544793715529378
7468484	38190	sql query for top 5 results without the use of limit/rownum/top	select * from (      select col1,             col2,            row_number() over (order by some_col) as rn     from the_table ) t where rn <= 5 	0.0270474465281025
7470138	41303	concatinating rows specific field and displaying the concatinated value in select query-sql	select distinct absence.empid, reasons.allreasons       from absence       cross apply ( select reasontext + ' ,'                      from absence emp2                     where emp2.empid= absence.empid                     for xml path('')  )  reasons ( allreasons) 	6.98188796173059e-05
7470199	7242	msql select and group from db where team_1 and team_2 are the same but reversed in the entry	select field1, field2, match_date, ......        ,greatest(team_1,team_2) as team1        ,least(team_1,team_2) as team2        ,field6, field7 from fixtures group by team1 order by match_date limit 10 offset 0; 	8.87188014484865e-05
7471625	31162	fastest check if row exists in postgresql	select exists(select 1 from contact where id=12) 	0.0142013335202797
7473109	14317	how to select the time between now() and last row inserted?	select min(now() - timestamp) from table 	0
7473483	38106	two select at a time in combo box - how to solve it?	selected="selected" 	0.424654260558395
7473592	9325	weighted search algorithm for php	select *, (red * @rw) as w1, (green * @gw) as w2, (blue* @bw) as w3, (yellow * @yw) as w4, (w1 + w2 + w3 + w4) as result    from items order by result desc; 	0.305542072524881
7474016	40703	sql query to return records that are exclusively of one type	select * from exampletable where linkid not in  (     select linkid     from exampletable     where linktype != 'a' ) 	0.000119341567916347
7474051	19156	fastest way to get number of records in mysql	select count(id) as total from table; 	7.3712524836391e-05
7474617	22745	select most recent items with dup values	select t1.*  from   cron_schedule t1    inner join (select params,      cs.cron_action_id,      max(time_entered) as time_entered      from cron_schedule cs      inner join cron_actions ca      on cs.cron_action_id = ca.cron_action_id      where  time_executed = 0      group  by params, cron_action_id) as t2    on t1.params = t2.params      and t1.cron_action_id = t2.cron_action_id      and t1.time_entered = t2.time_entered    inner join cron_actions ca2    on t1.cron_action_id = ca2.cron_action_id    where  t1.time_executed = 0 	0
7475332	26320	mysql index for group by / order by	select c1, sum(c2)  from table  where c4 = 2011  and c5 = 0  and c6 in (6,9,11) and c3 is not null    group by c1 	0.603531846541833
7476677	21384	how to get the last 4 digits of ssn	select right('123456789',4) 	0
7477969	11400	calculate the words number in a view in mysql	select   myid,   sum(length(text)-length(replace(text, ' ', ''))+1) from table group by myid 	0.00106487868628612
7478645	25164	sqlite3 select from multiple tables 'where' stuff	select preschoolers.first_name, favorite_gooey_treats.name as treat from preschoolers join favorite_gooey_treats on preschoolers.favorite_treat = favorite_gooey_treats.id where preschoolers.age > 15; 	0.0668423706586991
7478710	22008	ordering by count() in sql	select referrerid,        count(id) as num from   users group  by referrerid order  by case             when referrerid = 0 then -1             else count(id)           end desc; 	0.317385879511206
7478959	8472	sum datediff and group by	select t.name, sum(datediff(hh,t.date_due,t.date_start))as donation_hours  from tasks t   group by t.name order by name 	0.281598588226948
7480611	2984	select highest priority row	select [key],        value from (select [key],              value,              row_number() over(partition by [key]                                 order by priority desc) as rn       from yourtable) as t where rn = 1 	0.000282171509065266
7482882	2034	how to add columns data in sql server?	select sum(quantity) from table_name group by productcode 	0.00713884716287734
7484495	17615	mysql query for getting last row on the basis of category	select cat.value, ins.servicestatus from incidents ins, category cat where ins.scid = cat.id group by cat.id; 	0
7484620	29073	inner join and select of field with less string length	select cpc from cpc_options inner join cpc_targets where targeted_name like '%country%' and target_id = cpc_id  order by length(targeted_name) asc limit 1; 	0.0602854927332919
7485008	3050	selecting duplicate entries from a table and getting all the fields from the duplicate rows	select day2,count(*), group_concat(id)     from resultater     group by day     having count(*)>1; 	0
7485418	40397	exclude mysql result rows where count is zero	select      count(case when u.account_new = 1 then u.user_id end) as new_user,      count(u.user_id) as all_users,      c.country_name as country  from users u, countries c  where u.country_id = c.country_id  group by u.country  having count(case when u.account_new = 1 then u.user_id end) > 0 	0.00529270716751749
7485505	29820	need to perform a select which unrolls data	select    doc_id,    doc_date as from_date,   (lead(doc_date) over (partition by product_id order by doc_date) ) - 1  as to_date,   product_id,    price from   product_table 	0.306285897802041
7485671	25366	mysql "field like array" functionality	select id from sometable where substr(zipcode,0,5) in (select substr(zip,0,5) from someothertable) 	0.660723764505421
7486064	24811	get one day and monthly sum of amount from one table in sql server	select     currentdayamount = (                          select                             sum(c.amount)                          from                             charge c                          where                             c.edate between '09/16/2011' and '09/17/2011'                        )   , totalmonthlyamount = (                            select                             sum(c1.amount)                            from                             charge c1                            where                             c1.edate between '09/01/2011' and '09/20/2011'                          ) 	0
7486077	9785	is this the same as join in mysql query?	select cute_news.category, cute_news.id, cute_story.short, cute_story.post_id, cute_news.date, cute_news.url, cute_news.title  from cute_news  inner join cute_story on cute_story.post = cute_news.id where category like '10%'  order by date desc limit 0,35 	0.656077318839414
7486083	22783	top 2 results on group by statement?	select name, score, rnk from  (       select name, score         , @currank := if(@name=name, if(@score=score, @currank, @currank + 1), 1) as rnk         , @name := name         , @score := score       from  (             select name, score             from record               cross join ( select @currank := 0, @name := '', @score := -1 ) as z1             order by name, score desc             ) as r       ) as z where rnk <= 2 	0.0294762148128163
7487483	18735	receiving duplicate answers when query a database	select size, color_name, quantity, sizes.size_id, colors.color_id   from quantities     inner join colors on quantities.color_id = colors.color_id     inner join sizes on quantities.size_id = sizes.size_id where product_id = ? and quantity > 1 	0.243572160224193
7487853	36970	returning one result set from a stored procedure	select id, id1, id2 from (   select @rank:= @rank+1 as rank1, t1.id, t2.id1, t2.id2 from t1    straight join (select @rank:= 1) r   left join (select @rank as rank2, id1, id2 from t2 limit 1000) s     on (rank1 = rank2)   ) s1 	0.0172705986135035
7487992	39304	how to combine two columns in from two t-sql select?	select t1.params as a, t2.params as b from table1 t1  inner join table1 t2 on  @ctid = '1' and @id = '2' 	0
7488006	22479	how to know/ check a requested page is a sub row or sub-sub row in a db?	select  p.pg_id,  p.pg_url, p.parent_id, p2.pg_id as 'parentpageid', p3.pg_id as 'grandparentpageid' from root_pages as p left join root_pages as p2 on p.parent_id = p2.pg_id and p.pg_id <> p2.pg_id left join root_pages as p3 on p2.parent_id = p3.pg_id and p2.pg_id <> p3.pg_id where p.pg_id = '4' 	0.00210404491867878
7488262	23698	transposing rows to columns using self join	select categoryid,         min(switch(yourtable.flag = 'a',value)) as avalue,        min(switch(yourtable.flag = 'm',value)) as mvalue,        min(switch(yourtable.flag = 'p',value)) as pvalue from yourtable group by categoryid 	0.0349388320415061
7488610	8461	count on a calculated row in mysql	select sum(case when greatest(ctr_t0,ctr_t1,ctr_t3) = ctr_t0 then 1 else 0 end) as ctr_t0_count, sum(case when greatest(ctr_t0,ctr_t1,ctr_t3) = ctr_t1 then 1 else 0 end) as ctr_t1_count, sum(case when greatest(ctr_t0,ctr_t1,ctr_t3) = ctr_t3 then 1 else 0 end) as ctr_t3_count from (select .... ) as t 	0.00569037642721692
7489085	19125	select sum and multiple columns in 1 select statement	select sum(a) as car,b,c from toys  group by b, c 	0.00836020129624684
7489810	30284	php, check the difference in between multiple dates, how to?	select @previous := null; select datediff(`date`, @previous) as diff, @previous := `date` from `test` where diff < 1 	0.00013505963301753
7490169	25213	average of counts	select acc_id, data id, avg(total_ar_count) as avg_ar_count, avg(total_fr_count) as avg_fr_count...   from table  group by acc_id, data_id 	0.0024279002096595
7490544	32729	how do i make three tables share the same field as primary key in mysql?	select cc.part_no, cc.qty, cc.qty_time                  , ca.add_qty as qty_added, ca.add_time as time_added                  , cp.pull_qty as qty_pulled, cp.pull_time as time_pulled from cartons_current cc inner join cartons_add ca on (ca.part_no = cc.part_no) inner join cartons_pull cp on (cp.part_no = cc.part_no) where cc.part_no = '124' 	6.09094489576468e-05
7491160	17954	problem with sorting comments in date order	select b.*, max(c.date_added) as date from books b     left join comments c on (b.id = c.book_id)     group by b.id     order by max(c.date_added) desc      limit 5 	0.349748060040328
7492003	31651	mysql not in array	select * from table where find_in_set( this_id, '$this_id' ) = 0 	0.406729448990842
7492066	31071	mysql count() group by subquery(?) to count purchases on multiple items per month	select year(purchase_date) as year, date_format(purchase_date, '%m') as month, count(item_id) as cnt from items_purchased group by year(purchase_date), month(purchase_date) order by year, month, cnt 	0
7496160	22864	mysql sql query to compare integer and string	select c.id , c.name, count( * ) as quotescount  from categories as c  left join quotes  as q on (find_in_set(c.id,q.category_ids)) group by c.name 	0.0446090102858114
7497305	40343	db: find table name by id	select a.*,b.type  from article a  inner join      (select id,'news' as type      from news      union      select id,'courses' as type      from courses) b  on a.id=b.id; 	0.000386804540228001
7497481	8420	how to group by date,date's format is nvarchar	select left(date_col,10) as mydate, count(*)  from your_table group by left(date_col,10); 	0.430735729810424
7499641	17805	mysql searching, condition from another table	select p.* from product p inner join productgroup pg on (pg.id = p.productgroup_id) where (p.name like '%test%' or p.ean like '%test%')  and p.closed=0 and pg.closed=0 	0.00219534835473313
7499876	14740	find rows without relations in sqlite3?	select homes.*  from homes left join members on (members.home_id = home.id) where members.home_id is null 	0.0099023492259912
7500134	30463	only n records for every x field	select i1.* from your_table i1 left join your_table i2   on (i1.city = i2.city and i1.id > i2.id) group by i1.id having count(*) < 2 order by city, id; 	0
7502507	28341	values from two group by select statements into one	select      l.[methodid],      sum(case when datetime between @from and @to then 1 else 0 end) as count,     sum(case when datetime between @before and @from then 1 else 0 end) as previous from      [log] l where      l.[datetime] between @before and @to      and l.[methodid] in @methodids  group by      l.[methodid] 	7.36989548440494e-05
7502881	15515	joining query from two tables	select * from  ( select      serial_number,      system_id,      date_time  from      acp_parts ap  union all select      serial_number,      system_id,      date_time  from      acp_parts  test_results tr ) order by serial_number, date_time 	0.00397934255528667
7502982	412	sql server 2005 statements returning the same results	select     pubname as publication     ,count(*) as total     ,'$' + convert(varchar(12), sum(cast(price as decimal))) as price from [secureorders]  where datetime >= dateadd(hh, -24, getdate()) group by pubname 	0.236539630399379
7503089	25871	oracle - getting 1 or 0 records based on the number of occurrences of a non-unique field	select n_rec, my_field from (select n_rec, my_field         , count(*) over (partition by my_field) as counter     from mytable     where my_field = ?) where counter = 1 	0
7503608	13156	query transactions that occured only at a certain time	select distinct usercode,             transactionid,             action,             transactionhour,             source,             rxnumber,             description,             masterpatientid,             facilitycode,             administrationtime from    (   abc.tl tl        inner join           abc.s_view s_view        on (tl.rxnumber = s_view.rxnumber))    inner join       abc.pv patientvisit    on (tl.masterpatientid = pv.masterpatientid) where (tl.usercode not in ('abc'))    and (tl.action in ('a', 'dc'))    and (tl.transactionhour between to_date('2011/07/01 00:00:00', 'yyyy/mm/dd hh24:mi:ss') and to_date('2011/09/30 23:59:59', 'yyyy/mm/dd hh24:mi:ss')    and to_char(tl.transactionhour, 'hh24mi') = '2300'  	0.000115461704957064
7504043	26911	query to select last order (entry) of every product belonging to user that's not returned	select userid,productid from <table> group by userid,productid having sum(case cast(isreturned as int) when 0 then 1 else 0 end)-sum(cast(isreturned as int))>0 	0
7504419	6840	conditional from sum() of another table?	select `transaction`.id as `id`,    `transaction`.amount as amount,     sum(payment.amount) as payment,     `transaction`.amount - sum(payment.amount) as balance from `transaction` left join payment     on payment.`transaction` = `transaction`.id group by payment.`transaction` having balance > 0; 	0.00118771104664891
7505045	24888	mysql in-operator must match all values?	select *      from table1          inner join table2              on table1.threadid=table2.threadid      where table2.threadcontributor in ('1','52512')     group by table1.primarykey     having count(distinct table2.threadcontributor) = 2 	0.00821437549240793
7505644	16310	sql server convert datetime to int in query	select datediff(second, 0, '12:00:00') 	0.348906663125632
7505715	23214	case when exists then select	select name = coalesce(c.customer_name, o.other_entity_name)   from dbo.mainentity as m   left outer join dbo.customers  as c on m.something = c.something   left outer join dbo.othertable as o on m.something = o.something; 	0.632275140629268
7505936	40429	geolocation distance sql from a cities table	select *    from cities a  where :mylatitude >= a.latitude  - :mykm/111.12    and :mylatitude <= a.latitude  + :mykm/111.12    and haversine(:mylatitude,a.latitude,:mylongitude,a.longitude, 'km') <= :mykm  order by haversine(:mylatitude,a.latitude,:mylongitude,a.longitude, 'km') 	0.00972469068182188
7506841	20389	query to find users that haven't paid?	select * from booking where booking_id not in ( select bookingid from payment ) 	0.00152365534401396
7507655	24983	mysql: indexes on group by	select b, c, d, e, f, max(a) from table group by b, c, d 	0.558861773218296
7508361	13806	select max element columns from group	select * from users join (select groupid, max(userid) as maxu from users group by groupid) xx on xx.groupid=users.groupid and users.userid=xx.maxu 	0.000457914163233963
7509120	23625	mysql: using a reference id, see if data matches across that id	select count(*) where data='jacob' and data='apples' group by reference_id; 	0
7509687	16057	working out total from sub total and amount	select order_number ,sum(amount * cost_per_item) as total ,purchase_date from ecom_orders where member_id = '4' group by order_number,purchase_date order by purchase_date desc 	0.000144139679818817
7511064	35575	postresql - aliases column and having	select case            when pjz = 0 then 100           else pjz        end as pjz,        mass from (     select case               when sum(x.count)*3600 is null then '0'                else sum(x.count)*3600              end as pjz,              x.mass       from x       where x.mass > 2000       group by x.mass ) t where pjz = 0     or ((x.mass / pjz * 100) - 100) >= 10; 	0.634290990340052
7512499	40294	getting the number of rows with a group by query within a subquery	select   x,   y,    z,   (     select       count(distinct date_format( cvdbs2.datedone, "%y-%d-%m" ))     from       cvdbstatistics cvdbs2     where       cvdbs2.mediatorid = mediators.id   ) as activedays from   mediators left join   cvdbstatistics on   mediators.id = cvdbstatistics.mediatorid where   mediators.recruiterid = 409 group by   mediators.email 	0.000921300419427291
7512711	36096	searching for a specific job by the procedure it calls	select * from all_dependencies where referenced_name = 'your_stored_proc'; 	0.488657558850185
7514652	33361	select count of field by group	select sum(score) as total from table group by type 	0.00947164620655638
7514867	29681	introduce dummy row in a sybase query	select column1,column2,... into #temp from <actualtable> where condition='abc'... (1) if @@rowcount = 0     select "dummy col1","dummy col2"..... into #tmp     from <dummy table> insert #temp select column1,column2,... from <anothertable> where condition='abc'... (1) if @@rowcount = 0     insert #temp     select "dummy col1","dummy col2".....     from <dummy table> ...  select * from #tmp 	0.303830322752773
7515624	19128	how do i output the rowname based on a linking table?	select     tablea.a_name,     tableb.b_name,     tablec.c_name from tablelink join tablea on tablelink.a_id = a.id join tableb on tablelink.b_id = b.id join tablec on tablelink.c_id = c.id where tablelink.c_id = 42 	0.000196494355006765
7515731	34685	tsql - exclusion condition	select clientmatter,        case          when len(clientmatter) <> 11 then 'length problem'        end,        case          when isnumeric(clientmatter) <> 1 then 'non-numeric'        end from   tblclient where  isnumeric(clientmatter) <> 1         or len(clientmatter) <> 11 	0.743604897243142
7516535	23707	sql server all errors list?	select message_id, severity, text   from sys.messages    where language_id = 1033;  	0.157584490492435
7516774	30238	mysql get things after certain date	select blablabla... where availableuntil >= current_timestamp 	0.000247738460846984
7516994	30670	can i get a ratio from a selection in sql?	select user_id, user_time_by_batch / total_time_by_batch from (   select sum(time_elapsed) user_time_by_batch, user_id, batch_id   from batch_log   group by batch_id, user_id ) user_time_by_batch inner join  (   select sum(time_elapsed) total_time_by_batch, batch_id   from batch_log   group by batch_id ) total_time_by_batch on user_time_by_batch.batch_id = total_time_by_batch.batch_id 	0.00160680591328899
7518035	18954	how to get file paths of ms sql database that is stuck restoring	select filename      from master.sys.sysaltfiles     where db_id = db_id('database name'); 	0.15049881991983
7518960	40031	sql query - time comparison (sqlite)	select  case when  (select min(time(mycolumn)) from mytable where time(current_timestamp, 'localtime') < time(mycolumn)) is null  then  (select min(time(mycolumn)) from mytable where time(current_timestamp, 'localtime') > time(mycolumn))  else  (select min(time(mycolumn)) from mytable where time(current_timestamp, 'localtime') < time(mycolumn))  end 	0.627097777427283
7521129	8979	mysql, data spread over two tables, seperate rows	select     publisher,     stock,     dvd_info as info,     extra_dvd_info from dvd where publisher = ?     union all select     publisher,     stock,     cd_info as info,     null from cd where publisher = ? order by stock; 	0.00021682326241118
7521340	38677	concatenating numbers together in oracle apex using sql	select to_char(req_num, '00000009') ... 	0.205998246644302
7522821	29635	tsql query to create new table from a combination of two tables	select * from [table 1] t1 where not exists (     select * from [table 2] t2     where         t1.variable_1 = t2.variable_1         and t1.variable_2 = t2.variable_2         and t1.variable_3 = t2.variable_3 ) 	5.77182103374173e-05
7523933	21256	how do i select a record from one table in a mysql database, based on the existence of data in a second?	select distinct users.name from users join conversation_log on users.id = converation_log.userid 	0
7524130	20685	how to format getdate into yyyymmddhhmmss	select replace(        replace(        replace(convert(varchar(19), getdate(), 126),        '-',''),        't',''),        ':','') 	0.0271637615129288
7524445	3668	split a column value into two columns in a select?	select split_part(one_column, ' ', 1),split_part(one_column, ' ', 2) ... 	0
7524612	34623	how to count rows from multiple tables in sqlite	select (select count(*) from table_1  where mid = ?) +         (select count(*) from table_2  where mid = ?) +        (select count(*) from table_3  where mid = ?) +        (select count(*) from table_4  where mid = ?) 	0.00041022065025886
7525207	23162	select case with subqueries select and using top	select distinct browser =  case      when ( patindex('%ie%',browsername) is not null)  then   substring(browsername,patindex('%ie%',browsername),8)      when (patindex('%firefox%',browsername) is not null)  then substring(browsername,patindex('%firefox%',browsername),8)     when (patindex('%chrome%',browsername) is not null)  then substring(browsername,patindex('%chrome%',browsername),6)  end  from tablebrowsers where userid =21 	0.783329081808068
7526839	9638	sql find next date for each customer, sql for each?	select c.id, min(o.date) from customer c      inner join deliveryordercustomer co o on co.customerid = c.id      inner join deliveryorder o on co.deliveryorderid = o.id and o.date>getdate() group by c.id 	0
7528969	25057	find out date difference in sql server	select    datediff(dd, fromdate, todate)   -datediff(wk, fromdate, todate)   -(case when datepart(dw, fromdate) = 1 then 1 else 0 end) 	0.00515016242318205
7529683	24583	if the where condition is on a joined table, will i get duplicated results?	select       sum(t.estimated_nonrecurring + t.estimated_recurring) / 3600 as work_completed,       t.operationid from       tasks t inner join        batches b on        b.batchid = t.batchid inner join        batchlog bl on        bl.batchid = b.batchid where     bl.start_time between date("2011-08-01") and date(now()) group by        t.operationid 	0.000482853035982877
7531001	25867	fast way to generate concatenated strings in oracle	select listagg(column, separator) within group (order by field)   from datasource  group by grouping columns 	0.0592621386989435
7533105	1879	creating a next feature without adding fields to a table?	select p.poll_id from polls p where p.poll_id not in (select r.poll_id from poll_to_user r where r.user_id = [current_user_id]) order by rand() limit 1; 	0.00879074213263825
7533788	11683	database auto increment primary key with business login	select events.*, users.* from users left join events where users.id = events.user_id where user.username = 'johnboy' 	0.000961466803142162
7535216	9392	mysql two different groupings required in one query	select     child_name,     sum(behaviour_score),     sum(test_score)  from (       select child_name, max(behavior_score), sum(test_score)       from result group by child_name, week      ) as oneperweek group by child_name 	0.0102482286810315
7535533	17121	sql time difference within single table	select x.*, timediff(x.logout_date, x.login_date) as duration from ( select a.user_id, a.`date` as logout_date,  (select max(b.`date`) from table1 b where b.`date` <a.`date`  and b.user=a.user and b.type = 'login') as login_date     from table1 a where a.type ='logout' )x 	0.00201721335945047
7535939	25256	how can i fetch rand records from a union query?	select * from (     select a, b, c from your_table where [statement] order by rand() limit 1 ) t1 union select * from (     select a, b, c from your_table where [different statement] order by rand() limit 5 ) t2 	0.00221839039517258
7536386	33249	count users from table 2 in request to table 1	select p.id,      p.position,      sum(case w.status when 2 then 1 else 0 end)  as booked,     sum(case w.status when 3 then 1 else 0 end)  as placed   from  tbl_positions as p left join tbl_workers as w        on w.position=p.id group by p.id, p.position 	5.89824154247887e-05
7536907	38421	how to get exact time format using select query	select right('0' + ltrim(right(convert(varchar, getdate()), 7)), 7) 	0.00456097057472964
7537400	23472	what's the correct way to "flatten" data in mysql from 3 dimensions to 2?	select    u.id as user_id   , uvfirstname.value as firstname   , uvlast_name.value as lastname   , uvbook.value as book from users u left join uservalues uvfirstname         on (uvfirstname.label_id =              (select l1.id from label l1 where l1.name = 'first name')            and uvfirstname.user_id = u.id) left join uservalues uvlastname         on (uvlastname.label_id =               (select l2.id from label l2 where l2.name = 'last name')            and uvlastname.user_id = u.id) left join uservalues uvbook        on (uvbook.label_id =               (select l3.id from label l3 where l3.name = 'fav book')            and uvbook.user_id = u.id) 	0.0117462745672069
7538833	12485	how to structure this sql query. combining multiple tables?	select a.*,m.*,u.*,c.* from articles as a left join media as m on (m.mediatimestamp = a.articletimestamp) left join updates as u on (u.updatetimestamp = m.mediatimestamp) left join comments as c on (c.commenttimestamp = u.updatetimestamp) order by a.articletimestamp desc limit 30 	0.506213263177583
7538975	21031	how to check if condition in case statement of stored procedure	select      keywordresult = case          when @keywords = 'state' then 'one'         when @keywords = 'keyword' then 'second'         when @keywords = 'company' then 'third'         else 'other' end,     jobid,      jobtitle,      companyinfo,      jobsummarylong,      modifieddate   from      jobs   where      isactive = 1     and (@startdate <> '' and modifieddate >= @startdate)     and modifieddate <= @enddate + ' 23:59:59''' 	0.702345999908994
7539676	13356	count the status types and put totals in one row	select       count(case when name='type0' then 1 end) as type0,      count(case when name='type1' then 1 end) as type1,      count(case when name='type2' then 1 end) as type2 from yourtable 	0
7540385	3786	mysql search problem to find lowercase and uppercase letters at the sametime	select * from your_table  where lower(username) like '%arup' 	0.0187039532318018
7541732	22171	mysql query for between operator with range	select count (*) from table where rank1 not between min(incomingrank1, incomingrank2) - 1                      and max(incomingrank1, incomingrank2) + 1   and rank2 not between min(incomingrank1, incomingrank2) - 1                      and max(incomingrank1, incomingrank2) + 1   and date = incomingdate 	0.296728912128475
7543013	39549	mysql select multiple rows with same column value based on value from another column	select tag, count(*) from jodytable        where tag not in ('ldnon', 'ldnont')          and id in (select id from jodytable where tag in ('ldnon', 'ldnont')) 	0
7544409	24256	selecting the most recent results, in ascending order	select * from      (select count(*), time from visit group by time order by time desc limit 14) as t order by time 	0
7545103	1105	best way to search two queries and eliminate rows without a relationship	select *  from property p  where p.id in (     select pu.property_id     from property_to_unit pu         inner join unit u on pu.unit_id = u.id         inner join unit_to_unit_tenure uut on u.id = uut.unit_id     where uut.id = <cfqueryparam value="#uutid#"> ) 	0.00251337565393609
7545577	38527	giving users unique ids in the form of an auto_increment	select isnull(max(item_code) + 1) from item where user_id = 2 	0.000314822995262468
7545639	24789	sql cut results from table	select t0.cust_id, t0.cust_name, t0.duration from (  select cust_id,cust_name,sum(calls.duration) as duration from      calls, telephone where calls.from_t_no = telephone.t_no and calls.duration <=60 group by telephone.cust_id, telephone.cust_name) t0 join (select cust_id,cust_name,sum(calls.duration) as duration    from calls ,telephone   where to_t_no = telephone.t_no   and   calls.duration >=500   group by telephone.cust_id, telephone.cust_name) t1 on t0.cust_id = t1.cust_id 	0.0327991500080843
7546004	37697	sqlitedatabase select rows where column is equal something	select * from table where thecolumn in ('text1', 'text2', 'text3') 	0.0275727516002012
7550476	11033	using sql to retrieve the most popular queries in a dataset	select search_location, sum(num_searches) as total_searches     from my_table     group by search_location     order by total_searches desc     limit 100; 	0.000143583088818921
7552019	29999	sql union all *with* "distinct"	select col1,        col2,        min(grp) as source_group from   (select 1 as grp,                col1,                col2         from   t1         union all         select 2 as grp,                col1,                col2         from   t2) as t group  by col1,           col2 order  by min(grp),           col1 	0.068997176223467
7553346	28061	how to select last 3 minutes' records from mysql with php	select * from mytable where login_time > date_sub(now(), interval 3 minute) ; 	0
7556019	13676	select where column not in an other one 2 times	select * from table where id not in  (select c2 from table group by c2 having count(c2) = 2) 	0.000258757166856049
7556431	31376	select a value in a language if in another is empty	select ifnull(de.text, en.text) from   words de   join words en on     en.id = de.id and     en.lang = 'en' where de.lang = 'de' 	0.00289683994121707
7556508	1056	how to get halfbrothers/sisters in sparql?	select distinct ?name1 ?name2 where {    ?child1 oranje:hasparent ?parent , ?otherparent1 .    ?child2 oranje:hasparent ?parent , ?otherparent2 .    ?child1 rdfs:label ?name1 .    ?child2 rdfs:label ?name2 .    filter (?child1 != ?child2)    filter (?otherparent1 != ?parent)    filter (?otherparent2 != ?parent)    filter (?otherparent1 != ?otherparent2) } 	0.0219682385504742
7557119	24343	sql server: calculate field data from fields in same table but different set of data	select a.vehicle_no, a.stop1_deptime,         a.segment_traveltime, a.stop_sequence, a.stop1_deptime +   (select sum(b.segment_traveltime) from your_table b     where b.vehicle_no = a.vehicle_no and b.stop_sequence < a.stop_sequence) from your_table a order by a.vehicle_no 	0
7557817	31398	mysql: joining tables for translation records	select        eng.id,       eng.translated_text inenglish,       coalesce( spn.translated_text, eng.translated_text ) inspanish,       coalesce( frn.translated_text, eng.translated_text )  infrench    from       translation eng          left join translation spn             on eng.id = spn.id             and spn.language_id = 2          left join translation frn             on eng.id = frn.id             and spn.language_id = 3    where       eng.language_id = 1    order by        eng.id 	0.0248451892418798
7558492	40587	oracle - break dates into quarters	select  add_months( trunc(param.start_date, 'q'), 3*(level-1) )   as qstart     ,   add_months( trunc(param.start_date, 'q'), 3*(level) ) -1  as qend from    (   select  to_date('&start_date')  as start_date                 ,   to_date('&end_date')    as end_date             from    dual         ) param connect by add_months( trunc(param.start_date, 'q'), 3*(level) ) -1         <= param.end_date 	0.0123490355639975
7559748	16202	how to select fields from one table and order them by fields from another table	select id from first_table  inner join second_table on first_table.secondtableid = second_table.id where value = 'known value' order by second_table.title 	0
7560277	13607	match each variable passed in mysql in()	select users.id, users.name from users  inner join usersskills on users.id = usersskills.userid  inner join userslanguages on users.id = userslanguages.userid  where activated = "1"  and type = "graduate"  and usersskills.skillid in(2, 21) and userslanguages.languageid in(2, 22) group by users.id, users.name having count(distinct usersskills.skillid) = 2    and count(distinct userslanguages.languageid) = 2 	0.00354147566205102
7560317	39844	sql selecting record with highest id	select whatever from table  where q.id in      (select max(id) from table       where blah...blah       group by c.firstname, c.lastname) 	0
7560883	26153	how to assign a value to a casted column in oracle	select table1.*, (case when table1.id > 10 then 1 else 0 end) as value from table1 	0.00106253710813704
7562873	15606	sum a subquery?	select x.prod_name      , sum(x.total)   from ( select bp.prod_name               , ( select sum( wh.quantity ) * bp.weight                      from bus_warehouse_entries wh                    where bp.prod_code = wh.org_product_code ) as total        from bus_products bp ) x  group by x.prod_name 	0.380253809384068
7563442	20036	how to select rows with sum of group in sqlite3?	select saleid, count(1) as [count] from sales group by saleid 	0.00547967652802885
7563796	38580	how to do pivoting in postgresql- 9.1.0	select c.colorname, c.hexa, r.rgbvalue, g.rgbvalue, b.rgbvalue from (select colorname, hexa       from sometable       group by colorname) c join sometable r on c.colorname = r.colorname and r.rgb = 'r' join sometable g on c.colorname = g.colorname and g.rgb = 'g' join sometable b on c.colorname = b.colorname and b.rgb = 'b' ; 	0.31375908813605
7563893	24394	finding specific records based on user's preferences	select p.prj_title from prj as p join users as s on (     (u.x=p.x and u.x=1)     or (u.y=p.y and u.y=1)     or (u.z=p.z and u.z=1) ) where u.user_id='user1'; 	0
7564285	36144	how to select from more columns but group by 1 column?	select student_name, student_birth_day, studentnum from student s right join (   select studentnum, count(*) as cnt   from   attendance   where (attstatus = 'yes')    and   (unitcode = 'mma1034')   group by studentnum   having (count(*) < 4) ) a on a.studentnum = s.studentnum 	0.000205516087300747
7565084	38095	get all unique character of string in sql	select distinct lower(substr(firstname,1,1)) firstchars from your_table where lower(substr(firstname,1,1)) in  ('a','b','c','d','e','f','g','h','i','j',   'k','l','m','n','o','p','q','r','s','t',   'u','v','w','x','y','z') order by firstchars 	0.000123191050827598
7565716	3687	how to display data with 'yes' or 'no' entries unique.	select     * from (     select         unitcode,         stunum,         sum(case when substatus = 'yes' then 1 else 0 end) as countyes,         sum(case when substatus = 'no' then 1 else 0 end) as countno     from         students     group by         unitcode, stunum ) as student inner join student_details     on student.stunum = student_details.stunum where     countno > 0 and countyes = 0; 	0
7566742	10565	sqlite, how to entities associations without foreign keys?	select t.trackname, t.trackid   from track t  inner join artist a     on a.artistid = t.trackartist  where a.artistname = 'alex' 	0.0120781551547336
7568032	37245	mysql deleting rows not in other table	select * from dvd_role r where not exists (    select * from dvd_actor_role a    where a.roleid = r.id    ); 	0.00236377285242787
7569379	34322	mysql select statement with respect to another table field	select newpassengers.id  from newbus     inner join newpassengers on newpassengers.s_city = newbus.startcity where newpassengers.s_city = 'tcity'      and newpassengers.e_city = 'mcity'      and newbus.id = 5 	0.00527671866421965
7569399	11168	get a recursive parent list	select      t1.parentid, t2.parentid, t3.parentid, t4.parentid, t5.parentid from     tablename t1     left join tablename t2 on t1.parentid = t2.id     left join tablename t3 on t2.parentid = t3.id     left join tablename t4 on t3.parentid = t4.id     left join tablename t5 on t4.parentid = t5.id where     t1.name = 'thing3' 	0.00762387150922448
7569817	1222	remove subquery from join?	select    previous.nav as previousnav,    todays.nav as todaysnav,    isnull((todays.nav-previous.nav),0) netchange,    isnull((todays.nav-previous.nav) / todays.nav,0) bamlindex from     fireball..nav as previous join     fireball..nav as todays     on previous.portfolioid = todays.portfolioid where previous.date between @startdate and @enddate      and previous.portfolioid = @portfolioid     and todays.date = @enddate 	0.196556226526791
7570589	6018	mysql get a summary of data based on part of a string	select    substring_index(email,'@',-1) as domain   ,count(*) as usercount  from your_table group by domain  order by usercount desc; 	0
7570873	22991	joining tables in asp.net	select table1.column1,        table2.column2 from   table1        inner join table2            on table1.somecolumn = table2.somecolumn 	0.237896581580017
7571358	22496	need a twin group by value	select      some_id,      count(another_id) as without_filter     sum(case when some_condition then 1 else 0 end) as with_filter from some_table group by some_id 	0.198756736941525
7571589	6724	distinct join query	select dm.client_code  from dbo.dm_client as dm  left join dbo.stg_dm_client as stg     on stg.client_code= dm.client_code  where stg.client_code is null  group by  dm.client_code; 	0.502947037519892
7571820	37669	oracle, inserting correlative numbers based on other fields	select date, row_number()    over (partition by date order by date) as any_way_to_get_it     from mytable; 	8.48313023322889e-05
7571988	1272	how to select all tags for a post with a given tag in mysql?	select posts.id, group_concat(post_tags.tag) as additional_tags    from posts left outer join post_tags on posts.id = post_tags.post_id    where posts.id in (select post_id from post_tags where tag = :search_tag)    and post_tags.tag <> :search_tag    group by posts.id 	0
7572294	170	how to check if a row in a table has muti-byte characters in it in a mysql database?	select ... from yourtable where char_length(descr) <> length(descr) 	0.000190054680012222
7573745	11220	sql method of checking that inner / left join doesn't duplicate rows	select joinfield from myjointable group by joinfield having count(*) > 1 limit 1 	0.477312509506995
7574105	22182	how can i use two datasources in a cfquery?	select * from mytable  where myfield in  (select otherfield from otherdatabase.dbo.tablename) 	0.308746315899648
7575381	25739	sql server rows with latest date	select y.userid, y.event, y.eventdate     from (select userid, max(eventdate) as maxdate               from yourtable               where userid in ('john','tom',...)               group by userid) t         inner join yourtable y             on t.userid = y.userid                 and t.maxdate = y.eventdate 	0.00118540351784401
7579344	16142	getting the last answer id for the questions	select top 1 ansid where uid=@userid and qid=@questionid order by id desc 	0
7579457	27231	comparision of two columns within a single table	select `b`, count(*) as `count` from `alpha`  group by `b` 	6.43443573137799e-05
7579475	36298	procedure returning multiple values	select top 30 datepart(day, interactiondate) as day, count(1) as interactions from logtable group by datepart(day, interactiondate) 	0.145598710570101
7580314	7091	split result from sql query	select * from  (       select tb.*,rownum t_count from table_name tb ) ss where ss.t_count >= @min_value and ss.t_count <= @max_value 	0.0227084698491124
7581228	5996	left join resulting in null rows for column with no null rows	select m.*, mi.filename, count(p.movieid) as publicationscount     from movies m     left join movie_publications p         on (m.movieid = p.movieid)     inner join movie_image mi         on (m.movieid = mi.movieid)     group by m.movieid 	0.0061819611772369
7581349	38009	select the fields are duplicated in mysql	select *  from customer_offer  where key in  (select key from customer_offer group by key having count(*) > 1) 	0.00308075650727674
7581861	21378	mysql time overlapping	select * from activities where (.$start. between starttime and endtime) or (.$end. between starttime and endtime) or (starttime < .$start. and endtime > .$end.); 	0.0298768137844827
7582014	28344	sql to query drupal nodes with multiple taxonomies	select * from node  inner join term_node as tn on node.vid = tn.vid  left join content_type_extra_content as xc on node.vid = xc.vid  where tn.tid in ('146','223') group by node.vid having count(*) = 2 	0.731197965085205
7582030	24615	mysql between two dates index	select * from sal_import where datestats between '2011-07-28' and '2011-07-30' 	0.0085345839111744
7582508	4037	removing duplicate rows from a table	select      * from tablename t inner join (     select min(id) as id from tablename      group by address ) sub on t.id = sub.id 	0.000143630011170482
7582606	320	rendering query x times instead of required once because instance... help?	select distinct id  from lime_all_tokens  where fname='".$fname."' and lname ='".$lname."'" 	0.0439486099664754
7582728	11754	how to sort mysql search result by relevance?	select a.* from ( select add1, add2, add3, post_town, post_code, 1 as rank from address_mst  where add1 like '%".$keyword."%' union select add1, add2, add3, post_town, post_code, 2 as rank from address_mst  where add2 like '%".$keyword."%' union select add1, add2, add3, post_town, post_code, 3 as rank from address_mst  where add3 like '%".$keyword."%' union select add1, add2, add3, post_town, post_code, 4 as rank from address_mst  where post_town like '%".$keyword."%' union select add1, add2, add3, post_town, post_code, 5 as rank from address_mst  where post_code like '%".$keyword."%' ) a order by a.rank asc; 	0.173884519450216
7583515	8915	convert character to number in oracle	select 1 + ascii(columna) - ascii('a') from   table 	0.0415483617039334
7585445	40279	tsql distinct record count	select consumer, [program enrollment date], event_name, countperconsumer.[number of events] from #initiations i join (select consumer, count(distinct event_name) as [number of events]          group by consumer)countperconsumer      on countperconsumber.consumer = i.consumer 	0.0155101960492461
7585722	32857	i need to modify a table structure and need to find specific columns in database	select * from information_schema.columns where column_name = 'sysnames' select * from information_schema.views where view_definition like '%sysnames%' select * from information_schema.routines where routine_definition like '%sysnames%' 	0.00125795207303554
7586105	27756	mysql count(), sum() and group by	select      count(c.population) as c,      c.city as cc,      (select count(c.population) from city) as totalpop  from city c  group by c.city  order by c.city; 	0.116099160827818
7586696	2811	mysql double order	select users.id  from `users` join `profiles` on users.id = profiles.id  where profiles.zipcode = '$zipcode'    and users.id not in (1,2)   and profiles.picture != ''  order by users.last_activity desc, users.gender  limit 0,11 	0.634246257041049
7589181	14868	how to join multiple tables related by other tables	select p.id, p.name, p.date,            f.id, f.name,            i.id, i.src     from ta_publications p     join ta_publication_features pf on p.id = pf.publication_id     join ta_features f on f.id = pf.type_id     join ta_publication_images pi on p.id = pi.publication_id           and pi.order = 0     join ta_images i on i.id = pi.img_id     where p.id in (   	0.0007994101248187
7589449	8308	sql select query with count and where statement	select name, count(*) as total from table where date = today and type = 1 group by name 	0.795908982712214
7589632	29870	splitting elements of a string across multiple columns	select    s.id   ,substring(s.title,1, posoffirstnumber-1) as booktitle   ,substring(s.title, posoffirstnumber) as remainder from    (select       id       ,title       ,least(           ifnull(nullif(locate('1',title),0),999)           ,ifnull(nullif(locate('2',title),0),999)           ,ifnull(nullif(locate('3',title),0),999)           ,ifnull(nullif(locate('4',title),0),999)           ,ifnull(nullif(locate('5',title),0),999)           ,ifnull(nullif(locate('6',title),0),999)           ,ifnull(nullif(locate('7',title),0),999)           ,ifnull(nullif(locate('8',title),0),999)           ,ifnull(nullif(locate('9',title),0),999)           ,ifnull(nullif(locate('0',title),0),999)         )) as posoffirstnumber     from table1 ) s 	0
7589789	7047	oracle query that will list of the database objects referenced by a view	select * from dba_dependencies   where owner = 'view owner'     and name = 'view name'; 	0.00306605032011384
7590857	30534	get max of two entries query	select machinename, statuscode, max(size) as size from machine where machineid in( '33','22') and statuscode = 166  group by machinename, statuscode order by max(size) desc 	0
7591679	9129	get last created id with auto-increment in mysql	select last_insert_id(); 	0.000167725478214962
7591784	8287	tricky "grouped" ordering in sql	select car_id, car_brand, car_model, price from cars c1     join (select car_brand, min(price) as brand_price from cars group by car_brand) c2       on c1.car_brand = c2.car_brand     order by c2.brand_price, c1.car_brand, c1.price 	0.616780267137039
7598757	1108	oracle sql return all records within days of date	select    * from   table where   last_mod_date >= trunc(sysdate-20); 	0
7598953	1754	selecting records in order of the number of records that contain a certain field	select album_id, count(*) as numvotes      from wp_album_votes      where yearweek( time_voted ) = yearweek( current_date - interval 7 day )      group by album_id     order by numvotes desc limit 5 	0
7599474	25605	how do i extract data from xml columns into their own columns?	select      id,    body.value('(telemetry/esn)[1]', 'bigint') as 'esn',    body.value('(telemetry/timestamp_utc)[1]', 'varchar(50)') as 'esn',    body.value('(telemetry/longitude)[1]', 'float') as 'longitude',    body.value('(telemetry/latitude)[1]', 'float') as 'latitude',                 body.value('(telemetry/timestamp_utc)[1]', 'varchar(50)') as 'triggers' from    dbo.yourtablenamehere 	0
7599760	32058	mysql select all last added query	select    *  from me_tests  where start_date = (select                        start_date                     from me_tests                      order by start_date desc limit 1) 	0.000370198732375614
7599974	1894	how to do join with multiple conditions in mysql	select b.text, c.name from tablea a inner join tableb b on a.mid = b.mid inner join tablec c on b.uid = c.uid where a.uid = 1 	0.400439115412298
7600731	33987	sql - get matches where match is null or parameter with one-to-many	select * from rule  where rule.id not in (select ruleid from ruleequipment) or rule.id in  (    select ruleid     from ruleequipment        inner join equipment on ruleequipment.equipmentid = equipment.equipmentid    where equipment.equipmentcode = @inputequipmentcode ) 	0.324771602355716
7602398	27655	selecting greatest n records in x groups	select catx.category        catx.interest        t1.user_id        t1.score from      ( select category             , interest        from tablex        where user_id = @user_id_we_are_interested_in            order by interest desc       limit @x                              ) as catx    join      tablex as t1        on t1.category = catx.category    left join      tablex as t2        on  t2.category = t1.category        and t2.score > t1.score    group by t1.category          , t1.user_id   having count(t2.score) < @n                         order by catx.interest desc           , t1.score desc 	0
7602620	19270	query to get one entry from multiple rows	select machinename, statuscode, size, statusid from (     select         machinename,         statuscode,         size,         statusid,         row_number() over (partition by machineid order by size desc) as rn     from machine     where machineid in ('33','22')     and statuscode = 166  ) t1 where rn = 1 order by size desc 	0
7603540	1850	postgresql integer out of range error when inserting small numbers into integer fields	select nextval('index_index_id_seq') 	0.0019370296819142
7604509	9061	mysql query for tagging system, selecting used tags only	select     `blog_tags`.`tag_name`,     count(*) as `blog_article_count` from `blog_tags`     join `blog_tags_assoc`         on `blog_tags`.`tag_id`=`blog_tags_assoc`.`tag_id`     join `blog_articles`         on `blog_articles`.`article_id`=`blog_tags_assoc`.`article_id` group by `blog_tags`.`tag_name` 	0.0844202711882947
7604766	15722	mysql select timestamp(now()-3000);	select * from x where ts between timestamp(date_sub(now(), interval 30 minute)) and timestamp(now()) 	0.445071290752215
7605781	22198	need a query to put certain mysql database columns into a row	select t1.id,        t1.pagetitle,        (select value from table2 where contentid = t1.id and tmplvarid = 1) as author,        (select value from table2 where contentid = t1.id and tmplvarid = 2) as image   from table1 t1 	0
7605791	38681	trying to 'merge' partial data in 2 or more rows with mysql	select t.id, t.title, t.notes,  group_concat( concat(a.lastname, a.firstname, a.middlename) separator ', ') as author from titles t, author a, authortitle at where  t.title like '".$letter."%' and at.author_id_fk = a.id and at.title_id_fk = t.id group by t.id 	0.000950270295485918
7606305	9829	postgres select all columns but group by one column	select unit_id, time, diag from (     select unit_id, time, diag,            rank() over (partition by unit_id order by time desc) as rank     from diagnostics.unit_diag_history ) as dt where rank = 1 	6.45491390028382e-05
7606526	1656	select entries in "joined" table matching specific data and/or non-existing data	select table1.art_author, table1.art_date, table2.loc_title, table2.loc_text  from table1  left join table2 on table1.art_id = table2.art_id                  and table2.loc_lang = 'en' 	0
7606903	11515	convert varchar2 to timestamp in oracle	select to_timestamp('14-sep-11 12.33.48.537150 am', 'dd-mon-rr hh:mi:ss.ff am')  from dual; 	0.04790565596041
7607351	19150	add two array of objects from mysql result	select * from tbl_profile where admin_selected = 'y' or admin_selected = 'n' 	0.000264462315017454
7609197	2996	applying distinct to single column	select          process.reportlogprocessid as [process.reportlogprocessid],         process.processtitle as [process.processtitle],         max(cast(user0.primaryemail as nvarchar(max))) as [process_contacts.isprimarycontact]  from reportprocess as process  inner join reportprocesscontact as reportprocesscontact0 on        ((reportprocesscontact0.sessionid = process.sessionid))  left outer join [user] as user0 on        ((reportprocesscontact0.referenceid = user0.userid))  left outer join [group] as group0 on        ((reportprocesscontact0.referenceid = group0.groupid and        reportprocesscontact0.referencetype = 2))  group by process.reportlogprocessid, process.processtitle order by [process.processtitle] asc 	0.0172433088348736
7616103	2717	how do i use max() in sql	select t.col1, t.col2, t.col3 from mytable t,     (select col1,          max (col2) as mx      from mytable     group by col1) m where m.col1 = t.col1 and m.mx = t.col2 	0.457140518675036
7617110	38885	postgresql: in a single sql syntax order by numeric value computed from a text column	select id, number_value_in_string from table  order by case when substr(number_value_in_string,1,2) = '1/'         then 1/substr(number_value_in_string,3)::numeric          else number_value_in_string::numeric end, id; 	0.00274478066815384
7619117	3214	sorting groups of data looking at the newest entry	select rows.team, rows.date from (   select team, date,     if( @prev <> team, @rownum := 1, @rownum := @rownum+1 ) as rownum,     @prev := team   from my_table   join (select @rownum := null, @prev := 0) as init   order by team, date desc ) as rows where rownum <= 10 	0
7619499	3805	getting distinct column name and count when based on another table	select distinct cc.category, count(cc.category) as totalcategorycount  from companies c left join categories cc on c.category_id = cc.category_id where company_title like '%gge%' group by cc.category 	0
7619780	32784	many to many query with filter	select distinct s.*    from students as s    inner join group_student as gs on gs.student_id = s.id    inner join groups as g on g.id = gs.group_id    where g.id ="8" or (g.id="1" and s.name = "john") 	0.325741609775195
7620690	25488	how can i get the column names from an excel sheet?	select * from information_schema.columns where table_name = 'yourtable' 	6.92015669238572e-05
7623170	15601	check for match in other column	select     c1.category_title as category_title,     c2.category_title as subcategory_of from categories c1 left join categories c2 on c1.subcategory_id = c2.category_id 	0.00156413017471731
7628532	33433	mysql: join a table to itself	select       max(case when name = 'season_start' then value end) as season_start,      max(case when name = 'season_end' then value end) as season_end,      max(case when name = 'season_countdown' then value end) as season_countdown from txp_prefs where event='season' 	0.115470479347181
7628793	12528	set a parameter in select statement	select @foo = foo, @bar = bar, ... from headers where id = 42 select @foo as foo  select size, weight, color from trailers where bar = @bar  	0.479971427207815
7629160	21590	sql query to find customers who registered and purchased on the 2nd day to within 7th day of their registration	select distinct     users.custid from     users join order on users.custid = order.custid where     datediff(dd, users.posteddate, order.posteddate) between 1 and 6     and users.posteddate between @start_date and @end_date 	0
7629200	36059	creating a cumulative sum column in mysql	select num as n,         (select sum(num) from id where num <= n) from id order by n; 	0.0237558605851125
7630418	18606	sql view - combine multiple rows into 1 row	select table1.customerid, dbo.buildstringofcustomerproductnames(table1.customerid) from table1 	0.000165858046461936
7631396	6254	mulitple queries in different table	select     *,     (result.total + result._total) / 2 as rate from (     select         date,         sum(case when data.valid = 1 then 1 else 0 end) as ontime,         sum(case when data.valid = 0 then 1 else 0 end) as late,         count(*) as total,         sum(case when data.valid = 1 and data.status = 'valid' then 1 else 0 end) as valid,         sum(case when data.valid = 0 and data.status = 'invalid1' then 1 else 0 end) as invalid1,         sum(case when data.valid = 0 and data.status = 'invalid2' then 1 else 0 end) as invalid2,         sum(case when data.status in ('valid', 'invalid', 'invalid2') then 1 else 0 end) as _total     from (         select             date,             status,             valid = 1         from             valid         union all         select             date,             status,             valid = 0         from             invalid ) as data     group by         date) as result 	0.0240918359552155
7631986	34210	getting and ordering rows with value greater than zero then rows with value zero	select * from atable order by   display_order = 0,   display_order 	0
7632894	382	counting total per day with my result in sql	select date(claimed_at) as day     , sum(price) as total from orders group by day 	0
7633480	34635	how to check if referenced table is not empty?	select count(*) as number_of_connections   from master m   inner join slave s on (s.master_id = m.master_id) union all   select count(*) as rows_in_slave   from slave s2 union all   select count(*) as rows_in_master   from master m2 	0.0233584566876212
7635467	19248	way to copy the values from column1(containing numbers) declared as varchar to another column2 declared as number in mysql	select replace('052-12525', '-', ''), format(12332.1,0) 	0
7635632	9746	sql- identify nullable values	select * from information_schema.columns c with (nolock) 	0.0330525104170203
7638384	9280	crystal reports using multiple results from a stored procedure	select * from #temp 	0.25325613367611
7638675	38971	jquery hide post & show next post	select * from posts where liked = 1 limit 10 	0.000254454909426701
7639916	1300	mysql get duplicates of one value	select y.id, y.first_name, y.last_name, y.age     from (select first_name               from yourtable               where age = 18               group by first_name               having count(*) > 1) t         inner join yourtable y             on t.first_name = y.first_name     where y.age = 18; 	0.000150287042501748
7640396	21913	removing duplicate results while using union select	select id, max(qty) as qty from (     select id, qty from table1     union all     select id, qty from table2 ) t1 group by id 	0.0849231310281891
7641487	31516	adding values before mysql extraction or after?	select sum(points) as points, value from yourtable where x = y group by value 	0.0395388473155916
7641825	18408	mysql add second query to the same request, its complicated	select employers.employer_name, p.position_name,      case when w.position2 = p.position_id then p.position_name else 'no worker position found' end as worker_position_name,      sum(case when w.type = 2 then 1 else 0 end) as booked,      sum(case when (w.type = 3 or w.type = 31) then 1 else 0 end) as placed     from places as p           left join employers on employers.id = places.employer       left join (         select           w.id,           w.user_id,           case x.pos when 1 then w.pos1 else w.pos2 end as position,           case w.type             when 39 then case x.pos when 1 then 3 else 2 end             else w.type           end as type,           w.pos2         from workers as w           cross join (select 1 as pos union all select 2) as x       ) as w       on w.position = p.pos_id     group by p.pos_id, p.pos_name,w.position2,p.position_id,p.position_name     order by p.emp_id asc, p.pos_id asc; 	0.00312073992382667
7643397	8478	select results based on date but knowing the id	select * from history where date < (select date from history where url = 'foo') order by date asc 	0
7643736	26416	merge similar rows and sum their values?	select url, sum(art) as art, sum(design) as design from yourtable group by url 	0
7644669	38431	trying to display results in from a join mysql that are no present in one of the tables	select * from a_users  where id not in (select a_student_tutors.mem_id); 	0
7644957	27682	how to join 2 tables in combination with a relational table	select * from phonenumbers,customers,customers_has_phonenumbers          where customers.custumer_id = customers_has_phonenumers.customer_id          and phonenumbers.phonenumber_id = customers_has_phonenumers.phonenumber_id          and customers.customer_id = [id here] 	0.00912036600135033
7645821	31475	replace/convert via sql while querying csv	select cdate(right([business date],2) & "/" _     & mid([business date],4,3) & "/" _     & left([business date],2)) from [filename.csv] 	0.275416713412205
7649850	38831	mysql query on max date	select       id from        organiser as o where        ( select status         from events as e         where e.organiser_id = o.id         order by `date` desc         limt 1       ) = 'active' 	0.0536340208777758
7650627	16274	mysql not union	select t1.cust_no from table1 t1 left outer join table2 t2 on t1.cust_no = t2.cust_no where t2.cust_no is null 	0.718401518275231
7651143	27577	how to add a join based on parameter passed in stored procedure	select pm.*, pou.productnumber  from dbo.products pm left outer join productorgunit pou on                                       pm.productnumber = pou.productnumber 	0.0430213940678041
7653235	13437	mysql query with distinct and order by	select sku_size_part1 as sku_size_part   from sku_data union select sku_size_part2 as sku_size_part   from sku_data union select sku_size_part3 as sku_size_part   from sku_data  order by sku_size_part desc 	0.418327739041712
7654695	41090	query to retrieve days with no data	select prod_fact.moddate from prod_fact where prod_fact.moddate not in (   select distinct moddate   from prod_fact    where moddate = current_date - 7 days  ) 	0.000199879097296746
7654978	10794	using count to find the number of occurrences	select car_made, count(*) from cars group by car_made 	0
7655219	29361	sum() based on a different condition to the select	select m.member_id, m.teamname,      sum(case when r.track_id = '$chosentrack'           then total_points else 0 end) totalchosentrackpoints,     sum(case when r.track_id < '$chosentrack'           then total_points else 0 end) totallessthanchosentrackpoints,      total_points as last_race_points    from members m     join members_leagues l        on l.member_id = m.member_id       join member_results r        on r.member_id = m.member_id  where l.league_id = '$chosenleague'     and l.start_race = '$chosentrack'  group by m.member_id  order by r.total_points desc,       last_race_points  desc, m.teamname desc 	7.71894393881035e-05
7655832	15674	deleting duplicates	select distinct firstname from list; 	0.125163136638836
7658246	2457	how to do grouping?	select purchase_order, supplier_number, date, substring(item_number,1,5) mainproduct, sum(quantity) qty from tablea where purchase_order = '7896' group by purchase_order, supplier_number, substring(item_number,1,5), date 	0.132877807156478
7659418	3114	difference between 2 selects in sql	select *  from table where value not in ( select value from table where user = 1) 	0.013182251025725
7659691	24133	select the largest number of countries from database	select `country`, count(`country`) from `table` group by `country`; 	0
7660048	2518	how do i get the number of rows that have duplicate columns?	select count(distinct name) from (     select name     from  yourtable     where reply = 'yes'     group by name, topic     having count(*) > 1 ) t1 	0
7660068	30706	select latest one from each categories in a table	select cat_id, id   from mytable t  where not exists (         select *           from mytable          where cat_id = t.cat_id            and date > t.date        ) 	0
7660103	8508	mssql: select rows with more than 2 occurances in another table	select campaigntitle, staffno, count (campaigntitle) as [count]   from workson  where staffno in        (select staffno           from staffongrade          where grade > 2)  group by campaigntitle having count(campaigntitle) >2 	0.000130187879441288
7660182	35268	sql assistance with displaying names who have 2 same letters. gives error now	select   ename  from     emp  where    ename like '%l%l%', deptno = 30;  or       super = '7782'; 	0.0149447228138501
7662703	22486	retain ordering from in subquery	select p.*     from projects p         inner join votes v             on p.id = v.project     where v.uid = x     order by v.timestamp desc; 	0.48670921808027
7663539	28785	php/mysql: sort by time, then by date	select ... from status order by `date` desc, `time` desc 	0.00340241163576876
7663656	29802	sum of rows with join	select users.user_id,     users.user_name,     sum(timeduration) totaltime from users join (     select          pstart.user_id,         pstart.leg_id,         (pend.created - pstart.created) timeduration                     from (select pu.user_id,  pu.leg_id,  pu.created         from points_users pu         join points p on  pu.id = p.point_id and pu.leg_id = p.leg_id         where p.is_start = 1 ) pstart     join  (select pu.user_id, pu.leg_id,  pu.created         from points_users pu         join points p on  pu.id = p.point_id and pu.leg_id = p.leg_id         where p.is_start = 0 ) pend     on      pstart.user_id = pend.user_id     and     pstart.leg_id = pend.leg_id     ) tt on users.user_id = tt.user_id group by users.user_id, users.user_name 	0.0228377467448971
7663904	25719	query patient id #s from an excel 2007 list?	select counties.* from counties inner join (importedpatients inner join patients on importedpatients.patientid = patients.patientid) on  counties.countyid = patients.countyid 	0.0521318936738404
7665170	28244	mysql - get recent user visits. display the user only once	select v.* from user_profile_view v  where v.user_id != 1 and v.viewer_id = 1     and not exists       (select * from user_profile_view v2        where v2.user_id = v.user_id and v2.created_at > v.created_at) order by created_at desc limit 0,10; 	0
7665520	35338	query to group by and exclude from multiple lists	select ec.name, count(c.membershipno) as didnotreceive   from customers as c      , email_campaigns as ec  where not exists (     select 1       from email_received as r      where er.campaignname = ec.campaignname        and er.membershipno = c.membershipno)  group by ec.name  order by ec.name; 	0.0163196576339228
7666329	20573	tsql distinct count subquery2	select a.program, a.people_id, sub.event_name, a.program2, a.program3, sub.distinctevent  from (     select k.event_name, count(distinct k.event_name) as distinctevent      from #temp1 as a      join evolv_cs.dbo.facility_view as f on f.group_profile_id = a.group_profile_id      join evolv_cs.dbo.people_x as n on a.people_id = n.people_id      join event_view as k with (nolock) on k.event_definition_id = a.event_definition_id      where @start_date between a.enrolled_date and dateadd(d, 14, a.enrolled_date)      and (@service is null or @service = k.event_name)      group by k.event_name ) as sub  join #temp1 as a on a.event_name = sub.event_name 	0.277281026906353
7666439	23029	write a query to identify discrepancy	select studentid, count(*) dupcount   from table   group by studentid   having count(*) > 1   order by count(*) desc, 	0.727079058102664
7666553	3072	how do you resolve ambiguous aliases in mysql to the current table's definitions	select revenue,         units,         revenue / units as revperunit2  from   (select sum(revenue) as revenue,                 sum(units)   as units          from   inputtable) subsel 	0.135088329167539
7668612	31117	how do i make the rows of a lookup table into the columns of a query?	select s.student_id, s.name,   sum(i.name = 'a') as interest_a,   sum(i.name = 'b') as interest_b,   sum(i.name = 'c') as interest_c from students s inner join interest_lookup l using (student_id) inner join interests i using (interest_id) group by s.student_id; 	0
7668676	1063	count number of repeat rows after multi join statement	select   p.productid,   p.name,   p.storeid,   po.optionid,   oc.choicename,   (select count(*) from optionchoices where optionid = oc.optionid) as option_count from   products   p inner join   productoptions po     on p.productid = po.productid inner join   optionchoices  oc     on po.optionid = oc.optionid     where   p.productid=23317 	0.00110741062875452
7670774	15306	mysql between dates getting the result	select date_start from `mytable` where date(date_start) >= "2011-09-19" and date(date_start) <= "2011-09-30" limit 0 , 30 	0.00238885971122863
7671152	25619	simple way to select all record that are between two date	select user_id, sharj_value, datetime   from users  where user_id = 0653193963 and datetime between '1390/07/12 00:00:00' and '1390/07/14 23:59:59') 	0
7671363	6495	php mysql inventory likeness percentage	select sum(item.qty/(select sum(qty) total from basket where bid = xxx)        * 1/all_item.qty) likeness, basket.bid, all_basket.bid all_bid from basket join item using (bid)      left join      (basket all_basket join item all_item using (bid))      using (iid) where basket.bid = xxx group by basket.bid, all_basket.bid order by likeness desc 	0.126948628093018
7672758	11138	mysql: how to find where a specific primary key is used as a foreign key in other tables?	select    table_name, column_name      from   information_schema.key_column_usage where   referenced_table_name = '<table>'   and referenced_column_name = '<primary key column>' 	0
7675608	33760	sqlite primary key search in multiple tables	select [columns] from [table] where cid = [the cid you're interested in] 	0.0177214979105794
7675924	12620	breaking apart a csv string of id's in mysql to reference for a subquery	select     `d`.`id` as `docid`,     `p`.`human_name` as `permissionname`,     `pd`.`descriptor_text` as `permissionassignments`,     `pd`.`descriptor_text` regexp '.*role\\((-4,)?-3.*' as `everyoneaccess`,     if(`pd`.`descriptor_text` regexp '.*user\\([0-9,]+)$',         (select group_concat(`username`) from users where `pd`.`descriptor_text`             regexp concat('user[(0-9,]*[(,]', `id`, '[\),]')         ),         null     ) from `documents` as `d` inner join `permission_lookups`            as `pl`  on `d`.`permission_lookup_id` = `pl`.`id` inner join `permission_lookup_assignments` as `pla` on `pl`.`id` = `pla`.`permission_lookup_id` inner join `permission_descriptors`        as `pd`  on `pla`.`permission_descriptor_id` = `pd`.`id` left join `permission_descriptor_roles`    as `pdr` on `pdr`.`descriptor_id` = `pd`.`id` left join `permissions`                    as `p`   on `pla`.`permission_id` = `p`.`id` where `d`.`id` = 74; 	0.000675711321449721
7676038	9046	join tables, count based on value in column	select a.id,        sum(case when b.state = 1 then 1 else 0 end) as state1count,        sum(case when b.state = 2 then 1 else 0 end) as state2count     from alpha a         left join beta b             on a.id = b.id     group by a.id 	0.0001566275148983
7677114	30578	mysql query design - calculating a vote score for multiple content items	select i.contentid,         sum(case when v.direction = 1 then 1                 when v.direction = 2 then -1                 else 0 end) as votes     from items i         left join votes v             on i.contentid = v.contentid     group by i.contentid     having sum(case when v.direction = 1 then 1                 when v.direction = 2 then -1                 else 0 end) > -3 	0.00155309099279447
7677179	35190	mysql regular expression to exclude a certain literal at the beginning of a string?	select * from table where      table.field not like "re:%" and table.field like "%joined your network" 	0.000117885293198037
7677610	39665	mysql+vb.net - search in a column with a criteria, then select the highest value in the result	select max(id) from data where left(cast(`id` as char(10)), 1) = '3'; 	0
7678334	35208	mysql, php jquery.autocomplete single row search using multipule :term words	select productname from products where productname like :term[0] and productname like :term[1] 	0.0924482589005978
7679638	9569	counting rows by a condition in another table	select count(*) from table1 t1 inner join table2 t2 on t1.my_foreign_key_column = t2.my_primary_key_column where t2.creation_date >= 'my_date_literal' 	0.000214960122717512
7680230	37919	sql query to find count of values in two  columns	select number, count(number) as `count` from (   select      case       when to = 'me' then from       else to     end as number     from table   ) group by number; 	5.67090660898671e-05
7680628	8703	how to combine two numeric fields?	select name, cast(adress1 as varchar(20)) + cast(adress2 as varchar(20)) as columnz from table1 	0.0029624119528261
7682206	37267	sql - counting people with same job. simple code given	select     job,     count(job) from     emp e group by     job 	0.0446630215236033
7686049	10119	sql select to make a value appear only once	select d1.username, d1.tweet, d1.date from data d1 where d1.date =      (select max(d2.date) from data d2 where d1.username = d2.username) 	0.000532311044057066
7686469	18850	query the contents of stored procedures on sql server	select object_name(object_id),        definition from sys.sql_modules where objectproperty(object_id,'isprocedure') = 1   and definition    like '%foo%' 	0.0604604637126942
7689590	32595	finding last and previous values in the group with fast mysql query	select  a.*,          (select top 1 id from yourtable where fid = a.fid and id < b.maxid order by id desc) id2,         (select top 1 value1 from yourtable where fid = a.fid and id < b.maxid order by id desc) previous_value1 from yourtable a inner join (select fid, max(id) maxid             from yourtable              group by fid) b on a.id = b.maxid order by a.fid 	0
7690586	11101	msql inner join query dilemma - need joined auto increment value	select `car`.id as car_id, `requests`.id as request_id, *  from `car`  inner join `requests` on `car`.`make_id` = `requests`.`make_id`  where `car`.`user_id` =21 	0.105140156597663
7693337	36332	i want to divide date of a particular interval into 10 parts and query the count for each part in mysql	select ((unix_timestamp(date_col) / cast((time2 - time1)/10) as int) + time1), count(id) from my_table where date_col >= time1 and date_col <= time2 group by ((unix_timestamp(date_col) / cast((time2 - time1)/10) as int) + time1) 	0
7693613	29782	select most common value from a field in mysql	select column, count(*) as magnitude  from table  group by column  order by magnitude desc limit 1 	0
7695335	22777	select count(*) multiple rows and display result	select            (select count(*) from set_1           where set_1.start between list.start and list.end) as [count] from list 	0.000232482781404038
7695660	31629	query for creating database for a new project	select count(*) from table; 	0.201036863423364
7698533	24650	sql join when there is a corresponding post or not	select c.customerid, p.phonenumber, cc.complaint from customer c inner join customerphone p on p.customerid = c.customerid left join customercomplaint cc on cc.customerid = c.customerid 	0.454432617429003
7699143	12317	comparing multiple rows of data in sql	select top 1 *  from technician where _status = 'available' order by last_available_time 	0.00145197491822655
7699169	28192	retreive resultset based on where clause condition order in sql server	select * from mytable where colid in ('c', 'a', 'd')     order by        case colid           when 'c' then 0           when 'a' then 1           else 2        end 	0.0414015643971626
7700932	30198	mysql sum column1 if column2 equals today and column3 equals specific test	select item, sum( quantity ) as total from orders where date_prod = '2011-10-01' group by item 	6.92380211316963e-05
7703610	7476	return last id and count of id	select count(*), max(id) from mytab where category = 1 	0
7705050	29468	mysql: select data from a table where the date falls in the current week and current month	select * from posts where    week(post_date) = week(curdate())    and    month(post_date) = month(curdate()) 	0
7706990	26275	select all rows which satisfy constraints from another table	select a.*   from actions a  where not exists        (    select 1      from has_constraints hc     where hc.action_id = a.id       and not exists           (           select 1          from assure_constraints ac        where ac.state_id = $my_state_id          and ac.constraint_id = hc.constraint_id)) 	0
7707945	36925	deriving a column's data from a matching column in sql	select empgrunt.ename employee      , empgrunt.empno empnum      , empsuper.ename supervisorname      , empsuper.empno supervisorname from   emp empgrunt left outer join emp empsuper         on empgrunt.super = empsuper.empno 	4.6436991689869e-05
7708400	5009	tsql to number an ordered set	select mydate, ((row_number() over (order by mydate) - 1) % 4) + 1 from mytable 	0.00659505150373782
7708427	36972	two queries optimize	select  `type`,          count(`post`=`id`),          count(`post`!=`id`) as 'posts'  from    `items`  group by    `type`; 	0.533262828935875
7708890	41260	sqlite get last row id after connection is closed	select seq from sqlite_sequence where name=@table 	0
7710606	4103	jqpl: create new object within the query from multiple tables	select new com.test.customobject(t1.name, case when exists(select t2.id from table2 t2 where t2.id = :id2) then true else false end) from table1 t1 where t1.id = :id1 	0.00329269832838433
7710822	9231	getting the result of a mysql query order by date when the date field can contain strings differents than dates	select t.*, case when date_end = 'present' then curdate() else convert(concat(substr(date_end,7,4),'-',substr(date_end,1,2),'-'    ,substr(date_end,4,2)),date) end as "realdate" from mytable t order by "realdate" desc; 	0
7711605	30432	how to search with firstname and last name in - mysql	select * from contracts  where lower(concat_ws(' ', field_profile_first_name_value, field_profile_last_name_value))  like lower('%victor bre%') 	0.0108528229593345
7712340	11793	sales and refunds table	select sum(numberofsales) as numberofsales,sum(salevalue) from ( select count(sales) as numberofsales, sum(sales.value-refunds.value) as salevalue from transactions sales left join transactions refunds on sales.transid=refunds.refundid where refunds.refundid is not null and sales.value-refund.value>0 and sales.date>@begindate and sales.date<@enddate and sales.refund_flag='s' union select count(sales) as numberofsales, sum(sales.value) as salevalue from transactions sales left join transactions refunds on sales.transid=refunds.refundid where refunds.refundid is null and sales.date>@begindate and sales.date<@enddate and sales.refund_flag='s') 	0.0421208318379326
7712365	5827	mysql: check if there exist row(s) matching a condition	select case          when exists(select *                      from   yourtable                      where  condition = '*condition*') then 1          else 0        end 	0.0016925828422232
7712679	27826	select columns by numbers - select [m:n] from table_name	select [3:6] from table_name 	0.000341585714004822
7712728	33653	how to find single row records from two rows data with atttime in sql server	select enrollno, min(attdate), min(attmonth), min(attday), min(attyear), min(atttime) as firsttime, max(atttime) as lasttime       from attlog   group by enrollno 	0
7713895	20855	grouping, counting and excluding based on column value	select     w.projectid as project    ,count(*) as `staff count` from work w inner join      (select distinct w2.projectid          from work w2         inner join staff s on (w2.staffid = s.id and s.unit = 'chicago')) c on (w.projectid = c.projectid) group by w.projectid 	0
7714744	26641	sql - oracle database 10g group by queries	select title, sumgradegreaterthan2       from (select   camp.title, count (*) as staffmembers,                      sum (case                              when stfogrde.grade > 2                                 then 1                              else 0                           end) as sumgradegreaterthan2                 from  campaign camp                 left join workson wo on camp.title = wo.title                 left join staff stf on wo.staffno = stf.staffno                 left join staffongrade stfogrde on stf.staffno = stfogrde.staffno             group by camp.title)      where staffmembers > 3 	0.738545700986751
7714987	38763	way to list xml entities in sql server using xml methods?	select     b.value('local-name(.)','nvarchar(max)') as col1,     b.value('data(.)','nvarchar(max)') as col2 from @xml.nodes(' 	0.738518759609066
7716580	38877	having query to compare	select    sum(sembrado.f_areasiembra) as summedarea,    (select sum(f_areadedicadacultivos)       from fnc_tenenciausotierra       where c_fk_idboleta = sembrado.c_fk_idboleta)    as areadedicadacultivos from    clt_sembrado as sembrado where    sembrado.c_fk_idboleta = 45550711 group by sembrado.c_fk_idboleta having sum(sembrado.f_areasiembra) <= (select sum(f_areadedicadacultivos)       from fnc_tenenciausotierra       where c_fk_idboleta = sembrado.c_fk_idboleta) 	0.128894011842309
7717810	10476	union with different quantities of columns in the select-list?	select 'pregunta (12) el área sembrada es mayor al área dedicada a cultivos' as descripcion_error,    c_fk_idboleta as boleta,    (select sum(f_areadedicadacultivos)       from fnc_tenenciausotierra       where c_fk_idboleta = sembrado.c_fk_idboleta)    as areadedicadacultivos,    sum(sembrado.f_areasiembra) as areasembrada,     null as tenencia_finca from clt_sembrado as sembrado 	0.0015376820722267
7719425	39614	making opposite of select in mysql query	select name where name not in (select name where fruits like '%apple%') 	0.349217552384396
7719689	2530	get count of all results with limit in the query	select sql_calc_found_rows `p`.`name`, `f`.*     from `players` `p`, `folks` `f`     where `p`.`id` = `f`.`guid`      and `f`.`deleted` = 0     and `first` = {$id}      and `text` like ?     limit 10 select found_rows(); 	0.00071209258913132
7719855	21087	how to select data from database given an include all restriction?	select    firstname,    lastname from    table1 group by    firstname,    lastname having    count(distinct roomname) = (select count(*) from table2) 	0
7722721	21498	identify input and output parameters in stored procedure	select name,         is_output from sys.parameters where object_id=object_id('dbo.yourproc') 	0.790924696111457
7723005	40946	oracle new table is not accessible with only table name	select * from all_synonyms; 	0.0254422428241159
7724189	24072	mysql query with date range and selecting only the most recent records for each id	select t1.*  from `mytable` t1 inner join ( select max(`timestamp`) as timestamp from     `mytable` where    `date`  between  '2010-01-01' and      '2011-03-03' group by `id`  ) t2 on t1.timestamp = t2.timestamp 	0
7724197	26265	sum over timerange overlapping to next day over several days	select   date(date_sub('date', interval 15 hour)),   sum(val) from   tblvals where   time(date_sub('date', interval 15 hour)) < '19:00' group by   date(date_sub('date', interval 15 hour)) 	0
7724803	26088	getting a rank out of a total	select count(*) as 'total',         sum(case when score >= 'score' then 1 else 0 end) as `rank` from table where condition = 'condition'; 	0.000442531969947356
7724979	22462	how to get the most recent n entries in a subquery group?	select   `user_id`, sum(`value`) from     logs` as l where    (select count(*)           from `logs`           where `user_id` = l.`userid` and `date_created` > l.`date_created`) < 3 group by `user_id` 	0
7725236	35530	selecting the least value in a joined table	select   product.title,   product.url_name,   product.description,   a.price,   image.thumbnail from   mps_contents as product   left outer join     mps_contents as image      on       image.page_id = product.content_id and       image.display_order = '1' and       image.resource_type = 'image'   left outer join (       select price.price        from mps_contents as model        join mps_product_info price on (model.content_id = price.content_id)        where model.page_id = product.content_id        order by price.price       limit 1   ) as a where   product.active = '1' and   product.resource_type = 'product' and   product.featured = '1' order by rand( ) limit 3 	0
7726254	4039	mysql query with a conditional max value	select avg (least(500, rawsentiment) * magic_coefficient) from sentiment 	0.267028528402317
7726936	40274	group by time span in sql server 2008	select convert(date,entrytime) [date],        deviceid,        min(value) minvalue,        max(value) maxvalue,        avg(value) avgvalue from yourtable group by convert(date,entrytime),          deviceid 	0.33375397738235
7727174	36491	mysql aggregation function to sum the differences from row to row	select a.id,         b.value - a.value difference  from   mytable a         join mytable b           on b.id = a.id + 1 	0.000113066935166379
7728364	24406	how to get the average of a nested query returned as a single result based on the parent query	select s.name,s.surname,s.student_id,s.studentnumber,c.course, b.campus_title,m.module,sm.percentage_obtained,s.days_absent, sm2.avgpercentage_obtained from students s  inner join student_courses sc on sc.studentid = s.id  inner join courses_template c  on c.id = sc.courseid inner join branches b on b.id = s.branchid  inner join student_modules sm on sm.studentid =s.id inner join modules_template m on m.id = sm.moduleid outer apply (select avg(percentage_obtained) avgpercentage_obtained              from student_modules               inner join modules_template on modules_template.id = student_modules.moduleid              where student_modules.module = m.module) sm2 	0
7730296	25674	how to get sum of votes for an item in a db?	select item_id , title , description , sum(votes) as totalvotes from items      left join votes on     items.item_id = votes.item_id     group by votes.item_id     order by item_id desc 	5.94979734194248e-05
7732643	24145	how to join data from three different tables?	select   t1.column1 as columna,   t1.column2 as table1value,   t2.column2 as table2value,   t3.column3 as table3value from table1 t1 join table2 t2 on t2.column1 = t1.column1 join table3 t3 on t3.column1 = t1.column1 	0.000720133982440417
7733994	23027	count records in ms access using query	select v.scaledscore as [scaled score], count(i.rawscore) as [count] from verbal v left join basicinfo i on v.rawscore = i.rawscore group by v.scaledscore 	0.28764532215493
7734152	16020	can you pivot and aggregate on two columns with a sql pivot query	select performanceid,         judgeid,         [stuntsstrength] = avg(case when criteria = 'stunts' then strengthscore else null end),         [stuntsstyle] = avg(case when criteria = 'stunts' then stylescore else null end),         [jumpsstrength] = avg(case when criteria = 'jumps' then strengthscore else null end),         [jumpsstyle] = avg(case when criteria = 'jumps' then stylescore else null end),         [tumblestrength] = avg(case when criteria = 'tumbling' then strengthscore else null end),         [tumblestyle] = avg(case when criteria = 'tumbling' then stylescore else null end),         [chorstrength] = avg(case when criteria = 'choreography' then strengthscore else null end),         [chorstyle] = avg(case when criteria = 'choreography' then stylescore else null end) from    dbo.judgescores group by      performanceid, judgeid; 	0.332423111659054
7734541	25191	mysql - find duplicate users with firstname/lastname swapped	select    * from usertable ut join usertable ut2 on ut2.firstname = ut.lastname and ut2.lastname = ut.firstname 	0.00253227492811421
7735419	37565	sql: select n “most recent” rows in ascending order	select timestamp, message from (      select *      from your_table      order by timestamp desc      limit 3  ) t1 order by timestamp 	0
7736114	37501	how can i get the column names of a table referred by a dblink?	select column_name   from all_tab_columns@my_dblink  where table_name = 'my_table' 	0
7736903	39702	mysql query - how to force sign "_" in pattern matching?	select * from test where id like '1\_%'; 	0.278354139604655
7737049	2812	return shortest string if matches in first two or more words - php mysql	select distinct( trim(   left(title,     if( locate('dvd', title),         locate('dvd', title) - 1,         if( locate('bluray', title),             locate('bluray', title) - 1,             999         )     )   ) )) from `prprod_films` 	0.000129541585103948
7737207	32314	mysql details about tables	select table_name, count(column_name) as num_columns  from information_schema.statistics s      where table_schema = database() group by table_name order by table_name 	0.619486605258117
7738894	32185	sum of count of column for group by two columns mysql	select date_format( joined, '%m/%y' ) as     month , team, (     count( id ) / (     select count( * )     from tablex     where date_format( joined, '%m/%y' ) = date_format( tx.joined, '%m/%y' )     group by date_format( joined, '%m/%y' ) ) *100     ) as percentage     from `tablex` as tx     group by date_format( joined, '%m/%y' ) , team 	5.19865547661064e-05
7739602	30058	how to get the current effective date in oracle?	select tid,        tname,        effectivedate,        decode(sign(effectivedate - (select max(t2.effectivedate)                                      from mytable t2                                     where t1.tname=t2.tname and                                            t2.effectivedate <= sysdate)),               -1,'invalid',               0,'valid',               'inactive') status from mytable t1 	6.80247822350913e-05
7739789	25683	mysql innodb auto-increment pre-fetching values	select max(id) + 1 from table_name; 	0.500519517441955
7740519	27238	convert datetime to varchar	select cast(month(datefield) as varchar) + '/' + cast(day(datefield) as varchar) 	0.0631133475154518
7742556	23711	trouble with mysql sum of multiple datetimes	select sum(time_to_sec(timediff(end_date, start_date))) as timesum from schedules 	0.0968904799620685
7744108	21658	order rows in sql query based on which rows meet condition first	select     * from     images i where      i.name like '%test%'     or i.description like '%test%' order by     case         when i.name like '%test%' then 0         else 1     end asc; 	0
7744128	11825	only select count value if total row count is equal to row count with special id	select isnull(b.numrows, 0) as numrows from (     select count(*) as numrows from car ) a left join (     select count(*) as numrows from car where redcar = 'yes' ) b on b.numrows = a.numrows 	0
7744857	3230	adding total wages by group in php and mysql	select      schedules.group_id,      sum(employees.wages) as total_wages from schedules inner join employees      on schedules.emp_id = employees.emp_id where      schedules.sch_id = 55 group by      schedules.group_id 	0.0328369431620208
7748728	31737	sql statement that excludes the same records in a relational database	select id, nome from jobs where id not in (select jobs_id from jobsmanagement) 	0.00216168512045799
7749041	716	row concatenation with for xml, but with multiple columns?	select  thistable.id        ,[a].query('/somefield').value('/', 'varchar(max)') as [somefield_combined]        ,[a].query('/somefield2').value('/', 'varchar(max)') as [somefield2_combined]        ,[a].query('/somefield3').value('/', 'varchar(max)') as [somefield3_combined] from    thistable         outer apply (                      select (                              select somefield + ' ' as [somefield]                                    ,somefield2 + ' ' as [somefield2]                                    ,somefield3 + ' ' as [somefield3]                              from   sometable                              where  sometable.id = thistable.id                             for                              xml path('')                                 ,type                             ) as [a]                     ) [a] 	0.0102682539300279
7749576	35564	check if master record date in table a is later than latest records date in joined table b	select people.* from people   join actions on actions.peopleid = people.id   group by people.id   having max(action.creationdate) < people.alterationdate 	0
7750230	1306	php and mysql displaying 1 record of multiple name	select * from images   where eventname='name'  group by eventname 	0.000644325150123937
7750396	15312	oracle random row from table	select col1, col2, dbms_random.value from table order by 3 	0.00107695395793729
7752620	26681	many to many sql query for selecting all images tagged with certain words	select i.id, i.relative_url, count(*) as number_of_tags_matched from   images i     join tags_image_relations ti on i.id = ti.image_id     join tags t on t.id = ti.tag_id     where t.name in ('google','microsoft','apple')     group by i.id having count(i.id) <= 3     order by count(i.id) 	0.000146565920422289
7753080	27988	select row n times with sql	select     pg.showcount,     p.name,     g.groupname from persongroup pg inner join person p on p.personid = pg.personid inner join groups g on g.groupid = pg.groupid inner join dbo.numberstable(1,12,1) n on pg.showcount >= n.i 	0.00106706657902434
7753302	11457	what is the difference between checksum_agg() and checksum()?	select category, checksum_agg(checksum(*)) as checksum_for_category from yourtable group by category 	0.314513593740104
7753410	19238	mysql query order by supplied condition	select * from newmessage     where id in (5, 3, 2, 1, 4)     order by field(id, 5, 3, 2, 1, 4) union select * from newmessage where id not in (5, 3, 2, 1, 4) 	0.755144438550494
7753532	36687	is it possible to insert a new row at top of mysql table?	select * from users order by id desc 	0.000184953009250852
7755013	4271	function to check if a string contains a word from a database	select word from blocked_list where "you string" like concat("%", word, "%") 	0.00133461953271257
7755161	6656	how do i count the similar entries in a table?	select companyid, count(companyid) as totalentries from yourtable group by companyid 	0.000206122122530178
7756409	682	how to retrieve all entries with join?	select    ss.sub_service,    dd.date,   ts.qt from    (datedim dd, (select distinct sub_service from test) ss)  left join test ts on (dd.date = ts.date and ts.sub_service = ss.sub_service) order by ss.sub_service, dd.date 	9.68925413270085e-05
7757452	31949	mysql join to return count(report) from all places, even where the number is zero	select c.province, c.country, c.lat, c.lng, count(r.title)     from countries c         left join reports r             on c.province = r.province                 and c.country = r.country                 and c.lat = r.lat                 and c.lng = r.lng     group by c.province, c.country, c.lat, c.lng 	6.94820416369962e-05
7757513	37759	mysql distinct on one column with other max column	select report_id, max(time_sent) from  report_submissions where report_id in (1,2,3,4,5,6) group by report_id order by report_id asc 	8.83073326578509e-05
7758054	37164	searching returned records in mysql	select the_id, type, county from (     select type_name.the_id as the_id, type.field_value as type, county.field_value as county     from yourtable as type     left join yourtable as county on county.the_id = type.the_id and county.field_name='county'     where type.field_type = 'type' ) as child where county='lincolnshire' 	0.0184153014017982
7758167	8821	sql join 3 tables, unique rows, calculation across tables	select col1, sum(col2) as col2 from ( select col1, col2 from table1 union all select col1, col2 from table2 union all select col1, col2 from table3 ) as sub group by col1 	0.000982088992905323
7759558	5755	performing a sub query using values from the main query in postgres	select     world_id,     world_name,     player_id     count(*) as stats from     worlds     join players using (player_id)     join objects_destroyed using (player_id) where     player_id = <insert player id> group by world_id, world_name, player_id 	0.145359222539007
7760650	6890	checking for unique values from mysql db	select column1, column2 from table where column1='value1' or column2='value2' 	0.00111492510795871
7760996	21940	sort output from multiple tables	select t1.id1,t1.name from table1 t1, table2 t2  left join table3 t3 on t3.id = t1.id where t1.id=t2.id; 	0.00785114017169597
7761023	5290	join sql query to get data from two tables	select register from table_b b where not exists (select register from table_a a where a.register = b.register) 	0.000837473751276484
7766679	38961	how to write two replace functions in one select statement in oracle	select replace( replace( message, chr(acii_value), 0), chr(10), ' ')  from my_table; 	0.418777243446913
7767459	19207	how to get both my friends & friends of friends?	select friend_user_id from friends where user_id = ? union select f2.friend_user_id from friends f1 join friends f2 on f2.user_id = f1.friend_user_id where f1.user_id = ? 	0
7768563	7340	which type of join do i need?	select c.contract_id from contract c left outer join salesmen s on s.salesman_id = c.salesman_id where c.salesman_id is null 	0.266654736927321
7769656	20106	mutual friend column, select a pair only once	select id1,        id2 from   likes l1 where  id1 > id2        and exists(select *                   from   likes l2                   where  l1.id1 = l2.id2                          and l1.id2 = l2.id1) 	0.000110614448521743
7772738	13572	need to return title and count of each department from mysql	select d.title, count(dc.comment_id) as total_comments     from departments d         left join department_commments dc             inner join comments c                 on dc.commment_id = c.id                     and c.year_code = 1011             on d.id = dc.department_id     group by d.title 	0
7772913	9155	mysql group by doesn't give me the newest group	select    building   , appartment_id   , status  from ib30_history a where id = ( select max(id) from ib30_history b               where b.building = a.building and b.appartment_id = a.appartment_id) 	0.566168641863612
7773759	15434	postgres rank as column	select *  from (     select name,             rank() over (partition by user_id order by love_count desc) as position      from items ) t where position = 1 	0.0732474665110777
7778094	22908	whats "now" in sql server?	select sysdatetime()     ,sysdatetimeoffset()     ,sysutcdatetime()     ,current_timestamp     ,getdate()     ,getutcdate(); /* returned: sysdatetime()      2007-04-30 13:10:02.0474381 sysdatetimeoffset()2007-04-30 13:10:02.0474381 -07:00 sysutcdatetime()   2007-04-30 20:10:02.0474381 current_timestamp  2007-04-30 13:10:02.047 getdate()          2007-04-30 13:10:02.047 getutcdate()       2007-04-30 20:10:02.047 	0.629701060215746
7779784	23792	query to get non matching values from two table	select d.departmentname,e.employeename from department as d full join employee as e     on e.departmentid = d.departmentid where e.departmentid is null or d.departmentid is null 	0
7780048	3980	oracle select where value exists or doesn't exist	select cases.*, users.*, user_meta.* from cases join users on users."user_id" = cases."user_id" left join user_meta on user_meta."user_id" = users."user_id" and user_meta."meta_key" = ? 	0.479778100925096
7780306	3297	limit mysql query with select in select	select *    from messages    join messages_tags tags on tags.msg_id = messages.msg_id   where tags.tags = 'grusiin'    group by messages.msg_id   order by messages.msg_id    limit 5; 	0.426804038951312
7780315	4001	list of product customer didn't ordered?	select p.product_id, p.product_name from product p  join inventory i on p.product_id = i.product_id left join order o         on o.inventory_id = i.inventory_id         and o.customer_id = '1' where o.customer_id is null 	0.000199022778178584
7780795	38330	sql where if else	select * from p where p.storeid = @storeid or @storeid > 1 	0.790527764617119
7781421	34109	mysql selecting multiple values from the same column as a row	select c.id, c.name, condo.price, condo.rate, town_home.price, town_home.rate from community c left join property condo on condo.community_id = c.id and condo.type = 'condo' left join property town_home on town_home.community_id = c.id and town_home.type = 'town_home' 	0
7781834	11784	returning all items on a mysql join, not just ones that are matching	select i.item_id, c.user_id, if(c.user_id is null, 0, 1) as extra_column from items i left join checkouts c on (c.item_id = i.item_id and c.user_id = 10) 	5.90327838981132e-05
7783298	12349	sql add up all values in column per month	select     year(`date`) as theyear, month(`date`) as themonth,      sum(amount) as monthlytotal from      sometable group by      year(`date`), month(`date`); 	0
7783305	8024	how do i total up "yes's" from a column, by a userlevel and only for the past week? using php and sql	select userlevel, count(*) from form_2 where timestamp between x and y and signatu = 'yes' group by userlevel 	0
7783557	27974	sql: combining results	select     'name' as type,     id as r_id,     null as i_id,     name,     address,     null as m_id from restaurants where name like '%string%' union all select     'address' as type,     id as r_id,     null as i_id,     name,     address,     null as m_id from restaurants where address like '%string%' union all select     'item' as type,     null as r_id,     id as i_id,     name,     null as address,     m_id from menu_items where name like '%string%' 	0.22695050955564
7783650	19961	how to get max value from 2 tables	select    id, max(total) from     (     select id, total from table1     union all     select id, total from table2     ) foo group by    id 	0
7784600	35774	mysql query string for selecting certain row with a id	select title, date, content from table where id=5 	0
7790472	15435	how to find out the duplicate records	select    id, transaction, value from    table1 group by    id, transaction, value having count(id) > 1 	8.62484964346295e-05
7793012	35537	how to get a total of last five values in sqlite?	select  sum(avtime) from   (select average_time as avtime     from tbl_timer    order by id desc limit 5) 	0
7793331	31566	in mysql, using a query, is there a way to get total time in hours when the time is stored in minutes?	select doctor_id, sum(minutes_spent) / 60 as hours_spent from that_table group by doctor_id 	0
7794154	8443	write a query that pulls all fields from a table that has date in it	select column_name from information_schema.columns where table_name = 'yourtablename' and data_type like '%date%' 	0
7794242	7593	t-sql if value exists use it other wise use the value before	select t.account#, t.period, t.balance     from (select account#, max(period) as maxperiod               from table1               where period <= @inputperiod               group by account#) q         inner join table1 t             on q.account# = t.account#                 and q.maxperiod = t.period 	0.0019356312545641
7796345	27265	column '_id' does not exist simplecursoradapter revisited	select distinct room, 1 _id from tblrates where resid='abc' and date='2011-10-17' 	0.768686058197686
7796786	16576	sql query - fetch data from one column separated by comma	select * from table2, table1          where table1.id=$id          and find_in_set(table1.id, table2.table1id) <> 0 	0
7797743	32630	mysql query that matches two fields and has another field in common	select *     from yourtable t1         inner join yourtable t2             on t1.f1 = t2.f1     where t1.f2 = 'hi'         and t2.f2 = 'sup' 	0
7798361	1634	t-sql temp tables	select into 	0.220362894959718
7799706	8001	group sql query output by date	select conceptname,cast(datepart(year, inputdate) as varchar) + '/' +      cast(datepart(month, inputdate) as varchar) as rptmonth, count(*) as      tot   from concepttable ct join blog on content like      '%'+ct.conceptname+'%'   group by conceptname, cast(datepart(year,      inputdate) as varchar) + '/' + cast(datepart(month, inputdate) as      varchar) 	0.323765924339273
7800604	5524	select the latest mysql data but unique resort	select t.* from yourtable t join     (select resort, max(dateadded) dateadded     from yourtable     group by resort) m on t.dateadded = m.dateadded and t.resort = m.resort order by t.resort 	0.000199008781365031
7802900	21756	mysql sum, with row ids	select group_concat(id), sum(value) from table 	0.00142328740532463
7802944	26401	explicitly specify sort order for mysql query?	select * from table order by field(id,4,2,5,3,1) 	0.599092720046868
7803569	29022	get result by category with count for each category	select category as 'category/subcategory', count(*) as 'count' from  categories group by category union select subcategory as 'category/subcategory', count(*) as 'count' from  categories group by subcategory 	0
7803775	10409	sql queries involving ' for all'	select pg.name  from participation as p inner join programme as pg on p.pid = pg.pid group by p.pid  having count(*) = (select count(*) from employeee) select e.name  from participation as p inner join employee as e on p.eid = e.eid                         inner join programme as pg on pg.pid = p.pid where pg.department = e.department group by p.eid, e.department, e.name having count(*) = (select count(*)                     from programme as pg2                     where pg2.department = e.department) 	0.144156209682573
7808815	24081	selecting value from different schema	select tokenvalue from [insert schema here without brackets].tokens where typeoftoken = 'registration' and user_id = '48' 	0.000213720607435714
7809475	2459	sql select row where id=max(id)	select pd_id, pd_title, pd_description, pd_colour,        pd_price,pd_large_image,pd_date,cat_sub_id_3,pd_new from product  where    cat_sub_id_1 = '".$cat_sub_id."'    and cat_parent_id='".$cat_parent_id."'    and pd_id = (select max(pd_id) from product) group by pd_title 	0.112332851394414
7810006	9267	mysql query - group by one field and ordering by another	select member_id, from_unixtime(max(stamp)) as log_time from logins group by member_id order by stamp desc 	0.00378466107121124
7810108	32529	sequence and case in a select in oracle	select case when 1=0 then 'next ' || seq_id.nextval      when 1=1 then 'curr ' || seq_id.currval end col1 from dual; 	0.63004471816336
7814030	40121	mysql limit 1 row of multiple rows with same value in a column	select * from user_cars group by user_id 	0
7814440	14614	condition based select and join queries	select t2.mark, t2.age from table1 t1, table2 t2 where   t1.id=t2.id and   t1.id=1500 union select mark, age from table1 where   not id=1500 	0.0375039630008195
7815323	4871	search in grouped columns in mysql?	select g.name guy, a.name attribute, v._value value from guy g  join _value v on g.id = v.guy_id  join attribute a on a.id = v.attribute_id group by guy having (     sum(a.name = 'age'     and v._value > 10) = 1 and     sum(a.name = 'dollars' and v._value < 18) = 1 and     sum(a.name = 'candies' and v._value > 2 ) = 1 and     sum(a.name = 'candies' and v._value < 10) = 1        ) or        (     sum(a.name = 'age'     and v._value = 15) = 1        ) 	0.0114715643799348
7818887	40065	adding all the rows of same year using sql query instead of php code	select   ano,   sum(mes),   sum(s),   sum(n),   sum(o),   sum(total) from    mytable group by ano 	0
7819375	957	counting occurrences of unique values in a column using sql	select columnname, count(*) from tablename group by columnname 	0
7819654	28184	sql to get all the friends of friends who's not my friend	select f2.friend_id from friendships f join friendships f2 on f.friend_id = f2.user_id where f2.friend_id not in (select friend_id from friendships where user_id = @user_id)   and f.user_id = @user_id 	0
7821392	33895	how do i compare row count in a mysql statement?	select id, count(*) from table1 where date = 0000-00-00 group by id having count(*) = 4 	0.007559583490837
7821623	38039	matching two columns	select * from tablea where term_a in      ( select term_a from tablea       intersect       select term_b from tableb ) ; 	0.00120912802644339
7823344	38359	sql query group data	select [group], max(jan), max(feb), max(mar)     from yourtable     group by [group] 	0.361183720608117
7823539	30908	mysql union give priority to record from one of the select queries in case of duplicates	select *  from   ((select deal.dealid,                  deal.titleen,                  deal.capnum,                  deal.imagelink,                  sum(buy.quantity) as quantity,                  'a'               sortby           from   buy,                  deal           where  buy.dealid = deal.dealid                  and buy.isfinalbuy = '1'           group  by buy.dealid           having quantity = deal.capnum)          union          (select deal.dealid,                  deal.titleen,                  deal.capnum,                  deal.imagelink,                  null as quantity,                  'b'  sortby           from   deal           where  deal.enddate < curdate()))a  order  by dealid,            sortby,            titleen,            capnum,            imagelink,            quantity asc 	5.62828371848854e-05
7823596	38882	how to left join same table on different rows in one query	select * from message_treads left join usernames uid1 on uid1.uid=message_treads.uid_1 left join usernames uid2 on uid2.uid=message_treads.uid_2 	0.00012672412842822
7827213	30041	join but only get once with newest date	select c.customerid, c.fullname, c.sex, t.id as transid, t.bookingdate     from customer c         inner join (select customer, max(bookingdate) as maxdate                         from transaction                         group by customer) q             on c.customerid = q.customer         inner join transaction t             on q.customer = t.customer                  and q.maxdate = t.bookingdate; 	4.82832292147097e-05
7827649	17457	how to find next free unique 4-digit number	select idstring from idstringtable order by idstring asc where (available = 1) limit 1 	0
7827664	4270	joining on a select distinct in mysql reorders by joined table	select a.user_id, u.name    from article a    left join user u on u.id = a.user_id    group by a.user_id   order by max(a.id) desc 	0.00261392527039573
7828671	25962	how to combine these two queries into one	select   posts.id,   posts.type,   posts.title,   posts.body,   posts.date,   posts.author,   posts.email,   cat.name from   posts left join      cat_mapping as map on map.post_id = posts.id left join      cat_collection as collection on map.collection_id = collection.id where   posts.id = 1 	0.000494886556044404
7828736	18572	how do i add several rows to a table in one insert, tracking the count as i go?	select @val := 1; insert into yourtable (valfield) select (@val := @val + 1) from any_existing_table where @val < 100; 	6.73609777005516e-05
7829118	38381	how do i add a "total_num" field by aggregating equal values with sql?	select s.state, s.region, s.capital, count(*) as 'count' from secondtable s join firsttable f on s.state = f.state group by f.state, f.region, f.capital order by count(*) desc 	0.00389895164182017
7829524	7389	mysql return a value and the number of times its referenced from a mapping table	select cc.name, (select count(cm.id) from cat_mapping cm where cm.collection_id = cc.id) as cnt from cat_collection cc 	0
7830473	32553	finding total participation in sql	select s.sid, s.sname, s.deptid     from students s         inner join participation p             on s.sid = p.sid         inner join courses c             on p.cid = c.cid                 and s.deptid = c.deptid     group by s.sid, s.sname, s.deptid     having count(distinct c.cid) = (select count(*)                                         from courses c2                                         where c2.deptid = s.deptid) 	0.00586849730237777
7830978	38832	how can i select two columns from a table and combine the values into one column	select tbl_products.start_date from tbl_products union  select tbl_products.end_date from tbl_products 	0
7831318	31967	get all data with 2 different values in mysql	select name from table group by name having count(email_account) > 1 	0
7833365	14336	implement min or get the lowest record	select  t1.name,  t1.description,  t1.issue,  t1.dateres as atime,  t2.dateres as back,  min(timediff(t2.dateres,t1.dateres)) as totaltime,  t2.acknowledge, t2.resolution  from t1 left join t2 on t1.name = t2.name  and t1.ipaddress = t2.ipaddress  and t1.description = t2.description  and t1.issue = t2.issue  and t1.severity = t2.severity  and t1.timestamp = t2.timestamp  where t1.dateres is not null and t2.dateres is not null  and t2.acknowledge = 'user@home.net'  and t2.dateres >= '2011-10-18 00:00:00'  and t2.dateres <= '2011-10-23 23:59:59'  group by t1.name order by back asc; 	0.00172089173009371
7836036	36100	how to select by max(date)?	select report_id, computer_id, date_entered from reports as a where date_entered = (     select max(date_entered)     from reports as b     where a.report_id = b.report_id       and a.computer_id = b.computer_id ) 	0.111877438561007
7836242	39250	common record from 2 tables in sql server	select * from table1  join (select id, sum(amt) as amt from table2 group by id) t2 on t1.id = t2.id and t1.amt=t2.amt 	9.44722785383588e-05
7836384	2569	get remaining days, hours and minutes using mysql	select  timestampdiff(day,now(),'2012-01-01') as day,         timestampdiff(hour,now(),'2012-01-01')-timestampdiff(day,now(),'2012-01-01')*24 as hour,         timestampdiff(minute,now(),'2012-01-01')-timestampdiff(hour,now(),'2012-01-01')*60 as minute; 	0
7836906	39782	how to remove carriage returns and new lines in postgresql?	select regexp_replace(field, e'[\\n\\r]+', ' ', 'g' ) 	0.00618790060466269
7838140	22797	mysql distinct group_concat values	select concat (user.i,',) from  (select distinct ......  	0.120465002562775
7838630	30949	how do i select row based on the number of times it appears in the table?	select id     from tbla     group by id     having count(*) < 3 	0
7839137	30389	mysql, select rows where a parameter value depends on the value that it has in a diferent row	select t.id,t.par from your_table t where t.par <>      (select par from your_table      where id = t.id + 1) 	0
7840761	20580	how do you calculate all the values in a column in sqlite (android) into a new variable for textview?	select sum(ammount) from table 	0
7845983	27820	how to sum up fields across different groups in t-sql	select salesid, historyid, productid, name, productnumber, total.quantity from table1 join (      select salesid, sum(quantity) as quantity from table1 group by salesid      ) as total on table1.salesid = total.salesid where mainnumber=1 	0.000782039666729361
7849831	6038	retrieve rows that matches with all the values listed	select user_id,count(group_id)  from group_privilege_details g where g.group_id in (102,101)  group by user_id having count(group_id) = 2 	0
7850551	31758	oracle, make date time's first day of its month	select trunc(yourdatefield, 'month') from yourtable 	0
7851161	18872	how to get the matching tables for a particular column name in sql server?	select table_schema,        table_name from   information_schema.columns where  column_name = 'letter' 	0
7851167	23552	sql query in ms access to calculate averaged days depending on multiple criteria	select activator, month, promotion, avg(activation_date - request_date) from ... group by activator, month, promotion 	8.77799336249839e-05
7851208	19112	mysql php wildcard? fetching column from tables	select userchosenemails.email, userinfo.number from userchosenemails inner join userinfo on userchosenemails.email = userinfo.email 	0.0201760084936225
7853043	13524	sql query to grid from multiple tables	select products.name,'dealer 1','dealer 2','dealer 3','dealer 4' from ( select products.name,qty from products inner join products_to_dealers_xref pd on products.id = pd.product_id inner join dealers d on products.id = d.id) as p pivot  (sum(qty) for products.name in (['dealer 1'],['dealer 2'],['dealer 3'],['dealer 4'])) as pvt 	0.0233680180641939
7853187	28044	sql script to find foreign keys to a specific table?	select      f.name as foreignkey,     object_name(f.parent_object_id) as tablename,     col_name(fc.parent_object_id,     fc.parent_column_id) as columnname,     object_name (f.referenced_object_id) as referencetablename,     col_name(fc.referenced_object_id,     fc.referenced_column_id) as referencecolumnname from      sys.foreign_keys as f     inner join sys.foreign_key_columns as fc on f.object_id = fc.constraint_object_id 	9.15944340780301e-05
7854969	40623	sql multiple join statement	select ... from ((origintable join jointable1 on ...) join jointable2 on ...) join jointable3 on ... 	0.773833344545737
7857538	33286	mysql count group by having	select count(*) from (    select count(genre) as count    from movies    group by id    having (count = 4) ) as x 	0.316544557713125
7857954	24536	writing a single query for mutliple queries with same where condition same table	select  sum(  case when (column5=0 or column6=0 )   then 1 else 0 end     ) as c1 ,  sum(  case when (column5=0 or column6=0 )   then 1 else 0 end     ) as c2 ,  sum(  case when (column5=0 or column6=0 )   then 1 else 0 end    ) as c3 , sum(  case when (column5!=0 or column6!=0 )   then 1 else 0 end  ) as c1_ ,   sum(  case when (column5!=0 or column6!=0 )   then 1 else 0 end    ) as c2_ ,  sum(  case when (column5!=0 or column6!=0)    then 1 else 0 end     ) as c3_ , from table1 	0.0054192308715754
7857967	11574	mysql: set variable and use in where clause in same query	select * from (     things,     (select @exp_time := if(5 < 10, x, y) as var) as your_alias )                  ... 	0.741421453608273
7858417	23823	sql query for aggreating a related object	select p.id, count(c.id) tot from posts p inner join comments c on p.id = c.post_id group by p.id order by tot desc limit 10 	0.291099477400321
7858582	26509	writing a single query for mutliple where condition using same column same table	select telco,  sum(      case when (msg  like '%fatal%' or out_msg like '%exception%' or out_msg like '%fopen%') and a = '1'       then 1 else 0 end  ) as a, sum(      case when (msg  like '%fatal%' or out_msg like '%exception%' or out_msg like '%fopen%') and a = '2'       then 1 else 0 end  ) as b, sum(      case when (msg  like '%fatal%' or out_msg like '%exception%' or out_msg like '%fopen%') and a = '3'       then 1 else 0 end  ) as c,  sum(      case when (msg not like '%fatal%' or out_msg not like '%exception%' or out_msg not like '%fopen%') and a = '1'       then 1 else 0 end  ) as a_e, sum(      case when (msg not like '%fatal%' or out_msg not like '%exception%' or out_msg not like '%fopen%') and a = '2'       then 1 else 0 end  ) as b_e, sum(      case when (msg not like '%fatal%' or out_msg not like '%exception%' or out_msg not like '%fopen%') and a = '3'       then 1 else 0 end  ) as c_e from temp_inbox  group by t 	0.00104716186698489
7858841	17245	selecting specific rows	select *   from yourtable  where `index` between (select min(`index`) from yourtable where (col1 = 1 and col2 = 2))                    and (select max(`index`) from yourtable where (col1 = 3 and col2 = 1)) 	0.000935467194924856
7860899	28268	max aggregate within a group	select t.group_id,         t.index,         coalesce(t.group_id, mintgroup_index_min) group_index_min  from   yourtable t         left join (select group_id,                           min(index) group_index_min                    from   yourtable                   group by                           group_id) mint           on t.group_id = mint.group_id 	0.312642857653493
7860900	9856	how to join these tables?	select q.*, u.*, count(a.id) as answer_count from questions q  left join users u on q.user_id = u.id left join answers a on a.question_id = q.id group by q.id 	0.201546658431577
7860925	24728	oracle find tablename given an index name	select table_name from all_indexes where index_name = 'your_index' 	0.0082166443731511
7863329	7454	how do you extract median from mysql within mixed data?	select x.value from form_data x, form_data y where x.form_id=1 and x.field_id=1 and y.form_id=and y.field_id=1 group by x.value having sum(sign(1-sign(y.value-x.value))) = (count(*)+1)/2; 	0.00211507796382899
7863454	36864	how to conditionally convert inches to cm in mysql (or similar conversions during select)?	select avg(value) from (   select     case unit       when "cm" then value       when "in" then value*2.54       end as value     from data_table ) as all_in_cm 	0.351489418055823
7866462	29132	attributes query; also include attributes with no hits on inner join	select    attr.id, attr.title   , attrval.value, attrval.id as valid   , count(attrlink.id) as attrcount  from #__foc_users_attributes as attr  left join #__foc_users_attr_val as attrval         on attrval.attrid = attr.id and attrval.value !=''  left join #__foc_users_attr_link as attrlink         on (attrlink.valueid = attrval.id)  left join #__foc_users_items as item         on (item.id = attrlink.itemid)  left join #__foc_users_attr_link as attrlink1   <<        on attrlink1.itemid = item.id        and ((attrlink1.attrid=1 and attrlink1.valueid=33))  where item.published=1 and attr.published = 1 and attrval.value != ''  group by attrval.id 	0.0189726924670692
7867877	35921	selecting a value which is subtraction of two summary	select x.date,        x.d,        x.p,        x.d - x.p as s   from (select t.date,                sum(gk.d) as d,                sum(gk.p) as p,           from t           join gk on ...) as x 	0.000124091945836587
7868763	23253	sql query for multiple tables/records	select m.lastname, m.firstname, o.[date] as [off ice date] from tblmembers as m left join  (   select userid, max([date]) as [date] from off_ice_testing   group by userid )o on (o.userid = m.userid) where     (m.lastname like '%player%') 	0.755066891883289
7870378	32102	mysql query for duplicate contents	select c1, c2 from xx group by c1, c2; 	0.0235314098446523
7871820	17697	sql: display multiple record values in one field from a subquery	select s.*, group_concat(t.name) institutions from student s   left join (select * from institution i               join inst_map im                 on im.institution = i.id              ) t   on s.id = t.student group by s.id 	0
7874267	31017	oracle select column with special name	select "started at" from your_table 	0.151857427263541
7874327	10590	mysql query with conditions	select b.id, b.asset, p.published_value from bookmark b left join publish p on b.asset = p.asset where p.published_value is null       or p.published_value > 0 	0.631012704778029
7875473	40734	use of and and or in sqlite	select * from emailtable where friendsid=fid and       (emailsenderid=fid or      emailsenderid=myid) 	0.502904604108576
7876600	25654	joining and possible sub-queries	select * from blog_posts where user_id in  (select friend_id from user_friend where user_id=1) 	0.669011130826021
7878509	17630	how do i seperate a string a mysql db into two fields?	select substring_index(referrer, ':', -1) as keyword,substring_index(referrer, ':', 1) as referrer from table; 	0.000234054710729842
7879515	13608	t-sql: move column values to row values	select id, phase, [total hours], 'team1' as team, team1 as [team hours] from db.dbname union select id, phase, [total hours], 'team2' as team, team2 as [team hours] from db.dbname union  select id, phase, [total hours], 'team3' as team, team3 as [team hours] from db.dbname 	0.000249664736886355
7880553	16056	extracting date format from getdate()	select convert(char(8), getdate(), 112)         + replace(convert(char(5), getdate(), 108), ':', '') 	0.00145793160258208
7880724	20068	converting a datetime to a numeric representation	select cast(convert(varchar,getdate(),112) as int) 	0.0667053524677202
7880791	3693	how to create an internal numbering of occurrences with sql	select id, name, row_number() over(partition by name order by id)   from table  order by id 	0.00887237495373806
7880936	34124	mysql returns all rows when field=0	select * from table where email='0'; 	0.0188969276741392
7881826	30304	oracle nested data type as a flat file	select d.id,         wm_concat(d.description)        nested_column  from         descriptions d group by id; 	0.520597737539166
7882594	13866	mysql next and previous	select *  from .... order by rand(9325) limit 99, 9 	0.0037498333204529
7883782	6406	postgresql - joining 3 tables subquery-key value pairs	select m0.m_value from   metadata m join   file_metadata fm on fm.m_foreign_key = m.m_id join   file_metadata fm0 on fm0.f_foreign_key = fm.f_foreign_key join   metadata m0 on m0.m_id = fm0.m_foreign_key where  m.m_value = 'abc1' and    m0.key = 'geo' 	0.00139005831433023
7884025	15483	get the sum of a column value for all rows with same value in different column	select sum(votes) total, user_id from comments group by user_id order by total limit 10 	0
7885146	4644	how display multiple rows in a table with one row in another table after some calculations	select     u.user_name,      sum(if(t.type = 'credit', t.transactions, 0)) as totalcredit,     sum(if(t.type = 'debit', t.transactions, 0)) as totaldebit,     sum(if(t.type = 'credit', -1, 1) * t.transactions) as total from     transactions t inner join     users u on     u.user_id = t.user_id group by     u.user_name 	0
7886771	15849	sql server from xml parameter to table - working with optional child nodes	select s.x.value('resortid[1]', 'int') as resortid,        s.x.value('checkindate[1]', 'date') as checkindate,        s.x.value('checkoutdate[1]', 'date') as checkoutdate,        r.x.value('numberofadt[1]', 'int') as numberofadt,        r.x.value('count(chd)', 'int') as chdcount,        stuff((select ';'+c.x.value('.', 'varchar(3)')               from r.x.nodes('chd/age') as c(x)               for xml path('')), 1, 1, '') as chdages from @xmlvalue.nodes('/searchquery') as s(x)   cross apply s.x.nodes('room') as r(x) 	0.397621836636316
7887630	2076	using c#, how can i execute a tsql user-function and get its returned value?	select dbo.fn_myfunc(?) as result 	0.00736581023602941
7888395	4646	php mysql where length is longer then 1	select * from your_table where octet_length(blob_field) > 1 	0.215841110063162
7890047	20165	sql query to create records of dates and amounts?	select [date], sum(amount) totalamount from yourtable group by [date] 	0.000743962086886908
7892334	17166	get size of all tables in database	select      t.name as tablename,     s.name as schemaname,     p.rows as rowcounts,     sum(a.total_pages) * 8 as totalspacekb,      sum(a.used_pages) * 8 as usedspacekb,      (sum(a.total_pages) - sum(a.used_pages)) * 8 as unusedspacekb from      sys.tables t inner join           sys.indexes i on t.object_id = i.object_id inner join      sys.partitions p on i.object_id = p.object_id and i.index_id = p.index_id inner join      sys.allocation_units a on p.partition_id = a.container_id left outer join      sys.schemas s on t.schema_id = s.schema_id where      t.name not like 'dt%'      and t.is_ms_shipped = 0     and i.object_id > 255  group by      t.name, s.name, p.rows order by      t.name 	0.000141088060960196
7893020	37065	mysql: selecting duplicates among many fields	select tmp.email from (     select email as email from contacts where active = 1     union all     select email2 as email from contacts where email != email2 and active = 1 ) as tmp group by tmp.email having count(tmp.email) > 1 	0.00223107995249912
7893205	24368	select the requested cell by using max() and sum() functions	select top 1 * from ( select sum(deposits.deposit) as summonth , deposits.account_id as id from deposits group by deposits.account_id, month(deposits.date)  )  as a inner join accounts on accounts.id = a.id order by accounts.summonth desc 	0.0164732034835635
7893291	24509	sqlite select statement - where two conditions are met?	select * from games where genre = 'fps' and decade = 90 	0.0398796540627719
7894137	2443	how to get the duplicate names of employees who have multiple employee numbers	select e.employee_no, e.employee_name, e.id_no     from (select employee_name, id_no               from employee               group by employee_name, id_no               having count(*) > 1) q         inner join employee e             on q.employee_name = e.employee_name                 and q.id_no = e.id_no     order by e.employee_name, e.id_no, e.employee_no 	0
7894789	37106	how can i query 2 tables and multiple columns?	select table1.name, table2.product, tabl2.inventory, table2.catid from table1 inner join table2 on table1.name = table2.product  where table2.catid = '2' 	0.00359350639066621
7895194	14111	current_timestamp only get year, month, and day	select date_format('(%m/%d/%y)', now()) as datestring 	0
7896590	31270	how to optimise that query?	select     apv.article_id,     sum(coalesce(weight, 0) > 0) as up,     sum(coalesce(weight, 0) < 0) as down  from article_preselection_vote apv  left join vote     on apv.id = vote.id     and vote.resource_type = 'article' where apv.article_id in (11702, 11703, 11704, 11632, 11652, 11658) group by apv.article_id 	0.711614007006485
7897030	39272	how to join with similar columns?	select a.active as a_active, b.active as b_active, ...    from a join b on a.id = b.id 	0.0608705572710011
7897083	31715	sql max value of pre-defined rows	select m.* from members as m where exists       ( select *         from posts as p          where p.member_id = m.member_id       ) order by ads desc limit 1 	0.000726279999628187
7897525	22682	sql datetime comparing to date value	select * from table where date(date_time) = '$date' 	0.00263304786685079
7897687	32187	search data in two different tables with pagination and score	select id, title, content, link from ( select news_id as id, news_title as title, news_description as content,  match (news_description, news_title) against ('$keyword') as relevance from tbl_news union all select package_id as id, package_title as title, package_description as content, match (package_description, package_title) against ('$keyword') as relevance from tbl_packages )temp_sort_table where relevance >0 order by relevance desc limit $offset,$limit 	0.00248899678554994
7897921	1699	mysql if statement if one colum isn't empty, compare two others	select c.* from cca_coupons c join cca_owners o on o.id=c.owner_id where c.amount_generated >= c.max_redemptions and c.max_redemptions <> '0' 	0.000332872904747101
7898960	18510	elegant way of finding intersection of many-to-many entities using play	select s from student s inner join s.subjects subject where subject in (:subjectsofstudenta) and s != :studenta 	0.345531053026391
7900127	6087	mysql query and select data from two tables	select url_alias.alias    from url_alias, taxonomy_index   where url_alias.source = concatenate('taxonomy/term/', taxonomy_index.tid)     and taxonomy_index.nid = {given_nid} 	0.00180484852407082
7902397	11786	cross join! in sql server, but i really only need about a third of the rows?	select profiles.profileobjid, roles.rolename from dbo.rj_v_definedroles roles cross join dbo.profile profiles where profileobjid in (select profileobjid from dbo.profile                     where profileobjid between 10000 and 11000) 	0.589935309544813
7902450	15088	i want query to count duplicate entries from 3 separate columns in a table bu with same data type (c#)	select results.no_ident_2, count(results.no_ident_2) as repeat  from (      select no_ident_1 as no_ident_2 from p240538 where (p240538.date_dt > {2011/04/25})          union all      select no_ident_2 from p240538 where (p240538.date_dt > {2011/04/25})      union all      select no_ident_3 from p240538 where (p240538.date_dt > {2011/04/25})      ) results group by results.no_ident_2 	0
7904444	6838	most efficient way to compute running value in sql	select day, ordercount from yourtable order by day 	0.0801699636614115
7904944	17643	best way to exclude records from multiple tables	select * from vehicles v where summary <> 'honda'  and not exists (select 1 from vehicle_descriptions d where d.vin = v.vin and d.desc <> 'honda')  and not exists (select 1 from vehicle_parts p where p.vin = v.vin and p.part_for <> 'honda') 	0.000151169957550114
7905586	19073	mysql grouping a status field	select location,     sum(status = 1) as status_1,     sum(status = 0) as status_0 from my_table group by location 	0.0109309997259438
7906881	26387	using coalesce to set initial value of variable in query	select       @z := z+1 as nextnumber    from table,       ( select @z := 5,                 @anothervar := 'first value',                @anythingelse := 390.290 ) sqlvars      limit 5; 	0.065940407938557
7908341	31557	count 3 tables and check in one of them for existing id	select   c.categories_id, cd.categories_name,   case when aa.total_per_id is null then 0    else aa.total_per_id   end as total from categories as c    join categories_description as cd on c.categories_id = cd.categories_id    left join (     select a.categories_id,       count(*) as total_per_id from product_to_categories a     group by a.categories_id ) as aa on aa.categories_id = c.categories_id order by c.sort_order, cd.categories_name; 	0
7910980	15643	getting the whole row from grouped result	select a.id, a.productid, a.price from mytable a,     (select productid, max(datechanged) as maxdatechanged     from mytable     group by productid) as b where a.productid = b.productid and a.datechanged = b.maxdatechanged 	7.70837831451803e-05
7911073	1602	convert sql xml datatype to table	select t.c.query('.').value('(     t.c.query('.').value('( from @xmldoc.nodes('/people/person') t(c) 	0.0847097250382793
7911959	16299	selecting a user of every type	select * from member where not exists (    select *    from member_privilege left join privilege on member_privilege.pid = privilege.id)    where member_privilege.mid = member.id and privilege.id is null  ) 	0.000294500651838288
7913711	27221	sql: combining main and sub data in a query	select j.id, j.pkey, j.summary, j.created, j.updated, j.resolutiondate         ,j2.summary, j2.created, j2.updated, j2.resolutiondate        ,j3.summary, j3.created, j3.updated, j3.resolutiondate  from jira.jiraissue as j  inner join jira.issuelink i          on i.source = j.id  and i.sequence = 0 inner join jira.jiraissue as j2          on i.destination = j2.id left join jira.issuelink i2          on i2.source = j.id  and i2.sequence = 1 left join jira.jiraissue as j3          on i2.destination = j3.id 	0.524822740830727
7913873	34585	how to write the query command in mysql	select cd.categories_id, cd.categories_name from `table_categories_description` cd      inner join `table_categories` c     on cd.categories_id = c.categories_id where c.parent_id = your_id 	0.67942729804126
7914012	30208	creating a date series in postgresql 8.3	select ('2008-01-01 0:0'::timestamp        + interval '1 month' * generate_series(0, months))::date from   (    select (extract(year from intv) * 12           + extract(month from intv))::int4 as months    from   (select age(now(), '2008-01-01 0:0'::timestamp) as intv) x    ) y 	0.414102718749778
7914029	13396	t-sql: include a row count as a column for unique rows	select col1, col2, col3, count(*) as total from tablea group by col1, col2, col3 	5.26590929098815e-05
7915961	13834	export sql query results as xml in db2 script	select rec2xml(1.0, 'colattval', 'row', ct) from (select current timestamp as ct from sysibm.sysdummy1); 	0.642921505694205
7916166	30276	how to sort inside a tuple (sql)	select     (case when namea <= nameb then namea     else nameb end) as field1,     (case when namea < nameb then nameb     else namea end) as field2 from your_table 	0.201474504579745
7916210	5970	how to identify and kill longest running transaction?	select at.transaction_id,         at.transaction_begin_time,         st.session_id from sys.dm_tran_active_transactions at left join sys.dm_tran_session_transactions st      on at.transaction_id = st.transaction_id order by transaction_begin_time 	0.113511581937318
7916367	13413	complex mysql query, filter from multi table	select ot.order_name, oit.item_name from order_items_table oit inner join order_table ot on ot.order_id = oit.order_id where oit.order_item_id in (your,list,of,items) 	0.310958110092894
7918923	33739	how to do time_to_minute in mysql?	select time_to_sec('00:00:1') / 60 	0.346451169744529
7919619	31168	selecting max from two tables in select statement	select s.id, s.subject, s.description, t2.lastdate    from dbo.formsubjet s    inner join (     select id, max(date) as lastdate     from (         select id, date         from dbo.formpost         union all         select id, date         from dbo.formcomment     ) t1     group by t1.id           ) t2 on t2.id = s.id 	0.0004483264273472
7920908	27372	sql server 2008 duplication of rows and averages	select id  ,visitid = min(visitid) ,date = max(date) ,value= count(*) from table group by id 	0.0138102722706008
7920918	41206	sql where clause for two dates exactly one month minus one second apart from each other?	select * from table where col2 = dateadd(second, -1, (dateadd(month, 1 col1))) or col1 = dateadd(second, -1, (dateadd(month, 1 col2))) 	0
7921903	35628	returning several rows from a single query, based on a value of a column	select t1.fld, t1.number     from table t1, (         select rownum number from dual          connect by level <= (select max(number) from t1)) t2     where t2.number<=t1.number 	0
7923278	8424	sqlite: how to select a range of records?	select      fields_you_want_to_select from      filestbl where      datetime > start_of_range and     datetime < end_of_range limit     25 	0.000198755939341137
7927329	27283	sql ordering records by "weight"	select   task_id from (     select      task_id,      ((task_priority_order - 1) / task_priority_density) as task_processing_order   from (     select       t.task_id                                            as task_id,        t.priority                                           as task_priority,        row_number()          over (partition by t.priority order by t.priority) as task_priority_order,       case         when t.priority = 3 then 50         when t.priority = 2 then 25         when t.priority = 1 then 25       end                                                  as task_priority_density     from       table t   ) ) order by task_processing_order 	0.0143753024553095
7927383	5302	check the data between two tables	select id,t1.orderid, t2.orderid is null as notinboth from table1 as t1 left join table2 as t2 using (orderid); 	0.000369839742514308
7927747	33745	select last row if user is found	select problemid from <table> t1 where problemid in  (       select problemid from <table>       where (responsibleid = 0900 or assignedtoid = 0900)) and problemcode = 1 and unique = (select max(unique) from <table> where problemid = t1.problemid) 	0.000111773216528923
7928817	15513	plsql user defined table types and joins	select distinct someval  into outval  from othertable ot, table(srccodesin) sc  where ot.id = sc.column_value 	0.15744563468663
7929061	27377	standard sql to replace greatest() in mysql query	select   case when play_25 > play then play_25 else play end as play,   play_25,   play_50,   play_75,   play_100 from (   select     play,     case when play_50 > play_25 then play_50 else play_25 end as play_25,     play_50,     play_75,     play_100   from (     select       play,       play_25,       case when play_75 > play_50 then play_75 else play_50 end as play_50,       play_75,       play_100     from (       select         play,         play_25,         play_50,         case when play_100 > play_75 then play_100 else play_75 end as play_75,         play_100       from video_buckets     ) s   ) s ) s 	0.638450631025109
7929394	4336	how to query count over 2 columns	select team1, team2, sum(num) from (    select team1, team2, count(*) num    from table_name    group by team1, team2   union all    select team2, team1, count(*) num    from table_name    group by team2, team1 ) combined where team1 < team2 group by team1, team2 	0.00682591572198327
7930133	1783	query to add next row's same column	select m1.moneypaid,     ( select top 1 m2.moneypaid       from @money m2       where m2.id <m1.id        order by m2.id  desc    ) as prev_value    ,m1.moneypaid + ( select top 1 m2.moneypaid       from @money m2       where m2.id <m1.id        order by m2.id  desc    ) 	0
7930185	33596	sql join on two fields in one table	select         ag.id,         p.first_name,         p.last_name,         p.organisation,         p.event_date,         p.wave  from (       select booking.person_1 as id, booking.car as car from booking       union all       select booking.person_2 as id, booking.car as car from booking      ) as ag join people p on people.id = ag.id; inner | left join cars c on c.id = ag.car 	0.00165116001370409
7930537	2779	mysql describe table - concatenate fields?	select      group_concat(column_name)  from information_schema.columns  where     table_schema=database()  and table_name='your-table-name'; 	0.0101117010882025
7930603	33552	how do i perform a simple join on multiple tables?	select p.*,        m.first_name,        m.last_name from payments p inner join members m   on m.member_id = p.member_id inner join member_to_group mg   on mg.member_id = m.member_id where mg.group_id = 12 	0.75887427742105
7930810	23006	sql replace all nulls	select 'isnull(' + column_name + ',' +    case      when data_type = 'bit' then '0'     when data_type = 'int' then '0'     when data_type = 'decimal' then '0'     when data_type = 'date' then '''1/1/1900'''     when data_type = 'datetime' then '''1/1/1900'''     when data_type = 'uniqueidentifier' then '00000000-0000-0000-0000-000000000000'     else ''''''    end + ') as ' + column_name + ',' from information_schema.columns where table_name = 'tablename' 	0.182127200770241
7931869	12540	suggestions for creating a unique id when doing a union of more tables	select  1000000 + customerid as uniquecustomerid       , customerid       , customername from    customers union all select  2000000 + employeeid as uniqueemployeeid       , employeeid       , employeename from    employees union all select  3000000 + friendid as uniquefriendid       , friendid       , friendname from    friends 	0.0516253335706248
7932286	18625	sql: compare 2 tables with duplicates	select  t1.colname from    ( select    colname                   , count(colname) as colcount           from      tbl1           group by  colname         ) t1         inner join ( select   colname                       , count(colname) as colcount                from     tbl2                group by colname              ) t2 on t1.colname = t2.colname                      and t1.colcount <> t2.colcount 	0.00660894888600964
7932548	29096	how to get the category wise values related to user?	select `user name`,     sum(case when status = 'open' then 1 end) as open,     sum(case when status = 'assigned' then 1 end) as assigned,     sum(case when status = 'closed' then 1 end) as closed from status group by `user name` 	0
7933687	12949	how to remove duplicate entries from mysql database table	select distinct * from table; 	0
7933899	19695	count values in mysql database rows	select sum(count) from table_name 	0.00249638579050141
7934026	9871	sql - order by statement	select a.id, a.name, a.email, b.cata, b.catb, b.year from a join b on a.id = b.member order by b.year desc, (b.member is not null) desc 	0.706943293744249
7934793	6526	summing values multiple rows at a time in mysql	select first_column_name, sum(last_column_name) from table_name group by(first_column_name); 	0.000158325961786636
7935090	40022	sql unique values	select first 100 distinct e.email_id, e.location_id, e.email, l.location_type, p.salutation, p.fname, p.lname from email e, location l, person p where e.location_id = l.location_id and l.per_id = p.per_id 	0.0133003477242875
7935827	22662	a mysql query, some normalized tables, issues w/ counts from the normalized table rows (from php)	select      tbl_contract.id, count(*) as usercount from        tbl_contract left join   tbl_contract2user on tbl_contract.id = tbl_contract2user.contractid where       tbl_contract2user.pending = 0 and         tbl_contract.startdate <= {$billing['start_time']} and         tbl_contract.enddate    >= {$billing['end_time']} group by    tbl_contract.id 	7.29380113419815e-05
7938410	22357	select with specific attributes	select *  from products p  inner join (select * from details d where d.attributeid = 1 ) d1 on p.id = d1.productid  inner join (select * from details d where d.attributeid = 4 ) d4 on p.id = d4.productid  inner join (select * from details d where d.attributeid = 5 ) d5 on p.id = d5.productid  where  d1.value = 'black' and d4.value = '2011' and d5.value = '70 000:1' 	0.0301413326090866
7938802	21492	find a word within text in mysql	select * from table where field regexp '[[:<:]]theword[[:>:]]' 	0.0197882732181971
7939198	36028	is there any query to retrieve records from db randomly?	select top 10 field1, ..., fieldn from table1 order by newid() 	0.000153929261430441
7940872	20348	select only if one user role in sql	select user_accounts.user_id, count(roles_users.user_id) as cnt from user_accounts inner join roles_users on (user_accounts.user_id = roles_uers.user_id) group by user_id having (cnt = 1) 	0.00206609536164874
7941070	26020	filtering mysql results by date	select id from some_table where some_date_field between $first_date and $second_date 	0.0808558473066906
7941249	39406	php - mysql search database table return result with percentage match	select (if(like1='$like1',1,0) + if(like2='$like2',1,0) + if(like3='$like3',1,0))/3*100 match_percent, count(id) from helloworld group by match_percent; 	0.00441457404266995
7944331	31798	mysql - selecting distinct if not null	select distinct id,introtext,publish_up,publish_down,ifnull(x,id) as distinct_field  from #__content  where catid in(936,937,940,959,972,988,991) and state = 1  and ( publish_up = "0000-00-00 00:00:00" or publish_up <= "2011-10-30 12:12:59" ) and ( publish_down = "0000-00-00 00:00:00" or publish_down >= "2011-10-30 12:12:59" ) 	0.0733948927456394
7948120	9892	mysql : interval around id column and return another one from subquery with multiple columns	select col1  from table t where id between (select id from table where col1='xxx' and col2='yyy' and col3='zzz') -1      and (select id from table where col1='xxx' and col2='yyy' and col3='zzz') +1 	0
7954251	11427	how to execute one of the two queries based on a condition in oracle 10g?	select iim.index_num, iim.description from inv_item_mst iim where (:groupcd is not null and iim.group_cd =:groupcd) or (:groupcd is null and     iim.group_cd in (:groupcode1,:groupcode2,:groupcode3,:groupcode4,:groupcode5,:groupcode6,:groupcode7)     and iim.generic_cd like nvl(:generic_cd_param,'%')     and iim.supplier_cd like nvl(:supplier_cd_param,'%')    ) 	0.000172284750373832
7954714	27785	find foreign key matching multiple row values	select   person_id from   yourtable where      department = 'a'   or department = 'b' group by   person_id having   count(distinct department) = 2 	0
7955718	37337	querying database schema of sql server db via odbc?	select * from information_schema.columns isc 	0.306974997678563
7955971	14569	sql select from two tables (friendship) statement	select * from ( select row_number() over (order by ) as rownum, ls_id from ) as a where a.rownum between (@start) and (@start + @rowsperpage) 	0.0288273152089822
7956395	31421	sql query to search in a concated string	select * from prospect where concat(firstname,' ',lastname) like '%ohn smit%' 	0.342143158000161
7956502	37432	group by and group_concat - how to return correct values?	select ev.session_id, ev.q1, ev.comments, es.session_number, es.title, speaker from  `expo_session_eval` ev left join expo_session es on es.session_id = ev.session_id left join (     select ess.session_id, group_concat( concat( np.first_name,  ' ', np.last_name ) ) as speaker     from new_people np     left join expo_speaker sp on  np.id = sp.people_id     left join expo_session_speaker ess on sp.speaker_id = ess.speaker_id     group by ess.session_id ) np on np.session_id = es.session_id    order by es.session_number 	0.118481101715084
7958036	19363	convert multi-columns to rows	select id, fieldcode, fieldvalue     from      (         select  id, code1, codedesc1, code2, codedesc2, code3, codedesc3, code4, codedesc4, code5, codedesc5, code6, codedesc6         from test     ) mytable     unpivot     (fieldcode for fieldcodes in (code1, code2, code3, code4, code5, code6))as code     unpivot     (fieldvalue for fieldvalues in (codedesc1, codedesc2, codedesc3, codedesc4, codedesc5, codedesc6))as fieldvalues where right(fieldcodes,1) =  right(fieldvalues,1) 	0.0240592824605119
7958816	36917	how to get multiple rows into one line as a string? 	select     id, name,      emails = stuff((         select ', ' + email from table2 where table2.id = table1.id         for xml path ('')),1,2,'') from table1 	0
7960328	19335	mysql verify 10 minute increments in timestamps	select     y.c     , logger.timestamp from     (select          a +  cast(b || ' sec' as interval) as c     from          (select                cast('2011-10-31 10:00:00' as timestamp) as a                ,t.b from generate_series(0,100,10) as t(b)          )x     ) y      left join (          select timestamp from log     ) logger on y.c = logger.timestamp where      logger.timestamp is null; 	0.000432751274778115
7962776	7879	mysql: what is the best way to get last inserted value of a field with condition	select c.field_chapter_value from content_type_story c inner join term_node t on c.nid = t.nid where t.tid = ?  order by c.field_chapter_value desc limit 1 	0
7965648	37387	get distinct values from multiple columns (including a join)	select fromemail from messagestable where fromemail is not null union select toemail from messagestable where toemail is not null 	0
7966430	35799	how to sample rows in mysql using rand(seed)?	select id from foo where rand(42) < 0.05 order by id desc limit 100 	0.0871993820930913
7967459	17513	adding a month to a date in t sql	select * from reference where reference_dt = dateadd(mm,1,another_date_reference) 	0.00159170200770349
7968531	2001	remove trailing zeros in decimal value with changing length	select trim(trailing '0' from yourodds) from ... 	0.0029239097042241
7969338	2926	sql server 2008 query for members who meet multiple conditions	select orignumber from tbl_detailcalls where termnumber in ('2463332121', '2463334920', '2463339901') group by orignumber having count(distinct termnumber)>=3 	0.0533208977428758
7969906	39955	mysql select statement to retirve single row with the highest date from every month	select *  from your_table  where date_col in (   select max(date_col)    from your_table    group by month(date_col) ) 	0
7970957	22333	oracle sql inner join based on non-matching values	select * from table1 tl inner join table2 t2  on (tl.cola = t2.colb or (tl.cola ='ab3' and t2.colb='ab_mno_3') or (tl.cola ='ab3' and t2.colb='ab_pqr_3') or (tl.cola ='ab4' and t2.colb='ab_mno_4') or (tl.cola ='ab4' and t2.colb='ab_pqr_4')) 	0.0255241676188716
7971345	16503	oracle updatexml() changes xml structure?	select     updatexml(         updatexml(             updatexml(xmldata, '/test/value[not(text())]', '<value>temporary value</value>')         ,'/test/value[text()!="temporary value"]/text()', 'hello')     ,'/test/value[text()="temporary value"]/text()', null) examle from (select xmltype('<test><value>hi</value><value>hola</value><value></value></test>') as xmldata from dual); 	0.745545218182909
7972000	21815	mysql: select a range of ordered records based on a separator type	select * from table_name where position > 8 and  ( position < (     select min(position)     from table_name     where position > 8     and type = 'separator' ) or    position <= (select max(position) from table_name)  ) order by position asc 	0
7972311	2070	php & mysql counting records with a timestamp of under 5 minutes ago	select count(*) as cnt from yourtable where timestampfield >= date_sub(now() interval 5 minute) 	0
7974708	31196	check if friends and get friends list?	select case      when sender = @senderid then recipient     else sender end as friendid from friends where sender = @senderid or recipient = @senderid 	0
7976205	21351	sqlite order by month number in a 'yyyy-mm-dd' format	select * from mytable order by cast(strftime('%m', call_date) as integer); 	0.00106655465234515
7977310	12734	replace/assign a value in select statement	select case paymenttype when 'p' then 'part' when 'f' then 'full' end as paymenttype from paymentaccount 	0.117563849883286
7978581	33849	trying to get the members without logout time using mysql	select member_firstname, member_lastname,           visit_datetime, visit_status, visit_logout_datetime           from members, visits           where members.member_id = visits.member_id and visits.visit_logout_datetime is null           and members.member_active like 'y%' and visits.visit_status = 'accepted'  and visits.visit_date = '2011-11-02' order by visit_datetime desc limit 100; 	0.00279970379309152
7979176	29291	sql query to retrieve result without duplication	select teachername,         count(distinct classtakendate) as noofdays from schedule  group by teachername 	0.05002393280313
7980052	8454	how to do left join with more than 2 tables?	select a.x, b.x, c.x  from number as a left join customer as b on a.b = b.b left join numbergroup as c on a.c = c.c and c.b = b.b 	0.167619816677402
7980308	29587	mysql limit math	select * from my_table where id between x and y order by rand() limit 1 	0.712088637335167
7980315	38829	mysql join only return one result from the join	select   c.`candidate_id`,    c.`first_name`,    c.`surname`,    c.`dob`,    c.`gender`,    c.`talent`,    c.`location`,    c.`availability`,   date_format(now(), '%y') - date_format(c.`dob`, '%y') - (date_format(now(), '00-%m-%d') < date_format(c.`dob`, '00-%m-%d')) as `age`,   group_concat(ca.`url`) `url`,   group_concat(ca.`asset_size`) `asset_size` from `candidates` c left join `candidate_assets` ca on ca.`candidates_candidate_id` = c.`candidate_id` where c.`availability` = 'yes' group by c.candidate_id 	0.000687766375385144
7983369	3180	how do i combine a mysql query and subquery when there's multiple rows?	select      p1.id,     p1.vendor_name  from      products p1      inner join     (        select            vendor_name,           count(vendor_name) as productcount         from            products         group by            vendor_name        having           productcount >= 10     ) p2     on p1.vendor_name=p2.vendor_name 	0.0187247185332535
7983524	26464	how to join 3 tables in mysql query and save the result	select p.permissionid, p.permissionname from users u inner join roles r on r.roleid = u.roleid inner join permissions p on p.permissionid = r.permissionid 	0.121629773812332
7984285	2311	summing one tables value and grouping it with a single value of another table	select t.[month], sum(a.[hours]) as actualhours, t.[hourstarget] from [targettable] t join [actualstable] a on t.[month] = a.[month] group by t.[month], t.[hourstarget] 	0
7984495	15393	sql to select record for latest date	select stockid, max(date) from (select stockid, max(date)       from tablea       group by stockid       union all       select stockid, max(date)       from tableb       group by stockid) a group by stockid 	0.000171431186383821
7986493	7729	how to use an mysql association table to return categories not currently assigned to an entry	select c.* from category c left join association a on a.pid = c.pid and a.eid = '493' where a.eid is null 	0.00105226898553743
7988215	21208	sql server - how to display most recent records	select a.id, a.pid, a.lastmodified, a.reason  from mytable as a inner join ( select pid, max(lastmodified) as maxdate from mytable group by pid) as b on a.pid = b.pid and a.lastmodified = b.maxdate 	0
7988800	21878	sql server - how to display most recent records based on dates in two tables	select     tbl.id,     tbl.exdate from (     select         t1.id,         t2.exdate,         row_number() over(partition by t1.pid order by t2.exdate desc) as 'rn'     from         table1 t1     inner join table2 t2         on t1.exid = t2.exid ) tbl where     tbl.rn = 1 	0
7990100	5134	how do i get a row with a particular date in sqlite?	select * from items where mydate like '2009-11-28%' 	0.000149684941646456
7990609	1518	how to insert a record with validation	select s.* from  (select id, date, value from secondarytable ) s , ( select id, max(date) as date  from maintable group by id ) a where s.id = a.id and s.date>a.date 	0.0141214142980413
7990687	15708	how do i select the 5 highest values in an integer column?	select * from mytable order by id desc limit 5 	0
7992094	10945	join in sql query for matched results from two tables	select po.po_no,     (select count(*) from invoice      where po_no = po.po_no) as billed from porder po 	0.00659265770455301
7992125	12267	php & mysql create join query	select *  from table1  where table1.`id` not in         (select table1.`id`          from table1             join table2             on table1.id = table2.id_test          where table2.id_usrs = 1); 	0.679596938862224
7992484	28438	group by date in column which stores timestamp in long(bigint)	select mt.time,count(*) from my_table mt group by date( from_unixtime( mt.time )); 	0.000968814785427963
7992609	40381	how to select records coming in next 12 hours?	select * from bookings_mst where  addtime(booking_date, booking_time) between now() and now() + interval 12 hour; 	0
7993141	14045	how to select previous row based on date	select * from table where timestamp < :mytimestamp order by timestamp desc limit 0, 1 	0
7993750	31066	extract two many-to-many's in one query	select n.*, c2.* from country c   join country_news cn     on cn.country_id = c.id   join news n     on cn.news_id = n.id   left join country_news cn2     on cn2.news_id = n.id   left join country c2     on cn2.country_id = c2.id where c.id = 1 	0.00485612533447161
7993886	11087	left join on first value from right table?	select (select top 1 d2.didateend     from diary as d2     where d2.didateend > d1.didateend     order by d2.didateend) as righttabletime, * from diary as d1 	0.00707524373970006
7993931	36505	add columns to select *	select w1.*,         case         when w1.start_date < w2.start_date then             to_date(w2.start_date, 'dd/mm/yyyy') - 1         else         to_date(w1.end_date, 'dd/mm/yyyy')         end end_date_modified from weighted_average w1 	0.0336970959470801
7994407	34466	uploading images and how to get that image inside the sql using group by and max()	select album_name,        max(photo_number) as highest_photo_number     from photos     where accountid = (whatever)     group by album_name     order by highest_photo_number; 	0.00626394359693862
7994865	38994	how to get the sum of foreign key table as a value in the primary table row in a select statement	select    t.*,    ( select        sum(tt.value)      from table2 tt      where tt.id = t.id) sum_value from table1 	0
7995317	3770	sql query to select relational data	select    p.product_name   , p.product_description   , p.product_weight   , p.product_price   , p.product_image   , group_concat(f.feature_id order by f.feature_id) as feature_ids   , group_concat(f.feature_name order by f.feature_id) as feature_names from products p left join feature_products fp on (fp.product_id = p.product_id) left join features f on (f.feature_id = fp.feature_id) group by p.product_id 	0.274405974441268
7995528	3304	sql multiple join query	select ...  from users u      join players p on u.player = p.name     left join teams t on p.team = t.id where u.id = ? 	0.674921488043773
7995945	19066	how to i modify this t-sql query to return the maximum value for different column names?	select  [rate],         (select max(t.[rate])          from (values([ratemon]),                      ([ratetue]),                      ([ratewed]),                      ([ratethu]),                      ([ratefri]),                      ([ratesat]),                      ([ratesun])) as t([rate])         ) as maxrate from [room] where id=@id 	0
7996146	9334	oracle's materialized view: how to determine whether original tables were changed?	select count(*) 	0.00343701392798725
7996398	15295	is there a way to select normalized data back into one result set	select f.id, f.name, fa_color.value as color, , fa_flavor.value as flavor from foo f join fooattri fa_color on f.id = fa_color.fooid and fa_color.attribid = 1 join fooattri fa_flavor on f.id = fa_flavor.fooid and fa_flavor.attribid = 2 ... 	0.000723172912014912
7996456	26136	do in mysql i really must create temporary table before insert there	select     [list of columns except for id and numofact,      plus 'now() as dateofact' instead of dateofact] from acts; 	0.419388450739513
7997670	40494	how to select the best scores from my classes's latest test	select course_id, student_id, max(score) from test_scores group by course_id, student_id 	0.00151213377038078
7998009	288	select entrys with row count > 0 in other table	select distinct u.username from users u inner join items it     on u.pk = it.user_pk where it.status > 0 	0.000967415260205006
7999123	22873	query lines based on version number	select * from (     select *,         row_number() over(partition by worksheet order by version desc) as rownum     from yourtable ) a where rownum = 1 	0.00040327200524487
7999608	38043	null substitution in sqlite:	select ifnull(mycolumn,-1) as mycolumn from mytable 	0.734188091785401
7999948	10882	can i query mysql for a specific datatype?	select *     from information_schema.columns     where data_type = 'enum'; 	0.145954638994429
8001735	31288	limiting the records inserted in a sql table	select count(*) as seatsfilled, t.trainingkey, t.trainingdate from training t inner join studenttraining st on t.trainingkey = st.trainingkey group by t.trainingkey, t.trainingdate having count(*) < t.totalseats 	0.00129871713708579
8002154	3543	how to write mysql query with multiple data orders?	select * from tbl_event order by event_date desc where date(event_date) = date(now()) union select * from tbl_event order by event_date desc where event_date >= now() union select * from tlb_event order_by event_date desc where event_date < now() 	0.048295229962381
8003929	16241	tsql join to another table with group by	select          dbo.xmp_eventusers.id, dbo.xmp_eventusers.eventid, dbo.xmp_eventusers.userid,     convert(varchar(20),dbo.xmp_eventusers.datecreated, 100) as datecreated,      convert(varchar, dbo.xmp_event.cost, 1) as cost,      dbo.users.firstname, dbo.users.lastname,      dbo.xmp_event.cost + dbo.xmp_event.costtax - dbo.xmp_eventusers.paid as outstanding,      dbo.xmp_event.cost +     dbo.xmp_event.costtax as costactual,     dbo.xmp_event.cost + dbo.xmp_event.costtax - users2.amount as finalvalue from         dbo.xmp_event      inner join dbo.xmp_eventusers          on dbo.xmp_event.id = dbo.xmp_eventusers.eventid      inner join dbo.users          on dbo.xmp_eventusers.userid = dbo.users.userid     inner join (select userid, sum([amount]) as amount         from [dbo].[xmp_eventpromousers]         group  by userid) users2         on dbo.users.userid = users2.userid 	0.0585420340119209
8004655	2932	how to group by and return sum row in postgre sql	select id, sum(amount) as amount from yourtable group by id 	0.00705635448208937
8005586	15487	one of my mysql table's icon is changed and not showing data and when click to browse , download the page	select * from myview where userid = 3 	0.00713431742547569
8006077	18697	how can store only time from datetime into sql server 2005?	select convert(varchar(8),getdate(),108) as hourminutesecond 	0.000948890979016655
8006971	12415	mysql select given number of rows and always select all rows within the same day	select userid, created from some_user where created < '2011-11-04 09:10:11' and created >= (     select date(created)      from some_user     where created < '2011-11-04 09:10:11'     order by created desc     limit 99, 1  ) order by created desc 	0
8007347	17418	fetch record from xml	select t.x.value('.', 'varchar(max)') as id from @chargedetail.nodes('/amount/first/second') as t(x) 	0.000538079381045145
8009143	7799	counting refferers new members between 2 dates from the same members table	select   m.id,   m.fullname,   m.country_id,   m.city_id,   m.town_id,   m.totalref,   cnt.name countryname,   ct.name cityname,   t.name townname,   m2.newref from members as m    left join country cnt     on cnt.id = m.country_id   left join city ct     on ct.id = m.city_id   left join town t     on t.id = m.town_id   left join (     select ref_id, count(id) newref from members       where ref_id > 0 and registrationdate between '2011.11.04 00:00:00' and '2011.11.04 23:59:59'       group by ref_id     ) m2     on m2.ref_id = m.id where   m.country_id = '224' and    m.city_id = '4567' and   m.town_id = '78964' and    m.admin = '0' and    m.ref = '1'  order by   newref desc  limit   0, 25; 	0
8009379	23010	how to output a standings table on the fly from a mysql table of football [soccer] results?	select      team,      count(*) played,      count(case when goalsfor > goalsagainst then 1 end) wins,      count(case when goalsagainst> goalsfor then 1 end) lost,      count(case when goalsfor = goalsagainst then 1 end) draws,      sum(goalsfor) goalsfor,      sum(goalsagainst) goalsagainst,      sum(goalsfor) - sum(goalsagainst) goal_diff,     sum(           case when goalsfor > goalsagainst then 3 else 0 end          + case when goalsfor = goalsagainst then 1 else 0 end     ) score  from (     select hometeam team, goalsfor, goalsagainst from scores    union all     select awayteam, goalsagainst, goalsfor from scores ) a  group by team order by score desc, goal_diff desc; 	5.67567777270184e-05
8009741	2832	how can i only display certain rows from a database table in asp?	select [day], aoc, ryg, reasoning, notes  from dbo.ryg_conditions  where aoc ='administration' order by aoc asc,[day] desc 	0
8010543	16859	mysql: selecting many rows but establishing a limit on 1	select   food,           max(last_order_date) as max_last_order_date     from table group by food order by max_last_order_date desc 	0.00113759158009268
8010861	13563	mysql: display only 200 characters from total value	select left(description, 200) from yourtable 	0
8011313	23420	sql: group by count(*) as pct of total table row count	select categorynum,count,100*count/(sum(count) over ())::numeric as count_pct from(     select categorynum,count(1)     from tbl     group by categorynum )a; 	7.25596421957598e-05
8012619	612	query filtering	select     avg(age) avg_age,     avg(case when gender = 'm' then age end) male_avg_age,     avg(case when gender = 'f' then age end) female_avg_age from users; 	0.474276646622327
8012787	11770	how do i difference time in mysql query?	select time_to_sec(timediff(now(),time)) as time from mytable; 	0.0530584988784077
8015384	28275	how do i create an hstore from a table in postgresql ?	select hstore(array_agg(key order by key), array_agg(value order by key)) from yourtable 	0.0703004038478036
8016260	37176	grouping mysql query by date range and productid	select cpd.productid, sum(cpd.paymentsplitamount), date_format(cp.paymentdate, '%b-%y')   from campaign_payment_detail cpd   join campaign_payment cp on cp.paymentid = cpd.paymentid   join product on cpd.productid = product.productid  where cp.campaignid = 2413  group by cpd.productid, date_format(cp.paymentdate, '%b-%y')  order by cp.paymentdate desc, cpd.productid asc 	0.0132687761433814
8016549	15985	order by timestamp with nulls between future and past	select * from table if(mytime is null, [sometime],mytime) order by ... 	0.00211253758004322
8017481	26064	sql ordering colums query	select id, product_cat_id, product_type_id, ordering from table order by product_cat_id, product_type_id, ordering 	0.332433474646619
8017633	14177	how can i query a list of values into a column of rows using sqlite?	select 'john' as name union all select 'mary'  union all select 'paul'; 	0
8020983	20492	keeping returned records from mysql unique	select     exp_categories.cat_name, exp_categories.cat_id, exp_categories.cat_url_title   ,exp_category_posts.entry_id, exp_channel_titles.status  from (exp_categories  left join exp_category_posts         on exp_categories.cat_id = exp_category_posts.cat_id)  left join exp_channel_titles         on exp_category_posts.entry_id = exp_channel_titles.entry_id  where exp_categories.group_id = 2    and exp_category_posts.entry_id is not null    and exp_channel_titles.status = 'open'    group by exp_categories.cat_id order by rand()  limit 2 	0.00030877045954321
8021483	15969	most efficient way to query one to many to many table relationship	select gl.gameid, gl.type, ..., ul.userid, ul.username from     (         select gameid         from game2users         where userid = a_certain_numeric_id     ) as ug     inner join gamelist as gl         on ug.gameid = gl.gameid     inner join game2users as g2u         on ug.gameid = g2u.gameid     inner join userlist as ul         on g2u.userid = ul.userid 	0.00176025365850286
8022158	38339	how do i order by parent then child?	select  * from    @features feat order by         case          when parentid = 0          then feature          else    (                 select  feature                  from    @features parent                  where   parent.featureid = feat.parentid                 )          end ,       case when parentid = 0 then 1 end desc ,       feature 	0.00344371766891202
8023240	30683	query to get child categories and know if child categories have child categories of their own	select  * ,       case          when exists (select * from cat c2 where c2.parent_id = c1.cat_id) then 0         else 1         end as hassubcategories from    cat c1 	0
8027095	3292	first time to query 3 mysql tables	select n.student_id, n.student_name, s.subject_name, s.description from student_name n inner join student_has_subjects shs on shs.stud_name = n.student_name inner join subjects s on shs.stud_subject = s.subject_id 	0.00290071172553905
8029081	29592	select query to fetch same records more than once based on a column value	select d.content_id, 0 as download_time from downloads as d    inner join numbers as n     on n.number between 1 and d.download_count; 	0
8029334	13308	sql query calculations across multiple tables	select *, sum(amount_of_shares*c.share_price) as total from `portfolios` left join companies c on c.id = portfolios.company_id group by `user_id` order by total desc limit 5 	0.141101557927503
8030118	11118	finding related tags	select * from tag_table where qid = 3 order by frequency desc limit 5; 	0.00256943005363789
8030757	29242	add column from another table, but not affect count()	select reservation.reservation_id, customer.customer_id, customer.name,  count(ordered_services.reservation_id) as num_of_ordered_services, (select count(*) from payments where reservation.reservation_id=payments.reservation_id) as num_of_payments from reservations join customers on reservations.customer_id = customer.customer_id left join ordered_services on reservations.reservation_id = ordered_services.reservation_id group by reservation.reservation_id, customer.customer_id, customer.name order by reservation.reservation_id 	0.000301476966994399
8031530	8646	limited sum in mysql	select sum(least(5, var)) as modified_total; 	0.158928147657544
8031745	1596	sql to join tables only where all specified criteria are true	select cars.id   from cars   join car_properties as cp1     on cp1.car_id = cars.id    and cp1.property_id = 1   join car_properties as cp2     on cp2.car_id = cars.id    and cp2.property_id = 2 ; 	0.000471076692916506
8032943	1112	sql get rows matching all conditions	select * from table_name  where (name = 'toto' or name = 'tata')  and ( select count(*) from table_name where name = 'toto') > 0  and ( select count(*) from table_name where name = 'tata') > 0 	0.000100853518460042
8034253	7929	hourly sales into reporting services view, sql	select t.store, t.time, s.count_service, s.count_service_id_check from dim_timetable t left join hourly_sales s on t.store = s.store and t.time = s.time 	0.202277470338568
8034682	14094	count rows that fulfill a condition	select      team,      count(*) total_matches,     count(case when gametype = 'league' then 1 end) league_matches,     count(case then date > now() - interval 30 day then 1 end) recent_matches,     ... from matches  group by team 	0.00581957332397044
8036098	36861	is it possible to pull a row to the top of a query result in mysql?	select * from   foo where  id in ( 2, 14, 22 ) order  by id != 14 	0.000436235384427079
8036136	16876	ordering the query output based on the data division	select col2,col3    from a  order by (case when col1 like '63%' then 2 else 1 end), col1 	0.00451485334165476
8039085	9861	sql order by clause in for xml	select t.seccolumnname 'td' from   dbname.tablename t where  t.firstcolumnname = 1 order  by t.seccolumnname for xml path('tr'), root ('table') 	0.789952705656505
8039674	1941	sql average of a sum divided by a count	select avg(price) as averagespend, customername from customers, transactions where customers.customerid = transactions.customerid and transactiontypeid = 1 group by customers.customerid 	0.000499978911065937
8039675	41055	how to get records from table a that don't have equivalents in a certain status in table b?	select np.id as people_id, np.first_name, np.last_name, ur.rid from new_people np left join institute.users_roles ur on np.institute_uid = ur.uid and ur.rid =8 left join roster r on np.id = r.people_id  where np.company_id =1 and np.active =1 and (r.roster_id is null or r.status =  'pending' or r.status =  'submitted') order by np.last_name, np.first_name 	0
8039973	11531	equi-join with mysql	select videos.video_size, videos.video_datetime, videos.video_length,         cameras.camera_name   from videos inner join cameras using (user_id, camera_id)  where videos.user_id=69 	0.783088729900329
8040127	7395	how do i get an inclusive result set without using php?	select     entry_id from     exp_category_posts where     cat_id = 1 or     cat_id = 2 group by     entry_id having     count(*) = 2 	0.0146351223732462
8040788	20932	select timestamp by time ignoring date	select * from table where time(time) = '10:09:13' 	0.00287903748351098
8041280	12586	getting default constraints information	select  c.name ,          col.name,          c.definition from    rem.sys.default_constraints c          inner join rem.sys.columns col on col.default_object_id = c.object_id          inner join rem.sys.objects o on o.object_id = c.parent_object_id          inner join rem.sys.schemas s on s.schema_id = o.schema_id 	0.00949688848076516
8042750	26845	mysql return records that match and/or against second table values	select name, count(c.tag_id) as cnt from tablea a join tablec c on a.id = c.name_id where c.tag_id in (1,3) group by name having cnt = 2 	0
8044281	5559	sql : select distinct of one column while ignoring other columns	select id, min(keyid) from tbl group by id 	0
8045358	7974	getting the wrong result back from the stored procedure after calling another stored procedure	select 1                          as statusmsg,         'user successfuly created' as       msg,         'usercreation'             as   msgtype; 	0.243380217331037
8045365	20768	sql query ordering and using group by	select p.title as product_title, pt.title as product_type_title from products p inner join product_types pt     on p.product_type_id = pt.id where p.product_cat_id = 42 order by pt.ordering, p.ordering 	0.739846891170008
8046000	25052	list all sequences in hsqldb 1.8	select * from information_schema.system_sequences 	0.00470621453573333
8046349	10169	is it possible to show only value in mysql "show variables"?	select @@version; 	0.00122178826922373
8047307	32327	how to select from mysql record then add the amount together?	select sum(amount) as total_ammount from item 	0
8047696	26318	how to group by string id in sql server 2008	select left(id, 8) as nid,        sum(value) as tot from your_table group by left(id, 8) 	0.0667839733801229
8048480	32167	a sql query with multiple search word	select inl.name from dbo.[inventorylocalization] inl  where not exists     (select 1 from fnsplitstring(n'red green blue',' ') words      where (inl.name not like '%'+ words.item +'%')) 	0.388309831325601
8049026	14261	how to use the count function of mysql in qt?	select count(*) from dictionary.table_english 	0.393216190401589
8049697	5417	how to return the highest scoring image for a given product?	select p.*,         pc.categoryname, pc.categorydescription,         pim.thumbname, pim.score from products p inner join product_categorys pc      on p.categoryid = pc.pid left join product_images pim      on p.pid = pim.productid where p.vendorid =  '14'   and p.deleted =  0   and (pim.score =        (select max(score) from product_images pim2         where p.pid = pim2.productid)    or pim.score is null) group by p.pid order by title asc limit 10 	0
8050213	5598	how to sort and add my database record?	select date,amount,item_id from table group by date,item_id with rollup 	0.00521341577435048
8050854	18667	how to find maximum avg	select max (avg_salary) from (select worker_id, avg(salary) as avg_salary   from workers   group by worker_id); 	0.0024986728382226
8050956	5222	sql count group by	select    code,           sum(packet) as packet,           sum([weight]) as [weight] from      [yourtable] group by  code order by  code 	0.266919453910809
8051959	18644	how to use having without selecting field in mysql	select `dt1`.*  from   (select  `projects`.*,                  (select sum(`amount`)                  from `accountprojectspayment`                  where `projects_id` = `projects`.`id`) as `payed`                            from `projects`) as `dt1`             inner join `bids` on `bids`.`id` = `dt1`.`bids_id` where `bids`.`amount` >= `dt1`.`payed`; 	0.0353537081292531
8055244	16143	how do i count top poster on specific category in mysql	select  dt1.catname,   dt1.userid from  ( select count(*) as num_posts, catname, userid    from update_log    group by catname, userid) as dt1  inner join (   select max(num_posts) as max_posts, catname   from (    select count(*) as num_posts, catname, userid    from update_log    group by catname, userid) as dt2   group by catname) as dt3   on ( dt3.catname = dt1.catname        and dt1.num_posts = dt3.max_posts) 	0.000426477053998401
8055662	38241	sql server - query each group of a group by	select code      , avg(case when columna<>0 then columna else null end) as columna      , sum(columnb) as columnb from table tbl group by code 	0.0051209727321508
8055980	7083	php mysql join 3 tables	select * from feedback  left join members on feedback.author = members.id  left join clans on members.clan = clans.id where feedback.user = 1 	0.193471300554131
8057780	24323	how to get other columns in this query	select un.user, un.role, max(un.city), max(un.bday)  from [unique] un   group by user, role 	0.0053483708906969
8058433	37907	birthdays in sql... disregard year in a date value	select    * from    users where    month( users.birthdate ) = month( getdate() )    and    day( users.birthdate ) = day( getdate() ) 	0.000405627768921687
8061514	22269	how to combine data from multiple tables using sql?	select      pr.project_id,      pr.team_size,      pr.from_date,      group_concat(tech.technology_name separator ', ') as technologies from       project pr      join project_technologies ptech on pr.project_id=ptech.project_id     join technologies tl on ptech.technology_id=tl.technology_id group by     pr.project_id,      pr.team_size,      pr.from_date 	0.00158367665551483
8063639	39993	how do i build a sql query to show two columns of different date ranges?	select type,period_a,period_b,period_a+period_b as total from(   select type,count(1) as period_a   from contact_ext   left join contact   using(id)   where date>='20100101' and date<='20101212'   group by 1 )a join(   select type,count(1) as period_b   from contact_ext   left join contact   using(id)   where date>='20110101' and date<='20111111'   group by 1 )b using(type); 	0
8064459	24984	how to sort rows by on, off, sold	select * from table order by field(`sort_it`,'on','off','sold'),`sort_it` 	0.000400071454944335
8065162	28207	join products table with prices table, for products with n valid prices	select     pro.*   , pri.* from      product as pro   join     price as pri       on pri.priceid =          ( select p.priceid            from price p             where p.productid = pro.productid              and p.started <= current_date()               and ( p.expires is null                 or p.expires >= current_date()                  )            order by p.priceid desc             limit 1          ) 	0.00010372934522894
8065166	33393	how to change the date format to string	select convert(char(8), your_date_column_name, 112) from table_name 	0.00320977978786994
8067029	19792	join two tables: all rows from the first with a sub-set from the second	select e.empid, d.dob  from employee as e  left outer join dependent as d  on e.empid = d.empid and d.relid = 1 	0
8067681	36080	sql like clause multiple values	select t.column1 from @tablea t inner join @words w on charindex(w.word, t.column1) > 0 group by t.column1  having count(distinct w.word) = (select count(*) from @words) 	0.629599318960965
8068407	1519	whats the best way to compare a tables data against another?	select distinct email into    #tcustomersemail from    dbo.customers where   ( email is not null )     and ( email like '%@%' )     and ( right(email, 4) in ( '.net', '.com', '.org' ) )     and ( email not like '%@uniformcity.com' )     and ( email not like '%@lifeuniform.com' )     and ( charindex('.', email) <> 1 )     and ( right(rtrim(email), 1) <> '.' )     and ( left(ltrim(email), 1) <> '@' )     and ( email not like '%[`:;_*-,^[^]()+%\/=#-]%' escape '^' ) order by email select  replace(replace(replace(replace(emailoptout, '"', ''), ',held', ''),',unsub', ''), ',confirm', '') as cleanemail into #toptouts from    [lifemail].[dbo].[emailoptouts] select email from #tcustomersemail as tce where email not in (select cleanemail from #toptouts as too) 	0.000491701205989371
8069753	8662	sql query max id	select * from (     select top 13 row_number() over (order by fiscalyear, fiscalmonth) as id         ,fiscalyear         ,fiscalmonth         ,sum(stdcost) as stdcost         ,concat     from dbo.[13568]     group by fiscalyear, fiscalmonth, concat     order by fiscalyear desc, fiscalmonth desc ) as x order by fiscalyear, fiscalmonth 	0.0526776190261958
8070102	34283	tsql equality on groups of rows	select          (         case when matchcount = gdcount and matchcount = idcount              then groupidentifier              else null          end) groupidentifier,          cj.tempgroupidentifier      from     (     select gd.groupidentifier, id.tempgroupidentifier, count(1) matchcount     from @groupdata gd      cross join @inputdata id     where id.elementidentifier = gd.elementidentifier      group by gd.groupidentifier, id.tempgroupidentifier) as cj     cross apply (select count(groupidentifier) from @groupdata gdca where gdca.groupidentifier = cj.groupidentifier) as gdc(gdcount)     cross apply (select count(tempgroupidentifier) from @inputdata idca where idca.tempgroupidentifier = cj.tempgroupidentifier) as idc(idcount) 	0.00470757612289294
8070314	28145	how do i query "begin with" in mysql?	select ... where stuff like 'itunes%'; 	0.544809235384484
8070521	21341	grabbing random rows while maintaining order across other tables	select inner_listings.id, inner_listings.title, inner_listings.featured,   listingselements.field_name, listingsdbelements.field_value from    (select listings.id, listings.title, listings.featured   from listings   where rand()<(select ((20/count(*))*10) from listings)   order by rand()) inner_listings  inner join listingselements on inner_listings.id = listingselements.id where (listingselements.field_name = "price"   or listingselements.field_name = "bathrooms"   or listingselements.field_name = "bedrooms"   or listingselements.field_name = "sq_meter"   or listingselements.field_name = "city") 	0.000226712724178412
8071261	21499	count(*) multiple tables	select (select count(*) from table1) as table1count,         (select count(*) from table2) as table2count from dual 	0.0471339578508776
8071263	35587	sql server select random and not random	select top 10 booktitle,               bookauthor,               bookcategory from   thetable order  by case             when bookcategory like 'sale%' then 0             else 1           end,           newid() 	0.159492037659801
8071364	17359	how do i get mysql to join a whole table?	select * from subscriptions left join prices on subscriptions.id=prices.id where subscriptions.id=100 	0.00927486811212653
8071983	3476	how to get first and other random rows from a table	select * from foo order by id limit 1  union select * from foo where id not in (select id from foo order by id limit 1)    order by rand() limit 3 	0
8072231	38903	mysql - how to select minium and maximum in one (union) query	select ename, sal from emp where sal = (select min(sal) from emp) union select ename, sal from emp where sal = (select max(sal) from emp) 	0.00465899338415113
8072402	8607	looking to extract data between parentheses in a string via mysql	select substr(columnname,instr(columnname,"(") + 1, instr(columnname,")")) as temp from mytable 	0.0177283444684518
8072936	31328	which abbreviation should i use from time_zone_transition table?	select * from mysql.time_zone_transition_type ztt inner join mysql.time_zone_transition tzt on tzt.time_zone_id = ztt.time_zone_id and tzt.transition_type_id = ztt.transition_type_id where tzt.time_zone_id = 163 and unix_timestamp('2014-01-23 16:00') >= transition_time order by transition_time desc limit 1; 	0.511739762396485
8073578	35553	how to sort records except first record in sql	select * from table order by srno=1 asc, tempann desc 	0
8075037	28820	mysql - get min, max and a property of row containing max	select b.maxt, b.mint, viewtime  from session_progress, (select max(timestamp) as maxt, min(timestamp) as mint from session_progress  where session_id=2374 ) b where where session_id=2374 and timestamp = b.maxt 	4.59881202537251e-05
8075565	23343	min and max value for a row, not column	select greatest(`value1`, `value2`, `value3`, `value4`, `value5`) as `highest` from `tablename` where ..... 	0.000828268916741328
8075973	29467	sqlite: express the difference as days, hours, minutes between two given dates	select     cast((strftime('%s', '2011-11-10 11:46') - strftime('%s', '2011-11-09 09:00')) / (60 * 60 * 24) as text) || ' ' ||     cast(((strftime('%s', '2011-11-10 11:46') - strftime('%s', '2011-11-09 09:00')) % (60 * 60 * 24)) / (60 * 60) as text) || ':' ||     cast((((strftime('%s', '2011-11-10 11:46') - strftime('%s', '2011-11-09 09:00')) % (60 * 60 * 24)) % (60 * 60)) / 60 as text); 	0
8076176	11029	mysql select another row if one doesn't exist	select * from     (select * from your_table       where id = your_id       limit 1     union     select * from your_table       limit 1) a limit 1 	0.000780751345549368
8076236	29628	mysql between operator with dates	select date('2011-02-29') between date('2011-02-01') and date('2011-03-03') 	0.255517266317209
8076950	4301	event/time and criteria based sql	select a.*  from user a  left join event b on (b.user = a.id and b.event = 'userjoined')  where a.joineddt < '1 week ago date'  and b.id is null 	0.0104647495737475
8077174	4693	how to display a day on a given date using an sql select query in mysql?	select dayname(your_date) from your_table 	0
8078492	4229	pull data from two tables	select tb1.username as member_name,        tb2.username as friend_name from   membertable as tb1 inner join (        membertable as tb2,        memberrelationstable ) on (     tb1.member_id = memberrelationstable.member_id and     tb2.member_id = memberrelationstable.friend_id ) 	0.000249243617667968
8079985	21102	mysql query for returning results with starting few letters of a column field	select * from user where name like 'mic%' 	0.000359521674419259
8080624	28478	two tables with linking column "id" that return only unique "id" lines for the parent table	select t.*, p.*  from threads  inner join posts p on t.id = p.id  where ((t.subject like '%blue%') or (p.post like '%blue%'))  and p.timestamp = (select min(p2.timestamp) from posts p2 where id = t.id)  order by p.timestamp 	0
8084061	31227	select the earliest and latest dates	select t.in_click,      t.first_name,     t.create_date from tracker t where      t.create_date = (select min(create_date) from tracker where in_click = t.in_click)     or t.create_date = (select max(create_date) from tracker where in_click = t.in_click) 	8.40098454989899e-05
8084187	29599	return records with repeating column value in mysql	select someid from yourtable group by someid having count(1) > 1 	0.000276560983061291
8084571	16627	not unique table/alias	select pa.projectid, p.project_title, a.account_id, a.username, a.access_type, c.first_name, c.last_name       from project_assigned pa inner join account a         on pa.accountid = a.account_id inner join project p         on pa.projectid = p.project_id inner join clients c         on a.account_id = c.account_id      where a.access_type = 'client'; 	0.216727791901548
8086095	37808	sql query to retrieve products matching one or more filters	select * from products where p_id in    (     select pf_prod_id from product_filters      where pf_filter_id = @filterid and pf_filter_value = @filtervalue     union all    ) 	0.00064988746067289
8086711	1983	sql table column information probing	select column_name, data_type, character_maximum_length,      numeric_precision, numeric_scale from information_schema.columns where table_name = 'yourtable' 	0.0204167462049862
8087325	25397	finding foreign keys in ms sql server with information_schema	select object_name(parent_object_id), object_name(referenced_object_id)     from sys.foreign_keys     where referenced_object_id = object_id(@mytable) 	0.0196423307568527
8087444	36461	sql - how to select multiple tables and join multiple rows from the same column?	select painting.id,         painting.order,         painting_en.url,         `group`.en as `group`,         type.en as type,         location.en as location from   painting         left join painting_en         using (id)         left join id_portfolio `group`           on `group`.id = painting.id_group         left join id_portfolio type           on type.id = painting.id_type         left join id_portfolio location           on location.id = painting.id_location  where  painting_en.url = '2011-name3'  limit  1 	0
8088556	2990	mysql select within select	select s.phone from student s  inner join photos p  on p.student_id=s.id where p.photo is not null 	0.130957286716174
8088923	27360	incorrect number of rows with two inner joins that count related records	select animals.id, animals.name, species.name, species.exlevel, count(comments.id) from `animals`  inner join species on animals.spid = species.id left join comments on animals.id = comments.anid and comments.type =2 where animal.level =1 group by animals.id, animals.name, species.name, species.exlevel 	0.000238915159729931
8090557	39103	finding the lowest group of numbers in a row, not just the lowest	select `src`, `value` from (     select 'a' as `src`, a as `value` from yourtable where id = 42     union all     select 'b' as `src`, b as `value` from yourtable where id = 42     union all     union all     select 'j' as `src`, j as `value` from yourtable where id = 42 ) t1 order by `value` limit 3 	0
8090738	38868	c# storing sql select query into a variable	select distinct userroles.employeeid from userroles  inner join othertable on othertable.employeeid = userroles.employeeid  where (userroles.[status] = 'deleted') 	0.16416876846434
8093292	10661	android: select query in android database	select children from navigation where key='home' 	0.693607021580766
8093936	7931	how to using sql get row count that does have equal values?	select     created     ,count(*) as [occurrences] from     tablename group by     created having count(*) > 2 	0.000138627759672187
8094156	35897	know relationships between all the tables of database in sql server	select     fk.name 'fk name',     tp.name 'parent table',     cp.name, cp.column_id,     tr.name 'refrenced table',     cr.name, cr.column_id from      sys.foreign_keys fk inner join      sys.tables tp on fk.parent_object_id = tp.object_id inner join      sys.tables tr on fk.referenced_object_id = tr.object_id inner join      sys.foreign_key_columns fkc on fkc.constraint_object_id = fk.object_id inner join      sys.columns cp on fkc.parent_column_id = cp.column_id and fkc.parent_object_id = cp.object_id inner join      sys.columns cr on fkc.referenced_column_id = cr.column_id and fkc.referenced_object_id = cr.object_id order by     tp.name, cp.column_id 	0.00054635868681493
8094642	19505	repeat same row in the sql selection statement under some conditions	select courseid,coursename,credithours,labsession from courses union all select courseid,coursename,credithours,labsession from courses where labsession='y' order by courseid 	0.00110860040474617
8096550	20858	mysql: determine which database is selected?	select database() from dual; 	0.0291850713938616
8096634	32131	find duplicates, display each result in sql	select * from (select id, name, count(*) over(partition by name) [count]       from table) t where [count]>1 	0
8096833	19907	sql sub-select, show only items that is not zero	select     *     from (          ) dt     where dt.qty_s!=0     order by dt.upc 	0.00505786166967906
8097432	9429	mysql - many to one from room to apartment: how to get the lowest priced room for an apartment without having to iterate through all the rooms?	select apartment.id,      min(room.price)  from room      join apartment on room.apartmentid=apartment.id  group by apartment.id; 	0
8098736	2874	how to join on varchar(32) and binary(16) columns in sybase?	select strtobin(convert(char(32), '000036ca4c4c11d88b8dcd1344cdb512')) 	0.0909720017016297
8099747	22923	how to avoid duplicate on joining two tables	select std.id, std.name, m.mark, row_number()    over() as rownum   from student std      join marks m         on std.id=m.id and m.mark=50   group by std.id, std.name, m.mark 	0.00213848901016117
8102909	2641	get max and min values along with their row id?	select * from data  where temp_hi = (select max(temp_hi) from data) or temp_lo = (select min(temp_lo) from data); 	0
8104187	2382	mysql hierarchical queries	select  @id :=         (         select  senderid         from    mytable         where   receiverid = @id         ) as person from    (         select  @id := 5         ) vars straight_join         mytable where   @id is not null 	0.657026818776783
8105654	34222	mysql query - sum the capacity of multiple warehouses	select    warehouse.location,    warehouse.warehouseid,    sum(crate.max_capacity) as total_capacity from warehouse inner join crate   on crate.warehouseid = warehouse.warehouseid group by   warehouse.warehouseid 	0.0556528287262066
8105721	25088	grouping multiple fields using sql	select session_id, wm_concat(name_status), time from  (   select session_id, (name+':'+status) as name_status, time   from stuff ) group by session_id order by time 	0.121592662214868
8106094	28844	select all from two tables where ids match	select *  from product as p  join resource_downloads_history as r   on r.resource_id = p.resource_id 	0
8107602	16955	identify values based on date and limit	select     name,     date,     date >     (         select min(date)         from your_table         where date > (select min(date) from your_table)     ) as disabled from your_table order by date 	0.000198947264685403
8109642	14077	mutual friends mysql query	select * from friend_list as f inner join friend_list as mf on f.friend_id = mf.friend_id where f.uid = 7    and f.status = 1    and mf.uid = 3    and mf.status = 1 	0.0701528728612486
8111440	446	mysql count results of union all statement	select page_id, count(*) from tags where tag in ('new zealand', 'trekking') group by page_id having count(*) > 1 	0.0314150369124606
8111968	13870	join query on attribute of association table	select distinct ss.student_id,name  from studentcourse  ss join  students on ss.student_id = students.id  where not exists ( select course_id from studentcourse  where  student_id = ss.student_id and grade<>'f' ) 	0.00450833393256159
8112466	21039	how can i format strings with t-sql	select convert(varchar(10), cast(1234.333 as money), 1) 	0.327159524512054
8115289	12175	select results from mysql using a regular date from timestamp column	select      sum(total_amount) as total_sales_amount  from      purchases  where      timestamp <= date("2011-11-13")  and      timestamp >= date("2011-11-06") 	0.000189877133537748
8115504	4225	a query that tells the number of submits for each location along with the location's name	select     location_name,     count(*) as number_of_submits from reports join markers on markers.id = reports.location_id where reports.user_id = 104 group by reports.location_id 	0
8119083	29301	join by a number of criterias	select  actors.id         , max(actors.count) from    artists          inner join actors on artists.title = actors.title group by         actors.id 	0.0122590712007413
8120107	12947	what could be a select query to search records by "last week", "last month" and "last year"?	select * from my_table where createdate between date_sub(now(), interval 1 week) and now();     select * from my_table where createdate between date_sub(now(), interval 1 month) and now() ;    select * from my_table where createdate between date_sub(now(), interval 1 year) and now(); 	0
8120172	13814	looping through a numeric range for secondary record id	select o.orderid, o.userid, o.deskid o.orderid%100 + 1 as ordernumber,  case when lineitem%3 = 1 then 'a'  when lineitem%3 = 2 then 'b'  when lineitem%3 = 0 then 'c' end as itemletter, oi.productid from tb_order o inner join tb_orderitem oi on o.orderid=oi.orderid 	4.56238103873658e-05
8120826	8089	count number of rows in each group in mysqli	select n.name, count(*) from names n, mark m where n.nameid = m.nameid and m.child = '1' group by n.name 	0
8120953	29799	order by with columns that are sometimes empty	select companyname , lastname , firstname from ... join ... order by coalesce(companyname , lastname, firstname),          coalesce(lastname, firstname),          firstname 	0.00487617455676761
8122468	14941	adapting formats between an sql database and a ploting service	select datetime, count(id_stat) as numvisits where type="type_profile" and user_url = "xxx" group by date(date_sub(datetime, interval 1 day)) 	0.361517950225573
8122796	22320	get corresponding orderdate for max(orderprice)	select orderdate from table_name having max(column_name); 	0.00573629281184471
8125412	26239	sort by postcode depending user input	select mycolumn  from mytable order by case when mycolumn = 'l25' then 0 else 1 end,     mycolumn 	0.00515034828638004
8126088	16225	sql server 2000 convert datetime to get hhmm	select replace(convert(varchar(5), getdate(), 108), ':', '') 	0.0195248706043167
8126111	36427	mysql: innodb last modified	select max(`edited`) from `table1` union select max(`edited`) from `table2` union select max(`edited`) from `table3` union select max(`edited`) from `table4` order by `edited` desc limit 1 	0.00404502695344676
8126245	34887	multiple link columns for a report in application express?	select empno, ename, job, sal, null link_column1, null link_column2 from emp 	0.408958855104326
8126322	34378	sql inner join and count	select *,         coalesce(c.count_post_id,0) as count_post_id from   blogpost         inner join bloguser           on blogpost.bloguserid = bloguser.bloguserid         inner join category           on blogpost.categoryid = category.categoryid         left join (select blogpostid,                            count(blogpostid) count_post_id                    from   blogcomment                    group by blogpostid) c          on c.blogpostid = blogpost.blogpostid  order  by blogpost.blogpostid desc 	0.797435469192247
8126770	7572	sqlite: simple sql - where in timestamp field	select * from your_table where date(event_ts, 'localtime') = date(current_timestamp, 'localtime') 	0.429040487884697
8126824	5439	how to have 2 oder by in one sql query	select *  from   (select *          from   table          order  by value desc          limit  10) as mytable  order  by rand() 	0.00685593445382864
8127746	33919	how to select from a column while excluding certain values	select value1, value2 from tablename  where tablename.name != "nobody"  and   tablename.name != "mainconf" limit 2; 	0
8127779	40096	return rows that can be multiple types	select c.carid, c.carmodel from cars c inner join cartypes ct on c.carid = ct.carid where ct.typeofcar in ('chickmagnet', 'gasguzzler') group by c.carid, c.carmodel having count(distinct ct.typeofcar) = 2 	0.00760894170000702
8127871	6959	sql - select new values after particular time (or id)	select ip from mytable group by ip having min(time) >= 1321301522 	0.000210794449919135
8128725	14777	merging count(*) from different tables with different where condition	select name, count(posts.pk), count(replies.pk)   from owners, outer (posts, outer replies)   where owners.pk = posts.owner_pk     and posts.pk = replies.post_pk     and (posts.post_date between ? and ? or replies.reply_date between ? and ?)   group by name 	0.000100173392345032
8128795	39949	single query to get date and flag the date as enabled	select    t1.datecolumn,    case when isnull(t2.datecolumn)      then 1     else 0 end    as disabled  from table t1 left outer join   (select datecolumn from table     order by date_column asc limit 3) t2   on t1.datecolumn =t2.datecolumn  order by t1.datecolumn asc 	0.000345746975502497
8129276	29229	mysql combine two very large tables when three columns are equal	select t1.name, t1.birthdate, t1.ordernumber     from table1 t1     where not exists(select null                          from table2 t2                          where t2.name = t1.name                              and t2.birthdate = t1.birthdate                              and t2.ordernumber = t1.ordernumber) 	0.00129086499676007
8129284	29179	sql query to find the percentage difference of views between two given dates	select top8.idvideo, (vtoday.times - vyesterday.times) / vtoday.times from    (select       idvideo from nviews       where day = curdate()    order by watches desc limit 8) top8    inner join    nviews vtoday         on vtoday.day = curdate()        and vtoday.idvideo=top8.idvideo   left outer join     nviews vyesterday        on vyesterday.day= date_add( curdate(), interval -1 day) and            vyesterday.idvideo = top8.idvideo 	0
8131253	39123	mysql multiple aggregates	select        a.*,        b.*,        coalesce( preaggc.ccount, 0 ) as ccount,       coalesce( preaggc.withdcount, 0 ) as withdcount    from        tablea a          join tableb b             on a.id = b.aid          left join ( select aid,                              count( distinct id ) ccount,                             count(*) as withdcount                         from tablec                            left join tabled d                               on c.id = d.cid                         group by aid ) preaggc             on a.id = preaggc.aid 	0.569179090025629
8131498	19387	cleaning up session table in db	select * from `user_sessions` where id in (select max(id) as id from `user_sessions` group by userid) 	0.350262958455787
8131532	810	sql query to select common values	select t1.username  from ip_table as t1      join ip_table as t2      on  t1.`username` = t2.`username` and t1.ip = <ip1> and t2.ip = <ip2> ... etc 	0.00860866351466086
8132613	33452	calculating z-score for each row in mysql? (simple)	select     mergebuys.ptime,     (mergebuys.m1 - aggregates.avgm1) / aggregates.stdm1 as z1,     (mergebuys.m2 - aggregates.avgm2) / aggregates.stdm2 as z2,     (mergebuys.m3 - aggregates.avgm3) / aggregates.stdm3 as z3,     (mergebuys.m4 - aggregates.avgm4) / aggregates.stdm4 as z4 from     mergebuys     cross join (         select             avg(m1) as avgm1,             std(m1) as stdm1,             avg(m2) as avgm2,             std(m2) as stdm2,             avg(m3) as avgm3,             std(m3) as stdm3,             avg(m4) as avgm4,             std(m4) as stdm4         from             mergebuys     ) as aggregates 	0.00399255414233379
8133633	20126	how to know if it is unsigned of a field from mysql by mysqldb	select column_name, column_type   from information_schema.columns   where table_name = 'tbl_name' 	0.00355149212204509
8134729	28049	complex queries - get people with the most referrals	select ref.email, ref.refcode, ref.referrals from  (   select       email,      referral_code as refcode,      (select count(*) from beta_list where referrer=refcode) as referrals   from       beta_list ) as ref where      ref.referrals > 0 order by      ref.referrals desc limit      10 	0.00911387422018375
8136290	1794	recalculate field from datagridview	select     dbo.doss.behdr ,  dbo.doss.dosno ,  sum(dbo.kbpres.uur) as somuur ,  sum(dbo.kbpres.minuut) as somminuut  ,  cast ((sum(dbo.kbpres.uur) + sum(dbo.kbpres.minuut) / 60) as varchar(2)) +     ':' +     cast ((sum(dbo.kbpres.minuut) % 60) as varchar(2)) as [derivedcolumn]  from     dbo.kbpres     inner join     dbo.doss on dbo.kbpres.ino = dbo.doss.ino  where     (dbo.doss.behdr like @cbobeheerder)  group by     dbo.doss.behdr, dbo.doss.dosno 	0.0224051871153258
8136392	12744	convert a sql subquery into a join when looking at another record in the same table access 2010	select people.id, people.aacode, people.persno,          people.hrp, people.dvhsize, xmarsta.marital,         [marital] & " (" & [people.agecat] & ")" & [ral2] & [rage2] &          [ral3] & [rage3] as hstyp,         fam2.r01 as rel2,        fam3.r01 as rel3,         relat2.relationship as ral2,        relat3.relationship as ral3,        fam2.agecat as rage2,         fam3.agecat as rage3  from (((((people left join (people  as fam2) on (fam2.aacode = people.aacode  and fam2.persno = 2)) left join (relatives as relat2) on relat2.id = fam2.r01) left join (people as fam3)   on (fam3.aacode = people.aacode  and fam3.persno = 3)) left join (relatives as relat3) on relat3.id = fam3.r01) left join xmarsta on xmarsta.id=people.xmarsta) where (people.hrp=[people.persno]) order by people.aacode; 	0.00103691408831119
8136767	11839	how to write a sql query to get this output?	select loan_no from your_table where loan_no not in   select distinct loan_no from your_table   where status = 'unpaid') group by loan_no 	0.654363507728644
8137221	27154	select n rows before and after the row matching the condition?	select child.* from stack as child, (select idstack from stack where message like '%hello%') as parent where child.idstack between parent.idstack-2 and parent.idstack+2; 	0
8140513	35558	t-sql inner join first result of inner join	select p.propertyid, p.name, pi.propertyimageid, pi.source, pi.type    from property p         inner join propertyimage pi          on pi.propertyimageid = (select max(sub.propertyimageid)                                      from propertyimage sub                                    where sub.propertyid = p.propertyid) 	0.590073130097623
8141070	7933	first part of postcode	select records.company, records.full_postcode, area.[insert your fields here] from records  left join area     on area.stripped_postcode = records.stripped_postcode    and records.id= area.record_id where records.postcode like strsearch+'%' 	0.00782047080466021
8141789	40534	join one table against many rows in another table	select foo.code,     foo.title,     title.value as localized_title,     foo.description,     description.value as localized_description from foo join localization as title on title.code = concat('foo', foo.code, 'title')     and title.locale = 'es' join localization as description on description.code = concat('foo', foo.code, 'description')     and description.locale = 'es' 	7.06640805559248e-05
8142462	9391	date stored as text query between and higher	select * from recordtable  where (month(cast(birthday as date)) = 10) and cast(anotherdate as date) < cast('20081111' as date); 	0.0401571436081808
8142660	1102	can you have a sql where clause on a calculated field	select name, sum(exceptions) as exceptions from results as r group by (name) having sum(exceptions) > 0 	0.0701486552056214
8142681	38492	how to generate 5 random numbers in mysql stored procedure	select group_concat(i separator '|')   from (  select i             from (  select i                       from integers                      where i between 1 and 50                   order by rand()                      limit 5) sort_these_five         order by i) concat_these_five; 	0.0056847214812156
8146122	32271	how to get the last updated record?	select recid, max(lastmodified) from table group by recid 	0
8147743	27774	getting values of both status from a same field in mysql	select * from `lead` where    (`added_on` >= '$from' and `added_on` <= '$to')    and `status` in ('hot', 'paid') 	0
8147834	2284	how to echo print statements while executing a sql script	select concat ("updated ", row_count(), " rows") as ''; 	0.40020766481741
8148778	15852	sorting alphanumeric data	select your_field from your_table order by (your_field + 0 <> 0 or your_field = '0') asc, your_field + 0, your_field 	0.11902206395413
8148800	35376	sqlite distinct with sorting	select username  from messages group by username order by max(timestamp) 	0.323119978559779
8151907	15677	how to fetch dates between the from date and to date from a field which is stored as varchar in mysql	select * from payment where next_due_date  <= '$strtdate' and next_due_date  >= '$enddate'; 	0
8151986	38846	sum of long vectors in sql	select ifnull(v1.value, 0) + ifnull(v2.value, 0) from (     select i1, i2 from eigaki_vectors where name = 'a'     union     select i1, i2 from eigaki_vectors where name = 'b' ) indices left outer join eigaki_vectors v1 on indices.i1 = v1.i1 and indices.i2 = v1.i2 and v1.name = 'a' left outer join eigaki_vectors v2 on indices.i1 = v2.i1 and indices.i2 = v2.i2 and v2.name = 'b' 	0.782197072828282
8152136	9607	counting year and month entries from datetime fields	select count(*), year(fdateconfirmed), month(fdateconfirmed) from tsubscriber group by year(fdateconfirmed), month(fdateconfirmed) select count(*), year(fdateunsubscribed), month(fdateunsubscribe ) from tsubscriber group by year(fdateunsubscribed), month(fdateunsubscribed) 	0
8152306	37798	using group by & returning the latest duplicate	select     [what you want to know about the latest row] from     table t1     inner join     (         select             lat,             long,             max(timestamp) as latest         from             table         group by             lat,             long      ) as t2      on (          t1.lat=t2.lat and          t1.long=t2.long and          t1.timestamp=t2.latest      ) 	0.00182599497114539
8152853	41283	sql grouping and counting using existing row	select user_id, product_id, sum(count) as total from requests group by user_id, product_id 	0.0104305169889815
8153246	27481	duplicate answers when predicate in more than one field sql	select      a.* from      addresses a         join     individuals i     on a.addressid = i.addressid group by     a.streetname, i.firstname, i.surname having     count(1) > 1 	0.00977065702778153
8154585	3625	retrieving representative records for unique values of single column	select answers.*, cc.votes as votes from answers join (     select max(id) as id, count(id) as votes      from answers     group by trim(lower(choice)) ) cc  on answers.id = cc.id order by votes desc, lower(response) asc 	0
8154840	27621	sql sproc returning some duplicate records	select distinct     top (@recordcount)     p.productid,     p.name,     pv.variantid 	0.00695838822036724
8155664	30237	how do i calculate discount and add up the totals for records returned - php / mysql	select member_id, sum(asset_value * percent_owner / 100) from ... where ... group by member_id 	6.9696567198763e-05
8155924	32501	check membership of elements of one column in another, mysql	select count(*) from mytable mt1   left join mytable mt2 on mt1.column1 = mt2.column2 where mt2.column is null 	0
8156209	21589	how to determine if a date range overlaps any part of a specific month?	select *  from ea_engagements  where startdate <= '1999-11-30'    and enddate   >= '1999-11-01' 	0
8157234	456	how to perform range queries across tables in sql	select * from a, b where a1 between b1 and b2 	0.017458815014709
8157578	31845	counting type of data in a row	select count(sess) from (select distinct(session) as sess from stu_id); 	0.000749642303096195
8157912	30411	sql server group by dilemma	select top 1 with ties mysubid, count(mysubid) as mysubidcount from mytable group by musubid order by 2 desc 	0.757279649293257
8158462	24948	mysql left-join, count by unique value in a field not working	select g.group, count(gu.group_id) as groups_count     from groups g         left join groups_users gu              on g.id = gu.group_id     group by g.group; 	0.0581318519352463
8158732	27508	how to do calculations with database values in classic asp?	select top 1 xx+1 from w_table order by idx desc 	0.139267006667159
8158786	2181	mysql exclusion join when join condition is in other table	select * from contact   inner join mprod on mprod.contact_id = contact.id   inner join ivalues on ivalues.mprod_id = mprod.id   left outer join (     select mprod.contact_id, ivalues.*       from mprod       inner join ivalues on mprod.id = ivalues.mprod_id       where ivalues.period = 0         and ivalues.current = 1         and ivalues.cert = 1         and mprod.type_id = 15747         and ivalues.exists = 1   ) as pv on pv.contact_id = contact.id and pv.value > ivalues.value   where ivalues.period = 0     and ivalues.current = 1     and ivalues.cert = 1     and mprod.type_id = 15747     and ivalues.exists = 1     and pv.id is null   group by pr.id     order by iv.value asc   limit 10; 	0.584940225641268
8160707	4858	sql query for 3 tables	select *  from order_item oi inner join order o on o.id=oi.order_id left join process p on p.order_item_id = oi.item_id where o.customer_id = 1 and p.id is null 	0.185351332052479
8163091	4531	sql join to get most recent record	select       m.*, data.*  from [measure] m  cross apply      (select top 1 ev.* from [event] e join eventvalues ev on e.eventid = ev.eventid        where m.time >= e.time order by e.time desc) as data order by m.distance 	5.92457268673584e-05
8166573	34932	join on a table where a field not equal to a value	select a.*, lnk.act_id, lnk.remaining, u.username as u_username from anagrafiche a left join lnk_ana-act lnk      on a.id = lnk.ana_id left join users u      on a.uid = u.id where lnk.act_id <> 57 and a.closed = '0' group by a.id limit 10 	0.00278540382302808
8168184	28369	user role permission query	select        p.name,r.name role from          user_has_role as ur join          role as r on            ur.role_id = r.id join          role_has_permission as rp on            r.id = rp.role_id left join     permission as p on            rp.permission_id = p.id where         ur.user_id = [user_id] union    select p.name, 'super_admin'     from permission     where exists (select * from user_has_role, role                where ur.user_id = [user_id] and role.role_id = user_has_role.role_id and                            role.name = 'super_admin') 	0.326209526719198
8168193	20008	mysql select to fetch rows from two tables with or without a foreign key	select * from tickets left join members on tickets.member_id = members.member_id 	0
8169471	41181	how to count number of occurences of a character in an oracle varchar value?	select length('123-345-566') - length(replace('123-345-566','-',null))  from dual; 	0
8170165	40872	fetching from table throught its own data	select t.sessionid, count(tc.action)     from yourtable t         left join yourtable tc             on t.sessionid = tc.sessionid                 and tc.action <> 'login'     where t.action = 'login'     group by t.sessionid; 	0.00029870285105635
8170266	26813	mysql order by two columns and order results again	select * from your_table order by   case     when content is null then 1     else 0   end   ,content,title 	0.0215808015719635
8170443	26644	sql query - grouping with multiple tables	select t1.timestamp, t2.state, t1.otherdata from table1 t1 inner join table2 t2      on t1.specialnumber = t2.specialnumber inner join (select max(time stamp) maxts, state             from table1 inner join table2             on table1.specialnumber = table2.specialnumber             group by state) t3     on t2.state = t3.state and t1.timestamp = t3.maxts 	0.240674237004879
8170663	3907	how to select only max(position) from database where the memberid must be unique	select * from the_table inner join (     select id, max(position) as max_pos     from the_table     group by id     ) as t on the_table.id = t.id and the_table.position = t.max_pos  order by the_table.id 	0.00158833583391971
8170873	4711	how can i select multiple columns from a subquery instead of multiple similar subqueries?	select *,      sum(case when s.date < %s and s.date >= %s then s.view_count else 0 end)/     sum(case when s.date < %s and s.date >= %s then s.download_count else 0 end)          as ratio,     sum(case when s.date < %s then s.view_count else 0 end)/     sum(case when s.date < %s then s.download_count else 0 end)          as global_ratio,     count(*)==0 as count from images_image as w left join images_stats as s      on s.image_id = w.id where w.category_id = %s group by w.id order by count, ratio, global_ratio 	0.00297239093347385
8172270	36318	sql outer join on top 1 query	select top(1) p.pk_id,                type,                start_date,                end_date  from   events e  where  fk_program_id = p.pk_id         and end_date >= getdate() 	0.703409946212652
8172349	21822	how to convert connect by level in teradata	select 'mb' as drug_source from dual   union   select 'sb' as drug_source from dual   union   select 'total' as drug_source from dual 	0.545805861993257
8173645	10730	mysql query to find specific word that might start with different letters?	select title from table_name where title rlike '[ac]at' 	6.14082958860615e-05
8174214	16109	minimum and max price between price range mysql query	select id  from prices  where id not in (   select id   from prices   where price_per_week not between 200 and 1000 ); 	0
8175076	38958	replace number in row with description when running select query	select t1.username, t2.region_desc     from table1 t1         inner join table2 t2             on t1.region = t2.region_id; 	0.0223743156502196
8176565	7250	combine mysql queries	select c.cntldate, c.sd_class, c.created, r.restored from ( select date(crtdtime) as cntldate, sd_class, count(crtdtime) as created from master group by cntldate, sd_class ) c inner join ( select date(rstdtime) as cntldate, sd_class, count(rstdtime) as restored from master group by cntldate, sd_class ) r on r.cntldate = c.cntldate and r.sd_class = c.sd_class where c.cntldate = '2011-11-16' and r.cntldate = '2011-11-16' 	0.163994619109213
8178727	10186	conversion of varchar to number	select cast(replace(yourvarcharcol, 'dollars', '') as int) from table 	0.0111273698237919
8179447	3777	while loop in order based on associative array php?	select social.*, accounts.username  from social  inner join accounts  where social.withid = accounts.id  and (social.id = ? or social.withid = ?)  and type = 'friend' order by  (social.id = $user_id and social.friendaccept = 0),  (social.withid = $user_id and social.friendaccept = 0), (social.id = $user_id and social.friendaccept = 1) 	0.0133435411922009
8180104	28241	sql query query	select author_id, count(distinct genre_id) as genres from books  group by author_id  having genres = n 	0.726655126114283
8181598	11294	fetch all rows data from second table using single join query	select      t2.* from      table1 t1  left join table2 t2 on t2.table1_id = t1.id where t1.id = <id>; 	0
8181920	40124	need month in the range 24th to 23rd	select   monthname(groupingdate) as smonth,   year(groupingdate) as iyear,   sum(amount) as totalsale,   facilityid from (   select     facilityid,     amount,     date_add(       approveddate1,       interval if(day(approveddate1) < 24, 0, 1) month     ) as groupingdate   from orders ) as o group by   year(groupingdate),   month(groupingdate),   monthname(groupingdate),   facilityid 	0.00224532057670558
8182476	36042	mysql: select distinct combinations accross two rows, not double counting	select dc, rc, min(other_column1), sum(other_column2) from (select dc, rc, other_column1, other_column2 from table where rc >= dc  union all  select rc, dc, other_column1, other_column2 from table where rc < dc) v group by dc, rc 	0.000445644524396584
8182601	18366	how to set a value to true or false by null check in tsql?	select case             when code is null then 'false'            else 'true'         end as result  from the_table 	0.0100236636748749
8183024	18882	is any record connected to anather	select filename  from files f where (      not exists (select * from a where file_id= f.id)       and not exists (select * from b where file_id = f.id) ) 	0.0464078501404312
8183321	9293	are there better ways to select which ids do not exist?	select inlineid from   (values (11111),                (22222),                (33333)) t(inlineid) except select id from   mytable 	0.00927572405995914
8183427	36753	selecting a column with reference to max(adddate) from date column	select    ai_account.amount as amountpaid,    ai_account.adddate as lastpaymentdate  from ai_account  where ai_account.id = (     select      id     from ai_account      where ai_account.trader_id = :traderid     order by ai_account.adddate desc     limit 1     ) 	0.00011682520295245
8184380	11957	merge two tables before make my query?	select p.id from posts p, meta m    where m.post_id=p.id      and m.meta_value='192.168.0.1'      and p.post_date < (now() - interval 10 minute); 	0.0475035441702249
8184775	38440	how to select values from xml in sql	select      drivename, drivespace from      openxml (@idoc, '/arrayofdrivedata/drivedata',3)     with (drivename varchar(10) 'drivename', drivespace varchar(20) 'drivespace) 	0.003882050063183
8185145	32547	how can an get count of the unique lengths of a string in database rows?	select length(lastname) from mytable group by length(lastname) 	0
8186280	4604	combing rows based on a count, adding values	select     email,     count(email) as frequency,     sum(cost) as totalcost from     emails group by     email 	0.000106079311243987
8188086	27878	mysql subquery to sum the many records of one item of a select?	select product.id, sum(sold.amount) from product left join sold on product.id = sold.product_id group by product.id 	0
8188882	2352	mysql, sort alphabetically with exception	select *    from country  order by case when id = 100 then 0 else 1 end, country_name 	0.656312133517213
8192828	36289	how can i set default value to 0 if there is null in result in mysql query	select coalesce((c_count_girls/c_count_boys), 0) as ratio from place where placeid=1; 	0.045792845014738
8193734	36154	sql procedure for years?	select datepart(year, getdate()) - n as years from   (values(0),               (1),               (2)) t(n) 	0.128218444702692
8194940	26477	mysql - select two tables with different limit	select id,viewed,manganame,     (select chapter     from om_chapter      where om_manga.manganame=om_chapter.manganame     order by chapter desc     limit 0,1) as chapter,     (select volume     from om_chapter      where om_manga.manganame=om_chapter.manganame     order by chapter desc     limit 0,1) as volume from om_manga order by viewed desc limit 0,10 	0.00436720305317178
8198258	37914	mysql select all entries between two dates regardless of year	select * from yourtable where (month(yourdate) = 10 and dayofmonth(yourdate) >= 30)    or (month(yourdate) = 11)    or (month(yourdate) = 12 and dayofmonth(yourdate) <= 11) 	0
8198532	28572	mysql: sorting rows from 2 (or more) tables by their columns	select id, name, time from (     select book_id id, book_name name, book_time time from books     union     select movie_id id, movie_name name, movie_time time from movies ) booksandmovies order by time desc; 	0
8198962	26805	taking the second last row with only one select in sql server?	select top 1 * from (select top 2 * from cinema order by cinemaid desc) x                      order by cinemaid 	0
8200886	30550	the best way to get a page of threads + stickies?	select      fields from      threads  where      forum_id = x      and      (         sticky = 1          or (other conditions if needed)     )  order by      sticky, something, somethingelse  limit 0, 25 	0.00112048056519916
8202861	25615	selecting distinct substring values	select    id from    (    select       id,       row_number() over (partition by substring(id, 1, 3) order by id) as rn    from mytable    ) oops where    rn = 1 	0.00586411833460461
8204392	3941	how do i do this date calculation?	select     case when expiry_date > sysdate() then        date_add(   expiry_date  , interval 6 month)     else        date_add(           date_sub(               sysdate(),                 interval               ( datediff( sysdate(), expiry_date )  % ( 6 * 30) )                month           )           ,            interval 6 month)     end    as expiry_date from ... 	0.636424874954573
8206180	16184	how can i select all rows in a table, and cross-check it with another table?	select p.id, p.plant from plants as p left join trees as t on (p.id = t.id) where t.type = 'hard' or t.type is null 	0
8209131	38061	how to combine different rows's text in a table in oracle	select qid, wmsys.wm_concat(answer) concat  from t group by qid; 	0.00398880042440232
8210672	33159	how to select a query for a selected day[2010-11-04] to present date using mysql	select *      from stu_details     where created_date >= '2010-10-04' order by created_date 	0.00363690371717924
8211358	26161	mysql: display all data from one table regardless info from second table	select * from master as m  left outer join digital_info as d on m.catalogue = d.catalogue  union select * from master as m  right outer join digital_info as d on m.catalogue = d.catalogue; 	0
8211500	26907	sql server query start, limit	select * from (      select id, row_number() over (order by id) as row           from products where myparam='shopkeeper' ) a where a.row > 0 and a.row <= 10 	0.497775188634436
8211957	35624	fetching multiple rows based on two comparisons in each row	select *  from table  where       (col1 = 'a' and col2 = '01/01/2001')      or      (col1 = 'b' and col2 = '02/05/2004') 	0
8212174	22773	mysql count result with zero value	select s2.date, count(s1.id) as count from (select distinct `date` from scores) s2    left join scores s1     on  s1.`date` = s2.`date`     and s1.`name` = 'vijay' group by 1 	0.0216183573901991
8214031	7244	how do i join two tables with on multiple values	select * from table tt1 inner join table tt2 on tt1.value1=tt2.value2 and tt1.value5=tt2.value6 	0.00440688692988587
8214902	28648	order database results by bayesian rating	select id,title,( avg(this_num_votes) * avg(this_rating) + this_num_votes * this_rating )      / ( avg(this_num_votes) + this_num_votes ) as br from posts left join ( select distinct post_id, (select meta_value from postmeta where postmeta.post_id = pm.post_id and meta_key ='this_num_votes') as this_num_votes, (select meta_value from postmeta where postmeta.post_id = pm.post_id and meta_key ='this_rating') as this_rating from postmeta pm ) as newmeta on posts.id = newmeta.post_id group by id,title,this_num_votes,this_rating order by br desc 	0.134398790099766
8217197	22722	return a single mysql results with multiple values from a row	select b.title, b.pages, group_concat(a.author)     from books b         natural join authors a     where b.title like '%$search%'     group by b.title, b.pages; 	0
8217708	9191	conversion to timestamp from two columns	select to_timestamp(substr(to_date(prgm_start_day_key,'yyyymmdd'),1,10)||' '|| cast(lpad(prgm_start_tm_key,6,0) as time),'yyyy-mm-dd hh24:mi:ss') from dev_am_2..am_tv_program_instance_dim; 	0.000334617306129979
8219904	39836	how to do a mysql query without creating temp tables?	select tr.id, tr.cxl, tci.cd from testci as tci  inner join testrecurring as tr     on tci.id = tr.id left outer join future_recurring as fr     on tr.id = fr.id where tci.x_origin='1'      and fr.id is null group by tr.id, tr.cxl, tci.cd order by tr.id desc 	0.247798777757082
8221278	22757	sql query from multiple columns with prepared statement	select * from contacts where firstname like ? or lastname like ? or email like ? 	0.240469665680354
8221307	11994	sql server getting first & last row that makes up aggregation	select x.*, ti.open, te.close from ( select   instrument,          min(bartimestamp) as timestampini,          max(bartimestamp) as timestampend,          max(high) as high,          min(low) as low,          sum(volume) as volume     from timebar group by instrument, datepart(year, bartimestamp), datepart(month, bartimestamp), datepart(day, bartimestamp), datepart(hour, bartimestamp) ) x inner join timebar ti on ti.instrument = x.instrument and ti.bartimestamp = x.timestampini inner join timebar te on te.instrument = x.instrument and te.bartimestamp = x.timestampend 	0.000257442385861022
8221500	30490	how to compare 10-digit unix date with dd/mm/yyyy date format in mysql?	select productid, productname   from products  where entry_date between unix_timestamp('2008-01-01') and unix_timestamp('2009-01-01') 	0.000104795461439788
8223912	39038	mysql unix-timestamp date format	select date_format(from_unixtime(1264105904),'%b %d, %y %l:%i %p pdt'); 	0.0848456771020534
8224234	1278	sql script to know where the data is located	select object_name(id) from syscomments where [text] like '%whatever%' 	0.555891036462236
8224683	26425	select from multiple tables but ordering by a datetime field	select t1.hourx, sum(t1.column1) from (   (     select count(*) as column1, date_format(dated, '%y:%m:%d %h') as hourx      from upd8r_linked_in_accts      where cast(dated as date) = '".$start_date."'     group by hourx    )    union all    (     select count(*) as column1, date_format(dated, '%y:%m:%d %h') as hourx      from upd8r_facebook_accts      where cast(dated as date) = '".$start_date."'     group by hourx   )    union all    (     select count(*) as column1, date_format(dated, '%y:%m:%d %h') as hourx     from upd8r_twitter_accts      where cast(dated as date) = '".$start_date."'     group by hourx   )  ) t1 group by t1.hourx 	0.000624817169008973
8224763	40536	fetch index information in postgresql 8.4	select t.relname as table_name,        ix.relname as index_name,        array_to_string(array_agg(col.attname), ',') as index_columns,        i.indisunique from pg_index i   join pg_class ix on ix.oid = i.indexrelid   join pg_class t on t.oid = i.indrelid   join (select ic.indexrelid,                 unnest(ic.indkey) as colnum         from pg_index ic) icols on icols.indexrelid = i.indexrelid   join pg_attribute col on col.attrelid = t.oid and col.attnum = icols.colnum where t.relname = 'tablename' group by t.relname, ix.relname, i.indisunique order by t.relname,          ix.relname 	0.0639606949859086
8224794	22489	how to search value range inside another range in sql	select * from products where min < $max and max > $min 	0.000162963721801511
8227972	40435	how do i return distinct rows when using join?	select a.street, b.id  from tablea a left join tableb b on a.city = b.city group by a.street, b.id order by a.street 	0.0390912427936267
8230286	39030	nested set, product count and category depth in one query	select parent.id,                    parent.lft,                    parent.rgt,                    (select count(parent2.id) from businesscategories as parent2 where parent.lft > parent2.lft and parent.rgt < parent2.rgt) as depth,                    count(b_c.business_id) as bcount                 from businesscategories as node,                 businesscategories as parent,                 businesses_categories as b_c,                 where node.lft between parent.lft and parent.rgt and node.id = b_c.category_id                 group by parent.id having depth > 0                 order by parent.lft 	0.00586015174210466
8231409	39978	mysql - summing counts of multiple joined tables	select  (select count(*) from table_1 = where member_id = m.member_id)  +  (select count(*) from table_2 = where member_id = m.member_id) as total from members m where m.member_id = 27 	0.0017833865707299
8233013	34202	mysql_fetch_array from two different rows	select     s.id,     s.category_id,     s.body,     c.title,     c.description from something as s join category as c on s.category_id = c.id where id = '42' limit 1 	0.000188187327163479
8233535	5476	mysql join getting a value or a null into a column	select field1, field2, ..., pl.* from orderdetails  inner join orders on orderid = detailorderid  ... left join pricelists pl pn pl.productitemid = productitems.productitemid .. 	0.00401168494207892
8233746	11936	concatenate with null values in sql	select column1 + coalesce(column2, '') as result     from yourtable 	0.0154484112532822
8235563	27911	how to find all the products with specific multi attribute values	select p.* from "products" as p inner join "custom_field_answers" as a1 on p."id" = a1."product_id" inner join "custom_field_answers" as a2 on p."id" = a1."product_id"  where a1."value" = 'bangle' and a2."number_value" < 50 	0
8236697	6635	how to select empty fields where null is set to "no" and default is set to "none"	select * from some_table where target_field = '' 	0.0105008819844203
8238358	36324	query two colums into one?	select name1 from thetable union distinct select name2 from thetable 	0.000991047897507041
8238869	21261	how can i get the most recent date using mysql	select namestore, idstore, name, iditem, max(date) as date, price from tablename group by namestore, idstore, name, iditem, price order by date desc, iditem asc 	0
8239474	14376	exporting mysql table data to csv (modify field first)	select date_format(dob, '%d.%m.%y') from mytable; 	0.000421630193000488
8241388	37922	in a sql statement with multiple selects, how do i only put the master id once?	select * from movies m left join videos v on v.movie_id = m.movie_id left join actors a on a.movie_id = m.movie_id ... where m.movie_id = ? 	6.46916859069528e-05
8242076	14615	mysql transpose (pivot) variation: move all combinations of columns into new rows	select item,class,'x','a' from `test_pivot` where x=1 and a=1 union select item,class,'x','b' from `test_pivot` where x=1 and b=1 union select item,class,'x','c' from `test_pivot` where x=1 and c=1 union select item,class,'y','a' from `test_pivot` where y=1 and a=1 union select item,class,'y','b' from `test_pivot` where y=1 and b=1 union select item,class,'y','c' from `test_pivot` where y=1 and c=1 union select item,class,'z','a' from `test_pivot` where z=1 and a=1 union select item,class,'z','b' from `test_pivot` where z=1 and b=1 union select item,class,'z','c' from `test_pivot` where z=1 and c=1 	0
8242643	14890	search in integer array in postgres	select * from table where 10 = any (values); 	0.131286250854447
8243162	8412	how to get the sum of values in the different field in mysql?	select sum(payment) as payment_sum from   payment where  customer_id = <your_id> 	0
8243853	3728	sql server 2005 copy multiple result sets	select 'a' union all select 'b' union all select 'c' 	0.157152802267223
8243919	40517	calculate percentage with subqueries	select     day,     return_rate_mr * 100 / return_count as perc_value,     ... any other columns ... from     ( ... your original query here ...) as myalias; 	0.114490417412997
8244750	17734	sql select column when theres more than one of the same name	select t1.name as distroname, t2.name as originname, t3.name as desktopname from alldistros t1 left join origin t2 on t1.name=t2.name left join desktop t3 on t2.name=t3.name left join beginnerdistributions t4 on t3.name=t4.name 	0
8245585	20056	sql: list of users that logged out 1 minute after they logged in	select * from yourtable where datediff(ss, login_date, logout_date) <= 60 	0
8245630	11937	mysql combine two date fields and then order by	select     [some info],     greatest( ticket_date, ticket_history_date ) as latest_date from     [tables and join] order by     latest_date 	0.00062447722435622
8247768	32539	sql count empty fields	select count(improve) + count(timeframe) + count(impact) + count(criteria) from data 	0.0763917464794341
8247876	6036	convert rows to columns order by another column in sql server	select testid,    max(case when actionid = 'a1' then elapsed else null end) as a1,    max(case when actionid = 'a2' then elapsed else null end) as a2,    max(case when actionid = 'a3' then elapsed else null end) as a3,    max(case when actionid = 'a4' then elapsed else null end) as a4 from results group by testid 	0.000184148651474316
8248042	1517	how to fetch the values in 1 row instead of multiple rows in sql	select itemid,         itemname,         imagesurface,         fti.imagepath as imagefront,         bti.imagepath as imageback  from   tableitem i         left join tableimages fti           on fti.fitemid = i.itemid              and fti.imagesurface = 'front'         left join tableimages bti           on bti.fitemid = i.itemid              and fti.imagesurface = 'back' 	0
8248420	961	how to select couple of records for editing in mysql database	select `versions`.`value` from `versions` where `versions`.`value` like '%organiz%'; 	0.00301453190211661
8250911	34269	query same field from two different tables mysql	select title from tablea as a left join tablec as c on tablea.id=tablec.id where 1 and tablec.private='0' and ( title like '".$keyword."%' or title like '%".$keyword."%'               or title like '%".$keyword."' or title = '".$keyword."' ) union select title from tableb as b left join tablec as c on tableb.id=tablec.id where 1 and tablec.private='0' and ( title like '".$keyword."%' or title like '%".$keyword."%'               or title like '%".$keyword."' or title = '".$keyword."' ) 	0
8252021	33665	how to display my detail in correct order using mysql query?	select customer.companyname, customer.contactname, group_concat(eventinfo.eventtitle )  from eventinfo, testbook, customer  where testbook.username=customer.username and testbook.eventid=eventinfo.eventid group by customer.companyname, customer.contactname 	0.103319319477025
8252784	21788	mysql - how do i to select data from a table, ordering by the difference between the values of two columns?	select * from mytable order by (columna - columnb) 	0
8254522	15871	mysql table with fixed number of rows?	select id, name, `time` from documents order by `time` desc limit 10 	0.000129817167513205
8255073	39771	mysql result set combine columns	select  orderid, customerid as userid, sum (customerpayment) as payment from orders union all select  orderid, producerid as userid, sum (producerpayment) as payment from orders 	0.00600963941731159
8255191	35819	trigger with current date query/where clause	select count (*) into num_check from umriss u where mdsys.sdo_contains (u.shape, :new.point) = 'true' and u.umr_datum = ( select max(d.;umr_datum) from umriss d ); 	0.0831765321917558
8255628	2543	(mysql) query for multi columns with multi-level tables?	select t.date,b.title,a.name from book b   innerjoin transaction t on t.bookid = b.id  innerjoin author a on b.authorid = a.id 	0.17387177468676
8257106	13570	divide the value of a column by another column	select total_percent / no_of_scren as 'result' from yourtablename 	0
8257579	27594	php / mysql multiple substrings?	select concat(substring(<column>, 1, 1), '.', substring(<column>, 2, 2), '.', substring(<column>, 4)) from <table> 	0.116157193029679
8257834	3102	querying a many to many table	select e.id as id_evenement, m.id as id_member,    from evenement e, member m except select id_evenement, id_member    from member_evenement; 	0.0252188261813206
8257964	12708	group items and return common part	select count(*) as cnt,        city,        street,        somefield from   yourtable group  by city,           street,           somefield 	0.000610459186132892
8259921	3401	combining 2 time series	select c_name, t_date, t_price,t_volume from $tblname where c_name='fz10' union select c_name, t_date, t_price,t_volume from $tblname where c_name='fh11' 	0.00914709075117844
8262018	31208	mysql sql: select (select... as variable) from	select     orders.orderid,     orders.quantity,     totals.total_in_order from orders join (     select orderid, sum(quantity) as total_in_order     from orders     group by orderid ) as totals on orders.orderid = totals.orderid 	0.0601188423164358
8262147	13656	composite decomposible unique key	select    cast(tablea.id as varchar) + '-' +    cast(tableb.id as varchar)  + '-' +    cast(tablec.id as varchar)  as compositekey,    tablea.foo 	0.0472611727153884
8262148	20262	format mysql timestamp to something meaningful	select date_format(your_col, '%a %d %b %y %k:%i:%s') from your_table 	0.0743765782630597
8262352	23720	use mysql to order us states alphabetically	select distinct state from zip order by cast(state as char) 	0.736540912493085
8267674	9838	how to get a year and day of the year by using sql server	select right(year(getdate()),2), datepart (dayofyear,getdate()) 	0
8269438	31618	how can i search a nvarchar field to see if there are any lower case characters in the value?	select * from yourtable where yourcol like '%[a-z]%' collate latin1_general_bin 	0.030220229080561
8270093	3613	how to reduce the number of queries in a normalized database?	select     [fields required] from     articles a     inner join         users u on a.author_id=u.user_id     inner join          tag_map tm on tm.article_id=a.article_id     inner join         tags t t.tag_id=tm.tag_id where     a.article_id='$id' 	0.00162497847295998
8270763	25423	mysql - how to order a joined table?	select     artist.name,     max(product.id) from     artist inner join     product on     product.artist_id = artist.id group by     artist.artist_id, artist.name order by     artist.last_name, artist.first_name; 	0.0147988965495751
8271711	15406	select one row with distinct value of one column	select * from (     select table1.*, dense_rank() over(partition by merchant_id order by start_date desc, id) r     from table1     where sysdate between start_date and end_date ) where r = 1 order by start_date desc 	0
8273405	16683	mysql group by regex?	select count(*) as total_count, substring(col1 from position('-' in col1)+1 for 3) as col1_zoomed from table1 group by col1_zoomed order by total_count desc 	0.64515863959351
8273969	18630	php data objects fetching a fields name from a table	select column_name from columns where table_name = 'desired_table' and table_schema = 'database_name' 	0.00013464188620332
8273987	26524	select unique rows based on single distinct column	select a.* from emails a inner join  (  select distinct email, min(id) as id from emails    group by email  ) as b on a.email = b.email  and a.id = b.id 	0
8275373	28883	select top 5 biggest values - oracle	select * from     (select additional_info from your_table      order by to_number(additional_info) desc) r where rownum <= 5 	0.00122807509487838
8276978	21579	putting one specific letter before all others in mysql	select * from optsubjectitems order by (yr=x) desc, subject desc; 	0
8278672	8017	file tree in oraclesql	select lpad(' ', (level-1)*2) || name from (   select id_f, name, parent from folders   union all   select null, name, parent from files   ) start with parent is null connect by parent = prior id_f 	0.245926951592252
8278950	10695	how to apply non standard sql column sort order?	select *  from persons order by     pack,     case type         when 'man' then 1         when 'vrouw' then 2         when 'kind' then 3     end,     date asc 	0.0709940470888181
8279419	18245	mysql. most booked type of a room	select       hotel.city hotelname,       room.type bookedtype,       count(*) numberofbookings    from       booking b          join hotel             on b.hotelno = hotel.hotelno          join room             on b.hotelno = room.hotelno            and b.roomno = room.roomno    group by       b.hotelno,       room.type    order by       count(*) desc 	0.00357571186451737
8279443	38374	mysql select query used to find postion	select x.user,         x.position,        x.number   from (select t.user,                t.number,                @rownum := @rownum + 1 as position           from table t           join (select @rownum := 0) r       order by t.number desc) x  where x.user = 'c' 	0.140910363471987
8279472	13159	priorities for each clause of a query	select * from zipcodes  z where zip like @zip or (city like @citystate+'%' and state like @citystate+'%' )  order by  case     when z.zip like @zip then 1     when city like @citystate+'%' and state like @citystate+'%' then 2     when state like @citystate+'%' then 3     else 4 end, z.zip, city, state 	0.00848187828979633
8280412	35542	sql select; concatenating strings, avoiding double commas where columns are null?	select suppname as "supplier name", ( case when street is null then '' else street || ', ' end ||  case when town is null then '' else town || ', ' end || case when county is null then '' else county || ', ' end ||  case when postcode is null then '' else postcode end ) as "supplier address" from suppliers 	0.022570876218738
8280607	38277	fastest query to see if it returns at least one row	select 1 from tbl where conds order by null limit 1; 	0.000663047694984791
8282313	8916	using join to parse out duplicate data	select c.name,c.email     from users c  left join email e on (c.email=e.email)    where (e.email is null) and (c.subscribed=1) 	0.100323408311716
8283013	27849	mysql - create single record out of similar rows, chose values of greatest length for most columns	select max(name),        place_code,        max(email),        max(phone),        max(address),        max(details),        max(estd),        max(others) from table_x group by substring(name,1,4),place_code 	0
8283541	21135	merging multiple rows into one row and multiple columns on mysql	select um.user_id    , fn.meta_data as first_name    , ln.meta_data as last_name    , e.meta_data as email from wp_usermeta as um left join wp_user_meta as fn on um.user_id = fn.user_id    and fn.meta_key = 'first_name' left join wp_user_meta as ln on um.user_id = ln.user_id    and ln.meta_key = 'last_name' left join wp_user_meta as e on um.user_id = e.user_id    and e.meta_key = 'email' 	0
8287431	25248	sql cannot search	select * from image where platename like '%wdd 666%' 	0.784455473472926
8288544	34200	subtraction in sql statement	select  firstname, lastname      from  presidents       where  endterm > date_add(beginterm, interval 4 year) 	0.716533837396098
8288611	20168	mysql datetime select in between dates	select * from events where not ((event_end_date < @start) or (event_start_date > @end)) 	0.00531543271261065
8288776	39381	ranking the user with points in users table	select count(*) + 1 as rank   from tbl  where point > (select point                   from tbl                  where id = 5) 	0.0038917618709568
8289850	1477	getting the average number of orders per day using mysql	select count(*) / <days> from mytable where datetime between <start> and <end> 	0
8289978	32576	mysql how to retrieve table name as a field	select timeslot.*,     case         when test.timeslot is not null then 'test'         when interview.timeslot is not null then 'interview'         when lesson.timeslot is not null then 'lesson'     end as activitytype from ... 	0.000215763952828899
8292199	24701	query several nextval from sequence in one satement	select your_sequence.nextval from (    select level     from dual     connect by level < 1000 ); 	0.00922416051826315
8292417	32406	get "null" records from the database without using "is null" condition..?	select coalesce(colname,0) from table where colname != coalesc(colname,0); 	0.000487836322338812
8294489	34255	mysql, using a field created with as in a concat	select concat( name, 'is a', new_job ) from(        select name,            case job           when 'br' then 'cleaner'           when 'pd' then 'teacher'           else job           end as new_job    from table ) sub 	0.173640853493222
8295021	20188	how to identify high-load sql in oracle, using oracle views?	select a.sql_id, a.ratio, a.executions from   (   select sql_id, buffer_gets / executions ratio, executions   from v$sql   where executions > 10   order by 2 desc ) a where rownum <= 10 	0.699274232111546
8295311	36663	get information from two tables	select m.manufactor, count(o.car_id) from models m left join orders o on m.id = o.car_id group by o.car_id 	0.000116884568219532
8296881	9337	return same row twice if both 'or' conditions are true	select   wp_ema_fights.fighter1 as competitor,          wp_ema_fights.fighter2 as opponent,          wp_ema_fights.winner as winner from     wp_ema_fights union all select   wp_ema_fights.fighter2 as competitor,          wp_ema_fights.fighter1 as opponent,          wp_ema_fights.winner as winner from     wp_ema_fights order by competitor 	0.000284945793803154
8298432	40499	return only records validated against a lookup table	select p.prod_id from products p   left join product_keywords pk     on p.prod_id = pk.prod_id   left join valid_keywords vk     on vk.keyword_id = pk.keyword_id group by p.prod_id   having count(vk.keyword_id) = count(pk.keyword_id); + | prod_id | + |       2 | |       4 | + 	0.000228061262044279
8298769	35955	mysql max subquery	select id from lotresults where lot_id = 180 order by value desc limit 1; 	0.483628757491855
8301690	5488	comparing two cross reference lists	select org_id from cult_xref inner join cat_xref using (org_id) where (cult_id,cat_id) = (2,6) 	0.148104943700402
8303516	15805	using results from one mysql query to insert into another query	select subject.stitle, eresource.etitle from subject,subjectmap,eresource  where subject.id = subjectmap.sid   and eresource.id = subjectmap.erid order by subject.stitle, eresource.etitle 	0.000515837711903964
8304056	72	how to do a join in mysql with a select?	select s.id, c.fname, c.lname from search s join email c on c.id=s.id where s.talentnum > 0 and s.sex='female' and c.sms_ok='1' 	0.223013246338077
8305920	26937	sql: how to sort / order query result in somewhat arbitrary manner?	select *, 1 as sort_pref from table where column like 'chair%' union select *, 2 as sort_pref from table where column like '%chair%' and column not like 'chair%' order by sort_pref, column 	0.584857837927601
8306532	33480	how to make a select query with and	select * from table where     (@dept = null or department = @dept)     and (@div = null or division  = @div)     and (@comp = null or company = @comp) 	0.359734948207027
8306690	13449	order date stored as varchar in mysql?	select columns from table order by str_to_date(varchardatecolumn, '%m/%d/%y %h:%i:%s') 	0.156822161849012
8307101	30474	multiplying a query value with multiple select from another table	select (a.price * b.factor_p * b.factor_q / b.factor_r) as num from tablea a inner join tableb b     on a.name = b.name     and to_char(a.time, 'dd-mon-yyyy') = to_char(b.date, 'dd-mon-yyyy') where a.name = 'a'   and time between '2011/01/12 09.30.00' and '2011/01/12 16.00.00' 	5.35482015072817e-05
8308252	26980	determine table referenced in a view in sql server	select   cols.* from   sys.sql_expression_dependencies objs   outer apply sys.dm_sql_referenced_entities ( object_schema_name(objs.referencing_id) + n'.' + object_name(objs.referencing_id), n'object' ) as cols where   objs.referencing_id = object_id('view_name_here') 	0.0597493718038827
8309236	40531	how to add check against data within a mysql query?	select s.songid, s.userid,     case when exists     (         select songid         from stable3         where songid = $songid     ) then 'voted'    else    (        'not voted'    )    end    as 'voted or not' from stable3 s where s.userid = $userid 	0.010376028908768
8309390	35285	joins based on conditions in multiple tables	select a.*, b.*  from a inner join b on a.b_id = b.b_id where a.flag is null and b.date < now() union select a.*, b.*  from a inner join b on a.b_id = b.b_id inner join c on a.c_id = c.c_id where a.flag is not null and c.date < now() 	0.0100106624380389
8309486	9931	returning all rows falling within a time period	select * from [farmerfields] where getdate() between season_start and season_end 	0.000187053491802454
8310213	18128	how do i specify multiple header rows when using sql to query an excel spreadsheet?	select * from [sheet1$a2:s100] 	0.239273599769263
8313684	24828	how to replace output of select statemnt in mysql?	select id       ,descr as `category`       ,case parent_id           when 164 then 'advertisemnt'          when 167 then 'modeling'          when 154 then 'finance'          else          'unknown partent_id'        end as `department`      ,updated as `updated`      ,updatedby as `by` from  category 	0.159033785333086
8314218	22150	sql search for values in a field with text datatype regardless of casing	select count(blogpostid) as blogpostcount   from blogposts   where stateid='1'   and blogid = '20'   and blogpostcontent like '%test%'  collate sql_latin1_general_cp1_ci_as 	0.00778511134207737
8314310	32727	convert month name to month number in sql server	select datepart(mm,'january 01 2011')  select datepart(mm,'march 01 2011')   select datepart(mm,'august 01 2011')  	0
8314435	8951	insert into create new table	select top 0 * into newtable from bigtable1     cross join bigtable2 	0.00460824956468732
8315510	32616	query to fetch counting field values	select     count(case when c1<>'0' then 1 end) as c1_count,     count(case when c2<>'0' then 1 end) as c2_count,     count(case when c15<>'0' then 1 end) as c15_count from t 	0.000760513695615435
8316424	5294	how to assign a value from a select statement into a variable?	select @categoryid = a_categoryid from dbo.categories... 	0.000125187423049228
8318669	31707	how to multiply a row?	select item  from data,generate_series(0,1000)  where generate_series<qty order by item; 	0.00505393240569937
8319954	6786	mutiple duplicates finding	select ticket_id, destination,  count(ticket_id) as num_times from table group by ticket_id, destination having ( count(*) > 2 ) 	0.0302267969225916
8320537	31792	sql request - multiple value	select t.userid from yourtable as t inner join yourtable as t2 on t.userid = t2.userid    and t.title = 'gender'    and t.content = 'male'    and t2.title = 'location'    and t2.content = 'ny' 	0.0857447609801593
8321611	36090	counts on single column for different conditions	select    sum(case experience           when 'positive' then 1           else 0        end) as countpositive    , sum(case experience             when 'negative' then 1             else 0          end) as countnegative    , sum(case experience             when 'neutral' then 1             else 0          end) as countneutral from interview where c_id = 10 	0.000680742136850146
8321632	40709	mysql: is null in joined tables	select m.* from elvanto_members as m where    not exists    (     select 1 from       elvanto_groups as g        inner join elvanto_groups_categories as gc on          gc.group_id = g.id     where      gc.category_id in ('1','2') and      g.id = m.group_id and      g.deleted = 0   ) 	0.0919260756693776
8324076	31836	facebook app count top users	select top 100    fb_user_id    sum(outstanding) as outstandingtotal from yourtable group by    fb_user_id order by desc    sum(outstanding) 	0.0582874636459382
8324395	750	choose month according to number of date he has been hired	select round(<yourdate>, 'month') hire_month from dual 	0
8325282	23408	mutiple tables and queries	select *  from profiles, follow where follow.friend ='$user'    and follow.user !='$user'    and profiles.user1 =follow.user    order by id desc limit 20 union select *  from profiles  where user1='$user' 	0.114406036620609
8325525	32658	sql - proper "where" clause for current month	select * from date_sargable where  year(value) = year (getdate())   and month(value) = month(getdate()) ; select * from date_sargable where datediff(month, value, getdate()) = 0 ; select * from date_sargable where datediff(month, 0, value) = datediff(month, 0, getdate()) ; select * from date_sargable where value >= dateadd(month, datediff(month, 0, getdate())    , 0)   and value <  dateadd(month, datediff(month, 0, getdate()) + 1, 0) ; 	0.0379679021830197
8325809	13073	how do we check whether a column has any letters or not	select * from table where regexp_like(field, '^\d+\d+$'); 	0.00263720890275284
8325884	40838	sql server 2008 - replacing codes with values in multiple columns	select     table_1.id,     v1.text,     v2.text,     v3.text from table_1 left join table_2 v1 on table_1.value_code_1 = v1.id left join table_2 v2 on table_1.value_code_2 = v2.id left join table_2 v3 on table_1.value_code_3 = v3.id; 	0.073941907469182
8326417	24610	order by in sql query	select distinct model, day_rate from vehicle   inner join rate on vehicle.vehicle_type = rate.vehicle_type   order by day_rate 	0.58919967589219
8327547	17714	how to find threads only posted by friends?	select social_posts.message, social_posts.post_stamp, user.username, user.id, user.default_picture from social_threads join social_posts on social_posts.thread_id = social_threads.id left join user on user.id = social_threads.user_id join friends on (user.id = friends.user_a and social_threads.user_id = friends.user_b or user.id = friends.user_b and social_threads.user_id = friends.user_a) and friends.request = 1 order by social_threads.id desc 	7.82899610976044e-05
8327622	18247	how to select data based on a max(key) without grouping	select subquery.datacolumn, subquery.pk1, subquery.pk2, subquery.a.pk3, subquery.pk4 from (select a.datacolumn, a.pk1, a.pk2, a.pk3, a.pk4        ,row_number() over (partition by a.pk1, a.pk2, a.pk4 order by a.pk3 desc) ranking       from a a inner join b b on a.pk1 = b.pk1 and a.pk2 = b.pk2 and a.pk3 = b.pk3                inner join c c on a.pk1 = c.pk1 and a.pk2 = c.pk2 and a.pk3 = c.pk3 and a.pk4 = c.pk4       group by a.pk1, a.pk2, a.pk4) subquery  where subquery.ranking = 1 	0.000583529592563886
8327890	156	mysql, need a query to retrieve multiple fields from tables in one row	select id, name address, group_concat(phone) as phones from empinfo join empcontact using (id) group by id; 	0
8328548	38050	limit results to distinct system name when multiple records returned 	select sd.projectname, sd.systemname, sd.status, h.history_id  from dbo.si_systemdetail as sd  inner join dbo.si_projects as p    on sd.projectname = p.projectname  inner join dbo.si_statushistory as h    on sd.systemname = h.systemname where (p.cancelled = 'n') and (p.platform like '%ibm%') and ('20110101' <= convert(varchar(8), h.effectivedate, 112)) and (convert(varchar(8), h.effectivedate, 112) <= '20111111') and history_id = (   select max(history_id)    from si_status_history ish    where ish.systemname = sd.systemname) order by h.history_id desc, sd.systemname, sd.contactsbcuid, sd.actuallivedate desc, sd.projectname, sd.systemtype, h.effectivedate 	0.0274931137508352
8329126	39643	mysql: return max of the last 5 digits from column	select max(substring(isrc, -5)) from digital_info where left(isrc) = "gbcqv"; 	0
8331170	12291	embed a count statement in a a select list	select * from gisadmin.mn_schools_public msp where msp.school_code in (     select tss.school_code     from central2.gisadmin.trpd_schdgrps_schools tss     group by tss.school_code     having count(*) > 1 ) 	0.0300471794187261
8332672	40807	sphinx search, compound key	select id, t1.articleid, t1.propertyid, value from t1 inner join new_sphinx_table nt on t1.articleid  = nt.articleid and t1.propertyid = nt.propertyid; 	0.784131112237516
8333705	16416	mysql distinct values query	select t1.a, t1.b, min(t1.c) as c from yourtable t1 join (     select a, min(b) as b     from yourtable     group by a ) t2 on t1.a = t2.a and t1.b = t2.b group by t1.a, t1.b 	0.0675939897454933
8334493	6196	get table names using select statament in mysql	select * from information_schema.tables 	0.00120992678287206
8338607	29433	sql group by count of counts	select [count of register], count(1) [grouped count] from (     select count( [id]) as [count of register],            tag as [tag]     from [members]     group by tag  ) mytable group by [count of register] 	0.038344594794216
8339251	2556	how to write a mysql join query	select u.uid, u.city, u.username, u.flag  from users u join groupmember g on u.uid = g.uid where u.city = 'tokyo'   and g.groupid = 16; 	0.758447811689649
8343167	33642	select most specific row in mysql with wildcards	select result     from abr     where a = @lookupa         and (b = @lookupb or b = '*')     order by b desc limit 1; 	0.00718010824615807
8343673	39639	postgres find zip codes near specific zip code	select … from atable where zip = @zip union all select … from atable where not exists (   select *   from atable   where zip = @zip )   and zip like concat(left(@zip, 3), '%') 	0.106990734779784
8344468	26496	filtering records in sql server using date	select distinct company, name, phonenumber,  from request where company like @company  and requestdate >= dateadd(month, -18, getdate()) 	0.0330212525575024
8346394	22529	sql: remove duplicates (slightly different)	select   unique_id,   worker_id,   type_id into #validactive from   #tbl where date is not null select   unique_id,   worker_id,   type_id into #nullactive from #tbl where date is null delete from #tbl where unique_id in ( select #nullactive.unique_id from #validactive join #nullactive on #validactive.worker_id = #nullactive.worker_id where (#validactive.worker_id = #nullactive.worker_id and #validactive.type_id = #nullactive.type_id) ) 	0.0422635545303913
8349761	20979	adding datediff results to a new column	select datefrom, dateto,         datediff(day, datefrom, dateto) as 'difference in days',        datediff(hour,datefrom, dateto) as 'difference in hours' from tablename 	0.0244448108673714
8349856	19526	duplicated records for a column	select a.*  from table as a  where col2 <> 1   and exists       ( select *         from table b         where b.col1 = a.col1            and b.col2 = 1       ) 	0.0017387898590265
8350095	34357	make a report from 3 different tables using max and count?	select concat(d.firstname,' ',d.lastname) as completename      , c.name                             as cabinetname        , dv.maxvisits                       as maxvisits from doctors as d   left join     ( select medic_id            , max(numvisits) as maxvisits       from         ( select medic_id                , cabinet_id                , count(*) as numvisits           from vizits as v           group by medic_id                  , cabinet_id         ) as grp       group by medic_id     ) as dv     on dv.medic_id = d.id_med   left join     ( select medic_id            , cabinet_id            , count(*) as numvisits       from vizits as v       group by medic_id              , cabinet_id     ) as mcv     on  mcv.medic_id = dv.medic_id     and mcv.numvisits = dv.maxvisits   left join cabinets as c       on c.id_cab = mcv.cabinet_id 	0.00103909312139067
8351558	3025	tsql: split one column into two based on value	select sum(case               when gender = 'm' then 1               else 0            end) as males    , sum(case             when gender = 'f' then 1             else 0          end) as females    , class    , result from student group by class, result 	0
8353117	19846	mysql join order by	select u.* from user_prefs u    join categories cat on u.category_id = cat.category_id where p.user_id = 10 order by cat.name 	0.591036792787159
8353357	82	how to set the query to get the result as below?	select t.meta_id, t.terms_id, t.meta_value, tt.metavalue as meta_value1 from wp_terms as t inner join wp_terms as tt on t.terms_id = tt.terms_id    and t.meta_key = 'phone'    and tt.meta_key = 'location' where t.terms_id='" . $establishment['term_id'] . "' 	0.00283764115189131
8354442	29188	using information_schema in a cross database query	select 'db1' as dbname, * from db1.sys.columns union all select 'db2' as dbname, * from db2.sys.columns 	0.717701708781588
8356003	2220	randomly select one of last three entries from database	select * from (   select * from `news` where `display` = `1` order by `published` desc limit 3 ) as temptable  order by rand() limit 1 	0
8359390	4226	distinct values ignoring column order	select min(id) id, a, b from (select id, a, b from duplicatestable where a <= b       union all       select id, b a, a b from duplicatestable where a > b) v group by a, b order by 1 	0.00806871457438088
8361851	14424	sql server 2000 - picking one row out of many based on cell value	select distinct employeeid, extension      from accessid          where left(cast(extension as nvarchar), 1)='5'  union select distinct employeeid, extension      from accessid          where left(cast(extension as nvarchar), 1)='3'              and not exist (                 select employeeid from accessid                      where left(cast(extension as nvarchar), 1)='5') union select distinct employeeid, extension      from accessid              where left(cast(extension as nvarchar), 1)='7'                  and not exist (                     select employeeid from accessid                          where left(cast(extension as nvarchar), 1)='3'                              or left(cast(extension as nvarchar), 1)='5'); 	0
8362515	17016	how to use a query's results as column names in a select statement	select domain into @colname from mytable limit 1; set @s = concat('select `',@colname,'` from mytable'); prepare stmt from @s; execute stmt; 	0.0270316443353889
8364817	15150	query does not shows a result if there is one row with sum() function	select distinctrow     tbl_depts.who,     tbl_depts.dept,     sum(tbl_payments.payment) as [paid],     (tbl_depts.dept - [paid]) as remaining from tbl_depts left join tbl_payments       on tbl_depts.[id] = tbl_payments.[dept_id] group by tbl_depts.who, tbl_depts.dept, (tbl_depts.dept - [paid]); 	0.497676997470221
8365899	1239	mysql query to pull only the latest record	select m1.* from messages m1 left join messages m2  on m1.receiverid = m2.receiverid and m1.timestamp < m2.timestamp where m2.id is null 	0
8366140	28507	how can i get mysql to return select join with count?	select d.prop_id, d.prop_title, a.acnt_id    , sum(case             when u.prop_id is not null then 1             else 0          end) as unitcount from #prop_details as d inner join #prop_account as a on d.prop_id = a.prop_id left join #prop_unit as u on d.prop_id = u.prop_id group by d.prop_id, d.prop_title, a.acnt_id 	0.0165284140909292
8368089	11987	how can you weight date freshness in a mysql search?	select *, (ln(ln(-1/(datediff(published_time, now())+1)) + 1) 	0.0259252246998349
8368391	19869	sql query for calculating net promoter score over time	select date, sum(answer-1) * 100 / count(answer) as nps from yourtable group by date 	0.437110988511467
8369527	36674	another select statement if the value is null	select * from `locations` where 1 = (case when value is null then 1 else 0 end)  union all  select * from `companies` where 1 = (case when value is not null then 1 else 0 end) 	0.00740065026234413
8369768	1371	sql create table	select count(logid) as userid, loguserid,max(logdatetime) as maxlogtm into dbo.statslogsummary   from statslog group by loguserid 	0.117254921685175
8370114	19023	referring to a column alias in a where clause	select    logcount, loguserid, maxlogtm,    datediff(day, maxlogtm, getdate()) as daysdiff from statslogsummary where ( datediff(day, maxlogtm, getdate()) > 120) 	0.770981361195438
8370198	37470	counting total rows, whilst simultaneously selecting a subset of these - in one mysql query?	select reference.id, reference.name, count(1) as complete_count from reference where status = 2    or status = 3 group by reference.id, reference.name order by reference.date limit 5 	0
8370736	22304	sql counting rows together	select item_id, count(id) from orders  group by item_id 	0.01687181458894
8371327	32967	how to get 3 parameters from 3 different tables in one query - sql	select u.name as username,        max(p.date) as latestpost,        (select count(f.usernamefollower) from followers where userid = u.userid) as followercount from user u inner join post p on (u.userid = p.userid) group by u.userid 	0
8371895	40526	finding the seconds difference between two dates in mysql	select unix_timestamp(now()) - unix_timestamp(upload_date) from is_meeting_files; 	0
8372312	27652	mysql query to combine these tables correctly	select * from tbl_properties left join tbl_units on propertyid=tbl_properties.id 	0.56131109198548
8373778	15111	query "group by" mulitple items	select gameid, `team name`, sum(total) as tot, group_concat(`type`) as types from your_table group by gameid, `team name` 	0.0862753156890884
8374067	27091	how can i use data from other columns in sql?	select calcvaluea + 3,   from (select a + b calcvaluea from yourtable); 	0.00131841147231789
8376121	19197	mysql - show questions not answered before	select      *  from      question  where      categoryid = x and      not exists (         select              '1'          from              answers          where              sessionid = y and              answers.questionid = question.questionid     ) 	0.0911469993403781
8376838	39269	select max amount rows	select * from table as t1 where (select count(*) from table as t2        where t1.rubriek = t2.rubriek and t2.adv_nr > t1.adv_nr) < 5 order by rubriek,adv_nr desc 	0.000939753982293072
8377422	30344	join table with select...group by	select p.productname,        sum(od.amount) from   tblproducts p inner join tblorderdetails od on (p.id = od.productid) group by p.productname 	0.408817100430488
8377467	21254	mysql round & select query	select case               when onsale = 0 then 0         else               round(100 - (onsale) / (wholesaleprice) * 100)        end        as discountis 	0.325204697325088
8377559	8350	trying to calculate days to next birthday	select  date_field, abs(if(right(curdate(),5) >= right(date_field,5), datediff(curdate(),concat(year(curdate()+ interval 1 year),right(date_field,6))) , datediff(concat(year(curdate()),right(date_field,6)),curdate()))) as days from table 	0
8378121	29705	outer join on junction table	select * from [web].[dbo].[tblmenus] full outer join [web].[dbo].[tblproductsrelmenus]  on [tblmenus].id  = [tblproductsrelmenus].menuid full outer join [web].[dbo].[tblproducts]  on [tblproductsrelmenus].productid = [tblproducts].productid 	0.540740744128253
8378122	14413	sql query & multiple results for one record	select prod.id, prod.name, group_concat( pic.pic_name ) from products as prod left outer join pictures as pic on prod.picture_id = pic.pic_id  group by prod.id, prod.name 	0.00703014727453135
8378356	27457	mysql: order by match	select    (keywords regexp '.*(word1).*')   +(keywords regexp '.*(word2).*')   +(keywords regexp '.*(word3).*') as number_of_matches   ,keywords   ,field1   ,field2 from test  where keywords regexp '.*(word1|word2|word3).*' order by number_of_matches desc  limit 20 offset 0 	0.167738746918072
8378463	17758	using sum with a nested select	select   m.menuname,   p.productname,   t.amount from [web].[dbo].[tblmenus] m   full join [web].[dbo].[tblproductsrelmenus] pm on m.id = pm.menuid   full join [web].[dbo].[tblproducts] p on pm.productid = p.productid   left join (     select productid, sum(amount) as amount     from [web].[dbo].[tblorderdetails]     group by productid   ) t on p.producid = t.productid 	0.596416171205862
8379662	31569	how to add a "select all" entry to a dropdownlist tied to sqldatasource?	select value, description from reference_table union select -1, 'select all' order by 2 	0.000170494456392172
8380298	2474	mysql inner join. pull data from one table with data from another	select long_url.destination      , long_url.geo   from long_url inner   join short_url     on long_url.short_id = short_url.short_id  where short_url.slug = :slug    and long_url.enabled = 1 	0
8382218	4002	condition within group_concat()	select  *,         (         select  group_concat(m.name order by m.id)         from    project_milestones pm         join    milestones m         on      m.id = pm.milestone_id         where   pm.project_id = p.id                 and pm.status_id = 9         ) milestone_9,         (         select  group_concat(m.name order by m.id)         from    project_milestones pm         join    milestones m         on      m.id = pm.milestone_id         where   pm.project_id = p.id                 and pm.status_id = 10         ) milestone_10 from    projects p join    locations l on      l.id = p.location_id 	0.594837817815015
8384879	18258	combine two mysql queries looking at separate tables to count side by side	select   q1.day,   (q2.total / q1.total)*100 as percentage from  ( ) as q1 inner join ( ) as q2 using day; 	0.00122715542851541
8384893	2940	finding a geography point within a range of another - sql server	select * from yourtable where sqrt  ( power((yourtable.lat - reflat) * cos(reflat/180) * 40000 / 360, 2)  + power((yourtable.long - reflong) * 40000 / 360, 2)) < radiusofinterest 	0.000430014580018627
8385366	3396	mysql get the column name from column value	select states.name,        city.name as cityname    from       city          join states            on city.stateabbrev = states.stateabbrev    where       city.name = 'new york' 	0
8385461	32075	group by where null entries exist [resolved]	select products_id,options_id,sum(qty) from   (select 1 as purchase_id,10 as products_id,100 as qty         union all         select 2,11,100         union all         select 3,10,300         union all         select 4,12,50) purchases        left join (select 1 as purchase_attributes_id,1 as purchase_id,5 as                          options_id                   union all                   select 2,3,5                   union all                   select 3,4,5) purchase_attributes using(purchase_id) group  by products_id,options_id 	0.0147056959460728
8386394	1139	sql sum without repetition	select  name, pbudget, peamount from    firm         inner join         (select   firm_idfirm, sum(budget) as pbudget, sum(eamount) as peamount         from      project                   inner join                   (select id, sum(amount) as eamount                   from expense                   group by project_idproject) e         on e.project_idproject = project.id         group by firm_idfirm) p on firm.id = p.firm_idfirm 	0.423431447259201
8386802	2976	retrieve check in time of employee using sql by grouping method	select empid, date, min(check_in_time) as expr1 from leave where empid = @empid group by empid, date 	0.00102167188020911
8387305	37630	select table with column named "index"	select id, [index] from item 	0.0466807091500203
8392436	24080	how can i use count() to return a single record with totals from multiple tables (union)?	select sum(tot) as total from ( select count( np.id ) as tot from new_people np left join institute.users_roles ur on np.institute_uid = ur.uid left join roster r on np.id = r.people_id where np.company_id =55923 and ur.rid =8 and np.active =1 and r.roster_id is null   union all select count( people_id ) from roster where lu =1 and status <>  'complete' and company_id =55923) as t 	9.56548612794201e-05
8393222	27527	mysql: performance querying multiple columns with a single row	select day_name, group_concat ( cat_name ) as categories  from days as d left join days_categories as dnc on d.day_id = dnc.day_id  left join categories as c on c.cat_id = dnc.cat_id  group by ( dnc.day_id) 	0.0124568373926764
8401018	1198	list joint table records	select * from customer c, account a, branch b where c.cus_id in (         select a2.cus_id         from account a2, branch b2         where a2.bra_code = b2.bra_code         group by a2.cus_id         having count(distinct(b2.bra_code)) > 1     )     and c.cus_id = a.cus_id     and a.bra_code = b.bra_code 	0.00174449258258014
8401191	19463	mysql query output	select  categories.id ,  categories.title, count(*) as total from tutorial_categories as categories left join tutorials on tutorials.category = categories.id group by categories.id 	0.599782628048693
8402086	12058	query for current_timestamp between start- and end-time (w/o date!) oracle pl/sql	select * from tab1  where (current_timestamp - trunc(current_date)) between starttime and endtime 	0.0166258592325745
8402160	38439	postgresql sql statement: can't get the desired latest/recent comments, need to display the distinct posts.title with the latest comments	select p.title, q.latestcommentdate      from (select c.post_id, max(c.created_at) as latestcommentdate                from comment c                group by c.post_id) q          inner join posts p              on q.post_id = p.id; 	0.000132841864465497
8402244	38430	join on varchar column with subquery	select a.idmodel, a.modelname, price, sparepartdescription from modmodel a left join (     select m.idmodel, m.modelname, sp.price, sp.sparepartdescription         , row_number() over (partition by m.idmodel, m.modelname order by sp.price desc) as r     from   modmodel as m      inner join tabsparepart as sp          on m.modelname = left(sp.sparepartdescription, charindex('/', sp.sparepartdescription) - 1)     where  (charindex('/', sp.sparepartdescription) > 0)          and  (sp.fisparepartcategory = 6) ) b     on a.idmodel = b.idmodel     and b.r = 1 order by modelname, sparepartdescription 	0.390512864926894
8403092	10487	sql query finding best categories match	select i1.item_id,i2.item_id,count(1) from items i1 join categorizations c1 on c1.item_id=i1.item_id join categorizations c2 on c2.category_id=c1.category_id join items i2 on c2.item_id=i2.item_id where i1.item_id <> i2.item_id group by i1.item_id,i2.item_id order by count(1) 	0.0162936114979578
8403759	18759	mysql only do not select duplicated values	select min(id), email from some_table group by email 	0.00588998130761083
8407514	39445	mysql counts and averages with group by	select area, count(table2.table1_id) / count(table1.id) from table1 left join table2 on table1.id = table2.table1_id group by area 	0.0377919936427234
8409055	14433	how to return results for a query using pivot or something similar	select   receiver.country    as r_country,   sender.country      as s_country,   data.sender         as s_name,   data.receiver       as r_name,   data.msg            as msg,   data.date           as date from   tableb              as data left join   tablea              as sender     on sender.employeename = data.sender left join   tablea              as receiver     on receiver.employeename = data.receiver 	0.541920417942215
8409300	40099	mysql query to get the top 50 names appearing the most in the last 7 days	select count(id), name from tablename where date_sub(now(), interval 7 day) < create_time  group by name order by count(id) desc limit 50; 	0
8411116	4278	mysql display all records and count related records	select   s.*,   count(a.assignment_pk) as numassignments from   subject s    left outer join assignments a on     s.subject_pk = a.subject_fk and     a.teacher_fk = $sessionvar group by    s.* order by   s.subject_name asc 	0
8412369	28971	including limit to select top n rows within a group by clause	select b.id, a.receiver as z, a.sender as contact, a.type, a.time from table1 a  join table2 b on a.receiver = b.contact  where a.type = 'a'    and a.time < b.date 	0.000715921468022429
8413223	34024	how to get a value with leading zero's	select right('000' + max(id),2) from table1 	0.00117732859658694
8414215	21406	finding latest month and year in a table for different records	select t1.name, t1.subject, max(month) as latest_month_attended, t2.year as latest_year_attended from tab t1 join (     select name, subject, max(year) as year     from tab     group by name, subject ) t2 on t1.name = t2.name and t1.subject = t2.subject and t1.year = t2.year group by t1.name, t1.subject, t2.year 	0
8419144	13992	"select top 10, then join tables", instead of "select top 10 from joined tables"	select * from     (select top 10 * from your_table      order by your_condition) p inner join second_table t     on p.field = t.field 	0
8420453	16409	order results based on join conditions order	select coalesce(a1.website, a2.website) as web1,         coalesce(p1.website, p2.website) as web2 from books b left outer join authors a1 on a1.id=b.author1  left outer join authors a2 on a2.id=b.author2 left outer join publishers p1 on p1.id=b.publisher1  left outer join publishers p2 on p2.id=b.publisher2 where b.id ='12345' 	0.0282022549089863
8420958	28672	how to get the arithmetic mean of various dates of mysql from monday to sunday	select dayofweek(log_date), avg(log_hours) from log  where log_date >= date('2011-01-01') and log_date <= date('2011-10-31') group by dayofweek(log_date) 	0
8421224	36348	get database schema with one query?	select table_name, column_name     from information_schema.columns     where table_schema = 'yourdbname'     order by table_name, ordinal_position 	0.0185096589453567
8422934	12651	joined results as column names	select   sum(if(t2.code = 7, `7`, null)) as sum7,   avg(if(t2.code=8, `8`, null)) as avg8 from t1 join t2   on t1.id = t2.rel; 	0.00241881271651599
8423403	4128	get field name in sql query with distinct and union	select distinct(uniq) from (     select (sex + ' 1') as uniq from type4     union     select (fason + ' 2') as uniq from type4     union     select (color + ' 3') as uniq from type4     union     select (size + ' 4') as uniq from type4 ) as temp 	0.0119168098827075
8423623	16373	combine my results into a single flat table	select date,sum(apples) as apples,sum(oranges) as oranges from ( select a.date as thedate, count(a.id) as apples,0 as oranges  from dbo.apples as a group by a.date  union all select o.date, 0 as apples, count(o.id) as oranges  from dbo.oranges as o   group by o.date  ) xx group by thedate 	0.00357780880372164
8424431	37609	what are the differences between these query join types and are there any caveats?	select field1, field2 from table1 inner join table2 on (table1.id = table2.id) 	0.0159495068274047
8425578	10886	mysql query count output	select t.id, t.tilte, t.author, t.content, count(com.id) as comments from tutorials as t    join tutotials_categories as cat       on t.category = cat.id    join tutorials_comments as com       on com.tutorial_id = t.id where cat.title like'%category title'    and t.status = 1 group by com.id order by t.id asc 	0.45282555000209
8426696	34758	how do i print newline in sqlite3	select ''; 	0.485588111446961
8427198	30316	get last conversation row from mysql database table	select   *  from   user_chats uc  where  not exists (     select      1     from       user_chats uc2     where       uc2.created > uc.created and       (        (uc.sender_id = uc2.sender_id and uc.reciever_id = uc2.reciever_id) or          (uc.sender_id = uc2.reciever_id and uc.reciever_id = uc2.sender_id)      )   ) 	0
8427435	16967	order by is a case with ascending and decending orders	select distinct order_detail.*, -(1)*cast(order_detail.date as unsigned) as lorderdate, from order_detail order by case when type  = 1 then lorderdate when type = 2 then order_detail.date when type = 3 then order_detail.quantity end, case when type = 1 then order_detail.quantity when type = 2 then order_detail.quantity when type = 3 then lorderdate end, case when type = 1 then order_detail.amount when type = 2 then order_detail.amount when type = 3 then order_detail.amount end; 	0.125835910088081
8430244	22509	search mysql two date fields containing single date	select * from table where '2011-12-08' between date(start_date) and date(end_date) 	0.000326137797864583
8430269	26263	sql: nest sum with mn	select sum(lowest_price) from (select min(r1.price) as lowest_price  from rounds r1 inner join rounds r2 on r1.market = r2.market                     and r1.round = r2.round                      and r1.name = r2.name where r1.round ='1'  group by r1.market) innerselect 	0.759654844013017
8430405	7905	mysql multiple collation	select translation_text from translation where language_id = 42 order by translation_text collate latin1_german2_ci 	0.712881237218175
8431932	25951	mysql subquery for values in order by field	select song_id, count(id), max(score) from gameplay group by song_id order count(id) desc 	0.0766388044377819
8433465	30955	returning nearest date to date in a different table (oracle)	select *   from (select d.customer_id, d.doc_id, d.doc_start, d.doc_end, e.event_id,                 row_number() over(partition by d.doc_id                                    order by abs(d.doc_start - e.event_start)) rn            from doc d            join event e on d.customer_id = e.customer_id )  where rn = 1 	0.0007608057712425
8433931	34191	counting occurence of each distinct element in a table (sql,firebird)	select key, count(*) from your_table group by key 	0
8434030	29334	how to correctly set mysql timezone	select @@global.time_zone, @@session.time_zone; 	0.713613998964338
8434502	1773	unique results from database?	select distinct badge_number from your_table where category = 1 	0.00381051193071479
8434909	10363	mysql query -- choosing highest rank/ordered subject in table (join)	select i.img_name, i.ordered, a.user_name, c.keyword, c.cat_id from images as i join artists as a using (user_id)  join img_cat_table as im using ( img_id ) join catkeys as c using (cat_id) join ( select user_id, min(img_rank) img_rank from images as i  join artists as a on i.user_id = a.user_id join img_cat_table as im on im.img_id = i.img_id join catkeys as c on c.cat_id = i.cat_id where ( cat_id = 3) ) x on x.user_id = a.user_id and x.img_rank = img_rank where c.cat_id = 3 	0.0137967009352623
8435107	27284	mysql "where not in" using two columns	select * from completedtasks where (userid, taskid) not in       ( select userid, taskid         from plannedtasks       ) 	0.0684044779031646
8435502	9418	adding in derived data to an sql view	select guid, 'y' as is_clinician from tablea union all select guid, 'n'  from tableb 	0.276646729166172
8436155	19871	sql for mysql: how to select only data if value in one column exist in all categories from another column	select sample  from my_table  group by sample having count(distinct category) >= (select count(distinct category) from my_table); 	0
8437323	26592	sqllite query for getting data between 2 dates not working	select * from trip_mark where file_type = 2  and create_time between '2011-11-08 00:00:00' and '2011-11-10 00:00:00' 	0.0700696455268971
8437346	31789	sql query for showing total votes per user in so-like system	select user.id, user.name, count(vote.id) as votes from user  left join question on user.id = question.user_id left join vote on vote.question_id = question.id group by user.id, user.name order by 3 desc 	0.00127407315949618
8437629	38977	how to convert row data into different columns in sql server?	select t1.*, t2.counter as [size for 050], t3.counter as [size for 055] from table t1     left outer join table t2 on t2.key = t1.key and sizedescription like '050%'     left outer join table t3 on t3.key = t1.key and sizedescription like '055%' 	0
8437988	988	filter results by timestamp for the past 24 hours	select hour(landtime) as hour, count(*) as total from ord_log where landtime > (current_timestamp - interval 1 day) group by hour(landtime) order by hour(landtime) 	0
8438362	29080	removing special character sql	select regexp_replace(some_column, '[^0-9]*', '') as clean_value from your_table 	0.60233597340971
8443422	33269	how to find in all the tables containing columns having particular values?	select 'table1' from table1 where id = 100   union   select 'table2' from table2 where id = 100   union   ... 	0
8443813	1000	mysql dynamically selecting fields within join with where clause?	select * from schools,      users left outer join campuses          on users.campus_id != 0          and users.campus_id = campuses.id where users.school_id = schools.id 	0.37088994036219
8443878	35801	how to select a sql table's column value by giving column index?	select a, b, c, d, e, ...,        case ?            when 1 then a            when 2 then b            when 3 then c            when 4 then d            when 5 then e            ...        end as parameterised_column from ... 	0.0074981052201756
8444570	11875	if statement in mysql select query	select if(jq.course_id=0, 'some result if true', 'some result if false'), other_columns from ... where ... 	0.616203357117992
8445435	6403	get the min. value of the many rows in query	select min(min) from (   (select year(from_unixtime(min(add_date))) as min from table1)    union    (select year(from_unixtime(min(add_date))) as min from table2)    union    (select year(from_unixtime(min(add_date))) as min from table3) ) as t 	0
8445936	36011	t-sql to find rows with given number of digits	select *  from table where column1 like '%' + replicate('[0-9]',10) + '%' 	0
8446151	24067	mysql sort output by alphabet but get asc?	select userid, username from  (   select userid,username from table1 order by userid desc limit 15 ) as last_15 order by username; 	0.0228546921739927
8446671	26665	sql union query to group by a field and project into flattened result set	select word, max(translation1006), max(translation1007) from    (select             words.word,        translation1006 =         case region         when 1006 then trans         else null     end,       translation1007 =     case region         when 1007 then trans         else null     end     from        words) as detail group by word 	0.0101612201018628
8446839	26862	select distinct name with random id	select name, min(id)     from yourtable     group by name 	0.00194257520546532
8447737	36599	how i can search in many tables?	select name as findvalue, 'cars' as tablename from cars  where cars.name = "$search" union all select name as findvalue, 'people' as tablename from people where people.name = "$search" union all select city as findvalue, 'cities' as tablename from cities  where cities .name = "$search" 	0.134488930553285
8449074	29009	mysql order on 2 columns	select t.name, t.combineddate     from (select name, begin_date as combineddate               from yourtable           union all           select name, end_date as combineddate               from yourtable) t     order by t.combineddate 	0.00731297716302347
8449683	10917	mysql: get result greater than a number if it exists, but below if it doesn't?	select * from (       (         select *         from mytable         where myvalue >= 'number'         order by myvalue asc         limit 1       )       union        (         select *         from mytable         where myvalue <= 'number'         order by myvalue desc         limit 1       )     ) as temp order by myvalue desc  limit 1 	0.00310535565401605
8450256	30571	ignoring tables with no match	select table1.username, table2.age, table3.something_else from table1 left join table2 on (table2.id = table1.id) left join table3 on (table3.id = table1.id) where (table1.id = 37) 	0.03345474372958
8452966	21177	given 2 linestrings in postgis that touch, how to join them together?	select st_union(the_geom) from mytable; 	0.00196819117098495
8454533	25616	sql operation date query to find date between the to date	select distinct room_no   from tbl_roombook rb   where hotel_id = '$h_id'      and not exists       (select * from tbl_roombook        where hotel_id = rb.hotel_id            and room_no = rb.room_no            and start_date <= $date2            and end_date >= $date1) 	0.000534494775660873
8456639	30521	get list of table names in different schema of an oracle database	select table_name  from all_tables  where owner='other-schema' 	0
8456960	28968	how to match csv value in column	select * from products where find_in_set(2,subcatid) 	0.00119194434208539
8458132	40636	sql - get count of users with average age in range	select count(*) as sitecount from (       select avg(datediff(year, u.birthdate, uv.visit_date)) as avgage       from users as u         inner join user_visits as uv          on u.id = uv.user_id       group by uv.site_id         ) as t where avgage >= 40 and       avgage < 50 	0
8463346	35066	how to have a column count the number of times a bit field is zero and another column counting the number of time it is one?	select     part_id,     count(case when construction = 1 then 1 end) over () as countconstructionis1,     count(case when destruction = 1 then 1 end) over () as countdestructionis1 from    [dbo].[partswork] where     experiment_id = @experiment_id     and     partition_id = @partition_id 	0
8463958	17871	sql count and join from multiple tables	select p.id, p.text, count(v.product_id) as votes from product pro left join popular pop   on pro.id = pop.product_id left join vote v      on v.product_id = pro.id group by p.id, pro.text order by votes desc 	0.0235847185539669
8465912	16228	expressengine : custom query - grouping entries daily	select ect.year, ect.month, ect.day, count(ect.entry_id) as posts from exp_channel_titles as ect inner join exp_category_posts ecp   on ecp.entry_id=ect.entry_id inner join exp_categories ec   on ecp.cat_id=ec.cat_id where ect.status = 'open'    and ec.cat_name = "computer" group by ect.year, ect.month, ect.day order by ect.entry_date desc; 	0.00540874606772106
8466528	23440	how to get an id for the dates	select id, dates from table1 where dates < dateadd(month, -6, getdate()) 	0.000133469673494956
8467997	35128	order sql query records by frequency	select   `column`,          count(`column`) as `count` from     `table` group by `column` order by `count` desc 	0.0212024065498882
8468104	14113	mysql select query based on month span	select ... from mytable where somedatefield between makedate(year(now()),1) and now() 	0.000242256457836213
8468334	36471	find all stored procedures with particular starting name	select o.name from sysobjects as o inner join sysprocedures as p on o.id = p.id where o.name like "abc%" 	0.00018397535428758
8471263	15636	distinct users information and limited by records count query	select * from(     select user_id,            purchased_items_id,          row_number() over (partition by user_id order by dbms_random.value) as rnk     from            user_id join shopping using(user_id)      order by rnk ) where rownum <= 8000 	0.000561888540152722
8472211	17235	mysql denormalized table lookup	select b.name,     aa.displayname as vara,     ab.displayname as varb,     ac.displayname as varc,     ad.displayname as vard from tableb as b join tablea as aa on b.vara = aa.id join tablea as ab on b.varb = ab.id join tablea as ac on b.varc = ac.id join tablea as ad on b.vard = ad.id; 	0.346760727973959
8473302	9157	ping a table in the database with java	select count(*) from your_table 	0.120793701097269
8474341	33695	find ids where values are only in array	select id from table where value in ('green', 'orange', 'black')       and id not in (           select id           from table           where value not in ('green', 'orange', 'black')) 	0
8474797	2900	sql select from two tables	select itemid from tbl_spec where specid=5 or specid=7 group by itemid having count(distinct specid)=2 	0.0033071643733115
8477040	3725	highest salary in each department	select deptid, max(salary) from empdetails group by deptid 	0
8477420	16993	parent child query without using subquery	select a.id,a.name,max(b.date) from tablea a join tableb b on b.aid = a.id group by a.id,a.name 	0.113885964476403
8478298	18116	custom report on user data - sql server	select top 1   username,  count(username) as total from   tbluserlogins where   logintime between @datefrom and @dateto group by  username order by  total desc 	0.255572667942839
8480084	37472	mysql search with relations	select     u.firstname,     u.lastname,     d.name as domainname,     m.name as mandatename,     mc.name as mandatecatname from     user u     join user_rel_domain urd on urd.user_id = u.id and urd.value > 0     join domain d on d.id = urd.domain_id     join user_rel_mandate urm on urm.user_id = u.id and urm.value > 0     join mandate m on m.id = urm.mandate_id     join mandate_cat mc on mc.id = m.cat_id where     u.firstname = @searchterm     or u.lastname = @searchterm     or d.name = @searchterm     or m.name = @searchterm     or mc.name = @searchterm 	0.566525971442407
8480644	16575	mysql query using info from seperate tables	select count(*)     from history h     where h.ev_date between @start_date and @end_date         and ev_code = 1         and exists(select null                        from details d                        where h.mc_id = d.mc_id                            and d.lo_id = @locationid); 	0.00312741614621336
8480688	7746	one result from join between 2 tables?	select users.name, list(preferences.preference_description, ' ') as all_preferences from users join nodepreferences on users.fk_node_preferences = preferences.id where preferences.preference_description like '%abc%' group by users.name 	0.000300583728359399
8481564	13475	deriving dates from only day(1,2,3..31), based on current date	select dateadd(day,invoicingactivitystartday-1,                 dateadd(month,datediff(month,0,getdate())-1,0))        as [invoicingactivitystartdate]        ,case invoicingactivitystartday       when 1 then dateadd(ms,-3,                      dateadd(month,datediff(month,0,getdate()),0))       else dateadd(ms,-3,             dateadd(day,invoicingactivityendday,                     dateadd(month,datediff(month,0,getdate()),0)))       end as [invoicingactivityenddate]  from t 	0
8483470	25667	sql server: select x amount of character from value	select left(col_name,10) from your_table 	4.92849142921256e-05
8483622	6910	sql select multiple with sum	select *     ,(         select sum(shipment_cost)         from trackingnumbers         where trackingnumbers.orderid = orders.orderid     ) as shipping_cost from orders where orders.orderstatus = 'shipped'     and orders.shipdate > (getdate()-6)     and orders.paymentamount = orders.total_payment_received 	0.167508373384251
8484389	8442	sql stored procedure combining data from two rows	select top(1) studentname,   studentpercentage,   (your ranking selection code here as a subquery where studentid = @studentid) as rank from mytable order by studentpercentage desc 	0.00170705754646667
8486378	4582	select one row per id	select    ... from     (select        *,        row_number() over (partition by column1 order by (select 1)) as rn     from        mytable     ) foo where    rn = 1 	0
8486688	33703	merge record values into a record that contains multiple values with comma separated	select p1.product_id,        substring(           ( select ',' + engine_id               from productengine p2               where p2.product_id = p1.product_id               for xml path('') ), 2, 4000)        as engine_id       from products p1; 	0
8488764	21447	get result if end_date is 1 month before current month	select * from sales where date_format(date_end, '%y%m') = date_format(now() - interval 1 month, '%y%m') 	0
8490154	10394	sql server 2005 query columns to rows with a twist	select          main.code,         left(main.names,len(main.names)-1) as names     from         (         select distinct t2.code,          (          select              rtrim(t1.name) + ', ' as [text()]          from                test t1          where             t1.code = t2.code          order by              t1.code          for xml path ('')         ) [names]         from test t2         ) [main] 	0.028287822069563
8492282	31432	sql query, display people with most properties	select      count(p.propertyno) as numproperties,      o.fcname,      o.lname, o.telno from      property p,      owner o  where      o.ownerno = p.ownerno  group by      o.ownerno order by     numproperties desc limit 1 	0.00234777233179889
8492606	11098	sql select column names where the column is a key	select * from information_schema.table_constraints tc     join information_schema.key_column_usage kcu         on tc.table_name = kcu.table_name             and tc.table_schema = kcu.table_schema             and tc.table_catalog = kcu.table_catalog             and tc.constraint_name = kcu.constraint_name where tc.table_name = 'table_name' 	0.000567519209603605
8492726	28837	sql datetime convert to time string	select distinct datename(hour, rundate) + ':' + datename(minute, rundate) as output... 	0.0283871375900496
8492989	7760	query for articles in drupal 7	select     node.title, body.body_value, from_unixtime(node.created) as created, file_managed.uri as image from         node inner join                   field_data_body as body on node.nid = body.entity_id inner join                   file_usage on file_usage.id = node.nid inner join                   file_managed on file_usage.fid = file_managed.fid where     (node.type = 'article') 	0.0321022732973275
8493170	18781	sql: basics on joins and other tables	select b.id,c.name,c.countrycode  from base as b  inner join country_specifics as c on b.id=c.id where b.id=1 and c.countrycode='us'; select id featureid from features where productid = 1 	0.166994865588122
8493528	37599	select a product from filters	select p.*, s.id as setting from products p inner join product_setting p2 on (p.id = p2.product_id) inner join settings s on (s.id = p2.setting_id) where s.id in (1,2) group by p.id having count(*)=2; 	0.0163980231303809
8494363	1308	combining two queries (ms sql)	select a.clientid,sum(b.time)   from     table a as a   left join      table b as b on (a.productid = b.productid)   where     datepart(month, b.date_added) = 8   group by     a.clientid 	0.17506057238861
8494534	26494	i need to do an sql with if then else to join tables if the field is not null?	select      adminid,     tblapartments.nameno,      tblgarages.garageid,      tblclients.name  from      tbladmin inner join tblclients on tbladmin.clientid = tblclients.clientid     left outer join tblgarages on tbladmin.garageid = tblgarages.garageid     left outer join tblapartments on tbladmin.apartmentid = tblapartments.apartmentid 	0.558612971770933
8494810	18629	how to count the total post made by each user	select    count(post_id) as totalpost,    m.member_id from    member as m  left join     post on post.member_id=m.member_id  group by m.member_id; 	0
8495009	35463	querying for who worked on an item first and second	select  t1.reviewedby firstreviewer, t2.reviewedby secondreviewer from table t1 left outer join table t2 on t1.item_id = t2.item_id and t2.reviewdatetime > t1.reviewdatetime 	0
8495376	30365	how can i write just one query whose only difference is in the where clause, to capture logic of a boolean test?	select     id, flavor, color from     menu    where          (flag = 'y' and flavor in (1,2,3,4,5))         or(nvl(flag,'n') = 'n' and flavor in (2,4,6)) ; 	0.00708674520490095
8496646	17553	sql server datetime indication for today and yesterday	select distinct  datename(hour, rundatetime) + ':' +  datename(mi, rundatetime) as  distinctdate, case when datediff(day, rundatetime, getdate()) = 0 then 'y' else 'n' end istoday, case when datediff(day, rundatetime, getdate()) = 1 then 'y' else 'n' end isyesterday from testdates 	0.0399315546894952
8498116	35825	top 10 occuring values in a table	select top 10 querystring, count(querystring) as popularity from  (     select distinct ipaddress, querystring     from      (         select [datetime], ipaddress, querystring         from tblwebstats         where querystring like '%newsid=%' and [datetime] > dateadd(day, -7, getdate())     ) as datefilter ) as distinctfilter group by querystring order by popularity desc 	0.000166358280496285
8499603	15592	mysql - random 'a' from random 'b'	select quotes.*    from quotes,         (select author            from quotes           group by author           order by rand()           limit 1) random_author   where quotes.author=random_author.author   order by rand() limit 1; 	0.00102881259433263
8500112	7206	date format in mysql	select date_format(date, '%d %b %y (%a )') from table; 	0.0684953804294981
8501375	6726	join one row from a table with multiple rows	select straight_join     amount, carid, date from (     select saleid, count(*) as amount     from link     group by saleid     order by null) as amounts join sales on sales.id = amounts.saleid; 	0
8504807	24438	how can i obtain a transposed union of 3 sql tables?	select   (select top 1 column_a from table1) as 'column_a',  (select top 1 column_b from table2) as 'column_b',  (select top 1 column_c from table3) as 'column_c' 	0.0138100236367617
8506710	23268	the last result of the rules	select ru.id, ru.description, re.result_of_the_rule, re.date     from (select rule_id, max(date) as maxdate               from result               group by rule_id) q         inner join rules ru             on q.rule_id = ru.id         inner join result re             on q.rule_id = re.rule_id                 and q.maxdate = re.date 	0.000173280382691524
8506986	2229	getting distinct to work	select     top (100) percent convert(char(10), [reg date1], 103) as [reg date], sum(regs) from         (select     cast(setupdatetime as datetime) as [reg date1], count(distinct id) as regs                        from          dbo.tbl_user                        where      (cast(setupdatetime as datetime) between cast(dateadd(dd, - 7, cast(convert(varchar, getdate(), 112) as datetime)) as datetime) and cast(convert(varchar, getdate(), 112)                                                as datetime))       group by cast(setupdatetime as datetime)) as a group by convert(char(10), [reg date1], 103) order by convert(char(10), [reg date1], 103) 	0.618714240593343
8509330	27452	returning other columns of aggregate result	select   * from   yourtable inner join   (select col1, max(col2) as max_col2 from yourtable group by col1) as lookup     on  yourtable.col1 = lookup.col1     and yourtable.col2 = lookup.col2 	0.00578884711239808
8509563	17458	postgresql: need a sql query to find how many posts are there with one category	select c.id, c.category_name, count(p.id)    from public.categories c        left join public.posts p            on c.id = p.category_id    group by c.id, c.category_name 	0.000162618695294081
8509930	7592	take query string stored in sql and reformat as json	select '{"' + replace(replace(@x, '=', '":"'), '&', '","') + '"}' 	0.428639018802012
8510112	5256	how would you display the manager name from employee table in an sql query?	select    emp.ename as "employee",    emp.empno as "emp#",    emp.mgr as "mgr#",   m.ename as "manager" from   emp   left outer join emp m on    emp.mgr = m.empno 	0.000110682436939589
8510621	33160	need a sql query to find posts with most commented order by comments number/count desc	select          p.id,          c.postcount     from posts as p     inner join (                   select                          post_id,                          count(*) as postcount                   from comments                   group by post_id                ) as c            on p.id = c.post_id     order by c.postcount desc 	0.00132308491490661
8511081	189	mysql combining data from three queries	select name,         sum(case when delivery_date = '2011-11-22' then qty                  else 0 end) as qty_today,        sum(case when delivery_date = '2011-11-23' then qty                  else 0 end) as qty_tomororow,        sum(case when delivery_date = '2011-11-24' then qty                  else 0 end) as qty_om from order_item where delivery_date between '2011-11-22' and '2011-11-24' group by name 	0.0124840431430677
8512292	34242	sql query ordered alphabetically	select id, description     from yourtable     order by case when id = 5 then 1 else 0 end,              description 	0.154985696315137
8512925	17922	multiple results from single table in mysql	select     user_id,     count(*) as total_leads,     sum(lead_status = 'active') as active,     sum(lead_status = 'win') as win,     sum(lead_status = 'loss') as loss from your_table group by user_id 	0.00194170765739564
8512934	32586	pivoting dates in a month out as columns; possible without dynamic sql?	select a.id, coalesce(b.minutes, 0), coalesce(c.minutes, 0), (etc) from employees as a left join timeclock as b on b.employeeid = a.id and b.date = @given left join timeclock as c on c.employeeid = a.id and c.date = dateadd(day, 1, @given) (etc) 	0.000607986353997945
8513845	4773	sql: update column with with an index that resets if column changes	select     id,      type,      row_number() over(partition by type order by id) as [order] from yourtable 	0.11230323314314
8514784	14802	select records in a table that are repeated twice using mysql	select list_id from yourtable group by list_id having count(*) = 2 	0.000352222334848138
8515138	25975	need to select 5 latest records order by category?	select p.* from product p1 left outer join product p2   on (p1.brand_id = p2.brand_id and p1.product_id < p2.product_id) group by p1.item_id having count(*) <= 5 order by brand_id, product_publish_date; 	0
8515433	20144	order rows by result of algorithm outside of db query	select this, that, other, (author_karmar + ( pageviews/100 ) + age ) as score from table order by score desc 	0.00290369683003405
8516502	1505	counting the number of rows with a value greater than or equal to a value from another column in sql	select t1.num_marks,          (select count(t2.couple_id)    from table_name t2      where t2.num_marks >= t1.num_marks    ) as num_couples  from table_name t1   group by t1.num_marks    order by t1.num_marks desc; 	0
8516944	8546	query more than 2 tables with 1 key in mysql?	select p.product_id, p.product_name, (ifnull(w1.inventory1, 0) + isnull(w2.inventory2, 0)) as totalstock from `product_table` as p left join `warehouse1_table` as w1 on (     p.product_id = w1.product_id ) left join `warehouse2_table` as w2 on (     p.product_id = w2.product_id ); 	0.00862211834349689
8518120	18617	find total by weekly	select trunc(date,'d'), sum(total) from table where date >= trunc(sysdate - 20*7, 'd') group by trunc(date,'d') order by 1 	0.00054361725782295
8519747	19379	sql - how to count unique combination of columns	select count(*) from (   select distinct folderid, userid from folder ) 	0.000301953524813675
8520043	16176	how to join tag_map in a normalized database	select tag.id,  group_concat(post.post_id)  from    posts    inner join    post_tag on ...   inner join    tags on ...  group by tag.id; 	0.113320108766142
8520469	25690	sql: how to select using both wildcards (like) and array (in)?	select * from table_name where field_name like '%one'    or field_name like '_two'    or field_name like 'three[abv]' 	0.745624329033369
8523255	30218	use sql to query in order except the first record	select name from names order by   case when name = 'john' then 0 else 1 end,   name 	0.00492052590564701
8524988	15060	comma separated list	select personname, ( select    emailaddress + ',' from   dbo.email where   email.personid = person.personid order by  emailaddress for xml path ('') ) as emailaddresses from dbo.person 	0.00095686956019846
8525222	20982	trying to use if with max in mysql to get most recent date between 2 tables	select c.pageid, greatest(proddate.lastmodified,catdates.lastmodified) as lastmodified from (select p.catid as catid,max(p.updated) as lastmodified from products p group by p.id,p.catid) proddates inner join  (select c.id as catid,c.pageid,max(c.updated) as lastmodified from categories c where c.hide=0 group by c.id,c.pageid) catdates on proddates.catid=catdates.catid 	0
8526748	816	how do i apply limit to this parent / child tree like table in query	select `message`.*  from          `message` inner join         (select `id` from `message` where `parent` is null limit 30) `ids` on              `message`.`id` = `ids`.`id` or `message`.`parent` = `ids`.`id` 	0.243534168526295
8527015	21698	run a mysql query in a mysql query	select * from shout_out as so left join shout_out_reply as sor on sor.convers_id = so.convers_id where so.sent_to = '$username' and so.convers_id != 'no_reply' 	0.735926411009467
8527154	28651	mysql select from the most times this appears	select following     from yourtable     group by following     order by count(*) desc limit 1; 	0.000880237900584333
8528061	14557	sql - is it possible to join a table to a resultset created by several select/union-alls?	select te.*, t.ord from tblentity te inner join (     select 1 as id, 2 as ord     union all     select 2, 1 ) t on te.id = t.id 	0.15939798539844
8530267	7970	mysql query for records in a same table	select group_id, count(*) from members_user_table   group by group_id 	0.00138274050621648
8530632	18256	concat values in mysql query(to handle null values)	select   concat('the surname is ', ifnull(last_name, 'sadly not available')) from `employees` 	0.0530126420708349
8532125	4621	postgres - match as much as possible of beginning of search parameter	select n from your_table where n in (     select $1/(10^i)::int8 from generate_series(0,floor(log($1))::int) i ) order by n desc limit 1 	0.0277206703323469
8532599	34625	need to perform order by twice	select field1, field2 from table order by field1 asc, field2 asc 	0.753360231775953
8533240	10632	date comparison in oracle for the year ends with 00	select * form persons where  to_date(per_join,'dd-mm-yyyy')= to_date(i.emp_doj,'dd-mm-yyyy') 	0.0271813562322527
8533265	25807	sql query for retrieve rank list	select @rank:=@rank+1 as rank, r.* from (     select team_name, max(level) as level, max(completed_time) as completed_time     from results     where `status` = 'yes'     group by team_name     order by 2 desc) as r, (select @rank:=0) as init 	0.0128384948756365
8533310	37007	sql - double condition check in sql	select      table1.id,      table1.name,      table1.col3,      table2.id from      table2 right join table1 on (table2.name = table1.name) and (table2.id = table1.id) where      table2.id is null; 	0.525341883721171
8533370	29540	restrict records top 5 entity dataset	select="select top(5) title, id, listprice, salesprice" 	0.00268373565068724
8533438	7904	count and order by where clause matches	select * from "faq" where     ((lower("question") like '%what%'    or lower("question") like '%is%'    or lower("question") like '%a%'    or lower("question") like '%duck%')) order by     case when lower("question") like '%what%' then 1 else 0 end +     case when lower("question") like '%is%' then 1 else 0 end +     case when lower("question") like '%a%' then 1 else 0 end +     case when lower("question") like '%duck%' then 1 else 0 end descending; 	0.439630949572175
8535255	18309	is possible to use in () to find intersect	select f_product_id     from productparametervalues     where f_parametervalue_id in (1, 2, 3, ..., 1000)     group by f_product_id     having count(distinct f_parametervalue_id) = 1000; 	0.543981148476133
8535385	26930	how can i get a sum of the items in my grouped query?	select new with {                      .areadistrict= tip.areadistrict,                     .referralsum =lwrgrpq.sum(function(x) x.referrals)                  } 	0.000152773209457184
8535916	12010	how can i test for null and not null at the same time in sql?	select * from employees where lastname like '%smith%' and firstname like '%bob%' and nvl(middle,'') like '%%' 	0.0121079210631529
8536220	2524	sqlite for web, select two tables are empty	select * from complete union select * from incomplete; 	0.0159511273923799
8536593	14346	sql modified result set depending on date adding pre headers, etc	select data, date from mytable union all select distinct 0 as data, date from mytable order by 1, 2 	0.000174079133908657
8537273	15792	pl/sql column mask with fixed number of characters in queries	select   case when regexp_replace (dump (varchar2_column), '^typ=(\d+).*', '\1') = 1 then lpad(varchar2_column, 10, ' ')           else null end varchar2_column,          case when regexp_replace (dump (number_column), '^typ=(\d+).*', '\1') = 2 then lpad(number_column, 10, 0)           else null end number_column   from   table 	0.0029341178586077
8539362	24363	obtain oracle 11g partitioning interval by direct system table query	select interval from dba_part_tables where table_name = 'some_table' and owner = 'some_owner'; 	0.188688096397866
8539957	1770	phrasing sql that has subquery returning multiple rows	select *     from orders     where email = 'me@example.com'         and datediff(now(), datepurchased) <= 1; 	0.0364353567857251
8540493	23376	how to use join and avoid getting duplicate data?	select projects.name,         projects.description,         group_concat(categories.name separator ' ') as category_name from projects join projects_categories    on projects.project_id = projects_categories.project_id join categories    on projects_categories.category_id = categories.category_id where projects.project_id = ? group by projects.name, projects.description 	0.161841026522673
8541453	30719	sql query - selecting certain rows from a table	select   * from     test where    cola > 0  or       (cola = 0 and colb = 3)  	0
8541546	6654	limiting a query to the 5 lowest values for a query to the 5 lowest values for a variable	select * from (   select title, points, submissionid   from submission    where points >= '$sidepoints'    order by points asc   limit 5 ) t order by t.points desc 	0
8541807	13624	mysql results for joins where some fields are empty	select    h.id,    h.name,    h.age,   coalesce(group_concat(o.name order by o.name separator ', '),'nobody') as owners from    horses h left join    horse_owners ho  on    h.id = ho.horse_id left join   owners o on   ho.owner_id = o.id  group by h.id 	0.136098051994732
8542201	4861	how to join category table for parents in sql query?	select       p.id,       p.post_title,       p.category_id,       c.category_name as firstcat,       c.parent,       coalesce( c2.category_name, ' ' ) as parentcategory    from       posts p          join categories c             on p.category_id = c.category_id             left join categories c2                on c.parent = c2.category_id    where       anyfiltering 	0.0208364667111477
8543218	7718	display cell value as column name using sql	select   name,    max(case subject when 'c++'  then grade end) 'c++',   max(case subject when 'java' then grade end) 'java' from @test group by name; 	6.59088192243298e-05
8543535	32774	select distinct sum sql server	select      product.groupid,             max(product.productid) as productid,             max (product.brandid) as brandid,             max (product.year) as year,             max (product.name) as name,             max (tblbrand.brandname)as brandname,             max(tblreview.gradepoint) as gradepoint from        product inner join             tblbrand on product.brandid = tblbrand.brandid left outer join             (select groupid, sum(gradepoint) gradepoint from tblreview group by groupid) tblreview on product.groupid = tblreview.groupid group by product.groupid 	0.143226689563233
8546746	19515	mysql join with conditions	select * from jobs j left join groups g on g.group_number = j.relevant_group where j.relevant_group = 0 or (g.supervisor_id = j.job_lister_id and g.employee_id = :employee_id) 	0.684914393961419
8549521	2406	create view with two columns in two tables	select the_day, price, amount   from year_days left join (select sale_date, sum(price) price                               from sales                              group by sale_date) on the_day = sale_date                  left join (select expense_date, sum(expenses) amount                               from expenses                              group by expense_date) on the_day = expense_date  order by the_day; the_day        price     amount ... 01-dec-11 02-dec-11 03-dec-11 04-dec-11 05-dec-11       2000 06-dec-11                   300 07-dec-11 08-dec-11 09-dec-11 10-dec-11 11-dec-11        800        500 12-dec-11 13-dec-11 14-dec-11 15-dec-11                  1100 16-dec-11 17-dec-11       2400 18-dec-11 ... 	0.00080163372673554
8549888	17813	sql query to select records based on 2 different values in the same field and a condition	select distinct d1.trid  from dennis d1      inner join dennis d2 on d2.trid=d1.trid where d1.place = 'bangalore' and d2.place = 'mumbai' and d1.si < d2.si 	0
8550427	16823	how do i get column type from table?	select o.id [tableid], o.name [tablename], c.name [columnname], c.status [columnstatus] t.name [columntype] from sysobjects o inner join syscolumns c on c.id = o.id inner join systypes t on t.usertype = c.usertype where o.type = 'u' and o.name in (tablename) 	0.000324240322182446
8552470	36525	mysql pro rata counting of distinct values in last period	select  customerid, sum(datediff(dateend, fp) + 1) / (datediff(dateend, datestart) + 1) from    (         select  b.*, min(date) as fp         from    billing b         join    purchase p         on      p.customerid = b.customerid                 and p.date >= b.datebegin                 and p.date < b.dateend + interval 1 day         group by                 b.id, p.subcustomerid         ) q group by         customerid 	0
8553547	33791	sort posts by highest vote count?	select    links.id,    links.url,    links.user_id,    links.title,    links.description,    links.nsfw,    links.posted,    links.category_id from    links    inner join votes on votes.link_id = links.id group by links.id order by count(votes.id) desc 	7.87794487383001e-05
8556357	40451	oracle sql - maximum from two select statements	select max(salary) from table1 where role = 'manager' or role = 'developer' 	0.00268250635309677
8557918	29037	finding second smallest value in mysql table	select     min(nullif(sale_price, 0)) from `table` where product_id = 244; 	0
8558167	9509	calling id of a database object given the name	select * from table_1 where title='my_title'; 	0.000258205652357347
8559327	6695	php - how can i dynamically export data to excel file (.xls)?	select f.attendee_id as id1, f.answer as prenom, l.answer as nom, c1.answer as choix     into outfile '/path/to/file.csv'     fields             terminated by ';'             optionally enclosed by '"'     from wp_events_answer f      join wp_events_answer l on f.attendee_id = l.attendee_id      join wp_events_answer c1 on f.attendee_id = c1.attendee_id      where (f.question_id = 1) and (l.question_id = 2) and (c1.question_id = 28); 	0.0676208252264752
8561606	17920	timediff in mysql	select round((unix_timestamp()-unix_timestamp('[sql-param time]'))/3600); 	0.194819397501868
8563281	25530	sql join 4 tables	select s.sid, s.sname, e.ccode  from student s inner join enrolled e on s.sid = e.sid  inner join class c on e.ccode = c.ccode  inner join tutor t on c.tid = t.tid  where s.programme = 'it'     and t.tname = 'hoffman' 	0.262172034351503
8564031	2272	sql query: finding unique number combinations within all records	select distinct e.entryid from entry e, combination c where c.comb_num1 in (e.numberone, e.numbertwo, e.numberthree, e.numberfour, e.numberfive) and   c.comb_num2 in (e.numberone, e.numbertwo, e.numberthree, e.numberfour, e.numberfive) and   c.comb_num3 in (e.numberone, e.numbertwo, e.numberthree, e.numberfour, e.numberfive) and   c.combid = @combid 	0
8564898	20322	two queries, merge results, sort	select *     from yourtable     where agentid = 1234         or (officeid = 4321 and agentid <> 1234)     order by case when agentid = 1234 then 0 else 1 end,              agentid, officeid 	0.00671483135600009
8565127	28642	grouping data by column	select      val_id     ,max(case when col_name = 'status' then value end) as status     ,max(case when col_name = 'country' then value end) as country from     col_values v     join et_col c on v.col_id=c.col_id group by val_id 	0.0277048544500967
8567097	24850	php mysql counting multiple columns in single table	select animal, count(*) as animalcount     from animals     group by animal 	0.000561160504905503
8568346	40533	postgresql - how to manipulate the query results?	select name::text, id::int,  case when pass = true then 'passed' else 'failed' end as pass  from mytable; 	0.14664586506612
8568512	13708	return records where regexp not matched but does not contain word	select .. where myfield regexp '/all/page[0-9]+$' or myfield not regexp '/page[0-9]+$' 	0.153060457165071
8568630	35364	finding reference table from foreign key in sql developer	select acc.table_name referencing_table_name, acc.column_name referencing_column_name from all_constraints ac1, all_constraints ac2, all_cons_columns acc where ac1.constraint_type = 'p' and ac1.table_name = :table_name and ac2.r_constraint_name = ac1.constraint_name and ac2.constraint_name = acc.constraint_name; 	0.000163311021256356
8569637	18627	sql query to select from two tables with if condition	select    *      from    notification n             left outer join acknowledgment a on a.parent_id = n.id   where     (a.parent_id is null or a.status = @somevalue) 	0.00696598351051859
8570995	5398	group by on a value from different table	select code_two, sum(price) from table1 t1 inner join table2 t2 on t1.code_one = t2.code_one group by code_two 	0.000101935811644761
8571135	20430	select from two tables at the same time?	select objecto, atributo from table a union all select palabra, atributo from table b 	0
8571902	5687	mysql: select only unique values from a column	select distinct(date) as date from buy order by date desc; 	0
8572821	21688	group by with union mysql select query	select sum(qty), name from (     select count(m.owner_id) as qty, o.name     from transport t,owner o,motorbike m     where t.type='motobike' and o.owner_id=m.owner_id         and t.type_id=m.motorbike_id     group by m.owner_id     union all     select count(c.owner_id) as qty, o.name,     from transport t,owner o,car c     where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id     group by c.owner_id ) t group by name 	0.653406078469631
8573545	27448	calculate average time between post and first comment in two mysql tables	select   avg(first_comments.first_time - posts.created_at) from     posts join    (select   comments.post_id                   min(comments.created_at) as first_time          from     comments          group by post_id) as first_comments on       first_comments.post_id = posts.id; 	0
8574560	23330	mysql find occurrence of start and end date range between two date columns	select   sum(     if(datediff(least(validto, '2011-12-23'),                 greatest(validfrom, '2011-12-21')) >= 0,        datediff(least(validto, '2011-12-23'),                 greatest(validfrom, '2011-12-21')) + 1,        null) * rateperday  ) as total from thedata; 	0
8575542	38076	sql : can’t grab values in descending order when using group by	select * from ( select leads.id,leads.name, log.prob, log.current_stage, log.id as logid from leads left join log on log.leadid = leads.id where leads.name = '$name' group by log.leadid ) order by logid desc 	0.0210204832320795
8575863	17093	is there a way to determing how many records can a 200 mb sql server db have	select      object_name(object_id) as 'table name',              record_count,     min_record_size_in_bytes,     max_record_size_in_bytes,     avg_record_size_in_bytes from     sys.dm_db_index_physical_stats(db_id(), null, null, null, 'detailed') 	0.0118067657926035
8576148	102	sql server query to know if an id in a column equals to other in another column	select l.specialtychosenid, l.studentid, count(distinct r.subject) from students l left join students r on (l.studentid=r.studentid and l.specialitychosenid=r.subjectspecialityid) group by l.specialtychosenid, l.studentid 	0
8576740	16956	mysql select only 1 per match	select q.date, count(*)     from (select distinct email, date, time               from mail2_mailing_log               where id_message = @id) q     group by q.date     order by q.date desc 	0.000388923268860881
8577940	11636	sql find oldest student	select s.sid, s.sname, s.age from student s inner join enrolled e on s.sid = e.sid inner join class c on e.ccode = c.ccode inner join tutor t on c.tid = t.tid where s.programme = 'cis' and t.tname = 'kathy bond' order by s.age desc limit 1 	0.0136910121596799
8578222	40602	mysql return id with smallest count	select id from (   select id, count(id) as c      from <table name> group by id  ) as x order by c limit 1 	0.00303407552095289
8578243	1012	using between with max?	select * from tblname where id between 100 and (select max(id) from tblname) 	0.119264214962309
8579341	17456	does oracle's rownum build the whole table before it extract the rows you want?	select col1, col2 from (     select col1, col2, rownum rn from (         select col1, col2 from the_table order by sort_column       )       where rownum <= 20   )   where rn > 10 	0.0182305548094085
8579596	34432	datediff when time crosses midnight	select datediff(minute, '2011-12-20 11:43:00', '2011-12-20 11:50:00') select datediff(minute, '2011-12-20 23:59:00', '2011-12-21 00:07:00') 	0.797251094190191
8580003	11078	select root node from subtree (postgresql ltree) query, which returns several descendants	select   subpath(ancestry, 0, 1) from   some_table; 	0.0135490515906679
8580039	1965	count mysql union type query	select count(t.*) from (   (select 1 as sort_col,performerid,pic0         from $table         where performerid is not null           $performeridsql)    union      (select 2 as sort_col,performerid,pic0         from $table         where performerid is not null           $categorysql $buildsql           $breastsize $haircolor $age $ethnicity           $willingnesssql)   order by sort_col) ) as t 	0.460780499249044
8580161	25772	how to select row based on existance of value in other column	select i_id, option, p_id from (   select     i_id,     option,     p_id,     row_number() over (partition by i_id order by case option when 'c' then 0 when 'b' then 1 when 'a' then 2 end) takeme   from thetable   where option in ('a', 'b', 'c') ) foo where takeme = 1 	0
8580286	25215	sql server - check whether record with specific value exists	select coalesce (                     (select min(n1.slot) + 1                         from items n1                             left outer join items n2 on n1.slot+1 = n2.slot                       where n1.name = 'abc'                         and n2.slot is null                         and n1.slot < 11)                    ,0) 	0.00016832972765231
8581853	35648	get records that are only numbers	select distinct substring(paprojnumber, 1, 5) as study_number     from dbo.pa01201 as pa01201_1     where paprojnumber>'0'         and isnumeric(substring(paprojnumber, 1, 5) + '.0e0') = 1 	0
8582241	12562	mysql select a date between two dates using the time now	select * from kick_offs where `time` < date_add(now(), interval 1 hour) and `time`>= now() 	0
8582571	3846	mysql union query duplicate rows	select username, pic0  from ".$table."  where ( username like '%lunch%' )     or ( username is not null        and age between 28 and 45        and willingness like '%lunch%'        ) order by ( username like '%lunch%' ) desc 	0.0241273169792194
8583117	23074	sql query join limit results to one item per id	select p.*,        (select i.imagename           from images          where i.productid = p.id         order by i.date_created asc          limit 1)           as imagename   from products p 	8.43990270090683e-05
8583486	16614	add 0 at beginning in sql	select distinct       right('00'+ltrim(substring(convert(varchar, rundatetime, 100), 13, 2)),2) +       ':'      + right('00' + substring(convert(varchar, rundatetime, 100), 16, 2),2) + ' '      + substring(convert(varchar, rundatetime, 100), 18, 2) as distinctdate from testdates 	0.00927216850162079
8585237	17575	select data from 1st table and get the 2nd table's field for 2 columns in table 1	select a.*, b.description as description1, c.description as description2 from tabl1 a left join tbl2 b on a.refid1 = b.id left join tbl2 c on a.refid2 = c.id 	0
8585353	22255	select the maximum for each value in a mysql table	select state, max(orderamount) as amount from table group by state having amount > 15; 	0
8585481	10493	how make a select with "repeated" condition in sql?	select top 1    a, b, c, d  from    products  where   coddep in (10,12,12,13,26,27,32,34,248442,259741) order by    lastupdate 	0.326830977057234
8590552	19604	removing duplicates from join between two tables (oracle)	select * from (      select          n.*,          rank() over (partition by n.msisdn order by length(n.prefix) desc) as rnk     from (         select *          from msisdn a          left join ranges b               on a.msisdn like b. prefix || '%' and a.network = b.network          ) n      )t where t.rnk = 1 	0.00292295008315107
8593622	4070	sql: return most recent actions, but limit to 10 results	select * from activities a inner join (             select                actor               , max(created) created              from activities              where comment_type <> 'profile.status'              group by actor             limit 10 offset 0) t       on (a.actor = t.actor and a.created = t.created) limit 10 	9.74426685453606e-05
8594237	4743	finding items in a table that satisfy a subset frequency condition?	select userid from ownership  where itemid in (1,2,3,4,5,...)  group by userid having count(distinct itemid) >= 3  	0
8596910	11639	how do you order by two tables?	select  t.review,         score = case when totalreviews<> 0 then likedreviews/totalreviews else null end   from  (               select    *,                     (select count(*) from review_rating where review = r.review) as totalreviews ,                     (select count(*) from review_rating where review = r.review and like = 1) as likedreviews,               from  review r                      where  game = ?          )t order by t.review, score 	0.0189891683962563
8597266	34895	how do i select a record whose timestamp is the most recent	select * from table order by created_ts limit 1 	0
8598211	16847	sql syntax to select an entire table with values replaced with values in other tables	select  attr        = m1.sym_const,         val_const   = m2.sym_const   from  secondtable s         join maintable m1 on m1.id = s.attr         join maintable m2 on m2.id = s.val_const 	0.00063392040768917
8598956	4656	getting value from a third table	select posts.*, users.avatarid from posts  left join subscribers on posts.authorid = subscribers.profileid  join users on posts.authorid = users.userid where posts.authorid = ?  or subscribers.subscriberid = ?  order by postid desc  limit ? 	0.000271917798028137
8599035	29485	sql zero leading in comparing 2 record set	select * from inventory_nbp.v_dmnd_rsrv_dpnd_rqr_mrp where plnt_id ='wa01'  and mtrl_id in('g29329-001',cast(cast('000000000000909120' as int) as varchar(10)), '13-0006-001')  and   (mtrl_id, plnt_id)       in       (    select itm_cd, sap_plnt_cd            from pdm_analysis.v_itm_plnt_extn       ) 	0.00176453018752043
8600400	38604	sql query to removing rows when only one column value is duplicate	select t.lr_no, t.seq, t.len     from yourtable t         inner join (select lr_no, max(len) as maxlen                         from yourtable                         group by lr_no) q             on t.lr_no = q.lr_no                 and t.len = q.maxlen 	0
8600595	32487	sql server: calculate data by each month,year and group by something	select datename(mm, dateadd(m, datediff(m, 0, [date]), 0)) + ' ' +       select cast(datepart(yy, dateadd(m, datediff(m, 0, [date]), 0)) as varchar)       [date] sum(total) as total, item,warehouse from testing group by item, warehouse, dateadd(m, datediff(m, 0, [date]), 0) 	0.00049184626939223
8601124	13259	sql: ms access distinct for few columns	select *  from table_name t where not exists (select 1                    from table_name tt                    where tt.col1 = t.col1                      and tt.col2 = t.col2                      and tt.id > t.id) 	0.119180848600825
8603362	5194	php order by today, week, month ... not working	select stories.*, sum(votes.vote_value) as 'total_votes'      from stories join votes on stories.id = votes.item_name      where votes.item_name=$date      group by stories.id order by total_votes desc limit 10 	0.00326691498566148
8603517	5948	filter sql query for last 24 hours	select site_id, time, count(*) as site_num from url_visits where time > unix_timestamp(date_sub(now(), interval 1 day)) group by site_id order by count(*) desc 	6.2860519795121e-05
8603870	2807	select rows containing xml node at any position in document	select *  from customsettings  with (nolock) where settings_xml.value('(/settings/item[@name="colorscheme"]/@name)[1]', 'varchar(25)') is not null order by 1 desc 	0.000774637148289201
8604954	22695	how can i force tsql to accept two dates equal if there is only an n miliseconds difference?	select * from table1 t1  inner join table2 t2  on t1.halodate between dateadd(ms,-5,t2.halodate) and dateadd(ms,5,t2.halodate) 	0.000359481330740132
8607201	40978	optimizing my random row fetch	select id,title,banner_url,destination  from tbl_banners  where id = $rand_offset 	0.0551932596578459
8607701	15081	mysql joins to retrieve result	select b.id, sender.username as sender_username, receiver.username as receiver_username from tableb as b   join tablea as sender on b.from_userid = sender.userid   join tablea as receiver on b.to_userid = receiver.userid 	0.0696134191128741
8608250	6216	get duplicate rows and count based on single column	select distinct a.id, a.code, a.ownername, b.count from customers a join (   select count(*) as count, b.code   from customers b   group by b.code ) as b on a.code = b.code where b.count > 1 order by a.code; 	0
8608275	12887	how do i write this sql query? top 3 most matching results	select top 3 id from mytable  where attrib in ('a', 'b', 'c') group by id order by count(distinct attrib) desc 	0.0592260627161639
8608929	35447	getting mutliple threads and their latest post from a database using one query	select     thread.title,     post.text from     forum_thread thread join (     select               max(post.posted) as posted,         post.threadid     from         forum_post post     join          forum_thread thread     on          post.threadid = thread.id     where         thread.forumid = '$secfid'         and thread.accesslevel <= '$secuserlevel'            group by         post.threadid ) latest_post on      thread.id = latest_post.threadid join     forum_post post on     latest_post.threadid = post.threadid     and latest_post.posted = post.posted limit     $qstart, $ppp; 	0
8609771	22739	get messages between friends in database	select * from tbl_statuses where userid = @myuserid  or userid in (select friendid from tbl_friends where userid = @myuserid and accepted = 1) 	0.000491420693252846
8610438	20373	sqlite use order by, but have another delimiter put things at bottom of list	select *      from testtable      order by case when price = 2.00 then 1 else 0 end,              date 	0
8610531	39670	query to get percent of a total using select(count)	select  feh.forty_eight_hours         , auy.admit_uncomfort_yes         , percent_changed = cast(feh.forty_eight_hours as float) / auy.admit_uncomfort_yes from    (           select  forty_eight_hours = count(pain_48_hr_comfort_c)           from    cases           where   pain_48_hr_comfort_c = 'yes'          ) feh         cross apply (           select   admit_uncomfort_yes = count (pain_admit_comfort_c)            from     cases            where    pain_admit_comfort_c = 'yes'         ) auy 	6.97545953516709e-05
8611044	10706	check if username already exists in database mysql php	select username from table where username='$php_username_var'; 	0.019481265793449
8611083	10580	select count from country , city , continent	select   'city' as result_type            , city            , count(*) as cnt     from     homes     where    city like '%rom%'     group by city union all     select   'country' as result_type            , country            , count(*) as cnt     from     homes     where    country like '%rom%'     group by country union all     select   'continent' as result_type            , continent            , count(*) as cnt     from     homes     where    continent like '%rom%'     group by continent 	0.00189225506136495
8611526	4716	multiple distinct values with sum	select  userid, name, sum(amount), min(date) from    yourtable group by         userid, name 	0.0151199101580844
8611545	33863	sql concatenate string in result	select 'http: 	0.0180521575800541
8611858	28600	sql - retrieve last record of day for the last 7 days	select   pl_scores.* from   pl_scores inner join   (select max(updatedat) as maxupdatedat from pl_scores group by date(updatedat)) as lookup     on lookup.maxupdatedat = pl_scores.updatedat 	0
8612224	10268	generate xml from table	select  * from #tmp as record for xml auto,  root('doc') 	0.00525989135234569
8613510	9116	how do i include another column without having to place it in the group by clause? [sql server 2005]	select distinct t.serialno, e.controlno, t.adddate from tst_equipmentitem e join (     select serialno, max(adddate) as adddate     from tst_equipmentitem      group by serialno ) t on t.serialno = e.serialno and t.adddate = e.adddate 	0.137514941615803
8616970	31765	sql distinct rows based on date created the row	select name, email, dateapplication, description from ( select row_number() over (partition by name order by dateapplication desc) rownumber,               name, email, dateapplication, description        from yourtablename) where rownumber = 1 	0
8617979	11597	sql join + groupby select data from row with max(date)	select i.*, outert.entrydatetime, outert.varchar, outert.int from item i      left join      (select itemid as outeritemid, entrydatetime, varchar, int       from (select row_number() over (partition by lt.itemid order by t.entrydatetime) as rownumber, lt.itemid, t.entrydatetime, t.varchar, t.int             from tranaction t inner join linkingtable lt on lt.transactionid = t.id) innert       where rownumber = 1) outert on outert.outeritemid = item.id 	0.0248516281806593
8620502	24039	searching for a number inside a column mysql	select * from recipes where products like '243,%' or products like '%|243,% 	0.0215491340081486
8620714	22711	efficient way to get all articles with a set of tags in mysql	select a.* from  (     select at.articleid as id     from   article_tag at     join   tag t on t.id = at.tagid     where  t.name = 'tag1'     ) a1 join  (     select at.articleid as id     from   article_tag at     join   tag t on t.id = at.tagid     where  t.name = 'tag2'     ) a2 using (id) join article a using (id); 	4.6396429827633e-05
8622400	11423	in php, how can i compare three queries to select corresponding rows?	select cola, colb  from tablea join tableb  on a.commoncolumn=b.commoncolumn  join tablec on a.commoncolumn=c.commoncolumn  where ... 	0.000288953643660345
8622513	37317	select and delete rows within groups using mysql	select *     from my_table t1     where (status = 'pending'         and date < (             select max(date)                 from my_table t2                 where t2.file = t1.file                     and t2.status = 'done')); select *     from my_table t1     where (status = 'pending'         and date > (             select min(date)                 from my_table t2                 where t2.file = t1.file                     and t2.status = 'pending')); 	0.00378515820290896
8623557	3863	mysql table order by values with split string	select   coalesce(     if(left(subj1,4)='raj1', substring(subj1,6), null),     if(left(subj2,4)='raj1', substring(subj2,6), null),     if(left(subj3,4)='raj1', substring(subj3,6), null)) as raj1,   coalesce(     if(left(subj1,4)='raj2', substring(subj1,6), null),     if(left(subj2,4)='raj2', substring(subj2,6), null),     if(left(subj3,4)='raj2', substring(subj3,6), null)) as raj2,   coalesce(     if(left(subj1,4)='arun', substring(subj1,6), null),     if(left(subj2,4)='arun', substring(subj2,6), null),     if(left(subj3,4)='arun', substring(subj3,6), null)) as arun,   coalesce(     if(left(subj1,5)='muthu', substring(subj1,7), null),     if(left(subj2,5)='muthu', substring(subj2,7), null),     if(left(subj3,5)='muthu', substring(subj3,7), null)) as muthu from thetable; 	0.00388191425662243
8626559	15541	get only second record from details table	select appid, ssn ,rn from ( select appid, ssn , row_number() over(partition by appid order by  appid) as rn from table )t where rn=2 	0
8626738	34526	how do i select and match from multiple tables?	select * from users a inner join areas on areas.user_id = a.id where a.id not in (select user_id from matches) and a.visible = '1' and a.limit_age = '18:30' and a.limit_gender = 'f' and areas.country = ? and areas.city = ?; 	0.00210960229743711
8628213	10635	how to use join as a select column	select distinct x.id, x.name, case when r.id is not null then 1 else 0 end isrelated  from table x  left outer join relative r on r.nameid = x.id 	0.18427191616608
8629683	7785	find max row and its value in sql server 2000	select t.* from t left outer join t as t2 on t2.id = t.id and t2.[level] > t.[level] where t2.id is null 	0.000540087254370413
8631210	25175	group_concat order by	select li.clientid, group_concat(li.views order by li.views asc) as views,  group_concat(li.percentage order by li.percentage asc)  from table_views group by client_id 	0.647907977087753
8631860	2656	how can i write a query that returns a row for every distinct value in one column and returns an arbitrary value from another column?	select [name], min([guid]) as mguid from tablelikethis group by [name] 	0
8632432	23158	get a list of each value in a column and how many times it occurs sorted from highest to lowest	select count(friend_id), friend_id from table group by friend_id order by count(friend_id) desc 	0
8632433	13055	combining multiple queries of the same table into one sql statement	select cola,colb,colc from table1 t1     where      (     (col1 = $var1 and col2 like '%$var2%') and              exists (select 1 from table1 t2 where t2.col1 = $var1)     )     or      (     (col2 like %$var1%) and             not exists (select 1 from table1 t3 where t3.col1 = $var1)     ) 	7.83104460240706e-05
8634020	27077	how to change the date format	select convert(varchar(8),convert(datetime, '23/02/2009',103),112) 	0.00822846295041517
8634373	28825	how to using command sql get random 10 rows in php	select * from `table_name` order by rand() limit 10; 	0.000447327320986956
8638909	7769	mysql store file details in one or many database table design and best way of creating parent and child categories	select p.userid, p.parentcategoryid,c.childcategoryid  from parentcategory p inner join         childcategory c           on p.parentcategoryid=c.parentcategoryid where        p.userid = @userid 	9.03644229707472e-05
8641744	14969	mysql - conditions with precedence	select *, ( select min(condition_number) as first_condition_met from (  ( select t.*, 1 as condition_number from terms t where ... ) #first condition in where clause          union        ( select t.*, 2 as condition_number from terms t where ... ) #second condition in where clause          union        ( select t.*, 3 as condition_number from terms t where ... ) #third condition in where clause ) ) from (        ( select t.*, 1 as condition_number from terms t where ... ) #first condition in where clause          union        ( select t.*, 2 as condition_number from terms t where ... ) #second condition in where clause          union        ( select t.*, 3 as condition_number from terms t where ... ) #third condition in where clause     ) where condition_number = first_condition_number 	0.651703459985345
8646011	21956	how to select the rows where i found one times the customer id	select id, date_commande, id_customer from table where id_customer in (select id_customer from table group by id_customer having count(*) = 1) 	0
8647094	18465	finding the sum of integers from multiple mysql rows in same column	select sum(column_name) as total from table_name 	0
8647578	17295	mysql query table join	select g.game_id,         u1.first_name as ulname,         u2.first_name as u2name,         u3.first_name as u3name,         u4.first_name as u4name from tblgames as g    left join tblusers as u1 on g.p1_id =u1.user_id    left join tblusers as u2 on g.p2_id =u2.user_id    left join tblusers as u3 on g.p3_id =u3.user_id    left join tblusers as u4 on g.p4_id =u4.user_id 	0.420068033966193
8647725	35278	sum results from two select statements	select perceptionistid, ssnlastfour, sum(commissionpay) commissionpay,         sum(ptopay) ptopay, sum(holidaypay) holidaypay, sum(overtime) overtime, sum(totalpay) totalpay from (     select  perceptionistid, ssnlastfour, commissionpay,         ptopay, holidaypay, overtime, totalpay     from [dbo].fncalculatecommissionforweekof(@mondayofcurrentweek)     union all     select  perceptionistid, ssnlastfour, commissionpay,         ptopay, holidaypay, overtime, totalpay     from [dbo].fncalculatecommissionforweekof(@mondayoffollowingweek) ) t group by perceptionistid, ssnlastfour 	0.00690410134053179
8648131	20473	join together pre-joined tables to one single table	select   r.domainid,   r.dombegin,   r.domend,   d.ddid,   d.confid1 as confid,   c.pdbcode,   c.chainid from dyndomrun d   inner join conformer c on d.confid1 = c.id   inner join domainregion r on r.domainid::varchar(8) = d.ddid union all select   null,   null,   null,   d.ddid,   d.confid2,   c.pdbcode,   c.chainid from dyndomrun d   inner join conformer c on d.confid2 = c.id 	0.0030477404138947
8648600	36686	list of assemblies in sql server 2008	select * from sys.assembly_modules 	0.226523919562316
8652925	23221	find out the old date from a date column in sql	select updatedate from table1 where datediff(year,partdatecol,getdate()) in (select max(datediff(year,partdatecol,getdate())) diffyear from table1) 	0
8653344	29676	finding the maximum of various sum of values in mysql	select player from mytable  group by player order by sum(score) desc limit 1 	0
8654155	34061	how to get list of all the procedure inside a package oracle	select procedure_name  from all_procedures  where owner = 'you'  and object_name = 'your_package' 	0.00123032185380151
8654393	23913	how to left join while using a filter on the left table?	select *    from product_table pt      left join order_table ot        on ot.product_id=pt.id   where pt.id = 1 	0.449220709047551
8654534	12322	retrieving last year's data only if a single record for last month	select    trx_detail_1,   trx_detail_2 from (    select sum(            case when trx_date > add_months(sysdate, -1) then 1 else 0 end          ) over (partition by user_id) sum_user_last_month,          trx_detail_1,          trx_detail_2      from           transaction      where          trx_date > add_months(sysdate, -12) ) where       sum_user_last_month > 0; 	0
8655034	3540	how to split a column into multiple values	select substring([value],1,3) as val1,        substring([value],5,3) as val2,         substring([value],9,3) as val3   from table1 	0.000132021911077251
8658045	27506	echo sql query from voting table	select count(distinct ip) as votes, week(created_date) as week_num from 'vote' group by week(created_date) order by week_num desc 	0.0213937645764172
8659255	10856	getting last value in group concat	select course       , chapter      , substring_index(lessons, ',', -1) as last_lesson from tablex 	0.000774220344096891
8659725	6965	detect missing values in a (auto-incremented) sequence	select ifnull(min(r1.port) + 1, 30000) as minport from reg r1 left join reg r2 on r1.port + 1 = r2.port where r2.port is null: 	0.0245440253828852
8661331	28706	how to do a retrieve user posts from this database design?	select        u.username,        p.text from        userposts up  inner join       users u  on         u.userid = up.userid inner join        posts p on p.postid = up.postid 	0.000451548851414579
8661794	5638	how to select multiple columns values same rows from single table	select [table].a, [table].b, [table].c, [table].d, [table].e, [table].f, [table].g from [table] left join (select a, b, c, d from [table]  group by a, b, c, d having count(*) > 1) as sub on ([table].a=sub.a) and ([table].b=sub.b) and ([table].c=sub.c) and ([table].d=sub.d) where g>132 and sub.a is not null; 	0
8665222	9564	case statement returns multiple rows	select o.* from order_master as o where     (       ((@paymentstatus = 0) and (o.noofinstallment <> o.installmentpaid))       or        ((@paymentstatus=1) and (o.noofinstallment = o.installmentpaid))     ) 	0.507702053523213
8665665	32152	sql query to search partial data in one field	select * from table_name where file-id regexp '^32' or file-id regexp '^46'; 	0.00515697556868217
8666513	11217	count the result of a mysql count?	select times_won, count(*) from (     select user_id, count(*) as times_won     from my_table     group by 1 ) x group by 1 	0.00698713232432972
8667898	8579	create table variable (or temp table) from an existing table but with an extra column	select *, cast('hbkkj' as nvarchar(100)) as new_column into #temptable from existing_table where section = 2 	0.00131656956578398
8668057	29281	how to query through this tables structure	select p.products_id, p.products_number,p. products_status,p. products_price        pd.language_id, pd.products_description, pd.products_name from   products p,         products_description pd,        (select min(language_id) mlid          from products_description ipd          where pd.products_id=ipd.products_id            and ipd.language_id = pd.language_id) a where  p.products_id  = pd.products_id 	0.632923044509416
8668981	6334	number of hits that meet single criteria under openoffice or ms 97 or even mysql	select student_id, count(book_id) as num_of_books from mytable group by student_id 	0.000799454407065118
8669070	22010	query part of an xml column as a result set	select x.n.value('(keyvaluepairofstringstring/value[../key = "event"])[1]', 'varchar(100)') as event,        x.n.value('(keyvaluepairofstringstring/value[../key = "detail"])[1]', 'varchar(100)') as name from yourtable as t   cross apply t.xmlcol.nodes('/main/data/rows/_items/columns/values/keyvaluepairs') as x(n) 	0.0123277405300956
8670777	35721	how do i add a row to a mysql result set for use as a prompt in an html selectbox?	select 0, 'select a city:' union all select id as value, city as text from #__cities 	0.00404257348483849
8671168	19043	mysql select and display two column	select     t1.user_id,     t1.value as latitude,     t2.value as longitude from     wp_bp_xprofile_data t1     inner join wp_bp_xprofile_data t2 on         t1.user_id = t2.user_id where     t1.field_id = 65     and t2.field_id = 66 	0.000564363419139307
8671998	2733	how to select data from xml by t-sql?	select c.d.value('(.)[1]', 'varchar (100)') as section from store.dbo.testxml tx     cross apply tx.xcol.nodes('./docs/doc') as a(b)     cross apply a.b.nodes('./section') as c(d) where a.b.value('(@id)[1]', 'int') = 123 	0.0101073784929979
8673827	19499	how do i select data across two tables using sql where a field from each table matches?	select a.account_id, a.account_number, a.bank_id, a.external_code, m.account_string  from accounts a inner join master m on m.account_string = a.external_code 	0
8674201	14598	selecting rows with specific columns having a null or 'default' value	select * from table where col1 is null or col2 is null or ... or col1 = 'default' or col2 = 'default' ... 	0
8674692	13275	mysql: dynamically add columns to query results	select if(@rownum = 0, 'latest', 'previous') update_time, update_id,         title, content, date, (@rownum := @rownum + 1) r from updates, (select @rownum := 0) dummy where project_id = 2 order by date desc limit 2 	0.0169854361838687
8675768	6434	sql preferred column	select      name,     case when preferredemail = 'workemail' then workemail else homeemail end as email from     mytable 	0.65409389047572
8677307	19512	how to select the row of a minimum value of a group, while also using a where clause	select a.courseid, a.lesson, a.personid, a.thedate  from (     select personid, courseid, min(thedate) as earliestdate      from attendance      group by personid, courseid ) as x  inner join attendance as a    on (a.personid = x.personid and        a.thedate = x.thedate and        a.courseid=x.course_id) 	0
8680231	15665	sorting a join by result count from bridging table	select *  from      apartment a     join     (select count(*) as ct, apartment_id     from bridging     where amenity_id in ('x','y','z')     group by apartment_id      ) b on a.id = b.apartment_id  where     a.`city` = 'foo'     and a.`price` <= 'bar' order by     b.bt desc 	0.0166768759355466
8680737	29938	how to use a mysql column alias for calculations?	select wp_posts.*,      (`alias_1`.meta_value) as `lat`,      (`alias_2`.meta_value) as `lng`,      (3959 * acos( cos( radians(41.367682) ) * cos( radians( `lat` ) ) * cos( radians( `lng` ) -     radians(2.154077)) + sin(radians(41.367682)) * sin( radians( `lat` )))) as `distance` from wp_posts      left join `wp_postmeta` as `alias_1` on wp_posts.id = alias_1.post_id      left join `wp_postmeta` as `alias_2` on wp_posts.id = alias_2.post_id where       wp_posts.post_status = 'publish'       and wp_posts.post_type = 'page'       and wp_posts.post_date <  now()      and `alias_1`.meta_key = 'position'      and `alias_1`.meta_value like '41.%'      and `alias_2`.meta_key = 'position'      and `alias_2`.meta_value like '2.%' group by wp_posts.`id` order by `distance` asc 	0.547708207789647
8683356	27295	sql, comparing relationships housed in multiple link tables	select distinct     x.aid,     x.bid from     (select         az.aid,         bz.bid,         (select count(1) from az az1 where az1.aid = az.aid) as acount,         (select count(1) from bz bz1 where bz1.zid in (select zid from az az1 where az1.aid = az.aid) and bz1.bid = bz.bid) as bcount     from         az         inner join bz on             az.zid = bz.zid     ) x where     x.acount = x.bcount 	0.0256156253124277
8685390	17002	mysql order by with union duplicate results	select jokes.*      , case when title like '%only three doors%'                or joke like '%only three doors%'               then 1              when title like '%only%'                or joke like '%only%'               then 2             when title like '%three%'                or joke like '%three%'               then 3             else 4        end as ob  from jokes  where flags < 5    and ( title like '%only%'       or joke like '%only%'      or title like '%three%'       or joke like '%three%'      or title like '%doors%'       or joke like '%doors%'       ) order by ob asc        , ups desc        , downs asc  limit 0, 30 	0.151659545172849
8685721	29893	how to count in rows in mysql database	select username, count(*) as user_count from yourtable group by username order by user_count desc 	0.00725504707116241
8685836	14611	how does the primary key in a database works?	select  t.name ,       c.name from    sys.tables t join    sys.columns c on      c.object_id = t.object_id where   c.is_identity = 1 	0.27325910936457
8686228	36075	specific sql query trouble	select v.id, v.votes, c.clicks   from (select id, count(*) as votes           from vote_table as v1          where date(v1.`date`) = timestamp('2011-12-30')          group by v1.id) as v   join (select id, count(*) as clicks           from click_table as c1          where date(c1.`date`) = timestamp('2011-12-30')          group by c1.id) as c     on v.id = c.id  order by v.id; 	0.641377353792529
8686450	8590	how to use union in android	select a._id, a.x, a.y, b._id, b.z, b.q  from not a, q_a b  where a._id = id  and b.z = zid a.comid = b.refid 	0.768521058903237
8687627	7228	how to make table joins in phpmyadmin	select *  from    tracklisting t    inner join catelouge c on c.catno=t.catno  where t.id = 1 	0.75087714421386
8689449	5351	how to join 2 select queries when one of the queries is unified	select f.friends_friend as user_id,         users.username as friend_name, users.user_email as user_email,        users.user_avtr as profile_pic from friends as f left outer join(     select user_email, user_id,username,users.user_avtr from users )as users on f.friends_friend = users.user_id where f.friends_member = ? union select f.friends_member as user_id,         users.username as friend_name, users.user_email as user_email,        users.user_avtr as profile_pic from friends as f left outer join(     select user_email, user_id,username,users.user_avtr      from users )as users on f.friends_member = users.user_id where f.friends_friend = ? 	0.00913066540345324
8693545	25372	sort sold table by most frequent product_id	select * from sold s order by (select count(1) from sold ss where ss.product_id=s.product_id) 	0.000271436837059084
8694503	9827	how to pass the datetime value as parameter to a stored procedure?	select * from requestheader where    convert(varchar, rh.billdate ,105) between convert(varchar, cast(@fromdate as datetime),105)    and convert(varchar, cast(@todate as datetime), 105) 	0.0767440704782727
8694964	30139	display a range of values between two user input values between two different columns in sql?	select distinct column1, column2  from table  where column1  between '&column1' and (select column1 from table where column2 = '&column2')  order by column1; 	0
8695032	36522	mysql search across two tables	select a, b from language_learn where c like '%d%' union select a, b from language_know where c like '%d%' 	0.0168287032907347
8696825	37601	mysql - searching a field twice	select t1.uid  from languages t1 inner join languages t2 on t1.uid = t2.uid where t1.language = 'zh' and t1.type = 0   and t2.language = 'en' and t2.type = 1; 	0.0534697224405657
8697066	842	get references table name and table column	select cols1.column_name , r1.constraint_name , r1.constraint_type  , cols2.table_name , cols2.column_name from all_constraints r1 ,    all_cons_columns cols1 ,    all_cons_columns cols2 where r1.constraint_name = cols1.constraint_name and   r1.owner = cols1.owner and   r1.r_owner = cols2.owner(+) and   r1.r_constraint_name = cols2.constraint_name(+) and cols1.table_name = 'employees'  and r1.owner = 'hr'  / 	0.000118907715657787
8699260	7672	how to select sum of column based on date	select sum(value) as value_today from table_value where date = curdate() 	0
8699562	8243	how do i fetch data from two tables as one row	select a.post_title, b.meta_key, b.meta_value as level, c.meta_value as intro from wp_posts a left join wp_postmeta b on a.id = b.post_id left join wp_postmeta c on a.id = c.post_id where b.meta_key = 'level' and c.meta_key = '_post_main_intro' 	0
8699974	22248	joining table with conditions	select    *,    coalesec(pstd.price, pc.price) from     product_commons pc    join    product_prices pstd on pc.id = pstd.product_id and pstd.campaign_id is null;    left join     product_prices pp on pc.id = pp.product_id and pp.campaign_id = 3; 	0.0980299819617895
8705615	18088	select data from a right unknown table, how to?	select ... from usertable u left outer join usertype1 t1 on u.userid = t1.userid left outer join usertype2 t2 on u.userid = t2.userid 	0.0325657218703231
8705708	36396	returning a result set with two different values	select user_id, gift_id from table where (user_id = 15906 or gift_id=15906) and (user_id <> coalesce(gift_id,0)) 	0.000991590555425093
8706456	30515	mysql join / sum query	select courses.id      , courses.name      , count(student_courses.id) as number_of_students     from courses    left join student_courses       on student_courses.course_id = courses.id where courses.approved_by <> '0' group by courses.id having count(student_courses.id) < courses.student_slots 	0.578751538763807
8706805	39288	find rows where any two columns are not unique in mysql?	select * from the_table t where not exists (     select 0     from the_table t2     where t.col1 = t2.col1     and t.col2 = t2.col2     and t.id < t2.id ) 	0
8707636	29062	how to find out which user executed an sql statement?	select a.username,        b.sql_text,        a.status from   v$session a        inner join v$sqlarea b          on a.sql_id = b.sql_id; 	0.0561711176576783
8712771	19928	mysql extract year from date format	select year(str_to_date(subdateshow, "%m/%d/%y")) from table 	0.000142455807650416
8714931	1610	mysql count records grouped by day in multiple tables	select date_posted, count(*) from (select date_posted from article union all       select date_posted from blogposts) v group by date_posted 	0
8715588	9976	joining child results into parent (one to many query)	select ;       p.name as parentname ;       c.* ;    from ;       parent p ;          join child c ;             on p.id = c.parentid ;    order by ;       p.parentname, ;       c.name ;    into ;       cursor c_yourresultset 	0.000142190334269083
8716317	32151	mysql query issue - join product details into result	select        `list`.`time`,        `list`.`location`,        `prod1`.`prod_name` `prod_name1`,        `prod1`.`prod_price` `prod_price1` ,       `prod2`.`prod_name` `prod_name2`,        `prod2`.`prod_price` `prod_price2`  from `shopping_list` `list`      inner join  `products` `prod1`      on  `list`.`product_1` = `prod1`.`prod_id`            inner join  `products` `prod2`      on  `list`.`product_2` = `prod2`.`prod_id` 	0.711200940760494
8719004	18878	how can i select distinct records including datetime when datetime is different?	select distinct ordernumber, serialnumber, price, cast(testdatetime  as date) testdate from testtable order by ordernumber, serialnumber 	0.000376096819945274
8719516	26026	sql in query questions	select u_id from #__bl_teamcord where find_in_set('11',teams) 	0.593249781961558
8719727	4901	mysql query "in" 500,000 records	select t.value     from table t         inner join newtemptable n             on t.id = n.id 	0.206424015158604
8720382	31307	getteing more values with union all sql query	select * from ( select parent_id as mid, null, count(*) as cnt     from wp_forum_posts     where text like '%{$word}%'     group by 1     union all         select id, subject, count(*)         from wp_forum_threads         where subject like '%{$word}%'         group by 1) x order by 2, 1 	0.0766329933301445
8723057	7825	finding the relevant records using xquery/xpath	select *  from users  where [userdata].exist('/customer/addresses/addressblock                          [contains(upper-case(addressline1[1]),"somestreet") and                            contains(upper-case(city[1]),"somecity")]')=1 	0.00166215827082697
8723659	9317	retrieve data from movie database	select max(c.character_name) character_name,        max(a.name) || ' ' || max(a.surname) actor,        group_concat(distinct m.title) other_movies from cast c join actors a on c.actor_id = a.actor_id left join cast omc on c.actor_id = omc.actor_id and c.movie_id <> omc.movie_id left join movies m on omc.movie_id = m.movie_id where c.movie_id = ? group by a.actor_id 	0.00117788088396784
8726055	36480	get data from multiple tables	select p.productname, o.quantity from products p inner join order o on p.productid = o.prodid where o.orderid = <order id> 	0.000506435783204914
8727494	31553	mysql joining 3 tables on condition	select   a.actor_id,   a.first_name,   a.last_name,   f.film_id,   f.title from actor a   inner join film_actor fa     on fa.actor_id = a.actor_id   inner join film f     on f.film_id = fa.film_id 	0.0285108379301661
8727936	22298	mysql get mindate and maxdate in one query	select min(date_col),max(date_col) from table_name 	0.0104671444043188
8728030	30616	find which column differs between 2 rows?	select *     , case          when a.operationtype <> b.operationtype         then 1         else 0         end as operationtypediffers     , case         when a.operationdate <> b.operationdate         then 1         else 0         end as operationdatediffers from xusers a join xusers b     on a.xuserid < b.xuserid     and a.userid = b.userid     and (a.operationtype <> b.operationtype         or a.operationdate <> b.operationdate)  where a.userid = @userid 	0
8728371	16999	php: duplicate entry 'xx' for key 'yy'	select 1 from table where post_name = 'morandi-midnight-train' limit 1; 	0.000748014335647005
8728507	23509	sql query return values in a set sequence	select id from tablename order by   case when id = 3 then 1        when id = 6 then 2        when id = 1 then 3        when id = 9 then 4        when id = 2 then 5        when id = 5 then 6        else 7 end, id asc 	0.0191804759843284
8728826	498	debugging postgresql server process (how to identify the correct process id)	select pg_backend_pid(); 	0.093745562070942
8731610	29939	mysql: find max(var1) but return var2 of that entry instead	select * from (     select id, group_concat(name), min(prio) as lowest         from my_table     group by id ) foo join my_table mt on foo.lowest = mt.prio and foo.id=mt.id; 	0.000179630335269239
8733413	22093	my sql is reurning row with null value	select p.id, p.title, p.description, p.game, p.icon, p.comments_allowed, p.views, p.dnt, u.id as poster_id,  u.username as posted_by, u.icon as poster_icon, count(c.id) as total_comments      from ne_posts p          left join ne_users u              on u.id = p.posted_by          left join ne_comments c              on c.id = p.id      where p.game = "game1"      group by p.id, p.title, p.description, p.game, p.icon, p.comments_allowed, p.views, p.dnt, u.id, u.username, u.icon     limit 4 	0.186768841253918
8734352	37913	retrieve ids of rows with same column fields in mysql	select    count(*) as cnt,    group_concat( cast(id as char) ) as ids  from    homes  group by    number, street  having   count(*) > 1 	0
8734718	19720	select statement inside another select statement	select u.username, m.message, m.sent     from messages m         inner join users u             on m.u_id = u.u_id      where m.r_id = ?         and m.sent > ? 	0.426369340281354
8735134	769	sort by rate from homes with multiple rates	select * from homes inner join rates on rates.home_id = homes.id group by homes.id order by min(rates.price) asc 	0.0266951131187506
8735208	16353	group by - sorting pre and post grouping	select a.id, a.name, a.[type], a.modified_time from [events] as a     join (         select max([events].id) as id, [events].[type]         from [events]         group by [events].[type]         ) as b on a.id = b.id and a.[type] = b.[type] order by a.modified_time desc 	0.037166614273278
8735676	20539	sql query that returns value based on lookup of id in another table	select   events.eventname as eventname,   eventslocation.locationname as locationname from   events   inner join eventslocation on events.location=eventslocation.location (where ...) ; 	0
8736231	35029	comparing ranges of date fields to curdate() in mysql without regard to year	select     * from     `closures`  where     if(`yearly` = '1',         (             if(left(`start_date`,4) < left(`end_date`, 4),                 (                     if(right(curdate(), 4) > right(`end_date`, 4),                         (curdate() between concat(left(curdate(), 5), right(`start_date`, 5)) and concat((left(curdate(), 4) + 1), right(`end_date`, 6))),                         (curdate() between concat((left(curdate(), 4) - 1), right(`start_date`, 6)) and concat(left(curdate(), 5), right(`end_date`, 5)))                     )                 ),                 (                     concat(left(`start_date`, 5), right(curdate(), 5)) between `start_date` and `end_date`                 )             )         ),         (             curdate() between `start_date` and `end_date`         )     ) 	4.79336020586623e-05
8736412	23176	adding an if statement to a mysql query	select p.r1, p.r2, p.rounds, p.whenmatch, p.created, p.status, p.lid, p1.userid as userid1, p1.username as challenger, p2.userid as userid2, p2.username as challenged, p3.lname          from ab_league_match p          join vb_user p1 on p.challenger = p1.userid          left join vb_user p2 on p.challenged = p2.userid          join ab_league p3 on p.lid = p3.id 	0.592515640576714
8736905	25714	sql left join +one to many relationship	select c.uid, n.uid, n.nid, c.message    from node n      left join share_content c        on c.nid = n.nid             and c.auto_id              = (select max(auto_id)                 from share_content                  where nid = p.nid )   where n.nid = 40513    order by c.auto_id 	0.280353114854635
8737755	26462	mysql in operator returns values in descending order	select v.email, u.usernum from  (select 'blah@blah.com' email union select 'rawr@rawr.com' union select 'e@e.com') v left join usergroup u on v.email = u.emailmain order by v.email 	0.36866084797445
8740150	22439	sql left join 2 tables	select book.*, purchase.user_id  from book      left join purchase on book.book_id = purchase.book_id  where purchase.user_id = 3  order by purchase.purchase_date 	0.407410886719037
8740401	36539	mysql, inner join query, must match multiple rows	select vlc.*  from view_layout_rows vlc inner join view_layout_rows_columns vlrc1 on vlrc1.id = vlc.id inner join view_layout_rows_columns vlrc2 on vlrc2.id = vlc.id where vlrc1.row = 1 and vlrc1.columns = 5   and vlrc2.row = 2 and vlrc2.columns = 5   and vlr.rows = 2   and (vlr.owner = 0 or vlr.owner = 1); 	0.250066405235984
8741397	9223	create a mysql query when date is same for some id but time is differ	select wellid, max(dated), drillid from (table name) where drillid = 123 group by drillid 	0.000898695140357909
8741680	30235	how to take sum of two different query result counts in mysql?	select count(*) from( (select count(*) from view_category where 1=1) union (select count(*) from view sub category where 1=1) union (select count(*) from view subsub category where 1=1) ) as int_val; 	6.99601820929474e-05
8741737	1637	can you set a stored procedures parameters from the output of a query?	select p.prefix , t.*  from     products p    cross apply     dbo.someudf (p.min, p.max, p.prefix) t where     p.prefix in ('toaster', 'ladle', 'pan') 	0.0452885683078979
8741912	22521	sql statement to check the length of an attribute value in sqlite3 python	select statements  from x where length (statements) < 13 	0.00284292424677002
8742341	8633	mysql sum(costs) where id = x	select   sum(mytable.mycostamount) as total,   myothertable.myothertableid  from    myothertable   inner join mytable on myothertable.commonfield=mytable.commonfield where   myothertable.myothertableid = '$myint' 	0.017824163209888
8742994	25644	sql - finding different names with the same values	select brand from car group by brand having count(*) = (select count(*) from car where brand = 'ferrari') 	0
8743012	2180	mysql query - adding up columns & rows	select `product`.`productid`, `product`.`name`, `product`.`sku`, ifnull(sum(`product`.`stock`),0) + ifnull(sum(`option`.`stock`),0) as `stock` from `product` left join `option` on `product`.`productid` = `option`.`productid` group by `productid` 	0.0115327107102507
8743606	17028	mysql combine results from union of same-scheme tables	select `cli`,max(`ts`) as ts, sum(`questions`) as questions, sum(`answers`) as answers,sum(`correct`) as correct,sum(`last`) as last,sum(`minutes`) as minutes from (   select `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes`    from  `imsc_storage_users`   union all   select `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes`    from  `imsc_storage_users_archive` ) as baseview group by cli order by `correct` desc,`minutes` asc 	0.00364029057610124
8744036	31390	avoid mysql 'using temporary' in certain cases	select straight_join       u.name   from      followers f         join users u            on f.follows = u.id           and u.joined > 1234   where      f.user = x   order by       u.joined desc 	0.127821956559927
8744276	10098	how can i get data from multiple mysql tables and store in user session?	select studentid, name, access, period  from user join roster on user.studentid = roster.id  where user.studentid = '$studentid' 	0.000126370634674468
8744763	19921	oracle query termdates unique results	select * from (select t.*, rank() over (partition by recordid order by termdate desc) rn  from mytable t) where termdate is null or rn = 1 	0.271217966312063
8746917	33094	mysql join query	select pss.* from page_section_sub pss inner join page_section ps on pss.page_section_id = ps.id where pss.page_section_id in (1, 2, 3, 4, 5) order by ps.display_order 	0.724110026477687
8746969	38327	handeling querying an item with a single quote in it	select 'frank''s oracle site' as text from dual; 	0.0407974823924107
8749252	335	combining count(*) with sql statements into one table	select 'number of female users from table 2:' as msg,         count(*) as entries   from table1   where age >57 union all select 'number of users over the age of 57 from table 1:' as msg,         count(*) as entries   from table2   where gender = "female" 	0.00613045728192142
8750501	6315	trying to find a single record based on a group of records where there is a 100% match in mysql	select userid  from table group by userid having count(userid) = sum(if(skipped = 1,1,0)) 	0
8750860	40609	how do i include records lacking one half of a join?	select      s.staffid as staffid,      concat_ws(", ", lname, fname) as name,      group_concat(unit separator ", ") as units  from      staff s     left outer join staff_units r on s.staffid = r.staffid          left outer join units u on u.unitid = r.unitid  group by s.staffid  order by lname 	0.000605728133218582
8751896	41249	joining 3 tables in mysql	select *    from meetings   inner join minutes on meetings.meeting_id = minutes.meeting_id   inner join attendees on meetings.meeting_id = attendees.meeting_id   where minutes.approval = 'approved'     and meetings.meeting_id = '$id' 	0.0451709027514053
8752705	24487	calculate average of column from mysql query	select avg(p1_score) 	7.36984328398157e-05
8752919	32340	possible to limit amount if items shown after a sql sort? or not show items that have an int less than given amount?	select * from `table_name` where `countout` > 100 order by `countout` desc limit 20 	0
8753618	39315	concatenate columns if not equal	select iif([cola] = [colb], [cola], [cola] & '(' & colb & ')') as formattedcol  from mytable where 	0.00385912477775245
8754020	28495	how to select distinct rows that match multiple elements from same column in 1 query?	select *, count(id) as matches from table_name where type in('u','x','t') group by object order by matches desc 	0
8754316	31674	dense_rank on calculated column	select    *,    dense_rank() over (order by product) from ( select    case            when [col1] = 's' then 8           when [col1] = 't' then 6            when [col1] = 'u' then 9           when [col2] = 'v' then 1  ... end as product from dbo.tablea ) t 	0.0875224745786742
8754675	6534	slow mysql query that has to execute hundreds of thousand of times per hour	select * from tablename where username = 'username' order by datetime_sent desc limit 1 	0.000672930756463381
8755111	12226	how to combine 2 complex sql queries into 1	select    username,   (age_stuff) as age,   (distance_stuff) as distance from userlist where    distance < 15   and age < 24 and age > 64 order by distance limit 30 	0.0289675534490311
8755904	7766	how to select specific values from xml using oracle xquery	select t.*         from xmltable(xmlnamespaces(default 'http:                                    ,'http:                                     ,'http:                                     ,'http:                                     ,'http:                                     ,'http:                                     ,'http:                       ,'for $d in                         where $d/../../@name = "getfeature"                         and $d/../@name="outputformat"                         return $d' passing p_xml columns value varchar2(100) path '/') as t; 	0.00210687370030498
8756769	18265	splitting numbers and letters in sql server 2005 table	select substring(yourcol, 0, p),        substring(yourcol, p, 8000) from   yourtable        cross apply(select patindex('%[^0-9]%', yourcol + 'a')) split(p) 	0.00885584935521265
8757061	4281	sum(subquery) in mysql	select m.col1, (select sum(col5) from table where col2 = m.col1) from table as m 	0.60230144813372
8757577	14889	sql query select unique images from multiple tag_id	select   image_id  from     tag_relationship where    tag_id in ( 106, 73 ) group by image_id having   count(*) = 2 	0.00736614373007062
8758035	3167	get price from two tables	select ifnull( price.price, ifnull( product.price, product.msrp )) from  price join product on price.sku = product.sku       and (product.disponible > ifnull( price.disponible_from, "1970-01-01" )          and product.disponible < ifnull( price.disponible_to, curdate())) where ( price.periodfrom < curdate() and price.periodto > curdate()); 	5.52824868543054e-05
8758391	20659	sql bulk insert with on the fly table creation	select * from excel into newtable where 0=1 	0.00616352295614527
8758404	37633	time different betwen two columns in mysql higher than xx days	select * from table where abs(datediff(date1,date2)) > 14; 	0
8758976	16851	is there a t-sql function to return the name of the 'sa' account?	select suser_name() 	0.0207778508930712
8760717	2905	can i search two tables for a username?	select password, salt, 'employer' as user_type from employer where employer_name = '$username' union select password, salt, 'client' as user_type from clients where clients_name = '$username' 	0.0336332850529365
8762401	17720	selecting the rows from db based on date	select off_id,uid,leave_from,leave_to,leave_code from yourtablename where leave_from>="2012-01-01" and leave_to <="2012-01-05" 	0
8762528	15651	total comments from multiple rows mysql	select mid,sum(comments) as totalcommentcount from episodes  group by mid   order by  mid 	0
8763426	23601	additional mysql select query condition?	select     min(pp.price) from     products p     inner join product_prices pp on         p.product_id = pp.product_id     inner join products_categories pc on         p.product_id = pc.product_id where     pc.category_id = ?i     and p.status = 'a' 	0.521761820732184
8763455	5073	how to calculate the sum of any number of counts	select   id,   sum(factor*count) as totalscore from (     select       p.id as id,       st.factor as factor,       count(*) as count      from       s2p_photo p        left join s2p_score s        left join s2p_score_type st      group by p.id, st.name     order by p.id asc ) as baseview group by id 	0
8763783	3732	sql unique entry issue	select distinct yearfield from tablename; 	0.105950764204954
8764980	28873	mysql query based on date	select     * from     banks b1     inner join (select company, max(fromdate) as maxdate from banks where fromdate <= now()) b2 on         b1.company = b2.company         and b1.fromdate = b2.maxdate 	0.00482768178664681
8768661	26765	how can i find the ratio?	select       name,       total,      total/(select sum(total) from counts)*100 as percentage    from counts 	0.00459291618165877
8768884	34503	mysql join on the same field	select  m.id, u1.nickname as sender, u2.nickname as receiver, m.message_text from messages as m left join users as u1 on u1.id = m.sender_id left join users as u2 on u2.id = m.receiver_id 	0.00575100323214452
8769142	34845	query for count on coulmns by condition with group by	select id, count(id) as cnt, sum(if(now() - interval 7 day <= dated_on,1,0)) as lastweek from table group by id 	0.644955689777117
8769420	35787	group by count()	select     `month`, `shifts`, count(`user`) `users` from (       select          date_format( date, '%y %m' ) as `month`,          user_id as `user`,         count( schedule_id ) as `shifts`     from          schedule     group by          `month`, `user` ) s group by `month`, `shifts` 	0.19502282578925
8770188	41068	sqlite select field if text inside contains a specific text	select * from table where field like "hel%" 	0.0150566532770494
8770526	37099	taking max element(s)	select x,y from table where y=(select max(y) from table) 	0.0315530367707857
8772466	35576	grouping query result by month on the given period of time	select sum(price), date_format(from_unixtime(date), "%m") as month from sold_table group by month 	0
8773458	22658	how can i order a mysql result with an exception?	select *  from wp_postmeta where meta_key like "%_thumbnail_id" and post_id = 897 order by (case when meta_key = '_thumbnail_id' then 0 else 1 end) asc, meta_key 	0.794722933357522
8773511	1504	join three tables to create an access granted list	select distinct(f.id), f.filename from files f, access a where f.flie_access=1 or (f.user_id=2) or (f.user_id = a.user_id and a.allow_id=2); 	0.251561656312094
8774928	12680	how to exclude system table when querying sys.tables?	select s.name as owner, t.name as tablename from  sys.tables as t inner join sys.schemas as s on s.schema_id = t.schema_id left join sys.extended_properties as ep on ep.major_id = t.[object_id] where (ep.class_desc is null  or (ep.class_desc <> 'object_or_column'     and ep.[name] <> 'microsoft_database_tools_support')) 	0.0533635289965374
8775276	27073	using sql join for union of data	select count(*) from test where contract_name in ("h11","z10")   and trade_date="2010-12-01"   and trade_time="0900"; 	0.321158577609515
8775445	6749	mysql error when getting variable from url	select * from $user where devid='$devid' 	0.773930039827161
8777477	33181	in mysql select statement, how can a derived field utilise the value of another field in the select list?	select *, concat(first_name,  ' example') as full_name  from ( select  'tim' as first_name ) as t 	0
8778906	14728	fetching bit field with mysql_query()	select username, cast(emailverified as unsigned integer) as emailv, cast(blocked as unsigned integer) as block from user 	0.110544255851123
8779303	18441	do math in mysql from select	select          id,                 fullname,                 subtotal,                 payment,                 (subtotal-payment) as balance from                      (   select `transaction`.id,        concat(contact.`name`, " ", contact.last_name) as fullname,        (select sum(total) from transaction_product where transaction_product.ref_transaction = `transaction`.id) as subtotal,        (select sum(transaction_payment.idr_cash + transaction_payment.idr_bni + transaction_payment.idr_ame_exp + transaction_payment.idr_cc_niaga) from transaction_payment where transaction_payment.`transaction` = `transaction`.id ) as payment   from `transaction`    left join contact        on contact.id = `transaction`.contact_id    where reservation_status = 3        and `transaction`.id = 6345   ) 	0.159209714754864
8779503	23578	how to select every nth record?	select * from table where id mod 4 <> 0 	0.000119852942075904
8779608	28226	mysql searching query?	select * from $table_name where table_id=$id; 	0.510962546598519
8781400	6801	getting rows from one table that are related to each other throught another table	select   country.name as name from   neighbour   inner join country on     neighbour.id_country1=country.id     or neighbour.id_country2=country.id  where     (neighbour.id_country1=<your requested id>     or neighbour.id_country2=<your requested id>)     and country.id<><your requested id> 	0
8783002	30076	how to omit select results based on ids from another table in mysql?	select user_id, user_name from users where user_id not in (select user_id from projects_users where project_id = 1) 	0
8783731	32629	prior row depends on value of current row	select l.*       from user_logon l inner join (select max(logon_date) mdate,                    user_id               from user_logon           group by user_id) x on x.user_id = l.user_id                              and l.logon_date = x.mdate      where l.logoff_date is null 	0
8784018	10054	mysql time interval and sum of data according to the interval	select sum(`data`), min(`time) from tblname where `time` >= '9:01' and `date` = '2011-11'20 group by floor((time_to_sec(`time`) - time_to_sec('9:01')) / 60 / 2) 	5.3083046720818e-05
8785228	19404	no output from sql query	select atz_id, s_dat, b_dat, **cast(sugas as varchar)as sugas** from #vesture2 order by s_dat, b_dat; 	0.11917009741737
8786135	2116	mysql group by one field and order by another	select oid, pvalue from report join (select oid, max(date) as maxdate from report r where `deviceid` = 'mra-1011' and `date` <= '2012-01-20 00:00:00' group by oid) as foo on foo.oid=r.oid and foo.maxdate = report.date; 	0.00152109314113762
8786401	37663	searching multiple rows at a time through a single sql query	select a from yourtable where (b = 6 and c = 2) or        (b = 3 and c = 4) group by a having count(distinct b) >= 2 	0.00067583786510427
8787156	23769	wordpress custom select query - post id by both tags	select p .id from wp_posts as p   inner join wp_term_relationships as rel1     on p.id = rel1.object_id   inner join wp_term_taxonomy as tax1      on rel1.term_taxonomy_id = tax1.term_taxonomy_id   inner join wp_terms as term1      on tax1.term_id = term1.term_id   inner join wp_term_relationships as rel2     on p.id = rel2.object_id   inner join wp_term_taxonomy as tax2      on rel2.term_taxonomy_id = tax2.term_taxonomy_id   inner join wp_terms as term2      on tax2.term_id = term2.term_id where p.post_status = 'publish'    and p.post_type = 'header-image'    and tax1.taxonomy = 'tags'    and term1.name ='homepage'   and tax2.taxonomy = 'tags'     and term2.name ='position1' 	0.00326074047198676
8788133	21997	count records in mysql table as different columns depending on different values of a column	select       sum( if( s.job_search_text = 'a', 1, 0 ) ) as 'a',       sum( if( s.job_search_text = 'b', 1, 0 ) ) as 'b',       sum( if( s.job_search_text = 'c', 1, 0 ) ) as 'c',       sum( if( s.job_search_text = 'd', 1, 0 ) ) as 'd',       sum( if( s.job_search_text = 'e', 1, 0 ) ) as 'e',       sum( if( s.job_search_text in ( 'a', 'b', 'c', 'd', 'e' ), 0, 1 ) ) as 'other'    from        subscriber s 	0
8788344	28915	concatenating rows in relation to a join	select   ce.id showid,   group_concat(te.testid) testid,   group_concat(t.name) testname from cookingepisodes ce   left join testitems te     on te.episodeid = ce.id   left join tests t     on t.id = te.testid group by   ce.id desc; 	0.0220606237815021
8788361	34820	counting the number of results from a large database	select id, name, betcount from (   select     odds_providerfk as id,     count(*) as betcount   from bettingoffer   where active = 'yes'   group by odds_providerfk   order by betcount desc) as counts using (id); 	8.34842800777919e-05
8789685	38256	mysql: query for two values' presence	select count(*) from (     select distinct title from (         select title, text from table where title in ('a', 'b')     )     as filtered     where (title='a' and text like '%aaa%')        or (title='b' and text like '%bbb%') ) as allresults; 	0.0154448782233529
8789932	108	how do i combine these two queries into one?	select distinct f.firstoffrequencymhz, ( select min(l.distance) from licencedata as l where l.class_stat like 'f*' and l.type_lc = 'a' and l.frequency between f.firstoffrequencymhz-0.0249 and f.firstoffrequency+0.0249 ) cofx, ( select min(l2.distance) from licencedata as l2 where l2.class_stat like 'm*' and l2.type_lc = 'a' and l2.frequency between f.firstoffrequencymhz-0.0249 and f.firstoffrequency+0.0249 ) como from [freq list] as f 	0.000852077694091957
8790842	24844	i need to generate two letters to a person (one for each address). how can i accomplish this?	select newaddress as address from tablename union select oldaddress as address from tablename 	0
8790856	32708	sql server xquery in one line?	select convert(xml, n'<a key="2"></a>', 1).value('a[1]/@key', 'varchar(8000)') 	0.0868298467072305
8791322	27460	oracle sql: getting only one max row using multiple criteria	select department, name, email, id, date1, date2 from ( select row_number() over (partition by department order by date1 desc, date2 desc, id desc) as rownumber,         department, name, email, id, date1, date2 from mytable ) t where rownumber = 1 	0.000166747559504805
8791640	17796	select highest record of type per foreign key	select     l.* from     log l     inner join (     select         max(log_id) as maxid     from         log     group by         domain_id,         type     ) l2 on         l.log_id = l2.maxid 	0
8793006	35331	sql select whole table but unique value in a specific column	select postedby, date, comment from (select row_number() over (partition by postedby, order by date desc) as rownumber,               postedby, date, comment       from mytable) t  where rownumber = 1 	0
8793822	30695	sql server - view nodes elements in xquery	select  s.value('local-name(.)', 'varchar(8000)')  as myval  from @x.nodes('/data/add') as t(s) 	0.0789943499647415
8794419	16237	making a sql query (cross table)	select      client.fname, client.lname from     staff inner join class on staff.sid = class.sid and staff.fname = "allen" and staff.lname = "moore" inner join  client on class.cid = cliente.cid order by cliente.lname asc; 	0.698001710812584
8794708	36432	mysql group by sum by day	select      date(from_unixtime(created)) as d,      sum(amount) as amount from total_log  where user_id = $this->user_id  group by d 	0.00622243872254601
8797669	22944	oracle: select items in csv format?	select listagg(name, ',') within group( order by name)   from table_name  where dept = 123 	0.0123125332248078
8798061	12162	how to combine two sql scripts?	select [membershiptermid]   ,[memberstatusprogkey]   ,[startdate]   ,[enddate]   ,[additionaldiscount]   ,[entrydatetime]   ,[updatedatetime]   ,[membershipid]   ,[agentid]   ,[planversionid]   ,[forcethroughreference]   ,[isforcethrough]   ,[nexttermprepaid]   ,[isbillingmonthly]   ,[cicsmembernum]   ,[cicshistory]   ,[tmpseqnocolumn]   ,[lastpaymentdate]   ,[paidtodate]   ,[isindeterminate]   ,datediff(month, paidtodate, getdate()) as monthsdifference from [apollo].[dbo].[membershipterm]  where memberstatusprogkey='dormant'  and isbillingmonthly=1  and dbo.fullmonthsseparation (paidtodate, getdate()) > 2 	0.0368670929202493
8800253	2668	count grouped gaps in time for time range	select ztype, count(*) as gaps from (     select ztype, datetime, sum(n) over(partition by ztype order by datetime asc) as level     from (         select id, ztype, start_datetime as datetime, 1 as n from tmp.gaps         union all         select id, ztype, end_datetime, -1 from tmp.gaps         union all         select 0, ztype, '2012-01-12 00:00:00', 0 from (select distinct ztype from tmp.gaps) z         union all         select 0, ztype, '2012-01-19 00:00:00', 0 from (select distinct ztype from tmp.gaps) z     ) x ) x where level = 0 and datetime >= '2012-01-12 00:00:00' and datetime < '2012-01-19 00:00:00' group by ztype ; 	0.000112771899048125
8802063	6260	mysql if statement change value on the fly?	select * from table_name where $wherecondition order by case          when ( a = 0, b = 0, c = 100 and liststyle = 3700)  then 1         when ( a = 10, b = 20, c = 200 and liststyle = 3400) then 2         else 10     end 	0.00737710931934483
8802245	40346	mysql: how to aggregate data into days based on half hourly timestamps?	select from_unixtime(timestamp) as stamp, sum(data) from energy  where timestamp >= 1317423600 and timestamp <= 1320105600 group by (  date( stamp ) ) 	0
8802536	32854	select from one table plus and	select product_id from products_attribute_rel  where attribute_val_id in (161, 301, 304) group by product_id having count(distinct attribute_val_id) >= 3; 	0.000985494662558133
8802541	12159	mysql union select until found?	select     *  from     db  where     concat( 'one/two/three/four/five' , '/') like concat( url , '/%') order by    length (url) desc limit 1 	0.0528661715561062
8803051	14323	select distinct from multiple fields using sql & a date_time col	select client_id, max(dateloggedin) from table where dateloggedin > x group by client_id order by max(dateloggedin) desc 	0.00199546511409488
8803881	32454	mysql multiple many to many joins	select * from events    join events_styles on events.id = events_styles.event_id     join events_formats on events.id = events_formats.event_id    where events_styles.style_id = 3   and events_formats.format_id = 1; 	0.406674502639767
8803906	23304	sql query to check if today is employee's birthday	select * from employees where datepart(d, dateofbirth) = datepart(d, getdate())     and datepart(m, dateofbirth) = datepart(m, getdate()) 	0.00105205567845748
8804437	11304	select the max value from two tables	select user_id,         max(user_date) user_date   from    (      select user_id,              max(last_contact) user_date         from emails_sent       group by user_id    union all      select whatever_user_id_column user_id,              max(whatever_date_column) user_date         from whatever_table       group by user_id    )a group by user_id 	5.34928125747636e-05
8805785	3124	comparing nulls	select a.*  from table_a a inner join table_b b on b.key = a.key where not exists (select a.*                    intersect                    select b.* ) 	0.245124534784196
8806226	34093	comparing database items to find duplicates	select * from users u1 left join users u2 on (u1.firstname = u2.firstname)      where u1.id != u2.id; 	0.000510844601784699
8806817	39404	how to select last n records from a table in mysql	select q.name, q.cost     from (select name, cost               from test               order by name desc limit 10) q     order by q.name asc; 	0
8807830	33394	acceptable technique for group-wise maximum in mysql	select deptno, emp_id, address, name from (select * from emp order by salary desc) group by deptno 	0.0958062334014723
8808533	39341	joining 3 tables together	select `all_messages`.`user_1`, `messages`.* from `all_messages` join `messages`  on (`all_messages`.`user_2` = `messages`.`from_user`)  join  `users` on (`users`.`id` = `all_messages`.`user_2`) where `all_messages`.`user_1` = '12' order by `messages`.`id` desc limit 2 	0.0397337572247322
8809330	2071	mysql: need to retrieve all records but disregard old entries	select gt.game_id, gt.home_id, gt.visiting_id, gt.timestamp    from game_transactions gt        inner join (select game_id, max(timestamp) as maxtimestamp                        from game_transactions                        where 1 in (home_id, visiting_id)                        group by game_id) q            on gt.game_id = q.game_id                and gt.timestamp = q.maxtimestamp 	0
8810782	27218	mysql end substring with sentence	select substr('my_string', 1              , 300 - ifnull(                             locate('.', reverse(substr('my_string',1,300))                                   )                            , 1)               ) 	0.374566837327701
8810965	35239	how to select distinct of the max here	select     innerquery.*,            tabb.status from                   (select     a.ws_name,                         b.b2a,                         max(b.last_update_time) as maxupdatedtime             from       taba a             inner join tabb b on (a.id = b.b2a)             group by   a.ws_name,                               b.b2a) as innerquery inner join             tabb on (innerquery.b2a = tabb.b2a and tabb.last_update_time = innerquery.maxupdatedtime) 	0.0159600172691422
8812280	28164	birthdays (dates) between two months	select . from . where makedate( year(curdate()), dayofyear(birthday)      between curdate() and date_add( curdate(), interval 30 day ) or makedate( year(curdate())+1, dayofyear(birthday)      between curdate() and date_add( curdate(), interval 30 day ) 	0.000120924816584609
8812536	20737	convert subquery to join	select * from users u left join user_groups ug on u.usergroupid=ug.groupid join user_groups ug2 on ug.grouprank >= ug2.grouprank and ug2.groupkey = 'users' where u.userstatus=1 and ug.groupstatus=1 	0.718810489408298
8812733	25485	getting a count of each distinct row in sql server 	select name, count(name) as distinctcount from tablename group by name 	0.000134045574582868
8813062	25445	mysql get row rank	select *,        (select count(*) from table t2 where totalview > t1.totalview ) + 1 cnt   from table t1  where id = '$rand'; 	0.00443962214285021
8813370	36874	select if, i want column contents only if another column shows active	select `editor` from `editors` where `active`=1 	0
8815025	35672	apply like over all columns without specifying all column names?	select      yourtable.* from yourtable join (      select        id,        isnull(column1,'')+isnull(column2,'')+...+isnull(columnn,'') concatenated       from yourtable ) t on t.id = yourtable.id where   t.concatenated like '%x%' 	0.00017770206868229
8815140	40055	can i find all vertices that have no connected edges in orientdb?	select from the_cluster where in is null or in.size() = 0 	0.000535497166355629
8816689	11925	conditional group by (group similar items) in postgresql	select * from (     select s.id,            s.name,            s.prom,            s.some_other_field,            ... many more fields also,            row_number() over (partition by s.name order by s.id) as rnk,            count(*) over (partition by s.name) cnt     from mytable s     inner join (on some other tables etc.) ) a where cnt < 6 or (cnt >=6 and rnk = 1) 	0.198444245058712
8817025	1570	best way to make search sql query for variable number of parameters	select... where      (@begin is null or datefrom = @begin)  and (@end is null or dateto = @end) and (@name is null or name = @name) ... 	0.277538218945446
8817288	20424	want sql query which give me name of the column which contain particular data	select top(1) age.columnname from advance_sub_tests as ast   cross apply (                select 1, 'first_age',  ast.first_age  union all                select 2, 'second_age', ast.second_age union all                select 3, 'third_age',  ast.third_age  union all                select 4, 'fourth_age', ast.fourth_age union all                select 5, 'fifth_age',  ast.fifth_age               ) as age(sortorder, columnname, columnvalue) where ast.advance_sub_test_id = 1 and        age.columnvalue < 20 order by age.sortorder 	0.00111483343848844
8820218	31250	@@fetch_status returns -1 when trying to use cursor based on query on information_schema	select       information_schema.tables.table_schema,      information_schema.tables.table_name,      information_schema.columns.column_name 	0.445122982372449
8820924	15921	how can i combine these two sql queries into one?	select [coordinate], [value]   from market as m0   join (select top 1 m2.[source], m2.[date], m2.marketdataid, m2.datatype           from market as m2          where m2.marketdataid = ?            and m2.datatype = ?            and m2.[date] <= ?            order by m2.[date] desc, m2.[source]        ) as m1     on m0.[source]     = m1.[source]    and m0.[date]       = m1.[date]    and m0.marketdataid = m1.marketdataid    and m0.datatype     = m1.datatype  order by [coordinate] 	0.00144881953316917
8821325	40711	select missing rows	select master from mytable group by master having count(distinct language) < 3 	0.0279975180556787
8821463	4850	similar function to contains	select *     from yourtable     where charindex(' def ', ' ' + yourcolumn + ' ') <> 0; 	0.34081810704837
8821517	1273	how to find duplicate records in a table	select column1, column2, column3, column4, count(1) from yourtable group by column1, column2, column3, column4 having count(1) > 1 	5.81783053417996e-05
8822763	35912	matching user actions from a mysql table: each close should match the previous open for a given user	select   open.user,   open.transaction_time   close.transaction_time from   user_actions as close inner join   user_actions as open     on  open.user = close.user     and open.transaction_time = (select max(transaction_time) from user_action                                  where user = close.user                                  and transaction_time < close.transaction_time                                  and type='open') where     close.type = 'close' 	0
8822866	9390	mask values on mysql database	select concat(substring(test, 1,3),'.',substring(test,4,3),'.',substring(test,7,4),'-',substring(test,11,1)) from test; 	0.0350694072712685
8824376	35550	count based on two columns in mysql	select area, count(*) as distinctcount from    (select distinct ip, id, area from video) distinctvideos  group by area order by count(*) 	9.85702535512947e-05
8824529	6130	sql create field based on other field in record	select firstname, lastname, hometown, state      from person left join citytostate on hometown=city; 	0
8825605	17855	select multiple rows at different intervals	select *    from (select @i := @i+1 as count,                 gtc.* from guitar_tunings_chords gtc          where note_id >= 27) counts    join (select @i := -1 as counter) dummy  where count % 12 = 0      or (count-4) % 12 = 0      or (count-7) % 12 = 0; 	7.70044067141498e-05
8827183	10074	mysql - select month difference	select     ... from    tablename where    expires<=date_sub(curdate(), interval 1 month); 	0.0023569488208874
8830541	33146	triggering on time segments with tsql?	select top (1) triggervalue from dbo.vw_combinedview where segmentid = 2 and triggervalue < (     select sum(p.lasteventtimespan) as totaltime     from pagevisitevents p         where p.visitorid = '9fb63b905a004106bd26c80a5caec52b'     ) order by triggervalue desc 	0.694832830726897
8831205	14279	i am trying to export mysql data to a file using java, but i am not able to get the table headers	select 'idpago','fecha','lead','idalumno','idtipopago','idgpo',     'idtaller','iddocente','pagoimporte','nofactura','facturaimporte',     'mes','formapago','observaciones' union all (select id_control_pagos, fecha, lead, id_alumno, id_concepto_pago, id_gpo,id_taller,     id_docente, pagoimporte, nofactura, facturaimporte, mensualidad_no, formapago,     observaciones from control_pagos     into outfile 'c:\\data.csv'     fields terminated by ','     optionally enclosed by '"'     lines terminated by '\n'); 	0.11812920095681
8831536	8195	compare two table in sqlite	select distinct field1 from table1  where field1 not in      (select distinct field1 from table2) 	0.00367361688882106
8831732	18594	rows printing current month and then remaining months of the year	select v.i from (values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) v(i) where v.i>=month(getdate()) 	0
8833487	31029	get a column in output while grouping but without grouping that column only in case when only there is only one row for grouped column	select m.t1id,        case          when count(*) = 1 then max(t2.t2name)          else 'common'        end from   table1_table2_mapping m        join table2 t2          on t2.t2id = m.t2id group  by m.t1id 	0
8834402	29746	lpad a column with the max length of that column	select lpad(prod_id,             max(length(prod_id)) over (),             0) from   products_tbl; 	0.000730551779300643
8837262	13565	mysql only get overall rollup	select * from (   select name, number, count(1) from test group by name, number with rollup) t where name is null or number is null 	0.02585112958825
8837584	2586	mysql in statement	select item     from yourtable     where categories in ('red', 'blue', 'green')     group by item     having count(distinct categories) = 3 	0.617987680805731
8837642	12450	mysql provides rank number when sort?	select @rownum:=@rownum+1 `rank`, u.*  from (select * from `user` order by join_time desc) u,       (select @rownum:=0) r 	0.0918858160304008
8839868	15488	mysql - query to get floor() or round() to next lowest 100 unit (hundred block number for address)	select number - mod( number, 100 ) 	0.000159798011845352
8840769	16407	how to get the sum of the rows before the current row in mysql?	select       preagg.id,       preagg.amount,       @prevbal := @prevbal + preagg.amount as total    from        ( select               yt.id,               yt.amount            from               yourtable yt            order by               yt.id ) as preagg,       ( select @prevbal := 0.00 ) as sqlvars 	0
8841261	8432	sql - how to link two tables with a third table and get all records	select u.username, r.reportname, coalesce(rd.distribtouser, 0)     from user u         cross join report r         left join report_distrib rd             on u.userid = rd.userid                 and r.reportid = rd.reportid     where u.isactive = 1         and r.distributable = 1 	0
8841774	14370	mysql group by up to certain string character	select msg1,wholemsg from   (select substring_index(message, ':', 1) as msg1, message as wholemsg from <your table>   where <your condition>) group by msg1 	0.0076709652173849
8843125	40289	sql select like junction table	select e.email     from emails e         inner join email_tags et             on e.mid = et.mid         inner join tags t             on et.tid = t.tid     where t.name in ('t_a', 't_b')     group by e.email     having count(distinct t.name) = 2 	0.241107614086593
8844167	4357	select most recent row from another table	select   (select top 1 activity_notes from notes n where n.mainid = m.id order by m.entry_timestamp desc)   , (select top 1 entry_timestamp from notes n where n.mainid = m.id order by m.entry_timestamp desc) from main m 	0
8844796	27387	sql server 2008 - separating address field	select    left(postaladdress, charindex('^', postaladdress) - 1) as street_address,   left(second_part, len(second_part) - charindex(' ', reverse(second_part))) as suburb,   right(second_part, charindex(' ', reverse(second_part))) as state,   reverse(substring(reverse(postaladdress), 2, 4)) as postal_code from (   select     postaladdress,     rtrim(reverse(substring(reverse(postaladdress), 6, len(postaladdress) - charindex('^', postaladdress) - 5))) as second_part   from addresses ) as t1 	0.284012010448252
8845808	20059	can we get a oracle value with quotes	select q'[']' || mrpid || q'[']' from demandbasic; 	0.101503466621091
8846465	16414	using count and returning more than one row	select    (select count(*) from example where ip = x1.ip) as numofoccurances,    timestamp,    ip,    id from example x1 order by timestamp desc limit 2 	0.00395920943025449
8846514	710	combine dynamic columns with select query	select * from   tbluser  join   tblcalculatedtax using (userid) 	0.0774623183844584
8848184	24461	how to distinct result in sql view select query with join?	select  distinct  t.a,   t.b,  (select case when t2.field is null then 0 else 1 end as expr1) as c from table1 t1 left join table2 t2 on t2.link = t1.link 	0.417677199988029
8851732	2421	is it considered bad form to encode object-oriented data directly into single rows in a relational database?	select ... from patients left join conditions on patients.id = conditions.patient_id left join meds on patients.id = meds.patient_id where (meds.name = 'viagra') and (condition.name = 'heart disease') 	0.018810705736588
8853678	7410	sql select count by multiples of 10	select     floor(count(*) / 10) as ten_count from     referrals 	0.00163569369429556
8855573	33840	sql group by selecting	select *,max(id) as orderfield from messages where to_user_id = '$user_id'   group by from_user_id   order by orderfield desc,read 	0.0805172896626712
8855656	3557	is there a way to get a resultset involving 2 columns joined to the same table in one query in mysql?	select message.id, `fromid`, `toid`, `sent`, `message`, message.email, `read`, fromuser.*, touser.* from message left join `user` fromuser on message.fromid = user.id  left join `user` touser on message.toid = user.id   where `toid` = '$id' or `fromid` = '$id'   order by `read` desc, `sent` desc"; 	0
8856384	24104	sql select first letter of a word?	select left(columnx, 1) 	0.000309499021911775
8857634	35184	sql query for hours of the day	select datepart(hour, orderdate) as [hour], count(*) as [count] from [orders] where orderdate between @startdate and @enddate  group by datepart(hour, orderdate) 	0.000121288096127691
8861247	36123	specific mysql select query	select (`id_recipient` + `id_sender` - n) as `id_otherperson`,          max(`date`) as `date`, count(*) as `messages`  from `table`  where `id_recipient` = n xor `id_sender` = n  group by `id_otherperson`; 	0.100663963515148
8863083	21186	sql - joining data	select top 1 first.*, second.username, third.* from first  inner join second on first.id = second.master_id inner join third on first.id = third.master_id order by third.date desc 	0.117402840882473
8863525	39500	in a database, how to store event occurrence dates and timeframes for fast/elegant querying?	select * from events  #your table     where extract(dow from date_column)=4 # dow  goes from sunday (0) to saturday (6)     and extract(day from date_column)>7 # must occurr after 7th day of the month (ie. if the 1st is a thursday     and extract(day from date_column)<15 # and before the 15th (ie. if the 1st is a friday, so the first thursday is on the 7th, and the second is on the 14th) 	0.000293143795789592
8863651	23454	select users from database	select user.username, usertype.usertype   from user, usertype   where user.usertypeid = usertype.usertypeid     and usertype.role = 'user' 	0.00384422448890739
8864529	5184	how to select newest record from two tables sql?	select top 1 * from  (     select * from table_1     union all     select * from table_2 )  as all_records order by date desc 	0
8868504	1857	is there some way to select the first table without writing all the fields names in the query?	select distinct t1.* from t1 join t2 on condition 	0
8869369	39048	mysql get minutes between a datetime and now()	select unix_timestamp() - unix_timestamp(datetime_col) 	0.000216376911070616
8869988	29528	taking difference of tables	select t1.* from t1 left join t2 using (a, b) where t2.a is null 	0.016564532124134
8870178	33892	union of two table - intersection of two table	select   a, b from   (select a, b from table1    union all    select a, b from table2)   as combined group by   a, b having     count(*) = 1 order by a; 	0.000116421906157042
8873506	7770	mysql - getting information from four tables in one query	select s.id, group_concat(u.name separator ', ') as users, count(p.*) as product_count from stores s join city c on s.city_id = c.id join store_managers sm on sm.store_id = s.id join users u on u.id = sm.user_id join products p on p.store_id = s.id where s.owner_id = ? group by s.id 	0.000427111594060913
8874483	27034	mysql search between date and time	select catsid,id,dates,times,endtimes,published,title    from jos_eventlist_events    where catsid = 6 and published = 1     and (concat(dates, ' ', times)>= now()            or (     concat(dates, ' ', times) < now()                and concat(enddates, ' ', endtimes) >= now() ) )   order by concat(dates, ' ', times)   limit 1 	0.0144586241939589
8875426	7184	mysql two tables count and display	select  kategoria.name,          count(ogloszenie.id_kat) as icount from    kategoria left join ogloszenie         on kategoria.id_kat = ogloszenie.id_kat group by  kategoria.name 	0.000644517392085643
8876159	23442	rows of csvs in sql into table of columns	select substring(item, 1,         charindex(',', item) - 1     ) as field1, substring(item, charindex(',', item) + 1,         len(item) - charindex(',', item)     ) as field2 from a 	0
8877496	35867	sql join two tables with different number of rows and copy the results	select    l.languageid,   l.name,   p.productid,   p.name as productname from language l cross join product p 	0
8878354	2455	ranking joint positions in mysql	select userid, score,  (select count(distinct u2.score) from fschema.mytab3 u2  where  u2.score > u1.score) + 1 as position from fschema.mytab3 u1 order by position 	0.520512241894833
8878402	23199	sql query that returns aggregate and non aggregate results	select s.name      , s.weight      , ((s.weight/st.avgweight) * 100) as weight_apgaw      , ((s.height/st.avgheight) * 100) as weight_aphei from student s  join (    select grp_id         , avg(weight) as avgweight         , avg(height) as avgheight    from student    group by grp_id    ) st on s.grp_id = st.grp_id 	0.793476433722806
8878743	13160	sqlite: combine date column & time column	select datetime(d, t) from (   select date('now') as d, time('now') as t) as dt; 	0.000923150545760296
8880720	20915	is it possible to query order by on a number stored as string in the database to get data as numbers in descending order	select * from article order by cast(numbers as signed) desc; 	7.58665458309579e-05
8881713	38723	how to select values from two different tables in sql 	select test1.surname, test2.class, test2.medium from test1  inner join test2 on test1.regno = test2.regno 	0.000160310835916337
8883044	14508	get information about table valued function	select *  from information_schema.routine_columns  where table_name = 'yourtablevaluedfunctionname' 	0.781628598343256
8885100	21462	mysql check if value exist  in row, separated by minus	select *    from products   where concat('-',accessories) like '%-2-%'    limit 0 , 30 	0.000235938900017274
8885793	31476	how can i get the max value within a max value in mysql?	select id from cycles order by cycle_number desc , cycle_day desc limit 0 , 1 	0
8887321	17863	creating database relationship programmatically	select [db1].[dbo].[table1].*, [db2].[dbo].[table2].* from [db1].[dbo].[table1] left outer join [db2].[dbo].[table2] on [db1].[dbo].[table1].[field_in_db1_table1] = [db2].[dbo].[table2].[field_in_db2_table2] 	0.658651339895599
8888390	15478	how to select sum -or- 0 if no records exist?	select coalesce(sum(num), 0) as val from tab where descr like "%greetings%"; 	0.00372973030244047
8891060	35163	mysql select last 3 rows, order by asc	select *  from (select * from comments       where postid='$id'          and state='0'        order by id desc        limit 3) t order by id asc; 	0.000297305602839697
8892582	9687	how to insert master/detail record in sql server?	select * into dbo.onetable from production.anothertable 	0.033832948043015
8892718	24425	mysql query to select from multiple tables, order by date, different table structures	select po.*, ph.* from posts po left join photos ph     on po.toid = ph.userid where po.state = 0   and ph.state = 0 order by po.id desc, ph.date desc 	5.96812342767502e-05
8894097	40298	add single record on top of sql query	select id, name from  (   select null as id, 'select' as name   union all   select id, name   from prototype ) as t   order by case when id is null then 0 else 1 end, name 	0.000254629240306881
8894712	26586	count parent rows that have children	select count(distinct tablea.id) as count from (tablea) join tableb on tableb.tablea_id = tablea.id 	4.60475756414625e-05
8895394	7497	build league table and show position	select * from   (select row_number() over (order by total desc) as position,            userid,            total    from your_table) p where p.position between desiredid-2 and desiredid+2 	0.0371324327422465
8895675	32492	group by select that returns only groups with updated rows	select distinct c.company_fk, c.year, c.month, b.amount from postings c inner join (select company_fk, year, month, sum(amount) as 'amount' from postings group by company_fk, year, month) b on c.company_fk = b.company_fk and c.year = b.year and c.month = b.month where c.handled = 0 	9.50292691105359e-05
8895892	22710	connecting multiple database and join query across database in php	select     c.customer_name,     o.order_date from     db1.tbl_customers c left join     db2.tbl_orders o on o.customer_id = c.id 	0.167470500743016
8895927	28702	selecting/casting output as integer in sql	select    cast(sum(number)/count(number) as unsigned) as average,    date  from stats  where *  group by date 	0.653878310387721
8895965	22315	reading from one table to get a field and then using that field info to query and get information from another field takes a long time	select p.address, c.name, c.phone from property p join clients c on p.client_id = c.id where p.propertytype = 'house' 	0
8896663	12537	a way to extract from a datetime value data without seconds	select  cast(convert(char(16),'2011-11-22 12:14',113) as datetime) 	0
8898059	14973	error while trying to test if a specific table exists in a mysql database using jdbc	select count(*) from information_schema.tables where information_schema.table_schema='your_schema' and information_schema.table_name='basestations'; 	0.483886363069733
8898545	38700	order a result set in unnatural order	select * from units order by   case when unittype = 0 then 1        when unittype = 1 then 3        else 2 end 	0.237596790696682
8901161	37325	convert a sql server datetime to a shorter date format	select convert(varchar(10), getdate(), 103)  	0.027889633752468
8903702	1073	is there a number wilcard in mysql?	select * from table where title regexp '.*- h[0-9]+' 	0.102273404330119
8904208	28391	sql: help using group by (or other?) to select count of unique parent+child+max(created_dt) records	select [parent],        [child],        [count],        [created_dt] from   (select [parent],                [child],                [count],                [created_dt],                row_number() over (partition by [parent], [child] order by                created_dt desc)                       as                'groupid'         from   t) a where  groupid = 1 	0.00470351478528443
8904570	1748	how to join across 3 tables when one isn't a 'main' one	select * from project_contacts c left join projects p    on c.project=p.id left join people   on c.person=people.id left join project_contact_type    on people.project_contact_type=project_contact_type.id where p.live = 1 order by p.code limit 4; 	0.00343999380687112
8904916	15500	how to fetch rows that don't match where condition in a query using sum	select condition, sum(carnivore), sum(herbivore) from (     select k.condition,         sum(iif(animaltype=3,1,0)) as carnivore,         sum(iif(animaltype=4,1,0)) as herbivore     from animals a inner join knownconditions k on a.id = k.id     where a.id in (3, 11, 12)     and (animaltype=3 or animaltype = 4)     group by k.condition, a.id, k.id     union     select condition, 0, 0     from knownconditions ) group by condition 	0.000200666085809141
8905055	26951	select records from a table where all other records with same foreign key have a certain value	select item_id     from yourtable     group by item_id     having sum(case when status='a' then 1 else 0 end) = count(1) 	0
8905219	35856	how to display one rows from the two rows	select     t1.period     , t1.id     , t2n.value [not]     , t2h.value [hot]     , t1.total from     table1 t1     left join table2 t2n         on t1.period = t2n.period         and t1.id = t2n.id         and t2n.type = 'not'     left join table2 t2h         on t1.period = t2h.period         and t1.id = t2h.id         and t2h.type = 'hot' 	0
8906066	11697	mysql query to retrieve values using if statement	select       sum( if( inv.from_ledger = 1, inv.inv_amt, 0 )) as frominvoiceamounts,       sum( if( inv.to_ledger = 1, inv.inv_amt, 0 )) as toinvoiceamounts    from       hrmanager.invoice inv    where           1 in ( inv.from_ledger, inv.to_ledger )       and inv.inv_date between '1900-12-20' and '2012-01-30'       and inv.active = 'y'       and inv.comp_id = 2       and inv.inv_type = 'client' 	0.0278897843624453
8906154	32479	mysql select mutual friends	select a.friendid from       ( select case when userid = $id                       then userid2                        else userid                 end as friendid          from friends          where userid = $id or userid2 = $id       ) a   join       ( select case when userid = $session                       then userid2                        else userid                 end as friendid          from friends          where userid = $session or userid2 = $session       ) b     on b.friendid = a.friendid 	0.0225785133256425
8906596	14916	mysql query for parent child	select * from mytable where parent in (select child from parent where parent=1) or parent = 1 	0.0246165157023086
8907056	16246	order by clause in union all sql query	select   id,bill_typeid,cust_id,name,reg_date,account_number,amount,status   from  (   select id,bill_typeid,cust_id,name,reg_date,account_number,amount,status from cust_bill_reg_m_tbl    union all   select id,bill_typeid,cust_id,name,reg_date,account_number,amount,status from rail_ticket_booking_m_tbl   ) tmp order by convert(datetime, reg_date, 101) desc 	0.58322156783024
8907918	36815	sql: select number of records	select count(*) from items where item_subtype_id=1; 	0.000765831746867786
8908089	11603	selecting entire table when selecting columns - how	select col1,        col4,        col7,        table1.*,        col9  from (joined tables including table1) 	0
8909677	30468	mysql reuse virtual row	select   id,   name,   @ms1:=(salary+1) as ms1,   (@ms1-20) as ms2 from test_table; 	0.00944948686096659
8912434	25744	select from duplicated rows the biggest one	select id, max(second_col) from table group by id 	0
8913911	27707	query to calculate partial labor hours	select id, minutes - case when inminutes < 0 then 0 else inminutes end as totalmins from ( select id, case when datediff(mi,'8:00pm',outtime) >60 then 60 else datediff(mi,'8:00pm',outtime) end as minutes, case when datediff(mi,'8:00pm',intime) >60 then 60 else datediff(mi,'8:00pm',intime) end as inminutes from testhours ) xx 	0.00091841419220278
8915784	24177	how to get values of several fields in a select inside a stored procedure	select           f1,f2    into            p_f1,p_f2   from           t1   limit 1; 	0.000715219907373011
8916992	16152	sql many-to-many composite key link table join	select evententryid, evententrysource  from link_computers_evententries where computerid=1  	0.179026269854476
8917801	5454	mysql join 3rd table	select t2.name as username, t2.id as userid,             t2.lastactivity as lastactivity, t2.photo as avatar,t3.*     from exchange as t2       inner join          ( select (case when `buddy`.`penpala` = 887                           then `buddy`.`penpalb`                           else `buddy`.`penpala`                    end) as 'friend'           from `buddy`           where status = 1 and `penpala` = 887              or `penpalb` = 887         ) as _temp          on _temp.friend = t2.`id`      left join details t3 on _temp.friend=t3.userid 	0.142600467994738
8920165	38366	merging boolean results from different rows into single row	select searchid,         cast(case when sum(cast(bool1 as int)) > 0 then 1 else 0 end as bit) as bool1,        cast(case when sum(cast(bool2 as int)) > 0 then 1 else 0 end as bit) as bool2,        cast(case when sum(cast(bool3 as int)) > 0 then 1 else 0 end as bit) as bool3 from table group by searchid 	0
8920577	10427	getting nested unread messages from within a message thread	select  mt.id as thread_id,  mt.company_id, case when m_c.m_unread is not null then m_c.m_unread else 0 end as unread from message_threads as mt left join  (    select   thread_id,   count(*) as m_unread   from messages   where   is_read ='n'   group by 1 )m_c on mt.thread_id = m_c.thread_id 	0.0439150215555632
8922493	37388	how to find minimum value not in a integer field	select  val + 1 from    mytable t1 where   not exists         (select null from mytable t2 where t2.val = t1.val + 1) order by val limit 1 	0.000151114534107268
8923743	26113	joining a table with a list	select t.code, count(mytable.unique_id) from    (   select 'uxt8' as code union    select 'u61j' as code union    select 'u61w' as code union    select 'u62u' as code union    select 'x82u' as code union    select 'u5nf' as code union    select 'u635' as code union    select 'u526' as code union    select '28fx' as code   ) as t   left outer join mytable on t.code = mytable.key_field  group by t.code  order by t.code; 	0.00951449332080833
8924156	581	mysql inverse text search from two tables	select keyword from a where keyword not in    (select a.keyword from a     inner join b on a.keyword like '%' + b.keyword + '%') 	0.0141484377166289
8924899	35099	query order by count	select count(name) as total, id, name from table_name group by name    order by count(name) desc; 	0.349740675344516
8926134	7437	selecting all dates from a table within a date range and including 1 row per empty date	select      dt.tempdate ,     instructorid,           eventstart,      eventend,               cancelled,      cancelledinstructor,      eventtype,              devname,      room,                   simlocation,      classlocation,          event,      duration,               trainingdesc,      crew,                   notes,      lastamended,            instlastamended,      changeacknowledged,     type,      othertype,              othertypedesc,      coursetype  from    @datestbl dt  left outer join   opsinstructoreventsview iv     on  iv.eventstart >= dt.tempdate     and iv.eventstart <  dt.tempdate + 1     and iv.instructorid = @instructorid  where       dt.tempdate >= @startdate   and dt.tempdate <= @enddate order by   dt.tempdate,   iv.eventstart 	0
8928951	36941	how can i query a database for the last entry for each user on a given day with constraints?	select l.user, l.dateandtime, l.msg     from log l         inner join (select user, max(dateandtime) as maxdatetime                         from log                         where msg in ('off', 'on', 'sleep', 'wake')                             and logdate = '2011-12-31'                         group by user) q             on l.user = q.user                 and l.dateandtime = q.maxdatetime     where l.msg in ('off', 'on', 'sleep', 'wake')     order by l.user asc 	0
8930140	17864	mysql & unix timestamp query	select *, unix_timestamp(datetime) as end_datestamp  from `news`  where `datetime` > now() 	0.0253242944764794
8931054	34079	getting sum from 2 different tables into one result	select unit_no, totalrte, totalldsrte from (     select unit_no,sum(rateb) as totalrte      from loads      group by unit_no ) as tbl1 join (     select ss_num, sum(rateb) as totalldsrte     from loads     group by ss_num ) as tbl2     on tbl1.unit_no = tbl2.ss_num 	0
8931449	5083	matching and returning rows in php and mysql	select users.uid, groups.gid, groups.grpname from users inner join grouplink on users.uid = grouplink.uid inner join groups on grouplink.gid = groups.gid 	0.00955905972320212
8932410	11426	"flexible" mysql limit	select whatever from comments_table c where c.id in (select id from comments_table c2 where some_criteria_here limit 10) or c.parent_id in (select id from comments_table c2 where some_criteria_here limit 10) 	0.56869616655541
8933852	26237	sql stored procedure combine result	select 'acr'      as study,         somefield as availability from sometable1 union all  select 'fos'      as study,         somefield as availability from sometable2; 	0.393269234958062
8933854	12037	postgresql join 2 rows into 1 row	select t1.name as name,        t1.sum1 as r1_sum1,        t1.sum2 as r1_sum2,        t2.sum1 as r2_sum1,        t2.sum2 as r2_sum2   from insert_table_name_here as t1   full  outer   join insert_table_name_here as t2     on t1.name = t2.name    and t1.read = 1    and t2.read = 2 ; 	0.000373089149836919
8934029	23901	sql order by posts containing occurences of string in another table	select top 10 * from (     select tag,count(tag) as total     from tags t     join posts p on p.post like '%' + t.tag + '%'     group by tags ) totals order by total desc 	0
8934538	38609	mysql query based on length of string in a column	select *     from table     where length(rtrim(word)) = 6 	0.000318794499234281
8936553	41048	specify position and character in nvarchar column	select *  from shipment_info where dt_order >= '10/01/2010'     and substring(st_req_no, 11, 1) in ('g', 'w') order by dt_order 	0.0738750531667207
8937425	30415	how to display in a bounded datagridview a field from another table related to the bounded table?	select nid,nroleid,cmodulename,caccess  from tblaccess inner join tblmodule      on tblaccess.nmoduleid = tblmodule.nmoduleid 	0
8940356	4302	counting occurences of distinct multiple columns in sql	select city, country, count(*) from usertable group by city, country 	0.000222776933012875
8940532	20454	mysql maths based query	select * from firearms order by (dmg * (60/timer)) desc 	0.0955998614496394
8941420	36312	sql select statement check condition	select id, name from table where id=@id if (@@rowcount = 0)     select qty from table where id=@id 	0.357233424001464
8941567	20170	sql/rails find records where zero associated records are in a given state	select * from projects where id not in (     select project_id     from people_projects     where state in ('interested', 'left', 'kicked') ) 	0
8943490	19776	php & mysql - preg_match and query	select yourfield from yourtable where yourfield regexp '(!!|!sometext)' 	0.795874482519859
8943548	15989	how do i compare 2 rows from the same table (oracle 11g)	select id , column1 , column2 , ... column30 , count(*) from test group by id , column1 , column2 , ... column30 having count(*) > 1 ; 	0
8944584	2183	how to make this cumulative sales query span all 24 hours	select   calendar.date,   hours.hour,   sum(salesbyhour.sales)                                                        as cumulativesales,   max(case when salesbyhour.hour = hours.hour then sales.sales else null end)   as sales from   calendar cross join   hours left join   salesbyhour     on  salesbyhour.businessdate = calendar.date     and salesbyhour.hour        <= hours.hour group by   calendar.date,   hours.hour 	6.19595973011158e-05
8945816	6284	sql - return data from a column using 2 different ids	select users.user_id, friends.user_id as friend_user_id ... 	0
8946688	24392	select statement of a table sql 2008	select [1] as a1,        [2] as a2,        [3] as a3 from t pivot (max(val) for j in ([1],[2],[3])) as p 	0.14756295274324
8947980	4236	sql max date with where in clause	select p.projname, d.update_date, sum(e.pass), sum(e.fail)   from execution as e inner join (      daily as d inner join project as p on d.project_id = p.id )     on e.daily_id = d.id   where d.project_id in (25,26,28,29,30,31) and d.update_date = (      select max(update_date) from daily where project_id = d.project_id)   group by p.projname, d.update_date; 	0.528836864350528
8950586	1004	mysql query - select bottom n records	select column_name from table_name order by id desc limit 5; 	0.000854084192050625
8950986	4739	doctrine 2.1 dql - many-to-many query multiple values - item in multiple categories?	select j, t from entity\item j left join j.itemimages t where ?0 member of j.categories and ?1 member of j.categories and ?2 member of j.categories, etc. 	0.0153765315146641
8951932	9083	compare date and value related to id	select user.id             as user_id      , max(sc_now.score)   as score_now      , max(sc_prev.score)  as score_previous from user    join request as req_now     on  req_now.user_id = user.id      and req_now.date > (week unix ts)       join score as sc_now     on sc_now.request_id = req_now.id    join request as req_prev     on  req_prev.user_id = user.id      and req_prev.date between ? and ?       join score as sc_prev     on sc_prev.request_id = req_prev.id  group by user.id having max(sc_now.score) > max(sc_prev.score) 	0
8958237	5545	how to get the largest value from a table in mysql?	select * from table where length(column) = ( select max(length(column)) from table ) 	0
8958610	22112	join to same table several times in a single query?	select        t1.field,       t1.name,       t1.value as thisisyourparentkey,       t2.name as parentname,       t2.value as grandparentkey    from       yourtable t1          left join yourtable t2             on t1.value = t2.field    where       t1.name = 'a2' 	0.000440866417985726
8958718	25925	restricting sub-query to 2 arguments in same row	select i.* from subscriptions s join items i on i.crit1 = s.crit1 and i.crit2 = s.crit2 where s.user_id = 1 	0.00815295038007816
8959561	4420	calculations in a sql query	select empno, ename, job, sal,        comm,        sal * 25 / 100 as [house rent],        sal * 15 / 100 as [medical allowance],         sal * 10 / 100 as [transport allowance],        sal + comm + (sal  * (25 + 15 + 10) / 100) as net from emp 	0.562115691300095
8960360	5344	mysql query return only if number of rows is more than zero	select photos.photo  from albums inner join photos on albums.photoid = photos.id  inner join albumdata on albumdata.id = albums.albumid where albums.userid = '$id'    and albums.albumid = $albumid    and albumdata.state = '0' order by photos.id desc limit 6; 	0
8961148	16969	mysql match against when searching e-mail addresses	select * from addresses where match(email) against('"name@example.com"' in boolean mode) 	0.195598056755526
8961710	18499	how to check how many users has registered in one week	select count(*) from users  where to_days(now()) - to_days(`date_registered`) <= 7 	0
8969370	23299	sql server : concat or multiple select queries in gridview?	select c.contactid, convert(varchar(max), (                   select ct.contacttypedescription+ ', '                   from   contacttypes ct                   join contacts c1 on  ct.contactid = c1.contactid                     for xml path('')             )) as contacttypes, *              from contacts c 	0.697805495648565
8969780	40608	sum and average	select id, avg(diff)/60  from yourtable group by id 	0.0102163898831184
8969869	33274	how to split a column in two and display in two separate columns base on the conditions?	select left(col1, charindex(':-', col1)),        right(col1, len(col1) - charindex(':-', col1) - 1) 	0
8974048	9862	sql server correct way to account for the weekend	select * from table where date = (case   when datename(dw, getdate()) = 'friday' then     convert(varchar, dateadd(day, 7, dateadd(dd, 0, datediff(dd, 0,getdate()))), 103)      + ',' + convert(varchar, dateadd(day, 9, dateadd(dd, 0, datediff(dd, 0,getdate()))), 103)   else     convert(varchar, dateadd(day, 7, dateadd(dd, 0, datediff(dd, 0,getdate()))), 103)   end) 	0.26398145437873
8975321	34522	row count differs when using date and datetime	select * from table_name  where sample_timestamp >= unix_timestamp('2012-01-01')*1000  and sample_timestamp < unix_timestamp('2012-01-06')*1000 	0.00511751152118597
8975810	28178	sql unique multi column w/ distinct third column query	select a.columna from tablename a inner join (select columnb, columnc from tablename group by columnb, columnc having count(distinct columnd) > 1) b on a.columnb = b.columnb and a.columnc = b.columnc 	0.00941135871018937
8976925	31009	select statement in sqlite recognizing row number	select * from table limit 10 offset 0 	0.0183948077806085
8979763	2287	finding the difference in two mysql tables that should be identical	select t1.* from table1 t1 left join table2 t2   on t1.id = t2.id where t2.id is null 	0.000907028597484887
8982099	7892	does row exist and multiple where	select distinct m1.id  from metadata m1 where      m1.meta_key = 'school'  and m1.meta_value = 'some school 1'  and not exists  (   select * from metadata m2   where        m2.meta_key = 'hidden'    and m2.meta_value = '1'   and m2.id = m1.id ) 	0.158730153934237
8983823	25954	how to display last 3 recently stored items in sqlite database - iphone	select      whatever from        mytable order by    auto_inc_column desc limit       3 	0
8984147	26829	how to find the a and b where b value can be a value using mysql	select table_o.total      from <your_table> as table_i          left join <your_table> as table_o on table_i.a = table_o.b where table_i.b = ? 	6.32749636044365e-05
8984792	36368	oracle object types & object tables	select ot.table_name, tt.type_name   from ( select t.type_name,        connect_by_root t.supertype_name rkey   from user_types t connect by prior t.type_name = t.supertype_name ) tt,        user_object_tables ot        where ot.table_type = tt.type_name or ot.table_type = rkey 	0.175168351442106
8987392	3757	removing nested part from a select query	select distinct adata.* from  `audit` as adata inner join `audit` as aselector on adata.event_id=aselector.event_id where   adata.action_performed = 'rejected'   and aselector.username = 'someuser'    and aselector.action_performed in ('submitted_for_approval', 'saved_and_approved')   and aselector.action_timestamp >= '2012-01-12 00:00:00'   and aselector.action_timestamp <= '2012-01-24 23:59:59' ; 	0.152781183885335
8987733	18648	how to get neighboured elements in a many to many table?	select p2.* from people p1   join pople_to_favorite_food pf1     on pf1.people_id = p1.people_id   join favorite_food f1     on f1.food_id = pf1.food_id   join pople_to_favorite_food pf2     on pf2.food_id = f1.food_id   join people p2     on p2.people_id = pf2.people_id where   p1.name = 'bob' group by   p2.people_id; 	0.00018687916901163
8992568	25778	categorize a list of names from database	select * from t where name >= 'g' and name < 'm' order by name 	6.76623627178716e-05
8993063	20219	get data from three table sql	select    images.*,    users.username from images left join users on images.user_id = users.id left join user_follow on images.user_id = user_follow.follow_id where images.user_id = 3 or user_follow.user_id = 3 order by images.date desc 	0.00057396115639939
8993152	36456	select id where all user id match	select fk_conversation from my_table where fk_user in ( array values ) and fk_conversation in (     select fk_conversation     from my_table     group by fk_conversation having count(distinct fk_user) = array size ) group by fk_conversation having count(distinct fk_user) = array size; 	5.0128121095198e-05
8993647	16991	boolean logic in a group by part of a mysql query	select id, firstname, lastname, homephone, cellphone, city, state, zip, country from customers where homephone != '' or cellphone != '' group by case when homephone = '' then cellphone else homephone end 	0.425073243545567
8994872	7176	merging two different arrays from two different mysql queries	select * from searches_view where ... union select * from favorites_view where ... order by date_submitted desc 	0
8995073	22978	getting highest values in a data set	select id, speed from (   select     if(speed<@speed,@id,0) as id,     if(speed<@speed,@id:=0,@id:=id) as ignoreme,     @speed:=speed as speed   from     (select @speed:=0) as initspeed,     (select @id:=0) as initid,     yourtable   where ... ) as baseview where id>0 	0.000120839480675492
8995655	41009	select time range from unix-timestamp	select *     from table     where date_add( from_unixtime( timestamp ) , interval datediff( now( ) , from_unixtime( timestamp ) ) day )     between date_sub( now( ) , interval (span/2) hour )     and date_add( now( ) , interval (span/2) hour )     or date_add( from_unixtime( timestamp ) , interval datediff( now( ) , from_unixtime( timestamp ) ) -1 day )     between date_sub( now( ) , interval (span/2) hour )     and date_add( now( ) , interval (span/2) hour ) 	0.00129197394019484
8997330	36428	problems to get the full date info from oracle db (dd/mm/yyyy hh/mm/ss)	select ... where datefield >= :lowerparam and datefield < :upperparam 	0.000805933093362774
8998345	38625	how can have extra column from each table with union query in mysql?	select t1id, t2id, t1.date, t1.date, t1.barcode from t1 inner join t2 on t1.date = t2.date and t1.time = t2.time and t1.barcode = t2.barcode 	7.67807347611847e-05
8999337	37689	using limit clause along with union all or selecting top 2 and last 3 results 	select * from (     select *      from tbl_product     order by pd_price asc     limit 2 ) tbl1 union all select * from (     select * from (         select *          from tbl_product         order by pd_price desc         limit 3     ) tbl_a     order by pd_price asc ) tbl2 	4.54264642387165e-05
9001315	15936	sqlite "in" expression on multiple columns	select   a.name, a.surname, b.name, p.name, c.comment  from   authors                a   inner join authorship ab on ab.author_id = a.id   inner join books       b on b.id         = ab.book_id   inner join publishment p on p.book_id    = b.book_id   inner join copies      c on c.publish_id = p.id 	0.121126057063252
9001679	22772	how to find the difference between joining date and current date of and employee	select datediff(datepart, joindate, getdate()) as timeinservice from employee 	0
9002418	39920	changing multiple column names in a mysql table	select     concat(            'alter table ', c.table_name, ' change ',             c.column_name, ' ', replace(c.column_name, 'field_t', 'field_c')            ) from     information_schema.columns c where     c.column_name like 'field[_]t[_]%'; 	0.000773002216177246
9002597	16989	how to get the mm-dd-yyyy format	select convert(varchar, getdate(), 110) 	0.00219366102431152
9002740	9017	how to fetch from mysql something that has date for this week (from this monday till sunday)	select * from table_name where yearweek(date_column) = yearweek(now()) 	0
9003058	27104	display only the first row per match	select yourtable.area, yourtable.name from yourtable inner join (   select min(id) as minid   from yourtable   group by area) m on yourtable.id = m.minid 	0
9004228	9947	row order in table depending on relative table	select v.*, v2.numhits from (     select videoid, count(id) 'numhits' from lol_hits group by videoid ) as v2  join lol_videos v on (v.id = v2.videoid) order by v2.numhits desc; 	7.86617332101975e-05
9004492	23788	querying where date_created without time is same as last_updated without time	select * from table_name where date(date_created) = date(last_updated) 	0.028550781117249
9005992	21381	sql select column equivalence	select t1.tableid as tableid1,     t1.statevalue as statevalue1,     t2.tableid as tableid2,     t2.statevalue as statevalue2,     t1.statedefinition   from mytable t1 inner join mytable t2 on t1.tableid = 1 and t2.tableid = 2 where t1.statevalue = t2.statevalue      and t1.statedefinition  = t2.statedefinition 	0.154684159359535
9006443	2495	how to determine sql server 2008 or above	select    parsename(cast(serverproperty('productversion') as varchar(20)), 3) as majorversion,     value_in_use from     sys.configurations where    name = 'clr enabled'; 	0.558173704283931
9008539	33144	limit results in mysql?	select *  from events  where event_type = 'christmas listings' and event_active='yes'  order by event_date  limit 0, 5 	0.312230553173692
9009435	17437	how to find a value within a minimum and and a maximum in sql server	select * from salaries where @salary between minsalary and maxsalary 	0
9010136	15729	mysql random from top 10	select * from (    select * from bigtable     where column1='1'     order by column2 desc limit 10 ) t order by rand()  limit 1 	0.000432353687077824
9010176	16663	banding a date range in oracle	select a.a_field, to_char(add_months(a.start_date,r), 'mon-yy') as display_month from my_table a, (     select rownum-1 r      from all_objects     where rownum <= 200) b where add_months(trunc(a.start_date,'mm'),r) <= trunc(a.end_date,'mm') order by a_field, b.r 	0.0146264840701676
9010535	5964	selecting date from a table where the column variable type is varchar in sql	select convert(date, column1) as date from table1 where convert(date, column1) < '01/25/2011' and date is not null and date <> '' 	0.000133958706363719
9011293	36299	getting users based on group, but users, user_groups and groups kept in separate tables	select users.* from users join users_groups on (users.id=users_groups.user_id) where users_groups.group_id = 2 	0
9011783	8075	select this or that but not both	select abunchofstuff, isnull(r.xyz, r2.xyz) as netsell from normalmtm n join mtmprogram m on (    m.mtmprogram = n.loanprogram    and m.investor = 'xyzzy' ) left outer join rates as r on (     r.term >= '2012-01-01'     and r.investor = m.investor     and r.rate = n.rate     and r.program = m.basenormal     and r.clientcode = n.clientcode ) left outer join rates as r2 on (     r2.term >= '2012-01-01'     and r2.investor = m.investor     and r2.rate = n.rate     and r2.program = m.basenormal     and r2.clientcode = 0 ) left outer join mtmadjustments as ad on (     ad.loannumber = n.loannumber     and ad.investor = m.investor ) where n.loannumber = '12345678' and n.clientcode = 10 order by netsell desc limit 1 	0.790610683219775
9012613	22109	sql query to group multiple groups	select       case when cs(user-agent) like "%android%" then "android"            when cs(user-agent) like "%black%" then "blackberry"            when cs(user-agent) like "%windows%" then "windows"            when cs(user-agent) like "%iphone%" then "iphone"            else "other" end as browser,       count(*) as totalhits    from       yourtable.logfile    group by       browser    order by       totalhits desc 	0.125095600985936
9015568	4594	except condition in mysql query..	select name, price, color, vehicletype from carrecords where (vehicletype = 'sedan' and color  = 'black' and price <= 10000) or (vehicletype = 'sedan' and color in('red','white') and price <= 8000 ) or (vehicletype = 'suv' and color  = 'black' and price <= 15000) or (vehicletype = 'suv' and color  != 'black' and price <= 14000) or (price <= 7000) order by price asc 	0.388783699284693
9016578	25918	how to get primary key column in oracle?	select cols.table_name, cols.column_name, cols.position, cons.status, cons.owner from all_constraints cons, all_cons_columns cols where cols.table_name = 'table_name' and cons.constraint_type = 'p' and cons.constraint_name = cols.constraint_name and cons.owner = cols.owner order by cols.table_name, cols.position; 	0.00112830477053067
9020986	18164	calculate interval based on identifiers	select id,cat,max(realtime)-min(realtime) as interval from table group by 1,2; 	0.00101174136751864
9021127	29566	insert unique prng into db column	select @max := max( randomid ) from products; update products set randomid = @max := @max + rand() + 1; 	0.00252561247758526
9021440	14489	rows not ordered properly with group by	select userid,max(num) num from (select userid,substring_index(substring_index(data, '\"!', -1), '!\"', 1)+0 as num   from table  where type=2) a group by userid; 	0.418454913703139
9022528	405	sql oracle get data with more of one associated data	select cod_1 from tablename group by cod_1 having count(*) > 1 	0.000161065519500815
9023541	9399	how to replace text in a field for a dataset based on a condition- sql server	select      left(filename,len(filename)-16) as 'filename',     filecontent = case           when left(filename,len(filename)-16) = 'abc' then 'file is fubar'          when left(filename,len(filename)-16) = 'xyz' then 'file is hosed'          else 'file is good!'     end,     right(left(filename, len(filename) - 8), 8) as 'currentdate' from errorlogs  where       filecontent like '%error%'      and right(left(filename, len(filename) - 8), 8) =               replace(convert(varchar(10), getdate(), 102), '.', '') order by      filename asc 	0.000716537514941328
9024291	32978	dynamic sql columns	select laborcode,     sum(case when tag = '' then hours end) as regular,     sum(case when tag = 'vacation' then hours end) as vacation,     sum(case when tag = 'personal' then hours end) as personal,     sum(othours) as overtime from labortransaction  group by laborcode 	0.174625743360839
9025622	17018	parse datetime parameter	select id      from database      where datepart(yy, added) = datepart(yy, @p1)       and  datepart(mm, added) = datepart(mm, @p1)       and datepart(dd, added) = datepart(dd, @p1) 	0.535246557042228
9025650	16117	how to retrieve data from different rows of the same table based on different criteria	select r.name request_name,        sum( (case when l.taskid = 0                    then l.enddate - l.startdate                   else 0                end) ) task0_time_spent,        sum( (case when l.taskid = 1                    then l.enddate - l.startdate                   else 0                end) ) task1_time_spent,        sum( (case when l.taskid = 2                    then l.enddate - l.startdate                   else 0                end) ) task2_time_spent   from x_request_work_log l        join x_request r on (l.requestid = r.id)  group by r.name 	0
9028838	17037	logs with arbitrary numbers of entries in postgresql	select person_id,        row_number() over (partition by person_id order by row_timestamp) as row_num,        row_timestamp,        row_text from log_table 	0.00037787778998404
9030166	13011	mysql related query	select * from t1 where id = (select max(id) from t1 where status = "queued" group by status having count(status) > 2) 	0.164936063923529
9031160	35590	convert seconds to datetime in sql server	select dateadd(s, datetimeinmilliseconds, '19700101') 	0.05394640047271
9031468	3198	table with name "order" : invalid table name	select count(*)  from "order" 	0.077165289290335
9031891	6807	t-sql: single-query join with either one table or another	select  products.*,          [type],          amount from    products         inner join         (   select  productid, 'bill' [type], amount             from    bills             union all             select  productid, 'ret' [type], amount             from    returns         ) transactions             on transactions.productid = products.productid 	0.0643662489256506
9033357	40694	count columns according to dates in sql	select date, sum(counter) from all_stats group by date 	0.000463232909503438
9038980	2049	top 1 query from each id with multiple instances	select id, max(date) from [table] group by id 	0
9039363	33236	sql - using result from subquery in another subquery	select    qu.engineer_id,    qu.id as `quote_id`,   jb.author,   jb.job_id,   jb.job_title,   substring( jb.job_description, 1, 200 ) as `short_description` ,   jb.image_ref,   jb.timestamp,   count(qc.id) as comment_count from    jobs as `jb` left join quotes as `qu` on qu.job_id = jb.job_id left join quote_comments as `qc` on qu.job_id = qc.job_id where    jb.author = " . id . " group by    jb.job_id,   qu.engineer_id,   qu.id,   jb.author,   jb.job_title,   substring( jb.job_description, 1, 200 )   jb.image_ref,   jb.timestamp order by    jb.timestamp desc 	0.136038394041164
9039456	32168	how to create mysql record source for two related tables	select tblplayers.*, tblmatches.* from tblplayers left join tblmatches on ing_recordid_pk in (p1_id, p2_id) 	0.000128755682818378
9041570	24495	select posts and tags in a single query	select * from posts  left join posts_tags on posts.post_id = posts_tags.post_id left join tags on posts_tags.tag_id = tags.tag_id 	0.00103405191854985
9042560	28029	sql query to reconstruct rows of a spreadsheet from a table of cells	select  spreadsheettitle,         worksheettitle,         row,         [1] as col1,         [2] as col2 from    ( select    'spreadsheet' spreadsheettitle, 'worksheet' worksheettitle, 0 row, 1 as [columnid], 1 value            union all           select    'spreadsheet' spreadsheettitle, 'worksheet' worksheettitle, 0 row, 2 as [columnid], 2 value            union all           select    'spreadsheet2' spreadsheettitle, 'worksheet' worksheettitle, 0 row, 1 as [columnid], 3 value          ) as flat pivot     ( max(value) for [columnid] in ( [1], [2] ) ) as pivoted 	0
9043747	8260	total days difference is not showing properly	select datediff(day, convert(datetime, '01/01/2012', 103), convert(datetime, '01/02/2012', 103)) 	0.0043488706131103
9044136	34117	posts and tags - limit in join	select      p.*,     t.* from      posts as p left join     posts_tags as pt     on pt.post_id = p.post_id left join     tags as t     on t.tag_id = pt.tag_id where     p.post_id in (select post_id from post limit 0,10) 	0.0168843385512828
9044445	29377	how to check the count and based on that query	select d.dept_name, group_concat( concat(e.fname,' ',e.lname) order by e.lname  separator ',' ), from department d join employee e using(dept_id) group by dept_id having count(*) > 3; 	0.000208134207579462
9044847	24155	complex sql query from 4 tables	select  categories.name, count(distinct id_hotel) [count] from    hotels         inner join categories             on category_id = id_category         inner join         (   select  hotel_id, min(price) [lowestprice]             from    hotels_room_types                     inner join hotels_room_types_seasons                         on id_hotels_room_type = hotels_room_types_id             group by hotel_id         ) price             on price.hotel_id = hotels.id_hotel where   lowestprice between 10 and 130  group by categories.name 	0.30429041876293
9047056	41122	retrieve records where all values in related table are null	select mr.contact_id      from recipients mr  left join address a on mr.contact_id = a.contact_id   left join district_values di on a.id = di.entity_id      where mr.mid = 29  group by mr.contact_id     having count(a.*) = 0 and count(di.*) = 0 	0
9049766	31501	count data from table sql	select count(1) from user_follow where user_id in(3,6) and follow_id not in(3,6) group by follow_id 	0.00508838546329335
9050005	7422	how to prevent duplicates in an sql cross-query	select b1.beer as beer1, b2.beer as beer2, b1. price as price1, b2.price as price2 (b1.price+b2.price) as pair, b1.bar as bar from `beer`.`sells` b1, `beer`.`sells` b2 where b1.beer < b2.beer and b1.bar = b2.bar; 	0.317141892797917
9050481	28963	selecting the frequency of a result that could appear in multiple columns (sql)	select name, count(1)   from (           select name_1 as name from mytable          union all select name_2 as name from mytable          union all select name_3 as name from mytable          union all select name_4 as name from mytable          union all select name_5 as name from mytable        ) as myunion  group by name  order by count(1) desc limit 6 ; 	4.86652500883723e-05
9052815	27386	mysql: use a value from a select in the select itself	select day, @tmp:=some_crazy_expression_of(day) as testday,      expression_of(@tmp) as test2day from calendar 	0.00172689842388014
9053368	36443	in db2 how to calculate difference of adjacent rows	select name,         age,        (lag(age, 1, age) over (order by age desc)) - age as agediff from your_table order by age desc 	0.000145167401419279
9053805	9544	recover updated data - sql server 2005	select [page id],[slot id],[allocunitid],[transaction id] ,[rowlog contents 0] , [rowlog contents 1],[rowlog contents 3],[rowlog contents 4] ,[log record] from    sys.fn_dblog(null, null)    where allocunitid in  (select [allocation_unit_id] from sys.allocation_units allocunits  inner join sys.partitions partitions on (allocunits.type in (1, 3)    and partitions.hobt_id = allocunits.container_id)  or (allocunits.type = 2 and partitions.partition_id = allocunits.container_id)    where object_id=object_id('' + 'dbo.student' + ''))  and operation in ('lop_modify_row','lop_modify_columns')   and [context] in   ('lcx_heap','lcx_clustered') 	0.242947833852881
9054751	13155	php mysql join multiple table	select points.userid, points.username, points.email, sum(points.points) from (select u.*, count(*)*10 as points   from user u     join referral on u.userid = r.userid     join user verify_user on r.invemail = verify_user.email   group by u.userid, u.username, u.email union select u.*, count(*)*5 as points   from user u     join referral on u.email = r.invemail and u.userid != r.userid   group by u.userid, u.username, u.email ) as points group by points.userid, points.username, points.email 	0.18493112580729
9054912	25273	sqlite multi table selection with jquery	select column_name(s) from table_name1 inner join table_name2 on table_name1.column_name=table_name2.column_name 	0.553415522150853
9055010	6390	sql server, select a record every 'x' amount of records	select id, name, entrydate  from (select row_number over(order by id) rownumber, id, name, entrydate       from mytable) t where rownumber = 1 or rownumber % 5 = 0 	0
9055481	34056	sql query to provide me with the total number	select state, count(*) as num from table_name where gender ='male' group by state; 	0.0594363729183522
9056019	17127	compare dates by month and day only	select b_date from foos    where dayofyear(b_date) between      dayofyear('2011-01-07' - interval 10 day) and (dayofyear('2011-01-07' - interval 10 day) + 21)   or dayofyear(b_date) between      (dayofyear('2011-01-07' + interval 10 day) - 21) and dayofyear('2011-01-07' + interval 10 day)   group by foos.id; 	0
9057197	32056	retrieve username for 2 separate users on 2 separate things	select      c_name,           <     t_title,          <     t_by,             <     ut_by.username,   <     p_by,             <     up_by.username,   <     p_date,           <     count(p_id) as total_posts from     forum_categories        left join     forum_threads        on t_cat = c_id        left join     forum_posts        on p_thread = t_id        left join     users ut_by       on t_by = ut_by.id        left join     users up_by       on p_by = up_by.id where     t_cat = 1 	0
9060370	30956	difference between rows	select   c.*,   @diff:=if(@prev_km is null, 0, km - @prev_km) diff_km,   @prev_diff_km:=if(@prev_diff_km is null, 0, @prev_diff_km + @diff) total,   @prev_km:=km from   car_temp c,   (select @prev_km := null, @prev_diff_km:=null) t 	0.00226428161242187
9061344	2039	select top row of 2nd table in sql join	select users.*, comm_history.* from users inner join comm_history   on users.user_id = comm_history.user_id  left join comm_history later_history   on comm_history.user_id = later_history.user_id    and later_history.comm_date > comm_history.comm_date where later_history.user_id is null 	0.000220087679314101
9062815	23341	mysql select a field as null if not existent in table	select column_name from information_schema.columns where table_name = 'users' and table_schema = 'your-db-name'; 	0.0928619330633346
9063611	24400	sql server get date field if less than 3 month	select * from my table where addeddate>=dateadd(m, -3, getdate()) 	0
9064480	23099	order by different columns in same priority	select * from yourtable order by coalesce(modify_date, create_date) desc 	0.000243874012918011
9066498	28411	sum from rows and difference between total and rows	select tbl.*, total_values, @r:=if(@r=0, total_values, @r-tbl.`values`) as diff_values   from tbl, ( select @r:=0, sum(`values`) as total_values from tbl ) x; 	0
9068222	27107	can i do a query that has both distinct and non distinct fields in it?	select name, link from table group by name, link 	0.00281582321500925
9068577	12518	get the number of months from a date	select timestampdiff(month,your_date_column,now()) from ....; 	0
9068600	32037	sql server pivot mulitple tables	select p.classyear,         p.lastname,         p.firstname,         p.studentid,         pvt.math,         pvt.biology  from   (select sr.grade,                 si.classyear,                 si.studentid,                 si.firstname,                 silastname          from   student_info si                 inner join student_records sr                   on si.studentid = sr.studentid                 inner join course_records cr                   on sr.courseid = cr.courseid) p pivot ( avg (grade) for         coursedec in (         [math], [biology]) ) as pvt  order  by pvt.classyear; 	0.600412445014547
9069977	30275	how to include a 3rd column in the result table of a count and group by procedure	select  tp.status_name,         a.status_id,         a.total from (  select status_id, count(status_id) as total         from tbl_project inner join lkp_project_status         on tbl_project.status_id = lkp_project_status.record_id         group by status_id) a inner join tbl_project tp on a.status_id = tp.status_id 	0.000222327819539709
9070189	13147	i want to modify this sql statement to return only distinct rows of a column	select       p2.fbid,       p2.time,       c.`name` as cname,        o.`name` as oname,        u.`name`     from       ( select p1.fbid,                 min( p1.time ) firsttimeperid            from picks p1            group by p1.fbid ) as firstperid          join picks p2             on firstperid.fbid = p2.fbid            and firstperid.firsttimeperid = p2.time             left join categories c                on p2.cid = c.id             left join options o                on p2.oid = o.id             left join users u                on p2.fbid = u.fbid    order by        time desc 	0.00174473639740771
9070462	22909	sql select query - display related records in onr column	select i.invoiceid, i.date, ri.sum,     sum(r.cashtotal) over(partition by  i.invoiceid)       stuff( (select ', '+cast(recietr2.recietid as varchar(max))              from  reciet r2              where recietr2.invoiceid  = i.invoiceid              for xml path ('')            ), 1, 2, '') as recietids from invoice i left join recietinvoice ri on i.invoiceid = ri.invoiceid left join reciet r on ri.recietid = r.recietid 	0.000206846557502086
9070829	9700	sql server 2005 pivot table	select distinct          id       , class = stuff(                        cast(                             (select ', ' + cast(class as nvarchar)                               from tablename t2                               where t2.id = t1.id                               for xml path('')) as nvarchar(2000))                 ,1,2, n'') from tablename t1 	0.671110945429154
9071698	10297	sql command to group field and create new column	select date,        sum(case when url = 'facebook' then no else 0 end) as facebook,        sum(case when url = 'twitter' then no  else 0 end) as twitter,        sum(no) total,        count(distinct name) as `unique name` from       table group by       date 	0.0233569218064433
9072474	15142	time difference in sql with join	select        days     , count(*) as users from       ( select               datediff(min(s.created_at), u.created_at) as days         from                users as u           join               subscriptions  as s             on               s.user_id = u.id         group by                u.id       ) as grp group by        days 	0.149656612067916
9072869	22168	is there a way to merge these two simple queries	select      count(l.lease_id) as 'count_transactions_all',      sum(l.net_area) as 'total_area_all',     sum(case l.negotiation_type          when 'new' then 1 else 0 end)      as count_transactions_new from     lease_deal.lease l where     l.deal_approved_date >= @datefrom        and l.deal_approved_date  <= @dateto     and l.lease_status in(@leasestatus) 	0.387582379812793
9073435	29549	mysql - how do i find which of two tables has the row with a given value in a known column	select "tablea" as tablename,order_number from tablea where order_number=5 union select "tableb" as tablename,order_number from tableb where order_number=5; 	0
9073451	9677	how can i compare dates in related tables and use this to select the relevant record in a query? sql / ms access	select class.id,    max(courseversions.courseversionstartdate) as courseversionstartdate from      (course inner join class on course.courseid = class.courseid) inner join      courseversions on course.courseid = courseversions.courseid where      (((class.commencementdate) > courseversions.courseversionstartdate)) group by class.id; 	0.00133779075510355
9077329	15559	sum and compare columns from different tables and databases	select * from (select col1, sum(col2) from table1 group by col1) t1 inner join (select col1, col2 from table2) t2 on t1.col1 = t2.col1 where t1.col2 <> t2.col2 	0
9078008	37960	mysql count all records with duplicates as one record	select count(distinct main.id) from members as main  inner join subscriptions as sub on sub.member_id = main.id  where sub.status = '2' and sub.active = '1' 	0
9081440	29256	how to pass dynamic value in sql queries	select case @inputvalue         when 'a' then columna          when 'b' then columnb         else columnc     end from mytable 	0.301584558728502
9082315	437	how to select all elements of a table that match a set of ids in a crosslink table in mysql	select s.id,s.song_name from song s, tagxsong x    where s.id=x.song_id and x.tag_id in (57,58,60,63)    group by 1,2 having count(*)=4 	0
9082791	1860	sql query with sum of related table	select c.id, c.lastname from clients c join orders o on o.clientid=c.id join payments p on p.orderid=o.id where p.paymentdate >= '2011-01-01' group by c.id, c.lastname having sum(p.paymentamount) > 1000 	0.0154779339728759
9083121	7191	format date to string	select varchar_format(mydate, 'yyyy/mm/dd') from mycalendar; 	0.0243437764442591
9085118	17609	sql multiple count() from two tables, within a left join	select p.id , p.title , p.desc , p.progress , p.start , p.deadline ,     coalesce( m.cnt, 0 ) as members,    coalesce( t.cnt, 0 ) as tasks from site_projects p left join    ( select pid, count(*) as cnt from     site_project_members     group by pid ) m on p.id = m.pid left join   ( select pid, count(*) as cnt from     site_project_tasks     group by pid ) t on p.id = t.pid order by p.id asc 	0.0130146516251349
9085359	3383	mysql - in and not in within the same join	select music.id, music.name as name, music.filename, music.url_name, music.file_path_high, music.filesize, music.categories, music.duration, music.folder, tags.tag_name, music.has_versions, music.version_search_term, sum(active.weight) as total_weight from (music) inner join linked_tags as active on active.track_id = music.id and active.tag_id in (19,25)     and not exists ( select *                     from linked_tags active2                     where active2.track_id=active.track_id                     and active2.tag_id in (44,15)                   ) inner join tags on active.tag_id  = tags.id where is_version = 0 or is_version is null group by music.id having count(distinct active.tag_id)=1 order by total_weight desc limit 25 	0.0851997491179263
9085684	28039	mysql combining two tables without duplicates	select one.bibid,    two.name,    one_10.fied_data as length,   one_5.fied_data as year,   one_3.fied_data as country   from table_two two left outer join table_one one on one.bibid = two.bibid left outer join table_one one_3 on one.bibid = one_3.bibid and one_3.fieldid = 3 left outer join table_one one_5 on one.bibid = one_5.bibid and one_5.fieldid = 5 left outer join table_one one_10 on one.bibid = one_10.bibid and one_10.fieldid = 10 	0.00903416648491204
9086640	17368	calculate date interval in sql	select name      , sum(counts)      , datediff(max(date), min(date))/365 as age1        , year(max(date)) - year(min(date))  as age2   from tb group by name 	0.00836565430468377
9086938	22350	mysql: find (and display) strings that are not in a table	select 'cinéaste' as 'description' from `job` where not exists (select * from `job` where description = 'cinéaste') limit 1 	0.000104781251680393
9087088	24967	merging 2 mysql queries and ordering results by timestamp	select * from (     select col1, col2, null, null, time_stamp from table1     union     select null, null, cola, colb, time_stamp from table2 ) entries order by time_stamp desc limit $offset, $limit 	0.00445534426915322
9088919	26014	joining three tables	select m.member_id, b.brand_id, d.du_id from exp_members m, exp_brandrelations b, exp_du_mktgmats d where m.group_id = '5' and m.member_id = b.member_id and b.brand_id = d.brand_id and d.date >= date_sub(now(), interval 1 day) 	0.0453324970926632
9089260	24327	column names in mysql, or change in php?	select reallylongcolumnname as name ... 	0.0203302169755453
9089837	17567	transform sql rows into comma-separated values in oracle	select    listagg(name, ',')      within group (order by id) as list  from student 	0.00365882347726702
9090851	10452	combine data from multiple access tables to produce address label, preferring po box to physical address	select     t.poboxnumber as addrline1,    t.poboxsuburb as addrline2,    t.poboxcity as addrline3,    t.poboxpostcode as addrline4,    ""  as addrline5 from thetable t  where t.poboxnumber is not null union all select     addressbuilding as addrline1,    addressstreet as addrline2,    addresssuburb as addrline3,    addresscity as addrline4,    addresspostcode as addrline5 from thetable t  where t.poboxnumber is null 	0.0022375811079056
9094769	19502	using substring and stuff together	select stuff( (     select         ',',         cast(rating as varchar)     from product_reviews     where product_id = 8995     for xml path('') ), 1, 1, '') 	0.702334846529754
9095417	5936	how do you get columns in mysql that has no word greater than 40 characters?	select message from messages where message not regexp '[[:alnum:]]{41}' order by msg_id desc limit $postnum, 1 	0
9096034	22155	tsql -eliminating duplicates from resultset and combining them in a single row	select    id, name,     max(primaryemail1) as primaryemail1,    max(primaryemail2) as primaryemail2,     max(primaryemail3) as primaryemail3 from    employee  group by    id, name 	0.00010525892241957
9098079	38662	returning the number of records and ignoring duplicates in mysql / php	select count(*)                             as distinctclicks      , count(distinct ipaddress)            as distinctipaddresses      , count(distinct browser)              as distinctbrowsers      , count(distinct ipaddress, browser)   as distinctusers       from jb_statistics where month='$month' 	0.000259800178096778
9098252	8908	why are sql server week numbers different to java week numbers?	select datepart(iso_week, '01/01/2012') 	5.87830164932107e-05
9098518	4714	select columns from different tables, without creating a combination of different rows?	select b.val1, b.val1, c.val2 from tablea a inner join (select row_number() over () as rownumber, col1 as val1 from tablea) on a.col1 = b.val1 inner join (select row_number() over () as rownumber, col2 as val2 from tableb) c on c.rownumber = b.rownumber 	0
9100359	32607	select rows where id is not linked to user in separate table	select id from cases c where not exists (     select * from links l where l.case_id = c.id and l.user_id = @userid) 	0.000339587751373556
9101285	3864	sql select from multiple tables where name contains query	select name, description     from tablea     where name like '%yoursearch%' union all select name, description     from tableb     where name like '%yoursearch%' union all select name, description     from tablec     where name like '%yoursearch%' 	0.00607574317187015
9101504	3576	sql query - displaying the same column twice under different conditions	select     name,     min(id) as id1,    max(id) as id2 from table t group by name 	0.000421348852613822
9103234	17715	get invoking user id (only) from mysql	select substring_index(user(),'@',1); 	0
9103275	24456	restricting results to only rows where one value appears only once	select    a.activity_sk,    a.status,    b.study_activity_sk,    b.name,    b.project project b inner join    (select         activity_sk,        min(status) status,     from       activity     group by activity_sk     having count(activity_sk) = 1 ) a on a.activity_sk = b.study_activity_sk 	0
9103385	10510	how to use a an sql join	select a.id from a left join b     on b.a_id = a.id where b.a_id is null 	0.713425271213902
9103847	23683	sql: how to make a join query with only having the "largest" entry of any "type"?	select        eventtypes.*,       events.* from      events a inner join eventtypes b on a.eventtypeid=b.id where      a.timestamp in (select max(timestamp) from events group by eventtypeid) 	0.000833828214561979
9104207	18159	comparing record to previous record in postgresql	select client,         rate,        startdate,         enddate,         lag(rate) over client_window as pre_rate,        lag(startdate) over client_window as pre_startdate,        lag(enddate) over client_window as pre_enddate from the_table window client_window as (partition by client order by startdate) order by client, stardate; 	0.000146344541652414
9105697	13959	mysql get list of all products ordered per customer in date range open cart	select c.customer_id, c.first_name, c.last_name,         o.order_id, o.date_added,         op.name, op.quantity from customer c inner join orders o on o.customer_id = c.customer_id inner join order_products op on o.order_id = op.order_id where date_added > current_date - interval '7' day; 	0
9107828	16631	multiple tables query on postgis	select  row_number() over (order by a.gid, a.layer) as qid,  a.name, a.address, a."post code", a.layer, a.geom from ( select * from table1 union all select * from table2 union all select * from table3 )a where a.name like 'name%' 	0.138393189862855
9108872	15251	mysql: count rows based on fields name	select status, count(id) as `total` from your_table group by status order by total desc 	5.75260331614856e-05
9110664	9152	select rows from one table, join most recent row from other table with one-to-many relationship	select a.id, a.col_1, a.col_2, a.datetime_col, a.col_3 from     (select b.id, b.col_1, b.col_2, c.datetime_col, c.col_3     from tablea b left outer join tableb c on b.id = c.id     order by c.datetime_col desc) as a group by a.id 	0
9111305	26475	mysql: count rows based on fields name.( part-2 )	select r.resp_comp_name, sum(if(d.status = 'open',1,0)) as open,  sum(if(d.status ='closed',1,0)) as closed from pms_defects d, pms_responsibles r  where r.resp_id = d.resp_id group by d.resp_id 	0.000270691423770845
9111584	2562	two queries in one nested sql query	select date(dated) date_ord,  count(*) as orders_placed,  sum (         case             when action_text like '%staff%'             then 1 else 0 end) as orders_staff  from stats.sales_actions  group by date_ord  order by dated desc 	0.202835999633968
9111778	2988	sql select - merge rows with matching id	select   transid,   case     when g+s+x = 3 then 'm'     when s+x   = 2 then 's'     when g+x   = 2 then 'g'     when g+s   = 2 then 'm'     when s     = 1 then 's'     when g     = 1 then 'g'                    else '-'   end as aggregate_type from (   select     tansid,     max(case when type = 'g' then 1 else 0 end)   as g,     max(case when type = 's' then 1 else 0 end)   as s,     max(case when type = 'x' then 1 else 0 end)   as x   from     yourtable   group by     transid )   as data 	0.000181229266178836
9112110	9069	pick rows from one table but where statement condition is in another table	select specifyfields  from users_friends    inner join users_info on users_info.id=users_friends.friendid 	0
9114367	14059	sql server 2005 business intelligence use 2 datasets one report	select    country,     count(case when actstatus = 105 then status end) as failedcalls,    count(case when actstatus = 5 then status end) as goodcalls from    termactivity(nolock)      inner join    termconfig(nolock) on cfgterminalid = actterminalid where actstatus in (105, 5) group by country order by country 	0.369219614134312
9114500	14985	need to trim first 11 characters off a string in sql	select stuff(somestring,1,11,'') 	0.0312676430234747
9114781	30281	join multiple columns from one table to single column from another table	select t1.team_name as team1, t2.team_name as team2, t.team_1, t.team_2 from trades t inner join teams t1 on t1.id = t.team_1 inner join teams t2 on t2.id = t.team_2; 	0
9115074	7669	sql query does not give distinct value and other issues	select a.username as 'user name'     , max(b.game_level) as 'level reached'     , cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(b.time_spent as datetime))),0) as time) as 'total time spent'     , avg(cast(b.stars as float)) as 'stars'     , sum(b.game_level_score) as 'high score'     , a.current_state as 'online state' from game_users a join score b     on a.id = b.game_users_id group by a.username, a.current_state 	0.644710925386514
9117179	4418	retrieving duplicates in table and displaying them	select a.user_id, a.user_name from user as a inner join (select user_badge_name, user_email from user group by user_badge_name, user_email having count(*)>1 ) as dups on a.user_badge_name=dups.user_badge_name and a.user_email=dups.user_email order by a.user_badge_name, a.user_email 	0.000737059296675499
9119544	17728	how to select nth row in sql server 2005 database query	select * from (  select clgid ,row_number() over (order by clgid) as rn  from idmaker_db  where course ='b-tech' and [class]='ist year'  and branch='computer science and engineering'   ) a where rn=n    	0.0110202098053691
9119605	10439	in a stored procedure, how can i use the results of one query to be used in another	select p.*, c1.name as name1, c2.name as name2  from projects p left join component1 c1    on p.component1type = c1.componentid left join component2 c2    on p.component2type = c2.componentid where p.projectid = @projectid 	0.0636874223226529
9119857	38113	every derived table must have its own alias - error from combination descending mysql	select * from  (     (select '1' as `table`,  `vid_req_timestamp` as `timestamp`, `title` from `movies` where `vid_req` = '1')     union     (select '2' as `table`,  `ost_req_timestamp` as `timestamp`, `title` from `movies` where `ost_req` = '1') ) as `some_table_name_lol_this_is_an_alias` order by `timestamp` desc 	0.00150764793880368
9119991	20392	php mysql join tables return all results	select fixture.id, hometeam, awayteam, datetime, feed.fixtureid as fix_id,         feed.homeodd, feed.drawodd, feed.awayodd  from fixture  left join feed feed on (feed.fixtureid = fixture.id) 	0.0113515598952562
9121008	21108	i want the last row of all players in a specific month+year	select m1.* from table m1    left join table m2 on      (m1.player_id = m2.player_id and m1.date < m2.date       and m2.date < '2011-06-01')    where m2.date is null and month(m1.date) = 5 and year(m1.date) = 2011 	0
9121523	13217	which query is more efficient?	select * from names where account_id in ( select account_id from accounts where enabled=1); 	0.561583795074848
9123349	22355	sql join - summing count of different values	select     o.state_abbr,     s.state,     o.[count] from states s inner join (     select state_abbr, count(*) as count     from orgs     group by state_abbr ) o on s.state_abbr = o.state_abbr 	0.0027027316832743
9123635	29462	converting sql system datetime to non-standard format	select convert(varchar(10), editdate, 101) + ' ' + right(convert(varchar, editdate,100),7) as converteddate 	0.756540029753302
9123832	6265	mysql multiple query with a bit of logic	select case 1 when 1 then 'one' when 2 then 'two' else 'more' end; 	0.531508312368767
9124519	5392	select first in group query	select cola, colb, colc from (     select cola, colb, colc,            rank() over (partition by cola order by colb, colc asc) as r     from your_table ) as dt where r = 1 	0.0378510464609623
9124789	12747	convert varchar to datetime	select convert(datetime, '2010-04-14',120) + 10 as docduedate from tblactionheader ah 	0.0631133475154518
9126309	338	how do i compare rows from the same table?	select     _person_id, _project_id, date_of_hour, count(*) from    mydatatable where     _person_id = 'pe1'  and    date_of_hour between '13.10.2011' and '15.10.2011' group by   _person_id, _project_id, date_of_hour 	0
9126810	6628	retrieve date saved as string	select * from post where year(str_to_date(datum,'%d %m %y'))= 2011; select year(str_to_date('11 september 2011','%d %m %y')); 	0.00669618298000458
9127481	26187	count total on couple of conditions	select sum(col2) from table where col1 in (select col1 from table where id = 1) 	0.000459006914431949
9128038	29322	count words in column with sql	select length(words) - length(replace(words, ' ', '')) + 1 as words_count from table_name 	0.0654777393530008
9128919	18669	pl/sql - select columns values as string array	select a.userid, a.code, a.country, listagg(b.email, ',') within group (order by b.email) as "emails" from tab1.a, tab2.b where a.userid = b.userid and a.code = b.code and a.userid = 'rishi' group by a.userid, a.code, a.country; 	0.00207872298894836
9129234	14139	mysql select min row of inner joined table	select *, min(item_prices.price) as minprice     from items       left join item_details using(item_id)      left join item_prices using(item_id)  where 1=1 group by item_id; 	0.00215740152880395
9129724	22470	select inherit values from parent in a hierarchy	select t.id,     case when t.value is null     then (select a.value from test_levels a where a.id = t.parent_id)     else t.value     end,     t.level_no from test_levels t 	0.00107648979329
9130284	7310	mysql many to many relationship query. how to get all tags of filtered posts?	select distinct tag_id from     (select pt1.post_id from pt1     inner join tags t1 on (pt1.tag_id = t1.id)     where t1.id in (1, 2)     group by pt1.post_id     having count(distinct t1.id) = 2) matchingposts inner join pt2 on (matchingposts.post_id = pt2.post_id) where (pt2.tag_id not in (1, 2)) 	0
9130302	21084	select records after id	select * from mytable  where creation_time > (select creation_time from mytable where objectid='your_object_id_that_you_really_know' limit 1)  order by creation_time asc 	0.00135665213692172
9130846	28486	merge two unrelated views into a single view	select 'v1'::text as source, clothingid, shoes, shirts from   view1 union  all select 'v2'::text as source, clothingid, shoes, shirts from   view2; 	9.42084644813707e-05
9131420	10793	mysql rank comparison	select       allplays.videoid,       allplays.cnttoday,       @ranktoday := @ranktoday +1 as todayrank,       allplays.cntbefore,       allplays.beforerank    from       ( select vp.videoid,                sum(if(date(from_unixtime(vp.playtime )) = curdate(), 1, 0 )) as cnttoday,                sum(if(date(from_unixtime(vp.playtime )) < curdate(), 1, 0 )) as cntbefore,                @rankbefore := @rankbefore +1 as beforerank            from                video_plays7d vp               join ( select @rankbefore := 0 ) sqlvars            where               date( from_unixtime(vp.playtime ) ) >= date_sub( curdate(), interval 1 day )            group by              vp.videoid            order by               cntbefore desc       ) as allplays       join ( select @ranktoday := 0 ) as sqlvars2    order by       allplays.cnttoday desc 	0.533363773524844
9132209	13983	how do i find groups of rows where all rows in each group have a specific column value	select id1, id2 from mytable group by id1, id2 having count(type) = sum(case when type = 'a' then 1 else 0 end) 	0
9133410	2991	sql query to get date difference in select row	select * from     tablea where     datediff(day, expirationdate, getdate()) = 7     or datediff(day, expirationdate, getdate()) = 24 	0.000311349949622011
9134154	14345	force trim of query output values and add auto number	select row_number() over(order by sum(b.game_level_score) desc) as 'rank'     , a.username as 'user name'     , max(b.game_level) as 'level reached'     , convert(varchar(8), dateadd(millisecond,sum(datediff(millisecond,0,cast(b.time_spent as datetime))),0), 108) as 'total time spent'     , cast(cast(round(avg(cast(b.stars as float)),1) as numeric(25,1)) as varchar(25)) as 'stars'      , cast(sum(b.game_level_score) as int) as 'high score'     , a.current_state as 'online state' from game_users a     join score b on a.id = b.game_users_id     group by a.username, a.current_state 	0.000767751154631942
9134230	36384	how to query database for date = today, except... there is no year	select *    from users   where       date_format(from_unixtime(birthdate),'%m-%d') = date_format(now(),'%m-%d')      or (             (                 date_format(now(),'%y') % 4 <> 0                 or (                         date_format(now(),'%y') % 100 = 0                         and date_format(now(),'%y') % 400 <> 0                     )             )             and date_format(now(),'%m-%d') = '03-01'             and date_format(from_unixtime(birthdate),'%m-%d') = '02-29'         ) 	0.000331960695967097
9134260	6298	if statement in a sql query	select title,         case when t1.masterid <> 0 then t2.case else t1.case end as copy,         masterid from table1 as t1 left join table2 as t2     on t1.masterid = t2.masterid 	0.687440081172331
9134558	38230	how to write a mysql query that returns a temporary column containing flags for whether or not an item related to that row exists in another table	select   tu.id,              tu.name,             case when tf.id is not null then 'true' else 'false' end as flagged       from  table_user tu             left outer join table_flags tf on tu.id = tf.id 	0
9135260	25257	sql query to produce xml output	select  t1.name as practicesite,         (select t2.npi as npi,                  t2.firstname,                 (select t3.patientnumber,                          t3.diabetesdiagnosis,                          t3.dateofbirth                         from tbl3_abstraction t3                         where t3.pvid=t2.pvid                         for xml path('clinical-abstraction'), type                         ) as 'clinical-abstractions'                 from tbl2_applicant t2                 where t1.[facilityid]=t2.[facilityid]                 for xml path('applicant'), type         ) as 'applicants' from tbl1_site t1 for xml path('practicesites'), root('account'), elements; 	0.706580877460591
9135509	23984	mysql join unable to select from one table	select score.recipient, score.amount, u.* from score  left join `users` as u on score.recipient = u.id 	0.00897096020534877
9139617	33367	select rows with not not duplicated specified fields (transact-sql)	select        r1.id,                r1.way_id,                r1.node_id,                r1.sort from          relations r1 where        r1.way_id = 107187465 and r1.id = (select max(r2.id) from relations r2              where r1.node_id = r2.node_id) 	0.0702838348990167
9139673	40177	select with count, group by, order by	select customers_id,        customers_name,        max(date_purchased) as last_purchase,        count(*) as total_order from orders group by customers_id,customers_name; 	0.215605827389424
9141186	31216	select query - websql	select * from contacts where cname like ?% 	0.648231605221157
9142423	10664	sql case with multiple values	select name, case when statusid < 4 then 'alive'                   when statusid = 4 then 'dying'                   else 'dead' end as some_alias   from people 	0.437230374938723
9142585	33804	how to make mysql search for minimum 3 keyword matches?	select id, file, count(*) from   (select distinct id, file      from file_table        where find_in_set(keyword1, keywords)    union all    select distinct id, file      from file_table        where find_in_set(keyword2, keywords)    union all    select distinct id, file      from file_table        where find_in_set(keyword3, keywords)    union all    select distinct id, file      from file_table        where find_in_set(keyword4, keywords)    .... more union all ....) as files group by id, file having count(*) >= 3 	0.0545761280801213
9142806	3347	difficult sql statement... four tables?	select a.title, a.year, c.name, d.eventid from films a join nominations b on b.filmid = a.filmid join awards c on c.awardid = b.awardid join events d on d.eventid = b.eventid where events.eventid = xx 	0.786443783860127
9143325	30416	sort table, using loop in mysql with select and update	select @p:=0, @parent:=0; update page p1 join ( select title,    case when @parent<>parent_id then @p:=0 else @p:=@p+1 end as position,   @parent:=parent_id as parent_id   from page   order by parent_id, title desc ) p2 on p1.title = p2.title and p1.parent_id = p2.parent_id set p1.position = p2.position 	0.129603960634282
9144677	33302	left join on max value	select s.*, ss.* from student as s     left join student_story as ss on (ss.studentid = s.studentid)     where ss.dateline = (         select max(dateline) from student_story as ss2             where ss2.studentid = s.studentid     ) 	0.162741912768087
9145743	35005	join 2 tables on 2 fields 	select match.*,team_home.*,team_away.* from match   left join team team_home on match.hometeam = team_home.team_id   left join team team_away on match.awayteam = team_away.team_id   where match.match_id = 1 	0.0156278821724325
9147052	6307	how can a run a query on one table based on the results of a query on another table?	select users.firstname, users.lastname, users.username  from friends join users on friends.friend = users.username where friends.user = '$user' and friends.friend like '%$term%'; 	0
9147611	16577	is it possible to perform where on a field formed using as keyword in the same query?	select t.id, t.new_name from (select id,    case nickname when '' then full_name else nickname end as new_name from your_table) t where t.new_name = 'jen' 	0.39065304527271
9147774	31429	query all item from second table	select id, table1_id, item  from table2  where table2.table1_id=table1.id 	0
9148800	26853	mysql query. can't manage to get it	select distinct id from( select friend as id from friends where user = 100 union all select user as id from friends where friend = 100) ; 	0.662656821462452
9149030	41248	geocode - get the location	select sqrt(pow(latitude-[input latitude], 2)+pow(longitude-[input longitude])) as dist, * from location_table order by dist asc limit 1 	0.00925519896669671
9149742	7805	get the columns in a single query	select   sum(case c1 when 1 then 1 else 0 end) count_c1,   sum(case c2 when 0 then 1 else 0 end) count_c2 from yourtable 	0.000527085666960819
9149759	17438	multiply combination of columns based on a column value	select   col1,   col2,   col3,   col4,   case col4      when 'casea' then col1*col2     when 'caseb' then col1*col3     when 'casec' then col2*col3   end as total from yourtable 	0
9151773	6487	group my sql float values by range	select sum(case when weight > 60 and weight <= 70 then 1 else 0 end) as weight1, sum(case when weight > 60 and weight <= 80 then 1 else 0 end) as weight2 from mytable 	0.0228099183755424
9151883	31535	how to return rows that equal all substrings of a string	select col from tbl where instr(reverse('123456'), reverse(col))=1; 	0
9152509	23770	how to calculate time difference between two dates - mysql	select     unix_timestamp(`recent_date`)    -    unix_timestamp(`previous_date`) as    `time difference`; 	0
9152601	32351	get a row at a specific position in the result set	select postid from post p join thread t on p.threadid = t.threadid where t.forumid = 10 and t.visible = 1 and p.visible = 1 order by p.dateline desc limit 999999,1 	0
9153713	15121	mysql count of related fields in a table from two other tables	select fabrics.fabricname, count(reservations.ipaddr), count(fabricmember.ipaddr) from fabrics left join fabricmembers on fabrics.fabricname = fabricmembers.fabric left join reservations on fabricmembers.ipaddr = reservations.ipaddr group by fabric.fabricname 	0
9155230	14995	how to substract from the resut of two selects in mysql	select ( programapago.monto - coalesce(itotal.totalmonto,0)) result from programapago left join      (select programapago_id, sum(monto) as totalmonto     from caja group by programapago_id) as itotal         on programapago.id = itotal.programapago_id where programapago.id = 2 	0.00142372280525319
9155789	35157	the field type can have these values 1,2,3..10. how to count the records of the highest frequent value of type	select `type`, count(1) as `count` from `realestate` group by `type` order by `count` desc limit 1 	0
9156846	35615	sql server 2008 search for date	select result  from table  where       mycolumn >= @selecteddate  and mycolumn < dateadd(d, 1, @selecteddate) 	0.501375891981533
9157826	19101	general approach when needing to calculate values between rows	select  assignedto,          sum(datediff(day, timestamp, isnull(enddate, getdate()))) [days] from    (   select  id,                     [timestamp],                     assignedto,                     (   select  min(timestamp)                         from    [yourtable] b                         where   b.timestamp > a.timestamp                     ) [enddate]             from    [yourtable] a         )  a group by assignedto 	0.000819066327351795
9159161	40174	mysql query to get daily differential values	select   t1.dt as date,   t1.value - t2.value as value from   (select date(date) dt, max(value) value from table group by dt) t1 join   (select date(date) dt, max(value) value from table group by dt) t2     on t1.dt = t2.dt + interval 1 day 	0.00127946894057777
9160067	8048	how to use group by to calculate intervals	select     active.state,     age.base, age.base+4,     count(*) as totalcount,     count(case when t.[men/women] = 'man' then 1 end) as mancount,     count(case when t.[men/women] = 'woman' then 1 end) as womancount from     (     values (10),(15),(20),(25),(30),(35),(40) ,(90),(95)     ) as age(base)     cross join     (     values (0), (1)     ) as active(state)     left join     mytable t on t.age between age.base and age.base+4 and t.active = active.state group by     active.state,     age.base, age.base+4; 	0.0107528363368414
9161093	10171	query to get the percentage of orders placed by a customer	select cast(count(orderstatus) as float)/count(*)*100 percentage from dbo.product where customerid = 10 	0
9161161	8207	how to get a field, where another field has is max value	select top 1     key, id, value from    mytable order by    value desc 	0
9164415	5980	how to select distinct from one column where not existing in other columns?	select distinct(t1.username) from tablename t1 left join tablename t2   on t2.group1 = t1.username left join tablename t3   on t3.group2 = t1.username left join tablename t4   on t4.group3 = t1.username left join tablename t5   on t5.group4 = t1.username where t2.username is null   and t3.username is null   and t4.username is null   and t5.username is null 	0
9166039	23596	best way to fetch nearby locations?	select      id,      ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) as distance  from      markers  having      distance < 25  order by      distance  limit      0 , 20; 	0.0662743522310179
9166189	15706	exporting data to csv file using select mysql query	select      `number`,      replace(replace(replace(`description`, ',', ''), char(13),''), char(10),''),     mr.`dateinserted` from     `mr` where     mr.dateinserted >= '2012-01-01'  and      mr.dateinserted <= '2012-01-31' 	0.0980463056311763
9166877	31990	how to generate list of all dates between sysdate-30 and sysdate+30?	select trunc(sysdate)+31-level from dual connect by level <=61 	0
9168202	12850	return data from different table sql to html	select      username as user,      p.image as user_image,      i.image,      i.id as image_id,      i.description as text,      unix_timestamp(i.date) as image_date,      coalesce ( imgcount.cnt, 0 ) as comments,     fav.id as favorite_id,     unix_timestamp(fav.date) as favorite_date,     u2.username as favorite_user,     t.image as favorite_user_image from users u left join user_favorites fav on fav.user_id = u.id left join user_follow f on f.follow_id = fav.user_id left join images i on i.user_id = u.id left join users u2 on u2.id = i.user_id left join images p on p.id = (select b.id from images as b where u.id = b.user_id     order by b.id desc limit 1) left join (select image_id, count(*) as cnt from commentaries group by image_id  )     imgcount on i.id = imgcount.image_id left join images t on t.id = (select b.id from images as b where u2.id = b.user_id     order by b.id desc limit 1) where u.user_id = ? group by fav.id order by i.date desc 	0.000175541781741677
9169203	31027	selecting zip codes issue with sql	select   city, state, county,   group_concat(zipcode separator ',') as zipcodes from   mytable where   <whatever you have> group by   city, state 	0.698327308908697
9170982	27933	sql server split name	select   substring(name, 1, case when charindex(' ', name) = 0 then len(name) else charindex(' ', name) end) as [firstname],  case when charindex(' ', name) = 0 then null else  substring(name, charindex(' ', name) + 1, len(name)) end  as [lastname]  from (     select 'jon doe' name     union      select 'jon'  ) x 	0.0684290516386749
9171963	16535	sql join two table	select a.uid, a.name, b.address from a left join b on a.uid=b.uid 	0.0720787017726162
9172751	438	postgres: show inherited fields	select nmsp_parent.nspname    as parent_schema,        parent.relname         as parent_table,        nmsp_child.nspname     as child_schema,        child.relname          as child_table,                   column_parent.attname  as column_parent_name from pg_inherits join pg_class parent            on pg_inherits.inhparent  = parent.oid join pg_class child             on pg_inherits.inhrelid   = child.oid join pg_namespace nmsp_parent   on nmsp_parent.oid        = parent.relnamespace join pg_namespace nmsp_child    on nmsp_child.oid         = child.relnamespace join pg_attribute column_parent on column_parent.attrelid = parent.oid where column_parent.attnum > 0 and column_parent.attname not ilike '%pg.dropped%'; 	0.0171070202846072
9173289	38959	t-sql: finding rows in a different table without joins	select a.country, count(*) as occurrences from   tablea a     inner join  tableb b     on b.somenumber between a.startnumber and b.endnumber group by a.country 	0.00126480896134637
9176819	17351	showing rows if sub queries join columns if they exist	select   upd8r_user_accts.id,   upd8r_facebook_accts.fb_id  is not null  as has_fb_id,   upd8r_twitter_accts.twitter is not null  as has_twitter from   upd8r_user_accts left join   upd8r_twitter_accts     on upd8r_twitter_accts.user_id = upd8r_user_accts.id left join   upd8r_facebook_accts     on upd8r_facebook_accts.user_id = upd8r_user_accts.id where      upd8r_facebook_accts.fb_id  is not null   or upd8r_twitter_accts.twitter is not null 	0.00380301518932715
9177138	17427	how do you select two counts in a single query?	select sum(good_apples) as good_count, count(*) as all_count from apples 	0.00366008118670024
9177799	32705	converting datetime format to 12 hour	select convert(varchar, getdate(), 100) as datetime_in_12h_format 	0.0111036750451158
9177826	3623	removing white space and newlines from a database	select substring_index(substring_index(trim(somecolumn), ']', 1), '=', -1) 'lang' from sometable 	0.101851828690845
9178099	31007	providing two schema name in jdbc connection url	select db1.products.prod_id, db2.products.upc_code from db1.products left join db2.products on (db1.products.prod_id=db2.products.prod_id) 	0.419738690293395
9178328	31108	selecting from two tables?	select name, id from orders where ... union select name, id from orders_old where ... 	0.000464428646462085
9178982	879	mysql if date statement?	select case now() > start_date           then true           else false        end from your_table 	0.228815120508876
9179360	16157	populate field based on other fields values	select ...        case            when raceafroamer = 1 then 'raceafroamer'            when raceamerindian = 1 then 'raceamerindian'            when racecaucasion = 1 then 'racecaucasion'            when racehispanic = 1 then 'racehispanic'            when raceoriental = 1 then 'raceoriental'        end as racedescription,        ... 	0
9180637	14860	sql server query: how to return set of values based on condition?	select   professors.professorname,   departments.departmentname from   professors left join   professordepartments     on professors.professorid = professordepartments.professorid left join   departments     on professordepartments.departmentid = departments.departmentid     or professordepartments.departmentid  is null 	0.000227440291659779
9180918	19395	select similar rows from a table given a table of ids	select a.* from tablea a inner join tablea a2 on a.first = a2.first and a.middle = a2.middle and a.last = a2.last and a2.id in (select id from tableb) 	0
9183551	21626	how to get a query that only displays items that are in the present or future in mysql?	select e.name, e.event_date, e.time, e.data, e.picture, e.event_type, v.latitude, v.longitude, v.address, v.name as vname  from events e inner join venues v on e.vid=v.vid  where (find_in_set('livesports', event_type)>0  or find_in_set('dancing', event_type)>0  or find_in_set('drinksdeals', event_type)>0  or find_in_set('pubquiz', event_type)>0  or find_in_set('boardgames', event_type)>0  or find_in_set('fussball', event_type)>0  or find_in_set('speeddating', event_type)>0  or find_in_set('pool', event_type)>0  or find_in_set('livemusic', event_type)>0  or find_in_set('fooddeals', e.event_type)>0) and e.event_date >= date_sub(curdate(), interval 1 day) group by e.name 	0
9184046	31700	how to left join a cartesian product on another table?	select x.dog, x.cat,cs.chase  from       (select dog             ,cat        from dogs, cats) x left join catchases cs on cs.dog=x.dog and x.cat=cs.cat 	0.0371541461912082
9184290	34218	finding number of rows in each group by result	select eam_model, new_model, count(*) from rollout_systems  where scope_id = '.$id.'               group by eam_model, new_model 	0
9186450	19454	sql server 2008 - date format still retain date datatype	select convert(varchar(11), orders.shipdate, 6) as formateddate from orders order by shipdate desc 	0.278526395409667
9187842	21130	mysql, how to order by the first number in a set of numbers	select * from test order by cast(substring_index(quads,',',1) as unsigned) 	0
9188072	1707	mysql: using a subset of rows to check against where clause	select t2.uid, t2.responsedate from t2 left join (     select t1.uid, max(t1.responsedate) as maxdate from t1     group by t1.uid ) as subquery on t2.uid = subquery.uid and t2.responsedate = subquery.maxdate where maxdate is not null and field_01 = "yes" 	0.0104795897587141
9188115	11997	best mysql statement to insert time n calculate difference	select datediff('2007-12-31 23:59:59','2007-12-30'); select timediff('2000:01:01 00:00:00', '2000:01:01 00:00:00.000001'); 	0.000677252445659804
9188458	38412	mysql db with multiple numbers show as rows	select     concat("type: ", roomtype,     " - roomno: ", roomno,     " - features: ", group_concat(feature order by feature separator ', '))     as result from t1 group by roomtype, roomno 	0.000938545240036602
9191427	11685	can i return a string based on a value in the table?	select    case       operation   when 1 then 'op1'   when 2 then 'op2'   when 3 then 'op3'   when 4 then 'op4'   else      'unknown op'   end operationname   ,  [...] from tablename 	0
9191826	19666	combine two different select statements, one distinct the other not	select * from stevestable t  where t.data1 = '%s'  and t.data2 = to_date('%s','dd/mm/yyyy') and t.data1 in (select distinct data1 from anothertable ftt     join table1 tab on tab.somedata = ftt.somedata     where tab.somedata = 0     and tab.someotherdata = 1) 	0
9192777	18703	select distinct, show count at end of row	select area, postcode, count(*) from table group by area, postcode; 	0
9192957	29209	dates in between two days	select id, name from `movie` where  end_date >= '2012-01-05' and  start_date <= '2012-01-20' 	4.78036684600596e-05
9193071	31040	sql query accross three tables requiring different joins	select   * from   packages p where   not exists (     select 1        from applications a             inner join apppackages ap on ap.packageid = p.packageid      where ap.appid = <your app id>   ) 	0.172829036698662
9193330	29024	select only one row in the case where there are multiple values for a particular column	select max(a) as a, b from table group by b; 	0
9193541	4661	getting matching attributes from two tables	select id, min(is_ok) from (   select b.id id,           decode(b.value, a.value, 'y', 'n') is_ok   from a inner join b    on b.id_attr = a.id_attr ) group by id; 	0.000114270763083263
9196638	21731	select from inner join - php/mysql	select b.uid, g.first_name, g.last_name, b.pic from user_data.general_info g inner join user_data.bcards b on g.uid = b.uid where left(g.last_name, 1) = '$letter' order by g.last_name, g.first_name asc 	0.278462558679147
9196839	12968	how to select records and display text along with count?	select text, count(text)  from your_table  group by text order by count(text) desc 	0
9197210	24920	how to select just birthyear from dob in vb.net from sql server 2008 database	select distinct year(dateofbirth) as year from mytable order by year 	0.00997476436116754
9198878	34489	mysql, how to find intersaction of rectangular bounds	select *  from dashboard_entries  where intersects(geomfromtext('polygon((34.0160320 66.6578507,34.0160320 75.3818660,24.7482340 75.3818660,24.7482340 66.6578507,34.0160320 66.6578507))'), location_bounds) 	0.0168512395241449
9199333	10851	aggregate query in same select statement	select  *, sum(case when color = 'red' then 1 else 0 end) over() [red],         sum(case when color = 'blue' then 1 else 0 end) over() [blue],         sum(case when color = 'yellow' then 1 else 0 end) over() [yellow] from yourtable 	0.412457691634107
9199945	33882	mysql query with group by	select       o.ponumber,       o.customerid,       count(*) as totalorders,       min( o.orderid ) as firstorder,       min( o.orderdate) as firstorderdate,       max( o.orderid ) as lastorder,       max( o.orderdate) as lastorderdate    from       orders o    group by       o.ponumber,       o.customerid 	0.625773659821344
9200192	22245	exclude rows based on overlapping restrictions (sql)	select sum(amt) as total, name, year  from table  where ind='isvalid' and (name <> 'mary' or year <> 2008) group by name, year 	8.73122807189948e-05
9203885	23367	optimize a subquery searching for records in another table based on dates not in the past 360 days	select      * from        a left join   b         on  a.id = b.pid and b.issued >= date_sub(curdate(), interval 360 day) where       b.id is null and             date_add(a.dob, interval year(curdate()) - year(a.dob) year) =              date_add(curdate(), interval 1 day) 	0
9206177	25602	counting rows in left joined table	select u.id, u.email, u.salt, u.pass, u.approved,  u.ban, sum(u2.status) as status from `users` as u  left join `log` as u2 on u2.user_id = u.id  where u.email = ? group by u.id 	0.00468862530506447
9206399	28681	oracle sql: merge rows into single row	select studentid, studentname, max(mathgrade), max(scigrade) from vstudentgrade group by studentid, studentname, mathgrade, scigrade 	0.000108684787537571
9206433	23375	best way to create a temp table with same columns and type as a permanent table	select top 0 * into #mytemptable from myrealtable 	0.000198775863247493
9207023	10884	getting the sum of a column in winforms	select sum(isnull(total, 0))... 	0.00110973212618593
9210289	13454	mysql variables in the select	select    num_daysopen,    (28 - num_daysopen) as days_left from    (     select         datediff(date(now()), date(dateopened)) as num_daysopen     from         table    ) t 	0.141306427312038
9213298	9024	mysql query to find distinct rows shows incorrect result	select count(distinct column_name) from table_name 	0.0393523424267419
9214504	1920	sql query to compare 2 weeks	select country,      sum(case when actstatus in (5,105) then 1 else 0 end) as totalcalls,     sum(case when actstatus = 105 then 1 else 0 end) as failedcalls from country (nolock)     left outer join termconfig (nolock) on country = cycode     left outer join termactivity (nolock) on cfgterminalid = actterminalid  where (actterminaldatetime between @startdate-7 and @enddate-7) group by country order by country asc 	0.00376228910489702
9215408	33602	query to obtain number of occurrence of a given word in a database table	select  users.username as username,  round(sum((length(comments.comment) - length(replace(lower(comments.comment),"one", ""))) / length("one")), 0) as count from users  inner join comments on comments.uid = users.id group by users.id order by count desc; 	0
9215409	22855	sql server temp table	select deptno,count(*) cnt into #temptable   from emp     group by deptno; select    *,   case cnt when 0 then 'espace vide' else null end as column1 from #temptable if exists(select * from #temptable where cnt = 0) print 'espace vide' 	0.255454438932288
9217134	11222	compare each row's column to a particular row's column	select vc.name, vc.guid from vcomputer vc      left join inv_screensaver_file_info sfi on sfi._resourceguid=vc.guid      inner join vcomputer vc2 on vc2.guid = 'b5a85423-26c4-40c0-da28-237fb4cb0b3'      inner join inv_screensaver_file_info sfi2 on sfi2._resourceguid = vc2.guid where sfi.lastmodified is null    or sfi.lastmodified < sfi2.lastmodified 	0
9219046	22001	pdo fetch loop is returning an array of the same mysql table column names over and over instead of the data	select 'id','name'   from a_table_in_my_database 	0
9220771	9461	mysql index: 1 keyname multiple columns or 1 keyname per column?	select * from users where (age > 18 and name = "johnnie walker") 	0.00143358303420713
9221366	38721	using mysql to return results using left join where one of the tables does not contain a record	select *  from customers    join orders      on orders.custid = customers.id  where customers.email = '$email'    and orders.orderid not in          ( select orderid from reviews ) 	0.0183789298059884
9221909	27495	join if id exists else return other column	select   peoplelist.autoinc_id,   ifnull(employeelist.aliasname,peoplelist.name) as workername from   peoplelist   left join employeelist on peoplelist.employeeid=employeelist.employeeid ; 	0.00403123733418937
9222022	3486	sql query for max time with group on string excluding groups with null time rows	select max(end_time), name from table t where not exists (     select 1     from table tt     where end_time is null and tt.name=t.name ) group by name 	0.00032518248967352
9222664	21086	getting a count of two different sets of rows in a table and then dividing them	select     (select count(*) from tasks where completed = 1) /     (select count(*) from tasks where completed = 0) from dual 	0
9223299	29589	select from multiple tables mysql	select * from equitymarketnews where titleline like '%axis bank%' or storymain like '%axis bank%'  union select * from economynews where titleline like '%axis bank%' or storymain like '%axis bank%'  union select * from corporatenews where titleline like '%axis bank%' or storymain like '%axis bank%'  union select * from industrynews where titleline like '%axis bank%' or storymain like '%axis bank%'; 	0.00913962797016345
9225582	2534	mysql make select value default to positive integer 	select   datediff(date(now()), date(dateopened)) as num_daysopen,   greatest(0,(28 - datediff(date(now()), date(dateopened)))) as days_left from table 	0.0263808970543732
9227430	4385	database with timestamps, show distinct month	select     from_unixtime(timestamp, "%m") as m,     from_unixtime(timestamp, "%y") as y,     sum(packetssent ) as sent,     sum(packetsreceived) as received from atable group by y, m having y=year(now()) 	9.40710205409503e-05
9228149	17336	query search url match	select replace(replace(url,'http: 	0.442702744183943
9229252	4974	mysql - 'select' and 'as can make only one column.. how to make them more?	select t.name, p.x, p.y, p.w, p.h from text t left join pictures p on p.id_obj = 'example' and p.picture_type = 20 where t.id = 100 	0.000617596653375377
9229443	24724	sql query value duplication	select * from (    select name,companyid from users   union all   select distinct 'system', companyid from users ) order by companyid 	0.217252007246265
9229686	7561	how data will load in to memory in sql server	select * from [mytable] 	0.479186903144597
9229862	7987	how to count number of records per day?	select dateadded, count(custid) from responses where dateadded >=dateadd(day,datediff(day,0,getdate())- 7,0) group by dateadded 	0
9230018	2646	how to see if a value exists on multiple tables, and exclude tables who do not have any values	select   * from   @a        as a full outer join   @b        as b     on b.id = a.id full outer join   @c        as c     on c.id = coalesce(b.id, a.id) full outer join   @d        as d     on d.id = coalesce(c.id, b.id, a.id) where     (a.id is not null or (select count(*) from @a) = 0) and (b.id is not null or (select count(*) from @b) = 0) and (c.id is not null or (select count(*) from @c) = 0) and (d.id is not null or (select count(*) from @d) = 0) 	0
9230250	39326	how can i change row information in a query?	select    case when numbers <> 5 then 1 else numbers end from table 	0.0123560619871738
9231954	19180	how to get list of named mysql locks held by mysql client connections	select *  from information_schema.processlist  where state = 'user lock' 	0.00263673531030495
9232084	9183	how to append a value to a mysql query	select 'arbitrary_value' as node_title union all (select n.title as node_title   from program p   inner join node n on p.nid = n.nid order by node_title) 	0.0109610692532157
9232572	9395	splitting a comma-separated field in postgresql and doing a union all on all the resulting tables	select      yourtable.id,      regexp_split_to_table(yourtable.fruits, e',') as split_fruits from yourtable 	4.69650611701797e-05
9233372	16	sql merge 3 tables by date where some dates are missing	select source.id, source.date, x.x, y.y, z.z from (   select id, date   from tablex   union   select id, date   from tabley   union   select id, date   from tablez ) as source left join tablex x on source.id = x.id and source.date = x.date left join tabley y on source.id = y.id and source.date = y.date left join tablez z on source.id = z.id and source.date = z.date order by source.id, source.date 	0.000259416651931229
9234326	5196	excluding same day drop\adds while preserving the real start and end date	select     startdates.subid,     startdates.startdate,     min(enddates.enddate) as enddate,     startdates.prodtype from (     select         recid, subid, startdate, prodtype     from yourtable s1     where not exists (         select 1         from yourtable s2         where              s1.startdate = s2.enddate             and s1.subid = s2.subid     ) ) startdates join (     select         recid, subid, enddate, prodtype     from yourtable s1     where not exists (         select 1         from yourtable s2         where              s1.enddate = s2.startdate             and s1.subid = s2.subid     ) ) enddates on     startdates.subid = enddates.subid      and startdates.startdate < enddates.enddate group by     startdates.subid,     startdates.startdate,     startdates.prodtype 	0
9235729	1172	mysql: how to find the homewrecker by counting *each* group by subsection?	select distinct t.x, t.y, ttt.cnt from            couples t,            (select y, count(*) cnt from                    (select distinct x, y from couples) tt group by y) ttt         where t.y=ttt.y 	6.74955803105086e-05
9236649	354	find products that are sold at a price less than mine	select distinct p1.*  from prdtfrn p1 join prdtfrn p2 on p1.pid = p2.pid and p2.fid != 1 and p2.price < p1.price where p1.fid = 1; 	0
9239172	20283	sql for counting passive subscribers between given dates	select  count(*)  from    members as m          inner join subscriptions as s              on s.member_id = m.id where   s.enddate between '2011-01-01' and '2011-02-01' and     s.active = 0 and     m.hassubscription = 1 and     not exists         (   select  1             from    subscriptions a             where   a.memberid = m.id             and     a.active = 1         ) 	0.000590270694835691
9239215	13226	retrieving data from two chained many-to-many relationships	select movie.title, genre.name  from movie  left outer join movie_genre  on (movie.movie_id = movie_genre.movie_id)  join genre  on (genre.genre_id = movie_genre.genre_id)  left outer join genre_subgenre  on (genre_subgenre.genre_id = genre.genre_id)  left outer join subgenre  on (subgenre.subgenre_id = genre_subgenre.subgenre_id) 	0.000718569893374539
9239762	12455	find duplicates in the same table in mysql	select     artist, release_id, count(*) no_of_records from table group by artist, release_id having count(*) > 1; 	0.000406928499136741
9239905	29033	sql select distinct on one field mysql server	select distinct(columnname) from mytable where rulesapply 	0.00591479350159977
9240192	41088	selecting the second row of a table using rownum	select empno from     (     select empno, rownum as rn      from (           select empno           from emp           order by sal desc           )     ) where rn=2; 	0
9241090	15646	mysql union producing unexpected results and missing columns	select resume_id as id,  date_mod as date, 'resume' as type from resumes union all  select profile_id, date_mod, 'profile' from profiles  order by date  limit 5 	0.720588463712481
9243609	26184	sql query sorting groups by the most recent post	select g.group_id, g.group_name, max( p.post_date ) from   group g left join post p on g.group_id = p.group_id group by g.group_id, g.group_name order by max( p.post_date ) desc 	0.000101176288444158
9244378	19884	how to max(count(x)) in sqlite	select count(*) as result from blog_posts group by blog_id order by result desc limit 1 	0.367972159702367
9245427	27796	sql; plus + or minus – instead of dates (asp.net-c#)	select datediff(day,getdate(), max(amountpay.dateupto)) as [ paidupto], timetable.name, timetable.ref, timetable.time11to12 from amountpay full outer join timetable on amountpay.ref = timetable.ref where (timetable.time11to12 = @time11to12) group by timetable.name, timetable.ref, timetable.time11to12 	0.166102210631454
9246410	22185	mysql query: find customer w/orders but without payment	select c.customernumber from classicmodels.customers c   inner join classicmodels.orders o     on c.customernumber = o.customernumber   left outer join classicmodels.payments p     on c.customernumber = p.customernumber where p.customernumber is null; 	0.00715735179579545
9247842	34400	query on 3 tables with join	select * from table1 t1 left outer join table2 t2 on t1.dep_id = t2.dep_id left outer join table3 t3 on t1.dep_id = t3.dep_id 	0.250208047552548
9248788	34429	simple sql: how do i group into separate columns?	select day,    max(case when ticker = 'aapl' then price end) as 'aapl',    max(case when ticker = 'goog' then price end) as 'goog' from stocks group by day 	0.0299988392519263
9251093	37139	mysql join two nested queries	select o.customernumber as customernumber,      sum(od.quantityordered * od.priceeach) as amountordered,      sum(p.amount) as amountpaid from classicmodels.orders o inner join classicmodels.orderdetails od     on o.ordernumber = od.ordernumber left join classicmodels.payments p     on p.customernumber = o.customernumber group by o.customernumber 	0.66027613296501
9251192	19467	sql server ce 4 - how to select n random rows from a table?	select top n * from table order by newid() 	7.66218571196864e-05
9252760	31152	mysql (and wordpress): select rows containing the highest value in one column and order by another	select post_title, post_date, meta_value     from wp_posts, wp_postmeta     where id in (         select post_id             from wp_postmeta                 where meta_key = 'myissue'                 and meta_value = (                     select max(meta_value + 0)                         from wp_postmeta                             where meta_key = 'myissue'                 )        )     and id = post_id     and meta_key = 'myorder'     order by meta_value + 0; 	0
9253173	25539	how to write a query when pattern is in field	select * from pattern_table where 'hey bobby' like replace(f_pattern, '*', '%') 	0.427132113245288
9254490	27528	using mysql triggers to update table with last_modified data	select update_time from   information_schema.tables where  table_schema = 'dbname' and table_name = 'tabname' 	0.127297554175017
9255491	24849	sql get unique values from select	select      name       as name  ,     min(value) as value from abc group by name order by name asc; 	0.000125405609130824
9255794	27446	how to select tuples in sql with the largest specific attibutes	select make, model from cars where pistoncapacity=(select max(pistoncapacity) from cars) 	0.00145900770825982
9257756	1508	start with and connect by in oracle sql	select level, * from accounts  start with parent_account_id = account_id  connect by prior account_id = parent_account_id          and account_id <> parent_account_id 	0.531334650636044
9258552	18527	sql select distinct id where description contains certain text value	select id, description from table  where description like 'retro %'  or id in (    select id from table group by id having count(*) = 1 ) 	0
9261808	38621	filter on a date field not typed as a date	select champ_save_id, element_id, valeur from g_champ_save as cs inner join g_champ as c on cs.champ_id = c.champ_id where cs.valeur <> '' and not cs.valeur is null and c.champ_code = 'qualif_valide_qualif_fin' and convert(datetime, case isdate(cs.valeur) when 1 then cs.valeur end, 103)      <= @filterdate 	0.0125533867836933
9263188	26754	sql select boolean options	select case          when mybooleancolumn = 1 then 'true'          else 'false'      end as mybooleancolumn   from mytablethathasabooleancolumn 	0.405768468135247
9263672	36422	who sell with lowest price	select p.*  from (     select pid, min(price) as minprice     from prdtfrn     group by pid ) pm inner join prdtfrn p on pm.pid = p.pid and pm.minprice = p.price 	0.000998007056910345
9264815	28177	need help on aggregating data into a view (sql server)	select fruit,         [date],         sum(amount) as amount,         sum(case when bought_from_us = 'yes' then amount else 0 end)                    as amount_from_us from original_table group by fruit, [date] 	0.689756528039315
9264847	16621	extract only uppercase text from db field	select foo where myisallupperfunc(foo) = 1; 	0.000222535707603013
9264907	1925	how to sort date in mssqlserver	select convert(nvarchar(10), date_submit_inner, 103) as date_submit from  (     select distinct date_submit as date_submit_inner from tblformno2 ) as t order by t.date_submit_inner asc 	0.0525345958109496
9267719	24448	using a sub-select as a returned column	select st.id, st.name, group_concat(ct.classid) as classlist     from studenttable st         inner join classtable ct             on st.id = ct.id     group by st.id, st.name 	0.158732486599549
9270530	35885	difference between 3 values of 2 tables	select     cast(a.id as varchar(200)) + '-' +  cast(b.id as varchar(200)) + '=' + cast(a.id - b.id as varchar(200)) id     ,cast(a.att1 as varchar(200)) + '-' +  cast(b.att1 as varchar(200)) + '=' + cast(a.att1 - b.att1 as varchar(200)) att1     ,cast(a.att2 as varchar(200)) + '-' +  cast(b.att2 as varchar(200)) + '=' + cast(a.att2 - b.att2 as varchar(200)) att2 from     tablea a     inner join tableb b on a.id = b.id 	0
9272317	37193	date ranges in sql	select *  from accounts  where trial_expiration_date between date_sub(curdate(), interval 1 month)      and date_sub(curdate(), interval 2 week) 	0.0126923489847916
9272420	23754	i want to display the recipe containing the given ingredient but having other ingredients too	select r.* from recipe r inner join relationship ri on r.id=ri.recipe_id inner join ingredients i on i.id=ri.ingredients_id group by r.id having count(distinct i.ingredients_name)>2 and        count(distinct case when i.ingredients_name in ('chicken','mayonnaise')                             then i.ingredients_name end)=2 	0.000704532415411078
9273607	36153	mysql select count with another select count	select username,         avatar,        (select count(*) from tbl_entries where user_id = x) as entry_count from tbl_users  where user_id = x 	0.00896399853910597
9274379	10967	get the first record from the result set	select * from   (          select e.employeeid, h.fromdate, h.todate                 , rn = row_number() over (partition by e.employeeid order by designationid desc)          from   employee e                 inner join history h on h.employeeid = e.employeeid        ) eh where rn = 1 	0
9274457	32294	sql server - round time values to the next minute	select  dateadd(minute, ceiling(datediff(second, 0, cast(cast(pa.ora_inizio as datetime) as time)) / 60.0), datediff(day, 0, pa.ora_inizio)) as begin_time_rounded 	0.000509854216019683
9276514	29582	postgresql select query for date	select * from logs where creation_date >= now() - interval '15 minutes' 	0.160528908876175
9276914	387	how to query for all events on a given day, using the sql server sysschedules model?	select     *  from       msdb.dbo.sysschedules  where   (active_start_date = 20120228)      or (freq_type = 4 and freq_interval = 1)       or (freq_type = 4 and freq_interval = 14 and datename(dw, convert(datetime, convert(varchar(8), active_start_date), 112)) = 'tuesday')          or (freq_type = 8 and ((freq_interval & 4) = 4))           or (freq_type = 16 and freq_interval = 28)          or (freq_type = 32 and freq_interval = 3              and (freq_relative_interval = 8 or freq_relative_interval = 16))   	0
9277724	2163	mysql query to select last record for each of the past 7 days	select tracking.* from tracking inner join      (select max(lastchecked) as maxlastchecked, id from tracking      where datediff(lastchecked,now())<=7         group by day(lastchecked)) as lookup on lookup.id = tracking.id             where tracking.propertyid = 1 order by tracking.lastchecked asc 	0
9277834	21924	recurring events, sql query	select distinct(e.eventid),n.nameid,n.firstname,n.lastname,d.dt as dait,r.recurring from dates d  left join recurringtypes r on (r.rectypeid between 2 and 8 and r.day = d.dow)  or ((r.rectypeid between 9 and 36) and r.day = d.dow and r.occurrence = d.occurrence)  or (r.rectypeid >= 37 and r.day = d.dow and r.islast = d.islast) left join events e on e.rectypeid = r.rectypeid left join eventtypes t on e.eventtypeid = t.eventtypeid left join names n on e.namesid = n.namesid where (d.dt between '2012/02/01' and '2012/05/01') union select e.eventid,n.nameid,n.lastname,n.firstname,e.firstdate as dait,'no' as recurring from events e left join names n on n.names = e.namesid  and e.rectypeid <= 1  where e.firstdate between '2012/02/01' and '2012/05/01'  order by dait; 	0.197129997937742
9279249	7023	use column defined from subquery in query	select * from (   select *,   seats_reserved =   (select count(uid)   from person where person.res_date = reservation_dates.res_date    and person.archive = 'false')   from reservation_dates   where term = ? )   as data where seats_reserved < max_seats; 	0.345673484847169
9279417	1523	order by and group by of mysql query	select p_id, name, quantity from (   select p_id, name, quantity, name as parent, 1 as level     from product   union   select a.p_id, a.name, a.quantity, p.name as parent, 2 as level     from attribute a join product p on a.p_id = p.p_id ) combined order by parent, level, name 	0.223078777759693
9282003	31442	sql: counting dates formatted as varchar	select count(date_added)  from abatements_doc  where convert(datetime,date_added,1) >= convert(datetime,'07/01/2011',1) 	0.00534230484705302
9282099	39555	how do i query whether a row has n rows in another table that foreign key it?	select * from cards where (cards.id in (     select distinct cardid     from tags     where attributeid in (13, 45)     group by cardid     having (count(attributeid) >= 2) )) 	0
9282260	32364	sql every month basis report.	select myfield1,myfield2,...month(mydatefield) as monthdate,year(mydatefield) as yeardate  from mytablename order by yeardate,monthdate 	0.000690109420209559
9282407	21754	mysql, filtering but counting for different values	select t.name, count(*) as matches, sum(case when result = "win" then 1 else 0 end) as wins, sum(case when result = "draw" then 1 else 0 end) as draws, sum(case when result = "loss" then 1 else 0 end) as losses from teams t, matches m where competion = 'uefa' and t.name = m.team group by t.name 	0.00233266049445444
9282848	31583	crystal reports - limit records at startup to reduce start/refresh time?	select top 100 * from mytable; 	0.0496473003771566
9283325	37534	mysql count multi columns	select date(date_add) as date,         sum(case when user_id = 2422 then 0 else 1 end) as web,        sum(case when user_id = 2422 then 1 else 0 end) as iphone from stats group by date(date_add) 	0.0356146947415592
9283742	35651	showing the total amount in one line (sql server)	select sum (quantity*price) as total from item 	5.61248345776855e-05
9284536	1728	sql: exception to an otherwise sorted result set	select fruit as popluar_choices       from menu  order by case fruit when 'grapefruit' then 0                                       else 1               end,          fruit 	0.0324210293267584
9285660	15072	mysql - row number in recordset?	select table.*,@rn:=@rn+1 as row_num from table,(select @rn:=0) as r order by field_you_like 	0.00184079196204145
9287207	11747	display unique row from two tables	select employeeid, name, sum(amount) as totalbonus from (select employeeid, name, amount from @q1 union all select employeeid, name, amount from @q2) as all  group by employeeid, name 	0
9291592	30891	union issue for getting total count	select count(*) from (   (select name, phone from table1)    union    (select name, phone from table2)   ) as combined_table 	0.10438171750646
9293122	28960	inner join between three tables in mysql	select con.name as contact_name , com.name as company_name,campa.name as campaign_name from contact con inner join company com on con.companyid = com.companyid inner join campaign campa on com.campaignid = campa.campaignid 	0.261949929998434
9294130	32842	auto order in a select	select     count(userid) as c, month(createdate) as m, day(createdate) as d from       dbo.aspnet_membership where     (createdate between '2012/1/21' and '2012/2/19') group by  month(createdate) as m, day(createdate) as d order by  month(createdate) as m, day(createdate) as d 	0.0204949550417216
9294557	19857	stored procedure to get paged sorted results with a computed data column	select *      ,row_number() over (order by                     case when @sortfield = 'orderdate' and @sortorder = 'desc' then orderdate end desc,                     case when @sortfield = 'orderdate' then orderdate end,               case when @sortfield = 'netamount' and @sortorder = 'desc' then netamount end desc,                     case when @sortfield = 'netamount' then netamount end,               case when @sortfield = 'id' and @sortorder = 'desc' then id end desc,                     case when @sortfield = 'id' then id end,         case when @sortfield = 'gross' and @sortorder = 'desc' then netamount - discount end desc,                     case when @sortfield = 'gross' then netamount - discount end           ) as rowid                  from tborder 	0.000834780163754628
9295616	40357	how to get list of dates between two dates in mysql select query	select * from  (select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from  (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,  (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) t1,  (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) t2,  (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) t3,  (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) t4) v where selected_date between '2012-02-10' and '2012-02-15' 	0
9295758	34862	sql select from multiple records only the most recent	select id, name, value from customer_age where id in (     select min(id) as id     from customer_age     group by name ) 	0
9295900	17054	do i need a join?	select `products`.`products_model`, `products_description`.`products_name` from products, products_description, products_to_categories where `products`.`products_id` =  `products_description`.`products_id`     and `products`.`products_id`= `products_to_categories`.`products_id`     and `products_to_categories`.`categories_id` <> '91'  order by `products`.`products_model` desc 	0.749622586059212
9296229	583	join two tables, matching a column with multiple values	select p.* from products p inner join (     select itemid     from parametersitems      where parameterid in (7, 11)     group by itemid     having count(distinct parameterid) = 2 ) pm on p.id = pm.itemid 	0.00029469406205141
9296488	21598	sql select query for multiple tables	select p.post_title,         p.post_content,         u.username,         group_concat(c.cat_title) categories from posts p  left join users u on p.user_id = u.user_id  left join category c on c.post_id = p.post_id group by p.post_id 	0.146969500506405
9296496	38419	filter results by max count(field)	select s1.member_id, s1.screen_name, s1.viewed_url, s1.viewed_url_cnt from (   select t1.member_id, t1.screen_name, t1.viewed_url, count(*) viewed_url_cnt   from tracker t1   group by t1.member_id, t1.screen_name, t1.viewed_url ) as s1 join (   select s2.member_id, max(viewed_url_cnt) as viewed_url_max from (     select t1.member_id, count(*) viewed_url_cnt     from tracker t1     group by t1.member_id, t1.viewed_url   ) as s2   group by s2.member_id ) as s3 on s1.member_id = s3.member_id and s1.viewed_url_cnt = s3.viewed_url_max 	0.169846551423623
9297331	6047	sql: best way to write a condition that checks the value of a variable when the variable could be null	select * from table where column is not distinct from var 	0.0577351060884305
9298021	23464	how would i return a salary + a 5% raise?	select last_name || ' ' || salary || ' ' || (1.05*salary) || ' ' from f_staffs; 	0.00985286169328123
9298345	23462	how do i change column headers on a return value?	select yourcolumn as nameyouwant from d_cds 	0.000312024092871475
9299861	40225	how to do mysql union with check if row exists?	select  i.title,i.category,'a' as source from table_a  where regexp 'news' union  select i.title,i.category, 'b' as source from table_b where regexp 'news' 	0.0237523881649554
9300463	30062	sql select data from three tables	select a.id as areaid, a.area as areaname,         s.id as siteid, s.site as sitename,         l.id as locationid, l.location as locationname from area a      left join site s on s.areaid = a.id      left join location l on l.areaid = a.id 	0.00434002386040033
9301291	25669	year instead of date	select top 1 year(tblorders.orderdate)     from tblorders      order by tblorders.orderdate 	0.00135174593763198
9301573	40464	grouping results from 2 tables	select roadway,startmm, endmm, count(*) from table2 group by roadway, startmm, endmm 	0.00257840249356336
9301838	22343	mysql select all elements in array	select item     from yourtable     where tag in ('1', '3', '123')     group by item     having count(distinct tag) = 3 	0.00110034149989685
9302743	38956	count multiple fields same row - sql	select count(*) as reports, q.writer     from (select writer1 as writer               from yourtable               where loc1 = 1           union all           select writer2 as writer               from yourtable               where loc2 = 1) q    group by q.writer 	0.000697925433321581
9304900	2161	determine arbitrary latest day in a month via tsql?	select     maxvalues.f1,     detail.f2 from     (     select         datepart(year, f1),         datepart(month, f1),         max(f1) as f1     from         mytable     group by         datepart(year, f1),         datepart(month, f1)     ) as maxvalues     inner join mytable as detail on         detail.f1 = maxvalues.f1 	0
9306256	17140	if condition in mysql	select *  from contact_details  where contactdeleted = 0      and (          (contactvisibility = "public")          or         (contactvisibility = "private" and contactuserid = 1)          or          (contactvisibility = "group" and contactgroup = 3)     ) 	0.297114077055729
9308596	22159	joining three different tables based on one column name	select a.amount, t.idno, t.user_id from table_a a   join (     select idno, user_id from table_b       union all     select idno, user_id from table_c   ) t   on a.user_id = t.user_id 	0
9308849	17175	calculate total of particular column in sql query	select customername, payment, id, runningtotal from t1 union all select null,sum(payment),null,sum(runningtotal or any total) from t1 	6.95500875811046e-05
9309230	10475	finding multiple attribute from group by function in a query	select movie_id, count(*) cnt  from review  group by movie_id  having count(*)>1 order by cnt desc 	0.0053993277117357
9310068	17814	sort by date ascending with nulls last	select yourdatecolumn from yourtable where yourcondition order by   case when yourdatecolumn is null then 1 else 0 end,   yourdatecolumn 	0.000286906811541863
9311262	33950	how to pull mysql data from multiple tables with order by date field?	select * from saleitems,purchaseitems,stocktransfers where your condition order by saledate,purchasedate,trfdate 	4.89244137743072e-05
9311840	22395	select newest record where multiple records exist from where/like statement	select     *  from     dve_groupmember gm where     groupmember_groupname like 'muster%'     and groupmember_startdate = (         select             max(groupmember_startdate)         from             dve_groupmember _gm         where             _gm.groupmember_groupname like 'muster%'             and _gm.person_staffnumber = gm.person_staffnumber) 	0.000114638104619588
9311906	18905	how can i build a query to get all the distinct couples (column1, column2) and the count() of each couple.?	select column1, column2, count(*) as "count" from table group by column1, column2; 	0
9312459	31097	sql comparison where values of table1 not found in table2 and showing result as table3	select items  into table3 from table1  where not exists (select items from table2 where table2.items = table1.items) 	0.0229665458375685
9313948	20432	using sum with formula based row's text content, all together with where, join, order	select  distinct a.id_stock,          b.`name` as productname,         coalesce(f.totalreceived, 0) as totalreceived,          coalesce(g.totalsent, 0) as totalsent,         (coalesce(f.totalreceived, 0) - coalesce(g.totalsent, 0)) as remainingstock from    deliveries a inner join stockcards b              on a.id_stock = b.id_stock         left join              (                 select c.id_stock, sum(c.quantity) totalreceived                 from deliveries c                 where c.direction = 'rcvd'                 group by c.id_stock             ) f on a.id_stock = f.id_stock         left join             (                 select d.id_stock, sum(d.quantity) totalsent                 from deliveries d                 where d.direction = 'sent'                 group by d.id_stock             ) g on a.id_stock = g.id_stock order by productname asc 	0.00276906278436885
9314363	23024	mysql count of distinct records after match	select    distinctmatches.type as type,   count(distinct distinctmatches.name) as quantity from (   (     select distinct       type,       source as name      from x   )   union distinct   (     select distinct       type,       destination as name      from x   ) ) as distinctmatches group by distinctmatches.type 	0.000656702651147979
9314682	36577	sql query to display unique records	select email, lname, fname   from table1   group by email, lname, fname   having count(*) > 1   	0.000448683313234524
9315030	33956	how can i select rows and group duplicate results from 2 tables based on data in a third table?	select ca.customername as [affected users]     from customeractivity ca         inner join shipperactivity sa             on ca.ordernumber = sa.ordernumber     where sa.activitydate >= '2012-02-15 00:00:00'         and sa.activitydate < '2012-02-16 00:00:00' union select ea.employeename as [affected users]     from employeeactivity ea         inner join shipperactivity sa             on ea.ordernumber = sa.ordernumber     where sa.activitydate >= '2012-02-15 00:00:00'         and sa.activitydate < '2012-02-16 00:00:00' 	0
9317394	33383	tsql- need help in total day not week	select (e.firstname + ' ' + e.lastname) as name, convert(date, p.date_entered) p_date_entered, p.part_no, sum(p.durhr) as totalhours from  produseext p join employee as e on e.employeeid = p.employeeid where e.osvendor ='myvendor'  and p.date_entered between '2/5/2012' and '2/11/2012' group by  e.firstname,e.lastname, convert(date, p.date_entered), p.part_no order by e.firstname,e.lastname, p.durhr 	0.00319509711152294
9317860	27296	mysql query bring back those not in a list	select * from (   select 'email1' as email union    select 'email2'          union    select 'email3'          union    select 'email4'          union    select 'email5'  ) as a where a.email not in (select email from tresp); 	0.0341373085284216
9318373	5054	mysql further join using concatenated field on a union result to filter them	select     joineddata.uid,     joineddata.attr,     sum(joineddata.amount) as amount from (     (         select             table_ids.uid,             table_a.attr,             sum(table_a.amount) as amount         from table_a         inner join table_ids         on table_ids.a_id = table_a.id         group by table_ids.uid, table_a.attr     )     union     (         select             table_ids.uid,             table_b.attr,             sum(table_b.amount) as amount         from table_b         inner join table_ids         on table_ids.b_id = table_b.id         group by table_ids.uid, table_b.attr     ) ) as joineddata group by joineddata.uid, joineddata.attr 	0.00662130161542065
9322734	16206	how to accumulate the sql column data	select id        ,acc_no        ,firstdigit  = (acc_no / 1000)               ,seconddigit = (acc_no % 1000) / 100         ,thirddigit  = (acc_no % 100) / 10           ,fourthdigit = (acc_no % 10)                 ,accum       = (acc_no / 1000) + ((acc_no % 1000) / 100) + ((acc_no % 100) / 10) + (acc_no % 10)   from mytable 	0.00658600385274699
9323010	5551	mysql sum using a group by on one field while also considering another field	select t1.name, t2.attr, sum(t2.amount) from t1 join t2 on t1.id = t2.id group by t1.name, t2.attr 	0
9323293	26923	mysql how to group values not specified in the where clause as "others"?	select id_browser,      count(if(id_browser in (1, 3, 6),1,0)) as 136browser,     count(if(id_browser not in (1, 3, 6),1,0)) as other_browser     from table     where [...]      group by id_browser 	0.107683503281405
9325984	17252	sql query for single table, compare table columns values	select a.citin, count(a.caseid)  from a a  group by a.citin having count(a.caseid) > 1 	5.17719957927935e-05
9327176	439	select from two rows in the same table with sql	select ifnull(q.title, a.title) title, ... (other columns) from posts a left join posts q on a.ref_postid <> 0 and a.ref_postid = q.postid 	0
9327579	15233	return data from mysql with date later than now	select   ... whatever ... from   ... whatever ... where   ... whatever ...   and projects.p_deadline>now(); 	0.000242329946502562
9327873	29207	is it possible to append the columns (structure and content) of one mysql table to another?	select * from table1 left join table2 on table1.id=table2.id 	0
9328753	10043	select subset of rows using row_number() 	select * from (     select id, name, row_number() over (order by id asc) as [rowno]     from customers ) t where rowno between 50 and 60 	0.0748313775776155
9330086	5544	how to get the result of 3 linked tables for patient coverage	select * from   oen_fed_m_rxnorm rxnorm        inner join oen_fed_d_basic_formulary formulary on (rxnorm.rxcui = formulary.rxcui)        inner join oen_fed_m_partd_plan on (plan.formulary_id = formulary.formulary_id) where  rxnorm.gcn_seqno = [your residents drug ndcs] 	0.000151166274744934
9331644	33746	mysql order by date get 10 result back then order by id again	select q.*      from (select * from table            where            (           match (title,content)            against ('+$search' in boolean mode)           )            order by date desc           limit 0,10) q    order by q.id 	7.67893602158222e-05
9332115	14236	sql query with table structure	select m.mytableid, case when dt.datatypeid = 1 and d.datatypeid =1 then d.datavalue else null end as "address1"     , case when dt.datatypeid = 2 and d.datatypeid =2 then d.datavalue else null end as "address2"     ,m.datecreated     from datatype dt inner join     data d on dt.datatypeid = d.datatypeid inner join     mytable m on d.mytableid = m.mytableid 	0.408041881652376
9333715	2746	join table multiple times to another table that may or may not have those values	select a1.name as `type`, a2.name as `size`, a4.name as `color`, sum(coalesce( i.quantity , 0 ) ) as quantity from (attribute_values a1, attribute_values a2, attribute_values a4) left join items i on i.type_attribute_value_id = a1.id and i.size_attribute_value_id = a2.id and i.color_attribute_value_id = a4.id where a1.attribute_id = 1 and a2.attribute_id = 2 and a4.attribute_id = 4 group by a1.name, a2.name, a4.name 	0
9334619	3946	mysql query using or and and on same sentence	select n1.name     from names n1         inner join names n2             on n1.name = n2.name     where (n1.tag_id = 1 or n1.tag_id = 2)         and (n2.tag_id = 3 or n2.tag_id = 4) 	0.21988194758915
9336409	24349	sql: order by count from different table with condition	select r.number,        r.title,        count(i.itemnumber) from record r left join items i on (r.number = i.number) where r.title regexp 'sql for idiots' group by r.number having count(i.itemnumber) > 100 order by count(i.itemnumber) 	0.00346971656344886
9336912	1373	selecting count from mysql table by first letter of a column	select substring(last_name, 1, 1) as letter, count(*) as total from users            group by substring(last_name, 1, 1); 	0
9340511	10961	select entries that include a certain number of words in sqlite?	select     * from     tablename where     length(columnname) = length(replace(columnname, ' ', '')) + 1; 	0
9342566	23743	how can i insert database from two different methods	select * from gall order by image 	0.00297271841102288
9345143	12003	how can i remove duplicate relationships in a mysql table data?	select *  from friends d where exists ( select 1  from friends f where f.user1 = d.user2 and f.user2 = d.user1 and f.user2 < f.user1 ) 	0.00116945174673992
9345482	29988	sql three table join	select s.*, u.timestamp from stocks s  left join  (select  su.stock_id, max(u.timestamp) timestamp from updates u  inner join stock_updates su  on u.id = su.update_id group by su.stock_id ) as u on s.id = u.stock_id where u.[timestamp] is null or u.[timestamp] < @date 	0.210100442512326
9346793	27325	determine the rank of each row in a sorted table	select posts.*, @row:=@row+1 as 'rank' from posts, (select @row:=0) r order by posts.score desc 	0
9348140	12622	how to show values in textbox from database?	select userstable.username, approvetable.approvedby, branchtable.branchname from userstable, branchtable, approvetable where userstable.branch_id = branchtable.branch_id and userstable.approved_id = approvetable.approveid and userstable.user_id = %currentuserid% 	0.000427637493789442
9350640	31910	sql query ordering when order is in same table	select t1.resource_no        ,t1.name        ,t2.value        ,t3.value    from table1 t1  inner join table2 t2     on t1.resource_no = t2.resource_no and t2.[key] = 'location'  inner join table2 t3     on t1.resource_no = t3.resource_no and t3.[key] = 'order'  order by t3.value asc 	0.180427395772092
9352135	30535	reading evaluated data from mysql database	select     count(*) as total,     sum(if(status=0, 1, 0)) as stat0,     sum(if(status=1, 1, 0)) as stat1,     sum(if(status=2, 1, 0)) as stat2,     sum(if(length(note)>0, 1, 0)) as notes,     min(timestamp) as mintime,      max(timestamp) as maxtime from tbl_name where owner="name" group by owner 	0.0172004078100714
9352926	29830	android - retrieving data from sms contentprovider - group by	select thread, message, max(date) from sms group by thread 	0.0161511831762624
9353327	9438	mysql, order by like	select  t.*  from    threads t join    (         select  threadid         ,       count(*) as postcount         from    posts         where   p.content like '%" . $search .  "%'                  or p.user like '%" . $search ."%'         group by                 threadid         ) postcount on      postcount.threadid = t.threadid order by         postcount.postcount desc 	0.72084310647868
9353462	14874	days between two consecutive records in mysql	select datediff(a.created,b.created)   from table a,        table b  where a.id = 1    and b.id = 2 	0
9353650	379	get all records with an id, but the first records should match another condition also	select * from stations  where station_group_id = 1  order by if(line_id in('2','x','y','z'),0,1) 	0
9354209	32532	how to display the date from the mysql database	select date_format(`date_column_name`, '%d-%m-%y') ... 	0
9354790	14891	stock on the fly missing values with no sales	select qrystocklevel.item, qrystocklevel.productid, [qrystocklevel].[stock]-nz([qrysaletot].[quantity],0) as stockonhand from qrystocklevel left outer join qrysaletot on qrystocklevel.productid = qrysaletot.productid; 	0.000362237096267803
9355241	12828	sql: how do you select only groups that do not contain a certain value?	select restaurant_no from restaurant where restaurant_no not in (select restaurant_no from restaurant where restaurant_location = 'city c') 	0
9355603	3354	group by date in sql server	select      productcode,productname,producttype,unitprice,qty,amount,(convert(varchar, transactiondate, 101) )as stransactiondate    from dailytransactions     group by dateadd(day, datediff(day, 0, transactiondate), 0), productcode,productname,producttype,unitprice,qty,amount 	0.21470634828475
9356876	19587	how to reduce a long sql query based on create view?	select *  from table1 inner join table2 as alias1   on table1.col1 = alias1.col1 inner join table2 as alias2   on table1.col2 = alias2.col2 where col2 = 'some_condition' 	0.296435893243629
9357765	29357	subquery returns more than 1 row	select meta_value from  wp_frm_item_metas  where (item_id in (                      select id from                      wp_frm_items where                      form_id ='9' && user_id='1'                    )           && field_id=128         ) 	0.0740009786179106
9357817	16878	sorting a column in oracle based on time	select * from   details order  by ( case when date_column between start_time and end_time then 0 else 1 end )         , date_column         , start_time; 	0.00123475364101926
9357918	33462	mssql - howto to get full list from interval of ids	select        l.id     , l.label_number from       labels l   join       created_labels cl     on       l.id between cl.label_id_from                and cl.label_id_to 	0
9358290	14570	sql like for like orders a year ago	select   customerid,   thisyear = count(case year when year(getdate()) then 1 else null end),   lastyear = count(case year when year(getdate()) then null else 1 end) from data where year >= year(getdate()) - 1   and month = month(getdate()) group by   customerid 	0.00823211995849542
9358850	23359	sql query for grouping	select employeeid, count(distinct jobsid) as jobsapplied from employeetojobsapplied where applied = 1 group by employeeid 	0.477847760534298
9359031	10495	show static value if id has no value in other tables in joinning tables	select   table1.*,   coalesce(table2.id,0) as table2id from table1 left join table2 on table2.t1_id = table1.id 	0
9359192	22645	print two rows in one column [advanced sql]	select  coalesce(i.name, o.name) [name],         i.time [timein],         min(o.time) [timeout] from    (   select  *             from    timetable             where   status = 'in'         ) i         full outer join          (   select  *             from    timetable             where   status = 'out'         ) o             on o.name = i.name             and o.time > i.time group by coalesce(i.name, o.name), i.time  order by name, timein 	0.000525728238326317
9359624	14339	sql count total given a where/having parameter	select   count(*) from (   select   actorid   from     role   group by actorid   having   count(*) > 3 )   as actors 	0.00241389185678904
9360078	18109	select rows with max value grouped by two columns	select t1.* from attachments t1 left join attachments t2 on t1.entity_id = t2.entity_id and t1.group_id = t2.group_id and    t1.version_number < t2.version_number where t2.version_number is null 	0
9360717	35388	clustered table query in mysql	select data.* from data where data.cluster is null union select data.* from       (select cluster, max(score) as score from data group by cluster)         as max_score inner join data  on data.cluster = max_score.cluster                 and data.score   = max_score.score 	0.628361073727164
9360828	40178	sql to check if value exists or not	select finalvalue from tabledetail where id in (select isnull(t2.id,t1.id) from tablea t1 on t.id = t1.id and t1.num = @num left join tableb t2 on t.id = t2.id and t2.num = @num) 	0.127396672768378
9361309	21101	sql server select ids where number of rows is above specified amount	select     count(*) as expr2,  shopid as expr1  from          orders  group by shopid having (count(*) > 5000) 	0
9361596	31731	sql server: how to set column alias from another table during select?	select      db1, foo.enumtext as db1enumtext,      db2,      db3  from      table1     cross join     (select enumtext from table2 where enumvalue='db1') foo 	0.000341190366787946
9361876	36082	comparing data field to today's date - oracle	select decode(acceptance_date, trunc(sysdate), 1, 0) from table 	0.000655591484381955
9362314	4142	can i use column alias in many positions in the query?	select *, x/total from (     select id,name,score,total,calcit(total - score) as x from tblx;  ) as tblx 	0.763512228596071
9362615	39564	php query with 2 counts and joins	select     p.*,     pl.like_count,     pc.comment_count from post p #join likes left outer join (     select         post,         count(*) as like_count     from likes     group by post ) as pl     on pl.post = p.id #join comments left outer join (     select         post,         count(*) as comment_count     from comment     group by post ) as pc     on pc.post = p.id 	0.372213847735255
9363941	17800	sql query over two column	select     count(p.booking_ref_id) as payment_count,     year(b.date_created) as payment_year from booking b inner join payment_transaction p     on p.booking_ref_id = b.booking_ref_id group by year(b.date_created) 	0.0708811478432106
9365908	30847	trying to change sql statement to use exists instead of in	select      spas.sessionrecordid,     (          select              min(timevalue) as minanaes         from tbltmactualtimes tmat         where exists                  (                      select                          null                     from                          tbltmactualoperation tmao                     where                          tmao.sessionrecordid = spas.sessionrecordid                         and tmat.operationrecordid=tmao.operationrecordid                  )             and cftimedefinitionid = 'intoans'        ) as firstanaesthetic   from      tblspactualsession spas 	0.470163599359543
9366015	19032	 how to select most ordered products in sql server?	select top 10 prodname, count(*) as ordercount from sampletable group by prodname  order by ordercount desc, prodname 	0.0055587396742309
9366021	26134	checking whether an item does not exist in another table	select p.name, p.id_string from     process p     left join value_search v         on p.id_string = v.id_string where     v.id_string is null     and p.id_string is not null 	0.000985436053723314
9367172	21142	t-sql select accounts with no activity	select distinct q.id from (select id, max(created_date) as latestdate from tablename group by id) q where q.latestdate <= '2010-11-01' 	0.197428210707089
9367327	39608	empty rows for mysql query but using a where	select      coalesce(sum( cantidadmovimiento ),0) as cantidadmovimiento,     diasemana,     date_add(date(now()), interval diasemana-weekday(now()) day) as weekday from diassemana left join lcmovimientos     on diasemana = weekday( fechamovimiento )      and week(fechamovimiento) = week(now()) and year(fechamovimiento) = year(now()) group by diasemana; 	0.100546432851167
9367655	16632	adjust sql query to force a record to appear first?	select * from members order by case when memberid = xxx then 0 else 1 end 	0.00711216135013416
9368041	30037	can a mysql select query look for specific characters?	select time, value from temp_table where time between '2012-01-01' and '2012-02-20 23:59:59'   and second(time) = 0 group by time 	0.0950954832204301
9368417	22117	datasets in c#.net -- how to access related tables via a universal row	select table1.id as t1_id, table2 as t2_id ... 	0.0011770086925481
9369257	7123	find and store db relationships in mysql / php	select t1.userid, t2.userid from table t1, table t2 where t1.userid = t2.userchoiche    and t2.userid = t1.userchoiche 	0.0287692215938473
9369943	5283	select difference in record count between 28 days	select table_name,        record_count,        prior_record_count,        record_count - prior_record_count diff   from (select table_name,                record_count,                lag(record_count)                    over (partition by table_name                             order by created) prior_record_count,                rank()                   over (partition by table_name                            order by created) rnk            from <<name of table>>)  where rnk = 1 	0
9369963	6964	mysql order by 1+ and append 0 to the end	select  ...... order by show_title asc, seasons asc, (episode>0) desc, episode asc 	0.0101255163646208
9370175	20166	concisely retrieve many variables from a select	select * 	0.00446871483080727
9370437	38457	multiple inner join from the same table	select m1.metalcode as 'metal1', m2.metalcode as 'metal2',m3.metalcode as 'metal3' from item as k inner join metals as m1 on m1.metalid=k.metal1  inner join metals as m2 on m2.metalid=k.metal2 inner join metals as m3 on m3.metalid=k.metal3 where k.itemid=? 	0.00473489801704683
9372531	25143	how to get the rows that has the value above 3 minutes in this sql query?	select * from (      select trunc(a.received_ts) day, to_char(avg(extract(minute from b.received_ts - a.received_ts)*60 + extract(second from b.received_ts - a.received_ts)), '999.99') diff_in_secs, count(*)     from nps_request a, nps_reply b     where a.id = b.id     and a.received_ts > trunc(sysdate) - 10     and b.target_id is not null     and b.received_ts is not null     group by trunc(a.received_ts)     order by trunc(a.received_ts) desc; ) as a where a.diff_in_secs > 180 	0
9374445	13835	return 0 on count()	select      cities.cityname,      coalesce(count( intimeperiod.id ),0) as city_count from cities inner join people as haslivedin     on haslivedin.cityid = cities.id     and people.firstname =  'john'     and people.lastname =  'doe' left join people as intimeperiod     on intimeperiod.cityid = haslivedin.cityid     and intimeperiod.residency_date between date('1996-08-01') and date('1997-05-31') group by cities.cityname 	0.0382509887644208
9374716	8872	how to get cumulative totals mysql	select      consignment_date.*,     consignment_date.credits - consignment_date.costs as totalcosts,     (@runningtotal := @runningtotal + consignment_date.credits - consignment_date.costs) as netreturn from (     select         consignment_date,         sum(receipts) as credits         sum(service_amount + repairs + tyres + salaries_allowances + clearing_fee + others) as costs     from vw_local_freight      where vehicle_no = '123x'     group by consignment_date ) as a, (select @runningtotal := 0) as b 	0.00221933831965275
9375041	1573	count from single column and seperate it into 2 column	select a_id,     sum(case when rate='like' then 1 else 0 end) as 'like',     sum(case when rate='dislike' then 1 else 0 end) as 'dislike' from rating group by a_id 	0
9375571	10127	search different column names in different tables in mysql	select content.title, 'content' as src_table from content where title = 'keyword' union select news.mytitle, 'news' as src_table from news where mytitle = 'keyword' 	9.43641408300759e-05
9376514	31532	sql - select query for complex dynamic rows	select       t1.listingid from        tablex as t1    join                                       tablex as t2     on        t2.listingid = t1.listingid    join                                       tablex as t3     on        t3.listingid = t1.listingid  where        (t1.extrafieldid, t1.value) = (@extrafieldid_search1, @value_search1)   and        (t2.extrafieldid, t2.value) = (@extrafieldid_search2, @value_search2)   and        (t3.extrafieldid, t3.value) = (@extrafieldid_search3, @value_search3) 	0.731870679601786
9376856	38665	mysql minimum and maximum values of "rate" for each month	select     year(date) as thisyear,     month(date) as thismonth,     min(rate) as minrate,     max(rate) as maxrate from rates group by thisyear asc, thismonth asc 	0
9377707	11534	sql group by one column	select t0.id, t0.initial_date, t0.tax from (  select *, row_number() over(partition by id order by tax desc , initial_date desc) corr         from t) t0 where t0.corr = 1 	0.0228006489088025
9379282	10243	php mysql_insert_id() for mysql uuid() primary keys?	select uuid() 	0.39535824988788
9380965	26816	sqlite sorting text field	select * from test_table order by testname collate nocase; 	0.150836318688828
9381240	4775	identity increment	select identity(int,1,1) id, calls.*,patient.* into calls2 from calls,patient 	0.0438638897348392
9382086	17939	sql - group by parts of a string in sql	select substring_index(flavor,'_',1), sum(purchase) from table group by 1 	0.0349576662872796
9383003	14945	return value from nested sql	select      cop.wo_id,     oi.cop_workorder_id as order_item_wo_id from oseo_cop_wo as cop     left join oseo_orderitem as oi         on oi.cop_workorder_id = cop.wo_id where cop.wo_id = '123'; 	0.0248569909484655
9383627	1812	how to divide one select with another	select jmeno,         prijmeni,         cast(pr_o as float)/(avg(pr_o) over()) div from   (select jmeno,                 prijmeni,                 count(id_objednavky) pr_o          from   objednavky o                 join zamestnanci z                   on z.id_zamestnance = o.id_zamestnance          where  year(datum_odeslani) = 2010          group  by jmeno,                    prijmeni)aa 	0.00116787023549883
9383927	39922	how to join a mapping table in my query	select questions.*       , posts.post      , count(posts.post) as total_answers      , posts.votes      , posts.id as post_id      , posts.created      , users.id as user_id      , users.username, users.rep      , topics.name 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 left join topics on topic_mapping.topic_id = topics.id group by questions.id 	0.599256984665166
9384140	25467	sql multiple joins on the same table	select list_code,        count(donor),        sum(case when rectype = 'p' then 1 else 0 end) as pcount,        sum(case when rectype = 'g' then 1 else 0 end) as gcount     from dpgift     group by list_code 	0.0107106315795543
9386735	219	how to subtract one table sum from other	select article.name , (select sum(issue.quantity) from issue where issue.articleid = article.id and issue.personid = 2) - (select sum(return.quantity) from return where return.articleid = article.id and return.personid = 2) from article 	0
9386921	27906	mysql join and count	select  t_state_id_state       , t_state_name_full        , count(distinct t_location_id_location) as locations_number   from          t_state     left join          t_citystate   on t_state_id_state = t_citystate_id_state      left join          t_city   on t_citystate_id_state = t_city_id_city      left join          t_zipcodecity   on t_city_id_city = t_zipcodecity_id_city      left join          t_location   on t_zipcodecity_zipcode = t_location_zipcode    group by t_state_id_state    order by t_state_name_full asc ­ 	0.384204383104433
9387303	34903	full outer join - intertwined values from joined columns	select coalesce(city, name) as city_name ... 	0.0393470904300008
9388216	4361	sqlite subquery for group of ranked items	select s."group"   , s."rank"   , s."score"   , s."score"/ts."score" as "scoreratio" from scores s   join (       select "group", "score"       from scores       where "rank" = 1   ) ts   on s."group" = ts."group"     and 0.95 * ts."score" <= s."score" 	0.0364292252106726
9388489	9742	flooring timestamp to second	select current_timestamp(6),    date_trunc('second', current_timestamp(6)) 	0.00463127162156411
9389988	4961	sql server pivot table not grouping result set	select      emp_code,     [cl],     [lwp],     [pl],     [sl]  from  (     select          emp_code,          leavename,          act_days     from          @tmp_emp ) l  pivot (     sum(act_days)      for leavename in ([cl],[lwp],[pl],[sl]) )  as pvt  order by emp_code 	0.446385981319223
9391134	33115	how to query get max id from varchar type?	select max(cast((substring(id,2)) as decimal(5,2))) from table; 	0.000142567801099004
9391356	4681	sql - find average salary for each department with more than five members	select department,count(staff_id) as countstaff, avg(salary) as avgsalary from staff group by department having count(staff_id) > 5 	0
9392042	23102	sql - two tables retrieving data	select la.id,st.profilename, la.totalevents,la.date,ft.eventcategory from lasttable la inner join secondtable st on st.id=la.id inner join firsttable ft on ft.id = la.eventcategoryid 	0.00191724120465329
9392580	35675	display dates with comma separation	select   c.*,   e.name,   group_concat(if(month(date_entered) = 1, dayofmonth(date_entered), null)) jan,   group_concat(if(month(date_entered) = 2, dayofmonth(date_entered), null)) feb,   group_concat(if(month(date_entered) = 3, dayofmonth(date_entered), null)) mar from emp e   join customer c     on e.id = c.visited_by_emp_id group by e.id, year(date_entered) 	0.000711315149623298
9392907	17873	get percetage in one query	select   sum(if user=11,1,0)*100/count(*) as percentage from table_user; 	0.0162617646940343
9393646	38388	how to filter a query based on 2 fields	select id, user_id, type, title, description from   user_qualifications where  work_exp = 2 and education="ms" 	0.000319643811657299
9394758	21779	count rows with a specific condition in aggregate query	select  country,         count(*) as total,         count(case when reconnect = true then 1 end) as with_reconnect from    playersession s          left join player p              on p.id = s.player_id group by country 	0.0372658746914057
9396105	4679	how to find max of datetime value of each group in group by clause	select username, max([datetime]) from tablename group by username 	0
9396605	13191	moving multiple row data into its own column	select userid, fnm, lnm,     max(case when measure='lnf' then score else 0 end) as lnf,     max(case when measure='nfs' then score else 0 end) as nfs,     max(case when measure='cfs' then score else 0 end) as cfs from temptable group by userid, fnm, lnm 	0
9397925	22173	select values matching value from other column in the same table	select category_id from mytable where tag_id in(183, 200) group by category_id having count(distinct tag_id) = 2 	0
9398351	859	representing rows that do not exist or null rows	select p.mfg, p.part_number, last_call = max(c.yyyymm)   from dbo.product as p   inner join dbo.stock as s     on p.mfg = s.mfg and p.part_number = s.part_number   left outer join dbo.calls as c     on p.mfg = c.mfg and p.part_number = c.part_number     and c.yyyymm < '201202'  where s.onhand > 0; 	0.0150807976099629
9399410	32336	sql pulling from sub query	select b.topbid, b.topdate, a.*  from auction_items a left join ( select itemid, max(bid) as topbid, max(date) as topdate    from auction_bids   group by itemid ) b on a.id = b.itemid order by a.date desc limit 15 	0.142505625710302
9400435	21950	case from select with null	select * from tbl where (@type = 'o' and ol is null) or (@type <> 'o' and ol is not null) 	0.359544795164823
9400909	18274	opposite to top	select top 1 orderdate from ordersview order by orderdate desc 	0.0796837848778716
9401512	23212	sql order with join	select b.topbid, b.topdate, a.*  from auction_items a  left join     (select itemid, max(bid) as topbid,     max(date) as topdate from auction_bids group by itemid ) b  on a.id = b.itemid  order by coalesce(b.topdate, a.date) desc limit 20 	0.76170485159436
9404052	17468	mysql query for concatenate unknown number of values in a new field	select     `job_id` as `job id`,    group_concat(`employee_name` separator ", ") as `employee names` from    `table1` group by     `job_id` 	6.69937566203731e-05
9404430	27340	oracle/sql - multiple records into one [string aggregation]	select replace(blah2,',','')   from ( select wm_concat(blah) as blah2            from ( select '<option value="' || sid || '">' || city || '</option>' as blah                     from my_table                          )                  ) 	0.000909764108735344
9405627	38867	sql retrieve data from two table based on the id(key) of the first table	select    o.*,    s.* from    dbo.object o    outer apply (       select top 1 *       from dbo.objectstatus s       where o.objectid = s.objectid       order by datechanged desc    ) s 	0
9409630	39169	mysql : order differently within the same column	select * from foo order by if(fooid>0,rand(),-0.1) desc; 	0.00749704136893608
9410492	12534	sorting available products by date in php and mysql	select * from product p join date d  on p.product_id = d.product_id where d.date between '2012-05-05' and '2012-05-20' order by d.date desc 	0.00244286379023928
9410632	24197	mysql match against ~ example	select * from tbl where match(hotel) against('+the mill hotel' in boolean mode) limit 10"; 	0.382873010853796
9410686	16254	convert int to float in sql	select myintfield + 0.0 as myfloatfield from mytable 	0.176032436112426
9413663	12387	repeat remove quotes from 48 fields	select  'update [majestic].[dbo].hdiyouth_school_2 set ['+column_name+']=left(right(cast(datetime_updated as nvarchar),      len(cast(datetime_updated as nvarchar))-1),     len(cast(datetime_updated as nvarchar))-2) where datetime_updated is not null and datetime_updated like ''"%"'';' from information_schema.columns where table_name='employee' and table_schema='humanresources' 	0.00269142482465788
9416692	19434	how to get a list of user accounts from hsql?	select * from information_schema.system_users 	0
9416937	17430	how to join in an sql query across four tables?	select p.name from assignmentexception ex     join assignment a on ex.id = a.assignmentid     join project p on a.projectid = p.id where ex.type > 0     and p.installationid = 12345 	0.110470996013688
9417181	28374	efficiently showing the user only items he did not already see before (mysql)	select       a.id,       a.title,       a.text     from        articles a          left join article_views av             on av.user_id = 123            and a.id = av.article_id    where       av.article_id is null 	0
9419565	36856	how do you run a query to find all data in a row?	select firstname, lastname from persons where email = '$email' 	0.000263833607729361
9420065	15191	how to do in mysql one query to get username and same query to get another username from same users table?	select  a.userid,          a.senderid,          a.something,         b.username,          c.username from    mail a         left join users b on b.id = a.senderid         join      users c on c.id = a.userid where   a.id='1' 	0
9421135	12981	union select not displaying union results	select inspection_number, region, report_date,  inspection_type, key, report_key, shipper, po, commodity, label, status as type, customer, customer_number, shipper, po, key, report_key, shipper, po, commodity, label, status from reports join ( 	0.525211648224771
9421316	28005	oracle: i need a "partial" outer join. look at the image	select    coalesce(a.master,b.master) master,    a.cola,    b.colb from   a full outer join b   on a.master = b.master      and (a.cola = b.colb            or a.cola is null           or b.colb is null) order by      coalesce(a.master,b.master),     coalesce(a.cola,b.colb) 	0.626303686292784
9423515	25627	1:n relationship and sql query	select distinct  cat_id, categories.name from entries join categories on categories.id = entries.cat_id 	0.369260816890811
9423758	3610	changing row "status" in mysql for different time intervals in real-time	select   user,   from,   subject,   time,   created,   read,   if(now() - interval 7 day > created, 5,     if(now() - interval 3 day > created, 4,       if(now() - interval 2 day > created, 3         if(now() - interval 1 day > created, 2           if(now() - interval 1 hour > created, 1             0           )         )       )     )   ) from messages where user = 'foo' 	9.61757122677583e-05
9427350	40572	delphi: how to get table structure into object	select * from databasename.information_schema.constraint_column_usage  where table_name='tablename' 	0.00539752650439819
9427715	4232	get only date from date variable sql server	select subjectindex,letterno, cast(dateofissue as date) as dateofissue from [circularkeeper]   order by dateofissue desc 	0.000177073214004787
9430156	36829	sql query join and aggragation at the same time	select pp.projectid,pp.projectalias,sum(pd.projectpossibilityratio)     from project pp inner join projectcompletion pc on pp.projectid=pc.projectid      join projectprocedure pd on pd.projectprocedureid=pc.projectprocedureid      group by pp.projectid,pp.projectalias 	0.0148640298901952
9432161	33173	three tables difference query	select     n.name from names n left outer join todo t     on t.name = n.name     and t.date = your_date left outer join tasksdone td     on td.name = n.name     and td.date = your_date where     n.status = 'available'     and t.name is null     and td.name is null 	0.0344682475008636
9432908	33951	how do i output all rows of mysql table and include a column for counting duplicates?	select losers.*, (select count(*) from losers as sub where sub.name = losers.name) as `count` from losers order by date desc 	0
9433743	14014	group by and sorting before a where clause?	select * from yourtable where _record_status <> 'deleted' and ticket = @yourticketid 	0.64417240985013
9434087	30759	select recent events with all activities listed sql	select   * from   event inner join (   select   eventname, date   from     events   group by eventname, date   order by date desc   limit    20 )   as last_20_events     on  last_20_events.eventname = events.eventname     and last_20_events.date      = events.date 	0.000224027926803431
9435514	19056	sql - find users with at least 1 order and have conditions for each order. use count?	select users.email from users   join     ( select user_id, max(created_at) as created_at       from orders       group by user_id       having max(created_at) < curdate() - interval 3 month     ) as oo     on oo.user_id = users.id order by oo.created_at desc 	0
9437185	27760	mysql where from two tables	select * from products as p   left join categories as c on p.category = c.id   where c.name like 'category #1' 	0.0073676728599243
9437907	23980	add database table from website	select * from colleges where name = 'university of wisconsin' order by student_count asc 	0.00434012999399975
9438661	36296	mysql group by zip code	select left(zip,5) zip, count(id) as total from subscriptions where status = 'a' group by left(zip,5); 	0.497190005613341
9438729	29426	php + mysql date issue	select * from results, sync_info      where insertiondate between sync_info.last_sync and now() 	0.694619022099825
9440313	12549	joining two tables with mysql for aggregation?	select catid, categoryname, parent, count(*) totalprods from categories c inner join products p on p.catid = c.catid group by catid 	0.0499049221495885
9441592	23587	how do i select the max value after a sum() + group by?	select t.x  (select c.name x, sum(o.order_total)  from client c, orders o  where c.client_id = o.client_id    and year(o.date) = 2011  group by o.client_id  order by 2 desc  limit 1) t; 	0.00135519485051855
9441737	28293	mysql limit before grouping?	select *, count(*) as count from (select * from `posts` limit 30) t group by `category` 	0.183523223781249
9442163	8414	php mysql table inheritance	select f.*, h.* from food f join hotdog h on f.id = h.food_id where f.chief_id = chief0001 	0.211366901875379
9449785	14257	select data from two independent tables	select distinct coalesce(e.email, c.email) as email from emails e full outer join customers c on e.email = c.email where e.email is null or c.email is null 	0.00129213909382674
9449930	32894	run through a column in the mysql table for a specific word	select count(*) from users where username = $user 	0.00128383013705768
9449980	21009	"select" dilemma	select u.username, c1.name as location, c2.name as hometown from users as u left join cites as c1 on u.locationid = c1.id left join cites as c2 on u.hometownid = c2.id where u.id = 1 limit 1; 	0.408973127331197
9450789	2361	how to select row with a largest value in its group?	select   id,   taskname,   date from (   select      id,     row_number() over (partition by taskname order by date desc) ordinal,     taskname,     date   from yourtable ) t where ordinal = 1 	6.68365875211085e-05
9451267	41153	struggling to count and order by a column by reference in t-sql database	select id, ds, nm from (     select row_number() over (order by o.nm asc) as rownum, u.id, u.ds, o.nm     from t_usrs u inner join t_orgnzs o on (u.oid = o.id) ) t  where rownum>=1 and rownum<=16; 	0.225355074443979
9451323	19233	accessing multiple rows from a table	select     a.* from    question q    left outer join answer a on a.questionid = q.id where    q.id = 999 	0.000245249226957346
9452109	12817	sql query count divided by a distinct count of same query	select channel,         count(*) over (partition by channel, loc_code)         / count(*) over (partition by loc_code) as count_ratio from my_table 	0.00274762138103478
9452258	28057	how to display mysql count horizontally	select store_name,        sum(case when status = 'hold' then 1 else 0 end) as hold_count,        sum(case when status = 'ship' then 1 else 0 end) as ship_count,        sum(case when status = 'return' then 1 else 0 end) as return_count from table group by store_name 	0.00918894184671529
9452895	2168	mysql join query max value	select t1.* from mytable t1 left join mytable t2 on t1.parentid = t2.parentid and t1.rating < t2.rating join mytable parents on parents.id = t1.parentid where t2.rating is null and parents.name like '%mike%' 	0.14221609221159
9453578	30268	non aggregated average in mysql?	select   accounts.*, avg_amount.amount as avg_amount from   accounts left join (   select account_id, avg(amount) as amount from (     select month, account_id, max(amount) as amount from invoices group by month, account_id   ) as max_amount using(account_id) ) as avg_amount on (accounts.id = avg_amount.account_id) 	0.00633522510992146
9454585	35459	get data from last 30 minutes and get the latest rows	select timestamp, a.mmsi, navstatus, rot, sog, lon, lat, cog, thead, man, mtype from ais_cnb a inner join (select mmsi, max(timestamp) as max_timestamp from ais_cnb  where timestamp > (now() - interval 30 minute)  group by mmsi) t on ((timestamp = t.max_timestamp) and (a.mmsi = t.mmsi)) 	0
9455270	32606	mysql if statement for 2 tables	select   users.id as id,   users.username as username,   users.avatar as avatar,   ifnull(users_preferences.privacycontrols, 0) as userprivacy from   users   left join users_preferences on users_preferences.userid = users.id where   ifnull(users_preferences.privacycontrols, 0) = 0   and users.username like '%demo_user%' 	0.0878485011870703
9456915	26679	how to get related data from 2nd table in same select?	select p.*, (select filename from images i where i.id=p.which_image) as filename   from people p  where p.id in (1,3) 	0
9456919	39480	search between two sql tables?	select first_name, last_name, 'student' as `type` from   students where  first_name like '%<your string>%'    or  last_name  like '%<your string>%' union select fname, lname, 'teacher' as `type` from   teacher_accounts where  fname like '%<your string>%'    or  lname like '%<your string>%' 	0.015629027038033
9457077	31561	group by, group_concat, concat and how to select	select o.id, concat_ws("||", group_concat(gx.gid separator "|"), group_concat(gr.title, "#", gr.color separator "|")) as groups  from objects as o  join group_ref as gfilter on o.id = gfilter.oid and gfilter.gid=4 left join group_ref as gx on o.id = gx.oid  left join groups as gr on gx.gid = gr.id  where 1  group by o.id 	0.454717571968606
9458376	26466	mysql query to pull data even if no date is specified via php	select * from table_name where date <= "2012-02-10" order by date desc limit 1 	0.00427531146182761
9459822	36236	mysql querying two tables with different fields	select id, title, start, end, allday   from calendar    where mem_id='$logoptions_id'      and start >= date_sub( curdate( ) ,interval 0 month )    union all    select id,      title collate collation_name as title,      start, end, allday   from team_calendar    where team_id in (1,2)      and start >= date_sub( curdate( ) ,interval 0 month )    order by start asc limit 5 	0.00138246183865358
9460244	11180	order by the result of an expression on each result / user-generated meta data sorting	select   items.id,   items.color,   max(case when title = 'shape' then data else null end) as shape,   max(case when title = 'sound' then data else null end) as sound from items left outer join metadata on items.id = metadata.itemid group by items.id, items.color order by   case when shape is not null then 0 else 1 end,   shape 	0.000462952901927095
9460974	26283	mysql : sort id by a given string of id ? (building breadcrumbs for hierarchical-data)	select *  from category where category_id in ( 1, 6, 7, 8 )  order by category_id =1 desc , category_id =8 desc , category_id =7 desc , category_id =6 desc 	0.000152414657341983
9461642	35659	mysql query to check occurence which happened on each day between two dates?	select username, count(*) as nbr_day from (     select username, date(last_activity_time) as last_activity_date     from my_table     where ( last_activity_time >= @date1 )     and ( last_activity_time < date_add( @date2, interval 1 day) )     group by username, last_activity_date ) as sub group by username having ( count(*) = 1 + datediff(@date2, @date1) ) 	0
9463773	13348	sql: calc average times a customers ordered a product in a period	select precount.productno,        precount.totalcount / precount.countofyrweeks as avgperweek,        precount.totalcount / precount.countofyrmonths as avgpermonth,        precount.totalcount / precount.countofyears as avgperyear from   (select ol.productno,                count(*) totalcount,                count(distinct datepart(wk, o.orderdate)) as countofyrweeks,                count(distinct datepart(mm, o.orderdate)) as countofyrmonths,                count(distinct year(o.orderdate)) as countofyears         from   orderline ol  join [order] o                  on ol.orderno = o.orderno         group  by ol.productno) precount 	0
9464365	3761	postgresql join 2 tables	select t1.*, t2.action from tab1 t1 join (select t.*,              row_number() over (partition by tab1_id order by id desc) rn       from tab2 t) t2   on t1.id = t2.tab1_id and t2.rn = 1 	0.114365885144168
9464952	31188	oracle select months out of a timeframe	select      id,       add_months( "from", n.n ),      to_char( dt_column, 'mm' ) ,      to_char( dt_column, 'yyyy' )   from   yourtable t   inner join   (select rownum n    from   ( select 1 just_a_column          from   dual          connect by level <= 365   ) n     on add_months( "from", n.n ) <= last_day( t."to" ) 	0.00270326503018409
9465843	29745	sort in "original order" when using distinct	select filename from tableb group by filename order by min(id) 	0.133875504587298
9466869	40312	sort by popularity	select t3.name, count(*) as cnt from  (select t1.meta_value as name, t2.meta_value as type, t2.item_id as field_id  from  ( select * from wp_frm_item_metas where field_id=9) as t1 inner join ( select * from wp_frm_item_metas where field_id=13) as t2 on t1.item_id = t2.item_id where t2.meta_value="booked") as t3   group by t3.name order by cnt desc 	0.171835786000866
9470872	39587	taking duplicate lines and squeezing them into 1 row on sql server 2008 r2?	select  uid,         name,      age,     stuff(     (select ',' + child as [text()]             from parentchildren b             where a.uid = b.uid     for xml path('')),1,1,'') [childconcat] from parentchildren a 	0.000621985488077636
9471010	15431	select distinct emails from multiple tables	select email_address from table1   union select email_address from table2   union  	0.0021938790144037
9471189	4381	how do i combine these selects/joins?	select tile, description, link, groupname from table_2 join table_1 on table_2.userid = table_1.id join table_3 on table_3.id = table_2.table_3id join table_4 on table_4.id = table_2.table_4id 	0.201904953717379
9477366	12797	sql - joining tables	select c.comment_id, c.member_id, c.comment, c.posted, m.screen_name, m.country_code        sum(r.points) `member_rep` from blog_comments `c` left join members `m` using (member_id) left join members_reputation `r` using (member_id) where c.article_id = "&article_id&" order by c.comment_id desc 	0.108255547574035
9479269	40859	retrieve records using sql query	select     * from     undefined_table_name group by     image_type  order by    image_type asc; 	0.00951137838231809
9479655	19922	how to get rows form table that each email appear one time	select p.*, tmp.email   from persons p, (select person_id, email                      from emails e1                     where not exists (                           select 1                             from emails e2                            where e1.person_id = e2.person_id                              and e1.time_sent < e2.time_sent)) tmp  where p.id = tmp.person_id; 	0
9481593	28656	sql select with joins across two databases. confusing :-s	select convert (varchar, quote.quoteid) as quoteid, quote.firstname, quote.lastname,  quote.productsku, quote.quantity, quote.creationdate, convert (char(8),  quote.creationtime, 8) as creationtime, quote.companyname,  incommingquotestatus.statusdesc, quote.lockeddatetime, users.firstname + ' ' +  users.lastname as username, d2.stock from quote inner join incommingquotestatus on  incommingquotestatus.statusid = quote.status inner join users on quote.lockeduserid =  users.userid  inner join cbretaildb.dbo.products as d2 on quote.productid = d2.idproduct where (quote.status > 2 and quote.status < 6) order by quoteid desc 	0.773829169728121
9483246	20109	querying data from row_number result	select * from (select row_number() over(order by id) as countrow, productid, productname, tracklink, productimage, trackprice from productdetails) as a where countrow between 31 and 40 	0.0515582228805367
9483519	32882	how to delete a foreign key from mysql table dynamically?	select concat('alter table ', table_name, ' drop foreign key ', constraint_name, ';') from information_schema.key_column_usage where referenced_table_name = 'tblreferencedbyfk' and table_name = 'tbltablewherefkis'; 	5.39857679485037e-05
9484172	34311	using fields from select query in where clause in subqueries	select      person,     (         select              count(*)          from              table1          where              table1.status = 45             and persontbl.personid = table1.personid     ) as typeres1  from      persontbl where person like 'a0%' 	0.683241552246892
9484247	17492	group data into one variable from sql	select p.id, p.name, group_concat(s.size) as size  from products p  join stock s on s.productid = p.id  group by p.id 	0.00148931449352844
9484748	11119	fastest way to find not null filed in sqlite	select 1 from [app_status] where [status] is not null limit 1; 	0.186327260717429
9485858	6835	sql server 2005 - counter in a select query	select a.f1, a.f2, a.f3     , sum(case when b.f1 > 3 then 1 else 0 end) as myindex from mytable a join mytable b     on a.f2 >= b.f2 group by a.f1, a.f2, a.f3 	0.746102695429849
9486114	31491	how to find out rows based on a column where duplicate data exist	select * from table where code in (     select code from table     group by code having count(*) > 1 ) 	0
9487835	23489	get this week's data using sqlite	select * from mytable where date(timestamp) >= date('now', 'weekday 0', '-7 days'); 	0.0450050616958161
9487947	11884	sql - how can i query for all objects who have count(0) of related objects in a reverse relationship?	select * from person p where not exists     (         select h.person_id         from helmet h         where h.person_id = p.id             and is_safe = true     ) limit 100 	8.74186844529374e-05
9488384	4134	how can i select rows that do not match corresponding rows in the same table?	select original.* from table original   left outer join table corresponding on corresponding.key = original.key and corresponding.col_a = 'val1.1' and corresponding.col_b = 'val2.1' where original.col_a = 'val1.0'   and original.col_b = 'val2.0'   and corresponding.key is null 	0
9488842	8934	selecting window of entries	select wt.id   from (select wt.id               ,max(                  start_time)                over (order by start_time                      rows between 2 preceding and 2 following)                  as maxst               ,min(                  start_time)                over (order by start_time                      rows between 2 preceding and 2 following)                  as minst           from wt) wt  where minst < to_date('2012-02-28 14:00:00', 'yyyy-mm-dd hh24:mi:ss')        and maxst > to_date('2012-02-28 14:00:00', 'yyyy-mm-dd hh24:mi:ss') 	0.00171497040392323
9489050	38207	show columns command for hsqldb	select * from information_schema.columns 	0.0178979500520902
9489966	1190	sql inner join with distinct rows?	select collections.title, collections.uniqueid, uploads.uniqueid as thumb  from collections cross apply (     select top 1 *     from uploads     where collections.uniqueid = uploads.uploadgroup     order by uploads.uniqueid  ) uploads 	0.353936110941009
9490259	1581	stored procedure to return specific rows	select tblscheduledates.*, tblscheduledates.*  from tblscheduledates     join tblscheduletimes         on tblscheduletimes.scheduletimeid =             tblscheduledates.scheduletime_id where not exists      (         select 1          from tblbookings              join tblbookingstatus                 on tblbookingstatus.status = 'booked'         where tblbookings.scheduledate_id              = tblscheduledates.scheduledateid     ) 	0.00888920269958037
9491989	6857	calculating a daily average (or: how many mondays are in a date range?)	select date_format(datetime, '%a') as field1,  round(sum(price_paid)/ count(distinct(date(datetime))) ) as field2  from bills  where date(datetime) between '2012-01-02' and '2012-01-09'  group by weekday(datetime) 	0
9493341	19634	how can i combine these looped mysql queries?	select c.*, cu.user_url as cu_url, cu.display_name as cu_name,        r.*, ru.user_url as ru_url, ru.display_name as ru_name   from projects_comments as c   left join users        as cu on cu.id = c.userid   join project_replies   as r  on r.cid = c.commentid    left join users        as ru on ru.id = r.uid  where c.projectid = $projectid  order by c.commentid desc, r.id desc 	0.209567770772566
9495804	17769	query that returns duplicate record frequencies	select description, count(description) as count from updates where (updates.created_at >= date_sub(curdate(), interval 6 month)) and exists (select null from participations inner join customer on customer.id = participations.customer_id where participations.update_id = updates.id and customer.garage_id = 1) group by description order by count desc limit 10 	0.00365932651403185
9496540	27421	how to write below sql query with all mentioned conditions?	select distinct s.id_one, s.status   from sometable s join othertable o on (s.id_two = o.id_two)  where (s.id_one = 1946 and o.name = 'name1')     or (s.id_one = 1948 and o.name = 'name2')     or (s.id_one = 1949 and o.name = 'name3'); 	0.484549291124489
9496579	11612	filtering mysql results between two dates	select  b.sales_title,c.cat_name,count(b.sales_id) as cnt,count(distinct e.comment_id) as coun from tb_sale_report a  inner join tbl_sales b on a.sales_id=b.sales_id  inner join tb_category c on c.cat_id=b.category_id  left join tb_comment e on b.sales_id=e.sales_id  where left(a.view_date,10) between 'start_date' and 'end_date'; group by b.sales_title 	0.0026877170273479
9497383	34320	select records after top 1000 rows	select * from (    select tbl.*, p.*, row_number() over (order by productid_primarykey) rownum   from  tblproductinformation as tbl inner join tblproduct1 p    on p.productname = p1.productname  ) seq where seq.rownum between 1000 and 2000 	0.000183572501357439
9499337	8639	sql server - returning multiple distinct values	select * from (select *, row_number() over(partition by rquestion, rplayerid order by rid desc) corr       from tblresponses) a where corr = 1 	0.0743391739231409
9500891	4851	how can i exclude another value from a column in joined table sql	select u.user_id from users u join purchased_products p   on u.user_id = p.user_id and       p.product_id in (1001, 1002) group by u.user_id having count(distinct p.product_id) = 1 and        min(p.product_id) = 1001 	0
9503066	5807	how do i select the first of a number of rows sharing a single field in common using sql server 2005	select *  from my_table join (select email, min(rank) as rank from my_table group by email) min_ranks on min_ranks.email = my_table.email and min_ranks.rank = my_table.rank 	0
9503905	38635	searching mysql column for specific content	select * from my_table where my_column like 'user%' 	0.0103013340577876
9503959	38649	select distinct: control priority when there are accents?	select name from city_i18n  where (name != (select name from city_i18n where id = 2745 and culture = 'es_es')          or culture = 'es_es')  and id = 2745 and culture in ('es_es', 'en_gb'); 	0.21105397772177
9505845	13508	sql items in a linked range	select     r.name,     count(i.ingredient) as ingredients from     recipes r     left join ingredients i          on i.recipe = r.recipeid         and i.ingredient in ('milk','butter','sugar','flour','egg') group by r.name having count(i.ingredient) between 2 and 4 	0.00304263896623543
9506927	29627	how to find databases which accessible to me in sql server?	select name, has_dbaccess(name) from sys.databases; 	0.370668163978663
9507198	39299	two date columns, one date. how can i get the data?	select * from table where start_date <= '2012-02-29' and end_date >= '2012-02-29'; 	0
9507972	4156	mysql select 2 tables like	select neveras.panel, contactos.email  from neveras inner join contactos     on find_in_set(neveras.usuario, contactos.sensor) where neveras.alarma = 1 and neveras.estado <> 1 	0.100360083211325
9509148	15695	sql: select with equals before like	select id, type, number from roads where number like '12%' order by    case       when number = '12' then 0       else 1    end 	0.383153162238585
9510054	22821	retrieve a value through three tables in a single query	select course_name from table3 inner join table2 on table2.course_id = table3.course_id where table2.project_id = 1 	0.000127410792346563
9510879	38485	sql query to fetch record from 1 tables based on 2 records in the table	select game_id from table_name where game_id in(select game_id from table_name where genre_id=6000 and is_primary=0)  and ( ganre_id=6007 and is_primary=1); 	0
9511916	2011	ading another sub query in existing subquery	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 where dishoutresponsecode = '0000') as deals_redeemed from tblcustomer     group by created_date     order by created_date 	0.701095745387589
9512516	5841	django orm limiting queryset to only return a subset of data	select * from mytable where (id, user_id, follow, active) in (     select id, likeable, user_id, follow, active from mytable mt     where mt.user_id = mytable.user_id     and mt.user_id in (1, 2)     order by user_id limit 5) order by likeable 	0.00744157120304696
9512998	15797	sql select with count in it	select user_id, count(*) as total from orders  group by user_id having count(*) >=3 and count(*) <= 7 	0.392290784310427
9513065	19880	get all rows changed this week based on timestamp	select  * from    yourtable where   week(timestampfield) = week(current_timestamp) and     year(timestampfield) = year(current_timestamp) 	0
9513482	10143	any way to get null(empty) columns using in condition in oracle? without using is null?	select empno, ename, job  from employee  where nvl(job, 'null') in('salesman', 'manager', 'null') 	0.0874638378282226
9514497	32963	mysql correct way of selecting	select y1.*  from yourtable y1 join yourtable y2 on y1.user_id = y2.user_id join yourtable y3 on y2.user_id = y3.user_id where y1.field_id = 4 and y1.field_value = "london" and y2.field_id = 25 and y2.field_value in ("accounting", "web design") and y3.field_id = 27 and y3.field_value in ("food", "wine") 	0.085548744990261
9515633	14418	mysql query for the following tables	select * from comp c, trance t where c.advisorid = 1  and t.receiverid = 1  and c.changedate between '2012-02-01' and '2012-02-30' and t.date between '2012-02-01' and '2012-02-30' 	0.220496715586072
9515684	35479	sql - select newest record when there's a duplicate	select id, type, date from  (     select tb1.id, tb1.type, tb1.date,          row_number() over (partition by tb1.id order by tb2.date desc) as rowno     from table tb1     where tb1.type in ('a','b') ) x where x.rowno = 1 	0.000203204169872053
9519025	1341	select statement to retrieve what never happened	select customerid from callhistory group by customerid having count(case when callresult='inquired about pricing' then 1 else null end) > 0    and count(case when callresult='placed order' then 1 else null end) = 0 	0.362567224700974
9519926	26092	mysql how do i only show the max/highest values with the following query?	select d.d_name, s.s_title, f.f_value, if(max(r.confidence) is null, 'n/a', concat((max(r.confidence)),'%')) as confidence from f_things f join stuff s on s.s_id=f.s_id join dump d on d.d_id=s.d_id left join f_findings r on f.f_id=r.f_id group by d_name, s_title, f_value; 	0.00180294979079026
9520304	32334	fetch the data from second tables according to keys in 1st table	select s1.detail as item1,        s2.detail as item2,        s3.detail as item3,        s4.detail as item4,        s5.detail as item5     from tbdata d         inner join secondtable s1             on d.item1 = s1.sno         inner join secondtable s2             on d.item2 = s2.sno         inner join secondtable s3             on d.item3 = s3.sno         inner join secondtable s4             on d.item4 = s4.sno         inner join secondtable s5             on d.item5 = s5.sno     where queryparam1 = @queryparam1        and queryparam2 = @queryparam2 	0
9520639	34642	mysql multiple table select	select iduser, username, link.title, count(idcomment) from users left join link on (iduser = userid) left join comment on (linkid = idlink) group by iduser, idlink 	0.0494418411674797
9521215	3128	i want to have the highest number of town_city each year mysql	select year, city, count(*) from city_table ct1 where year=(select max(year) from city_table ct2 where ct2.city=ct1.city) group by year, city 	0
9522996	9135	sql get last month name	select left(datename(month, dateadd(dd, -1, getdate())), 3) 	0
9524617	660	sqlite : get all entries in a row	select email from email_db 	0
9527887	4834	roll up sql query?	select        name, microsoft_vsts_scheduling_startdate as startdate,                          (select        sum(microsoft_vsts_scheduling_originalestimate) as originalestimatetotal                            from            currentworkitemview as wi1                            where        (iterationpath in                                                          (select        iterationpath                                                            from            currentworkitemview as wi2                                                            where        (workitemtype = 'sprint') and                                                                                       (microsoft_vsts_scheduling_startdate > wi3.microsoft_vsts_scheduling_startdate))) and (state not in ('removed')))                       as originalestimatetotal from            currentworkitemview as wi3 where        (workitemtype = 'sprint') and (state <> 'removed') order by startdate 	0.642913256523142
9528798	37279	order by for desc table	select column_name, data_type, is_nullable, column_default   from information_schema.columns  where table_name = 'tbl_name'   [and table_schema = 'db_name']   [and column_name like 'wild'] order by column_name 	0.179541581146759
9530760	20638	get user posts and/or comments in a sharing blog using sql	select p.id as post_id,         p.author_id as post_author_id,         c.author_id as comment_author_id,        p.title,         c.content from posts p  left join comments c on p.id = c.post_id and c.author_id = $userid where p.author_id = $userid union all select p.id as post_id,         p.author_id as post_author_id,         c.author_id as comment_author_id,        p.title,         c.content from posts p  right join comments c on p.id = c.post_id where c.author_id = $userid 	0.000618372162529408
9530889	7288	how to get this logic in sql query?	select user_id, user_role, activity_time_stamp as logintime,  ( select activity_time_stamp    from activityaudittrail aud2   where aud2.activity_id=2    and activityaudittrail.user_id=aud2.user_id    and activityaudittrail.user_session=aud2.user_session  ) as logouttime from activityaudittrail where activity_id=1 	0.772244959966227
9531109	1325	convert mysql longtext value to varchar value?	select id, cast(yourlongtext as char(255)) as yourvarchar from some_table 	0.00782049498845678
9531168	11555	how to group by one column and summation of second?	select carname, sum(rentedtimes) from cars group by carname order by sum(rentedtimes) desc 	0.000205840461745535
9531590	12514	conditional row subtraction	select     case when a = 0 or b = 0          then 0          else a - b     end c 	0.22577168771795
9532140	26727	how to select the max of two element of each row in mysql	select p.id as post_id,         p.author_id as post_author_id,         p.created_date as post_created,        c.author_id as comment_author_id,        c.created_date as comment_created,        p.title,         c.content,        coalesce(c.created_date,p.created_date) as sort_date from posts p  left join comments c on p.id = c.post_id where p.author_id = $userid union all select p.id as post_id,         p.author_id as post_author_id,         p.created_date as post_created,        c.author_id as comment_author_id,        c.created_date as comment_created,        p.title,         c.content,        c.created_date as sort_date from posts p  right join comments c on p.id = c.post_id where c.author_id = $userid order by sort_date 	0
9532522	3329	how to check for existence of row in a joined table - mysql	select projects_comments.*,         users.user_url,        users.display_name,         comments_loves.userid is not null as loves from projects_comments projects_comments left join users users    on users.id=projects_comments.userid   left join comments_loves   on projects_comments.commentid = comments_loves.commentid and       comments_loves.userid = '$userid' where projectid = '$projectid' order by projects_comments.commentid desc 	0
9533173	28198	sum by two different group by	select      claimed,     ordered  from       #tsp  inner join       (select               fitsp,               sum(ordered) as ordered         from                #sp         group by                fitsp) as sums            on       sums.fitsp = id; 	0.00452036941216257
9534590	4774	previous trimester in oracle sql	select trunc(trunc(sysdate, 'q') -1, 'q') as startlastquarter,        trunc(sysdate, 'q')-1/(24*60*60)   as endlastquarter,        trunc(sysdate, 'q')                as startthisquarter     from dual; 	0.194412885505264
9534996	16037	merge columns from two sql query results with different number of columns	select user_tbl1.username, user_tbl1.surname, user_tbl1.givename from user_tbl1 union select user_tbl2.user_pk, '-', '-' from user_tbl2 	0
9536673	8447	using sql in and together	select product_id from values where value in ('large','short') group by product_id having count(distinct value) = 2 	0.462962121771877
9537212	22074	order by date issue	select     datecreated, datemodified from         (select     top (100) percent datecreated, datemodified                        from          mytable                        where      (datecreated > getdate() - 7)                        order by datecreated) union all select     datecreated, datemodified from         (select     top (100) percent datecreated, datemodified                        from          mytable                        where      (datemodified is null) or                                               (datemodified > getdate() - 7)                        order by datemodified) 	0.677893963441843
9537569	38546	sql server query,	select id_hw,     mintable.data as mindata,     maxtable.data as maxdata,     (maxtable.data - mintable.data) as _days_,     (maxtable.lampda - mintable.lampda) as consumed  from (select id_hw, max(data) as data, lampda from table group by id_hw) maxtable,   (select id_hw, min(data) as data, lampda from table group by id_hw) mintable  where maxtable.id_hw = mintable.id_hw 	0.698580681859737
9537788	40102	grouping 'like' rows in sql and summing?	select membersep, location, consumer, sum(todkwh001), sum(todkwh002) from yourtable group by membersep, location, consumer 	0.0883380586521438
9540130	5107	how to select all this data without repeating subqueries?	select     *,     round(thumbs_up / (thumbs_up + thumbs_down), 2) as average_rating from (     select         yourcolumns...         sum(case when r.thumb = 'up' then 1 end) as thumbs_up,         sum(case when r.thumb = 'down' then 1 end) as thumbs_down     from         posts p left join         ratings r on r.post_id = p.id     group by yourscolumns ) sub 	0.0816182201948072
9540681	6747	list postgres enum type	select n.nspname as enum_schema,          t.typname as enum_name,          e.enumlabel as enum_value from pg_type t     join pg_enum e on t.oid = e.enumtypid      join pg_catalog.pg_namespace n on n.oid = t.typnamespace 	0.0298235142376828
9541702	31028	compare two tables with mysql through php	select color from fav_color, country      where fav_color.username='sarah' and     fav_color.username = country.username and     country = 'canada'; 	0.00640875326322497
9542842	37425	data from multiple tables and using a count() inside a select	select x.description, x.name, z.year, count(z.id_service) from services x inner join history z on z.id_service = x.id_service  group by x.description, x.name, z.year 	0.00424207352863215
9545009	13099	add subquery in existing subquery	select t.created,    count(c.field1) enrolled,    count(case c.field1 when 'e-mail' then 1 end) enrolled_as_email,    count(case c.field1 when 'cell phone' then 1 end) enrolled_as_cell,    count(case when c.field1 is null then 1 end) [deals redeemed] from tbl_transactiondishout t left join tblcustomer c     on t.cardno = c.cardno group by t.created order by t.created desc 	0.565916752628234
9545637	29542	sql order by count	select group, count(*) from table group by group order by count(*) desc 	0.281706301075683
9546580	4581	how to determine which mysql database has been selected?	select database(); 	0.00131913571357833
9546596	11564	how can you get high and low values across group using a group by in mysql?	select string, min(low), max(high)   from table  group by string 	0.00167504642796232
9548667	15027	select from table with three foregin keys to one table	select subjects.name as subject_name        , opinions.value        , o_users.name as opinion_guy        , p_users.name as professor from  opinions        join subjects on ( opinions.subject_id = subjects.id)       join users as o_users on ( o_users.id = opinions.opinion_guy_id)       join users as p_users on ( p_users.id = subjects.professor_id) / 	0.000107856389153684
9550633	37738	how to pull same row from another table by date in mysql	select first.f_id, first.date, second.s_id, second.name   from first join second on second.f_id = first.f_id 	0
9551354	14811	mysql query - grouping by combined ids	select index.pid, sum(index.value) totalsum from index where (wid = 5 or wid = 7) group by index.pid order by totalsum desc 	0.0140050159423609
9551622	2611	select popular posts from specific period of time	select * from stats where date between   date_sub(now(), interval 2 month) and   date_add(date_sub(now(), interval 2 month), interval 1 week) order by views desc limit 10 	0
9554025	23718	php myaql union query with different uid	select * from my_table where image!='' order by rand() group by uid limit 10 	0.73797704933999
9554099	9852	mysql search query two columns	select title, bookid, publisher, pubdate, book_image, books.authorid, authors.author  from books left join  authors on  books.authorid = authors.authorid  where (title like '$querystring%' or author like '$querystring%') limit 5 	0.0266105532236399
9554471	25693	distinct values in set	select group_concat(distinct `method`) from `table` where ...; 	0.017208373502798
9557433	17966	dealing with a curriculum database	select ... where (subject.req_year is null or student.year >= subject.req_year) ... 	0.741917609451898
9559060	25736	select and replace values from another table	select a1.id,        coalesce        ( a1.valuea,          ( select b.valueb              from b             where b.priority =                    1 + ( select count(1)                            from a as a2                           where a2.id < a1.id                             and a2.valuea is null                        )          )        )   from a as a1  order by a1.id ; 	0.000267233049629917
9560839	653	mysql help: how to find all orders from a customer till price <= 20 and status='unpaid'	select propersummed.*    from        ( select               o.orderid,                o.price,                @runningtotal := @runningtotal + o.price as unpaidsofar            from               orders o,                (select @runningtotal := 0 ) sqlvars            where o.ownerid = 1              and o.paymentstatus = 'unpaid' ) propersummed     where         propersummed.unpaidsofar <= 50 	0
9560905	31822	mysql select all users who have not logged in for 30 days	select member_id, max(login_timestamp) from logins  group by member_id having max(login_timestamp) <= 1329461087 order by max(login_timestamp) desc 	0
9562648	37181	mysql script check whether column exist or not before adding column in table	select *  from information_schema.columns  where      table_schema = 'db_name'  and table_name = 'table_name'  and column_name = 'column_name' 	0.00235222104118649
9562886	27120	join query for fetching the count	select t2.ofid, cast(t2.offer_text as varchar(max)), count(*) from tbl_transactiondishout t inner join tbl_offer t2 on cast(t.offerno as varchar(max)) = cast(t2. ofid as varchar(max)) group by t2.ofid, cast(t2.offer_text as varchar(max)) 	0.20883710014846
9563193	643	mysql + select 2 columns - 1 being unique	select * from (   select * from table order by rand()) t group by   domainname 	0.00089667363936586
9563698	18194	get values for every day in specific month (or between months)	select     *  from     yourtable as t  where      yourdatetimefield between str_to_date('2012-01-01', '%y-%m-%d') and                                str_to_date('2012-12-31', '%y-%m-%d') and      dayofweek(yourdatetimefield) <> 1 and    '  sunday     dayofweek(yourdatetimefield) <> 7        '  saturday  group by     day(yourdatetimefield); 	0
9565820	27476	compare db value and get the value + duplicates	select group_concat(distinct username            order by username desc separator ',') as users, thedate from $table_name  where thedate > now() group by thedate order by thedate asc 	0
9565878	6677	mysql query to append most recent result	select  t1.msisdn         , t2.field2         , t2.date from    table1 as t1         inner join table2 as t2 on t2.msisdn = t1.msisdn         inner join (           select  max(date) as date, msisdn           from    table2           group by                   msisdn         ) t2max on t2max.msisdn = t2.msisdn                    and t2max.date = t2.date 	0.00137554621792201
9566919	31542	query to retrieve rows where values are empty or numeric only	select * from yourtable where sr is not null and sr not like '%k%' 	6.70095584656875e-05
9569591	31523	sql query- number of statuses in percentage	select      t.status, 100.0 * count(*) / total from     (      select          id, status, count(*) over () as total      from         sr     ) t group by       t.status, t.total 	0.00340410115705433
9570995	31465	how can i select if date column is as same as current year	select * from student where year(registerdate) = year(getdate()) 	0
9571264	40498	mysql select exact word	select * from articles where match (title,body) against ('+spa' in boolean mode); 	0.0677703354075577
9571444	24814	how select a grouping of matching values from a table?	select distinct (     stuff      (         (             select ',' + feature             from sitefeatures t2             where  t1.siteurl = t2.siteurl             order by feature             for xml path(''), type, root         ).value('root[1]','nvarchar(max)')         ,1,1,''     ) ) as chars from sitefeatures t1; 	0
9572204	19388	sql query multiple tables	select t2.id, t3.maskname, t3.total from table2 as t2 inner join table3 as t3 on (t2.maskid = t3.maskid) where id = 123 	0.217201663000197
9572502	7041	how to fetch data of last month from database	select count(js_id) from yourtable   where datediff( m, applied_date, getdate() ) = 0 	0
9572930	22635	re-writing without using unique construct in sql	select t.course_id  from course as t  where (select count(*)        from section as r         where t.course_id = r.course_id and r.year = 2009) = 1; 	0.757265651120407
9573821	22719	mysql - finding partial strings - full text?	select * from main_small where file_path like '%thumbs.db' 	0.0612570975825082
9573905	35824	sql pivot table for many-to-many relationship for use in ssrs	select username,            rightname from users u inner join rightmembership rm on rm.userid = u.userid              inner join rights r on rm.rightid = r.rightid 	0.69912598712343
9574308	28700	select 1 rand() from each of 4 where clauses mysql	select    max(if(row_num = 1, ad_html, null)) as 'ad_space_1',    max(if(row_num = 2, ad_html, null)) as 'ad_space_2',    max(if(row_num = 3, ad_html, null)) as 'ad_space_3',    max(if(row_num = 4, ad_html, null)) as 'ad_space_4' from (    select       @row_num := @row_num + 1 as 'row_num',       ad_html    from           (select            @cnt := count(*) + 1,          @lim := 4,          @row_num := 0       from          ads       ) vars    straight_join       (       select          r.*,          @lim := @lim - 1       from              ads r       where             (@cnt := @cnt - 1)          and rand(203121231) < @lim / @cnt       ) i ) j 	0.00020345932670865
9574851	15003	return all duplicate rows	select *  from styletable  where color in (   select color     from styletable      group by color     having count(*) > 1  ) 	0.000177794567247
9576001	32174	combine 2 queries	select users.id as userid,users.username, policy.id as policyid,policy.policyname, source.path from users join groups on group.id = user.groupid_fk     join policy on group.policyid_fk = policy.id    left join source       on group.policyid_fk = source.policyid_fk       and sourcetype = 0 	0.0359488286054109
9578716	1885	how to find most recent birthday	select id,        dateofbirth,        dateadd(yy,                datediff(yy,dateofbirth,getdate()) -                            case when dateadd(yy,datediff(yy,dateofbirth,getdate()),dateofbirth)>getdate()                            then 1 else 0 end,                dateofbirth) mostrecentbirthday from ... 	0
9579610	14619	how to split column into multiple values using another	select date,sum(case when hour>='00: 00:00' and hour<=' 11:59:59 then accidents else 0 end) as 'at day', sum(case when hour>='12: 00:00' and hour<=' 23:59:59 then accidents else 0 end) as 'at night'  from vehicles  where date>='2012-01-01 'and date<='2012-01-31' group by date 	0
9580658	14582	limit max value of sql calc	select case when max(convert(float,isnull(runhrs,runho))) -                  min(convert(float,isnull(runhrs,runho))) > 24             then 24             else max(convert(float,isnull(runhrs,runho))) -                  min(convert(float,isnull(runhrs,runho)))         end as runho, ... 	0.0181983632238738
9580810	11960	how to do sql calculation from a view?	select  channel,         sum(case when type = 'n' then -1 else 1 end * total_month_count) "calculation" from    yourview group by channel 	0.0775832822286472
9581608	34442	specified record in top of results list	select * from mytable  order by     case when id = 42 then 0 else 1 end, id 	0.000245956277532153
9582393	27019	how can i select rows in reverse order (mysql)	select * from sometable where id < 6 order by id desc limit 4,1 	0.0414498523148617
9582883	11348	sql server 2008: looping through results of select + performing other queries depending on position in loop and result	select   [timestamp],  case     when latitude>0 then latitude    else (select top 1 latitude           from @vehicledata v2          where             latitude > 0 and            v2.[timestamp] < v1.[timestamp]          order by v2.[timestamp] desc )    end    as latitude from   @vehicledata v1 	0.00104985259393842
9583182	21340	how to get last 5 unique product ids?	select productid from (select productid, max(orderno)  from orders  group by productid  order by 2 desc) sq limit 5 	0
9584295	24541	store the results of a sub-query for use in multiple joins	select   `l`.`status`,   `l`.`acquired_by`, coalesce(`a`.`name`, 'unassigned') as 'acquired_by_name',   `l`.`researcher`,  coalesce(`r`.`name`, 'unassigned') as 'researcher_name',   `l`.`surveyor`,    coalesce(`s`.`name`, 'unassigned') as 'surveyor_name' from `leads` `l` left join `web_users` `r` on `r`.`id` = `l`.`researcher` left join `web_users` `s` on `s`.`id` = `l`.`surveyor` left join `web_users` `a` on `a`.`id` = `l`.`acquired_by` where `l`.`id` = 566 	0.487299280678239
9584352	11213	mysql join query to extract ids which are blocking only closed bugs	select b.* from bugs b   join (     select       d.*     from dependencies d       join bugs b         on b.bug_id = d.blocked     group by d.dependson       having count(if(status = 'closed', status, null)) = count(*)   ) t   on b.bug_id = t.dependson 	0.000147782614653195
9586221	8865	sql select newest records based on duplicate records	select e.merchant, e.price, e.url, m.merchant_logo, m.merchant_name, e.eventname from wp_events e inner join wp_merchants m  on e.merchant = m.merchant_name and e.uploaddate = (select max(uploaddate) from wp_events where merchant = e.merchant and eventname = e.eventname) order by price asc 	0
9586645	34	incorrect results using sum()	select      v_rpt_company.company_name, v_rpt_service.agreement_name, count(distinct v_rpt_service.ticketnbr) as tickets,                           sum(isnull(v_rpt_service.hours_actual, 0)) as hours,( sum(isnull(agr_detail.agd_qty, 0))/count(distinct v_rpt_service.ticketnbr)) as endpoints 	0.75305199885869
9587165	10082	combining two columns on a id	select   case when null       then 0       else (select sum(posts.timesreported) as total_posts_reports             from  posts  inner join users on (posts.userid = users.id)              where posts.userid=5)        end   +  case when null       then 0       else (select sum(comments.timesreported) as total_comments_reports             from  comments  inner join users on (comments.userid = users.id)              where comments.userid=5)        end from dual; 	0.000147836829804052
9589016	10502	sql command to select library shelf containing only books of a given color	select shelf from test group by shelf having count(if(color = 'red', 1, null)) = count(*) 	0.00192454283933424
9589478	3056	select values based on several lines and columns	select  id   from  mytable t         join mytable t2 on t.id = t2.id  where  t.characteristic  = 'color' and t.value ='blue'    and  t2.characteristic = 'shape' and t2.value='rectangle'  	0
9591238	28215	exclude results of the first query on the second query in same table with mysql	select * from (   select * from `langcategories`    order by `langcategories`.`amount` desc    limit 8,2000000000 ) as baseview  order by name asc 	0
9591554	11725	use regex stored in a table as criteria for an sql query	select a.*, b.regex   from a join b on a.foo ~ b.regex 	0.739952814267134
9591568	6849	sorting in mysql	select * from test order by substring(value, 2) + 0,           substring(value, 1, 1); 	0.366857979520273
9591677	40147	nonexisting oracle database constraint violated	select * from all_ind_columns where index_name = 'my_table_two_uk01'; 	0.100348849417433
9592287	12935	retrieve the maximum length of a varchar column in sql server	select max(len(desc)) from table_name 	0
9592714	37558	mysql : find a sequential pattern appears on multiple rows	select     yt1.id as first,     yt2.id as second,     yt3.id as third from     yourtable yt1      join yourtable yt2          on yt2.id > yt1.id          and yt2.action = 'fgh'          and yt2.product_id = y1.product_id     join yourtable yt3          on yt3.id > yt2.id          and yt3.action = 'zab'         and yt3.product_id = y1.product_id where     yt1.action = 'abc' 	0.000315576025523362
9592875	190	sql server: left outer join with top 1 to select at most one row	select * from careplan c outer apply (     select top 1 *      from referral r     where r.careplanid = c.careplanid      order by ) x 	0.00628268904465089
9592894	5437	select query statement	select personal.nume, raspunsuri.raspuns, intrebari.intrebari as answer from personal inner join raspunsuri on personal.cod_numeric_personal = raspunsuri.cod_numeric_personal inner join intrebari on raspunsuri.id_intrebare = intrebari.id_intrebare group by nume 	0.647833774844355
9593003	23638	combining two mysql queries to get posts by friends only	select * from posts   where toid=fromid and state='0' and toid in     (select case when userid=$session then userid2 else userid end as friendid        from friends        where userid=$session or userid2=$session) order by id desc limit 10 	0
9593169	27415	create multiple report rows from single row of data	select employeename,  case     when type like 'type1%'     then 'type1'     else 'type2' end typecol, total  from (select employeename, type1column1, type1column2, type2column1, type2column2      from storedprocdata ) as f unpivot (total for type in (type1column1, type1column2, type2column1, type2column2) ) as u 	0
9593293	34108	better ordering of mysql/php search results	select id, match (gametitle) against ('%$namekeys[$i]%') as score from games where match (gametitle) against ('%$namekeys[$i]%') limit 10; 	0.616405441571797
9598864	26604	postgis geometry database query	select a.gid, a.the_geom from pointstable a left join river_100_1k b  on st_intersects(a.the_geom, b.the_geom) left join  river_200_1k c on not st_intersects(a.the_geom, c.the_geom)  left join river_1000_1k d  on not st_intersects(a.the_geom, d.the_geom)  where  and c.gid is null and d.gid is null and b.gid=2 and c.gid=2 and d.gid=2 ; 	0.589748036452328
9599027	23076	sql query between current date and previous week	select sge_job.j_owner as "owner"       ,sum(sge_job_usage.ju_cpu) as "cpu total" from sge_job_usage, sge_job  where sge_job_usage.c1 = sge_job.c2   and ju_start_time between localtimestamp - interval '14 days' and localtimestamp group by j_owner; 	0
9599628	19982	mysql: latest items grouped by a string	select a, group_concat(id) from    ( select * from table_name order by b ) group by a limit 1 	6.14435985733098e-05
9600054	23661	wrap tables in oracle	select c153427 from t765648 	0.537836709019301
9600092	8416	mysql adding new columns to query result	select location_string, equipment_string, reject_time , (select emrs_code from `rejectlogging`.`emrs_data` where emrs_time <= reject_data.reject_time and emrs_location = reject_data.reject_location order by emrs_time desc limit 1) as emrs_code, (select emrs_string from `rejectlogging`.`emrs_data` where emrs_time <= reject_data.reject_time and emrs_location = reject_data.reject_location  order by emrs_time desc limit 1) as emrs_string from reject_data, equipment, locations where reject_equipment = equipment_id      and reject_location = location_id      and reject_location in (7)      and reject_equipment in (1,2,3,4,5,6)      and reject_time between 0 and 1331113803000 order by reject_id desc  limit 100 	0.0156516723407165
9600587	31757	how to sum multiple lines in sql	select company_name, company_id, sum(amount)  from tablename group by company_name, company_id 	0.0151429567162604
9600870	3272	sql: joining tables on primary key and returning the primary key	select mails.*  from mails inner join mailassignments  on mails.msgid = mailassignments.msgid 	0.000374214596750419
9601160	19896	sql index searching	select lastname,         firstname,         count(distinct filmid) as films,        count(distinct case when rn=1 then filmid end) as alpha_first from  (select p.lastname,         p.firstname,         f.filmid,         row_number() over (partition by f.filmid order by lastname, firstname) rn  from person p, filmparticipation f, filmitem i, film fi  where fi.filmid = i.filmid and        i.filmid = f.filmid and        p.personid = f.personid and        f.parttype = 'cast' and filmtype = 'c') person group by lastname, firstname having count(distinct filmid) >= 50 order by lastname, firstname desc; 	0.634665324199362
9601679	5129	outer join on 3 tables	select      t.id as [toolid],             t.name as [toolname],             cast(case when ct.id is null then 0 else 1 end as bit) as [hasthistool] from        tool t left join   clienttools ct on          t.id = ct.toolid and ct.clientid = @clientid 	0.551203251636183
9601885	29869	selecting last event given certain conditions	select a.*  from eventos_centralita a left join eventos_centralita b    on b.codagente = a.codagente    and b.evento = 'deslogado'   and b.fechahora > a.fechahora left join eventos_centralita c   on c.codagente = a.codagente    and c.fechahora > a.fechahora where b.idevent is null and c.idevent is null and a.evento <> 'deslogado' group by a.codagente; 	0
9603507	35735	how do i count the frequency of an item in a new column, without changing the structure of the table? sql	select bs, item_id, price,         count(*) over (partition by bs) amount from yourtable 	0
9606757	34676	select query result based on the difference of a "quantity" in same column of two tables	select course_id, course_name from table2 where course_id not in (select course_id from table1) 	0
9606797	17545	sql server finding duplicates	select record_number   from my_table   group by record_number   having count(distinct employee) > 1 	0.105143131349065
9607571	9556	how to retrieve parsed dynamic pl sql	select v$sql.sql_text     ,v$sql_bind_capture.* from v$sql_bind_capture inner join v$sql on     v$sql_bind_capture.hash_value = v$sql.hash_value     and v$sql_bind_capture.child_address = v$sql.child_address where lower(sql_text) like lower('%priceworx.fdg2j(sysdate)%'); 	0.0733264665470504
9607786	12316	best approach to time-series data in sql server 2008	select count(*)...where date between [2dates] 	0.748558947471201
9608063	18650	selecting rows that are the same in one column, but different in another	select * from yourtable where x in (   select t1.x   from yourtable t1 inner join        yourtable t2 on t1.x = t2.x   where t1.date <> t2.date ); 	0
9609153	17074	database design - how can i have a recurring database entry?	select  * from    events where   recurring = 0 union select  event_id,         title,         description,          dateadd(week, interval, start_time) [start_time],         dateadd(week, interval, end_time) [end_time],         group_id,         recurring from    events,          (   select  row_number() over(order by object_id) [interval]             from    sys.all_objects         ) i where   recurring = 1 and     interval <= 52  	0.00412281488678731
9609177	16729	complex summing in sql	select sum(subsum) / 15 from (    select sum(column1) as subsum       from table      union all     select sum(column2) as subsum       from table      union all     ...     select sum(column10) as subsum       from table ) 	0.791097899840367
9609666	10501	mysql query to get min field data with timestamp equal to current date	select min(mycolumn) as mycolumn  from mytable  where time_stamp between date(now()) and date(now() + interval 1 day) and id = 1; 	0
9609880	15110	mysql 'min' in 'where' clause	select date(fecha) as day, min(num) as mi   from mytable where date(fecha) >= date(now())  group by day having min(num) < 10; 	0.764868843210783
9611115	19997	prevent duplicate count in select query	select  eventid, numberrunners,         case when numberrunners <5 then 1              when numberrunners >=5 and numberrunners <=7 then 2              else 3          end as numberplacings   from  (             select  eventid,                     numberrunners = count(competitorid)               from  comps             group by eventid         ) t order by eventid; 	0.0381975900114495
9611349	29201	mysql: grabbing the latest id from duplicate records within a table	select max(id) from table 	0
9611471	3698	sql: how to use the value of query as a field of another query?	select u.id      , o.name      , case when u.group = 'admin'           then o.admin            else o.user        end as permissions from   user_object        u join   object_permissions o        on (u.object_id = o.id); 	0.000280094122532487
9613339	19879	group totals in a sql pivot table	select city, sex, count(case when race = 'african-american' and age between 20 and 30 then 1 else null end) as [20_30_african-american], count(case when race = 'asian' and age between 20 and 30 then 1 else null end) as [20_30_asian], count(case when race = 'caucasian' and age between 20 and 30 then 1 else null end) as [20_30_caucasian], count(case when race = 'hispanic' and age between 20 and 30 then 1 else null end) as [20_30_hispanic] from test5 group by city, sex with rollup order by city, sex 	0.15612813869481
9614139	27367	mysql nested select referencing outside table?	select     course_category.id      as languageid,     course_category.code    as languagecode,     course_category.name    as languagename,     t.total as languagewordstranslated from     course_category join (     select gradebook_category.course_code, sum(gradebook_result.score) as total     from gradebook_result     join gradebook_evaluation on  gradebook_evaluation.id=gradebook_result.evaluation_id     join gradebook_category on gradebook_category.id=gradebook_evaluation.category_id     group by gradebook_category.course_code ) t on t.course_code = course_category.code where     course_category.code != 'gen' order by     name asc 	0.59492686125697
9617210	26584	return a default record from a sql query	select * from mytable where id = 2 if (@@rowcount = 0)    select ... 	0.00135874638190913
9617709	16664	how to create left joins without repetition of rows on the left side	select a.*, b1.type as typex, b2.type as typey from a left join b b1 on a.aid = b1.aid and b1.type = 'x' left join b b2 on a.aid = b2.aid and b2.type = 'y' 	0.273869106742772
9618134	36857	how to find which views are using a certain table in sql server (2008)?	select *  from   information_schema.views  where  view_definition like '%[yourtablename]%' 	0.000135662568732106
9618559	22988	select top record for each year	select top (1) with ties   c.companyname,   year(o.orderdate) as yr,   sum(od.quantity) as total from orders as o join customers as c on c.customerid = o.customerid join "order details" as od on od.orderid = o.orderid group by c.companyname, year(o.orderdate) order by    row_number() over (     partition by year(o.orderdate)     order by sum(od.quantity) desc   ); 	0
9620859	27867	adding zero values to report	select     tktermid ticketterminalid,     mchlocation machinelocation,     coalesce(count(tkvouchernum),0) totaltickets,     coalesce(cast(sum(tkcomission) as float),0) / 100 totalcomission from     machconfig (nolock)     left join     ticketssold (nolock)     on         tktermid = mchterminalid  where     cfglocationcountry = 'uk'     and     dateadded between dateadd(day, -100, getdate()) and getdate() group by     vstermid,     cfglocation order by     coalesce(cast(sum(tkcomission) as float),0) / 100 desc;  	0.033336006509798
9622787	5040	sql query to get data from two tables	select movie_name from table1 join table2 using (movie_id) where movie_genre = 'some_genre' 	0.000319833093370523
9623545	4631	adding an element to xml sql 2008 query	select   'acme dynamite' as company,   'jan 01 2013' as createdate,   (       select       [employeeid] as '@id',       [lastname],        [firstname],       [title]     from        [dbo].[employees]     for xml path('employee'), type   ) for xml path(''), root('employees') 	0.367073613310845
9623642	6250	mysql replace value from each record	select group_concat(char(ch) separator '') 'missing letters' from    (select @tmp:=@tmp+1 ch     from (select @tmp:=96) a, information_schema.collations    where @tmp<122) z left join tablea on ch=ord(tablea.code) where tablea.code is null; 	0
9625382	8418	sql - adding a count to select clause	select name, count(*) as total_trends, sum(if(datetime between '"&fromdate&"' and '"&todate&"' ,1,0)) as total_last_7_days, ((sum(if(datetime between '"&fromdate&"' and '"&todate&"' ,1,0)) /count(*) ) *100) as percentage from trending_names group by name order by count(*) desc limit 10; 	0.35494503415329
9625925	6788	give priority to those fields where match was found	select * from test order by case    when read_to = 1 and read_from = 1 then 0    else 1 end; 	0.00134918057318005
9626096	17960	sql query get max date from different table	select tanks.tankid, tanks.unitnumber, (select max(table2.expiradate) from table2 where table2.tankid = tanks.tankid) as max_expire_date from tanks where companyid = '1111' and   tanks.tankid = '22222' order by tanks.tankid 	7.0952398271428e-05
9626273	26417	make exact match show at top of internal partial match t-sql query	select *  from client where identifyingnumber like '%86%' order by len(identifyingnumber) 	0.000362607251576585
9626410	12102	how do i cast the result of a union in sqlite?	select cast( column1 as blob ) from (     select column1     from table1     union     select column1     from table2 ); 	0.0926562438534794
9627306	9760	select two columns from two different tables each with different column names	select   a.vid,   b.pid from (   select vid, row_number() over (order by vid) as rn   from tablea   where title like '%somevalue%' ) a full join (   select pid, row_number() over (order by pid) as rn   from tableb   where title like '%somevalue%' ) b on a.rn = b.rn 	0
9628493	30798	sql join two tables with a link table between - gorm/grails	select distinct source.name from person left join person_source on person_source.person_source_id = person.id join source on source.id = person_source.source_id 	0.00598933691228936
9628887	36605	given two users, select every post rated by both users, and the rating of each user towards each post	select r1.post_id, r1.rating as rating1, r2.rating as rating2 from ratings r1 join ratings r2 on r1.post_id=r2.post_id and r1.user_id!=r2.user_id where r1.user_id=1 and r2.user_id=2 	0
9629592	36366	mysql query with multiple tables	select * from userinfotbl, userpvtbl where userpvtbl.username = userinfotbl.username and userpvtbl.username = 'user0003' 	0.254518771640242
9629864	9665	is null greater than any date data type?	select *    from someschema.sometable   where coalesce(sysdate, timestamp_format('0001-01-01 23:59:59', 'yyyy-mm-dd hh24:mi:ss'))  > @a 	0.0124249640897276
9632392	39589	get mysql database entries within last week	select * from tablename where timecolumn > unix_timestamp() - 24 * 3600 * 7 and username = 'givenusername' 	0
9632449	35327	mysql query - select distinct showing wrong results	select distinct uid from kicks order by created desc limit 3 	0.746094841238097
9635355	26957	change of values while generating csv	select     case your_column        when 0 then 'zero or any other string'        when 1 then 'one or any other string'     end as your_alias from     your_table_name 	0.0184636123378136
9636477	40850	spaces in mysql field	select * from table where field != '' or field is not null 	0.118147887517363
9637364	8573	postgresql - 2 select statements from 2 different tables into 2 columns?	select prd_id, 0 lst_id from products where title like %$var% union all select 0 prd_id, lst_id from lists where title like %$var%; 	0
9637416	13847	display rows which contain "#error" in query ouput	select table1.number1 from table1 where table1.number1 not in (     select table2.number2 from table2 ) 	0.0485862696873208
9637596	23257	sql query, retrieve only two rows per user	select       prequery.*,    from       ( select @lastuser := 0,                @lastadseq := 0 ) sqlvars,       ( select               ads.id_user,               ads.id,               ads.title,               ads.url,               @lastadseq := if( @lastuser = ads.id, @lastadseq +1, 1 ) as seq,               @lastuser := ads.id_user as carryover            from               ads            order by               ads.id_user,               rand()             having seq <= 2 ) prequery 	0
9638309	1821	select non-matching record in same table - sql	select distinct(report_number) from reports  where report_type='a' and report_number not in (select report_number from reports where report_type='b') 	0.000455092166683996
9638431	536	listing all data sources and their dependencies (reports, items, etc) in sql server 2008 r2	select     c2.name as data_source_name,     c.name as dependent_item_name,     c.path as dependent_item_path from     reportserver.dbo.datasource as ds         inner join     reportserver.dbo.catalog as c         on             ds.itemid = c.itemid                 and             ds.link in (select itemid from reportserver.dbo.catalog                         where type = 5)          full outer join     reportserver.dbo.catalog c2         on             ds.link = c2.itemid where     c2.type = 5 order by     c2.name asc,     c.name asc; 	0.0057759582739051
9639366	21257	calculate with datetime-format and integers	select dateadd(minute,106, getdate()) 	0.0588158043076405
9640122	9659	mysql query on combination of and and or	select * from students where roll_no like '__2011%' and (subject1 ='maths' or subject2='maths' or subject3='maths' or subject4='maths' or subject5='maths' or subject6='maths'); 	0.114077027333917
9640202	9040	query to find out the stored procedure depending on a column	select object_name(m.object_id), m.* from sys.sql_modules m join sys.procedures p on m.object_id = p.object_id where m.definition like '%blah%' 	0.000657584781841531
9640571	33476	dates return null and not null values mysql	select sub_client_cd, policy_holder_id, suffix_id,        sum(case when disenroll_date is null then 1 else 0 end) as nulldatecount,        sum(case when disenroll_date is not null then 1 else 0 end) as notnulldatecount     from enrollment_test     where status = 0     group by sub_client_cd, policy_holder_id, suffix_id     having count(*) > 1; 	0.0135827429466917
9640788	25813	extracting first 3 out of 5 numbers through regexp in mysql	select distinct sic from siccodes where sic regexp '^781[0-9][0-9][0-9]'; 	0
9641485	35865	mysql view that "flattens" data	select     group_id,     sum(case when type = 1 then amount end) as type1_amount,     sum(case when type = 2 then amount end) as type2_amount,     sum(case when type = 3 then amount end) as type3_amount from your_table group by group_id 	0.0981609910325724
9642588	28377	how can i create a view that splits data from one record in the source table into up to three records in the view?	select shipid, 1 transfer, airlineid, airport1 origin, airport2 destination   from mysourcetable  where airport1 is not null union all select shipid, 2, airlineid2, airport3, airport4    from mysourcetable  where airport3 is not null union all select shipid, 3, airlineid3, airport5, airport6    from mysourcetable  where airport5 is not null order by 1, 2 	0
9643819	28317	get super set records not contained in a subset (mutual exclusion)	select * from tablea a  where not exists ( select b.itemid from tableb b where b.itemid = a.itemid                         and b.invid = parameter ) 	0.005355880788711
9644687	12832	select calculation for each row	select    d.id,    @tmp := (match (r.text) against('sleet snow rain' in boolean mode)) as r_matches,    s.total_matches,   s.total_matches + @tmp as total from days d left join condition_days r   on (d.id = r.day_id and match (r.text) against('sleet snow rain' in boolean mode)) left join (   select ss.day_id, count(distinct ss.condition_id) as total_matches    from conditions ss where ss.condition_id in (4, 13, 20) group by ss.day_id) s on (s.day_id = d.id) 	0.000533832619279304
9646677	16185	get people where multiple rows are equal (oracle sql)	select a.id as id1       ,b.id as id2 from   (select distinct id from mytable) a       ,(select distinct id from mytable) b where  a.id < b.id and    not exists        ( select a2.like          from   mytable a2          where  a.id = a2.id          minus          select b2.like          from   mytable b2          where  b.id = b2.id        ) and    not exists        ( select b2.like          from   mytable b2          where  b.id = b2.id          minus          select a2.like          from   mytable a2          where  a.id = a2.id        ); id1 id2 === === p1  p3 p2  p4 	0.000284010960207183
9647022	20816	how to merge records from two tables using group by clause in oracle?	select ward1.ward_id as "ward_id",ward2.ward_name, count(ward1.ward_id)as "no of occurrence"  from ward1,ward2  where ward1.ward_id = ward2.ward_id group by ward1.ward_id,ward2.ward_name; 	0.000506327265627663
9649744	36519	avg and count from one columns	select  teacher_id ,       course_id ,       count(*) ,       count(case when marks between 16 and 20 then 1 end) as counta ,       count(case when marks between 11 and 15 then 1 end) as countb ,       count(case when marks between 6 and 10 then 1 end) as countc ,       count(case when marks between 0 and 5 then 1 end) as countd from    yourtable group by         teacher_id ,       course_id 	0.000655469054869756
9651146	21858	ssrs - how to group date into today/yesterday/week/month in a matrix?	select   case when datediff(day, getdate(), datecolumn) = 0 then somecolumn else 0 end ctoday  case when datediff(day, getdate(), datecolumn) = 1 then somecolumn else 0 end cyesterday  case when datediff(day, getdate(), datecolumn) > 0 and             datediff(day, getdate(), datecolumn) < 8 then somecolumn else 0 end cweek  case when datediff(day, getdate(), datecolumn) > 0 then somecolumn else 0 end cmonth from   sometable where   datecolumn > dateadd(day, -28, getdate()) 	0.0174026254715335
9652221	21140	mysql query returning same fields referencing 2 different foreign keys	select  concat(student.lname,', ',student.fname),   concat(dep_faculty.lname,', ',dep_faculty.fname) as `assigned advisor`,  concat(actual.lname, ', ', actual.fname) as `actual advisor` from    student    join dep_faculty on student.assigned_advisor_id=dep_faculty.id   left join advise_hist on student.id=advise_hist.student_id   left join dep_faculty as actual on advise_hist.actual_advisor_id = actual.id 	8.6853991017079e-05
9652675	30477	unique columns with mysql union	select  distinct a.follow_id, a.user_id, a.following, b.donor_id, b.firstname, b.lastname, b.image from followers a inner join donors b on a.user_id = b.user_id where following = 257 	0.0191939243146688
9653445	2789	how can i select the the second last and last row from the database?	select top 2 * from names order by name desc 	0
9653461	14800	large mysql database	select count(*) as 'total', count(distinct u.uniqueuserid) as 'unique', ((count(*) / ( select count(*) from `sessions` where applicationid = '[appid]' and startapp between '[start]' and '[end]')) * 100) as 'percent', u.langid  from `sessions` as s, `uniqueusers` as u where s.uniqueuserid = u.uniqueuserid and s.applicationid = '[appid]' and s.startapp between '[start]' and '[end]' group by u.langid 	0.32670344867237
9654610	20230	mysql query : finding related attributes	select l.creatorid as u1, u.userid as u2 from table2 as u inner join table1 as l on l.listid = u.listid 	0.0143311360616975
9660942	6214	php/mysql pattern to order posts?	select * from `posts` order by sort_index desc, date_posted desc 	0.0227906953258402
9661757	23218	force avg to return 0 instead of null when preforming on an empty set in sql server 2008	select isnull(avg(rating),0) as average, name,levels.levelid,blocks from levels left join reviews on levels.levelid = reviews.levelid group by levels.levelid, name, blocks 	0.610865715467823
9661784	4340	sql comparing two tables	select ur.uno,         count(case when q.eno='1' then 1 end)*5 as test1,         count(case when q.eno='3' then 1 end)*5 as test3  from question q,        userresponse ur where q.eno in ('1', '3')   and q.eno = ur.eno    and q.qno = ur.qno    and q.correctanswer = ur.response  having count(case when q.eno='1' then 1 end) >        count(case when q.eno='3' then 1 end) 	0.014435870501059
9662054	6683	count based on row entries?	select substring(grade, 1, 1), count(substring(grade, 1, 1))   from grades  group by substring(grade, 1, 1) 	0
9663473	18162	need to show only the duplicate value in sql	select id, name, roll, class from (select id, name, roll, class,              count(*) over(partition by name, roll, class) as c       from yourtable) as t where c > 1 order by id 	0.000217801196234302
9663607	30807	what are ways to get mutual friends in a (1, 2) (2, 1) friendship scenario?	select name from users u join friends f1   on u.uid = f1.uid or u.uid = f1.fid join friends f2   on u.uid = f2.uid or u.uid = f2.fid where (f1.uid=1 or f1.fid=1) and (f2.uid=3 or f2.fid=3)    and u.uid<>1 and u.uid<>3; 	0.000195795725149158
9666334	24974	contains search	select * from table where email like "*" & [enter string to search for:] & "*" 	0.198515768094298
9666579	336	mysql - timestamp in where clause	select * from t_splits where insert_ts < date_sub(now(),interval 10 second)  order by   insert_ts ; 	0.478964287347126
9667486	22791	how do i get the avg of multiple groups, by the parent's table id in mysql	select r.result_id, s.section_id, avg(sum) from answers as a join results as r on r.id = a.result_id join sections as s on s.id = r.section_id group by r.result_id, s.section_id 	0
9667589	4842	getting a list of friend's names from mysql	select name from users u join friends f    on u.uid = f.uid or u.uid = f.fid where (f.uid=1 or f.fid=1)    and u.uid<>1; 	0
9670561	22288	mysql execute query with on-the-fly values	select count(*) from ( select "apple" union select "pear" union select "onion" union select "ananas" union select "banana" union select "coconuts" ) t 	0.780016272001173
9670803	39977	how to reference a table by id	select     * from products p inner join store s     on s.storenumber = p.storenumber where p.id = 42 	0.00266045342510551
9670898	6701	joining tables , foreign key	select d.name, e.name, e.email, ... from deparments d inner join employees e on d.id = e.department_id. 	0.00157042893404324
9671707	2741	select command in mysql	select ( select the tables you want and concat into one string ) from table 	0.487063156843997
9672388	27408	concatenating columns and rows together	select distinct c.cust, options = ((select c2.opt1 + c2.opt2    from dbo.mydb as c2 where c2.cust = c.cust    for xml path(''), type).value('.[1]', 'nvarchar(max)')) from dbo.mydb as c; 	0.00167110538696631
9673575	19923	how to do complicate order by in mysql	select a, b, c, (2*a+b+3*c) combined_weighting from table order by combined_weighting desc; 	0.590999717012528
9673745	32980	outer join based on concatenated select	select ... from t1 left outer join t2 on t1.key = t2.pt1 || t2.pt2 where ... 	0.0281276186628969
9673843	13130	sql db2 conditional select	select  a.genrc_cd,         a.desc_30,         a.dol,         a.dlu,         a.lu_lid,         b.email_id_50 from    genrccd a left join         mpplnr b on a.desc_30=b.matl_plnr_id where a.genrc_cd_type = 'mdaa' 	0.740523809420291
9675935	17361	mysql query two tables, retrieve messages for each conversation	select m2.*, c.sender from (     select m1.conversationid, max(m1.messageid) as messageid     from messages m1     group by m1.conversationid ) latest_msg inner join messages m2     on latest_msg.messageid = m2.messageid     and latest_msg.conversationid = m2.conversationid inner join conversations c     on m2.conversationid = c.conversationid order by m2.messageid desc 	0
9676204	25770	cumulative percentage categorization query	select companypartnumber      , (parttotal + isnull(cum_lower_ranks, 0) ) / sum(parttotal) over() * 100 as cum_pc_of_total     from partsalesrankings psrmain    left join          (             select psrtop.item_rank, sum(psrbelow.parttotal) as cum_lower_ranks               from partsalesrankings psrtop               left join partsalesrankings psrbelow on psrbelow.item_rank < psrtop.item_rank              group by psrtop.item_rank          ) as psrlowercums on psrlowercums.item_rank = psrmain.item_rank ) sub2 	0.110717601908069
9676652	30043	sql join on a table name equal to a field value	select $table.*  from $table  join t_lastmod on '$table' = t_lastmod.table_name  where $table.lastmod != t_lastmod.lastmod " 	0.000404759034178757
9677171	11751	sql-server - ability to pass subset parameter in the select?	select [date], sum( case when type = 'electronics' then (ordersize) else 0 end) as electronicssum, sum( case when type = 'electronics' then 1 else 0 end) as electronicscount, sum( case when type = 'books' then (ordersize) else 0 end) as bookssum, sum( case when type = 'books' then 1 else 0 end) as bookscoumt from orders group by [date] 	0.252011447596238
9678260	1179	find all columns of a certain type in all tables in a sql server database	select table_name [table name], column_name [column name] from information_schema.columns where data_type = 'ntext' 	0
9680920	25331	how to sum and group values using mysql ?	select     sum(how_many) as per_day,     `date` from     cigaretes group by     date(`date`) 	0.138910037959101
9680948	4964	select everything after a certain row in sql	select  * from    fruit where   fruitname >= 'cherry' 	0.000337230606925435
9682931	16977	two tables connected by foreign key	select * from table_1 tbl1 left join table_2 tbl2 on tbl2.id = tbl1.id 	0.000276777385498982
9683289	163	get all data from parent record as the child record	select s.requestid, s.primaryrequestid, coalesce(p.prefix, s.prefix) as prefix from mytable p right join mytable s on p.requestid = s.primaryrequestid 	0
9684757	17849	query to get lowest value that's greater than zero ans is not null	select     taskdeadline,     subtasksdeadline,     nullif(         least(             coalesce(nullif(t.deadline, 0), 2147483647),             coalesce(nullif(sub.deadline, 0), 2147483647)         ), 2147483647     ) as deadline from     tasks t     left outer join subtasks sub on sub.task_id = t.id 	0.00150726944372209
9685053	8200	sql dynamic sum of column values	select   .   . case when dbo.school.schoolid = @schoolid then 1 else 0 end +   case when dbo.jobtitle.roletitleid = @roleid then 1 else 0 end as [newcolumn] 	0.0120066318296642
9685601	35261	transpose mysql query rows into columns	select     `year`,     `month`,     sum(if(`transporttype` = 'inbound',                 1, 0)) as `inbound`,     sum(if(`transporttype` = 'localpmb',                1, 0)) as `localpmb`,     sum(if(`transporttype` = 'long distance',           1, 0)) as `long distance`,     sum(if(`transporttype` = 'shuttle',                 1, 0)) as `shuttle`,     sum(if(`transporttype` = 'export',                  1, 0)) as `export`,     sum(if(`transporttype` = 'extrusions-longdistance', 1, 0)) as `extrusions-longdistance`,     sum(if(`transporttype` = 'extrusions-shuttle',      1, 0)) as `extrusions-shuttle` from `deliveries` group by `year`, `month` 	0.00111818400881215
9685984	21970	how to exclude some rows from a select statement when 2 keys match?	select   * from   courses where   not exists (select * from scores where courseid = courses.courseid and userid = @userid) 	0
9686609	10418	view to replace values with max value corresponding to a match	select userid,useridx,maxnum,date from table a inner join (     select userid,useridx,max(number) maxnum     from table     group by userid,useridx) b  on a.userid = b.userid and a.useridx = b.useridx 	0.000341059881907532
9687687	6760	working out a sum total cost where purchases and prices are in separate tables	select sum(purchases.quantity * rewards.cost_to_user) as total_points_spent 	0.00010773572652632
9688330	24213	retrieve date format from machine settings	select dateformat  from   sys.syslanguages  where  name = @@language 	0.00263066391402631
9689262	28575	searching in 2 tables in one query mysql	select id, stafffirstname as name1, stafflastname as name2 from import_staff where concat(stafffirstname,space(1),stafflastname) like '%$querystring%' limit 10 union all select id, studentfirstname as name1, studentlastname as name2 from import_student where concat(studentfirstname,space(1),studentlastname) like '%$querystring%' limit 10 	0.0101762677876482
9690295	40447	inserting multiple rows in a single table	select * from dual; 	0.000620888343766829
9690375	13180	different search query in sql with different string on column	select id, data from mytable where 'abcghilnm' like concat('%', data, '%') 	0.00347442169131748
9691805	29836	mysql: best way to combine multiple max() selects with an array?	select * from table where id in (45,23,14,7) order by price desc, rating desc, field(id,45,23,14,7) asc limit 1 	0.0583098958233303
9693273	39802	mysql group by having return a set	select * from table a, (select * from table where url_id in (3629,4115) group by url_id having max(id)) b where a.id=b.id; 	0.0999537903148194
9693581	17582	select list of grouped rows, showing content of most recent	select      messages1.`from`,      messages1.`message`,      messages1.`date` as d,      messages2.`count`,      contacts.`contactid`,      contacts.`contactname`,      contacts.`contactfrom`  from messages as messages1,    (           select               max(`date`) as maxdate,              `from`,              count(*) as `c`           from messages           where              `user` = 'myuser'           group by `from`    ) as messages2 left join   (       select           *       from          `contacts`       group by `contactsfrom`   ) contacts on    (        contacts.`contactuser` = 'myuser' and        contacts.`contactsfrom` = messages2.`from`    ) where    messages1.`from`= messages2.`from` and    messages1.`date` = messages2.`date` order by `date` desc; 	0
9698600	11993	selecting records from one table	select * from tbl_product_rel where attr_id in (10,15,20) group by product_id having count(product_id) = 3 	0
9698977	23421	group by month of unix timestamp field	select    month(from_unixtime(date_assigned)),    year(from_unixtime(date_assigned)),    count(*) from assignments group by    month(from_unixtime(date_assigned)),    year(from_unixtime(date_assigned)) 	0
9700774	39098	inserting random numbers into a table in mysql	select @cnt := count(*) from my_table; update my_table set random = floor(@cnt * rand()) + 1; 	0.000577999491439418
9701169	16454	mysql and several concats?	select concat('insert into catalog_category_entity_text (value) values(\'',value,'\') where value_id = ', value_id) from catalog_category_entity_text where value like '%category-slider%' 	0.175215798695917
9704070	26566	calculate totals of field based on current fiscal year only - sql	select userid, sum(total_hours) - sum(missed_hours) as hours     from mytable where startdate >= cast( cast(year(dateadd(mm,-6,getdate())) as varchar(4)) +                           '-07-01' as date ) and       startdate <  cast( cast(year(dateadd(mm, 6,getdate())) as varchar(4)) +                           '-07-01' as date ) group by userid 	0
9704238	7506	ssis getdate into datetimeoffset column - data value overflowed the type	select cast(your_date_column as datetimeoffset(0)) 	0.00101504811896753
9704867	24311	looking to print custom message from select query at ms sql	select stuff(substring(str_id,5,12),6,7,' '),value from board (this is a simplify query, the one has several joins) 	0.131091824180076
9707381	18020	mysql complex select	select w.* from warehouses w join hardwares h on w.hardware_id = h.hardware_id join brands b on h.brand_id = b.brand_id where brand_id=10; 	0.774442729857469
9708702	7596	given a user, select the user with most common ratings	select     r1.user_id as user1     ,r2.user_id as user2     ,r1.rating as rating     ,count(*) as num_matching_ratings from     ratings r1      inner join ratings r2         on r1.post_id = r2.post_id              and r1.rating = r2.rating             and r1.user_id <> r2.user_id  where     r1.user_id = 1      and r1.rating = 'like'  group by     r1.user_id     ,r2.user_id     ,r1.rating having     count(*) > 1  order by     count(*) desc 	0
9708925	31815	sql query to select from same column but multiple values	select distinct customer from tblname t1 where exists (select * from tblname where product = 'pen' and customer = t1.customer)     and exists (select * from tblname where product = '19" lcd screen' and customer = t1.customer) 	0.000173918697951581
9711249	13092	counting all sub categories whitin a category	select cct.id,     (select count(1) from category_cats where parent=cct.id) as subcount from category_cats cct 	0.000914614471532821
9712660	14533	mysql - getting maximum without grouping	select `name`,        (select max(age) from mytable) as `age` from mytable; 	0.00808634840879935
9712704	39618	how would i join 2 tables if where the primary key matches a 3rd and sort by the 3rd table?	select table_1.*, table_3.expire as t3_expire   from table_1   inner join table_3 on table_1.id = table_3.id union all select table_2.*, table_3.expire   from table_2   inner join table_3 on table_2.id = table_3.id order by t3_expire desc; 	0
9714392	35076	mysql error: subquery returns more than 1 row	select t2.studentid    from feesasigned t2    inner join (   select t3.studentid, sum(t3.remittedamt) feesum   from remittedfees t3    group by t3.studentid) v on t2.studentid = v.studentid and t2.fees = v.feesum 	0.656922265200273
9717015	12385	how to get row when change in column data	select *  from 'table_name' t where t.status = 'onsite' and         exists(select t1.id                 from 'table_name' t1                 where t1.status = 'abroad' and t1.id<t.id                order by t1.id desc                 limit 1,1); 	0.000316614411571152
9718195	3015	retriving all rows with maximum value	select state as ls,count(*) as total ,max(sales) as ye from  table     where sales = (select max(sales) from table) group by state 	7.06376037850203e-05
9719040	36955	t-sql compare a number against a padded number substring	select  * from    atable where   right('0' + cast(colb as varchar), 2) +         colc +         right('000' + cast(cold as varchar), 4) +         cole +         cast(colf as varchar) <> cola 	0.0004427213749279
9719629	18403	selecting data from four tables at once	select * , group_concat( concat(tags.tag_id,'=',tags.tag_name)) 	0
9719742	19813	sql server daily average	select cast(datecolumn as date), avg(value) from table group by cast(datecolumn as date) 	0.00597608440344569
9721436	27818	string conversion to datetime in sql server	select convert(datetime, convert(char(23), '2010-07-28 20:07:25.733000000')); 	0.319343477209505
9722227	10963	setting date and time variables in php	select * from events where %date_start_selected% between to_date(start_datetime and end_datetime) 	0.211944475447801
9722284	38197	joining counts in sql	select planned_realized as vehicle,         sum(total_planned) as total_planned,        sum(total_realized) as total_realized from (select planned as planned_realized,          1 as total_planned         0 as total_realized  from subquery  union all  select realized as planned_realized,         0 as total_planned,         1 as total_realized  from subquery ) sq group by planned_realized 	0.121048504015267
9722490	11103	computing ratio of records existing in another table	select t1.attr, count(t2.url) / count(t1.attr) as ratio from t1 left join t2 on t2.url = t1.link group by t1.attr order by ratio 	5.07676363925054e-05
9722865	2808	mysql query; select all items in category tree	select item.* from #table_items as item left join #__foc_shop_categories as cat1 on (cat1.id = item.catid) left join #__foc_shop_categories as cat2 on (cat1.parentid = cat2.id) ... (and so on for more depth) where (cat1.id = 12 or cat2.id = 12 or ...) group by item.id 	0.000346486250145165
9723445	29183	return sql subquery as boolean field?	select p.person_name, p.person_lastname,    (pn.phonenmb_id is not null) as hasphonenumber from person p   left outer join phone_number pn on pn.phonenmb_person_id = p.person_id                                   and pn.phonenmb_number = somenumber group by p.person_name, p.person_lastname 	0.302247580800983
9724761	3400	how can i convert a date to format "dd/mm" in oracle?	select to_char(date_open, 'dd/mm') from ... 	0.0596238835980454
9725162	1055	multiple left joins with multiple count()	select post.idposts, post.title, post.date_poste,     coalesce(cc.count, 0) as commentcount,     coalesce(lc.count, 0) as likecount from post p  left outer join(     select post_idpost, count(*) as count     from post_has_comments     group by post_idpost ) cc on p.idpost = cc.post_idpost left outer join (     select post_idstories, count(*) as count     from post_has_likes     group by post_idstories ) lc on p.idpost = lc.post_idstories where p.idusers = 1 	0.794230518317826
9725413	21136	count() return 0 instead of null	select       v_rpt_company.company_name,  count(distinct so_activity.so_activity_recid) as touches,  max(so_activity.date_entered) as lasttouch from   v_rpt_company   left outer join  company_team  on company_team.company_recid = v_rpt_company.company_recid and company_team.acctmgr_flag = 1 left outer join v_rpt_member on v_rpt_member.member_recid = company_team.member_recid   left outer join so_activity on v_rpt_company.company_recid = so_activity.company_recid and ((so_activity.last_update >= convert(datetime, @date_start, 101)) and ( so_activity.last_update <= convert(datetime, @date_end, 101)))  where v_rpt_member.member_id = @member  group by v_rpt_company.company_name order by v_rpt_company.company_name asc,lasttouch desc,touches desc 	0.0170636089684354
9725885	13581	how can i sort a group by in mysql?	select max(id), user_id from orders group by user_id 	0.117393972749836
9727320	1268	most viewed posts in the last 21 days	select visits.blogpostid, count(dtpost) as counted from posts  left join posts on posts.id = visits.blogpostid  where dtpost between (now() and <-21 days interval function>)  order by counted desc group by visits.blogpostid; 	0
9728212	2966	grab top 5 rows and combine the rest sql server	select top 5 groupname, sum(amount) as theamountspent into #tempspent from purchases group by groupname order by theamountspent desc select * from #tempspent  select sum(amount) as theamountspent from purchases where groupname not in (select groupname from #tempspent) drop table #tempspent 	0
9729966	23410	querying facebook's location_post table for specific region	select id, page_id from location_post where distance(latitude, longitude, '37.86564', '-122.25061') < 10000 	0.0258836715124955
9730325	21750	performing boolean logic on specific multiple rows in a mysql table/view	select 0 =   (   select    (     (select ran from expect.task_status where task='network_backup')      +     (select ran from expect.task_status where task='tape_backup')   ) ) 	0.0201679131114177
9730873	22116	select from mysql view with having clause returns empty result set	select * from (     select      restaurantname,      restaurantid,      locationid,      locationcity,      locationstate,      locationaddress,      locationlatitude,      locationlongitude,     ( 3959 * acos( cos( radians('%s') ) * cos( radians( locationlatitude ) ) * cos( radians( locationlongitude ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( locationlatitude ) ) ) ) as distance      from newview ) s where distance < '%s'  order by distance 	0.31623544234068
9732647	1485	sorting groups within a query	select * from songs t1 join ( select to_days(date) day from songs  group by day  order by day desc  limit $start_row, $items_per_page ) t2 on to_days(t1.date) = t2.day order by id desc 	0.105645218936382
9733642	9761	increase row count in sql server after some count (say 25,000)	select column1,         column2,        1 + ((row_number() over(order by column3) - 1) / 5) from yourtable 	0.0316826443360824
9734879	34165	apply distinct and top(1) together 	select m.id, m.value, m.createddate, o.x, o.y, o.z from (select tm.*, row_number() over (partition by id order by createddate) rn       from #tblmain tm) m left join othertable o on m.id = o.id where m.rn=1 	0.777865225558084
9734893	7681	sql unique and join	select from (select l.*,               row_number() over (partition by [userid], [detailstatid]                                 order by [createdon] desc) rn       from detailstatuserlog l) ll join ssusers u on ll.[userid] = u.[userid] join detailstat s on ll.[detailstatid] = s.[detailstatid] where ll.rn=1 	0.163085123257921
9735240	31923	select rolling date range from year/month instead of date field	select item, [year], [month],[demand qty]  from [table1]  where ( [year] = year(getdate())-'1' and [month] >= month(getdate()) ) or        ( [year] = year(getdate()) and [month] <= month(getdate()) ) 	0
9737015	35148	return true if all the the records of first table exists in second table	select case           when exists (select id                        from   @t1                        except                        select id                        from   @t2) then 0           else 1         end 	0
9738307	21213	i want to search no of rows containing aphostrophe string	select * from table where field like '%''%' 	0.00340507983677869
9739524	30475	sql server - field that hold value from subquery	select * from (     select p.id,            received = (select rec from exp                          where estamt = (select max(ex.estamt) from exp ex                                        where ex.prot = p.id and estamt > 0)                       )     from prot   ) subsel  where received = 1 	0.0106817768501846
9739601	16519	order by (count records with this fk)	select         count(c.aid) as number_of_records      , a.*    from         `tablea` a     join         `tableb` b       on b.id  = a.bid      left join                               `tablec` c                          on c.aid = a.id group by     a.id order by      number_of_records desc; 	0.248381769968026
9740421	1047	get max average for each distinct record in a sql query	select  playerid ,       max(league_avg.score) from    (         select  playerid         ,       avg(score) as score         from    scores         where   season = '2011-2012'                  and score > -1         group by                 playerid         ,       leaguename         ) as league_avg group by         playerid 	0
9740430	9077	efficiency of query	select country, count(id) rowcount from tbl where hide <> 1 group by country having rowcount >= 1 	0.497915490054992
9743435	39548	list the same field twice if different field in same table matches two different values	select posts.post_id as post_id, meta1.meta_value as genus, meta2.meta_value as species   from wp_posts posts     left outer join wp_postmeta meta1       on posts.post_id = meta1.post_id and meta1.meta_key = "genus"     left outer join wp_postmeta meta2       on posts.post_id = meta2.post_id and meta2.meta_key = "species" 	0
9743437	2331	same sql query on each array element	select   the_table.room,min(eventtime) as event_start_time_of_day from     the_table group by the_table.room; 	7.35193771650114e-05
9743714	255	sql counting rows for two columns where col1 same as col2	select * from   (select data1, count(data1) from table group by data1) d1   join (select data2, count(data2) from table group by data2 order by data2) d2     on d1.data1 = d2.data2   order by d1.data1; 	8.10869521024575e-05
9743810	6441	calculate closest working day in postgres	select max(s.a) as work_day from (     select s.a::date     from generate_series('2012-01-02'::date, '2050-12-31', '1 day') s(a)     where extract(dow from s.a) between 1 and 5     except     select holiday_date     from holiday_table     ) s where s.a < '2012-03-19' ; 	0.00521880310038584
9743866	30113	mysql query returns duplicates	select table1.image_name, table1.item_id from table1, table2, table3 where table2.catagory="item" and table3.account_id=59 and table1.id = table2.item_id and table2.item_id = table3.id 	0.484019353659295
9743944	15877	sql merge rows - string data type	select     code,     max(col1) as col1,     max(col2) as col2,     max(col3) as col3 from your_table group by code 	0.00213437778781212
9744144	26744	take hourly average in sql	select      cast(floor(cast(timestamp as float)) as datetime) as day              , datepart(hh, timestamp) as hour             , avg(value) as average from        times group by    cast(floor(cast(timestamp as float)) as datetime)             , datepart(hh, timestamp) 	0.00138116867928883
9744272	24546	how to retrieve an oracle sequence value?	select to_char(my_schema.my_sequence.nextval, 'tm9') from dual 	0.00302754316896418
9746314	17165	sql item number based on the items that are "visible"	select * from (     select                        b.*,     @itemcount:=@itemcount +1 as item_number     from items b, (select @itemcount :=0) r     where visibility != 0 ) as b  limit 0, 30 	0
9746402	33601	mysql query 2 tables in 1	select     u.name,     s.points from     tbl_users as u left join tbl_scores as s on u.user_id = s.user_id 	0.0370239978555493
9748191	10514	is there a better way to determine the most trusted users in a bookstore database?	select judgedloginname, sum(if(trustlevel = 0, -1, 1)) from judges group by judgedloginname, order by 2 desc 	0.00999433838715493
9749265	6993	retrieve data from complex situation of tables	select acct1.name as doc_name,         acct2.name as hospital_name from accounts_csm as acsm left join accounts as acct1     on acsm.account_id_c = acct1.id left join accounts as acct2     on acsm.doctor_hospital_id_c = acct2.id 	0.0118623351307191
9749675	30382	sql query for selecting data from a table with complex structure	select     t1.student_name ||      coalesce(' ' || t2.student_name, '') ||     coalesce(' ' || t3.student_name, '') ||     coalesce(' ' || t4.student_name, '') as "first 4 names"   from mytable t1   left join mytable t2 on t1.student_id = t2.student_id and t2.name_id = 2   left join mytable t3 on t1.student_id = t3.student_id and t3.name_id = 3   left join mytable t4 on t1.student_id = t4.student_id and t4.name_id = 4   where t1.name_id = 1 	0.035033685512956
9750254	33599	what is the correct way to query two columns in a table using and or in sql?	select * from products where category1 = 2 or category2 = 2 	0.148400464388207
9751169	17761	mysql union duplicating results	select      p.id as id,     p.publisher as publisher,      p.flag as flag,     sum( p.visits ) as visits,     count(distinct m.id) as magazines  from     publisher p left outer join     magazine m      on m.publisher = p.id group by p.id, p.publisher, p.flag order by publisher 	0.414668373217001
9751632	19220	not exists: select accounts not assigned to particular project?	select client_id, first_name, last_name, profile_pic, job_title, company_name   from client  where client_id in         ( select account_id             from account            where access_type = 'client'         )    and client_id not in         ( select account_id             from project_assigned            where projectid = 48         ) ; 	0.0474653609522058
9752092	4331	date clashes between form and database	select * from room where date_booked = convert(date, @userentereddate) 	0.0122017394809452
9753561	27402	how to search a value which can returns true in where condition or in having condition?	select     article.id,     article.name,     group_concat(tags.name order by tags.name) as nametags,     group_concat(tags.id order by tags.id) as idtags,     max(if(article.name like '%var1%',1,0)) as var1match,     max(if(article.name like '%var2%',1,0)) as var2match from     article     left join ....     left join .... group by id having     (nametags like '%var1%' or var1match=1)     or (nametags like '%var2%' or var2match=1) 	0.115129040249111
9755253	31487	how to query to create new database table from 2 separate tables?	select   products.productid,   products.productname,   red  .price as redprice,   green.price as greenprice,   blue .price as blueprice from products left join prices red   on products.productid = red  .productid and red  .color = 'red' left join prices green on products.productid = green.productid and green.color = 'green' left join prices blue  on products.productid = blue .productid and blue .color = 'blue' 	0
9756006	3372	find newest billings unpaid	select user_id, sum(if(type = '+', amount, -amount)) amount from t group by user_id + | user_id | amount | + |       1 | -0.75  | + 	0.0127711359388105
9756424	3253	show "0" in count column when where does not match?	select `users`.`user`, count(`played_games`.id) as `c` from `users` left outer join `played_games` on `users`.`user_id` = `played_games`.`user_id` and `played_games`.`game_cat` = "fps" group by `users`.`user_id` order by `c` desc, `user` asc 	0.165471513720794
9756964	18970	how to select within one column where the fields are similar	select t1a.*  from table1 t1a  join table1 t1b   on t1a.column2 = t1b.column2 and t1a.column1 <> t1b.column1 where t1a.column1 in ('andrew', 'brandon') and        t1b.column1 in ('andrew', 'brandon'); 	0.000159965517568193
9756997	24630	sql select statement with two foreign key taken from the same table	select a.cityname,c.cityname from b b join a a on b.fromcityid=a.cityid join a c on b.tocityid=c.cityid 	0
9757222	26981	sql query to exclude certain values from table	select distinct room_id from room_booking where room_id not in      (select distinct room_id      from room_booking      where date_booked = '$date'     ) 	0
9757679	24477	how to get individual count of same value rows with join	select c.`id`, count(1)   from categories c inner join subcategories sc         on c.`id` = sc.`cat_id`  group by c.`id` 	0
9758328	23534	mysql getting mutliple collections and their latest image from a database using one query	select c.*, images.* from collections c inner join (     select collection_id, max(images.id) as max_id     from collection_images     inner join images         on collection_images.image_id = images.unique_id     group by collection_id ) as latest     on c.unique_id = latest.collection_id inner join images     on latest.max_id = images.id where (c.creator in ($dropper_id)) 	0
9758817	36213	going mad - i need to get grouped results sorted based on conditions	select p1.* from products p1 left join products p2   on p1.item=p2.item and      (if(p1.totalstock,1,0) < if(p2.totalstock,1,0) or       (if(p1.totalstock,1,0) = if(p2.totalstock,1,0) and        p1.price > p2.price) or       (p1.price = p2.price and         p1.totalstock < p2.totalstock) or       (p1.price = p2.price and         p1.totalstock = p2.totalstock and        p1.id > p2.id)) where p2.id is null 	0.000247417032483909
9759015	38214	sql less than 7 days	select order_id from (     select order_id, min(date) as mindate, max(date) as maxdate     from tbl     group by order_id) t where datediff(maxdate,mindate) <= 7 	0.000844126296447427
9759341	31791	postgresql - order by using arrays. can i create array dynamically?	select mandato, raggruppamento, banker,      count(*) over (partition by raggruppamento) as order1.     count(*) over (partition by banker) as order2 from ok_filiali order by order1 desc, order2 desc; 	0.16400479584371
9759506	5718	sql query - all leisures of a person	select l.nom from personnes p join personner_loisirs pl on p.id = pl.fk_personnes join loisirs l on l.id = pl.fk_loisirs where p.nom = 'smith' and p.prenom='alex' 	0.00737207849081277
9759967	2354	sql server - select specific rows	select * from yourtable where a_no is not null union all select * from yourtable where id not in      (select id from your table where a_no is not null) 	0.011872481453691
9761114	840	check if a user exists in sql database, make the user, if not, don't make one?	select id from user where login="johnsmith" 	0.00175945261897745
9761454	40269	mysql count function across multiple tables	select ta.user_id,   (select count(*) from tb where ta.user_id = tb.user_id) countb,   (select count(*) from tc where ta.user_id = tc.user_id) countc from ta where ta.user_id = 1 	0.116079031309543
9761959	7877	postgres left join is creating more rows than in left table	select citation_id from stops join master on stops.citation_id = master.citation_id group by citation_id having count(*) > 1 	0.647387257316108
9762928	15353	how to find email with more than 2 dots using regexp mysql function?	select * from users where email regexp '[.].*[.].*@'; 	0.0977165212536575
9763033	20057	sql selecting from two tables	select ci.city_name, co.country_name from city ci inner join country co on ci.country_id = co.country_id where co.country_id = 1; 	0.000697821319091645
9763922	39159	select from two tables where linked column can be null	select * from orders o left join orderdata od on o.orderid=od.orderid 	0.00667081752891471
9764464	13732	sql compare date and particular time	select dateentry from mytable where date_add(dateentry, interval 8 hour) >= now(); 	0.00114679609231165
9766083	1355	how to get a comma seperated value for the following db table scenario	select outert.notice_idn,        stuff(isnull((select ', ' + innert.group_name                 from targettablename innert                where innert.notice_id = outert.notice_id             group by innert.notice_id, innert.group_name              for xml path (''), type).value('.','varchar(max)'), ''), 1, 1, '') group_name,        stuff(isnull((select ', ' + innert.employer_name                 from targettablename innert                where innert.notice_id = outert.notice_id             group by innert.notice_id, innert.employer_name              for xml path (''), type).value('.','varchar(max)'), ''), 1, 1, '') employer_name              from targettablename outert group by outert.notice_id 	0
9768479	22499	select rows where count of 2 fields is greater than 1 with where clause	select t.* from orders t inner join (     select ref, deleted, status     from orders     where deleted = 0 and status = 'paid'     group by ref     having count(ref) > 1 ) d on t.ref = d.ref and t.status = d.status and t.deleted = d.deleted; 	0.00112048340789493
9768808	8783	group ordering in mysql	select * from quotes  inner join quotes_panels on quotes.wp_user_id = quotes_panels.id  where quotes.created >= '$startdate'  and quotes.created <= '$enddate' and quotes.wp_user_id != '0' and quotes.roofarea = (select max(q.roofarea) from quotes q where q.wp_user_id = quotes.wp_user_id) group by quotes.wp_user_id 	0.447628402142577
9771682	15632	sql use rows as columns	select date,        min(case when product = 'p1' then sold end) as "p1",        min(case when product = 'p2' then sold end) as "p2",        min(case when product = 'p3' then sold end) as "p3"   from ___insert_table_name_here___  group     by date ; 	0.0235913206268502
9772133	3411	create a view of 3 tables	select pv.*,   max(if(pf.field = 'category1', pv.value, null)) as category1,   max(if(pf.field = 'category2', pv.value, null)) as category2,   max(if(pf.field = 'category3', pv.value, null)) as category3 from profile_values pv   left join profile_fields pf     on pv.fid = pf.fid group by uid 	0.0151067307557653
9772292	14308	sql - choose minimal row	select scr.order_number, scr.product_code, rel.operation, sum(rel.quantity) from scrdata as scr inner join relbde as rel on scr.order_number = rel.order_number, ( select scr2.order_number, min(rel2.operation) as operation                  from scrdata as scr2                  inner join relbde as rel2 on scr2.order_number = rel2.order_number                  group by scr2.order_number) as scr_op  where scr.order_number = scr_op.order_number    and scr.operation = scr_op.operation group by scr.order_number, scr.product_code, rel.operation 	0.00940046693873282
9772614	22630	sql apply sum avg conditionally	select index, case when index in (1, 3) then sum(value) else avg(value) end from yourtable group by index 	0.42265785426889
9777101	4335	mysql: selecting rows one batch at a time using php	select [stuff] limit 5000 offset 5000; 	0
9777498	25468	average data for every four hours in sql?	select  day ,       (hour - 1) div 4 ,       avg(value) from    yourtable group by         day ,       (hour - 1) div 4 	0
9778320	35812	how to get a textbox to dynamically update in apex?	select deptno d, deptno||':'||dname r from dept order by 1 	0.0171887718831151
9778390	1936	merge the two xml fragments into one?	select @a, @b for xml path ('') 	0.000185717206268921
9778908	15732	is there a way to group by using one column, but a set of values it could equal for a given group?	select case when id in (1,2)                then '1,2'                else id                end as custom_id_group          ... group by case when id in (1,2)                then '1,2'                else id                end 	0.000157269950123042
9780682	28969	sql server 2008 finding the user	select q.user_id from (   select distinct item_name from item where item_name like 'gun%' ) p, (  select distinct x.name_item,y.user_id  from userinventory x,    (select user_id,count(distinct name_item) as count_guns_userid   from userinventory   where name_item like 'gun%'   group by user_id  )y where x.user_id=y.user_id   ) q where p.item_name=q.name_item group by q.user_id having count(q.name_item)=3; 	0.0638194962024194
9781248	16574	sql select statement by choosing min timestamp value	select * from t t1 left join t t2 on t1.num_ser = t2.num_ser and t1.timestamp > t2.timestamp where t2.timestamp is null 	0.0140094137968951
9781337	36335	how to create a concatenated string of row values based on flags in sql server	select a.id,     replace(replace(replace(     (          select text         from flagtable as b          where a.flags & b.flag <> 0          order by b.text for xml raw     )     , '"/><row value="', ', '), '<row value="', ''), '"/>', '')      as 'attributes' from flagmappingtable as a order by a.id; 	0
9783047	30196	mysql how to make sure multiple associations exist	select videos.* from videos inner join tags_videos t1 on (t1.video_id = videos.id and t1.tag_id=1) inner join tags_videos t2 on (t2.video_id = videos.id and t2.tag_id=2) inner join tags_videos t3 on (t3.video_id = videos.id and t3.tag_id=3) 	0.643047659756089
9783453	33513	mysql filter table by related options table with grouped records	select distinct i.id, i.name from items i inner join items_has_options ihs1 on     i.id = ihs1.item_id inner join items_has_options ihs2 on     i.id = ihs2.item_id inner join options o1 on     ihs1.options = o1.id and (o1.name = "red" or o1.name = "blue" or o1.name="green") inner join options o2 on     ihs2.options = o2.id and o2.name = "s" 	8.98591782692739e-05
9783719	3975	selecting distinct join table data in cakephp	select      asapstructure.id,     asapaccelerator.id,     asapaccelerator.foreign_id,     asapaccelerator.title,     acceleratorsnode.progress_status,     asapaccelerator.filename,     asapaccelerator.filesize,     asapaccelerator.language,     asapaccelerator.doctype,     asapaccelerator.progress_status,     asapaccelerator.modified from     accelerators as asapaccelerator         left join     accelerators_nodes as acceleratorsnode on (acceleratorsnode.accelerator_id = asapaccelerator.id)         left join     asap_structure as asapstructure on (acceleratorsnode.node_id = asapstructure.id) where     asapaccelerator.progress_status = 5 group by asapaccelerator.id order by asapstructure.id asc, asapaccelerator.title asc limit 50 	0.0133415142246289
9784027	13958	calculate moving averages in sql	select year(gdte) as year,         month(gdte) as month,         sum(case when i=0 then active end)/6 as total,        sum(active)/(max(i+1)*6) as avg from (select s.*, date_add(dte, interval m.i month) gdte, m.i  from saturne s  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 union select 10 union select 11) m ) sq where gdte <= curdate() group by year(gdte), month(gdte) 	0.00468165487069632
9787846	19302	sqlite query to search in a combination of several columns concated to on string	select   t1.name as name,   tmpv1.name || tmpv2.name || tmpv3.name as v1v2v3 from   t1 join   t2 as tmpv1 on t1.v1 = tmpv1._id  join   t2 as tmpv2 on t1.v2 = tmpv2._id  join   t2 as tmpv3 on t1.v3 = tmpv3._id where   v1v2v3 like '%isi%' ; 	0.00100325188917805
9788211	2096	sql query to find rows where 1 column value matches another column on another row	select t1.symbol, count(0) as rows from table t1 join table t2 on t2.column2 = t1.symbol group by t1.symbol 	0
9788934	25851	how to select only date part from sql server ce datetime column?	select * from data where datediff(day, date, @date)=0 	0.000481658311683587
9792418	33961	how do i select user id, first and last name directly from wordpress database?	select a.id, b1.meta_value as first_name, b2.meta_value as last_name from wp_users a inner join wp_usermeta b1 on b1.user_id = a.id and b1.meta_key = 'first_name'  inner join wp_usermeta b2 on b2.user_id = a.id and b2.meta_key = 'last_name' where (b1.meta_value like '%st%' or b2.meta_value like '%st%' or a.user_email like '%st%') 	0
9793298	23926	how to replace ' from the select query	select distinct replace(city,'''', '''''') from person.address where city like '%''%' 	0.0259020820103278
9794275	4338	mysql select matching results	select m1.lid, l.lname from  `match` m1, `match` m2, leagues l where m1.lid = m2.lid and m1.lid = l.id    and m1.userid = 1    and m2.userid = 4 	0.0373322439528055
9794787	24399	convert not in to not exists	select id,         name,         cat  from   posts p  where  not exists (select 1                     from   (select 1 as col                             from   dual                             union                             select 100 as col                             from   dual) a                     where  p.id = a.col); 	0.701815626498814
9795360	31658	display todays bookings from mysql mrbs calendar	select * from $bookings where start_time >= unix_timestamp(current_date) and start_time < unix_timestamp(current_date + interval 1 day) order by start_time, room_id 	0.00153793996703191
9796102	7724	getting the missing dates from a sql table	select t1.enddate as gapstart, (select min(t3.startdate) from `table` t3 where t3.startdate > t1.enddate) as gapend from `table` t1 left join `table` t2     on t1.enddate = t2.startdate where t2.startdate is null 	0.000475521510048935
9796247	31175	sql grouping with two tables	select distinct     t1.datecreated, t2.code from     table1 t1 join     table2 t2 on t1.id = t2.id 	0.0411990136243461
9796781	34323	table join with count() condition	select * from patrons  where exists (select 1 from circulations                where circulations.patron_id = patrons.id) 	0.234494724994907
9797353	27618	sqlite: group_concat() multiple columns	select      company,     group_concat(concat) as formated from (     select         company,         case              when job is null then name             else name || ' (' || job || ')'         end as concat     from jobs ) group by company 	0.12267900962606
9797483	3188	form sql to return bool to c#	select case when count(column_name) = 0 then 0 else 1 end as iscolumpresent from information_schema.columns where table_name='customers'  and column_name = 'birthdate' and data_type = 'datetime' 	0.161925043375345
9797978	19814	transpose row to column using sql server	select distinct t.col1, ( select stuff( (     select ',' + convert(varchar(10),col2)     from table     where col1 = t.col1     for xml path('') ), 1, 1, '')  ) col2 from table t 	0.0203482922248681
9798409	17125	how do i dynamically create column in a sql view using a select statement?	select     sym1, msg1, 'src1' as src  from       table_src1  union all  select     sym2, msg2, 'src2' as src  from       table_src2 	0.165103305151691
9800628	39666	using new query as an alias	select  time as 'time',  counter_name as 'apples'  counter_id_2 'nuts' from t2 	0.773390510794586
9801112	25675	php / mysql query - if current time/date is in schedule	select * from events where now() between starttime and endtime 	0.0295909588980833
9802280	26058	display **start or end error message** with dates values using mysql	select `id`,`name`,`start_date`,`end_date`, '' `error_message` from teams  where sub_cat_id = '84' and  sysdate() > `start_date` and sysdate() < `end_date`  union all select null `id`, null `name`, null `start_date`, null `end_date`,         case when min(`start_date`)<sysdate() then 'start'             when max(`end_date`)>sysdate() then 'end'             when count(*)=0 then 'subcat'        end `error_message` from teams  where sub_cat_id = '84' and         not exists (select 1 from teams                    where sub_cat_id = '84' and  sysdate() > `start_date` and sysdate() < `end_date`) order by `id` desc; 	0.00881309890721998
9802333	20162	can i use unlike and "in" in one query?	select    *  from    att  where    uid = "f6c507fe-8928-4780-8b54-819611435755"  and    (item_position <> '99' or item_position is null) and    category in('cat1','cat2'); 	0.450942969912859
9802764	19664	sql get count of month	select month(datecolumn), count(*) from table group by month(datecolumn) 	0.000375138546485239
9802928	11178	make sure the records should be unique base on seq number?	select        v.name,v.age,v.seq from          t_values as v inner join    (     select        seq, count(seq) as total     from          t_values     group by      seq     having        count(seq) > 1 ) as d     on        v.seq = d.seq 	0.00714211816815628
9803004	16968	mysql group by with where clause with having count greater than 1	select * from `orders` where `deleted` = 0 and `status` = 'paid' group by substr(`ref`,1,5) having count(*) > 1 order by `id` desc 	0.494535889163247
9803384	5075	using 'and' in sql where clause for the same filed	select press_contacts.email from contacts_category     inner join press_contacts          on (contacts_category.contactdid = press_contacts.id) where contacts_category.categoryid in (1, 2) group by press_contacts.email having count(distinct contacts_category.categoryid)=2 	0.27518998100145
9805825	34998	return count grouped by category with item containing that category	select distinct  v.code,  v.codetype,  cnt = (      select count(*)       from mv_vehcode_union v2       where v2.code=v.code and v2.codetype = v.codetype ),  locations = stuff((      select distinct ',' + cast(locationid as varchar)       from mv_vehcode_union v2       where v2.code=v.code and v2.codetype = v.codetype       for xml path('') ),1,1,'')  from mv_vehcode_union v order by v.code 	0
9806227	20990	select blog articles by tag	select * from blogs b join blog_tag bt on b.id = bt.blogid join tags t on bt.tagid = t.id where t.text = 'mysql' 	0.0329293579477128
9807515	7890	modify the sql result	select      'self' as parent_id     count(*) as total from page as p where p.parent_id = p.page_id and p.type = 'page' 	0.187887332404673
9808851	27168	sql server 2008: store a date in nvarchar field	select cast(datepart(yyyy,getdate()) as char(4)) + '-'          + replace(str(datepart(mm,getdate()),2),' ','0') + '-'         + replace(str(datepart(dd,getdate()),2),' ','0') + ' '         + replace(str(datepart(hh,getdate()),2),' ','0') + ':'         + replace(str(datepart(mi,getdate()),2),' ','0') + ':'         + replace(str(datepart(ss,getdate()),2),' ','0') + '.'         + replace(str(datepart(ms,getdate()),3),' ','0') 	0.112423968542452
9809407	6505	how do i retrieve data with mysql such that i won't be getting duplicate values in a single column?	select distinct parent_course from mdl_course_meta 	0.000179959692658184
9810191	25558	oracle - select the latest distinct record from table	select * from (     select          id,         heading,         date,         row_number() over ( partition by id order by heading desc nulls last ) r     from table1 ) where r = 1 	0
9811422	38800	varchar datatype as primary key in in many-to-many relationship	select j.icd_fk     from icd_junction j         left join icd_text t             on j.icd_fk = t.icd_id     where t.icd_id is null; 	0.0247042749072632
9811508	33484	flex sqlite display sum() result	select sum(amount) as sum from maintable trace(result[0].sum); 	0.00654848521207765
9811533	32287	how to merge the result of this 2 queries in mysql server	select     `c`.`code`, `c`.`name`, `pc`.`sku`, `pc`.`cat_code`, `pp.title`,     `ol`.`sku`, `ol`.`update_date`, `ol`.`description`, count(*) as `total_sold` from `cat_parent` `cp` inner join `cat` `c`     on `c`.`code` = `cp`.`cat_code` inner join `prod_cat` `pc`     on `cp`.`cat_code` = `pc`.`cat_code` inner join `products` `pp`     on `pp`.`sku` = `pc`.`sku` inner join `orderline` `ol`     on left(`pc`.`sku`, 7) = left(`ol`.`sku`, 7) where `cp`.`parent_code` = 01110 and `hide` = 0 and `ol`.`update_date` >= ( date_add(curdate( ) , interval -14 day ) ) and `ol`.`update_date` <= ( date_add(curdate( ) , interval -7 day ) ) group by left( `ol`.`sku`, 7 ) order by `total_sold` desc 	0.0189943268481847
9812772	12452	mysql limit number of results for specific column	select distinct job, exists(select 1 from scan where scan.job_job = job) as scanning from job; 	0.000531338495414111
9813758	15527	filtering database results in android based on substring	select * from table_name where name like '%sky%'; 	0.0164661854683207
9814468	34462	mysql query list	select * from onlinechart where daytime >= ? order by maxcount 	0.17465897986472
9815028	20371	combine columns joined?	select if(client.first_name is null,admin_agency.admin_first_name,client.first_name)  as first_name ,... from ... joins.... where ... 	0.00360632190439715
9815310	22181	mysql two counts in one query with 3 tables involved	select *, count(distinct village.villageid) as cnt_village,  count( farmer.farmerid ) as cnt_farmers from town join village on village.townid = town.townid join farmer on farmer.villageid = village.villageid group by town.townid order by town.townname 	0.00185532998701242
9815707	38549	compressing sql rows for oracle 10g	select type,         name,         max(color) color,         max(description) description   from table_name  group by type, name; 	0.42748260057888
9820721	26858	select from table where there's multiple entries in one row	select id, group_concat(urls.url separator ' ') from ids  natural join urns  natural join urn_urls natural join urls  where type=4  group by ids.id  having count(distinct urls.url)>1; 	0
9821573	27490	sql to get distinct name and number from table	select *, count(*) from my_table group by name 	0
9821863	24158	joining 3 tables to get only two rows	select t1.c1, coalesce(t2.c2, t3.c2) c2 from table1 t1 left join table2 t2 on t1.c1 = t2.c1 left join table3 t3 on t1.c1 = t3.c1 	0
9822018	11562	mysql count from two tables	select idlibrarian, count(*) from loan group by idlibrarian order by 2 desc 	0.00225020557182194
9822285	10640	adding totals from two unrelated mysql queries	select     (sum(if(client.charging_identifier = 100000, costcl, 0)) - sum(if(client.charging_identifier = 100000, costadmin, 0))) +     (sum(if(client.charging_identifier <> 100000, costres, 0)) - sum(if(client.charging_identifier <> 100000, costadmin, 0))) from call_history, client where month(start) = 3 and year(start) = 2012 and call_history.client_reseller_id = client.id and client.charging_identifier <> 999999; 	0.00118517294680938
9822423	7423	how can i show duplicate rows using mysql "like"?	select   t1.vid, t1.number, t1.name from table t1   inner join table t2   on cast(t1.number as signed)=cast(t2.number as signed) and t1.vid!=t2.vid group by t1.vid 	0.00706254208437332
9824634	27922	find the result in one mysql query	select ((    select sum(val) from expenses where type='travel' ) / (    select sum(val) from expenses )) as pct 	0.0047441795193241
9826005	31520	combining two sql statements	select   * from   (select min(capacity) as mincapacity, max(capacity) as maxcapacity from room) as room cross join   (select min(grade) as mingrade, max(grade) as maxgrade from room_grade) as room_grade 	0.14449805087583
9827722	6792	get the maximum field value between different tables and the table from which it came	select 't1' as source, field from t1 union all select 't2' as source, field from t2 union all select 't3' as source, field from t3 order by field desc limit 1 	0
9828046	7042	sql query concatenate two columns during inner join	select *   from a  inner join b  on a1 + a2 = b1 	0.00781019244960195
9828190	29856	replace null values with another column in another table in sqlite	select case when t1._id is null then t2._id else t1._id end as id, t1.name , t2.img from t1 join t2 on (t1._id = t2._id); 	0.000216630353350601
9828195	887	combining results from same query into one new result - mysql	select    tag,   max(acquisition_cost),   max(purchase_date),   max(user)  from `table1` group by tag 	0
9831109	17700	tsql round to half decimals	select round(1.1 * 2, 0) / 2  select round(1.4 * 2, 0) / 2  select round(1.6 * 2, 0) / 2  select round(1.9 * 2, 0) / 2  	0.349882853134657
9833111	4812	joining two separate tables	select * from ( select roomid, room, latitude, longitude,                 acos(sin((:lat))*sin(radians(latitude)) + cos((:lat))*cos(radians(latitude))*cos(radians(longitude)-(:lon)))*(:r) as d from rooms as t1 where latitude>(:minlat) and latitude<(:maxlat)                 and longitude>(:minlon) and longitude<(:maxlon)                 and acos(sin((:lat))*sin(radians(latitude)) + cos((:lat))*cos(radians(latitude))*cos(radians(longitude)-(:lon)))*(:r) < (:rad) order by d limit 6 ) a, ( select name, date, roomid, descr from events as t2    where date > now() group by roomid order by date ) b where a.roomid = b.roomid; 	0.00284439171469086
9835901	18599	select an entry with specified id, and also one entry before and after with the same foreign key value	select * from test where id=3 and fk_book = 2 union all  select * from test where id < 3 and fk_book = 2 order by id desc limit 1 union all  select * from test where id > 3 and fk_book = 2 order by id asc limit 1 	0
9837734	36937	copy table from one server to another using select statement	select * into [newtable] from [linked_server].[databasename].dbo.[tablename] 	0.000321971740015194
9838969	6686	sql server avg function to return null if all values are null	select sum(a) from (select convert(int, null) a union select null) a 	0.0123517583654678
9839391	28242	sql server row with relative value?	select name,        money_earned,        money_earned / sum(money_earned) over() as his_percentage from [table] 	0.0168500769592754
9840772	40594	using like with a list	select b.*   from bulkjob b       ,sys_user s   where b.bulkjob_owner like '%' || s.sys_user_login     and s.sys_user_type_id in (3,4,5) 	0.409565395493451
9841915	40829	get the time difference?	select datediff(hh, dateadd(ss, 1332516308, '19700101'),dateadd(ss, 1335192846, '19700101')) 	0.00116375589595957
9845785	40085	find sql server tables that have two specified column names	select name from sysobjects where id in  ( select id from syscolumns where name = 'columna' ) and id in  ( select id from syscolumns where name = 'columnb' ) 	0
9846884	33495	select greater than oracle	select distinct count(*) as no_reservations, hg.resv_id, hr.booking_cus_id as booked_by, c.cus_name from holiday_reservation hr inner join(holiday_group hg inner join customer c on hg.cus_id = c.cus_id) on hr.booking_cus_id = hg.cus_id where hr.resv_id >= 2 group by hg.resv_id, hr.booking_cus_id, c.cus_name having count(*) > 1; 	0.0747447682057474
9847810	11677	mysql select query, splitting column data conditionally into 2 new columns	select     user_id,     sum(if(amount > 0, amount, 0)) bought,     sum(if(amount < 0, amount, 0)) spent from credit_log group by user_id; 	0
9847872	37484	mysql: select from table excluding where parameter	select * from your_table where id not in(7); 	0.013342725302364
9848545	8180	order by on date field starting in a middle point of the dates range	select * from test order by if(     date <= '2012-03-22',      datediff('2000-01-01', date),     datediff(date, '2000-01-01')  ); 	0
9848958	2922	showing auto-generated primary key on jsp	select last_insert_id(); 	0.113267624102416
9849348	23145	group only when there are more than 2 similar rows?	select counts.col,         counts.k  from   test         inner join (select col,                            count(col) k                     from   test                     group  by col                    having count(col)  < 3 ) counts           on test.col = counts.col  union all  select col,         count(col) k  from   test  group  by col  having count(col) > 2 	0.000411530359098572
9850293	14746	how to fetch null values in mysql through joins?	select `sfo`.*, `sc`.`message` from `sales_flat_order` `sfo` left join `shipping_comment` `sc` on `sfo`.`shipping_comment_id` = `sc`.`shipping_comment_id`; 	0.0237254150119803
9850758	6888	sqlite query for grouped time-frame	select strftime('%h', started, 'unixepoch') hour_,         sum(ended-started)+              (              select sum(now-started)              from sessionhistory               where ip='123.123.123.123' and ended=0              group by strftime('%h', started, 'unixepoch')              ) total_time_  from sessionhistory  where ip='123.123.123.123' and ended!=0 group by strftime('%h', started, 'unixepoch') 	0.0704823084820072
9851082	18397	sql query involving null values	select reviewer.name  from reviewer inner join rating on reviewer.rid = rating.rid where rating.ratingdate is null 	0.347372681348446
9851576	38974	combine dbgrid column values	select    sdate,    stime,    concat(cast(pcid as char), '_', cast(billno as char)) as machineandbillno,   c.customer_name,   ... 	0.00719257950223031
9852508	15341	group on id, and sum from different table (3 table total)	select top 10 s.salesid,     sum(sp.lineamount) as 'totallineamount' from ax_custpackingslipjour as s right outer join ax_salesline as sp on s.salesid=sp.salesid  left outer join ax_inventtrans as p on sp.itemid=p.itemid where s.salesid is not null group by s.salesid 	0
9852824	39819	i have 4 oracle sql queries which i want to have in one result	select * from  ( select rownum rownr, a.* from (select count(tl.usr) as "antall oppslag" from table tl where  tl.timestamp >= (sysdate - (1/24)) group by tl.usr order by count(tl.usr) desc) a where  rownum <= 20 ) a, ( select rownum rownr, b.* from (select count(tl.usr) as "antall oppslag" from table tl where  tl.timestamp >= (sysdate - (1)) group by tl.usr order by count(tl.usr) desc) b where  rownum <= 20 ) b,  ( select rownum rownr, c.* from (select count(tl.usr) as "antall oppslag" from table tl where  tl.timestamp >= (sysdate - (7)) group by tl.usr order by count(tl.usr) desc) c where  rownum <= 20 ) c, ( select  rownum rownr, d.* from (select count(tl.usr) as "antall oppslag" from table tl where  tl.timestamp >= (sysdate - (30)) group by tl.usr order by count(tl.usr) desc) d where  rownum <= 20 ) d where a.rownr = b.rownr  and a.rownr = c.rownr and a.rownr = d.rownr 	0.00295234456035985
9852972	38414	sql select all records from one table which appear < 3 times in another	select * from event where event_id in ( select themed_id from reservation group by themed_id having count(*) < 3) 	0
9853671	15153	sql select most common values	select age from persons group by age having count(*) = (   select count(*) from persons   group by age   order by count(*) desc   limit 1) 	0.000600123127676977
9854180	32526	display column value as table header rather than its original one	select distinct sd.submissionid    , sdname.fieldvalue as name    , sdposition.fieldvalue as position    , sdroom.fieldvalue as room from storage_det as sd left join storage_det as sdname on sd.submissionid = sdname.submissionid    and sdname.fieldname = 'name' left join storage_det as sdposition on sd.submissionid = sdposition.submissionid    and sdposition.fieldname = 'position' left join storage_det as sdroom on sd.submissionid = sdroom.submissionid    and sdroom.fieldname = 'room' 	0
9854749	40025	display multiple columns sql query into pl/sql stored procedure	select name, size_for_estimate, size_factor, estd_physical_read_factor into l_name, l_size_for_estimate, l_size_factor, l_estd_physical_read_factor   from v$db_cache_advice; 	0.00659519307319551
9856704	8219	simple where clause for column name 'user id'?	select * from user where `user id` = 'xyz'; 	0.14006621861482
9856977	12516	concatenating values in mysql where multiple rows in one table relate to one row in another table without displaying several rows	select pro_id, surname, firstname, group_concat(degree,school,year) as qual from profile left join qualification on qualification.qua_id = profile.pro_id group by qua_id 	0
9857534	28276	select non-existing pairs of ids in one mysql statement	select     m1.id as id1   , m2.id as id2 from myids as m1   join myids as m2     on m1.id <> m2.id where not exists       ( select *         from mycouples as c         where (c.id1, c.id2) = (m1.id, m2.id)       )   and not exists       ( select *         from mycouples as c         where (c.id2, c.id1) = (m1.id, m2.id)       ) 	6.52688968301464e-05
9858482	16849	mysql join - select col1 where col2 matches a (filtered) col in other table	select u.avatar from usertable u join replies r on u.responder_id = r.responder_id where r.convo_id = 1234 	0.00988909849144255
9858520	12222	query the two table for draw in one	select table1.email as email,      table2.accesses as acesses,      table1.attempts as attempts from table1  inner join table2  on table1.email = table2.email 	0.00274608783889472
9859590	27365	how would i display the winner in the following database schema?	select con.name, win.name as winner   from contestant con   join contestant win     on win.race_id = con.race_id    and win.position = 1  where con.name='thorpe' 	0.0269763081958093
9859596	16319	create new column with sql	select column_1,        column_2,        'content' as test from your_table 	0.065450688367347
9859821	33688	postgresql select statement	select       p.perf_date,       p.perf_time,       p.title,       s.area_name,       count(*) as seatssold    from       performance p          join booking b             on p.perf_date = b.perf_date             and p.perf_time = b.perf_time             join seat s                on b.row_no = s.row_no    group by       p.perf_date,       p.perf_time,       p.title,       s.area_name 	0.576251707556387
9860289	32989	select from array in mysql	select 1 union select 2 union select 3 	0.0201698762833387
9861986	4288	get earliest year from multiple tables	select min(y) from (     select min(year(added)) as y from table1     union select min(year(added)) as y from table2     ... ) as t1; 	0
9863755	8712	showing record from table year wise	select to_char(date_time, 'yyyy'), count(case_id) from   emer_complaint group by to_char(date_time, 'yyyy'); 	0
9864177	22365	sql server query to get selected rows by adding particular no of days to specific date	select *  from table where getdate() <= dateadd(dd, noticevisibilitydays, createdon) 	0
9864640	26677	get average of user distinct best score	select     gameid   , min(min_time) as min_time   , avg(min_time) as avg_time from     ( select           gameid         , min(time) as min_time       from            tablex       group by           gameid         , userid     ) as x group by     gameid 	0
9864722	36999	count rows of sql query involving select specific rows+from+where+and	select      count(collections.collection_id) from      users,     collections where      collections.user_id = users.user_id     and (             collections.description like  "%%searchterm%%"             or collections.name like  "%%searchterm%%"             or users.name like  "%%searchterm%%"         )     and (         reported = false         or (             reviewed = true             and approved = true         )     ) 	0.00600531477532223
9865247	31363	mysql: problems using count and sum functions in multi row select	select * from (   select @t1 := @t1 + 1 as num, ads.*   from ads, (select @t1 := -1) init   where city = 'maitland' and spot = 'home-banner'   order by id asc ) dt where dt.num = (   select sum(views) % count(id) from ads   where city = 'maitland' and spot = 'home-banner') 	0.76319750852785
9866216	13915	mysql query by string and limit	select * from details d where company in ('news', 'events', 'features') and not exists (     select 1 from details d_     where d_.company = d.company     and d_.id < d.id  ) 	0.343958001745852
9867115	35945	how to make the query fast of comparing between different data types in mysql	select *  from table1 join table2 on table2.intcol = cast(table1.varcharcol as signed) 	0.000532644871495798
9867301	25353	select from 3 fields, row0 unique id, row1 multiple id numbers, row2 a letter int(1) into new array	select el1.* from entry_log el1 left join (   select entry_id, log_id from entry_log   where type = 'd' ) el2 on el1.entry_id = el2.entry_id and el1.log_id < el2.log_id where el2.log_id is null and el1.type = 'd' 	0
9868409	37726	how to get records randomly from the oracle database?	select * from   (     select *     from   table     order by dbms_random.random) where  rownum < 21; 	0
9869383	18377	drop down list to change value on select	select * from ads_db where country='$q' 	0.00226934073535974
9869526	31369	how to match the values of two columns(same table) in diagonal and display the result when they don't match	select *  from bus_route b1  left join bus_route b2 on b1.from_city=b2.to_city and b1.to_city=b2.from_city where b2.from_city is null 	0
9870913	6494	php mysql - select where similar_text()>x	select ref_name, lst_name, levenshtein_ratio( ref_name, lst_name ) as textdiff from reference, list having textdiff > 60; 	0.678924723749683
9871008	26421	identify rows which are identical in 2 different tables	select * from tablea intersect select *  from tableb 	0
9872135	3452	t-sql - pivot by week	select depots.name as 'depot',  account.name, '22/01/2012',  '29/01/2012',  '05/02/2012',  '12/02/2012',    from  (select name,      from deliveries     inner join account on deliveries.customer = account.id     inner join depots on account.collectiondepot) as source pivot (     sum(deliveries.rates)     for date in ('22/01/2012',  '29/01/2012',  '05/02/2012',  '12/02/2012') ) as 'pivot table' 	0.068193108993408
9873928	18291	chosing row with smallest glength value	select glength(     linestringfromwkb(     linestring(         geomfromwkb(point(j.latitude,j.longitude))     ,geomfromwkb(point(51,22))))),j.latitude,j.longitude from my_database.place_table j  order by  glength(     linestringfromwkb(     linestring(         geomfromwkb(point(j.latitude,j.longitude))     ,geomfromwkb(point(51,22))))) asc limit 1; 	0.00425073533448479
9875782	33584	getting the most recent record of a group	select max(a.datecreated) as datecreated     , b.code from table1 a     join table2 b on a.id = b.id group by b.code 	0
9876013	6017	mysql query to list records with a count later related records	select invoice_id, company_id,    (select count(invoice_id)         from invoice i2 where i2.invoice_stamp > i.invoice_stamp)    as future_invoice_count from invoice i; 	0
9877131	13801	mysql timestamp selecting older records	select * from `file` where `accestime` != '0000-00-00 00:00:00' and `accestime` < timestampadd(day,-60,now()) 	0.00011626742977107
9877641	9166	round up date field to next half hour in sql	select case when to_number(to_char(sysdate,'mi')) > 30        then trunc(sysdate,'mi') + ((60 - to_number(to_char(sysdate,'mi')) +30)/1440)        else trunc(sysdate,'mi') + (30 - to_number(to_char(sysdate,'mi')))/1440 end from dual 	8.49815891929663e-05
9877896	19885	grouping by one column and two rows	select empid,sessionid,     min(created),max(created),     datediff(mi,min(created),max(created))  from a  group by empid,sessionid 	0.00014270531482714
9878523	36188	select a column if other column is null	select isnull(a, b) 	0.00231941791660881
9878667	31290	t-sql: same fields using multiple joins	select     c.customerid,     cov1.*,     cov2.*,     cov3.*,     insco1.inscompanyname as inscompanyname1,     insco2.inscompanyname as inscompanyname2,     insco3.inscompanyname as inscompanyname3,     etc... from     customer c     left outer join insurancecoverage cov1 on cov1.customerid = c.customerid and cov1.line = 1     left outer join insurancecoverage cov2 on cov2.customerid = c.customerid and cov2.line = 2     left outer join insurancecoverage cov3 on cov3.customerid = c.customerid and cov3.line = 3     join insurancecompany insco1 on insco1.inscompanyid = cov1.inscompanyid     join insurancecompany insco2 on insco2.inscompanyid = cov2.inscompanyid     join insurancecompany insco3 on insco3.inscompanyid = cov3.inscompanyid     join insuranceplan inspl1 on inspl1.insplanid = cov1.insplanid     join insuranceplan inspl2 on inspl2.insplanid = cov2.insplanid     join insuranceplan inspl3 on inspl3.insplanid = cov3.insplanid 	0.102337223653954
9879044	37740	find items where all parts are in stock	select tblcocktail.cocktailname from tblcocktail where   (   select  count(*)              from    tblcocktailingredient              where tblcocktailingredient.cocktailid = tblcocktail.cocktailid)          =         (   select  count(*)             from    tblingredient                      inner join (tblcocktailingredient                                 inner join tblunitconversion                                      on tblcocktailingredient.unitid = tblunitconversion.fromunitid)                         on (tblingredient.ingredientid = tblcocktailingredient.ingredientid)                             and (tblingredient.onhandunitid = tblunitconversion.tounitid)              where   [tblcocktailingredient].[amount] <= [tblingredient].[onhandamount]*[factor]                     and tblcocktailingredient.cocktailid = tblcocktail.cocktailid ) 	5.49885905916606e-05
9879096	2872	adding result of two different queries in mysql	select (select count(id) from table1) + (select count(id) from table2) as count 	0.00229601711532331
9879921	12643	two values either way round in two fields	select case when person1 = 'jim'       then person1       else person2 end as person1derivation, case when person2 = 'bob'      then person2      else person1 end as person2derivation from friends where (person1 = 'jim' and person2 = 'bob') or (person1 = 'bob' and person2 = 'jim') 	0.00129118300127032
9879946	5477	searching in mysql using match clause	select * from users where match(username) against ('lu*' in boolean mode) 	0.628017762431014
9880118	22493	mysql time delay a trigger	select sleep(600); 	0.360924491567281
9880175	21274	using sql to determine rate of change in data set	select t1.day, t1.item, (t2.value - t1.value) as rate from datatable t1 inner join datatable t2 on t1.item = t2.item  and t1.day + 1 = t2.day 	0.0074616251059122
9881802	10597	how to add more colums in mysql query	select distinct * from <table> where <whereclause> 	0.0374879319991704
9882466	31133	return all values that contain a specific string using oracle	select the_value from table1 where the_value like ‘%orange%’ 	0.00010247942352963
9883240	2487	mysql + codeigniter + click tracking unique & total clicks	select     *, count(acl.id) as totalclicks, count(distinct acl.ip_address) as uniqueclicks from       map_advertisements a left join  map_advertisements_click_log acl on a.id = acl.aid where      a.id = $aid; 	0.00673670680454239
9883758	18860	select a cloumn from given condition which is not the column name	select t2.*, t1.itemname from table2 t2 inner join table1 t1 on   (t2.shopcode = 1 and t2.itemcode = t1.codea) or   (t2.shopcode = 2 and t2.itemcode = t1.codeb) or   (t2.shopcode = 3 and t2.itemcode = t1.codec) or   (t2.shopcode = 4 and t2.itemcode = t1.coded); 	0.000118205666692393
9884236	17082	mysql union query with condition	select id, name, modified_date, 'event' as type from events  union  select id, name, modified_date, 'festival' as type from festival  order by modified_date desc 	0.767324182048158
9884715	18346	mysql custom order by	select a.prodname from tablea a   left join tableb b     on a.id = b.prod_id group by   a.id order by   if(b.prod_id is null, 1, 0), a.prodname; 	0.622135307420526
9884766	14409	how to store the result of a query into an sql variable	select * from city a  where not exists  (select 1 from city b where b.from_city=a.to_city and b.to_city = a.from_city ) 	0.00988353006062393
9885677	23174	calculate substraction by a specific quarter of year	select  ((select sumquarter from table where years=2009 and qtr=2 and rownum=1) -   (select sumquarter from table where years=2010 and qtr=2 and rownum=1)) as substract from dual 	5.00713725943821e-05
9885879	7736	how to group and choose lowest value in sql	select id, date_from, date_to, min(price) from table group by id, date_from, date_to 	0.00212432886447469
9886756	17010	database disjoint relationship described	select employee.firstname, [salaried employee].annual_salary, [hourly employee].hourly_rate from employee join [salaried employee] on [salaried employee].employeeid = employee.employee_id join [hourly employee] on [hourly employee].employeeid = employee.employee_id 	0.404153982327084
9886823	9373	recurring selection of rows based on value of the value in previous row	select id, name, mgrid from emp start with id = 101 connect by prior mgrid = id order by id 	0
9887894	24776	select rows not in another table for each condition of a field in the other table	select *  from agents, (select distinct document from documentsread) docs  where not exists (     select *      from documentsread      where agentid = agents.agentid and document = docs.document ) 	0
9888263	35	count records for every month in a year	select    count(*)  from      table_emp  where     year(arr_date) = '2012'  group by  month(arr_date) 	0
9889566	3084	refining the result of mysql query result	select nid, group_concat(fid) from tbl group by nid 	0.13761734966378
9889951	350	comparing "consecutive" rows in ms access	select t2.* from (select t.id, t.subid, t.time, t.value, t.value2 from test2 t where t.time=4)  as t2 left join (select t.id, t.subid, t.time, t.value, t.value2 from test2 t where t.time=3)  as t1 on t2.id = t1.id where t2.value<>t1.value  or t2.value2<>t1.value2  or t1.id is null union all select t1.* from (select t.id, t.subid, t.time, t.value, t.value2 from test2 t where t.time=3) t1 left join (select t.id, t.subid, t.time, t.value, t.value2 from test2 t where t.time=4) t2 on t1.id=t2.id where t1.value <> t2.value or  t1.value2 <> t2.value2 or t2.id is null order by id 	0.0129409562006679
9890202	12966	mysql left join with condition on table1	select students.* from students              left join courses                            on students.id = courses.id                  having students.id = 6 limit 1 	0.725378914487692
9890428	23640	self join plus another join	select     c.country,     s.score from     countries c     inner join scores s on c.id = s.fromid where     c.group = (select group from countries where country = 'france' limit 1); 	0.607806971186966
9891025	7404	sql select * from column where year = 2010	select * from mytable where year(columnx) = 2010 	0.012610243159435
9892057	34092	how to join two tables when the on clause is variable	select *   from mail    inner join member     on (mail.frommember = @me and mail.tomember = member.memberid)     or (mail.tomember = @me and mail.frommember = member.memberid) 	0.163168984177949
9893594	29624	how to query multiple rows involving a max?	select a, b, (select max(b) from table) as maxb from table 	0.0154940891673347
9894121	20644	find duplicates mysql up to number digits	select round(latitude,4), group_concat(point_id separator ',') from googlemap group by round(latitude,4) having count(*) > 1 	0.000832687168629273
9894691	12370	sql query to join results from two tables but also include rows that do not have counterparts in the other table?	select coalesce(a.name, b.name) as name, apples, oranges  from apple a  full outer join orange o on o.name = a.name 	0
9895743	19320	selecting duplicates	select c.id,         c.country  from   countries c         inner join (select country,                            count(distinct id) k                     from   countries                     group  by country                     having k > 1) t           on c.country = t.country 	0.0320405134720873
9896036	18229	sql - grouping, id, name	select stops.id, stops.name from route  inner join stops on route.stop = stops.id where route.num = 4 and route.company = 'lrt' 	0.0144263016009977
9896087	11066	how to make array from select returning more than one row	select array_agg(console_id) as consoles from archive_sessions where tournament_id = 14817 	0.000243296418150162
9896331	40215	is there an alternative to joining 3 or more tables?	select * 	0.575688591926128
9896457	35410	limit number of rows returned from sqlite	select col1, col2 from mytable where foo = 'bar' limit 42; 	0.000103784884902945
9897189	26429	select all colums from a table and some from another using left join	select a.*, b.id, b.name   from table1 a   inner join table2 b on b.id = a.id 	0
9897831	34157	join sum from same date	select date, sum(dollar)   from tablename  group by date 	0.00183658855441881
9898609	1928	join two tables and then group by	select     cn.country_name,     count(distinct c.c_id) as count_of_cities from     country cn left join     city c on c.id = cn.id group by cn.country_name 	0.0207718999621721
9899643	2939	sql - get results from table 1 but count all matching results from 2, 3 & 4	select a.title, c.cnt as comments, p.cnt as photos, v.cnt as videos   from blog_articles a  inner join admins ad     on a.author_id = ad.admin_id   left outer join (    select article_id, count(comment_id) as cnt      from blog_comments     group by article_id) c     on a.article_id = c.article_id   left outer join (    select article_id, count(photo_id) as cnt      from photos     group by article_id) p     on a.article_id = p.article_id   left outer join (    select article_id, count(video_id) as cnt      from videos     group by article_id) v     on a.article_id = v.article_id  where a.status = 'online' group by a.article_id order by a.published desc limit 0, 20 	0
9899880	41257	how do i efficiently select unique row/record data from 2 mysql tables and return one merged result, ordered by timestamp?	select records.datatype, comments.*, submissions.* from (     (         select comment_id, datatype         from comments         where userid=3         order by timestamp desc         limit 20     ) union all (         select content_id, datatype         from submissions         where userid=3         order by timestamp desc         limit 20     )     order by timestamp desc     limit 20 ) as records left join comments     on records.comment_id = comments.comment_id     and records.datatype = 'comment' left join submissions     on records.comment_id = submissions.content_id     and records.datatype = 'post' 	0
9900159	27116	mysql date formats - difficulty querying on a date	select noslots from calender where coursedate = str_to_date('01-01-2012', '%d-%m-%y'); 	0.0284660039682181
9900362	13244	semi-complicated result set in sql query	select a.name,b.percentage_yes_rsvp,b.percentage_after_yes from  (    select u.id as id,u.firstname+''+u.lastname as name   from users u ) a, (   select a.userid,a.percentage_yes_rsvp,b.percentage_after_yes from      (     select b.userid,round((cast(b.count_yes_rsvp as float)/b.total_count)*100,0) as percentage_yes_rsvp         from       (select a.userid,        sum(case when a.status=3 then 1 end)as count_yes_rsvp,        count(*) as total_count        from attendance a          group by a.userid      ) b   ) a,   (   select c.userid,(cast(c.count_after_yes_rsvp as float)/c.total_count)*100 as percentage_after_yes      from     (select a.userid,        sum(case when a.status=3 and a.attendance='true' then 1 end)as count_after_yes_rsvp,        sum(case when a.status=3 then 1 end) as total_count    from attendance a      group by a.userid    ) c )b    where a.userid=b.userid ) b where a.id = b.userid; 	0.625681061061952
9900758	38525	how do i write sql to get objects	select a.id, a. firstname, a.lastname, b.orderno from persons a inner join orders b on         a.id = b.personid where a.id = 1 	0.0999212428926674
9901942	12307	summation of concated fields in mysql	select user_id,        sum( activity + speed ) as indeks from tfts_fans  group by user_id  order by indeks desc 	0.0748171455536639
9902090	5902	mysql pulling two column from one table using join	select empname, ap_1.name, ap_2.name from employee  left join approver as ap_a on (employee.approver1 = ap_1.id) left join approver as ap_b on (employee.approver2 = ap_2.id) 	0.000129699917746143
9902394	31796	how to get last record from sqlite?	select *      from    table     where   id = (select max(id)  from table); 	0
9903697	18824	specific cross-join query	select a.*, value_b, value_c from tablea a left join (    select nvl(b.id_a, c.id_a) as id_a, b.value_b, c.value_c      from       (         select b.id_a, b.value_b,                row_number() over (partition by b.id_a order by b.id) rn           from tableb b      ) b      full outer join      (         select c.id_a, c.value_c,                row_number() over (partition by c.id_a order by c.id) rn           from tablec c      ) c        on b.id_a = c.id_a       and b.rn = c.rn ) maxrows   on a.id = maxrows.id_a 	0.311546859635201
9904355	16173	how to generate number between 1-99 from existing mysql table column?	select id, name, surname,  if(number between 1 and 99 ,number,floor(1 + rand() * 99)) as number  from table 	0
9905171	18399	recipe finder with php and mysql based on ingredients	select r.recipes_id     from recipes r     inner join recipes_pos rp on r.recipes_id = rp.recipes_id     where rp.ingredients_id in (4, 6)     group by r.recipes_id     having count(distinct rp.ingredients_id) = 2 	0.0577366805525909
9906326	25228	run a query on a query in mysql	select     assignments_join.* from     assignments as assignments_base     join assignments as assignments_join on         assignments_base.case_id = assignments_join.case_id where     assignments_base.username = 'ticrane' 	0.555083673192036
9906436	9140	select rows matching calculation	select id from   users where  date_format(date, '%a') = 'fri' and hour(date) = 9 	0.00757706992223576
9907856	22838	how to query comma delimited field of table to see if number is within the field	select * from `table` where `column` regexp  '(^|,)951($|,)' 	0
9908792	11516	how to get sum and count from this result set?	select collector, sum(amount) as amount, count(*) as `count`, name  from yourtable group by collector, name 	0.0032436571916597
9908838	17014	select current time "now ()"  and convert it to gmt 0	select utc_timestamp(); 	0.0011202381521661
9909042	35194	of people who took at least one ride, what's the average number of metro lines they rode?	select avg(ln) as avg_lines from (     select user_id, count(distinct line_id) as ln     from rides r join locations l on (r.location_id = l.location_id)     group by user_id ) 	0
9909843	1157	sql: querying counts on field values in a single table	select    'attr_1' as evaluation,   sum(case when attr_1_eval = 'correct' then 1 else 0 end) as correct,   sum(case when attr_1_eval = 'incorrect' then 1 else 0 end) as incorrect,   sum(case when attr_1_eval = 'undetermined' then 1 else 0 end) as undetermined from product union select    'attr_2' as evaluation,   sum(case when attr_2_eval = 'correct' then 1 else 0 end) as correct,   sum(case when attr_2_eval = 'incorrect' then 1 else 0 end) as incorrect,   sum(case when attr_2_eval = 'undetermined' then 1 else 0 end) as undetermined from product union select    'attr_3' as evaluation,   sum(case when attr_3_eval = 'correct' then 1 else 0 end) as correct,   sum(case when attr_3_eval = 'incorrect' then 1 else 0 end) as incorrect,   sum(case when attr_3_eval = 'undetermined' then 1 else 0 end) as undetermined from product 	0.000147970987448317
9910703	31537	get indexes by coumn name	select object_schema_name(object_id), object_name(object_id), name from    sys.indexes where   type > 0 and object_name(object_id) in (     select c.column_name     from information_schema.columns c      where collation_name is not null and collation_name <> 'sql_latin1_general_cp1_ci_as' ) 	0.0460884264239183
9913814	26705	sql query return null	select    distinct repdailyinfo.date  from    repdailyinfo  left outer join    repdailycollection c  on    c.repdailycollectionid = repdailyinfo.repdailyinfoid where    repdailyinfo.repid = 205 and c.isreceived = 0 	0.342790058594199
9914733	26250	one sql query instead of three sql queries	select t.size,         t.paper,         t.zip  from   tools t         inner join (select `id`,                            `country`                     from   `users`                     where  `ip` = ?                     limit  1) u         on t.users  like concat('%',u.id '%')            or t.user like 'all users'            or country like  concat('%',u.country '%')             or country like 'all countries' 	0.0378183692545336
9916218	3833	getting mulitple columns for group by from case-when-then	select (case @type        when 2 then kle.jnum         when 3 then kle.desc + kle.jnum          else kle.lnum end) as varchar) + @q + cast(count(sk.id) as varchar) + @q  from    dbo.sk sk  inner join k k  on k.kitid = sk.kitid inner join dbo.mlegend mtl on k.type = mtl.mtype inner join dbo.klegend kkl on mtl.kittype = kkl.kittype inner join dbo.kexpiry kle on k.expiryid= kle.expiryid where sk.sid=id  group by case @type      when 2 then kle.jnum      when 3 then kle.desc + kle.jnum      else kle.lnum end, mtl.ktype order by mtl.ktype 	0.00360572405562178
9916827	38769	mysql if statement	select if(@result = 0, 'true', '((something here))') as message 	0.557486168194769
9917497	30907	get post - wrong selection	select distinct p1.post_id_post from post_has_tags p1 where not exists (   select * from post_has_tags p2   where p1.post_id_post = p2.post_id_post and p2.tags_id_tags not in (561, 562) ) 	0.11435701293768
9917809	20288	two consecutive unions	select * from product natural join laptop        union     select * from product natural join pc        union     select * from product natural join printer 	0.0746315198009632
9919108	30149	i don't want mysql to sort the results found	select * from tablename where id in (4, 1, 7, 8, 2, 5, 6) order by find_in_set(id, '4, 1, 7, 8, 2, 5, 6'); 	0.00921694928880642
9919354	16258	mysql avoid displaying results twice from 2 conditions	select distinct(options.label) from options where userid='1' or userid="" 	0.0218499831177661
9919407	33289	php mysql - number of rows with column value between x and y, is there a better way?	select hour(from_unixtime(time)), count(*) from visitors where time between ('$start_time', '$end_time') group by hour(from_unixtime(time)) 	0
9919848	28393	t-sql how to count the number of duplicate rows then print the outcome?	select @numrecord= count(distinct productnumber) from productnumberduplicates_backups  print cast(@numrecord as varchar)+' product(s) were backed up.' 	0
9919958	18624	replace datetime in mysql	select  now() - interval minute(now()) mod 5 minute 	0.29455986782853
9920292	5943	mysql + count all words in a column	select count(length(column) - length(replace(column, ' ', '')) + 1) from table 	0.002140203385632
9921490	16044	use cursor to display rows and group them by one column using variable	select     salesordernumber + ' (' + convert(varchar, count(*)) + ' items) due ' + convert(varchar, h.duedate, 20) + ' is ' + statuses.name from     [sales].[salesorderdetail] s      join sales.salesorderheader h         on s.salesorderid=h.salesorderid     join (         select 1 as status, 'in process' as name         union all select 2, 'approved'         union all select 3, 'backordered'          union all select 4, 'rejected'          union all select 5, 'shipped'          union all select 6, 'cancelled'     ) statuses on         statuses.status = h.status where      h.duedate between '2008-08-01' and '2008-08-31' group by     h.salesordernumber,     s.salesorderid,     h.duedate,     h.status order by     h.salesordernumber desc 	0.000212404033423849
9921752	22975	selecting from two tables into an xml	select table2.name,table2.description,lastmeasurement.measurementid  from table2 t2     inner join         (select * from table1         inner join         (select max(datetime) as lastmeasurement, measurementid as lastmeasurementid         from table1 group by measurementid) as lastmeasurement         on (table1.measurementid = lastmeasurement.lastmeasurementid)          and (table1.datetime = lastmeasurement.lastmeasurement)) as hlastmeasurement     on table2.id = hlastmeasurement.id     order by table2.id asc 	0.000111490178289565
9922208	39812	select limit on a view in mysql	select * from sphinx limit 1 offset 512 	0.157372099338995
9922307	28131	mysql mixing counts from several tables	select  a.id section_id,          ifnull(count(distinct b.id),0) topics_count,          ifnull(count(c.id),0) post_count,          (select post from fposts where id = max(c.id)) last_post from    fsections a left join ftopics b     on      a.id = b.cat_id     left    join fposts c     on      c.topic_id = b.id     where   a.section = "gd" group   by a.id 	0.0241056394015828
9923888	21865	mysql query for getting top instances of a class	select col1, col2, col3 from (   select e1.*, count(*) p from entries e1     left join entries e2       on e1.col2 = e2.col2 and e1.col3 <= e2.col3     group by e1.col2, e1.col3   ) t where p < 3 + | col1  | col2   | col3  | + | item5 | class1 | date2 | | item3 | class1 | date3 | | item7 | class2 | date3 | | item4 | class2 | date4 | | item2 | class3 | date2 | | item6 | class3 | date6 | + 	0.00355285782146769
9923902	6551	sql datetime needs to read 00:00:00.000	select dateadd(d,datediff(d,0,dateadd(s,-1,dateadd(m,datediff(m,0,getdate()),0))),0) 	0.746176002591678
9924132	2110	sql select query count	select actorid, count(*) from roles   group by actorid   having count (*) >= 3 	0.310094338083817
9924373	34969	mysql, get data from two related tables if second table not always have matching rows	select main.id as id, coalesce(timed.total, main.total) as total from main left join timed on main.id = timed.id_main and sysdate() between timed.date_from and timed.date_to 	0
9924508	141	how to parse value to nested select in mysql	select sandwiches.name,   sandwiches.sandwich_id,   sum(order_sandwiches.quantity) as sq,   sum(order_sandwiches.total_price) as sp from sandwiches join order_sandwiches on order_sandwiches.sandwich_code = sandwiches.sandwich_id group by sandwiches.name, sandwiches.sandwich_id order by sandwiches.sandwich_id 	0.173195627170694
9926909	3711	select most recent from non-normalized data in mysql	select   yourtable.* from    yourtable inner join (   select     callername,     max(callerdate) as callerdate   from     yourtable   group by     calledname )   as mostrecent     on  mostrecent.callername = yourtable.callername     and mostrecent.callerdate = yourtable.callerdate where   yourtable.status='notanswered' 	0.000238439624708587
9927803	22767	select in where clause, access to current parent select columns	select   * from   table_1 as t1    inner join table_2 as t2 on     t2.pk = t1.fk  where   (... and ...)   or   (   not exists (select * from table_3 as t3 where t3.t1_id = t1.id)   ) 	0.00238242879017228
9928066	20607	get rank of player from mysql query	select name, score, rank from   (select *, @r:=@r + 1 rank from table_name order by score desc) t1,   (select @r:=0) t2 where name = 'linda' 	0.00159595758583242
9928263	21749	sql server using select	select id, max(cn) as cn, max(sn) as sn, max(dc) as dc from mytable group by id 	0.529182521695719
9928463	13300	how to add dates to mysql result on which there are no records in the database?	select date_range.`date`, count(messages._date) from (     select '2012-02-01' + interval (id - 1) day as `date`     from dummy     where id between 1 and 58     order by id asc ) as date_range left join messages     on date_range.`date` = messages._date group by date_range.`date` asc 	0
9928780	37459	how to set default value in subquery result using mysql	select           p.`id`, p.`name`, p.`class_name`, cpd.`status_team`,     cpd.`home`, cpd.`guest`, cpd.`mvp`, cpd.`oscar`,     cpd.`wam`, cpd.`status`, cpd.`added_date`,     ifnull(rc.`result`, 0) as `result` from `cron_players_data` cpd inner join `players` p     on cpd.`player_id` = p.id left join result_cards rc     on cpd.`result` = rc.id where cpd.`added_date` = '2012-03-29' and cpd.team_id = '15' 	0.0465902812434627
9929825	11762	is there any way do display an associated query as row?	select b.title as blog_title, group_concat(t.name) as tag_name from blog b   join tag_blog tb     on tb.blog_id = b.blog_id   join tags t     on t.tag_id = tb.tag_id group by b.id 	0.00410688504461114
9929921	25687	sql - enhance schema to count unread messages	select count(mtu.*) from messagethreadusers mtu join messagethreads mt on mt.threadid = mtu.threadfk where mtu.lastchecked < mt.lastupdated group by mtu.userfk 	0.568948156538399
9931715	19030	sql: how can i build a string from column values of one row?	select ('' +      case when red = 1 then 'red, ' else '' end     case when blue = 1 then 'blue, ' else '' end     case when green = 1 then 'green, ' else '' end ) as note from mytable 	0
9932217	31096	joining on a group by	select o.ordersid, o.ordertotal, c.customername, c.(other customer data) from  (     select orders.ordersid             , sum(orderdetails.total) as ordertotal             , orders.customersid     from orders     left outer join orderdetails              on orders.ordersid = orderdetails.ordersid      group by orders.ordersid, orders.customersid ) o left join customers c     on o.customersid = c.customersid 	0.0785937950973247
9932547	23888	what day based on datetime	select datename(weekday, movie1) from @data 	0.000456488987105147
9933795	29384	mysql select overlapping count	select     sum(case when day(create_time)=day(now()) then 1 else 0 end) as daycount,     sum(case when weekofyear(create_time)=weekofyear(now()) then 1 else 0 end) as weekcount,     sum(case when month(create_time)=month(now()) then 1 else 0 end) as monthcount,     sum(case when year(create_time)=year(now()) then 1 else 0 end) as yearcount from     conversations where     year(create_time)=year(now()) 	0.0304081814673566
9936056	14565	sql server percentage calculation	select num1, num2,  case num2  when 0 then 100  else abs(100- ( 100 * cast( cast(num1 as decimal(6,3)) / cast(num2 as decimal(10,3) ) as decimal(6,3) ) ) )   end as percentdiff from @numtable 	0.356558163810368
9937264	36234	how to use inner join queries for four tables	select a.name, sum(c.unit), a.unit, sum(c.price)  from items as a      inner join categories as b on a.category=b._id     inner join expenses as c on a.name=c.item_name     inner join notes as d on c.note_id=d._id where      d.date1 between '2012-01-01' and '2012-03-31' and b.name='vegetables' group by     a.name, a.unit 	0.661239777696268
9937855	18415	conversion failed when converting the varchar value '71.8' to data type int	select isnull(cast(nullif(age, 'null') as numeric(10, 2)), 0) from agetable 	0.118709371136026
9937865	29668	see if event occurs (true or false) on each day on specific month	select datefield, bool_field from table where (whatever) group by extract (day from datefield) 	0
9940827	3706	null not in exhaustive list	select * from foo where foobar <> 1 and foobar <> 2 and foobar <> 3 	0.449259465060369
9941192	18386	mysql group by and aggregate, how to get the wanted id at the end?	select group_concat(images.id order by images.id), contributions.id from images join contributions on images.object_id = contributions.id where (object_type = 1 or object_type is null) and place = 1 group by contributions.id having count(*) > 1 	0.000736019761232686
9941583	30137	select one row's id in case of multiple max values in sql	select id from table1 where precedence =(select max(precedence) from table1) 	0
9941895	10429	mysql join where one field is a part of a filed in a other table	select german_subsidiaries.*, customers.*  from german_subsidiaries  inner join customers on customers.name  like concat('%', german_subsidiaries.searchable_name, '%') 	0.000198804167720603
9942590	16691	pivot table sql	select     id,     sum(if(subject = '2gslig', score, 0)) as `2gslig`,     sum(if(subject = '3eciti', score, 0)) as `3eciti` from table_score group by id 	0.343610850717632
9944526	35870	sql - join without duplicating the key	select * from a inner join b using (key) 	0.130062075962305
9949712	10509	return value that doesn't exist in table	select name, 'true' as is_user from users; 	0.00462190325704635
9950136	31439	in oracle, how do i get a page of distinct values from sorted results?	select * from (    select * from (     select id from (       select id, name, row_number() over (partition by id order by name) rn       from table1       inner join table2 on table2.fkid = table1.id       )    ) where rn=1 order by name, id   ) where rownum>=1 and rownum<=4; 	0
9951739	2699	select sup name from same user table same user id t-sql	select sup.name, usr.name from userstbl usr left join userstbl sup on sup.userid = usr.supid order by sup.name 	0
9952365	19602	mysql update query from another table returns 0 rows affected	select * from ps_product, tmp_bmb where tmp_bmb.supplier_reference = ps_product.supplier_reference and ps_product.price!=tmp_bmb.price; 	0.000355439418435487
9953350	6932	grouping or pivoting data in mysql query to make row as column	select     t1.coldist,     t1.attnedanceprcnt as colmale,     t2.attnedanceprcnt as colfemale from     tablename as t1 inner join tablename as t2 on t1.coldist = t2.coldist and t1.colgender != t2.colgender where     t1.colgender = 'male' 	0.0235418608076393
9953370	7413	how to retrieve rows from database by passing month in where condition	select * from table    where month(datecolumn) = 1 	0
9953935	38951	check if group exists mysql query	select groupingid, count(*) as accounts_present from group_members where accountid in (5001,5002,5003) group by groupingid having accounts_present=3 	0.271170747083364
9954088	29471	calculate max, average of some row sql	select name, sum(v) as sum from table group by name order by sum(v) desc 	0
9954129	33799	how to use mysql query using group by to find all the uniq titles used for the group	select   `group`,   group_concat( title ) from `table` group by `group` 	0.0192968298768106
9954197	12275	ms access order by row	select * from yourtablename order by point desc 	0.259239883107806
9956520	34428	if then join else other join	select * from a left join b on a.id = b.id left join c on b.id is null and a.id = c.id 	0.268367189502866
9957155	17973	how to get count and records in single query	select picture_id,    (select count(*) from pictures p1 where p1.user_id = pic.user_id) as num_pics   from picture pic   where pic.user_id = 1   order by picture_id   limit 20; 	0.000357693136196631
9960548	27828	trouble query finding the entry with the highest number	select   movie.*,   rating.stars from   movie inner join   rating     on movie.mid = rating.mid where   rating.stars = (select max(stars) from rating) 	4.61245260757052e-05
9961210	32260	how to select random rows from table with an exact number of row?	select * from table  where some condition order by rand()  limit 6 	0
9962010	246	sql server ce - select random rows	select top(20) * from mytable order by newid() 	0.0929548208822758
9964158	8097	how to write a mysql query to meet below requirements?	select * from tbl_loans where length(loan_number)<>4; 	0.434425304598983
9965494	1542	mysql pattern matching	select * from table where field rlike '[0-9]\\?' 	0.0658768333301073
9966556	38173	union of two queries to get the result in mysql	select table_both.request_id, table_both.tdate, sum(table_both.amount) as amt from (select request_id, cc_amount as amt, date_format(transaction_datetime,'%b %y') as tdate     from table1      union all      select request_id, request_amount, date_format(transaction_date,'%b %y')     from table2) table_both group by table_both.request_id, table_both.tdate  	0.00110669498904516
9967807	7779	mysql sum of item purchases and its 'up'/'down' votes are multiplied by a factor of 22?	select subject, tots, yes, no, fullnane   from (     select item_id, sum(purchaseyesno) as tots, sum(rating=1) as yes, sum(rating=0) as no     from items_purchased     group by item_id   ) i   join items on i.item_id = items.item_id   join accounts on items.account_id=accounts.account_id    where subject like '%album by joe%' or description like '%album by joe%'   order by tots desc, yes desc 	9.84733452160105e-05
9968825	41160	join or sub-query to "detect missing records"?	select cc   from geo_country  where cc not in         ( select cc                              from geo_world         ) ; select cc   from geo_country  where not exists         ( select 1             from geo_world            where cc = geo_country.cc         ) ; select geo_country.cc   from geo_country   left  outer   join geo_world     on geo_world.cc = geo_country.cc  where geo_world.cc is null              ; 	0.466184316628572
9970495	28993	mysql - how to select based on value of another select	select name,        sum(value) as "sum(value)",        sum(value) / totals.total as "% of total" from   table1,        (            select name,                   sum(value) as total            from   table1            group by name        ) as totals where  table1.name = totals.name and    year between 2000 and 2001 group by name; 	0
9972759	26162	how merge the data of 2 table order by date in sqlite database?	select id,name,date from tblcreditdetail union all select id,name,date from tblgiftdetail order by date 	0
9972914	76	sql return default value for join where attributes not exist	select o.value, d.date from day_table o left join other_table d on o.date=d.date and key = "bar" group by d.date; 	0.0693183297936645
9973386	5452	how can i convert a datetime into number of months in t-sql?	select datediff(m, '1970-03-01', getdate()) 	7.24103088730361e-05
9977053	22518	sorting an alphanumeric value mysql	select columnname from tablename order by convert(int, right(columnname, 5)) desc 	0.0685975226379272
9977582	3775	movable type: category relationships	select placement_entry_id from mt_placement where placement_category_id = <your category numeric id>; 	0.0350296769942705
9977586	9080	select all data from multiple tables non-relationally	select col1, col2 from table1 union all select col1, col2 from table2 union all ... select col1, col2 from table6 	0.000388236094981226
9980472	37226	is it possible to query a one-to-many with one query	select * from posts p join posts_tags pt on p.postid = pt.postid join tags on pt.tagid = t.tagid 	0.629805005473422
9980635	33038	mysql: select statement that compares values across multiple tables isn't returning the correct rows	select     queue.*,     coalesce(manager_group_settings.delivery_enabled, user_settings.delivery_enabled) as setting_delivery_enabled from queue inner join campaigns on queue.campaign_id = campaigns.id inner join users on queue.user_id = users.id left outer join managers_groups on managers_groups.managee_group_id = users.group_id left outer join settings as user_settings on user_settings.group_id = users.group_id left outer join settings as manager_group_settings on manager_group_settings.group_id = managers_groups.managee_group_id group by queue.id order by queue.send_at, queue.id 	0.0020807522496543
9980646	17001	query to return text if row is null from oracle db	select nvl(paramone, 0), nvl(trim(paramtwo), 'empty') from tablename where search_param = 'x' 	0.0090775660891272
9981647	25995	query for null records where filestream is enabled	select documentid, filename from docslist where datalength(filedata)>0 	0.741411571898286
9984152	33049	mysql totalvalue when another collum has a set value	select b.borname, sum(bt.value) as 'total' from borrower b join loan l on b.borid = l.borid join bookcopy bc on l.bcid = bc.bcid join booktitle bt on bc.btid = bt.btid group by b.borname 	0.00183526556928977
9985592	28286	how to select product and sort by discount desc (php,mysql)	select *, (full_price - sell_price) * 100 / full_price as discount from product where full_price > 0 order by discount desc 	0.0141553132501406
9985674	26344	sql sum with sub query?	select serverip, sum (viewerlimit/cast (servercount as float)) load from  (   select customerid, count(*) servercount from distribution group by customerid ) a inner join settings    on a.customerid = settings.customerid inner join distribution     on settings.customerid = distribution.customerid group by serverip 	0.782265173335928
9987336	14981	mysql get top 5 results per group on inner join	select      j.tag,     j.post_id,     j.title,     j.cnt from (             select                 case when @b <> i.tag then (select @a := 0) end tmp1,                 case when @b <> i.tag then (select @b := i.tag) end tmp2,                 (select @a := @a + 1) num,                 i.*             from (                         select                             p.title,                             p.post_id,                              p.tag,                              count(*) cnt                         from posts p                         left join tickles t on t.post_id = p.post_id                         group by                              p.post_id, p.tag, p.title                         order by p.tag, count(*) desc             ) i             left join (select @a := 0, @b := '') x on 1=1  ) j where j.num <= 5 	0.000969426485119698
9988254	41075	check if multiple records match a set of values	select t.*  from tablename t join (select 'somevalue1' value1, 'somevalue2' value2 union all       select 'someothervalue1', 'someothervalue2') v   on t.value1 = v.value1 and t.value2 = v.value2 where 2= (select count(distinct concat(v1.value1, v1.value2))  from (select 'somevalue1' value1, 'somevalue2' value2 union all        select 'someothervalue1', 'someothervalue2') v1  join tablename t1    on t1.value1 = v1.value1 and t1.value2 = v1.value2) 	0
9988481	32144	how to get rows of a specific type matching a specific value?	select * from providerdxcptcodes where codetype='cpt' and name like '%flu%'; 	0
9990158	27511	sql bring back highest sum of rows	select * from   (select *,                dense_rank() over (partition by customerid order by baskettotal desc) as rnk         from   (select sum(price) as baskettotal,                        basketid,                        customerid                 from   order a                 group  by basketid,                           customerid                           ) a        ) b        where rnk = 1 	0.000286987687734832
9990163	33123	aggregate list of users and values into a table with list of users and counts of values	select username,         sum(accepted) accepted,        sum(rejected) rejected   from atable  group by username 	0
9990321	12628	oracle: transpose table	select no from (select 1 a, 2 b from dual) dummy unpivot (no for col in (a as 'a', b as 'b')) 	0.11208179842811
9990671	1940	substracting two sum from the same table	select sum(minutes * case type when 'subtract' then -1 else 1 end) as balance from timeaccount where worker = 'john.fisher' and type in ('sum','subtract') 	0
9991043	18418	how can i test if a column exists in a table using an sql statement	select column_name  from information_schema.columns  where table_name='your_table' and column_name='your_column'; 	0.162128039339817
9991072	11701	how to select rows from another table if not enough rows in the first? with sql	select * from (select 'items' table_name, i.*   from items i where name = 'michael' and char_length(description) > 10   union all   select 'moreitems' table_name, m.*   from moreitems m where name = 'michael' and char_length(description) > 10   order by 1,2) v limit 3 	0
9992248	10246	order query results by two key/value pairs, where the fields for the key/value pairs are the same	select p.* from wp_posts p inner join wp_term_relationships r on      (p.id=r.object_id and r.term_taxonomy_id=34) left join wp_postmeta m1 on      (p.id=m1.post_id and m1.meta_key='department_head' and cast(m1.meta_value as char)='private-client') left join wp_postmeta m2 on      (p.id=m2.post_id and m2.meta_key = 'staff_surname' and cast(m2.meta_value as char) != '') where      p.post_type = 'people'    and      (p.post_status = 'publish' or p.post_status = 'private') group by p.id order by m1.meta_value desc, m2.meta_value desc limit 0, 10 	0
9993086	31902	a sql query to find out duplicate records	select column1, count (*) from mytable where column2 = column3 group by column1, column2; 	0.000711555380891459
9993544	10691	sqlite selecting two columns as one with null	select (coalesce(column1,'') || " " || coalesce(column2, '')) as expr1 from your_table; 	0.000355541588039083
9994108	13602	select the opposite row of a where clause in a joined jquery result	select     user_games.game_id,     users.id,     users.email from     users      left join user_games on users.id = user_games.user_id where     users.user_id <> @youruserid and exists     (select         null     from         user_games as myusergames     where         user_games.game_id = myusergames.game_id     and myusergames.user_id = @youruserid) 	0.0105753863962722
9994347	10034	multiple results in my query?	select fp.id,             usr.id as userid,             usr.firstname,            usr.lastname,             c.id as courseid,             c.fullname,             c.idnumber,             fd.name,             fd.timemodified as discussioncreatedon,             fp.created as timeofpost,             fp.modified,             fp.subject,             fp.message       from mdl_forum_posts fp inner join mdl_forum_discussions fd on fp.discussion = fd.id inner join mdl_forum f on f.id = fd.forum inner join mdl_course c on f.course = c.id  inner join mdl_user usr on fp.userid = usr.id      where exists (select 1                       from mdl_user_enrolments ue                inner join mdl_enrol e on ue.enrolid = e.id                      where usr.id = ue.userid                        and e.courseid = f.course) 	0.61510079336405
9994830	2739	check a whole table for a single value	select * from   tbl t where  t::text like '%999999%'; 	0.000338796627924733
9996249	27404	mysql select double constant	select 0.0 + '0' as zero 	0.377259921609134
9998074	29107	sql count function	select count(wage), first_name from employee, job, link  where job.wage = 1000    and job.job_id = link.job_id and employee.employee_id = link.employee_id; group by first_name 	0.667558278759905
9999289	12078	order by on a group sum criteria	select    l.* from table l inner join (   select category, sum(price) as total from table group by category ) r on l.category = r.category order by r.total, <some_other_column> 	0.0330969002017552
10000643	24671	mysql hierarchical grouping sort	select * from `data` order by coalesce(`parent`, `id`), `parent`, `id` 	0.295086790614873
10000842	7358	to sort date(which is in the form 'january 2001') starting from january to december	select * from (     select distinct          cast(             datename( month , dateadd( month , (convert(int,datefield1)) - 1 , '2000-01-01' ) )              +' '+ datename( year , dateadd( year , (convert(int,datefield2)), '2000-01-01' ) )          as datetime) as   [date]      from dbo.table1      where datename( year , dateadd( year , (convert(int,datefield2)), '2000-01-01' ) )= 2009 ) as mydate order by date 	0.000698539484655233
10002496	12269	using the results from 2 tables to get info from a 3rd one	select person.name from      english      join harvard on havard.person_id = english.person_id     join persons on persons.person_id = harvard.person_id 	0
10006321	13470	sql where condition for int but column type is varchar	select * from buttons where      convert(integer, button_number) >= 10 and convert(integer, button_number) <= 50 	0.199956994354184
10006454	7259	compound sql select	select     * from     auth_user where     auth_user.is_active=0     and not exists         (             select                 null             from                 userprofile_userprofile              where                 userprofile_userprofile.user_id=auth_user.id         ) 	0.471473744781802
10006956	19874	join two queries into one in order to join the results	select tbl_costprevisions.month, sum(tbl_costprevisions.value) as 'cost' , sum(tbl_incomeprevisions.value) as 'income' from tbl_costprevisions inner join tbl_incomeprevisions on tbl_costprevisions.month = tbl_incomeprevisions.month where tbl_costprevisions.year = @year and tbl_incomeprevisions.year = @year group by tbl_costprevisions.month 	0.00472963514824663
10009069	31787	does mysql where conditions regard brackets the same as php?	select * from translation where (language='en' and translation_label='lbl_submit') or (language='en' and translation_label='lbl_submit_btn') 	0.65266749730008
10009329	15223	get the associated name of two database columns of the same type	select dep.name as departure_airport, arr.name as arrival_airport  from flights f     join airports dep on f.departure_airport_id = dep.id      join airports arr on f.arrival_airport_id = arr.id 	0
10009899	416	match on two subqueries with count	select * from (     select count(1) as items,            [basket id],            [customer id]     from   order_lookup     group  by [basket id],               [customer id] ) as query1 join (     select count(1) as items,                      a.[basket id],                      a.[customer id]               from   c1059204.order_lookup a               where  a.[product id] not in (select [product id]                                             from   orders                                             where  [customer_id] = a.[customer id]                                                    and orderdate = dateadd(day, datediff(day, 0, getutcdate()), -2)                                                    and orderstatus in ('posted' ))               group  by a.[basket id],                         a.[customer id]  ) as query2 on query1.items = query2.items 	0.0623454323120282
10009951	22118	how to fetch data in below format?	select     substring_index(         group_concat(             `id`             order by                 `date` asc separator ','         ),         ',',         1     ) as `id` from     `table` group by     date(`date`) 	0.0079927434523831
10010271	3051	mysql, search columns that have two keywords in boolean mode	select * from bookmark where match title against ('"iphone review"' in boolean mode) 	0.00830023995642429
10010964	21048	travel distance table design	select distance from distance_table where from_location = "a" and to_location = "c" 	0.222150016630068
10011269	29439	how can i find tables, having a defined column?	select      * from    syscat.columns where  colname = 'person_name' 	0.00620075283297847
10011443	18380	to print the list of user_id from the string list	select u.user_id from user u where u.user_id in ( '2, 3, 4, 5, 6, 7, 22, 33, 44, 55, 66, 77, 13, 23, 43, 53, 63, 73' ) 	0
10011902	24642	join/merge two tables, improvise/make up "missing" entries	select y.bar_id, x.baz_id, x.foo_id, x.some_field from (     select a.foo_id, a.some_field, b.baz_id     from tbl_foo as a, tbl_baz as b ) as x     left join tbl_bar as y on x.foo_id = y.foo_id         and x.baz_id = y.baz_id order by x.baz_id, x.foo_id 	0.00151154314336638
10012890	40463	sql - counts not returning zeros	select mem.member_id, mem.screen_name, mem.firstname, mem.lastname, mem.country_code,   mem.joined, rep.rep as reputation, ifnull(com.cnt,0) as comments from members as mem  left outer join (      select member_id, sum(awarded_what) as rep      from members_reputation      group by member_id) rep      on mem.member_id = rep.member_id  left outer join (      select member_id, count(comment_id) as cnt      from blog_comments      group by comment_id) com      on mem.member_id = com.member_id  group by mem.member_id  order by mem.joined desc 	0.281739407663794
10012901	9215	sql server sort column based on the same column itself	select display_order as currentdisplayorder,      row_number() over (order by display_order) as newdisplayorder from yourtable order by display_order 	0
10013841	29982	mysql interval - bring in users that have not logged in for 6 months	select * from wp_users where last_login < date_sub( now(), interval 6 month ) 	5.62870759450737e-05
10014692	22761	how to convert result set row into columnn	select     if(user_id=57, 57, '') as user57,     if(user_id=57, 83, '') as user83,     if(user_id=57, 71, '') as user71,     if(user_id=57, 40, '') as user40,     if(user_id=57, 96, '') as user96,     if(user_id=57, 58, '') as user58,     if(user_id=57, 99, '') as user99,     if(user_id=57, 27, '') as user27,     form tablename 	0.00178899037396199
10014995	37811	select fields with join where column exists in distinct subquery with less fields	select top (1) with ties        classid       ,code       ,section       ,course       ,students       ,classstart       ,teacherdescrip       ,adteacherid       ,email       ,term       ,campus   from classscedule   join staff on staff.staffid = classscedule.adteacherid   where classstart between '2012-03-01' and '2012-03-30'   and teacherdescrip is not null    order by row_number() over (     partition by code, teacherdescrip, term     order by classid desc   ) 	0.109701951795013
10015645	5734	how can you figure out a discrepancy between two queries returning different results	select x.* from ( select  tableb.c_id, count(*) as c from    tableb left join tablec     on tableb.c_id = tablec.c_id where tablec.c_id != tablec.c_id_update group by tableb.c_id ) x left join tablea a on a.c_id = x.c_id where a.c_id is null 	0.0456631498754834
10015945	29249	how to serialize (to comma separated list) sql rows	select id, name, properties = stuff((     select ',' + propertyname from dbo.properties     where id = x.id     for xml path(''), type).value('.[1]', 'nvarchar(max)'), 1, 1, '') from dbo.viewname as x group by id, name; 	0.000131066010474991
10015973	37229	total user count monthwise	select tots.*, @var := @var + tots.`count` from (     select         year(registered) as `year`,         month(registered) as `month`,         count(*) as `count`     from user     group by `year`, `month` ) as tots, (select @var := 0) as inc 	0.00139680122283113
10019438	26675	what is the size of a image field content in sql server?	select datalength(imagecol) from  table 	0.0183259743455889
10019819	18216	most effective way to get value if select count(*) = 1 with grouping	select case when min(id) = max(id) then min(id) else null end as id,        value, count(*) as [count] from   yourtable group by value 	7.26160507991149e-05
10020540	40288	checking for maximum length of consecutive days which satisfy specific condition	select * from (     select t.*, if(@prev + interval 1 day = t.d, @c := @c + 1, @c := 1) as streak, @prev := t.d     from (         select date(timestamp) as d, count(*) as n         from beverages_log         where users_id = 1         and beverages_id = 1         group by date(timestamp)         having count(*) >= 5     ) as t     inner join (select @prev := null, @c := 1) as vars ) as t order by streak desc limit 1; 	0
10020891	22209	mysql : returning empty field instead of no row	select tbl_cms_categories_en.id as id,     en.name as en_name,     if(es.name is null, "no translation found", es.name) as es_name  from   tbl_cms_categories_en as en left join tbl_cms_categories_es as es     on tbl_cms_categories_en.id = tbl_cms_categories_es.id 	0.00137499574453971
10021571	34025	writing a select query for the following table	select cars from (select cars, count(*) as nbr from thetable group by cars)  where nbr > 1; 	0.292747430238214
10021727	15799	how to list the number of automobile crashes associated with each weather type in the descending order?	select weather_condition, count(weather_condition) as count  from nyccrash group by weather_condition order by weather_condition desc ; 	0
10021775	10395	truncating a field value in a sql select	select substring(mytextfield, 1, 30) from table 	0.00787485214417737
10022027	19689	mysql sum the total up and down votes by all users for the items bought by a single user	select item_id, sum(purchaseyesno) tots, sum(rating = 1) yes, sum(rating = 0) no from items_purchased where item_id in (     select item_id from items_purchased     where purchaser_account_id = 12373 ) group by item_id 	0
10022669	18363	mysql get records greater than 10 hours	select ... from ... where yourtimestampfield <= (now() - interval 10.5 hour) 	0
10024126	6804	mysql select query with two tables - never giving result	select      pre.`id` ,      pre.`deal_id` ,      pre.`coupon_code` ,      pre.`csv` from `precoupon` as pre left outer join `customerorders` as oc     on oc.`uniqueid` = pre.`coupon_code` where oc.uniuqueid is null 	0.532824059634595
10025934	19617	how to pivot text columns in sql server?	select severity_id, pt.people, assets, environment, reputation from  (     select * from comm.consequence ) as temp pivot (     max([description])      for [type] in([people], [assets], [environment], [reputation]) ) as pt 	0.162989109597789
10027077	36030	how to calculate weekly permonth in aqua data studio	select weekinthemonth from dbo.calendar where basedate = @somedate 	0.0766636677695037
10027235	39236	count number of occurences of a character in sql string value?	select len('you.late.you@asdf.com') - len(replace('you.late.you@asdf.com', '.', '')) 	0
10028951	19767	order by a field containing numbers and letters	select id, cast('0' + id as integer) a  from "my.db"  order by a, id 	0.00153010734008535
10029647	27534	joining two columns on a table in sql	select distinct day, time1 from mytab union select distinct day, time2 from mytab 	0.000599434573409141
10029733	34946	mysql find tuples with the largest value in a specif row, where there are multiple tuples that meet the creiteria	select model from printer where price = (select max(price) from printers) 	0
10030336	8664	sql to list services by the number of ratings the service owners have	select   s.*, r.rated_id, r.pushed_count from   service s join user u on   u.user_id = s.user_id left join (     select       rated_id, count(if(pushed = 1, 1, null)) pushed_count     from       ratings     group by       rated_id   ) r   on r.rated_id = u.user_id order by   r.pushed_count desc 	0.000348715413248001
10032768	29509	fetching from the results of table functions	select mytable.column1, mytable.column3, etc from table(func(params)) mytable order by somecolumn; 	0.00410733646817995
10033020	39168	using inner join twice in the same query	select t.*   from filter as f0  inner join filter_thread as ft0     on ft0.filter_id = f0.filter_id  inner join thread as t     on ft0.thread_id = t.thread_id  where f0.tag like '%filter1%'     or f0.tag like '%filter2% 	0.315172059150133
10033805	27705	multiply value in n columns by n columns in a second table?	select     i.id ,   i.itmqty1 ,   i.itmqty1 * c.itmcost1 as itmttl1 ,   i.itmqty2 ,   i.itmqty2 * c.itmcost2 as itmttl2 ,   i.itmqty3 ,   i.itmqty3 * c.itmcost3 as itmttl3 from items i join costs c on 1=1 	0
10036402	5764	how to exclude weekends data in a whole month?	select * from @t  where datediff(d, 0, dates)%7 < 5 	9.41118667130877e-05
10036546	5191	how to check if a table exists and return a value (0/1) if it doesn't without using a stored procedure?	select cast(count(*) as bit)   from information_schema.tables  where table_schema = 'dbo'     and table_name = 'orderupdates'     and table_type = 'base table' 	0.00451709899346503
10036913	33442	selecting a random row that hasnt been selected much before?	select * from item order by times_seen + rand()*100 limit 1; 	0.000179525583000831
10037570	33525	ranking rows using sql server rank function without skipping a rank number	select *, dense_rank() over (order by apples) as therank from #test 	0.0241038630703213
10038180	39056	showing sum in last row of table using mysql	select col1, col2 from tablename union select 'sum' as col1, sum(col2) col2 from tablename 	0
10039827	15979	want to add if conditions in query	select sum(case     when $p{month} in ('jan','feb','march') then t.quarter1     when $p{month} in ('apr','may','june') then t.quarter2     when $p{month} in ('july','aug','sept') then t.quarter3     when $p{month} in ('oct','nov','dec') then t.quarter4     else 0 end) as quarter,     s.name as sname, f.name as fname, m.name as pname   from ... 	0.140732988181968
10041844	17334	join 2 mysql queries, where the second query depends on the output of the first	select tc.id,tc.name,tci.images from temp_card tc     inner join temp_card_images tci on tc.id=tci.temp_card_id where sex='$sex'    and city='$city'  group by tc.id order by name asc 	0
10041910	11707	catching sockpuppets	select * from log l1 inner join log l2     on l1.ip_address = l2.ip_address     and l1.user_id < l2.user_id     and l1.login _time between (l2.login_time - interval 5 minute) and (l2.login_time + interval 5 minute) 	0.776788482600668
10044617	26117	mysql: selecting row's id which has minimum in some field	select `id` from `table` order by score asc limit 1 	0
10046239	24467	counting the number min records within groups	select      _item_detail.job_id,      _item_group.group_id,      _scan.company_id,      date(scan_date_time) as scan_date,      count(1) from     _scan s1     inner join _item_detail          on _item_detail.company_id = s1.company_id          and _item_detail.serial_number = s1.serial_number         and _item_detail.job_id = '0326fcm'     inner join _item_group          on _item_group.group_id = _item_detail.group_id         and _item_group.group_id = 13 where      s1.company_id = '152345'     and s1.scan_date_time = (         select min(s2.scan_date_time)         from _scan s2         where              s2.company_id = s1.company_id             and s2.serial_number = s1.serial_number     ) group by      _item_detail.job_id,      _item_group.group_id,      s1.company_id 	0
10046332	6243	trying to create fields based on a case statement	select   sum(case when category = 'a' then payment end) as a_payments,   sum(case when category = 'b' then payment end) as b_payments,   sum(case when category = 'c' then payment end) as c_payments from r_invoicetable 	0.0370438224993274
10046497	35101	select count based on another row in the same table	select count(distinct email) from entries 	0
10046741	40221	searching full name or first or last name in mysql database with first and last name in separate columns	select *  from table where concat( namefirst,  ' ', namelast ) like  '%joe%' 	0
10048233	7074	mysql select as alias from multiple tables	select  (select count(*) from tablea) as ac, (select sum(views) from tablea) as vc, (select count(*) from tableb) as mc 	0.0493244535755325
10048240	30482	sql select statement max id	select group_id, max(id) as max_id from apps where type = 1 group by group_id 	0.0546685524877087
10052483	17198	concatenating rows into single column when taking value from two different tables	select a.[userid], dbo.myagg(b.[subjectname]) as [subjectname]  from table1 as a  left outer join table2 as b on a.[fksubjectid] = b.[pksubjectid]  group by a.[userid] 	0
10054340	14009	mysql left join with one ordered result from another table	select products.product_title, products.product_key, news.news_date, news.news_text from products left join news on products.product_key= news.pid where news.news_date = (select max(news.news_date) from news where news.pid = products.product_key) order by products.product_key 	0.000648138022593426
10056063	35847	how to return source table name when using a union?	select   'table1' as tablename,   other columns from table1 union all select   'table2' as tablename,   other columns from table2 union all … 	0.0167425571518662
10058608	19033	mysql arithmetic	select c.team1, sum(c.team1score) as gf, sum(c.team2score) as ga, (sum(c.team1score)-sum(c.team2score)) as gd  from calendario c  group by c.team1 	0.778268072012311
10059220	34734	select rows as columns in mysql?	select _date,     sum(case when _user_id = 1 then cnt else 0 end) as user1,     sum(case when _user_id = 2 then cnt else 0 end) as user2,     sum(case when _user_id = 3 then cnt else 0 end) as user3,     ... from views group by _date 	0.00319513241279476
10061531	12601	sqlite sorted rows within group by	select u.*, l.*  from user as u  inner join log as l on l.userid=u.id  where l.date = (select max(date) from log where l.userid=u.id order by l_id desc limit 1) 2 mike 4 open  '5 dec' 1 jhon 2 close '3 dec' 	0.00337060607943447
10061807	25441	add default value for unknown	select v.name, u._id as userid, vu._id as vaccineid from user u left outer join vacc_user vu on u._id = vu.userid left outer join vaccine v on ((v._id = vu.vaccineid) or (v._id is null)) where u._id = 4; 	0.0417919767712001
10063041	23620	mysql mutliple joins and count	select s.subject, s2.subject, count(q.id)   from subjects s   left join subjects s2 on s.parent_id  = s2.id   left join questions q on q.subject_id = s.id   group by s.subject_id, s2.subject_id, q.subject_id 	0.464463570989196
10063575	16263	how would i compare two fields in an sql select statement to then select other fields based on this result?	select * from mytable where column1<=column2 	0
10063760	3085	making mysql query to tables based on the values from another table	select * from vouchers   left join  details on vouchers.voucher_no = details.voucher_no  left join   accounts on accounts.code = vouchers.account_code  where voucher_type='1' and t_code in (select * from code_table)  union all select * from vouchers  left join details on vouchers.voucher_no = details.voucher_no  left join   accounts on accounts.code = details.t_code   where voucher_type='0' and account_code in (select * from code_table) 	0
10064194	12554	counting the number of child records in a one-to-many relationship with sql only	select file_id, count(*)   from data  group by file_id 	0
10064294	37571	how to select multiple names in a single query	select * from users where uname in ("ali", "veli") 	0.00209859240572357
10065310	10711	need to get most recent date of category change (post addtion, modification) for 10000 categories	select     categoriestoposts.category,     max(posts.lastmodified) as lastmodified from categoriestoposts left join posts on posts.id = categoriestoposts.post group by categoriestoposts.category 	0
10065798	5871	mysql php count lines in two tables with one query	select c.club_id, count(*) from user u, club c where u.user_id = 12        and c.club_id in (5,8,19)       and u.club_id = c.club_id group by c.club_id 	0.00116270100839706
10066166	25793	how to use distinct when i have multiple column in sql server	select carbrand , caryear ,carmodel  from cars  group by carbrand , caryear ,carmodel; 	0.0917863066843354
10067070	5642	mysql multiple fields from subquery	select    (select date from forums where topic_id=f.id or id=f.id order by id desc limit 1) as last_reply,   (select author from forums where topic_id=f.id or id=f.id order by id desc limit 1) as last_author,   f.*, p.id as pid, p.name from forums f        inner join players p on p.id = f.author    where f.topic_id=0 order by f.id desc 	0.0522811118268489
10069066	32483	sql return blank string when there's a non-numeric value involved in function?	select      case          when              max(case when gd.grade = 'no grade' or gd.grade = ' ' then 1 else 0 end) = 1 then ' '         else              round(sum((g.unitsacademic*gd.grade))/sum(g.unitsacademic),3)       end as 'gwa'   from gradesheet g   inner join gradesheetdetail as gd         on gd.gradesheetid = g.gradesheetid 	0.0248498521749874
10069398	34195	can you assign a variable in a select, and then using it later in the same select?	select     c.current_bid,     c.current_bid * 1.05 as min_bid from     (         select max(b.amount) as current_bid from ...     ) c 	0.000191323903950281
10069599	31411	use of not in command with find in set	select user_id from user where user_id not  in ( 1,2,3,4,7,8,21,42,12 ); 	0.324131825990789
10069631	26581	select amount for given year	select       country as "recipient",       sum(if(project_year = 1991, usd_amount, 0)) as "1991",      sum(if(project_year = 1992, usd_amount, 0)) as "1992",      sum(if(project_year = 1993, usd_amount, 0)) as "1993", from tb1 group by country order by country 	0.000140551464064575
10070697	29813	select data from 2 tables in mysql, join it	select users.* , comments.* from users join comments on comments.userid = users.userid  where comments.imageid = $imageid 	0.00621730554280873
10071867	33312	find search term in multiple columns	select * from posts where    `title` like '%android%' or `content` like '%android%' 	0.0143781094734333
10071891	12234	nested select in mysql	select * from mytable where id in (select id from data where dataid = 1); 	0.657135461174583
10074240	16667	combining data from two queries in sql server 2005	select  sq.question_id, sq.question_text, qo.question_option_id, qo.option_text, g.total from    dbo.survey_question sq left outer join dbo.question_option qo      on sq.question_id = qo.question_id left join (select ra.question_id, ra.question_option_id, count(*) as total  from dbo.form_response_answers ra  group by ra.question_option_id, ra.question_id ) g     on g.question_id = sq.question_id and g.question_option_id = qo.question_option_id order by sq.question_id 	0.0178303662688035
10074667	17907	sql average result	select min(average_of_availability) from ( select avg(dailynodeavailability.availability) as average_of_availability from nodes  inner join dailynodeavailability      on (nodes.nodeid = dailynodeavailability.nodeid) where  ( datetime > (getdate()-7) )  and   (   (   (nodes.caption like '%server1%') or    (nodes.caption like '%server2%') or    (nodes.caption like '%server3%')    ) ) group by nodes.caption ) avgavailability 	0.0222805055083749
10075208	24355	mysql join query retrieving profile images of users with ids from other table	select      a.profile_image as attacker_profile_image,     d.profile_image as defender_profile_image from      `battles` b left join      `users` a  on      b.`attacker_id` = a.`id`  left join      `users` d  on      b.`defender_id` = d.`id` 	0
10075476	7901	displaying multiple columns mysql	select     paper.title,     paper.username,     paper.abstract,     paper.filelocation from `paper` inner join `topic` on `paper`.`topic_id` = `topic`.`topic_id` where topic_name = 'artificial intelligence' 	0.0176440214418418
10077003	26043	how to sort records with limit clause	select  * from      (          select id,name,entry_date from users order by entry_date desc limit 0,5     ) as a order by a.entry_date asc 	0.0693715614947483
10078107	38547	count of non null values in a row	select    (case when first is null then 1 else 0 end) +    (case when id is null then 1 else 0 end) +    (case when last is null then 1 else 0 end) +    (case when telephone is null then 1 else 0 end)  from client  where id ="1"; 	0.00039599299510459
10079190	5117	mysql datetime comparison with previous row	select date2      , dd       , date_format(dd, '%b %e, %y') as final_date      , date1_duplicate      , date1_was_null from ( select date2        , coalesce( (date1 = @d or date1 = @prev), false)            as date1_duplicate        , (date1 is null)               as date1_was_null        , @d := case when (date1 = @d or date1 = @prev)                   then date2                   else coalesce(date1, date2)                 end as dd        , @prev := date1 as pre   from tablex as t     cross join       ( select @d := date('1000-01-01')              , @prev := @d        ) as dummy   order by date2 asc  ) as tmp order by date2 desc ; 	0.0117974523232002
10079218	5346	seaching for duplicate customers with like	select distinct randomtest.customer_id, concat(randomtest.first_name,' ',randomtest.last_name) as name  from randomtest     inner join randomtest dup on randomtest.last_name = dup.last_name where ((dup.first_name like concat('%', randomtest.first_name, '%')              or (randomtest.first_name like concat('%', dup.first_name, '%'))          )     and dup.customer_id <> randomtest.customer_id ) order by name 	0.0693004021626846
10079879	23911	find polygon overlaps	select     t.id     , o.id     , t.shape.stintersection(o.shape) intersection from @table t inner join @table o     on t.shape.stintersects(t.shape) = 1     and t.id > o.id 	0.115583261827829
10080943	2537	creating an alias after row's computations?	select *, alias1 + alias2 + alias3 as alias_sum from  (     select          case when aaa ... then ... else end as alias1,         case when bbb ... then ... else end as alias2,         case when ccc ... then ... else end as alias3     from... ) as casequeries 	0.657286357407461
10081287	39353	mysql - how can i get the first result from a subquery?	select pa.albumid, pa.title, p.src from album pa left join photo p    on p.photoid = (select min(photoid) from photo where albumid = pa.albumid) where pa.userid = 1 	0.000319947718692503
10083757	2196	postgresql: selecting distinct values on single column while sorting on another	select (case when parent_id != -1 then parent_id else id end) as mid, max(create_dte ) from messages  group by case when parent_id != -1 then parent_id else id end order by max(create_dte) desc; 	0
10083836	28661	sql select group by and string concat	select p1.id,        ( select name + ' and '             from yourtable  p2           where p2.id = p1.id           order by name             for xml path('') ) as name,         sum(amount)       from yourtable p1       group by id ; 	0.263251617617859
10084400	18466	how to count the number of columns in a table using sql?	select count(*)  from user_tab_columns where table_name='mytable'  	4.76269447519212e-05
10085171	31157	sub groups within group by query in mysql	select case  when a = 0 then '0' when a = 1 then '1' when a >= 2 then '2' end as anothernamethana, sum(b) as `sum` from yourtable group by anothernamethana 	0.369233442177773
10085209	15207	combine these two mysql queries	select users.*,         sum(overtime_list.shift_length) as overtime_total,         (select group_concat(roles.short_name) from users_roles           inner join roles on user_roles.role_id = roles.role_id          where users.user_id = users_roles.user_id) as roles     from availability_list     inner join users         on users.user_id = availability_list.user_id     inner join stations         on users.station_id = stations.station_id     inner join overtime_list         on overtime_list.user_id = users.user_id         and overtime_list.date >= '$totalovertimedays'     where availability_list.date = '$date'     and availability_list.type = '$type'     group by users.user_id     order by overtime_total asc 	0.0443845496388131
10086062	40504	sql query - multiple joins on same field	select a.issueid, b.user_label, c.user_label from issues a inner join users b on a.authorid_fk = b.userid inner join users c on a.assignedid_fk = c.userid 	0.0465317552765826
10087072	1397	merge and replace table id with string of two table sql	select b.id,         (select a.text from tablea a where a.id = b.title) as title,         (select a.text from tablea a where a.id = b.teme) as teme,         year,         (select a.text from tablea a where a.id = b.ed) as ed,         (select a.text from tablea a where a.id = b.cont) as cont from tableb b where b.id = 8 	6.00024586705517e-05
10087232	40062	sql - using a subselect	select case    when child.blocked > coalesce(parent.blocked,0)   then child.blocked    else parent.blocked  end as blocked from custtable child  left join custtable parent on child.invoiceacc = parent.accountnum where child.accountnum = '1-1' 	0.758293386027289
10087287	109	sql: how do you look for missing ids?	select t1.id from your_list t1 left join your_table t2   on t1.id = t2.id where t2.id is null 	0.0234950283528023
10087532	11471	mysql query to find highest and lowest among 2 tables	select max(point) as highest, min(point) as lowest from   (select pointa as point from tablea    union    select pointb as point from tableb) t 	0
10088184	40136	how to combine sum values of different tables? (good performance?)	select sum(t1.views) data_1_views, sum(t1.clicks) data_1_clicks from data_1 t1  select sum(t2.views) data_43_views, sum(t2.clicks) data_43_clicks from data_43 t2; 	0.00804762810479088
10089728	27787	display only unique entries in mysql	select   messages.*,   users_from.screen_name as from_screen_name,   users_to.screen_name as to_screen_name from   messages     join users as users_from on messages.from = users_from.id     join users as users_to on messages.to = users_to.id where   (messages.to = $id and messages.from = $friend)   or ( messages.to = $friend and messages.from = $id) 	0
10090217	6177	how to select record whose matching percentage is higher than other using like operator in sql server?	select top 2 firstname, lastname, countryname, statename  from employee where     statename like '%gujarat%' and countryname like '%india%' order by     dbo.edit_distance(statename, 'gujarat') + dbo.edit_distance(countryname, 'india') desc 	0.000478116188475744
10090699	13761	how can i get a subset of rows from oracle database?	select   a, b, c, d from   yourtable group by   a, b, c, d select   distinct   a, b, c, d from   yourtable 	0
10091181	2306	how to use contains keyword in sqlite database	select fieldname from tablename where fieldname like ('%$myvar%'); 	0.425297419138611
10093301	10861	mysql if function	select     if(assignedto = 0,'none', concat(`payments`.`assignedto`," - ",`people2`.`fname`," ",`people2`.`lname`)) as result,     concat(`payments`.`personid`," - ",`people`.`fname`," ",`people`.`lname`) as `personname`     from `mb_payments` as `payments`     left join `mb_people` as `people` on `people`.`personid` = `payments`.`personid`     left join `mb_people` as `people2` on `people2`.`personid` = `payments`.`assignedto` 	0.683066166054165
10093346	35137	how to query sql-database how many times an item has been purchased between two dates?	select itemcode, count(itemcode) 'times purchased', sum(quantity) 'amount purchased'   from `temp_trans`  where `trans_date` >= '2012-01-08' and `trans_date` <= '2012-03-23'  group by itemcode 	0
10093912	2108	select distinct top 5 in sql server	select top 5 tblproduct.productid,  tblproduct.productname,  tblcomment.dateadded from   tblcomment  join   tblproduct on tblproduct.productid = tblcomment.productid join   (select productid, max(id) as maxid from tblcomment group by productid) t on tblcomment.id = t.maxid  order by tblcomment.dateadded desc 	0.0178669439163132
10094130	36097	how to write the t-sql code for a query	select a.firstname, a.lastname, b.bookname from books b outer apply  (     select top 1 t.bookid, t.firstname, t.lastname      from authors t     where t.bookid = b.bookid ) a  where b.bookclassification = 2 	0.697707355974896
10095386	32682	how to get data of maximum date in php	select seeker.seeker_nic, donor.donor_nic, donor.area, status.requestfulfilled_by, status.request_fulfilled_date from seeker join (   select seeker_nic, max(request_fulfilled_date) as last_date   from status   group by seeker_nic ) x on x.seeker_nic = seeker.seeker_nic join status    on x.seeker_nic = status.seeker_nic   and x.last_date = status.request_fulfilled_date join donor    on status.donor_nic = donor.donor_nic where seeker.username = '$uname' 	0
10096209	37900	sql cast from int to decimal	select cast(cast(total as float) / totalanswers * 100 as decimal(8, 2)) 	0.0776739941369873
10096267	21801	sqlite query sorting	select date(starttime, 'unixepoch') as startdate,        time(starttime, 'unixepoch') as starthour,        time(endtime,   'unixepoch') as endhour,        all_day_flag   from table   order by     startdate, all_day_flag, starthour; 	0.579841627081858
10096969	19531	how do i perform a simple string mapping as part of a t-sql select?	select    case column1      when 'a' then 'b'      when 'f' then 'z'    end  from tbl 	0.575315379015166
10099130	33466	case statement that adds column values	select  id,     cast( (case when race1 is not null then 1 else 0 end)    +(case when race2 is not null then 1 else 0 end)    +(case when race3 is not null then 1 else 0 end) as char) + '-3' as general_turnout from test4 	0.210040722579543
10099389	32291	sql query to return display by month	select   name,    case when month(createdate) = '1' then amount end as jan,   case when month(createdate) = '2' then amount end as feb from   table1 group by   name ; 	0.000495110718973096
10100709	18604	sql query from www.db-class.com	select distinct m1.director, m1.title, r1.stars from movie m1 join rating r1 on m1.mid = r1.mid left join (     select m2.director, r2.stars from movie m2     join rating r2 on m2.mid = r2.mid ) s on m1.director = s.director and r1.stars < s.stars where s.stars is null and m1.director is not null 	0.268130854977644
10101072	31362	search database if column name/field name exists in a table in mysql	select * from   information_schema.columns where  table_schema = 'my_database'        and column_name in ( 'my_column_name' ); 	0.00938321009280146
10102435	8014	mysql select query to prepopulate dropdown fields	select      cp.cp_description, cp.cp_discountprice, cp.cp_discountpercent,      p.pd_id, p.pd_name,      cat.cat_id, cat.cat_name from tbl_coupon cp  inner join tbl_product p on p.pd_id = cp.pd_id inner join tbl_category cat on p.cat_id = cat.cat_id  where cp_id = $cpid 	0.303428920900207
10103327	3998	how to use sql union	select t2.domain from table2 t2 left join table1 t1     on t2.domain = t1.domain where t1.domain is null 	0.659806228502445
10103511	34187	how to remove non-alphanumeric characters in a column?	select distinct    replace(replace(replace(replace(name,      ' ', ''),     '|', ''),     '?', ''),     '-', '') from your_table 	0.0145815505953151
10103623	36060	grouping per day	select message, day(time) daytime, personid, count(*) from errorlog where time between to_date(todays date - 10 days) and to_date(todays date) and substr(message,0,3) = 'err' group by daytime, personid, message order by 4 	0.000407170995601945
10103849	38465	merge the common rows in sql	select case when code = lag(code) over(order by code, manager, employee)          then null          else code        end as code,        case when manager = lag(manager) over(order by code, manager, employee)          then null          else manager        end as manager,        employee from yourtable y order by y.code, y.manager, y.employee 	0.000414138773308137
10104146	84	how to get the "next row" and "previous row" in a resultset, without selecting the entire resultset?	select * from table where `id` > 4 order by `id` asc limit 1 select * from table where `id` < 4 order by `id` desc limit 1 	0
10105525	18972	how can i show unique date and count() records mysql?	select date(`timestamp`) as `date`, count(*) from t1 where f_inserted = 1 group by date(`timestamp`) 	8.48453389085783e-05
10106274	12564	get ids based corresponding value pairs uniquely	select   min(id) from (   select      id,      group_concat(value order by value) as values   from <table>   group by id ) r group by values 	0
10106541	5670	how to calculate a total of values from other tables in a column of the select statement	select co.id,         count(do.denid) as `total denominations`,         sum(d.amount) as `total amount` from custorder co inner join denominationorder do on co.id = do.orderid inner join denomination d on do.denid = d.id group by co.id 	0
10106701	32832	how to replace one field of table with another?	select t1.name, t2.data  from table1 t1 inner join table2 t2     on t1.status = t2.id order by t1.name 	0.000133019904642843
10107740	530	date part function in sql server	select dateadd(m, datediff(m, 0, getdate()), 0) 	0.465254437429246
10107888	19856	kill sql server transactions after some minutes	select datediff(second, last_batch, getdate()) as secs_running, * from sys.sysprocesses where hostname != ''     and open_tran = 1 	0.171993466126729
10108335	13932	sql server xml to table logic	select i.n.value('.', 'int') as id  from @xml.nodes('test/report') as r(n)   cross apply r.n.nodes('body/table1/row/id') as i(n) where r.n.exist('title[@reportid = sql:variable("@reportid")]') = 1 	0.513218878871534
10108429	657	how do a make a query to count which string appears the most in a certain column?	select top 1 column, count(*) from table group by column order by count(*) desc 	0
10110069	24474	counting rows from second table	select g.name, count(u.id) from groups g left join users u on g.id = u.group group by g.id, g.name 	0
10110341	624	group records by time	select datetime((strftime('%s', time) / 900) * 900, 'unixepoch') interval,        count(*) cnt from t group by interval order by interval 	0.0117274515825348
10110786	2620	what is the optimal string format for converting to an array?	select * from `yourtable` group_concat(     concat('{"id":"',id,'","name":"',name,'"}')      separator ',') 	0.609631244698017
10111179	21015	select bottom results in mysql	select * from  ( select * from messages   where ( senderid = "1" or receiverid = "1" )    and ( senderid = "3" or receiverid = "3" ) order by addeddate desc limit 10 ) tb  order by addeddate asc 	0.040200017320139
10111669	29371	how to get max int but exclude specific int?	select max(score) , empid from table where score < (select max(score) from table ) group by empid 	0.000200174878076784
10115899	22956	sql query join same column twice	select c.id, c.name, ls.localename source, lt.localename target from content c join locale ls on c.source = ls.localecode join locale lt on c.target = lt.localecode 	0.059793838654968
10115993	18107	order by number of duplicates from several tables mysql	select name from  (select name from a    union all   select name from b   union all  select name from c) t  group by name order by count(name) desc 	0.000167791194434339
10116036	5682	using top (1) in sql server for getting the most number of occurrences of a string in a column	select top 1 name    from names_table   group by name  order by count(1) desc; 	0
10117619	14539	how to write a join when the second table has an on match but not a where match	select distinct a1.a, b2.d from a a1 join b b1 on a1.a = b1.a left join b b2 on a1.a = b2.a and b2.c = 10 where a1.a = 1 	0.00124808947325878
10118072	20114	number of digits from floating point values in a mysql query?	select name, round(lat, x, 1), round(lng, x, 1) from locations limit 10 	0.000530514892664456
10118622	24097	select top 1 result from table ordered by field	select top 1 * from table order by start_date 	0
10119785	32674	how to count total dates?	select s.username, (     select br1.requireddate     from bloodrequest as br1      where br1.bloodrequest_id =      (         select max(br2.bloodrequest_id)         from bloodrequest as br2          where br2.seeker_nic = s.seeker_nic     ) ) as requireddate, (     select count(br3.id)     from bloodrequest as br3         where br3.seeker_nic = s.seeker_nic ) as total_dates from seeker as s 	0.000475135295628116
10121411	13245	table name list from my sql database	select table_name from information_schema.tables where table_schema = 'db_name' 	0.00423947715149482
10122674	15405	distinct, count and sort in one sql query	select fk_user from  xxx group by fk_user order by count(*) desc 	0.0152927076569989
10125519	7696	two tables and trying to access info from another table	select u.firstname, u.lastname, t.* from users u inner join tickets t     on u.id = t.user where u.firstname = ???   and u.lastname = ??? 	0
10125913	30308	how to check for unique values in two columns with one query?	select     sum(case when foo='foo' then 1 else 0 end) as foocount,     sum(case when bar='bar' then 1 else 0 end) as barcount from     `mytable` 	0
10126404	683	calculate distance between two points directly in sqlite	select * from points where lat between ? and ? and lon between ? and ? 	0.0029521573408998
10126486	13339	count months from datetime in mysql with years	select year(datetime) as year, monthname(datetime) as month, count(*) from log group by year, month order by year, month; 	0.000234925772457345
10128069	29959	query results that have less than x characters in mysql	select `post_id` from `wp_postmeta` where `meta_key` = 'location' and char_length(meta_value) < 10 	0.00395801066194533
10128192	18739	include sys.databases name as column in dynamic sql union	select @sql = coalesce(@sql + 'union all ',' ') + ' select '''+name+''' as dbname, c.* from ' + name + '.dbo.combinedprovider c' from   sys.databases where  name in ('first_databasename', 'second_databasename') 	0.388282309917067
10131206	33069	mysql how do i select only highest for each pair values from the following table?	select farm_id, gate_id, max(score) from table group by farm_id, gate_id 	0
10134609	26635	getting last 5 char of string with mysql query	select right(columnname,5) as yourvalue from tablename 	0.000272255139572598
10134817	39073	sorting/ordering mysql with two fields	select *    from mytable order by  coalesce(sale, price) asc 	0.0600862345994513
10138386	12213	mysql selection from two tables	select aid,description,price,searchname from supplierdb s inner join articledb a on a.sid = s.sid 	0.00513074406120901
10138837	330	jpql date between interval	select m.* from message m where m.tabid = :idtab and date_field between :startdate and :enddate order by m.id desc 	0.0397929131126922
10139288	29708	how to create a search result page using php and mysql?	select * from table where name like '$nameorphone%' or phone like '$nameorphone%' 	0.0796920144250389
10141006	29083	aggregate results based on where clause using sqlite	select      sum(case when pt_task_assay_disp like 'ss%' then 1 else 0 end) as sscount,     sum(case when pt_task_assay_disp like 'ip%' then 1 else 0 end) as ipcount  from vbasedata v where      v.pt_task_assay_disp like 'ss%' or     (v.pt_task_assay_disp like 'ip%' and     v.pt_task_assay_disp not like 'ip cut' and     v.pt_task_assay_disp not like 'ip neg'); 	0.376378709878079
10142211	11678	select rows within a certain range	select id, title, content, date from tbl_news order by id desc limit 5, 5 	0
10142746	1787	how do i change the package variable value during runtime?	select '[' + ? + '_s]' 	0.028000939371256
10143043	3036	oracle consolidate 2 rows into column	select distinct studentname      , min(city) over ( partition by studentname ) as city1      , min(street1) over ( partition by studentname ) as street1      , case when min(city) over ( partition by studentname )                    <> nvl( max(city) over ( partition by studentname ), 'x')               then max(city) over ( partition by studentname ) end as city2      , case when min(street) over ( partition by studentname )                    <> nvl( max(street) over ( partition by studentname ), 'x')               then max(street) over ( partition by studentname ) end as street2   from my_table 	0.00061375409377317
10144382	9513	mysql how can i select the time difference between two log entries over a set?	select trackkey, (max(executetime) - min(executetime)) as time_difference from table where entry in('start update', 'complete update') group by trackkey 	0
10144387	12630	selecting order by matches in second table	select `idofphotovotedon`, count(`idofphotovotedon`) 'votes'  from `competitionvotes`  where 1 group by `idofphotovotedon` order by count(`idofphotovotedon`) desc, `idofphotovotedon` 	0.00032898437504624
10144389	41167	mysql - how can i know which field matches the result when using ors	select table1.*,         table2.*,         case (table2.field1 like 'keyword%' and table1.field1 like 'keyword%')            when 1             then 'f1'             else 'f2'         end as field from table1 ... 	0.083705051428358
10145197	41193	sum of a summation in mysql	select sum(value) from    (select    (sum(l.app_ln_amnt)/count(l.app_ln_amnt)) as value   from receipt_history l ) t 	0.0787449931237838
10145307	23187	need to check other table if field in table has 1 in it	select first_name, last_name,title from ( select first_name, last_name,title from students s     inner join high_schools hs on s.high_school_id = hs.id where s.other_high_school=0 union select first_name, last_name,title from students s     inner join other_high_schools ohs on s.high_school_id = ohs.id where s.other_high_school=1 ) as combined_schools order by last_name,first_name 	0.000137779847956444
10146606	20772	finding the sum of an average column in mysql	select   sum(group_avg) as total from (   select avg(<some_value>) as group_avg   from receipt_history   group by <column> ) q; 	8.41637548008542e-05
10147559	17179	can we do a mysql case with selecting tables after from?	select     tale0.*,     case when tale0.id = 1 then class.column1 else hamburger.column1 end as column1,     case when tale0.id = 1 then class.column2 else hamburger.column2 end as column2,     ... from     table0, class, hamburger 	0.061291681239227
10147868	2748	sql query - need to get information from different table	select b.bookid, b.bktitle , count(l.loanid) as cnt_loan from book b inner join loan l on l.bookid = b.bookid where rownum < 2 group by b.bookid order by cnt_loan desc 	0.000492523530973905
10148883	30213	selecting top 4 records from multiple sql server tables. using vb.net	select top 4 date, link, anchor, thumb  from (   select date, link, anchor, thumb      from archive1    union all   select date, link, anchor, thumb      from archive2    union all   select date, link, anchor, thumb      from archive3    union all   select date, link, anchor, thumb     from archive4  ) archive order by date desc 	0.000182842261987077
10153045	37118	checking is username exists on two tables php pdo?	select   users.user_login from  users  where   users.user_login = ?  union all select   users_banlist.user_banlist from   users_banlist where   users_banlist.user_banlist = ? 	0.0688871105977439
10154058	144	mysql - group by multiple rows	select       case when yt2.age between 13 and 17 then "13 - 17"            when yt2.age bewteen 18 and 24 then "18 - 24"            when yt2.age between 25 and 35 then "25 - 34"            else "35 and over" end as agegroup,       sum( if( yt1.value = "male", 1, 0 )) as maleflag,       sum( if( yt1.value = "female", 1, 0 )) as femaleflag    from       yourtable yt1          join yourtable yt2              on yt1.user_id = yt2.user_id             and yt1.survey_id = yt2.survey_id             and yt2.key = "age"    where       yt1.key = "gender"    group by       agegroup 	0.0292145994729312
10154577	27720	oracle select statement	select case when a.field1 > a.field2 then 1 else 0 end from a 	0.636910579913084
10154592	21247	check if all fields in the table are empty	select count(col1), count(col2) from products 	7.43983128806437e-05
10156709	5491	sql query needed to get information from two separate tables	select b.authorid, b.bktitle, a.authfname, a.authlname from book b   inner join author a     on b.authorid = a.authorid and b.authorid in (   select authorid   from book   group by authorid   having count(authorid) > 1 ) order by a.authlname, a.authfname 	0.000596107620870766
10157434	19110	return distinct on a table	select p.productid, p.title, max(pi.filename) as filename       from [ordering].[products] p inner join [ordering].[productimages] pi on p.productid =pi.fk_productid       where p.title like '%' + @title +'%'   group by p.productid, p.title   order by p.title asc 	0.00599776886845948
10158646	10796	joining 3 tables using newest rows	select * from children inner join families    on children.familyid = families.familyid inner join  (   select childid, researcher, status     from statuslog     inner join      (       select childid, max(id) id         from statuslog        group by childid     ) lastsl     on statuslog.childid = lastsl.childid    and statuslog.id = lastsl.id ) sl   on children.childid = sl.childid 	0.000704408820260709
10161852	12960	select every other row as male/female from mysql table	select * from (     select people.*,         if(gender=0, @mr:=@mr+1, @fr:=@fr+1) as rank     from people, (select @mr:=0, @fr:=0) initvars ) tmp order by rank asc, gender asc; 	0
10162399	36328	selecting and grouping on ranges	select sum(if(height<400,1,0)) '<400', sum(if(height>=400 and height<600,1,0)) '400-600'... 	0.00164323205248481
10162568	11650	how to perform several calculations in mysql?	select ((select total price query)*(select discount query) + (select shipping query)) 	0.356847202424442
10164897	8167	getting every possible combination of columns	select name, gender, company from t group by name, gender, company with cube 	0.000472052146785699
10165915	35836	getting data from database from different tables	select st.firstname + ' ' + st.lastname,se.year, c.coursename,c.credits,ri.mark  from students st  inner join registeredin ri on ri.studentid=st.id inner join semester se on se.id=ri.semesterid inner join courses c on c.id=se.courseid 	0
10166451	32397	mysql query: select most	select account from table where tag = 'sport' group by account order by count(*) desc 	0.061683588741821
10168194	13556	get last 3 rows in a select statement and make it asc order	select a.* from(        select *        from post_replies        where post_replies.post_hash=:posthash        order by post_replies.reply_id desc        limit 3) a     order by a.reply_id asc 	0.000252692981562716
10168607	40869	sql - order by different case on one column	select *    from tablename  order by      case        when checking_acct_months = 'average'        then 1 else 0     end,     checking_acct_months desc 	0.0128457954637314
10169316	30410	mysql query for daily hits	select count(id), date(created) from a_table group by date(a_table.created); 	0.0274895996043541
10170043	5609	how to get a total of recent date	select id, date, total  from table1 t where date = (select max(date) from table1 where id = t.id group by id) 	0
10170544	16459	getting results between two dates in postgresql	select *    from mytable   where (start_date, end_date) overlaps ('2012-01-01'::date, '2012-04-12'::date); 	0.00159011261444666
10170726	11568	mysql in - all values are compulsary and not 'or'	select * from conference where active='1' and 9 in conference_feature and 8 in conf 	0.0179826840677641
10172178	27839	count on sql only when the price is not 0,00	select zone, count(nullif(price,0)) as total from table1 group by zone 	0.0202072790800459
10172285	4916	get sum of php array	select sum(saleprice) as sum 	0.00318748163752207
10172945	11257	sql join on two tables that are not related or have primary keys	select service, level_3_structure, total_reduced, sum(fte) as total_fte from (     select      dbo.table1.service,      dbo.table1.level_3_structure,      sum(table1.reduced) as total_reduced      from dbo.table1      where       dbo.table1.period = 'cumulative'      group by       dbo.table1.service,      dbo.table1.level_3_structure  ) t1 inner join table2 on t1.service = table2.service  and t1.level_3_structure = table2.level_3_structure      group by       dbo.table1.service,      dbo.table1.level_3_structure 	0.000285270845989121
10174428	3585	grouping and getting the most popular item in a table	select count( * ) as rows1, spl_id, name from `new` group by `spl_id` , `name` order by   `rows1` desc 	0
10174830	17641	how can i convert sql datetime to dd/mm/yyyy 22:00	select convert(varchar(10), getdate(), 101) + ' ' +         convert(varchar(5), getdate(), 108) 	0.0384340039373174
10175337	652	how to create hbase columns / table for related but separated entities	select   employee.name,   employee.height,   project.name,   employee_project_role.role_name  from    employee    inner join employee_project_role      on employee_project_role.employee_id = employee.employee_id    inner join project      on employee_project_role.project_id = project.project_id 	7.20363339889578e-05
10176264	27546	exclusive mysql select query, two tables	select        od.id_order,       sum( if( p.id_supplier in ( 2, 4 ), 1, 0 )) as hassupplierlookingfor,       sum( if( p.id_supplier in ( 2, 4 ), 0, 1 )) as hasothersuppliers    from       order_details od          join product p             on od.id_product = p.id_product    group by       od.id_order    having            hassupplierlookingfor > 0       and hasothersuppliers = 0 	0.0353614825501267
10176538	15744	how to keep a specific row as the first result of a query (t-sql)?	select name from (     select 'all'       as name     union      select distinct    manager     from               is_projects ) t order by case name when 'all' then 0 else 1 end, name 	0
10178224	34360	how do i use where on computed column?	select if(o.is_discounted != 1, o.item_cost, o.discounted_item_cost) order_item_total,   sum(oi.quantity * oi.price) item_total from orders o inner join order_items oi on oi.order_id = o.id group by o.id having order_item_total != item_total 	0.0776687940084117
10179127	31880	non-dynamic approach to do a series of union statements on table value function tvf	select accountdetails.* from account cross apply (   select *      from dbo.tbfdetailsbyaccountkey(account.accountkey) ) accountdetails where account.depositkey = @pdepositkey 	0.0324718030927836
10179649	32176	get top-k of each group in mysql	select postid, clicks,     @num := if(@year = @year and @month = month, @num + 1, 1) row_number,     @year := year year, @month := month month from (     select * from t     order by year, month, clicks desc ) s, (select @num := 0, @year := '', @month := '') init group by year, month, postid, clicks having row_number <= 2 order by year, month, clicks desc 	0.000217193245868392
10179831	36174	how to check if change tracking is enabled	select *  from sys.change_tracking_databases  where database_id=db_id('mydatabase') 	0.242748815239491
10181511	36033	get related information mysql query	select model.id, brand.brandname, model.modelname  from model inner join brand on model.id = brand.id 	0.00655617628260927
10181736	12509	mysql - selecting the most recent post by each of the 10 most recent authors	select userid,postid, win from posts where postid in ( select max(postid) as postid from posts  group by userid )  order by postid desc  limit 10 	0
10182635	26316	group values together in php / mysql and add the value of one of the columns up into the group	select sum(items), date(creationdate) from people group by date(creationdate) order by creationdate desc 	0
10183460	29164	return sums of multiples of nth	select        m20.*    from        ( select                transdate,               score,               if( @runtotal + score >= 20 * @multcnt, 1, 0 ) as thisone,               @multcnt := @multcnt + if( @runtotal + score >= 20 * @multcnt, 1, 0 ) as nextseq,               @runtotal := @runtotal + score            from mult20s,                 ( select @multcnt := 1,                          @runtotal := 0 ) sqlvars            order by transdate ) m20    where       m20.thisone = 1 	0.000172913742411235
10183649	29784	return columns vertically	select id, 'name' columnname, name1 '1st', name2 '2nd' from yourtable union select id, 'description' columnname, description1 '1st', description2 '2nd' from yourtable union select id, 'notes' columnname, notes1 '1st', notes2 '2nd' from yourtable 	0.0302120704001103
10184783	4330	sql to return rows that which contain same data for one field but different data for others	select teachername from (     select teachername, coursen     from teacher     group by teachername, coursen     ) t1 group by teachername having count(*) >=2 	0
10186490	7689	multiple rows into single row with header name	select s.id, s.name,         max(case when s.subjectname = 'english'         then s.obtainedmarks end) as 'english',        max(case when s.subjectname = 'islamic-studies' then s.obtainedmarks end) as 'islamic-studies',        max(case when s.subjectname = 'pak studies'     then s.obtainedmarks end) as 'pak-studies' from students s group by s.id, s.name 	0
10186922	28172	nested sql count from two count queries into one query	select count(orderid) as counted from tableorder where (year(orderdate) between 2012 and 2012) union select count(errorid) as counted from  tableerror                       where (year(errordate) between @year1 and @year2) group by surname, firstname; 	0.00217433885177216
10188131	36625	condition for counting distinct rows in an sql query	select count(id) from (     select id from mytable     group by id     having count(id) > 2) p 	0.0227306382398495
10188556	17122	include sorting in query	select * from constructions as whole inner join (     select distinct construction as results     from data     where product =2     and application =1     and requirement =1 ) as a on whole.id = a.results order by whole.sorting 	0.439054143815304
10190244	21647	sql - how to select top 5 from inner statement	select *      from (          select *           from table           where name is null           order by date desc           limit 20          ) as t      order by date asc     limit 5; 	0.0249613874950445
10190464	35105	trim, convert and compare a string from an sql db, in a single sql query	select     device_no,    case        when          ltrim(rtrim(rms_size)) like '%mm'       then          substring(rms_size,1,len(rms_size)-2)       else          rms_size       end       as rms_size from dw_data.dbo.dim_device 	0.00247734431210442
10190596	3450	checking if column contains a pattern or not?	select user_name_n,        left(user_name_n,patindex('%[, ]%',user_name_n + ' ')-1) from   sfcha10_04_02_2012; 	0.125453229683427
10191398	13895	get first/last n records per group by	select tablea.ida, tablea.titlea, temp.idb, temp.textb from tablea inner join (     select tb1.idb, tb2.ida,     (         select textb         from tableb         where tableb.idb = tb1.idb     ) as textb     from tableb as tb1         join tableb as tb2             on tb1.ida = tb2.ida and tb1.idb >= tb2.idb     group by tb1.ida, tb1.idb     having count(*) <= 5     order by ida, idb ) as temp on tablea.ida = temp.ida 	0
10191859	24931	counting records in access	select count(*) as total from  (     select distinct state     from yourtable ) 	0.0261150936891957
10193052	3813	sql using min with char content in select()	select min(               cast( replace(                       replace ( field, '.', '' ),                       ',', '.'                     )                    as decimal(5,2))            )  ... 	0.157507280901069
10197151	8041	order by tablename?	select *, 'tablea' as tablename from tablea union all select *, 'tableb' as tablename from tableb order by tablename 	0.238070541082851
10197290	22342	sql date compare	select * from tbl where publishdate = (select max(publishdate) from tbl) 	0.0208256597538234
10198668	30234	i need to write an sql statement that joins multiple tables, including one table twice, and sorts by counting a group .. i think	select source.airportid as source_airportid,        source.city source_city,        dest.airportid as dest_airportid,        dest.city as dest_city,        count(*) as flights from   flights inner join airports source on source.airportid = flights.source inner join airports dest on dest.airportid = flights.dest group by        source.airportid,        source.city,        dest.airportid,        dest.city having count(*) >= 2 order by 5; 	0.430466444200516
10199055	12800	mysql two tables joining and getting result based on only and only by same field value	select       c.contactid    from       contacts c          left join transactions t             on c.contactid = t.contactid            and t.cancelled = "yes"    where       t.contactid is null 	0
10199825	12046	postgresql - how to fetch rows higher then year since the date	select * from your_table where the_date_column > current_date - interval '2' year 	0
10199902	20301	how do i count the number of appearances of any string that is not "string1", "string2", "string3" etc.?	select strings, count(*) as appearances  from tbl where strings not in('string1', 'string2', 'string3') group by strings 	0.00214223017453939
10200405	15318	reading values from mysql db to average the rows	select avg(overall),avg(othercolumn1),avg(othercolumn2),avg(othercolumn3) from ... 	0
10201496	33387	mysql query for sorting posts by entry_date based on status	select * from tablename order by if(status=1,0,1), entry_date desc 	0.000532383349064138
10202097	13493	suming rows in two different tables in a nested join. sql server	select sum(likes) as totallikes,         sum(dislikes) as totaldislikes    from (select isnull(sum(beats_likes_dislikes.[like]), 0)  as likes,                 isnull(sum(beats_likes_dislikes.dislike), 0) as dislikes            from users           inner join beats                 on users.userid = beats.userid           inner join beats_likes_dislikes                 on beats.beatid = beats_likes_dislikes.beatid          where  users.userid = '110'          union all          select isnull(sum(flows_likes_dislikes.[like]), 0)  as likes,                 isnull(sum(flows_likes_dislikes.dislike), 0) as dislikes            from users           inner join flows                 on users.userid = flows.userid           inner join flows_likes_dislikes                 on flows.flowid = flows_likes_dislikes.flowid           where users.userid = '110') as t 	0.0197860730826525
10202427	11076	select mysql rows where today's date is between two date columns	select * from table where from_date <= '2012-04-10' and to_date >= '2012-04-10' 	0
10202967	27646	oracle sql possible to trim characters before a character is found?	select regexp_substr('david', 'v.*') from dual  where regexp_like('david', 'v.*') 	0.474664236971883
10204203	2194	query change from mysql to ms access	select a.employee_id as employee_id,        a.employee_name as employee_name,        a.flat_no as flat_no,        a.area as area,        a.building_name as building_name  from   tblallotment a            inner join tblflat f              on a.flat_no = f.flat_no  where  f.status = 'a'        and (not (a.employee_id in                  (select c.employee_id                   from   tblallotment a                           inner join tblcancel_allotment c                              on a.employee_id = c.employee_id                   where c.date_cancellation = 0))) 	0.33255399582889
10205712	38460	mysql select from one table with concat results from another table	select      docs.id as id,      docs.orig_file as orig_file,      docs.date_sent as date_sent,      group_concat(distinct tags.tag_name) as alltags from documat as docs left join documat_file2tag as f2t on f2t.doc_id = docs.id left join documat_tags as tags on tags.id = f2t.tag_id group by docs.id 	0
10206117	21488	query varchar date with between	select distinct monthcol from bo_alerts where monthcol between '2011.03' and '2012.04' order by monthcol desc 	0.0538914215868905
10206934	8316	group by retrieve 3 values	select  cod ,         min(id) as id__min,         max(id) as id_max,         sum(id)-max(id)-min(id) as id_middle,         count(*) as tot from    table a ( nolock )         group by cod having  count(*)=3 	0.00214345886402528
10207068	33216	join table complicate	select  person.id_prs,  person.name,  fonction.id_fonct,  fonction.label as label_fonct, fonction.id_categ, category.label as lab_cat, metir.id_met, metirlabel as lab_met,  analys.id_ana, analys.label as lab_ans from person inner join con_prs_fonc on person.id_prs = con_prs_fonc.id_prs inner join fonction on fonction.id_fonct = con_prs_fonc.id_fonct inner join category on category.id_categ = fonction.id_categ inner join metir on metir.id_met = fonction.id_met inner join analys on analys.id_ana = fonction.id_ana 	0.611951630532076
10207281	37690	column that matches in a fulltext index spanning multiple columns	select text_test.*,        match(name) against ('dude' in boolean mode) as name_match,         match(info) against ('dude' in boolean mode) as info_match    from text_test   where match(name, info) against ('dude' in boolean mode); 	0.015778747949793
10208003	34053	sql check a set of elements containing a specific value	select distinct [email] from [dbname].[dbo].[users] inner join dbo.orders on dbo.orders.customerid = dbo.users.userid inner join dbo.orderlines on dbo.orderlines.orderid = orders.orderid where users.subshopid = 1  and orderlines.productid <> 1 order by email desc 	0
10208104	23542	is it possible to select a specific order by in sql server 2008?	select *  from requirements order by       case day       when 'monday' then 1      when 'tuesday' then 2      when 'wednesday' then 3      when 'thursday' then 4      when 'friday' then 5      when 'saturday' then 6      when 'sunday' then 7      end 	0.512930122738552
10210517	32190	postgresql: calculate rank by number of true or clauses	select * from mytable  where fld = 'a' or fldb = current_date or fldc = 7 order by    (fld = 'a')::int + (fldb = current_date)::int + (fldc = 7)::int   desc 	0.00488088026629759
10210824	31055	postgresql query count and max together?	select id,        icon,        type,        cnt,        max(cnt) over () as max_cnt from  capability  join (     select s0_.capability_id as capability_id0 ,            count(capability_id) as cnt       from service_offer_capability s0_      inner join service_offer s1_ on s0_.service_offer_id = s1_.id      where s0_.value <> 'i:0;' and s1_.service_id = 2      group by s0_.capability_id ) af on af.capability_id0=id; 	0.227551886503325
10211230	30117	recompute big table in sql database	select top 10000 * from t where id > @lastidprocessed order by id 	0.243755824332523
10211846	17562	mysql joins with 3 tables	select * from a left join b on a.article_id = b.article_id left join c on b.file_id = c.submission_id and c.user_id = 6; 	0.417888071020967
10212788	12821	return multiple records as one string in query	select   last_name, group_concat(sports.title) as sport from   students s left join  students_sports ss on  s.id = ss.student_id left join  sports on  ss.sport_id = sports.id group by s.id 	0.000999712474119346
10213973	2268	mysql select all from today up until now	select * from tbl where idate > date(now()) and idate < now() 	4.9508668758498e-05
10214198	8482	check who has logged in using sql server 2000 trc files	select * from ::fn_trace_gettable('c:\sqlauditfile2012322132923.trc', default); 	0.010678271181203
10214309	32701	join 2 tables with extra maths	select teamid, sum(score * if(fldjoker = round, 2, 1)) ... 	0.282631281080726
10214489	5886	how can i get odd numbered characters in a string using sql	select regexp_replace(mycolumn, '(.).', '\1') from   mytable 	0.252422766723422
10214554	29372	if field is null, pull certain fields; otherwise, pull other fields	select     columna,     case when columna is null then column1 else column3 end as columnb,     case when columna is null then column2 else column4 end as columnc from     testtable 	0
10215388	13047	mysql retrieving newest entry between set integers	select u.id, u.user_id, u.response from user u where u.id in  (  select max(id) from user where user_id = $userid  and response in (8,9) ) ; id  user_id response 12  15  8 	4.76113773258161e-05
10216057	37493	search for strings with multiple {tokens} in database	select * from messages where (length(message) - length(replace(message,'{bar|','')))/5 between 1 and 2; 	0.365877604599616
10216645	24229	sql check if next row doesn't exist	select id, name, pass, count(*) over () as rows from users 	0.00351992105207573
10216729	37799	mysql/php selecting and counting from multiple tables	select     town.state_id as state_id,     town.town_id as town_id,     count(street.street_id) as count from     state inner join town on state.state_id = town.state_id      left join street on town.town_id = street.town_id group by     state_id,     town_id having     town.misc_property = 'stuff'; 	0.000754512778439667
10218999	39386	sql same join in two columns with different values	select  f1.fighter as fighter1,         f2.fighter as fighter2 from    fight         inner join fighters as f1 on fight.fighter_id1 = f1.id         inner join figthers as f2 on fight.fighter_id2 = f2.id 	9.11820164281764e-05
10219993	1982	try to get current and next schedule by php	select field1,field2,when from schedules where channel_id = 13 and  when >= $time order by when asc limit 2 	0.000114198233195745
10222338	24821	counting the number of first place scores with mysql	select      concat(h.username ," has ", count(h.username)," high scores ") from     highscores h inner join     (select lid, max(score) as maxscore      from highscores group by lid) t on h.lid = t.lid and h.score = t.maxscore group by h.username 	0.000129839750201976
10223641	8429	check database for similar value , mysql	select distinct brand from tablename 	0.0105671366554468
10224626	22571	sql query to view eav data as 3nf? (drupal 6 profile values)	select    u.user_id,    (select value from profile_values f1 where f1.field_id=1 and u.user_id=f1.user_id) as first_name,    (select value from profile_values f2 where f2.field_id=2 and u.user_id=f2.user_id) as last_name   from users u 	0.0280804136211011
10225131	8587	concatenate two column values in linq lambda expression	select new {     username = currentuser.first_name + " " + currentuser.last_name,     currentuser.email_id,     currentuser.guid }; 	0.0114509823543171
10226544	36459	determining average from database using vb6	select studentid, avg(grade) as averagegrade from studentgrade group by studentid 	0.00231516800157137
10227407	34325	sqlserver 2008 - return value of stored procedure after catching an exception	select 'testing 3' 	0.556463325380959
10227686	31060	sql-server and mysql interoperability?	select t1.cola, t2.colb from sqldbname.dbo.tablename as t1 inner join openquery(mysqllinkedservername,                       'select cola, colb from tablename') as t2 on t1.cola = t2.cola 	0.639627591665384
10227801	36617	mysql search on match	select * from tblr where r_num like '2011%'; 	0.121974057896776
10228485	21216	mysql select only data that contains some letters in any order	select * from yourtable where yourcolumn rlike '/^([1-5])+$/'; 	0.000419344501532634
10230542	38135	mysql return join of same table with same name	select        s.stud_num,        concat(p1.first_name, " ", p1.last_name) as prof1,        concat(p2.first_name, " ", p2.last_name) as prof2    from        students s          left join prof p1             on s.prof1 = p1.prof          left join prof p2             on s.prof2 = p2.prof 	0.000165635206183581
10230886	36447	mysql join, grouped data, and a compare?	select  i.*, v.id from    items i join    variations v on      v.item_id = i.id where   (         select  count(distinct vi.id)         from    variations vi         where   vi.item_id = i.id                 and vi.id in (23, 25, 29)         ) = 3 	0.00652792500691351
10230959	21867	joining two relations with default values	select v1.obj, nvl(v2.attribute, 0) from view1 v1 left join view2 v2 on v1.obj = v2.obj 	0.00658945234846576
10231340	26410	how can i get a difference of two columns in two different tables in a select query	select  (         select  sum(col1 + col2)         from    tablea         ) -         (         select  sum(total)          from    tableb         where   color not like '%black'                 and model not like 'cf%'         ) as result 	0
10231528	6136	search product with their specifications filter	select product  from my_table   where (custom = 'ram' and custom_value = '2')      or (custom = 'vga' and custom_value in ('1', '512')) group by product having count(distinct custom) = 2 	0.0433352763335186
10232114	4608	manipulating sqlite data in c# or string manipulation for image tag	select parenttableid, photoid, replace(path,'h:\','') as path from tblphoto 	0.338560461796342
10233302	14502	join 3 tables without nested queries	select o.*,     up.phone,     u.username from orders o left outer join userprofiles up on o.iduserprofile = up.id left outer join users u on up.iduser = u.id order by o.date 	0.604989147512771
10236229	27334	how do i limit the number of rows returned by this left join to one?	select * from table1 left join (select * from   (select *,            row_number()              over(partition by assignmentgroup order by assignmentgroup) as seq     from  table2) a where  seq = 1) v on assignmet = v.assignmentgroup 	0.00237317860340352
10237984	14127	if condition in an sql query	select * from table where datediff(day, getdate(), maildate) = case when     datepart(hour, getdate()) >= 16 then 1 else 0 end 	0.593852944609692
10239170	6366	distinct value in two column	select f1,f2,f3 from (select f1,f2,f3 from tablename as table1 group by f1) as table2 group by f2; 	0.00116082881044767
10241385	20372	how to query a table and display null on the joined table if it does not meet the filter?	select v.organizer, (cases i.vacation_id is null then i.value else null end) from vacation as v left join itinerary as i    on v.vacation_id = i.vacation_id 	0.000155168102484957
10241993	30141	add a top single row to the ordered result set of a query	select null as projectid, 'all' as projectname, 1 sortorder union all select  project.projectid,  project.projectname, 2 sortorder from project order by sortorder, projectname 	0
10242065	31508	select result grouped by all fields	select   a.codeid as vendorid ,                                     a.hname ,                                     a.hnamee ,                                     case when v.audienceid = 0 then 1                                          else 0                                     end as hasall                            from     dbo.dtany as a                                     left join vendoraudience as v on a.codeid = v.vendorid                            where    a.hrclvl = @level                                     and a.dcode = @dcode                                     and a.codeid = isnull(@vendorid, a.codeid)                                     group by vendorid ,a.hname ,a.hnamee ,                                     case when   v.audienceid = 0 then 1                                          else 0                                     end 	0.000757433332414857
10242221	8987	how to improve mysql query that trying to find distinct values from two tables?	select source_ip, timestamp from tb1 where  source_ip not in (select source_ip from tb2)  and timestamp not in (select timestamp from tb2) 	0.000271398726955823
10243852	13433	determine if column value string starts with a number	select case when isnumeric(substring(ltrim(description), 1, 1)) = 1           then 'yes'           else 'no'         end as startswithnumber from questions 	6.88411117492647e-05
10244148	9956	sql - joining one table with another based on ( row value from first table to column value of second table)	select   dealnum              , currencyvalue              , currencycode               , date        , deal =           case month(t1.date)            when 1 then t2.jan            when 2 then t2.feb            when 3 then t2.mar            when 10 then t2.oct            when 11 then t2.nov            when 12 then t2.dec         end from table1 t1  inner join table2 t2 on t1.currencycode = t2.currencycode 	0
10245877	26955	i18n database tables get value of a field by culture	select tp.id, nvl( t.description, tp.description) from task_priority tp    left outer join task_priority_i18n t      on t.id = tp.id      and t.culture = :culture 	8.00391148488513e-05
10246421	32561	why select of count fetches a lot of rows?	select count(1) from teams where userid = 100 	0.153853769217343
10246928	3236	how do i count the number of instances from 2 columns where a given string appears?	select count(*) from   games_table where  game_outcome = 'home wins' and    (home_team = 'chelsea' or away_team = 'chelsea') 	0
10247050	4191	sql server convert varchar to datetime	select convert(datetime, '2011-09-28 18:01:00', 120)  select convert( varchar(30), @date ,105)  + ' ' + select convert( varchar(30), @date ,108 )  	0.153919093874533
10247254	15196	sql server 2008 - split parameter by space, return records like all split results	select a.yourfields from yourtable a inner join (select *, count(*) over() total from dbo.split(@description)) b on a.yourfield like '%' + b.data + '%' group by a.yourfields having count(*) = max(b.total) 	0.00264911761135083
10248223	22119	how to reorder a sql query?	select [program_id], [program_name] from  (    select    null as [program_id],    '-all-' as [program_name] ,   0 as num1   union all   select distinct    [program_info_id] as [program_id],    [program_name] ,   1 as num1 )a order by a.num1, a.[program_name]  	0.39890976070415
10251785	21976	mysql - getting days of the week	select *    from special_offers  order by (special_offers.special_day + 8 - dayofweek(now())) mod 7   limit 1 	0
10252607	2563	how come i am getting the same total values of 2 different columns	select category ,'p3' as period ,'2013' as fiscalyear   ,sum(case securitylayer when 'dblayer' then 1 else 0 end) as db_sec_count ,sum(case securitylayer when 'applayer' then 1 else 0 end) as app_sec_count from [db_ecam].[dbo].[tbl_secchecks]   group by category 	0
10255266	3345	select users from one table only if not in another	select * from users where id not in (select id, from, to from lendings) and borrower = 1 	0
10255341	18859	using mysql joins across 3 tables	select movies.title, group_concat( genres.name separator ‘, ’ ) as 'genres' from movies inner join genres_in_movies on movies.id = genres_in_movies.movie_id inner join genres on genres_in_movies.genre_id = genres.id where movies.id = 12345 group by movies.title; 	0.219314257625907
10260424	1465	combine two string records in where cause	select name, surname, id from users where concat(name, ' ', surname) like '%".$term."%' 	0.00893659228255132
10260502	16925	counting from another table [mysql]	select t1.search_term, count(*) from t1 join t2 on t1.id = t2.search_term and t1.site_id = t2.site_id where t1.site_id = 2 group by t1.search_term 	0.000519603179311317
10262653	19966	return a random row without using id, mysql	select * from $tbl_name t join (select ceil(max(id)*rand()) as id from $tbl_name) as x on t.id >= x.id limit 1; 	0.000484786575669772
10263771	3307	count rows that have at least one associated item	select count(distinct(sale_id)) from sale_items where item_id='<your_item_id>' 	0
10264120	27560	mysql 5.5 select max from table2 for every unique id in table1	select t2.id,  'count_' + cast(max(cast(replace(t2.value, 'count_', '') as int)) varchar) intvalue from table1 t1 join table2 t2 on t1.id = t2.id group by t2.id order by max(cast(replace(t2.value, 'count_', '') as int)) desc 	0
10264484	5791	mysql - how to get number of unique active users per month who posted or commented?	select   t.action_year,   t.action_month,   count(t.user_id) active_users from   (   select distinct user_id, year(post_date) action_year, month(post_date) action_month from content   union   select distinct user_id, year(comment_date) action_year, month(comment_date) action_date from comment   ) t group by   t.action_year,   t.action_month order by   t.action_year asc,   t.action_month asc 	0
10264780	37073	left join duplicate column	select  from items      left join images      on items.item_id = images.item_id   where items.display_items = '1' and items.active = '1'  order by items.item_year desc, items.fullname desc, images.position asc 	0.185763546336973
10266177	27074	count num_rows base on field value	select   sum(case when vote_type = 'up' then 1 else 0 end) as up,   sum(case when vote_type = 'down' then 1 else 0 end) as down,   sum(case when vote_user = 'john' then 1 else 0 end) as john from   yourtable where   vote_id = 3 	0.00320391964887249
10266180	34478	how to retrieve match records across multiple tables in mysql	select *  from table1 t where exists       ( select *         from table2 tt         where (col1, col2, col3, col4)              = (t.col1, t.col2, t.col3, t.col4)       ) ; 	0
10267491	29500	to serialize array or not to serialize array: how to store a survey	select text, count(*) as count from answers where question_id = 1 group by text 	0.456154871010111
10270627	21518	how to display all tables in postgresql while having two schemes in db?	select table_name from information_schema.tables where table_schema = 'scheme_one'; 	0.000297869280573057
10271811	11206	just display rows with 3 or more equal data in a column	select yourcolumn from yourtable group by yourcolumn having count(*) >= 3; 	6.16246177973804e-05
10273602	14979	mysql query where a pair of values does not exist in another table	select b.id, b.blog_name from blogs b inner join featured f on f.blog_id = b.id where b.id not in (select id from subscriptions where member_id = 3) 	0.00825885771183051
10273971	7928	storing a sql string array, and subsequent querying	select t.tag_name, i.image_name from image_tags it     inner join images i on it.image_id = i.id     inner join tags t on it.tag_id = t.id where t.tag_name in ('beach', 'palms') 	0.0564892690024305
10275826	22561	find correctly answered questions in an online test with single and multi choice questions	select   count(*) - count(incorrect_answers_per_question) correct from (   select     d.test_id,     d.question_id,     sum(case when r.correct_response_flag = 'n' then 1 end) incorrect_answers_per_question   from test_response d   join question_response r on d.response_id = r.question_resp_id   where d.test_id = '10113'   group by d.test_id, d.question_id ) 	0.651843051476883
10276822	32431	random records, but maximal one from each category	select     mixed_stamp.stamp_id,     random.country_name_cs  from     (select * from stamps order by rand()) as mixed_stamp  left join (select country_id from countries order by rand() limit 3) random on (random.country_id = mixed_stamp.country_id)  group by random.country_id 	0
10277025	25531	select the offset of a row respecting the order without fetching all previous rows	select @rownum := 0; select * from (     select @rownum := @rownum + 1, id, some_column, sortcol     from `table`     order by `sortcol` ) all_rows  where `some_column` = somevalue; 	0
10277482	6764	how to mention a range in the where clause of a query?	select column_name(s) from table_name where column_name between value1 and value2 	0.023704153006254
10278116	31803	how to fetch two column value in one colume based on boolean field	select     bill.*,     case          when bill.isservice=1         then service.sname         else product.pname     end as name from     bill     left join service         on bill.typeid=service.sid     left join product         on product.typeid=bill.bid 	0
10278442	9467	reuse calculated field in same query for new calculation	select min(q.order_created) as first_ordered,                   max(q.order_created) as last_ordered,        sum(if(date_add(q.order_created,interval 12 month) >= now(),pq.product_qty,0))/12 as monthly_rate,                             sum(pq.product_qty) as yearly_sales,        sum((pq.product_cost_price * pq.product_qty) - pq.product_total_price ) as net_sold,        sum(pq.product_cost_price * pq.product_qty)  as total_ordered,        100 - ((sum(pq.product_cost_price * pq.product_qty) - sum((pq.product_cost_price * pq.product_qty) - pq.product_total_price ))/sum(pq.product_cost_price * pq.product_qty) )*100 as discount,        q.billing_account_id as custid from quotes q left join products_quotes pq     on q.id = pq.quote_id where pq.product_id = '28e96e3d-460f-49fc-7d52-4f390b86d6b8'     and q.deleted = 0         and pq.deleted = 0 group by q.billing_account_id order by q.order_created group by q.billing_account_id order by q.order_created 	0.00354359586235245
10279895	17344	multiple references on one separate table-column possible?	select       p.model, manufacturer.name as manufacturer,       subcontractor.name as subcontractor from product as p left join       manufacturers as manufacturer        on p.manufacturerid = manufacturer.id left join       manufacturers as subcontractor       on p.subcontractorid = subcontractor.id 	0.00714443222601647
10281906	18382	how to find column information for an aggregate grouping	select userid, os, dateinstalled from installations join (    select userid, dateinstalled = max(dateinstalled)    from installations    group by userid ) as t on installations.userid = t.userid and installations.dateinstalled = t.dateinstalled 	0.00870146992854367
10282270	8648	mysql list users and their groups	select u.user_name, group_concat(g.group_name) from `user` u inner join group_member gm on gm.user_id = u.user_id inner join `group` g on g.group_id = gm.group_id group by u.user_id 	0.000255872244222749
10282835	41275	sql: select number text base on a number	select foo from table where cast(foo as int)>@n 	0.00035251549534656
10283605	13642	mysql- select records that exceeding certain time range	select visits.id from visits inner join physician_schedules   on visits.physician_id = physician_schedules.id   where         upper(day_of_week) = upper(dayname(visit_date))     and (scheduled_intime < start_time or scheduled_outtime > end_time) 	0
10284478	31345	find multiple column duplicates then list them all	select s.name, r.name region, c.name country      from supplier s      join region r on r.id = s.regionid      join region c on c.id = isnull(r.pid, r.id)      inner join (select s.name, r.name region, c.name country                 from supplier s                 join region r on r.id = s.regionid                 join region c on c.id = isnull(r.pid, r.id)                 group by s.name, r.name, c.name                 having count(s.name) >1 ) dups      on s.name = dups.name         and r.name = dups.region         and c.name = dups.country 	0
10285302	19987	sql display only 6 biggest values	select p_name, p_size  from part  order by p_size fetch first 6 rows only 	0
10285761	13558	get records having both values in "in" using sql	select a.id from applicant a join applicantdeployment ad on a.id = ad.applicantid join applicantattachment at7 on a.id = at7.applicantid and at7.tag = 7 join applicantattachment at8 on a.id = at8.applicantid and at8.tag = 8 where a.applicanttype = 'tcn/ln'  and ad.groundlocation in (4,8,14) and ad.deploymentstatus = 1 and ad.trainingdeploymentstatus = 6 	0.00132231902077008
10287105	28205	how do i write a sql server function to return a single value from result of several queries	select  top 1         trxstatus from    (         (         select  top 1                 *         from    trans1         where   jobno = @job                 and trxdate <= @trxdate         order by                 trxdate desc         )         union all         (         select  top 1                 *         from    trans2         where   jobno = @job                 and trxdate <= @trxdate         order by                 trxdate desc         )         ) q order by         trxdate desc 	0.000994318668070934
10288239	35779	query to check if record exists and column null	select  o.*,         od.order_price,         case         when od.order_id is null then                 'not exists'         when od.order_price is null then                 'exists, is null'         else                 'exists, is not null'         end as nullness from    orders o left join         order_data od on      od.order_id = o.id 	0.00508835997465187
10288364	23163	mysql find full name across two rows	select t1.submit_time, t1.field_value, t2.field_value from your_table t1 inner join your_table t2 on t2.submit_time = t1.submit_time where t1.field_name = 'firstname' and t1.field_value = 'paulo' and t2.field_name = 'lastname' and t2.field_value = 'hill' 	0.000463274492447371
10288436	25886	multiple rows into one field on grouped results mysql	select sum(case when rstat = 1 then 1 else 0 end) as attended,        sum(case when rstat = 2 then 1 else 0 end) as tentative,        sum(case when rstat = 3 then 1 else 0 end) as rejected,        sum(case when rstat = 4 then 1 else 0 end) as outstanding,        sum(case when rstat = 6 then 1 else 0 end) as accepted,        sum(case when rstat not in (1,2,3,4,6) then 1 else 0 end) as other     from estatus 	0
10288520	15073	oracle: copy a role from one database to another?	select dbms_metadata.get_ddl('role', role) from dba_roles; select dbms_metadata.get_granted_ddl('role_grant',  '&&your_role_name') from dual; select dbms_metadata.get_granted_ddl('system_grant','&&your_role_name') from dual; select dbms_metadata.get_granted_ddl('object_grant','&&your_role_name') from dual; 	0.000183856145328445
10291763	11501	mysql join with conditions on join on the fly	select c.customerid, max(i.datedue) from customers c left join invoice i on i.customerid = c.customerid where i.datedue <= unix_timestamp() and c.status!='d' group by i.customerid order by i.datedue desc limit 0,1000 	0.153930796265996
10292042	37538	join with alternating possibilities	select      i.itemid         ,   s.price         ,   s.qty         ,   s.company from        dbo.item    i cross apply (                 select  min(price)  price                 from    dbo.sku     mp                 where   i.itemid    = mp.itemid                 and     qty         > 0             ) mp cross apply (                 select                  top 1   price                     ,   qty                     ,   company                 from    dbo.sku     s                 where   s.itemid    = i.itemid                 and     s.price     = mp.price             ) s 	0.659271148329834
10292330	38307	fetching orders from database with special kind of grouping / aggregation	select substring(ordernumber, 1, 9) as ordernumber     , count(*) as ordercount     , sum(subtotal) as total     , orderedby from [table] group by substring(ordernumber, 1, 9), orderedby 	0.0134875505325242
10294668	10592	oracle - select most voted items by distinct users	select itemid,        votecount from   (     select itemid,            count(distinct userid) as votecount,            rank() over(order by count(distinct userid) desc) as rn     from uservote     group by itemid   ) u where rn = 1; 	0.000144041222946437
10295583	30903	mssql select count where condition is met across a date range	select tmain.date, (     select count(distinct taux.employeeid)     from roster taux     where taux.shiftworked = 'night'       and taux.date >= dateadd(day, -7, tmain.date)       and taux.date <= dateadd(day, 7, tmain.date) ) as [number_of_distinct_people_with_night_shift] from roster tmain order by tmain.date; 	0.00180499937964756
10295689	40466	single-row subquery returns more than one row - how to find the duplicate?	select applications.sap_sid, count(dr_option)  from applications  group by applications.sap_sid  having count(dr_option) > 1 	0.000145337213338131
10299086	33355	query to find row till which sum less than an amount	select max(cum_sum), max(date) from (     select date,          sum(amount) over (order by date) cum_sum ) where cum_sum < 8 	0
10299797	24238	show sql table other way	select code, a, b from   (     select code, zone, price      from yourtable   ) t pivot   (     min(price) for zone in (a, b)   ) p 	0.0045540655918793
10300628	34996	how to select two columns, where one column must be distinct?	select col1, max(col2) col2_max from table1 where col3 = 'x' group by col1 order by col2_max 	0.000318049426074873
10301581	33876	sql truncate/pad strings	select     convert(char(9), client_ahcccs_id) +     convert(char(25), client_first_name) +     convert(char(25), client_last_name) +     replace... 	0.560144225118576
10301938	34253	mysql - how can i find the maximum size of content in a field	select max(length(field)) from table 	0
10302650	9288	mysql - very complicated random row	select  * from    posts where   id not in         (         select  pid         from    user_unread_posts uup         where   uid = $myuserid         ) order by         rand() limit 1 	0.557946898172182
10303638	13697	sql select foreign key rows that have no rows in child table	select authid,     sname,     fname,     b.bid from author u left outer join allocation a on a.authid = u.authid left outer join book b on a.bid = b.bid order by authid 	0
10304146	21435	select values from a table that are not in a list sql	select * from (   select 'test 1' thename union   select 'test 2' union    select 'test 3' ) where thename not in (select name from foo) 	7.0329786088352e-05
10304942	16552	what is the fastest/easiest way to tell if 2 records in the same sql table are different?	select field1, field2, field3, .... field7, count(*) from table [where primary_key = key1 or primary_key = key2] group by field1, field2, field3, .... field7 having count(*) > 1 	0
10305960	14484	return all non leaf nodes using recursive cte in ms sql	select * from table where id in (select mgtid from table) 	0.0941873747679693
10307515	30332	select statements with sql	select b.*, username from a  left join b on b.userid = a.userid  where a.entry = "xxxxx" 	0.624351720175616
10308223	14425	how to write a query so that based on a date, it takes data for the next 7 days	select maildate, status, jobno from table_1 where maildate between @maildate and @maildate + 7 	0
10310062	14872	how to join all data in table for one column as string with sql?	select stuff(     (select ',' + t.name from table_name t      where t.foreingid = 1 for xml path ('')), 1, 1, '') 	0.000233476894631958
10310860	5297	how to find most common words in a mysql database and average a second column	select     avg(t.score) as scorceavg,     t.name from     (         select              substring(table1.name,1,instr(table1.name, ' ')) as name,             table1.score         from              table1         union all         select              substring(table1.name,instr(table1.name, ' ')) as name,             score         from              table1     ) as t group by     t.name 	0
10311179	23298	conditional mysql order by two (equally important) columns	select p.* from products p join ( select category_id, max(date) as category_date from products   group by category_id ) pg on p.category_id = pg.category_id order by pg.category_date desc, p.category_id, p.date desc 	0.051194603219222
10311282	6274	aggregate log-table without using two selects	select     sum(case when table1.action='view' then 1 else 0 end) as views,     sum(case when table1.action='order' then 1 else 0 end) as orders,     table1.object  from     table1 group by     table1.object 	0.731397288202654
10311464	31848	multiple aggregate queries as one row	select (select count(*)           from table1          where column1 = value1) quotescreatedcount,        (select count(*)           from table2          where column1 = value1) quotesreferredcount 	0.0205327602831192
10312285	8694	get the last row in mysql	select prices.id_ticker, max(prices.date) as last, prices.price  from prices group by prices.id_ticker  order by prices.id_ticker desc 	0
10312888	2471	mysql update datetime column - add 10 year 3 month 22 days and 10 hours, 30 minutes to existing data	select datetime + interval 10 year + interval 3 month + interval 22 day        + interval 10 hour + interval 30 minute as new_date_time from table 	0
10314399	10881	sql sorting within groupings	select * from staff order by     admin desc,     case admin when 'true' then updated end desc,     hr desc,     case hr when 'true' then updated end desc,     sales desc,     case sales when 'true' then updated end desc,     it desc,     updated desc 	0.512699431205731
10314494	16600	selecting from two columns?	select distinct p.team, ( select count(*) from player where team=p.team )  from player p 	0.000140903758859262
10314627	25952	how to use group by to retrieve a result set with priority on alphabeticization for case field?	select id,  case     when filename like '%.mp3' then 'song'     else 'other' end as type from filenames group by id desc; 	0.007577399200172
10315762	30690	how to execute different query based on the result got from executing query in mysql?	select * from ( select id,name from table1 union select id,name from table2 union select id,name from table3 ) num where num.id = ? 	0.00463386384699663
10316540	17128	get all records that don't completely match on all fields from a table join	select field1, field2, field3, field4   from table1  except  select field1, field2, field3, field4   from table2 	0
10316584	37025	select count of specific values	select name from table where element in (select element                   from table where element in('c', 'o') group by element                   having count(element) > 2) 	0.00111467597720217
10316718	13511	events lists with one or more days length in next 14 days	select gpe.*, gpr.name   from growl_presevents gpe, growl_presrail gpr   where gpe.location like gpr.railid  and (     (date_1 >= '$today' and date_1 <= '$week')     or (isnull(date_2,0) >= '$today' and isnull(date_2,0) <= '$week')     )   and gpe.publish = 'y'   order by date_1 asc 	0
10317027	10987	sql table highest sequence number	select distinct clid,                  first_value(seqnu)                      over (partition by clid                            order by bal desc) as seqnu,                  max(bal)                      over (partition by clid) as bal from your_table 	0.00028313110834431
10317655	39848	sql select & count from two tables	select users.id,(select count(1) from projects where projects.user_id = users.id) as 'count' from users order by id 	0.00182896995707373
10319060	35424	select statement to show next 'event' in the future	select top 1 e.*  from events e  where e.startdate > getdate() order by e.startdate asc 	0.000383870260099886
10319784	23917	order results from one mysql table by another, which is saving multiple values into the order field	select *, (select count(*) from offer where find_in_set(type._id, offer._type)) as _count from type order by _count desc limit 0, 10 	0
10320484	31702	sql statement to alphabetize and count	select terms, count( id) as count      from table  group by terms  order by terms desc 	0.747870180848993
10322788	4822	generate single xml file based on data from two tables or more	select meals.mealname, food.foodname from food join meals on (food.mealid = meals.mealid) 	0
10323107	26029	age calculation - fastest age calculation formula from timestamp field	select (curdate()-birth_dt)/365 from dual 	0.000477925283656812
10323318	14794	concatenate in classic asp/vbscript sql string	select tbl1.id, tbl1.country as a, tbl1.state as b, tbl1.code as c from tbl1    inner join tbl2 on cast(tbl1.country as varchar(20)) + '.' + cast(tbl1.state as varchar(20)) + '.' + cast(tbl1.code as varchar(20)) = cast(tbl2.id as varchar(20)) 	0.0801500129660113
10325642	38605	sql - find max based on contents of another column	select element        ,coalesce(max(case when qualifier = '=' then value else null end), max(case when qualifier = '<' then value else null end)) from chem group by element 	0
10326027	10426	mysql stored procedure: if in where	select column from table where a = a1 and (b = b1 or (b != b1 and (b = b2 or (b != b2 and b = b3)))) 	0.775976930842182
10326324	34185	getting a singular projection from a select query with multiple attributes	select top 1 email_id from update_winnerslist  where item_index = 10 order by bid_amount desc 	0.0105981471510097
10326462	30941	sql and php: find all "assets" connected to "presentation"	select a.id, a.name from asset a  join presentationasset pa on pa.assetid = a.id and pa.presentationid = 3 join presentation p on p.id = pa.presentationid 	0.00290257048749373
10326708	17289	sql/coldfusion display duplicated row	select max(productid) as productid, upc from products group by upc having count(upc) > 1 	0.000549557955119097
10327192	3905	pl/sql reg exp found last number and split	select test     ,regexp_replace(test, '(.*[[:digit:]].)(.*)', '\1') c1     ,regexp_replace(test, '(.*[[:digit:]].)(.*)', '\2') c2 from (     select '1234john4345 this is a test.' test from dual union all     select '1234john4345a this is a test' test from dual ); 	0.000324266877080659
10327252	39770	partitioning related rows into groups	select orderid,        sku,        type,        row_id,        (row_number() over(partition by type order by row_id) - 1) %         case type           when 'single' then 1           when 'double' then 2           when 'triple' then 3         end + 1 from yourtable order by row_id 	0.000620548799713969
10327448	13295	sql - sum two rows of data while still showing the rest of the rows	select id, sum(sales) from table where id in (100,500) union all select id, sales from table where id not in (100,500) 	0
10327746	4433	returning id from insert query in c#	select @@identity 	0.0204083802506512
10327895	23265	how should i collapse two tables into one on select?	select table1.*, ifnull(table2.extra_info, 'defaultvalue') as extra_info from table1 left outer join table2 on table1.id = table2.id 	0.00122425912563705
10328937	14397	how to sum accounts by account code length?	select   f.timekey,   s.accountkey,   sum(f.debit) as debit,   sum(f.credit) as credit from dimaccounts s   inner join dimaccounts b on b.accountcode like s.accountcode + '%'   inner join factbudget  f on f.accountkey = b.accountkey where s.accounttype = 's'   and b.accounttype = 'b' group by   f.timekey,   s.accountkey 	0.022653328523608
10329021	25841	how to get a datetime interval as seconds (int)?	select [session_id],datediff(ss,[start],[end]) as 'duration' from @sessions 	0.000542522706932399
10329608	1654	how to extract the last comment from each profile?	select c.*  from comment c join    (select max(created_at) created_at, profile from comment    group by profile) p on p.profile = c.profile and p.created_at = c.created_at order by c.created desc , p.profile asc  limit 100 	0
10333015	8463	tsql selecting unique value from multiple ranges in a column	select distinct a.start_time, a.end_time, b.error_code from b inner join a on b.timestamp between a.start_time and a.end_time 	0
10333041	5409	reformatting mysql table as grid	select token, group_concat(concat(iso,'|',content)) as contents from translations group by token 	0.280699493296427
10336692	10776	sql searching for specific value within a string	select table_name      , column_name   from user_tab_columns  where regexp_like (column_name, '(^|(_)+)ing((_)+|$)') 	0.00432656980407048
10336969	40972	sql: combine four "where" clauses on the same table	select       y,       sum( iif( c = 'denmark', n, 0 )) as sumdenmark,       sum( iif( c = 'finland', n, 0 )) as sumfinland,       sum( iif( c = 'norway', n, 0 )) as sumnorway,       sum( iif( c = 'sweden', n, 0 )) as sumsweden,       sum( n ) totalsumvalue,       count(*) totalentries    from        stat    where       c in ( 'denmark', 'finland', 'norway', 'sweden' )   group by        y 	0.00129401464192217
10337644	14640	how to join two tables based on certain conditions being met?	select  sample_id from    samples where   status = 'pending'         and member_id <> $someuserid         and sample_id not in         (         select  sample_id         from    votes         where   member_id = $someuserid         ) 	0
10339107	4764	mysql: in list of rows find a proper row using given value	select * from discounts where 27 between count_from and count_to select * from discounts where 33 between count_from and count_to 	0
10340118	11598	declare set from the same table in sql 2005	select     a.*,     b.firstname as managerfirstname from     salesrep_info a     left join salesrep_info b on a.managerid = b.repid 	0.00256590189699226
10340616	41128	getting all cities related to a zipcode	select distinct concat(city, ', ', state) as location, city, state, group_concat(zip separator '|') as zip_codes  from civic_zip_code  group by concat(city, ', ', state),city 	0.00163875814194259
10340754	28770	sql server - using join to show only entries from second table	select tbl1.r_time, tbl1.q1 from table1 tbl1 inner join table2 tbl2 on tbl2.id = tbl1.id where tbl2.supervisor = 3 	0
10344104	11470	mix count and exist in one query	select  count(orderid),         case             when exists(select id from tbtest where customerid = {n}) then 'exist'               else 'not exist'         end from tbtest 	0.127814803713865
10344786	25875	sqlite query, compare datetime field with current  date time	select task_datetime from tasks where task_datatime < current_time 	6.17207994171822e-05
10344923	16107	mysql left join returns unexpected amount of rows	select    ( select count(*) from table1 where.... ) + ( select count(*) from table2 where.... ) as total from dual 	0.0765146199056783
10345713	12329	how to get excel to treat a date as a date not a string when doing copyfromrecordset	select cast(date_text as date) from testexceldates; 	0.0116965508493596
10347033	26147	how to select all rows where mycolumn is an integer value?	select * from mytable where mycolumn regexp '^[0-9]+$' 	0.000553181561425241
10347552	20876	how to avoid distinct	select       user_id,       count(*) as orders    from       orders    group by       user_id 	0.277272766728553
10348069	6601	sql converting a text field to other text	select case <fieldname> when  'sterling'  then 'gbp' when 'euros' then 'eur' end from <tablename> 	0.0273122847895402
10349612	24743	how do i retrieve two values from the same column based on two different conditions in mysql?	select     route.route_id,     fromstation.name,     tostation.name from     route     left join stations as fromstation         on route.route_from =fromstation.station_id     left join stations as tostation         on route.route_to  =tostation.station_id where      route.route_id = 1; 	0
10350075	30045	mysql - search field for unordered text	select name from your_table where      type rlike '^a+$'                               or type rlike '^((a[ac]*c)|(c[ac]*a))[ac]*$'       or type rlike 'b'                                  or type rlike '(a.*c)|(c.*a)'                    ; 	0.0878729641311908
10350548	10040	comparing  two rows within two separate tables	select item_id, can_be_returned from purchases p join items using (item_id) where purchase_id = 42 	0
10352800	1563	sum a field for each month cummulatively and dynamically	select t1.id, t1.singlenum, sum(t2.singlenum) as sum      from @t t1 inner join @t t2 on t1.id >= t2.id     group by t1.id, t1.singlenum     order by t1.id 	0
10353405	24151	how to return last inserted (auto incremented) row id in hsql?	select top 1 id from [tablename] order by id desc 	0
10353436	14255	mysql: limiting number of results received based on a column value | combining queries	select * from (     select *, @num := if(@some_id = some_id, @num := @num + 1, 1) as row_num,            @some_id := some_id as some_id     from example     order by last_modified desc ) as e where row_num <= 5 	0
10353813	21897	mysql - retrieve row value from different table depending on value of row in a table	select mem.*, g.*, coalesce(m.male_build, f.female_build) as build from members_table mem inner join general g on mem.meber_id = g.member_id left join males m on mem.member_id = m.member_id left join females f on mem.member_id = f.member_id 	0
10354600	13735	oracle generate list of iw week dates	select trunc(sysdate - (level * 7), 'iw') thedate       from dual    connect by level <= 7 	0.000111557096246576
10357410	26419	any way to identify which rows were generated by which conditions in where clause	select p.col1, p.col2, p.col3,      t.dep = 'cle' or t.arr = 'cle' as first_condition,      p.lat > 34 and p.lat < 40 and p.lon > -100 and p.lon < -90 as second_condition from position as p  join trip_table t on (t.tripid = p.tripid) where (t.dep = 'cle' or t.arr = 'cle') or (p.lat > 34 and p.lat < 40 and p.lon > -100 and p.lon < -90) 	0.00438485718089882
10357658	27464	sql query yield distinct by one column	select min(dataid) dataid, ted_id from (     select         llattrdata.id dataid,         max(case when llattrdata.attrid = 2 then llattrdata.valstr end) ted_id     from llattrdata     join dtree on llattrdata.id = dtree.dataid     where llattrdata.defid = 19400074     and llattrdata.vernum = dtree.versionnum     group by llattrdata.id ) t1 group by ted_id 	0.0752823878867614
10358078	34000	sql & php query with union	select i.invoiceid as transactionid, i.date, i.total,  i.total - (select ifnull(sum(p.amount), 0) from payment p where p.invoice = i.invoiceid) as remainingbalance, 'invoice' as transaction_type         from invoice i inner join client c         on i.client = c.clientid         where i.isdeleted = 0 and i.client = 1         union select p.paymentid as transactionid, p.date, p.invoice, p.amount, 'payment' as transaction_type         from payment p inner join invoice i         on i.invoiceid = p.invoice         inner join paymenttype         on paymenttype.paymenttypeid = p.paymenttypeid         inner join client c         on c.clientid = i.client         where c.clientid = 1         and i.isdeleted = 0         order by date 	0.793199815313106
10359546	27947	don't return any result if the precedent query has at least 1 result?	select t1.*     from        ( select if( count(*) > 0, 1, 2 ) includetype            from tbl t2            where t2.type = 1 ) precheck,       tbl t1    where        t1.type = precheck.includetype 	0.00021081537661311
10359903	20825	oracle sql - find common items purchased between two users	select item.id, item.name from item, purchaselog p, user u where lower(u.username) = lower('username1') and p.user_id = u.user_id and item.id = p.itemid and p.purchasedate between sysdate and sysdate-365 intersect select item.id, item.name from item, purchaselog p, user u where lower(u.username) = lower('username2') and p.user_id = u.user_id and item.id = p.itemid and p.purchasedate between sysdate and sysdate-365 	0
10364336	7005	how do i get query output as text in the pgadmin v1.14.2 query tool?	select t::text from tbl t; 	0.0838801402534062
10365553	30582	mysql subquery to gather grouped subset with limits	select       u.*,       @lastseq := if( @lastip = u.ip, @lastseq +1, 1 ) as ipsequence,       @lastip := u.ip as carryfornextrecord    from        ( select @lastip := '', @lastseq := 0 ) sqlvars,       users u    order by       u.ip,       u.time desc    having        ipsequence <= 2000 	0.627521450633411
10367229	11171	sql query for nested records	select t1.id, t1.type     , concat( coalesce( concat(cast(t4.id as char(10)),','),'')         , coalesce( concat(cast(t3.id as char(10)),','),'')         , coalesce( concat(cast(t2.id as char(10)),','),''))         as hierarchy from exampletable as t1     left join exampletable as t2         on t2.id = t1.parentid     left join exampletable as t3         on t3.id = t2.parentid     left join exampletable as t4         on t4.id = t3.parentid 	0.390121160831361
10367247	280	a tricky sql statement using 3 tables with a status check	select u.userid, u.holidaysallowed, u.holidaysallowed -  coalesce(      (select sum( datediff( h1.dateto, h1.datefrom) + 1)           from holiday h1           inner join status s1          on s1.holidayid = h1.holidayid          where h1.userid = u.userid          and s1.statusid = 1      ), 0) as holidaysleft, coalesce(      (select sum( datediff( h2.dateto, h2.datefrom) + 1)           from holiday h2           inner join status s2          on s2.holidayid = h2.holidayid          where h2.userid = u.userid          and s2.statusid = 1      ), 0) as holidaystaken from usersettings u ; 	0.259772880146761
10369284	23881	postgresql lowercase to compare data	select lower(name) from user_names  where name ilike '%$search%' order by name asc 	0.0295082934427999
10370105	37119	mysql query check date	select * from rooms where (checkin is not between user_entered_checkin and user_entered_checkout)   and (checkout is not between user_entered_checkin and user_entered_checkout) 	0.0775335023775932
10371306	24251	best way to find the last inserted id in mysql using php	select last_insert_id() 	0
10371365	28733	getting grand totals using group by	select      sum(dbo.tbl_orderitems.mon_orditems_pprice) as prodtotal,     avg(dbo.tbl_orderitems.mon_orditems_pprice) as avgprice,     count(dbo.tbl_orderitems.uid_orditems_prodid) as prodqty,     dbo.tbl_orderitems.txt_orditems_pname from      dbo.tbl_orderitems inner join      dbo.tbl_orders on (dbo.tbl_orderitems.uid_orditems_orderid = dbo.tbl_orders.uid_orders) where      dbo.tbl_orders.uid_order_webid = <cfqueryparam cfsqltype="cf_sql_integer" value="#session.webid#">     and dbo.tbl_orders.txt_order_status = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.sale_status#"> group by     dbo.tbl_orderitems.txt_orditems_pname with rollup 	0.073901097540297
10371448	37498	how to get count of records added since the start of the current month	select count(*) from ws_account_log where       account_log_account_id='1'   and account_log_timestamp >= subdate(curdate(), dayofmonth(curdate())-1) 	0
10371589	27893	sql: get last 3 posts of each theme	select * from ( select if(@prev != sq.theme, @rownum:=1, @rownum:=@rownum + 1) as rownumber, @prev:=sq.theme, sq.* from (     select     *     from     posts     , (select @rownum:=0, @prev:=0) r      order by theme, created desc ) sq ) q where q.rownumber <= 3 	0
10372563	24022	how can i fetch records from two tables along with count?	select o.p_id, count( o.p_id ) as p_id_count, p.p_name, p.p_price, p.p_image_path from orderitem o inner join products p on o.p_id = p.p_id group by o.p_id order by p_id_count 	0
10372657	31377	calcutate membership duration, until now or until end date	select datediff(ifnull(member_until_date, now()), member_since_date) as days_member from ... 	0.000406545391358241
10372728	26310	how to query across three tables joined by an intermediate table?	select c.*, p.*  from categories c inner join project_category pc on pc.category_id = c.id inner join projects p on pc.project_id = p.id 	0.00559068353734198
10372885	33129	how do i check values across multiple tables having same design?	select id, topic, date from (     select id, topic, date from table1     union all      select id, topic, date  from table1 ) t1 where datediff(date, date(now())) <= 7 	0.000521006604152349
10372982	24694	sql/coldfusion select rows with duplicate field	select    p1.productid, p1.display, p1.upc from   products as p1, products as p2 where   p1.upc=p2.upc and p1.display=0 and p2.display=1; 	0.00122410793211827
10373234	2835	nested mysql group by month, year	select month(p.created_at) as month,        year(p.create_at) as year,        sum(if(ci.item_id = 8, 1, 0)) as new,        sum(if(ci.item_id = 13, 1, 0)) as renewal   from payments p,        inner join carts c on c.payment_id = p.id        inner join cart_items ci on ci.cart_id = c.id  where ci.item_id in (8,13)  group by month, year; 	0.00907641125912562
10373369	24687	how to add extra atrributes in a for xml path statement	select     id as '@id',     title,     duration,     'true' as 'instructionalmethod/@primary',     instructionalmethod    from      dbo.mytable for xml path ('event'), root('events'), type 	0.285004391077408
10374367	13231	how to check if the value already exists in android sqlite database?	select count(*) from tbl_user where meeting_date like ' + my_date' and name = ' + edittextname.gettext() + ' 	0.00143458589460563
10377418	1290	need to select the non-duplicate values from two table columns	select `city_name`  from `first_table` where `city_name` not in (select `city_name` from `second_table`) 	0
10377781	21282	return boolean value on sql select statement	select case when exists (     select *     from [user]     where userid = 20070022 ) then cast(1 as bit) else cast(0 as bit) end 	0.0614111527293585
10379053	2657	php variable variables with mysql resultset	select sid, count(*) from `table` where userid = 44 group by sid ; 	0.421095270747269
10379533	11767	select query in sql server 2005	select whatever from your_table where       your_column like '7,%' or       your_column like '%,7,% or       your_column like '%,7' 	0.756618360970101
10380741	39029	sql server query, running total in view, reset when column a changes	select 'cat a' as class,10 as value into #x union all select 'cat a',20  union all select 'cat a',30  union all select 'cat b',15  union all select 'cat b',15  union all select 'cat c',10  union all select 'cat c',10  ;with running_total as ( select * ,row_number() over (partition by class order by value asc) as row  from #x  ) select  r1.class ,max(r1.value) as value ,sum(r2.value) as running_total from running_total r1 left outer join running_total r2 on r2.class = r1.class                 and r2.row <= r1.row group by  r1.class ,r1.row 	0.0257937128250998
10380990	38444	sql - how to group by on two fields and count	select a, b, count(a) from tbl group by a, b 	0.00435875144026961
10381592	39874	sql select query output with specific format	select id, server_name, substring(domain_name, 1, charindex('.', domain_name) - 1) from mastertable 	0.182915648307713
10382768	39167	how do i narrow down the distinct rows based on column filters?	select transactioncode,         idkey from   (     select transactioncode,             idkey,            row_number() over(partition by transactioncode                               order by actiondate desc) as rn     from transtable      where transactioncode in (1,2,3) and            actiondate < getdate()    ) t where rn = 1 	8.7881220845361e-05
10382915	17698	t-sql: finding the closest location of an object on a map grid	select min(abs(s.latitude - 47) + abs(s.longitude - -122)), s.id from sites as s group by id; 	0.000786798214339783
10383229	31734	multiple count from multiple tables	select   count(users.users)    users,   (select      count(users_types.users_types)    from teams)    userstypes from users 	0.00423039118137781
10383873	25045	mysql return single result from single table with complex condition	select coalesce(    max(field1),    (select coalesce(max(field1),0)+1 from table)    )  from table where field2=? and field3=? and field1<>0; 	0.00412883411822759
10384028	40319	i want to show relational data, when theres data missing in a mysql query	select u.user_email  ,       um1.value as school ,       um.value as postcode from `wp_users` as u left join `wp_bp_xprofile_data` as um   on u.id = um.user_id   and um.field_id = 322 left join `wp_bp_xprofile_data` as um1   on u.id = um1.user_id   and um1.field_id = 69 	0.012657167666702
10384253	1271	order by time starting at?	select *   from table  where date = 2012-04-29  order by case when hour(time) < 6 then 1 else 0 end, time; 	0.00511356529183602
10386026	20616	t-sql: conditionally joining using a parameter	select td.* from tablea ta join (     select tc.* from tablec where @usetablec = 1     union all     select tb.* from tableb where @usetablec = 0 ) td on ( ) 	0.418950486297716
10387047	40825	mysql select query grouping by wildcards	select case when game like '%rift%'      then 'rift   '             when game like '%swiftsure%' then 'swiftsure'        end as groupname,        count(*) as  postcount    from       forums    where          game like '%rift%'        or game like '%swiftsure%'     group by       groupname 	0.76487906416642
10387118	5116	sql query: how to create a 'sessions' column	select  yt.id ,       yt.name ,       yt.visitcounter ,       count(prev.id) as session from    yourtable yt join    yourtable prev on      prev.id <= yt.id and         prev.visitcounter = 1 group by         yt.id ,       yt.name ,       yt.visitcounter order by          yt.id 	0.0937345035883698
10387556	39149	getting the average price of products in a category	select avg(product_price) from products where products_id in (select products_id from products_to_categories where categories_id = x) 	0
10387956	19406	sql duplicate field	select    productid,           title,           upc,           display from      products where     upc in(                      select   upc                      from     products                      where    display = 1                      group by upc                      having   count(upc) > 1                 ) and       display = 1 	0.020498163805678
10388262	30385	mysql stored function - append string	select group_concat(meta_option separator ',') from offer_metas where category = searchcat and offer_id = searchprod; 	0.609447173134804
10389684	15745	possible to get an early exit on a distinct sqlite query?	select distinct column1,column2 from table where column3='some value' limit 20 	0.0447360419765182
10391054	34265	sql - check for uniqueness of composite key	select order_id, product_id, count(*) as x from temp_order group by order_id, product_id having x > 1 	0.0475341008776064
10392197	16769	count(), group by and null values in a mysql query	select p.product_id, p.product_name, p.sales,     p.length, p.hits, count(w.product_id) as favorites     from `products` as p     left join `products_mf_xref` as m         on p.product_id = m.product_id and m.manufacturer_id = '1'     left join `wishlist_items`  as w on m.product_id = w.product_id   group by m.product_id order by p.product_id asc 	0.0623878728085775
10393577	14900	query adding and multiplying values	select      int_id,     died - born as age_died,     3 * (died - born) as age_died_tripled from my_table where died > 0; 	0.0307022196321231
10395744	27419	unnesting a table in oracle 10g	select rec.*   from actor_quotes a,table(a.quotes) rec 	0.506766866822561
10396024	20275	comparison with more than one value in sql	select secondtable.* from secondtable  inner join firsttable on (firsttable.id = secondtable.id) where firsttable.somefield = 'something else' 	0.026896359937184
10396043	39185	illegalargumentexception when trying to get objects from oracle database with jpa	select moduleconnection from moduleconnection as moduleconnection  where moduleconnection.parentmodule.id = :parentmoduleid 	0.121692452910905
10396418	39915	return n results for different groups with additional condition oracle sql	select *  from(     select id,             team,            auditor,            row_number() over (partition by auditor order by rank1) as rank       from (select id,                     team,                     auditor,                     row_number() over (partition by auditor, team order by id) rank1                from table)        ) where rank <= 3; 	0.00228887727668836
10396875	160	mysql sum() with count() on multiple columns	select   concat_ws(' ', parent_title, parent_fname, parent_sname) as 'parent name',   count(distinct student_id) as 'number of students',   count(distinct student_id, class_id) as 'number of classes' from        parent   join student  using (parent_id)   join rollcall using (student_id)   join class    using (class_id) group by parent_id; 	0.00753235334772242
10400755	24088	how do i truncate a field and append "..." to it?	select case             when (len(table1.longtext) < 100) then table1.longtext            else substring(table1.longtext,1, 97) + '...'        end as [description] from table1; 	0.015481784103424
10401393	3977	remove reversal pairs using sql	select sum(qty) as newqty, date, fuel_type from fuel_transactions group by date, fuel_type 	0.0628548740773525
10402463	31911	database table with field of type date not allowed in sql server 2008 r2?	select @@version; 	0.478001770380082
10402480	21678	how do i write a query that bridges two tables?	select      e,g,h from      tablea      inner join tableb          on b = f 	0.0732932196439995
10403132	32136	mysql select with max getting wrong id?	select id, max(amount) as value from bids group by id 	0.13205030668463
10404958	594	mysql max query not returning latest record on join	select        a.*,       pfinal.thumbnailphotopath as picture     from        album_access ac           inner join albums a             on ac.albumid = a.id            and a.private = 1          left join ( select                            p.albumid,                            max( p.dateuploaded ) as maxdate                         from                            photos p                         where                                p.isprocessed = 1                            and p.isprivate = 0                         group by                             p.albumid ) pmax             on ac.albumid = pmax.albumid                 left join photos pfinal                   on pmax.albumid = pfinal.albumid                  and pmax.maxdate = pfinal.dateupladed    where            ac.accessuserid = ?        and ac.ispending = 0        and ac.fullcontrol = 1     order by        a.datecreated desc     limit ?,?; 	0.00758234440094787
10405323	30627	mysql statement select where a column is not a number	select id, area, city from `homes` where (abs(area) = 0 and area != '0') or (abs(city) = 0 and city != '0') 	0.0974252788309442
10406448	27929	saving a table to an xml file	select col1, col2, col3 etc.   from dbo.tablename   for xml auto, elements; 	0.0906384796726246
10406910	538	mysql: how to get distinct numbers in this way?	select [distinct] mac from table t where  t.time between '2012-01-09 00:00:00' and '2012-01-16 23:59:59' and  not exists (select * from from table t2 where t2.mac = t.mac and t2.time between '2012-01-01 00:00:00' and '2012-01-08 23:59:59' 	0.028100448280765
10407415	5710	how to fetch values of column 1 that contain only the given value of column 2?	select name from <table> where country = 'mexico' and name not in (     select name     from <table>     where country <> 'mexico') 	0
10409056	31132	sql query database	select name, marks,  case when marks >= 85 then 'a' else 'b' end as grades from your_table 	0.443870854695203
10410966	38448	mysql trasnposing rows to columns	select tr.tr_id_pk, abundance, life_stage    from taxon_record as tr   left join (     select rad.tr_id_fk, rad.rad_value as abundance     from       record_attribute_data ra join record_attribute rad         on rad.ra_id_fk = ra.ra_id_pk     where ra.ra_name = 'abundance'   ) as tabundance on tabundance.tr_id_fk = tr.tr_id_pk   left join (     select rad.tr_id_fk, rad.rad_value as life_stage     from       record_attribute_data ra join record_attribute rad         on rad.ra_id_fk = ra.ra_id_pk     where ra.ra_name = 'life_stage'   ) as tlife_stage on tlife_stage.tr_id_fk = tr.tr_id_pk 	0.00497857750624164
10411834	14011	mysql - how to get the highest value of each record?	select id, score, date from   table1 t1 where  date=(select max(t2.date)               from table1 t2               where t1.id = t2.id); 	0
10411938	28407	appending different values from same column with each other	select [subject], stuff((select ', ' + [body] from ccsemails t2 where t1.[subject] = t2.[subject] order by [body] for xml path('')),1,1,'') as [body] from ccsemails t1 group by [subject] 	0
10412068	39175	mysql count with empty column	select     count(case when id_connect='' then 1 end)   + count(distinct nullif(id_connect, '')) from tb1 	0.0797086890927233
10414666	16822	search through grid view that can take closely matching data	select jobno, accountname, city from table_1 where jobno = @jobno and accountname like @accountname + '%' 	0.00473607952702055
10415257	4233	join two tables with not exactly matching dates in sql	select endofmonth.*, begofmonth.*  from endofmonth join begofmonth  on dateadd (dd , 1 , endofmonth.date ) = begofmonth.date 	0.00525714340099266
10416436	4537	filtering results in two tables	select id_delivery_note, number_delivery_note, date, x.id_product, x.price, qty_delivered from delivery_note d inner join product_price x on x.id_product = d.id_product and d.client_code = x.client_code where d.client_code = 1 and d.invoiced = 0 group by id_product 	0.0200274875805936
10416471	20708	how to count rows in mysql query?	select * from people_history order by id desc limit 10 	0.024239820157083
10417541	8477	what is the correct way to join two tables in sql?	select userdata.text, userdata.image, follows.userfollow   from userdata   left join follows on follows.userfollow = userdata.username   where follows.userid = $username 	0.540148430159947
10417872	16689	t-sql: conditional sorting on two columns	select t.cola, t.colb from t order by t.cola    ,case when t.cola = 0 then t.colb end asc    ,case when t.cola = 1 then t.colb end desc 	0.0437965773444595
10419109	21957	discover last insert id of autoincrement column in mysql	select id from table order by id desc limit 1; 	6.19220537174176e-05
10419777	36145	calculate (next day) date for messages posted after 16:00	select count(msg_id), if(_time >= '16:00:00', _date + interval 1 day, _date) as effective_date from yourtable group by effective_date 	0
10421017	37553	t-sql: select rows not equal to a value, including nulls	select top 30 col1, col2, ..., coln from mails where (assignedbyteam <> 'team01' or assignedbyteam is null) 	0.00383165588517066
10421441	26144	use daterange table to also return empty resultset	select user_id, d_date,        count(case when messages.m_date = d.d_date then 1 end) volume from messages cross join datetable d group by messages.user_id, d.d_date order by messages.user_id, d.d_date asc 	0.00571452905611405
10422796	3739	mysql query the sum of values based off int_id	select int_id, sum(prize) as total_money from tablename group by int_id 	0.000243825045689262
10423748	32768	sql get change in values based on consecutive dates, grouped by a value	select t1.price-t2.price from table t1 inner join table t2 on date_add(t1.date,interval 1 day) =t2.date          and t1.company=t2.company 	0
10424177	13716	count column and then group two columns in sql	select userid, count(distinct ip) as ipcount   from yourtable  group by userid 	0.0005805972749348
10424192	40019	how do i fetch the count from ms access tables using group by clause?	select      a.acountry         ,   r.result_placing         ,   sum(*) as cnt  from        athletes        a  right join  result_placing  r  on          a.anumber       = r.anumber  group by    a.acountry         ,   r.result_placing  order by    a.acountry 	0.0268911755740754
10424900	29983	sql query for finding a value appearing more than once	select * from `entry table` where placed <= 3 group by driver_id  having count(*) > 1 	0.000424759135152153
10425531	29316	sql get count of users who participated in a survey	select stab.name, count(si.id) from surveytable as stab inner join surveyinfo si on si.surveyid = stab.surveyid group by stab.name 	0.000131400152095783
10425813	17961	only update the sql fields if the fields are true	select count(1) from notifications (nolock) where user_id=123 and unseen=1 	0.000206551052037443
10429057	24938	count distinct rows via a pair of known values	select      ms.master_content_id,     (select count(distinct f.user_id) from flagged f where                       f.content_id = ms.slave_content_id or                       f.content_id = ms.master_content_id) from     master_slave ms 	0
10429174	23388	display data in gridview according to priority	select id, priority, txt from table order by priority asc, id desc 	0.000234682450979865
10429509	12667	sorting database columns according to time in android?	select * from persons order by lastname desc select * from persons order by lastname asc 	0.00274092239825438
10429555	30022	sql query with sum on column in joined table	select  app.orders.id, app.orders.userid, app.orders.purchasedate, app.orders.totalprice, sum(app.orderitems.quantity)  as productcount from app.orders join app.orderitems on app.orders.id=app.orderitems.orderid  group by app.orders.id, app.orders.userid, app.orders.purchasedate, app.orders.totalprice 	0.0113351993729327
10429725	30070	sql, matching all the values in column b and return column a for those matches	select cola  from your_table where colb in(1, 3) group by cola having count(cola) > 1 	0
10429945	26846	grouping similar names together in mysql as unique record	select     sum(t.price) as price,     t.name from (     select         price,         (             case when name like 'hello ap%'             then 'hello apts'             else name         ) as name     from         table1 ) as t group by     t.name 	0.000285133066267348
10430335	28690	sql query to find absent tables from database	select a.table_name from (select 'a' as table_name                 from dual union                select 'b' as table_name                 from dual union                select 'c' as table_name                 from dual union                select 'v' as table_name                 from dual union                select 'h' as table_name                 from dual) a where not exists ( select 1 from dba_tables b where b.table_name=a.table_name) 	0.0022091527151493
10430395	35165	translating a query from oracle into tsql	select *  from my_table p  where user_id = 167  and not exists (     select         null     from         exclusion_table     where         exclusion_table.field1=p.field1         and exclusion_table.field2=p.field2         and exclusion_table.field3=p.field3 ) 	0.404334654811553
10430725	28597	aggregate column containing different values into one	select min(type) as type,        load,        sum(total) as total from t group by load 	0.00015927224387463
10432694	30100	how do i group by generic field?	select case when status <> 'success'               and status <> 'running'              then 'failure'              else status          end status,         count (*) [count] from atable group by case when status <> 'success'                 and status <> 'running'                then 'failure'                else status            end 	0.267048736110709
10432734	28829	derby sql using scalar subqueries and order by and fetch next to limit result to one	select * from cows where lastmilkeddate =  (select max(milkdate) from lactaction where cowid=55) 	0.0450683825573152
10435876	5206	select sql with 2 table	select * from user u join user_authenticate ua     on u.user_id = ua.user_id  where u.user_name = 'yourusername'     or u.email = 'yourname@email.com' 	0.0368987607297506
10438241	11306	how to alter all columns without specifying column_name?	select 'alter table ' + table_name + ' alter column '+ column_name +' ' + data_type +  (case    when character_maximum_length is not null and character_maximum_length <> -1 then ' (' + cast(character_maximum_length as varchar) +')'    when character_maximum_length = -1 then '(max)'   else '' end)  + ' null;'  from tempdb.information_schema.columns where table_name = '<your table name>' and is_nullable='no'; 	0.00213702004920934
10439365	31282	merging two tables in sql server	select    one.matchingcolum,    one.oddcolum,    two.evencolumn from one join two on one.matchingcolumn = two.matchingcolumn 	0.0111605821651954
10439836	12814	mysql select repeatable fields into columns	select    o.asset_id,    `5`.title as title_type_5,   `4`.title as title_type_4,   `3`.title as title_type_3 from    foo o left join foo `3` on `3`.title_type = 3 and `3`.asset_id = o.asset_id left join foo `4` on `4`.title_type = 4 and `4`.asset_id = o.asset_id left join foo `5` on `5`.title_type = 5 and `5`.asset_id = o.asset_id where    o.title_type = "4"    and o.title = "blsh" 	0.0028887559261474
10442271	2098	mysql - joins - too many rows are being returned - one for each of the joined table but dont want that	select  tbl_users.*,  tbl_photos.filename  from tbl_users  left join tbl_photos on tbl_photos.user_id = tbl_users.id  where tbl_users = approved order by rand() limit 1 	0
10442310	17409	how can i stop joins from adding rows in my match query?	select     e.*,      match.id,      match.signdate,      ... from        pofdexpectation e  outer apply (     select  top 1         min(id) as matchid,          min(signdate) as matchsigndate,          count(*) as matchcount,          ...     from    form f     where   form.[match criteria] = expectation.[match criteria]      group by id (matching criteria columns)        ) match 	0.167612727385843
10443512	25091	how to make mysql answer in only one line	select  group_concat(name order by id separator ';') from    test_table where   level = 1 	0.00343049461006699
10446424	38216	get child records on one column	select p.id,        p.name,        stuff((select ','+cast(s.id as varchar(10))               from son s               where s.parentid = p.id               for xml path('')), 1, 1, '') allmysons from parent p 	0
10446431	15629	add a counter to a select query's results	select row_number() over (order by your_column), *  from your_table 	0.0597950893058088
10448462	17460	get value from database if two rows exist and value is equal to	select `status` from `notes` where `custom` = '$custom' and `createdtime` > (current_date - interval 3 day); 	0
10448742	38916	how do i get the last four weeks including current week using an sql query	select count( distinct ip ) as uni, (      date_added     ) as wday, from_unixtime( date_added ) as cusotms     from `site_stats`      where from_unixtime( date_added ) >= curdate( ) - interval dayofweek( curdate( ) ) -3week     group by week( from_unixtime( date_added ) )      limit 0 , 30 	0
10450768	36852	multiple mysql queries with different tables in one	select s.userid as user  from stats s left join logs l on (l.attacked = s.userid) where ($attack + $bonus) > (s.defense + s.bonus)      and l.attacker = $id     and l.date > $time - 86400 order by s.gold desc limit 1 	0.00371437623792844
10450799	8526	mysql join query for users with 0 assigned records	select `user.id`, `user.admin`, `user.active`, `user.name`, `user.email`, `user.last`,     (select count(*) from voter where `user.id` = voter.owner) from `user`  where user.cid = '$cid' order by `user.id` asc 	0.0269446311685859
10450818	24078	find top 3 values with an inner join	select sum(price) as sumoftopvalues from users_preferred_zips where username in (   select username   from users   where pref_acct_balance >= 5 ) 	0.0275643370000527
10452975	25491	using mysql, what is the best way to not to select users that exist in a different table?	select    concat (p.firstname, " ", p.lastname) as manager    , p.hash from  persons p    left join teams t on p.hash = t.leader where    p.role_id = 2    and t.id is null  	0.00316112110162781
10453332	34681	mysql/php highest values of two fields: two queries needed?	select max(score), max(whenadded) from scores 	0.000113964436678527
10453890	5331	how to get next 4 digit number from table (contains 3,4, 5 & 6, digit long numbers)	select min([number]) as next_number from  linenumbersnotused where         [number] > 999     and [number] < 10000; 	0
10454179	9340	select parts of one table and count rows of another	select     people.person_id,     people.name,     count(connections.person_id) as number_of_connections from people left join connections on people.person_id = connections.person_id  group by people.person_id 	0
10454196	4733	get day of the week from stored datetime	select datename(weekday,dob)  from mytable 	0
10455073	3394	mysql result row to string, union	select name as client,  case      when debt = 0 then 'not debtor'     when debt between 1 and 1000 then 'low debtor'     else 'medium debtor' end as debt from tblclients 	0.0239303104750759
10455233	38627	distinct by order date and products sql server 2008	select           products.productid          sum(orderdetails.orderdetailquantity) as totalordered, from orders  inner join orderdetails on orders.orderid = orderdetails.orderid  inner join products on orderdetails.productid = products.productid  where orders.orderdate between cast(@from as date) and cast(@to as date) group  by               products.productid  declare @from datetime = '1/1/2000 10:30:22',         @to datetime = '1/3/2000 9:11:31' declare @orders table (i int, dt datetime) insert into @orders     values(1, '1/1/2000 8:00'),(2, '1/2/2000 10:00'), (3, '1/4/2000 3:00') select * from    @orders where dt between @from and @to select * from    @orders where dt between cast(@from as date) and cast(@to as date) 	0.0520604894810482
10458534	21063	how i can derive count(*) from another table using left join mysql	select p.*,         totalreview,         totalfavorite,         totalphoto  from   place p         left outer join (select placeid,                                 count(*) as totalreview                          from   review                          group  by placeid) r                      on p.placeid = r.placeid         left outer join (select placeid,                                 count(*) as totalfavorite                          from   favorite                          group  by placeid) f                      on p.placeid = f.placeid         left outer join (select placeid,                                 count(*) as totalphoto                          from   photo                          group  by placeid) ph                      on p.placeid = ph.placeid 	0.0146422331958846
10458770	37391	combine two mysql count(*) results, different columns	select      case when sender = '$userid' then recipient else sender end as otheruser,      sum(sender = '$userid') as rcount,      sum(recipient = '$userid') as scount,      count(*) total from      privatemessages  where      '$userid' in (sender , recipient ) group by      otheruser 	0.000140236795232313
10459588	32953	mysql select statement based on hour, day, month, year	select      t.id,      date_format(t.time_stamp, "%y-%m-%d") as time_stamp,      (select `value` from table_name where time_stamp between date_format(t.time_stamp, "%y-%m-%d 00:00:00") and date_format(t.time_stamp, "%y-%m-%d 23:59:59") order by id asc limit 1) as start_value,     (select `value` from table_name where time_stamp between date_format(t.time_stamp, "%y-%m-%d 00:00:00") and date_format(t.time_stamp, "%y-%m-%d 23:59:59") order by id desc limit 1) as end_value from table_name t  group by date_format(t.time_stamp, "%y-%m-%d") 	0
10459805	20360	how to group by in left join	select      patient_master.pid,      patient_master.patient_id,     patient_master.patient_name,     patient_master.sex,     patient_master.patients_birth_date,     patient_last_visit.visit_date  from      patient_master    left join     ( select            pid,           max(visit_date) as visit_date       from           patient_visit       group by           pid      ) as patient_last_visit         on patient_master.pid = patient_last_visit.pid  order by      patient_master.patient_name 	0.744433654958634
10460904	37971	sql multiple row merge into single row with specific pattern	select a.name,a.task_date, b.tasklist from tb_master a outer apply (   select stuff ((select ' , '                       + convert(varchar(10), row_number()                                                     over(order by id desc))                       + ') '                        + tasks                     from tb_tasks b                   where a.id = b.id_tbmaster                   order by id desc                 for xml path (''))                , 1, 3, '') tasklist ) b 	0
10460992	2921	sql: select sum of each individual value of a column	select class, count (*) from mytable group by class 	0
10462635	26231	mysql - how come i get 0 rows when i compare 2 tables when 1 of them return null?	select id from tbl1 where id not in (select id from tbl2) 	0
10465167	27794	mysql query that will find users using the same ip address for multiple usernames	select ipaddress, group_concat(distinct username) from qvb_post group by ipaddress having count(distinct username) > 1 order by count(distinct username) desc 	0
10465832	31588	mysql finding data using in and like wildcard	select * from mytable where people='jack' or people like '%bob%' 	0.53355558464561
10466196	28013	select from database immediately after writing	select last_insert_id(); 	0.107406966822264
10466852	37981	identifying results by group and rank using sql	select rank() over(partition by a.id order by a.timestamp) as rnk 	0.24764489370945
10467349	481	check table with certain values in the other table	select  em.empid from empmaster em where not exists (     select null      from emppers      where empid = em.empid and pertypeid = 3 ); 	0
10470319	38129	how to find the recent date from the table	select id, max([date])  from [table] group by id 	0
10471128	30861	retrieve data from two or more tables	select     tblalt.alttext,     count(tblanswers.answerid) from tblalt left join tblanswers on (tblalt.altid = tblanswers.altid) where tblalt.questionid = " & cint(questionid) & " group by tblalt.alttext; 	0.000185781565852595
10472115	32829	how to create variables at runtime and what was its scope in c#	select subject_nme from subject where subjid in ('1','2','7','12') 	0.306982896710388
10475218	32827	sql count from inner join	select count(*) from (     select count(table1.act) as actcount from table1     inner join table2 on table1.act = table2.act     group by table1.act ) t 	0.38279868014888
10475517	16297	multiple count() in database	select tblalt.alttext, count(tblanswers.answerid), (select count(answerid) from tblanswers) as total_count from tblalt left join tblanswers on (tblalt.altid = tblanswers.altid) where tblalt.questionid = " & cint(questionid) & " group by tblalt.alttext; 	0.0789031433494499
10476510	19559	mysql select comments for friends then other comments while chronological order	select     posting.id,     if(a.friend_id = b.criteria, 1, 0) as is_friend ... order by is_friend desc, posting.id desc 	6.21991569387262e-05
10477101	8553	mysql sub-query listing information on one line	select    event_id,           group_concat(if(place = 1, `money`, null)) `first`,           group_concat(if(place = 2, `money`, null)) `second`,           group_concat(if(place = 3, `money`, null)) `third` from      tablename group by  event_id 	0.0174676334155762
10479270	33968	how to draw a name in a database	select * from table where num_value >= rand() * (select max(num_value) from table) limit 1 	0.0255167937501535
10479708	9501	how to convert varchar to numbers in sql developer	select * from users where id in  (select regexp_substr(list_of_ids,'[^,]+', 1, level) from dual connect by regexp_substr(list_of_ids, '[^,]+', 1, level) is not null) 	0.0391701421534262
10479745	11493	sql sub query need to add two query	select foodjoint_id,foodjoint_name,open_hours,cont_no,address_line,city,  ( 3959 * acos( cos( radians('".$userlatitude."') ) *     cos( radians( foodjoint_latitude) ) * cos( radians( foodjoint_longitude) -     radians('".$userlongitude."') ) + sin( radians('".$userlatitude."') ) *     sin( radians( foodjoint_latitude) ) ) ) as distance, (select avg(customer_ratings) from customer_review where  foodjoint_id=provider_food_joints.foodjoint_id) as customer_rating  from provider_food_joints  where  foodjoint_id in  (select foodjoint_id from menu_item where cuisine_id='".$usergivencuisineid."') having distance < '3' order by distance 	0.548760861941318
10480856	8893	order sql query data	select * from (   select i.id, i.art_id, i.c_izm, i.c_zime_izm, i.ac_izm, i.rc_izm, i.f_nos,           convert(nvarchar,dateadd(mi,-30,i.datums),100) as dat,          0 set_id     from nol_art_izmaina i    inner join nol_art a on i.art_id=a.id    where datepart(year,print_dat)=2005    union all   select distinct null,null,'','','','', f_nos, min(dat),          1 set_id     from nol_art_izmaina     where datepart(year,print_dat)=2005    group by f_nos ) tableplusheaders order by f_nos, set_id, dat desc 	0.378496432159348
10481806	29494	sql count column by date and select the correspondent date	select value,        count(*) as count,        dateadd(day, datediff(day, 0, time), 0) as newtime from yourtable group by value, dateadd(day, datediff(day, 0, time), 0) 	0.00141326246903949
10482705	17733	mysql query help to display results less than given date	select *  from tblfedachrdfi  where str_to_date(changedate,'%m%d%y') > "2012-08-05"; 	0.00346938718042277
10483862	1066	if condition in sql query	select       @type = (case tn.notification_type                     when 1 then 'work flow'                     else 'something else'                  end) from tbl_notification tn 	0.528670176920374
10483872	3858	search multiple columns returned most matches	select boxid, sum(matches)  from (select boxid,        (case when styleid in (4) then 1 else 0 end) +        (case when colorid in (1, 5) then 1 else 0 end) matches         from test) t1 group by boxid order by sum(matches) desc; 	0.000641000589073579
10484227	37227	mysql - order from table by x starting with id y	select * from table where (views = 4000 and id>6) or (views < 4000)  order by views desc, id asc; 	0
10484366	10554	multiple counts on different tables in same query	select      grps.groupname,     grps.groupsize,     psts.totalposts from (     select count(pg.personid) as groupsize, g.groupname, g.groupid     from group g inner join persongroup pg g.groupid = pg.groupid     where lastviewed between @startdate and @enddate and         g.type = 0     group by g.groupid, g.groupname     order by groupsize) grps join (     select count(gp.postid) as totalposts, g.groupname, g.groupid     from group g inner join grouppost gp on g.groupid = gp.groupid         inner join post p on gp.postid = p.postid     where g.type = 0 and         gp.created between @startdate and @enddate     group by g.groupid, g.groupname     order by totalposts) psts on psts.groupid = grps.groupid 	0.000468260723659792
10487876	10836	tsql determine duplicates respecting date ranges	select c1.name, c2.name, c1.id from client c1  join client c2 on c1.id = c2.id and c1.pk < c2.pk where c1.start > c2.end or c1.end < c2.start 	0.00661014556328298
10487946	645	are column alias'/ calculated columns not returned in sql server 2008 sprocs?	select ((5229 - 5249)/5249) 	0.147823552000392
10489447	33918	difference two rows in a single sql select statement	select d1.recdate, d2.recdate,        (d2.col1 - d1.col1) as delta_col1,        (d2.col2 - d1.col2) as delta_col2,        ... from (select *       from dated_records       where recdate = <date1>      ) d1 cross join      (select *       from dated_records       where recdate = <date2>      ) d2 	0.000636173659705701
10491474	15864	mysql select distinct multiple columns based on the uniqueness of one row?	select `state`, `state_name` from `geo` group by 'state', 'state_name' order by `state_name` asc 	0
10492164	16006	how do i count columns of a table	select count(*) from information_schema.columns where table_name = 'tbl_ifo' 	0.00100785597819883
10495150	20328	oracle: how can i get a value 'true' or 'false' comparing two numbers in a query?	select   case sign(actual-target)     when -1 then ...     when  0 then ...     when  1 then ...   end 	0.000201758482210964
10496154	5982	count row in table with identical value of two column in sql server 2008	select     receiver, caller, category, playfilename,     count(*) over (partition by receiver, category) as countperreceivercategorygroup from tbl_record 	0
10496509	23389	how to change datatype of a column in sybase query?	select ric_code as ric, weight, convert(numeric(16,4), adjusted_weight) as adjweight, currency as currency  from v_temp_idx_comp  where index_ric_code='.axjo' 	0.0213195521185178
10496668	32444	working with numbers in sql	select sum(quantity), client_id, productid, cart from ( select  1 quantity, * from    feed where  event = 'add' union all select  -1 quantity, * from    feed where  event = 'rem' ) temp group by client_id, productid, cart 	0.698399396520249
10497635	15942	how to write inner query that returns latest message for a given user?	select u.fname, u.lname, m.id, m.userid, m.datem, m.content from users as u left join ( select id, userid, date, content             from messages             where active             order by date desc) as m on u.id = m.userid where u.active     # and u.id = {$int_user_id} group by u.id 	0.00377697812638342
10498300	33623	join on data from xml in t-sql	select t.c.value('./@id', 'int') as id, t.c.value('./@name', 'varchar(max)') as name  from @xml.nodes('/message/changes/deleted/row') t(c) inner join other_table tbl     on tbl.id = t.c.value('./@id', 'int') 	0.0468215898768779
10501037	40230	how to select last record from each day with mysql	select t1.* from dk_location_records t1   join (select date(date) date_date, userid, max(date) max_date         from dk_location_records         group by date_date, userid         ) t2     on t1.date = t2.max_date and t1.userid = t2.userid; 	0
10502611	12953	sql how to select max dates from results of a join	select    oils.oilid, oils.shipid, rob.lastrob, rob.received, rob.datereceived,             rob.portreceived, rob.totalused, rob.currentrob, rob.datesent  from             (             select distinct oilid, shipid              from   [index]              where  shipid = [queryshipid]            ) as oils              left join              (             select shipid, oilid, lastrob, received, datereceived, portreceived,                     totalused, currentrob, datesent              from   [oil rob]             )  as rob on oils.shipid = rob.shipid and oils.oilid = rob.oilid where     rob.datesent = (                            select max(datesent)                             from   [oil rob]                             where  shipid = rob.shipid and                                    oilid = rob.oilid                          ); 	0.000629098361295621
10503711	7212	want to run a count on sub select with doctrine	select count(e) as eventcount from comments\entities\event e  where e.type = 'addcomment' and timestampdiff(minute, e.commentedonpublished, e.created) < 60 	0.555653783879319
10504105	36331	mysql inner join query - how do i combine these 2 queries?	select distinct t.*,u.username from filter as f inner join filter_thread as ft  on ft.filter_id = f.filter_id inner join thread as t  on ft.thread_id = t.thread_id inner join users as u on u.id = t.owner_id where f.tag like '%test%' order by t.replystamp desc 	0.56732850277569
10504139	22135	mysql - find fields with same id	select car_id from mytable where keyword in ('old','ford','cheap') group by car_id having count(*) = 3 	0.000313341534972507
10506731	26030	get difference in years between two dates	select id, floor(datediff(curdate(),birth_date) / 365) from student 	0
10506843	28919	sql order by 2 date columns	select * from (    select orderid        , 'colection' as visittype       , collection_date as visitdate    from orders    union all    select orderid      , 'delivery' as visittype      , delivery_date as visitdate   from orders ) as v order by v.visitdate 	0.00392593365244346
10507210	8567	how to limit result set of an sql left join query by count	select      `customers`.`id` as `cust_id`,     `orders`.`id` as `order_id` from     `customers` left join `orders` on     `customers`.`id` = `orders`.`customer_id` inner join        (select `customer_id `            from `orders`        group by `customer_id`            having count(id) > 1) as `morethanone` on     `customer`.`id`  = `morethanone`.`custmor_id` order by     `cust_id` 	0.432621029191506
10507827	23179	mysql: getting the rest of a row's data when using 'max'	select user_id, item_id, bid_amount from bids  where (item_id, bid_amount) in (    select item_id, max(bid_amount) from bids group by item_id ) 	0.000101058290733286
10510088	32787	mysql joins - where unique id lies in 1 table	select e1 . * from events_vevent e1 left outer join events_vevent e2 on  ( e1.catid = e2.catid and e1.ev_id < e2.ev_id ) group by e1.ev_id having count( * ) < 5 order by catid, ev_id desc 	0.00460926561901803
10511205	36354	how to look which room is available between 2 datetimes	select * from room as ro where ro.id not in              (               select re.roomid               from reservations as re                where (date_begin >= @start and date_begin < @end)                 or (date_end >= @start and date_end < @end)              ) 	0.000273638680060306
10511461	3708	select distinct list of all elements x of all records in sql xquery	select distinct t.n.value('.','nvarchar(64)') from table1   cross apply xmlcol.nodes(' 	0
10511876	41023	fetch top 5 customers from mysql table	select customer_id , count(order_id) as total_orders  from `tbl_order`  group by customer_id  order by total_orders desc limit 5 	0
10511904	26646	unable to form sql	select * from [orders] where orderreceived >= @startdate     and orderreceived < @enddate     and (strftime("%h", orderreceived) = "14"         or strftime("%h", orderreceived) = "15") 	0.44610355953072
10512228	34875	returning rank with full text search contains query	select mas_text.*, k.rank from mas_text      inner join containstable(mas_text, text, 'wanted and engineers') k     on mas_text.primarykey = k.[key] 	0.787425930780597
10512508	29192	how to get the next 12 future dates	select date , i.m , date_format(date(date_add(cmh.date, interval i.m month)), '%y-%c-%d') as overdate from contact_method_history as cmh , (     select 1 as m     union all select 2 as m     union all select 3 as m     union all select 4 as m     union all select 5 as m     union all select 6 as m     union all select 7 as m     union all select 8 as m     union all select 9 as m     union all select 10 as m     union all select 11 as m     union all select 12 as m ) as i where ( date(date_add(cmh.date, interval i.m month)) = '$sqldate' ) and (entityref = ".$this->entityid.") group by i.m, date(date_add(cmh.date, interval i.m month)) 	0
10512794	35103	adjacency model , given an id return the leaf nodes	select distinct t2.id , t2.name from     categories as t1 left join categories as t2     on t1.id = t2.parent      left join categories as t3     on t2.id = t3.parent     where  t1.parent = $id or t1.id = $id and t2.visible = 1 	0.000383548859444606
10513678	28309	why is it displaying same result in two rows?	select poll_questions.id, vote_types.type as answer from   poll_questions   join poll_answers on poll_questions.id    = poll_answers.question_id   join vote_types   on poll_answers.vote_id = vote_types.id where  poll_questions.referendum_id = 1 	0.0169636323768331
10513820	33164	convert sql columns to rows	select 1 union select 2 union select 3 	0.00353984884467782
10514197	22834	mysql: query'ing results [pic]	select ... from exp_channel_titles as ect   join exp_channel_titles as ect2     on (           ect2.author_id = ect.author_id       and ect2.title like '%member%'       and ect2.status = 'complete'     )   ... where ect.status = 'members-id5' 	0.344714169894088
10514724	41077	search mysql with two search terms	select * from isc_products  where prodname like '%fire%'  and prodname like '%poi%' limit 100 	0.315212607858394
10514812	517	a table with random values from each table	select (select top 1 name from @tablea order by newid()) as name union all select (select top 1 name from @tableb order by newid()) union all select (select top 1 name from @tablec order by newid()) 	0
10515163	10551	refering to columns from more tables having the same attribute name	select t1.title as title1, t2.title as title2 from ... 	0
10518920	7559	sql distinct group by rows	select date, name, score from temp t1 where date = (select max(date) from temp where t1.name = temp.name) 	0.027595280369444
10521060	25559	joining two tables in sql, but using an earler row if no result on the right table	select   * from   computerconfigs left outer join   computerhassoftware     on computerhassoftware.computerid = computerconfigs.computerid     and computerhassoftware.lastchangedate = (                                               select max(lastchangedate)                                                 from computerhassoftware                                                where computerid = computerconfigs.computerid                                                  and lastchangedate <= computerconfigs.lastchangedate                                              ) left outer join   software     on software.softwareid = computerhassoftware.computerid 	0.00048678709196096
10521115	29393	how to display data from 3 tables?	select c.name     , count( distinct op.model ) as quantity     , sum( op.total + op.total * op.tax /100 ) as total from order_product op left join product_to_category ptc      on op.product_id = ptc.product_id left join category_description c     on ptc.category_id = c.category_id where ptc.category_id =192     or ptc.category_id =177 group by ptc.category_id, c.name 	8.6418995617215e-05
10521305	38259	find all geometry that intersects a point	select *  from sf_blocks  where st_contains(     the_geom,      st_geomfromtext('point(-122.44107 37.750066)', 4326) ); 	0.00383934989459351
10521409	492	mysql n to m query	select domains.id, name,group from transit inner join domains on transit.domainid = domains.id inner join products  on transit.productid = products.id where domains.name= ? 	0.0329413479440044
10522235	1909	how to "dual" join in a sql query?	select b.title, a.name as author_name, e.name as editor_name from books b inner join people a on a.id=b.authorid inner join people e on e.id=b.editorid 	0.761390358694889
10522856	6875	where vs. having with calculated field	select count(*) as counts from mytable where datediff(yyyy,dob,admitdate) between 5 and 10 	0.642917135746476
10525291	39788	multiple select statements with sum() and where?	select u.name, sum(case when status = 'new' then amount else 0 end) as total_new, sum(case when status = 'pending' then amount else 0 end) as total_pending, sum(case when status = 'final' then amount else 0 end) as total_final, sum(case when status = 'closed' then amount else 0 end) as total_closed from users as u left join transactions as t on u.userid = t.userid group by u.name 	0.364489953202078
10527396	34059	pad middle of string with 0s in mysql order by clause to respect "true" numeric order	select * from tbl order by substr(subdomain, 1, 6), cast(substr(subdomain, 7) as unsigned) 	0.243792883986036
10529764	27139	sqlite reverse the order of the result set?	select * from (     select *      from sample      where index1 < 70      order by index1 desc      limit 0,5 ) order by index1 asc; 	0.0140519585299755
10529848	28712	php: doing the same query over and over?	select * from product left join category on product.category_id = category.id; 	0.166563182374485
10530331	24359	select default value if column has 0 value in sql server	select id,        case when col1 = '0' then 'xyz' else convert(varchar, col1) end as col1,        col2 from table 	0.000437426265511151
10530522	35614	merging rows in a single table shows duplicate result	select   check_in.log_id           as `checkin id`   ,      check_in.user_id          as `user_id`   ,      check_in.xtimestamp       as `checkin`   ,      min(check_out.xtimestamp) as `checkout`  from     clock                     as `check_in`   join   clock                     as `check_out`       on (            check_out.info = 'checkout'        and  check_in.info = 'checkin'        and  check_in.user_id     = check_out.user_id        and  check_in.xtimestamp <= check_out.xtimestamp       ) group by check_in.log_id, check_in.user_id, check_in.xtimestamp; 	0
10532717	26130	mysql multiple count and join	select t1.id, t1.pid, t1.title , count(t2) as subelements from tree as t1  left join tree as t2 on t2.pid = t1.id where t1.pid=10 group by t1.id, t1.pid, t1.title 	0.277115666958609
10535916	40270	sql code to identify average daily totals	select   * from   yourtable where       (contact_start_date >= cast('20120510' as datetime) or contact_start_date is null)   and (contact_end_date   <= cast('20120510' as datetime) or contact_end_date   is null) 	0.00223765461153779
10536146	21634	sql: how to separate combined row into individual rows	select rownum, id,        substr(']'||check_number||']'               ,instr(']'||check_number||']',']',1,level)+1               ,instr(']'||check_number||']',']',1,level+1)                 - instr(']'||check_number||']',']',1,level) - 1) c1value,        substr(']'||amount||']'               ,instr(']'||amount||']',']',1,level)+1               ,instr(']'||amount||']',']',1,level+1)                 - instr(']'||amount||']',']',1,level) - 1) c2value     from table connect by id = prior id and prior dbms_random.value is not null         and level <= length(check_number) - length(replace(check_number,']')) + 1 rownum id  c1value c2value 1      1   1001    200 2      1   1002    300 3      1   1003    100 4      2   2001    500 5      2   2002    1000 6      3   3002    100 7      3   3004    300 8      3   3005    600 9      3   3007    200 	0
10538296	37196	how to produce detail, not summary, report sorted by count(*)?	select * from ( select count(*) over (partition by ch_id) cnt,         ch_id, customer from sales ) order by cnt desc 	0.00891775780863273
10538539	26889	join two select statement results	select t1.ks, t1.[# tasks], coalesce(t2.[# late], 0) as [# late] from      (select ks, count(*) as '# tasks' from table group by ks) t1 left join     (select ks, count(*) as '# late' from table where age > palt group by ks) t2 on     t1.ks = t2.ks 	0.241412070121745
10539070	4363	mysql sum of table sums with different where clauses	select (select sum(1column2) from table1 where 1column1 = '0') - (select sum(1column4) from table1 where 1column3 = '0') - (select sum(2column2) from table2 where 2column1 = '0' and 2column3 = 'w' and 2column4 != 'f'); 	0.00505248362546984
10539502	11907	selecting distinct where not null in mysql	select distinct name, id from testtable where name <> '' union all select name, id from testtable where name = '' 	0.15600992553554
10540939	38501	query to get value from two columns	select * from `table` where `to_user_id` = 21 or `from_user_id` = 21 	0
10542236	27716	mysql, how to join many records to one	select e.id,         e.loc_id,         e.a,         l.b,         p_name.value `name`,         p_age.value  age  from   wp_em_events e         inner join wp_em_locations l           on e.loc_id = l.loc_id         inner join wp_postmeta p_name           on e.id = p_name.post_id         inner join wp_postmeta p_age           on e.id = p_age.post_id  where  e.id = 1              and p_name.`key` = 'name'              and p_age.`key` = 'age' 	0.00359725417484599
10542393	38696	how to format sql datetime to comapre it to a given date and retrive one record?	select top(1) * from documents where issuedate <= ? order by issuedate desc 	0
10543646	5377	sql count in related table of 2nd order for selecting data for a forum index	select   f.category,   f.id,   f.name,   f.description,     count(distinct t.id) as topics,     count(distinct p.id) as posts,     min(lastuser.id),     min(lastuser.username),     min(p.create_date) from posts p join users u on p.user_id = u.id join topics t on p.topic_id = t.id join forums f on t.forum_id = f.id join (select         t.forum_id,         u.id,         u.username,         p.create_date         from posts p         join topics t on p.topic_id = t.id         join users u on p.user_id = u.id         join (select                t.forum_id, max(p.id) as max_postid               from posts p               join topics t on p.topic_id = t.id               group by t.forum_id               ) lastpost on p.id = lastpost.max_postid              and t.forum_id = lastpost.forum_id        ) lastuser on lastuser.forum_id = f.id group by f.category, f.id, f.name, f.description 	0.000114313345358788
10543772	20680	mysql select query for getting co-workers	select * from workers  join (select distinct workerid from workerjobs join workers on worker.workerid = workerjobs.workerid and worker.age = 22) worker22 on worker22.workerid = worker.workerid join jobs on jobs.jobid = workerjobs.jobid join workerjobs on workerjobs.workerid = workers.workerid and workerjobs.jobid = jobs.jobid 	0.441015501032213
10544052	3059	custom type auto increment id codeigniter	select lpad(member_id,8,'0') from table where id = 1 	0.00312568284239182
10545576	20814	how to remove duplicates and get the greatest value	select max(id),value from foo group by value order by max(id) desc 	0.000106036607130651
10545774	37424	return multiple fields using case in select statement of sql server	select id,name ,case flag when 'y' then (city +' ' +descrip ) when 'n' then 'inactive' end as status  from tb3 	0.34045793701835
10547153	19752	formating column in sql	select   column1,           column2,          case             when column3 is not null             then '|'             else ''           end from your_table 	0.326985970554997
10548090	29737	how to select columns from two tables, and order by one of them?	select article, article_id from first_table f join second_table s on f.article_id = s.id and f.article = s.name order by s.commit_date 	0
10549327	15688	postgresql select until certain total amount is reached	select id,         date,         amount,         running_total from (     select id,            date,            amount,            sum(amount) over (order by date asc) as running_total     from transactions ) t where running_total <= 6 	0
10550130	3077	getting distinct values in this query	select distinct(tbl_order_detail.order_id), tbl_order_lead_send_detail.customer_id, tbl_order_detail.order_title, tbl_order_detail.dealer_id , tbl_order_lead_send_detail.send_date_time         from tbl_order_detail         inner join tbl_order_lead_send_detail         on tbl_order_detail.order_id=tbl_order_lead_send_detail.order_id         where tbl_order_detail.order_status='active'         order by tbl_order_lead_send_detail.send_date_time desc 	0.239568890835068
10550205	5514	last row in the database	select id from table order by id desc limit 1; 	0.000141275809289043
10550707	22746	oracle sql developer - combining cartesian product, count/sum and group by	select p.type, count(p.type) cnt, sum(i.amoumt) total from products p, invoice i where (p.account = i.id) group by p.type 	0.795613687280686
10551771	9375	user-defined variable in a query	select tsum.*, sum(cnt) over (partition by null) as totalpop from (select gender, count(*) as cnt       from t       group by gender      ) tsum 	0.791138141335659
10552614	1035	excluding records from a search which are associated with a record	select distinct customers.* from customers outer join ( select distinct customers.id from customers inner join tag_assignments on tag_assignments.customer_id = customers.id where tag_assignments.tag_id in (?) ) as neg_customers on (neg_customers.id = customers.id) where neg_customers.id is null; 	0
10555603	34689	results order with union query	select 1 as seq, count(datediff(yyyy,dob,admitdate) as counts   from mytable  where ...condition-1... union select 2 as seq, count(datediff(yyyy,dob,admitdate) as counts   from mytable  where ...condition-2...  order by seq 	0.703247049190105
10556404	20560	mysql select int as currency or convert int to currency format?	select concat('$', format(val, 2)) ... ; 	0.145434855238042
10557897	18989	sql. getting a max(avg(column))	select source_id, company_id, max(avg_click) as max_click from  (select source_id,company_id,avg(clicks) as avg_click from table_company group by source_id,company_id order by avg_click desc) tmp group by company_id 	0.299739114423207
10559647	21516	how do i get the index of varray items after converting to a table	select t1, row_number() over ( partition by t1 order by t1), t2.* from  (select 'x' as t1 from dual union select 'y' from dual) t1,  table (sys.odcivarchar2list('a', 'b', 'c'))             t2; 	0.000194986425770225
10560394	33363	how do i query using fields inside the new postgresql json datatype?	select * from   json_array_elements(   '[{"name": "toby", "occupation": "software engineer"},     {"name": "zaphod", "occupation": "galactic president"} ]'   ) as elem where elem->>'name' = 'toby'; 	0.253064634308693
10561700	28444	skill matching algorithm	select top 20 *  from candidate order by square(candidate.javaproficiency - @javaproficiency) + square(candidate.sqlproficiency - @sqlproficiency) 	0.0719701633473784
10562085	17811	replacing the zero with next same id's value - mysql	select   staffid               as staff,          sum(frequency='less') as lesscount,          sum(frequency='full') as fullcount,          sum(frequency='more') as morecount from     effort_frequency group by staffid 	0
10563075	6982	how to use join in three tables	select     tbla.id,     tbla.doc_id,     tblb.d_name,     tblc.seg_color from     tbla, tblb, tblc where     tbla.doc_id = tblb.doc_id     and     tblb.d_segid = tblc.seg_id     and     tbla.mr_id = 22     and     tbla.date = '2012-05-23' order by     tblc.seg_name 	0.276232729059823
10564602	18548	query with verified if table exist	select c.table_name from v_c_country c inner join information_schema.tables i on i.table_name = c.table_name 	0.219923824045702
10564695	22748	mysql - bottleneck - join one to many, tags of news articles	select (     select group_concat(name)     from   tags, posts_tags     where  posts_tags.posts_id = posts.posts_id     and    tags.tags_id = posts_tags.tags_id ) from posts limit 10 	0.00293830906323993
10564973	21411	how do i combine these two select queries with an or case	select * from `t_activities` where (`uid` = {$uid} or `uid` in (select `cid`                                     from `t_con`                                     where `uid` = {$uid} and `flag` = 1)) and `del` = 0 group by `fid` order by `time` desc  limit 10 	0.452723072913799
10565433	5540	join two select queries with mysql	select cd.salesrep_id as customerssalesrep_id,        cd.issalesrep,        cd.repcom,        cd.salesrep_id,        sr.repdispname,        sr.defaultrepcom from   customerdetails as cd left join salesreps as sr using(salesrep_id) where  cd.customer_id = $customer_id 	0.23353772211635
10565924	26402	mysql select rows where date is older than datetime	select status_column from your_table  where added_date < '2012-05-12' 	0.000729902974728285
10568191	30601	sql query needs to sort on multiple date columns together	select top 10 * from core_table order by   case       when start_date >= process_date and start_date >= archive_date            then  start_date       when process_date >= archive_date            then  process_date       else  archive_date   end  desc 	0.00623760781357078
10568547	37442	how to combine these 2 mysql select statements together?	select * from `users` u join `profiles` p on u.user_id = p.user_id join `geo` g on u.zip = g.zip_code join `user_activity` ua on u.user_id = ua.user_id order by u.featured desc,     u.user_id desc limit ". ($page_num - 1) * $per_page .", ". $per_page; 	0.0334522360926822
10569142	29826	crosstab in mysql	select car_name,   max(case when year = '2011' then price else 0 end) as `2011`,   max(case when year = '2012' then price else 0 end) as `2012` from t group by car_name 	0.579596253973777
10570154	6719	mysql related fields	select users.firstname, users.lastname, users.screenname,        posts.post_id, posts.user_id, posts.post, posts.upload_name,        posts.post_type, date_format(posts.date_posted, '%m %d, %y %r') as date,         count(nullif(feeds.user_id, ?)) as everybody,        sum(feeds.user_id = ?) as you,        group_concat(case when not likes.user_id = ? then               concat_ws(' ', likes.firstname, likes.lastname) end) as names   from (select user_id from website.users where user_id = ?         union all         select user_id from website.friends where friend_id = ?         union all         select friend_id from website.friends where user_id = ?) as who   join website.users users on users.user_id = who.user_id   join website.posts posts on users.user_id = posts.user_id   left  join website.feeds feeds on posts.post_id = feeds.post_id   left  join website.users likes on feeds.user_id = likes.user_i)  group by posts.pid  order by posts.pid desc; 	0.0293207042497978
10571615	5953	mysql join query using three tables	select questions.question,         count(comments.question_id) as 'total comments',         user.user from user    join questions on user.user = questions.customer_id   left join comments on questions.question_id = comments.question_id where user.status = 1 group by comments.question_id,  questions.question, users.user order by questions.question limit 5 	0.461102856724187
10572430	40125	how to use two values to define order in mysql but priorize one of them?	select * from messages where parent=0 order by ifnull(last_reply,written) desc 	0.0001803698582833
10573531	39157	sql query not pulling records the same	select book.title, book.copyright, book.publisher, book.id,     materialtype.type, item.id as item_id, 100 as relevance from `books` as `book` left join `material_types` as `materialtype` on (`materialtype`.`id` = `book`.`material_type_id`) left join `items` as `item` on (`item`.`book_id` = `book`.`id`)  where `item`.`accession_number` = '0936' group by `book`.`id` 	0.0030760143331973
10573550	16456	sql statement filtering from 2 tables	select * from questions where accept = 0 and not exists (select id from answers where user_id = 2 and id in (select question_id from questions)) 	0.0236906771547453
10575132	32663	multiple tables mysql join	select main.id,main.name,taba.name,tabb.name  from main  left join taba on taba.fk=main.id  left join tabb on tabb.fk=main.id  order by main.name 	0.215037187079354
10575281	5066	how to express postgresql variable as a string	select * from :"table_name"; 	0.53309370385515
10575405	12567	select from one table where count=1 in second table and two more conditions	select  * from table1 t1 inner join table2 t2 on t1.num = t2.num and t1.date = t2.date  group by t1.num having  group_concat(t1.payment) = 'cash' 	0
10576009	371	sql - how do i return the top 5 highest earning years?	select * from final_ytd_amounts order by ytd_amount desc limit 5 	0
10576775	37618	how to select the biggest value from a list of duplicate entries	select * from foo where status = 3 order by id desc limit 1; 	0
10578054	29941	varchar2 to timestamp	select to_char(to_date(t.feed_time,'dd:hh:mi am')+1, 'dd:hh:mi am') from feed_type t where t.feed_code = 'credit'; 	0.0329771423175065
10578436	21187	finding difference resullts in subquery returns more than 1 row in mysql error	select table11.fk_tbl_states_stateid,table1.gender,table1.value - table2.value as diff from (select * from tbl_populations where fk_tbl_states_stateid = '16' and fk_tbl_districts_districtid = '0' and residence = '0' and aspect = '2' ) table1, (select value,gender from tbl_populations where fk_tbl_states_stateid = '16' and fk_tbl_districts_districtid = '0' and residence = '0' and aspect = '1' ) table2 where table1.gender = table2.gender 	0.105222622426679
10578608	5487	selecting multiple columns from a subquery	select column1, column2, column3 from itembase ib outer apply dbo.fngetitempath(ib.id) 	0.00141770617581609
10578854	9330	sql query that gives the total order value for a month?	select     sum(price*amount) as total from     orderrader     join ordrar         on orderrader.ordernumber =ordrar.ordernumber where     year(date)=2010     and month(date)=1 	0.000113630016099273
10579106	5639	how to reduce query time using jdbc?	select * from stops stops inner join stop_times stoptimes on stoptimes.stop_id = stops.stop_id where stops.stop_id = ?    and stops.agency_id = ?    and stops.location_type = 0    and stoptimes.agency_id = ?    and stoptimes.route_type = ? order by stops.stop_name 	0.707895271775736
10579221	32031	sql query "find the article that has generated most income?"	select  articlenumber, sum(price*amount) as totalincome from orderrader group by articlenumber  order by sum(price*amount) desc limit 1 	0.00016100448102229
10579773	41086	sql select row dependent on time last chosen	select *  from table t where lastranat < dateadd(mi, (t.refreshtime * -1), getdate()) 	5.16120150976531e-05
10580853	41278	mysql sql distinct with join two table	select *  from eventvenue  join event on eventvenue.id_event_ev = event.id_event  where eventvenue.id_location_ev=1 group by event.id_event, eventvenue.id_event_ev 	0.0607204502339833
10581260	27190	single sql query for retrieval of data with different where clause possible?	select column 1, column2 from table1, table2 where id in (1,2,3,4,5) 	0.168327356178748
10582388	5709	mysql return parent & child	select a.name, b.name as parent_name from categories a left join categories b on a.parent_id = b.id where a.id in (3,5); 	0.00412072505728904
10584460	20506	how to get last inserted rows with repeated values in a column?	select * from person_gps a inner join client_gps b on a.gps_id = b.gps_id inner join gps c on a.gps_id = c.gps_id where b.client_id = @client_id and not exists (select 1 from person_gps where x a.gps_id = x.gps_id and x.date2 is null) 	0
10584923	16805	sql import/export	select'insert into table1(col1,col2) values('+cast(col1 as varchar(500))+',' +cast(col2 as varchar(500))+')' from table1 	0.688949553253353
10586035	24360	mysql select in range	select job from mytable where id between 10 and 15 	0.0244272863332162
10586746	7939	how to have group by and count include zero sums?	select   calendar.calendar_date,   count(people.created_at) from   calendar left join   people     on calendar.calendar_date = people.created_at where   calendar.calendar_date >= '2012-05-01' group by   calendar.calendar_date 	0.00590535475883476
10587298	18033	sql select: multiple customers have muliple order lines. list each customer and true false whether certain lines ordered	select cust,        (case when sum(inrange) > 0 then 'true' else 'false' end) as count from (select t.*,              (case when code between 'n002' and 'n004' then 1 else 0 end) as inrange       from t      ) t group by cust 	0
10589155	30779	if i have two types of row in an sql table, and i want to prefer one but accept the other	select * from directory where     usertype = 'employee'     or userid not in (         select userid         from directory         where usertype = 'employee'     ) 	0
10589413	23861	cross-table criteria query	select *  from (   select      e.ebusref,      count(e.eid) as empcount,      sum(abs([esenior])) as senior,      [senior]/([empcount]/100) as [%senior]   from tblemployee as e   group by e.ebusref) q where q.[%senior]<=50 	0.509781517892828
10590146	40038	how to do a full outer join of two tables with the same layout not repeating the?	select coalesce(a.id,b.id) as id, val1a , val2a , val1b , val2b from tablea a full outer join tableb b on <.....> 	0.00809390652350395
10590158	3661	sql summarize different rows	select player_id, sum(result) from (select player_a_id as player_id, player_a_result as result from games union select player_b_id, player_b_result from games) as u group by player_id order by player_id 	0.0091573484947626
10591113	29486	drop all functions from postgres database	select 'drop function ' || ns.nspname || '.' || proname         || '(' || oidvectortypes(proargtypes) || ');' from pg_proc inner join pg_namespace ns on (pg_proc.pronamespace = ns.oid) where ns.nspname = 'my_messed_up_schema'  order by proname; 	0.0134914531598092
10591429	26232	mysql select 7 days before event and 7 days after event	select *, if(right(birthday,5)>=right(curdate(),5),concat(year(curdate()),'-',right(birthday,5)),concat(year(curdate()+interval 1 year),'-',right(birthday,5))) as next_birthday, if(right(birthday,5)<right(curdate(),5),concat(year(curdate()),'-',right(birthday,5)),concat(year(curdate()-interval 1 year),'-',right(birthday,5))) as prev_birthday from users having next_birthday  between curdate() - interval 7 day and curdate() + interval 7 day or prev_birthday  between curdate() - interval 7 day and curdate() 	0
10591454	3466	sql select now()	select curdate() 	0.169226879083106
10592650	37581	sql same column subtraction	select sum(case when a=1  then 1 else 0 end)- sum(case when a=0  then 1 else 0 end) as result from table 	0.0195515507965099
10593316	30667	how do i create a list(array) of values with the number of times they appear in another array	select ordprodname, sum(ordprodqty), ordprodid from isc_orders, isc_order_products  where orderid = orderorderid and orddate >= unix_timestamp() - ('$days' * 86400)  group by ordprodname  order by sum(ordprodqty) desc"); 	0
10593378	8699	mysql: return parent rows conditionally on two children of that parent which are the same table	select gameid from game g inner join playergamestate gs1 on g.p1state = gs1.playergamestateid inner join playergamestate gs2 on g.p2state = gs2.playergamestateid where gs1.ready=1 and gs2.ready=1 	0
10595528	19960	join on following queries?	select widget_uid, campaign_name, campaign_type from (select widget_uid,param_value as campaign_name from widget_config_value  where widget_uid in  (select widget_uid from widget_config_value  where param_name="active"  and param_value="1"  and widget_uid in (select widget_uid from partner_widget where partner_uid=4))  and param_name="widgetcampaignname") tbl1, (select widget_uid,param_value as campaign_type  from widget_config_value  where widget_uid in  (select widget_uid  from widget_config_value  where param_name="active"  and param_value="1"  and widget_uid in (select widget_uid from partner_widget where partner_uid=4))  and param_name="widgettype") tbl2 where tbl1.widget_uid = tbl2.widget_uid; 	0.629383901653025
10597318	12481	mysql many counts from subqueries	select        t1.id, t1.name,        coalesce( t2counts.t2count, 000000 ) + coalesce( t3counts.t3count, 000000 ) as total_occurences_in_t2_and_t3    from       ( select @t2countt := 0,                @t3countt := 0         ) sqlvars,       t1         left join ( select t1id, count(*) as t2count                        from t2                        group by t1id ) as t2counts            on t1.id = t2counts.t1id         left join ( select t2id, count(*) as t3count                        from t3                        group by t2id ) as t3counts            on t1.id = t3counts.t2id 	0.106578046438212
10598037	8585	get a group id from bridge table	select group_key from (  select group_key, listagg(dim_key, ',') within group(order by dim_key) dim_key    from t   group by group_key) where dim_key = '11,12,13' 	0.000318753612230101
10602562	4380	one table vs multiple tables	select * from documents d left join doc_comments c                             on d.id = c.docid                             where d.id=42; 	0.0217278416759981
10603582	10238	get closest date in php	select schedule_date  from  schedule_table where date(schedule_date) >= '2012-06-07' and   event_id='23' order by schedule_date asc        limit 1 	0.00324939814716077
10605929	8948	mysql search for item with all tags	select distinct tm.book_id, b.other_info from tagmap tm inner join tags t     on tm.tag_id = t.tag_id   left join books b     on tm.book_id = b.book_id having count(tm.book_id) = 2 	0.00102631467716031
10606062	2767	getting database results from array of ids	select * from slides where slideid in (1,2,3,4,5, ...) 	6.08829447655354e-05
10606726	30079	batch count in active record or mysql	select count(*) from votes group by entry_id 	0.00206286183298798
10607852	4377	select distinct user_id from a table for each request type	select      supporter.user_id,     min(supporter.created) as created,     supporter.*,     supporter.source from     supporters as supporter group by supporter.user_id, supporter.source order by supporter.created asc 	0
10607874	4720	sql query data join has null values that it ignores	select ... into dbo.ocommittedtbl from [committedtbl] ct left join [codeledgertbl] lt on lt.ledgerkey = ct.oc_ledgercode  left join [vendortbl] vt on vt.v_venkey = ct.oc_vendorname 	0.256653395865595
10608991	24835	2 rows presented as 1	select * from table as s1 where exists        ( select *         from table as s2         where ( s2.code = s1.code )           and (  ( s1.column1 is null  and  s2.column1 is not null )                or ( s2.column1 is null  and  s1.column1 is not null )               )       ) ; 	0.00648061103911913
10609367	2574	sql find missing associations	select * from items where book_id not in (select id from books) 	0.135822619299268
10610978	40607	mysql summing with an algebraic expression for every row	select sum(       w.weight * w.repetitions        + w.weight * coalesce(w.seconds,0) / 3) from workout_exercise_logs w join workout_logs wo on `w`.`workoutlogid`=`wo`.`workoutlogid` join workouts wor on `wo`.`workoutid`=`wor`.`workoutid` where w.weighttype=1 and `wor`.`userid`=34 	0.103447718613861
10613940	25456	postgresql column not found, but shows in describe	select transactionamount from ... where ... group by transactionamount; 	0.464939483506606
10614150	38932	sql query to get records even if count is 0 in one table	select surrogatetable.name,         surrogatetable.category,         count(id) as totalcalls from  (   select 'whatever1' name,          'first category' category   union all   select 'whatever2',          'second category' ) surrogatetable left join missed_call   on surrogatetable.name = missed_call.name group by surrogatetable.name, surrogatetable.category 	0.000179174471070638
10615261	1771	mysql query order by sum field of another table	select h.id, h.hotel_name, sum(hp.allotment)   from hotel h join hotel_price hp on (h.id = hp.hotel_id)  group by h.id, h.hotel_name  order by 3 desc; 	0.000992691030762273
10616588	9499	fetch values from 3 tables without redundancy-sqlite	select name,         ifnull (sum(bamt), 0) bamt,        ifnull (sum(ramt), 0) ramt from (   select name,           null bamt,          null ramt     from table1    union all   select name,          bamt,          null     from table2    union all   select name,          null,          ramt     from table3 ) alltables group by name order by name 	0.000231915719806592
10617459	12207	select tables rows matching where condition based on two columns	select fieldtypeid,level  from [table] where fieldtypeid <> 2  or level = 1 	0
10617840	36314	inner join to more than one table	select st.firstname, st.lastname, c.name, sm.name, m.mark from (((mark m         inner join student st on st.id = m.studentid)         inner join course c on c.id = m.courseid)         inner join semester sm on sm.id = m.semesterid) 	0.0717647995141946
10621402	22712	query the database for laptops with price close to entered price	select product.maker, pc.model, pc.speed, abs(pc.price - '$p') as offset from pc left join product on pc.model=product.model order by offset asc limit 1 	0.010796591614092
10622947	30396	i am trying to get data from row to match into defined columns	select customers.*, data_type.datavalue as type, data_region.datavalue as region from   customers   join cust_data as data_type on (          data_type.listid   = customers.list_id      and data_type.dataname = 'type'   )   join cust_data as data_region on (          data_region.listid   = customers.list_id      and data_region.dataname = 'region'   ) 	0
10622964	24396	sql: how to select the earliest date and data that corresponds to it	select top 1 a.custnmbr, a.tax_date as first_date, a.sopnumbe  from sop30200 as a  where a.custnmbr = '3344771005'  order by a.tax_date asc 	0.000635512100609314
10623546	20226	combining two queries : selecting friends from friend table and join tham with users table	select u.id,     u.username,     u.avatar from friends_table f join users_table u on f.u1_id = u.id || f.u2_id = u.id where u.id <> $profile_id     and (f.u1_id = $profile_id || f.u2_id = $profile_id) 	0
10623940	3510	can't seem to find record by simple id query	select um00200m.account_no as index1,               concat (concat (trim (um00200m.person_lnm), ' '),                       trim (um00200m.person_fnm))                  as index2,               decode (nvl (trim (sg00100m.person_id_custom), 0),                       0, um00200m.person_no, decode((   replace(    translate(     trim(sg00100m.person_id_custom),'0123456789','00000000000'    ),'0' ,null   )  ),null,to_number(trim(sg00100m.person_id_custom))) ) index3,               null as index4,               'cons_acctg' as groupname          from um00200m, sg00100m         where um00200m.person_no = sg00100m.person_no 	0.577218443269903
10624705	36256	display data only once	select     parents   , group_concat(name order by name) as children from   ( select          group_concat(p.id_parent order by p.name) as parents_ids       , group_concat(p.name order by p.name) as parents       , pc.id_child       , c.name     from parents p        join parents_children pc using(id_parent)       join children c using(id_child)     group by pc.id_child   ) as tmp  group by parents_ids ; 	8.90419274817578e-05
10624902	5900	sql moving average	select  (current.clicks    + isnull(p1.clicks, 0)   + isnull(p2.clicks, 0)   + isnull(p3.clicks, 0)) / 4 as movingavg3 from  mytable as current  left join mytable as p1 on p1.date = dateadd(day, -1, current.date)  left join mytable as p2 on p2.date = dateadd(day, -2, current.date)  left join mytable as p3 on p3.date = dateadd(day, -3, current.date) 	0.0137962355510705
10625583	12634	sql returns no rows via myodb, but in sql there are rows	select cast(sum(entry_data_1) as unsigned) as score from contests_entries 	0.00246994466180246
10626536	26855	compare multiple columns, but only those having valid values, and create y/n flag if all are equal	select id,         case           when c = 1 then 'y'           else 'n'         end as dflag  from   z_test         cross apply (select count(distinct d) c                      from   (values(d1),                                    (d2),                                    (d3),                                    (d4)) v(d)                      where  len(d) > 0                          and d like '%[^0]%' ) ca 	0
10626911	13690	mysql, how to query the table comments?	select a.column_name, a.column_comment from  information_schema.columns a  where a.table_name = 'your_table_name' 	0.0118285786106881
10630342	5835	mysql: apply order by on a field having datatype varchar	select id, name, cat from (select * from portfolio order by id desc) as x group by cat 	0.0927034644004923
10631081	173	determining if a particular query produces any results or has any results using linq	select app.newvalue).singleordefault();      if (appno == null)     {       insertapplicationno();       }     else     {      ..     } 	0.499220827084033
10631698	39109	how do i select a field from the result of a select?	select contractor_uid from (select r.realname contractor_name, u.uid contractor_uid...) t; 	0.000141159598784403
10632892	1706	how do i get a single line per customer including the first line of an order in sql	select c.*, o.* from customer c  join (select max(id) as order_id, customer_id        from order group by curtomer_id) conn on c.id = conn.customer_id join order o on o.id = conn.order_id 	0
10633379	27841	averaging multiple columns inside an sql table join	select reviews.style_id,        (avg("col1") + avg("col2")) / 2.0 from reviews, audios where reviews.consumer_id = audios.consumer_id group by style_id 	0.0595176707695332
10633618	21757	classic asp - display records from databse in the table week-wise or month-wise	select emp_number, datepart(year, order_date), datepart(month, order_date), datepart(wk, order_date), sum(grand_total) from order_details group by emp_number, datepart(year, order_date), datepart(month, order_date), datepart(wk, order_date) order by 1, 2, 3, 4 	7.15008111814482e-05
10635439	24739	mysql request from two tables	select u.id, u.username, u.email, group_concat(a.account) from users as u join accounts as a    on a.user_id = u.id group by u.id; 	0.00719603235156872
10635604	29367	check if a field content is not in the multiple field in other table	select players.* from   players   left join bans      on players.host in (bans.host, bans.second_host, bans.ip)    and (bans.expires >= unix_timestamp() or bans.expires = -1) where  bans.pk is null;   	6.47763614007187e-05
10637226	20222	how to use datetime fields as period range? are there some alternatives?	select ... where case rangetype   when 'daily'   then time(      now()) between time(      rangestart) and time(      rangeend)   when 'weekly'  then dayofweek( now()) between dayofweek( rangestart) and dayofweek( rangeend)   when 'monthly' then dayofmonth(now()) between dayofmonth(rangestart) and dayofmonth(rangeend)   when 'yearly'  then dayofyear( now()) between dayofyear( rangestart) and dayofyear( rangeend) end 	0.00423576683944335
10637559	17579	join two tables together and condense multiple rows in a single row	select ( select top 1 value from tableone t1 join tabletwo t2 on t1.rawdataid = t2.rawdataid where t1.rawdataid in ( select rawdataid from tabletwo where meterid = tbl.meterid ) and timestamp = dateadd(mi, -1440, tbl.timestamp) ) as valueb, ( select top 1 value from tableone t1 join tabletwo t2 on t1.rawdataid = t2.rawdataid where t1.rawdataid in ( select rawdataid from tabletwo where meterid = tbl.meterid ) and timestamp = dateadd(mi, -1439, tbl.timestamp) ) as valuec from tabletwo tbl 	6.79552330788797e-05
10638421	1759	stored procedure list and parameter number used in conjunction with combobox	select     sprocs.routine_name,     parms.parameter_name,     parms.data_type from     information_schema.routines sprocs     left outer join information_schema.parameters parms on parms.specific_name = sprocs.routine_name where     sprocs.routine_type = 'procedure' 	0.691362369401011
10638728	34045	t-sql: selecting column from an alternate table when null	select a.id, coalesce(a.cola, b.colb) as 'cola' from tablea a left join tableb b on a.id = b.id and b.colc = 70 	0.019012042786731
10639542	4027	consolidating and adding data to new lines to a field in a column in mysql table	select       x2.id,       stuff((select char(10)+x1.state+':'+x1.type from tablex x1 where x1.id=x2.id group by x1.id for xml path(''),type),1,1,'') as stype  from tablex x2 group by x2.id 	0
10639685	24345	return a string instead of field value when condition is met in mysql	select m.id, m.msg, if(user.id = 4, 'you', user.name) as name from m left join user on m.by = user.id 	0.000507814656859705
10639926	6440	sql query don't show duplication records	select     row_number() over (order by c.name) as myrow,     if(myrow=1,name,' ') as name,     o.productname as product from     customers c join     orders o on c.orderid = o.id 	0.00700703176577917
10640265	36678	tsql query for week comparison	select * from table where column between getdate()-14 and getdate()+14 	0.13274505959763
10640552	18456	mysql-db request: how to get the db-name and the db-type as output of the request	select table_name, table_type, engine from information_schema.tables where table_schema = 'yourdbname'; 	0.00254991859616442
10640743	4991	sql query, join multiple tables, oracle	select a.playerno, a.playername, sum(c.amount) as amount, b.teamno as team from players a, teams b, penalties c where a.playerno = b.playerno and a.playerno = c.playerno group by a.playerno, c.teamno having sum.... 	0.588249083998416
10640850	11560	mysql - grab default records if specific records arent found	select * from   table1 where  typeid = if((select count(*) from table1 where typeid = 5), 1, 5); 	0
10641372	35152	fetching result from different tables	select table1.application_id from table1  inner join table2 on table2.application_id = table1.application_id where table1.genre_id = 123 and table2.language_code = 'en' 	0.000977247935172202
10641768	30236	sql select and count at the same time	select   *, (     select count(*)     from morestuff     where morestuff.id = stuff.id       ) as total from stuff where id = '{$id}' 	0.000689496082184317
10641941	26985	sql server multiple tables query for a specific date from many	select * from (     select          *,         rn = row_number() over (partition by member_id order by id)     from         activity ) activitywithrn inner join detailed on detailed.activity_id = activitywithrn.id where activitywithrn.rn = 2 	0.00149105002957256
10642319	27410	can i have a real time query on sql server?	select * from logitems where id > @lastseenid 	0.195698392648091
10644061	25889	how to list all sequences in netezza database?	select * from  _v_sequence 	0.00578300639211827
10645469	6522	managing user points on q&a site	select u.user_id, sum( from points p join users u on p.point_user = u.user_id group by p.point_user 	0.591367183245271
10645887	40158	get birthdays a week before/during/week after	select * from table  where bday between curdate() - interval 7 day and curdate() + interval 7 day 	0.000466932224254524
10648149	13782	how to fetch record in mysql order by user_id desc and created_date ase	select  	0.00156862492793638
10649419	15182	pivot tables php/mysql	select week,      count(*) as total,      sum(technical) as technical,      sum(non_technical) as non_technical)  from(     select week,      case(type) when 'technical' then 1 else 0 end as technical,      case(type) when 'non-technical' then 1 else 0 end as non_technical ) as data group by week 	0.26558086475523
10649541	12168	mysql joining table data, needing to drag out data from both in 1 query	select s.store_location_id,     s.country,     s.latitude,     s.longitude,     d.name,     d.description,     d.city from store_locations s     join store_locations_descriptions d     on s.store_location_id = d.store_location_id 	0.000256240707121563
10650145	10091	postgresql: any on subquery returning array	select id, alias from users where (select user_list from user_lists where id = 2 limit 1) @> array[id]; 	0.557513383605522
10650674	8986	sql: compare if column values in two tables are equal	select a.accusedid , sum(a.accusedid) as cnt_a, sum(coalesce(b.accusedid, 0)) as cnt_b from a left join b on a.accusedid =  b.accusedid and a.articleid = b.articleid group by accusedid having cnt_a = cnt_b 	0
10652921	13013	t-sql group rows into columns	select * from (   select ref,           name,           link,          row_number() over (partition by ref, name order by link) rn   from table1 ) s pivot (min (link) for rn in ([1], [2], [3], [4])) pvt 	0.00166520991306692
10653969	5630	compare 2 fields and list the results in mysql	select user_id, username, total_exp from yourtable where total_exp = exp_since_death; 	0.000273887357814292
10655758	22025	truncating leading zeros in sql server	select count(test) as cnt,  substring(test, patindex('%[^0]%',test),len(test)) from (   select ('000200aa') as test   union   select '00000200aa' as test   union   select ('000020bcd') as test   union   select ('00000020bcd') as test   union   select ('000020abc') as test   )ty  group by substring(test, patindex('%[^0]%',test),len(test)) 	0.376374434031047
10657681	33039	change order of columns appearing in results, without changing select order	select     d.name    ,d.height    ,d.power    ,d.masteryken       ,d.blahnum    ,d.blahtext    ,d.blahdate    ,d.blahcalc    ,d.blahflag    ,d.blahflag    ,d.blahcompare from (select           vi.name          ,vi.height          ,vi.power          ,case when tt.losses < 3                then 'y'                else 'n'           end as masteryken          ,tt.blahnum          ,vi.blahtext          ,vi.blahdate          ,vi.blahcalc          ,tt.blahflag          ,vi.blahflag          ,vi.blahcompare       from senshivitalinfo vi        join tatakautable tt          on vi.namecd=tt.namecd      ) d 	0.00125344655858249
10659615	38703	get records that doesn't have connection	select products.* from  products right outer join join_table    on products.id = join_table.product_id   and join_table.property_id = 2 where products.id is null 	0.00209009515951051
10660250	18009	time slot from table with available hours (not time slots in table)	select start.day, start.hour from table as start  inner join table as hour1     on ((hour1.hour = start.hour + 1) and (hour1.tempres = '0000-00-00 00:00:00')) inner join table as hour2     on ((hour2.hour = start.hour + 2) and (hour2.tempres = '0000-00-00 00:00:00')) inner join table as hour3     on ((hour2.hour = start.hour + 3) and (hour3.tempres = '0000-00-00 00:00:00')) where table.tempres = '0000-00-00 00:00:00' 	0
10661734	18700	mysql - how to get results back from a table, and the count of how many joined items there are in one query?	select s.display_order, s.section_name, s.solution_section_id       ,count(c.comment_id) as comment_count   from solution_sections s   left outer join suggested_solution_comments c on (c.solution_part = s.solution_section_id)   group by s.display_order, s.section_name, s.solution_section_id   order by display_order 	0
10661849	1118	wordpress: using the category slug get the category id using mysql query	select wp_term_taxonomy.term_taxonomy_id from   wp_terms   join wp_term_taxonomy using (term_id) where  wp_term_taxonomy.taxonomy = 'category'    and wp_terms.slug = ? 	6.13983539325175e-05
10662458	12117	mysql substring_index reverse	select substr('www.java2s.sth.com', 1, (length('www.java2s.sth.com')-      length(substring_index(('www.java2s.sth.com'), '.', -1))-1));` 	0.761995195076904
10664953	11718	sort grouped rows in mysql statement	select a.name as 'customer name', b.title as 'order title' from customers a, orders b where a.id=b.customerid and b.timestamp_unix=(select max(c.timestamp_unix) from orders c where c.customerid=a.id) group by a.id 	0.0101222298678613
10665870	114	using xquery in oracle	select xmlquery('     for $customer in ora:view("customer")/row        return $customer/last_name ' returning content) from dual; 	0.647698599057749
10666590	38528	how to exclude replication tables in select from sysobjects	select * from sys.tables where is_ms_shipped = 0 	0.0047969982158817
10668177	16931	best practice for query to select a column twice	select c1.name, c2.name from concept c1 inner join concept_relation cr    on cr.firstconceptid = c1.id inner join concept c2    on cr.secondconceptid = c2.id where cr.relationid = 22 	0.0475949394039688
10668279	23791	flattened string of fields from an associated table in the result sets as a comma separated string	select u.*, e1.*, e2.*,         group_concat(t.team_name order by t.team_name) as team_names from employee_db e join employee_db e2 on l.manager_id = l2.id join users u on u.id = l.id join team_user_associations ta on ta.user_id = u.id join teams t on ta.team_id = t.id group by user_id 	0
10670075	7758	select top 1 from records with weight taken into account	select top 1 t.* from (select t.*, cumulative_sum(weight) as cumweight,              sum(weight) over (partition by null) as totalweight       from t      ) t where rand()*(totalweight+1) < cumweight order by cumweight desc 	0
10672918	6667	mysql - how to query for one value but default to another?	select * from table1 where this in(5,1) order by this desc limit 1 	0.000283038067273491
10673079	19991	selecting multiple max timestamps from database	select * from (   select * from products      order by timestamp desc ) as products_temp group by product_id; 	0.000118699078752792
10674110	24249	mysql sum multiple groups of data in a single table	select   name,   sum(time_to_sec(timediff(enddate,startdate))) totalruntime,   count(*) as totaljobs from results where name='name0' group by name; 	0.000138403958582995
10674745	15718	selecting the most popular entry from the last ten values entered	select tableorder.*  from (select *        from table       order by id desc        limit 10) tableorder  order by tableorder.popularity desc  limit 1 	0
10678997	40483	sql server 2005 group by with same column but different date and time?	select u.[date], u.prodcode from   (     select min(t.[date]) as startdate,            max(t.[date]) as enddate,            t.prodcode     from        (         select [date],                prodcode,                row_number() over(order by [date]) as rn1,                row_number() over(order by prodcode, [date]) as rn2         from yourtable       ) t     group by t.prodcode, t.rn2-t.rn1   ) t unpivot   (     [date] for d in (startdate, enddate)   ) u order by u.[date] 	0.000770768061896346
10679457	24376	dropping all view under particular schema - sql	select 'drop view ' + quotename(sc.name) + '.' + quotename(obj.name) + ';' from sys.objects obj inner join sys.schemas sc on sc.schema_id = obj.schema_id where obj.type='v' and sc.name = 'myview'; 	0.0499804139305098
10681276	36477	how to recive the last row id in the database?	select max(id) as latest_id from table_name 	0
10681467	41338	getting custom linear unique id in oracle in select statement based on date	select request_id,        name_of_training,        applied_date,        to_char(applied_date,'mon-yy') || '/' || row_number over (partition by to_char(applied_date,'mon-yy') order by to_char(applied_date,'mon-yy')) as uniqueorderid from tablename; 	0.000182895797405511
10681545	36214	`single-row subquery returns more than one row` error unclarity	select distinct id from name where text1='first_name'  and id in ( select name_id from value where text2='john') 	0.782725157205698
10683149	26411	multiple query in one query	select  'myfirstcontrol' as controlname, thisvalue as controlvalue from    thattable1  where   condition1  union all select  'mysecondcontrol' as controlname, thisvalue as controlvalue from    thattable2 where   condition2 union all select  'mythirdcontrol' as controlname, thisvalue as controlvalue from    thattable3 where   condition3 	0.123174181033404
10684420	38049	aggregate values and pivot	select     pvt.buildingid,     pvt.snapshotid,     pvt.timestamp,     pvt.[6] as electricity,     pvt.[7] as gas,     pvt.[8] as water from     (     select          meterdataoutput.buildingid,          meterdataoutput.value,          meterdataoutput.timestamp,          utilityid,          snapshotid      from @meterdataoutput as meterdataoutput      inner join @insertoutput as insertoutput          on meterdataoutput.buildingid = insertoutput.buildingid         and meterdataoutput.[timestamp] = insertoutput.[timestamp]     ) as sourcetable pivot (     sum(value)     for utilityid in ([6],[7],[8]) ) as pvt 	0.417412669769656
10684686	1931	how can i select distinct rows for sum()?	select    date_format(transactions.createdate,'%m-%d') as monthandday,    date_format(transactions.createdate,'%m, %d') as day,    sum(transactions.amounttotal) as dailysales from    transactions where    transactions.transaction_id in (select distinct transaction_id from plots) and    transactions.createdate <= curdate() and    transactions.createdate >= date_sub(curdate(),interval 3 month) group by    monthandday order by    monthandday asc; 	0.005413269216339
10687618	24782	retrieving a piece of text form a text field in mysql db until a special character is found	select substr( your_column, instr( your_column,  'start_char_goes_here' ) , instr( your_column,  'end_char_goes_here' ) - instr( your_column,  'start_char_goes_here' ) )  from your_table 	0.000436237696554697
10687857	5897	how can i combine multiple rows into a comma-delimited list in sql server?	select x.x_id, x.x_name, y_value = stuff((select ',' + y_value from dbo.y   where y.x_id = x.x_id   for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '')   from dbo.x; 	0.000279887147647333
10688272	23294	is it possible to select the highest value of a dense_rank() field as a field?	select v.*, max(row_num) over () as max_row_num from  ( select ...,   dense_rank() over(order by a.distance, a.state || a.idnum, a.taxid, a.location) row_num   from ... ) 	0
10688764	22324	how to see hql final query	select c from content c where lockedtimestamp <= dateadd(minute, -6, getdate()); 	0.572056864714339
10690179	9095	with ms access and sql, how do i create one table and 1 set of columns from 2 separate select queries on a single table?	select tablea.* from mastertable_1 inner join tablea on mastertable_1.id = tablea.id where mastertable_1.field = 'some specific value'; union all select tablea.* from mastertable_2 inner join tablea on mastertable_2.id = tablea.id where mastertable_2.field = 'some specific value'; 	0
10691023	21974	how to compare two tables and show only results not equal to 0	select  * from    stl_wk_vw a join    tdn_summary b on      b.id = a.id group by         b.id having  abs(sum(missing + non_missing)) > sum(case when standard not like '%non' then st_total end) 	0
10691330	41096	mysql count for days	select cast(date(from_unixtime(`time`)) as char) as dateoftime, count(ip) as cnt from tablename where date(from_unixtime(`time`)) > date_sub(current_timestamp, interval 10 day) group by cast(date(from_unixtime(`time`)) as char) 	0.00462982249876008
10691443	17434	how do i get primary key from database using another column's value? (android, sqlite)	select id from table where name is myvar 	0
10691560	15254	group by range of timestamp values	select food_id, count(*) from food_logs group by date(log_date, 'unixepoch'); 	0.000286980480556067
10691744	28607	mysql nested set retrieving path with join	select parent.placeid, parent.name, parent.type, parent.ico, url from places as node, urls left join places as parent on parent.urlref = urls.urlid where node.lft between parent.lft and parent.rgt and node.urlref = :urlid order by parent.lft 	0.586065579993715
10691824	19336	how to combine result of two select statements	select job, quantity, status    from mytable  order by case when quantity >= 400 and status = 'ok' then 1                 when quantity >= 400 and status = 'hold' then 2                when status = 'ok' then 3                else 4           end 	0.00305484921683916
10692026	16345	get a count of one column based on another column	select buyer_id, count(distinct acct_id) from table1 a where exists (   select * from table1   where acct_id = a.acct_id      and buyer_id =5) group by buyer_id 	0
10692153	26362	mysql select need count if field less than 0 and greater than 0	select sum(case when x > 0 then 1 else 0 end) as greatherthanzero     , sum(case when x = 0 then 1 else 0 end) as equalzero from table where x >= 0 	0.00505624039145669
10693080	21056	sql retrieve data from parent type	select   l.name,   l.email,   e.description as expertise from lecturer_has_expertise le   inner join lecturer l on l.id = le.lecturer_id   inner join expertise e on e.id = le.expertise_id where e.description = @inputexpertise    or exists (      select *      from lecturer_has_sig ls        inner join sig_has_expertise se on ls.sig_id = se.sig_id        inner join expertise e on e.id = se.expertise_id      where e.description = @inputexpertise        and ls.lecturer_id = le.lecturer_id    ) 	0.000380055881777727
10693728	33686	how to add mysql sum() function to this query?	select p.post_id, p.user_id, u.username,     get_time_diff(p.date) as date, p.ip, p.text,     p.parent_post_id, p.approved as posts, ifnull(v.vote_count, 0) as vote_count from msgboard_user u, msgboard_post p left join (select post_id, count(*) vote_count from msgboard_vote group by post_id) v on p.post_id = v.post_id where p.user_id = u.user_id and p.approved = "yes" order by p.date desc 	0.791479864522597
10694894	26549	find all leaf node records using hierarchyid	select a.hieracrchyid, a.hierarchyid.tostring()   from dbo.tablea as a    left outer join dbo.tablea as b   on a.hierarchyid = b.hierarchyid.getancestor(1)   where b.hierarchyid is null; 	0.000173255572960347
10695717	3029	how to get selected number of rows in select statement?	select sender, count(*) as cnt from messages where message_id = :message_id group by sender 	0
10696649	34988	how to get table's schema name	select    object_schema_name(f.parent_object_id) as tablenameschema,    object_name(f.parent_object_id) as tablename,   col_name(fc.parent_object_id,fc.parent_column_id) as columnname,   object_schema_name(f.referenced_object_id) as referencetablenameschema,   object_name (f.referenced_object_id) as referencetablename,   col_name(fc.referenced_object_id,fc.referenced_column_id) as referencecolumnname,   f.name as foreignkey from   sys.foreign_keys as f   inner join sys.foreign_key_columns as fc on f.object_id = fc.constraint_object_id   inner join sys.objects as o on o.object_id = fc.referenced_object_id 	0.00408848717643909
10698450	35370	sum a column when another column has equal values	select place_id, sum(area_sq)/count(distinct n) from your_table group by place_id; 	0
10699792	37332	sql query for unique set of record	select name_1, dpid_clid, city  from dts_master_dividend  where upper(name_1) like upper('%') and dpid_clid like upper('in30290243450560%') group by name_1, dpid_clid ,city 	0.00235937809820971
10699997	21343	sql server - transpose rows into columns	select [1234], [1235] from (     select     id = 1234,     value = 1     union     select     id = 1235,     value = 2 ) a pivot (   avg(value) for id in ([1234], [1235]) ) as pvt 	0.00125490749316082
10700892	35019	find details for minimum price entry for each group of rows with the same article number	select b.*   from bigtable as b    join (select ean, min(price) as price           from bigtable          group by ean        ) as p     on b.ean = p.ean and b.price = p.price  order by b.ean; 	0
10701118	15965	mysql query compare 2 table values	select chat.*,             timestamp.*,            wp_posts.*        from wp_posts inner join wp_postmeta chat         on wp_posts.id = chat.post_id             and chat.meta_key = 'aw_chat_id' inner join wp_postmeta timestamp         on wp_posts.id = timestamp.post_id             and timestamp.meta_key = 'aw_chat_timestamp'      where wp_posts.post_type = 'chatt'        and timestamp.meta_value > 2        and chat.meta_value = 'test-chat-av-chattuser' 	0.00142153684631081
10701195	39034	mysql query - counting like terms	select term from tablename group by term order by count(*) desc 	0.676266316912917
10701730	34154	find latest value earlier than specified date	select top 1   rate from   mytable where   datecolumn <= '20120520' order by   datecolumn desc 	0
10702154	18002	select users with certain rights	select users.id,         user_info.first_name,         user_info.last_name,         user_rights.right  from   users         inner join user_info           on users.id = user_info.user_id         left join user_rights           on user_rights.user_id = users.id              and user_rights.right = '101'         left join groups           on user_rights.group = groups.group              and groups.group_name = 'human resources'  order  by user_info.first_name; 	0.000911773834053781
10703061	39600	create a full many-2-many matrix	select allab.aid, allab.bid, max(case when ab.aid is not null then 1 else 0 end) as haspair from (select distinct a.id as aid, b.id as bid       from tablea a cross join            tableb b      ) as allab left outer join      tableab ab      on allab.aid = ab.aid and         allab.bid = ab.bid group by allab.aid, allab.bid 	0.760075757914313
10703201	33048	get data type without the ui	select data_type  from information_schema.columns where table_name = 'tablename' and column_name = 'columnname' 	0.0135214737224138
10704172	31915	mysql innodb, fetching parent rows and their children in order for rendering in an ul	select * from group order by concat_ws('_', fk_parent_group_id, id) 	0.000137906171243724
10706617	25055	how to combine columns from 2 tables into 1 without using join	select firstname as first, lastname as last from (   select row_number() over (order by id) as rownum, firstname   from firstname ) t1 inner join (   select row_number() over (order by id) as rownum, lastname   from lastname ) t2 on t1.rownum = t2.rownum 	0
10707291	19996	select data from table and compare column in the same table	select io.carid from insurance as io where dateadd(day, 1, io.enddate) in     (select ii.startdate      from insurance as ii      where ii.carid = io.carid); 	0
10708202	27711	sql convert int to datetime	select datetime( 1323648000, 'unixepoch' ); 	0.12867186105946
10709115	6934	how can i return sql results that are only about specific attributes?	select  id from    (         select  distinct id         from    rel_aid_to_attributevalue a         where   attributevalueid in (1319, 1320)         ) q where   not exists         (         select  id         from    (                 select  attributevalueid                 from    tbl_attributevalues                 where   attributetypeid = 1                         and attributevalueid not in (1319, 1320)                 ) t         join    rel_aid_to_attributevalue a         on      a.id = q.id                 and a.attributevalueid = t.attributevalueid         ) 	0.00202484275684688
10712349	34150	mysql sub-select from same table	select      sku,      quantity from      inventory inv where     inv.date = getdate() - 1     and inv.quantity < (select min(prev_inv.quantity)                          from inventory prev_inv                         where                              prev_inv.date < getdate() - 1                              and prev_inv.sku = inv.sku                        ) 	0.00857689099498045
10712358	35895	mysql and or on many to many table	select    id  from    word_relationships where   (word_a = w1 and word_b = w2) or   (word_a = w2 and word_b = w1) 	0.062694535090375
10717541	40337	group by and selection of columns	select    mcid,   max(timedone),  program,  deviceid,  orderno from  trace where   pcbid = 'c825514362' and  deviceid <> 0 group by   mcid,  program,  deviceid,  orderno 	0.0139047516060832
10718906	5240	maximum difference between rows	select v.id, v.value  from values v  where exists(     select null from values v2      where v2.id <> v.id and     abs(v2.value - v.value) between 0 and 5 ) 	0.00012334215937763
10722579	26345	get rows with second-most-recent timestamp by category?	select   t1.*, count(*) pos from formstatus t1   left join formstatus t2     on t2.form = t1.form and t2.timestamp >= t1.timestamp group by   t1.form, t1.timestamp having   pos = 2; 	0.000159087439252309
10723903	27825	ms access distinct records in recordset	select c.*  from   component c  where  c.id in (select c.component_id                  from   widget w                         inner join widget_component c                           on w.id = c.widget_id                  where  w.mfg_id = 123) 	0.0387197946436506
10725846	1426	sum until a certain point	select t.item, t.transaction_date, t.adj_qty,         sum(tprev.adj_qty) as cumsum from t t join      t tprev      on t.item = tprev.item and         t.transaction_date >= tprev.transaction_date group by t.item, t.transaction_date, t.adj_qty having 100 between sum(tprev.adj_qty) -t.adj_qty + 1 and sum(tprev.adj_qty) 	0.000860021975699863
10726936	7743	sql query count from instances	select  busid, count(*) from    (         select  busid, studentid,                 row_number() over (partition by studentid order by id desc) rn         from    bussignupinstance         ) q where   rn = 1 group by         busid 	0.0104525144967823
10728000	213	how can i make a query for each month of each year in mysql?	select year(datefield), month(datefield), count(field1), count(field2) from table group by year(datefield), month(datefield) 	0
10728083	32533	getting total download bandwidth served from file size and total download count	select sum(size*downloads) as bandwidth from files f    join users u       on f.u_id = u.u_id where u.username = ? group by u.u_id 	0
10728219	33418	recommended techniques for merging database records	select *   from maintable   where mainid = 1 union all select maintable.*   from mergetable   inner join maintable     on maintable.mainid = mergetable.currentmainid   where mergetable.originalmainid = 1 limit 1 	0.0184244073544226
10728467	23455	how to calculate a ratio and cater for division by zero in sql	select cast([timestamp] as date) as 'day'   , sum(p) as pas   , sum(u) as ufr   , sum(d) as des   , sum(f) as fir   , sum(m) as mol   , isnull( (sum(m) / nullif( sum(p) * 1.0000 + sum(u), 0 ) ) *100, 0) as [m%] from dataset group by cast([timestamp] as date) order by [day] desc 	0.00743540564421301
10728537	3491	adding the same foreign key to 96 columns of a table	select  concat("constraint `fk_library_mix_lib_id`",column_name,"     foreign key (`",column_name,"` )     references `library` (`lib_id` )     on delete no action     on update no action ") as sqlstatement from information_schema.columns where table_name ="library_mix" and column_name like "index%" 	0
10729020	35182	randomly picking entity not yet in a join table	select i.id from items i  left join users_items ui on ( i.id = ui.item_id and ui.users_id = 2 ) where ui.item_id is null; 	0.154546951100616
10729460	27792	return 0 when result is empty	select numberofaccedentinyear = isnull (   (select count(accedentid)    from         accident    group by driverid, year(accedentdate)    having     (driverid =@driverid)<3))    , 0 ); 	0.200788592777413
10730873	25981	wordpress users and usermeta - joining multiple rows in one table to one row in another table	select     u1.id,     u1.login,     u1.password,     u1.email,     m1.meta_value as firstname,     m2.meta_value as lastname,     m3.meta_value as country from wp_users u1 join wp_usermeta m1 on (m1.user_id = u1.id and m1.meta_key = 'first_name') join wp_usermeta m2 on (m2.user_id = u1.id and m2.meta_key = 'last_name') join wp_usermeta m3 on (m3.user_id = u1.id and m3.meta_key = 'country') where 	0
10732507	9692	get all userid friends give unnexpected result	select  id, fid, name from users,friends where users.id=friends.fid where users.id = 33456 	0.000476233344023394
10732673	32304	select statement in oracle	select column20/100 computed_col20, a.*   from table_name a 	0.632186497318134
10733010	5975	how to use union all with manual value (not from another tabel)?	select csatuan2,csatuan1,nkonversi from ms_metriks  union all select 'ltr','pcs','1' union all select 'pcs','ltr','1' 	0.00439930431304126
10733141	25511	sql server, how can i transpose data of a column	select stuff (  (select n', ' + city from citytable for xml path(''),type)   .value('text()[1]','nvarchar(max)'),1,2,n'') 	0.0108433744542428
10734420	40976	sql query in listview	select inlt_parentcompanyid,inlt_effectinterest,inlt_sharetype,inlt_shares,inlt_childcompid,inlt_effectinterest,inlt_sharetype,inlt_shares from interestlogtable inner join interestlogtable on interestlogtable.intl_parentcompanyid=interestlogtable.inlt_parentcompanyid where 	0.735495746612862
10736828	2061	display all tables in a single row in new table	select sum(case when s.assettype = 1 and                       s.assetsubtype = 4                  then 1 end) as 'physicalservers',        sum(case when s.assettype = 1 and                       (s.assetsubtype = 1 or s.assetsubtype = 3)                  then 1 end) as 'workstations',        sum(case when s.assettype = 2 and                       s.assetsubtype = 16                  then 1 end) as 'emailonlyusers',        sum(case when s.assettype = 1 and                       s.assetsubtype = 4 and                       s.operatingsystem = 1                  then 1 end) as '#ofmsservers',        sum(case when s.assettype = 1 and                       s.assetsubtype = 4 and                       s.operatingsystem = 2                  then 1 end) as '#oflinuxservers' from asset s where s.companyid = @companyid 	0
10736852	25912	search over item ids in amazon sdb	select * from domain where itemname() like '1234%' select * from domain limit n select * from domain where itemname() like '1234%' order by itemname() limit 2500. 	0.00688381391067766
10738265	21644	mysql, actualize datetime column	select max(`timestamp`) from yourtable into @a_variable; update yourtable set `timestamp` = date_sub(`timestamp`, interval timestampdiff(second, now(), @a_variable) second) 	0.0844695941388783
10738753	16115	finding the max and min date values in sql server tables	select tabone.*,         last.reading lastreading,         first.reading firstreading from tabone outer apply (   select top 1          reading     from tabtwo    where tabtwo.val_key = tabone.val_key   order by tabtwo.date desc ) last outer apply (   select top 1          reading     from tabtwo    where tabtwo.val_key = tabone.val_key   order by tabtwo.date asc ) first 	0.000255164641466076
10739280	41161	average posts per hour on mysql?	select the_hour,avg(the_count) from (   select date(from_unixtime(`date`)) as the_day,     hour(from_unixtime(`date`)) as the_hour,      count(*) as the_count   from fb_posts   where `date` >= unix_timestamp(current_date() - interval 7 day)   and created_on < unix_timestamp(current_date())   group by the_day,the_hour ) s group by the_hour 	0
10739867	34495	what' the difference between these 2 sql commands?	select * from studysql.dbo.id_name n left join studysql.dbo.id_sex s on n.id=s.id and s.sex='f' select * from studysql.dbo.id_name n left join studysql.dbo.id_sex s on n.id=s.id where s.sex='f' 	0.0558805521225109
10741093	39626	update sysdate - 10 min in oracle	select sysdate - 10/(24*60) from dual; 	0.0177861844110308
10741424	17981	mysql query for joining three tables	select requests.*,requesters.requesters_name,count(1) as c from requests left join requesters on requesters.requester_id = request.requester_id left join responses on responses.request_id = requests.request_id group by requests.request_id 	0.101054900007124
10742367	13342	reporting services expression avoid comma if the field value is null	select coalesce(address + ',', '') + coalesce(city + ',', '') + ... 	0.681141501167617
10742751	26385	mysql converting a substring losing number after decimal	select  substring(plugintext,locate('cvss', plugintext), 21) as cvss_base_score_text,  convert(substring_index(substring(plugintext,locate('cvss', plugintext), 21),' : ',    -1),   decimal(10,1)) as cvss_base_score_number  from vulnerabilities_internal 	0.0756000653360676
10743776	35586	how to select two different datasets with mysql	select     count(*) total,     sum(if(read='1',1,0)) total_read from messages where id='1'; 	0.00278339072331071
10744726	40677	select top nth group by time	select actual.dateandtime, actual.tag, actual.val from resulttable actual left join resulttable exclude on exclude.date = actual.date and exclude.hr = actual.hr and exclude.min = actual.min and exclude.dateandtime > actual.dateandtime where exclude.dateandtime is null 	0.00237564765271096
10746248	13167	sql join 2 tables to 1 table	select * from task t left join unit ut on ut.id = t.unit_id left join building bt on bt.id = t.building_id 	0.0127635688820107
10749121	27236	how to regroup records with different values in one sql query	select * from (select *,case when country ='switzerland' then 'a'                          when country ='italy' then 'a'                            when country ='france' then 'b'                            when country ='england' then 'b'                       else 'c' end) classification from table1)          order by classification 	0.00014795707269721
10749665	25379	parent child relationship in oracle	select parentid parent, id child    from table1 connect by prior id = parentid   start with parentid = 1 	0.0119303979799712
10751534	11715	php mysql search with like matches too many rows	select id,title from research where members like '%|$arr[0]|%' or members like '$arr[0]|%' or members like '%|$arr[0]' 	0.54591442954613
10752601	35933	how do i match two values from 1 column in mysql	select  * from    combination c left join         option o on      o.id = substring_index(c.combination, '_', 1) left join         variant v on      v.id = substring_index(c.combination, '_', -1) 	7.49363154100861e-05
10754720	27428	mysql query multiple year values	select * from `table`  where year in (7, 8, 9, 10, 11, 12) order by parent desc, student asc, audience desc 	0.00723114062493866
10754812	30747	auto number and reset count for each different column value	select if(@prev != a.clientid, @rownum:=1, @rownum:=@rownum+1) as rownumber, @prev:=a.clientid, a.* from ( select  visitdate,  clientid  from visit, (select @rownum := 0, @prev:='') sq order by clientid,visitdate ) a 	0
10755834	29158	sql: table with multiple foreign keys linking to the same primary (2)	select p.name as 'player name', m.matchid as 'match id', case s.scorerid when isnull(s.scorerid,0) then 'yes' else 'no' end as 'scored?', s.name as 'scorer name'  from match m inner join player p on p.player_id in (m.playerid1, m.playerid2, m.playerid3) left join scorer s on s.matchid = m.matchid     and s.player_id in (m.playerid1, m.playerid2, m.playerid3) 	0
10757002	29469	mysql select highest record for each relation	select   t1.name, t1.version, t1.project_id from   tablename t1 join   (select max(version) as version, project_id from tablename group by project_id) t2 on t1.project_id = t2.project_id and t1.version = t2.version 	0
10757075	25173	ignoring a column when joined column has more than one value	select      o.id, o.name, a.address from      orgs o left outer join      (select orgid from addresses group by orgid having count(*) > 1) x on o.id = x.orgid left outer join      addresses a on x.orgid = a.orgid and o.addressid = a.id 	0
10759089	6313	sql server convert timestamp datatype to decimal	select val, cast((convert(bigint, timestampcol)) as decimal) as 'ts as decimal'  from teststmp 	0.0581736510847232
10760203	9106	select records but if null, show a message	select coalesce(    (select somefield from sometable where [@sometablevariable].someid = @someid),   'none to delete' ) 	0.00225333514815773
10760830	37951	most common number in mysql select statement	select quantity,count(*) from ... group by 1 order by 2 desc limit 1; 	0.000876676161169956
10761611	35320	how to merge db rows together?	select q.questionid,        q.questioncontent,        group_concat(an.answer, separator ' ') from answer an inner join question q on q.answerid = an.answerid group by q.questionid,        q.questioncontent 	0.00308486859609617
10762342	8355	one to many query with two date constraints	select items_register.ir_id, items_register.ir_name,      items.i_version_name, items.i_datetime from items_register join (     select items.i_register_id,          max(items.i_datetime) as most_recent_item_datetime     from items     where items.i_date_expiry > '$f_date'     group by items.i_register_id ) as item_date on item_date.i_register_id = items_register.ir_id join items on items.i_register_id = items_register.ir_id      and items.i_datetime = item_date.most_recent_item_datetime 	0.00106080921330594
10763031	12353	how to subtract 30 days from the current datetime in mysql?	select * from table where exec_datetime between date_sub(now(), interval 30 day) and now(); 	0
10764838	34231	how can i sum two or more count values in mysql query?	select   client_name.client_name,          escort,          sum(mission_status_reason = 4)        as awaiting_upload_at_origin,          sum(mission_status_reason = 6)        as awaiting_military_escort,          sum(mission_status_reason = 3)        as enrouted_to_destination,          sum(mission_status_reason = 9)        as awaiting_download,          sum(mission_status_reason in (3,6,9)) as total from     usc_tmr left join client_name on client_name.id = usc_tmr.client_name where    escort = 'usg' and mission_status_ops in (1,4,5,6) group by client_name 	0.0167515208431803
10765225	10712	merging and sorting two tables	select unixtime, id, type, type_id from (( select unixtime, id, 'comment' as type, threadid, forumid         from (  select unixtime, id, threadid                 from comments                 order by unixtime desc) as h         group by threadid)         union all       ( select unixtime, id, 'thread', id, forumid         from threads)         order by unixtime desc) as h2 group by threadid order by unixtime desc 	0.00458298669106883
10765460	17713	how to fill a field with random unique numbers in sql2008	select abs(cast(cast(newid() as varbinary(5)) as bigint)) as uniqueno 	9.88048951878824e-05
10765657	28203	select a column based on multiple condition (many to many relation)	select classes.classid, classes.classname, subjects.subjectid, subjects.subjectname, teachers.teacherid, teachers.teachername from (teachers inner join (classes inner join teacherclass on classes.classid = teacherclass.classid) on teachers.teacherid = teacherclass.teacherid) inner join (subjects inner join teachersubject on subjects.subjectid = teachersubject.subjectid) on teachers.teacherid = teachersubject.teacherid where classes.classid = k and subjects.subjectid = p group by classes.classid, subjects.subjectid, teachers.teacherid, classes.classname, subjects.subjectname, teachers.teachername; 	0.000309935039316211
10766689	38964	how to make search on time in sql server?	select * from your_table where cast(time_column as time) between '10:00:00' and '11:00:00' 	0.244830740925972
10768176	38810	compare two tables and extract missing element per date	select     d.dateplaying, p.nameplayer from     table2 p cross join      (select distinct dateplaying from table1) d left join     table1 t on t.idplayer = p.idplayer and t.dateplaying = d.dateplaying where     t.idplayer is null 	0
10768318	874	php/mysql merge duplicate records in table and create a new table	select min(id), username, min(filename), min(date), min(desc), storetype,  min(password), min(email), min(ftp)  from table1  group by username, storetype 	0
10768566	16777	sql count by room type	select room_type, count(*) as numarrezervari from   dbo.reservation re join   dbo.room ro on ro.roomid = re.roomid join   dbo.room_type rt on rt.room_type_id = ro.room_type_id where  month(re.data_check_in) = 5 group  by room_type 	0.212511385263996
10769354	13210	select parents with childs and count of childs for each parent	select a.ind, count(*) total  from a join b on a.lid = b.lid where a.ind>0 and b.yes = 0 group by a.ind order by a.ind 	4.85659174801015e-05
10769386	15089	mysql - return when row doesn't exists in other table or exists and the field is greater than x	select distinct links_clicks.linkid from (select links.id as linkid   from links   left join clicks on links.id = clicks.linkid  where links.id is null or clicks.click_date <= curdate())  as links_clicks; 	0
10771506	6937	retrieving rows based on time in sql server 2008	select * from mytable where starttime <= '08:40:00'   and endtime   >= '08:00:00' 	0.000254333858177242
10771711	10920	three counts in one sql query	select fruit, count(id) from table group by fruit 	0.0382104642338991
10772775	26357	select the max number of repeated records in a sql table	select name, max(score) from <table_name> group by name 	0
10773835	21630	amount of rows in database table	select count(*) from table_name; 	0.000146579650535047
10775070	1293	getting end date from start date	select id, name, start_date, lead(start_date) over (partition by name order by start_date) as end_date, post from emp; 	0.000162532228131432
10775458	31337	work out the nearest users mysql	select *, (acos((sin(radians(ref_latitude))*sin(radians(latitude))) +  (cos(radians(ref_latitude))*cos(radians( latitude ))*cos(radians( longitude) -radians(ref_longitude)))) * 6371) as distance from table order by distance asc 	0.255181758184881
10776340	41189	most popular products of store , array from table 1 and shown on table 2	select p.* from products p inner join (select item_id, views from $tablename) as i on i.item_id = p.item_id order by i.views desc  limit 5 	0
10776804	3140	sql, finding most recent entry in conversation between two people	select * from messages main left join messages earlier     on earlier.time < main.time and          (             earlier.to_user = main.to_user and earlier.from_user = main.from_user or               earlier.to_user = main.from_user and earlier.from_user = main.to_user         ) where (main.to_user = x or main.from_user = x) and earlier.id is null order by main.time desc 	0
10776880	21455	conditional joins based on column value	select      event.type as type,     if(type = 'birthday', birthday.id, null) as birthday_id,     if(type = 'graduation', graduation.id, null) as graduation_id,     if(type = 'wedding', wedding.id, null) as wedding_id from      event         left outer join birthday b  on event.target_id = b.id         left outer join graduation g    on b.id is null and event.target_id = g.id         left outer join wedding w   on b.id is null and g.id is null and event.target_id = w.id 	0.00880486029510479
10777107	4682	which join to get entry even if it is not known in other table	select t2.*, case                 when u.username is null                 then 'unknown'                 else u.username               end as u_name       from table2 t2 left outer join users u on t2.left_user_id = u.user_id  where t2.right_user_id = '.$user_id.'      order by t2.time desc; 	7.88524558052781e-05
10779519	14114	postgres join queries	select wt.work_type,pm.emp_name as projectmanager,ar.emp_name as arhitect,tl.emp_name as  techlead,dept.dept_name as department from work  inner join employees as pm on (wt.project_manger_id=pm.emp_id) inner join employees as ar on (wt.architect_id=ar.emp_id) inner join employees as tl on (wt.tech_lead_id=tl.emp_id) inner join dept as dept on (wt.dept_id=dept.dept_id) 	0.556767703673056
10779931	12325	sql serial number by group	select  *,         dense_rank() over (order by name) from    mytable 	0.0113090705174821
10780787	33517	count (*) statement tips	select  country, sum(units) from    mytable group by country 	0.396207709674036
10781326	1085	how to ignore collation in mysql query	select  * from    tblcoutnry where   find_in_set(cast('kan' as char character set latin1) collate latin1_general_ci, tlang) 	0.79318465089818
10781878	4819	compare and select three top results	select name_tbl.*, ( (arts_tbl.score+science_tbl.score+sports_tbl.score)/3 ) as avg_score from name_tbl  left join arts_tbl on name_tbl.name_id = arts_tbl.name_id  left join sports_tbl on name_tbl.name_id = sports_tbl.name_id  left join science_tbl on name_tbl.name_id = science_tbl.name_id  order by avg_score desc limit 3 	0.00346393830549599
10784409	10215	select rows if the sum of a field in the table is less than x for each date in the table	select start, end, a.date, slots, totals          from 1000_appointments a         join         (select sum(slots) as totals,date             from 1000_appointments              where date > now() and hour(end) <= 12 and employeeid='1000001'             group by date having totals < 6         ) t          where a.date = t.date 	0
10784793	10110	sql query joining	select d.emp_name from emp_table t join emp_detail d on t.emp_id = d.emp_id 	0.416783349542686
10785356	13280	nested select with a previous selected value in sql server 2008	select i.column_name,        i.data_type,        i.character_maximum_length,        (        select t.x.value('/*[local-name(.)=sql:column("i.column_name")][1]', 'nvarchar(max)')        from           (          select *          from mytable          for xml path(''), type          ) as t(x)        ) as column_value from information_schema.columns as i where i.table_name = 'mytable' order by i.ordinal_position 	0.0530848851028674
10785518	12753	asp.net / c# sqldatasource commands and parameters based on table	selectedindexchange 	0.154727292547234
10785640	29522	postgres query (more than function)	select human.name, car.human_id, count(*) as total from human, car group by human.name, car.human_id having count(*) > 1 	0.691612585926007
10785922	24061	mysql select from more than one table	select     members.main,     members.id,     image.main,     image.thumb,     bio,     altered,     members.title,     author from members left join image on members.main = image.id 	0.000849190814498901
10786253	11424	select those event that came on same day from table which contain date column in milliseconds?	select event_id,        event_title,        datetime(event_date_in_milli_sec / (24 * 60 * 60 * 1000)) as dt from table_events order by dt 	0
10786921	36315	ordering by sql on fields not in projection	select a,b,c from (select a,b,c,d from mytable order by d) 	0.398063499511482
10787765	14781	selecting daily/hourly data	select extract(hour from date_time_of_task) as thehour,        sum(case when extract(day from date_time_of_task) = 1 then 1 else 0 end) as day_01,        sum(case when extract(day from date_time_of_task) = 2 then 1 else 0 end) as day_02,        sum(case when extract(day from date_time_of_task) = 3 then 1 else 0 end) as day_03,        sum(case when extract(day from date_time_of_task) = 4 then 1 else 0 end) as day_04,        ... up to day 31 group by extract(hour from date_time_of_task) order by 1 	0.0296596455172904
10792105	30264	mysql comparing field using concat with two fields	select concat_ws('/', exp_year, exp_month) as exp_date  from `cc_info` where concat_ws('/', exp_year, exp_month) <= '12/05' 	0.0107087800796013
10792743	10497	joining in another table with possible new values for field	select zip from submission union select zip from addresses 	0.000212558875656771
10793219	31120	sql join - all stores where employee has not worked	select * from stores s where id not in (     select storeid     from employeestorerelationshiptable     where employeeid=[employeeid]) 	0.012188253437666
10793685	26915	sum sql fields together for total result	select sum(week1) + sum(week2) + sum(week3) + sum(week4) + sum(week5) +           sum(week6) + sum(week7) + sum(week8) + sum(week9) + sum(week10) +           sum(week11) + sum(week12) + sum(week13)   from results   where username = '$username'   group by username 	0.00217218525516102
10794099	22023	how to display specific data in year	select * from di_elemod where paydat >= trunc(p_paydat, 'yyyy')  and paydat <= trunc(add_months(p_paydat,12),'yyyy')-1 	0
10795990	33573	display positive result with a plus sign (+) in sql	select    case       when convert(decimal(11,1),sum(column/1000*-1)) >= 0       then concat('+', convert(decimal(11,1),sum(column/1000*-1)))       else convert(decimal(11,1),sum(column/1000*-1))    end as name from table 	0.00653749678766212
10796067	20885	sql query to count ads added in the last 7 days	select count(*) from   table_name where  user_id = 20 and created_date > now() - interval 7 day 	0
10796465	29475	mysql: how to limit to query?	select date, uid from users where date >= 'your date'   and date < 'your date' limit 0, 3 	0.296323722947755
10797147	30502	make a sequence in oracle database	select 'ltr' || to_char('09999', the_sequence.nextval) from dual; 	0.357112917808384
10799427	15415	how to match string with escaped quote character in mysql?	select t1.title from myrecords as t1 where replace(title,'\\\"','@') like "%@%"; 	0.218155471350018
10799785	1340	get rows from the table using row no in sql server	select * from (select row_number() over (order by @column) as row,*  from  table) as t where row between 100 and 150 	0
10801329	35428	mysql - order by and leading zeroes	select code from your_table order by cast(code as signed) 	0.385488980915352
10801503	9292	count ids inside the grouped tables	select fullname,company_id from ( select sum(i.grosstotal) as total,    sum(i.other_money_value/1.18) as other_total,    count(ir.product_id) as no_products from company c join #dsn2_alias#.invoice i      on c.company_id=i.company_id join #dsn2_alias#.invoice_row ir on i.invoice_id=ir.invoice_id join #dsn3_alias#.product p      on p.product_id=ir.product_id join #dsn3_alias#.product_cat pc on p.product_catid=pc.product_catid where p.product_id=<cfqueryparam value="#attributes.product_id#" cfsqltype="cf_sql_integer"> order by total desc ) group by company_id,fullname 	0.000643159053307758
10802345	40538	look-up another row based on current row in in the same table in oracle	select t.* from (select t.*, mt.currenttagname, mt.conditiontagname,          lag(eventid, 1, null)          over (partition by mt.currenttagname                order by eventid)   from t join        (select currenttagname, conditiontagname         from ((select currenttagname, conditiontagname                from conditionmappingtable mt               ) union all               (select distinct currenttagname, currenttagname                from conditionmappingtable mt               )              ) mt        )        on mt.conditiontagname = t.tagname  ) t on currenttagname = conditiontagname 	0
10802397	31875	get written user posts and the posts that he promoted	select * from posts left join promotions on promotions.post_id = posts.id where posts.author_id = $userid or promotions.promoter_id = $userid 	0
10805170	20421	asp.net relational database	select productcategoryname from products join productcategories on products.productcategoryid = productcategories.productcategoryid mygrid.datasource = mydataset; mydataset.bind(); 	0.627843450722373
10806195	20041	mysql grouping a group	select login, c1, d1, count(login) as c2  from (...your select...) as orig group by login having c2 = 1 	0.211923997734337
10806541	26456	join two table with everything	select * from form left join records on record.form_id = form.form_id 	0.0486703382629878
10808558	11032	select a random row per group in a large table	select id,rule,temp from treenode where temp>? order by temp limit 0,100000; 	0.00010800080501047
10810642	16582	query to select the month and nos of weekend and public holiday in that month	select year(holidaydate),month(holidaydate),              sum(case weekend when true then 1 else 0 end) wkend,              sum(case publicholiday when true then 1 else 0 end) pubhol       from holiday        group by year(holidaydate),month(holidaydate) 	0
10812380	8226	sql query: reference another table data for two variables in the same query	select     a.pk as "pk",     e1.event_title as "closed_event",     e2.event_title as "current_event" from     events as e1     join archive as a on e1.event_id = a.closed_event_id     join events as e2 on a.current_event_id = e2.event_id 	0.000201374527403469
10812833	18280	sql joining query	select * from menu_item where foodjoint_id in (     select foodjoint_id from provider_food_joints where foodjoint_name='".$foodjoint_name."'"); 	0.416783349542686
10812910	38657	combine two statements with limits using union	select  * from    (   select  *              from    seq              where   julianday('2012-05-25 19:02:00') <= julianday(timep)              order by timep             limit 50         ) union select  * from    (   select  *              from    seq              where   julianday('2012-05-29 06:20:50') <= julianday(timei)              order by timei             limit 50         ) 	0.505162053448392
10813467	22503	use max in a varchar to get result > 999999?	select max(col1) from(   select to_number(numbers) as col1 from table ) d 	0.0209046307663784
10813767	19167	how to tell oracle to sort by a specific sort order passed in from java?	select t.id from t_test t order by decode(t.id, 3, 'a', 'b') asc,          decode(t.id, 4, 'a', 'b') asc,          decode(t.id, 5, 'a', 'b') asc,          decode(t.id, 6, 'a', 'b') asc,          decode(t.id, 1, 'a', 'b') asc,          decode(t.id, 2, 'a', 'b') asc; 	0.00958156046669581
10814083	15232	mysql regexp search	select *  from tbl where clmn like '%a%b%c%' 	0.6191508086132
10814205	16836	get records from yesterday from log table	select * from  mytable where modifieddate >= dateadd(day,datediff(day,0,getdate()),-1)     and modifieddate < dateadd(day,datediff(day,0,getdate()),0) 	0
10814965	4367	mysql select exclude specific result	select        u.username    from        friend_request fr          join users u              on fr.user1 = u.id    where       fr.user2 = theprimaryperson union select        u.username    from        friend_request fr          join users u              on fr.user2 = u.id    where       fr.user1 = theprimaryperson 	0.00629186192461943
10815268	8162	finding most common values in each column	select   ( select value1     from mytable     group by value1     order by count(*) desc            , value1 desc     limit 1   ) as value1,   ( select value2     from mytable     group by value2     order by count(*) desc            , value2 desc     limit 1   ) as value2, ...   ( select valuen     from mytable     group by valuen     order by count(*) desc            , valuen desc     limit 1   ) as valuen ; 	0
10816116	40413	postgres dynamically update constraint foreign key	select 'alter table '||pgn.nspname||'.'||tbl.relname||' drop constraint '||cons.conname||';' from pg_constraint cons   join pg_class tbl on cons.confrelid = tbl.oid   join pg_namespace pgn on pgn.oid = tbl.relnamespace where contype = 'f' union all  select 'alter table '||pgn.nspname||'.'||tbl.relname||' add constraint '||cons.conname||' '||pg_get_constraintdef(cons.oid, true)||' on update cascade on delete cascade;' from pg_constraint cons   join pg_class tbl on cons.confrelid = tbl.oid   join pg_namespace pgn on pgn.oid = tbl.relnamespace where contype = 'f' 	0.00177877156304578
10816696	4364	how to get get unique records based on multiple columns from a table	select primarykey, id, activity, template, creator, created from (     select *, row_number() over (partition by id, activity, template order by created) as rn from table ) a  where rn = 1 	0
10816829	34224	mysql unix timestamp select	select * from orders o where date_format(date_sub(now(), interval o.reorder day), '%d/%m/%y') = date_format(from_unixtime(o.date), '%d/%m/%y') 	0.00789251639995936
10817923	6633	adding count column in sql query	select p.name,p.layer,count(c.chartname) as test from production p left join chart c on c.chartname like '%'+ p.name+'_'+p.layer + '%' group by p.name,p.layer 	0.141024815124956
10818067	30499	sql - finding common rows based on a column (intersect)	select appname, version, count(distinct(machinename)) as machinecount from installedapps group by   appname, version having   count(distinct(machinename)) > 1 	0
10818115	15855	cell to cell comparison in sql server?	select t1.id, t1.tbl1, t2.tbl2 from (        select u.id, u.tbl1, u.col        from tbl1          unpivot (tbl1 for col in (c1, c2, c3)) u      ) t1   inner join       (        select u.id, u.tbl2, u.col        from tbl2          unpivot (tbl2 for col in (c1, c2, c3)) u      ) t2     on t1.id = t2.id and        t1.col = t2.col order by t1.id 	0.0273882984481686
10819329	37979	oracle: handle different date format	select  case         when regexp_like(mydate, '\d{2}/\d{2}/\d{4}') then                 to_date(mydate, 'dd/mm/yyyy')         when regexp_like(mydate, '\d{2}-[a-z]{3}-\d{4}') then                 to_date(mydate, 'dd-mon-yyyy')         end from    mytable 	0.0245504650926353
10821836	21002	error assigning value using top 1	select top 1 @maxno = convert(int, (substring(noorder, 7, 4))) from orders order by noorder desc; 	0.467906670422674
10824382	11386	a grouping and count select for tabular results in sql server 2008	select a.name as 'area', t.name as 'town',   sum(case v.votingyn when 'y' then 1 else 0 end) as 'yes'   sum(case v.votingyn when 'n' then 1 else 0 end) as 'no' from votes as v   join town as t on v.townid = t.id   join area as a on v.areaid = a.id group by (a.name, t.name) 	0.22446099901282
10824406	40625	tsql what is the most efficient way to query a view on a linked server?	select * from   openquery(         heavy,         'select businessdate,                location,                sum(sales)         from   mydatabase.dbo.last7daysofsales          group by businessdate, location') 	0.482596122141071
10824915	39893	mysql: count in column (with join)	select   zone_id, city_name, count(user_id) as users from     zone   inner join city       using (city_id)    left join management using (zone_id) where    country_id = 3 group by zone_id, city_name 	0.226489853381557
10826393	7038	query syntax error selecting from 3 tables	select usuarios.first_name,usuarios.last_name,usuarios.avatar,poblacion.poblacion,groups.name as groupname                                 from usuarios left join poblacion on usuarios.id_loc=poblacion.idpoblacion,                                      helps left join groups on helps.id_group = groups.id                                 where  usuarios.id = '.$this->id_user.' and groups.id = '.$this->id_group 	0.510109612248277
10827099	4966	calculating the total elements unique to each data	select     subject_code + academic_period_code as [type],     sum(duration) as duration from view2 group by     subject_code + academic_period_code; 	0
10828647	31182	count of the column names in phpmyadmin (mysql)	select count(*)  from information_schema.columns  where table_name = '<table_name>' 	0.00314686170153289
10828679	21218	mysql get data by matching row of fixed position with strlength()	select roll_no from your_table where substring(cast(roll_no as char(11)), 4, 2) = '32' 	0
10829812	32848	sql query, where = value of another table	select column1 from table1     inner join table2 on table1.column = table2.column    where table2.columne=0 	0.0023179198559909
10831941	31683	mysql request | group by day	select      a.id,     a.close from (     select          id,         close     from         `orders`     order by         close desc ) as a group by      date(a.close) order by      a.id asc; 	0.0225034694682289
10832217	172	how to find count of conficted date	select tbl.startdate, count(tbl.startdate) from yourtable tbl where  exists(select * from yourtable tbl2 where ((tbl2.startdate>=tbl.startdate and tbl2.startdate<=tbl.enddate) or (tbl2.enddate>=tbl.startdate and tbl2.enddate<=tbl.enddate))) group by tbl.startdate 	0.00135840920391958
10832387	362	summing values based on a group by as well as all of them?	select     sum(colx) over (partition by col1)       as [all of col1],     sum(colx) over (partition by col2)       as [all of col2],     sum(colx) over (partition by col1, col2) as [percol1col2pair],     sum(colx) over ()                        as [all of col1 and all of col2] from     mytable 	0
10833779	34803	mysql query with count	select comment_post_id, count(like_id)  from (select distinct comment_post_id,like_id         from comments_like cl , comments c  where cl.comment_id= c.comment_id ) as iq  group by comment_post_id 	0.467064795096181
10834305	11820	appending a string before count function in oracle	select 'hdr' || count(quote_id) from    t_conv 	0.336122576223279
10834692	826	getting active members by gender	select   month,          sum(if(gender='f' and activetype='employee' , total_paid, 0)) as femp,          sum(if(gender='m' and activetype='employee' , total_paid, 0)) as memp,          sum(if(gender='f' and activetype='dependent', total_paid, 0)) as fdep,          sum(if(gender='m' and activetype='dependent', total_paid, 0)) as mdep from     activemembertype group by month 	0.0104718350346222
10834850	2160	generate connection table from table with duplicates	select    di.word_id   ,di2.word_id  connected_id  into newtable  from duplicateids di   inner join duplicateids di2    on di2.word = di.word     and di2.word_id <> di.word_id 	0.0025198280009955
10836001	39265	doing some fairly basic sums with different tables	select sumofpointsearned.points - coalesce(sumofpointsofpurchasesmade.points, 0) as currentpoints from    (     select sum(points) as points, recipient_id      from   transactions              where recipient_id= 137642     group  by recipient_id ) as sumofpointsearned      left join      (         select purchases.student_id,  sum(rewards.cost_to_user) as points          from   purchases              inner join rewards              on purchases.reward_id = rewards.reward_id                      where student_id = 137642         group  by purchases.student_id     ) as sumofpointsofpurchasesmade      on sumofpointsearned.recipient_id = sumofpointsofpurchasesmade.student_id 	0.609360806788181
10839350	30267	sql - selecting the first record found before a given date	select top 1 id, date from table where date < '4/1/12' order by date desc 	0
10840182	12181	can you select the nth row in the dataset returned by select statement?	select  * from    (         select  *, row_number() over (order by col2) rn         from    mytable         where   col1 = condition         ) q where   rn = 4 	0.000190994212256755
10841949	5325	calculating ltv accurately	select avg(custavg) from (select tblservice.customerid, avg(tblservice.total) as custavg from tblservice group by tblservice.customerid); 	0.725088953364479
10845932	24713	mysql: query to display data from previous day doesnt work when its a new month	select count(*)    from osticket.ost_ticket   where  date(created) = date(date_sub(now(), interval 1 day)); 	0
10846640	25163	sql order by on union - random order on datetime field	select a, b, c, datefield from  (select a, b, c, datefield from whatever union select a, b, c, datefield from whatever union select a, b, c, datefield from whatever) x order by datefield 	0.0143015602207328
10847303	8795	combining two mysql queries into one	select * from threads where poster = $myusername or id in ( select threadid from replies where poster = $myusername ) 	0.00178464799618131
10847689	26786	mysql (beginner): replace field from another table based on query answer	select (select sum(score) from mobscores where mobscores.name = mobkills.name group by name) as score from mobkills  where name= 'mcminer' and date >= somequerydatetostartfrom; 	0.000187271057488523
10847708	39661	mysql count some column's values in one column	select id, col1 + col2 + col3 as colnew from my_table 	0.000102483155830516
10850731	18262	mysql return more than one row	select ...     if(!isnull(td_doc_nr.value_string), sub.one, null) as one,     if(!isnull(td_doc_nr.value_string), sub.two, null) as two from ... left join (     select  d.doc_nr, group_concat(product_name separator ','),group_concat(distinct b.msisdn separator ',') from documents d      join document_bundles b on b.document_id = d.id     join document_products p on p.doc_bundle_id = b.id     join document_product_cstm_fields f on f.doc_product_id = p.id     join document_product_cstm_field_data fd on fd.cstm_field_id = f.id     where value_string ='auto'     group by d.doc_nr ) sub on sub.doc_nr = td_doc_nr.value_string 	0.001236122715191
10851520	5513	tsql: select with dynamic where come from another table	select field1, ...    from selldata   inner join conditiontable     on selldata.idincentive=conditiontable.idincentive     and selldata.cdmarca=conditiontable.cdmarca    and selldata.cdsettore=conditiontable.cdsettore    and selldata.cdgruppo=conditiontable.cdgruppo  where conditiontable.completa = 0 	0.00464122703747412
10851544	1533	recommended table schema for customer accounts table?	select customers.name  , customers.id  , ( select sum(charges.amount)        from charges       where customerid = customers.id )  , ( select sum(payments.amount)        from payments        where customerid = customers.id ) 	0.00293458007047319
10851905	37359	mysql substring in selection only when a character is present	select distinct       if(locate(' - ', vendor)>0, substring(vendor, 1, locate(' - ', vendor)), vendor) from feed_data; 	0.0629758672236975
10853280	17256	overall unique count from two tables in mysql	select count(distinct aa.id)  from (select distinct major_id as id from `major`  union all select distinct team_id as id from `team`)  as aa 	0.00030769099758722
10853937	7957	merge two rows in sql for-fitting one column field	select min(device_id) as device_id, other_id from   tbl group  by other_id order  by other_id; 	0
10854529	1356	minimize select queries on the same table mysql	select * from u_settings where setting in ('username', 'password','email','tag','active','version','time','warn','dis'); 	0.00217031349156031
10855208	18750	need to return a value and its count as 0 when it does not exist with in a range of dates	select tn.teamtext,        sum(case when convert(smalldatetime,dmodlast,101) between '2012-03-01' and '2012-03-10'                  then 1 else 0            end) as cnt from teamnames as tn join      caseaudit as ca      on tn.teamid = ca.referteamid2 where ca.referteamid1 <> ca.referteamid2 and       teamid in (99, 107, 124, 27, 31, 44, 110, 43, 57, 50, 46) group by tn.teamtext order by tn.teamtext 	0.000560641021058324
10855326	4573	custom order after distinct statements	select * from ((select distinct 'in' as statusa, (select count(*) ...        from table       )       union all       (select distinct 'out',  (select count(*) ...)        from table        )       union all       (select distinct 'finished',  (select count(*) ...)         from table       )      ) t order by status,       (case statusa when 'in' then 1                     when 'out' then 2                     when 'finished' then 3        end) 	0.560480322664333
10855391	20611	dynamicobject returned by dapper query doesn't contain all selected columns	select id, computedcolumn from mytable where id = scope_identity() 	0.00956951207775317
10855438	40003	find two-ways binding in many-to-many table	select  least(x, y) l, greatest(x, y) g from    r group by         l, g having  count(*) > 1 	0.123958859445823
10857798	1500	mysql count with join and group	select      student.*, count(*) from student      left join schedule on student.id = schedule.studentid group by student.* 	0.530370809371921
10858221	11485	query table depending on id matching comma separated field	select `section` where find_in_set('$userid', `useraccess`) != 0 	0
10861232	20634	oracle sql for count	select institute.id inst_id, institute.placement placement, institute.address institute_location, count(distinct institute_department.id) departments count(distinct institute_campus.id) campuses from institute left join institute_department on (institute.id = institute_department.institute_id) left join institute_course on (institute.id = institute_course.institute_id) left join institute_campus on (institute.id                       = institute_campus.institute_id and institute_campus.is_active = 1 and institute_campus.is_deleted = 0 and institute_campus.deleted_date is null) where institute.id                     = 1761 and institute.is_active                = 1 and institute.is_deleted               = 0 and institute.deleted_date            is null and institute_department.is_active     = 1 and institute_department.is_deleted    = 0 and institute_department.deleted_date is null group by institute.id, institute.placement, institute.address 	0.400581088817536
10861498	12338	select specific columns from two tables 	select e.strempname, s.monsalary from tblemployee e join tblempsalary s on e.intemployeeid = s.intemployeeid where e.strdepartment + '-' + cast(s.monsalary as varchar(20)) in (      select e2.strdepartment + '-' + cast(max(s2.monsalary) as varchar(20))      from tblemployee e2      join tblempsalary s2 on e2.intemployeeid = s2.intemployeeid      group by e2.strdepartment) 	0.000212667007303487
10861540	31587	how to find a text from database column in a table?	select id from table where url like ('%example%'); 	9.09720184340233e-05
10863286	21603	select certain field based on another field in table	select team_manager_id from   hierarchy h inner join aliases a on h.user_id = a.alias_id  inner join login l on a.user_id = l.user_id where  email = 'ron.jones@gmail.com'; 	0
10865338	27305	how to get group of fields with all results, less than all etc	select car_id from keywords ,,group_concat(keyword) where keyword in ("old","ford", "cheap")  group by car_id 	0
10866236	34463	mysql multi column lookup	select  t3.circuit_id, t3.assignment1, t21.account_username, t3.assignment2, t22.account_username, t3.assignment3, t23.account_username from    t3 left join         t2 t21 on      t21.account_id = t3.assigment1 left join         t2 t22 on      t22.account_id = t3.assigment2 left join          t2 t23 on      t23.account_id = t3.assigment3 	0.149171760016135
10866393	13025	rewriting sql of counting offers made by user	select   cargo.cargoid,   cargo.cargotime,   count(offer.offerid) as offercount from     cargo   inner join     offer   on     offer.cargoid = cargo.cargoid where   offer.offerstatu <> 1 group by   cargo.cargoid,   cargo.cargotime having   sum(case offer.userid when 12 then 1 else 0 end) <> 0; 	0.142739679554298
10866860	26246	sql merge row from union result and calculate	select   operation,   sum(case route when 'no'  then measurement end) as measurementno,   sum(case route when 'yes' then measurement end) as measurementyes,   sum(case route when 'yes' then measurement end)   - sum(case route when 'no'  then measurement end) as measurementdifference from atable t group by   operation 	0.000277884499603702
10867925	3651	join two tables in a mysql query	select   p.post_id,    p.user_id,   p.post_body,   p.date_upload from   posts p,   follows f where   f.user_id = 4      and   f.followee_id = p.user_id order by   p.date_upload desc 	0.0940348972882228
10868201	40088	find out the popular domains in mysql database using two columns	select domain, sum(clicks) as "total_count" from table group by domain order by total_count asc 	7.26657298779085e-05
10870121	34256	select custom strings and values without fields sql	select field1, '0' as answers from table 	0.0310478594071091
10870513	19315	double select statement issue, multiple rows returned , subquery returned more than 1 value	select projects.project_name  from projects inner join project_distribution on (projects.project_id = project_distribution.project_id) inner join accounts on (project_distribution.employee_id = accounts.employee_id) where accounts.employee_id = 'tbogdan' 	0.0940483157592545
10870536	34237	joining on two columns to the same third column	select semesterclasses.class_id, allclasses.classname, prerequisite.classname as prerequisitename from semesterclasses left join allclasses on allclasses.class_id = semesterclasses.class_id left join allclasses as prerequisite on prerequisite.class_id = semesterclasses.prerec_id 	0
10871951	10781	row selection based on subtable data in mysql	select measurements.* from   measurements inner join measurement_flag         on measurements.measurement_id = measurement_flag.measurement_id        and flag = 'x'        and 'y' not in (                select flag                from   measurement_flag                where  measurement_id = measurements.measurement_id); 	0.000542815591302861
10873030	4434	how do i select x random rows while guaranteeing that y certain specific rows are in the result?	select top 20 * from question where category = @category order by ismandatory desc, newid() 	0
10873615	3554	sql for getting data from linked tables if sum of data is above certain number	select name, surname, email, sum(number_of_point)  from user, user_event, event_type  where user.userid = user_event.userid and user_event.event_typeid = event_type.event_typeid  group by user.userid having sum(number_of_point) > :threshold order by name asc 	0
10879585	39427	providing a list with a select query	select speciality, count(distinct name)  from medics  group by speciality 	0.16472795914448
10881544	21125	mysql how to return concatenated name and lastname of a user	select id                                    as value,         concat(left(name, 1), '. ', lastname) as label  from   table; 	0.00143998728052097
10881645	18015	sql multi table select query	select pc.id, pm.name, pcm.name, pmm.name, pc.name, pc.desc, pc.thumb, pc.src, pc.status from project_content as pc left join project_master as pm on pm.id =  pc.p_id left join project_content_menu as pcm on pcm.type_id = pc.p_c_id  left join project_menu_master as pmm on pmm.id = pc.m_id 	0.225431251016268
10882097	25008	join mysql tables	select project_members.fk_mem_id,         a.mem_name as child,         b.mem_name as parent  from   project_members         inner join members a                 on project_members.fk_mem_id = a.mem_id         left join members b                on project_members.meb_parent_id = b.mem_id 	0.30836982525185
10885788	38320	datetime and integer functions on varchar fields	select column1, column2 from table where convert(datetime, datecolumn, 3) between @startdate and @enddate 	0.0574843971459397
10888097	29996	sql query for join table and multiple values	select table1.id, count(table1_table2.table2_id) from table1 join table1_table2 on (table1_table2.table1_id = table1.id                    and table1_table2.table2_id in (#somelist#)) group by table1.id having count(table1_table2.table2_id) = (#length of somelist#) 	0.0744425758568696
10888965	28975	how to get the number of next increment in mssql in php?	select ident_current('image') + ident_incr('image') 	0
10890150	20748	return results where first entry is 1 and all subsequent rows are 0	select patient_id ,case when r.rank = 1   then 1  else 0  end , order_number from (   select    order_number   ,patient_id   ,row_number() over (partition by patient_id order by order_number)[rank]    from    patienttable )r 	0
10890314	678	how to inner join 3 tables using mysql?	select m.id as mid, c.id as cid, u.id as uid  from members m  left join companies c on m.id=c.id  left join users u on m.id=u.id 	0.459228425798647
10890378	17777	mysql special order by	select * from `table` order by field(`genre`, 'horror', 'scifi', 'horror'), `name`; 	0.565487042104771
10890819	25802	conditional cumulative sum in mysql	select idstudent,        sum( hourcourse * mark ) / sum( hourcourse ) as weightedavg from (   select t.*,   case when @idstudent<>t.idstudent     then @cumsum:=hourcourse     else @cumsum:=@cumsum+hourcourse   end as cumsum,   @idstudent:=t.idstudent   from `test` t,   (select @idstudent:=0,@cumsum:=0) r   order by idstudent, `key` ) t where t.cumsum <= 30 group by idstudent; 	0.206235101185143
10891044	5192	send member reminder based on their last login sql statement	select distinct members.email, max(member_login.date_login) from   members inner join member_login on members.id = member_login.m_id group by members.email having max(member_login.date_login) < curdate - interval 30 days 	0
10892269	31559	way to construct a query in which a date falls between a start and end date in sqlite?	select * from time_table  where date_column  between '01-01-2012'  and '12-31-2012' 	0.000206642165627957
10893580	11829	mysql convert column into row	select id,'col1' as colname, col1 as value from table1 union all select id,'col2' as colname, col2 as value from table1 union all select id,'col3' as colname, col3 as value from table1 union all select id,'col4' as colname, col4 as value from table1 	0.00209254864554214
10893960	25606	where date difference between now and max date value is greater than x	select * from  (select usermaster.userid, date_trunc('days', now()-max(paymentdate)) as           last_payment from usermaster, paymentdetail  where usermaster.userid=paymentdetail.userid group by usermaster.userid ) as temptab where last_payment>100; 	0
10894178	40493	executenonquery result in c#	select schema_name from information_schema.schemata where schema_name = 'demodb' 	0.54638437428085
10894324	12771	mysql query with zero values	select "2011-01-01" as date, a.name, ifnull(s.total, 0) from article a left join (     select idarticle, count(*) as total     from sale     where date = "2011-01-01"     group by idarticle ) as s on a.id = s.idarticle 	0.123895886917982
10894757	39192	filter mysql result w/ empty row	select      p.path, p.title, p.body, p.post_date, u.username  from pages p  left join users u on p.post_author = u.id where      p.path is not null and      p.path <> '' order by p.id asc 	0.0697649211942829
10895089	33970	get value from a column if the point is higher than a specific amount	select * from rewards where point <= 2300 order by point desc limit 1 	0
10895764	16508	mysql join comma separated field	select  m.studentid from    batch b join    marks m on      find_in_set(m.studentid, b.batch)         and m.subject = 'english' group by         m.studentid having  sum(marks) > 45 	0.00320012434896421
10896647	33758	optimize mysql query to select the values	select  audit_name,         sum(audit_choice = 'passed') as passed,         sum(audit_choice = 'failed') as failed from    audit group by         audit_name 	0.245916969761755
10899805	24692	php/mysql search for date and send email if date is today	select .... where datefield=curdate(); 	0.00113562954009943
10899818	39766	finding the total number of records for a given location	select     sku,      quantity,      inventory.isbn13,      author,      title,      pub_date,      binding,      defect.defect,      source,      location,     t.cnt from      inventory i         inner join              (             select                 inventory.location_id,                 count(book.isbn13) as `cnt`             from inventory                   left join book on inventory.isbn13 = book.isbn13             group by inventory.location_id             ) t on t.location_id = i.location_id         inner join location l       on i.location_id = l.location_id         left join source            on i.source_id = source.source_id         left join defect            on i.defect_id = defect.defect_id         left join book_condition    on book_condition.condition_id = defect.condition_id where      i.quantity > '0'  and l.location_id >= '986'  and l.location_id <= '989' 	0
10900660	5225	count first value, second value or both	select sum(cond1) + sum(cond2) from table1 where cond1 or cond2 	0
10902344	40549	query to count number of unique relations	select id1, count(id2),name      from (              select distinct tud1.user_id id1 , tud2.user_id id2             from t_user_deal tud1, t_user_deal tud2              where tud1.deal_id = tud2.deal_id             and tud1.user_id <> tud2.user_id) as tab, t_user tu      where tu.id = id1       group by id1,name 	0.00128788136726924
10904218	533	mysql sort grouped data	select wm.id, wm.from_userid, (wm.read is null) as unread, wm.sent from (select max(id) as id from who_messages where to_userid = '41' group by from_userid) sub inner join who_messages wm on sub.id = wm.id order by wm.sent desc, wm.read 	0.0121754475421628
10905122	3699	join subquery temp table to query table	select a.teamtext, a.cnt, b.cnt2 from (select tn.teamtext, tn.teamid, sum(case when convert(smalldatetime,dmodlast,101) between '2012-03-01' and '2012-03-10' then 1 else 0 end) as cnt  from teamnames as tn     left outer join caseaudit as ca     on tn.teamid = ca.referteamid2  where ca.referteamid1 <= 0 and ca.referteamid1 <> ca.referteamid2 and isactive = 1 and groupid = 18 and accountid = 2  group by tn.teamtext, tn.teamid) as a left outer join  (select tn.teamtext, tn.teamid, sum(case when convert(smalldatetime,dmodlast,101) between '2012-03-01' and '2012-03-10' then 1 else 0 end) as cnt2   from teamnames as tn      left outer join caseaudit as ca     on tn.teamid = ca.referteamid2   where ca.referteamid1 <> ca.referteamid2 and isactive = 1 and groupid = 18 and accountid = 2   group by tn.teamtext, tn.teamid) as b on a.teamid = b.teamid order by a.teamtext 	0.366705747476827
10905658	7690	changing a query to count number of unique values rather than total rows	select count(distinct zip) as unique_zip_cnt   from submission 	0
10906366	34558	mysql_query select from multiple columns with or	select * from articles where (articletitle like '%$term%') or (articledescription like '%$term%') or (articletags like '%$term%'); 	0.010270469264304
10906448	28579	mysql grouping by day then display the date from the grouped results	select count(*) as count, day(datesubmitted) as newday,  year(datesubmitted) as newyear ,month(datesubmitted) as newmonth from results  group by day(datesubmitted), year(datesubmitted), month(datesubmitted)  order  by  year(datesubmitted) desc, month(datesubmitted) desc, day(datesubmitted) desc 	0
10906992	5653	two tables into 1 sql query	select whatever fields you need,        ((acos(sin($lat * pi() / 180) * sin(gps_lat * pi() / 180) + cos($lat * pi() / 180) * cos(gps_lat * pi() / 180) * cos(($lon - gps_long) * pi() / 180)) * 180 / pi()) * 60 * 1.1515) as distance from listings   join building_types_listings     on listings.id = building_types_listings.listing_id where building_type_id = '$building_type' 	0.0076353839048306
10907027	2226	i need to show only records that start with a prefix of "250" in my table from mysql	select type, part_no, description, artwork, min, max, qty from cartons_current where part_no like '250%' 	0
10907750	16298	how to calculate difference between two datetime in mysql	select timestampdiff(second, '2012-06-06 13:13:55', '2012-06-06 15:20:18') 	0.000139376583954749
10907882	34418	why can't i add a single value to an entire column in postgresql postgis?	select   polys.id,   st_transform(st_intersection(polys.the_geom, box.the_geom),3857) as the_geom_webmercator,  st_area(st_transform(st_intersection(polys.the_geom,box.the_geom),3857)) as polygonarea,  sum(st_area(st_transform(st_intersection(polys.the_geom,box.the_geom),3857)))  over () as totalarea from polys,box 	0.0409667107508683
10908014	7673	selecting records in sql that have the minimum value for that record based on another field	select x.recordid, vendorsource, vendorprice from clientdata x inner join sources s on x.recordid = s.recordid inner join prices p on s.sourceid = p.sourceid inner join (select c.recordid, min(weight) min_weight             from clientdata c             inner join sources s on c.recordid = s.recordid             inner join prices p on s.sourceid = p.sourceid             where weight != 0              group by c.recordid) w on x.recordid = w.recordid where p.weight = w.min_weight 	0
10908282	11215	how to count number of times team is highest scorer in a game from a mysql cross table?	select count(1) as wins from game_results as gr1 left join game_results as gr2 on gr1.game_id=gr2.game_id and gr2.team_id != 1234 where gr1.team_id = 1234 and gr1.score > gr2.score 	0
10908692	17304	how to match specific pattern from a string	select regexp_count('7839,king      ,president,0000,17-nov-1981, 005000.00 ,000000.00,10,',',') from dual 	0.000585983712038956
10909236	806	how to select values in oracle10g database?	select name from table_name where ','||skills||',' like '%,java,%' 	0.00856761870897617
10909672	35173	how to exclude a table from select distinct	select distinct table_name from information_schema.columns where column_name in ('quoteid') and table_name != 'clientdata' and table_schema='$db'; 	0.000250774207792402
10910294	38176	hive count(*) shows one row more than in actual sql table	select * from table-name where $conditions 	0.000689729003819734
10910425	40316	how to select all fields where a string is common in all the tables in a mysql database?	select * from groupstage, quarterfinal, semifinal where groupstage.date = quarterfinal.date and quarterfinal.date = semifinal.date and date = "your date" 	0
10910761	21044	select with a max in joined table	select  * from    (         select  distinct request_id         from    workflow         ) wd join    steps s on      s.step_id =         (         select  si.step_id         from    workflow wi         join    steps si         on      si.step_id = wi.step_id         where   wi.request_id = wd.request_id         order by                 stem_num desc         limit 1         ) 	0.00972764217307976
10911184	24571	mysql date returns null	select date(from_unixtime(created)) from mytable where 1 limit 5 	0.178847355124015
10912146	28950	how to round the timing with nearest value	select substring([time], 1, 3) +         right(rtrim(('0' + cast(substring([time], 4, 2) / 5 * 5 as char))), 2) from table1 	0.00848924603606271
10912230	36137	mysql select specific entry from a table which is not in another table	select user_id from users u left join views v on v.user_id=u.user_id and v.article_id = 10 where v.user_id is null 	0
10912337	8522	how to show comments of a column with desc operation	select tc.column_name ,      tc.nullable ,      tc.data_type || case when tc.data_type = 'number' and tc.data_precision is not null then '(' || tc.data_precision || ',' || tc.data_scale || ')'                             when tc.data_type like '%char%' then '(' || tc.data_length || ')'                             else null                        end type ,      cc.comments from   user_col_comments cc join   user_tab_columns  tc on  cc.column_name = tc.column_name                             and cc.table_name  = tc.table_name where  cc.table_name = upper(:tablename) 	0.00368920635966237
10912588	18608	getting ids from 3 tables	select teamid,teamname from team where teamid in (select teamid from quiz) or teamid in (select teamid from questionnaire); 	0.000168073802031636
10912693	26543	exact count of all rows in mysql database	select count(*) from table 	0.00018413248702521
10915516	23535	getting usernames in forum topic information from linked tables	select forumtopic.*,          innerv.*,          (select name from user as u1 where u1.id = innerv.first_user)                                 as startedusername,         (select name from user as u2 where u2.id = innerv.last_user )                                 as lastusername from forumtopic left join forumcategory on forumcategory.id = forumtopic.forumcategoryid  left join ( select forumtopicid, max(date) as last_posted_date, min(date) as first_posted_date, substring_index( group_concat(posteruserid order by date), ',', 1 ) as first_user, substring_index( group_concat(posteruserid order by date), ',', -1 ) as last_user, count(1) as posts_under_topic from forumpost where forumpost.active='y'  group by forumtopicid ) innerv on innerv.forumtopicid = forumtopic.id  where forumcategory.rewrittenname='someforumcategory'          and forumcategory.active='y'          and forumtopic.active='y' 	0.00123031950265604
10916158	27449	select the names from multiple tables and sort with the same id	select ci.name, co.name       from cities  ci inner join country co on co.id = ci.id   order by ci.name, co.name 	0
10916485	23714	find references to other databases	select object_schema_name(referencing_id), object_name(referencing_id)    from sys.sql_expression_dependencies   where referenced_database_name = 'yourdatabasename'; 	0.00140246479825314
10916934	6885	full outer join using each row once	select * from (   select *,     row_number() over (partition by foreignkeyid order by id) as n   from @t1 ) t1 full outer join (   select *,     row_number() over (partition by foreignkeyid order by id) as n   from @t2 ) t2 on t1.foreignkeyid = t2.foreignkeyid and t1.n = t2.n 	0.00656596684404353
10917100	10519	mysql - get last messages max(time) by users	select m.user as user_sent, m.conversation, m.text, m.time as time_sent , mu.id, mu.user as user_read, mu.time as time_read from message as m  join (   select mx.conversation, max(mx.time) as maxtime    from message as mx group by mx.conversation   ) as mx on m.conversation = mx.conversation and m.time = mx.maxtime join (   select mu.message, max(mu.time) as maxtime, min(mu.time) as mintime    from message_user as mu    group by mu.message ) as mux on m.id = mux.message join message_user as mu on m.id = mu.message and case when mux.mintime = 0 then mux.mintime else mux.maxtime end = mu.time 	0.00015685909311288
10917322	35192	mysql set default to null if multiple rows dont match	select case when count(is_business_invoice) = sum(is_business_invoice)              then 1              when sum(is_business_invoice) = 0             then 0             else null        end as isbusinessinvoices from invoices group by booking_id 	0.00070191840497086
10917626	4930	options for pgsql_fdw	select dblink_connect('connection_name', 'host=hostname dbname=fdbname user=user password=secret'); create foreign data wrapper dblink_fdw validator postgresql_fdw_validator; create server dblink_fdw_server foreign data wrapper dblink_fdw options(hostaddr 'hostname', dbname 'fdbname'); select * from dblink('connection_name', 'select * from public.foreigntable') as foreign_table(columna bigint, columnb text); 	0.481736287787246
10917838	28930	how best to query a many-to-many relationship for "all y for each x that has a matching y"	select other_table.* from   `table` t1   join `table` t2 using (group_id)   join other_table on other_table.user_id = t2.user_id where  t1.user_id = 3 	0
10920671	24819	how do you deal with blank spaces in column names in sql server?	select [response status code], [client response status code] from tc_sessions (nolock)  where startdate between '05-15-2012' and '06-01-2012'  and supplyid = 3367 	0.0410321548560923
10920686	9485	mysql: how to fetch by "new and bestselling" like amazon?	select case(when datediff(curdate()-uploaddate) < 7 then 1 else 0 end as relative week 	0.180926610883804
10920971	8599	implementing hierarchy in sql	select cdate, secid, source, value from (   select t.cdate, t.secid, t.source, t.value,     row_number() over (partition by t.cdate, t.secid                        order by h.hierarchy desc) as nrow   from table1 t   inner join table2 h on h.source = t.source ) a where nrow = 1 	0.768695240733106
10921290	24779	multiple joins to the same table	select pa.appointment_key, p.profile_key as rep, p2.profile_key as customer,          p.first_name as repname,p2.first_name as customername from profile_appointment pa     join profile_appointment pa2 on pa.appointment_key = pa2.appointment_key join profile p    on p.profile_key = pa.profile_key    and  p.profile_type_key = '4' join profile p2   on p2.profile_key = pa2.profile_key   and  p2.profile_type_key = '6' 	0.00995641199965082
10923240	15893	how do i nest two count() statements?	select country_count, count(*) as people_count    from (select name, count(distinct country) as country_count            from travels           group by name          having count(distinct country) > 1) group by country_count 	0.272228930676148
10923264	506	how to select from a datetime column using only a date?	select *  from mytable where date(postedon) =  '2012-06-06' 	4.68400967829389e-05
10923651	24627	getting column values as array, zend_db, mysql, php	select person.id, person.first_name, person.city, person.state, group_concat(study.name separator '|') as studynames from person left join person_studies on person.id = person_studies.person_id left join study on person_studies.study_id = study.id  where person.id=14; 	0.00761355451091316
10923905	22231	mysql: sum() and join from multiple tables	select id, sum(sm) as sm, sum(md) as md, sum(lg) as lg from (    select * from red    union all    select * from white    union all    select * from blue ) as somealias  group by id 	0.0174738445903114
10925437	4276	can i sort mysql database records by the sum of multiple columns without displaying the sum itself?	select   player, team, pass_yds, pass_tds, int_thrown, rush_yds, rush_tds from     ff_projections where    position = 'qb' order by pass_yds + pass_tds + rush_yds + rush_tds desc 	0
10925504	11642	sql order by content of in statement	select * from properties  where zip_code in('77808', '77805', '77806', '77807') order by field(zip_code, '77808', '77805', '77806', '77807') 	0.21908724129116
10925585	33551	mysql a column into multiple columns based on the value	select   substring_index(description, ':', 1) status,   substring_index(substring_index(description, '''', 2), '''', -1) description,   substring_index(substring_index(description, '''', 4), '''', -1) device,   substring_index(substring_index(description, '''', 6), '''', -1) system,   substring_index(substring_index(description, '''', 8), '''', -1) code from   devices where   id = 172; 	0
10926292	14906	get subtract weekday	select  datepart(weekday,getdate())-1 weekday 	0.00205407409890657
10927501	1697	mysql remove duplicate using group by?	select * from   meber natural join (   select   latitude,longitute,max(position) as position   from     meber   group by latitude,longitute ) as t 	0.042915500428416
10928689	35470	how to create dynamic action in apex4.1 tabular form	select emp_name d, emp_id||':'||emp_name r from employee order by 1 	0.196210263701288
10929773	23883	fetching weekly, monthly, yearly data in one query	select    user_id,    sum(if(ts>current_date - interval 1 week,votes,0)) votes_weekly,    sum(if(ts>current_date - interval 1 month,votes,0)) votes_monthly,    sum(if(ts>current_date - interval 1 year,votes,0)) votes_yearly from table where ts>current_date - interval 1 year group by user_id; 	0.000733795263794446
10930462	40795	mysql count with statement	select     sum(jq.batchid > 0) as nb_batchid_positive,     sum(tl.taskqueueid is not null) as nb_taskqueueid_not_null from jobqueue jq left join taskslogs tl     on jq.taskqueueid=tl.taskqueueid     and jq.documentgroupid=0     and tl.statusdefinitionid=1 where jq.jobid=140; 	0.590884461700903
10931145	36598	sql query for sorting on the column partial value	select  substring_index(code, ':', 1) as dept         substring_index(code, ':', -1) as sr_no from    mytable order by         sr_no 	0.00364465800313432
10932220	27958	return count(*) even if 0	select    bb.name,    [count] = sum(case when bb.numa > bb.numb then 1 else 0 end) from dbo.boffers as bb where exists  (     select 1 from dbo.boutcome      where id = bb.boutcomeid     and eventid = 123     and offertypeid = 321 ) group by bb.name; 	0.047824397102337
10932893	13813	getting the closest time in a pdo statement	select * from `table` where `date` < '$var' order by date limit 1; 	0.0461482285960097
10933755	38924	sort multiple tables using date and time functions	select     if(datediff(today, yesterday) <= 7, "green",         if(datediff(today, yesterday) <= 14, "orange",             "red")) as colour from (     select     now() as today,     date_sub(now(), interval 15 day) as yesterday) t; 	0.0232300726457124
10936078	19570	mysql count and sort enhance query	select count(offices) as c from active group by offices having count(offices) >= 5  order by c desc 	0.553036994410111
10936857	19491	sort by column that contains null values?	select c1 from t1 where c1 is not null order by convert(varchar(max),c1) desc 	0.00124215705710831
10937003	34450	find users with consecutive leaves	select userid from (select t.*,               dateadd(d, -seqnum, t.date) as diff       from (select t.*, row_number() over (partition by userid order by date) as seqnum             from t             where datediff(d, t.date, getdate()) <= 30 and leave = 'y'            ) t      ) t group by userid, diff having count(*) > 1 	0.00377226646616297
10937814	23900	in ddl alter table trigger, how can i get the new create table statement?	select create_table from sys.something 	0.000885507534574247
10937865	25980	multiple table mysql query	select uploads.*, audienceuploadassociation.* from   uploads   join audienceuploadassociation     on uploads.upload_id = audienceuploadassociation.upload_id  where uploads.member_id = '1'    and uploads.member_school_id='1'    and subject = 'esl'    and topic = 'poetry' group by uploads.upload_id limit  20 	0.145209798532571
10938494	4250	sql - parent - child relationships in different records	select folder.drawerid, folder.folderid, folder.foldername, doc.documentid, doc.documentname     from      (select drawerid, itemid as folderid, parentid, [name] as foldername from drawers where [type] ='folder') folder,     (select drawerid, itemid as documentid, parentid, [name] as documentname from drawers  where [type] ='document') doc     where doc.parentid = folder.folderid     order by drawerid, foldername, documentname 	0.000103749029731064
10938585	3580	mysql return null when more rows than in values	select conversation_id from conversation_list where user_id in (5,6) and conversation_id not in (     select conversation_id from conversation_list where user_id not in (5,6) ) group by conversation_id having count(*) = :nb_users 	0.00320413973326574
10938865	15128	how do i use a php/mysql-based script to ban ip blocks from a website?	select * from bans where inet_aton("127.0.0.1") between start_ip and end_ip 	0.741287896527175
10940621	15545	how to query a many-to-many relationship and use group by?	select count(*), typename from..... group by typename 	0.456272071830077
10940652	30123	multiple date periods	select * from periods where [a date] between pstart and pend 	0.00960101450262706
10942219	23204	how do you select a date range in postgres?	select * from table where timestamp > now() - interval '1 month' 	0.00190556631045953
10944276	25328	returning the closest to a date in a table using pdo mysql/mssql	select * from `table` where `date` < `startdate` order by `date` limit 1; 	0.00841832226917334
10946600	8373	xml from sql column: cannot call methods on nvarchar(max)	select [learner_course_xml_test].[xml_ex].query('data(sco/cmicore/total_time)') as  timetaken from [learner_course_xml_test] 	0.787242843670927
10946608	28595	how to write a query to get number of queries per minute in a database which is fed with the log files 	select  convert(nvarchar(16), timelog, 120) requesttime,         count(*) from    logdata group by convert(nvarchar(16), timelog, 120)` 	7.69963027568306e-05
10947771	13905	distinct count of the number of account numbers, that appear in multiple profiles	select count(*) from      (            select account_num, count(profile_id) as num_users          from dbo.sample          where account_num <> '' group by account_num     ) t   where num_users > 1 	0
10947839	29245	how to write table.column	select     a.id as a_id, b.id as b_id from     a inner join b on (a.id = b.id) 	0.657674357594103
10947957	6152	combine multiple mysql queries into a single query	select coalesce(sum(if(c=1 and a=0 and b=1  ,  1, 0)),0) as active from users where date between 'date1' and date '2' 	0.0070877239493498
10949683	3187	how do i merge data from several rows in sql server	select code,        ( select name + ' '            from table1 t2           where t2.code = t1.code           order by name             for xml path('') ) as name       from table1 t1       group by code ; 	0.000399344779773499
10950181	8255	how do you fetch one single record from a mysql database using a pdo prepared statement?	select `caption` from `photos` where `id` = ? limit 1 	0.000262610343806545
10950555	15473	trying to add a subquery to a join query	select tbl_products.*, group_concat(tags.name) from tbl_products, (select page_collection_name as name     from tbl_page_collections    ,tbl_page_collections_products    left join tbl_pages on tbl_page_collections.page_id = tbl_pages.page_id     where tbl_pages.page_name like '%friends%') tags left join tbl_page_collections    on tbl_page_collections.page_collection_id = tbl_page_collections_products.colid  left join tbl_pages    on tbl_page_collections.page_id = tbl_pages.page_id  left join tbl_products    on tbl_products.product_id = tbl_page_collections_products.product where  tbl_pages.page_name like '%friends%' 	0.514978537060728
10950806	938	mysql query select exclusion	select     * from     scores as t     join          (             select                 max(t2.id) as maxid             from                 scores as t2             group by                 t2.userid         ) as latest         on t.id=latest.maxid where     t.gameid=11 	0.683440381348536
10951361	16799	hql: count null values in a collection	select s, sum(case when (a.excuse is null and a.id is not null) then 1 else 0 end) 	0.195752530139229
10952573	39838	mysql multiple subquery on same table	select id   , sum( case when bank = 1 then amount end ) as bank1total   , sum( case when bank = 2 then amount end ) as bank2total from sourcetable group by id 	0.0173669503006054
10953138	33121	sql order by highest value of two columns	select  * from    mytable order by         greatest(pc_1, pc_2) desc, least(pc_1, pc_2) desc 	0
10953847	40620	select a field only if no other records with the same field value meet a condition	select distinct t.id,  from templates t left outer join reports r on r.template_id = t.id where r.start_time >=  utc_timestamp() and t.id not in (select concat_ws(',',tid) where report started) 	0
10954225	32898	mysql not in query only including result that i want to exclude	select      item_id from      t1 where      item_id not in (select item_id from t2) 	0.00615212830237393
10954394	17080	mysql: select time ranges using timestamp column and grouping	select     host,     min(ts) as startdate,      max(ts) as enddate from (     select         ts,         host,         result,         (   select                 count(*)              from                 hoststatus h2              where                 h1.host = h2.host                 and h1.result <> h2.result                 and h2.ts >= h1.ts) as rungroup     from         hoststatus h1) a where result = 1 group by host, rungroup order by rungroup desc; 	0.000459072240608497
10954410	27883	find how many days from begining of the month to current day (oracle)	select trunc(sysdate) - trunc(sysdate,'month') + 1 from dual 	0
10954511	20489	oracle pl/sql results into one string	select listagg(name, ',') within group (order by 1) as names from temp_table 	0.0149745069803588
10954737	25152	xml shredding to include attribute and inner element value	select t.data.value('@type', 'varchar(20)'),    t.data.value('.', 'varchar(20)') from @data.nodes('orders/totals/total') t(data) 	0.00259341283311362
10955954	14621	options for "rows where any 3 out of 7 fields aren't blank" criteria	select * from   customer where  3 <= ((select count(nullif(c, ''))               from   (values (firstname),                              (lastname),                              (addressline1),                              (addressline2),                              (city),                              (state),                              (country)) v(c))) 	6.57208856023642e-05
10956188	1588	join and group_concat with three tables	select u.id,         u.name,         group_concat(us.id_sport order by pref) sport_ids,         group_concat(s.name order by pref)      sport_names  from   users u         left join user_sports us                 on u.id = us.id_user         left  join sports s                 on us.id_sport = s.id  group  by u.id,            u.name 	0.551346314037564
10956536	7628	how do i ensure a select statement returns null values for specific columns?	select displayname, null as 'regularhours', null as 'overtimehours' 	0.00127709117652385
10957963	29114	remove everything in brackets with mysql	select replace(replace(title,'(', ''),')','') as  title from table 	0.426749424211255
10959937	16819	convert single column with multiple rows into a single row having multiple columns	select pvt.* from (     select *     from testc     )as p pivot (min(comments) for row_count in ([1],[2],[3],[4],[5],[6],[7]))pvt 	0
10962438	13411	how to get max repeated count with sql	select name, count(name) as `cnt` from cou  group by name order by `cnt` desc limit 1 	0.00848742883447162
10963832	12111	how to join two tables using jpa's jpql	select distinct p from products p  where p.producthistory.lastupdatedate > ? and p.producthistory.lastupdate < ? 	0.282492550906939
10964173	37682	mysql: how can i remove character at start or end of field	select trim(trailing ‘xyz’ from ‘barxxyz’); 	0.000810336514302171
10964431	4451	selecting row base on date range of 2 inputs	select * from table where  ('2012-12-02' between db_start and db_end) and ('2012-12-19' between db_start and db_end) 	0
10964701	39066	using group by on a non numeric field	select min(id), name, age from table group by name, age 	0.02434122629825
10965411	21573	echo data from several sql tables	select * from      (select * from artists order by timestamp desc     union     select * from news order by timestamp desc     union     select * from tracks order by timestamp desc     union     select * from gigs order by timestamp desc     union     select * from feature order by timestamp desc) as temp order by timestamp desc; 	0.00165630264250664
10965529	20289	simple mysql query displaying results in specific order	select * from conversation c, messages m  where (c.user_id1='$userid' or c.user_id2='$userid') and c.last_message_id=m.message_id order by created_time desc 	0.539235245272189
10965893	8204	find all rows not matching a criteria, mysqli mysql php	select * from threads_read where id not in (select id from important_threads) 	0.000163352391769907
10969468	2484	counting multiple rows in mysql	select sum(`likes`) as `likes`, sum(`tweets`) as `tweets` from `table` group by `post_id` 	0.00795768763434676
10970258	16403	joining translate table, keeping order form indexes in sqlite	select word  from unigram, wordidxtranslate where      unigram.follow=wordidxtranslate.word_idx     and     unigram.follow in (select t1.follow                         from unigram as t1                         where t1.alternativespelling like 'test'                         order by t1.freq desc                         limit 10) order by freq desc 	0.596852286616875
10970463	5060	combining rows with similar ids and same dates mysql	select id, date, sum(amount) from mytable group by date, left(`id`,7) 	0
10972599	40550	sqlite 3: select and count together with group by and without group by	select opt      , count(*) as count      , round(cast(count(*) as real)/total, 2) as percent  from tbl_poll    cross join     ( select count(*) as total        from tbl_poll        where poll_id = 'jsfw'      ) as t where poll_id = 'jsfw'  group by opt ; 	0.106996217447556
10972730	30243	compare field with value and return bool	select      (case when password = 'writtenpassword' then 1 else 0 end) as is_equal from     users where     username = 'someuser' 	0.00176809769296353
10972823	10248	mysql 2 columns from 2 tables	select animize_users.username, animize_profile.avatar  from animize_users, animize_profile  where `animize_profile`.`userid` = 1 and `animize_users`.`id` = 1  limit 0 , 1 	0.000124374181098804
10973103	36562	sql - insert a number for another number	select         salesrep,         ordervalue,         paymentmethodid,         case             when paymentmethodid = 1 then 15.00             when paymentmethodid = 2 then 15.00             when paymentmethodid = 3 then 12.50         end as commisionpercent from sometable 	0.000256661288177854
10975434	30497	populating listview from 2 tables sqlite database	select name, expense_name, expense_notes from my_folders, my_expenses where my_folders._id = my_folders.e_fid 	0.00827492827865304
10976226	11765	how to get all rows from left table in a join statement?	select tab1.emp_cd, tab1.emp_name, sum(tab2.num_dy) from employee_mstr tab1, "2nd table records" tab2 where tab1.emp_cd = tab2.emp_cd group by tab1.emp_cd, tab1.emp_name; 	0.000228090456774797
10976568	21653	sql view for acquaintance from table	select t1.player_id, t1.friend_id from tablename t1 inner join tablename t2 on t1.player_id = t2.friend_id and t2.player_id = t1.friend_id 	0.0492955459577815
10977786	2600	how to get x hours after specific hour in mysql?	select hour from hours where hour >= 1339372800 order by hour asc limit 3 	0
10979285	15569	mysql display list of user defined functions in phpmyadmin	select * from information_schema.routines; 	0.0121845227546343
10980112	38598	sql selecting people you may know	select `friend_id` as `possible_friend_id` from `friends` where `player_id` in (             select `friend_id`             from `friends`     where `player_id` = 1)  and `friend_id` not in (           select `friend_id`     from `friends`     where `player_id` = 1) and not `friend_id` = 1        group by `possible_friend_id`  order by count(*) desc         	0.0381944687163028
10981937	16954	return audit date to date type 110	select convert(varchar, [audit date], 110) as audit_date from [your table here] 	0.00479602953234529
10982432	3118	teradata auto-increment query	select   current_date + row_number() over(partition by column2,                                    order by column2)       as mydate   column2,   column3 from fake_table group by 1,2,3 	0.784222500940333
10983624	28220	how to get the last 15 minutes values(sessions) for each row in the table in sql select with sum	select  s1.requesttime ,       (         select  sum(numberofsessions)         from    sessions s2         where   dateadd(minute, -15, s1.requesttime) < s2.requesttime                 and s2.requesttime <= s1.requesttime         ) as totalnumberofsessions from    sessions s1 	0
10984192	12388	sql select user	select  a.hometown,          a.first_name,          a.uid,          a.last_name,          b.friend_one,          b.friend_two,          b.friend_request_id,          p.thumbnail  from    users a         inner join friend_requester b              on b.friend_one = a.uid         inner join profile_pics p              on p.uid_fk = b.frind_two         inner join         (   select  uid_fk, max(created) as created             from    profile_pics             group by uid_fk         ) maxpic             on maxpic.uid_fk = p.uid_fk             and maxpic.created = p.created where   p.uid_fk = $uid 	0.121803162042675
10985085	12428	break up data into columns in mysql	select `ip` ,  substring_index( `ip` , '.', 1 ) as a, substring_index(substring_index( `ip` , '.', 2 ),'.',-1) as b,  substring_index(substring_index( `ip` , '.', -2 ),'.',1) as c, substring_index( `ip` , '.', -1 ) as d from log_table 	0.00493851851735383
10986426	21083	is the query correct?	select po.orderid, p.lastname, p.firstname  from persons as p, product_orders as po  where p.lastname='hansen' and p.firstname='ola' and po.personid = p.personid 	0.66791567599423
10986520	13829	mysql join on most recent start_date?	select t.event_date, t.amount, p.percent from bedic_sixsummits_transactions as t left join bedic_sixsummits_percent as p on p.effective =     ( select max( p2.effective ) from bedic_sixsummits_percent as p2      where p2.effective <= t.event_date    ) order by t.event_date desc limit 0 , 30 	0.00168531579737181
10989026	16374	how to set date format for the result of a select statement in sql server	select * 	0.00481695488410179
10989109	18988	mysql insert with duplicate support	select * from player as p, playerdata as pd where p.username = '" + name + "' and pd.username = '" + name + "' 	0.423251251376709
10989319	19612	select with 2 tables	select p.idpaciente, p.nombres, p.apellidos, p.fecnac, p.direccion, p.telefono,         e.detalle, a.namea, a.apea from paciente as p join enfermedad as e on e.idenfermedad = p.idenfermedad  join apoderado as a on e.idapoderado = a.idapoderado 	0.031328301991902
10992166	34898	converting string with multiple dates into a dd-mm-yyyy format in javascript (php/sql) ont he backend	select group_concat(date_format( date_time_column, '%d-%m-%y' )) from test_table; 	0.0053889653356862
10993251	36965	join two group by commands into one	select   message,   sum(read) as num_read,   sum(case read when 0 then 1 else 0 end) as num_unread from message where user_id = 6 group by user_id 	0.015536259408876
10993815	5695	group function is not applying on character rows	select max(gname), pbook, max(cnic),  lpname, sum(acre)     from your_table group by pbook, lpname 	0.626601129073341
10994538	16525	mysql change view column from bigint to bit	select f1.player_id,         f2.player_id,         case           when f2.player_id is null then 0           else 1         end as back  from   friend f1         left outer join friend f2                      on f1.friend_id = f2.player_id 	0.0389711553101873
10994814	26904	search between two dates and show results - gridview	select * from your_table where name='name1' and date between 'first date' and 'final date'; 	0.000389911567149807
10994980	41327	how to find current month and year from custom date range?	select  dateofjoining,         dateadd(day, 20, dateadd(month, datediff(month, 0, getdate()) - 1, 0)) periodstart,         dateadd(day, 19, dateadd(month, datediff(month, 0, getdate()), 0)) periodend from    tblemployeemaster where   dateofjoining > dateadd(day, 20, dateadd(month, datediff(month, 0, getdate()) - 1, 0))          and          dateofjoining < dateadd(day, 20, dateadd(month, datediff(month, 0, getdate()), 0)) 	0
10995324	20460	count and select query from two tables	select u.name, u.email, u.rank, u.id, count(p.id) as 'pagecount' from users u join pages p on     p.id = u.id group by u.name, u.email, u.rank, u.id 	0.00222454448637654
10996174	29575	database entry for every webpage view (analytics)	select count(*)   from your_table  where site = 'thesite'        and date = '<date>'  group by site, date 	0.0085226533534923
10997019	28773	to retrieve the name , host and sessionid of the of the users with top 10 maximum of sessionids in a particular time	select top 10 name, host, sessionid, count(*) from table where timelog between @a and @b group by name, host, sessionid order by count(*) desc, name, host, sessionid  	0
10997131	6659	how to check the isolation level of another connection sql server 2008	select case transaction_isolation_level                          when 0 then 'unspecified'                          when 1 then 'readuncomitted'                          when 2 then 'readcomitted'                          when 3 then 'repeatable'                          when 4 then 'serializable'                          when 5 then 'snapshot'                    end  from sys.dm_exec_sessions  where session_id = <spid_of_other_session> 	0.0682620042628733
10999281	11057	find records that do not have a corresponding record in the same table	select jobid from jobs group by jobid having max(resulttype) = 0 	0
10999913	15892	why do results from a sql query not come back in the order i expect?	select * from table   order by column1 desc 	0.766216070162381
11001265	26348	mysql/php order by on malformed data	select * from (   select year, col2, col3 ... from `values` where `object_id`='$id'        order by  `year` desc, `id` desc limit 18   ) a order by year asc 	0.352487194944408
11001376	19887	how can i compare two columns against a combination of two columns in a table in oracle?	select *   from tableb  where (prods, prod_colour) in        (select prods, prod_colour           from tablea a          where date_ > tdate or date_ is null); 	0
11001993	21840	remove all dots from a string except first, with oracle regexp_replace	select regexp_replace(num, '(\d+)(\.)(.*)', '\1\2') ||         replace( regexp_replace(num, '(\d+)(.*)', '\2') ,'.','')  from my_table; 	0.000118703543887174
11002368	35316	mysql join table as content?	select name, province,  (select group_concat(word) from answers a where a.user_id = c.user_id) as words  from contacts c 	0.139528038040873
11002565	15956	mysql self-referencing query	select * from table as t1 inner join table as t2 on t1.client_id = t2.client_id where t1.client_input = 'city' and t2.client_input = 'state' and t2.input_value = 'ca' 	0.564099525091464
11003140	24794	how can i select multiple rows from a table using a range of values in where clause?	select f.member_id as user, c.member_id as commentby, c.comment as comment from commentingtable as c, friendstable as f where c.member_id = f.member_id    or c.member_id = f.friend_id group by f.member_id 	0
11003229	34344	retrieve specific field from a previous date	select a.id,      a.company,      a.currentvalue,      isnull(b.currentvalue, 0) as 'lastyearvalue',     a.date from dbo.table a left join dbo.table b on a.company = b.company and b.date = dateadd(year, -1, a.date) 	0
11003431	31359	sql between dates- format an issue?	select emailaddress,birthday from table1 where birthday between to_date('01-01-1946','mm-dd-yyyy') and to_date('01-01-1988','mm-dd-yyyy'); 	0.281555140753998
11003821	21818	left join and get total records on joined table	select `users`.`id` as id  from (`users`) left join `work_orders` on `users`.`id` = `work_orders`.`assigned_to`  where (work_orders.status = 'approved'    or work_orders.status = 'scheduled'    or work_orders.status = 'published')    and work_orders.is_paid = 0  group by `users`.`id` order by `users`.`id` desc limit 30 	5.57553656443708e-05
11005238	31505	using left join and where in another field of joined table	select field1, field2, ... from work_orders where exists (     select 1      from users      where  users.id = work_orders.assigned_to         and manager_id='143' ) 	0.00690828865109985
11006449	4444	sql server : splitting the results of group by into a separate columns	select id, sum(event0), sum(event1), sum(event2), sum(event3), sum(event4) from (     select id,          case eventtype when 0 then 1 else 0 end as event0,         case eventtype when 1 then 1 else 0 end as event1,         case eventtype when 2 then 1 else 0 end as event2,         case eventtype when 3 then 1 else 0 end as event3,         case eventtype when 4 then 1 else 0 end as event4     from dbo.events ) e group by id 	0.000125378859325448
11006591	14281	database suggestions for storing a "count" for every hour of the day	select * from my_table where date='2012-06-12' 	0
11006777	15644	retrieving certain strings within a string using oracle sql - part 2	select regexp_substr(line, 'axyzapple[^,]*') subtxt from (select regexp_substr(:x, '[^,]*\,', 1, rownum + 1) line       from dual       connect by level <= length(:x) - length(replace(:x, ',', ''))) where line like '%axyzapple%'; 	0.000177065636033182
11010204	33704	how can i get the roomattributes description which belongs to the rooms sql	select room.id, room.roomname, roomattributes.attributename  from room  inner join roomrelationsship on roomrelationsship.room_id = room.id inner join roomattributes on roomrelationsship.roomattributes_id = roomattributes.id 	9.02359708530351e-05
11010373	7836	return first of each id in query	select  * from    players p1 where   p1.id =         (         select  id         from    players p2         where   p2.playerid = p1.playerid         order by                 date desc         limit   1         ) 	0
11011242	15430	oracle: select with applied transform unless field is empty	select a.cluster_id,        case            when a.cell_geom is not null then sdo_cs.transform(a.cell_geom, 4326).get_wkt()            else a.cell_geom.get_wkt()        end cell_geom,        case            when a.cell_centroid is not null then sdo_cs.transform(a.cell_centroid, 4326).get_wkt()            else a.cell_centroid.get_wkt()        end cell_centroid,        case            when a.cluster_centroid is not null then sdo_cs.transform(a.cluster_centroid, 4326).get_wkt()            else a.cluster_centroid.get_wkt()        end cluster_centroid,        a.num_points,        a.feature_pk,        case            when a.cluster_extent is not null then sdo_cs.transform(a.cluster_extent, 4326).get_wkt()            else a.cluster_extent.get_wkt()        end cluster_extent from highways.cluster_128000m a 	0.214421394232813
11011345	4839	conversion failed when converting date and/or time from character string error	select convert(date, '13-5-2012', 105) 	0.782435611046212
11012218	3966	mysql: selecting all the rows which are related with a particular value from another row	select * from yourtable  where trans_id in (     select trans_id from yourtable where code='b' )  and code!='b' 	0
11016346	8146	mysql regex with null value	select * from table where ifnull(field, '') regexp 'whatever'; 	0.313630701896277
11017073	37393	sql compare 2 columns data and show matching	select  callref,personref  from urtable group by callref,personref  having count(*) > 1 	0
11017836	33883	selecting averages with limit	select  avg(case when rownumber <= 5 then x end) as avg_5,         avg(case when rownumber <= 10 then x end) as avg_10,         avg(case when rownumber <= 15 then x end) as avg_15,         avg(case when rownumber <= 20 then x end) as avg_20,         avg(case when rownumber <= 25 then x end) as avg_25,         avg(case when rownumber <= 30 then x end) as avg_30,         avg(case when rownumber <= 35 then x end) as avg_35 from    (   select  @i:= @i + 1 as rownumber, x             from    my_data,                     (select @i:=0) as i             order by create_date desc         ) as data 	0.0139796608577257
11018801	33260	pull three upcoming events from mysql database	select * from events where concat(year,'-',month,'-',date) > date_format(now(),'%y-%m-%d') order by year desc, month desc, date desc limit 3; 	0.000370294389430005
11019853	7468	working with two lots of columns using inner join	select w.colum1 as name1, w.colum2 as name2, w.*, v.colum1 as name3, v.colum2 as name4, v.* from  `wait_times` as  `w`  inner join  `venues` as  `v` on  `v`.id =  `w`.venue_id where w.user_id =1 limit 0 , 30 	0.762223025995436
11020401	30193	php/mysql - select all rows where a field is unique	select * from table group by (column_b) having count(column_b) = 1; 	0.000127730017248926
11020548	4552	count distinct itesm from mysql query	select count( ft.thread_id ) as num_items from filter_thread ft inner join filter f on ft.filter_id = f.filter_id where f.tag like  '%foo%' or f.tag like  '%bar%' group by ft.thread_id 	0.0496095486404521
11020629	40372	use result from one query as an input into another query on mysql	select dl.* , lv.* from discussion_links dl left join link_votes lv on lv.link_id = dl.link_id where link_side = 'michigan' 	0.0011049968645229
11021082	25820	sql special character	select * from dtcountries where countrycode like '%''%' 	0.611049095290199
11025851	25357	sql query for specific date interval	select [mydate]      from [table]      where datepart(hh,[mydate]) >= 6          and datepart(hh,[mydate]) <= 8      order by datepart(hh,[mydate]) 	0.0222139267295054
11026267	40166	join tables multiple times on different rows in one result set	select      a.id as 'member id',     a.name     sum(a.d1exp) as 'doc 1 expiry',     sum(a.d2exp) as 'doc 2 expiry',     sum(a.d3exp) as 'doc 3 expiry' from     (         select              aa.id,             aa.name,             coalesce(d1.expiry, 0) as d1exp,             coalesce(d2.expiry, 0) as d2exp,             coalesce(d3.expiry, 0) as d3exp         from             members aa         left join             documents d1 on aa.id = d1.member_id and d1.type = 1         left join             documents d2 on aa.id = d2.member_id and d2.type = 2         left join             documents d3 on aa.id = d3.member_id and d3.type = 3     ) a group by     a.id,     a.name 	0
11029592	1343	is it possible to delete all databases that were created by a specific user?	select db from mysql.db where user = "<user>" 	0.00011653246469837
11030306	40452	replace text according to table data	select xmlagg(xmlelement(e, conv)               order by l).extract(' from   (select distinct level l,                          substr('dec', level, 1) letter    from dual connect by level <= length('dec')) inner join jap on alpha = letter order by l ; 	0.00897236345869352
11031639	23103	total and partial columns / column as a total of columns	select user, count(*) as total, sum(if(cup = "cup_1", 1, 0)) as cup_1, sum(if(cup = "cup_2", 1, 0)) as cup_2 from cups group by user 	0
11031956	360	select distinct from two tables	select u.ph    from users u    where exists (select id from orders where user_id = u.user_id); 	0.000992622878071341
11031989	8702	sql server pivot table for hours	select *   from (select datepart(hour, createdon) as searchhour            from asearches) aps  pivot (count([searchhour]) for searchhour in           ( [0],  [1],  [2],  [3],  [4],  [5],             [6],  [7],  [8],  [9], [10], [11],            [12], [13], [14], [15], [16], [17],            [18], [19], [20], [21], [22], [23])) as pvt 	0.0326073140958254
11036243	2498	query items from a database between dates	select * from phoneappdetail where salebarn = 'osi' and (saledate between '2012-06-6' and '2012-06-12') order by wtcode 	0.000160174708191336
11037379	33338	substracting 2 rows in a mysql query left join	select        u.*        cs1.x - cs2.x as xdiff,       cs1.y - cs2.y as ydiff,       cs1.z - cs2.z as zdiff    from        users u          join selections s             on u.id = s.user_id             join clients c                on s.client_id = c.id                join  client_stats cs1                   on ( c.id = cs1.client_id and cs1.`date` = yourfirstdatevariable )                join  client_stats cs2                   on ( c.id = cs2.client_id and cs2.`date` = yourseconddatevariable ) 	0.105873067869576
11038238	10109	apply filter on joined tables with mysql	select id  from   items i where  not exists (select 1                     from   genres g                    where  g.`name` = 'bar'                     and    i.id = g.item_id); 	0.0645905702247353
11038811	8378	sql server : lookup / join on variable length string	select top 1 group1, group2, group3  from temp  where 'aabb' like hier_code + '%' group by group1, group2, group3 order by max(len(hier_code)) desc 	0.437283874447671
11039887	37328	finding sum of values found from a query	select count(memberid) count  from `friendrequest`, member  where status = 2 and (     (memberid = sender and receiver = 19) or      (memderid = receiver and sender = 19) ) 	0.000197025682580604
11040803	4782	sql aggregate of calculated field	select  tblb_1.fooid,      sum(tblc.quantity * (tbla.quantity)) as quantity,      tblb_1.name as name from    tblb as tblb_1 inner join           tblc on tblb_1.fooid = tblc.fooid right outer join           tblb inner join             tbla on tblb.fooid = tbla.fooid on tblc.parentfooid = tblb.fooid where   (tblb.isbundle = 1) and (tbla.isdeleted = 0) group by tblb_1.fooid, tblb_1.name 	0.0830595899354809
11043264	35857	searching for users and returning friends first (order)	select     a.first_name,     a.last_name,     a.uid,     a.hometown,     if(b.friend_two is null, 0, 1) as isfriend from     users a left join     friends b on a.uid = b.friend_two and b.friend_one = $uid where     concat(a.first_name, ' ', a.last_name) like '%q%'     and a.uid <> $uid order by     isfriend desc 	0.000972462468852788
11043407	4931	sort results by the distance from a location javascript	select *, distance(userlat, userlong, places.latitude, places.longitude) as dist from places, uservalues order by dist 	0.00303042819965555
11043930	31143	how to structure tsql query to handle multiple subtables	select sa.shipperstate   from dbo.customers as c left outer join dbo.orders as o  on o.customer_fk = c.customer_pk left outer join dbo.orderstypea as oa   on oa.orderstypea_pk = o.orderstypea_fk left outer join dbo.orderstypeb as ob   on ob.orderstypeb_pk = o.orderstypeb_fk left outer join dbo.orderstypec as oc   on oc.orderstypec_pk = o.orderstypec_fk left outer join dbo.shippers as s   on s.shipper_pk = coalesce(oa.shipper_fk, ob.shipper_fk, oc.shipper_fk) left outer join dbo.shipperaddress as sa   on s.shipperaddress_fk = sa.shipperaddress_pk; 	0.530045407884259
11044334	28082	how to find sum of pivoting two columns in sql server 2005?	select enroll_number,        course_id,        semester,        p as presents,        a as absents,        p+a as sumpa,        1.0*p/(p+a)*100 as percentage from   (     select enroll_number, course_id, semester, flag     from attendence     where course_id = @course_id and            semester = @semester   ) ps pivot   (     count(flag) for flag in ([p],[a])   ) as pvt 	0.000300973831036667
11045611	22170	mysql: substracting values based on two quries	select   a.id,   a.account_name,   a.op_balance,   ifnull(e.amount1,0) as amount1,   ifnull(l.amount2,0) as amount2,   ((ifnull(sum(e.amount1),0)-ifnull(l.amount2,0))+a.op_balance) as balance from accounts a   left join (select                accounts_id,                sum(amount)     as amount1              from entries                left join accounts                  on accounts.id = entries.accounts_id              where entries.side = 'd'                  and accounts.op_balance_dc = 'd'              group by accounts.id) as e     on e.accounts_id = a.id   left join (select                accounts_id,                sum(amount)     as amount2              from entries                left join accounts                  on accounts.id = entries.accounts_id              where side = 'c'                  and op_balance_dc = 'd'              group by accounts.id) as l     on l.accounts_id = a.id group by a.id 	0.000227470629198808
11046517	17464	pivoting in sql	select salesorderid,        max(case partnertype when 1 then partners end) as reseller,        max(case partnertype when 2 then partners end) as distributor,        1 as resellertype,        2 as distributortype from @t group by salesorderid 	0.307704153316689
11047876	39013	select'ing a relationship with postgres as a list	select a.type,        string_agg(b.name, ','); from a    join b on a.id = b.type_id 	0.00423823749374192
11050014	5199	t-sql data migration from xml to columns	select x.id,        t.n.value('@key', 'nvarchar(50)') as [key],        t.n.value('@value', 'nvarchar(50)') as [value] from #xml as x   cross apply x.xmlroutes.nodes('/route/pair') as t(n) 	0.00544427998332141
11051079	32649	finding only strings starting with a number using mysql like	select distinct label_no_country from releases  where label_no_country  regexp '^[0-9]' 	0.00061416823782408
11051506	1558	how to get hierarchy of employees for a manager in mysql?	select * from employee where manager = 7 or manager in (select id from employee where manager = 7) 	0.000261449612320109
11053029	14458	how to get minimum value from the sql table?	select  case when min(coalesce(date, '19001231')) = '19001231' then null else min(date) end as date, id  from x  group by id 	0
11053153	30131	counting different instance of records	select count(*) from (     select distinct [quote number], [quote version]     from table1     ) s 	0.000176509736390818
11056235	15350	finding rows with same values in multiple columns	select a.* from yourtable a inner join (select address, state             from yourtable             group by address, state             having count(*) > 1) b on a.address = b.address and a.state = b.state 	0
11056531	17411	sql joining 5 tables due to a criteria	select * from posts  inner join  (select group from user_rights where right = 101 and user_id = 1) as rights on posts.posted_in = rights.group 	0.0226356399722689
11056753	28640	issue with data fetch in cakephp2.1	select album_id, artist_id, group_concat(song_id) from my_table group by album_id, artist_id 	0.64950271452333
11057136	19232	how to show a null value instead of deleting the entire row when the selected variable isn't there	select * from products t1 left join mybridgetable t2 on t1.productid = t2.productid left join shops t3 on t2.shopid = t3.shopid 	0
11058714	7823	sql query to intersect	select * from gamedata_similar_games g inner join gamedata_franchises f on g.game_id = f.game_id  where f.id= '244' 	0.764312895942494
11058896	36805	mysql column join	select u.id, d1.v as v1, d2.v as v2 from users u  inner join data d1 on u.k1 = d1.k  inner join data d2 on u.k2 = d2.k 	0.254623694819316
11059182	31575	select users from mysql database by privileges bitmask?	select * from users where (user_privileges & 1) >0 	0.0148306928992797
11062401	6805	count how many different countries are in the table	select  count(distinct country) from    yourtable 	0.000363014957687332
11063408	15398	ms access sql: aggregating on min value but retrieving other fields	select a.col1, a.colm, m.col3 from     (         select col1, min(col2) as colm         from test         group by col1     ) as a inner join test m on a.col1 = m.col1 and a.colm = m.col2 	0.000716270952883766
11064279	19293	i need to convert hh:mm:ss to seconds	select   substr(substr("0000000"||time,length(time),8),1,2)*3600 +    substr(substr("0000000"||time,length(time),8),4,2)*60 +    substr(substr("0000000"||time,length(time),8),7,2) from   table where   ... 	0.0385382431965194
11066894	31450	how to find out if a user logged in every day in the last 10 days?	select user_id,        count( distinct date( login_date )) as days from   log_table where  login_date > date_sub( current_timestamp, interval 3 day ) group by user_id having days >= 3; 	0
11068266	20428	calculate an avg with no decimals	select      `tc code`,      round(avg(alw_amt),0) as avg_amt from      office_claims_physicians group by      `tc code` order by      `tc code`; 	0.20245751784004
11069865	21182	how to combine 2 mysql tables like this? (many-to-one relationship)	select a.id, b.username, b.comment        from friendlist a inner join usercomments b on a.id = b.id   order by a.id desc 	0.167958255568461
11072172	18446	how to compute ranks in mysql?	select student_id, mark, rank from (     select t.*,            @rownum := @rownum + 1 as realrank,            @oldrank := if(mark = @previous,@oldrank,@rownum) as rank,            @previous := mark     from student_marks t,           (select @rownum := 0) r,          (select @previous := 100) g,          (select @oldrank := 0) h     order by mark desc  ) as t  order by student_id; 	0.578102217423397
11072217	40398	getting a count of unique records in mysql	select size, color, count(*) from table group by size, color 	0.000245312341793916
11073321	4946	max function without group by	select top 1 id, num  from [table]  order by num desc 	0.507917657708685
11073495	19325	mysql: how to sum up vaues of rows and sort the result?	select id, sum(val) as total from your_table group by id order by total desc; 	0.000556608316764634
11073646	25022	group values from different columns and count	select  coalesce(winner_id, finalist_id) as player_id ,       count(winner_id) as winner_times ,       count(finalist_id) as finalist_times from    (         select  winner_id         ,       null as finalist_id         from    yourtable         union all         select  null         ,       finalist_id         from    yourtable         ) as subqueryalias group by         coalesce(winner_id, finalist_id) 	6.9483200757772e-05
11078557	24109	linq to sql in c# : how to get name via id	select new course_list {   id = cl.id,   name = cl.name,   e_type = cl.e_type.name,   company = cl.company.name }; 	0.00401515607754346
11078798	20626	selecting missing rows and grouping by date (with read-only access to db)	select @rownum:=@rownum+1 rownum, t.*from (select @rownum:=0) r, ("yourquery") t; 	0.00879892679948596
11082223	38785	join sql results	select t1.name,        t1.value,        t2.value from table1 t1 inner join table3 t3 on t1.idfoo1 = t3._id inner join table2 t2 on t2.idfoo2 = t3._id_2 where t3.id=1 and t2.name = 'fooname' 	0.565163289353444
11082949	25789	sql query split and correspond to another table	select a.* from table_a a   left join table_b b on b.name2 = substring_index(a.name1, '-', 1)   where datediff(now(), a.create_date) < b.keep_time 	0.00196897707913566
11084216	30245	select statement to get a specific row from an inner join	select t.id,        t.name,        t.state   from  (     select a.id,            a.name,            b.state,            row_number() over ( partition by a.id order by b.timestamp desc) rownumber       from table_a a      inner join table_b b on a.id = b.prodid ) t where t.rownumber = 1 	0.00203254864506609
11085202	2582	calculate monthly userscores between two tables using mysql?	select userpoints.userid, userpoints.points - coalesce(userscores.points,0)                                                   as mpoints      from `userpoints`     left join `userscores` on userpoints.userid=userscores.userid                  and year(userscores.date) = year(curdate())          and month(userscores.date) = month(curdate())     where userpoints.userid != ".$adminid."     order by mpoints desc;" 	0.000338152331842792
11088632	1551	my sql database specific senario?	select a.plotid, a.size, a...., a.status, b.neighbour_plotid, sum(a.plots_area) from tbl_plots as a inner join tbl_plot_neighbours  as b on a.plotid = b.plotid where a.status = 'no sold' and sum(plots_area) between '1' and '4'; 	0.381408861359474
11089850	2570	integrityerror duplicate key value violates unique constraint - django/postgres	select setval('tablename_id_seq', (select max(id) from tablename)+1) 	0.000301788744462392
11090140	32702	oracle sql to roll up counts into ranges	select     a.mini,     a.maxi,     count(a.item) from (     select         table.item,         case (table.counter)             when counter>=0 and counter<=100 then 0             when counter>100 and counter<200 then 101             when ....         end as mini         table.item,         case (table.counter)             when counter>=0 and counter<=100 then 100             when counter>100 and counter<200 then 201             when ....         end as maxi     from         table ) a group by     a.mini,     a.maxi 	0.00881919536745
11093148	39926	how to select all distinct filename extensions from table of filenames?	select distinct substring_index(column_containing_file_names,'.',-1) 	6.39297964643287e-05
11094466	40369	generate serial number in mysql query	select  @a:=@a+1 serial_number,          marks  from    student_marks,         (select @a:= 0) as a; 	0.00595885272629589
11094628	32320	selecting max date in range, excluding multiple other date ranges	select top 1 tdate.seqdate from dbo.fnseqdates('6/1/2012', '6/30/2012') tdate     left join bfshow tshow         on tdate.seqdate between tshow.datestart and tshow.dateend where tshow.showid is null  order by tdate.seqdate desc  	0
11097049	8600	mysql query for finding the distance with in a radius in miles	select id,first_name,avatar,user_des,thirdparty_account_type,     user_latitude,user_longitude,last_login_time,     sqrt( pow( 69.1 * ( user_latitude - 13.00887806598545) , 2 ) + pow( 69.1 * ( 77.65931731975401 - user_longitude ) * cos( user_latitude / 57.3 ) , 2 ) ) * 0.621371192 as distance from ls_users order by distance asc limit 0,40 	0.193092917741185
11097290	2499	sql column exists in table but not in information_schema	select  satcomratingtableid from    dbo.tblsatcomratingtable  select  f.field ,         c.column_name from    dbo.wiztbl_fields f         left join information_schema.columns c on c.column_name = f.field              and c.table_name = 'tblsatcombillingpackage'   where   f.dataobjectid = 2717         and column_name is null  	0.130115543876312
11098269	33027	group query results after they have already been grouped (codeigniter)	select date, type, sum(amount) as total from accounts group by date, type; 	0.000785518309610332
11098363	38568	mysql query that will group records	select     cid,     sum(arrived = 't') > 0 as arrived,     sum(arrived = 'f') > 0 as not_arrived  from [table 1] group by cid; 	0.0419774590545298
11098978	15564	how to get individual count using this mysql query	select cpd.result, count(*) from cron_players_data cpd where cpd.`status` = '1'  and (cpd.`result` = '1' or cpd.`result` = '2')  and cpd.`player_id` = '81' group by cpd.`result` 	0.0952039461301775
11099458	32335	order by date difference between two date columns	select * from table order by timediff(to, from) 	0
11100046	32861	mysql: get todate , fromdate from week no.	select   adddate(curdate(), interval 1-dayofweek(curdate()) day) _from,   adddate(curdate(), interval 7-dayofweek(curdate()) day) _to; 	0.00195163265149256
11101154	32436	selecting data from two mysql tables	select p.* from table_global_products p inner join table_stores s on s.store_id = p.store_id where s.store_country = 1 	0.000208043702293099
11101614	10867	obtaining inserted sqlite from command line	select last_insert_rowid(); 	0.0121980672452932
11103273	5704	sql to join two tables with some business conditions	select  cat.accountno,          sum(case when cat.balance1 <> 0 or isnull(sat.balance2,0) <> 0 then 1 else 0 end) counttransactionid,         sum(case when cat.balance1 <> 0 or isnull(sat.balance2,0) <> 0 then cat.balance1+sat.balance2 else 0 end) sumbalance1balance2 from cat left join sat on cat.balanceid = sat.balanceid 	0.0879227587786134
11103958	27232	mysql convert 48 hours into 48:00:00	select concat(datediff(end_time, now()) * 24), ':00:00') 	0.00203992274058828
11104641	33217	selecting a summed value from a subquery that relies on a joined table	select  c.id,          c.company,          coalesce(sales.amount, 0) as sales,          coalesce(payments.amount, 0) as payments from    customers c         left join         (   select  customer_id, sum(amount) as amount             from    invoices                     inner join invoice_transactions                         on invoice_id = invoices.id             group by customer_id         ) as sales             on sales.customer_id = c.id         left join         (   select  customer_id, sum(amount) as amount             from    account_payments                      inner join invoice_transactions tr                         on tr.id = transaction_id             group by customer_id         ) as payments             on payments.customer_id = c.id; 	0
11105557	37362	mysql query - join tables to show all values from one table and only matching results in other column	select j.job,p.person  from   jobs j  left  join   `persons-jobs` p  on     j.job = p.job  and    p.person='johnsmit' 	0
11106262	39383	no mysql result until where specified	select customerid, name, boxid, count(codes.code) as codesused  from customers  inner join codes on customers.boxid = codes.boxid  group by customerid, name, boxid, codesused having codes.retrieved = 1 	0.0334432319920959
11106888	11514	using or in like query in mysql to compare multiple fields	select * from mytable where (column1 like '%keyword1%' or column2 like  '%keyword1%') and (column1 like '%keyword2%' or column2 like '%keyword2%'); 	0.261609723387823
11107077	13739	delete partial duplicates from a mysql table	select * from persons group by id 	0.0013197994821252
11107359	14610	obtaining unique/distinct values from multiple unassociated columns	select ts.system, town.owner from (select system, row_number() over (order by system) as seqnum       from (select distinct system             from t            ) ts      ) ts full outer join      (select owner, row_number() over (order by owner) as seqnum       from (select distinct owner             from t            ) town      ) town      on ts.seqnum = town.seqnum 	0.000560454869755115
11108230	11157	inner join query using multiple values	select aa.*, bb.appreleaseid, bb.releasedate from app aa left join (             select a.appid, a.appreleaseid, a.releasedate             from apprelease a inner join (                         select appid, max(releasedate) mx from apprelease                          group by appid                     ) b on a.appid = b.appid and a.releasedate = b.mx         ) bb on bb.appid = aa.appid 	0.632927520808813
11108645	3295	how to display data according to the user information	select r.*,u.* from users u join requests r on (r.uid = u.id) where r.request_id = ? 	0
11112395	34327	postcodes and distance mysql query	select dist,p1,p2,dealer_postcode from t_dealer, t_postcodes where (if(dealer_postcode<$user_postcode,p1,p2)=dealer_postcode) and (if(dealer_postcode<$user_postcode,p2,p1)=$user_postcode) 	0.677288726783789
11112894	21755	sql: viewing the latest id based on latest updated timestamp	select route_de.route_name, route_de.route_id from route_de join (select max(updateddate) as maxdate, route_name from route_de group by route_name) maxroutes on maxroutes.maxdate = route_de.updateddate and maxroutes.route_name = route_de.route_name 	0
11112926	7416	how to find nearest location using latitude and longitude from sql database?	select id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) as distance from markers having distance < 25 order by distance limit 0 , 20; 	0.00257534844783426
11113614	33507	select count from another table to each row in result rows	select c.classid, c.classname, count(s.studentid) as studentcount from classes c left join students s on (c.classid=s.classid) group by c.classid, c.classname 	0
11113944	23513	case when with multiple values	select t.a from t where (t.a in (1,2,3) and t.b = 1) or (t.a in (4,5) and t.b <>1) 	0.507511417786589
11115285	1068	compare data two table in mysql	select a.* from a left join b on a.column_a = b.column_b and a.id = b.id where b.id is null 	0.00124771916734347
11120407	12901	calculate if hour has at least half double coverage	select * from (     select row_number()          over (partition by hour order by employeesworking desc) as rownum, *     from table ) as agg where rownum = 2 	0.000118858121942902
11121775	4479	transforming shape of a sql table using pivot	select batchid,     max(case when entitychanged = 'abc' then changevalue end) 'abc',    max(case when entitychanged = 'abcd' then changevalue end) 'abcd',    max(case when entitychanged = 'something' then changevalue end) 'something',    max(case when entitychanged = 'somethingmore' then changevalue end) 'somethingmore' from yourtable t  group by batchid 	0.688791767623396
11122262	38250	sql server select first instance of ranked data	select min(rank) as rank, name from tablename group by name 	0.00171866304812451
11122520	4294	mysql - select info based on many tables	select distinct d.username, c.ip  from delivery d inner join customers c     on d.username = c.username     and date(d.date) >= "2012-06-01" order by c.ip 	0.000243071405652357
11122790	5581	total field in crosstab query in sql server 2008	select  equipt, [bsl] as bsl, [aq] as aq, ([bsl] + [aq]) as ttl from  (       select equipt, shed       from punctualitymain       where date >= '4/1/2012' and date <= '4/30/2012'            and classification    = 'loco'  ) x pivot  (      count(shed)      for shed in ([bsl], [aq]) )  p 	0.107679862380217
11122903	20645	greater of two variables in mysql query	select a, b, greatest(date1,date2) as date from... 	0.0175235112382474
11124437	10445	how to merge 2 xml variables in sql server 2008	select isnull(s.n.query('.'),f.n.query('.')) as '*' from @first.nodes('/dbperson/*') as f(n)   full outer join @second.nodes('/fromui/*') as s(n)     on f.n.value('local-name(.)', 'nvarchar(100)') = s.n.value('local-name(.)', 'nvarchar(100)') for xml path(''), root('dbperson') 	0.0754855279040709
11125498	37096	join 2 tables, print data from 2nd table when joined rows occur	select u.id, u.onoma_u, u.name_u,        coalesce(u.programa, aa.programa) as programa,        coalesce(u.barcode, aa.barcode) as barcode,        coalesce(u.plan, aa.plan) as plan,        coalesce(u.im_exp, aa.im_exp) as im_exp,        coalesce(u.symb, aa.symb) as symb        from (select a1.id, a1.onoma_u, a1.name_u, a1.programa, a1.barcode, a1.plan, a1.im_exp, a1.symb        from aitisi a1          union            select a2.id, m.name, m.surname, null, null, null, null, null            from members m         join aitisi a2 on a2.id = m.symbid) u        join aitisi aa on aa.id = u.id; 	0
11126379	33460	mysql - how to select case (two tables, if not present in one, check the other)	select address, suburb, city, postcode, province from user_postal inner join user_info on user_postal.id = user_info.id where user_info.emailcontact = 'example@example.com' union select address, suburb, city, postcode, province from user_postal inner join user_business_info on user_postal.id = user_business_info.id where user_business_info.emailcontact = 'example@example.com' 	7.27309478784262e-05
11126912	6395	using column from outer mysql query in subquery	select     category as category,     count(*) as without,     sum(pointsoff = 0) as with from items where id=706 group by category; 	0.746004654268674
11127234	5669	sql count distinct	select count(distinct employeeid) from .... 	0.134589483711289
11127412	4007	group by and display latest entry date for that group	select     productid,     color,     sum(quantity) as totalquantity,     max(timestamp) as latestdate from inventory group by productid, color; 	0
11127864	36045	need specific output in sql	select concat('ids', ' > ','9000'),'100,00' 	0.345657637944537
11130164	27008	querying aggregate columns in a sql server select statement	select      messageid_,      issue,      mailed,      successes,      opens,      unique_opens,      convert(decimal(3,1),((convert(float,[unique_opens]))/[successes]) * 100) as 'rate'  from   (select       outmail_.messageid_,        convert(varchar(10),outmail_.created_,120) as 'issue',        lyrreportsummarydata.mailed,        lyrreportsummarydata.successes,        count(*) as 'opens',       count(distinct clicktracking_.memberid_) as 'unique_opens'     from outmail_      right join clicktracking_ on clicktracking_.messageid_ = outmail_.messageid_     right join lyrreportsummarydata on lyrreportsummarydata.id = clicktracking_.messageid_      group by  outmail_.messageid_, convert(varchar(10), outmail_.created_,120), lyrreportsummarydata.mailed, lyrreportsummarydata.successes    ) subquery 	0.337345348009504
11131278	2664	linq to sql : how to get data - one to many	select new unit_list() {     unit_name = cl.name,     unit_type_name = cl.unit_type.name,     tool_name = string.join(", ",          cl.unit_tools.select(ut => ut.tool.name).toarray()     ) }; 	0.00291453961292435
11131717	29432	selecting max date and sum of comprate in sql server	select     sum(comprate) as compratesum from         (select     top (2) id, employee_code, effdt, comprate                        from          _test                        where      (employee_code = '000321514')                        order by effdt desc, id desc) as derivedtbl_1 	0.00274050146538013
11131940	20924	mysql data search with varchar type	select * from checkfinale  where associateid = 51 and      str_to_date(completeddate,'%d/%m/%y') >= '16/04/2012'     and str_to_date(completeddate,'%d/%m/%y') <= '22/06/2012' 	0.19431857610703
11132436	25349	retrieve nested parent child xml based on parent xml in sql xml	select firstname,        lastname,        class as "details/class",        mark as "details/mark" from student for xml path('students'), type 	0
11132532	6817	sql query - merge data from rows with same id	select      post_title, b.object_id, b.term_taxonomy_id, c.term_id, group_concat(d.name) from wp_posts a     join wp_term_relationships b on a.id = b.object_id     join wp_term_taxonomy c on b.term_taxonomy_id = c.term_taxonomy_id     join wp_terms d on d.term_id = c.term_id group by post_title, b.object_id, b.term_taxonomy_id, c.term_id 	0
11134452	25746	find/cut string from first integer in mysql	select      replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(substring_index(column, '-', 1), '0', ''), '1', ''), '2', ''), '3', ''), '4', ''), '5', ''), '6', ''), '7', ''), '8', ''), '9', '') as extracted from     yourtbl 	0.00197591039745519
11135464	35962	finding number position in string	select    myword,    least (     if (locate('0',myword) >0,locate('0',myword),999),     if (locate('1',myword) >0,locate('1',myword),999),     if (locate('2',myword) >0,locate('2',myword),999),     if (locate('3',myword) >0,locate('3',myword),999),     if (locate('4',myword) >0,locate('4',myword),999),     if (locate('5',myword) >0,locate('5',myword),999),     if (locate('6',myword) >0,locate('6',myword),999),     if (locate('7',myword) >0,locate('7',myword),999),     if (locate('8',myword) >0,locate('8',myword),999),     if (locate('9',myword) >0,locate('9',myword),999)   ) as mypos from mytable; 	0.00138529678025045
11135540	869	mysql join over multiple tables	select    category_id, s.meta_kw, s.meta_desc, m.meta_keywords, m.meta_description from cms_sites s  left join cms_category_meta m on s.site_id = m.site_id  left join cms_categories cat on m.category_id = cat.category_id                             and cat.category_url = '?' 	0.260263772200379
11136023	12364	mssql, table contains duplicate row values for one column but its values for other coumn are diffrent, unique values of multiple entry?	select distinct (artikelnr) from artalias where artikelnr not in      (select artikelnr from artalias where enhet = 5) order by artikelnr 	0
11136044	36235	how to check for multiple values in mysql using in and a parameter?	select tbl.products  from table as tbl  where find_in_set(tbl.color , 'red,green,blue,yellow,orange,black'); 	0.0189971868736752
11136063	32917	using group by for an non-uniqueness-warning column	select    key,    min(value1) as "a value1",    min(value2) as "a value2",    max(value2) as "another value2",    count(distinct value2) "number of value2" from tbl group by key having count(distinct value2) > 1 	0.357819976165939
11137438	883	sql select rows by comparison of value to aggregated function result	select     mv.* from     (         select             team, gameid, min(max_minions) as maxmin         from             minionview         group by             team, gameid     ) groups     join minionview mv on         mv.team = groups.team         and mv.gameid = groups.gameid         and mv.max_minions = groups.maxmin 	0.00578219180804865
11138014	7357	how to write sql query to get data which the best matches with data in database	select text  from mytable  where levenshtein_ratio(text, 'text_to_compare') > 80  limit 1 	0.000839563292889484
11138545	38633	how to set default empty in query	select new {      x,      a.desiredfieldfroma,      b.desiredfieldfromb,      name = c.name ?? string.empty }).tolist(); 	0.0952034276852892
11139049	28807	sql top 1 in xml path ('')	select(     select m.code + '   ' + cast(m.completed as varchar(max)) + '   '+ cast(ol.billed as varchar(max)) + '  ' + cast(m.delete as varchar (max))      matterdetails as m     full join (select id, max(billed) as 'billed' from officeledger) as ol on ol.id=m.id         order by ol.billed desc  for xml path('')) 	0.31405353485805
11140258	30214	convert varchar into date without day	select convert(date, data + '-01') from dbo.table; 	0.000208161152211524
11140267	4900	mysql query in query with only 1 result for each in id	select name, item_id, min(position) from my_table  where item_id in (17, 3) and name != '' group by item_id; 	0.000130343261883754
11142511	22142	column decimal point value	select convert(decimal(10,2),sum(papostedtotalcostn)) as total_cost  from pa01201 where pa01201.pacontid = '00900' 	0.0102564697835848
11143119	30517	mysql find only unique records in a subquery and show the count	select web_login_id, cw.open_projects from login l left outer join       (select copywriter, count(project_web_id) as open_projects        from project        where `status`  in ('open', 'qual')        group by copywriter       ) cw       on l.web_login_id = cw.copywriter where l.roles like '%copywriter%' and l.tierlevel like '%c1%'  order by open_projects asc 	0
11143219	24369	return rows random and then order by	select t1.*  from table t1, (select id from table order by rand() limit 10) t2 where t1.id = t2.id order by t1.name 	0.00147558846777504
11144627	2123	newbie: mysql join 2 tables to gether and count the results	select word, count    from words natural join segments; 	0.132264904920076
11144683	28834	how to pivot the results of a stored procedure in sql server	select * from  (     select date, value, unit     from      (         select *         from t1     ) x     unpivot ([value] for unit in ([unita], [unitb], [unitc])) u ) a pivot (     sum(value)     for date in ([2010], [2011], [2012]) ) p 	0.316443617214104
11145863	24289	allow entry of only once till year.?	select * from domains where url like '%$url%' and time < date_sub(now(),interval 365 day); 	0
11147708	37440	selecting rows based on distinct 2 fields in postgres	select distinct on (least(user_id, recipient_id), greatest(user_id, recipient_id))     id, user_id, recipient_id, message from the_table where user_id = 1 or recipient_id = 1 	0
11148137	26045	rank books with ties	select * from book_ranks cer inner join (select rank() over (order by book_score desc  )    as ranc, book_id   from book_ranks   where category = 'fiction' group by book_id, book_score  ) ranker on cer.book_id = ranker.book_id; 	0.253777770583744
11148374	27183	count two columns with two  where clauses	select     count(distinct member_id) as members,     count(*) as trans from     tbl where      member_id not in     (         select distinct member_id         from tbl         where trans_date > '2012-01-01'     ) 	0.00342507743384475
11149981	7445	full outer join on full column list first, otherwise partial column list	select * from   a full   join b using (a,b,c) order  by a desc nulls last; 	0.0010318283123701
11150435	1359	mysql order by min() not matching up with id	select id,min(hit_count),domain from table group by domain having domain='$domain' 	0.0311316959443135
11151939	13194	calculation and multiple joins in mysql	select   p.productid,   (ifnull(g.g_sum,0) + ifnull(rq.rq_sum,0))-(ifnull(i.i_sum,0) + ifnull(ro.ro_sum,0)) as stockbalance,   ifnull(g.g_sum,0) as grn_quantity,  ifnull( rq.rq_sum,0) as return_in_quantity,  ifnull( i.i_sum,0) as inventory_quantity,  ifnull( ro.ro_sum,0) as return_out_quantity from products as p   left join (select            productid,            sum(grnqty)  as g_sum          from grnqty group by productid) as g     on g.productid = p.productid   left join (select            productid,            sum(retinqty) as rq_sum          from returninqty group by productid) as rq     on rq.productid = p.productid   left join (select            productid,            sum(invqty)  as i_sum          from invoiceqty group by productid) as i     on i.productid = p.productid   left join (select            productid,            sum(retoutqty) as ro_sum          from returnoutqty group by productid) as ro     on ro.productid = p.productid 	0.720062560495821
11151987	16778	selecting a record on the basis of last modified status	select     a.fieldid from     (         select fieldid, max(createdwhen) as maxdate         from tbl         group by fieldid     ) a inner join     tbl b on          a.fieldid = b.fieldid and         b.createdwhen = a.maxdate and         b.status = 'up' 	0
11155725	37384	select random row that exists in mysql	select * from table order by rand() limit 1 	0.0044934394313697
11155886	8653	split firstname and lastname in sqlite	select   substr( name, 1, pos-1) as first_name,   substr( name,    pos+1) as last_name from (       select         author.name,         numbers.x as pos       from       author       inner join numbers       where substr( author.name, numbers.x, 1) = ' '       group by author.name      ) as a order by last_name; 	0.709584884487832
11155944	10767	how to get pk info from sql server compact	select index_name, column_name   from information_schema.indexes   where primary_key = 1   and table_name = 'mytable'; 	0.00572673432280065
11156563	32831	using alias name in another column	select    mytable.myword,    mypos.l,   if (l=999,mytable.myword,substr(mytable.myword,1,l-1)) as newstring from mytable,  (select myword, least (     if (locate('0',myword) >0,locate('0',myword),999),     if (locate('1',myword) >0,locate('1',myword),999),     if (locate('2',myword) >0,locate('2',myword),999),     if (locate('3',myword) >0,locate('3',myword),999),     if (locate('4',myword) >0,locate('4',myword),999),     if (locate('5',myword) >0,locate('5',myword),999),     if (locate('6',myword) >0,locate('6',myword),999),     if (locate('7',myword) >0,locate('7',myword),999),     if (locate('8',myword) >0,locate('8',myword),999),     if (locate('9',myword) >0,locate('9',myword),999)   ) as l from mytable) as mypos where mypos.myword = mytable.myword 	0.0301236565374931
11157148	8279	sql query in oracle flattening out a table	select      controlnum "controlnumber",     taxyear "taxyear",     payrollg "payrollgroup"     max(nvl(alaska, 0)) 'alaska'     from      states     group by controlnum, taxyear, payrollg 	0.368247342133356
11157758	6668	correcting spelling mistakes in a column based on another table in mysql	select * from tablea as orig left outer join tableb as correct on soundex(orig.city_name) = soundex(correct.city_name) where orig.city_name not in (select city_name from tableb) 	0.000135968189253586
11160140	5537	joining 2 sql queries in mysql	select r.hotel_id, count(distinct k.room_id) as numrooms,        count(distinct kr.room_id) as numreserved from room k left outer join      room_reservation kr      on kr.room_id = k.room_id  group by r.hotel_id 	0.109280681488535
11161728	14873	displaying mysql dob records between now and xx days	select * from table where date_col between curdate() and date_add(curdate(), interval 15 day) 	0
11161875	18747	getting the previous and next step unique id based on current step number	select     nxt.stepnum as nextstep,     nxt.unqid   as nextunqid,     prv.stepnum as prevstep,     prv.unqid   as prevunqid from (select null) as dummy  left join ( select stepnum, unqid from foo   where stepnum = (select min(stepnum)                    from foo                    where stepnum > 5 ) ) as nxt on true left join ( select stepnum, unqid from foo   where stepnum = (select max(stepnum)                    from foo                    where stepnum < 5 ) ) as prv on true 	0
11164533	36156	trying to run a select sql query based on the dropdown list result. mysql php	select date, subject, message from news where date = $_post['fieldvalue'] 	0.00284651076222949
11165959	41217	sort queryies by id and name	select table2.staffid, table1.firstname from table1 inner join table2 on table2.staffid = table1.id order by firstname 	0.00645604352008914
11167540	38391	mysql - select most recent of column type entry	select     b.* from     (         select sup_type, max(sup_date) as maxsupdate         from tbl         group by sup_type     ) a inner join     tbl b on          a.sup_type = b.sup_type and          a.maxsupdate = b.sup_date order by     b.s_id 	0
11167903	2913	hh:mm format in sql server	select substring( convert(varchar, getdate(),108),1,5) 	0.159353994563055
11171405	18279	can i combine 2 queries into one data array from 2 different tables?	select id_file, name, 'file' as `type`  from `files`  left join `folders` on `files`.`folder_id` = `folders`.`id`  where `folders`.`id` = 198 union select id_folder, name, 'folder' from `folders` where `parent` = 198 limit 0, 20 	0
11171503	9466	get the highest amount of visitors grouped by date	select date(date_visited) from visitors group by date(date_visited) order by count(*) desc limit 1 	0
11172525	37215	query to count number of followers	select     count(case when user_email = '<email>' then 1 else null end) as following_cnt,     count(case when following_email = '<email>' then 1 else null end) as follower_cnt from     list where      '<email>' in (user_email, following_email) 	0.00835336997619457
11172714	32496	getting elements from linking table	select distinct element  from  your_table where element not in (select element                        from your_table                        where `group` = 2) and `group` = 1 	0.000132116475948386
11174161	25210	finding first pending events from sql table	select source.* from tv_guide as source join (select channel_id, min(start_time) as start_time     from tv_guide     where start_time >=  now() group by channel_id ) as start_times on (source.channel_id = start_times.channel_id      and source.start_time = start_times.start_time) order by channel_id; 	0
11175360	34407	how to modify this query to show the total number of employees and percent completion in each division?	select  d.divisionshortcut ,       c.coursename ,       d.employeecount as divisionemployees ,       count(c.courseid) as completedcourses ,       100.0 * count(c.courseid) / d.employeecount as percentagecompleted from    dbo.courses c join    dbo.employee_courses ec on      c.courseid = ec.courseid join    dbo.employee e on      ec.employeeid = e.username join    (         select  d2.sapcode         ,       d2.divisionshortcut         ,       count(e2.divisioncode) as employeecount         from    dbo.divisions d2         join    dbo.employee e2         on      d2.sapcode = e2.divisioncode         group by                 d2.sapcode         ,       d2.divisionshortcut         ) d on      d.sapcode = e.divisioncode where   c.groupid = 1 group by          d.divisionshortcut ,       d.employeecount ,       c.coursename 	0
11175669	32252	how to select previous record with left joined tables in mysql?	select klha.buyerid      from agents as v     left join seller_authorized as klhs          on klhs.agent= v.agentid          and klhs.iln = v.seller         and v.`status` = 'auth'     left join cust_list as klha          on klha.buyerid  = klhs.userid         and klha.accountno = klhs.accountno     where v.iln = parameter_2       and klhs.acccountno is not null       and klha.buyerid = (select max(buyerid) from agents                              where buyerid < parameter_1)     order by klha.buyerid      limit 1 	0.0011625598827284
11175880	20263	select articles which are in a table but not in a second table	select articleid, description from articles where articleid in (select articleid from ordearticle) and articleid not in (select articleid from ereportarticle) 	0
11176095	14759	sybase - duplicate rows after union	select id, coalesce(a.dn, b.dn), coalesce(a.pn, b.pn), coalesce(a.sp,b.sp) from dn a     left outer join sp b          on a.id = b.id 	0.0109383677142861
11177607	26770	convert signed int to string ip address in sql server	select          ltrim(cast(substring(ip,1,1) as tinyint)) + '.' +          ltrim(cast(substring(ip,2,1) as tinyint)) + '.' +          ltrim(cast(substring(ip,3,1) as tinyint)) + '.' +          ltrim(cast(substring(ip,4,1) as tinyint)) from dbo.ipaddress cross apply (select cast(ipaddress as binary(4))) c(ip) 	0.0731012237272178
11178067	1338	how to join three semi related tables	select      countries.name as country,     cities.name as city,     hotels.name as hotel from countries left join cities on cities.country_id = countries.id left join hotels on hotels.city_id = cities.id where countries.id = @id 	0.0561683626429912
11179059	32392	sql, how to find the maximum time in column a that is < the time in column b of the current row	select  b.time ,       b.data ,       a.state from    b outer apply         (         select  top 1 *         from    a         where   a.time < b.time         order by                 a.time desc         ) as a 	0
11179251	27749	mysql: how to reuse a calculation within a query	select      t.key, t.dif from (         select key, timestampdiff(hour, table.date_last_consulted, current_timestamp) dif         from table      ) t where      t.dif <= 7  order by      t.dif 	0.138286250337149
11179484	14713	mysql: using alias as a column	select  * ,       item_unitprice * total_ecuation as item_subtotal ,       (item_unitprice * total_ecuation) - item_discount as item_total from    (         select  ri.item_code         ,       case status_code                 when 11 then ri.item_quantity - rr.item_quantity                  when 12 then ri.item_quantity + rr.item_quantity                 end as total_ecuation         ,       rr.item_unitprice         ,       rr.item_quantity         ,       rr.item_discount * rr.item_quantity as item_discount         from    qa_returns_residues rr         join    qa_returns_items ri         on      ri.item_code = rr.item_code         ) as subqueryalias where   total_ecuation > 0 	0.438212332435841
11180616	14559	mysql select query	select *, if(deaths,civilian_kills * $civ + neutral_kills * $neu + rival_kills * $riv) / deaths,1) as kdr from sc_players order by kdr desc limit 100 	0.387336905290878
11180706	18255	how to check if a row exists when there are two tables involved?	select *  from table1  left join table2      on table1.tool_owners_id=table2.tool_owners_id  where table1.user_id=1  and table2.tool_name='hammer' 	0.000160147057745006
11181174	5711	delete query is runing and not delete any data	select * from `messages` where last_change < 1332201600 && last_change !=0 limit 10 	0.681652696335022
11182852	39332	pull data from mysql that was entered today	select * from contacts where (contacttype = 'buyer' or contacttype = 'seller' or contacttype = 'buyer / seller' or contacttype = 'investor') and date = date(now()) order by date desc 	8.42813674097596e-05
11184067	3159	date between validation using php & mysql	select * from tbl where (applied_from =< @inputdate and applied_to >= @inputdate)  and staff_id=@inputid 	0.0510003452588384
11184229	10187	reclaim disk space from failed insert	select count(*) from new_table; 	0.236095728458354
11184476	26041	how to calculate age in t-sql with years, months, days, hours, minutes, seconds and milliseconds	select  @years as [years] , abs(@months) as [months] , abs(@days) as [days] , abs(@hours) as [hours] , abs(@minutes) as [minutes] , abs(@seconds) as [seconds] , abs(@milliseconds) as [milliseconds] 	0
11184948	36794	equivelent of fn convert in oracle	select convert('groß', 'us7ascii') "conversion" from dual; 	0.486771092012182
11185007	7726	ora-00001: unique constraint check data source	select count(1), f1, f2, f3 from <tables> group by f1, f2, f3 having count(*) > 1; 	0.00222466330304598
11185211	7370	how to show the quizzes that the employee did not participate in them?	select q.title, q.description  from quiz q where          (not exists                                    (select uq.quizid           from userquiz uq, employee e          where q.quizid = uq.quizid and e.username = uq.username)      ) 	8.66137344213247e-05
11186686	5541	sql search results by month in format 2010-04-01 10:40:20	select * from table where month(date) = 4 and year(date) = 2010 	0.0337579176505345
11189575	12721	mysql, pdo "rank"	select * from (select * from mail_schema order by last_updated desc) as x group by id 	0.513703496032324
11190776	2833	join operation on two tables retrieving dates	select   date, total from           (           select   date, sec_to_time( sum( time_to_sec( `total_hours` ) ) ) as total            from     `work_details`            where    employee_id='28' and date between  '2012-02-01' and '2012-02-29'            group by date            union all           (              select holy_date as date, null as total             from   holiday             where holy_date between '2012-02-01' and '2012-02-29'           )          ) as t group by date order by date 	0.00245103245989128
11191340	19963	sql - select on table with multiple rows doubling result	select       sum(tc.weekly_hours) as 'hrs',     sum(pc.var_cash) as 'cash' from         time_capture tc left outer join      (     select          emp_no,          effective_date,          sum(var_cash) as 'var_cash'     from         payment_capture)     pc          on tc.emp_no = pc.emp_no         and tc.effective_date = pc.effective_date where        tc.effective_date = '17 june, 2012' group by l     eft(tc.cost_centre, 4) 	0.00338145486536613
11193520	33592	get the ten minute intervals from a range of datetimes	select dateadd(minute, datepart(minute, datetimesent) / 10 * 10,  dateadd(hour, datediff(hour, 0,datetimesent), 0)) ten_minute_column from  (select cast('2012-06-11 18:27:58.000' as datetime) datetimesent union all  select cast('2012-06-15 15:19:08.000' as datetime)) a 	0
11193724	37079	get repeated rows mysql	select a.id, a.name from table1 a join table2 b on b.id = a.id 	0.00328941114417835
11193896	31580	select distinct or unique records or rows in oracle	select a.a_id, max (b.test) , min (c.test2) from tablea a  join tableb b on a.a_id = b.a_id join tablec c on a.a_id = c.a_id group by a.a_id order by b.test, c.test2 select a.a_id, (select top 1 b.test from tableb b where a.a_id = b.a_id order by test2), (select top 1 b.test2 from tableb b where a.a_id = b.a_id order by test2), (select top 1 c.test3 from tablec c where a.a_id = c.a_id order by test4) from tablea a    declare @a_id int set @a_id = 189 select a.a_id , b.test, b.test4 from tablea a  join tableb b on a.a_id = b.a_id join (select min(b.b_id) from tableb b where b.a_id = @a_id order by b.test3) c on c.b_id = b.b_id where a.a_id = @a_id 	0.00136737936979088
11194923	18614	difference between two times stretched across different days in mysql	select hd.definition_id, if(         hd.sun_end is null or hd.sun_start is null,         0,         if(             hd.sun_end = hd.sun_start,             24,             if(                 hd.sun_end < hd.sun_start,                 24 + (time_to_sec(timediff(                     hd.sun_end,                     hd.sun_start                 )) / 3600),                 time_to_sec(timediff(                     hd.sun_end,                     hd.sun_start                 )) / 3600             )         )) from audit_hour_definition as hd 	0
11195100	7819	how to make a 1 column query by choosing from two columns mysql	select     *,     if(ruser_id = $user_id, suser_id, ruser_id) as the_other_guy from private_mesg where ruser_id = $user_id     or suser_id = $user_id; 	0.000169729021619688
11195106	25030	how to change datatype of a column in a temporary table in sql	select tablea.id_no,    sum(convert(decimal(18,2), tablea.cost) * tableb.qty) as total into #matcalc from tablea a  inner join tableb  on a.id_no = b.id_no; 	0.00155451965718837
11195219	1893	insert missing values from table	select lhs.id + 1 as firstgap from tablename as lhs left join tablename as rhs     on rhs.id = lhs.id + 1 where rhs.id is null 	0.00229519098454996
11195675	23037	generate a spending report from the following tables	select user, retail_category, sum(grand_total) from receipts inner join stores on receipts.store = stores.id_store inner join franchises on stores.franchise = franchises.id_franchise group by user, retail_category; 	0.00792425502941942
11195773	7786	mysql converting various date formats into a unified one	select       case when date regexp '[m-d-y]'           then str_to_date(date, %) 	0.00146279008494331
11196165	36679	sql get first matching results	select * from ( select id , substr(id,0,3),rank() over ( partition by substr(id,0,3) order by id) rank  from mytable where id like 'r43%' or id like 'd32%' or id like 'f22%') where rank = 1 	0.000541145025625015
11196420	41108	selecting of data between a time period and calculating the difference of another parameter(time)	select count(*) as 'processes' from table1 where timestampdiff(minute, start, end) > 10 and start between date_sub(now(), interval 28 day) and now() 	0
11196608	38921	a query calls two instances of the same tables joined to compare fields, gives mirrored results. how do i eliminate mirrored duplicates?	select distinct alias1.id id_1, alias2.id id_2, alias1.file_tag,        alias1.creation_date in_dt1, alias2.creation_date in_dt2 from alias1 join      alias2      on alias1.file_tag = alias2.file_tag and         alias1.id < alias2.id order by alias1.creation_dt desc 	0
11196744	12760	get a certain number of contiguous rows	select p.id, p.prev_id1, p.prev_id2 from (         select id, lag(id, 1) over(order by id) prev_id1, lag(id, 2) over(order by id) prev_id2         from places      ) p where p.prev_id1 = id-1  and   p.prev_id2 = id-2 	0
11199106	19827	find all user in table a that are also in table b	select a.user1, a.user2 from a, b  where (a.user1 == b.user3 and a.user2 == b.user4) or (a.user1 = b.user4 and a.user2 = b.user3); 	0
11200808	31775	sql limit, but from the end	select * from ( select * from people order by age desc limit 3 ) x order by age asc 	0.00941002254952099
11202676	24161	unable to get desired output in mysql	select distinct(`cust_1`) from `daily_visit_expenses` where user='sanjay' and `purpose_1`='sales' union distinct select distinct(`cust_2`) from `daily_visit_expenses` where user='sanjay' and `purpose_2`='sales' union distinct select distinct(`cust_3`) from `daily_visit_expenses` where user='sanjay' and `purpose_3`='sales'; 	0.387914065692966
11205227	11720	finding distinct elements in a column without using keyword distinct in sql	select v1 from ztable group by v1         ; 	0.00137957674014195
11207813	2132	different conditions in one select statement	select vehicule,        (select count(*) from tablename t1 where t1.vehicule = t.vehicule and date between @monday and @sunday) as 'weekly',        (select count(*) from tablename t1 where t1.vehicule = t.vehicule and date >= @januaryfirst) as 'annual' from tablename t 	0.0152887357454058
11210621	17983	oracle sql return count(*) column along side of regular column?	select username,count(*) from table where username='username' group by username 	0.00185674762786191
11213235	27634	sql select multiple rows into one displayed row	select      maintbl.mkey1,     maintbl.mkey2,     tcd.stat as sdata11,     tcr.stat as sdata12 from maintbl left join(     select * from supptbl where sdata1 <> 22 ) tcd on maintbl.mkey1=tcd.skey1 and maintbl.mkey2=tcd.skey2 left join(     select * from supptbl where sdata1 = 22 ) tcr on maintbl.mkey1=tcr.skey1 and maintbl.mkey2=tcr.skey2 	0
11213325	40731	query to select data from db based on a particular day and count how many rows are there?	select  * from    yourtable where   date_sub(curdate(), interval 1 day) < datecolumn         and datecolumn < curdate() 	0
11213793	25174	how can i join two tables such that all rows of one are duplicated for all rows of another?	select * from t1 cross join j2 	0
11213862	20761	joining multiple tables and getting multiple attributes from one of them	select * from courses  inner join courserevisions on courserevisions.pelid = courses.pelid inner join coursegroups on coursegroups.coursegroupid = courses.coursegroupid inner join [dbo].[opg_employees] empupdatedby on empupdatedby.employeeid = courserevisions.updatedby inner join [dbo].[opg_employees] empapprovedby on empapprovedby.employeeid = courserevisions.approvedby inner join [dbo].[opg_employees] emprequestedby on emprequestedby.employeeid = courserevisions.requestedby 	0
11214963	34121	show the percentage of the answer choices among all users	select  questionnr ,       100.0 * count(case when answer in (1,2) then 1 end) / count(*) as onetwo ,       100.0 * count(case when answer in (3,4,5) then 1 end) / count(*) as threefourfive from    yourtable group by         questionnr 	0
11218257	10634	postgresql reusing computation result in select query	select foo.c from (     select (a+b) as c from table ) as foo where foo.c < 5  and (foo.c*foo.c+t) > 100 	0.763532911363169
11219010	26470	sql sorting with two joined tables	select p.id, p.name, max(a.date_answered) from people p left join answer_sheets a on p.id = a.personid group by p.id, p.name order by max(date_answered) asc 	0.0200875109534524
11219458	24768	search in mysql replacing space with null values	select * from tablename where replace(columnname,' ','') = '0431248892' 	0.209265182458499
11219469	36416	user ranking query	select    id,rank, name,point  from (     select id,         name,         point,           @rank := @rank + 1 as rank             from (       select * from tbla order by point desc) as a,      (select @rank := 0) as vars       ) t  where id=1 	0.298209582033648
11221183	26115	sql server 2008 compare two different database tables for column name, data type and length	select       t.[name] as [table_name], ac.[name] as [column_name],           ty.[name] as system_data_type from    [master].sys.[tables] as t       inner join [master].sys.[all_columns] ac on t.[object_id] = ac.[object_id]      inner join [master].sys.[types] ty on ac.[system_type_id] = ty.[system_type_id] except select       t.[name] as [table_name], ac.[name] as [column_name],           ty.[name] as system_data_type from    test.sys.[tables] as t       inner join test.sys.[all_columns] ac on t.[object_id] = ac.[object_id]      inner join test.sys.[types] ty on ac.[system_type_id] = ty.[system_type_id] 	0
11223249	16112	sql select two tables which have relationship with one another table	select players.playername,         player.playernumber,         l1.location,         partners.partnername,         partners.partnernumber,         l2.location  from   registration r         inner join players                 on players.id = r.playerid         inner join partners                 on partners.id = r.partnerid         inner join locations l1                 on players.locationid = l1.id         inner join locations l2                 on partners.locationid = l2.id 	0
11223381	19970	mysql - merging table rows (group by won't work)	select u.firstname, u.lastname, il.invid, il.name, if(sum(il.name = 'conference dinner') > 0,     'diner', '') as 'conference_dinner', if(sum(il.name in ('regular conference fee',                    'conference fee for phd. students')) > 0,     'conference', '') as 'conference', if(sum(il.name = 'pre-conference fee') > 0,     'pre-conference', '') as 'pre_conference' from invoice_line il, events_tickets et, users u where il.invid = et.invid and et.userid = u.id group by u.id 	0.236333393735408
11223630	5549	temporary table from stored procedure result in sql server	select  * into    #temp from    openquery(servername, 'exec pr_storprocname') 	0.112459372789376
11224529	6734	oracle sql - find special non numeric characters in field	select *   from <table>  where regexp_like(<column>, '[^[:digit:]]'); 	0.0309810305568778
11224687	23759	returning multiple lowest value rows	select top 1 with ties code, level from table order by level 	0.000704136183084192
11224954	39261	transposing a key value pair sql table	select   bookid, price, isbn, pages from (   select bookid, key, value from yourtable )   as sourcetable pivot (   sum(value) for key in (price, isbn, pages) )   as pivottable order by   bookid 	0.000833373253572193
11225082	20842	select rows from a table joining only one row of another table	select h.name, p.filename from home h left join photos p on (h.id = p.homeid and p.splash = 1) 	0
11226018	4956	sql server - how can i select date-hour from a date-time field	select convert(varchar(10),date_field,120) + ':'+ convert(varchar(2), datepart(hour,date_field)) 	0.00730978327581154
11226441	25538	postgresql selecting with limit equal values?	select story_id,        site_id  from (    select story_id,           site_id,           row_number() over (partition by site_id order by story_id desc) as rn    from the_table ) t where rn <= 2 order by story_id desc limit 30 	0.0120626375758523
11228432	25608	sql query: select the last record where a value went below a threshold	select tablename.* from tablename inner join  (     select tablename.item, min(tablename.[date]) as mindate                  from tablename         inner join (                         select                               item,                               max([date]) lastoverdate                          from tablename                          where val>@const                          group by item                                ) lastover         on tablename.item = lastover.item         and tablename.[date]> lastoverdate     group by tablename.item ) below     on tablename.item = below.item     and tablename.date = below.mindate 	0
11228965	35803	how to apply group_concat in mysql query	select   group_concat(t.week_no) as weeks,   group_concat(t.death_count) as deathcounts from (select     week(cpd.added_date) as week_no,     count(cpd.result) as death_count       from cron_players_data cpd       where cpd.player_id = 81       and cpd.result = 2       and cpd.status = 1       group by week(cpd.added_date)) as t 	0.797687399896088
11229046	3596	how do i filter an sql query that joins two tables, where an item is associated with too many items it is joined to?	select `row_id` from `a` join `b` on (`b`.`column2` = `a`.`column1`) group by `a`.`row_id` having count(*) > 100 	0.00289411398695
11229236	4283	how can i ensure a null is assigned to a variable when using max in oracle?	select table_a.* from  (     select         sessiondate,          max(case when vernumber is null then 'a' else vernumber end) as ver     from table_a     group by sessiondate ) td inner join table_a  on nvl(table_a.vernumber, 'a') = td.ver  and table_a.sessiondate = td.sessiondate 	0.210224752783851
11229316	7161	selecting the 2nd row in sql	select     clientusername, desthost, count(desthost) counts   from      #proxylog_record   where     clientusername = (             ;with cte as          (             select row_number() over (order by clientusername) as rn, *              from #proxylog_count_2         )          select clientusername from cte where rn=2         ) group by      clientusername, desthost  order by      counts desc 	0.000410212897561019
11229466	3462	is today between two (datetime) columns? (empty or all zeroes count as unbound upper/lower limit)	select * from your_table where product_id = 1 and (    (curdate() between start_date and end_date)     or (curdate() >= start_date and end_date is null)     or (curdate() <= end_date and start_date is null)    or (start_date is null and end_date is null) ) 	4.8161696879751e-05
11229794	40095	restrict rows based on a join table, using a count	select e.employeeid, v.maxvacationdays from employees e          inner join vacations v on (v.employeeid = e.employeeid) where e.isactive = true group by e.employeeid, v.maxvacationdays having count(v.employeeid) > v.maxvacationdays 	0.000313309194988856
11230725	10195	merge data in two row into one	select servername, country, contact = stuff((select '; '      + ic.contact from dbo.customer as ic   where ic.servername = c.servername and ic.country = c.country   for xml path(''), type).value('.','nvarchar(max)'), 1, 2, '') from dbo.customer as c group by servername, country order by servername; 	0
11230947	12066	most recent rows at least 1 hour apart in mysql	select * from (   select * from mytable    where `date`<date_sub(now(), interval 2 hour)    order by date desc limit 1 ) union select * from (   select * from mytable    where `date`<date_sub(now(), interval 1 hour)    order by date desc limit 1 ) union select * from (   select * from mytable    order by date desc limit 1 ) order by `date`asc 	0
11231250	10637	sql server 2008 - set a value when the column is null	select     name ,   dob ,   coalesce(address1, 'na') ,   coalesce(address2, 'na') ,   coalesce(city, 'na') ,   coalesce(state, 'na') ,   coalesce(zip, 'na') from users 	0.0653023611503934
11232153	3849	sql query to group by and concat rows	select doc, code, sum(qty), concatrelated("[next]","tablename",,,"-") as [next] from tablename group by doc, code 	0.132733639361371
11232408	23599	query to get number of cell's questionn , a specific user has got	select count(*) from question-cell where questionid in (select questionid from  user-question where userid = 3 and competitionid = 4) 	0
11232877	38895	oracle timestamp error	select to_timestamp(trunc(state_date) || ' ' || substr(state_time,1,12),'dd-mon-yyyy hh24:mi:ss:ff3')  from state_log 	0.752305630446384
11233241	40840	pulling info from the same table in different orders and quantities using mysql	select * from (select * from (select date, count, (@s := @s + c) as run_total  from (select d1.date, count(d1.person_id) as c, @s := 0 from table d1 group by month(d1.date) order by d1.date) as t1) tmp order by `date` desc limit 4) tmp2 order by `date` asc 	0
11234155	21646	is it possible to return multiple cells into a single cell from a php/mysql query?	select id,group_concat(product) product,description from (     select kb.kbarticleid as id,     kbc.title as product,     kb.subject as description,      kbd.contentstext as contents      from swkbarticles kb      inner join swkbarticledata kbd on kb.kbarticleid = kbd.kbarticleid     inner join swkbarticlelinks kbl on kb.kbarticleid = kbl.kbarticleid     inner join swkbcategories kbc on kbl.linktypeid = kbc.kbcategoryid ) a group by id,description; 	5.11713940435938e-05
11234257	27605	combine data from two tables with one taking precedence	select courseid, systemcomplete, usercomplete from usercompletion where userid = 1 union select courseid, null, null from coursestogroup where groupid = 1 and courseid not in      (select courseid from usercompletion      where userid = 1) 	0.00038732393666789
11237059	8514	don't want to sort but want null values last	select id, date, value from mytable order by id, (case when value is null then 1 else 0 end), date 	7.56816272993833e-05
11237209	8730	how to get foreign key used tablenames	select student_table.studentid,student_table.studentname  from student_table  left join roll_table on student_table.studentid = roll_table.studentid  left join address_table on student_table.studentid = address_table.studentid  left join contact_table on student_table.studentid = contact_table.studentid 	0.00129063282161154
11237712	992	mysql store checksum of tables in another table	select table_name,checksum from information_schema.tables where table_schema = 'test' and engine='myisam'        and checksum is not null; 	0.00346652545642756
11240009	37904	fetch company with all deactive jobs	select  * from    tbl_company_info c where   not exists         (         select  *         from    tbl_posting_job_info j         where   j.company_id = c.company_id                 and j.status = 'active'         ) 	0.00395651784048762
11240357	27729	sql - count into multiple columns	select `num`,     sum(type = 1) as `1`,      sum(type = 2) as `2`,      sum(type = 3) as `3` from `your_table` group by `num` 	0.00441904894060022
11241952	8621	mysql combine select with sum from other table	select @p:=@p+1 as position, t.* from (   select   user.user_id,            user.user_name,            ifnull(sum(score.score_points),0) as total_points   from     user left join score on user.user_id = score.score_user_id   group by user.user_id   order by total_points desc ) as t join (select @p:=0) as initialisation 	0.000317388095856533
11243224	38741	mysql query for merging two tables to get a single result	select t1.id as 'article id', t1.title as 'article title',  count( t2.tag_id ) as 'tags',  group_concat( t2.tag_id order by t2.tag_id asc) as `tag ids` from table1 t1 join table2 t2 on ( t1.id = t2.id ) group by t1.id; 	7.73794281488066e-05
11243561	12298	sql multiple select count statements in one query	select a, b, c from (select count(cars) as a from tablecars) a cross join (select count(boats) as b from tableboats) b cross join (select count(trees) as c from tabletrees) c 	0.0866192785652865
11245939	6171	how to make a query where some rows are counted multiple times?	select `color`, (count(*) + rb.`cnt`) as `count` from gems,      (select count(*) as `cnt` from gems where color='rainbow') as rb group by `color` having `color`<>'rainbow' 	0.000634393384911538
11246833	18374	merge 3 times 2 columns at a time into one in only one command	select concat(name1, ', ', surname1) as name1, concat(name2, ', ', surname2) as name2, concat(name3, ', ', surname3) as name3 from table; 	0
11247160	7373	get complete content of two web database tables	select table1.iticketname from table1 union all  select table2.iticketname from table2 	0.00234144759447913
11247425	37548	trying to group by a substring()	select  m.cabot_source,    case substring(m.cabot_source,6,1)     when 'c' then 'coregusernamelc'     when 'p' then 'ppc'     when 'o' then 'organic'     when 's' then 'ad swap'     when 'i' then 'internal'     else 'unknown'    end as source_type from members_ m  where m.cabot_source != ''  group by    m.cabot_source,    case substring(m.cabot_source,6,1)     when 'c' then 'coregusernamelc'     when 'p' then 'ppc'     when 'o' then 'organic'     when 's' then 'ad swap'     when 'i' then 'internal'     else 'unknown'    end 	0.307900302817752
11247455	5585	multiple sql queries to single query using inner join	select i.*, p.* from messaggi i inner join messagemap p on i.messageid = p.messageid where i.messageid = ? and p.userid = ? and p.tipoid = ? 	0.780863449470822
11250358	33633	sql - dynamically generated insert or select statement based on some condition	select (case when     date_created >= trunc(sysdate,'q')                    and date_created < trunc(add_months(sysdate,3),'q')              then name || '-' || invoice_number              else name          end),        date_created,         invoice_number   from customer; 	0.025144152304882
11250787	2552	distinct date in where clause possible?	select sum(amountsold), date  from tablea group by date 	0.450108708194314
11252750	23014	how to join factors from different rows under multiple loops	select mytable.*, x.price as prev_price from mytable left join     (select * from mytable) as x on     mytable.id = x.id     and mytable.brand = x.brand     and mytable.name = x.name     and mytable.time = x.time + 1 	0.00101158898710929
11255059	38478	getting max of multiple avg grouped by another column	select  playerid, name, max(score)avg, gamescount, leaguename, season from( select  playerid, player.name as name, player.gender as gender, round(avg(score),2) as score, count(score) as gamescount, leaguename, season     from  scores join players as player using(playerid)     where score > -1 and bowlout = 'no' and season = '2011-2012'     group by playerid, leaguename, season     having gamescount >= 50     order by score ) as league_avg where gender = 'male' group by playerid order by avg desc limit 0,50; 	9.48291648427411e-05
11255367	26602	sql select statement - the thing i am querying for has a single quotation mark	select * from department where departmentname = 'controller''s office' 	0.356754415520047
11258850	23761	how to return rows only if there is more than one result	select *   from (select col1,                col2,                count(*) over() cnt           from your_table          where <conditions> )  where cnt > 1 	7.49488754015421e-05
11258999	9496	how to return distinct records in case insensitive oracle db?	select distinct(upper(r.name)), r.expiry_date, r.category from realtime_exempt r where r.submitted_by='admin' 	0.279311850829547
11260943	27180	pictures in a table	select * from fotos, tekst where fotos.id=tekst.id order by tekst.datum desc limit 30 	0.0792255054713207
11261060	9803	sql query to group results into hourly buckets	select   `name`,          sum(if(hour(timediff(curtime(), `time`)) <= 1, `count`, 0)) as `last-1`,          sum(if(hour(timediff(curtime(), `time`)) <= 3, `count`, 0)) as `last-3`,          sum(if(hour(timediff(curtime(), `time`)) <= 6, `count`, 0)) as `last-6` from     `table` group by `name` 	0.0238163465175592
11261194	13252	count total results found based on country	select  country.name country, count(*) from mydata.hotel      as hotel join mydata.city       as city     on hotel.city = city.id join mydata.region     as region   on region.id = city.region join mydata.country    as country  on country.id = region.country where hotel.tel not like '' and accos.tel not like '+%' group by country 	0
11262636	39021	how do i get the records from the left side of a join that do not exist in the joined table?	select distinct u.id,     u.lastname from user u left join context ct on ct.userid = u.id where ct.userid is null 	0
11263171	18413	how can i use top and conditionally ignore a union all?	select top (@top) ..., ft.[rank] * p.popularity into #foo ... <ft query>; if @@rowcount < @top   insert #foo select top (@top) ..., p.popularity from <like query>; select top (@top) ... from #foo order by popularity desc; 	0.0188021456258499
11263347	419	sql group & sort by two columns	select entries.facebook_id, min(entries.score) as score, min(entries.time) as time from entries     inner join (         select facebook_id, min(score) as score         from entries         group by facebook_id) highscores     on highscores.facebook_id = entries.facebook_id     and entries.score = highscores.score group by entries.facebook_id order by min(entries.score) asc, min(entries.time) asc 	0.00505273463139494
11264264	26053	select row belonging to multiple categories	select * from entity e where exists (select * from category c where c.entry_id=e.entry_id and c.cat_id=233)   and exists (select * from category c where c.entry_id=e.entry_id and c.cat_id=234) 	0.00129177481866042
11264481	23682	t-sql, select into	select 'a' as 'label' into #tmp union select 'b' 	0.0831672571583371
11264955	4633	searching database in php from single column to all	select * from test where concat(cola,colb,colc,cold) like '%keyword%' 	0.000152959296118908
11265610	22061	using between mysql function ignoring year	select * from   users where  timestampdiff(year, birthday, current_date + interval 15 day)      > timestampdiff(year, birthday, current_date) 	0.0705587831119755
11265831	4835	tsql group by clause with sum and multiple columns	select top 1000       m1.date       ,min(m1.time) as 10mintime       ,(select price from dbo.mydata m2         where m2.date = m1.date         and datepart(hour, m2.time) = datepart(hours, m1.time)         and datepart(minute, m2.time) = datepart(minute, m2.time) %10)       ,sum(items) as sumitems   from dbo.mydata m1   group by [date],datepart(hour, [time]),(datepart(minute, time))%10   order by [date] desc, 10mintime desc 	0.178250962170304
11266052	6104	mysql count with multiples groups	select u.char_id, sum(u.kills) as kills, sum(u.killed) as deaths, sum(u.kills)- sum(u.killed) as points from ( select killer_cid as char_id, count(killer_cid) as kills, 0 as killed from kill_log where `time` >= (now() - interval 30 day) group by killer_cid order by count(killer_cid) desc union select killed_cid as char_id,0 as kills, count(killer_cid) as killed from kill_log where `time` >= (now() - interval 30 day) group by killed_cid order by count(killer_cid) desc ) as u group by u.char_id order by sum(u.kills)- sum(u.killed) desc 	0.030030079060573
11267791	25234	separate count for multiple items within a day mysql	select sum(if(statuses = st1,1,0)) as st1,  sum(if(statuses = st2,1,0)) as st2,  sum(if(statuses = st3,1,0)) as st3      from table_dates      group by dates; 	0
11268018	23789	sql : how to calculate limited rows and reset the counter	select   * from   table inner join (   select     min(g.id)   as first_id,     max(g.id)   as last_id,     count(*)    as group_size   from     table as p   inner join     table as g       on g.id > coalesce(                   (select max(id) from table where id < p.id and resolution = 'pass'),                   ''                 )      and g.id <= p.id   where     p.resolution = 'pass'   group by     p.id )   as groups     on  table.id >= groups.first_id     and table.id <= groups.last_id 	0.000486221909977216
11268181	12212	lastest number of string with some format	select code from table1 where code like "bok%" order by cast(substring(code from 5) as signed) desc limit 1 	0.00128229184626428
11268403	38748	select columns of a view	select * from information_schema.columns where table_name = 'view_name' 	0.00739948958398775
11268774	9214	mysql sorting and grouping on last one	select t2.* from (select max(id) as id,tn from my_table group by tn) as t1 left join my_table as t2 using(id) 	0.000356788874516029
11269197	16282	how to find primary keys for all foreign keys in a db using information_schema	select  ccu1.table_name as fktable, ccu1.column_name as fkcolumn,          ccu2.table_name as referencedtable, ccu2.column_name as referencedcolumn from    information_schema.constraint_column_usage ccu1,         information_schema.constraint_column_usage ccu2,         information_schema.referential_constraints rc where   rc.constraint_name = ccu1.constraint_name and     rc.unique_constraint_name = ccu2.constraint_name 	0
11269444	35788	how in mysql do i get latest records by date with distinct column(s) and common key?	select   mytable.* from     mytable natural join (   select   size, color, max(created_date) as created_date   from     mytable   group by size, color ) as t 	0
11269655	5608	combine multiple coloums values in to single value in sql select statement	select * from your_table where concat(column1, ' ', column2, ' ', column3) like '%this is good%' 	0.00073727536885659
11270061	26252	orderby through 2 different tables	select * from     addons a , addons_count c  where    c.addon_id = a.addon_id and    a.addon_size = 'small' order by    c.addon_count limit     {$startpoint_small} , {$limit} 	0.0102368539056184
11270800	22784	query to get max donation from each person	select   * from   donations d where   donation=(select max(donation) from donations where fullname=d.fullname group by fullname) 	0
11271234	30629	mysql query with distinct and max	select id, `from`, `to` from yourtable where id in (     select max(id)     from yourtable     where `from` = 'joe' or `to` = 'joe'     group by least(`from`, `to`), greatest(`from`, `to`) ) order by id desc 	0.22556381707426
11271804	2308	how do i run a select query with count()?	select au.*,p.* from account_users au inner join posts p on p.account_users.id = au.id group by p.post_id having count(*) > 5 	0.407294743362348
11272544	10643	finding maximum data from multiple rows	select id, max(field1), max(field2) from mytable group by id; 	0
11273673	5300	sql percentage of rows comparing two dates	select 'yes' as sla,  (sum(case when targetfinish > actualfinish  then 1.0 else 0.0 end) / count(*) ) * 100 as percentage  from incident  where targetfinish is not null and actualfinish is not null union  select 'no' as sla,  (sum(case when targetfinish <= actualfinish  then 1.0 else 0.0 end) / count(*) ) * 100 as percentage  from incident where targetfinish is not null and actualfinish is not null 	0
11274458	19693	mysql join to pull up latest posts by comparing post dates and comments dates	select c.*, max(com.date_posted) as last_post from community c left outer join community_comments com on com.community_id = c.id group by c.id order by max(com.date_posted) desc limit 5 	0
11275290	25872	inner join depending on rows	select   * from   posts p inner join meta_keys mk1 on p.post_id = mk1.post_id inner join meta_keys mk2 on p.post_id = mk2.post_id where   mk1.meta_key = 'guadalajara' and   mk2.meta_key = 'zapopan' ; 	0.0148012526540478
11276606	19096	sql - check for duplicate values	select entity_id, count(offer_id) as count from   paid_offers group by entity_id 	0.0050685286449837
11276866	9747	combining 2 queries into 1	select   author.author_id,   author.name,   count(distinct more_tracks.lyrics_id) as total from track inner join lyrics_author using (lyrics_id) inner join author using (author_id) left join lyrics_author as more_tracks using (author_id) where track.track_id = $trackid group by author.author_id 	0.00750836008717021
11277443	17384	mysql join more that 2 tables	select friends.friendid, users.firstname, users.lastname, comments.comment, comments.commentdate   from users   join friends on friends.friendid = users.id   join comments on comments.commenter = friends.friendid   where friends.userid = '12' and comments.commenter != '12' 	0.0335935195381793
11277502	24900	hiding new column (alias column)	select id, col2, col3, col4 from yourtable group by col2, col3 	0.0434680150864801
11279685	20499	mathematics on a special column in mysql	select numcol, ((numcol / 11 ) * 0.5 - numcol) as calccol   from special_table; 	0.154739697507379
11279701	35334	django model group by more than 2 elements	select rating, count(rating) as rc, count(distinct userid) from rating_tbl group by rating order by rc desc; 	0.0300216497385904
11283416	6206	query for multiple values to an id separated with comma from the database	select  id, group_concat(code separator ',') from yourtable group by id 	0
11287909	14957	mysql - multiple union	select   b.id,   b.name,   b.middle_id,   m.top_id,   m.name,   t.name from bottom as b   left join (select  id,`name`, top_id  from middle) as m  on m.id = b.middle_id   left join (select  id,`name`from top) as t   on t.id = m.top_id 	0.347920140381919
11291885	11578	jquery autocomplete getting id cha	select: function (event, ui) {         var v = ui.item.value;         $('#messageto').html("something here" + v);         $('#hidden1').html("something else here" + v);         this.value = v;          return false;     } 	0.64890791863984
11292115	6448	how to count the values in this type of query?	select count(*) from table where id in (2,3) 	0.033038037438255
11293357	28090	list with percentage	select t.name,         cast((count(a.id) / count(q.id)) * 100 as unsigned) as percentage from tests t left outer  join questions q on q.test_id = t.id left outer  join answers a on a.question_id = q.id group by t.name 	0.034789009208239
11295843	26839	select distinct for some columns, and the minimum value for others (what is `group by`?)	select myname, min(mydatetime) from tablea group by myname; 	0.000144539391232042
11296636	23132	alphabetizing results after order by sort	select *      from hospital      where status = 1      order by case hospitaltype                   when 'hos' then 1                   when 'nh' then 2                   else 3                end,                hospitalshortname 	0.165520324579553
11296852	21798	trouble aggregating rows with sql statement	select contractdate,       max(case when vendor = 'airdat' then vendor_average end) as airdat,        max(case when vendor = 'cwg' then vendor_average end) as cwg   from (   select [contractdate] , vendor, (sum(wf.temppop) / sum(wf.population)) as vendor_average   from [ecpdb].[dbo].[weather.forecast] as wf    inner join ecpdb.[lookup].[newweatherstation] as ws      on wf.[station_id] = ws.[station id]   inner join ecpdb.[lookup].[countynew] as c      on ws.[county fips] = c.[county fips]   where tradedate = '7/2/2012' and [bentek cell] = 'northeast'  group by contractdate, vendor ) as subquery      group by contractdate 	0.70488919709293
11299886	2523	sql get multiple custom post meta values	select post_id from `database_table` where `meta_value` regexp '<date[1|2|3]>[0-9]+<\/date[1|2|3]>' 	0.00183965544348989
11301083	19344	sql : count the number of occurences occuring on output column and calculate some percentage based on the occurences	select     a.id,     a.resolution,     b.* from      table1 a cross join     (         select             concat(sum(aa.resolution = 'pass'), '/', count(*)) as attempts,             concat((sum(aa.resolution = 'pass') / count(*)) * 100, '%') as percent_attempts,             concat(sum(bb.mindate is not null and resolution = 'pass'), '/', sum(resolution = 'pass')) as first_attempt          from             table1 aa         left join              (                 select                      min(`date`) as mindate                  from                      table1             ) bb on aa.`date` = bb.mindate     ) b 	0
11301861	38936	self-join ... new synthetic columns for values in existing column	select uuid,     case when u.valuea>0 then 'ok' else 'missing' end as valuea,    case when u.valueb>0 then 'ok' else 'missing' end as valueb from   (select t.uuid,       (select count(*) from mytable as m where t.uuid=m.userid and valuefield='valuea') as valuea,       (select count(*) from mytable as m where t.uuid=m.userid and valuefield='valueb') as valueb   from (select distinct uuid from mytable) as t   group by uuid) as u order by uuid 	0.000383113712940796
11302633	13528	how can i get the entity types' name in an esql query	select it.[id] as id, it.[entitytype].[name] + " - " + it.[name] as name from oftype([auditedobject], [datumobject]) as it 	0.0579608116983445
11303701	36700	select users and groups for specific account	select  users.id, users.name, groups.id, groups.name     from users join groups on users.groupid= groups.id where groups.accountid=1 	0.000468471414349305
11307829	22268	mysql join using 4 tables	select `a`.`id`,`a`.`page` xpage,`a`.`action`, `b`.`header` xheader, `b`.`page_id`, `c`.`content` xcontent,`b`.`page_id`, `d`.`footer` xfooter,`d`.`page_id` from `a` join `header` b on `a`.`id`=`b`.`page_id` join `content` c on `a`.`id`=`c`.`page_id` and `a`.`id`=`d`.`page_id` join `footer` d on `a`.`id`=`d`.`page_id` where `a`.`page`='main' 	0.304177842485294
11310074	12501	display row data as column in sqlite	select distinct name,     (select sum([count]) from test tst where tst.name = test.name) as count,     (select sum([count]) from test tst where tst.name = test.name and type='ca') as ca,     (select sum([count]) from test tst where tst.name = test.name and type='bt') as bt     from test 	0.000279885302147348
11311319	13472	can i get comma separated values from sub query? if not, how to get this done?	select country, allstates =      stuff((select ', ' + state            from country_state_mapping b             where b.country = a.country            for xml path('')), 1, 2, '') from country_state_mapping a group by country 	0.000728844142225291
11313749	896	conditional mysql column	select i.item_code, i.item_name,      case when q.selltype_name = 'unit' then i.item_price else 0 end as unit,     case when q.selltype_name = 'box' then i.item_price else 0 end as box,     case when q.selltype_name = 'pound' then i.item_price else 0 end as pound,     case when q.selltype_name = 'gallon' then i.item_price else 0 end as gallon from qa_items i inner join qa_selltypes q on i.selltype_code = q.selltype_code 	0.41372097799241
11315042	29121	sql to reference another column's value	select q.cola as "next repricing", q.cola as "balloon date" from (select acct, name, address, case when pterm||' '||ptermc = '0' then date(digits(matdt7))  when pterm||' '||ptermc = '1 d' then curdate()  when pterm||' '||ptermc = '1 m' then date(digits(prevd7))+30 day when pterm||' '||ptermc = '3 m' then date(digits(prevd7))+90 day when pterm||' '||ptermc = '6 m' then date(digits(prevd7))+180 day when pterm||' '||ptermc = '12 m' then date(digits(prevd7))+365 day else null end as cola, ...) as q 	0.000537276516889306
11316982	28089	sql change result by case	select name,     country,     case normal_state         when 1 then 'open'         when 0 then 'closed'         else 'unknown'     end as normal_state,     case current_state         when 1 then 'open'         when 0 then 'closed'         else 'unknown'     end as current_state from soms_table where name like 'ar%'     and normal_state <> current_state order by country 	0.686803591242975
11317529	20893	populating column from another column	select 'x' + right('000'+ convert(varchar,num),4) from numbers 	0.000415215039010105
11317551	1492	joining tables based on values from other tables	select   g.pgid, g.gname,   gallerycategoryname = case c.pcatname when '0' then n.categoryname else c.pcatname end from tblphotogalleries g inner join tblphotogfallerycats c on c.pcatid = g.fk_pcatid left join tblnewscategories n on n.categoryod = c.connectednewscatid 	0
11318792	26798	sql query to return nil for dates not present in the table	select dt,count(id) from  ref_dt ref  left outer join my_table mt  on ref.dt=my_table.date group by ref.dt; 	0.00417916156461775
11319611	1193	filtering query results with another query results	select settbl.setid, grouptbl.group_id, resultstbl.name, resultstbl.age, resultstbl.address, grouptbl.myid from resultstbl inner join grouptbl         on (resultstbl.myid = grouptbl.myid or resultstbl.age between grouptbl.agefrom and grouptbl.ageto)      inner join settbl         on grouptbl.group_id = settbl.group_id 	0.151867007823471
11319762	5990	performing a sum over nested foreign key relationships	select   employee.name, sum(emailstats.curse_words) total_curses from     email   join emailstats on emailstats.email = email.id   join employee   on employee.id      = email.from where    email.to = 5 group by employee.id order by total_curses desc 	0.0303858622615601
11320039	6613	mysql get top average entries	select courses.* from   courses natural join (   select   courseid, avg(rating) avg_rating   from     ratings   group by courseid   order by avg_rating desc   limit    3 ) t 	0
11321075	17416	doing a second search automatically	select * from banlistip where lastip = (select distinct lastip from banlistip where name like '%$iplookup%' or lastip like '%$iplookup%') 	0.0869813439191527
11321132	37345	join two tables using hiveql	select count(buyer_id), buyer_id  from table1 dw  left outer join table2 dps on (dw.buyer_id = dps.user_id)  where dps.user_id is null group by buyer_id; 	0.123599181661829
11321777	9132	python sqlite adding a row	select last_insert_rowid() 	0.0775447775760732
11322954	28762	sql query for selecting sum of multiple column based on other column	select a as p, sum(b) as q from x group by a 	0
11323024	30893	how to convert columns to rows in sql server	select id, page, line, city, value from sourcetable unpivot    (value for city in        (c01, c02, c03) )as unpvt; 	0.00298819897327593
11323379	28696	fetch mysql results, then randomize order of results, then display one differently from the rest	select * from `table` order by rand() limit 6; 	0
11323896	4081	how to increment the datetime value with the increment value as 30 minutes in oracle?	select to_date('2012-01-01', 'yyyy-mm-dd') + (level-1)/48 as datetime    from dual connect by level <= 48 	0
11324647	36334	is there a faster way to get information from multiple tables?	select   min(t1.startdate) as start,   max(t1.enddate) as end,   t2.start,   t2.end,   t3.start,   t3.end   from table1 as t1   left join (select            min(t2.startdate) as start,            max(t2.enddate) as end          from table1) as t2     on t1.id = t2.id   left join (select            min(t3.startdate) as start,            max(t3.enddate) as end          from table1) as t3     on t1.id = t3.id   where t1.projectid = 1 	0.00829552789514691
11325191	10585	select top and order from two tables	select top 10  count(d.orderid) as total, d.productid, p.title from orderdetails d  inner join products p on d.productid = p.productid where d.sellerid = 'xxx'  group by d.productid, p.title order by count(d.orderid) desc 	0.00053419299435407
11325556	1840	how do i find the maximum database space and the used database space in sql azure?	select sum(reserved_page_count)*8.0/1024 from sys.dm_db_partition_stats; 	0.000894602016993344
11329324	7650	sql get rows containing two rows from bridge table	select pg1.game_id from player_game pg1 inner join player_game pg2 on pg1.game_id = pg2.game_id where pg1.player_id = 1234 and pg2.player_id = 9876 group by pg1.game_id  	0
11330175	19489	tricky sql query involving consecutive values	select   name, surname, min(date) date_since_fail from     results natural left join (   select   name, surname, max(date) lastpass   from     results   where    result = 'pass'   group by name, surname ) t where    result = 'fail' and date > ifnull(lastpass,0) group by name, surname 	0.379866546743706
11332325	39723	removing duplicates from this sql join	select n1.surname, n2.surname from names n1  join names n2 on n1.name = n2.name where n1.surname >= n2.surname    ; 	0.585005306124706
11333078	23931	sql take just the numeric values from a varchar	select substring(fieldname, patindex('%[0-9]%', fieldname), len(fieldname)) 	0.000218727316864372
11333221	24479	sql query all in one - to avoid number of queries	select sum(if(age >= 40,1,0))               as older40,         sum(if(age >= 50 and age <= 60,1,0)) as between50and60        sum(if(age >= 60 and age <= 70,1,0)) as between60and70        sum(if(age >= 80,1,0))               as over80 from table 	0.00165112828773031
11333863	34514	sql server 2005: order with null values at the end	select * from tablename order by case when ordernum is null then 1 else 0 end, ordernum 	0.0280495031759707
11334258	18236	mysql query order by most occurences	select m.id, m.game_type, m.votes  from mytable as m inner join     (select game_type, count(game_type) as typecount      from mytable      group by game_type      order by count(game_type) desc) as u   on m.game_type=u.game_type order by u.typecount desc, m.game_type, m.votes desc 	0.0185454257998495
11334879	14763	sql subqueries to count on multiple conditions	select name, count(distinct name) as uc, count(*) as tc, sum(if(ret_date is null, 0, 1)) as rc, sum(if(ret_date is not null, 0, 1)) as pc from vb group by name; 	0.326935871344855
11334969	14052	obtain the top users within a time range mysql	select count(*), iduser from register  where date>='$beginningdate' and date<'$enddate' group by iduser order by count(*) desc limit 10 	0
11334971	12208	how do you get the comment count of the post through mysql query?	select     a.title,     count(b.post_id) as 'comment count' from     post a left join     comment b on a.id = b.post_id group by     a.id 	0.000264196992866962
11337319	37837	sql- calculating sum/count with rows of table	select      a.storenumber,     sum(case when a.price < b.price then 1 else 0 end) as wins,     sum(case when a.price > b.price then 1 else 0 end) as losses,     sum(case when a.price = b.price then 1 else 0 end) as ties,     sum(a.price) as store_price_sum,     sum(b.price) as competitor_price_sum from     pricecomparison a inner join     pricecomparison b on          a.itemnumber = b.itemnumber and          a.storenumber <> b.storenumber group by     a.storenumber 	0.00227632848091257
11337981	19793	query to get summary of survey questions answered (distinct column values)	select     (sum(happy_or_sad = 'no') / count(*)) * 100 as percentage_no,     (sum(happy_or_sad = 'yes') / count(*)) * 100 as percentage_yes,     (sum(happy_or_sad = 'sometimes') / count(*)) * 100 as percentage_sometimes, from     survey_result 	0.000217840297912656
11338048	34411	how do i limit this to exclude duplicates? i'm seeing my message twice because i'm friends with more than one person	select p.* from posts p inner join friendships f on (p.username = f.user2 or p.username = f.user1) where f.user1 = '$sessionusername' or f.user2 = '$sessionusername'  group by posts.id order by id desc 	0.597071778140629
11338240	32285	product count from database	select *, count(products_items.productid) as itemcount  from products      left join products_items     using(productid)  group by productid  order by `order` asc, `productid` asc"; 	0.00995738564798995
11338653	28251	how to display sql result like that	select document_name, group_concat(tag separator ', ') from documents group by document_name 	0.0156206302703321
11339166	36013	sql in between. comparing records and ranges (two different tables)	select i.ip  from ip i  where not exists (    select null    from dhcprange d    where i.ip between d.start and d.end) 	0
11340514	39337	to delete and update photo	select @albumid = album, @photoname = photoname from blogphoto where id = @id delete from blogphoto where id = @id update blogalbum set coverphoto = 'noimage.jpg' where albumid = @albumid and photoname = @photoname 	0.146651078862243
11341192	5853	return all the columns in a mysql table in a string format	select group_concat(column_name separator ', ')  from information_schema.columns  where table_name = 'course'  group by table_name 	0
11342173	21826	active record select 15 records order by date with different field value using	select   min(id) as id,           min(text) as text,           group_id,           source_id,           min(created_at) as created_at from     articles where    source_id = @your_parameter_value group by group_id,          source_id order by 5 	0
11342795	17285	three table with value join query base value is first ,secound and third table	select * from user_details d inner join user_type t on t.us_ty_id = d.us_ty_id inner join user_master m on m.usr_ma_id = t.usr_ma_id; 	0
11343846	34580	sql query handling three tables	select  pm.description,         count(pc.code) total,         count(case when ps.value = 'a' then ps.value else null end) statusa,         count(case when ps.value = 'b' then ps.value else null end) statusb from    product_master pm join product_child pc on pm.code = pc.code         join product_status ps on pm.status_code = ps.status_code group by pm.description 	0.788799169658514
11344595	25090	converting dbclob/clob to xml	select    xmlcast (     xmlparse (       document cast (         column1 as blob       )        preserve whitespace     ) as xml   )  from    table1 	0.708567395410776
11344817	25811	limits ocurrence in a select	select * from avi where codavi in (select e.codavi from csa e where e.codeca in (select c.codeca from csa c where  c.codavi = 19) group by e.codavi having count(*) = (select count(*) from csa a where a.codavi  = 19)) 	0.73776497609367
11346809	16468	select only rows where count of rows in other table is greather than 0	select * from products p where exists (select * from products_photos pp where pp.product_id = p.id) 	0
11347363	18818	determine db2 text string length	select * from table where length(fieldname)=10 	0.0990657418097629
11347857	12678	exclude columns from mysql csv export	select field1, field2, field7 from table 	0.000297729756638882
11350518	21138	get detailed field information for a pgsql resultset in php	select * from information_schema.columns  where table_name = 'regions' and column_name = 'capital' 	0.00508079651849164
11351829	31460	sql count within a select	select p.photoid, p.photoname, m.memberid, m.memberfname, count(r.ratingid) as ratingcount from photo p inner join member m on p.memberid = m.memberid left outer join rating r on p.photoid = r.photoid group by p.photoid, p.photoname, m.memberid, m.memberfname 	0.102327488449144
11351907	20756	how to mysql query based on matching column values?	select s.id,s.last,s.first,s.course1,s.course2,s.course3       ,e.id,e.last,e.first,e.course1,e.course2,e.course3   from $startsem1 s   join $endsem1 e on s.id = e.id 	6.78892008997949e-05
11354265	1539	writing a mysql following users query	select   user.user_id,   user.user_name,   he.follower_id as follower_id,   if(me.followed_id,1,0) as metoo from       following as he inner join user    on user.user_id = he.followed_id left  join following as me    on me.follower_id = 1   and me.followed_id = he.followed_id where he.follower_id = 2 	0.555173422975655
11354500	6443	remove duplicates from one column keeping whole rows	select tbla.*    from ( select userid, max(totalpointspend) as maxtotal            from tbla            group by userid ) as dt inner join tbla      on tbla.userid = dt.userid    and tbla.totalpointspend = dt.maxtotal            order by tbla.userid 	0
11355283	16476	how to check if connection alive?	select 1   from dual 	0.236917268489224
11357034	23295	how to check if a table already exists in the database by using mysql?	select table_name from information_schema.tables where table_schema = 'dbname'   and table_name = 'my_tablename'; + | table_name           | + | my_tablename | + 	0.000950725234000412
11359934	6960	how to get all the data from two tables?	select products.*, category.cat_id  from products, category  where products.prod_id = category.prod_id 	0
11360610	17775	ms sql select multiple columns based on the max(id) with distinct	select e.ev_id, e.ev_contactemail, e.ev_cusname from         events as e     inner join         ( select max(ev_id) as ev_id           from tblevents ev             inner join tblcustomers cus                on cus.cus_id = ev.ev_customerid           where cus_isadmin = 'y'             and cus_live = 'y'              and ev_live = 'y'              and ev_enddate >= '20120705t00:00:00'                and ev_contactemail <> ''                          group by ev_contactemail         ) as tmp       on tmp.ev_id = e.ev_id ; 	0.000608188875898936
11360745	15859	counting how many times rows appear in one table in access	select distinct [tbl funktietitels].persoon,             [tbl goedkeuring].goedk1,             [tbl goedkeuring].db_user              (select  count(*)               from  [tbl goedkeuring]               where [tbl goedkeuring].goedk1 = [tbl funktietitels].funktiecode                      and ((([tbl goedkeuring].bevestiging)=false))              ) as aantal   from [tbl goedkeuring]         inner join [tbl funktietitels]             on [tbl goedkeuring].goedk1 = [tbl funktietitels].funktiecode; 	6.86686320632869e-05
11360802	16128	need to generate xml from sql in this following format	select ordernumber as @id, customerid, item from orderheader for xml path('order'), elements, root('orders') 	0.499906454655828
11361073	5713	wrong result in sum()	select cota ,telegestionador ,sum(case when table_name = 'contactados' then work_value else 0 end) as contactados_sum ,sum(case when table_name = 'nc' then work_value else 0 end) as nc_sum ,sum(case when table_name = 'fq' then work_value else 0 end) as fq_sum ,sum(case when table_name = 'qt' then work_value else 0 end) as qt_sum from ( select  cota ,telegestionador ,work_value ,'contactados' as table_name from contactados union all select  cota ,telegestionador ,work_value ,'nc' as table_name from nc union all select  cota ,telegestionador ,work_value ,'fq' as table_name from fq union all select  cota ,telegestionador ,work_value ,'qt' as table_name from qt ) summary group by cota ,telegestionador 	0.685387345458985
11361468	36445	frequency distribution with weighted average	select type     , cast(sum(amount) as decimal(10,5))/(select sum(amount) from t) from t group by type 	0.00316959282042777
11362066	26897	ssrs report showing different record to different user. how can this be implemnetd?	select b.[name] as [name2],b.[salary] as [salary2],b.[grade] as [grade2]  from empolyee a cross join empolyee b where a.grade <= b.grade and a.name like 'jack'  and b.empid not in (select empid from empolyee c   where c.grade = a.grade and c.name <> a.name) 	0.0137925834104053
11362711	17957	putting data from 2 tables into a mysql view	select email, name, appdate from table1 union select s_email as email, s_name as name, s_appdate as appdate from table2 	0.000241232946352917
11363204	8497	match all records	select u.* from dbo.users u join dbo.form f on u.? = f.formid join dbo.formemployment fe on fe.formid = f.formid join dbo.grade g on g.gradeid =  fe.gradeid join dbo.shiftgrade shg on shg.gradeid =g.gradeid join dbo.shift sh on sh.shiftid = shg.shiftid where     sh.shiftid =  and g.gradeid ==  	0.00111680396885167
11363861	24233	how can i combine three select queries, each excluding the results from the previous ones?	select    case when stagecompleted = 1 then 'final'         when startdate < now() then 'active'         else 'inactive'    end,    id from stage 	0
11365309	6776	truncate (using round) has stopped working after changing column data type	select cast(round(sum(price),0,1) as decimal(22,0)) as sumnetprice from transactions 	0.0931267857575303
11365937	1753	get row with max(column)	select x.user, y.col1, y.col2, x.col3 from (   select user, max(col3) as col3   from table   group by user ) x inner join table y on y.user = x.user and y.col3 = x.col3 order by x.user 	0.00344288131074256
11366123	32457	getting unique results in a multi-column search	select apex_item.checkbox(1,gs_users.user_id) checkbox,  "gs_users"."username" as "username",  "gs_users"."first_name" as "first_name",  "gs_users"."last_name" as "last_name",  "gs_users"."admin_flag" as "admin",  "gs_users"."email" as "email",   decode("gs_banned_users"."user_id",null,'unbanned','banned') as status from       "gs_users" "gs_users",      "gs_banned_users" "gs_banned_users" where gs_users.user_id = gs_banned_users.user_id (+); 	0.0285439434420802
11367833	3662	check for mysql ascending field	select t.id - 1 as [missingrank]  from urtable t  left join urtable t2 on t.rank = t2.rank + 1  where t2.id is null 	0.00677853639148411
11368389	8595	collecting two separate column results from mysql query	select counter.process, count( counter.process ) as count,       (select count(errors.process)           from errors         where process=counter.process            and (time between '2012-07-01 00:00:00' and '2012-07-06 23:59:59')) as errors                             from counter where (time between '2012-07-01 00:00:00' and '2012-07-06 23:59:59')                             group by counter.process                             order by count desc 	0.00072812627342521
11369065	31005	relational database query	select a.* from comments a inner join topics b on      a.topic_id = b.id and      b.deleted = '0000-00-00 00:00:00' 	0.468541602361792
11369843	16010	how to select the sum of distinct values in a table using mysql	select state, district, company, count(*) as countzz     from company group by state, district, company 	0.000165895274249731
11371708	8193	mysql finding rows in one table with information from another	select b.title, b.color, b.detail from table1 a inner join table2 b         on a.pic_id = b.pic_id where friend_id = 84589 	0
11372464	23522	how to find doubles with sql?	select cus.customerid,tra.name,count(cus.customerid) as tot        from invoice as inv        join customer as cus on inv.customerid=cus.customerid        join invoiceline inl on inv.invoiceid=inl.invoiceid        join track tra on tra.trackid=inl.trackid        group by cus.customerid,tra.name        having tot > 1 	0.093462004500387
11373239	36672	how to match part of a field with data in another field with query?	select t1.*, t2.name from table1 t1, table2 t2 where t1.id = (right(t2.action, 4)) and t2.action like 'added %' 	7.69127074675353e-05
11373356	37965	how to multiple join tables?	select w_child.*, e_parent.experience from workers as w_child  left join workers as w_parent on (w_parent.id = w_child.worker_parent)  left join experience as e_parent on (w_parent.id = e_parent.worker_id)  where e_parent.worker_id is not null order by e_parent.experience desc 	0.101087409525939
11373549	34553	mysql count query in join	select     m.id,     m.name,     (select  count(f.notified) from friends as f where f.member_id = m.id and f.notified = 1) as numfriends from     member as m  group by     m.id 	0.586799271912032
11374931	33890	sql server: seperate queries return in less than a second but combining those with intersect takes 3 mins	select * from pi_inform with (nolock) where  pk in (select pk from dbo.getinformfulltextpks('"hello"')) and   record_date>dateadd(hour,-48, getdate()) 	0.00139879705504359
11375153	16549	mysql add new column as result	select v2.longitude as something,2*v2.longitude as something2 from points as v2 	0.0105800276645328
11375221	35879	cron to check dates in large mysql database	select something from tbl_name where now() >= date_col; 	0.0462126709234696
11376441	15911	sql counting up records	select c.naam     ,sum((d.prijs+e.prijs+f.prijs)*(a.eind_datum - a.start_datum)) as pricesum from hotel c     inner join kamer b         on b.hotelid = c.hotelid     inner join reservatie a         on a.kamerid = b.kamerid     inner join verblijfsformule d         on a.verblijfsformuleid = d.verblijfsformuleid     inner join verblijfsperiode e         on a.verblijfsperiodeid = e.verblijfsperiodeid     inner join kamertype f         on b.kamertypeid = f.kamertypeid  group by c.naam 	0.0182014688949972
11377503	32598	sql joining main table with two tables returning number of records - maximum of other two tables?	select     t1.id   , t2.service   , t3.device from         t1     left join             ( select                   row_number() over (partition by id order by service) as rn                 , id                 , service               from                   t2             ) as t2         full join              ( select                   row_number() over (partition by id order by device) as rn                 , id                 , device               from                   t3             ) as t3           on  t3.id = t2.id           and t3.rn = t2.rn       on coalesce(t2.id, t3.id) = t1.id ; 	0
11379171	24676	sql queries using distinct sum and subtract function	select transactionfile, sum(case when kindoftransaction = 'debit' then -1 else 1 end * transactionamount) from financial where accountnumber = 4568643 group by transactionfile 	0.188919084757644
11379341	33402	return set from single result as multiple rows	select      a.material,      a.states from (     select material, substring_index(states,',',1) as states     from settbl     union     select material, substring_index(substring_index(states,',',-3),',',1) as states     from settbl     union     select material, substring_index(substring_index(states,',',-2),',',1) as states     from settbl     union     select material, substring_index(states,',',-1) as states     from settbl ) a order by     a.material 	0.000105035221386903
11381403	35999	how to display a list sqlite database tables, except table sqlite_sequence?	select name from sqlite_master where type = 'table' and name <> 'sqlite_sequence' 	7.73059572581466e-05
11382178	12824	return all values with same count	select id, nameofpet, count(fed) from petlover, pets where id = 180 and petlover.nameofpet = pets.nameofpet group by fed having count(fed) >= all (     select count(fed)     from petlover, pets     where id = 180 and petlover.nameofpet = pets.nameofpet     group by fed ) 	0.000177192728829408
11382423	4886	how to display the search results based on two dates in the listview?	select     dbo.safetysuggestionslog.title, dbo.safetysuggestionslog.description, dbo.safetysuggestionslog.username, dbo.safetysuggestionslog.datesubmitted,                        dbo.safetysuggestionsstatus.status from         dbo.safetysuggestionslog inner join                       dbo.safetysuggestionsstatus on dbo.safetysuggestionslog.statusid = dbo.safetysuggestionsstatus.id where     (dbo.safetysuggestionslog.datesubmitted between @startdate and @finishdate) 	0
11384045	384	select all rows with maximum value of a temporary table	select   test.*,           @curmax := if(@curmax = -1, value, @curmax) from     test,          (select @curmax := -1) r having   @curmax = value or @curmax = -1 order by value desc; 	0
11384052	31396	mysql - group order without sorting	select item, price, timestamp from supplydemand inner join (     select item, min(timestamp) as minimumtimestamp from supplydemand ) as minimums on minimums.item = supplydemand.item and minimums.minimumtimestamp = supplydemand.timestamp 	0.422816439820702
11386384	29887	building a pre-desc row table on my-sql to make faster searching query	select * from `bookmark` where `topic` = 'apple' 	0.792203639244512
11386907	27322	mysql timestamp - display 3 rows within last hour	select * from made_orders where timestamp >= now() - interval 1 hour order by timestamp desc limit 3 	0
11387007	31718	join two similar tables	select *  from table1  left join table2 on table1.item_id = table2.product_id and table1.buyer_id = table2.user_id  where table2.product_id is null 	0.0461024521104144
11387068	24754	mysql: group values	select   logid, @lastuser:=user as user, time from     mytable, (select @lastuser:=null) init having   not @lastuser<=>user order by time desc 	0.0819811950802109
11388588	22971	how to select data from table only recorded the last three days (use php, mysql)	select *  from tlb_students  where date >= now() - interval 3 day order by date desc limit 20 	0
11390124	26487	mysql query to show what doesnt match	select j.job, r.training from riskstraining r join jobsrisks j on j.risk=r.risk where r.training not in  (select training from coursescompleted where person='$person') 	0.372775379801534
11391897	36436	how to display how many times each records in a table used by other table	select t.*, count(t.id) as totale from tbl_tag t left join tbl_tag_usedby u on u.tagid = t.id and t.status =1 group by t.id 	0
11392149	7496	mysql if condition for two columns	select case when fld_intime is null              then 'inmiss'             when fld_outtime  is null              then 'outmiss'             else 'present'        end as remarks from your_table 	0.00767918478457742
11393084	32277	search for characters within a string with mysql	select * from table where text_field regexp '.*p.*h.*p.*' 	0.197707386899229
11393151	30921	mysql multiple table select over 3 tables	select t.template_name, a.area_name from page_versions p inner join templates t on t.template_id = p.template_id inner join template_areas a on a.template_id = t.template_id where p.page_id = 123 	0.0118342190751178
11395187	16910	mysql count since	select c.id,c.post_id,c.comment,c.date,         (select count(*)         from votes as v          where v.date > c.date            and v.comment_id in (select id from comment as c2                                 where c2.post_id=c.post_id)) as votes_after_submission from comment as c order by c.post_id, c.date 	0.112153039983371
11396355	27302	mysql order by related with today's date	select *, datediff(`date`, curdate()) as diff  from `post` order by case when diff < 0 then 1 else 0 end, diff 	0.00544387196299411
11397193	16648	sql searching for entries with the same name column?	select vehiclename, count(*) as total from vehicles group by vehiclename having total > 1 order by total desc; 	7.49713119042627e-05
11397690	30494	sum a pair of counts from two tables based on a time variable	select `year`, format(sum(`count`), 0) as `total` from (     select `table1`.`year`, count(*) as `count`     where `table1`.`variable` = 'y'     group by `table1`.`year`     union all     select `table2`.`year`, count(*) as `count`     where `table2`.`variable` = 'y'     group by `table2`.`year` ) as `union` group by `year` 	0
11397757	10992	sql count* group by bigger than,	select itemmetadata.key, itemmetadata.value, count(*)  from itemmetadata  group by itemmetadata.key, itemmetadata.value having count(*) > 2500 order by count(*) desc; 	0.1626018018983
11400298	25114	select statement needs to output value conditional on null data	select name, lastname,  case when  (p1 is null and p2 is null and p3 is null and p4 is null) then 1  else 0 end , city, st, zip     from mytable 	0.257716491812221
11400392	24190	oracle ranking columns on multiple fields	select group_id,  datetime, rn,        dense_rank() over (order by earliestdate, group_id) as rn2 from (select group_id,  datetime,               row_number() over (partition by group_id order by datetime) as rn,               min(datetime) over (partition by group_id) as earliestdate       from table_1      ) t order by group_id; 	0.0122479165816457
11401407	4932	joining multiple tables (following/activity)	select * from activity a join following f on f.following_user_id = a.user_id  where f.user_id = 1 	0.0732691433494633
11401699	24309	providing mysql a manually-typed list of rows to left join with?	select someline, effy.text from table left join (   select 'a' as text   union all   select 'b'   union all   select 'c' ) as effy 	0.105722622289353
11402178	13838	compare a string to the system time	select   * from  table where   date(to_date(time_stamp,'dd-mm-yyyy hh:mi:ss')) < [current system time] 	0.00541006540174279
11402518	38645	mysql nested queries how to select more than one row	select   id,   parent_id,    name,    '0' as depth,    @tree_ids := id as foo from     tree,   (select @tree_ids := '', @depth := -1) vars where id = 500 union select    id,   parent_id,   name,   @depth := if(parent_id = 500, 1, @depth + 1) as depth,   @tree_ids := concat(id, ',', @tree_ids) as foo from    tree  where find_in_set(parent_id, @tree_ids) or parent_id = 500 	0.0099078509065952
11402843	36921	sql: join parent - child tables	select *  from topics t inner join users tu on tu.userid = t.userid left join comments c on c.topicid = t.topicid left join user cu on cu.userid = c.userid 	0.0144833441303641
11403144	8932	sql command combining rows from a field	select  itemid ,     projectkeyid ,     ( select    serialnumber + ', ' as 'data()'       from      dbo.tblsopartsused u                 join tblserialnumbers nbr on u.sopartsused = nbr.fksopartsused       where     sonumber in ( select    sonumber                               from      dbo.tblserviceorders                               where     projectkeyid = tso.projectkeyid )                 and itemid = tso.itemid     for       xml path('')     ) from    ( select distinct                 c.itemid ,                 projectkeyid       from      dbo.tblserviceorders a                 join dbo.tblsopartsused b on a.sonumber = b.sonumber                 join dbo.tblserialnumbers c on b.sopartsused = c.fksopartsused     ) tso 	0.00242546840111641
11404926	6007	mysql select sum with conditional to change the sign of the column being summed	select      if(buyerid = 100, sellerid, buyerid) as other_company,     sum(if(buyerid = 100, transactionamount, transactionamount * -1)) as netsum from transactions where 100 in (buyerid, sellerid) group by other_company order by netsum desc limit 1 	0.0074989056738206
11405221	30560	mysql combining 2 tables	select m.* from messages m inner join participants p  on m.thread_id=p.thread_id  where m.thread_id = '1' and p.participant_id='the-session-holder-id' 	0.0218593061540817
11405501	285	pad a number with zeros, but only if it's below a certain length?	select case when len(convert(varchar(12), column)) > 7 then      convert(varchar(12),column) else      right('0000000' + convert(varchar(12), column), 7) end   from dbo.table; 	0
11406230	21337	oracle query to compare result row with another and output if match found	select a.application_id "application id1",            a.applicant_name "applicant_name1",            a.applicant_dob "applicant_dob1",            a.receiver_name "receiver_name1",            a.receiver_dob "receiver_dob1",            b.application_id "application id2",            b.applicant_name "applicant_name2",            b.applicant_dob "applicant_dob12",            b.receiver_name "receiver_name2",            b.receiver_dob "receiver_dob2"       from     applications a, applications b       where   a.applicant_name=b.receiver_name       and      b.applicant_name=a.receiver_name                 and      b.receiver_dob =a.applicant_dob                  and      a.receiver_dob =b.applicant_dob; 	0.000451196609994603
11409004	1520	mysql union with where	select * from     ( (select a.id ,a.name,a.surname,a.program,a.date,a.expires      from tablea a left outer join tableb b      on b.aid=a.id      where b.card=1 and (a.id between '1' and '2'))     union all     (select a.id ,b.name,b.surname,a.program,a.date,a.expires      from tablea a left outer join tableb b      on b.aid=a.id      where b.card=1 and (a.id between '1' and '2'))) t     order by id 	0.714295311639308
11410312	14106	(my)sql full join with three tables	select ids.id,        ifnull(table1.a, 0) a,        ifnull(table2.b, 0) b,        ifnull(table3.c, 0) c,        ifnull(table1.a, 0) + ifnull(table2.b, 0) - ifnull(table3.c, 0) r   from    (     select id       from table1     union     select id       from table2     union     select id       from table3   ) ids   left join table1     on ids.id = table1.id   left join table2     on ids.id = table2.id   left join table3     on ids.id = table3.id 	0.558814375259586
11414582	30250	issues with selecting distinct records in mysql	select distinct trim(' 0123456789' from city) as city from t 	0.04037037715987
11415177	10004	how to return a mysql record when value between 2 column values?	select shippingprice  from mytable where 250.0000 between ordertotalfrom and ordertotalto 	0
11415284	22410	mysql select from multiple tables, multiple group by and group_concat?	select leaderboard.name,   (select actions.action    from actions    where actions.name = leaderboard.name      and actions.action like 'ate%'    order by time desc    limit 1   ) as latest_action,   group_concat(items.item                order by items.time desc                separator ', '               ) as items from leaderboard      left join items on leaderboard.name = items.name group by leaderboard.name having latest_action is not null order by leaderboard.score desc 	0.0202134078445729
11415726	17731	query to use group by multiple columns	select     contpat,     contresp,     contins,     month(contdue) as mo,     year(contdue) as yr,     count(*) as 'records' from     mytable group by     contpat,     contresp,     contins,     month(contdue),     year(contdue) having     count(*) > 1 	0.13481360539305
11418870	32186	sql - ugly combination of group by and coalesce	select state, coalesce(max_created,max_updated) from (   select state, min(foo) as min_foo, max(foo) as max_foo,      max(datecreated) as max_created,     max(dateupdated) as max_updated   from data   group by state)  where min_foo = max_foo 	0.668521068815101
11419199	31556	counting date and time for historical reporting	select t3.payment_date, t3."hr", t3."min",        (select count(*)         from invoice_archive t4         where datepart(month, t4.payment_date) <= t3."hr" and               datepart(day, t4.payment_date, 'dd') <= t3."min"        ) as "num" from (select t1.payment_date, t2."hr", t2."min"       from (select top 961 (floor((level + 359)/60)) as "hr",                     mod((level + 359), 60) as "min"             from (select top 961 row_number() over (order by (select null)) as level                   from invoice_archive                  ) t            ) t2 cross join            invoice_archive t1      ) t3  order by t3.payment_date, t3."hr", t3."min" 	0.0317167286858449
11419428	11070	how to summarize sql table to return value conditionally	select    name,    min([description]) as description from      tablea group by name 	0.00215235858020261
11419964	23447	how to average a column of results in sql query	select             dtcreated, bactive, dtlastupdated, dtlastvisit,      datediff(d, dtcreated, dtlastupdated) as difference,    avg(datediff(d, dtcreated, dtlastupdated)) over() as avgdifference from      customers  where             (bactive = 'true')      and (dtlastupdated > convert(datetime, '2012-01-01 00:00:00', 102)) 	0.00124532497341818
11420582	17233	sql join in the same table	select a.product_type from product_table a join product_table b on a.product_type = b.product_type left join product_table c on a.product_type = c.product_type                          and c.brand_id = 'c' where a.brand_id = 'a'   and b.brand_id = 'b'   and c.brand_id is null 	0.0163714107702877
11421581	25061	mysql select to rank a number out of a set of numbers	select     a.make as make,     a.model as model,     a.price as ourprice     max(case when a.compnum = 1 then pricelist end) as comp1price,     max(case when a.compnum = 2 then pricelist end) as comp2price,     find_in_set(a.price, group_concat(a.pricelist order by a.pricelist)) as rank,     count(a.pricelist) as outof from (     select make, model, price, price as pricelist, 0 as compnum     from mytable     union all     select a.make, a.model, a.price, ct1.price, 1     from mytable a     left join competitor1table ct1 on a.model = ct1.model     union all     select a.make, a.model, a.price, ct2.price, 2     from mytable a     left join competitor2table ct2 on a.model = ct2.model ) a group by     a.make, a.model 	0
11424326	34800	getting the primary key of a newly inserted row in sql server ce and c#?	select @@identity 	0.000770935890069316
11424506	6453	selecting the first row from each group, with order by more than one column	select t1.x,        t1.y,        t1.a,        t1.b   from       (select x,               y,               a,               b,               row_number() over (partition by x,y order by a,b) as rownum          from t      ) t1 where t1.rownum = 1 	0
11425272	35583	joining and counting in the same query without double calculation of field	select      ...,             (               select count(*) from hermes.lom.dbo.lom_specimen where specimen = lom.specimen              ) as colcount from         dbo.quicklabdump                  left outer join hermes.lom.dbo.lom_specimen lom                  on quicklabdump.[specimen id] = lom.specimen                  left outer join salesdwh.dbo.isomers isomers                  on quicklabdump.[specimen id] = isomers.[accession id]    where     lom.specimen is null                  and isomers.[accession id] is null 	0.00135153664470519
11428037	22089	mysql query group by to get the last id	select * from table where id in (     select max(id)     from table     where sender = 'jon'         or receiver = 'jon'     group by if(sender = "jon", receiver, sender) )  order by id desc; 	0
11428214	26322	mysql: get records from specific date and group the specific station each hour	select station, hour(call_time) as call_time(h), count(call_id) as total_call from call_log group by station, hour(call_time) 	0
11428216	34369	how to get maximum repeating value in last week	select *, count(1)  from property_viewers where datediff(date, date(now()))<8 group by property_id order by count(1) desc 	0
11428838	6618	find the id of a mysql row based on another field	select id from users where username = 'nstorm'; 	0
11430310	37095	make in clause to match all items ot any alternative?	select hotelid from hotel_to_facilities_map where facility_id in (3,5,2) group by hotelid having count(*) = 3 	0.074650685804007
11431976	17511	searching name from database	select * from tablename where lower(replace(name,' ','')) like lower('%mohankrishna%') 	0.0128233393805112
11433498	1205	select records by comparing subsets	select   table1.x from   table1 inner join   table2     on table1.y = table2.z group by   table1.x having       count(*) = (select count(*) from table2 as lookup)   and count(*) = (select count(*) from table1 as lookup where x = table1.x) 	0.00422027087306809
11434124	38517	mysql select distinct by highest value	select      p.* from         product p     inner join         ( select                magazine, max(onsale) as latest           from               product           group by                magazine         ) as groupedp       on  groupedp.magazine = p.magazine       and groupedp.latest = p.onsale ; 	0.000434113610516113
11435231	26780	sql query to (group by ) by condition of column	select     sum(case when age >= 0 and age <= 18 then 1 else 0 end) as [0-18],     sum(case when age >= 19 and age <= 25 then 1 else 0 end) as [19-25] from     yourtable 	0.0715461067499258
11435981	36277	mysql select 2 counts on same field	select correct, count(*) from table group by correct; 	0.000326640844863493
11436067	14654	unable to count the no: of null cells in a column of a table	select sum(if(data is null, 1, 0)) as null_count from users 	7.83080242316734e-05
11436432	17479	how can i check if a procedure exists in a package?	select *   from sys.dba_procedures   where object_type = 'package' and         object_name = '<your package name>' and         procedure_name = '<your procedure name>' 	0.232592635085735
11439360	9015	how to subtract one one column set of dates from another set of dates and finally add all the rows	select    sum(unix_timestamp(`end`) - unix_timestamp(`start`)) as time_sum from    data 	0
11439380	39137	sql to create a column from the value of another column	select id, srtd = substring(name, 1, charindex(' ', name)), name   from dbo.table; 	0
11439932	29208	php/mysql: selecting same column from a table but with different primary id	select b.ban_id,     b.account_id,     a.username as account_username,     b.bannedby_id,     a2.username as admin_username, from bans b inner join accounts a on b.account_id = a.account_id inner join accounts a2 on b.bannedby_id = a2.account_id 	0
11440317	25059	how can i select 4 distinct values from 2 tables containing many rows of data in sql server?	select top 4      g.galleryid     ,g.gallerytitle     ,g.gallerydate     ,max(m.mediathumb) as maxmediathumb from galleries g     inner join media m         on g.galleryid = m.galleryid group by g.galleryid, g.gallerytitle, g.gallerydate 	0
11442903	41124	using query on sql server database to count records of some type and grouped by some foreign key	select     id_angajat     ,sum(case when stare_task = 'closed' then 1 else 0 end) as [closed_records] from sarcini group by id_angajat 	0
11447114	1424	mysql compare dates	select * from  `order`  where  datetimeadded < now( ) - interval 8 hour ; 	0.00954793072951319
11448146	15442	regarding combining queries into one	select *    from txn_header   inner join txn_detail      on txn_header.txhd_txn_nr = txn_detail.txhd_txn_nr  where txn_header.txhd_receipt_id = 'receipt_id_val'     and txn_header.till_short_desc = 'till_no_val'    and txn_detail.till_short_desc = 'till_no_val' 	0.0664201319591057
11449114	10833	calculating difference of dates in oracle	select trunc(end_date) - trunc(start_date) + 1 as elapsed_days   from a_table 	0.00279908090191325
11449960	34446	how do i append a column to the end of another column in sql	select image || url as imageurl from 'films'; 	0
11452242	34860	mysql - returning data from one table which match multiple combinations of data in another table	select b.book_name from books b, meta_data m, meta_data md where b.id = m.fk_id and b.id = md.fk_id  and m.label ='pages' and m.data = 10  and md.label ='pub' and md.data='smith' 	0
11452498	4519	sql: creating aging buckets based on last payment date for financial reporting	select (case when t.daysago between 0 and 30 then '0-30'              when t.daysago between 31 and 60 then '31-60'              else 'old'         end),        <whatever you want here> from (select account.cust_id, sum(account.balance) as balance       from account       group by account.cust_id      ) a left outer join      (select transactions.cust_id, max(transactions.post_date) as lastpaymentdate,              datediff(d, x(transactions.post_date), getdate()) as daysago,        from transactions       where transactions.tx_type = 'payment'       group by transactions.cust_id      ) t      on a.cust_id = t.cust_id  group by  (case when t.daysago between 0 and 30 then '0-30'                 when t.daysago between 31 and 60 then '31-60'                 else 'old'            end) 	0.000259497484362473
11452835	20	oracle wm_concat to get one row then case to check value	select   ...          wm_concat(job_type) as myjob_type,          sum(decode(job_type,'painter',1,0)) from     ... group by ... 	0.000119602119848669
11455221	33446	mysql query multiple group by	select  o.username, a.requestcount , b.completecount from (select  username from owner_login_pass )  as o left join (select field1, count(1) as requestcount from table1 where date_complete between '2012-06-12 00:00:00' and '2012-07-12 23:59:59'  group by field1) as a on o.username=a.field1 left join (select field2, count(1) as completecount from table1 where date_complete between '2012-06-12 00:00:00' and '2012-07-12 23:59:59'  group by field2) as b on o.username=b.field2 	0.393409816165611
11456202	7284	sql: only querying results that have two rows in a second table associated to them	select ... from ... where name_id in (select name_id                   from address                   where type in ('home', 'business')                   group by name_id                   having count(distinct(type)) = 2) 	0
11456394	28527	select maximum from related table	select table1.*, concat(table1.number, '-', table1.item_id) as idnumber, max(ifnull(table2.id),0) as table2id   from table1   left join table2 on (table1.id = table2.equip_item_id) where table1.group_id > 0   and table2.in_progress = 1 order by table1.id asc limit 15 	0.00010861970582483
11456995	35339	search in data base mysql php	select nl.name,np.person  from (select @rownum:=@rownum+1 ‘rank’, person from  (select @rownum:=0) r, programmer order by rank) as np inner join (select @rownum:=@rownum+1 ‘rank_1’, name from  (select @rownum:=0) r, lang order by rank_1) as nl on (np.rank=nl.rank_1) 	0.0717176303742037
11457453	3086	mysql select from two table per rows of first query	select a.username, a.email, c.name from accounts a, characters c where a.id=c.account order by max(c.rank) desc 	0
11457550	29715	mysql sum hours by rate	select sum(num_hours) as total_hours,      rate,     st.tech_code from ost_hours ht left join ost_staff st on ht.tech_code = st.tech_code group by rate,     st.tech_code 	0.00393664612203357
11457757	14241	select column as other column	select attributes.value as attribute from attributes group by identifier 	0.00221454470143545
11459395	28246	joining two different queries under one answer	select q1.value, q2.value, q1.value - q2.value from   (select count(distinct id) as value from table_name      where date<= '2012-05-31') q1,   (select count(suba.id) as value from        ( select a.id from table_name a          where a.date < '2012-06-01' group by 1          having count(a.service_type) > 1 ) suba) q2 	0.000463290950278284
11461666	39153	mysql - selecting first and last row (not min/max)	select      max(a._date) weekending,      max(case when a._date = b.mindate then a._opening_price end) openingprice,     max(case when a._date = b.maxdate then a._closing_price end) closingprice from mytable a inner join (     select          concat(year(_date), '-', week(_date)) weeknum,          min(_date) mindate,          max(_date) maxdate     from mytable     group by weeknum ) b on a._date in (b.mindate, b.maxdate) group by b.weeknum 	0
11463619	6329	sql count each distinct value in column and add name from another table where the id matches	select a.name, count(*) as num from table2 b  inner join table1 a  on b.status_id=a.id  group by status_id 	0
11464408	18658	how to select a random result for each distinct item in mysql	select a.question, a.answer_id, a.user_id, a.totalvotes from (     select a.question, b.answer_id, c.user_id, count(d.vote_id) as totalvotes     from questions a     left join answers b on a.question_id = b.question_id     left join users c on b.user_id = c.user_id     left join votes d on b.answer_id = d.answer_id     group by a.question, b.answer_id     order by rand() ) a group by a.question 	0
11465126	34653	sql query grouping and select complete row	select empid, joindate , deptid from (select row_number() over(partition by deptid order by joindate) as rnk,* from employe)e where e.rnk=1 	0.155518407538411
11465550	19728	summing result sets in sql server	select      isnull(class, 'grand total') as score,      sum(maths) as maths,      sum(english) as english,     sum(maths) + sum(english) as total from      table  group by      isnull(class, 'grand total') with rollup 	0.176413885148679
11466452	34567	how to add rank, based on points in mysql	select a.*,  (@row := @row + 1) as rank from (       select  bu.username,                 bg.id as goal_id,                 br.id as reason_id,                 (select count(test_reason_id) from test_rank where test_reason_id = br.id) as point                                from                 test_goal as bg inner join test_reason as br on                  br.user_id=bg.user_id inner join test_user as bu on                 br.user_id=bu.id                                 where                 bg.id       =   br.test_goal_id             group by                 bg.id             order by                 point desc ) a, (select @row := 0) r 	0.000868445324687261
11466976	35110	query to fetch the manager name by managerid	select e1.id, e1.name, e1.empid, e1.rankid, e1.deptid, e2.name as managername from employee e1 left outer join employee e2 on e1.managerid = e2.id 	0.00816026443875907
11467755	12313	sql subtract times from tables (decreased additionally for specific time status from second table)	select      t1.id,     t1.time2-case when status='hold' then t2.time else 0 end-t1.time1 from     t1 left join t2 on t1.id=t2.id and t2.status='hold' 	0
11468234	38144	efficient way to filter out rows which are referenced in other table	select r.*  from reports r  left join report_deletes rd on r.id = rd.report_id and rd.user_id = 1  where rd.report_id is null 	7.8644336729632e-05
11469549	32911	how to prevent mysql cross join query returning zero results if one of the queries returns null	select e.id as current, prev.id as previous, next.id as next  from events e  left join   (      select id from events       where date < '{$result['date']}'       order by date desc       limit 1  ) on prev 1=1  left join   (      select id      from events       where date > '{$result['date']}'       order by date       limit 1  ) on next 1=1  where e.date = '{$result['date']}' 	0.0820034222192876
11470849	12598	how do i know one table's primary key field value is used in any another related tables in mysql?	select * from your_table where id in  (     select id from ref_table1     union     select id from ref_table2     union     select id from ref_table3 ) 	0
11471614	8304	mysql join, only get max value	select `plugins`.`name`, users.username, maxvers.version, mcversions.version from users inner join `plugins` on `plugins`.author = users.id inner join (select version, max(time), id from versions) as maxvers  on maxvers.id = `plugins`.id  inner join mcversions on versions.mcversion = mcversions.id 	0.00108975111699567
11472151	9119	plsql bulk collect into udt with join of 1-n tables?	select t_group_emp(g.gid,                       g.gname,                       cast(multiset(select e.empid,                                            e.gid,                                            e.empname                                       from emp e                                     where e.gid = g.gid                                   ) as t_emp                          )                     )     from emp_group g 	0.043889929539855
11477081	18445	sorting with sql	select     country,     sum(amount) over(partition by country) as countrytotal,     town,     amount from        mytable order by    countrytotal, country, town 	0.546705854581365
11479258	24025	mysql select using string based on data from another field	select `nid`, concat('node/', `nid`) as `vpath`, `title`, `alias` from `node` left join `url_alias` on `url_alias`.`source` = `vpath` where match(`title`) against ('a*' in boolean mode) 	0
11479677	34841	how to order by on this mysql query?	select reported_user, count(*) from reported_users group by reported_user order by count(*) desc 	0.75215805599434
11480216	7830	sql select where value = 'x' or min value	select top 1 orgid as [default] from mytable where personid = 12 order by     case when isdefault = 't' then 0 else 1 end,     rowid 	0.00325360253822052
11480648	19589	merge the count from two table in one	select id2, count2, coalesce(count1, 0) as count1   from table2   left outer join table1     on id1=id2 	0
11481269	783	getting sum of mastertable's amount which joins to detailtable	select sum(amount)  from master m  where m.id in (   select distinct masterid   from detail   where pid in (1,2,3) ) 	0.00591336540313125
11481589	30769	achieving a derived column based on maximal value of subgrouping	select a.state,         a.county,         a.population,         coalesce(b.ismostpop, 'no') as flag from state_pops a left join (     select state, max(population) as maxpop, 'yes' as ismostpop     from state_pops     group by state ) b on a.state = b.state and a.population = b.maxpop 	0.000187911227515631
11481898	29666	sql: not a specific year	select * from table where year(year) <> '1997' 	0.0158296340075002
11484867	12820	select top order by query returns unexpected result	select top 1 special_code1 * from customers  where isnumeric(special_code1)=1  order by cast (special_code1 as integer) desc 	0.347530233986912
11485539	24342	displaying messages from the database the other way round	select * from (     select *     from place_chat      where whereto = mysql_real_escape_string($where)     order by id desc     limit 7 ) newest_place_chat order by id asc 	0.00022002749966048
11487697	7795	mysql select id and count in one command?	select count(*) from user a inner join msg b on a.id = b.user_id where a.name = 'name' 	0.00572370753453431
11488253	35642	in date_sub function while using a interval can we use an interval of month and day combined?	select * from users     where year(`start`) = year(date_sub(now(), interval 1 month))        and month(`start`) = month(date_sub(now(), interval 1 month)) 	0.00220637590466265
11491184	11684	count columns where column1 like %something%	select  col1, sum(col2), sum(col3), sum(col3)*sum(col2)  from table group by col1 	0.103400880861101
11494653	6128	mysql left join not returning all rows from the left table	select bp.*, count(bpc.id) as post_comments from blog_posts as bp left join blog_post_comments as bpc on bpc.post_id = bp.id  group by bp.id limit 0, 10 	0.0225172165838193
11495832	22027	mysql query cross database join return null	select t1.cardid, t2.description, t5.biodata  from db2.tblemployeeinfob as t1 left join db2.tbldepartments as t2 on t1.department = t2.departmentid left join db1.tblbiometrics as t5 on t1.cardid = t5.cardid 	0.718028282629677
11495870	20773	get related row in many to many relation once	select distinct a.* from a     inner join b         on a.id = b.id     inner join c         on c.id = b.id where c.somefield = 'somevalue' 	0
11497186	18463	sql - get next set of xx items	select * from table where id > 30  order by id limit 50 	0
11498274	24043	mysql random unique string	select uuid() 	0.0109739487746239
11499922	33016	triggers sql(change type column)	select r.id, user_name, user_phone, date_create, replace( date_payment,  '0000-00-00 00:00:00',  'no payment' ) as updated_date_payment, payment_method, amount, rs.name_ru from request as r, request_status as rs where r.status = rs.id limit 0 , 30 	0.120860832602978
11500201	40729	sql query to calculate total in hh:mm format	select cast ( (sum (datepart(hh, convert (varchar, timespent, 108))) + (sum(datepart(mi, convert (varchar, timespent, 108)))/60) ) as varchar(2) ) + ':' + cast ( sum(datepart(mi, convert (varchar, timespent, 108))) - 60 * (sum(datepart(mi, convert (varchar, timespent, 108)))/60)  as varchar(2))from production 	0.000677109425241419
11501105	3334	how to select from a commas separated parameter?	select top 1 para1 from mytable   where  ','+@name+',' like '%,'+cast(name as varchar(100))+',%' order by date asc 	0.00043743190595038
11501890	21770	join several times	select * from (     (select * from table where something = 1) a,     (select * from table where something = 2) b,     (select * from table where something = 3) c ) 	0.070569425141982
11501972	41241	using the difference between two dates in a where clause	select * from tablename where timestampdiff(minute,timestamp,now()) < 10 	0.00238317910516587
11502109	6050	exclude foreign keys from sql query	select column_name from information_schema.columns where table_name='your table' and column_name<>'contact_id' 	0.000713645431246192
11502682	36079	select 10 rows closest to a field numeric value	select id, number, abs(100 - number) as delta from mytable order by delta limit 0, 10 	0
11503163	5257	sql php select priority	select *  from tablename orderby id1 desc, id2 desc 	0.144129936042824
11504137	30845	mysql if not there in table1 then take from table 2	select (case when t1.field <> 0 then t1.field else t2.field end)  from table1 t1, table2 t2 	0.000311533368014748
11504662	18449	can one column come another sql query	select a.name,count(*) as tasks, a.gender, a.year  from tablea a join tableb b on a.name = b.name  group by a.name, a.gender, a.year 	0.00157236739250288
11504675	11339	different format / efficiency for mysql statement	select       e.empname,      cs.sitename  from      employee e  inner join  (  select  custid,empid from employeeassignment ea1 where enddate=(               select min(ea.enddate)              from                    employeeassignment ea               where                  getdate() between ea.startdate and ea.enddate                  and ea.custid=ea1.custid              ) ) as ea on      e.empid = ea.empid  inner join      customersite cs  on      ea.custid = cs.custid 	0.36262534752884
11505711	20396	how can i combine values from one column into one row?	select products.product,group_concat(tags.tag) from products join tags on tags.product_id = products.rowid group by tags.product_id; 	0
11506971	17024	how to remove rows with duplicate values in a specific column sql	select distinct x.xref_status from table3.xref_data x where x.code=4545645 and x.vehicle_code=9999999 	0
11507253	5849	merging the lines of a sqlite query	select      min(codeirrigation) as 'codeirrigation',      min(codesecteur) as 'codesecteur1',      max(codesecteur) as 'codesecteur2' from table group by date_irrigation 	0.00218365721351758
11507608	23721	how to concatenate a string to mysql resultset	select `id`, concat('str', `id`) as `str_id`, `foo` from `tbl` order by `id` asc; 	0.00210394240324775
11509320	9060	sqlite if no rows returned print 0	select case when d.user_tag is null then '0' else '1' end as user_tag_exists,        tagtypes.tagtype,        d.user_tag, d.device_type, d.ip_address from (     select '%frt%' as tagtype     union     select '%bck%' as tagtype     union     select '%ppp%' as tagtype     union     select '%smes%' as tagtype     union     select '%gm%' as tagtype ) as tagtypes left join     devices d         on d.device_type like tagtypes.tagtype 	0.00246477328846168
11509950	18515	how to merge column data using the last updated value in mysql?	select dname.name,         l1value.unit1_left,         l2value.unit2_left  from   (select distinct `name`          from   table1) `dname`         left join (select `name`,                           max(id) id                    from   table1                    where  unit1_left is not null                    group  by `name`) l1                on dname.`name` = l1.`name`         left join table1 l1value                on l1.id = l1value.id         left join (select `name`,                           max(id) id                    from   table1                    where  unit2_left is not null                    group  by `name`) l2                on dname.`name` = l2.`name`         left join table1 l2value                on l2.id = l2value.id ; 	0
11511394	33381	not able to get the value out of query	select count(1) as my_value from   (select `login_id`          from   `data`          where  ( year(`start_at`) = year(date_sub(now(), interval 1 month))                   and month(`start_at`) = month(date_sub(now(), interval 1 month)                                           ) )                 and ( end_at > date_add(start_at, interval 5 minute) )          group  by `login_id`          having count(`login_id`) > 1) as value $two_cnt = mysql_fetch_assoc($two_tier); echo $two_cnt['my_value']; 	0.0030080909194429
11512654	18790	count values in different rows	select b.descripcion as estado, count(42) as [howmany]   from proyecto a, proyecto_estado b, empresa c   where     a.id_proyecto_estado=b.id_proyecto_estado and     c.id_empresa=a.id_empresa and     c.rut='96659140'   group by b.descripcion 	0.00043252928636636
11514666	37634	mysql number of users per month	select cast(concat(year(`timestamp`),'-',month(`timestamp)) as char) as `month`, count(*) as `hits` from db.table where `username`='<the_username>'  group by `month`; 	0
11515165	17752	sqlite3 select min, max together is much slower than select them separately	select min(x) from table;  select max(x) from table; 	0.47220769737161
11517048	34993	counting column in database mysql	select id,sum(if(sex='m',1,0)) as 'male',  sum(if(sex='f',1,0)) as 'female'  from hospital  group by id 	0.0221585612375244
11517699	19652	mysql inner join 2 tables and order by count	select     c.name,     count(c.id) as countofproperties from     projects a,     project_assignments b,     properties c where     a.id=b.target_id     and b.property_id=c.id group by     c.name order by     count(c.id) desc; 	0.212357194573134
11518380	38955	how to retrieve data from different tables using store procedure?	select  workassigned.workid, usertable.employeename, usertable.employeeemailid,roletable.emplopyeerole,projects.projectname,workassigned.[status] from workassigned   inner join employeegroup  on roletable.groupid=workassigned.groupid inner join projects  on projects.projectid=workassigned.projectid  inner join employeedetails on  usertable.employeid=workassigned.employeid 	0.000100596482400762
11521944	24395	mysql: sort by number of occurrence in tables	select id from (     select id from table1     union all     select id from table2     union all     select id from table3  ) as t group by id order by count(id) desc 	0.000132584646301197
11526202	27640	sql server merge two tables with different structures	select u._id_no,         case when u.ship_date is null                 then ''                else convert(nvarchar(50), u.ship_date,101) end as ship_date,        u.status,         u.total  from (   select a.id_no, a.ship_date, a.status, a.total    from tablea   union all   select b.id_no, null as ship_date, b.status, b.total    from tableb ) as u 	0.00126353623557023
11527195	5969	converting an int field to date time	select case when len(datenumber) = 8 and isdate(rtrim(datenumber)) = 1     then convert(nvarchar(25),          cast(cast(datenumber as varchar(10)) as datetime), 121)     else 'notvalid'      end as result from (     select 20051216 as datenumber     union select 20051217     union select 20051218     union select 10000     union select 90     union select 600     union select 99421946 ) mysubquery order by result 	0.0180001589043602
11529040	34684	subtract data from the same column	select max(gallons) - min(gallons) from table1  group by date having date = '2012-07-01' 	0
11530120	25156	fetching first lowest value in table and the date on which it occurs, for every distinct user	select *   from      (      select a.*,              row_number() over(partition by user_id order by weight) as position        from diet_watch a     ) a     where a.position = 1 	0
11533844	6515	oracle view creation from name value pair table	select   row_num,    max(decode(name, 'col1', value)) col1,    max(decode(name, 'col2', value)) col2,   ... from name_value_pair group by row_num; 	0.000952966345508669
11533977	30446	how to check a date in mysql using other field of the same table	select * from your_table where date < 'your_input_min_date'    and 'your_input_max_date' >= date_add(date, interval days day) 	0
11535215	33794	sum of two field in two table	select a.invcid,        a.invcdate,        a.sumofinvoice,        b.sumofamount from   (select ti.invcid,                ti.invcdate,                sum(td.itemprice * td.itemquantity) as sumofinvoice         from   tblinvoice as ti                left join tblinvcdetail as td                       on ti.invcid = td.invcid         group  by ti.invcid,                   ti.invcdate) a        left join (select tp.invcid,                          sum(tpd.amount) as sumofamount                   from   tblpay as tp                          left join tblpaydetail as tpd                                 on tp.payid = tpd.payid                   group  by tp.invcid) b               on a.invcid = b.invcid 	0.000108639471287334
11536711	38734	sql group by, having, and ordering (mysql)	select `code`, min(distance) as minimal_distance from places group by `code` 	0.624820420117557
11538816	15363	all row values in one column	select user_id, listagg(degree_fi, ',') within group (order by degree_fi) from user_multi_degree group by user_id 	0
11539120	4141	select "step" records	select grp,        ind,        val from (    select grp,            ind,            val,           lag(val,1,0::numeric) over (partition by grp order by ind) - val as diff    from test_table ) t where diff <> 0; 	0.0119506626530532
11539355	35088	"unpivot" data from excel	select * into newtable from   (select id,somefields,supplier,price,weight from table    where somefield is not null    union all    select id,somefields1,supplier1,price1,weight1 from table    where somefield1 is not null    <...>) 	0.11959305287645
11540927	872	multiple joins to collect user ratings?	select   q.id as qid,   q.content,   q.date,   coalesce(sum(r.rating), 0) as rating,   coalesce(sum(if(r.uid = 4, r.rating, null)), 0) as user_rated from quotes q left join ratings r on q.id = r.qid group by q.id 	0.102638546279188
11541633	39421	how to take some column from three table in mysql	select `table1`.*,`table2`.`g`,`table3`.`h` from `table1`  inner join `table2` on `table1`.`a`=`table2`.`a` inner join `table3` on `table2`.`g`=`table3`.`g` 	0.000158798648352787
11543561	33666	mysql query: single table multiple comparisions	select id from mc a where   id != 1 and   member in (     select member from mc where id=1) group by id having   count(*) in (     select count(*) from mc where id=1) and   count(*) in (     select count(*) from mc where id=a.id); 	0.052727122040814
11543696	10	mysql - calculating percentile ranks on the fly	select      c.id, c.score, round(((@rank - rank) / @rank) * 100, 2) as percentile_rank from     (select      *,         @prev:=@curr,         @curr:=a.score,         @rank:=if(@prev = @curr, @rank, @rank + 1) as rank     from         (select id, score from mytable) as a,         (select @curr:= null, @prev:= null, @rank:= 0) as b order by score desc) as c; 	0.0186833833869228
11544266	39813	how can i compare this datetime from the mysql database with now?	select * from mytable where lastlogin < date_sub(now(), interval 30 day) 	0.008613781330567
11545537	35430	mysql - selecting total results returned in each row	select id, (select count(*) from mytable) from mytable; 	0
11545771	9383	sql sum and count returning wrong values	select (select sum(v.rating) from votes v where v.content_id = t.id),         (select count(vi.id) from visits vi where vi.content_id = t.id) from topics t where t.id=1  group by t.id 	0.382626281328076
11545889	19835	multiple and conditions mysql	select * from table where x=x and y=y and z=z 	0.222107440467511
11546848	30406	filling in last known value in mysql recordset output when no data available	select distinct 1 as stock_id, d._date,         (select s2.open from stocks s2         where s2.stock_id=1           and s2.nyse_date < date_add(d._date, interval 1 day)          order by s2.nyse_date desc         limit 1) as open,        (select s3.close from stocks s3         where s3.stock_id=1           and s3.nyse_date < date_add(d._date, interval 1 day)          order by s3.nyse_date desc         limit 1) as close from daterange d left join stocks s1 on d._date=s1.nyse_date order by d._date ; 	0
11547111	22636	mysql distinct or group by	select player2, max(time) as time   from logs   where player1=3   group by player2   order by time desc 	0.359640917375967
11547475	14136	mysql query column that contain text	select * from table where name regexp '[:<:]]someword' 	0.0718825888728734
11548673	2135	how to best maintain status in a parent-child relationship	select     fl.id as firstlevelid     ,fl.active as firstlevelactive     ,sl.id as secondlevelid     ,coalesce(nullif(fl.active, 1), sl.active) as secondlevelactive     ,tl.id as thirdlevelid     ,coalesce(nullif(fl.active, 1), nullif(sl.active, 1), tl.active) as thirdlevelactive from     first_level fl     left join     second_level sl on         (sl.first_level_id = fl.id)     left join     third_level tl on         (tl.second_level_id = sl.id) 	0.113316371226046
11549111	27364	average of top 10 & bottom float_value, with date, group by date	select lpp.prod_id, lpp.date,        avg(case when seqnum_asc <= 10 then perm end) as avg_bottom10,        avg(case when seqnum_desc <= 10 then perm end) as avg_top10,        (avg(case when seqnum_desc <= 10 then perm end) - avg(case when seqnum_asc <= 10 then perm end)) as delta from (select lpp.*,              row_number() over (partition by prodid, date order by perm) as seqnum_asc,              row_number() over (partition by prodid, date order by perm desc) as seqnum_desc       from live_pilot_plan lpp      ) lpp group by lpp.prod_id, lpp.ate 	0
11549113	18328	sql join table and order them by a multiplied value	select * from games_records join      (select furni, max(time) as maxtime       from pricelist_furnis_tradevalue       group by furni      ) as maxf      on games_records.furni = maxf.furni join      pricelist_furnis_tradevalue       on games_records.furni = pricelist_furnis_tradevalue.furni and         pricelist_furnis_tradevalue.time = maxf.maxtime order by (pricelist_furnis_tradevalue.value*games_records.amount) desc 	0.00564806966865521
11550288	1927	sql: get a substring by removing character off the right and left	select substr(<val>, 2, length(<val>) - 2) 	0.282453630079095
11551822	25513	mysql - get one row for each group with order and limit	select p.* from users u  inner join photo p on p.id = (     select id from photos p2      where p2.username = u.username      order by cover desc      limit 1 ) where u.username in('$usernames'); 	0
11552502	10096	extract size (numeric) from string	select ltrim(rtrim(left(val, pos1 - spacebefore))) as product,      substring(val, pos1 - spacebefore + 1, 1000) as size from (select t.*, charindex(' ', reverse(left(val, pos1-1))) as spacebefore       from (select t.*,                    charindex(' x ', val) as pos1             from (select 'abce 15/3 x 2' as val) t            ) t      ) t 	0.00326232648694218
11553041	10855	mysql dynamic select box	select s.id, s.name, ue.id as userselected   from sizes s     left join user_entries ue on s.id=ue.size_id and ue.user_id=xxx   order by s.id 	0.711204245946714
11554383	28237	sort query result without selecting that column but sort by that column?	select empname, salary, status   from (select   *             from emp         order by empno)  where salary > 5000 	8.86519370115529e-05
11554386	16418	sql query one table with union and orderby	select u.pet_id_pk, u.petname, a.address_string, c.contact_number, u.gender  from user u left join address a on u.address_id_fk=a.address_id_pk left join contact c on u.contact_id_fk=c.contact_id_pk where owner_id=$1 order by u.gender,bought_date desc 	0.247209566796337
11554821	10602	join in mysql need to return single record for each primary key	select a.id,a.name,max(b.name) as img  from `jos_properties_products` as a left join `jos_properties_images` as b on a.id = b.parent group by a.id,a.name 	0
11555657	10349	is there a way to partition a query that has a "group by" clause?	select    i.country  ,count(1) population  ,count(case when gender = 'male' then 1 end) male  ,count(case when gender = 'female' then 1 end) female from   individual i group by   i.country ; 	0.646265922186493
11556260	28176	mysql, glue table counts	select productid from product_options where optionid in (6,7) group by productid  having count(distinct optionid)=2 	0.0787478188646164
11557834	22467	connect linked server programatically c#	select *  from openquery ( <linked_server>, 'select code, name, from your_table') 	0.781868525005901
11559612	26640	how to get the final parent id column in oracle connect by sql	select level,            item_id,            parent_id, lpad(' ', 4 * (level - 1)) || item_desc as item_desc            , connect_by_root item_id  as super_id       from oracle_connet_by_test      start with parent_id = 0     connect by prior item_id = parent_id     ; 	0.000234854541003241
11560713	4470	generate insert script for selected records?	select * from [table] where fk_companyid = 1 	0.00690134677175282
11561383	15144	php/sql select all that expires within 48 hours	select   * from   my_table where   unix_timestamp() between (creationtime + 1036800) and (creationtime + 1209600) 	0.000335772908838946
11561740	9003	getting maximum number from three different queries	select max(to_number(substr(attr_value,instr(attr_value, '-')+1)))+1 from circ_inst inner join      circ_attr_settings      on circ_inst.circ_inst_id=circ_attr_settings.circ_inst_id and         val_attr_inst_id=1045 where circ_attr_settings.attr_value like 'layer 2 switch-%') or       circ_attr_settings.attr_value like 'ipanema-%' or       circ_attr_settings.attr_value like 'firewall-%' 	0
11562232	35389	query for records that do not exist	select today.status, group_concat(tomorrow.work_order order by line), today.code, today.events     from today left join tomorrow    on today.code = tomorrow.code    where today.status = 1 or       (today.status = 3 and isnull( tomorrow.work_ordertext ))     group by today.code 	0.05610712667511
11563408	23446	similar queries have way different execution times	select nvl(sum(adjust1),0) from (   select     manyoperationsonfieldx adjust1   from (     select       substr(balance, instr(balance, '[&&2~', 1, 1)) x     from       table     where       a >= to_date('&&1','yyyymmdd')       and a < to_date('&&1','yyyymmdd')+1       and (           b like '..'           and e is null           and (b not in ('..','..','..'))           or  (b='..' and c <> null)       )   ) ) where   adjust1>0 	0.0355193429569552
11563636	40143	column calculation comparison in mysql	select if(valid,employee_name,"null") as name, valid from (select t.*, if(salary/days > 1000, true, false) as valid       from t      ) t 	0.412319266454778
11566537	25753	retrieving only the most recent row in mysql	select * from yourtable where date_and_time = (select max(date_and_time) from yourtable) 	0
11567219	34910	average number of days using mysql	select a.name,         avg(datediff(a.resolved, b.created)) as avgdays from (    select name, resolved, @val1:=@val1+1 as rn    from tbl    cross join (select @val1:=0) val1_init    where name = 'mike'    order by resolved ) a inner join (    select created, @val2:=@val2+1 as rn    from tbl    cross join (select @val2:=1) val2_init    where name = 'mike'    order by resolved ) b on a.rn = b.rn 	0
11567880	7675	oracle daily count/average over a year	select count(distinct chargeno), to_char(chargetime, 'mmddyyyy')  as chargeend  from batch_index where plant=1 and chargetime>to_date('2012-06-18','yyyy-mm-dd')  and chargetime<to_date('2012-07-19','yyyy-mm-dd') group by to_char(chargetime, 'mmddyyyy') ; 	0.00718993184943732
11568740	40506	select sum ignoring group by	select    wordlist.word,   sum( worddocfreq.freq ) / ( select sum( freq )                                from worddocfreq                                  join sourceparsed on                                        sourceparsed.srcid = sp1.srcid                                   and sourceparsed.parsedid = worddocfreq.parsedid                             ) as proportion from sourceparsed sp1   left join worddocfreq on sourceparsed.parsedid = worddocfreq.parsedid   left join wordlist on worddocfreq.wordid = wordlist.wordid where   sourceparsed.srcid = 30032 group by   wordlist.word 	0.10595193958882
11569978	16895	sql self join to concatenate columns	select serviceentryid, partdescription =      stuff((select ' | ' + cast(b.id as nvarchar) + ' ~ ' + partdescription            from part b             inner join serviceentrypart c                 on c.partid = b.id            where c.serviceentryid = a.serviceentryid            for xml path('')), 1, 3, '') from serviceentrypart a group by serviceentryid 	0.0660644802454895
11571179	27173	improving a query to find out-of-sync values between two tables	select   tableoneid,   tableonedata,   d as tabletwodata from tabletwo join (select tableoneid, sum(a + b + c) as tableonedata       from tableone       group by 1) x on tableoneid = tabletwoid where tableonedata <> d; 	0.00306925733518904
11571505	20097	mysql query ; finding if two person sharing the same group	select * from group_table where group_id = id and (userid = a or userid = b) 	7.41587399008008e-05
11572161	36114	selecting a random row from sqlite table with where?	select question, answer, category from records where category=2 order by random() limit 1; 	0.000186120184733912
11575040	26271	a way to select a date between two dates in t-sql	select dateadd(n, datediff(n, dtin, dtout)/2, dtin) from t 	0.00036052360279967
11575309	21527	selecting specific row number from select	select     cid, cluedetails, location, author from    (       select    @rownum := @rownum + 1 as `rowno`,                  p.cid,                  p.cluedetails,                  p.location,                  p.author          from (                select cid, cluedetails, location, author                  from mytablename                 where location = 'loc 1' and author = 'auth 1'              ) p , (select @rownum:=0) r      ) y where y.rowno = 3 order by rowno 	0
11576610	22524	mysql group query by according to type	select group_concat(title) as titles from service_types group by `type` 	0.0788443559084023
11576642	32836	sql using count & group by without using distinct keyword?	select  u.*  from    users u         inner join          (   select  ur.userid             from    users_roles ur                     inner join roles r                         on r.roleid = ur.roleid             where   r.permissionlevel > 100              group by ur.userid         ) ur             on u.userid = ur.userid where   u.active = 1   order by u.lastname 	0.538074240425054
11576688	26247	finding non repeating record	select      s.* from     systems as s  where     s.system_id not in      (select l.system_id from licenses as l where l.licence_type='full') 	0.00110902174555122
11577306	25928	sql - counting the number of rows that contain two distinct fields	select fieldb, count(distinct  fielda, fieldb) as count  from table  group by fieldb; 	0
11577857	9948	enter multiple rows explicitly in single select statement	select t.*  from (values(1,2,3), (2,3,4)) as t(col1,col2,col3) 	0.087977766437777
11578740	16205	find mysql entries without match in other tables	select * from events_artists where event_id is null or event_id not in (select id from events) 	0
11578887	104	need select top 10 people sql	select user_id, count(follow_id) as total_followers from users  group by follow_id  order by total_followers limit 10; 	0.00387039946263485
11579155	8046	select multiple rows from tow tables mysql	select    blood_donation.serial_number,   donor.blood_group  from   blood_donation ,   donor  where donor.donor_number = blood_donation.donor_number  and date_of_donate = '2012-07-18' ; 	0.000832960012011541
11579709	24492	groupby ordering and single row selecting	select u.logical_id, u.instance_id, u.node_id, u.state, u.time_stamp from  (  select m1.logical_id, m1.instance_id, m1.node_id, m1.state, m1.time_stamp, 1 as node_type  from mytable m1  where m1.instance_id=1 and m1.state='starting'   order by m1.time_stamp desc limit 1  union  select m2.logical_id, m2.instance_id, m2.node_id, m2.state, m2.time_stamp, 0 as node_type  from mytable m2  where m2.instance_id=1   order by m2.time_stamp desc limit 1 ) as u order by u.node_type desc  limit 1 	0.00422703230168004
11580379	208	selecting multiple columns in sql	select  column_name + ',' from    information_schema.columns where   table_name = 'your table name'         and column_name like 'nvarchar%' 	0.00528518333713476
11580518	35127	two ways join in mysql	select request.id as offer_id, request.product_id, request.licence_id as target_licence_id, request.trans_price  , products.source_licence_id      from request      join products on request.product_id = products.id      join licences as l1 on products.source_licence_id = l1.id      join licences as l2 on request.licence_id = l2.id      join users_licences on l2.id = users_licences.licence_id      where users_licences.user_id='$user_id'      group by request.id      order by request.trans_price desc 	0.172098982720483
11580635	34599	what is the cr or lf char in text taken from a webpage text area?	select 'foo' + char(13) + char(10) + 'bar'; 	0.0977462277724997
11580885	4030	get a list of fields out of an xml data type	select     distinct t.c.value('local-name(.)[1]', 'varchar(100)') from @employees cross apply employeedetails.nodes('employee/employeedetails/*') as t(c) 	0
11580972	786	compare and join multiple tables but only show if there is a relation	select mt.checknumber as checknumber,   c1.name as name,   c1.totalcash as totalcash,   c1.bonus as bonus,   mt.reimbursement as reimbursement from maintable mt   inner join childtable1 c1 on c1.checknumber = mt.checknumber union select mt.checknumber as checknumber,   c2.name as name,   c2.totalcash as totalcash,   c2.bonus as bonus,   mt.reimbursement as reimbursement from maintable mt   inner join childtable2 c2 on c2.checknumber = mt.checknumber 	0.00060662008314074
11581143	28874	record has one relation to specific other record	select tag.tag_id,    (count(tagitems.tag_id) > 0) as is_assigned_to_item from tag    left outer join tagitems on tagitems.tag_id=tag.tag_id and tagitems.item_id = ? group by tag.tag_id 	0
11581922	5123	batting average mysql query	select b1.name, sum(b1.runsscored) / b2.numout as bat_avg from batsmen b1 inner join (   select name, count(howout) as numout   from batsmen   where howout <> 'not out'    group by name ) b2   on b1.name = b2.name group by b1.name 	0.0517424185421574
11585958	31895	sql server subquery for 2 columns optimal	select p.parentword,c1.childword,c2.childword from @parent p left join @child c1 on p.childid = c1.childid left join @child c2 on p.childotherid = c2.childid 	0.234260329543274
11586694	755	mysql select records where there are multiple matching records in related table	select * from table1 a where exists (select * from table2 b where a.id = b.id and b.category = 'x')  and exists (select * from table2 b where a.id = b.id and b.category = 'y') and exists (select * from table2 b where a.id = b.id and b.category = 'z') 	0
11586923	40073	select distinct with left join, ordered by in t-sql	select t1.id from tbl t1 left join  tbl t2 on t1.type = t2.type and t1.dtin = t2.dtin group by t1.id, t2.dtout order by t2.dtout 	0.426737126567455
11588510	21350	count the mismatch and missing	select tt.buyer_id , count(*) from (select testingtable1.buyer_id, testingtable1.item_id, testingtable1.created_time from  testingtable2 right join testingtable1   on (testingtable1.item_id = testingtable2.product_id   and testingtable1.buyer_id = testingtable2.user_id   and abs(datediff(mi, testingtable1.created_time,testingtable2.last_time)) <= 15)  where testingtable2.product_id is null) tt group by tt.buyer_id; 	0.411605239180959
11590362	40675	mysql query subtraction values	select        a.purchase_code,       b.item_code,        '15' as status_code,       sum(         case b.status_code              when 15 then b.itempurchase_quantity         else              - (b.itempurchase_quantity)          end)          as itempurchase_quantity,       b.item_costprice from qa_items_purchases b     inner join qa_suppliers_invoices a          on a.supplier_invoice_code = b.item_invoicecodesupplier group by purchase_code, b.item_code, b.item_costprice     having itempurchase_quantity > 0     order by purchase_code      limit 0,20000 	0.163533585018915
11592889	23226	mysql - how to return array from first table and select from another table using that array in one query?	select v.game_id from videos v inner join game_follower gf on gf.game_id = v.game_id where gf.user_id = 1 	0
11594389	21127	how to order sql rows by value?	select t1.user_id     from yourtable t1      join yourtable t2         on t1.user_id = t2.user_id         and t2.meta_key = 'rating'     where t1.meta_key = 'b'     order by cast(t2.meta_value as signed) 	0.00445330973585467
11594522	6049	mysql maximum rows in a variable timeframe	select lb.userid from logbook lb where datediff(now(), lb.date) >= 7*24 group by userid having count(*) >= 90 	0.00108009006138804
11595790	24767	selecting from two non-related tables at the same time	select bt.*, ort.* from bigtable bt cross join      onerowtable ort 	0
11595945	33018	php and mysql content displaying out of order	select * from content where pages like '%$pageid%' order by type desc 	0.0256350683105627
11595970	38600	mysql comments tag breaking my code (php)	select * from something where var=':var#' and value=':value' 	0.491171214573635
11595993	18626	retrieve highest value from sql table	select name,max(profit) from table group by name 	0
11596464	4220	get private message group by user mysql/php	select * from messages  where message_id in(select max(msg.message_id) from messages msg                     where msg.receiver_id = 3 group by sender_id ) 	0.064762103198514
11596690	29180	multiple tables, same column, using where	select     names.total as toal_names,     names.pending as total_pending_names,     misc.total as total_misc,     misc.pending as total_pending_misc,     events.total as total_events,     events.pending as total_pending_events from      (         select              count(names_revisions.id) as total,             sum(if(names_revisions.status = "pending", 1, 0)) as pending         from names_revisions         where names_revisions.created_by = :user_id     ) as names,     (         select              count(misc_revisions.id) as total,             sum(if(misc_revisions.status = "pending", 1, 0)) as pending         from misc_revisions         where misc_revisions.created_by = :user_id     ) as misc,     (         select              count(events_revisions.id) as total,             sum(if(events_revisions.status = "pending", 1, 0)) as pending         from events_revisions         where events_revisions.created_by = :user_id     ) as events 	0.00672450383537868
11596757	4706	join mysql on date range	select a.date, d.name, c.price from apples_sold a inner join (     select a.date, max(b.date) as maxdate     from apples_sold a     inner join price_history b on a.date >= b.date     group by a.date ) b on a.date = b.date inner join price_history c on b.maxdate = c.date inner join apple_name d on a.apple_id = d.apple_id 	0.012888931473553
11596987	30146	query return a bad output	select a.id_offer, t.tags from    (select * from offer o     where o.id_offer in (600, 629)     and o.state=0     order by ? desc     limit ?,?) a inner join offer_has_tags b     on a.id_offer = b.offer_id_offer inner join tags t     on b.tags_id_tags = t.id_tags 	0.673548851257784
11597240	33058	reverse mysql database results with php	select * from $table_name order by id desc 	0.341785436284797
11598041	17262	order by name and by most popular title - oracle	select movie_name, user_name, count(movie_name) popularity  from movie natural join movie_queue natural join users group by (movie_name, user_name) order by popularity, movie_name; 	0.00184252274762089
11599087	16509	mysql: how can i select a value (date) based on a result from another table and include it in said result?	select      a.*, b.date as bestrounddate, c.date as bestaveragerounddate from (     select          d.id,          d.name,         count(distinct re.raceid) as numraces,         min(ra.date) as firstrace,         max(ra.date) as lastrace,         min(re.bestround) as bestround,         min(re.averageround) as bestaverageround     from driver d     inner join result re on d.id = re.driverid     inner join race ra on re.raceid = ra.id     group by d.id, d.name ) a inner join (     select aa.driverid, aa.bestround, bb.date     from result aa     inner join race bb on aa.raceid = bb.id ) b on a.id = b.driverid and a.bestround = b.bestround inner join (     select aa.driverid, aa.bestaverageround, bb.date     from result aa     inner join race bb on aa.raceid = bb.id ) c on a.id = c.driverid and a.bestaverageround = c.bestaverageround order by     a.name 	0
11601832	32266	save all results to excel	select distinct id, cast(text as varchar(255)) as text from tablea, tableb where (various joins here...) 	0.108202311596869
11602414	20784	count events in sql server?	select dateadd(minute, m * 5, 0) as d,        count(*) as c from (       select datediff(minute, 0, d) / 5 as m       from @t       where d >= @startcheckingtime and             d < dateadd(day, 1, cast(@startcheckingtime as date))       ) t group by m order by m 	0.110654880782623
11603978	27879	mssql data parsing	select     guild_data.guild_name from char_data0 inner join guild_data on guild_key = convert(int,cast(reverse(substring(char_data, 33, 4)) as binary(4))) where convert(int, substring(char_data, 261, 1))=0x00 order by level desc 	0.297910847212701
11604125	26070	reducing mysql queries and time	select      a.id,      a.created,      a.name,      b.clientname,      a.isfeatured,      a.views,      a.clientid,     coalesce(c.img_cnt, 0) as gallery_image_count,     coalesce(c.comment_cnt, 0) as gallery_comment_count from      gallery a  inner join      client b on a.clientid = b.id  left join (     select aa.galleryid,             count(distinct aa.id) as img_cnt,             count(1) as comment_cnt     from galleryimage aa     inner join imagecomments bb on aa.id = bb.imgid     where bb.note <> ''     group by aa.galleryid ) c on a.id = c.galleryid where      a.istemp = 0 and     a.clientref = '{$clientref}' and     a.finish = 1 and     a.isarchive = 0  order by      a.created desc 	0.608775555856738
11606638	25520	joining a count on a query	select a.postid,c.author,c.title, c.id,c.body,c.date,c.pic, c.tags, c.imgdesc, count(a.key) as num_comments from blog c left outer join comments a on a.postid = c.id group by c.id order by id desc 	0.0582637014762009
11608103	40870	count average age from database, merge 2 queries	select age.aid, job.id, age.guess, count(age.guess) as countguess  from age, job  where ((age.aid = job.id) and (age.aid='$id'))  group by guess  order by countguess desc 	0
11608300	4997	how to index two columns automatically in sql	select job_number,     row_number() over (partition by job_number order by time_submitted asc) as srno from tbl 	0.0130011177877459
11609803	2305	sql query to get desired result from three tables	select d.phototitle,        m.albumid,        p.phototn as tn,        p.photoid as pid,        p.photolarge as pl,        case when d.photoid is null              then 'no'              else 'yes'          end as [details]   from photos p  inner join photomappings m     on p.photoid = m.photoid   left join  photodetails d     on p.photoid = d.photoid  where m.albumid = 14    and m.languageid = 1 	0.00736801303249034
11611033	25119	mysql agregation function. average price and item price	select count(*) from item as t1 inner join ( select id,avg(price) - std(price) as sum1, avg(price) + std(price)  as sum2 from item  group by id ) as t2 on t1.id=t2.id and t1.price>sum1 and t1.price<sum2 	0.00042967411437417
11614631	5997	how to create a row in sum set for group in sql server?	select t2.deptname, total = coalesce(sum(total),0) from tab t1 right outer join (select 'dept1' as deptname union all                   select 'dept2' union all                   select 'dept3' union all                   select 'dept4') t2 on t2.deptname = t1.deptname group by t2.deptname 	0.0098444932497851
11615514	19878	how can i group by date starting at a different time than midnight?	select cast(date as date) as daydate, sum(books) as lostbooks from (select rbv.*,              cast(dateadd(h, -7, date) as date) as newdate       from restartbooksview rbv      ) where name = 'auht167' and newdate > (getdate() - 105) group by newdate order by cast(date as date) asc 	8.96210989283745e-05
11615595	29087	mysql statement (group and sum() => getting multiple "sum" result per line	select user_id, sum( point_row ) as points_total, user_data...,...     from points     join user_data as ud     on ud.user_id = points.user_id join ( select field1,field2,field3, max(activation.user_id) as user_id    from activation where activation_info = 'yes'   group by field1,field2,field3 as activ )  as activ   on user_data.user_id = as activ.user_id where points.points_status = '1' and   activ.activation_info = 'yes' group by points.user_id order by total desc  limit 0 , 100 	0.00225549814765107
11615766	37863	mysql queryto list only uppercase row from database	select *           from accounts           where cast(username as binary) rlike '[a-z]'; 	0.000119042782517509
11616693	32437	sql query for a total amount between date range	select i1.clientid     , sum(invoiceamt) as total from invoice i1 inner join (     select clientid, min(invoicedate) mindate     from invoice i     group by clientid  ) i2     on i1.clientid = i2.clientid where i1.invoicedate between i2.mindate and dateadd(d, 15, mindate) group by i1.clientid 	0
11617249	40877	mysql: how to query multiple tables and apply a limit to only one?	select * from subitem inner join                (select * from items limit 10) as i               on subitem.item = i.id 	0.00196648088773409
11618024	32054	aggregation data from many tables	select id, timestamp, contents, filter from  ((select t1.id, t1.timestamp, t1.contents, 'filter1' as filter         from table1 t1          where t1.parent_id = $1        )        union all        (select t2.id, t2.timestamp, t2.contents, 'filter2' as filter         from table2 t2          where t2.parent_id = $1        )        union all        (select t3.id, t3.timestamp, t3.contents, 'filter3' as filter         from table3 t3          where t3.parent_id = $1         )       ) table_alias order by timestamp; 	0.0124997530721917
11618498	18292	i need a sql statement to include address 1 or address 2 or use both addresses to create a mailing list	select a.*      , tblgeographicalarea.quarterstarted     , tblmailoutdetails.mailoutlist from  ( (select youngcarersid     , "select address1" as wherefrom     , t.flagged     , t.firstname     , t.lastname     , t.address1     , t.address2     , t.address3     , t.useaddresslabel  from tblyoungcarersdetails  t where t.useaddresslabel  = "address 1"       or t.useaddresslabel  = "both"  union  select youngcarersid     , "select address2" as wherefrom     , t.flagged     , t.firstname     , t.lastname     , t.[2ndaddress1]     , t.[2ndaddress2]     , t.[2ndaddress3]     , t.useaddresslabel  from tblyoungcarersdetails  t where t.useaddresslabel  = "address 2"       or t.useaddresslabel  = "both" ) as a inner join tblmailoutdetails      on a.youngcarersid = tblmailoutdetails.youngcarersid ) inner join tblgeographicalarea      on tblmailoutdetails.youngcarersid = tblgeographicalarea.youngcarersid where tblmailoutdetails.mailoutlist=yes 	0.140164850760639
11618778	18105	sql: nested queries based on values of a column	select content_type_code_id     , abs(price)     , count(if(price >= 0,1,null)) as debits,     , count(if(price < 0,1,null)) as credits, from dbo.transaction_unrated  where transaction_date >= '2012/05/01'      and transaction_date < '2012/06/01'      and content_provider_code_id in (1)  group by content_type_code_id, abs(price) order by price asc 	0.000894143557919498
11618826	17934	how to find mysql difference between 2 tables	select p.p_id from picture p where p.p_id not in     (select s.p_id from seen_picture s where s.u_id = "$user_id") picture p_id(primary key) picture seen_picture id(primary key) u_id p_id 	0.000145045139815212
11619170	22829	case condition then using two tables	select firstname,lastname  from table1 (nolock)  left outer join table2 on table1.id=table2.id where isnull(billingaddress, shippingaddress) like 'lake street' 	0.112357202652698
11619637	19097	how to limit the result of query with a join?	select categories.category, m.id, m.title, m.message from categories right join      (select *       from messages       order by messages.id desc       limit 2      ) m      on m.id = categories.message order by m.id desc 	0.0887710092482214
11621775	37419	select column from first and last record matching criteria	select group_id,min(`date`) as start_date,        (select `date` from slots s3          where s3.group_id=t.group_id          and s3.`date`<t.next_stop_date         and s3.free_spots > 0         order by s3.`date`desc         limit 1) as end_date from    (select s1.*, min(s2.`date`) as next_stop_date     from       slots s1 left join slots s2         on s2.`date` > s1.date and s1.group_id=s2.group_id and s2.free_spots = 0    where s1.free_spots > 0     group by s1.group_id, s1.`date`    order by s1.group_id asc, s1.`date` asc   ) as t group by group_id, next_stop_date 	0
11623851	18815	how to sum up grouped results in sql	select avg(sum_seconds) from (select sum('seconds') as sum_seconds between date a and date b group by week('date')) as a 	0.0243376999703742
11624104	12101	find the record with the lest amount of associated records	select questions.id, count(results.id) result_count from     questions     left join results on questions.id = results.q_id group by questions.id order by count(results.id) 	0
11625513	10603	reusing auto increment id	select id + 1 from tablename t1 where not exists (select 1 from tablename t2 where t2.id = t1.id + 1) limit 0,1 	0.00285790299656867
11625776	29918	mysql using pow() for table data	select  event_id, place, money,pow(money,2)/2 as new_money from prize; 	0.1160655926708
11627822	36434	selecting all the tables containing specific columns	select distinct table_name from information_schema.columns where column_name in ('sname','dtcreatedat','dtmodifiedat','ixlastmodifiedby','fstatus') and table_schema = 'your_db_name' 	0
11631991	26027	sql query taking several times information from a table	select m.id, sender, reveiver, message,   sender.name as sender_username, receiver.name as receiver_username from messages m inner join users sender on sender.id = m.sender inner join users receiver on receiver.id = m.reveiver 	0.00155633107804607
11633028	16842	sql counting aggregate query	select prop_id, sum(amount) as bnp_spent,        sum(case when cost_type = 'direct cost' then 1 else 0 end) as direct,        sum(case when cost_type = 'burden cost' then 1 else 0 end) as burden from cost group by prop_id 	0.595320235632958
11634118	11394	mysql join help. get results based on number of comments in seperate comments table?	select  r.id  ,r.title, r.body from results r inner join (select result_id, count(id) cnt from comments group by result_id) c on r.id = c.result_id order by c.cnt desc 	0
11634969	13157	mysql query 2 tables unrelated column	select faq.*, workers.* from faq inner join workers on faq.faq_id = workers.faq_id where faq.member_id = 1 and (workers.owner1 = 1 or workers.owner2 = 1) 	0.00368157050968643
11635373	19628	retrieve the first record using only a where clause	select *  from mytable  where customer_id = 1 and created in (     select min(created) as mincreated     from mytable     where customer_id = 1 ) 	7.80900215431141e-05
11635522	19840	count distinct items in stored procedure variable	select value, count(*) from ( select value1 as value from sometable union all  select value2 as value from sometable union all  select value3 as value from sometable union all  select value4 as value from sometable union all  select value5 as value from sometable union all  select value6 as value from sometable union all  select value7 as value from sometable union all  select value8 as value from sometable) as sometable group by value 	0.0619601042693055
11636061	13253	matching all values in in clause	select itemid from itemcategory where categoryid in (5,6,7,8)  group by itemid having count(distinct categoryid) = 4 < 	0.00556707801705359
11636282	33073	mysql: group by grouped column?	select     substring_index(group_concat(nid order by likes desc),',',1) as most_likes_nid,     max(likes) as most_likes,     substring_index(group_concat(nid order by dislikes desc),',',1) as most_dislikes_nid,     max(dislikes) as most_dislikes from (     select          nid,         count(if(type = 'like', 1, null)) as likes,         count(if(type = 'dislike', 1 ,null)) as dislikes     from node_likes     group by nid  ) as t 	0.0210411741455718
11636468	6732	display duplicated data in the list	select     region, category, energy from     (     select        region, category, energy,        row_number() over (partition by region, category, energy order by region) as rn     from        mytable     ) x where    x.rn > 1 	0.00017058944565161
11637337	21827	sql query - not in a set of already in-use items	select a.* from jobs a left join (     select a.job_id     from assigned a     inner join     (         select max(id) as maxid         from assigned         group by user_id     ) b on a.id = b.maxid ) b on a.id = b.job_id where b.job_id is null 	0.00914861505861843
11637925	20265	dynamically create and load table from select query	select      mem_id, [c1],[c2]  into #temp from      (select          mem_id, condition_id, condition_result      from tbl_gconditionresult     ) x  pivot      (        sum(condition_result)        for condition_id in ([c1],[c2])     ) p  drop table #temp 	0.029270082268095
11639040	14492	select query to get total records count in sql server	select  count(*) as totalrecords,  sum(case where status = 'pass' then 1 else 0 end) as passrecords, sum(case where status = 'fail' then 1 else 0 end) as failerecords from table 	0.000151074216073877
11639606	15611	oracle date aggregating	select to_char(dateid, 'yyyy-mm')||'-01' as thedate, count(*) from picture_table group by to_char(dateid, 'yyyy-mm') order by 1, 2 	0.154357095622801
11640474	2691	how to calculate a moving 4 week average every week in mysql	select yearweek, sum_cnt/sum_dys as avg_moving_4wk from (     select a.yearweek, sum(b.sumcount) as sum_cnt, sum(b.numdays) as sum_dys     from weekly_results a         join weekly_results b         on a.yearweek - b.yearweek <4 and a.yearweek - b.yearweek >=0     group by a.yearweek ) t1 group by yearweek 	0
11640689	19190	mysql subqueries where less than 3 and places more than once	select name, horse_id  from horse left join  (select horse_id, count(horse_id) as c from entry where place < 4 group by horse_id) as h  using (horse_id) where c > 1; 	0.0103148865558085
11640703	8796	plsql compare and get max value	select student, subj, period, score from (select t.*,              row_number() over (partition by student order by score desc) as seqnum       from t      ) t where seqnum = 1 	0.000602129945596447
11640707	12264	getting all of a row's attributes via a key value table	select p.name,        max(case when a.a_id = 1 then a.a_name end) as attr1,        max(case when a.a_id = 2 then a.a_name end) as attr2 from person p join      keyval kv      on p.key = kv.key join      attribute a      on kv.a_id = a.a_id group by p.name 	0
11640899	24450	sql category tree - category, categoryrelationship and product tables - need totals of products for each subcat	select c.id, c.name, c1.name, cr1.categoryid, c2.name, cr2.categoryid,  (select count(*) from product where product.subcategoryid = cr2.categoryid and deleted = 0 and statusid = 1)  from category c left outer join categoryrelationship cr1 on cr1.categoryparentid = c.id left outer join categoryrelationship cr2 on cr2.categoryparentid = cr1.categoryid inner join category c1 on c1.id = cr1.categoryid inner join category c2 on c2.id = cr2.categoryid where c.categorytypeid = 1 order by c.name, c1.name, c2.name 	0
11641812	22236	multiple avg in single sql query	select nid, did, indexid, 100.0 * avg(standardscore)      from 'indicators'     inner join 'indexindicators'       on indicators.indicatorid=indexindicators.indicatorid  group by nid, did, indexid 	0.217012062599025
11642001	4699	sql queries on relation table	select e.name   from emp e, works h_w, dept h_d, works s_w, dept s_d  where e.eid = h_w.eid    and e.eid = s_w.eid    and h_w.did = h_d.did    and h_d.dname = 'hardware'    and s_w.did = s_d.did    and s_d.dname = 'software' 	0.112772423950151
11643725	4767	sql query, return randomly ordered rows with limits, possible?	select * from tbl order by rand(s); 	0.0137932619568769
11643974	22329	sql view with date calculations	select h1.invid,i.inventoryname,h1.siteid,h1.[timestamp] [date in], min(h2.[timestamp]) [date out]  from    history h1 left outer join history h2 on      h1.invid=h2.invid and h1.[timestamp]<h2.[timestamp] join inventory i on i.inventoryid= h1.invid where   h1.siteid=1 group by    h1.invid,i.inventoryname,h1.siteid,h1.[timestamp] 	0.342187433644811
11644565	36837	how to check the given name persent in database column	select * from tablea where status= 'approved' and       (forward1 ='jose' or  forward2 ='jose' or  forward3 ='jose'          or  forward4 ='jose'  or  forward5 ='jose'); 	0.000191560693782988
11645386	9978	mysql compare column with count()	select   rooms.id as room_id,          count(customer.id) as occupied,          rooms.head as total_head,          rooms.head - count(customer.id) as remaining_head from     rooms left join customer on customer.room_id = rooms.id group by rooms.id having   remaining_head > 0 	0.0161939421965869
11645691	7878	wordpress sql : get all category of a post	select c.* from wp_categories c inner join wp_post2cat pc on pc.category_id = c.cat_id inner join wp_posts p on pc.post_id = p.id where p.id = 1 	0
11646011	20108	subtract and display in percentile	select convert(varchar,((t.revenue - tt.revenue)*100)/(t.revenue)) +'%'   as value from dbo.table_1 t inner join dbo.table_1 tt on tt.data = t.data and t.loading = 'before load' and tt.loading = 'after load' 	0.000793202370649093
11646130	39694	sql query - average data increase	select  datepart(wk, day) as weeknr ,       avg(increaseperday) as averagedailyincrease from    (         select  cast(d1.measuredt as date) as day         ,       avg(d2.level) - avg(d1.level) as increaseperday         from    yourtable d1         join    yourtable d2         on      cast(d2.measuredt as date) = cast(d1.measuredt as date) + 1         group by                 cast(d1.measuredt as date)         ) as subqueryalias group by         datepart(wk, day) 	0.0311684744158337
11646401	32739	select max of count	select top 1 app_rate_unit, count(*) from dbo.well group by app_rate_unit order by count(*) desc 	0.0176983395369568
11646810	21268	sql select on parent child relation with multiple join conditions	select distinct a.parent_id, b.child_id, b.child_value   from test1 a   left outer join test1 b                on a.parent_id = b.parent_id               and b.child_value = 'x' 	0.0144539342057979
11648641	9645	mysql using like with two variables in different tabel	select lg  from a, b  where a.id = 22 and         a.gr like concat('%', b.lg, '%'); 	0.294012833625757
11649615	22358	shredding xml into table with groups with t-sql	select      rn,     t2.entry.value('./@language','varchar(5)')  ,            t2.entry.value('./@text','varchar(50)')              from     (         select              row_number() over (order by rows.n) as rn,             rows.n.query('.') as trans               from @p.nodes('/root/translation') rows(n)     ) trans              cross apply trans.nodes('translation/entry') as t2(entry) 	0.0169284173503598
11650438	20409	replace select into statement with a cursor oracle	select max(q.id_liste_type_question) keep (dense_rank last order by q.some_date) into vintidlistetypequestion from   ceq_formulaires f join   ceq_liste_type_questions q on q.id_liste_type_formulaire = f.id_type_formulaire where  f.id_formulaire = to_number(out_rec.id_formulaire)  and    f.date_inactive is null and    q.webcode = 'item_beta_lactamase' 	0.710207063869459
11650793	25261	code igniter - one to many child join?	select a.id,a.name,sum(b.value) from    tablea a join tableb b on a.id=b.id group by a.id,a.name 	0.0461134552825289
11651467	35114	sql - combine multiple columns into one column with more rows	select ques, answer from t1 unpivot (     answer     for ques in (col1, col2, col3, col4) ) u 	0
11652091	11974	sql: get last (highest) record on each row from the other table (group by?)	select firstname + ' ' + lastname as fullname, yearlevelname from students s inner join (     select studentid, max(yearlevelid) as maxlevel     from levelsattained     group by studentid ) maxlevels on maxlevels.studentid = s.studentid inner join yearlevels y on y.yearlevelid = maxlevels.maxlevel 	0
11652187	11065	converting a xml variable to a resultset in sql server 2008	select t.n.value('(*[local-name(.)=sql:variable("@idname")])[1]', 'int') as [key],        t.n.query('*') as value from @xml.nodes('/row') as t(n) 	0.597333360041042
11654379	5332	combine two sql queries with a different status column in each	select *, 'required' as status from tblmain where where_1 union select *, 'optional' as status from tblmain where where_2 and id not in (select id from tblmain where where_1) 	0
11654773	28409	pre-fetching row counts before query - performance	select t.*, r.val from table t left outer join      ref r      on t.refid = r.refid 	0.58908880481907
11654843	25229	sql join statement to collect both user's friends' and user's messages	select      m.msg_id,      m.uid_fk,      m.message,      m.alert,      m.created,      m.uploads,      m.owner,      u.uid,      u.first_name,      u.last_name  from      users u      join messages m on m.uid_fk = u.uid where     u.uid = :uid     or u.uid in (         select f.friend_two         from friends f         where f.friend_one = :uid     ) order by m.created desc limit 10 	0.00272182591993514
11657221	11108	insert into - sql server query	select * into [dbo].[dest]  from openquery(linkedserver,'select * from source') 	0.261745939705613
11658620	37855	joining different values in columns, within the same table, into one row	select transaction, name, min(receipt), max(receipt) from t group by transaction, name 	0
11659340	37640	oracle - how to filter out duplicate rows without using group by	select projectid, versionid, modifiedattributeid, modifieddate, name from (select c.projectid, c.versionid, c.modifiedattributeid, c.modifieddate, v.name,              row_number() over (partition by c.projectid, c.versionid, c.modifiedattributeid, v.name                                 order by c.modifieddate desc) as seqnum       from tpm_projectchanges c inner join            tpm_projectversion v on c.projectid = v.projectid and c.versionid = v.versionid       where c.modifieddate between to_date('07/18/12', 'mm/dd/yy') and                                    to_date('07/25/12', 'mm/dd/yy')      ) t where seqnum = 1 	0.00447981990447147
11659425	31927	insert into command with columns	select col.column_name from     information_schema.columns col where      (col.table_schema = 'schema_name') and     (co.table_name = 'table_name') 	0.0327456490258888
11660482	36307	selecting sum across two tables for each user	select  users.*,          coalesce(sum(credit_purchase.coins) - sum(credit_spend.coins), 0)  from    users              left join credit_purchase                     on users.id = credit_purchase.user_id              left join credit_spend                      on users.id = credit_spend.user_id  group by users.id 	0
11660716	39017	trying to find "top n" but getting some errors with dates	select flavor, sum(purchase_count) as purchase_count_total from buy_history  where date >= concat(year(curdate()), '-' month(curdate()), '-1') group by flavor  order by sum(purchase_count) desc  limit 10; 	0.00060389801664913
11660802	11916	how to check if many-to-many-to-many... exist in table	select x.* from (select *       from a,b,c,d) as x left outer join j     on (x.a = j.a and         x.b = j.b and         x.c = j.c and         x.d = j.d) where j.a is null and       j.b is null and       j.c is null and       j.d is null 	0.0157417388848653
11662136	41148	how create mysql query that will show only before and after of one specific record?	select  a.id, a.color_name from  (    (       select  id, color_name from colors       where color_name <= 'red'       order by color_name desc       limit 2    )   union    (       select id, color_name from colors       where color_name > 'red'       order by color_name asc       limit 1    )  ) as a order by a.color_name 	0
11664574	7430	generate list of partition name	select  'p_partition_' || to_char(add_months(sysdate, level),'yyyymmdd')  || ' values less than ' || to_char(sysdate, 'yyyy-mm-dd')   from dual connect by level <= 12; 	0.0112769482829025
11665487	1625	sql query to select values for a current or specific month in a given date/time format	select * from table where date_format(date_field,'%m-%y') = '07-2012'; 	0
11666236	1210	join two tables without duplicates and with a mark	select p.id, p.contents, c.id,        if(c.id is not null, 1, 0) as isused from prefixes p      left join (select distinct id                 from click_links where id in(544,545...)                )c       on c.prefix_id = p.id; 	0.0115827052187626
11666988	3416	jpa named query search within a list	select g from groups g left join fetch g.users u where (g.users is empty or (u.id = :id)) 	0.285214499241623
11667712	38356	select randomly 3 rows equal number of times	select *  from table  order by display_count asc, rand()  limit 0,3; 	0
11672273	10250	sql select query for ranking	select l.iusername,  ((select count(1) from logs where iusername=l.iusername) -  (select count(1) from logs where ousername=l.iusername)) as rank   from logs l  group by l.iusername  order by rank asc 	0.530315896180495
11672428	13694	merge rows from cross referenced tables 	select ct.id ,  left(companyname.value('.','varchar(max)'), len(companyname.value('.','varchar(max)'))-1) as companyname  from      contract ct      cross apply      (      select cm.name + ',' [text()]     from      contractcompanycrossref cc      inner join company cm     on cc.companyid = cm.id       where ct.id = cc.contractid      for xml path (''),type     ) cmnames(companyname) 	0.00317224637720214
11672481	3782	difference between tables with the same structure	select * from table_a except select * from table_b 	0.000603657780007531
11674176	26479	php , mysql selecting row	select * from ads1 where state in ( 'romania' , 'germany' ) 	0.0071801628273507
11674772	4154	how to get distinct rows from sql	select * from marks_table a     where version = (select max(version) from                          marks_table where stud_id = a.stud_id); 	0.000190261914725765
11675265	17759	average a column returned from a subquery	select sum(`retail_subtotal`)/count(distinct lead_id) as avg from `order` where `status` in ('o') 	0.000752117221647202
11676006	4614	omit certain records in sql	select  * from    yourtable where   id not like 'z|_%' escape '|' or status = 'fail' 	0.000989460477845809
11677527	24823	pass value to derived table	select top 10 [docsvsys].[sid], [si].[count]  from docsvsys   cross apply  (      select count(*) as [count]         from docsvenum1 as [sit]      where  [sit].[sid] = [docsvsys].[sid]   ) as [si]   order by [docsvsys].[sid] 	0.0354377715162499
11679468	14387	mysql daily downloads counter	select sum(counter) from download_log where userid = 258 and date >= date_sub(now(), interval 24 hour); 	0.0986471900239518
11681021	699	how to do grouping of sets in sql server and filter records	select sales_order_id,datedifference,flag from @t where sales_order_id not in   (select sales_order_id from @t where flag=1) 	0.00318413667274966
11681556	39458	mysql one table inner join with 3 different entity tables	select e.email, r.table, c1.name as company_name, c2.name as contact_name from email_company_contact_ref r join email e on e.id = r.email_id left join company c1 on (c1.id = r.ref_id and r.table = 'company') left join contact c2 on (c2.id = r.ref_id and r.table = 'contact') group by r.table, e.email 	0.0219552101935423
11681809	17891	how can i get rows from one table that have a specific value or don't exist in another table that has a 1-1 relationship to the first?	select fruits from tbleatables where eatid   not in  (select eatbles_id where  edible_status = 1) 	0
11685186	15605	query codeigniter	select distinct user_id, count('user_id') from tbl_tickets_replies where user_id in     (select id from tbl_users where username in          (select username from tbl_tickets where site_referers_id =1)) group by user_id 	0.549997703850796
11685310	11644	mysql using inner joins on an alias of a calculated column	select user.id, 10*10 as distance  from users  inner join  (      select location.user_id,      min(10 * 10) as mindistance      from location      group by location.user_id   ) l on user.id = location.user_id and l.mindistance =10*10 	0.669564621077365
11687082	18	total count in grouped tsql query	select      data.equipmentid,     avg(measurevalue) as averagevalue,     count(*) as bincount,     count(*)/ cast (cnt as float) as bincountpercentage from (select *,         count(*) over() cnt  from multipletableswithjoins) data group by data.equipmentid, cnt 	0.00398316067732195
11687798	10230	compare current time with a time in a row using sql in mysql	select `hour`, class from your_table where time(`hour`) > curtime() and `day` = dayname(now()) order by time(`hour`) asc limit 1 	0
11688428	13654	mysql: return 2 different result together	select qe.id, qe.content, a.id, a.content, a.dt, acr.checked, acr.score   from `questions_and_exercises` qe,  `questions from-to` qft  left join `questions-answers` qa on (qa.qid=q.id and qa.uid=?)  left join answers a on (a.id=qa.aid)  and qft.to_lid=?  and qft.uid=? 	0.00304804526968842
11688486	13585	sql join: three tables, one of them is the relationship between the other two and rows may not exist	select prodname, price from products p left join sells s   on p.pid = s.pid left join competitors c   on s.cid = c.cid where c.cid = 1    or c.cid is null 	0
11691275	19061	sql: view full name from user id (send to / send from)	select      messageid,     (fromtable.firstname + ' ' + fromtable.lastname) as messagefrom,     (totable.fristname + ' ' + totable.lastname) as messageto,     subject from     messages     inner join     (         (select userid, firstname, lastname from students)         union          (select userid, firstname, lastname from employees)     ) as fromtable on fromtable.userid = messages.messagefrom     inner join     (         (select userid, firstname, lastname from students)         union          (select userid, firstname, lastname from employees)     ) as totable on totable.userid = messages.messageto 	0.000145523898027061
11692831	33605	mysql select data by relation of parameters	select * from projects inner join partners     on projects.partner1 = partners.partner1     and projects.partner2 = partners.partner2 	0.0735609767863135
11693131	29134	selecting the very last record of the returned table	select top(1)    tbl_acerpfssurveyivr.ntlogin,   tbl_acerpfssurveyivr.customer_firstname,   tbl_acerpfssurveyivr.customer_lastname,   tbl_acerpfssurveyivr.caseid,   tbl_acerpfssurveyivr.contactnumber,   crm_trn_order.order_price,   crm_trn_order.order_createddate from   tbl_acerpfssurveyivr join crm_trn_order     on tbl_acerpfssurveyivr.customerid = crm_trn_order.customerid order by   crm_trn_order.order_createddate desc 	0
11693214	38760	how i can assign the result of a query to multiple variables at once without use a cursor?	select @max =  max(field_name), @min = min(field_name) from table_name 	0.000829577627298226
11694761	656	select and display only duplicate records in mysql	select id, payer_email from paypal_ipn_orders where payer_email in (     select payer_email     from paypal_ipn_orders     group by payer_email     having count(id) > 1 ) 	0
11695175	7335	how to get a count via a subselect	select firstname, lastname, title,                (select count(1) from table where title=a.title) title_count  from table a; 	0.0199276101360802
11695195	33708	create a report of user's privileges	select iduser      , max(case when idmodule=1 then 1 else 0 end) as module1      , max(case when idmodule=2 then 1 else 0 end) as module2      , max(case when idmodule=3 then 1 else 0 end) as module3      , max(case when idmodule=4 then 1 else 0 end) as module4 from   your_table group by 1 	0.0196889621892626
11696557	33458	mysql count not correct	select b.cid, b.id,        sum(be.bookread) as readcount,        count(distinct case when be.bookread = 1 then be.userid end) as usercount,        sum(be.userdownload) as downloadcount,        count(distinct case when be.userdownload = 1 then be.userid end) as userdownloadcount from book as b inner join      book_event be      on be.bookid = s.id where b.cid = 1011 group by b.id, b.cid order by b.id desc 	0.731858832075894
11696792	33931	sql server query max and min	select min (pv) as minimumtemperature, max (pv) as maxtemp, year(datefield) as year, month(datefield) as month, day(datefield) as day from plexxium201.dbo.pv_history group by year(datefield), month(datefield), day(datefield) 	0.376841157408447
11697143	12334	sql - sum columns from same table having multiple unique ids	select id, sum(area1 + area2 + area3) as 'sum' from yourtable group by id 	0
11697619	18099	taking t-sql query into another query and find matches	select  data,  encrypteddata, convert(varchar, decryptbykey(encrypteddata)) as 'decrypteddata', count(distinct(decrypteddata)) from table where count (distinct(decrypteddata)) >1 group by data 	0.0049272393565087
11697796	28343	i have a database and along with multiple record of same date and related amount	select      cast(date as date),      sum(amt) as totamt from tablename group by cast(date as date) 	0
11699600	38913	fill month gaps	select date, product from ( select date,sum(orders.product) as product from orders  group by month(date),year(date) union  select datefield as date, '0' as product from calendar where (calendar.datefield between (select min(date(date)) from orders) and (select max(date(date)) from orders)) group by month(date),year(date) ) as a group by month(date),year(date) order by date 	0.00113594888520497
11700003	17688	a query to find average value for each ranges?	select floor(subdistance*1000)/5.0)*5.0 as lower_bound, avg(iri_avg) as avg_ari_avg from t group by floor(subdistance*1000)/5.0)*5.0 order by 1 	0
11700412	22519	i need to put amount '0' if the row exist but has no amount in my "where " conditions	select t1.aaa, coalesce(t2.bbb_count, 0) bbb_count,     coalesce(t2.ccc_sum, 0) ccc_sum from (   select distinct aaa   from nrb ) t1 left join (   select t.aaa, count (t.bbb) bbb_count, sum (t.ccc) ccc_sum   from nrb t   where t.vvv in  ('3','4','5','6','d','e','f')     and t.ddd like '50%'     and t.eee >= to_date('2012/03/21','yyyy/mm/dd')     and t.eee <= to_date('2012/07/21','yyyy/mm/dd')   group by t.aaa ) t2 on t1.aaa = t2.aaa order by t1.aaa; 	5.03712451001624e-05
11700546	9776	number of decimal digits in oracle sql developer query result sheet	select to_char(salary,'999999.000'), employee_id from employees; 	0.00609349778262228
11702247	37315	joining 3 tables sql join	select users.name as name,  reviews.review as review,  votes.vote as vote  from  users join reviews on users.email=reviews.user  left join votes on users.email=votes.user and reviews.entity = votes.entity where reviews.entity='entity_id' 	0.140042535305672
11707665	4957	date format in dd/mm/yyyy hh:mm:ss	select convert(varchar(10), getdate(), 103) + ' '  + convert(varchar(8), getdate(), 14) 	0.00533890192541975
11707693	21464	sql hierarchy query	select ppse.subordinate_position_id child_position_id            ,ppse.parent_position_id manger_position_id            ,b.person_id from per_pos_structure_elements_v ppse   ,apps.xxkpc_hr_personnel_v2_mv  b where b.position_id(+) = ppse.subordinate_position_id and b.type(+) = 'kpc employee' and ppse.pos_structure_version_id =64 and ppse.parent_position_id=12493 and  (b.person_id!=null or   ppse.subordinate_position_id in              (select subordinate_position_id from per_pos_structure_elements_v)) 	0.540634009858666
11707736	34562	sql groupby month	select        count(*) as expr1, name, month(appointment_date) as appointment_month from            reportingtable group by name, appointment_month 	0.0564100828667174
11707758	15915	select distinct combinations from two columns	select distinct            case              when source < destination then source              else destination            end as source,           case              when source > destination then source              else destination            end as destination from hyperlinks 	0
11708878	17505	get values from database where column is unique and add condition	select r.* from result r inner join (     select athelete_id, min(result_time) as fastesttime     from result     where event_code = 1     group by athelete_id ) rm on r.athelete_id = rm.athelete_id and r.result_time = rm.fastesttime 	0
11709046	22351	how to find whether an unordered itemset exists	select itemsetid, from (select coalesce(ps.itemid, is2i.itemid) as itemid, is2i.itemsetid,              max(case when ps.itemid is not null then 1 else 0 end) as inproposed,              max(case when is2i.itemid is not null then 1 else 0 end) as initemset       from proposedset ps full outer join            itemsets2items is2i            on ps.itemid = is2i.itemid       group by coalesce(ps.itemid, is2i.itemid), is2i.itemsetid      ) t group by itemsetid having min(inproposed) = 1 and min(initemset) = 1 	0.00321041552644122
11711019	3654	sql server t-sql xml with optional elements	select t.n.value('@x', 'int') as ea,        t.n.value('b[1]/@ysamename', 'int') as yb,        t.n.value('c[1]/@ysamename', 'int') as yc from @x.nodes('/root/a') as t(n) 	0.616013220563682
11713424	16121	order by before group by	select * from     (select * from post order by datotime desc) as inv     where fk_user_to = '$userid'     group by fk_user_from     order by datotime desc 	0.209837942405828
11714054	20707	sql expression to get names of friends	select relationship.requester, relationship.requested,         requester.firstname, requester.lastname,        requested.firstname, requested.lastname, from relationship left join user as requester on user.guid = relationship.requester  left join user as requested on user.guid = relationship.requested where relationship.requester = {$userid}   and relationship.approved = 1 	0.00105891360861233
11714711	35696	sql query between 3-tables of a many-to-many relationship	select  f.id, f.name, last_known_date, l.lat, l.lon from friends f join (     select  f.id, max(l.date) as last_known_date     from    friends f     join    friend_location fl on f.id = fl.friend_id     join    location l on l.id = fl.location_id     group by f.id ) flmax on flmax.id = f.id join friend_location fl on fl.friend_id = f.id join location l on fl.location_id = l.id and l.date = flmax.last_known_date 	0.0855325206475633
11715707	7252	find minimum score from 4 column of database	select least(t.column1, t.column2,t.column3,t.column4) as lowest                                                         from table_name t 	0
11716240	29840	join from muliple column to one table	select titleid,     b.description as description1,     c.description as description2,     d.description as description3,     e.description as description4,     f.description as description5 from genere a     left join generedesscription b         on a.genid1 = b.genid     left join generedesscription c         on a.genid2 = c.genid     left join generedesscription d         on a.genid3 = d.genid     left join generedesscription e         on a.genid4 = e.genid     left join generedesscription f         on a.genid5 = f.genid; 	0.00074919749112878
11716346	29288	can't get full result when joining the same table several times	select t1.offname as 'offname1', t2.offname as 'offname2', t3.offname as 'offname3',  t4.offname as 'offname4', t5.offname as 'offname5', t6.offname as 'offname6', t7.offname as 'offname7' from as_addrobj_29 t1 left join as_addrobj_29 t2 on t1.parentguid = t2.aoguid and t1.parentguid not null left join as_addrobj_29 t3 on t2.parentguid = t3.aoguid and t2.parentguid not null left join as_addrobj_29 t4 on t3.parentguid = t4.aoguid and t3.parentguid not null left join as_addrobj_29 t5 on t4.parentguid = t5.aoguid and t4.parentguid not null left join as_addrobj_29 t6 on t5.parentguid = t6.aoguid and t5.parentguid not null left join as_addrobj_29 t7 on t6.parentguid = t7.aoguid and t6.parentguid not null where t1.offname like "smth%" 	0.000548041717961154
11716956	14393	sql query to fetch data even if conditon not satisfied	select      img.path as path, pav.value_text as beds, post.post_id as postid  from      postings post      inner join post_attributes_values pav on post.post_id = pav.post_id and pav.attr_id='33'      left outer join images img on post.post_id = img.post_id and  img.sequence='1'  where  post.status !='expired' and post.post_id=49 	0.287524490964255
11719096	15733	get id of the rows which were updated by query	select id from user where area like '%abc road%' 	0
11719703	38619	how to write mysql scipt to filter data for a given datetime without second?	select distinct count(*), date_format(created, '%y-%m-%d') as my_date from your_table     [where date_format(created, '%y-%m-%d') = <date needed>] 	0.000397763556459878
11720361	13831	mysql statement to select names that start with specific range of characters	select name from db.table where name regexp '^[c-e].+'; 	0
11720774	38612	selecting male and female seats based on age	select        booking_id       , sum(case when gender_id = 24 and passenger_age > 11 then 1 else 0 end) adult_male       , sum(case when gender_id = 25 and passenger_age > 11 then 1 else 0 end) adult_female       , sum(case when gender_id = 24 and passenger_age <= 11 then 1 else 0 end) child_male       , sum(case when gender_id = 24 and passenger_age <= 11 then 1 else 0 end) child_female from passenger_information group by booking_id 	0.000756963969470765
11721491	34326	id for max value	select id, uid from table1 where a=(select max(a) from table1) 	0.00242180098265058
11722259	36705	how to get data from two different tables using storeprocedures?	select b.bugid     , b.title     , b.projectname     , b.createdby     , e.employeename as assignedto     , bh.tostatus from bugs b inner join bughistory bh     on b.bugid = bh.bugid inner join employee e     on bh.assignedto = e.employeeid 	0
11723204	2025	and multiple values like in clause	select car from your_table where feature in ('f1', 'f2') group by car having count(distinct feature) >= 2 	0.495774922894544
11723443	32912	mysql query to match date and null between two tables	select s.student_id, s.student_firstname, s.student_lastname, a.student_absence_startdate, a.student_absence_enddate, a.student_absence_type from students s  left join  (select * from studentabsence a1 where ('2012-07-30' between a1.student_absence_startdate and a1.student_absence_enddate) ) a  on a.student_id = s.student_id 	0.00114895788487824
11723449	27050	finding duplicate names sql	select organization.name, count(organization.id)   from organization  where organization.approved=0    and organization.created_at>'2010-07-30 10:30:21'  group by name having count(organization.id) > 1; 	0.00145291768699762
11725165	2190	ignore #,\,/, uppercase,$ in mysql select query	select   account_name  from   dba_account  where    cast(account_name  as binary) rlike '[a-z]'    and account_name not rlike '[#$\\\\/]' limit 50; 	0.315608096606662
11725262	15049	fetch timestamped counts from multiple tables	select created, type from (    select created, type    from node where status = 1    union all    select timestamp as created, 'forum_comment' as type    from comments    inner join node on comments.nid = node.nid    where node.type = 'forum'      and comments.status = 1 ) as u order by u.created 	0.000531131405525775
11726890	18725	union 2 tables and set value based on source of data	select personid     , personfirstname     , personlastname     , 'person' as yourcolname from dbo.person union all select adminid as personsid     , adminfirstname as personsfirstname     , adminlastname as       personslastname     , 'admin' as yourcolname from dbo.useradmins 	0
11728132	1964	how do i cast enums to their integer values when selecting into an outfile in mysql?	select ..., enum_field+0, ... 	0.00145582123619006
11730387	206	finding the differences in two tables	select * from table_a where name not in     ( select name from table_b ) 	0.000185955161038365
11731241	9858	mysql data statistics	select     category,     if(date_sub(curdate(), interval 16 hour) <= datez, sum(1), 0) as c16hours,     if(date_sub(curdate(), interval 1 day) <= datez, sum(1), 0) as c1day,     if(date_sub(curdate(), interval 30 days) <= datez, sum(1), 0) as c30days,     (...) from tickets  group by category 	0.0861647824229856
11731653	30092	select all records that are not wednesday and are only 30 days old	select * from mytable where date >= curdate() - interval 30 day and       weekday(date) <> 2 	0
11731655	24113	how to do a count on a union query	select count(*) from (     select distinct profile_id      from userprofile_...     union all     select distinct profile_id      from productions_... ) x 	0.0924040214885151
11732903	6943	how to select last date in 2 record in mysql	select b.id, a.name, b.title, b.sid, b.datea  from tablea a left outer join    (( select sid, max(datea) as latest          from tableb           where title is not null            group by sid) as dt inner join tableb b  on b.sid= dt.sid  and b.datea=dt.latest ) on a.sid=b.sid 	0
11734272	32053	getting row sum of the table	select date,        col1 + col2 + col3 as total,        col1, col2, col3   from your_table; 	0.000322716611055775
11734349	15870	how do we select multiple columns in a sum()/group by query?	select a.[vendor name], [vendor no], [item no], [item description],  [item cost], [quantity],b.total  from [salesdb] a   inner join     (select [vendor name], sum([quantity]) as total     from [salesdb]     where [vendor no] in (1,2,3,4,5,6,7,8)      and [item description] = 'bolts'     group by [vendor name])b   on a.[vendor name]=b.[vendor name] 	0.040029117890158
11736228	40508	query to make group of records	select name, max(colb), max(colm), max(colp) from table group by name 	0.0338549080204406
11736854	34515	mysql select record containing highest value, joining on range of columns containing nulls	select     rate.*,     newest.id from rate     left join rate as newest on(         coalesce(rate.client_company,1) = coalesce(newest.client_company,1)         and coalesce(rate.client_contact,1) = coalesce(newest.client_contact,1)         and coalesce(rate.client_group,1) = coalesce(newest.client_group,1)         and coalesce(rate.role,1) = coalesce(newest.role,1)         and newest.date_from > rate.date_from     ) where newest.id is null 	0
11737499	1266	mysql - selecting rows that dont match a date range?	select * from table where [todaysdate]<datestart or [todaysdate]>dateend 	0
11737820	27245	how to return mutiple records from a join as columns?	select   re.day,  re.flashcardsadded,  re.flashcardstested,  re.flashcardslearned,  re.totalpoints as totalforday,  sum(case la.language when 'french' then  la.total else 0 end) as french,  sum(case la.language when 'german' then  la.total else 0 end) as german,  sum(case la.language when 'italian' then  la.total else 0 end) as italian,  sum(case la.language when 'russian' then  la.total else 0 end) as russian from dpod_site_reportdays as re  join dpod_site_reportdaylanguagetotals as la on re.day=la.day group by re.day,  re.flashcardsadded,  re.flashcardstested,  re.flashcardslearned,  re.totalpoints order by re.day desc 	0.000102997588827851
11738083	31012	sql - if a value equals a certain number then the amount of rows should equal that certain number	select t.name from test12 t join master..spt_values m on t.number>m.number where type='p' 	0
11740258	4399	mysql - 1:n relationship	select * from tablea as a left join tableb as b on a.id = b.a_id; 	0.199146753167831
11740458	765	sql, get the average on a group while escaping the where condition	select      avg(tyd.price) as avg_price, count(tyd.id_product) as cnt_id_p,     catalog.id_marchand, catalog.id_product, catalog.price as c_price,      catalog.img_src, tyd.login as tyd_l from catalog  inner join tyd on catalog.id_marchand = tyd.id_marchand                and catalog.id_product =   tyd.id_product               and tyd.step = "0"  group by catalog.id_product, catalog.id_marchand having tyd.login = "user1@tyd.fr" 	0.00205018851396222
11740506	36719	how to create parent child relation in query?	select t.id       ,t.parentid   from table_name t  start with t.parentid = 0 connect by prior t.id = t.parentid 	0.00795152978630766
11740881	11187	fetch mysql information based on column value	select firstname from users where email='$email' order by id asc limit 1 	0
11741467	30674	oracle - select * where column>5	select * from table where column > '5' 	0.795436680830269
11743029	2610	select several averages of an interval	select avg(`value`) from `table` where timestamp >= now() - interval 7 day and timestamp <= now() group by concat(date(`timestamp`), case when hour(`timestamp`) between 0 and 7 then 1                                         when hour(`timestamp`) between 8 and 15 then 2                                         else 3 end) 	0.00225653319248082
11745290	3442	how to get aggregate result without changing number of results sql	select  serial_number,      daq.qtag_no,      min(toh.start_time),      order_number,      daq.creation_time,      qtag_status,      ar_code,      pro_foundin,      pro_category,      root_cause,      remark  from unit u  left  join    work_order wo      on  wo.order_key = u.order_key left  join    tracked_object_history toh      on  toh.tobj_key = u.unit_key     and toh.op_name = 'assembly' where   u.creation_time > '01/01/2012' and u.creation_time < '07/20/2012' and     order_number not like '[r]%'  group by serial_number, qtag_no, order_number, daq.creation_time, qtag_status, ar_code, pro_foundin, pro_category, root_cause, remark order by serial_number 	0.000848501862727587
11746613	555	1 to many > 1 to many grouping/sub queries	select  order_id, sum( price_paid       * ordered_qty       + ifnull((select sum(option_cost)            from order_line_options olo          where olo.order_line_id = order_lines.order_line_id),0) ), group_concat(   concat(product_code,    ' (',    (select group_concat(           concat(option_name, ': ',                  option_value, ', '                  option_cost                  )           separator '-'           )      from order_line_options olo     where olo.order_line_id = order_lines.order_line_id     group by olo.order_line_id    ),    ')'   )    separator ' / ' )  from orders join  order_lines using (order_id) where   date_format(order_date, '%y%m') >= '201203' and date_format(order_date, '%y%m') <=   '201203' and order_status = 'shipped' and item_status = 'lineshipped' group by order_id  order by order_id 	0.0889594144538095
11748697	26391	sql query: how to list joined values on the same row	select list.id, list.activation_date, list_fieldj.value,list_fieldc.value  from listings as list  inner join listings_fields as list_fieldj on list.id = list_fieldj.id      and list_fieldj = 'title'  inner join listings_fields as list_fieldc on list.id = list_fieldc.id      and list_fieldc = 'category'  where list.activation_date > some value  order by list.activation_date desc 	0
11750058	27195	how to make this sql query using in (with many numeric ids) more efficient?	select respondentid, min(sessionid) as 'sid'  from big_sessions (nolock)      inner join respondentsfiltertable          on big_sessions.respondentid = respondentsfiltertable.respondentid where entrydate between '07-11-2011' and '07-31-2012'  group by big_sessions.respondentid 	0.688116581369144
11750889	38164	how can i get max sum in table with mysql	select objid, sum(rating) as totalrating from objecttable group by objid order by sum(rating) desc limit 3 	0.00491307332993608
11751065	17932	how to select 2 sub records using mysql?	select u2.* from users u1 join users u2 on u2.user_id in (u1.left_id, u1.right_id) where u1.user_id  = 1 	0.0135307928136311
11751567	15830	can't do sum of sum?	select d.itemid1 as item,         sum(d.sum + d.count*h.sumliked)/sum(d.count) as ratingvalue from (select h.userid, h.itemid, sum(h.liked) as sumliked       from history h       group by h.userid, h.itemid      ) h join      dev d       on h.userid=:id_user and         d.itemid1<>h.itemid and        d.itemid2=h.itemid  group by d.itemid1 	0.198232325546298
11751855	14589	suppress result from insert trigger	select * from #inserted 	0.10624571334928
11753873	39213	postgresql: random value for a column selected frm second table	select     drivers.driver_id as drivers_driver_id,     (         select             drivers_names.name_en         from             drivers_names         order by random()+drivers.driver_id limit 1     ) as driver_name from     drivers 	0
11756098	17017	sqlite query to convert string to date in sqlite?	select column from table where columndate between '2012-07-01' and '2012-07-07' 	0.069823756138718
11756940	25727	mysql concatenate 2 calulcated fields into 1 column?	select concat(sum(month(b.casedate) = 1), '-',        sum(if(month(b.casedate) = 1, b.casecommission, 0)) ) as january; 	0.000102955368471821
11758721	26023	how to read mysql time?	select from_unixtime(1343821692) select unix_timestamp('2012-08-01 13:41:1'); 	0.223607254118329
11762052	31387	sql server - how to modify values in a query statement?	select a.lastname,a.firstname,a.email,b.floornumber  from employee a join floor b on a.floorid = b.id where a.locationid=1 and (a.statusid=1 or a.statusid=3)  order by a.floorid,a.lastname,a.firstname,a.email 	0.360508108572346
11764064	10784	oracle sql assign consecutive numbers to a subset based on column values	select id_1, id_2, seq, the_group       ,case when (start_count - end_count) > 0 or (start_count = end_count and the_group = 'end')             then start_count             else null        end as group_seq   from ( select id_1, id_2, seq, the_group                ,sum( case when the_group = 'start' then 1 else 0 end )                   over( partition by id_1 order by id_1, seq ) as start_count                ,sum( case when the_group = 'end' then 1 else 0 end )                   over( partition by id_1 order by id_1, seq ) as end_count            from mytable )   order by id_1, seq 	0
11765352	27045	suggest sql query to retrieve all leaf nodes from adjacency list model	select group_concat(lev0) from  (select concat_ws(',',lev2,group_concat(lev3)) as lev0 from  (select  t2.id as lev2,  t3.id as lev3,  t4.id as lev4 from menus as t1 left join menus as t2 on t2.parent_id = t1.id left join menus as t3 on t3.parent_id = t2.id left join menus as t4 on t4.parent_id = t3.id where t1.id = '2') t0 group by lev2) t; 	0.000821864467499625
11767810	11322	subcount's as fields in a mysql query	select sum(js_enabled=1),        sum(flash_enabled=1),        sum(non_binary_field='yes') from your_table where `os` = 'w7' and date(`date_time`) = '2012-08-01' 	0.326213018158528
11769172	17489	find column dependency	select  object_name(k.parent_object_id) as parenttable           , c1.name as parentcolumn           , object_name(k.referenced_object_id) as referencedtable           , c2.name as referencedcolumn     from    sys.foreign_keys k             inner join sys.foreign_key_columns f               on  f.parent_object_id = k.parent_object_id             inner join sys.columns c1               on  c1.column_id = f.parent_column_id               and c1.object_id = k.parent_object_id             inner join sys.columns c2               on  c2.column_id = f.referenced_column_id               and c2.object_id = k.referenced_object_id     where   c2.name = 'xxx'     and     object_name(k.referenced_object_id) = 'zzz' 	0.0189728614088001
11769663	24660	how to search multple database entries by 2 columns	select * from ticketdetails as t1 inner join ticketdetails as t2 on t1.ticket = t2.ticket where t1.description='bogo' and t2.description='$5 off' 	0.000154785848381214
11769755	33357	comparing two views	select  * from    oldview o         left join newview n           on  o.field = n.field where   n.value is null 	0.0236146846080296
11770264	14341	how to compare two tables in mysql and php?	select a.*,b.* ,case when b.clientid is not null         then 'found'        else 'not found' end as vipexists  from clients a left outer join vipclients b on a.clientid=b.clientid 	0.00184217067156814
11772722	39531	find rank of a student in a table that its contained students point	select * from (select username ,average,[fname],[lname],point,   rank() over(order by point desc) as  'ranking'   from karbar order by point desc) t where username=@username 	0
11773418	14783	making sql more efficiency by making two queries into one instead of having a loop	select sum(correct_answers) as total_correct_answers from `juegos_sesiones_detalle` d inner join  `juegos_sesiones` s on s.`sesionid` = d.`sesionid` where  `usuarioid` = $_session['mm_userid'] 	0.0326868450330214
11774087	32642	linking and extracting records in mysql	select     action,     date,     user,     location,     refnumber from     yourtable order by     refnumber,     action 	0.00101461767939433
11774870	24647	how to find out defragment index pages in sql server 2008 using script?	select object_id, index_id, avg_fragmentation_in_percent, page_count from sys.dm_db_index_physical_stats(db_id('adventureworks'),  object_id('humanresources.employee'), null, null, null) 	0.746604110100473
11775186	23964	mysql union query, joining results with names	select     (select  count(id) as rank1 from `db_ranking` where `sid`=2 and `rank`=1) as rank1,     (select  count(id) as rank2  from `db_ranking` where `sid`=2 and `rank`=2) as rank2,     (select  count(id) as rank3  from `db_ranking` where `sid`=2 and `rank`=3) as rank3,     (select   count(id)  as rank4  from `db_ranking` where `sid`=2 and `rank`=4) as rank4,     (select count(id) as rank5 from `db_ranking` where `sid`=2 and `rank`=5) as rank5     from dual 	0.103007845378187
11775585	9591	how to select most recent data in my table?	select *  from am_history  order by id desc  limit 10; 	0.00027561329090913
11776338	13717	sql - multiple counts as appended columns	select e.owner as 'owner',         count(l.enquiryid) as 'total sales lines',        sum(case when l.loststatusid = 2 then 1 end) totalsold,        sum(case when l.loststatusid = 3 then 1 end) totallost   from daybookquotelines l  inner join daybookenquiries e     on l.enquiryid = e.enquiryid  where month(e.enquirydate) = 8     and year(e.enquirydate) = 2012   group by e.owner 	0.0244144486895939
11779402	32678	what is the sqlite sql statement to find todays records only?	select * from alarms where alarmstate in (0,1,2)   and alarmpriority in (0,1,2,3,4)   and alarmgroup in (0,1,2,3,4,5,6,7)   and alarmtime like "2012/08/01%"   order by alarmtime desc 	0.0012270548239949
11779743	2369	join mysql tables: display all results from right table in one row of left table	select person.*, (     select group_concat(attribute separator ',')     from attribute     where person.id = attribute.person_id ) as attributes from `person` 	0
11782439	17625	how to combine select sql subquerys with rand?	select r.*, c.url, (select p.name from photo p where p.concertid = r.curid order by rand() limit 1) as photoname from  (select galleryid, addeddate,(select concertid from concert c where c.galleryid = g.galleryid order by rand() limit 1) as curid from gallery g order by addeddate desc limit 8) as r join concert c on r.curid = c.concertid 	0.394917686826296
11783343	39539	display records from two tables side by side matching only some of the fields	select a.*, b.* from (     select customer_id, product, dateofsale, paymeth1, paymeth2, sum(qty) as qty     from tablea     group by customer_id, product, dateofsale, paymeth1, paymeth2 ) a join (     select customer_id, product, dateofsale, paymeth1, paymeth2, sum(qty) as qty     from tableb     group by customer_id, product, dateofsale, paymeth1, paymeth2 ) b  on a.customer_id = b.customer_id 	0
11783444	21849	selecting unique values from more arrays	select distinct country from blahs where country is not null order by country 	6.07582581631721e-05
11783608	10923	table design for user selectable schedule and select using pivot	select * from (     select empnum,         reason,         datepart(dw, start) as dyofwk     from #schedule ) s pivot (     max(reason)     for dyofwk in ([1], [2], [3], [4], [5], [6], [7]) ) as pvt 	0.514042551430967
11784316	2587	how to add a counter to a recurring dataset in sql?	select id,         name,         class,        row_number() over (partition by class order by id) as i_need,        count(*) over (partition by class) as cnt from the_table order by id 	0.0156729734764539
11784427	25475	selecting rows based on data from two tables	select cars.* from cars join ids on cars.id = ids.car_id 	0
11786011	17917	group sql server results by similar date	select   *  from     tablea a1          inner join tablea a2            on  a1.patientid = a2.patientid            and a2.textvaluecolumn = 'abnormal' where    a1.textvaluecolumn = 'screening' and      datediff(wk, a1.date, a2.date) = 1 	0.140187960157223
11787622	3221	mysql: get the total query number after grouping and counting	select count(*) totalcount from (     select count(*) c , id      from hr      where  time >= '2011-11-8 00:00:00' and             time <= '2011-12-9 23:59:59'      group by id      having count(*) > 3 ) x 	0
11787671	24184	how to retrive the last inserted id using mysql?	select event.event_name, restaurants.res_name  from event_choices inner join restaurants on event_choices.res_id = restaurants.res_id inner join event on event_choices.event_id = event.event_id  where event.event_id = (select max(event_id) from event) 	0
11788612	14564	sql xml parsing nodes	select t.o.value('@id', 'int') sid,        a.o.value('@aid', 'int') as aid  from @xml.nodes('/data/surveys/survey')as t(o)   cross apply t.o.nodes('answers/answer') as a(o) 	0.285995425815828
11788878	34267	set one var with 2 elements in select	select count(page_id)     from (     select page_id, max(rating_time)     from ranks_update     where ranking_id = new.ranking_id         and page_id <> new.page_id          and current_sum_vote >= @current_sum_vote         and rating_time >= (*** a subquery ***)      group by page_id     ) ru 	0.00111456721721893
11792464	8141	join of two select in sql in two columns	select text, a.cnt, b.cnt from (select text, count(*) cnt from xxxxx main inner join xxxxxx on xxxxx where status = a group xxxxx) a join (select text, count(*) cnt from xxxxx main inner join xxxxxx on xxxxx where status = b group xxxxx) b using text order xxxxx 	0.00083914325136624
11792836	15952	sql server : concatenate year and month	select cast(year(mydate) as char(4))+'/'+cast(month(mydate) as varchar(2)) from mytable group by year(mydate),month(mydate) 	0.000231078838806399
11793152	20911	compare two sql server tables	select table2.id, table2.name, table2.dob from table2 left outer join table1 on table2.name = table1.name and table2.dob = table1.dob where table1.id is null 	0.00965962308275713
11793970	30484	selecting item from columns in two different tables	select  ta.cat_name, sum(tb.cat_price) as price  from tablea ta inner join tableb tb   on ta.cat_id=tb.cat_id group by ta.cat_id 	0
11794182	27078	get records which were not updated the day before	select     aboproducts.asin, aboproducts.sku from       dbo.aboproducts  where aboproducts.asin  not in(      select aboproducts.asin       from       dbo.aboproducts       inner join                 dbo.lowestprices       on aboproducts.asin = lowestprices.productasin      where     (lowestprices.pricedate >= dateadd(day, - 1, getdate()))  ) 	0
11794242	4180	oracle select with subquery	select "news"."newsid" as id,    "news"."slug",    "news_translation".*,     (select * from (select filename from news_media where newsid = id order by position asc) and rownum = 1) as filename from "news"  inner join "news_translation" on news.newsid = news_translation.newsid  where (news.publish = 1) and (news_translation.lang = :lang)  order by "news"."newsid" desc; 	0.774255046652579
11794950	35207	mysql 4 table query posts with images always at the top	select   p.media, f.title from   posts p inner join   folder_posts fp   on   fp.postid=p.id inner join   folder_users fu   on   fu.id=fp.folderid inner join   folder f   on    f.id=fu.folderid and f.userid='loged_user_id' where p.media is not null group by p.id order by f.date 	0.000685583268300998
11795487	9371	mysql and foreign key relationships over multiple tables	select * from subjects s join events e1 on e1.subject_id = s.id join events e2 on e2.subject_id = s.id and e1.id != e2.id join assessment1 a1 on a1.event_id = e1.id join assessment2 a2 on a2.event_id = e2.id 	0.00155098807525024
11795547	15941	if value contains these letters, then	select case when col1 like '%http%' then '<a>' + col1 + '</a>' else '<b>' + col1 + '</b>' end as 'desired column name', col2 from table 	0.00175097818552382
11798478	9941	return empty string if string is 0 in sql	select    case name when '0' then '' else name end as "cname"  from dba 	0.0554878817429257
11799824	79	prevent from double/triple suming when joining	select sum(p.sumpaidamount) as sumpaidamount, sum(p.sumcopay) as sumcopay,        p.pmt_date, d.load_date, p.accn_id from  (select accn_id, p.pmt_date, sum(paid_amt) as sumpaidamt,               sum(copay_amt) as sumcopay        from accn_payments p        where p.posted='y' and              p.pmt_date between '20120701' and '20120731'        group by accn_id, pmt_date       ) p join       (select distinct load_date, accn_id from accn_demographics) d       on p.accn_id=d.accn_id group by p.pmt_date, d.load_date,p.accn_id order by 3 desc 	0.232061842425368
11800484	24115	search approach for location based search	select location.name, location.lat, location.lon, …     from locations, cities    where location.city = city.id      and city.name = ?      and location.tag = ? order by pow((location.lat - ?), 2) + pow((location.lon - ?)*city.geoaspect, 2) 	0.0215000807762425
11800915	6990	further group by count	select usercount, count(*) as usercountcount from (     select count(installuserid) as usercount     from installusers     group by installationid ) as t1 group by usercount order by usercount 	0.330818592014116
11800934	25074	stripping when selecting	select * from avail_students  where lastplayed < now()  and not exists (     select * from students_playing     where left( students_playing.name, 5 ) = left( avail_students.name, 5 ) ) 	0.105804312003237
11803700	11053	mysql query group by where condition limit 1	select max(id), writer_id, title, text from articles group by writer_id; 	0.574914950102607
11803736	5628	mysql increment user variable when value changes	select      (case when @date <> date then @row := @row +1 else @row end) as rownum,      @date:= date,      date from ( select @row := 0, @date := now() ) r, stats 	0.0138716067992661
11804160	10313	mysql query to average distinct items in a group	select     state,     convert(datetime, avg(averagedate)) as averagedate,     sum(itemcount) as [item count],     avg(px) as px from (     select         state,         item,         count(*) as itemcount,         avg(cast(date as int)) as averagedate,         avg(px) as px     from sales     group by         state,         item ) group by state; 	0.00109328656268051
11804172	37722	remove duplicate rows on a sql query	select distinct item from mytable where something = 3 	0.0023869238328353
11805166	1463	how to return distinct domain names from email address values in mysql?	select substring_index(user_email,'@',-1) as domain_name from user_email group by domain_name 	0
11807439	35311	query max on a join	select max(messagenumber) from article left join newsgroup on article.newsgroup_id=newsgroup.id  where newsgroup.newsgroup = "gwene.com.economist" 	0.266122622622423
11807447	25535	display only uncategorised item in 1 mysql query	select i.* from items i left outer join category c on i.sub = c.id where c.id is null 	0.000213970402608989
11807843	13911	select common value from two similar columns	select     player,     count(player) as count from (     select homepom as player     from matches     where homepom is not null and homepom != '' and league_id = xxx and other_things     union all     select awaypom as player     from matches     where awaypom is not null and awaypom != '' and league_id = xxx and other_things ) as players group by player order by count desc  limit 5 	0
11808100	20223	multiple query into one?	select * from `result` where status = 'new' and year(`end_date`)  = '2012' limit 20 union select * from `result` where status = 'new' and year(`end_date`)  = '2013' limit 20 union select * from `result` where status = 'new' and year(`end_date`)  = '2014' limit 20 union select * from `result` where status = 'new' and year(`end_date`)  = '2015' limit 20 union select * from `result` where status = 'new' and day(`end_date`)  = '1' limit 20 union  select * from `result` where status = 'new' and day(`end_date`)  = '2' limit 20 order by submit_date desc 	0.0135087663180995
11810125	8145	mysql - total of parent + child categories	select          tmp1.id, tmp1.name, tmp1.parent_id, tmp1.total, tmp1.total + tmp2.s as parenttotal    from    (select         ca.id, ca.name, ca.parent_id, sum(tr.amount) as total    from         transactions tr    inner join         categories ca    on         tr.categoru_id = ca.id     group by         ca.id)as tmp1         left outer join     (    select      c.parent_id as categoryid, sum(t.amount) as s      from       transactions t    inner join       categories c    on       t.category_id = c.i    group         by c.id ) as tmp2    on        tmp2.categoryid = tmp.id 	0
11810298	34879	how do you get data from two relational tables without a 1:1 relationship? - mysql	select   group_concat(d.domain) as domains,   c.* from core c join domains d   on d.cid = c.id where c.id = 1 group by c.id 	8.82397715349115e-05
11810375	20564	mysql syntax for join depending on condition	select   * from     (               select    a.id as table1id, a.type, b.id, b.title, b.language, null as flag          from      table1 a          join      table2 b on a.id = b.table1id          union all          select    a.id, a.type, c.id, c.title, c.language, c.flag          from      table1 a          left join table2 b on a.id = b.table1id          join      table3 c on a.id = c.table1id          join      (                    select   max(id) as maxid                    from     table3                    group by table1id                    ) d on c.id = d.maxid          where     b.id is null          ) a order by a.table1id 	0.432006854420433
11812215	10859	mysql - select most recent date out of a set of several possible timestamps?	select id, timestamp from updates order by timestamp desc limit 1 	0
11814853	10382	comparing date in access sql query	select * from bookingmaster where journeydate = #2012/08/01#; 	0.251630268767255
11815037	40806	display all parent records except those having 4 child records	select   employee.* from     employee left join donation using (employee_id) group by employee_id having   count(*) < 4 	0
11815861	39177	mysql best way to get result	select posts.*, group_concat(cats.name) as cats, group_concat(tags.name) as tags from   posts   left join linked_data on linked_data.r1 = posts.id   left join cats        on linked_data.r2 =  cats.id and linked_data.name = 'cat'   left join tags        on linked_data.r2 =  tags.id and linked_data.name = 'tag' group by posts.id 	0.030323741157105
11816108	21671	in mysql can i write a query to find if a given month has any dates between two dates?	select id from mytable  where start_date <= '2012-03-31'  and end_date >= '2012-03-01' 	0
11816528	25899	get users which are not stated in the query	select      c.name,      c.level,      c.sex,      c.playtime,      c.killcount,      c.deathcount,     coalesce( cl.name, ' - ' ) as clanname from      character as c            inner join       account as a            on c.accountid = a.accountid           left outer join      clanmember as cm            on c.characterid = cm.characterid           left outer join      clan as cl           on cm.clanid = cl.clanid where      a.userid='".mssq ... 	0.00232584883486828
11817253	27248	rows order in sqlite database (ios)	select rowname from tablename order by rowname 	0.0857684034994605
11818198	15498	listing matched and unmatched records in a database	select        t1.store_number, t1.invoice_number, t1.invoice_date, t1.vehicle_tag, t1.void_reason, t1.void_employee_tax_payer_id, t1.invoice_total, t1.void_flag,                           t2.invoice_number as expr1, t2.vehicle_tag as expr2, t2.invoice_total as expr3, case when t2.vehicle_tag is null then 'n' else 'y' end as retendered from            invoice_tb as t1 left join                          invoice_tb as t2 on t1.vehicle_tag = t2.vehicle_tag and                          (t2.void_flag = 'n') and (t2.invoice_date between convert(datetime, '2012-08-01 00:00:00', 102) and convert(datetime, '2012-08-02 00:00:00', 102)) where        (t1.void_flag = 'y') and (t1.invoice_date between convert(datetime, '2012-08-01 00:00:00', 102) and convert(datetime, '2012-08-02 00:00:00', 102)) 	0.00253713353001431
11819077	39425	select a time between two times range	select *  from geocoord  where id="3574"  and starttime < time_format("00:00:00","%h:%i:%s")  and endtime > time_format("05:00:00","%h:%i:%s") 	0
11819640	24559	selecting from mysql table using an expression	select b.*  from bubbles b    join bubble_types bt     on b.type = bt.type where    (b.city = 10 and b.type = 'golden')   or    (bt.category = 'charm' and bt.type = b.type); 	0.0371083712783936
11820108	28907	how do i list entries in sqlite by the order they were added?	select * from transactions order by transactiondate desc, rowid desc; 	0
11820492	7568	mysql - show results only if both tables have entries	select distinct [list of columns]   from tracking, files   where tracking.track_id = files.track_id  and         tracking.archived = '0' and approved = '0'  order by tracking.po_number; 	0
11822876	1953	sql query using table aliases	select c1.name, c1.country, c2.name, c2.country  from city c1, city c2 where c1.country < c2.country 	0.741249276397672
11824501	27057	inner joining three tables	select * from     tablea a         inner join     tableb b         on a.common = b.common         inner join      tablec c         on b.common = c.common 	0.188785921301538
11825158	19986	sum of specific values in sql	select sum(v) from ( select *  from  (select * from yourtable) u unpivot ( r for co in (co1, co2, co3)) as u1 unpivot (  v for va in (va1, va2, va3)) as u2 where right(co,1) = right(va,1) ) v where r = 'aa1'  	0.00246234217649853
11825345	6330	sqlite : limit on a left join	select tnode.node, ..., titem2.itemname, titem2.itempriority from tnode left join   (select itemname,min(itempriority) as min_priority from titem group by titem.node) as titem2 on titem2.node=tnode.node order by tnode.node 	0.766551396678846
11825474	10524	sum across joined tables	select user_id,created_at,sum(accamount) from ( select a.id account_id,a.user_id user_id, dt.created_at created_at, ( select amount from balances b3 where (b3.account_id=a.id) and b3.created_at= (select max(created_at) as lastaccdate from balances b where b.created_at<=dt.created_at and b.account_id=a.id) ) accamount from accounts a, (select distinct created_at from balances) dt ) accountamounts group by user_id,created_at order by 2 	0.00837527159862597
11825553	17566	merge row values from separate tables into one column. [sql]	select package, sum(licences) as totallicences   from (         select package, licences from table1          union all         select package, licences from table2          union all         select package, licences from table3        ) as alllicences  group by package 	0
11825681	18535	finding a related entity which matches one field	select count(id) as campaign_count, campaign_id from campaignregion where (city_id = 32076 or district_id = 127 or state_id = 7 or country_id = 156) group by campaign_id having campaign_count > 0; order by (city_id = 32076) desc, (country_id = 156) desc, (state_id = 7) desc, (district_id = 127) desc; 	9.07102801203188e-05
11826940	7851	apex hightlight row according to column comparison	select a.phone, b.phone       ,case when a.phone = b.phone then 1 else 0 end as match   from a, b   where a.id = b.id 	0.0083926902545403
11827333	16496	how can i use a single sql string to create a data-set from multiple tables in c#?	select assignments.task_no, assignments.assignment_no, assignments.assignment_date,  task_information.client_name, emp_information.f_name, emp_information.l_name   from emp_information    inner join task_information    on task_information.task_no = assignments.task_no    inner join assignments    on emp_information.emp_id = assignments.assignee   where (((assignments.assignment_date) like "%this is just some date the user has to enter...%")) 	0.00103772971649558
11828085	7214	how to get id between two table?	select userid ,coursename ,course_desc  from am_course  where name='java' and userid in (     select userid      from am_timetable      where `date_time` between '2012-08-07 00:00:00' and '2012-08-20 00:00:00' ) 	0
11828733	17798	sql server find what jobs are running a procedure	select j.name    from msdb.dbo.sysjobs as j   where exists    (     select 1 from msdb.dbo.sysjobsteps as s       where s.job_id = j.job_id       and s.command like '%procedurename%'   ); 	0.607158127870996
11829034	40361	how to get details from multiple tables?	select  c.cid, c.course_desc, user.name from am_course c inner join am_inter inter on inter.cid = c.cid inner join am_user user on user.uid = inter.uid inner join am_timetable tt on inter.cid = tt.userid where c.name = 'coursename' and tt.date_time between '2011-08-12' and '2012-08-12' 	0.000462157599117882
11831555	30631	get nth element of an array that returns from "string_to_array()" function	select (string_to_array('1,2,3,4',','))[2]; 	0.000123649832200073
11832829	26946	sql server - convert varchar to datetime. yyyy-mm-dd 10:30:36.157 format	select * from table  where  convert(datetime,responsedate)  between '6/30/2012' and '8/1/2012' 	0.176698592333149
11832878	11609	aggregation subquery with top n	select c.busstationid, avg(c.distance) from coffee c where c.coffeeshopid in  (select top 5 c2.coffeeshopid from coffee c2 where c2.busstationid = c.busstationid order by c2.distance) group by c.busstationid 	0.110472216594197
11835117	39046	retrieve all data from table, then count how many results there are in another	select      t2.id,     count(t3.tag_id) as global_count,     group_concat(t3.image_id) as images_with_tag from      tagged t1     join tags t2 on t2.id = t1.tag_id     left join tagged t3 on t3.tag_id = t2.id where t1.image_id = 1 group by t2.id order by global_count desc 	0
11836104	24265	crossing mysql tables	select agent_log.campaign_id from agent_log, campaigns where agent_log.campaign_id = campaigns.campaign_id        and campaigns.active = 'y' 	0.264194574245297
11836874	30359	return a grouped list with occurrences using rails and postgresql	select tag_id, count(*) as times from   taggings group  by tag_id order  by times desc limit  5; 	0.00447026275775465
11839326	11769	mysql query (or doctrine 1.2 query) - get most recent item from joined table and filter	select c.first_name, c.last_name from contacts c   left join     (select a1.contact_id, a1.date, a1.activity_type_id from activity a1       join (select contact_id, max(date) date from activity group by contact_id) a2         on a1.contact_id = a2.contact_id and a1.date = a2.date      ) a   on c.contact_id = a.contact_id where a.contact_id is null or a.activity_type_id = 3; 	0
11841810	3237	find ids with duplicate records in mysql	select group_concat(id) as duplicate_ids,        columna,         columnb from your_table group by columna, columnb having count(id) > 1 	0
11841856	17039	adding duplicate values to original value	select   email, date, column_c, column_d, column_e,   group_concat(column_f separator ' ') as column_f from (   select *   from tablename   order by date ) i group by email   having date = max(date) 	0.000435838500608453
11841983	17903	how to retrieve a count number of specified values in mysql (even if no records)?	select sum(if(rating=-1,1,0)) as rating1,     sum(if(rating=1,1,0)) as rating2 from mytable 	0
11842005	13115	querying different table if first result is empty	select *    from (     select usertbl.id as uid, persontbl.email as email, 'y' as active       from persontbl         join usertbl on persontbl.person_id = usertbl.person_id         where (usertbl.id = @id)     union all     select upt.id as uid, ppt.email as email, 'n' as active       from personspendingtbl ppt         inner join dbo.userspendingtbl upt on ppt.person_id = upt.person_id       where (upt.id = @id)) user   limit 0,1 	0.000493437234505857
11842047	17356	select latest date with non-null values, given weekends and work-free days in php	select * from ind_cotatii where id_nom=3 and `data` >= 'date_sub('".$data_start."',interval 1 week)' and `data` <= '".$data_end."' "; 	0
11843582	19253	sql order by column with 0 as exception	select * from cats  order by case when cat='none' then 0 else 1 end ,val desc 	0.697870949376437
11843677	37943	sum of two different columns (with additions) of different tables and multiple table joining in oracle	select m.schoolcode, m.schoolname, e_sum, c_sum    from dise2k_master m  inner join  (     select schoolcode,            sum(c1 + c2 + c3 + c4) e_sum       from dise2k_enrolment09      where year='2011-12'        and caste in(1,2,3,4)       group by schoolcode  ) e     on m.schoolcode=e.schoolcode  inner join  (     select schoolcode,            sum(rooms) c_sum       from dise2k_clsbycondition      where year='2011-12'        and classid in(7,8)      group by schoolcode  ) c     on m.schoolcode=c.schoolcode  where m.year='2011-12' 	0
11843813	19418	how can we sort the records of having duplicate records?	select * from table order by firstname, surname; 	5.8351496378998e-05
11844609	36983	how do i choose records with equal values in some column?	select ide, fn, ln, debt from empl where ln in (     select ln     from empl     group by ln     having count(*) > 1 ) 	0.000221200749537767
11844655	1724	how to form this sqlite query?	select itemname from itemdata where itemid in ( select itemid from storeitem where storeid = 3 and value = 1) 	0.771100472292832
11845624	24089	selecting a specific number as column value in the query	select id,'0' as choices from tbl1 ; 	0
11845702	30277	union select only one row	select top 1 * from  (                  select fault,occurredon                   from atmstatus                  where ticket=189703                  union                   select fault,occurredon                  from atmstatushistory                  where resolved=0 and ticket=189703 ) x order by occurredon desc 	0.000848211725535632
11846429	15739	getting value of mapping table ids when value is from same column	select  b.title as titlea,         c.title as titleb from    mapping a             inner join records b                 on a.id1 = b.id             inner join records c                 on a.id2 = c.id 	0
11847173	30995	how to write a loop to do the calculation in mysql	select date(date) as date, count(distinct user) from video where date >= '2012-01-30 00:00' and date_pl <= '2012-02-19 00:00' group by date(date) 	0.367636330576191
11847775	32518	firebird sql: wildcard % with null values	select   * from   my_table where   coalesce(my_field, -1) = some_value 	0.571192131010705
11847931	40509	how to select mysql 1-to-last on 1-to-many relationship	select *     from master_file as master     left join activity_file as activity on activity.id = master.id     left join (select id , max(entry_date) entry_date                 from activity_file                  group by id) last_activity     on activity_file.id = last_activity.id       and  activity_file.entry_date= last_activity.entry_date     order by master.display_name 	0.156847321191851
11848905	35136	select last 12 rows oracle	select * from      ( select estatisticas, rownum rn         (select *         from series          order by odata desc) estatisticas          where ponteiro = 50 and lotus = 30     order by odata asc) where rownum <=12 	0.00035189516130584
11849177	30586	selecting data from a table conditional on 2 unique values from another table	select   option_data.* from   stock_data inner join   option_data     on  option_data.id = stock_data.id     and option_data.date between stock_data.date-60 and stock_data.date+60 	0
11849451	7874	how to convert bigdecimal to integer in mysql	select cast(sum(items) as binary) ... 	0.11506860771204
11850496	8116	create a non-existant field in mysql view	select a.*, if(a.living = 1, "tick.gif", null) as image from authors a 	0.119658697183254
11851173	5612	get existing and non existing combinations between two tables through a relationship table	select a.id, b.fromid, b.toid, a.km, a.obs from distances a right join( select a.id as fromid,         a.name as fromname,        b.id as toid,        b.name as toname from froms a join tos b on 1=1) b on a.fromid = b.fromid    and a.toid = b.toid 	0
11851341	40873	sqlite group by a non-calendar month (from 10th in one month to 10th in next month)	select strftime("%y %m", tendaysbefore), <whatever> from (select foo.*,              date(thedate, '-10 days') as tendaysbefore       from foo      ) t group by strftime("%y-%m", tendaysbefore) order by 1, 2 	0
11852800	39623	count the instances of value in sub-query, update table	select id, mytype, count(*)  from table_name group by id, mytype 	0.000418134101415708
11852887	23339	sql multiple joins and sums on same table	select t.group,        sum(case when t.date = current_date - 1 then t.amount end),        sum(case when t.date = current_date - 2 then t.amount end) from table t group by t.group 	0.0111142265492096
11853065	19245	trying to count # distinct values of a field based on value of a different field	select customer from your_table group by customer, type having count(distinct store) > 1 	0
11853413	9035	mysql double join	select g.uid as game_uid,         t1.name as team_one_name,         t1.rank as team_one_rank,         team_one_score,         t2.name as team_two_name,         t2.rank as team_two_rank,         team_two_score,         game_date from games g  inner join teams t1 on t1.uid = team_one_uid inner join teams t2 on t2.uid = team_two_uid 	0.786838469869752
11859233	32560	mysql distinct and whitespace	select distinct binary textcolumn from dummytable 	0.245018447139827
11860169	14130	sql count average	select userid, sum(total)/count(distinct semid) from custom where userid=36 	0.0181103522253125
11860847	23571	choose people with identical name and family sql	select fn, ln from      depart          inner join      empl           on depart.debt = empl.debt where      city = 'lviv' group by fn, ln having count(*)>1 	0.00473223280702038
11861799	3972	mysql query to select results with auto increment as a new column added in the result	select  @s:=@s+1 serial_number,student_id,student_name,student_avg from    students,         (select @s:= 0) as s where student_avg > 4; 	9.67337516972494e-05
11862175	37592	calculating anniversaries of employees with their joining dates	select * from  employees where      dayofyear(`start date`) between dayofyear(curdate())-10 and dayofyear(curdate()) 	6.57512787284998e-05
11862366	32761	database produce result and number of other fields in php	select name,count(name) from book where attr3 = 'something' group by name select attr1,count(attr1) from book where attr3 = 'something' group by attr1 select attr2,count(attr2) from book where attr3 = 'something' group by attr2 	0.000254074277198936
11862665	10999	where is the oracle db stored in windows	select * from dba_data_files;  select * from v$logfile;  select * from v$controlfiles;  	0.756904922371913
11863643	33469	how do i return two columns from first table if only one column partially matches with the second one?	select   a.`artno`,   a.`name` from   art a left join   store s on s.artno=a.artno where   s.artno is null 	0
11864367	12547	sql - grouping duplicates and unique id issue	select min(id), min(subid), col1, col2, col3, col4 from tab group by col1, col2, col3, col4 	0.0538759265731679
11865498	30620	mysql query - comparing string with set type	select * from table where find_in_set('$string', alphabet) > 0 	0.144266095288857
11866095	31254	mysql select row based on count of another table	select *  from blogposts  where id in      (select postid from photos group by postid having count(*) >= 5) 	0
11867172	6773	how can i limit the number of results returned from left join without a sub select?	select * from (select lu.*,              (select photo_id               from profile_photos               where lu.user_id = profile_photos.user_id               order by rand()               limit 1              ) as photo_id       from login_users lu      ) lu left join      profile_photos pp      on pp.photo_id = lu.photo_id left join      profiles p      on p.user_id = lu.user_id  where lu.restricted <> 1 order by lu.birthdate desc limit 0, 20 	0.00411915682665806
11869539	37078	left join to most recent record	select   g.*, s.* from   games g left join (     scores s   inner join   (     select       n.game_id,  max(n.created_on) as max_score_date     from       scores n     group by       n.game_id   )     y       on  y.game_id        = s.game_id       and y.max_score_date = s.created_on )     on s.game_id = g.id 	0.00201326997452517
11870981	21092	max value of a column	select t1.id, t2.id, t2.val from table1 t1 inner join  (     select max(value) val, id     from table2     group by id ) t2     on t1.id = t2.id 	0.00127827270779663
11871380	17364	selecting all users who subscribe to a particular user, but to whom that user does not subscribe	select     u.id from     subscriptions sub  join     users u on u.id = sub.subscriber_id left join     subscriptions unsub         on unsub.subscribee_id = sub.subscriber_id         and unsub.subscriber_id= sub.subscribee_id  where     sub.subscribee_id = :user_id     and unsub.subscribee_id is null 	0
11874804	2985	get the balance of my users in the same table	select user_id,        sum(case when type = 'income' then amount else - amount end) as balance from t group by user_id 	0
11875377	9201	tsql query for "accumulated value"	select datehere,        total,        total + coalesce(                          (                             select sum(total)                             from mytable b                             where b.datehere < a.datehere                           ), 0) as runningtotal from     mytable a order by datehere 	0.45208509829023
11876967	28747	mysql select statement to return data that isn't always in the same column.	select    case      when homerunner = 'brian' then 'home'     else 'road'   end outcometype,   case      when homerunner = 'brian' then homeoutcome     else roadoutcome    end outcome from $db where homerunner = 'brian' or roadrunner = 'brian' 	0.00110626097702033
11877612	27151	how to show last 20 comments using mysql query	select * from (     select * from comment where answerid=$answerid order by time desc limit 20 ) d order by time 	5.25272253089304e-05
11878307	4024	converting integer to text during the select query in mysql	select case intfield         when 1 then 'low'         when 2 then 'medium'         when 3 then 'hi'            end as inttext from table 	0.0954202978929756
11879113	9075	finding the next free time slot	select * from slots s1 where     s1.endtime > :instarttime and     not exists (select 1 from slots s2 where s2.starttime > s1.endtime and s2.starttime < dateadd(s1.endtime, :inendminusinstart)) order by     s1.starttime detachedcriteria subquery = detachedcriteria.for(slot.class)     .add(<filter on resource>)     .add(restrictions.propertygt("starttime", "s1.endtime"));     .add(restrictions.propertylt("starttime", projections.sqlfunction("dateadd", projections.property("s1.endtime"), instarttime - inendtime, hibernate.datetime)); session.createcriteria(slot.class, "s1")     .add(<filter on resource>)     .add(restrictions.gt(endtime, instarttime))     .add(subqueries.notexists(subquery)) 	0.000237717662022139
11880453	20603	getting data from 2 tables when they dont have any primary-foregin key relationship	select coalesce(a.col1,b.col1)         , coalesce(a.col2,b.col2)         , coalesce(a.col3,b.col3)         , coalesce(a.col4,b.col4) from b left outer join a     on a.id = b.id 	0
11881162	17339	unpivot table with multiple columns and dynamic column names	select  productid,productname, substring(col1,1,3) as type,  grossrevenue, directcost, netrevenue     from    (          select * from #tmpproducts      ) as t      unpivot ( grossrevenue for col1 in (b2b_grossrevenue,b2c_grossrevenue)) as unpvt      unpivot ( directcost for col2 in (b2b_directcost, b2c_directcost)) up2     unpivot ( netrevenue for col3 in (b2b_netrevenue, b2c_netrevenue)) up3 where substring(col1,1,3)=substring(col2,1,3) and  substring(col1,1,3)=substring(col3,1,3) 	0.00250881332244308
11881163	20043	text manipulation of strings containing "the "	select id,        text from list l order by trim(leading 'the ' from text); 	0.21364584058615
11882072	7757	combine two tables in sql	select college,    department ,  course  ,  section ,        sum(case when <pass condition> then 1 else 0) as passed  ,        sum(case when <fail condition> then 1 else 0) as failed from <table1> join <table2> on (condition) group by college,    department ,  course  ,  section 	0.0105566663358998
11885955	23562	how to check that group has a value in oracle?	select     min(created_timestamp),     max(resource_id),     max(price),     min(case when event_type in (1704, 1701, 1703)                   then found_value               when event_type = 1707                   then 1707                   else null          end) from subscriptions group by guid ; 	0.0014947731658942
11886100	32513	mysql, tuples related by field on same table, group by or self join?	select *  from involved i where i.type=1    and i.idincident in (select i2.idincident                         from appointmentinvolved ai                           inner join involved i2 on ai.idinvolved = i2.idinvolved                           where ai.idappointment=<whatev>) 	0.00531759081957287
11886983	11757	sql query multiple table with same column	select count(*) from (     select creationdate, lastmodifieddate from table1     union all     select creationdate, lastmodifieddate from table2     union all     select creationdate, lastmodifieddate from table3 ) a  where creationdate is null or lastmodifieddate is null 	0.00901472066941756
11886985	38064	complex mysql query for related users and posts	select ... from posts p inner join users o on p.uid = o.uid   inner join devices od on o.uid = od.uid   inner join related r on o.uid = r.uid1   inner join comments c on r.uid2 = c.uid and p.pid = c.pid   inner join devices cd on c.uid = cd.uid   where pid = yourpostid 	0.0267232954719229
11887059	33825	selecting multiple rows out of a second table for every row in a first table	select date, location from calendar, locations 	0
11888131	36752	sql select statement between row number n and j	select top 500 name from  ( select top 24000 name from table order by name ) order by name desc 	0.000435913363977294
11888167	7533	get next 10 batch of info after a certin id mysql query?	select [...] limit 20,10; 	0
11888928	36974	transpose a table oracle 10	select id,   min(case when area = 'a1' then area end) area1,   min(case when area = 'a1' then car end) car1,   min(case when area = 'a2' then area end) area2,   min(case when area = 'a2' then car end) car2,   min(case when area = 'a3' then area end) area3,   min(case when area = 'a3' then car end) car3 from yourtable group by id 	0.0075414652094929
11889898	1781	sql query to select all fields where creation date is more than 30 minutes old	select         id,         creationdate,         name     from tablename     where creationdate < dateadd(minute, -30, getdate()); 	0.000148084163939031
11890173	35985	mysql check if field has number in it	select     * from     your_table where     find_in_set('2',replace( '1;2;23;12', ';' , ',' ) ) > 0 	0.00146295834911744
11890647	6079	sql server 2008 conditional select to output multiple true values	select a.* from ((select t.*, 'all' as thecode        from t       ) union all       (select t.*, 'system1'        from t        where system1 = 1       ) union all       (select t.*, 'system2'        from t        where system2 = 1       )      ) a 	0.448223679700475
11890809	5529	one to many join with mysql	select * from  (select order_id, data_code, data_value from tablename pivot (sum(data_value) for data_code in ([milk_money], [num_eggs], [total_spent])) pvt 	0.131190023640724
11892161	37509	writing a select statement that compares information within the same column without creating a seperate function	select o.age, o.name,     (select top 1 c.school     from students c     where c.age < o.age     order by c.age desc) as school from students o 	0.00719708568884888
11892247	7501	mysql show all grouped results and sort	select t.letter, t.value from mytable t inner join (     select letter, sum(value) as valuesum     from mytable     group by letter ) ts on t.letter = ts.letter order by ts.valuesum desc, t.letter, t.value desc 	0.000321191001759724
11892556	39188	oracle sql query and perhaps subqueries across 4 tables	select p.policy_id, qcv.value  from policy p inner join quote q on p.policy_id = q.policy_id  inner join quote_clause qc on qc.quote_id = q.quote_id  inner join quote_clause_variable qcv on qcv.quote_clause_id = qc.quote_clause_id  where p.template_id = '28'  and qcv.variable_name = 'r01011c1'; 	0.74536667621989
11893000	32579	how to further specify a sqlite query	select name from students where grade = (select max(grade) from students); 	0.509136804810356
11893156	11652	in sql, how can i give one matching column precedence over another?	select * from companies where symbol like 'zy%' or name like '%zy%'  order by    (case when symbol like 'zy%' then 1         when name like '%zy%' then 2         end), symbol asc; 	0.00107984480196577
11893551	7715	how to write one query for multiple groupings?	select col1 cc, col2 gm, col3 terr, col4 mkt, null seg,  sum(sumit) ss from #temp1 group by col1, col2, col3, col4, col5 with rollup 	0.17795553678628
11894202	38541	datediff convert minutes to decimal	select cast(datediff(second, min(start_time), min(complete_time))/60.0 as decimal (10,10)) from tracked_object_history toh1 where toh1.op_name = 'assembly' 	0.0245836878756457
11895784	9235	sql getting last date and values associated with description of value in another table	select authorizations.*, anothertable.description from  (     select max(authorization_date) as max_date, request_id     from authorizations     group by request_id ) last_auths inner join authorizations on last_auths.max_date = authorizations.authorization_date     and last_auths.request_id = authorizations.request_id inner join anothertable on anothertable.role_id = authorizations.role_id 	0
11897683	13878	doing a group by within a group	select    business_line,    business_segment,    grand_total,    a_total * 100.0 / grand_total as a,    c_total * 100.0 / grand_total as c,    e_total * 100.0 / grand_total as e from    (        select           business_line,           business_segment,           sum(transaction_value) as grand_total,           sum(case when payment_type = 'a' then transaction_value end) as a_total,           sum(case when payment_type = 'c' then transaction_value end) as c_total,           sum(case when payment_type = 'e' then transaction_value end) as e_total        from           sometable        group by           business_line,           business_segment     ) as t 	0.415103323450556
11897946	38820	how to display record number for all database	select table_name, table_rows from   information_schema.tables where table_schema = '<your db>' 	0
11898003	33497	sql - exists comparison	select t1.id,t1.country,t1.status     from table t1     join table t2 on t1.country=t2.country and t2.status='untreated'     where t1.status='treated'  select id,country,status             from table t1             where                   t1.status='treated' and                  exists (                       select 1 from table t2 where                             t2.country = t1.country and                             t2.status = 'untreated'                  ) 	0.683242264782936
11898033	23259	finding the rank of a player from the scoreboard	select * from (select @rank := @rank + 1 as rank, id,username, score from table , (select @rank := 0) r order by score ) k where k.username = 'y' 	0.000149644563586834
11899024	8202	postgresql query to return results as a comma separated list	select string_agg(id, ',') from table 	0.000407670141375077
11899183	13225	split one column into 3 and numerate each row	select * from (       select (@var_count := @var_count + 1) as order1, value as value1, 0 order2, 0 value2, 0 order3, 0 value3       from table_name, (select @var_count := 0) a       limit 33       union all       select 0 order1, 0 value1, (@var_count := @var_count + 1) as order2, value as value2, 0 order3, 0 value3       from table_name, (select @var_count := 33) a       limit 34, 33       union all       select 0 order1, 0 value1, 0 order2, 0 value2, (@var_count := @var_count + 1) as order3, value as value3       from table_name, (select @var_count := 66) a       limit 67, 33      )a; 	0
11900533	18117	get latest date in multiple join	select c.cat_id, c.cat_name, c.cat_description, tp.topic_subject, tp.topic_id, tp.maxpostdate from categories c  left join (select t.topic_cat,t.topic_subject,t.topic_id, max(post_date) maxpostdate  from topics t            left join posts p on p.post_topic = t.topic_id            group by t.topic_cat,t.topic_subject,t.topic_id) tp on (c.cat_id=tp.topic_cat) where tp.maxpostdate = (select max(post_date) from topics t2                        left join posts p2 on p2.post_topic = t2.topic_id                        where t2.topic_cat=c.cat_id                        ) order by unix_timestamp(tp.maxpostdate) desc 	0.000482356536826855
11900876	23422	regexp of a number with 11 digits beginning with 09	select *  from  table`  where  `number` regexp '^09\d{9}$' limit 0 , 30 	0.00556514489876129
11900975	23915	how can i count registers that created in last 24 hours?	select username from table where date>=dateadd(current_date+interval -1 day) group by username   having count(*)>3 	0
11901032	6000	concatenation of fields in different rows in mysql	select concat(group_concat(distinct val1_col1a),                group_concat(distinct val1_col2a),                group_concat(distinct val1_col1b),               group_concat(distinct val1_col2b)) as value from table_name; 	0.000910439531139757
11901146	29274	selecting rows with the nearest date using sql	select      id, location, code, date, flag  from      table1  join (     select id as subid, max(date) as subdate      from table1      where date < '11/11/2012'         and exists (select * from #temp_code where table1.code = #temp_code.code)          and id in (14, 279)     group by id     ) as sub on id = subid and date = subdate 	0.00113580123340273
11901352	24000	sql select last occurrence of row  & count number of occurrences	select      id, customerid, estimateno, orderyear, orderno, productionno, addedby,         addeddate, sizelength, sizewidth, homemodelid, hometypeid, drawingno,      customerreference, buildpieces, productionpieces, notes, specdocument, orderid,     (select count(*) from orderspecs as os where o.orderid=os.orderid) as [count] from       orderspecs as o where      (addeddate = (select max(addeddate) as expr1                   from orderspecs as i                   where (o.orderid = orderid)))      and (customerid = @customerid) 	0
11902941	36699	retrieve all record from one table and particular record from other	select * from tbl_users left join tbl_cmp_user  on tbl_cmp_user.cmp_id = tbl_users.usr_id  and tbl_cmp_user.cnt_status =1 	0
11903114	23053	combine results from sql select into string	select    ([address line 1] + ', ' + [address line 2] + ', ' + [address line 3] + ', '            + town + ', ' + region + ', ' + postcode) as address from      tablename 	0.00132498340905989
11903209	5245	mysql: move specific records on top of the resultant array beside order by	select * from countries_table order by name = 'australia' desc,          name = 'uae' desc,          name = 'pakistan' desc,          name = 'uk' desc,          name = 'usa' desc,          name asc; 	0
11904455	25709	how to store and query based on daterange/age?	select <whatever> from (select c.*, datediff(day, c.joindate, getdate())/365.25 as ageyears       from customer c      ) c left outer join      ncl_commissions com      on c.custcode = com.custcode and         c.producttype= com.producttype and         c.salesrep = com.salesrep and         c.ageyears between minage and c.maxage 	0.00919565523172463
11906143	4316	get latest text entry of group by statement	select *, max(conversations_mails.created_on) as conversation_last_reply,   max(conversations_mails.id) as maxid from conversations  left join conversations_mails on conversations_mails.conversation_id = conversations.id  where conversations_mails.id = (select max(conversations_mails.id) from conversations_mails where conversations_mails.conversation_id = conversations.id) group by conversations.id  order by conversation_last_reply desc 	0.000107578187662691
11906212	18213	grouping rows with the id using a join mysql?	select table1.q_id,table1.q_text,table1.date,table2.a_id,table2.a_text     -> from table1     -> left join table2     -> on table1.q_id = table2.q_id; 	0.00529515238533452
11906283	22166	t-sql: calculating the nth percentile value from column	select max(case when rownum*1.0/numrows <= 0.9 then cola end) as percentile_90th from (select cola,              row_number() over (order by cola) as rownum,              count(*) over (partition by null) as numrows       from t       where cola is not null      ) t 	0
11906811	36971	add a following 0 to inserted integer	select right('0' + rtrim(number) + '0', 5) from dbo.tablename; 	0.0206195587630353
11908456	9904	derived/calculated column on existing table	select    l.*,            q.summary as summarypreviousyear from      lists l left join       (           select    date,                      summary           from      lists            where     month(date) = 12      ) as q             on year(l.date) = year(q.date) + 1 	0.0121522709085163
11909251	5618	trying to sum and group two sets of results from three sql tables	select w.name as name1, sum(h.atk) as atk, a.name as name2  from h  join w on w.wid=h.wid join a on a.aid=h.aid group by w.name, a.name 	0.000185829664528701
11911773	11791	using sql sms how do i return a list of numbers using low and high columns	select id,low,high,number as num_list from sub_inst , numbers where low<=number and high>=number 	0.000108520362997208
11914100	5474	select all items in common between two users from a single table	select item_id from xyz where  user_id in ('a','b') group by item_id having count(distinct user_id) = 2 	0
11914305	40990	how to count students and classes of every teacher in sql server?	select      t.teacher_id, t.name,     classes = (select count(*) from class c where c.teacher_id = t.teacher_id),     students = (select count(*) from student s where s.teacher_id = t.teacher_id) from teacher t 	0.000935254944207129
11914974	915	fetching / select data from sql server 2008 into data gridview	select      g.godown_id, g.godown_name, t.type_name, b.count, r.bags_received,     b.lb_per_bag, s.supplier_name from     tbl_yarn_book b, tbl_godown g, tbl_godown_transaction gt,      tbl_yarn_receive r, tbl_yarn_supplier s, tbl_yarn_type t                         where     gt.godown_id = g.godown_id      and gt.receive_id = r.receive_id     and r.book_id = b.book_id      and b.type_id = t.type_id      and b.supplier_id = s.supplier_id 	0.00363667029847826
11915665	2363	advantage of select query in from clause	select name, age, address from (    select name, age, address,      rn = row_number() over (partition by address order by age desc)   from dbo.emp ) as x where rn = 1; 	0.274916488619068
11916920	27501	how do i select 4 random tables from a mysql database that has thousands of tables?	select table_name from information_schema.tables t where table_schema = 'your_db_name' order by rand() limit 4 	0
11917415	28334	getting recent message of the user	select * from     (         select max(id) as message_id         from private_messages         where to_id='$session_user_id'         group by sender_id     ) msg_ids join private_messages on msg_ids.message_id = private_messages.id order by time_sent desc; 	0.000540549240170179
11918624	35658	selecting row with many child rows	select date_format(calendar_date,'%w %d, %m, %y') as calendar_date, tmp.var1 from calendar_month left join      (select group_concat(calendar_entry_title, ' ',calendar_entry_teaser) as var1, calendar_id          from calendar_entry      group by calendar_id) as tmp on tmp.calendar_id = calendar_month.calendar_id order by calendar_date 	8.07221699974507e-05
11919094	33566	mysql if two columns equal and if they are both greater than one	select id,username,clan  from `users`  where username != '".$user['username']."'  and (clan = 0 or clan != ".$user['clan'].")" 	0
11919902	4785	using a mysql join	select  * from    posts a left join relationships b on a.user_id = b.user_2 where   b.user_1 = $user_id and  b.status in (1,3,4) union distinct select * from    posts a where   a.user_id = $user_id (my id) 	0.57525095786168
11920318	8622	mysql query with multiple where clauses	select post_id  from wp_postmeta  where meta_key = 'location' and meta_value = 'texas'                    and post_id in (select post_id                    from wp_postmeta                    where meta_key = 'bathrooms' and meta_value= '2') 	0.746169672340271
11920801	15782	select different columns based on outer join	select     tablea.rowid,     tablea.name,     coalesce(tableb.enabled, tablea.enabled) as enabled from tablea  left outer join tableb on tablea.rowid = tableb.rowid 	0.00225078231520939
11921988	31068	how can i get 10 first records of join tables in sqlite?	select   keyword,   nemayeh.nemayeh from   (select keyword.id,keyword.keyword     from keyword    order by keyword.keyword asc    limit 10 offset 0) as tmp inner join keyword_nemayeh on keyword_nemayeh.id_keyword = tmp.id inner join nemayeh on nemayeh.id = keyword_nemayeh.id_nemayeh order by 1,2 limit 0, 10 	0
11922275	26768	mysql select the most recent incoming or outgoing messages of distinct users	select m1.*    from table_name m1    inner join (select max(senddate) as senddate,                       if(member_id2 = 3, member_id1, member_id2 ) as user                  from table_name                 where (member_id1 = 3 and delete1=0) or                       (member_id2 = 3 and delete2=0)                group by user) m2           on m1.senddate = m2.senddate and             (m1.member_id1 = m2.user or m1.member_id2 = m2.user)       where (member_id1 = 3 and delete1=0) or             (member_id2 = 3 and delete2=0)     order by m1.senddate desc 	0
11924141	37786	how to fetch data from multiple table from single database	select ft.fileno, pt.amount, 'true' ispayment from filetable ft join paymenttable pt on pt.fk_fileid = ft.fileid union all select ft.fileno, et.amount, 'false' ispayment from filetable ft join expensetable et on et.fk_fileid = ft.fileid 	0
11925081	14039	subtracting totals using the same table with sql server	select txt_web_name, sum(mon_pay_amount) as webtotal, avg(mon_pay_amount) as webavg,        sum(case when txt_pay_type <> 'credit' then mon_pay_amount else 0 end           ) as totalnocredit,        avg(case when txt_pay_type <> 'credit' then mon_pay_amount end           ) as avgnocredit from tbl_payment      inner join dbo.tbl_orders on (uid_pay_orderid = uid_orders)      inner join dbo.tbl_websites on (uid_order_webid = uid_websites) where dbo.tbl_payment.bit_pay_paid = <cfqueryparam cfsqltype="cf_sql_bit" value="yes">       and txt_pay_status <> <cfqueryparam cfsqltype="cf_sql_varchar" value="credit"> group by txt_web_name 	0.0023502399480843
11925689	35595	how to get those values which didn't return any row in select query while using in function	select x.f from (select 'val1' as f union all select 'val2' union all select 'val3') x left join table t on x.f = t.column2 where t.column2 is null 	6.53508405761056e-05
11926474	41258	how do i combine data from two mysql tables to return a list of users sorted by the count of user entries in one table?	select users.user_id, count(tracks.user) from users left join tracks on (users.user_id = tracks.user) group by tracks.user order by count(tracks.user) desc; 	0
11926611	33150	combining two separate mysql databases tables in an array	select * from `database1`.`table1` where `condition1` union select * from `database2`.`table2` where `condition2` 	0.001513023052338
11929375	15	sql date difference	select to_char(date '2000-01-01' + (frm_time-hours_in),'hh24:mi') from time_test 	0.0289243887576632
11929623	18375	names repeated in dropdown.(sql query )	select min(id), name  from master group by name 	0.396933803364957
11929721	21055	sql select from 3 tables with sum	select   t2.name as period        , sum(t1.linetotal) as amount        , max(t0.docrate) as exchangerate from   oinv t0 inner join inv1 t1         on t0.docentry = t1.docentry         inner join dbo.ofpr as t2         on t1.finncpriod = t2.absentry  where t0.docstatus = 'o'  group by t2.name 	0.00813982595920701
11931227	15157	mysql - select true when count is greater than zero	select if(count(*) > 0, 'true', 'false') as newresult   from restaurants_offers  where (date(now())  between date_start and date_end) and         restaurant_id = 1 	0.0378339186835087
11931499	20285	select from multiple tables with multiple where clauses	select      casestatus.casestatusid,     casestatusdesc,     count(caseid) from casestatus     left join cases          on casestatus.casestatusid = cases.casestatusid         and cases.isdeleted=0 where     casestatus.isdeleted=0 group by         casestatus.casestatusid,     casestatusdesc 	0.0226601611110875
11936791	6854	how to combine two records into one line?	select name,        'mobile',        max(case when ttype = 'mobile' then phone end) as mobilephone,        'home',        max(case when ttype = 'home' then phone end) as homephone from t group by name 	0
11937206	4654	sql query multiple columns using distinct on one column only	select * from tblfruit where tblfruit_id in (select max(tblfruit_id) from tblfruit group by tblfruit_fruittype) 	0.00014261093928284
11939123	31180	obtaining only first result from a left join	select bg.patientid, datediff(hour, bg.createdate, getdate()) timetotarget  from bloodglucose bg cross apply (  select top 1 *  from ivprotocol i  where i.patientid = bg.patientid  order by some_critera ) i where bg.bgvalue >= i.targetlow and bg.bgvalue <= i.targethigh order by bg.patientid asc 	0.0015176458620287
11939141	9990	datalist or datagrid to display rows of database looking like a table?	select  * from    ( select    [region] ,                     [store] ,                     [sales]           from      [regionsales]         ) rs pivot ( sum(sales) for region in ( [mex], [usa] ) ) as salesperregion 	0.00666170911812127
11941766	17100	selecting all fields with values greater than a current field value	select distinct `pdb`.`point_id` as `id`  from `path_detail` as `pda`, `path_detail` as `pdb`   where  pda.point_id = 111 and pda.path_id = pdb.path_id  and pda.step < pdb.step order by `pdb`.`point_id` asc 	0
11941838	12623	plsql: change first two digits of year	select    substr(to_char(end_dt,'yyyy'),2,1) ||   substr(to_char(end_dt,'yyyy'),1,1) ||    substr(to_char(end_dt,'yyyy'),3,2) ||'-'||   to_char(end_dt,'mm-dd hh:mi:ss')   as dt from db; 	0
11942754	39322	sorting table in sql or access	select code, fname, listagg(cast(freq as varchar(32), ',') within group (order by freq) from t group by code, fname 	0.592726450386917
11944509	24341	just added a new index, do i have to freeproccache?	select * from table where userid = 1; 	0.0256777936965483
11945485	7870	selecting top 100 largest values in a table given possible duplicates	select * from (   select itemid,value,steamid from $table group by itemid order by value desc ) as tbl1 group by itemid, value limit 0,100 	0
11946769	388	how to modify this query to show the number of seats in each active event?	select     dbo.events.title, dbo.events.description, dbo.events.location,            dbo.events.numberofseats, count(distinct dbo.bookingdetails.networkid) as [number of bookings],            dbo.events.numberofseats - count(distinct dbo.bookingdetails.networkid) as remainingseats from         dbo.bookingdetails inner join                       dbo.users on dbo.bookingdetails.networkid = dbo.users.networkid right outer join                       dbo.events on dbo.bookingdetails.eventid = dbo.events.id where     (dbo.events.isactive = 1) group by dbo.events.title, dbo.events.description, dbo.events.location, dbo.events.numberofseats 	0
11946852	30564	sql query to select from and to date	select period_name     from gl_periods where :l_date_from <= end_date     and :l_date_to >= start_date 	0.0124954444351147
11947592	1147	how to select record from mysql if date is in '14-aug-2012' format	select vid from tm_visitor where date(intime) = str_to_date('01-aug-2012', '%d-%b-%y') 	0.000500584262604015
11947627	36908	query group by skipping a row	select    a.class,           a.gender,           count(b.class) as total_students from      (           select     a.class,                       b.gender           from       students a           cross join (                      select 'male' as gender union all                       select 'female'                      ) b           group by   a.class,                       b.gender           ) a left join students b on a.class = b.class and                          a.gender = b.gender group by  a.class,           a.gender 	0.0310350868135006
11948042	31251	mysql period(.) search pattern	select (length(str) - length(replace(str, substr, ''))) / length(substr) as cnt ... order by cnt desc 	0.112505680668796
11948663	27728	can i find tables that countains a column name x?	select table_name from all_tab_columns where column_name like '%your_search_column_name%' 	0.000142109897989529
11948904	20298	sqlite select record based on time format "hh:mm:ss"	select * from t where  ( (starttime<=endtime) and   ('07:00:00' between starttime and endtime) )  or ( (starttime>endtime) and   (      ('07:00:00' between starttime and '23:59:59')      or     ('07:00:00' between '00:00:00' and endtime)  ) ); 	0
11949086	30380	how to determine cubes which use particular dimension?	select  * from    $system.mdschema_measuregroup_dimensions where   cube_name = 'your_cube_name' 	0.0461530988337421
11949255	24858	get index of each  letter series from dictionary database	select id,        word from   (   select id,          word,          row_number() over(partition by left(word, 1) order by word) as rn   from yourtable   ) as t where rn = 1 	0
11951548	5141	mysql concat according to number of results	select id,companyname,countycount,countynames, if(countycount=1,concat(countynames,' county'),    if(countycount=2,concat(replace(countynames,', ',' and '),' counties'),          concat(substring_index(countynames,',',countycount-1)             ,' and '             , substring_index(countynames,',',-1)             ,'  counties'             )       ) ) result from ( select o.id,max(o.organization_vc) companyname, group_concat(c.county_vc separator ', ') countynames,count(c.id) countycount  from tblorganizations o left join jncountyorg co on (o.id=co.org_fk_id)  left join tblcounties c on (co.county_fk_id = c.id) group by o.id ) m order by m.id 	0.00161175398423981
11954937	38539	how to create a sum column without an internal subquery?	select *, sum(case when condition = 1 then value end) over() sumofconditionalvalues from @t 	0.124983885187306
11955043	38441	how to combine two similiar mysql statements into one	select *,      round((amazon_new_price/100*80) - lowest_new_price,2) as margin,     'new' as type      from ".tbl_books."      where rank < 200000 and rank is not null      and lowest_new_price < amazon_new_price/100*80      and amazon_new_price < 9999      and round((amazon_new_price/100*80) - lowest_new_price) > (lowest_new_price/100*".margin.")  union select *,      round((amazon_used_price/100*80) - lowest_used_price, 2) as margin,     'used' as type      from ".tbl_books."      where rank < 200000 and rank is not null      and lowest_used_price < amazon_used_price/100*80      and amazon_used_price < 9999      and amazon_used_price < amazon_new_price      and round((amazon_used_price/100*80) - lowest_used_price) > (lowest_used_price/100*".margin.")  order by type asc, rank asc 	0.00110070905269533
11955554	3316	how to query just the last record of every day	select distinct on (sample_time::date) sample_time, amp_hours from power order by sample_time::date desc, sample_time desc; 	0
11956596	40175	sql multiple conditions for group of data	select ssys,         material_number,         'sh_desc' characteristic,         max(case when characteristic = 'sh_desc' then description end) description,        case when max(case when characteristic = 'sh_desc' then description end) is not null and                  max(case when characteristic <>'sh_desc' then description end) is null              then 1             else 0        end count from mydb group by ssys, material_number 	0.0460535745828997
11956844	40876	spaces when concatenating multiple columns and one column is null - oracle	select decode(first_name,'','',first_name ||' ') ||        decode(middle_name,'','',middle_name ||' ') || last_name from table_a; 	0.00387248913027799
11957140	13088	php mysql join two tables	select s.id from songs s inner join (select * from history h order by date_played desc limit 1) lasthistory on lasthistory.title = s.title and lasthistory.artist = s.artist 	0.074441516890107
11957543	40304	order popular items with multiple tables	select b.col1, cnt from listb b     left outer join      (select col1, count(*) cnt       from lista a group by col1) a1 on b.col1 = a1.col1     order by cnt desc 	0.00350309189213844
11958838	34662	mysql - selecting distinct on single column	select t.*, c.first_name, c.last_name from (select `freetrial`.*,`company`.name as name,              (select contactid               from contact where contact.company_id = company.id               order by rand()               limit 1              ) as thecontactid       from  `contact_freetrial` inner join              freetrial`              on `contact_freetrial`.freetrial_id=`freetrial`.id left join             `company` on `company`.id=`freetrial`.company_id     ) t join     contact c     on t.thecontactid = c.contactid 	0.000884590380667293
11961106	23834	mysql union duplicate values	select data.isbn, data.title, data.rank, min(data.lowest_price) as [lowest price], b.lowest_location from <your_query> data inner join <your_query> b on data.isbn = b.isbn and data.lowest_price = b.lowest_price order by data.rank 	0.019769384935536
11964390	26037	mysql join table on three columns	select t1.date, t1.transaction, t1.p1, t1.p2, t1.p3, t1.p4, t1.p5        u1.name, u2.name, u3.name, u4.name, u5.name from table1 t1 left outer join table2 u1 on t1.p1 = u1.id left outer join table2 u2 on t1.p2 = u2.id left outer join table2 u3 on t1.p3 = u3.id left outer join table2 u4 on t1.p4 = u4.id left outer join table2 u5 on t1.p5 = u5.id 	0.0113351162123644
11964425	251	extract dates from all years less than mm-dd in postgres	select * from persons where     extract(month from age(current_date, birthday)) = 11;  	0
11965137	38747	mysql join, all rows from one table and first row from the other table	select      t1.* ,     t2.image from properties as t1  left join (            select                 min(id),                 pid,                 image             from property_images              group by pid) as t2  on t2.pid = t1.pid 	0
11965259	23529	join three tables on a condition of the thirst table	select op.*, g.*, gp.*  from openid as op  inner join users as g on g.userid = op.userid inner join profiles as gp on gp.userid = op.userid where op.openid = 2 	0.00362402885949158
11965336	14487	sql : how can i count distinct record in ms access	select     user_id   , count(*) as count_distinct_clients from     ( select distinct           user_id,            client_id       from tbl_sactivity     ) as tmp group by     user_id ; 	0.079072033256017
11967199	118	mysql query custom sorting from function	select * from $table order by ( 0.5 * likes + 0.25 * rating - view ) desc 	0.747135893902966
11967361	3562	executequery in multiple threads closes hsqldb database connection	select array_agg(cd_name order by cd_name) as arr from class_descriptors where cd_concrete=true array array = rs.getarray(1) 	0.376023038461028
11969411	31727	sql query to get count with left join	select count(*) from messages as m                   inner join folders as f                   on m.folderid = f.folderid                   where upper(f.foldername) = 'inbox' 	0.551119818554097
11970675	37113	how can i query the following in mysql?	select c1.id,    c1.dealer_id,    c1.name,    c1.model_year,    c1.date_added from cars c1 inner join (   select dealer_id, max(date_added) mxdate   from cars   group by dealer_id ) c2   on c1.dealer_id= c2.dealer_id   and c1.date_added = c2.mxdate group by dealer_id order by id desc limit 3; 	0.429127002823006
11971554	33194	where clause only if not null	select beer.id as beerid,  beer.barrelid as barrelid,  beer.imageid as imageid,  beer.title as title,  beer.map as map,  beer.longitude as longitude,   beer.latitude as latitude,   brand.name as brandname,   brew.type as brewtype,  image.name as imagename,   variation.name as variationname  from brand, brew, image, beer left outer join variation on variation.id = beer.variationid where beer.id = %s  and md5(beer.memberid) = %s  and beer.review = 1  and brand.id = beer.brandid  and brew.id = beer.brewid  and image.id = beer.imageid 	0.609088085338562
11972622	4737	is there a way to select distinct and intersect with related subqueries in single query?	select  inputedname, inputedcode, group_concat(idproduct) from    sampletable where   idpage = 27 group by inputedname, inputedcode order by coalesce(inputedname, 'z'),             coalesce(inputedcode, 'z')     	0.339961016983128
11973229	27174	mysql count from other table as join and add to every row of results	select  c.totalcount,         a.job_id,         a.user_id from    users_applications a             left join users b                 on a.user_id = b.id             left join                 (                     select job_id, count(*) totalcount                     from user_applications                     group by job_id                 ) c on a.job_id = c.jobid 	0
11974400	7263	query to get records present in one table but not in the other	select distinct lm.teacher_email from teacher_lm as lm where lm.teacher_email not in (select coalesce(lt.teacher_email, '')                                from  teacher as lt) 	0
11974568	7293	attempting to join 3 tables in mysql	select i.item, r.ratetotal as total, c.commtotal as comments, r.rateav as rate from items as i left join     (select item_id,      count(item_id) as ratetotal,      avg(rating) as rateav      from ratings group by item_id) as r  on r.item_id = i.items_id left join     (select item_id,      count(item_id) as commtotal      from comments group by item_id) as c on c.item_id = i.items_id where i.cat_id = '{$cat_id}'  and i.spam < 5 order by trim(leading 'the ' from i.item) asc;"); 	0.629900848551501
11975749	22043	reference an alias elsewhere in the select list	select    firstname, lastname, other,    flag = case when other is not null then 1 else 0 end from  (   select firstname, lastname,     case when lastname = 'jones'      then 'n/a'     end as other   from dbo.table_name ) as x; 	0.179209426854484
11975790	5264	order by a column not included in a group by clause	select memberid, sourceid, acuity from your_table group by memberid, sourceid, acuity order by min(myid) 	0.673088571864774
11976746	24965	transposing and grouping rows into columns in a sql query	select     m.item_name,     m.item_cost,     a.analysis_date,     sum(case when analysis_type = 'a' then item_quantity else 0 end) as type_a_quantity,     sum(case when analysis_type = 'b' then item_quantity else 0 end) as type_b_quantity from item_master m join itemanalysis a     on m.item_name = a.item_name group by m.item_name, m.item_cost, a.analysis_date 	0.00045505474126436
11976792	6782	how to sum two columns at left and display total in third column	select   date , sum (case when institution = 'abc' then qty1 else 0 end) as abc , sum(case when institution =  'xyz' then qty2 else 0 end) as xyz , sum(qty1+qty2) as total from mytable group by date with rollup 	0
11977096	16387	sql server check for greater than with select statement	select distinct wt.id from vwlist wt where flag = 1 and       getdate()  < (select dbo.fn_date(ps.date1,ps.uploaddate) from pseres ps where ps.id = wt.id) 	0.173109307704705
11978078	1960	alias a column name on a left join	select si.field1 as si_field1,        si.field2 as si_field2,        ind_data.field1 as ind_data_field1   from sites_indexed as si   left join individual_data as ind_data           on si.id = ind_data.site_id   where `url` like :url 	0.408050862249534
11978129	8858	fetch the rows which have the max value for a column - with duplicates	select t1.*, t3.* from mytable as t1   left outer join mytable as t2     on (t1.userid = t2.userid and t1."date" < t2."date") join myothertable as t3 on t1.userid = t3.userid where t2.userid is null; 	0
11978136	10455	how can i get just the first row in a result set after ordering?	select * from     ( select *    from emp    order by sal desc )    where rownum <= 5; 	0
11978536	23891	how do i return the next available date from mysql?	select _date     from dates    where _date > '2011-03-14' order by _date    limit 1 	0
11978966	20353	some database logic, retrieving correct entries	select `uniqueid`  from currentgames  where (`victim` = '$victim' and `rival` = '$rival') or (`victim` = '$rival' and `rival` = '$victim'); 	0.00800459164011465
11979929	17650	oracle sql query needs to change based on timezone	select tablea.columna,tableb.columnb  from tablea inner join tableb on  tablea.aid = tableb.aid  where (to_timestamp_tz('1970-01-01 00:00:00 +10:00','yyyy-mm-dd hh24:mi:ss tzh:tzm') +    ((tableb.epochvalue+(10*60*60*1000))/60/60/24/1000)) >  to_date('##from_date## +10:00', 'yyyy-mm-dd hh24:mi:ss tzh:tzm')  and (to_timestamp_tz('1970-01-01 00:00:00 +10:00','yyyy-mm-dd hh24:mi:ss tzh:tzm') + ((tableb.epochvalue+(10*60*60*1000))/60/60/24/1000)) <= to_date('##to_date## +10:00', 'yyyy-mm-dd hh24:mi:ss tzh:tzm'); 	0.0702567748643279
11980546	28611	unable to pivot table	select  vendorid,         avg(case             when incomeday = 'mon'                 then incomeamount             else null         end) [mon],         avg(case             when incomeday = 'tue'                 then incomeamount             else null         end) [tue],         avg(case             when incomeday = 'wed'                 then incomeamount             else null         end) [wed],         avg(case             when incomeday = 'thu'                 then incomeamount             else null         end) [thu],         avg(case             when incomeday = 'fri'                 then incomeamount             else null         end) [fri],         avg(case             when incomeday = 'sat'                 then incomeamount             else null         end) [sat],         avg(case             when incomeday = 'sun'                 then incomeamount             else null         end) [sun] from    #dailyincome group by vendorid 	0.435350330420476
11980687	16307	mysql math - calculate value from another column	select devices.id, devices.d_type, devices.multiplier, devices.`value`, if(multiplier = '/', 1/value, 1*value) as eps from devices; 	0.000139509342792435
11982067	21943	how to select in table and results sorted by another table	select p.from_id  from posttable p left join lovetable o on p.from_id=o.uid and o.post=100  where p.post_id=100 order by o.uid is not null desc,p.from_id 	4.61801529647751e-05
11984180	36025	how to get the un answered questions in quetion table?	select * from  users as ru left join answers as ra on ru.uid=ra.uid  left join questions as rq on rq.uid=ru.uid  where   rq.qid not in(select qid from answers) group by rq.qid order by rq.qid desc 	0.00518591553212466
11984526	21588	mysql call result order by other table	select uid_frm from post_table a      left join user_table b         on a.uid_frm = b.fid where postid = '10' order by (if(b.name = 'tom', b.fid, null)) asc, a.uid_frm asc 	0.0469633316085007
11985037	3521	sort max score in time length of each player	select player_id, max(score) as max_score from score  where month(time) = month(now())  group by player_id order by max_score desc 	0
11985864	35688	how do i count the number of pageviews per day of the month in mysql?	select day(_date),sum(pageviews) from pageviews group by day(_date) 	0
11986307	32670	how to split the string value in sql	select (case when charindex('+', title) > 0              then right(title, charindex('+', reverse(title))-1)              else title         end) as lastone 	0.00155424620913037
11987067	21911	pivoting of data using two columns	select user_id,    max(case when lang = 'fi' then org else ' ' end) org_fi,   max(case when lang = 'fi' then position else ' ' end) position_fi,   max(case when lang = 'en' then org else ' ' end) org_en,   max(case when lang = 'en' then position else ' ' end) position_en,   max(case when lang = 'sv' then org else ' ' end) org_sv,   max(case when lang = 'sv' then position else ' ' end) position_sv from source group by user_id order by user_id 	0.000902459270633062
11987584	10745	sql server order by query	select name from listing l left join listingproperties lp on l.id=lp.listingid order by isnull(lp.fixedprice, l.currentprice) 	0.72453770482297
11988395	16155	writing a query to select specific foreign key entries given a specific criteria	select distinct userid from yourtable t where t.productid=@productid1 and not exists(select userid from yourtable                        where userid=t.userid and productid=@productid2) 	0
11989483	38343	select entries filtering rows with same field by lowest second_field	select id, flag, price from tbl t where not exists (   select 1   from tbl tt   where t.flag = tt.flag     and (tt.price < t.price           or (tt.price = t.price and t.id < tt.id))); 	0
11992845	39924	how to find the number of results a query returns in my mysql?	select count(*) as count from mytable where... int count = rs.getint("count"); 	0.00202044330538316
11993073	32462	is there away in sql server to sort by the number of matched words in a contains function on a full text index	select * from myitemstable m inner join containstable(myitemstable, description, 'truck or blue or with or gold or two or tone') as l     on m.myitemstable=l.[key] 	0.00414405802012523
11993331	31834	mysql query, conditional join if in between two dates	select current.*, programs.name,    case when t.id is null then 0 else 1 end as betweenstartend from current    left join programs on current.pid = programs.id    left join timewindows t on (t.pid = current.pid      and date_format(now(), '%y-%m-%d') > start_date      and date_format(now(), '%y-%m-%d') < end_date   ) order by pid asc 	0.0659952018018341
11995065	18394	order results by results from a different table in one query	select     * from     `images` order by     (select count(`id`) from `image_likes` where `image_id`=images.`id`) asc 	0.000255904383587701
11995297	2080	sql - compare datetime with current datetime	select * from banners  where now() between banner_start_date and banner_end_date 	0.000836556548026295
11997049	23107	strategies for storing derived data in a normalized relational database	select c from comment c join fetch c.target t join fetch t.group g where g.id = :groupid and c.datecreated > :date 	0.113332304749689
12000770	18746	sql query for showing monthly report	select    sno,   toolname,   projectname,    year(dtfrom) as year,   jan=sum(case when month(dtfrom) =1 and month(dtto)=1 then quantity else 0 end),   feb=sum(case when month(dtfrom) =2 and month(dtto)=2 then quantity else 0 end)        ..... from <table> group by toolname,   projectname,   dtfrom 	0.181756402924327
12000789	24270	php mysql date extract with distinct	select distinct date_format(colname, '%y-%m') from tablename 	0.0155803658441411
12001017	26701	why i must double quote the schema name and the table name in order to query from an oracle table?	select * from m."album" 	0.0644443130616753
12001304	38352	sql query: please help weird output on sql query. (counting each client latest status)	select s.user_id, s.act_status, count(s.act_status) as countofact_status from tbl_sactivity as s inner join [select a.client_id, max(a.act_date) as max_act from tbl_sactivity as a group by a.client_id]. as s2 on (s.act_date = s2.max_act) and (s.client_id = s2.client_id) group by s.user_id, s.act_status 	0.432094095681854
12003013	13682	stitch two mysql tables with a common column	select a.contract_id, a.price1, a.price2, a.price3, b.owner, b.address from (select contract_id, price1, price2, price3, (@rank := @rank + 1) as rank       from t1, (select @rank := 0) tmp      )a left join       (select contract_id, owner, address, (@rank1 := @rank1 + 1) as rank       from t2, (select @rank1 := 0) tmp      )b on a.rank = b.rank and a.contract_id = b.contract_id order by a.rank asc; 	0.00104507174617793
12003276	31273	mysql concat address into string seperated by commar	select    concat_ws(', ',         nullif(location_address1, ''),        nullif(location_address2, ''),        nullif(location_town, ''),         nullif(location_region, ''),         nullif(location_postcode, ''),         nullif(country_name, '')   ) as address from    countries c       where    c.country_id = locations.country_id limit 1 	0.00984770174359922
12003957	22632	sql oracle: replace an empty result with word	select member from tablemember where membergroup = 'testgroup' union   select  'no entry'   from dual   where not exists ( select member from tablemember where membergroup = 'testgroup') ; 	0.558502858704907
12004059	19027	subtraction between two queries	select * from b where  not exists (select no from a where a.id=b.id and date=@yourdate) 	0.032983274036425
12006428	7778	mysql query for find category	select p.name   from products p     join product_category pc on  p.id=pc.prod_id     join category c on c.id = pc.categ_id  where c.name='category' 	0.0142326514214637
12006713	30232	find where a row of data in one column doesn't exist in another column	select table1.column1 from table1 where table1.column1 not in (select table2.column2 from table2) 	0
12006722	28628	get dummy records for attendance in ms access	select caldate,stid,atdate,present   from calendar  left join attendances  on calendar.caldate=attendance.atdate 	0.0675940992337832
12007072	32101	i ask for the datetime value with datareader and get the min value	select docnumber, doctype,  cast(cast(createdate as varchar(10)) + ' ' + cast(hora as varchar(12)) as datetime) as fulldate from solped 	0.000376071835608744
12008953	23898	mysql - how to get all differences from one table to another (huge amount of rows ~ 500k)	select distinct new_ids from synchro_newitems n where not exists (select 1 from synchro_olditems o where n.new_ids = old.old_ids) 	0
12009961	38537	how do i search a mysql database for a specific column name	select table_name,table_schema from information_schema.columns where column_name='sort_method' 	0.0027001462249265
12010014	12412	mysql querying a many-many relationship table - 'relational divison'?	select pageid from t join      list l      on t.tagid = l.tagid cross join      (select count(*) cnt from list l) as const group by pageid having count(*) = max(cnt) 	0.149656407284118
12011569	39477	normalize array subscripts for 1-dimensional array so they start with 1	select ('[5:7]={1,2,3}'::int[])[-2147483648:2147483647]; 	0.562037514152956
12011640	11447	select statement to return additional row	select mycol from mytable union all select 'something' as mycol 	0.0331138849604783
12012452	26331	sql to oracle sql conversion	select pd.propertyid, pd.propertyname, cast(v.value as varchar(255)) as displayvalue from property_dictionary pd inner join      corptax_lookupdefinition l      on l.lookupkey = pd.referencetype join      mdtable md      on l.datadictionarytypeid = md.tableguid join      valuechar v       on v.tableid = md.tableid and          v.attributeid = l.displayattributeid  where pd.datatypeid = 7 and pd.propertyname = 'esregion' 	0.763302511262706
12015314	27051	aggregating data from multiple columns (similar to a pivot table)	select 'c1',sum(case when c1=1 and c3=1 then 1 end)as c3,             sum(case when c1=1 and c4=1 then 1 end)as c4 from t1 union all select 'c2',sum(case when c2=1 and c3=1 then 1 end)as c3,             sum(case when c2=1 and c4=1 then 1 end)as c4 from t1 	0.000416561033909942
12016499	4057	select distinct from two columns in t-sql	select id, (select top 1 type from tbl a where id = b.id) from tbl b group by id 	0.000517522996752423
12017189	6774	how to check whether column in table contains any of a set of values?	select distinct column1 from table1 where column1 in ("string1","string2","string3") 	0
12018775	23822	done: for z companies, calculate average value of a over x days. how do i now: return value of b for day x for company with highest average of a?	select s.sp100_id, s._date,        (s.bullishness+splus1.bullishness+splus2.bullishness)/3 as avgb,        splus2.returnpct from (select s3.*,              (select min(_date)                     from stocks s4                     where s4.sp100_id  = s3.sp100_id and                           s4._date > s3.dateplus1                    ) as dateplus2       from (select s.*,                    (select min(_date)                     from stocks s2                     where s2.sp100_id  = s.sp100_id and                           s2._date > s._date                    ) as dateplus1             from stocks s            ) s3      ) s left outer join      stocks splus1      on s.sp100_id = splus1.sp100_id and         s.dateplus1 = splus1._date left outer join      stocks splus2      on s.sp100_id = splus2.sp100_id and          s.dateplus2 = splus2._date order by 2, 3 desc 	0
12022900	19645	how can i count elements with using timestamp	select      count(timestampcolumnname)  from      yourtable  where      timestampcolumnname>date_sub(now(), interval 30 minute) 	0.00778047913632935
12024847	1655	way to join 4 mysql tabels	select     articles.id,     articles.user_id,     articles.article,     users.name,     count(article_comments.id) as `num_comments`,     sum(article_points.points) as `points` from     articles inner join     users on     articles.user_id = users.id left outer join     article_comments on     article_comments.article_id = articles.id left outer join     article_points on     article_points.article_id = articles.id group by     articles.id 	0.607953104681852
12024989	24957	format result from timediff in days:hours:min:sec	select concat(    floor(hour(timediff('2012-08-05 09:56', '2012-08-02 11:20')) / 24), ' days, ',    mod(hour(timediff('2012-08-05 09:56', '2012-08-02 11:20')), 24), ' hours, ',    minute(timediff('2012-08-05 09:56', '2012-08-02 11:20')), ' minutes, ',    second(timediff('2012-08-05 09:56', '2012-08-02 11:20')), ' seconds') as timediff 	0.0179558633225721
12025886	33492	not sure how to make the correct mysql query to get data from multiple tables in 1 query	select projects.id,         projects.name,         projects.start_date,         projects.end_date,         projects.finished,         users.username as project_leader,         count(tasks.id) as tasks from projects left join tasks on (tasks.project = projects.id) join user_has_project on (user_has_project.projectid = projects.id) join users on (projects.project_leader = users.id) where user_has_project.userid = 1 group by projects.id 	0.017362638449971
12026016	27257	sql server 2005 select from multiple tables	select top 200 col1, col2 from (     select col1, col2 from table1     union     select col1, col2 from table2     union     select col1, col2 from table3     union     select col1, col2 from table4 ) mytablealias order by col1 	0.0442418517110221
12026244	33087	ordering records by a field only with respect to records with the same id	select * from thetable order by  id, weight desc 	0
12027529	13652	price difference table in sql with date	select t1.id, t1.dt date_1, t2.dt date_2, t1.hotel,     t1.price price_1, t2.price price_2, t1.price - t2.price difference from test t1 inner join (     select id, dt, hotel, price     from test ) t2     on t1.hotel = t2.hotel     and t1.dt < t2.dt 	0.00190789293168845
12028721	30082	order by date bugs	select id, header, date from table order by str_to_date(date, '%d-%m-%y') desc 	0.0780177123512601
12029790	30087	mysql return rows with number of column relationships in another table	select `categories`.`category_title`, total_posts  from `categories` join      (select categoryid, count(posts.post_id) as total_posts       from `posts`       group by categoryid       having count(*) > 3      ) pc      on `pc`.`category_id` = `categories`.`category_id` order by `categories`.`date_created` desc 	0
12034178	27376	suitable mysql query for latest status	select  a.*, b.`datettime`, d.status_txt from    tickets a             inner join statusses b                 on a.id = b.ticket_id             inner join             (                 select  ticket_id, max(`datetime`) currentticketdate                 from    statuses                 group by ticket_id             ) c                 on  b.ticket_id = c.tecket_id and                     b.`datetime` = c.currentticketdate             inner join status_codes d                 on b.status_id = d.id 	0.0123929801652962
12034849	29177	accessing column alias in postgresql	select *  from (     select distinct robber.robberid, nickname, count(accomplices.robberid)       as count1 from robber                        inner join accomplices       on accomplices.robberid = robber.robberid       group by robber.robberid, robber.nickname   ) v order by count1 desc 	0.256904425146842
12036030	8515	sql - find total records that occur before another	select a.* from      (select clientid,typeid,min(date) as date      from event      group by clientid, typeid)a join     (select clientid,min(date) as date      from event      group by clientid)b  on   b.clientid=a.clientid  and  b.date=a.date  where typeid=10 	0
12038471	5552	mutual non-mutual friend query mysql	select m1.* from wp_fd_matches m1 left outer join      wp_fd_matches m2      on m1.event_id = m2.event_id and         m1.event_user_id = m2.event_user_match_id         m1.event_user_match_id = m2.event_user_id where m2.id is null 	0.549371269049503
12038975	32765	mysql query group by	select        recipecomments.recipeid,       max(recipecomments.commentid),       recipes.recipeid,       recipes.name,        recipes.categoryid,       recipes.ratingtotal,       recipes.imagemed  from recipecomments                    join recipes on recipecomments.recipeid = recipes.recipeid   group by        recipecomments.recipeid,       recipes.recipeid,       recipes.name,        recipes.categoryid,       recipes.ratingtotal,       recipes.imagemed 	0.513514763275716
12042136	7595	mysql group by 2 columns combine results	select field, sum(cnt) from (   select rb_1 as field, count(*) as cnt   from ci_lineups   group by rb_1   union all   select rb_2 as field, count(*) as cnt   from ci_lineups   group by rb_2 ) group by field order by sum(cnt) desc limit 10; 	0.00276178301680896
12042164	34557	what stored procedures update a table?	select object_name([object_id])   from sys.sql_modules   where lower(definition) like '%update%table_name%'; 	0.532654397954171
12042240	3820	sql multiply and round in select statement	select  a.rate as 'rate'  ,a.loi as 'liability'  ,cast((a.rate * a.loi / 100) as decimal(38,2)) 'premium' from tblaspecs a 	0.240175754114477
12042331	20666	select in sql should give false if there is one record with 0. possible?	select     sum(amount),    case when sum(cast(isconfirmed as int)) = count(*) then      1    else      0    end as isconfirmed from repamount where comid = 1234 group by rd.date 	0.137843637701605
12042418	18139	timestamp difference and get hours, minutes, and seconds alone	select hour(x.timediff), minute(x.timediff), second(x.timediff)  from    (     select sec_to_time(avg (timestampdiff (second, `survival`, `lastupdate`))) as timediff     from main   ) as x 	0
12043017	5393	i want to combined two sql queries into one	select so.shop_order_id, so.shop_order_suffix, so.status, so.mfg_method, so.description,  so2.user_att27, so2.user_att28     from shop_order so      join shop_order so2 on so2.shop_order_id like 'zz1810c%'     where so.shop_order_id = 'zz1810c' and so.shop_order_suffix = '000'     order by shop_order_suffix desc; 	0.00208634747481184
12043515	41166	merging many to many results	select      id,     max( case when name = 'flavor' then value else null end ) as flavor,     max( case when name = 'type' then value else null end ) as type from prefix_site_tmplvars     left join prefix_site_tmplvar_contentvalues      on prefix_site_tmplvar_contentvalues.tmplvarid = prefix_site_tmplvars.id     left join prefix_site_content     on prefix_site_tmplvar_contentvalues.contentid = prefix_site_content.id where prefix_site_tmplvar_contentvalues.value = "chocolate" group by id 	0.0242254250409964
12043540	30687	display information from sql server view	select column1, column2 from dbo.example_view; 	0.00329293894379677
12048633	13340	sql query to find record with id not in another table	select id, name  from   table1  where  id not in (select id from table2) 	0.0001311975654292
12050110	26400	sql query to get countries	select c.country from   countriesinfo c  join     (select *      from  countriesinfo      where country='india')a on c.continent=a.continent 	0.0767801507108761
12050179	3339	how to specify schema name in connectionstring in asp.net	select field1, field2 from [schema].[table] 	0.634372646312081
12051111	30810	select 2 columns from 3 tables	select  c.c1, b.c2 from    t1 a             inner join t2 b                 on a.i2 = b.i2             inner join t3 c                 on a.i1 = c.i1 	0.000155142505622463
12052026	18230	compare two table ids and create third column based on same ids	select t1.id,         t1.name,        case when t2.id is null              then 'false'              else 'true'          end doesexist   from table1 t1   left join table2 t2     on t1.id = t2.id 	0
12052135	20819	get multiple data from column in one row	select tutor, group_concat(projects separator ',') as projects_list from your_table group by tutor 	0
12052221	28538	combining two view into one result set with transform?	select isnull(a.town, b.town) town,        isnull(a.tileroofs, b.tileroofs) tileroofs,        isnull(a.[brick wall], b.[brick wall]) [brick wall],        isnull(a.flats, 0) flats,        isnull(b.houses, 0) houses   from viewone a   full outer join viewtwo b     on a.town = b.town    and a.tileroofs = b.tileroofs    and a.[brick wall] = b.[brick wall] 	0.00094775103712101
12052405	36560	past 26 weeks and their respective week number	select (number/7)+1 as multiple ,         number+1 as number,         dateadd(dd,-(182-number),getdate()) as equivdates from    master..spt_values  where   type='p' and     number<182 	0
12054315	3309	get date from varchar stored date format for friends birthday	select u.fname, u.lname, u.profile_pic, u.uid, u.bday, f.uid, f.friend_id, f.status from      friend_list f, users_profile u where f.uid = '3' and f.status = '1' and u.uid = f.friend_id        and    day(str_to_date(u.bday, '%m-%d-%y')) = day(curdate()) and     month(str_to_date(u.bday, '%m-%d-%y')) = month(curdate()) 	0
12060038	7323	crystal reports: record selection snafu	select itemid, new_state, rec_date, max_newstate from (select itemid, new_state, rec_date from table) t inner join (select itemid, max(new_state) as max_newstate     from state_change     where change_time < {?enddate}       group by itemid) mx on t.itemid = mx.itemid and t.new_state = mx.max_newstate 	0.142176781010972
12060271	35024	xquery on 2005 and sqlsm2008	select @@version 	0.671965168347352
12062160	34258	mysql group by & return largest group	select fruit from (     select fruit, count(*) as `count`     from fruits     group by fruit ) sub order by `count` desc limit 1; 	0.0246786681736212
12062565	23060	use a second order by in mysql query	select t.* from (<your query here>) t order by expiry_date desc 	0.141945395479974
12062772	16354	once an hour results from mysql	select * from records r where not exists (select 1                   from records r2                   where r2.eventoccured > r.eventoccured and                         timestampdiff(minute, r.eventoccured, r2.eventoccured) < 60                  ) 	0.000591060688952346
12063302	9503	get list of programtypes for booked programs	select distinct programtype.label from program join      programtype      on program.programtype = programtype.id where exists (select occurrence.uuid               from booking inner join                    enrolment                    on enrolment.booking = booking.uuid  inner join                    occurrence                    on occurrence.id = enrolment.occurrence and                       occurrence.programme = programme.uuid and                       booking.status in ('completed','booked')              ) 	0.00216980474798825
12063519	3179	mysql find like items in same column	select * from mytable as t1  inner join mytable as t2  on t1.name = t2.name  and t1.address like concat(t2.address, '%')  and t1.address != t2.address; 	0.000682359003696866
12064426	14493	see contents of table variable using immediate / locals windows	select * from @table 	0.0489378263369003
12065325	642	mysql query from query results	select a.*, group_concat(u.user_name separator ', ') as allusers from announcements a join      acknowledgement ak      on a.announce_id = ak.announce_id join      user u      on u.user_id = ak.user_id group by a.announce_id 	0.186206863197931
12067261	32165	result from two tables without join condition	select    (select count(u.user_id) as count1 from users where user_id>1001) as count1,   (select count(c.hits) as count2 from source  c where loginid like 'fb%') as count2 	0.00636652906925993
12067687	14490	mysql display by date grouping	select date(min(your_date_column)), date(max(your_date_column)), customer from your_table group by customer 	0.00341773688535965
12067864	38005	mysql date_add interval with mysql table fields	select datas.day_count, datas.day_type, min( datas.start_date ) as mindate, max( datas.end_date ) as maxdate, start_date, min(start_date) as min_date, case day_type    when 'month' then date_add(max( datas.end_date ),interval datas.day_count month)    when 'day' then date_add(max( datas.end_date ),interval datas.day_count day)  end as exactdate, datas.trade_service_id from datas 	0.0689539555146231
12070420	6451	fastest way to perform multiple "in" queries in sql	select su.systemuserid from [dbo].[systemuser] su  where su.systemuserid in (     10, 61, 80, 93, 98 ) except select gm.systemuserid from [dbo].[groupmembership] gm where gm.groupid in (     1, 7, 8, 10, 32 ) 	0.596540716554014
12071027	27478	display random data from table	select name, link, table from mytable order by rand() limit 1 	8.89204200229602e-05
12072113	29366	obtain the missing number	select top 1 x.letterid +1  from tablename x where not exists(select * from tablename xx where xx.letterid  = x.letterid  + 1) order by x.letterid 	0.00484226552356963
12074074	3499	two sum() queries on the same table but using different where clauses	select    category_id   ,sum(content_add) as content_add_count   ,sum(category_add) as category_add_count   ,sum(if(issued_by_user != '" . $user_id . "' and plus = '1',normal_vote,0)) as agree_votes from table1  where user_id = '" . $user_id . "'  group by category_id 	0.000136084533722331
12074530	21457	sql server : getting a unique count from multiple xml rows?	select      id,     count(distinct( x.sw.value('@name','varchar(50)'))) from     detailstable cross apply     detailstable.details.nodes('/details/software') x(sw) group by id 	0.000208347219709999
12075582	34838	dropping all views in postgresql	select 'drop view ' || table_name || ';'   from information_schema.views  where table_schema not in ('pg_catalog', 'information_schema')    and table_name !~ '^pg_'; 	0.153421022672018
12076332	18762	interleaving values in single column of resultset	select val from ((select distinct hm as val, 1 as ishm,               dense_rank() over (order by hm) as ranking        from t       ) union all       (select cast(box_no as varchar(255)), 0 as ishm,               dense_rank() over (order by hm) as ranking        from t       )      ) a order by ranking, ishm desc, val 	0.000598551794913255
12076443	20299	sql count messing up when joining table to itself	select d.userid     ,avg(cast(c1.choice as float))     ,avg(cast(c2.choice as float))     ,avg(cast(c3.choice as float))     ,avg(cast(c4.choice as float))     , d.cnt from (   select userid, count(*) cnt   from tbltmpdemographics   group by userid ) d inner join tbltmpdemographics c1    on d.userid = c1.userid inner join tbltmpdemographics c2    on d.userid = c2.userid inner join tbltmpdemographics c3    on d.userid = c3.userid inner join tbltmpdemographics c4    on d.userid = c4.userid where c1.qid in ('1','5')   and c2.qid in ('2','6')   and c3.qid in ('3','7')   and c4.qid in ('4','8') group by d.userid,  d.cnt 	0.116751037961393
12076780	38350	match against "foo.bar" (with a full-stop/period)	select col1, col2 from some_table where match (col1,col2)     against ('+\"foo.bar\"' in boolean mode); 	0.338415818695573
12077575	21866	mysql aggregate by month with running total	select t.date        , t.newusers        , @rt := @rt + t.newusers as `running total`     from (select @rt := 0) i     join (            select date_format(created,'%y%m%d') as `date`                 , count(item_id) as `newusers`              from ap_user             where year(created) > 2011               and user_groups = '63655'               and user_active = 1               and userid not in $excludedusers             group by date_format(created,'%y-%m')             order by date_format(created,'%y-%m') asc          ) t 	0.00759219463938471
12077958	29706	oracle find duplicate records that are similar but aren't exact matches	select a.mytext_column search,        b.mytext_column compare,        utl_match.jaro_winkler_similarity( a.mytext_column, b.mytext_column ) similarity   from table_name a,        table_name b  where a.<<primary key>> != b.<<primary key>>  order by utl_match.jaro_winkler_similarity( a.mytext_column, b.mytext_column ) desc 	0
12081522	37910	count different values	select region, count(distinct politicalviews),  sum(politicalviews='liberal'), sum(politicalviews='conservative') from table group by region; 	0.00459654249670256
12081611	4897	getting quize data, questions and answers in 1 query?	select      question,      group_concat(qa.answer separator ',') as answers,     group_concat(qa.user_id separator ',') as userids,     group_concat(up.nickname separator ',') as nickname from quize_questions qq inner join question_answers qa on qa.question_id=qq.question_id inner join user_profile up on up.user_id = qa.user_id group by qq.question_id 	0.10825456146884
12082353	8411	select rows in a self-relationship where all children meet a condition	select distinct `documents`.* from (`documents`) left outer join `documents` children_documents   on `documents`.`id` = `children_documents`.`parent_id`   and `children_documents`.`status` = 'accepted' where `children_documents`.`parent_id` is null 	6.41514135564967e-05
12082475	33334	count by ratio and then group by msql	select      id,      sum(if(name like 'a%',1,0))/sum(if(name like 'b%',1,0))  from `table`  group by id 	0.0216294132971521
12082757	21680	is it possible to have group by sort in any order other than ascending?	select * from (select         u.id as user_id,         u.name,         i.id as item_id,         i.timestamp       from user u       join item i on i.user_id = u.id       order by timestamp desc      ) x group by user_id 	0.00373086012884349
12085382	34401	how to get the matching db record	select teamid  from player_team  where playerid in (p1_id,p2_id,p3_id,p4_id) group by  teamid having count(playerid) = 4 	8.94494582706981e-05
12086310	26195	get two days data from mysql table	select * from table_name  where check_in_mktime >= unix_timestamp(curdate() - interval 1 day) 	0
12086528	3615	sql query for retrieval	select * from table where lat > 0  group by id 	0.705763971630108
12087284	18152	sort sql result by date greater than today (d-m-y)	select * from my_table where my_date_field >= curdate() 	0.000940735404570968
12087519	10505	how to query 10 random unique records in mysql database?	select distinct(category),id,image_name from images    where id=     (floor(rand() *             (select count(*) from images )           )     ); 	8.84960685199208e-05
12088119	7731	sql select with multiple and and or's	select * from table1 where custid = 20   and confirmed = 1   and (cancelled <> 1 or cancelled is null)   and (completed <> 1 or completed is null) 	0.695152575129534
12088681	10413	the equivalent of cross apply and select top	select     countryid, country, cityid, countryid, city from ( select cities.*,     country,     row_number() over (partition by cities.countryid order by cityid) rn from  cities     inner join countries on cities.countryid= countries.countryid ) v where rn<=3 and countryid=1 	0.502074399337296
12088959	5882	merging unused timeslots	select      staffid,     branchid,     min(starttime),     max(endtime),     patientid from ( select *,            row_number() over (order by starttime)        - row_number() over (partition by isnull(patientid,-1) order by starttime) rn      from @results ) v group by staffid, branchid, patientid, rn order by min (starttime) 	0.0526626818488483
12090371	39088	how to find the birth month	select id, dob from   table1 where  month(dob) =10 	0.00012579333145622
12090772	18913	unix timestamp bigint(20)	select from_unixtime(634583466272408810/1000000000) 	0.0149492753197087
12091047	10520	selecting like value in subquery	select distinct initial   from atm_tasks_dit,atm_name_initials  where task_given_to like concat('%',initial,'%') 	0.127506342736175
12091516	33467	how to find matching fields in another table	select * from stats, pages where  stats.url like '*' & pages.pageid & '*' 	0
12091530	31551	mysql query to find the last insert code	select 1+max(convert(right(your_column_name, 4), signed)) as newindex from your_table where your_column_name like 'p%'; 	0.00142233936447803
12091762	7385	order by specified order before group by	select *, count(`ap_id`) as `num` from (         select `account_id`, `product_id`, `product_name`, `ap_status`, `ap_id`         from (accounts_products_view)         where `account_id` = 13         order by field(`ap_status`, 'n', 'p', 'd', 'c', 'b', 'x') desc     ) as res group by product_id 	0.184563527242589
12092307	18569	sql query to find the avg salary based on the nearest client dob's	select t1.clientid,         t1.clinetdobs,        avg(t2.slaries) avg_slaries   from table1 t1  inner join table1 t2     on t1.clinetdobs >= t2.clinetdobs    and t1.clinetdobs <= dateadd(day, 3, t2.clinetdobs)    and t1.jobtype = t2.jobtype   group by t1.clientid,         t1.clinetdobs having count(*) > 1 	0.000177357259278147
12092756	22402	sql joining two tables and fetching a value	select a.*, b.emp_compensation from talent_employee_details_v a join      talent_empcomp b      on a.empid = b.emp_id where a.emp_firstname like '%' and a.emp_id='$emp_id' order by a.emp_firstname 	0.000960303916576619
12093055	30165	retrieving the last filtered record in each group	select m.*, t1.* from mood m  left join temper t1 on ( m._id = t1.mood_id and t1.status_id !=1)  left join temper t2 on ( t1.mood_id = t2.mood_id and t1._id < t2._id and t2.status_id !=1 )  where t2._id is null  and m.grantee_username = "username"  and m.status_id != 1; 	0
12094306	8709	issue retrieving particular sql rows	select "limit" from rules 	0.0260849207956804
12096801	35325	sql query to fetch data with a time interval	select * from (     select *,         datepart(minute, yourdate) mn,         row_number() over(partition by datepart(minute, yourdate) order by yourdate) rn     from yourtable ) x where (mn % 5) = 0     and rn = 1 	0.00638602565902182
12096930	5108	how to get the rowcount from the query itself (i.e. without mysql_num_rows() or found_rows())	select count(distinct lot_id,data_file_id)    from data_cst   where target_name_id=208082     and wafer_id=425845; 	0.037098143359336
12097368	17230	mysql order by string with numbers	select * from table_name order by     substr(col_name from 1 for 1),     cast(substr(col_name from 2) as unsigned) 	0.0698595576551883
12099296	17201	postgresql coalesce	select coalesce((1.0 * 7)/2, 0) as foo; 	0.76760375596192
12100275	39344	how to count non-null/non-blank values in sql	select   job_number, item_code,  case when rtrim(pono) = '' or pono is null then 0 else 1 end +  case when rtrim(partno) = '' or partno is null then 0 else 1 end +  case when rtrim(trinityid) = '' or trinityid is null then 0 else 1 end   as [count] from yourtable 	0.0366207930154837
12100294	34650	joining tables in oracle 8i to limit results	select a.part_primarykey, b.part_price, a.po_date   from po a, po_lineitem b  where a.po_primarykey = b.po_primarykey        and (a.part_primarykey, a.po_date) in              (  select a.part_primarykey, max(a.po_date)                   from po a, po_lineitem b                  where a.po_primarykey = b.po_primarykey               group by a.part_primarykey); 	0.292755836379626
12100835	39696	sql multiple tables replace results from table	select m.subject, m.body, u.username,m.priorityid from messages m inner join messageuser mu on mu.messageuserid = m.frommessageuserid inner join users u on mu.userid = u.userid 	0.00780610079768153
12101212	6234	mysql parent details if it is a child account	select a.id, e.email  from account a           inner join emails.e                on e.account_id = if(a.parent <> 0, a.parent, a.id) 	0.0049000729026929
12101624	4310	getting rows by id from csv string	select * from table where something='yes' and id in (4,53,34,23) 	5.63770268491695e-05
12102267	22826	how do i select the 1st row from a selection of 10 random rows	select * from (     select * from table order by rand() limit 10 ) order by number desc limit 1 	0
12104510	18056	mysql sums and grouping by date	select `bannerid`,         date_format( `t_stamp` , '%m/%d/%y' ) as `date`,         sum( `views` ) as `views`,         sum( `uviews` ) as `uviews`,         sum( `hits` ) as `hits`,         sum( `uhits` ) as `uhits` from    test_bannerstats where   date( t_stamp ) between '2012-07-01' and '2012-08-24' group by date(t_stamp) order by date(t_stamp) asc; 	0.0294185968370514
12105893	19175	get top n results for each column value	select name,kind from ( select name,kind,       @i:=if(@kind=kind,@i+1,1) rn,       @kind:=kind        from t, (select @i:=0,@kind:='') d        order by kind,name ) t1 where t1.rn<=2      order by kind,name 	0
12107142	39455	how to get update record based on given record in oracle?	select *  from table1 where trunc(last_updt_s) = to_date('23-aug-12') 	0
12107842	40170	sql filter from many-to-many relationship	select      location_id  from categorylocations where category_id in (2,3) group by location_id having count(distinct category_id) = 2   	0.0594830001547456
12108139	11710	checking if id contained in a list in jpa	select p from person p where not exists  (select a from person pe left join pe.addresses a where p = pe and a.id = ?1) 	0.0199435489838969
12110055	31820	how to get two datetime fields difference in days and hours in postgresql view?	select to_char(end_date - start_date, 'd.hh24') as diff from your_table; 	0
12110171	21504	remove default order by from union statement	select   * from (   select 0 as pos, 'total avg' as column1, '60%' as column2   union   select 1 as pos,                column1,          column2 from tblavg  )   as data order by   pos, column1, column2 	0.0816800825717482
12110321	38976	is there a stuff() function available in oracle?	select to_char(          to_timestamp('24051103084950', 'ddmmyyhh24missff2'),           'yyyy-mm-dd hh24:mi:ss.ff3')    from dual 	0.711959208604653
12110853	2628	can i avoid locking rows for unnecessary amounts of time [in django]?	select_for_update() 	0.165545500550872
12113624	36106	mysql - get count of specific value inside a query that has a group by	select     count(*),     id_seed from     (         select              id_seed         from              messages          where              id_campaign = 140          group by              id_chat     ) group by     id_seed 	7.59075111055061e-05
12113635	10061	averaging a column twice in one query	select         node,        isnull(todaysavgloadtime, 0)        isnull(historicalloadtime, 0) from          (             select                   node,                   avg(loadtime) 'todaysavgloadtime'             from                   dbo.table             where                   failed != 1             and  datediff(day, datetimecst, getdate()) = 0              group by node         ) as a         full outer join         (             select                   node,                   avg(loadtime) 'historicalloadtime'             from                   dbo.table             where                   failed != 1             group by node         ) as b         on a.node = b.node 	0.00582986194859391
12115012	24379	mysql random m out of n selection	select * from students where schoolid = 10 order by rand() limit m 	0.00173408245549395
12115512	12774	calclute number of fields	select t.nametag, count(*)     from artitag at         inner join tag t             on at.idtag = t.idtag     group by t.nametag; 	0.00444762992012653
12116357	22213	mysql query to get first 200 characters	select left(column,200) from table 	0.00182427316166874
12116723	20069	mysql append unrelated table	select  a.rank, a.name, a.age, b.type from (select @rownum:=@rownum+1 ‘rank’, t1.name, t1.age from  table1 t1, (select @rownum:=0) r) a left join (select @rownum:=@rownum+1 ‘rank’, t2.type from  table2 t2, (select @rownum:=0) r) b on a.rank = b.rank 	0.0119782250019247
12116748	5679	ssas data source view variable	select player, investment,         investmentrange=        case when investment >=0 and  investment <(a.avg/3)              then 1             when investment >=(a.avg/3) and  investment <(4*a.avg/3)    then 2             when investment >=(4*a.avg/3) and  investment <(6*a.avg/3)  then 3                                      when investment >=(2*a.avg)                                 then 4        end                                from  aaaa cross join  (select sum(investment)/count(distinct meta_id) as avg from aaaa) a 	0.34694237714194
12117884	41187	mysql show events in logical order	select id, name, event_date from yourtable order by event_date < unix_timestamp(), abs(unix_timestamp() - event_date) 	0.0793452169458234
12118993	30722	mysql echo value only once from multible columns	select distinct name from (     select name1 name from table_name     union all     select name2 name from table_name ) 	0
12121724	32424	sybase sql: how to check if date or timestamp field is empty	select * from ... where ... and cast(mydatefieldname as char) is null 	0.00403465544899245
12124157	30372	selecting data from 3 tables using sql in oracle	select  employee.empid,  first, last,  location.locationid  from customer, employee, location where  customer.custid = employee.custid and employee.locationid = location.locationid and and employee.empid = '111111'; 	0.00243121969340847
12124304	27628	mysql query needs to count to different fields where one field is 1	select projects.id,        projects.name,        projects.start_date,        projects.end_date,        projects.finished,        users.username as project_leader,        count(tasks.id) as tasks,        count(nullif(tasks.finished, 0)) as finished_tasks 	0.00112399188249513
12124658	38533	calculating end time from a start time and a percent complete in mysql	select timestampadd(second, round(timestampdiff(second, '2012-08-22 22:00:30', now())*(100/33)), '2012-08-22 22:00:30'); 	8.28406610883393e-05
12126075	32949	how to do dynamic if statement in sql?	select case  when post.type = 'thread' then thread.deleted when post.type = 'response' then response.deleted else 'default' end from post  left join thread on post.effective_id = thread.id left join response on post.effective_id = response.id 	0.720849083383084
12126638	5861	mysql order by > swap results if values are equal	select product, clicks, rand() as rand  from suggestions  where source = :source_item_id  order by clicks, rand  desc  limit 7 	0.00533837484846982
12128077	15149	mysql: count, group by yet return all results	select  c.*, colorcounts.colorcount from    colors as c inner join  (             select color, count(*) as colorcount             from colors             group by color             ) as colorcounts         on  colorcounts.color = c.color order by c.color, c.id 	0.0167149751581153
12129227	31812	get only decimal part in float number in sql server	select substring (parsename(5.4564556,1), 1, 4) 	0.00027565367817728
12129697	36170	fetch data from database and display in datagridview	select      g.godown_name,      s.supplier_name,      t.type_name,     b.lb_per_bag,      sum(r.bags_instock) as total_bags_instock,      sum(t.rate * r.bags_instock)          /sum(r.bags_instock) as average_rate from tbl_godown_transaction  as gt join tbl_godown          as g  on gt.godown_id   = g.godown_id  join tbl_yarn_receive    as r  on gt.receive_id  = r.receive_id join tbl_yarn_book       as b  on r.book_id      = b.book_id  join tbl_yarn_supplier   as s  on s.supplier_id  = b.supplier_id  join tbl_yarn_type       as t  on t.type_id      = b.type_id group by     g.godown_name,      s.supplier_name,      t.type_name,     r.lb_per_bag 	7.35873656671975e-05
12131924	24409	referencing field values between queries	select     qb1.companyname,      qb1.assetname,      qb1.year,      qb3.mppoilrevised - totaldatapointvalue - totaldatapointvaluefactor from     ((         select              qb1.companyname,              qb1.assetname,              qb1.year,              sum(qb1.datapointvalue) 'totaldatapointvalue',             sum(qb2.datapointvalue * 1000000) 'totaldatapointvaluefactor'         from              (pebasequery as qb1              inner join pebasequery as qb2              on qb1.year = qb2.year and qb1.assetname = qb2.assetname)         where              qb1.datapointid in (2033, 2035, 2043, 2037, 2031)          and qb2.datapointid = 2003         group by qb1.companyname, qb1.assetname, qb1.year     ) qb1     inner join pe_mppoilrevised as qb3      on qb1.year = qb3.year and qb1.assetname=qb3.assetname) 	0.0163242840475634
12136392	31285	how to get second record onwards	select  yt.* from    your_table yt inner join         (             select  [id],                     min([datetime]) first_datetime             from    your_table             group by    [id]         ) f on  yt.id = f.id             and yt. [datetime] > f.first_datetime 	0.000102471319808713
12138264	29141	total time difference between login time and logout time-mysql	select t.user_id,        date_format(t.login_time,'%d %b %y') as datez,        sec_to_time(sum(time_to_sec(timediff(t.logout_time, t.login_time)))) as timediffe from tic_login_log t where user_id = 5       and login_time between '2012-08-01' and '2012-08-2' group by t.user_id,datez; 	8.37763175924536e-05
12139449	26013	number of rows in which two or more specified values appear	select count(*) from your_table where 1 in (n1,n2,n3,n4,n5) and 26 in (n1,n2,n3,n4,n5) 	0
12140345	31013	join query between 2 tables, the first with several fields refering to the same fields in the other	select alias1.name as name1,        alias2.name as name2,        alias3.name as name3   from t1  inner join t2 alias1     on t1.field1 = alias1.id  inner join t2 alias2     on t1.field2 = alias2.id  inner join t2 alias3     on t1.field3 = alias3.id; 	0
12140408	38663	how to get the count of the records in sql?	select p.projectname, count(b.bugid) as bugcount    from projects p        left join bugs b            on p.projectid = b.projectid   group by p.projectname 	5.37650223976201e-05
12142206	38046	pivot the results from this union query?	select * from (yourunionquery) src pivot (count(vendor_desc) for part in ([1],[2],[3], ... )) p 	0.67798948982982
12143166	20437	how to pull out the employees who have 'first name,lastname and date of birth' as same from employee table	select * from   (     select *,            count(*) over(partition by firstname, lastname, dob) as cc     from yourtable   ) as t where t.cc > 1 	0
12144260	21628	in mysql, in or like query is it possible to get the maximum matched result at the top?	select * from abc where xyz like $x or xyz like $y or xyz like $z order by ((xyz like $x) + (xyz like $y) + (xyz like $z)) desc 	0.00051719292134015
12144822	10477	oracle sql cursor for loop to check dates and assign a value	select t.*,        dense_rank() over (order by startdate) as trip from t 	0.00377612600013393
12147114	1600	select records that match some of the input criteria	select r.recipe.name, group_concat(i.ingredientname separator ', ') as ingredients,        count(*) as numingredients from recipeingredient ri join      recipe r      on ri.recipeid = r.recipeid join      ingredient i      on ri.ingredientid = i.ingredientid left outer join      desired d      on i.ingredientname = d.ingredientname group by r.recipe.name having max(case when d.ingredientname is null then 1 else 0 end) = 0  	5.55796629513348e-05
12147809	31477	adding two values in sql server	select   (select sum(emailssent) as firsttally    from jobagentemails    where date between '7/1/2012 12:00:00 am' and '7/31/2012 11:59:59 pm') - (select count(usermodified) as secondtally    from jobagents     where usermodified = 1) 	0.0259795758543009
12148394	39072	sql query to find leaves in a tree	select e.* from elements e left outer join elements leafs on e.id = leafs.parent_id where leafs.parent_id is null 	0.105074314359585
12149996	2131	computing a field to identify chronological order of datapoints that share the same id	select c.*,        (case when indicator = 1              then row_number() over (partition by id, indicator order by [date])         end) as orderindicator from current c 	0
12151849	15177	data from 3 tables with a primary key in common	select  a.accountid from    account a where   not exists  (                     select 1                      from invoice i                      where i.accountid = a.accountid                      and i.scheduletype = 'hold'                     and i.startdate < '8/1/2012'                     and i.enddate >= '7/1/2012'                     ) and     not exists  (                     select 1                     from visits v                     where v.accountid = a.accountid                     and v.sessiondate >= '7/1/2012'                     and v.sessiondate < '8/1/2012'                                       ) and     a.startdate < '8/1/2012' and     a.enddate >= '7/1/2012' go 	0
12152043	18429	how to get summary query using arbitrary expiration dates in second table?	select ld.period, ld.type, l.funding_code, l.vendor_code, sum(fee) as fee,        l.license_expiry_date from license_detail ld left outer join      (select l.*,              lead(license_expiry_date, 1) over (partition by license_type                                                 order by license_expiry_date)                                                ) as nextdate       from licenses l      ) l      on ld.license_type = l.license_type and         ld.active_date >= coalesce(license_expiry_date, ld.active_date) and         ld.active_date < coalesce(nextdate, to_date('9999-01-01', 'yyyy-mm-dd')) group by ld.period, ld.type, l.funding_code, l.vendor_code, l.license_expiry_date 	0
12154484	19166	create a view to add a row no. for a specific set of data filtered by a column index	select id, lecture, lecture.subject_id, date, c,  (select count(subject_id) + 1 from lecture as l   where l.subject_id = lecture.subject_id   and (l.date < lecture.date or (l.date = lecture.date and l.id < lecture.id))   and is_deleted != 1  ) as flow_no from lecture inner join (  select subject_id, count(subject_id) as c  from lecture  where is_deleted != 1  group by subject_id ) as counts on lecture.subject_id = counts.subject_id where is_deleted != 1 order by subject_id, date; 	0
12158220	26222	remove trailing numbers from field with sql	select trim(substring(tag, 1, (char_length(tag) - locate('(', reverse(tag))))) as new_tag from table_name; 	0.00279052401516787
12159053	19448	get last time activity with sum, group and subquery	select employee_id, name, sum(pieces) pieces, max(sl_time)   from db_schema.tbl_sales      group by employee_id, name   having sum(pieces) > 100 	0.00131565250837585
12159162	14307	sql: group by bases on computed column?	select      case when month(entbookings.bookingdate) <4          then year(entbookings.bookingdate)-1          else year(entbookings.bookingdate) end  as duration,      sum(dbo.entbookings.itemcost) as totalcost where   entbookings.branchid = @brachid group by case when month(entbookings.bookingdate) <4           then year(entbookings.bookingdate)-1           else year(entbookings.bookingdate) end as [year] 	0.0170018363732196
12159818	9966	what is the best way to write the date in mm-mm-yyyy in sql	select convert(varchar(8), getdate(),120)       + convert(varchar(3),datename(month,getdate())) 	0.703587686554232
12160768	37249	select the highest row based on mysql sum result, with relations	select a.student_id, a.student_firstname, a.student_lastname, a.isactive,      a.city_name,     a.student_startdate, a.student_enddate,     max(a.total)  from (select s.student_id, s.student_firstname, s.student_lastname, s.isactive,      c.city_name,     sd.student_startdate, sd.student_enddate,     sum(scpe.scpe_estemated_days) as total         from students s              inner join cityselections c on c.city_id = s.student_city_id             inner join studentdates sd on sd.student_id = s.student_id             left join studentcourseplan scp on scp.student_id = s.student_id             left join studentcourseplanelements scpe on scpe.scpe_cpl_id = scp.cpl_id                 group by scp.cpl_id) as a group by a.student_id; 	0
12160928	27134	get a parameter's name	select argument_name from all_arguments where object_name = 'sp_example'; 	0.0266174903201155
12161647	6296	combining 2 select queries using dates and then joining 2 tables	select  ea.`employee_id`, e.`employee_surname`,  e.`employee_first_name`,  e.`employee_second_name`,          format((if(sum...some basic maths...)),1) as nt,          format((...some basic maths...),1) as ot,          format((...some basic maths...),1) as total,          sum(case when weekday(ea.empl_attendance_date) > 5 then ea.empl_attendance_total end) as sundaytotal  from empl_attendance ea join       employee e       on ea.`employee_id = e.employee_id   where  ea.empl_attendance_date between '$start_date' and '$end_date'   group by `employee_id` 	0.000138379197829439
12161857	33254	same sql error in a few queries	select qb1.companyname        , qb1.assetname        , qb1.year        , (qb2.mppoil - sum( iif( qb1.datapointid=2003,                                  qb1.datapointvalue*1000000,                                  qb1.datapointvalue))) as unallocatedlossesoil from  pebasequery as qb1        inner join pe_mppoilrevised as qb2 on qb1.assetname = qb2.assetname where qb1.datapointid in (2032,2034,2042,2036,2030,2028) group by qb1.companyname          , qb1.assetname          , qb1.year          , qb2.mppoil; 	0.432901185830897
12161868	11511	how do you turn a date in sql to text using a select statement?	select firstname,        lastname,        prize,        datename(mm, winning_date) + ', ' + datename(yyyy, winning_date) as  from prize_table order by winning_date desc 	0.0410737192613898
12162890	11942	composite key queries in mysql	select m.m_id, m.name, m.version, m.descr       from module as m inner join mod_depends as md         on m.m_id = md.depends      where md.m_id_1 = 1; 	0.283536137165369
12162957	26321	php/mysql filtered search similar to facebook	select      name, slug, '$bp->groups->table_name' as table from      ".$bp->groups->table_name."                               where      name like '%".$search_string."%'         or      name = '%".$exp_string[0]."%'         or      name in ('".$join_string."'); 	0.339902941960726
12164336	6281	sql group by not equal results	select case when buyerstate in ('or','wa') then buyerstate else 'other' end   as "state",     count(buyerstate) as "acura",     saletype          as "n/u"  from   lydeal  where  stocklocationid = '8'     and saledate > '8/01/12'     and saletype = 'n'  group  by case when buyerstate in ('or','wa') then buyerstate else 'other' end,        stocklocationid,        saletype 	0.420826648556258
12164610	15872	select - values to columns in query	select   tablea.workplace,   tablea.date,   tablea.shift,   sum(downtimemins),  tableb.code1,  tableb.code3,   tableb.code4,   tableb.code6  from tablea  left join downtime on   tablea.workplace=tableb.workplace and   tablea.date=tableb.date and   tablea.shift=tableb.shift  group by tablea.workplace, tablea.date, tablea.shift 	0.00656683339105672
12164932	30413	oracle 11g sql query to get data from two tables joining	select sal_id,gal_id,actual_id,null estimate_id,amount,tax from actual where process_flag='n'  union all select sal_id,gal_id,null actual_id,estimate_id,amount,tax from estimate where process_flag='n' and (sal_id,gal_id) not in (select sal_id,gal_id from actual where process_flag='n') 	0.000542009957736556
12165072	16743	how to get number of records along with min/max values in mysql?	select count(recordcount),         max(max_price),         min(min_price)         from   (select count(a.id)   as recordcount,                 a.nos,                 a.nos_anzeige,                 max(preis_ek) as max_price,                 min(preis_ek) as min_price          from   artikelstammdaten a          where  a.iln != "1111111111111"                 and a.iln != "2222222222222"                 and a.iln != "7777777777777"                 and a.aktiv = "ja"                 and a.artikelnummer like '%name%'                 and ( a.modus = "open"                        or a.iln in ( 55555555555, 66666666666, 2222222222222 ) )          group  by a.iln,                    a.artikelnummer,                    a.preis_aktuell,                    a.artikelbezeichnung          having ( ( sum(a.bestand) != 0 )                    or ( a.nos = "ja"                         and a.anzeige = "ja" ) )) temp 	0
12165104	8198	oracle/hyperion xml date format	select to_date('19700101', 'yyyymmdd') + 1348257648893/(86400*1000) from dual; 	0.0833549089528424
12165354	31639	extracting portion of string using regexp_substr when it contains ( and )	select regexp_replace('fn_sum(accrued_interest)', '(.*)?\((.*)?\)(.*)?$','\2') from dual; 	0.0213805892970722
12166242	1458	import xml by matching on tag attribute content in sql server 2005	select     y.id.value('(@number)[1]', 'int') as number,    y.id.value('(@date)[1]', 'datetime') as [date],    cancelledorders = y.id.value('(value[@field="canceledorders"]/@value)[1]', 'decimal(18,4)'),    totaldollars = y.id.value('(value[@field="totaldollars"]/@value)[1]', 'decimal(18,4)') from       @input.nodes('/sales/store') as y(id) 	0.00286894206305133
12166957	30752	mysql group_concat label results from one column with value from another	select other_columns, group_concat(concat_ws('*', photoflag, photoname))     from yourtable     group by somecolumn; 	0
12167626	29842	mysql query for summing occurence of some column	select count(*) as 'login_times', name  from logins  group by name  order by login_times desc 	0.00768511669046699
12168592	39558	mysql results need to combine tables	select names.id, names.name, names.dog_id, dogs.dog from names left join dogs on dog_id = dogs.id; 	0.084821078664052
12170150	16475	logic in having clause to get multiple values of a group by result	select distinct a.user_id, a.code    from my_table a    where a.user_id in         (select b.user_id        from my_table b        where b.role_id = 13)     and a.user_id in         (select b.user_id        from my_table b        where b.role_id = 15)    and a.user_id not in         (select b.user_id        from my_table b        where b.role_id not in (13,15)) 	0.0190056403597756
12170202	396	percentage of day that has elapsed	select datediff(millisecond, convert(date, getdate()), getdate())/864000.0 	5.26614677902335e-05
12172094	22165	is there any way to count matches between 2 tables using sql?	select count(*) from table1 join table2 on table1.title = table2.title 	0.0120339749967603
12172679	29957	sql server - return multiple row values in single row	select substring( (select ';' + e.emailaddress from employee e for xml path('')),2,8000) as csv 	8.94313821786222e-05
12172768	4520	how to convert a query from mssql in to a query in msql	select date_add(now(), interval 1 second) as starttime 	0.0689338083167725
12173091	3449	tsql - query xml	select * from table where xmlfield.value('count(/dynamicresults/regquery[@regsubkey="software\microsoft\windows\blabla"]/*)','int')>0 	0.584598874910875
12173248	26748	calculating percentage within mysql query based on conditions	select 100 * sum(if(ca001result='fail', 1, 0)) / count(ca001result) as 'ca002 %' from data_table where '$product' and area='$area' 	0.00208077906746552
12173751	2275	select records between values of two columns	select * from (    select *, year*100 + week as yearweek    from table ) v where yearweek between 201150 and 201205 	0
12174252	86	aggregate query using percentage data	select qb1.companyname, qb1.year,        (((sum(qb1.defaultoil)*1000000)/sum(qb2.mppoil))*100) as peoil from pe_field_oil_gas as qb1  inner join pe_field_mppoilrevised as qb2  on qb1.assetname=qb2.assetname group by qb1.companyname, qb1.year; 	0.349292915939854
12177761	30681	mysql eav query returns all entries	select a.boatuid     from tx_gcnwnxmlparser_boats_specs a         inner join tx_gcnwnxmlparser_boats_specs b              on a.boatuid = b.boatuid                 and b.slug = 'taxpaidtoname'     where a.boatuid in (20,24,25)         and a.slug = 'taxstatuscode'         and a.fieldvalue = 'paid'         and b.fieldvalue = 'no'; 	0.00584764887576756
12178304	34015	mysql get dates that have records but are missing a specific record	select   user_id, stamp from     my_table group by user_id, stamp having   not sum(item_id=5) 	0
12178565	15959	sql group by item, with price in increments	select item_id, floor(quote * 4.0)/4.0 as roundquote, sum(qty) as qty from t group by item_id, floor(quote * 4.0) order by 1, 2 	0.00285596585571287
12178728	34300	count every distinct tag	select filename, group_concat(tagstr separator ',') as tags,        count(*) as numdistincttags,        sum(cnt) as numtags from (select filename, tag,              concat(tag, ' (', count(*), ')') as tagstr,              count(*) as cnt       from dados d       group by filename, tag      ) d group by filename order by filename 	0.00655390184693776
12179295	38295	comma separated sql server result set 'joined' with other columns	select projectname, stuff((select distinct ', ' + meternumber                from projectmeter m               where p.id = m.projectid             for xml path(''), type             ).value('.', 'nvarchar(max)')          ,1,1,'') meternumbers from projectmaster p 	0
12180133	24447	saving a checklist with values of checkboxes in a database	select clp.type from checklistlink cll join      checklistproperties clp      on cll.property_id = clp.property_id where cll.user_id = <user_id> 	0.0165025709703838
12181663	27071	how to join table in sql without removing data from table1	select     a.time_stamp,     a.rdate,     a.type,     a.person,     b.last, from table1 a left outer join table b on a.person = b.person 	0.00384676080756302
12182156	10942	alternative of executing same sql query again with different parameters	select (select table1.abc from table1 where col1 = ? and col2 = ?),     (select table1.abc from table1 where col1 = ? and col2 = ?),     (select table1.abc from table1 where col1 = ? and col2 = ?) from table1 limit 1 	0.579517996322437
12184363	17069	sql top and join	select eb.submitted_date     from event_bill eb     join     (     select event_id as prev_event_id     from  event      where customer_id = @custid     and event_type = 'followup'     and event_id < @eventid      and event_date =      (       select max(event_date)       from  event        where customer_id = @custid       and event_type = 'followup'       and event_id < @eventid      )     ) x     on eb.event_id = x.prev_event_id 	0.243845445848236
12184399	35001	sql max get the highest id	select      c.clientid, c.clientname, c.billingdate,      i.total - (select ifnull(sum(p.amount), 0) from payment p                 where p.invoice = i.invoiceid order by i.invoiceid) as remaining  from      client c  inner join      invoice i  where      c.clientid = i.client  and i.invoiceid = (select max(i2.invoiceid) from invoice i2 where i2.client = i.client)  order by      clientname 	0
12185270	37797	make sure that min() only retrieves one value	select r.* from result r join      (select r.athelete_id, min(result_id) as minresult_id       from result r inner join            (select athelete_id, min(result_time) as fastesttime             from result             where event_code = 1             group by athelete_id            ) rm            on r.athelete_id = rm.athelete_id and r.result_time = rm.fastesttime       group by r.athelete_id      ) aft      on r.result_id = minresult_id 	0.00236424120165227
12185753	29452	how to duplicate a record set spread over multiple tables in mssql?	select *  into #tablen from tablen where quotationid = @oldquotationid 	0.000262219973356645
12185951	6869	t-sql: build new table from result set	select [userid],     count(case when age < 14 then 1 else null end) as [less than 14 days],     count(case when age between 14 and 17 then 1 else null end) as [14 to 17 days],     count(case when age between 18 and 28 then 1 else null end) as [18 to 28 days],     count(case when age between 29 and 44 then 1 else null end) as [29 to 44 days],     count(case when age >= 45 then 1 else null end) as [over 45 days] from [db].[dbo].[db_view] group by [userid] 	0.0124358529370479
12186356	40035	convert column to row	select * from ( select cast(oi.orderid as varchar(max))+'.'+cast(oi.orderitemid as varchar(max))     as      ordernumber ,p.abbreviation as product, o.orderdate ,oifd.value as value ,oifd.fieldname as fieldname from orderitems oi join products p on p.productid = oi.productid join orders o on o.orderid = oi.orderid left join orderitemformdatafields     oifd   on  oifd.orderreference = cast(oi.orderid as varchar(max))+'.'+cast(oi.orderitemid as varchar(max)) ) as p pivot (     max(value) for fieldname in ([subj_street_addr],[add_subj_baths],[add_subj_bedrooms],[add_subj_date],[add_subj_gla]) )as pvt 	0.00661298346256092
12186549	39205	sybase *= to ansi standard with 2 different outer tables for same inner table	select   a.id,  a.name, b.id,   b.job,  a.job,  a.duty     from (select * from #jt1           cross join #jt3  ) a  left outer join #jt2 b       on a.id = b.id    and a.job = b.job 	0.189328265745827
12186610	27623	how to add a column via a query which counts the total rows with a specific criteria in a table with circular relationship in ms access 2007	select [employees].name, [employees].parentid, [employees].name, count([employees1].parentid) as noofemployees from [employees] left join [employees] as [employees1] on [employees].id = [employees1].parentid group by [employees].id, [employees].parentid, [employees].name; 	0
12186870	30640	complex multiple join query across 3 tables	select    a.*,           coalesce(b.item_cnt,  0) as item_cnt,           coalesce(b.avg_price, 0) as avg_price,           coalesce(b.buyer_cnt, 0) as buyer_cnt from      shops a left join (           select    a.cid,                      a.szbid,                      count(*)     as item_cnt,                      avg(a.price) as avg_price,                     b.buyer_cnt           from      shop_items a           left join (                     select   cid,                              iid,                              count(distinct zbid) as buyer_cnt                     from     shop_inventory                     where    cid = 1                     group by cid,                               iid                     ) b on a.cid = b.cid and a.id = b.iid           where     a.cid = 1 and                     a.szbid <> 0           group by  a.cid,                     a.szbid           ) b on a.cid = b.cid and a.zbid = b.szbid where     a.cid = 1 and            a.zbid <> 0 	0.520381429946792
12187087	14977	finding records with specific datetime difference in mysql	select d1.referenceid,   timestampdiff(second, d1.dttm, d2.dttm) timetaken from data d1 left join data d2 on d2.referenceid = d1.referenceid   and d2.status = 'success' where d1.status = ''   and timestampdiff(second, d1.dttm, d2.dttm) > 10 	0.00017086163636299
12188027	26212	mysql select distinct multiple columns	select  (select group_concat(distinct a) from my_table) as a, (select group_concat(distinct b) from my_table) as b, (select group_concat(distinct c) from my_table) as c, (select group_concat(distinct d) from my_table) as d 	0.00892646909864845
12188584	16132	specific query to select all rows in table a that don't match criteria defined in rows of table b?	select * from entries e where not exists ( select *                    from criteria c                    where e.tuple like           case coalesce( unit    , '' ) when '' then '%' else unit    end                                       + ' / ' + case coalesce( product , '' ) when '' then '%' else product end                                       + ' / ' + case coalesce( part    , '' ) when '' then '%' else part    end                  ) 	0
12188808	23962	selecting from multiple subtables	select    meeting.*,   conclusion.*   discussion.*,   note.*,   topic.* from meeting    left join conclusion on meeting.id = conclusion.meeting_id    left join discussion on meeting.id = discussion.meeting_id    left join note on meeting.id = note.meeting_id    left join topic on meeting.id = topic.meeting_id where meeting.id in   (select mp.meeting_id from meeting_permissions mp where mp.user_id = $user) 	0.00842824416373682
12189147	5252	my sql best practice with php for counting rows	select count(*) from table where abc=123 	0.0983917653394813
12189228	40138	query to order time events showing first future events and after show current events	select *,        datediff(start_time, curdate()) as diff from   events where  start_time >= curdate()         or ( start_time <= curdate()              and end_time >= curdate() ) order  by case             when diff > 0 then 0             else 1           end,           diff asc; 	0
12190700	9863	mysql group by date	select  `user_id`,          concat(`follow_up_date`, ' - ', `follow_up_date` + interval 6 day) as f_week,          group_concat(`follow_up_date`) as c_date from feedback_2  where `follow_up_date` > '' group by f_week, `user_id` order by  `user_id`, f_week 	0.107634899214452
12191568	10356	sql query to compare rows	select * from     (select t1.sequence as s1, t2.sequence as s2, t1.id      from t as t1, t as t2     where t1.sequence < t2.sequence        and t1.date > t2.date        and t1.id = t2.id) subq    inner join t on (t.id = subq.id                 and (t.sequence = subq.s1 or t.sequence = subq.s2)) 	0.0128196909607365
12192291	12493	how can i get a list with totals in sql stored procedure?	select type, subtype, total from source union all select type, 'total', sum(total) from source group by type order by type 	0.0323940134284854
12194219	11948	combine two datetimes	select convert(varchar(10),@daypart,111) + ' ' +          convert(varchar(10),@timepart,108); 	0.00421906348285933
12195787	33801	mysql search by time on time stamp	select * from   table where  date_format(yourdatecolumn, '%h:%i:s') > '10:20:00' 	0.0080378818744103
12196146	25498	sql server stored procedure for getting rows from table	select @leavetype=id_leave_type, @idemployee`=id_employee,@datefrom=dt_from,@dateto=dt_to,@reason=txt_reason from cor_leave 	0.0102916283062799
12196385	35832	mysql query return unexpected values	select c.id, c. name,        count(distinct lq.id) as questions,        count(distinct case when a.id is null then lq.id end) as unanswered,        count(distinct case when cr.id is null then lq.id end) as unchecked 	0.163993590790582
12197599	19087	mysql- fetching multiple records from same table	select child.name, parent.name from tbl as child     left join tbl as parent     on (child.parent_category__id = parent.category_id); 	5.02033517340725e-05
12197930	20782	sql group by two fields	select branch as 'branch code',     sum(case when customerstatus_value = 'e' then 1 else 0 end) as 'created',     sum(case when customerstatus_value = 'a' then 1 else 0 end) as 'active',     sum(case when customerstatus_value = 'b' then 1 else 0 end) as 'blocked',     sum(case when customerstatus_value = 'c' then 1 else 0 end) as 'cancelled',     count(customerstatus_value) as 'all' from customerstatusentries group by id 	0.0344512618587916
12198315	3577	mysql to csv using php and replacing values	select order.order_id,        case when order.customer_id = '0' then 'guest' else order.customer_id end as customer_id,  ... 	0.0379557163592704
12198572	32723	sql query to get latest prices, depending on the date	select dbo.twproducts.title, dbo.lowestprices.productasin, dbo.twproducts.sku,         dbo.lowestprices.tweamzprice, dbo.lowestprices.price, dbo.lowestprices.pricedate from   dbo.aboproducts inner join        dbo.lowestprices on dbo.aboproducts.asin = dbo.lowestprices.productasin         inner join dbo.twproducts on dbo.aboproducts.sku = dbo.twproducts.sku where  dbo.lowestprices.pricedate in         (select max(lowestprices_1.pricedate)          from   dbo.lowestprices as lowestprices_1           where dbo.lowestprices.productasin = lowestprices_1.productasin) 	0
12198729	22593	assign a unique number in a range randomly	select personnum, firstnm, lastnm, row_number() over (order by newid()) randomnumber from person 	0
12199035	15424	get how many users who responded to a survey	select count(distinct id_user) from fs_surveys 	0.000334425723922385
12199136	33921	finding the most current entry for a month using mysql	select p.name,   v.v_name,   sum(case when month(py.pay_date) = 4 then amount end) april_amount,   max(case      when month(py.pay_date)= 4      and py.pay_date = (select max(pay_date)                         from payment                         where month(pay_date) =4 )    then amount else 0 end) max_pay_april,    sum(case          when month(py.pay_date) = month(curdate())         then amount end) current_month_amount,   sum(case          when month(py.pay_date) = month(curdate())-1         then amount end) previous_month_amount from persons p left join vehicle v   on p.id = v.person_veh left join payment py   on p.id = py.person_id group by p.name,   v.v_name 	0
12199754	41304	sql query to find out sum of the slots for each department	select * from  ( select departmentcode,scheduledstartdate,[tmain.totalslots] ,(select sum(t1.totalslots) from tempslotsassignedfordept  t1 where t1.departmentcode=a.departmentcode and t1.scheduledstartdate = dateadd(day, -1, a.scheduledstartdate )) t1subtotalslots  ,(select sum(t1.totalslots) from tempslotsassignedfordept  t1 where t1.departmentcode=a.departmentcode and t1.scheduledstartdate = dateadd(day, -2, a.scheduledstartdate )) t2subtotalslots  from  ( select  tmain.departmentcode,  convert(varchar(20), tmain.scheduledstartdate, 101) scheduledstartdate, sum(tmain.totalslots) 'tmain.totalslots' from    tempslotsassignedfordept tmain group by    tmain.departmentcode,tmain.scheduledstartdate ) a) b where [tmain.totalslots] is not null and t1subtotalslots is not null and t2subtotalslots is not null 	0
12201153	7249	searching two mysql tables, server becomes unresponsive	select * from table1 where table1.field>=date_sub(utc_timestamp(), interval 5 minute))   union select * from table2 where table2.field>=date_sub(utc_timestamp(), interval 5 minute)) 	0.177470227612666
12201914	28815	how to get the correct result in the sql query?	select e.des_event,        e.date,        count(*) num_participants   from event e,        event_access ea,        participant p  where ea.name = ?    and ea.event_id = e.id    and p.event_id = ea.event_id  group by e.ddes_event, e.date 	0.0217122525485366
12202099	5649	what is the best method to limit content to first 10 users, potentially using php & mysql?	select * from `load_count_table` where campaignid = 1 php: <?php if($countofrows < 10) {    if($row['userip'] !== $ipofcurrentuser)    {       include_once('special_page.php');       query("insert into `load_count_table` (userip, campaignid, the_time) values('$ipofcurrentuser', '1', 'sql formated datetime, timestamp')");    }    else    {       include_once('sorry_page.php');    } } else {   include_once('sorry_page.php'); } ?> 	0.00332925736475053
12203521	20329	selecting most recent record for each user	select memberid, contractid, startdate, enddate from member_contracts  where contractid in (     select max(contractid)     from member_contracts      group by memberid ) 	0
12204737	37527	combining multiple rows in mysql using concat / group concat	select roadname,        group_concat(roadpoint order by id separator ',') as geometry from (select a.*,              concat('(', lat, ',', long, ')') as roadpoint       from a      ) t group by roadname 	0.0902502260637984
12205271	40377	caché sql - convert minute format to hours	select ((myfield*100)+right(myfield,2))/60           || ':'           || right('00'(((myfield*100)+right(myfield,2))#60),2)  from mytable 	0.0102523807354453
12205902	19398	strategy for storing multiple nullable booleans in sql	select p.* from bitfields bf join      paragraph p      on bf.bfid = p.bfid where <conditions on the bit fields> 	0.309009517344678
12207200	40311	mysql join with multiple tables and sums	select invoice.invoiceid, invoice.`date`, invoice.terms, invoice.datedue, invoice.status, client.clinicname, invoiceitemsum.sumofamount, paymentsum.sumofpaymentamount   from invoice   inner join client on client.clientid = invoice.clientid   inner join (     select invoiceid, sum(amount) as sumofamount       from invoiceitem       group by invoiceid   ) invoiceitemsum on invoiceitemsum.invoiceid = invoice.invoiceid   inner join (     select invoiceid, sum(paymentamount) as sumofpaymentamount     from payment     group by invoiceid   ) paymentsum on paymentsum.invoiceid = invoice.invoiceid 	0.147342724650701
12208491	16591	show the specific field on mysql table based on active date	select trx.trxid, trx.trxdate, uh.usrname, ud.usrloc from trx       inner join usrdetail ud on (trx.usrid = ud.usrid)      inner join usrheader uh on (trx.usrid = uh.usrid) where ud.date = (select max(t.date)                  from usrdetail t                  where t.usrid = trx.usrid                    and t.date <= trx.trxdate) 	0
12210030	26745	retrieve records from oracle table with batch inputs where some column criteria can be optional	select      *  from     invoices where     (invoice_id, entity_id, vendor_id) in                                 (                                    (1, 101, 201),                                     (2, 102, 202)                                )     or      (invoice_id, entity_id) in                                 (                                    (3, 102)                                   ) 	0.000199900437467256
12210378	33294	sql server 2008 datetime range query	select username  from users   where createtime >= '2012-08-30' and createtime < '2012-09-01' select username  from users   where createtime >= '2012-08-30 00:00:00' and createtime < '2012-09-31 23:59:59' 	0.185902388125928
12211413	29734	find count in equijoin	select   hosts.id,count(*) from     hosts  join     events  on       hosts.id=events.host_id group by hosts.id having   count(*)>=3 	0.129362553938943
12211930	40697	sql : how to select a column based on partial string of the column	select    comments, substr(comments, instr(comments, '2012'), instr(comments, 'm') - 6) year   from tablea   order by substr(comments, instr(comments, '2012'), instr(comments, 'm') - 6) desc   where rownum = 1 	0
12213077	21714	query to find the most played enemy	select * from (     select        player1,       player2,       count(*) cnt     from       (         select player1, player2 from matches          union all         select player2 player1, player1 player2 from matches       ) sub     group by       sub.player1,       sub.player2     ) sub2 group by   sub2.player1 having   sub2.cnt = max(sub2.cnt) 	0.0046900119074993
12213271	39981	sql query to find out third highest salary involving multiple tables	select firstname, lastname, salary   from   (  select      employee.*, details.salary,     row_number() over (order by salary desc) salaryrank  from        employee  inner join        details            on employee.empid = details.empid  ) v  where salaryrank=3 	5.29588006152321e-05
12213872	1406	list of items which were not updated in the last 24 hours	select     asin  from       dbo.aboproducts  where     (asin not in                 (select    aboproducts_1.asin                  from      dbo.aboproducts as aboproducts_1 inner join                            dbo.lowestprices on aboproducts_1.asin = dbo.lowestprices.productasin                  where    (dbo.aboproducts.amzlive = 'true') and                            (dbo.lowestprices.pricedate > dateadd(day, - 1, getdate())))) 	0
12215862	8169	if in mysql join php codeigniter	select user.name, marksheet.marks, holiday.holiday        from user  left join marksheet on marksheet.id = user.id and user.id not in ($bad_pupils)  left join holiday on holiday.id = user.id and user.id not in ($bad_pupils) 	0.587582891054488
12216240	10973	how to combine an aggregate sql query and normal query?	select jobname, sum(kilocounter) as totalkilos,        sum(barcounts) as totalbars,        min(startdate) as startdate,        max(enddate) as enddate,        max(stage) as stage  from vwoeeinterval group by jobname 	0.726133959559812
12217276	20512	joining tables with a historical timeline	select a.id, a.timestmp, b.value from a left outer join      (select b.*,              lead(timesmtp) over (partition by id order by timesmtp) as nextts       from b     ) b     on a.id = b.id and        a.timestmp >= b.timesmtp and        a.timestmp < coalesce(nextts, a.timestmp) 	0.0734460612857231
12217751	9493	random items from query	select * from allimages order by rand() limit 400 	0.003176454774095
12218392	31712	mysql group by and order	select console_msgs.* from   console_msgs natural join (          select   max(time) as time          from     console_msgs          where    `to` = $user[id]          group by `from`        ) t where  `to` = $user[id] 	0.358661952014228
12218436	28036	sql query for student schema	select a.department, a.number, a.section, b.title, a.population  from offering a inner join titles b  on a.department=b.department and a.number=b.number  order by a.department, a.number, a.section 	0.521259343124459
12219013	40737	need to join 4 tables	select *     from t1 left outer join          t2          on t1.id = t2.id left outer join          t3          on t1.id = t3.id left outer join          t4          on t1.id = t4.id 	0.359416955292967
12220157	35025	need help in mysql database retrieving (unable to retrieve the current value)	select * from table order by `timestamp_field` desc limit 1 	0.00040471267590284
12221747	1744	finding a value in a database table multivalued column	select sr_redirect from search_redirect inner join search_keyword_to_synonym on search_redirect.sr_id=search_keyword_to_synonym.sr_id where search_redirect.sr_keyword=whatever_input_you_have. 	0.000185643561846454
12223122	8528	get the entire row of the maximum value of a column in every category	select * from (     select * from table order by date desc ) as t group by t.category; 	0
12223164	40428	sorting by relationship count with mapper table	select book_id, count(*) cnt  from mapper  group by book_id  order by cnt desc 	0.0986092101653104
12223245	39232	mysql, how to batch execute many queries and knows which ones are returning rows	select   '`theprint_depotlive-v16`.`xmlconnect_notification_template`' as table,   '`name` like \'%1720%\'' as condition,   count(*) as count from `theprint_depotlive-v16`.`xmlconnect_notification_template` where `name` like '%1720%' union select   '`theprint_depotlive-v16`.`xmlconnect_notification_template`' as table,   '`push_title` like \'%1720%\'' as condition,   count(*) as count from `theprint_depotlive-v16`.`xmlconnect_notification_template` where `push_title` like '%1720%' union ... where count > 0; 	0.00187908113519743
12225295	3441	php get list of selected times range from pool mysql time	select id from table where '$from_time' >= start_time and '$to_time' <= to_time; 	0
12229893	37091	selecting two different random entries for each category with mysql	select x.question,        x.scope,        x.type   from (     select bp.question, bp.scope, bp.type,      case when bp.type = @type           then @rownum := @rownum + 1          else @rownum := 1          end as rank,     @type := bp.type from (select * from q order by rand()) bp join (select @rownum := 0, @type := null) r where bp.scope = 'a' order by type     ) x  where x.rank <= 2 order by x.type 	0
12230582	40809	mysql distinct query using joins	select * from student_table, students_requirements_table, requirements_table, requirement_type_table where student_table.name = "jon smith" and students_requirements_table.id = student_table.id and requirements_table.id = students_requirements_table.requirement_id and requirement_type_table.id = requirements_table.requirement_type_id; 	0.787849683386679
12231424	6524	get the first and last posts in a thread	select first.text as first_post_text, last.text as last_post_text from   (select max(id) as max_id, min(id) as min_id from posts where thread_id = 1234) as sub join posts first on (sub.max_id = first.id) join posts last on (sub.min_id = last.id) 	0
12232789	10377	select * from 'many to many' sql relationship	select t.id, group_concat(p.id) from teams t inner join teams_players tp     on t.id = tp.team_id  inner join players p     on tp.player_id = p.id group by t.id 	0.0141261650569126
12232967	37201	sql find last date and last time of event	select max(dateheld) as 'maxdate', starttime  from events where starttime in        (select max (starttime) as temp from events) 	0
12234178	4184	apply right join on a derived table and a calendar table to get all dates between two days	select date_format(c.date,'%d %b %y') as this_date, count(*) as views  from calendar c left outer join      promotion_insights pi      on c.date between '2012-08-15' and '2012-08-19' and         c.date = pi.created_at where f_id = '2' and p_id = '12' group by c.date 	0
12234982	2270	google maps geocoder to find nearby places from mysql database	select *,     acos(cos(centerlat * (pi()/180)) *      cos(centerlon * (pi()/180)) *      cos(lat * (pi()/180)) *      cos(lon * (pi()/180))      +      cos(centerlat * (pi()/180)) *      sin(centerlon * (pi()/180)) *      cos(lat * (pi()/180)) *      sin(lon * (pi()/180))      +      sin(centerlat * (pi()/180)) *      sin(lat * (pi()/180))     ) * 3959 as dist from table_name having dist < radius order by dist 	0.00712604042529685
12235509	24670	how to first order by column a, return a top-3, then order the result by column b in one query?	select *    from (            select sp100_id,                     avg(bullishness) as bullishness,                    avg(agreement) as agreement               from stocks              where _date between '2011-03-16' and '2011-03-22'           group by sp100_id          order by bullishness desc             limit 3   ) subquery   order by agreement asc 	0
12235595	665	find most frequent value in mysql column	select       `value`,              count(`value`) as `value_occurrence`      from     `my_table`     group by `value`     order by `value_occurrence` desc     limit    1; 	6.45748149756088e-05
12239169	40291	how to select records without duplicate on just one field in sql?	select min(id) as id, title from tbl_countries group by title 	0
12244634	17661	joining two rows using mysql statement	select locationname,         stationname ,         group_concat(`12:00 - 13:00` separator ' ') `12:00 - 13:00`,         group_concat(`13:00 - 14:00` separator ' ') `13:00 - 14:00`,         group_concat(`15:00 - 16:00` separator ' ') `15:00 - 16:00` from tablename group by  locationname,            stationname 	0.0232357064780297
12245289	12990	select unique values sorted by date	select n_place_id  from   (     select *,      extract(epoch from (dt_visit_date - now())) as seconds,       1 - sign(extract(epoch from (dt_visit_date - now())) ) as futurepast     from #t  ) v  group by n_place_id  order by max(futurepast) desc, min(abs(seconds)) 	9.62830422300707e-05
12245314	2408	join two tables to show already purchased items	select t.*, p.payment_id from templates t left join (     select * from payments where user_id=2 ) p on t.template_id = p.template_id 	4.76609041237309e-05
12245607	18724	oracle: using where rownum = 1	select        **values**  into          **variables**                   from          **table** inner join    **other table** on            **join target** _where        rownum = 1_ order by      **sort criteria**; 	0.553326742175522
12245653	14959	ssis - data source with sql statement containing a convert	select cast(replace(convert(varchar(10), dob, 111), '/', '-') as varchar(10)) as dob from person 	0.441957158727511
12245781	2286	sql - can i search for particular numbers in a record?	select col_name  from table_name  where find_in_set('563', col_name); 	0.00214644029150829
12246163	24015	mysql find minimum value and according date, starting at a certain row	select value,`date` from (select value,`date` from tablexy     where id=1 limit 11, 1000)   as x  order by value limit 1; 	0
12246305	11717	get newest row for user	select e.status, e.userid from employeetable e inner join (   select userid, max(asofdate) as d   from employeetable   where userid in ('nis','rele')   group by userid ) u on u.userid = e.userid and u.d = e.asofdate 	0.00018204337191581
12247667	22670	which mysql method is fast?	select substring(your_column, 1, 200) as your_column from your_table 	0.716711639097902
12247817	29421	mysql query not saving the correct results in the variables	select @upper:=max(`postid`), @lower:=min(`postid`)  from ( select wall.postid from wall,posts where   wall.postid = posts.postid and posts.userid=puserid order by wall.postid desc limit 4 offset 0)m 	0.767168989397639
12249456	39975	connecting tables with no key	select name, time, activity from (     select         a.name, a.time, b.activity,         row_number() over (partition by a.time order by b.time desc) as rn     from tablea a, tableb b     where a.time >= b.time and a.name = b.name ) where rn = 1; 	0.031306112495475
12249485	27670	sqlite count data between max and min dates	select count(oneparticular_column)  from  mytable where mydates_col between (select min(mydates_col) from  mytable) and (select max(mydates_col) from  mytable) 	0.00117765523309013
12249568	11943	update variable for each row in a select in oracle	select max(currentusers) from (   select sum(change) over (order by eventtime) as currentusers    from events ) 	0.00056475590960118
12250763	11368	how can i query records depending on value existance?	select  id, value, category   from  (       select id, value, category,           row_number() over (partition by id) as seq_id         from my_table       order by id, category desc   )  where seq_id = 1 	0.000234982055928148
12251313	2764	joining multiple tables with different id's	select ... from table_orders_products op left join table_products p on op.products_id = p.products_id left join table_orders_products_attributes pa on op.products_id = pa.orders_products_id where ... 	0.000325575074906312
12252635	24207	how to store xml result of webservice into sql server database?	select * from xmllogging with (nolock) where response like '%order12%' 	0.0138112853634662
12253287	34098	sql sum over products of grouped elements	select g.id as id, g.group as name, sum(i.cost * i.amount) as total from groups g inner join items i on i.groupid = g.id group by g.group, g.id 	0.00025387062676348
12253383	25140	better way to select last row version in multi-column primarykey	select     d.*    from     "dataset" as d     left join "dataset" as d_ on d_."id" = d."id" and d_."version" > d."version" where     d_."id" is null ; 	0.0167333105973451
12254672	9136	trying to use partitioning instead of sub querys	select useremails.email as oldemail,gab.email as neweamil from   useremailsfromaddressbook   inner join useremails on useremails.email=useremailsfromaddressbook.email       and isprimary =0 inner join useremailsfromaddressbook  gab on gab.memberid=useremailsfromaddressbook.memberid      and gab.isprimary=1 	0.780799381195205
12254821	14586	selected time + 1440 minutes	select unix_timestamp(min(tarih) + interval 1440 minute) from ... 	0.00637329066816034
12255233	22306	mysql view with conditional column	select tablea.name,        tableb.id,        tableb.categoryid,        tablec.categoryparentid   from tablea   join tableb     on tableb.id = tablea.id   left  outer   join tablec     on tablec.categoryid = tableb.categoryid ; 	0.622133014883384
12257878	35798	mysql - fix multiple records	select    cf.user,    cf.fk_collection as followitem,    c.collectionname as followname,   'collection' as followtype from collectionfollows as cf inner join collections as c on cf.fk_collection = c.collectionid where cf.user = 2 union all select    uf.fk_userme,    u.userid,    u.username   'user' as followtype from userfollows as uf inner join users as u on uf.fk_useryou = u.userid where uf.fk_userme = 2 	0.181468161451708
12258218	16063	add counter column to table	select row_number() over (order by (select 0)) as number,value from @tablevariable 	0.010472432310379
12258281	25083	mysql select query does not return the exact result	select user.name,holiday.city from  `user` left join `holiday`                   on user.userid  =holiday.userid                         where (user.name like '%bre%'                          or holiday.city like '%bre%') 	0.296747655494761
12258616	11626	how do i select a number to put into interval as part of date addition function in postgresql	select l.status, l.inserted + (interval '1 hours' *  coalesce(timezone_offset, '0')) from log as l left outer join users u on u.usersid = l.usersid left outer join companies c on c.companiesid = u.companiesid  where l.usersid=? 	0.000165849658960347
12258699	31115	selecting rows from the same table using a reference	select * from( select @rank :=  if(@prevval<>ref or ref is null,@rank, @rank+1) as rank,         id,ref, @prevval:=ref from   scores ,         (select @rank := 0,@prevval:=null) r  order by id) m where m.rank=1 	0
12259149	27294	grouping sql tables	select sports_name.name, teams.team_name, player_name.player_name  from player_name join    teams on player_name.team_id = teams.id join    sports_name on sports_name.id = teams.sport_id order by sports_name.name, team_name 	0.136438471757699
12259207	11307	data in multiple rows into single row (values not standard)	select name,         [1] address_1,        [2] address_2,        [3] address_3 from (   select name,          address,          row_number() over (partition by name                             order by updated desc) rn     from table1 ) o pivot (min(address) for rn in ([1], [2], [3])) p 	0
12260874	18687	finding the specific column (field) name from multiple tables in a database	select distinct     table_name  from     information_schema.columns where column_name = 'country' 	0
12261614	1277	sql query to derive a column value based on the entry in another table	select p.id,p.email,if(count(s.category_id)>0,1,0) as is_subscribed from person as p left join subscription as s on s.person_id=p.id group by p.id 	0
12262258	26512	select rows based on combination of columns but only latest time stamp	select * from  (       select *,              row_number() over (partition by name, action order by timepoint desc) rn       from yourtable ) v where rn = 1 	0
12264868	39281	query for a range of records in result	select t from thetable where t = x union all select * from  (     select top 1 t     from thetable     where t > x     order by t ) blah union all select * from (     select top 1 t     from thetable     where t < x     order by t desc ) blah2 	0.000673828485558835
12266013	3027	pl/sql using instr to find exact match	select replace(name,' serv ', ' services ') from names; 	0.145297342960171
12266522	28821	check any 4 out 10 conditions are satisfied in sql	select * from     yourtable where     case col1 when @value1 then 1 else 0 end +     case col2 when @value2 then 1 else 0 end +         ...     case col10 when @value10 then 1 else 0 end      >=4 	0.00405288850500325
12266838	35984	mysql return row with higher value	select * from table_name order by id desc, score desc group by reviewitem, date 	0.00126679731131492
12268334	31626	recursive oracle sql to identify a value	select listagg(source,',') within group (order by source) final_source from (  select distinct b.source source from taba_parent a, taba b where b.name = a.parent_name and b.name_type = 'category' connect by prior a.parent_name = a.name start with a.name = 'name3'         ); 	0.210514952294512
12269319	10707	sql server 2008 query to get mixed data from two tables	select tbla.id, tbla.name, tbla.photo, tblb.category_name, tblb.category_id from [table-b] tblb inner join [table-a] tbla on tbla.category_id = tblb.category_id where tblb.parent_id = 1  and tbla.id = (select max(id)        from [table-a]       where category_id = tblb.category_id) 	0.00259174748605588
12269806	21459	depth of nested set	select count(*)   from table   where lft<7330   and   rgt>7330 	0.188121710406786
12270348	31810	how can i add an attribute to the root element of xml generated by sql's select for xml	select 'person' as "@tablename",  (select * from deleted for xml path('dataitem'), type)  for xml path('root') 	0.000333066266070749
12270412	36939	get multiple columns from a large subquery	select cast(p.idvendor as varchar(10)), cast(p.description as varchar(50)),        s.val1, s.val2, sl.val3 from vendors p join      agents ag       on p.codeagent = ag.codeagent join      (<a variation of your subquery here with all three columns defined and idvendor in the select list>      ) s      on p.idvendors= s.idvendor 	0.00181570732372497
12270953	24502	combine multiple rows into one mysql	select concat(   ' select `value`.`key_id`,' ,        '`keys`.`keys`,' ,         group_concat(            'group_concat(if(`value`.`lang_id`=',id,',`value`.`value`,null))'           ,   ' as `', replace(language, '`', '``'), '`'           ) , ' from `keys` join `value` on `value`.`key_id` = `keys`.`id`' , ' group by `value`.`key_id`' ) into @sql from `langs`; prepare stmt from @sql; execute stmt; deallocate prepare stmt; 	0.000214667360827043
12271235	28568	mysql query next sequence number for mysql auto-incremented field	select auto_increment from information_schema.tables where table_name='the_table_you_want'; 	0.000807151164946318
12271504	3022	mysql getting data and looking it up in another table	select   lineid, title  from     owners  where    lineid in (select lineid from followers group by lineid )  order by owners.lineid 	0.0130199094485451
12273633	24336	find and display only values that are the same in sql	select swimmers,         eventid,         place from  results a inner join         (             select eventid, place ,count(place) totalplace             from results             group by eventid, place             having count(place) > 1         ) b on a.eventid = b.eventid and                 a.place = b.place 	0
12273884	11333	mysql group_concat distinct by id	select group_concat(value) from (     select distinct id, value     from tablename ) a 	0.0686224525585388
12276087	23708	how to group continuous ranges using mysql	select   catid, begin, max(date) as end, rate from (   select   my_table.*,            @f:=convert(              if(@c<=>catid and @r<=>rate and datediff(date, @d)=1, @f, date), date            ) as begin,            @c:=catid, @d:=date, @r:=rate   from     my_table join (select @c:=null) as init   order by catid, rate, date ) as t group by catid, begin, rate 	0.0539719159156377
12276901	30322	sql - get two users' names	select  b.`username` as votee_name,         c.`username` as voter_name from    votes a             inner join userinfo b                 on a.voteeid = b.id             inner join userinfo c                 on a.voterid = c.id 	0.000177385469953517
12278403	25011	join two sql queries where the second only returns one row and column	select jobname, weight, current_job from (yourfirstquery) q1, (yoursecondquery) q2 	0
12278787	32	mysql query with column of null values	select distinct u.id, u.name, n.network_id, n.perm  from users as u  left outer join nets_permissions as n  on u.id = n.user_id  and n.perm<> 3  where u.id!=%s 	0.0219966894192599
12280496	934	joining 3 sql queries into one result set	select drps.assetnumber, drps.mocalcsum,drps.micalcsum,     drps.cocalcsum,drps.cicalcsum,issued.totalissued,redeemed.totalredeemed from (select assetnumber, sum(mocalc) as [mocalcsum],sum(micalc) as [micalcsum],         sum(cocalc) as [cocalcsum],sum(cicalc) as [cicalcsum]         from drops         where  dropdate > '09/01/2012' and dropdate < dateadd(hour,-0,getdate())         group by assetnumber) as drps left join (select snissued,sum(amount) as [totalissued] from tickets     where  dateissued > '09/01/2012' and dateissued < dateadd(hour,-0,getdate())     group by snissued) as issued     on drps.assetnumber=issued.snissued left join (select snredeemed,sum(amount) as [totalredeemed] from tickets     where  dateredeemed > '09/01/2012' and dateredeemed < dateadd(hour,-0,getdate())     group by snredeemed) as redeemed     on drps.assetnumber=redeemed.snredeemed 	0.00259409733764326
12280857	23319	oracle apex - how to create popup lov which contained multiple display values?	select      first_name || ', ' || last_name as display_value,       user_id as return_value   from all_users  order by 1 	0.00245842641563034
12281763	26948	is it possible to search for whole given word in full text search of mysql	select * from trafficker.traffics where match (column1, column2) against ('"greater noida"' in boolean mode); 	0.109596454871498
12283916	7540	sql- query - select best car num	select r.race_num,        max(score) as maxscore,        avg(score) as avgscore,        max(case when seqnum = 1 then c.carnum end) as topcarnum,        max(case when seqnum = 1 then cd.model end) as topcarmodel from (select r.*,              row_number() over (partition by race_num order by score desc) as seqnum       from result r      ) r left outer join      car c      on c.car_id = r.car_id left outer join      car_description cd      on c.car_id = d.car_id group by r.race_num having count(*) > 2 	0.533828035123664
12283990	14384	sql server 2008 script to drop pk constraint that has a system generated name	select name      from sys.key_constraints      where parent_object_id = object_id('yourschemaname.yourtablename')         and type = 'pk'; 	0.0718226037039295
12284076	29354	sql to calculate % with select and group by in the denominator	select system, color_code, count(color_code) as colorcount, count(color_code)*100 /(select count(*) from detail where system = d.system) as colorpercent from detail d group by system, color_code; 	0.0373697784357264
12284307	525	query latest record per user include id	select user, max(id), max(date) from table group by user 	0
12284502	11421	inner and left join on the same tables	select a.x, a.y from tablea a inner join tableb b on a.x = b.x 	0.14956788588555
12286474	8236	sql join table on max and condition	select     m.idmanufacturer     , m.discperc     , c.couponcode from     @maxdiscount m      left outer join coupons c on  c.idmanufacturer = m.idmanufacturer and c.discperc = m.discperc      where c.couponcode is null or        (c.endrange - c.startrange) =         (select max(c1.endrange - c1.startrange)          from coupon c1          where c1.idmanufacturer = c.idmanufacturer and c1.discperc = c.disperc) 	0.100843517603395
12287744	40406	stored procedure results in csv format	select 'nvarcharcolumn1header,intcolumn2header'              + char(13) + char(10)          + (select nvarcharcolumn1                      + ',' + cast(intcolumn2 as nvarchar)                              + char(13) + char(10)             from table1             for xml path(''), type).value('(./text())[1]','nvarchar(max)') 	0.335055182271807
12287878	10467	how to print together elements from two different mysql tables	select      history.videoid, annotated.description  from      history, annotated  where      history.videoid = annotated.videoid  and      history.videoid in ($implodedidvideo) group by      history.videoid order by      history.videoid desc"; 	0
12288004	22704	mysql count on multiple columns	select g.name, count(distinct s.user_id) as numusers from sessions s join      games g      on s.game_id = g.id where date = <whatever your date> group by g.name 	0.0090692792350828
12288336	12512	how to eliminate duplication with two columns in a table	select t1.* from mytable t1 left outer join mytable t2 on t1.no1 = t2.no2 and t1.no2 = t2.no1 where t2.no2 is null     or t1.no1 <= t2.no1 	0.00104748178069054
12288909	3366	insert into select query taking over 10 minutes	select detail.school_id,    detail.year,    detail.race,   round((detail.count / summary.total) * 100 ,2) as percent  from school_data_race_ethnicity_raw as detail inner join (   select school_id, year, sum(count) as total   from school_data_race_ethnicity_raw   group by school_id, year   ) as summary on summary.school_id = detail.school_id      and summary.year = detail.year 	0.0021389227822798
12289192	39367	php mysql - count & average in same query	select count(field) as `count`, avg(field) as `average` from table_name 	0.00296660487846649
12289557	24991	getting multiple aggregations in single statement	select t.city,        sum(case when type = 'atm' then 1 else 0 end) as atm,        sum(case when type = 'branch' then 1 else 0 end) as branch from t group by t.city 	0.0711817976584779
12290389	2450	query to show specific values from related tables	select aa.id         , aa.number         , aa.name         , aa.debt         ...         , max(aa.date_lastpayment) as date_lastpayment         , min(aa.date_nextpayment) as date_nextpayment from     (            select a.id             , a.number             , a.name             , a.debt             ...             , case when c.ispaid = 1 then c.[date]                     else null                     end as date_lastpayment             , case when c.ispaid = 0 then c.[date]                     else null                     end as date_nextpayment     from contractstable a     inner join agreementstable b on b.contractid = a.id     inner join paymentstable c on c.agreementid = b.id     where b.isvalid = 1 ) aa group by aa.id             , aa.number             , aa.name             , aa.debt             ... 	0
12290816	1348	sqlite: get total/sum of column	select id,   dt,   pool_name,   pool_id,   buy_price,   (select sum(buy_price) from yourtable) total from yourtable 	0.00580865999973249
12291354	19713	sql, select does not return numeric value	select press, count(new) as [number of new books] from books where new = true group by press having count(new) =  (   select max(s)    from    (   select count(new) as s, press        from books       where new = true       group by press   ) ) 	0.218345161039067
12293115	28938	how to select rows surrounding a row not by id	select t.id, t.word from word t  where t.word >=  (     select lo.word from `word` lo      where lo.word <= 'dinner' order by lo.word desc limit 3,1 ) order by t.word asc limit 0,7 ; 	0.00020116716993976
12296115	17876	how to sort (non-standard) mysql data using iteration?	select x.id,x.name,x.type,x.number   from (select t.id,                t.name,t.type,t.number,                case                  when @type != t.type then @rownum := 0                  when @type = t.type then @rownum := @rownum + 1                  else @rownum                 end as rank,                @type := t.type           from  scores t,                (select @rownum := 0, @type)var       order by t.type)  x order by x.rank, x.type 	0.64355375960845
12298011	9360	count rows in more than one table with tsql	select count(*)   from (       select null as columnname        from tbl1            union all       select null        from tbl2      ) t 	0.00118505737089749
12299195	22507	mysql select column name as field	select `column`, column_value    from (     select id, 'col_1' as `column`, col_1 as column_value from tab      union     select id, 'col_2' as `column`, col_2 as column_value from tab      union     select id, 'col_3' as `column`, col_3 as column_value from tab   ) pivot   where id=1 	0.0068706437786341
12299247	760	sql server query- four results from two columns	select 'test' as charge,        max(case when t.charge = 'test' then value end) as value,        max(case when t.charge = 'bob' then value end) as "bob value",        sum(case when t.charge in ('test', 'bob') then value end) as total from t 	0.00204742513096202
12301740	32412	mysql order by closest date/hour before or after	select str_to_date(data_hora, '%d/%m/%y %h:%i') as data_hora  from requisicoes  order by abs(timediff( now() , str_to_date(data_hora, '%d/%m/%y %h:%i'))) limit 1 	0.145649917568608
12304103	3333	is it possible to have result and row count of the result in adjacent columns?	select t.*,           (select count(*) from t1) as count     from t1 t 	0.000112770232014973
12304664	20417	mysql: merge tables, run select and update duplicates	select * from tableb where userid = 1 union select * from tablea where groupid = 1         and id not in (select id from tableb where userid = 1) 	0.031109968679147
12304717	11521	pull specific xml node for each row	select   xmlvalue.value('(/root/node[sql:column("specificnode")])[1]', 'varchar(100)') from @table as tbl 	0
12306311	1905	sql math with date/time	select * from mylog where datediff(h, mytimestamp, getdate()) < 48 	0.658092622465442
12306376	3231	display all tables created after a particular date	select object_name, owner, created from all_objects where object_type = 'table'  and created >= to_date('20120901', 'yyyymmdd') 	0
12306829	30039	how to get many-to-many relationship data from mysql table sorted and displayed with php?	select      s.state, u.company  from      states s, users u  where      s.company_id = u.company_id  and      s.state = "$state"  group by      s.state  order by      s.state, u.company 	0
12306879	8779	delete from multiple related tables	select l.location_id, c.contact_id   into #x   from dbo.locations as l   inner join dbo.contacts as c   on l.location_id = c.location_id   inner join dbo.contacts_sources as cs   on c.contact_id = cs.contact_id    where cs.source_id = 10014918; delete dbo.contacts_sources where contact_id in (select contact_id from #x); delete dbo.contacts where contact_id in (select contact_id from #x); delete dbo.locations where location_id in (select location_id from #x); 	0.00134849248111747
12307187	19001	sql selecting value by matching date to date range?	select     t.name,     t.[date],     t.hours,     d.dept from     timesheet t     join department d         on t.name = d.name         and t.[date] between d.[from] and d.to 	0
12307685	36094	join more than 2 tables in r using rsqlite	select coalesce(filea,fileb),vala,valb                from t1 left outer join t2 on t1.filea= t2.fileb union select coalesce(filea,fileb),vala,valb                from t2 left outer join t1 on t1.filea= t2.fileb 	0.0731519253491974
12307942	28132	how to count the number of occurrences of something in one month	select count(person_id) as person_count        month(date) as month from table_votes group by month(date) 	0
12309132	11074	check for value of a checkbox in database	select eventcode, eventdesc, date_format(date, '%m/%d/%y') as format_date  from camps_events where reg_status!= 'archived'  and eventcode in (select distinct eventcode from registrations)  ".getallowedprograms()." order by eventdesc"; 	0.00462604665175982
12309843	31239	join tables and return 2 separate entries with null values	select a.svc_prefix, b.svc_cd, a.anotherdata, cd.svc_id, cd.isgood, cd.ishappy   from a join b on b.svc_prefix = a.svc_prefix and b.svc_cd = a.svc_cd join (   select svc_id, isgood, ishappy   from c   union   select svc_id, isgood, null as ishappy   from d ) as cd on cd.svc_id = b.svc_id 	0
12310059	12702	again mysql "count distinct"	select count(distinct case when a.inc = 0 then null else a.inc end) as inc,        count(distinct case when a.cls = 0 then null else a.cls end) as cls,        count(distinct case when a.ord = 0 then null else a.ord end) as ord,        count(distinct case when a.fam = 0 then null else a.fam end) as fam,        count(distinct case when a.subfam = 0 then null else a.subfam end) as subfam,        count(distinct case when a.gen = 0 then null else a.gen end) as gen,        count(distinct case when a.spec = 0 then null else a.spec end) as spec,        count(distinct case when a.subspec = 0 then null else a.subspec end) as subspec     from a     where (a.inc = 11) 	0.234334570176906
12310229	20361	wordpress custom search	select distinct(m1.post_id) as post_id from      wp_postmeta m1,      wp_postmeta m2 where     m1.post_id=m2.post_id and     (m1.meta_key='class' and (m1.meta_value in ('$a2','$a3','$a4','$a5','$a6','$a7','$a8'))) and     (m2.meta_key='fuel' and (m2.meta_value in ('$c2','$c3','$c4'))) 	0.710436154441834
12313739	38682	select count(*) on intermediary table with many-many relationship only if exists in both related tables	select c.idcourse, c.name, count(*) as count   from courseusers as cu      left join course as c          on cu.idcourse=c.idcourse      left join users as usr          on (usr.iduser=u.iduser)   group by u.idcourse  order by count desc   limit 3 	0.000205669201679792
12315661	18855	php search a mysql string results	select count(*) from table where likes regexp '[[:<:]]facebook.com[[:>:]]' 	0.177966655611219
12316495	3744	sql query to avoid loop or cursor to fetch record	select distinct     username,     menuname,     case when table3.userid is null then 0 else 1 end as allowed     from table1     cross join table2     left join table3 on table1.userid = table3.userid      and table3.menuid = table2.menuid 	0.307254072812538
12318553	3088	how can a dbms_job mark itself as broken?	select job from all_jobs where what like '%your_job_procedure%'; 	0.119273861022809
12319042	22066	sql server partition unnormalized data	select p1.setitemid  from (        select setitemid, componentitemid, quantity         from setdata         where isprimary = 1) p1   inner join (               select setitemid, componentitemid, quantity                from setdata                where isprimary = 0) p0    on p0.setitemid = p1.setitemid     and p1.quantity > p0.quantity 	0.795264598339704
12321127	25611	multi join query returns to many results and improperly matched	select * from source     inner join cats on source.catid = cats.id     left join status on source.sourceid = status.catsource          and statusid=1 	0.68943991644985
12322380	19303	select the first row with specific column value	select top 1     *     from data         where status = "not dialled"         ; 	0
12322481	19785	sql count on a field which is a code	select qid,        sum(case when toggle_value='yes' then 1 else 0 end) as yesqty,        sum(case when toggle_value='no' then 1 else 0 end) as noqty,        sum(case when toggle_value='na' then 1 else 0 end) as naqty,        sum(case when toggle_value='resolved' then 1 else 0 end) as resolvedqty   from answers   group by qid 	0.0379633324688448
12322682	11860	obtaining sums from multiple tables	select c.caseno,        i.invfees,        t.fees from   tblcases as c        inner join (select caseno,                           sum(invfees) as invfees                    from   tblinvoices                    group  by caseno) as i          on c.caseno = i.caseno        inner join (select caseno,                           sum(fees) as fees                    from   tbltimesheetentries                    group  by caseno) as t          on c.caseno = t.caseno order  by c.caseno; 	0.00270822895312265
12323655	23947	how to find classmates of student c who are taking any of the classes that c is taking, in sql?	select distinct s2.ssn, s2.name     from students s1         inner join courses c1             on s1.ssn = c1.ssn         inner join courses c2             on c1.course = c2.course         inner join students s2             on c2.ssn = s2.ssn     where s1.name = 'c' 	0.000163125918582053
12323757	32416	how sql query result insert in temp table?	select *  into #yourtemptable from yourreportquery 	0.118387855343676
12323811	39343	select mysql set column as bit string?	select bin(cast(column1 as decimal)) from table1; 	0.0339239526662749
12323977	14388	append a zero to value if necessary in sql statement db2	select ... from table_a as a join table_b as b   on cast(substr(digits(a.str_nbr),3,3)as char(4)) = b.locn_no 	0.218479932834936
12325142	12098	retrieve the second last record for each user from the database	select   name,   max(updated_on) as updated_on,   status from userstatus a   where (name, updated_on) not in   (select name, max(updated_on) from userstatus group by name) group by name, status having updated_on =   (select max(updated_on) from userstatus b where a.name = b.name    and (b.name, b.updated_on) not in   (select name, max(updated_on) from userstatus group by name)   group by name); 	0
12325233	24117	reversing the display of mysql_fetch_array on html page	select * from (     select * from replies where topicid = $topicnumber order by time desc limit 5 ) as a order by time asc 	0.000491395969768531
12325465	19684	return mysql result set only if found in other table	select vg.*     from video_groups vg     where exists (select 1                       from videos v                       where v.groupid = vg.id) 	0.000119507046968045
12329918	31540	getting the items belonging to specified keywords and categories	select articles.name from articles inner join ckw on ckw.article_id = articles.id inner join ccat on ccat.article_id = articles.id where ckw.key_id in (5, 7)  and ccat.category_id in (12,18) group by articles.article_id , articles.name  having count(distinct ckw.key_id) = 2  and count(distinct ccat.category_id) = 2 	0.000333419348810671
12330947	29952	need advice on retrieving data from db	select     posts.id,      posts.post_date,      posts.post_author,      posts.post_content,      posts.post_title,      group_concat(postmeta.meta_id) as metaid,      group_concat(postmeta.meta_key) as metakey,      group_concat(postmeta.meta_value_ as metavalue from     posts          inner join postmeta              on posts.id = postmeta.post_id where     posts.post_type = 'post' group by     posts.id,      posts.post_date,      posts.post_author,      posts.post_content,      posts.post_title 	0.058665150983135
12331022	4196	how to group results with conditions?	select     property,     max(value1) as value1,     max(value2) as value2 from  ( select transl_id as property,     case when lang = 'en' then text else null end as value1,     case when lang = 'de' then text else null end as value2 from t1 ) t group by property 	0.23578070054283
12331588	25472	database row quantity max insert to proceeding row	select s.section from section s join      sectionstudent ss      on s.section_id = ss.section_id group by section having count(*) < max(s.capacity) 	0.000327847836608283
12331726	40382	how to get rows with maximum id with condition of a table in sql server	select id, value, rowinid from ( select *, row_number() over (partition by id, order by rowinid desc) rn from yourtable ) v where rn = 1 	0
12332128	1231	joining two tables using third as linking table, including null entries	select     account.bill_acct,     account.status,     account.remarks,     stage.account_class from     registration_account account     left join registration_profile profile             on account.profile_id = profile.reg_prof_id     left join acct_stg stage             on stage.ecpd_profile_id = profile.ecpd_profile_id                 and stage.bill_acct = account.bill_acct where     profile.ecpd_profile_id = ? 	0
12332308	36610	sql query to get rows with maximum of some column	select vehicleid, max(vehiclespeed) from vehicledata group by vehicleid 	0
12334143	30554	how to distinct select from one table and add information from another to the result?	select distinct   tunes.riddim as riddim,   tunes.year as year.   riddims.image as image,   runes.label as label from riddims inner join tunes on riddims.riddim=tunes.riddim where tunes.year="2012" order by riddims.last_modified limit 20 ; 	0
12334969	2106	display multiple categories codeigniter	select p.title, c.category_name 	0.00416291767275067
12335375	22654	how to select specific table in sql?	select table_name      from information_schema.columns     where column_name = 'timestamp'       and table_schema='yourdatabase'; 	0.00897866403573333
12337192	34675	mysql timecard summary	select date, emp_id,      max(if(event='t_in',time_in - start, 0)) as 't1_in_diff',     max(if(event='t_out',time_out - end, 0)) as 't1_out_diff',     max(if(event='b1_in',time_in - start, 0)) as 'b1_in_diff',     max(if(event='b1_out',time_out - end, 0)) as 'b1_out_diff', from timecard  group by date, emp_id; 	0.476081663506894
12337195	526	how to part date and time from datetime in mysql	select date_format(colname, '%y-%m-%d') dateonly,         date_format(colname,'%h:%i:%s') timeonly 	0.000603529490119536
12341319	13046	finding most recent value for a specific month in mysql	select p.name, lp.yr, lp.mon, pa.amount from persons p join      (select person_id, year(pay_date) as yr, month(pay_date) as mon,              max(pay_date) as max_pay_date       from payment       group by person_id, year(pay_date), month(pay_date)      ) lp      on p.id = lp.person_id join      payment pa      on p.id = pa.person_id and         pa.pay_date = lp.max_pay_date group by p.name, lp.yr, lp.mon, pa.amount 	0
12342224	34921	mysql retrieve all row data using a group_concat	select concat('i visited ', p.city, ', ', p.country, ' on ', date) from visitor v left outer join       places p       on find_in_set(p.id, v.id_visited_place) group by visitor.id 	0.00045509157544383
12344795	6970	count the number of occurences of a string in a varchar field?	select      title,     description,         round (            (             length(description)             - length( replace ( description, "value", "") )          ) / length("value")             ) as count     from <table> 	0
12345328	21593	using a second table as a lookup?	select  a.* from    post a             inner join posts_tags_link b                 on a.id = b.post_id              inner join tag c                 on b.tag_tag_id = id where   a.content like '%keyword%' or              c.tag like '%keyword%' 	0.00543363440031484
12345670	32671	count and having query	select state,     district,     sum(case              when status = 0                 then 1             else 0             end) active,     sum(case              when status = 1                 then 1             else 0             end) inactive from (     select distinct state,         district,         status     from tablea     ) a group by state,     district 	0.407797180192767
12345882	10721	sql server view show records with no data in certain tables	select a.field1,b.field2 from tablea a left outer join tableb b on b.fieldc = a.fieldc 	5.85100452688131e-05
12347791	466	sql join relationship - if an entry is found, then don't select	select users.*, roles.rolename from users inner join roles_users on users.userid = roles_users.userid inner join roles on roles_users.roleid = roles.roleid where not exists(select roles_users.userid from roles_users       where roles_users.userid = users.userid and rolename = 'super admin') 	0.00490104108860515
12348144	26415	sql fill days for dates not found in database	select date_table.date as [date], count(your_table.primary_key) as [number] from date_table left join your_table on date_table.date = your_table.date where date_table.date between '2012-01-01' and '2012-06-30' 	0.000351655024200494
12348300	8332	retrieve sum(count) by enum value	select drug_id,         sum(case route when 'po' then `count` else 0 end) totalpo,         sum(case route when 'iv' then `count` else 0 end) totaliv from core_reports_antiinfectives group by drug_id 	0.00106145863728902
12348668	29103	calculate values fetched from 2 separate inline select statements	select name,starttime,endtime,time_to_sec( timediff( endtime , starttime) as timediff from( select x.name ,    ( select data.ts       from data       where prim_key = x.prim_key and roll_no ='1'    ) starttime ,   ( select data.ts      from woman_data      where prim_key = x.prim_key and roll_no ='10' ) endtime from data x       inner join  y  on x.prim_key = y.prim_key)a order by x.prim_key 	0.000449349252451392
12349018	11263	join two sqlite tables in android application	select  t1.name, t1. phone,         t2.description, t2.value from    table_socio t1         inner join relationaltable r on t1.id = r.id_socio         inner join table_quota t1 on t2.id = r.id_quota 	0.630403367964474
12349920	24939	concatenate date and time variable using sql query	select cast(dt as date) + cast(tm as datetime) from yourtable 	0.0177529049925837
12350345	37468	selecting users that does not have a workgroup, only active users	select *   from user u   inner join userrole r     on (r.uid = u.uid)   left outer join userrolesetting s     on (s.rid = r.rid and         s.id = 1000)     where u.active = 1 and         s.rid is null 	5.79276209294178e-05
12350438	17911	merge 2 or more results together?	select username,sum(total) , date (     select m.username, count(*) as total, date(status_date) as date from com_result_b         left join members as m on m.member_id = com_result.member_id       group by date(status_date), com_result.member_id      union all    select m.username, count(*) as total, date(status_date) as date from com_result_b          left join members as m on m.member_id = com_result_b.member_id        group by date(status_date), com_result_b.member_id  ) v group by username, date 	0.0333962446215537
12350509	2529	match all foreign key's length with their pk in oracle	select cc.table_name,        cc.column_name,        tcf.data_type || '(' || tcf.data_precision || ',' || tcf.data_scale || ')' dtype1,        rcc.table_name as r_table_name,        rcc.column_name as r_column_name,        tcp.data_type || '(' || tcp.data_precision || ',' || tcp.data_scale || ')' dtype2,        cc.position from   user_constraints c        join user_cons_columns cc on c.owner = cc.owner and c.constraint_name = cc.constraint_name        join user_cons_columns rcc on c.owner = rcc.owner and c.r_constraint_name = rcc.constraint_name and cc.position = rcc.position        join user_tab_cols tcf on tcf.table_name = cc.table_name and tcf.column_name = cc.column_name        join user_tab_cols tcp on tcp.table_name = rcc.table_name and tcp.column_name = rcc.column_name where tcf.data_type || '(' || tcf.data_precision || ',' || tcf.data_scale || ')' != tcp.data_type || '(' || tcp.data_precision || ',' || tcp.data_scale || ')' order by c.constraint_name, cc.table_name, cc.position; 	5.00484929371827e-05
12350793	8619	sql server join on value else null	select     t1.*, t2.* from     table1 as t1      left join  table2 as t2 (t1.failurebitnr = t2.failurebitnr)     where t2.fileprojectnr is not null union all                    select     t1.*, t2.* from     table1 as t1      left join  table2 as t2 (t1.failurebitnr = t2.failurebitnr) and      where t1.failurebitnr not in (select failurebitnr from table2 where fileprojectnr is not null) 	0.528096946214125
12351851	40584	how to use gps data like the double value returned by getlatitude()?	select      id,      ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) as distance  from      markers  having      distance < 25  order by      distance  limit      0 , 20; 	0.286630134709829
12353040	26989	find top n average values	select uid, [group], avg(value) from (  select *,         row_number() over (partition by uid, [group] order by value desc) rn          from yourtable ) v where rn<=15 group by uid, [group] 	0
12353232	35699	(postgresql) calculate time slots based on given start date,end date and interval in minutes	select generate_series(    '01-08-2012 00:00:00'::timestamp,     '02-08-2012'::timestamp,    '5 minutes'::interval);   ┌─────────────────────┐   │   generate_series   │   ├─────────────────────┤   │ 2012-01-08 00:00:00 │   │ 2012-01-08 00:05:00 │   │ 2012-01-08 00:10:00 │   │ 2012-01-08 00:15:00 │   │ 2012-01-08 00:20:00 │   ... 	0
12353281	39668	merging 2 tables with first five characters common	select a.name,b.name from table1 a, table2 b where upper(substr(a.name, 1, 8)) = upper(substr(b.name, 1, 8)) order by a.name,b.name; 	0
12353687	10193	how to calculate %-difference between todays and yesterdays values in mysql?	select id, _date, views, change_pct from  (   select @id := id as id, _date as _date, @views := views as views,      (case when @id = @last_id then round(((@views - @last_views)/@last_views)*100,2) else 0.00 end) as change_pct,     @last_id := @id, @last_views := @views   from your_table   order by id,_date ) as sub_query order by id,_date; 	0
12353875	22852	my sub-query returns more than 1 row	select movies.name, movies.id, username  from users    inner join movies      on movies.added_by_id = users.id 	0.237684843094028
12354207	19283	sql, count in multiple columns then group by	select x.f1,count(x.f1) from (select p1 as f1 from table  union all  select p2 as f1 from table  union all  select p3 as f1 from table) x group by x.f1 	0.00799087994568803
12354727	28250	find percentage of products against total customers	select sum(case when products = 1 then 1 else 0 end) * 100   / count(distinct products.userid) as 'currently used products%', sum(case when products = 0 then 1 else 0 end) * 100   / count(distinct products.userid) as 'used products%', sum(case when products = -1 then 1 else 0 end) * 100   / count(distinct products.userid) as 'not sold products%' from products 	0
12355187	8786	correlate group by and left join on multiple criteria to show latest record?	select g.parent_id, g.quantity, customer.reference from (     select parent_id, sum(stock.quantity) as quantity, max(id) as latestid     from stock     group by parent_id ) g left join stock_reference as custome     on g.latestid = customer.stock_id and stock_reference_type_id = 1 	0.000240703260070141
12356098	32036	union and get top1 for every record..?	select lo_id, ca_id, type, status, category from (select distinct  ln.lo_id, cast.ca_id, type, status,               (case when type='abc' then 'abc'                    when type='xyz' then 'xyz'                    else ''               end) as category,              row_number() over (partition by ca_id, type) as seqnum       from  ln inner join             cast             on cast.ca_id = ln.ca_id inner join             type             on type.typeid = cast.typeid       ) t  where type in ('abc', 'xyz') or seqnum = 1 	0.00109654648344218
12356765	27851	how to display null if a field's where condition is not met	select t.table_name as 'table name',        keys.column_name as 'primary key' from information_schema.tables t left outer join      information_schema.table_constraints constraints      on t.table_name = constraints.table_name and         t.table_schema = constraints.table_schema left outer join      information_schema.key_column_usage as keys       on constraints.table_name = keys.table_name and         constraints.constraint_name = keys.constraint_name and         constraints.constraint_type = 'primary key' 	0.00706757965033867
12357941	36463	display duplicate records in mysql	select user_key, count(*)  from (     select user_key,admin_status,count(*)      from user_admin_status      group by user_key,admin_status      having count(*) > 1  ) x group by user_key having count(*) > 1 	0.00024491605210608
12358435	11219	sql select puzzle	select t1.table1_id,      t1.table1_description,      t2.totalcount,      t2.completedcount from table1 t1 left outer join (     select table2_linkedid,          count(*) as totalcount,         count(case when table2_status = 'completed' then 1 end) as completedcount     from table2     group by table2_linkedid ) t2 on t1.table1_id = t2.table2_linkedid 	0.662848765566222
12359365	25742	how to write query summing?	select  date, (select sum(point) from a where date <= maintable.date) as points from a maintable group by date 	0.457601366053988
12360474	37437	how to find the maximum number of entries in a table that have a column that satisfies a certain condition?	select seed_id,          count(*) as cnt     from structures     where type='v'  group by seed_id  order by count(*) desc    limit 1 	0
12361220	7983	how to round down to nearest integer in mysql?	select floor(your_field) from your_table 	0.058811503828951
12361319	19596	mysql avg() in sub-query	select a.day,     case          when a.revenue_per_person > b.avg_revenue then 'big spender'         else 'small spender'    end as spending_bucket from     (         select day, person, avg(revenue) revenue_per_person         from purchase_table         group by day, person     ) a inner join     (         select day, avg(revenue) as avg_revenue         from purchase_table         group by day     ) b on a.day = b.day 	0.766263365366218
12361614	9640	sql - subqueries for top result without order by	select c.givenname, c.familyname, count(r.place) as totalplaces from competitors c  inner join results r on r.competitornum = c.competitornum where r.place in (1,2,3) group by c.competitornum, c.givenname, c.familyname having count(r.place) =              (                 select max(totalplaces)                 from                 (                     select count(r.place) as totalplaces                     from competitors c                      inner join results r on r.competitornum = c.competitornum                     where r.place in (1,2,3)                     group by c.competitornum, c.givenname, c.familyname                 )             ) 	0.341457659082486
12361712	16864	how do i search for a pattern in a serial number?	select *  from partnumber  where "ecmyk123456" like concat('%', code, '%') 	0.00351673420806672
12362085	26343	get the field with longest string for same id value	select id,test_data from (   select   id, test_data,       row_number() over( partition by id order by length(test_data) desc) as rnum from   test  ) where rnum=1 	0
12362121	34359	organizing mysql database	select name,date,sum(count) as sumcount from <your table> group by name,month(date) 	0.387072576970665
12362497	13657	mysql: unknown column in field list	select latest_exam = date(max(ex_date)).. 	0.0243594665156063
12362558	18854	select every min(date) from group of similar rows?	select  verb,          object,          min(date) oldestdate from    posts group by    verb, object 	6.21818498067577e-05
12362863	39032	organize a mysql database by lat/long more	select name, astext(location) from points      where x(location) > 0 and x(location) < 1 and     y(location) > 38 and y(location) < 39 	0.110069677748719
12364103	12664	return a default timestamp object instead of null	select ifnull(colname, your-default-value) from xyz; 	0.00260759119762815
12364999	38689	oracle get records updated in last one hour	select count(*) from my_table where last_updated_date >= (sysdate-1/24) 	0
12365678	33131	oracle query for finding non-repeated rows	select name from tbl_name group by name having count(name) = 1 	0.0390986613701595
12365942	1708	convert column heading to row data - sql	select     case region      when 1 then 'north'     when 2 then 'south'      when 3 then 'west'     when 4 then 'east'     when 5 then 'central' end as region       , count(id)    from atm where atmstatus = 0 and bank = 1 group by region 	0.0104792410687373
12365953	38922	sql select the longest char	select top (1) * from customer order by len(adresse) desc; 	0.0276395242512958
12366834	8104	best way to sort by avg and count in mysql	select (sum_rates / count_rates) from images 	0.117727730990603
12366875	34974	sql sum of a ntext field using len	select sum(len(field1)) as totallength from table 	0.231164427846357
12368733	18121	retrieving digit from a string mysql	select * from numbers where find_in_set(1, numberss); 	0.00113559267368086
12369207	5564	how do i select unique, most recently inserted, values from a mysql table?	select d.id, d.name, d.value    from products d    join (      select max(id) id, name        from products       group by name    ) m on (d.id = m.id) 	0
12371456	28158	mysql query distinct id over multiple lines	select prop_id from features    where name = 'wifi' and prop_id in (        select prop_id from features where name = 'close to pub'        ) 	0.00540034869017649
12373962	20568	joining queries in wordpress	select m.user_id, count(c.from_id) as cnt  from wp_usermeta m left join wp_chats c      on  m.user_id=c.from_id   and c.received=0   and c.to_id=2 where m.meta_key='user_last_login'  and m.meta_value>=1347305273                group by m.user_id; 	0.293610909297085
12374123	18119	how to write a query to parse a column?	select item, status from tb1 where status like '%[bdf]%' 	0.2348309922514
12375888	33836	oracle date function for the previous month	select count(distinct switch_id)      from xx_new.xx_cti_call_details@appsread.prd.com    where dealer_name =  'xxxx'        and creation_date between add_months(trunc(sysdate,'mm'),-1) and last_day(add_months(trunc(sysdate,'mm'),-1)) 	0.00176814930856174
12376106	35961	mysql query syntax, get data from different tables	select b.id, b.title, sum(s.qty) as numsold  from books b  left outer join sales_item s on b.id = s.book_id  group by b.id, b.title  order by b.title 	0.0043821422567064
12376793	41222	mysql statement that combines tables into single table	select m.id,     m.title,     m.category,     n.title,     v.title from maintable m left join attrtable a     on m.id = a.mainid left join nametable n     on a.nameid = n.id left join valuetable v     on a.valueid = v.id 	0.00488261365049829
12377041	35942	fixed array and random numbers in an sql query	select str from (   select 0 as id, 'apple' as str   union all   select 1, 'banana'   union all   select 2, 'orange'   union all   select 3, 'cherry'   union all   select 4, 'lemon' ) x where id = floor(rand() * 5) 	0.00954989034286256
12377770	4473	calling a function on distinct values from table	select *, fcn_dosomething(a, b, c)  from  (select distinct a,b,c from users) v 	0.00977077594501011
12378193	17649	mysql group by having min	select t1.id_ctr,     t1.account_number_cus,     t1.original_date_ctr,     t1.mrc_ctr   from yourtable t1 inner join (     select min(original_date_ctr) as mindate, account_number_cus     from yourtable     group by account_number_cus ) t2     on t1.account_number_cus = t2.account_number_cus     and t1.original_date_ctr = t2.mindate 	0.349233710236797
12378825	31226	t-sql query to select last 3 months of data, last years month, averages of this month and average of all months	select   category ,[sep 2012]=sum(case when year(trandate)= year(getdate()) and month(trandate)= month(getdate()) then amount else null end) ,[aug 2012]=sum(case when  year(trandate)= year(dateadd(month,-1,getdate())) and month(trandate)= month(dateadd(month,-1,getdate()))  then amount else null end) ,[jul 2012]=sum(case when year(trandate)= year(dateadd(month,-2,getdate())) and month(trandate)= month(dateadd(month,-2,getdate())) then amount else null end) ,[avg sep 2012]=avg(case when year(trandate)= year(getdate()) and month(trandate)= month(getdate()) then amount else null end) ,[avg 12 months]=avg(case when trandatee > cast(dateadd(year,-1,getdate()) as date) then amount else null end)/12 from table1 group by category,amount 	0
12380160	25219	mysql select count() accross tables using where statement?	select riddims, tunes, artists from (select count(*) as riddims from riddims where . . . ) r cross join      (select count(*) as tunes from tunes where tunes not in  . . .) t cross join      (select count(*) as artists from tunes where artist not in . . .) a 	0.296251762808934
12380557	4139	select innner join from friends and owner's posts	select * from posts p   inner join user_info u on u.account_id = p.poster_id where p.poster_id = $sessionid or p.poster_id in  (select f.friend1 from friend_match f  where f.friend2 = $sessionid) order by post_id desc limit $page, $limit; 	0.000813794116713139
12380631	22017	c# sql server query first/last name columns where first name has space	select * from [user] where    first_name + last_name like '%' + token[0] + '%' and   first_name + last_name like '%' + token[1] + '%' and   first_name + last_name like '%' + token[2] + '%' ... 	0.00158280755458522
12381402	22803	sql query to group by data using id and last 7 days from given date	select s1.item, s1.date, sum(s2.count) as countpast7 from slidinghitcount s1   inner join slidinghitcount s2 on s1.item = s2.item where s2.date between dateadd(dd, -7, s1.date) and s1.date group by s1.item, s1.date 	0
12385860	29597	select rowid of certain row when using group by in sqlite	select rowid, c1, min(c2) from t1 a where c2=(select min(c2) from t1 b where b.c1=a.c1)  group by rowid,c1; 	0.00233006644142159
12386401	38487	introducing records on the fly in mysql	select 1 id, 'foo' value   union select 2 id, 'bar' value 	0.00590909440230634
12387644	13123	mysql "or" query fetch rows in order of conditions	select * from `mytable` where (condition 1) or (condition 2) or (condition3) order by case when condition=1 then 1           case when condition=2 then 2          case when condition=3 then 3          end 	0.00925054885680537
12389049	34114	how to fetch data from two tables?	select top 25 count(b.applied_job_id), a.companyid from tbl_posting_job_info a inner join tbl_jobseeker_applied_job b on a.job_posting_id = b.job_posting_id group by a.companyid order by count(b.applied_job_id) desc 	7.32714933049586e-05
12389767	25861	sum currency column based on status?	select   c.referralname,   sum(case when (d.casestatusname) = 'active'    then b.leadcost else 0 end) as active,   sum(case when (d.casestatusname) = 'completed' then b.leadcost else 0 end) as completed,   sum(case when (d.casestatusname) = 'submitted' then b.leadcost else 0 end) as submitted,   count(b.caseid) as total,   sum(b.leadcost) as cost from   tblcontacts a inner join   tblcases b on a.contactid = b.contactid inner join   tblreferral c on c.refferalid = a.contactreferrelsource inner join   tblcasestatus d on d.casestatusid = b.casestatusname group by   c.referralname with rollup 	0.000203795790609982
12390179	3160	php mysql join and count	select group_name, count(distinct i.id) from imagesgroup ig left join images i on (ig.id = i.category) group by ig.id, ig.group_name 	0.39598113867331
12390790	774	getting the type of an existing hypersql table	select hsqldb_type  from information_schema.system_tables  where table_name = '<table name in uppercase>' 	0.00489074898283138
12391200	7043	select flat data into table format	select year, sum(if(month=1,amount,0)) as '1', sum(if(month=2,amount,0)) as '2', sum(if(month=3,amount,0)) as '3' from mytable group by year 	0.00434142690151927
12392594	10156	database logic, querying a table with repeated values	select id from   table where  attribute in (1,2) group by id having count(id) = 2 	0.0300406776541512
12393086	27330	querying for status updates per day from an audit log of version control?	select extract(year from timestamp), extract(month from timestamp),        extract(day from timestamp),        status, count(distinct wc_id) from a group by extract(year from timestamp), extract(month from timestamp),          extract(day from timestamp), status order by 1, 2, 3, 4 	0
12393216	4650	mysql calculating the difference between two dates but with a twist	select u.phone_number, u.created, u.cancelled, p.date as 'productdate' from (     select u1.phone_number, u1.date as 'created', u2.date as 'cancelled'     from user u1       join user u2 on u1.phone_number=u2.phone_number     where u1.type = 'n'       and u2.type = 'c'   ) u   left join product p on u.phone_number = p.phone_number                      and p.date between u.created and u.cancelled 	7.38438913106401e-05
12393744	11463	how to group results from mysql	select     username, 'member' from     chat_users where     id in($this_groupmembers) union select     username, 'invitee' from     chat_users where     id in($this_groupinvites) 	0.0286474681372415
12394201	17219	combining sql select and count	select      a.a_name,      (         select count(b.b_pk)          from b          where b.a_pk = a.a_pk     ) as b_count  from  a 	0.102736105273972
12394545	34168	replace null values with just a blank	select isnull(colname, '') as colname from tablename 	0.0612734590320634
12396731	32221	finding records where values of multiple columns are equal to another column	select u1.name, u1.date, u1.[main item], u2.name, u2.date, u2.item from (     select test.name, test.date, test.[main item]     from test)  as u1  inner join (     select test.name, test.date, test.[alt item 1]  as item     from test     union all     select test.name, test.date, test.[alt item 2] as item     from test     union all     select test.name, test.date, test.[alt item 3] as item     from test)  as u2  on (u1.name = u2.name) and (u1.[main item] = u2.[item]) where u1.date>u2.date 	0
12397614	3093	how to select the maximum version of a document from a list of document in sql?	select * from tbl t1 inner join (select title, max(version) as version from tbl where pageid=25 group by 1) t2 on(t1.title=t2.title and t1.version=t2.version) where t1.pageid=25 	0
12398386	18289	getting the next login	select * from ( select logi_in.logdatetime as 'in' , logi_out.logdatetime as 'out'  from mstr_attendance logi_in left outer join mstr_attendance logi_out on logi_in.employee_id=logi_out.employee_id and logi_in.tkstype=0 and logi_out.logdatetime =( select     min(logdatetime)                from       mstr_attendance mstr                 where      mstr.employee_id = logi_out.employee_id                and        mstr.tkstype = 1              and        mstr.logdatetime > logi_in.logdatetime         ) and logi_in.employee_id='ph120013' and logi_in.logdatetime='2012-08-26 02:30:00.000')t where out is not null 	0.00522552423351766
12398628	37912	select rate based on date dow	select       case          when cast(extract(dow from caldates) as int) < 6  then weekday_rate         else weekend_rate     end as the_date_rate from      calendar  where      caldates >= '2012-08-30' and  caldates <=  '2012-09-04' ; 	0.000810833458042028
12398903	4455	intermediate mysql query - join two tables together and limit the results	select post_id,post_votes,comment_id,comment_time,  @rn := case when @prev_post_id = post_id then @rn + 1 else 1 end as rn,         @prev_post_id := post_id from   (select p.post_id,post_votes,comment_id,comment_time from   (select post_id,post_votes from posts order by post_votes desc limit 10) p     left outer join     comments c on p.post_id=c.post_id order by post_id,comment_time desc )m having rn<=5 	0.0847700987871023
12399281	20494	select from union tsql	select a from (     select a, b from tablea     union     select a, b from tableb ) as tbl where b > 'some value' 	0.103195477474908
12399650	4574	sql count duplicate row as single	select distinct    x.state,    x.district,    sum(case when x.status=0 then 1 else 0 end) as active,   sum(case when x.status=1 then 1 else 0 end) as inactive from    (select state, district, stationcode, status    from station_master     group by state,district, stationcode, status) as x group by x.state, x.district 	0.00121346933980581
12403125	13254	get table join with column value	select msg_id,        msg_body,        usersby.username as msg_by,       usersto.username as msg_to,        msg_by_usertype     from messages     inner join      (select admin_id as id, admin_name as username       from admin_table               union               select manager_id as id, manager_name as username       from manager_table ) usersto on msg_to = usersto.id        inner join      (select admin_id as id, admin_name as username       from admin_table              union               select manager_id as id, manager_name as username       from manager_table ) usersby on msg_by = usersby.id 	0.00185126125369324
12403306	12517	how can i remove duplicates from a union all join query	select partnumber, min(price) from (   select 1 as tn, partnumber, table1.price   from   table1 join maintable using (partnumber) union all   select 2 as tn, partnumber, table2.price   from   table2 join maintable using (partnumber) union all   select 3 as tn, partnumber, table3.price   from   table3 join maintable using (partnumber) ) t group by partnumber having count(distinct tn) >= 2 	0.00744677364039756
12404561	21215	join where records dont match	select [columnslistyouneed] from  tableb  left join tablea on tablea.id = tableb.id 	0.0162822014908547
12406592	441	sql selecting from view and table	select v.col1, t.col2 from view v, table t where v.col1 = t.col1 	0.00417207954456239
12407467	9084	oracle sql help counting the same thing two different ways, but with common grouping	select t1.closure_date, count(t1.incident_id)      , ( select count(t2.incident_id) from incident_table t2           where t2.status = 'open'             and t2.raised_date < t1.closure_date )   from incident_table t1  where t1.closure_date is not null    and t1.status = 'closed'  group by t1.closure_date 	0.00124044606213932
12407594	39931	getting count values in mysql	select count(distinct semesterid),         count(distinct courseid)    from table1   where branchid = 4; 	0.0201279196235289
12408804	31928	deriving a thousands or hundreds range from a number in t-sql	select job_number,         convert(varchar(10), job_number / 1000 * 1000)       + '-'       + convert(varchar(10), job_number / 1000 * 1000 + 999) range   from whatever 	0.000813267975779891
12412548	35986	sql when a result has two rows of output, how can i sum them?	select cdt, sum(actions) as actions_sum     from (  select trunc(cdt) as cdt, count(cdt) as actions               from player_tapjoy              where trunc(cdt) >= to_date('2012-sep-01', 'yyyy-mon-dd') and                    trunc(cdt) < to_date('2012-sep-12', 'yyyy-mon-dd')           group by trunc(cdt)           union all             select trunc(cdt) as cdt, count(cdt) as actions               from player_aux_pt              where site = 'appcircle' and                    trunc(cdt) >= to_date('2012-sep-01', 'yyyy-mon-dd') and                    trunc(cdt) < to_date('2012-sep-12', 'yyyy-mon-dd')           group by trunc(cdt)) group by cdt 	8.55735104563808e-05
12412794	40053	mysql many-to-many search	select u.id, u.name from `user` u inner join `user_skill` us on u.id = us.user_id where us.skill_id in (1, 2) group by u.id having count(distinct us.skill_id) = 2 	0.526244281429098
12413014	22541	sql/oracle joining multiple functions	select sum(actions) from ( select count(t.create_dtime) as actions from player_tapjoy t inner join player_source s on (t.player_id = s.player_id) inner join feature_group_xref f on (s.group_id=f.group_id and f.feature_name = 'bc') where trunc(t.create_dtime) = to_date('2012-sep-12','yyyy-mon-dd') union all select  count(a.create_dtime) as actions from player_aux_pt a inner join player_source s on (a.player_id = s.player_id) inner join feature_group_xref f on (s.group_id=f.group_id and f.feature_name = 'bc') where a.site = 'appcircle' and trunc(a.create_dtime) = to_date('2012-sep-12','yyyy-mon-dd') ) 	0.682412024997601
12413145	35545	monthly report for project and total billingtime	select p.projectid,     p.projectname,     year(bt.createdon) as year,     month(bt.createdon) as month,     sum(bt.actualtotaltime) as totaltime from projects_tasks pt inner join projects p on pt.projectid = p.projectid inner join tasks t on p.taskid = t.taskid inner join billingstimes bt on t.taskid = bt.taskid group by p.projectid,     p.projectname,     year(bt.createdon),     month(bt.createdon), 	0.00238886797207865
12414552	4609	tsql: returning customers by date descending?	select top 30 name from customer group by name order by max(timestamp) desc 	0.0146584953642079
12414918	12589	top 1 row with count	select min(bin_name) as bin_name, count(*) as bin_count from ... 	0.00432178677251856
12416855	40103	sql query joining two tables	select products.product_id,liked_items.product_id,liked_items.user_id  from products       left join liked_items       on products.product_id=liked_items.product_id 	0.0411861209074664
12417896	10956	query to select record	select  * from    table t where   qty = 0 and     exists  (                     select  name                     from    table t1                     where   t1.name = t.name                     group by name                     having sum(qty) > 0                 ) 	0.0331660524940644
12418044	33881	how to run t-sql in another db server?	select * from [server].[database].[owner or schema].[tablename] 	0.110964805391542
12418281	34171	how to select a row where a col has two characters in a parentheses?	select * from t where c like '%(__)%' 	0.000819207412399936
12418843	9587	room booking sql query	select r.room_id from rooms r where r.room_id not in (     select b.room_id from bookings b     where not (b.end_datetime   < '2012-09-14t18:00'                or                b.start_datetime > '2012-09-21t09:00')) order by r.room_id; 	0.689943964557724
12420040	1733	linking row with a column in sql server	select ag.loc, ag.glacct,  ag.amount as agigingamount, trialbalanceamount= case ag.glacct    when '1101' then tb.g1101    when '1102' then tb.g1102 end from aging ag,trialbalance tb  where ag.loc = tb.loc; 	0.00700671546268982
12420249	19910	howto find a maximum value for attribute pairs in an mysql?	select date, device, max(configuration) as configuration from logdata group by date, device 	0
12421113	7058	how to pass different values of a certain column to an aggregate function conditionally?	select  loan_id,  sum(case when paid = 1 then amount else 0 end) as payed,  sum(case when paid = 0 then amount else 0 end) as remaining from payment group by loan_id 	0.000182514789655614
12422266	33483	how to find record count for some specific tables based upon a condition?	select users.id, users.email,         count(distinct orders.oid) as orders,         count(distinct travellers.tid) as travellers  from users     left join orders on users.id = orders.userid     left join travellers on users.id = travellers.userid where users.email = @email group by users.id, users.email 	0
12423192	10386	how can i count the number of rows in a table based on one field while trying to use other fields as well in ms sql server?	select *   from tblstudents   where studentid in (     select studentid       from tbltest       group by studentid, testid       having count(*) = 1   ) 	0
12425839	10123	select * from only one table	select t1.* from t1 inner join t2 on t1.joincolumn = t2.joincolumn order by t2.sortcolumn 	0.00017190160598165
12426491	26235	sql to get distinct records with pk	select min(id) as id, col1, col2 from tablex group by col1, col2 	0.00290134756127685
12426911	904	select the top child of a top child for each record	select a.id, (     select top 1 i.mycolumn     from groupb b      inner join groupc c on b.id = c.bid     inner join image i on c.imageid = i.id     where a.id = b.aid     order by b.id, c.id ) as mycolumn from groupa a 	0
12427729	17557	mysql differences between two select queries	select phone from civicrm_phone phone left join civicrm_participant participant on phone.contact_id = participant.contact_id where phone.is_primary = 1 and participant.id is null and     not exists (select 1                 from civicrm_phone phone2                 left join civicrm_participant participant on phone2.contact_id = participant.contact_id                 where phone.is_primary = 1                       and participant.id is null                       and phone2.phone = phone.phone               ) 	0.00233931592154743
12428380	5511	count on multiple joined tables	select     players.id,     players.name,     games.season_id,     games.game_type_id,     sum(case when g.goals is null then 0 else g.goals end) as goals,     sum(case when a.assists is null then 0 else a.assists end) as assists from players cross join games left join (   select     game_id, player_id,     count(*) as goals   from goals   group by     game_id, player_id ) g on     g.player_id = players.id     and g.game_id = games.id left join (   select     game_id, player_id,     count(*) as assists   from assists   group by     game_id, player_id ) a on     a.player_id = players.id     and a.game_id = games.id group by     players.id,     players.name,     games.season_id,     games.game_type_id 	0.00725664163487892
12429465	18488	how do i get a running sum in sqlite?	select type, count,        (select count(*)         from things t2 inner join              thinggroups               on thingid = t2.id inner join              groups               on groups.id=thinggroups.groupid          where groups.name='space' and               t2.type < things.type        ) as cumsum from (select things.type, count(things.name) as count        from things inner join            thinggroups             on thingid = things.id inner join            groups             on groups.id=thinggroups.groupid         where groups.name='space'         group by things.type       ) t order by type 	0.0360032487474184
12429615	25012	group by with multiple tables	select distinct agreements.agrmntid, jobsites.sitename,    customers.companyname, laborcodetypes...... 	0.130067156884311
12429693	21597	group and count patient records based on date of last visit with a physician	select        min(received_date) as firstvisit      , patient_id         as patientid into #lookuptable from f_accession_daily select         f.doctor           as doctor      , count(f.*)         as countnewpatients      , month(firstvisit)  as month      , year(firstvisit)   as year from f_accession_daily f  inner join #lookuptable l on f.received_date = l.firstvisit                           and f.patient_id = l.patientid group by f.doctor        , month(firstvisit)        , year(firstvisit) drop table #lookuptable 	0
12429763	6826	combine two mysql views into one view	select     portfolio.id,     portfolio.customer_id,     portfolio.location_id,     portfolio.title_text_id,     portfolio.description_text_id,     portfolio.started,     portfolio.finished,     mural.width from     portfolio join mural on mural.portfolio_id = portfolio.id 	0.000802107708567475
12431636	33677	mysql join to replace ids with value from another table	select    fromenc.encodingname as fromencoding,    toenc.encodingname as toencoding from encodingmapping inner join encoding as fromenc   on fromenc.id=encodingmapping.encodingfromid_fk inner join encoding as toenc   on toenc.id=encodingmapping.encodingtoid_fk where encodingmapping.itemid_fk = 45 	4.78323660950165e-05
12433749	36044	sql join multiple tables & get avg	select x.avgrating as rating, poker_sites.*,         networks.network_name, networks.network_icon      from poker_sites     left join networks         on (poker_sites.network_id=networks.network_id)     left join      (         select avg(editor_content.rating) as avgrating, editor_content.assign_id         from editor_content         group by editor_content.assign_id     ) x         on (poker_sites.site_id = x.assign_id)     where poker_sites.published=1 	0.0575654547432602
12434944	31279	retrieve data from mysql server within a time interval	select * from tbl_name where date_sub(now(),interval 1 minute) <= created; 	0.000213857295402997
12436634	22671	get results from entered first name plus last name of a user	select * from users_profile where concat(fname,' ',lname) like '%$q%' 	0
12438600	25010	sql: matching column's values as rows?	select t1.listing_id , t1.listing_value as listing_value1 , t2.listing_value as listing_value2   from table t1, table t2 where t1.listing_id = t2.listing_id and t1.field_id = "fruit" and t2.field_id = "color" 	0.000171104251142587
12438990	38310	select records from postgres where timestamp is in certain range	select *  from reservations  where arrival >= '2012-01-01' and arrival < '2013-01-01'    ; 	0
12439985	6579	get rows based off of first records values	select      field_value, field_label, record_id, data_element, data_id  from substance_data  where      record_id = 8  or  record_id in (select distinct                        data_id                    from                        substance_data                    where                        record_id = 8                  ) 	0
12440119	17171	php get mysql table info function	select table_schema, table_name from information_schema.tables; select * from information_schema.columns where table_schema='schema' and table_name='table'; 	0.012082702160549
12443709	31496	remove rows having swapped column values	select t1.* from dbo.mytest t1 where (select count(t2.rowid)           from dbo.mytest t2          where t2.tocol= t1.fromcol           and t2.fromcol= t1.tocol           and t1.rowid> t2.rowid) = 0 	0.000743793849882031
12443835	30981	search phpmyadmin database for similar entrys	select distinct ip, count(id) from users group by ip having count(id) > 1 	0.632371884751451
12446062	9840	mysql time difference on different row	select timediff(min(time_out), min(time_in)) as time_diff from your_table group by emp_id, `date` 	0.000233888086636454
12446349	27941	mysql select reverse query by db physical insertion	select ... from ... order by pk desc 	0.634213912833024
12447511	36756	effective sql query to find a given month is in between two dates	select     * from      your_table where     convert(datetime,'2012-02-01')         between dateadd(month, datediff(month, 0, start_date), 0)              and dateadd(month, datediff(month, 0, end_date), 0) 	0
12448036	30603	mysql/php forum order by?	select  f_thread.`id` as thread_id, f_thread.`uid`, f_thread.`title` as thread_title, f_thread.`hits`, u.`username`, max(f_posts.date) as last_post_date from `forum_thread` as f_thread left join `users` as u on u.`id` = f_thread.`uid`  left join `forum_posts` as f_posts on f_posts.`type_id` = f_thread.`id`     where f_thread.type_id = ".$_get['type_id']." group by thread_id order by last_post_date desc 	0.59177091246122
12449018	12300	sql count on many to many	select f.feature, count(f.feature)        from  post_feature l         join  features f on l.featureid = f.id         join  post p on l.post_id =p.id         where p.date > 'some_date'        group by f.feature 	0.0738176606130427
12451902	5266	mysql get difference of 2 dates...1 retrieved and 1 hardcoded	select datediff(concat(year(now()),'-12-25'), purchase_date) 	0.000301003196662778
12452396	1955	sql - grouping results by totaling	select retention as day      , sum(count(retention)) over(order by retention desc) as num_users_retained  from (select player_id             , round(init_dtime-create_dtime,0) as retention         from player        where trunc(create_dtime) >= to_date('2012-jan-01','yyyy-mon-dd')          and init_dtime is not null        ) group by retention order by retention 	0.234770064844231
12453508	25911	sql -- displaying results as percentages	select retention      , num_users_retained      , round(num_users_retained/max(num_users_retained) over() * 100, 2) as perc   from (select retention              , sum(count(retention)) over(order by retention desc) as num_users_retained          from (select player_id                     , round(init_dtime-create_dtime,0) as retention                 from player                where trunc(create_dtime) >= to_date('2012-jan-01','yyyy-mon-dd')                  and init_dtime is not null               )         group by retention         order by retention)  order by retention 	0.748031310432465
12454983	18303	build sum based daily record	select action, day,   (select sum(difference) from x     where action = t2.action and day <= t2.day     group by action) as total from x t2 group by action ,day 	0.00024057650104775
12457363	21761	how do i check the existence of a table using a variable as tablename	select @tabelexists = count(*) from sys.tables where name = ''' + @newtabelname +''') 	0.000882056585266884
12459340	16105	custom row numbering	select  mod(@currow := @currow + 1, 3) as row_number from    mytable m join    (select @currow := 0) r; 	0.0541541430149726
12461299	33726	date format in php/sql	select rfp_id, date_format(issue_date,'%d-%m-%y') as issue_date... etc 	0.0980715281324189
12461507	20462	getting scores from mysql - better option than sub-queries?	select playerid, count(playerid) as total from ( select playerid from scores where score1='10'  union all select playerid from scores where score2='10' union all select playerid from scores where score3='10' union all select playerid from scores where score4='10' union all select playerid from scores where score5='10' ) as thetable group by playerid 	0.516195365714374
12461700	25573	sql server 2008 - comma seperation using coalesce as part of a larger query	select  det.description,         starttime,          endtime,          (         select substring(         (select ',' + fileas         from objects         where objectid in (select objectid from dbo.get_xml_links(de.diaryeventid) where objecttypesystemcode = 'cct')         for xml path('')),2,200000)          )as contacts from diaryevents de inner join diaryeventtypes det on det.diaryeventtypeid = de.eventtypeid where eventtypeid in (29,40) 	0.761167812823837
12461765	38841	mysql and search on multiple row with multiple keywords	select * from table_name where concat(field1, ' ', field2) = 'apple peach'; 	0.0235838253395147
12462176	17397	show sql case statement as different columns	select bh.batch                 as batch_number,         bs.tbs_description       as batch_description,        bh.num_vouchers          as "num_vouchers(batch)",        sum (case when vs.tvs_code = 1 then 1 else 0 end) as in_stock,        sum (case when vs.tvs_code = 3 then 1 else 0 end) as terminate,        sum (case when vs.tvs_code = 5 then 1 else 0 end) as in_progress,        sum (case when vs.tvs_code = 6 then 1 else 0 end) as used,        sum (case when vs.tvs_code = 8 then 1 else 0 end) as deactivate from batch_hist   bh,      batch_status bs,      vouch_hist   vh,      vouch_status vs where substr(bh.allocat_date, 1, 6) = 201207 and   to_char(bh.status) = bs.tbs_code and   bh.batch = vh.batch and   to_char(vh.status) = vs.tvs_code group by bh.batch,          bs.tbs_description,          bh.num_vouchers order by 1,2,3; 	0.0346671982260958
12462310	33081	mysql select with multiple order by	select * from `table` order by `off`,     case `off`         when 0 then timestampdiff(second, current_timestamp, `when`)         when 1 then timestampdiff(second, `when`, current_timestamp)     end 	0.253084900938097
12463001	23056	mysql - stored procedure utilising comma separated string as variable input	select * from moments.product  where find_in_set(ean, var1) 	0.0275866957027372
12463233	29187	substring and trim in teradata	select case when tx.abcd = 'group'              and character_length(trim(both from tx.xyz) > 3             then substring(tx.xyz from (character_length(trim(both from tx.xyz)) - 3))             else tx.abcd        end from db.descr tx; 	0.680176303556468
12463263	21234	select number of records in various tables	select  'table1' as table_name, count(*) as record_count from table1 union all  select  'table2' as table_name, count(*) as record_count from table2 union all  select  'table3' as table_name, count(*) as record_count from table3 union all  select  'table4' as table_name, count(*) as record_count from table4 	0
12464669	34866	return value at max date for a particular id	select t1.id, t2.mxdate, t1.value from yourtable t1 inner join (   select max(date) mxdate, id   from yourtable   group by id ) t2   on t1.id = t2.id   and t1.date = t2.mxdate 	0
12464753	40765	dealing with missing values in sql server with binary column	select   id,   isnull(surveyresponserate, 0) as surveyresponserate,   isnull(personresponserate, 0) as personresponserate,   case when surveyresponserate is null then 1 else 0 end as survrrna,   case when personresponserate is null then 1 else 0 end as perrrna from ... 	0.165546582232756
12465180	13297	get last x rows using limit and order by col asc	select * from (     select *     from pms     where         (             (id_to = $id and id_from = ".sesion().")             or (id_from = $id and id_to = ".sesion().")         )         and id > $from     order by fecha desc     limit 50 ) q1 order by fecha asc 	0
12465642	6084	calculate how many hours from datetime and day of week name	select convert(date,starttimestamp) as date       , datename(dw,convert(date,starttimestamp)) as dayofweek       ,convert(time,[starttimestamp])as starttime       ,convert(time,[endtimestamp])as endtime       ,convert(time,[starttimestamp])+ convert(time,[endtimestamp])   from [taskmanagementsystem_db].[dbo].[timesheet_entry] 	0
12466825	22621	how to check if logins are enabled?	select logins_disabled from system.dictionary; 	0.00761906564742697
12467288	20319	showing all rows for keys with more than one row	select a.id, a.init, a.job from kal a inner join   (select init, count(init)    from kal   group by init   having count(init) > 1) b on b.init = a.init 	0
12467540	17879	sql join, or two selects?	select b.data  from tbl1 a left join tbl2 b on b.id = a.fid where a.id = 2 	0.541605699940937
12470132	10016	selecting a set based on an if or statement	select   iif( [sales].[retail] > 0 or [sales].[reseller] > 0 , { [measures].[revenue] } , {} ) on 0    from [cube] 	0.00371379096899323
12470319	37800	select value of column doesnt exist	select *  from store as s    left join setting as set           on s.store_id = set.store_id and set.key = 'config_template' order by url 	0.00638094596539798
12470680	41205	how to concat string in mysql?	select playtime,type  from( select m.medid,    min(timestampdiff(second, s.dmtviewstart, s.dmtviewend)) playtime,   concat(m.medtitle,' (minimum)') as type from tbldoctormediatracktest s left join tblmedia m   on s.medid = m.medid group by m.medid union all select m.medid,    avg(timestampdiff(second, s.dmtviewstart, s.dmtviewend)) playtime,   concat(m.medtitle,' (average)') as type from tbldoctormediatracktest s left join tblmedia m   on s.medid = m.medid group by m.medid union all select m.medid,     max(timestampdiff(second, s.dmtviewstart, s.dmtviewend)) playtime,   concat(m.medtitle,' (maximum)') as type  from tbldoctormediatracktest s left join tblmedia m   on s.medid = m.medid group by m.medid)a order by medid,  playtime 	0.180928939252878
12472057	27059	how to compare records within the same table and find missing records	select   t1.name,   t1.vlan from t t1 where not exists (select 1                      from t t2                    where t2.name <> t1.name                      and t2.vlan = t1.vlan) create table t  (   name varchar(10),   vlan int ) insert into t values('switch 1',1)    insert into t values('switch 1', 2) insert into t values('switch 1', 3) insert into t values('switch 2', 1) insert into t values('switch 2', 2) 	0
12473929	34589	mysql select from one table where does not exists in another, and is not a child in a third table	select distinct `ai`.`name` from `authitem` `ai` left join `auithitemassignment` `aa` on `aa`.`itemname` = `ai`.`name` and `aa`.`userid` = 1 where   `aa`.`itemname` is null  and `ai`.`name` not in (     select     `aic`.`child` itemname     from `authitemchild` `aic`     join `auithitemassignment` `aa`     on `aa`.`itemname` = `aic`.`parent`     where `aa`.`userid` = 1 ) 	0.000128881393301922
12474658	35247	calculate total working days left of the month	select number+1 as 'day' from   master..spt_values where  type='p' and    number <datepart(dd, dateadd(day,-1,dateadd(month,1,dateadd(month,                                           datediff(month, 0, getdate()),0)))) and    datename(weekday,dateadd(month, datediff(month, 0, getdate()),                                          number) ) not in ('saturday','sunday') 	0
12474886	17088	mysql select current and previous column from the same table	select a.orderid,a.parent,a.child from tbl a  join (select orderid,parent,child from tbl where orderid={$orderid}) b  on a.parent=b.parent  and a.child=b.child  where a.orderid<=b.orderid  order by orderid  desc limit 2 	0
12476005	4814	query in that matches all	select distinct report_id     from template t    where template_id in ('d','e')    and not exists        (select t1.report_id          from template t1         where template_id not in ('d','e')         and t.report_id=t1.report_id) 	0.00904545937376611
12477694	4745	sql unique records with multiple joins	select   table1.id1,   table1.id2,   table1.field1,   table1.field2,   table1.field3,   table1.field4,   table2.field1,   table2.field2,   t3.field1 from table1 left join table2   on table1.id1=table2.id2 and table1.id2=table2.id2 outer apply (select top 1 * from table3 where left(table1.id2,14)=left(table3.id2,14)) t3 	0.0324514184458611
12478056	32587	can i schedule a job to run at midnight of each timezone, and how to let the proc know which timezone to process?	select datediff(minute, getdate(), getutcdate()); 	0.00734301226570924
12478294	26238	is it possible to put null records as last results on a order by?	select top(200) ida from categories order by case when [order] is null then 1 else 0 end, [order] 	0.000250378645004249
12479018	27185	exclude records that have specific value in joined table	select table1.id from table1, table2 where table1.colour = table2.colour and not exists  (select t3.size from table2 t3 where    t3.size = 'small' and t3.colour = table1.colour); 	0
12479621	23387	check whether a column is empty	select * from items where extra is null or extra = '' 	0.00374709970693257
12480195	12363	query to identify submissions within x seconds of each other	select * from table t1 join table t2 on t1.user_id != t2.user_id where abs(to_seconds(t2.last_registered) - to_seconds(t1.last_registered)) < 3 	0
12480900	4788	remove duplicates from cfquery based on a particular column	select name, max(value) as value from yourtable group by name 	0
12481381	26899	getting data from 4 joined tables in on query (mysql)	select     articles.subject, group_concat(tags.tag) as tags, comments from articles     left join (           select aid,count(cid) as comments from comments group by aid     ) as commentscount on commentscount.aid = articles.aid     left join relations on relations.aid = articles.aid     left join tags on tags.tid = relations.tid group by     articles.aid 	0.000818277737697943
12481945	35650	mysql and gathering and counting information from multiple tables	select      a.name,     count(*) as 'count' from      c     join b     on c.matchedwith = b.b_id     join a     on a.id = b.b_id group by a.name order by count desc; 	0.00082568121644912
12482263	11557	oracle sql: transpose columns to rows	select max( case when rn = 1 then tot_dls else null end ) col_1,        max( case when rn = 2 then tot_dls else null end ) col_2,        max( case when rn = 3 then tot_dls else null end ) col_3,        <<25 more>>        max( case when rn = 29 then tot_dls else null end ) col_29,        max( case when rn = 30 then tot_dls else null end ) col_30   from (select day,                tot_dls,                rank() over (order by day) rn           from your_table          where day between date '2012-09-01'                         and date '2012-09-02'         ) 	0.00506713233235443
12482303	13832	oracle 10g select records that satisfy a certain condition	select msg_id from the_table where msg_id in (select msg_id from the_table where status = 'start') group by msg_id having count(distinct status) = 1 	0.000326843381660201
12483109	35572	how can i query using a foreign key in mysql?	select u.*, s.* from users u     inner join statuses s on u.status_id = s.id where u.status_id = 2 	0.0186402286558463
12484079	39798	small ms sql query to get the max of an id with some criteria	select top(1) a.id, a.[image], a.s_id, b.stat, b.[desc]   from tablea a   join tableb b on a.s_id = b.s_id  where b.stat = 1 order by a.id desc 	0.000918971199818613
12484254	21663	sql percentage count query by date	select a.adate, a.val, count(a.val) / b.datecount from table1 as a inner join (     select c.adate, count(*) as datecount     from table1 c     group by c.adate ) as b on a.adate = b.adate group by a.adate, a.val, b.datecount 	0.038472718696953
12484600	30376	verify result set has a row for each value in a column	select      subid,     workflowid from @datatable  group by subid, workflowid having sum(case when processcode = '10' then 1 else 0 end) > 0 and count(distinct (case when processcode in ('20','30','40') then processcode else null end)) < 3 	0
12485095	15831	selecting items in a manytomany relationship with jpql/hibernate	select article from article article inner join article.categories category where category.id = :categoryid 	0.00593509045919394
12486353	31485	order by number of selections found	select entity_name, count(*) count    from (          select e.entity_name, t.tag            from tag t            join entity e on (t.entity_id = e.entity_id)           where t.tag in ('tag', 'tag', 'tag')          )x   group by entity_name   order by count desc 	0.0321436807395583
12487495	40448	group rows by timestamp and conditionally sum different columns	select sum(count) as total     , sum(case                when source = 'outside'                     and destination = 'inside'                     then count                 else 0 end) as [inbound]     , sum(case               when source = 'inside'                    and destination = 'outside'                    then count               else 0 end) as [outbound]     , sum(case                when source = 'inside'                   and destination = 'inside'                    then count               else 0 end) as [internal] from table  group by round(timestamp/60) 	0
12488073	37308	selecting rows where conditions match a single row?	select * from tablea inner join tableb on tablea.timetag >= tableb.start and tablea.timetag <= tableb.stop where tableb.id = "1" 	5.88862959554336e-05
12488863	12576	mysql count and join tables	select table_forum.name_forum,count(table_thread.id_forum) from table_thread join table_forum where table_form.id_forum = table_thread.id_forum group by table_thread.id_forum 	0.179283353657433
12491091	15354	retrieve the later date from a collection in java	select max(date_column) from table group by trunc(date_column) order by 1 	0.000225880770767276
12491496	28027	enriching table	select   a.account_type as account_type ,b.at_account_type_desc ,count(a.ban) as num_ban ,  sum(case when a.column=value then 1 else 0 end) as 'user_colname1', sum(case when b.column=value then 1 else 0 end) as 'user_colname2'  from csm_adx.billing_account_act as a   left outer join csm_adx.account_type_act as b  on a.account_type = b.at_acc_type  group by 1,2 	0.169221500022344
12491909	28828	how to fetch data from multiple table?	select  a.*,         b.*,         c.*,                 d.*,         e.* from    tblmedassign a         inner join tbldoctor b             on a.doctorid = b.docid         inner join tbluser c             on b.usrid = c.usrid         inner join tblzone d             on c.userzoneid = d.zone_id         inner join tblmedassign e             on e.medid = a.medid where   d.zone_id = @zone_id or             d.zonename = @zonename 	0.000206671911358739
12492266	22760	sql query with order by inside two different groups	select id, player, mp, ppg from      playertable order by if (mp>=30, 1, 0) desc, ppg desc, mp desc` 	0.041435580774591
12493867	12320	mysql count rows in a join table statement, is it possible?	select a.dogtag, a.dateedited from dvdpedia a join dvd_uploads b on a.dogtag = b.dogtag join dvd_moderators c on a.dogtag = c.dogtag join  (select dogtag   from dvd_moderators   group by dogtag   having count(dogtag) = 1  ) as d on a.dogtag = d.dogtag where 1=1  and   b.uploader != 9  and   c.moderator != 9 order by a.dogtag asc limit 50; 	0.198445363708094
12494495	12494	select either one of the row with condition	select * from     (select a.*,           row_number() over (partition by product_reg order by product_no) as rnk     from supplier_details a    order by product_reg) where is_payable is null or rnk = 1; 	0.00126540939216597
12497325	1768	sql: sort a table by the first relation to a second table	select a.nm from tablea a cross apply (select top 1 *           from tableb b          join tablec c on b.id2 = c.id          where a.id = b.id1          order by c.nm) bc order by bc.nm 	0
12498876	31785	mysql - remove dublets and preserve first instance	select t.*, (t.created_date = tf.mindate) as isfirst from tbl_users t inner join (     select phone_number, min(created_date) as mindate     from tbl_users     group by phone_number ) tf on t.phone_number = tf.phone_number 	0.00790538486465769
12499490	4031	mysql order by disregarding signed numbers	select *  from table  order by abs(passion_level) desc 	0.0375655304853231
12499606	38611	non matching columns in two tables	select con.m_warranty_sku_id,        con.contract_type,        con.program_type,        con.underwriter,        wsk.m_warranty_sku_id,        wsk.contract_type,        wsk.program_type,        wsk.sku_underwriter from   mdhdba.m_contract con innerjoin mdhdba.m_warranty_sku wsk on wsk.m_warranty_sku_id = con.m_warranty_sku_id where  con.contract_type <> wsk.contract_type 	0.000193040062272779
12500521	23694	sql: select distinct sum of column with max(column)	select sum(s.pay) from (select person_id, max(start_date) as maxstartdate       from salary       where person_id in ( . . . ) and             start_date < <first day of month of interest>       group by person_id    ) p join    salary s    on s.person_id = p.person_id and       s.maxstartdate = p.start_date 	0.00494924632312852
12500770	27744	difference between starttime and endtime for groups of tasks	select nominalstart,min(timestarted),max(timeended),        datediff(ms ,min(timestarted),max(timeended)) as difference from taskruns group by nominalstart order by nominalstart 	0.000718834277007281
12500772	21416	anyone advise about sql queries and grouping 15 min interval data in to days?	select year(begintimeperioddt),         month(begintimeperioddt),         day(begintimeperioddt),         user_id,         sum(totallogintime) from mytable group by year(begintimeperioddt),           month(begintimeperioddt),           day(begintimeperioddt),           user_id 	0.0733444910492851
12500856	6899	select record based upon dates	select rate    from table1   where id = 1 and effdate = (   select max(effdate)      from table1     where id = 1 and effdate <= '2012-15-01'); 	6.35907173183184e-05
12501354	16332	total answer count	select q.postid, count(a.postid) from posts q  left outer join posts a on q.postid = a.parentid where q.type = 'q'  group by q.postid 	0.00615336880971828
12503005	15071	spaces returning all results in table	select distinct user_id 	0.0159410260609682
12504985	563	how to take last four characters from a varchar?	select right('abcdeffff',4) 	0
12506634	35509	oracle how to return the values in a single row	select       year     ,month     ,week     ,a.customer_id           ,c.cp_pk                                                                 ,c.dept_pk     ,min(decode (e.en_type,'11', e.en_pk )) as col1     ,min(decode (e.en_type,'11', d2.attr_pk)) as col2     ,min(decode (e.en_type,'10', e.en_pk )) as col3     ,min(decode (e.en_type,'13', e.en_pk )) as col4     ,min(decode (e.en_type,'13', d2.attr_pk)) as col5     ,count(*)       txn_count     ,sum(a_amount) total_amt from txn_header  t      ,customer a       ,txn_detail d1      ,txn_detail d2      ,cp_attribute c      ,gen_lookup e where   a.type  =  0             and     t.customer_id = a.customer_id and     t.txn_pk= d1.txn_pk and     t.txn_pk= d2.txn_pk and     d1.cp_pk = c.cp_pk and     d1.operation = 1  and     e.en_code = d2.new_code and     t.txn_pk= 12313 group by       year     ,month     ,week     ,a.customer_id           ,c.cp_pk     ,c.dept_pk 	0.000122615915052823
12508435	8670	mysql getting distinct id when joining a table with itself	select * from wp_posts p join                 (                     select max(post_date) as max_dtm, id                     from wp_posts                     group by if(post_parent = 0, id, post_parent)                 ) v on p.id = v.id and p.post_date = v.max_dtm; 	0.00244444775350884
12508619	38451	php show data with my case	select messages.msg_id,  messages.message,  messages.date_post,  messages.url,  messages.username,  user.username,  user.full_name,  user.status_friend from  messages,  user  where  message.username = user.username and (user.status_friend = '1' or user.username = 'myusername') order by msg_id desc 	0.557223257021614
12509664	3902	return only the current and past months of the year	select datename(month, dateadd(month, number-1,0)) from master..spt_values where type='p' and number between 1 and month(getdate()) 	0
12509794	8834	using max for date but adding column to group on 'breaks' the query - sub query?	select * from (      select location,date, type, notes, row_number() over (partition by location, type order by date desc) rn       from           notestable a            inner join location b on a.locationid = b.locationid            inner join type c on a.typeid = c.typeid       where typeid <> 8 ) v where rn = 1 	0.124491110373974
12512244	1376	oracle problems in obtaining data from the last list	select no from book where rowid = (select max(no) from book) 	0.000792861377644532
12512369	18846	tsql grouping with count	select   count(*) as count from (   select     name,     sum(score) as score   from    tablename   group by     name   having      sum(score) = 0 ) as aa 	0.31535083373953
12512952	17240	mysql group by last entry	select t1.* from payment_status t1   join (select payment_id, max(created) max_created         from payment_status         group by payment_id         ) t2     on t1.payment_id = t2.payment_id and t1.created = t2.max_created; 	0.000523640027373944
12513536	14212	xquery get node value	select @xml.value('declare namespace ns="http: 	0.00649249251038099
12514644	34995	sql multiple elements selection	select last.elementid, start.actionid as startaction, last.actionid as lastaction from (     select elementid, max(actionid) as actionid     from association     group by elementid     ) last inner join (     select elementid, min(actionid) as actionid     from association     group by elementid     ) start on start.elementid = last.elementid 	0.0375920588231597
12514807	14742	composite primary keys example in mysql	select pl.personid, l.languageid, l.languagename    from personlanguage pl     join language l on l.languageid = pl.languageid     where pl.personid = 1 	0.338323846216294
12515874	28465	how get min group row only in mysql?	select t.name, t.mygroup, t.scale     from test1 t         inner join (select mygroup, min(scale) as minscale                         from test1                         group by mygroup) q             on t.mygroup = q.mygroup                 and t.scale = q.minscale 	0.000330602317243099
12516078	37589	mysql count across multiple tables and get single value	select (select count(*) from t1)         + (select count(*) from t2)         + (select count(*) from t3)  ; 	6.31874744058904e-05
12516307	27520	finding a text from single or multiple mysql databases using a query	select col1 from db1.table1 where col1 like '%text%' union all select col2 from db1.table1 where col2 like '%text%' union all select col1 from db1.table2 where col1 like '%text%' union all select col1 from db2.table1 where col1 like '%text%' and so on 	0.00441287811468369
12517298	11320	how do i select the min and max values using a self join	select t1.client, t1.minvalue, t1.maxvalue, min(t2.date) as date_for_min_value, min(t3.date) as date_for_max_value from (     select client, min(value) as minvalue, max(value) as maxvalue     from mytable     group by client ) t1 inner join mytable t2 on t1.client = t2.client and t1.minvalue = t2.value inner join mytable t3 on t1.client = t3.client and t1.maxvalue = t3.value group by t1.client, t1.minvalue, t1.maxvalue 	0.0615324045084787
12518452	22189	get the result set from a table for each month of the selected date	select * from   your_table where  day(your_field) = 10 	0
12518533	5884	speeding up counting	select count(memberid) as membersincountycat from member     inner join nykacat on member.nykacatid = nykacat.nykacatid  where nykacountyid = @nykacountyid     and (nykacat.nykacatid = @nykacatid or nykacat.parentid = @nykacatid)     and profiletypeid <> 1 	0.591500615119327
12520617	32322	remove same values rows over different column mysql	select distinct type, user_id, friend_id, date  from table t1  where t1.user_id > t1.friend_id      or not exists (         select * from table t2              where t1.type=t2.type and t1.date=t2.date              and t2.user_id = t1.friend_id and t2.friend_id = t1.user_id      ) 	0
12521259	4168	sql - join 2 queries?	select   trunc(create_dtime) as day,   count(player_id) as new_users,   count(case when trunc(init_dtime) >= trunc(sysdate) - 7 then player_id else null end)     as retained_users from player where trunc(create_dtime) >= to_date('2012-jan-01','yyyy-mon-dd') group by trunc(create_dtime) order by 1 	0.336513805111123
12521407	19136	mysql how to find this substring position?	select @foo := locate(" used ", file), substring(file,@foo - 7,1) from test; 	0.171744268903223
12522373	17373	mysql multiple order set	select * from table_name   order by     if(status < 2, status, 3),     if(status = 2, to_days(end_date) * -1, to_days(end_date)) 	0.178978758463509
12523015	26857	how can i trim the results of a sql query, and remove duplicates?	select distinct substring(columnname,1,(charindex('.', columnname) - 1)) from tablename 	0.0231330797020762
12523105	22609	get unique rows of two tables	select id, name, 'tablea' from tablea where (id, name) not in (select id, name from tableb) union select id, name, 'tableb' from tableb where (id, name) not in (select id, name from tablea) 	0
12524784	18593	finding the min in a column where two other columns are zero	select min(imageid) from tablename where processing=0 and finished=0; 	0
12526017	4076	select multiple rows where matching two conditions	select userid from tablename where   (questionid = 14 and         answer = 'yes' ) or         (questionid = 54 and         answer <> 'empty') or         (questionid = 100 and         answer > 10) group by userid having count(*) = 3 	0.000827161615308747
12526222	35714	how to get results with zero values	select m.year_id,count(*) as distinctions         from newtestdb.dbo.[master_marks2005] as m left join         newtestdb.dbo.master_student as s on         s.student_id=m.student_id join         newtestdb.dbo.master_school as sc on         sc.school_id=s.school_code where         sc.school_code= 'an0001'         and         m.year_id between 1 and 8         and         m.[nrc_class]='d'  group by m.year_id, 	0.00234970321595482
12527578	39277	mysql find a line of text in a longtext column	select paragraphs from books where paragraphs like '\na line of text starts here%' 	0.0027520438823599
12527871	17120	storing/quering multiple value in sqlite	select group_concat(name) as [tree name]  from tree  where month like '%jan,feb,mar%' 	0.0651481947439815
12528048	23371	sql optimization : select distinct from one table	select  customer_product_order as order from master_list  where project_id     = "abcdd" group by customer_product_order  order by   order asc 	0.0260382860157033
12528644	28551	count duplicates records in mysql table?	select count(*) as duplicate_count from (  select name from tbl  group by name having count(name) > 1 ) as t 	0.00342221902233979
12529468	5684	finding the difference in days between different entries with same ticket	select ticket, date_diff(max(resolution_time) - min(arrival_time)) as diff from table group by ticket 	0
12530956	10809	mysql how do i count the number of occurences of each id?	select key_cat_name ,count(*)  from products_keyword_categories pkc      inner join products_keyword_to_product ptk on pkc.id=ptk.key_id  group by id; 	0
12531052	4843	mysql: get local time for a specific time zone	select * from users where hour(convert_tz(now(), server_tz, `timezone`))=16 	0.000773581315728026
12532114	8983	group by x and count the nulls in the same col	select concat( year( prm.fromdt ) , '|', month( prm.fromdt ) ) as k,         coalesce(concat( year( prm.fromdt ) , ' - ', month( prm.fromdt ) ), cast(count(*) as varchar(255)) as v    from prm group by k order by `k` desc 	0.000798294830047839
12532594	20093	mysql timestamp: output utc time instead of local server time?	select unix_timestamp(<your_datetime_col>)... 	0.0279721540843558
12532782	16079	query to know the average of data in each day	select  cast(datahora as date) as [date],         count(chave_id) as [entries] from    san_chave group by cast(datahora as date) order by [date] 	0
12534248	23775	sql server reverse order after using desc	select q.*      from (select top 3 *                from table                order by id desc) q     order by q.id asc 	0.773244063099827
12534305	17951	left join (or similar) on a single-column table to get whether each row is in other table or not	select * , b.id as `down` from `table_a` a left join `table_b` b on a.id=b.id 	0
12536778	11468	mysql complex query filtering by dates	select customers.ssn, certs.cert_num, certs.cert_start, certs.cert_finish from customers inner join      certs      on certs.ssn = customers.ssn group by customers.ssn having sum(case when certs.cert_finish < date_add(now(), interval 14 day) and                       certs.cert_finish > now()                 then 1 else 0            end) > 0 and          sum(case when certs.cert_finish > date_add(now(), interval 14 day)                 then 1 else 0            end) = 0       	0.599011026879581
12537968	19494	order by only the numeric part of a string	select [number] from dbo.tablename  order by convert(int, left(number, patindex('%[^0-9]%', number + 'z')-1)); 	0.00123208455952399
12538896	11899	mysql one to many join return all records	select * , group_concat( cast( g.genrename as char ) separator  ', ' ) as genrename from profiles p left outer join genre_profiles gpro on gpro.profileid = p.profileid left outer join genres g on g.genreid = gpro.genreid where gpro.isinfluence =  '0' and p.profileid in  (select gp.profileid from genre_profiles gp where genreid = 10) group by p.profileid 	0.000232862490814766
12538926	25490	database query to search using address	select city, postcode, name   from dealers   where name = p_search_term or         postcode = p_search_term or         city = p_search_term   order by case when postcode = p_search_term then p_search_term else 1 end desc            , case when name = p_search_term then p_search_term else city end asc 	0.324459197679585
12539209	12209	my sql query to find the max <= date with a matching primary key	select u.username,         (select email         from         (select tbl_user_hist.src_user_pk, tbl_user_hist.username, tbl_email_hist.email,         tbl_email_hist.src_email_pk, tbl_email_hist.tstamp, tbl_user_hist.user_pk         from  tbl_email_hist          inner join         tbl_user_hist on tbl_email_hist.src_email_pk = tbl_user_hist.email_pk and         tbl_email_hist.src_email_pk = tbl_user_hist.email_pk and                                tbl_email_hist.tstamp <= tbl_user_hist.tstamp) as e         where e.user_pk = u.user_pk order by e.tstamp desc limit 1) as email,         u.tstamp as username_tstamp          from tbl_user_hist as u 	0.000377744185677432
12539229	8303	mysql - count users where (last 30 days, last one year, all time)	select  count(case when datediff(curdate(),signup) <= 30 then id                    else null               end) as last30days ,         count(case when datediff(curdate(), signup) <= 365 then id                    else null               end) as last365days ,         count(*) as alltime from    table1 where   reffered = 14 	0
12540936	27547	mysql: excluding items in the same table collected in a subquery	select * from requests where completed = 0 and entity_id not in (select entity_id where accepted_account_id = '8' group by entity_id) 	0.000368883883239375
12541105	27574	sorting from smallest to largest	select *, substring_index(capacity, 'x', 1) as width,      substring_index(capacity, 'x', -1) as height  from mytable  order by width+0 asc, height+0 asc 	0.00153930837160127
12541170	23488	mysql how to find numbers near a string	select trim(replace(replace(`file`,'amount used',''),':','')) as `values` from mytable  where `file` like '%amount used%' 	0.0145189285379675
12541888	34107	sql ordering query	select name,         case isnumeric(substring(name, len(name)-4,2))      when 1 then              left(name, len(name)-8) + 'z' + right(name, 2) + '-' + substring(name, len(name)-4,2)          else name     end as sortby from [your table name] order by sortby 	0.657614478373812
12543595	15179	sqlite pragma to return a value in vb.net	select x from y 	0.0266873031117282
12543723	9561	selecting multiple maximum rows	select   x.domain,   x.no_of_users from   (select     d.domain,      count(d.domain) as no_of_users   from     domain d   group by      d.domain) x where   x.no_of_users =      (select       max(x2.no_of_users)     from       (select          d2.domain,          count(d2.domain) as no_of_users       from          domain d2       group by          d2.domain) x2) 	0.000176599792350864
12544953	23091	how to write a database query to search for the customers using address	select    city, postcode, name  from    dealers where  ... order by   case when @postcodeparam is not null then postcode end desc,   case when @nameparam     is not null then name     end,    case when @citynameparam is not null then cityname end 	0.0347832609856231
12546542	30466	sql query from related tables	select s.id, b.buyer, f.fruit  from shopping s join fruits f on s.fruit = f.id join buyers b on s.buyer = b.id 	0.0122921616077145
12547350	16813	mysql limit to not split a group	select schools.name,      regions.name from schools join (         select id, name          from regions          order by regions.name         limit 0,2) as regions     on regions.id = schools.region 	0.153644763388911
12548188	40954	select all threads with tag & the rest of the tags?	select threads.*, group_concat(tags.title) from threads as t left join thread_tags as tt on t.id = tt.threads_id left join tags as tt on tt.tag_id = tags.id where t.id in (     select tt.threads_id     from thread_tags as tt     join tags on tt.tag_id = tags.id               and tags.title = "test" ) group by t.id 	0
12552228	22839	mysql query help to fetch data by joining multiple tables	select b.domain, ex.country_code, c.country_name from base b  inner join extended ex on b.domain=ex.domain inner join countries c on ex.country_code=c.country_code where b.domain not in (select domain from banned_domains); 	0.0545811106811515
12552350	36500	mysql select count ... not like	select      count(             case                  when restricted not like '%us%' then 2                  else 1              end     ) as totalcount  from      reviews  where      restricted not like '%us%'      and restricted != ''      and restricted is not null 	0.699644662770484
12552665	943	query to select var regex many columns	select * from users where concat(username, ',', name, ',', email) regexp 'abc' 	0.184951269068434
12552768	38336	how can i select a value from a table twice with different values	select       sur.su_username  as recievername            , sus.su_username as sendername  from            message                 join systemuser sur                   on (sur.su_id = message.messagereciever )                join systemuser sus                   on (sus.su_id = message.senderid ) 	0
12554403	4272	db decision on choosing way to create a monitoring servers project	select * from `db_servers` where `user_id` = 5 	0.43013331289843
12555195	32634	return the sum of a field and all the rows using mysql	select *,        (select sum(amount)         from gains        where  `paid_date` like '%2012-09-23%') as sum_amount from gains where  `paid_date`  like '%2012-09-23%' group by admission order by `paid_date` 	0
12555413	17832	order by in other table	select topics.* from topics join comments on comments.id_topic = topics.id group by topics.id order by max(comments.date_comment) desc 	0.0140817410230631
12557446	7821	sql - select all records for month based on timestamp	select snapshot.xid, max(snapshot.timestamp) as timestamp_actual   from snapshot  group by snapshot.xid having max(snapshot.timestamp) >= dateadd(mm, datediff(mm, 0, getdate()), 0)    and max(snapshot.timestamp) <  dateadd(mm, 1+datediff(mm, 0, getdate()), 0) 	0
12558783	25749	move a table from one database to another database sql server	select * into db_2.t1 from db_1.[dbo].[t1] 	6.58209154762841e-05
12560460	31338	mysql : triggers calling procedures	select   sum(if(sem = 1, c_load, null)), sum(if(sem = 2, c_load, null)) s2   into s1, s2 from course c   join prefer p     on p.course_id = c.id   where staff_id = sid; update staff set sem = if(s1 > s2, 1, 2) where id = sid; 	0.728586814908809
12561239	26898	mysql search weight to result	select * from  ( select * from name where name like '% na%' union select * from name where name like 'na%' union select * from name where name like '%na%' ) a 	0.0721542527834558
12563952	11027	how to select item matching only in list in sql server	select pageid from   pagetags where  tagid in ( 1, 2, 4 ) group  by pageid having count(distinct tagid) = 3 	7.66323249080102e-05
12565780	20074	merging of rows along with getting other data in same query	select t1.col1, t1.col2, t1.type from table t1 join table             t2 on t1.col1 = t2.col2 and t1.col2 = t2.col1 and t1.col1 < t2.col1 union select t1.col1, t1.col2, t1.type from table t1 where not exists (select 1 from table where col1 = t1.col2 and col2 = t1.col1) 	0
12565790	18675	selecting both min and max from the table is slower than expected	select min(sdate), max(sdate) from mytable 	0.0390466892551248
12566168	40960	two indexes with a few columns or one index with all columns	select cola, cold, cole from dbo.my_table where cola = 1 and cold = 2 	0.000338489447330592
12566246	40971	[solved]search more strings in a query sql	select id_category  from wrs_category_lang  where id_lang = 5 and name in('keyword1','keyword2'...); 	0.659823121322898
12567197	560	use part of string in query	select ... from ... where (month(dob) = 9) and (day(dob) = 24) 	0.201570209815561
12568016	32958	concat columns including reserve word	select concat(sno,`table`) as stb from levels 	0.0264443353664196
12568771	40259	portable way to add dates between oracle and mysql?	select datecolumn + interval '1' day  from your_table 	0.0294691564721317
12568779	37304	transposing columns to rows using unpivot	select row id, left(yp, 1) as year, cast(right(yp, 1) as int) as period, val from (select row id     , qtyc1 as c1     , qtyc2 as c2     , qtyc3 as c3     , qtyc4 as c4     , qtyn1 as n1     , qtyn2 as n2     , qtyn3 as n3     , qtyn4 as n4 from mytable ) sub unpivot (val for yp in (c1,c2,c3,c4,n1,n2,n3,n4)) as pvt 	0.00617287403606998
12569334	33372	sql level the data conditionally	select market,   max(case when rn = 1 then value end) as submarketavalue,   max(case when rn = 2 then value end) as submarketbvalue,   max(case when rn = 3 then value end) as submarketcvalue,   max(case when rn = 4 then value end) as submarketdvalue,   max(case when rn = 5 then value end) as submarketevalue from  (   select id, market, submarket, value,     row_number() over(partition by market                        order by market, submarket) rn   from yourtable ) x group by market 	0.0984260352192017
12569419	17810	hybrid left/right join based on condition?	select u.name username, c.name company from user u left outer join company c on u.companyid = c.id where c.id is null or c.is_deleted = 0 	0.0575151923044943
12570454	30976	extracting data as columns for each month using only mysql	select `year`, `month`,     count(if (`new visitor?` = 'yes', 1, null)) as `yes`,     count(if (`new visitor?` = 'no', 1, null)) as `no`,     count(if (`new visitor?` = 'maybe', 1, null)) as `maybe`     from `table`     group by `year`, `month`; 	0
12570747	26028	how to: sql server select distinct field based on max value in other field	select id, tmpname, date_used, tkt_nbr from  (     select id, tmpname, date_used, tkt_nbr,         rownum = row_number() over (partition by tkt_nbr order by date_used desc) ) x where row_num=1 	0
12571857	18478	how to combine two columns into one	select    tb1.account,    status = coalesce(tb1.status, '') + coalesce(tb2.status, '') from tb1 inner join tb2  on tb1.account = tb2.account; 	0
12571995	39829	correlating data from two tables in oracle using a third which maps them together	select a.userid, a.name, b.groupname from users a, groups b, usergroupmap c where c.userid = a.userid and  b.groupid = c.groupid and c.userid = <searchid> 	0.000135068788996067
12572307	13075	how to dispaly the oracle search results?	select name, city, zip from (select name, city, zip,              (case when zip like '%7%' then 1                    when city like '%7%' then 2                    when name like '%7%' then 3                    else 0               end) as matchitem       from demo      ) d where matchitem > 0 order by matchitem 	0.259384785646124
12572899	17192	sql get offline website by threshold	select `sourcewebsiteid`, `name` from `sourcewebsite_updatelog` join `sourcewebsite` on `sourcewebsite_updatelog`.`sourcewebsiteid` = `sourcewebsite`.`id` where hour(timediff(now(), `sourcewebsite_updatelog`.`datetime_start`)) < `sourcewebsite`.`offlinethreshold` group by `sourcewebsiteid` having max(`episodestotal`) = 0 	0.0444678046005141
12573036	40938	how do i combine two queries into one?	select 1, * from table where name='name' union all select 2, * from table where name!='name'  order by 1, name; 	0.000617970781840576
12573139	19268	how to use order by for individual search result in oracle?	select title, place, postcode from (select title, place, postcode,              (case when postcode like '%9%' then 1                    when place like '%9%' then 2                    when title like '%9%' then 3                    else 0               end) as matchresult                        from test      ) d where matchresult > 0 order by matchresult,          (case when matchresult = 1 then postcode end) desc,          (case when matchresult = 2 then place                when matchresult = 3 then title           end) asc 	0.261220682954404
12575185	28077	hierarchical query and counting siblings?	select employee_id, manager_id, full_name, emp_level     ,(         select count(*)         from employees         start with employees.manager_id = employees2.employee_id         connect by prior employee_id = manager_id     ) descendents from (     select employee_id, manager_id, last_name||', '||first_name full_name, level emp_level     from employees     start with manager_id is null     connect by prior employee_id = manager_id ) employees2 where emp_level <= 2; 	0.735842273049782
12576446	2735	how to subtract records coming from one query from the records that is coming from another query?	select isnull(a.cnt,0) -  isnull(b.cnt,0) as cnt,a.zila from     (select zila,count(*) as cnt as abhidaynotpaidsansthan     from panjikaranmaster group by zila) a     left join      (select zila,count(*) as cnt from abhidaymaster,panjikaranmaster     where panjikaranmaster.officeregid=abhidaymaster.officeregid and     abhidaymaster.dipositdate between ('2012-09-19') and ('2012-09-24')     group by panjikaranmaster.zila) b      on a.zila = b.zila 	0
12577750	4077	select distinct on one col and everything else	select a.* from items a      inner join ( select min(id) id                   from items                   group by name                 ) b                 on a.id = b.id order by a.name; 	0.0164636286344711
12577881	22334	sql select distinct with where clause	select distinct personid from tablename where personid not in     (         select personid         from tablename         where kvalifikationid = 2     ) 	0.750335627165487
12580010	2117	list record by mysql query	select r.store_id, r.product_id, r.price from (        select *       from (             select *,             @cnt := if(@store_id = s.store_id, @cnt:= @cnt + 1, 1) as row_count,             @store_id:=s.store_id as a              from stores as s              left join (select store_id as sid, product_id, price                         from products order by store_id,price asc) as p              on s.store_id=p.sid where product_id is not null            ) as b, (select @store_id:='',@cnt:=0) as c       having row_count<=2       order by rating desc,store_id asc,price asc      ) as r; 	0.0166598114967591
12580867	38783	mysql adding values in a column based on values in other column	select @rownum := @rownum + 1 as id, invoiceid, sum(amount)  from <tablename>, (select @rownum := 0) r group by invoiceid 	0
12581556	2522	find duplicated rows that are not exactly same	select a, b from mytable where a in (     select a from mytable group by a having count(*)>1 ) 	0
12583063	25553	how can i join tables conditionally?	select * from tbl1 left join tbl2 on tbl1.value = tbl2.value and tbl2.value <> 0 	0.184110105082694
12583508	6218	splitting sql data into months	select count(id) as customers, datepart(month, enquirydate) as monthtotal, productcode from customerenquiries where enquirydate > '2012-01-01 00:00:00' group by productcode, datepart(month, enquirydate) 	0.00199850765192898
12584242	22691	how can i use pdo the php extension to make a query in mysql that uses a join (2 tables from different databases)?	select * from t1 left join otherdb.t2 on otherdb.t2.t1_fk = t1.id 	0.00466895740400062
12585550	34479	sql server 2008, how to check if multi records exist in the db?	select recipeid as existingrecipeid from recipeingredient where (ingredientid = 1 and quantity = 1)     or (ingredientid = 8 and quantity = 1)     or (ingredientid = 13 and quantity = 1) group by recipeid having count(*) = 3  	0.0089212934212425
12586723	4366	combining multiple complex select statements so they appear on one row	select     max(case sensorid when 1 then temp else null end) as "inttemp",    max(case sensorid when 2 then temp else null end) as "inttemp",    avg(case             when sensorid = 1               and tempreaddt >= dateadd(day,-1, sysdatetime())             then temp else null end) as "avgtemp24h",    avg(case             when sensorid = 1               and tempreaddt >= dateadd(day,-7, sysdatetime())             then temp else null end) as "avgtemp7d",    max(tempreaddt) maxtemp from temperature 	0.00740990189739913
12587241	13536	getting count() of a related tag	select count(*)                                                                from keywords   join topics_keywords  using (keyword_id)  where keyword != 'value'    and topics_id in (          select topics_id            from keywords             join topics_keywords            using (keyword_id)           where keyword = 'value' ); 	0.00262611974197093
12589342	500	sql group by - merge groups	select count(*)      , case size          when 'extra-large'          then 'large'      else size end as grouped_size from sizes group by grouped_size 	0.0280914607832466
12589963	13616	t-sql query against previous queries results	select distinct c1.* from @cust c1 where c1.entrydate between '2012-08-01' and '2012-08-30' and not exists (select 1      from @cust c2      where c2.entrydate < '2012-08-01'     and ltrim(rtrim(c1.firstname + c1.lastname + c1.company)) = ltrim(rtrim(c2.firstname + c2.lastname + c2.company)) ) 	0.143299723344057
12591498	39429	mysql - using 'as var_name' in select	select empcrns.crnansiclasscode,     concat('rev. ', empcrns.crnansiclasscode, ' ', emp_models.name) as modelname from emp_models join emp_revisions      on emp_revisions.id=emp_models.revision_id join (     select id,          case ansi_class             when -1 then 'n'             when 150 then 0             when 300 then 1             when 600 then 2             when 900 then 3             when 1500 then 4             when 2500 then 6             when 3500 then 8             else 'x'         end as crnansiclasscode     from emp_crns ) empcrns     on empcrns.id=emp_revisions.crn_id 	0.620585688061144
12593719	31	mysql: select query	select mat_id,sum(yes) yes_sum  from mat_likes  group by mat_id  order by yes_sum desc 	0.387336905290878
12594875	2227	how to determine the sql server replication type by tsql?	select       p.publication     ,p.publication_type     ,s.subscriber_id     ,s.update_mode from mspublications p inner join mssubscriptions s     on p.publication_id = s.publication_id 	0.340734900588329
12595578	40013	sp_helptext in oracle	select text from all_views where view_name = 'your_procedure_name' 	0.755759467372255
12600156	28561	retrieving an overall total of points and a weekly total within the same query	select   giver_id,   sum(points) as totalpoints,   sum(if(datetime >= '2012-09-24' and datetime <= '2012-09-30', points, null)) as weeklypoints from transactions group by giver_id 	0
12600699	29160	combine two select statements from same table with diff. where condition	select    sum(case when manager = 1 then 1 else 0 end) as managernumber,    sum(case when subb = 1 then 1 else 0 end) as subordinate  from emp 	0.00011141688822738
12601859	36758	group data based on one column	select      player,      max(case when name = 'email'   then  value end) as email,      max(case when name = 'gender'  then value end) as gender,      max(case when name = 'age' then value end) as age    from table     group by player 	0.000132783562067827
12602304	10904	mysql using select concat results as a condition in the same query	select * from users,room where user_name=concat('tm_',name); 	0.0417526714162132
12602362	9778	joining two tables on based on second number value from first table	select    t2.* from table1 t1 inner join table2 t2 on substring(t1.cul1,2,len(t1.cul1)-1)=substring(t2.cul1,2,len(t2.cul1)-1) 	0
12603677	17451	sql - using the results of subquery in select in the select	select concat(( select ... ), ' ', ( select ... )) 	0.0476742328843753
12603915	7662	sql join 2 tables based on third	select question, answer     from tbl_question q      inner join question_has_answer qha     on q.id = qha.question_id     inner join tbl_answer a     on qha.answer_id = a.id order by question,answer 	0.000988272128416158
12604146	32965	sql join on table a value within table b range	select * from table a     join table b         on a.month = b.month            and a.average between b.rangestart and isnull(b.rangeend,10000)  	8.59286007027876e-05
12604252	37436	mysql select pdostatement->rowcount	select count(*) 	0.445071290752215
12605107	30786	how to select data from two tables using a single query	select * from member left join networking on member.networkingid=networking.id where member.id=2 	0.000193374558194416
12607134	28410	sql - create "virtual" column based on data from other columns	select [sn],        [pn],        [computername],        [model],        [os],        [architecture],        [ram],        [cpu],        o.[username] as [primary user] from   computers c        outer apply (select top 1 [username]                     from   (select top (5) *                             from   logons l                             where  l.[sn] = c.[sn]                             order  by [timestamp] desc) last5users                     group  by [username]                     order  by count(*) desc,                               max([timestamp]) desc) o 	0
12608442	11081	how to get 2 records only if difference between them is more then 15 min	select     time1.time,     time2.time,     time1.serial,     (time2.time - time1.time) / 60 as usage from     mytable time1,     mytable time2 where     time1.id != time2.id     and time1.serial = time2.serial     and time2.time - time1.time > 60 * 15 	0
12609615	33628	mysql count record on condition, multiple fields selected	select   `jockeys`.`jockeyinitials`,   `jockeys`.`jockeysurname` ,   count(  `runs`.`jockeysid` ),    count( case when `runs`.`finish`=1 then 1 else null end ) as `finish` ,    sum(  `runs`.`stakewon` )  from runs, jockeys where  `runs`.`jockeysid` =  `jockeys`.`jockeysid`    and  `runs`.`jockeysid` >=1   and  `runs`.`jockeysid` <=100 group by  `jockeys`.`jockeyinitials`,   `jockeys`.`jockeysurname` 	0.00083635172866974
12611380	31502	choosing criteria in access	select [table 1].name, [table 2].name   from [table 1]   inner join [table 2]  on [table 1].name = [table 2].name 	0.227867969326838
12613493	14545	search mysql data in two tables with custom search options	select a.product_id from product_table a inner join multiple_table b on b.product_id= a.product_id 	0.0896624720435822
12613592	17979	select the latest entries by date grouped by serial	select  a.* from    `gps-log` a         inner join         (             select serial, max(`date`) maxdate             from `gps-log`             group by serial         ) b on a.serial = b.serial and                 a.`date` = b.maxdate 	0
12616509	21045	transactions and locks	select * from employee with (updlock) where id = @id update employee set name = @name where id = @id 	0.658797626677905
12617759	16300	how to display a string depending on datediff value in asp.net gridview?	select memname,      (case when  datediff(d,completedate,freetrialtaskmst.enddate) >0 then 'completed' else 'not complete' end) as  deadline   from member 	8.43077159959152e-05
12618662	18583	get last updated records doctrine mysql	select * from yourtable where id in(select max(id) from yourtable group by data_id) 	0
12620229	4500	get the list of tables created on any date?	select * from sys.tables where create_date >= '20120914' and create_date < '20120915' 	0
12620802	28564	incorrect sum when i join a second table	select reportsummary.reportdate, sum(reportsummary.sumheadcount) as sumheadcount, sum(productionsummary.sumquantity) as sumquantity from (   select report.reportdate, sum(report.headcount) as sumheadcount   from report    group by report.reportdate ) as reportsummary inner join (   select report.reportdate, sum(production.quantity) as sumquantity   from production   inner join report    on report.reportid = production.reportid   group by report.reportdate ) as productionsummary on reportsummary.reportdate = productionsummary.reportdate group by reportsummary.reportdate order by reportsummary.reportdate 	0.144850456797913
12621927	25519	check sql server table values against themselves	select strvalue= case                  when t1.intweight >= t2.intweight then t1.strtitle                  else t2.strtitle                end,         dist = fn_lev(t1.strtitle, t2.strtitle)  from   @tmpresults as t1         inner join @tmpresults as t2           on t1.intitemid < t2.intitemid  where  fn_lev(t1.strtitle, t2.strtitle) = 3 	0.0344421499408267
12622927	11267	group by and "first" or "min"	select a.*,u.name,m.subject,m.body from (select "from",max("datetime") as sent from messages  where "to" = 31 group by "from") a left join users u on a."from" = u.id left join messages m on a.sent=m."datetime" and a."from"=m."from" 	0.0378840988312492
12624457	9686	select query to generate and exclude some results by joining two tables	select home, configname, data, active from config union select ce.home, c.configname, c.data, c.active from config_exceptions ce inner join config c on c.configname = ce.configname where ce.data <> c.data and c.home = 0 	0.000331022243877051
12624693	33398	sql server : merge  instead of update	select * into temptable1 from table1 update temptable1  set value = 'asdf'  where id = 100` 	0.043395986121582
12626039	36330	loading multiple sql datatables to a single datatable, all tables share one column	select                 [t1].[catalogid]               , [t1].[name]               , [t1].[price]               , [t2].[stock]               , [t3].[minstock]     from               [table1] [t1]         left join               [table2] [t2]                 on [t2].[catalogid] = [t1].[catalogid]         left join               [table3] [t3]                 on [t3].[catalogid] = [t1].[catalogid] 	4.65308484693725e-05
12626246	37616	selected by groups with totals (mysql)	select  group_id, count(*) users_with_at_least_one_event from  ( select  u.user_id, u.group_id, count(*) as event_count from    users u         join events e         on u.user_id = e.user_id group by u.user_id, u.group_id having count(*) > 1 ) sub group by group_id 	0.0215702816161904
12627146	9530	how to group by in sql and then mark as 0,1	select item_id,        max(case when user_id = 3 then 1 else 0 end) as hasmatch from t group by item_id order by item_id 	0.0214628471704155
12627694	41050	how to select all within a category if at least one falls within range	select t.* from t join      (select distinct category_id       from t       where date between <datefrom> and <dateto>      ) tc      on t.category_id = tc.category_id order by t.category_id, date 	0
12628559	33510	select distinct of a column, but have other columns returned normally	select t1.user_id,         t1.donation_id,         t1.payment_status,         t1.pending_reason,        t1.txn_id,         t2.sum_gross,         t1.amount from the_table t1 join (    select max(donation_id) as max_id,            sum(mc_gross) as sum_gross,           user_id    from the_table    group by user_id ) t2 on t2.max_id = t1.donation_id     and t2.user_id = t1.user_id; 	0
12628860	9159	select first group of 10 for each day (removing duplicate records)	select id, clientid, type, [order], value, timestamp from (   select *, row_number() over (partition by clientid, [order],                                             datediff(d,0,timestamp)                                order by timestamp desc) rn   from billinginformation ) x where rn=1 	0
12629371	23188	sql server select query one column is the same and another is different	select      t1.id,      t1.week from      yourtable t1     join yourtable t2          on t1.id = t2.id         and t1.team < t2.team         and t1.week = t2.week 	6.48933126942607e-05
12630378	16199	t-sql to find length of time a particular value is in-range	select a.t, b.t   from tbl a  cross apply (     select top(1) *      from tbl b     where a.t < b.t        and <here's your function between a row and b row>     order by b.t asc ) x 	0.000168623239736069
12631801	38686	mysql query to retreive distinct count between moving date period	select     date_format(d1.started, '%y-%m-%d') as started,     count(distinct d2.userid) users from (     select         date(started) as started     from         session     group by         date(started) ) d1  inner join (     select distinct         date(started) as started,         userid     from         session ) d2 on d2.started between d1.started - interval 7 day and d1.started group by     d1.started order by     d1.started desc 	0.000287021791638961
12632638	37350	mysql group by with multiple column sums and a total sum for each group	select person,         sum(positive_vote) totalpositive,         sum(negative_vote) totalnegative,        (sum(positive_vote) + sum(negative_vote)) totalvotes from votes  group by person 	0
12633159	16267	how to determine if and which index is being used in oracle	select * from table(dbms_xplan.display); 	0.48798268591142
12633704	33867	how to select different value from same column?	select type,        case when  age < 10 then age end as ' age<10',        case when  age between 10 and 20  then age end as ' age 10-20',        case when  age > 20 then age end as ' age>20'   from your_table 	0
12634058	32794	oracle sql: show n rows for each id	select id, url from     (         select id, url,                row_number() over (partition by id order by url desc) rn         from   tablename     ) a where rn <= 5 	0
12634488	11346	how can i write a mysql query that will only return duplicate values, without using aggregate functions?	select w1.* from work w1     inner join work w2 on w2.manager_name = w1.manager_name and w2.worker_name != w1.worker_name     inner join work w3 on w3.manager_name = w1.manager_name and w3.worker_name != w2.worker_name     where w1.manager_name = w1.worker_name 	0.0334571539096118
12635552	4262	want to create comparison matrix from mysql table	select mrp,     max(if(brand='abc', usage,0)) as 'abc',     max(if(brand='xyz', usage,0)) as 'xyz' from table group by mrp; 	0.035659388452598
12637229	37543	basic sql subqueries to get more than two table	select flights.code, flights.start_time, flights.end_time,  flights.start_id, flights.endid,  a.name as sloc, b.name as eloc from flights left join airports a on (flights.start_id = a.id) left join airports b on (flights.endid = b.id) 	0.0546888404164189
12639030	19021	get the list of stored procedures created and / or modified on a particular date?	select      name,     create_date,     modify_date from sys.procedures where create_date = '20120927' 	0
12639226	35318	joining two mysql queries containing time functions	select      extract(hour from (timediff(now( ), (         select min(date_cmd)          from arc_commande_temp         where id_cmd =  '6580'      )))) as hours     ,     extract(minute from (timediff(now( ) , (         select min( date_cmd )          from arc_commande_temp         where id_cmd =  '6580'      )))) as mins 	0.0775812670889676
12641772	19740	native sql , generic duplicate entries retrieval	select f1 from t group by (f1) having (count(f2) > 1 and count(f3) > 1) 	0.0219269725168099
12643165	6382	wildcard in sqldatasource where clause to show all results	select * from [db_table] where ([site] = @site) and (roletype=@roletype or @roletype is null) 	0.256958210768548
12643888	9818	sql join two tables	select a.date, t.value1 from alldates a left outer join table1 t on a.date = t.date and t.userid = 1 where year(a.date) = 2012 and month(a.date) = 9     order by a.date 	0.0897065757232085
12644045	7379	mysql select closest result from todays date past/future	select e.*, s.* from      events e     inner join      schedules s on e.id = s.event_id order by      abs(unix_timestamp(schedule_datetime_from) - unix_timestamp(now()))) limit 1 	0.000391790879533883
12644686	30159	reorganise table structure or possible with one query	select count(1) from a join b on a.prod_id = b.prod_id where a.site_name = 'foo' 	0.39836207873929
12645297	35989	merge multiple rows into one column without duplicates	select player,   stuff((select distinct ', ' + cast(score as varchar(10))            from yourtable t2            where t2.player = t1.player            for xml path('')),1,1,'')  from yourtable t1 group by player 	0
12645414	22407	count and group by join	select     products.product,     count(users.prod_id) as productsbought from     a as products     inner join b as users         on products.prod_id = users.prod_id where products.site_name = 'ebay' group by products.product 	0.360261964323044
12645694	35151	retrieving multiple rows in mysql	select * from table where uniqueid in (111,123,220); 	0.00371141820884224
12646103	13240	mysql varchar to gmt date time value conversion	select str_to_date(substr(srcfilename,3,15), '%y%m%d.%h%i%s') from tablea; 	0.00544391911306326
12648565	10414	how to get the total rows on a database with one query	select (select count(1) from bill) + (select count(1) from items); 	0
12649119	39737	select total of childrens in multiple tables in one query with mysql	select u.name, w.uw as wins, l.ul as loses, d.ud as draws from user     left join (select user, count(id_won) uw from wons group by user) w on w.user = u.user_id     left join (select user, count(id_lose) ul from loses group by user) l on l.user = u.user_id     left join (select user, count(id_draw) ud from draws group by user) d on d.user = u.user_id 	0.000318735048600104
12652889	33265	how can i summarise several columns in mysql	select     sum(if(band="e",wte,0)) as `band6_wte` from  `orthoptists` as o left join `instances` as i on o.instance_fk = i.id where i.region = 14 	0.0188352062948826
12654263	3704	how do i put these different columns into the same row in postgresql?	select     item_bacon || ' + ' || item_eggs as items,     year,     bacon_avg_value + eggs_avg_value as amount,     bacon_avg_value as bacon_price,      eggs_avg_value as eggs_price from (     select t1.item, t2.item, t1.year, t1.avg_value, t2.avg_value     from (             select item_category, year, avg_yr_value             from earnings_and_prices             where item_category = 'bacon'     ) as t1(item, year, avg_value)     join (             select item_category, year, avg_yr_value             from earnings_and_prices             where item_category = 'eggs (dozen)'     ) as t2(item, year, avg_value)     using( year ) ) as t(item_bacon, item_eggs, year, bacon_avg_value, eggs_avg_value) order by year 	0
12654500	20624	sql: automated column selection	select current.* from some_table current    join other_table prev on prev.fid = current.id    join third_table nxt on nxt.oid = prev.id 	0.311182734264132
12659493	11196	how to convert int to datetime in sqlserver	select dateadd(second, 1100330268, '1970-01-01') 	0.0547251171796031
12660782	2857	sql check if group contains null	select id,         count(*) - count(value) as value from your_table group by id 	0.0858725860897292
12665869	37492	query different table when column exist	select (case when type = 'type1' then (select field from table1) else (select field from table2) end) as a from table; 	0.0120946920514692
12666502	3492	mysql in clause: max number of arguments	select * from table1  where table1.id in      (    select id from table2     ) 	0.115159111295795
12666513	12633	mysql query matching multiple fields?	select distinct b.collaborator_id, b.item_id from collab_table a     join collab_table b     on a.item_id = b.item_id where a.collaborator_id = 1     and b.collaborator_id != 1 	0.0300133086484939
12667515	34949	count rows by joining 3 tables	select au_agentid,mr_agentid    from            (select a.agentid,count(au.agentid) as au_agentid              from   agents a            left join assignunits au             on     au.agentid=a.agentid            where  a.adminsid='0'            group  by a.agentid )au       join       (select a.agentid,count(mr.agentid) as mr_agentid           from   agents a            left join assignmarketreport mr             on    mr.agentid=a.agentid            where a.adminsid='0'            group by a.agentid)mr         on    au.agentid=mr.agentid 	0.00201012796806034
12668421	13938	mysql comma separated	select *  from articles where find_in_set(articles.article_id,(select likes from user where user_id=100)); 	0.00526515419126728
12668528	26307	sql server : group by clause to get comma-separated values	select reportid, email =      stuff((select ', ' + email            from your_table b             where b.reportid = a.reportid            for xml path('')), 1, 2, '') from your_table a group by reportid 	0.0865557954081608
12668630	25916	sql select case	select catalogid, numitems, allitems - numitems ignoreditems from (   select i.catalogid,     sum(case when (ocardtype in ('paypal','sofort') or                    ocardtype in ('mastercard','visa') and                    odate is not null) and not exists (                      select * from booked b                      where b.ignoredoid = o.orderid                    ) then numitems                    else 0 end) numitems,     sum(numitems) allitems   from orders o   join oitems i on i.orderid=o.orderid   group by i.catalogid ) x 	0.758030227898525
12669430	27148	mysql query to select join from 5 tables	select t.tagid, t.tagdetails, count(distinct u.u_status), count(distinct i.i_status)         from tag t              join subscribe s on t.tagid = s.tagid              join user u on s.userid = u.userid              join item_tag it on t.tagid = it.tagid              join item i on it.itemid = i.itemid         where u.u_status = 'active' and i.i_status = 'active'         group by t.tagid         union         (select tagid, tagdetails, 0, 0         from tag         except         select t.tagid, t.tagdetails, 0, 0         from tag t              join subscribe s on t.tagid = s.tagid              join user u on s.userid = u.userid              join item_tag it on t.tagid = it.tagid              join item i on it.itemid = i.itemid         where u.u_status = 'active' and i.i_status = 'active'         group by t.tagid) 	0.0152714474939947
12669757	29330	sql, not in within a group	select f1  from t1      left join t2          on t1.f2 = t2.f3          and t2.f4=2 where f3 is null 	0.51828156052687
12670926	5008	search for negative numbers in mysql	select count(*) from account where amount<0; 	0.031927908939677
12671117	33231	comma separated values with sql query	select city_code,        post_code =          stuff((select ', ' + post_code            from your_table b             where b.city_code = a.city_code            for xml path('')), 1, 2, ''),       post_code_description=         stuff((select ', ' + post_code_description            from your_table b             where b.city_code = a.city_code            for xml path('')), 1, 2, '') from your_table a group by city_code 	0.00356478481467011
12671961	34506	mysql get count and average	select       yt.questionid,       yt.responsevalue,       count(*) as totaloptresponses,       totalbyq.totalqaverage    from       yourtable  yt          join ( select questionid,                        avg(responsevalue * 1.0000 ) as totalqaverage                    from                       yourtable                    group by                       questionid ) totalbyq             on yt.questionid = totalbyq.questionid    group by       yt.questionid,       yt.responsevalue 	0.00133894653634058
12674559	12997	datediff every 3 days	select distinct  claim_no, modifiedby, claimtype, claimstatus, emailaddress, from ep_admin_item_reminder where status = 1 and datediff(day,dateadded,getdate()) > 2 	0.000698099237241861
12674658	3524	how to concatenate 2 same-table queries results keeping a unique key in sqlite?	select  a.* from    foo a         inner join         (             select  aaa, bbb, max(ccc) maxc             from foo             group by aaa, bbb         ) b on a.aaa = b.aaa and                 a.ccc = b.maxc and                 a.bbb = b.bbb 	0.000152796458342832
12674714	34606	sql different column type comparison error	select * from users u  inner join trans t on u.userid  = (case when isnumeric(t.id) = 1 then convert(int, t.id) else 0 end) 	0.517507775608683
12675322	13158	how do i select unique combinations from mysql?	select least(col1, col2), greatest(col1, col2) from mytable group by least(col1, col2), greatest(col1, col2) 	0.00052600930422385
12675386	26792	how to display data from different tables column into one table column	select     location =c.location            ,customer =c.customer            ,service =c.service            ,location2=(select b.location from table2 b  where     b.customerid=c.customerid)     from   customer c  	0
12675882	20327	mysql using like command to find between semi-colon	select *   from `products`  where `category` = 'swarovski'  and (     `colours` = 'silver'      or `colours` like 'silver;%'      or `colours` like '%;silver;%'      or `colours` like '%;silver'  ) 	0.234714641732431
12676727	28034	list a status even when there are no records in the resultset with that status when querying with t-sql	select s.name as status, coalesce(count(t.*),0) as [count],      coalesce(sum(t.amount),0) as amount from status s left outer join mytable t on s.id = t.statusid group by s.id, s.name 	0
12677133	35725	sql: modify query result rows that have a unique value	select tba.mychar , case when tbu.mychar is null then tba.mynum else 0 end as newnum from mytab tba left join (     select mychar     from mytab     group by mychar     having count(*) = 1 ) as tbu on tba.mychar=tbu.mychar 	0.000163801736785754
12677707	39599	mysql select date equal to today	select users.id, date_format(users.signup_date, '%y-%m-%d')  from users  where date(signup_date) = curdate() 	0.00277079930404505
12677941	18939	matching sub string in a column	select pin, count(1)  from mytable (nolock)  cross apply splitstring(offercode,'~') outparam  where outparam.value = @offercode and pin = @pin group by pin 	0.0205137449105048
12678330	30849	mysql left join does not return all values	select  d.flight_no   , b.arrival_flight from   jtl_booking_transfer_details b left join jtl_flight_info d          on  d.flight_no = b.arrival_flight left join  jtl_booking_master a     on a.voucher_number = b.voucher_number left join jtl_hotels c     on b.hotel_id = c.hotel_id left join jtl_airlines  e     on  e.airline_code = d.airline_code 	0.357469507996002
12678555	39270	comparing values in different tables with sqlite	select max(maxdateadded) from (  select max(dateadded) as maxdateadded from a   union  select max(dateadded) as maxdateadded from b  union  select max(dateadded) as maxdateadded from c ) as unioneddateaddedtables 	0.00233361371019562
12680502	36290	sql create an array from several rows	select id, collect_set(some_value) as list_of_values     from yourtable      group by id; 	0.00173513397833522
12684139	11090	mysql concatenate data from multiple columns skipping dups	select locationid, group_concat(day_group) from (     select     locationid, concat(group_concat(`day`),": ", open, "-", close) as day_group     from tableb     group by locationid, open, close ) daygroup; 	6.391416905204e-05
12687150	29656	how to order by multiple columns with different priority for each column?	select *, priority*0.6+age*0.4 as sortkey from ... order by sortkey. 	0
12688019	33259	how to group and count 2 different types like this?	select items, status, count(*) as count    from tablename    group by items, status 	0.0764576332962935
12688080	39290	sql query to combin results from same table	select * from (select id as customerid, name as customername, phonetype, phone      from customers inner join phones on customers.id = phones.customerid ) src pivot (max(phone) for phonetype in ([phone1],[phone2],[mobile1],[mobile2])) p 	0.00388974424431159
12688085	35759	sql joining multiple tables, columns from 3rd table not showing	select catalogid , numitems, allitems - numitems ignoreditems, x.c1,x.c2,x.c3,x.c4,x.c5,x.c6,x.c7,x.c8     from (      select i.catalogid,      sum(case when (ocardtype in ('paypal','sofort') or                     ocardtype in ('mastercard','visa') and                     odate is not null) then numitems                     else 0 end) numitems,      sum(numitems) allitems ,      t1.c1, t1.c2, t1.c3, t1.c4, t1.c5, t1.c6, t1.c7, t1.c8     from orders o     join oitems i on i.orderid=o.orderid     join products t1 on t1.catalogid = i.catalogid     group by i.catalogid, t1.c1, t1.c2, t1.c3, t1.c4, t1.c5, t1.c6, t1.c7, t1.c8     ) x 	0.000370035765708317
12688161	14248	mysql select rows not in query	select id from statistics  where id not in (select id from statistics where useragent not like '%bot%') 	0.148244348651653
12688205	11886	sql: find difference between rows where a column value matches	select x1.yg_requester_id, datediff(second, x1.newdatetimefield, x2.newdatetimefield) as timedifferenceinseconds, x1.referent_id as newarticle, x2.referent_id as formerarticle from ( select row_number() over(partition by yg_requester_id order by newdatetimefield desc) as position, newdatetimefield, yg_requester_id, referent_id from yourtable ) x1 inner join  ( select row_number() over(partition by yg_requester_id order by newdatetimefield desc) as position, newdatetimefield, yg_requester_id, referent_id from yourtable   ) x2 on x2.yg_requester_id = x1.yg_requester_id and x2.position = x1.position - 1 	0
12688339	22126	mysql query for 1nf table	select c.clientname,    c.clientlastname,   c.clientzip,   c.product from clients c inner join  (   select clientname   from clients   where product = 'product1'  ) x   on c.clientname= x.clientname 	0.403652809872131
12688783	37776	sql: find all children whose parents are like mine	select   otherkids.* from   child me   inner join parent myparents on myparents.id = me.parentid   inner join parent otherparents on otherparents.class = myparents.class   inner join child otherkids on otherkids.parentid = otherparents.id where   me.id = :myid and   otherkids.id <> me.id 	5.00920690988736e-05
12689640	584	sum of multiple records from joined table?	select sum(at.hoursworked) from     anothertable at     join (select a, b, c from thistable) t     on at.a = t.a and at.b = t.b and at.c = t.c 	0
12690619	1632	retrieve names columns of all tables in a sql server database	select   sysobjects.[name] as tablename,        syscolumns.[name] as columnname,        systypes.[name] as datatype,        syscolumns.[length] as length    from        sysobjects inner join syscolumns    on sysobjects.[id] = syscolumns.[id]        inner join systypes   on systypes.[xtype] = syscolumns.[xtype]   where  sysobjects.[type] = 'u'   order by  sysobjects.[name] 	0
12690663	2208	group mysql query results in php generated table and add results of table row together with same id	select   job_number,          sec_to_time(sum(time_to_sec(time_off) - time_to_sec(time_on))) from     my_table group by job_number 	0
12691545	34167	exclude records with sql	select *  from komponens where kkod not in (     select kkod     from komponens     where fkod = "su" ) 	0.0132132949705049
12693089	34876	pg::error: select distinct, order by expressions must appear in select list	select distinct(event_id, start_time) from ... select distinct event_id, start_time from ... 	0.304501490167672
12693111	33261	count multiple columns with group by in one query	select       sum(case when column1 is not null then 1 else 0 end) as column1_count     ,sum(case when column2 is not null then 1 else 0 end) as column2_count     ,sum(case when column3 is not null then 1 else 0 end) as column3_count from table 	0.00662682201976434
12693284	12251	prevent query from using index	select ... from sometable ignore index (`name_of_index`) where ... 	0.321823704229501
12693566	26431	sql select what in range number	select * from table where ? between minrange and maxrange 	0.0132719149036033
12694986	41256	mysql self join to find a parent child relationship in the same table	select horses.horseid, horses.horsename, horses.sireid, b.horsename as sirename from horses left join horses b on (horses.sireid = b.horseid) 	9.04326346959682e-05
12695128	18921	how to get a list of user defined data types on sybase ase?	select s1.name,          (select name           from systypes s2           where s2.usertype=(                             select min( s3.usertype)                              from systypes s3                              where  s3.hierarchy=s1.hierarchy)         ) base_type,  user_name(s1.uid) as owner     from systypes s1     where s1.usertype>100 	0
12695339	19691	mysql two select statements into one mark differences with column value	select a.alias_title, a.title, a.hits, a.created_on, a.updated_on, a.updated_by,        im.alias_title = in_image_alias_title as q1,          a.user_id      = user_id              as q2    from   album       a   join album_image ai on a.id        = ai.album_id   join image       im on ai.image_id = im.id where  (im.alias_title = in_image_alias_title or a.user_id = user_id)    and a.approved = in_album_approved    and a.visible  = in_album_visible 	0
12695352	17514	mysql query to get last status value entered	select t1.id,      t1.check_date,     t1.number,     t1.status from yourtable t1 inner join (     select max(check_date) maxdate, number     from yourtable     group by number ) t2     on t1.check_date = t2.maxdate     and t1.number = t2.number 	0
12695393	8157	something like not like (select statement from other table)	select * from valid_list where not exists    (select * from prefix_list where valid_list.part1 like '%' || item || '%')   and not exists   (select * from suffix_list where valid_list.part2 like '%' || item || '%') 	0.321833416371692
12695963	9130	find broken relations in mysql	select * from link_users where link_id not in (select link_id from links); 	0.0903178514842754
12696364	34966	how to compress multiple rows with concat	select c.id, group_concat(o.name)     from cog c         inner join organism o             on c.id = o.cog_id     group by c.id; 	0.023769402932392
12696477	11835	query the database to find what nth is the record	select e               as entry,        sum(sessions)   as tot_sess,        count(*)        as tot_cust,        sum(sessions=1) as 1sess,        sum(sessions=2) as 2sess,        sum(sessions=3) as 3sess,        sum(sessions=4) as 4sess,        sum(sessions>4) as more4sess,        sum(orders  =1) as order1sess,        sum(orders  =2) as order2sess,        sum(orders  =3) as order3sess,        sum(orders  =4) as order4sess,        sum(orders  >4) as ordermore4sess from (   select b.e, b.c_id, b.sessions, count(a.entry) as orders   from   customer_activity_log a right join (     select   date(entry) as e, c_id, count(*) as sessions,              min(if(ord_num=0,null,entry)) as o     from     customer_activity_log     group by e, c_id   ) b on a.c_id = b.c_id and date(a.entry) = b.e and a.entry <= b.o   group by b.e, b.c_id ) t 	0.000639163838684375
12696548	40763	in sql, trying to return a record for each instance where it triggers the from criteria	select clientname, null as spousename, birthday     from clientdetailstable     where <birthday calculation is true> union all select clientname, spousename, spousebirthday     from clientdetailstable     where <spouse birthday calculation is true> 	0
12697142	18200	rails mysql find joined table's joined table by date created at not within n months	select companies.* from companies  join clients on clients.company_id = companies.id   join groups on groups.client_id = clients.id  group by companies.id  having max(groups.created_at) < '2012-06-01'; 	0
12698608	15505	sql find match in at least two of the three tables - combine queries	select * from [user] u left outer join user_job_not_looking as ujnl on ujnl.user_id=u.user_id left outer join user_job_own_venture as ujov on ujov.user_id=u.user_id left outer join user_job_ft_job as uj on uj.user_id=user_id where  (ujnl.user_id is not null and ujov.user_id is not null) or (ujnl.user_id is not null and uj.user_id is not null) or (ujov.user_id is not null and uj.user_id is not null) 	0
12701578	37916	combine 2 mysql queries into one table with unique rows	select x.expr1, sum(x.expr2) from    (select      projects.name as expr1     , sum(time_records.value) as expr2   from project_objects   inner join projects     on projects.id = project_objects.project_id   inner join time_records     on time_records.parent_id = project_objects.id   where time_records.parent_type = 'task'    group by projects.name   union   select      projects.name as expr1     , sum(time_records.value) as expr2   from projects   inner join time_records     on projects.id = time_records.parent_id   where time_records.parent_type = 'project'   group by projects.name) x group by x.expr1 	0
12701683	18467	pivot table and get aggregation on multiple arguments	select p.region,        p.item,        isnull(p.[1998], 0) as [1998],        isnull(p.[1999], 0) as [1999],        isnull(p.[2000], 0) as [2000] from yourtable unpivot (itemssold for item in (carssold, bicyclessold)) as u pivot (sum(itemssold) for year in ([1998], [1999], [2000])) as p order by p.region, p.item 	0.082420889850769
12702769	37256	retrieving the last level of categories in mysql	select id, name, parent from category  where id not  in ( select parent from category ) 	0
12702918	28329	mysql where column = distinct	select id, date, name from table group by date(date) 	0.0963691182202584
12702923	28967	sql query- id not exist in another table or exist but with all records are in history?	select * from t1 where id not in(select id from t2 where history_flg!=1) 	0
12705306	24758	how to get list of all materialized views in oracle	select * from all_snapshots 	0.000720256064673459
12706310	37444	linq select different column into one	select new { address = s.address + " " + t.address }; 	0.00100750464431774
12706948	32201	mysql delete rows from a table that have 2 columns or more in common	select * from tb as t1   where exists (     select 1 from tb as t2      where t2.c0= t1.c0     and t2.c1= t1.c1     and t2.c2= t1.c2     and t2.id> t1.id ) 	0
12709320	38047	need a sequence number for rows in query	select * from (    select (@row:=@row+1) as row, id , cola, colb, colc     from tablea      join tableb on tableb.id = tablea.id     join tablec on tablec.id = tablea.id      ,(select @row := 0) r  ) t order by row asc 	0.0112883705495526
12709663	1007	alter mysql db column value in select	select if(mycol=-1, 0, mycol) 	0.00665523101884698
12710041	36431	how can i find the average agi given the number of returns with mysql?	select zipcode,         avg(a00100) as average_income from taxbyzip2008  group by zipcode 	0
12710095	11460	mysql: calculate the duration for multiple statuses	select first_name, last_name,   (date_format( from_days( sum( case when q.status_id = 1 then datediff( ifnull( q.date_to, now() ) , q.date_from ) ) else 0 end ) , "%y" ) +0) as active_years,  (date_format( from_days( sum( case when q.status_id = 2 then datediff( ifnull( q.date_to, now() ) , q.date_from ) ) else 0 end ) , "%y" ) +0) as veteran_years, (date_format( from_days( sum( datediff( ifnull( q.date_to, now() ) , q.date_from ) ) ) , "%y" ) +0) as total_years   from member a   left join member_status q on a.id = q.member_id and q.status_id in (1,2)  group by a.id 	0.00281673861459421
12711699	8826	return all rows where the entire list of a relation matches (as opposed to any combination of)	select          data.id       from          data      inner join          taggeddata on (data.id = taggeddata.data_id)      inner join          tag on (tag.id = taggeddata.tag_id)      where          tag.id in ('1' , '2')      having count(distinct tag.id)=2 	0
12711788	28903	group by with the most recent elements	select ru.page_id as id,      pfrom.name as name,     unix_timestamp(ru.rating_time) as action_date,                               ru.current_rank as current_rank,             rum.maxdate from ranks_update ru inner join(     select page_id, max(rating_time) as maxdate     from ranks_update     where ranking_id = :id_rk         and page_id in ( ** subquery 1 **)         and rating_time >= ( ** subquery  2 **)        group by page_id ) rum on ru.page_id = rum.page_id and ru.rating_time = rum.maxdate inner join pages pfrom on ru.page_id = pfrom.page_id order by ru.current_sum_vote desc 	0.000115996108052728
12712197	3697	join produces 2 rows instead of one	select a.name, a.count1, a.min1,a.max1,a.sum1,a.avg1 from #amt_payments a union select b.name, b.count1, b.min1,b.max1,b.sum1,b.avg1 from #cur_bal b 	0.00276824778067371
12713187	7869	sql sum field when column values match	select sum(value) as 'total', [product name] from tablex   group by [product name] 	0.00237676663212934
12714625	22174	mysql efficient lookup query	select products.*,stock.stock,cheapest.cheapestprice from (select id,min(price) as cheapestprice from stock group by id) cheapest inner join stock on stock.id = cheapest.id inner join products on product.id = stock.pid order by cheapest.cheapestprice 	0.724944426290999
12715694	29680	selecting rows where a column contains at least one character not in a whitelist	select top 10 foo from bar where foo like '%[^a-z0-9]%' 	0
12716996	19269	how to form an sql query that is like using 'in' across two columns as pairs?	select yourtable.*  from yourtable      inner join       (           select 2 as v1, 3 as v2            union select 3,4           union select 2,5           union select 3,6      ) pairs          on yourtable.value1 = pairs.v1          and yourtable.value2 = pairs.v2 	0.00192286569970083
12717372	4686	mysql: need help by selecting every nth row	select * from thetable where id like "%4"; 	0.00370834150583459
12720135	18805	mysql stored procedure to find the closest matching call rate for a phone call	select     s.a_party, s.b_party, (            select  cr.rate_per_min            from call_rate_overrides cr            where s.a_party like concat(cr.a_party, '%')            and s.b_party   like concat(cr.b_party,  '%')            order by length(cr.a_party) + length(cr.b_party) desc, cr.rate_per_min            limit 1      ) as rate_per_min from call_usages s 	0.0234640663897531
12722400	11847	mysql select from colon	select title  from thread where find_in_set(thread.thread_id,         (select replace(replace(my_threads,':',','),' ','') from user where user_id=100)) 	0.0399840300092307
12722605	38189	pull db row with foreign key	select user.*, userpost.*    from user, userpost   where user.id=userpost.userid 	0.000203539938038432
12722728	28823	query to find the first date after a specific grouped sum value	select articleid,stockdate from  (     select t.articleid, t.stockdate, row_number() over (partition by t.articleid order by v.articleid desc, stockdate) rn     from yourtable t     left join      (         select articleid, max(stockdate) as msd from yourtable t1         cross apply (select sum(stock) as stockrt from yourtable where stockdate<=t1.stockdate and articleid=t1.articleid) rt         where stockrt = 0         group by articleid     ) v     on t.articleid = v.articleid     and t.stockdate>v.msd ) v where rn=1 	0
12723985	32535	how to select from several tables with additional conditions?	select c.code,     case when s.code is null then 'not in stock'          else cast(sum(case when s.dc = c.location then s.qty else 0 end) as varchar(20)) end,     case when s.code is null then 'not in stock'          else cast(sum(case when s.dc <> c.location then s.qty else 0 end) as varchar(20)) end from table_codes c left outer join table_stock s on c.code = s.code group by c.code, s.code 	0.0065578523649588
12726148	15332	split numeric from character data	select      substring(data, 1, patindex('%[0-9]%',data)-1) as ename,     substring(data, patindex('%[0-9]%',data), len(data)) as sal  from       table 	0.00424860970057054
12726549	31023	select one value from a group based on order from other columns	select g,a,b,v     from (   select *,@rn:=if(g=@g,@rn+1,1)rn,@g:=g     from (select @g:=null,@rn:=0)x,tab order by g,a desc,b desc,v  ) x    where rn=1; 	0
12727932	27871	applying calculations based on a number of criteria stored in separate tables?	select ... product.productprice as price, customerrules.productpricerules as rules from product left join customer on ... left join customerrules on product.productid = customerrules.productid and customer.customerid = customerrules.customerid 	0
12727942	40374	can i group by an unknown number of columns?	select b.thread_group,  case when d.sequence=1  then d.dye_code end as code1, case when d.sequence=1  then d.dye_conc end as conc1, case when d.sequence=2  then d.dye_code end as code2, case when d.sequence=2  then d.dye_conc end as conc2, case when d.sequence=3  then d.dye_code end as code3, case when d.sequence=3  then d.dye_conc end as conc3, <lots of boring copy&paste...> case when d.sequence=20 then d.dye_code end as code20, case when d.sequence=20 then d.dye_conc end as conc20 from #t_batch t, #t_batch_dye d where t.batch_id  = d.batch_id 	0.00840504792122321
12730262	33422	t-sql calculate threshold from a recordset	select t1.contentsendid, t1.contentid, t1.newsletterid, t1.position, t1.isconditionmatch, t1.senddate, t1.numberofsends, t1.issendvalid  into #t from yourtable t1     inner join yourtable t2 on t1.contentsendid>=t2.contentsendid group by t1.contentsendid, t1.contentid, t1.newsletterid, t1.position, t1.isconditionmatch, t1.senddate, t1.numberofsends, t1.issendvalid  having sum(t2.numberofsends) < @threshold 	0.00157528598416591
12730275	37380	teradata: aggregate across multiple tables	select article_id,        (sum(sales_value) - sum(promo_value)) /        (sum(sales_qty) - sum(promo_qty)) from (     select           article_id,          sum(euro_value) as sales_value,          sum(qty) as sales_qty,          0 as promo_value,          0 as promo_qty     from sales_table sales     where year >= 2011     group by article_id     union all     select           article_id,          0 as sales_value,          0 as sales_qty,          sum(euro_value) as promo_value,          sum(qty) as promo_qty     from sales_table sales     where year >= 2011     group by article_id ) as comb group by article_id; 	0.240819299126496
12730756	18277	select rows in a table which aren't in another one with a nullable foreign key	select    defect.defectid,    defect.description from    defect where    qapid = ? and    defectid not in       (select         defectid       from         ereportdefect       where ereportid = ? and defectid is not null); 	0
12731093	27736	concatenating data in sql	select a.key1,   a.value1,   stuff((select distinct ', ' + value2          from b          where a.key1 = b.fk           for xml path('')),1,1,'')  from a 	0.0949472009869095
12732795	5896	sql query to indicate presence of a corresponding row	select a.*,        (case when 0 = (select count(*) from b where b.aid = a.aid)              then 'n'              else 'y'         end) as hasrowinb from a 	0.00133970871579299
12733644	28331	ms sql query to calculate average monthly unique visitors	select  avg(hitcount) as averagehits,     avg(uniquehitcount) as averageuniquehits from ( select  count(ipaddress) as hitcount,         count(distinct ipaddress) as uniquehitcount,         datediff(d, getdate(), datetime) as day from tblhitcounter where datetime > getdate() - 30 group by datediff(d, getdate(), datetime) ) sub 	0.000208650283561516
12733855	8525	how to select field with particular value or null from joined table	select a.x,b.y from a left outer join b on a.id= b.a_id and ( b.y ='abc' or b.y is null ) 	0
12735026	16360	sql group by last status change	select distinct     l1.id,  l1.number, l1.status, l1.timestamp  from      my_logs l1   left outer joing     my_logs l2         on l1.number = l2.number and l2.status <> 'buffered' where      l1.status = 'buffered' and     l2.number is null 	0.00128336273158188
12736017	13373	sql server - how to execute the second half of 'or' clause only when first one fails	select      * from      tbl where      value='company/about' or (     not exists (select * from tbl where value='company/about')     and     value=substring('company/about',0,charindex('/','company/about')) ) 	0.000559461271939301
12736376	22916	comparing an id to id of different tables rows mysql	select  *, group_concat(interest_id) interests from    people a         inner join people_interests b             on b.person_id = a.id         inner join         (             select distinct person_id             from volleyballplayers         ) c on b.person_id = c.person_id group by a.id order by lastname, firstname 	0
12736829	32824	oracle outer join on 3 tables	select *  from a     left outer join b on a.id = b.id    left outer join c on c.id = b.id 	0.707072002770073
12738481	31014	should i have less tables and use complex queries to fetch data or have more tables to simplify queries?	select distinct city_id from traffic_stats 	0.700957131399582
12740714	36129	select from nth record and so on in mysql	select * from tbl limit 95,18446744073709551615; 	0.000517990775842306
12742799	4436	change row to columns	select [test new],[abc],definitionid from ( select     dbo.[values].value, dbo.definition.fieldname, dbo.definition.definitionid  from         dbo.records as r inner join                        dbo.[values] on r.recordid = dbo.[values].recordid inner join                        dbo.definition on dbo.[values].definitionid = dbo.definition.definitionid  ) src pivot (max(value) for fieldname in ([test new],[abc])) p 	0.00240908278228643
12743916	40190	populate sql database column with repeating sequential values	select record,(select count(0)                  from table1 t1                  where t1.record <= t2.record       )%3+1 as 'id' from table1 t2  order by record; 	0.00753365868863202
12744373	209	r - how to assign 0 instead of "no rows selected" (dataframe 0 rows 0 columns)	select coalesce(count(id) > 0,'1','0') as column_name from payments where user_id=25578 	0
12744846	17812	sql convert string value	select cast(case when charindex('/', val) > 0 then substring(val, 0, charindex('/', val))                   else val end as float) /        cast(case when charindex('/', val) > 0 then substring(val, charindex('/', val) + 1, charindex('/', reverse(val)))                  else 1 end as float) from dbo.test12 where charindex(' ', val) = 0 union all select cast(substring(val, 0, charindex(' ', val)) as float) +        cast(substring(val, charindex(' ', val), charindex('/', val) - charindex(' ', val)) as float) /        cast(substring(val, charindex('/', val) + 1, charindex('/', reverse(val))) as float) from dbo.test12 where charindex(' ', val) > 0 	0.0338706249109285
12745414	24989	sql how to retrieve the middle point between two given dates?	select dateadd(ms,            datediff(ms,'2012-10-04 12:48:56:000', '2012-10-04 12:48:58:000')/2,          '2012-10-04 12:48:56:000') 	0
12745458	31831	using a groupby clause to sum	select date_format(utcdt,get_format(date,'iso')) as utcdt,              hour(utcdt) as hour,              country,             sum(impressions) as impressions              from rtb_impressions where campaign_id='cid2204184260'             group by date_format(utcdt,get_format(date,'iso')), hour, country 	0.713461421305586
12745660	38351	removing union from mysql query to get 2 row output in a single row	select calldate       ,sum( case when (hour0 != 42 and hour0 != 52) then 1 else 0 end ) as failedcalls       ,sum( case when (hour0  = 42  or hour0  = 52) then 1 else 0 end ) as successcalls   from call_status   where calldate='2012-09-14' 	0
12746380	3432	sql server : select distinct max(date) group	select a.*, b.cnt from( select max(date) as date, oid, head from offs group by oid, head )a inner join offs b on a.date=b.date and a.oid=b.oid and a.head=b.head 	0.283605689370666
12746870	29185	select distinct set common to subset from join table	select booth_id from table1 where [user_id] in (1,2,3) group by booth_id having count(booth_id) =  (select count(distinct([user_id])) from table1 where [user_id] in (1,2,3)) 	0.000146961051023113
12747474	13821	compare a table to itself	select staffno      , locono   from tbl a  where not exists       (select 1          from tbl b         where a.staffno <> b.staffno           and a.locono = b.locono) 	0.0061222041800054
12747855	17386	sql - returning all rows even if count is zero for item	select tree.type as 'requirement type',        count(case when [tree].[creationdate] >= ('2010-01-01') and [tree].[creationdate] < ('2020-01-01') then tree.type end) as 'number in creation range' from [tree]  inner join @reqtype as rt on rt.type = tree.type inner join [project_info]  on [project_info].[projectid]=[tree].[project_id]  inner join @creationcount as ccount on ccount.baselineid=tree.baseline_id  where [project_info].[name] = 'address book' and ccount.name = 'current baseline'  group by tree.type 	0.000169923700972337
12748384	9470	impossible mysql query	select u.id, u.name, n.network_id, n.perm   from users as u    left join nets_permissions as n     on u.id = n.user_id and n.perm = 3 and n.network_id=1234   where n.network_id is null 	0.764949419984029
12749219	25252	mysql: compare 2 strings which are numbers?	select * from your_table where cast(your_column as signed) = 100012345 	0.000171556598369237
12749306	40376	mysql select multiple values error	select * from `sheet1` where `state` in  ('alaska',  'arizona') 	0.383481869538156
12749432	15432	mysql: select number of users with specific number of contest entries	select num_contests_entered,        count(1) num_users   from ( select count(ce.contest_id) num_contests_entered            from user u            left           outer            join contest_entry ce              on ce.user_id = u.user_id           group              by u.user_id        ) t  group     by num_contests_entered  order     by num_contests_entered ; 	0
12749906	28295	oracle select multiple rows filter by uniqeness of one row	select tablea.value, tableb.value, tablec.value, tabled.value   from tablea  join tableb on ###### join tablec on ##### join tabled on ##### where 1 = (select count(*) from tablea tablea2 where tablea2.value = tablea.value) 	0.000117894892675467
12750446	24348	sql selecting where all distinct values exist in another column	select company from your_table group by company having count(distinct year) = (select count(distinct year) from your_table) 	0
12751126	9146	join two select queries together	select [datapointid], [assetid], [datapointid], [sourcetag],        '-' + [timestep] + [timestepvalue] as timestep,        [dataretrievalinterval] + [dataretrievalintervalvalue] as [retinterval],        d.datepointdate, d.datapointvalue,        0 as dataflagid,        dateadd(-1, d @searchdateend) + @searchtimeend datedatagrabbed,        getdate() datetimeaddedtodb from [dbo].[tbltss_assets_datapoints] cross join      (select datapointdate, sum(datapointvalue) as datapointvalue from @temp       group by datapointdate      ) d where assetid = 204 	0.141510624223304
12752350	9712	mysql displaying incorrect data	select *  from products  where category in (3073, 3074, 3100, 3102, 3106, 3109, 3111, 3115, 3130, 3134, 3144, 3146, 3152, 3157, 3162, 3163, 3164, 3166, 3167, 3168, 3170, 3171, 3177, 3181, 3182, 3184, 3190, 3191, 3192, 3213, 3224, 3227, 3228, 3235, 3238, 3239, 3240, 3244, 3245, 3246)  and active = 1  and price_notax > 0  and deleted = 0  order by position asc limit 0, 24; 	0.540587670099603
12753408	12448	sql union? or other method	select * from usa.dbo.viewusa union all select * from main.dbo.viewmain vm where vm.idcust not in (select idcust from usa.dbo.viewusa) 	0.603404564758599
12753937	801	selecting a post and all of its tags from two table with a single query	select * from post p  inner join table tag on tag.tag_id = p.tag_id where p.post_id=? 	0
12754587	22125	query count with three joining table	select regions.region, projecttypes.projecttype,        (select count(*) from projects         where projects.typeid = projecttypes.id           and projects.regionid = regions.id) as totalcount from regions, projecttypes 	0.063218921357075
12756320	21713	sql server 2005 money format	select cast(round(1234.1234, 2) as money) 	0.530711666231817
12759138	23309	select id which are there in t1 but not in t2	select id   from t1  where not exists (select null                      from t2                     where t2.t1id = t1.id) 	0.00663465793290891
12759427	9357	where clause in sql query remove also null values	select u.id, u.name, n.perm from users as u left outer join  (select * from nets_permissions where network_id=1234) as n on u.id = n.user_id  where (n.perm <> 3 or n.perm is null) 	0.0987396825750926
12759573	13699	ranking / popularity system	select ifnull(purchases,0) * .4 + ifnull(product_age,0) * .1 + ifnull(save_count,0) * .3 + ifnull(view_count,0) * .2 as weighting from my_table 	0.66521935445543
12760536	27642	mysql: select on many-to-many relation table with set of conditions	select fcomp from relcomplabel where flabel in (1, 2, 3) group by fcomp having count(flabel) >= 3 	0.0183180180722513
12760914	39757	designing an sql query	select  p.purchase_id,         p.purchase_time,         p.user_id,         i.image_name,         i.image_caption,         c.coupon_id from    purchase p         left join image i             on p.image_id = i.image_id         left join coupon c             on c.image_id = p.image_id and                 c.user_id = p.user_id where p.user_id in ($friends_id_string) order by p.purchase_time desc 	0.772347904840687
12763639	37064	php mysql calculate how many rows have the same data	select count(`project_id`) as `duplicates` from `table` group by `project_id` having `duplicates` > 1 	0
12765630	8771	rewards the products qualify for	select r.reward_id from (   select reward_id, product, count(*) needed   from reward_requirements   group by reward_id, product ) r left join (   select product, count(*) bought   from products_purchased   group by product  ) p on r.product=p.product and p.bought >= r.needed group by r.reward_id having count(reward_id) = count(distinct p.product) order by r.reward_id 	0.123082890109289
12766772	30401	finding the maximum value of primary key field after extracting certain characters in mysql	select max(cast(substring_index(id,'_',-1) as signed)) from foo; 	0
12767502	9679	sql - max of a column corresponding to two columns	select a.server, a.directory, a.`usage`, a.datetime     from usagestats as a inner join (         select server, directory, max(datetime) datetime             from usagestats             group by server, directory         ) as b on (             a.server = b.server             and a.directory = b.directory             and a.datetime = b.datetime         )     order by a.server, a.directory, a.datetime 	0
12767768	32890	counting mysql group by	select t1.uid, t1.type, t2.count  from table t1, (   select r_hash, count(*) as count     from table    group by r_hash ) t2  where t1.hash = t2.r_hash 	0.128003279649998
12771311	4780	substring mysql query	select substr(r.regnumber, 4) from registration as r 	0.596249082115626
12775697	8501	how to extract ids of the rows with minimum value in sql	select t.recordid,        t.[group],        t.date,        t.value from    (     select recordid,            [group],            date,            value,            rank() over(partition by [group], date order by value) as rn     from yourtable   ) as t where t.rn = 1 order by t.recordid 	0
12778329	15464	mysql data extraction from 3 tables - joins and max	select * from video join (   select   videotags.tag_id, max(points) points   from     video join videotags on video.id = videotags.video_id   group by videotags.tag_id ) t using (points) join tags on t.tag_id = tags.id 	0.00652492446797593
12782186	26688	mysql column sorting of string data	select my_col  from tbl_user  order by ltrim(replace(my_col,'"', '')) asc 	0.00867066058557036
12782277	18748	eliminate sub queries from this query	select      page.page_name,     page.page_id,     isnull(read,0) as read     isnull(write,0) as write,     isnull(delete,0) as delete,     isnull(export,0) as export from      page     left join permission on page.page_id = permission.page_id and permission.user_id = @user_id 	0.793074687155201
12782627	25309	short sql query to merge rows	select sum(column1) column1, sum(column2) column2, column3 from table1 group by column3 	0.0909644829603413
12782676	23894	how to order by column if equal, order by another	select     * from     mytable order by      col1,     col2 desc 	0.0024018431560824
12783810	5068	t sql- use results of one query as a variable for other query	select distinct top 2 ref, credit, paymentid       from  payment      inner join     (select ref, paymentid  from payment where paymentdate = '2012-09-23' ) query2         on payment.ref = query2.ref and payment.paymentid <= query2.paymentid       order by paymentid desc 	0.0307400151662039
12784043	40626	select subset of records from very large sql table	select distinct l.persona, l.personb  from longtable l   inner join shorttable s on l.persona  = s.persona 	0.000925716541002572
12786035	36716	mysql reservation system with multiple conditions	select a.*  from slots as a left join appointments as b on a.startdate between b.apptdate and date_add(b.apptdate,interval b.appttime minute) and b.physician=1234  where b.appointment is null 	0.797176341305663
12786598	7141	mysql return inverse? results of a search or results not containing	select tickets.id      from        tickets      where        tickets.id not in (select ticket_id from labels_tickets where labels_tickets.label = 'out of hours' or labels_tickets.label = null)      group by        tickets.id 	0.217503685451561
12786739	28336	mysql query from different tables same id	select sum(voting_result1) as "total" from #__ratings table  where id = 1 or  id in (select idi from #__content table where idi = 1) 	5.6218671511035e-05
12787422	9502	sql retrieve results	select * from order  where  ( to_char(order_time,'yyyymmdd hh24:mi:ss')>to_char(sysdate,yyyymmdd) || ' '|| '17:00:00'  or order_time is null )  and ( to_char(cancel_time,'yyyymmdd hh24:mi:ss')>to_char(sysdate,yyyymmdd) || ' '|| '17:00:00'  or cancel_time is null ) 	0.0286576020610322
12787897	14488	how to specify a time based range based on last inserted pk match in mysql?	select *    from [yourtable] t1   join [yourtable] t2   using (userid)  where t1.userid = [userid]     and t1.time is between t2.time and date_sub(t2.time, interval 1 month); 	0
12789349	35294	sql - derived field in where clause	select * from (...) where ... 	0.667298384032259
12794552	37151	mysql select based on aggregate of multiple columns	select (fname_approved * lname_approved) as all_approved from my_table; 	0.000442141490145041
12794935	1515	query for show latitude longitude polygon in mysql	select astext(your shape) from your table; 	0.425084027796146
12794991	35274	select rows with in particular range sql query	select distinct name as `students name`  from students where age_start between 15 and 27 	0.00178648199694418
12798485	26087	joining three mysql tables/two select statements	select    civicrm_contact.last_name,    civicrm_contact.first_name,    civicrm_uf_match.uf_id,   (select group_concat(jos_content_statistics.date_event)     from jos_content_statistics     where user_id = civicrm_uf_match.uf_id       and civicrm_uf_match.contact_id = civicrm_contact.id       and component = "com_users"     group by user_id) as date_events from civicrm_contact join civicrm_uf_match on civicrm_contact.id = civicrm_uf_match.contact_id where civicrm_contact.contact_sub_type='student' 	0.439419215491727
12799197	6115	find efficient way of joining tables	select title.*, film.*,songs.*   from title t join film f     on t.title_name = f.title_name  join songs s     on t.title_name = s.title_name 	0.0119159946198012
12799207	20405	oracle to_number(1234.567)?	select to_number('1234.5678', '9999d9999', 'nls_numeric_characters=.,') from dual; 	0.761542701354177
12801216	7720	creating a related post script in php - not wordpress	select * from post where category = '$current_blog_post_category'        and post.id <> '$current_blog_post_id' order by post_date desc limit 4 	0.198550326381767
12801458	10371	find list of users based on recorded entries	select p.id, p.name, max(ph.name) as phase from patient p     left join status s  on p.id=s.patient_id     left join phase ph  on ph.id=s.phase_id     left join message m on p.id=m.patient_id where (ph.name='c' or ph.name='d')     and (m.type != 'meeting_planned' or m.type is null)     and p.id not in (         select p.id         from              patient p             inner join             status s on p.id = s.patient_id             inner join             phase ph on ph.id = s.phase_id         where ph.name > 'd'         ) s group by p.id, p.name 	0
12801823	2631	mysql nested query with max value	select count(*) from questionnaires q inner join visits v1 on q.visit_id = v1.id inner join (     select max(visit_number) maxvisitnumber, member_id     from visits     group by member_id ) v2 on v1.member_id = v2.member_id and v1.visit_number = v2.maxvisitnumber inner join members m on v2.member_id = m.id where m.id = @someid 	0.389982027679941
12803040	10189	sql get username twice in one query	select folder.*, userfolder.username, comment.*, usercomment.username   from folders folder inner join   user userfolder on folder.fkuser = userfolder.id inner join   comments comment on comment.fkfolder = folder.id inner join   user usercomment on comment.fkuser = usercomment.id 	0.0123068597592604
12803211	17953	search column name in linked server	select t.name as tablename, c.name as columnname from servernamehere.databasenamehere.sys.columns c  inner join servernamehere.databasenamehere.sys.tables t on c.object_id = t.object_id where c.name like '%yoursearchhere%' 	0.0984647479282479
12805342	27959	how to select records from table1 which doesnt have records in table 2 between certain dates	select crm_customers.id, crm_customers.companyname from crm_customers  left join crm_activities    on crm_customers.id = crm_activities.customerid  and datediff(dd, crm_activities.createddate, getdate()) < 30 where crm_activities.customerid is null 	0
12806425	24798	reading the number of rows inserted from another ongoing transaction	select count(*) from table2 with (nolock); 	0
12806518	40537	sql - selecting the most occurring value	select p.nid, p.name, count(*) from players p inner join games g on g.pid= p.nid group by p.nid, p.name order by count(*) desc limit 1; 	0.000271555489894777
12807021	5557	sql sort with default value always on top	select ... from ... order by case mycol when 'n/a' then 0 else 1 end, mycol 	0.00576129622742359
12807347	41199	t-sql use exists as column	select column1,        column2,        case when exists (select 1 from table2 t2         where t2.column = t1.column) then 1 else 0 end as isflag from table1 	0.471020744359544
12807881	7916	compare values from 2 tables based on dates from one of the 2 tables?	select p.profilename, p.aggregationdate, p.totalsalesamount as profileamount, a.datavalue as aggregationamount, case when p.salesamount <> a.datavalue then 1 else 0 end as equal from aggregation a  inner join profilereconcilation p on convert(date,p.aggregationdate) = a.datadate 	0
12808584	4687	select max one value per day (stored in unix timestamp)	select    users_id,    max(value)  from table where from_unixtime(created) between  (curdate() - interval 30 day) and curdate() group by users_id, month(from_unixtime(created)), day(from_unixtime(created)) 	0
12810624	7661	sql server union on geography columns	select r.geography, f.geography from regions r join facilities f on r.geography.stintersects(f.geography)=1 	0.200721269744266
12811283	37200	mysql time zone	select convert_tz(now(),'-07:00', city.timezone) as time, city.name     from city, country      where country.name='usa' and city.countryid= country.countryid; 	0.0713007386023118
12811875	1942	mysql count in select statement	select class,       sum(case when gender = 'm' then 1 else 0 end) `m`,       sum(case when gender = 'f' then 1 else 0 end) `f`,       count(1) total from table1 group by class 	0.360508575216082
12813069	2930	how to get the unique set of count for rows with different values for a certain hour	select hour, sum(count) from stats group by hour 	0
12813561	15932	sql to select unique list of user, along with other data depending upon timestamp	select t2.quotes_user, t2.email_address, t2.sent_at as '________sent_at________' from (    select quotes_user, max(sent_at) as maxdate    from table     group by quotes_user ) t1 inner join table t2 on  t1.quotes_user = t2.quotes_user                      and t1.sent_at = t2.maxdate 	0
12814575	3414	combine year, month, day, hour, minute and second fields to a one column at "timestamp" in sql	select year || '-' || month  || '-' || day  || ' ' || hour  || ':' || minute  || ':' || second from table_name 	0
12814937	23378	print data of two table	select t1.myname,t2.value as phone,t3.value as location from tab1 t1  inner join tab2 t2 on t1.id=t2.id and t2.type='phone'  inner join tab2 t3 on t1.id=t3.id and t3.type='location' 	0.00052686937587452
12817010	18267	getting content and count from sql at same time	select count(billeder.album_id) as albumsize,         albums.album_name,         albums.album_id    from albums   left outer join billeder                on billeder.album_home = albums.album_id   group by albums.album_id, albums.album_name 	8.50275413534206e-05
12817935	16651	order query results by specific where condition (complex)	select top (10) *  from   [dbo].[products_products]  where  [partnumber] like '%' + @searchphrase + '%'          or [manpartnumber] like '%' + @searchphrase + '%'          or formatsitenameforsearch([sitename]) like '%' + @searchphrase + '%'  order  by case              when [partnumber] = @searchphrase                    or [manpartnumber] = @searchphrase then 1              when formatsitenameforsearch([sitename]) like                   '%' + @searchphrase + '%' then 2              when [partnumber] like '%' + @searchphrase + '%'                    or [manpartnumber] like '%' + @searchphrase + '%' then 3              else 100            end 	0.763844901656995
12818346	40366	select query according to date	select * from tbl_events where startdate <= @end and @start <= enddate 	0.0118212046900172
12820627	40821	sql server pivot average	select * from (     select itemname as itm, [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]      from     (         select itemname, month(effectivedate) as mon, val             from items     ) as sourcetable     pivot     (         sum(val)         for mon in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])     ) as pivottable ) a cross apply (select sum(val) as sumval, avg(val) as avgval from items i where i.itemname = a.itm) b 	0.153917225101051
12821119	2677	how implement one-to-many objects database in sqlite for android	select u.user_id, u.name, p.time, p.message from users u inner join posts p on u.user_id = p.user_id 	0.795092979854616
12824129	5187	sorting mysql results based on client side input	select * from table where expirationdate between date1 and date2 	0.026229696704258
12827209	35538	sql evaluate two columns and create two rows (potentially)	select 'flu' as vaccineadministered from table  where fluspecifics != '' union select 'pheumonia' as vaccineadministered from table where pneumoniaspecifics != '' 	0.000176889652922512
12827394	28222	mysql query search with 3 tables	select v.vmaker, max(b.price) price from vehicle v left join buyvehicle b     on v.vin = b.bvvin group by v.vmaker 	0.298679688694134
12827602	5167	is several joined subqueries the ony way to test multiple tables?	select count(*) from ( (select max(process_month) from table1)   union (select max(process_month) from table2)   union (select max(process_month) from table3) ); 	0.107867118743655
12828033	34983	how to order database records based on these criteria?	select winner_team, count(id) as wins from your_table group by winner_team order by wins desc limit 20 	0.000117529450107149
12828174	4547	mysql multiple table query search	select c.maker,sum(b.price) from (     select ssn     from customer as a     join buyvehicle as b     on b.bvssn = a.ssn     group by ssn     having count(bvssn) >= 3 ) as a join buyvehicle as b on b.bvssn=a.bvssn join vehicle as c on c.vin=b.bvvin group by c.maker 	0.20272851024104
12828357	41262	is it possible to find out which field matched in table mysql?	select blob,         bid,         id,        case            when blob like :blob1 then 0            when blob like :blob2 then 1           else -1         end as matching_blob from  statuses where id <> :id  and (blob like :blob1 or blob like :blob2) 	0.00139481715564309
12828368	13239	get the average with quantity	select coalesce(sum(quantity * unit_price) /sum(quantity), 0) from (select     sum(case when action='unit_price' then data else 0 end) as unit_price,    sum(case when action='quantity' then data else 0 end) as quantity   from test group by user) as a 	0.000442213021394532
12829291	38931	how do i display the sum of a sql query in html?	select sum(subtotal) as todaysales from dbo.salesord_hdr where orderdate >= 41187 	0.00106981902815289
12829616	25360	mysql query - how to construct total for only ids that have a particular value in another table?	select sum(t1.total_time) from table1 as t1  inner join table2 as t2 on t1.vehicle_id = t2.vehicle_id and t2.feature_id = 2 	0
12829788	34363	what is a mysql formula that produces a truncated julian day?	select (to_days(date_column) - to_days('1968-05-24')) 	0.569863998009592
12830560	13868	oracle sql - creating multiple ranges for date possibilities in a query	select player_id,        count(distinct trunc(create_dtime, 'mm')) num_months   from player_chkin_cs  where trunc(create_dtime,'mm') in (date '2010-12-01', date '2010-01-01')  group by player_id having count(distinct trunc(create_dtime, 'mm')) = 2 	0.0821850614826745
12831745	1326	filter orders by product	select orders.id, orders.order_price, orders.purchase_date, customers.email,     product_orders.qty, products.name from orders, customers, product_orders,     products where     orders.customer_id = customers.id and     product_orders.order_id = orders.id and     products.id = product_orders.product_id and     products.id = 1 	0.0117626485627542
12832904	2894	sql query 4 way join to find who's not there	select  c.friends_id from    articles a         inner join users b             on a.user_id_creator = b.user_id         inner join friends c             on b.user_id = c.user_id         left join article_shares d             a.article_id = d.article_id where   b.user_id = 63 and         a.article_id = 34 and         d.article_id is null 	0.422100538304444
12832999	40724	next closest date and time in mysql	select date(auction_startdate) closestdate     from    auctions     where   date(auction_startdate) > '2012-10-27'     order by auction_startdate asc     limit 1 	0.000826781045497647
12833191	14833	get count of several times slots on between given two mysql time slots	select count(*) from table name where `in time` <= '2012-02-02 10:00' and `out time` >= '2012-02-02 11:00' 	0
12835177	27944	oracle: merge two rows	select  round(sysdate,'mi'),col1, sum( case when col2> 0 then col2 else 0 end ) col2, sum( case when col2 < 0 then col2 else 0 end ) col3 from table group by round(sysdate,'mi'),col1 	0.00271387629587356
12835768	34227	rounding time to the nearest 15 minutes in php/mysql	select   sec_to_time((time_to_sec(time_field) div 900) * 900) as round_time from table 	0.00115128260780651
12838442	39601	value in one field as lookup from same table	select c.id,  left(c.title, instrrev(c.title, "/")-1)  as parentvalue , p.id as parentid from nodeids c left join nodeids p on left(c.title, instrrev(c.title, "/")-1) = p.title 	0
12840011	29846	how to get the rows that is in the same week?	select      trunc(date_column,'d') as start_date,      trunc(date_column,'d')+6 end_date,      count(*) from your_table group by trunc(date_column,'d') 	0
12840352	13790	using a count from one table in another table	select   t2.monyear,   t2.total,   t1.tcount,   t2.reh_bal from (   select varmonth, monyear, count(*) tcount   from #test8   where account_number1 is null    group by varmonth,monyear ) t1 inner join (   select monyear,      count(*) as total,     sum(current_balance_amount) reh_bal,   from #table1   where rownumber = 1    group by varmonth,monyear ) t2 on t1.monyear = t2.monyear order by t1.varmontth, t2.monyear 	0
12842519	3817	how do i get all articles in video (ordered by id) and all subsections of it?	select a.name from art as a where a.sid in (select distinct(s2.id) from sec as s left join section as s2 on s2.id = s.id or s2.sid=s.id where s.id=1) order by a.id; 	0
12844144	18677	sql query - how to construct multiple sums (based on different parameters) in one query	select  sum(lt.total_time) as total_all,         sum(case when (vft.feature_id is not null) then log_table.total_time else 0 end) as feature_total from    vehicle_table vt         join log_table lt         on vt.vehicle_id = lt.vehicle_id         left join vehicle_features_table vft         on vt.vehicle_id = vft.vehicle_id and vft.feature_id = 2 where   vt.class_id = 1 	0.0013484092577123
12844637	28878	slick way to count null and non-null rows?	select country, profession,         count(postalcode) as num_have       , (count(*) - count(postalcode)) as num_not_have from citizens group by country, profession; 	0.0103430348625281
12845328	33553	db2 - ways to get multiple positions for character in a string	select customers.customernum, reasons.id from customers, reasons where substr(customers.reasons, reasons.id, 1) = 'x' 	0.0163245059827591
12846235	397	mysql query check user assessment	select user_id     from user_assessment     where video_id in (1, 2, 3)     group by user_id     having count(distinct video_id) = 3 	0.183397310924363
12846995	18926	selecting distinct values in a joined table	select t1.id, t1.date from (select a.id id, b.foo foo, a.date date       from a join b       on a.b_id = b.id) t1 join (     select b.foo foo, max(a.date) maxdate     from a join b     on a.b_id = b.id     group by b.foo) t2 on t1.foo = t2.foo and t1.date = t2.maxdate order by t1.date desc limit 10 	0.000205411756563482
12847549	35206	oracle/sql - find records that or null or may not exist or are null in another table	select *   from persons  where person_id not in         ( select p_id             from secondary_table            where cola is not null              and colb is not null         ) ; 	0.00246794587580304
12849122	18209	mysql where row = multiple values	select * from shop_id where    scheduled = '0'    && end_date >= curdate()    && shop_area in('757','804','540','252'); 	0.00921920222588546
12849456	7115	sql - inner join on two columns from table 1 with one column from table 2?	select m1.name , m2.name from members m1 inner join match m    on m1.user = m.user inner join members m2    on m2.user = m.match 	0
12849566	19202	joining 2 queries into one query, as subquery	select stu_name      , add_addr_line_1      , add_addr_line_2      , add_addr_line_3      , add_postcode      , nte_note      , enrolment.enr_startdate      , enrolment.enr_id      , student.stu_student_id      , studentaddress.add_id      , studentnote.nte_id   from student   join studentaddress     on student.stu_student_id = studentaddress.add_student_id   left join studentnote     on student.stu_student_id = studentnote.nte_student_id   join enrolment     on student.stu_student_id = enrolment.enr_student_id   left join enrolment as e2     on enrolment.enr_student_id = e2.enr_student_id    and (enrolment.enr_startdate, enrolment.enr_id) > (e2.enr_startdate, e2.enr_id)  where e2.enr_startdate is null ; 	0.0165396667520256
12849945	9397	how to do where ((select count(*) ...) = 0 or exists (select * from ...))?	select *   from person p  where not exists (         select *          from personevent         where eventid = '290')     or exists (         select *          from personevent pe         where pe.personid = p.id and pe.eventid = '290') 	0.149993638081807
12850488	33151	mysql. one column, two different data types, multiple where query	select *  from `table`  where tourop = 'aaaa' and (val = '5698-' or val = '49_01') or tourop = 'biew' 	0.000174508148843219
12852262	39585	sql query to descending order the datas in table	select   *  from     tablename  order by colname desc; 	0.0135136179426589
12852692	16980	mysql query to get the value	select      t1.processid,     t1.newid,     t1.value,     t2.processid,     t2.mapnewid from  t1 left join t2  on t1.processid = t2.processid and t1.newid =  t2.mapnewid where t1.processid = 1 and t2.processid is null 	0.00404768383310021
12852773	3285	sql join with count	select *, date_format(a.date, '%d/%m/%y') as article_date, count(*)   from articles a   left join article_shares ash on ash.article_id = a.article_id  where (a.user_id = '63') order by a.article_title asc 	0.589189557181662
12853006	28240	query to get tables created on a particular date	select table_name,create_time from information_schema.tables where table_schema='quadv2_dev' and date_format(create_time,'%y-%m-%d')='2012-09-17' 	0.000299474897335154
12853286	975	sql concatenating row values on primary key	select distinct a.groupid as itemid,( select isnull(b.label,'')+': '+isnull(b.value,'')+' '+isnull(b.unit,'')+';' from table b where b.groupid=a.groupid for xml path('')) as [value] from table a 	0.000259697702054887
12854180	36005	how to weekly aggregate data in sql and include skipped weeks too	select dateadd(wk, number, dateadd(wk, datediff(wk, 0, @startdate)-1, 6)) as [week commencing],  coalesce(sum(unresolved), 0) as unresolved, coalesce(sum(resolved), 0)as resolved, coalesce(sum(turkspend), 0) as turkspend from dbo.v_urlbatchstats  right join master..spt_values  on scheduledate between @startdate and @enddate and source=isnull(@source,source) where type = 'p' and dateadd(wk, number, dateadd(wk, datediff(wk, 0, @startdate)-1, 6)) <= @enddate group by dateadd(wk, number, dateadd(wk, datediff(wk, 0, @startdate)-1, 6)) order by dateadd(wk, number, dateadd(wk, datediff(wk, 0, @startdate)-1, 6)) 	0.158461805767853
12854910	22633	how to concatenate strings before group_concat	select   id,   group_concat(concat('id_', test_id)) from   your_table group by id 	0.022953345278161
12855006	37670	sub query on joined table	select * from documents d  where d.createdby = isnull(@userid, d.createdby)      or d.documentowner = isnull(@userid, d.documentowner)       or d.documentowner = ( select managerid from directreports where @userid = userid) 	0.105199003297634
12855053	4926	parent child relationships php and mysql	select son.name as name, father.name as parent_name from table_name as son left join table_name as father on son.parent_id = father.id 	0.00770761449652784
12855285	23019	select rows with join which have 2 conditions on second table	select distinct * from `goods` as `g` join `cats_goods` as `cg1` on (`g`.`id` = `cg1`.`good_id`) join `cats_goods` as `cg2` on (`g`.`id` = `cg2`.`good_id`) where (`cg1`.`cat_id` = 24 and `cg2`.`cat_id` = 4) 	0
12855496	21489	find matching column data between two rows in the same table	select t1.rowid as r1, t2.rowid as r2, t2.col as matchvalue from <yourtable> t1 join (   select rowid, col1 col from <yourtable> where rowid = 3 union all   select rowid, col2 from <yourtable> where rowid = 3 union all   select rowid, col3 from <yourtable> where rowid = 3 ) t2 on t2.col in (t1.col1, t1.col2, t1.col3) and t1.rowid < t2.rowid  and t1.rowid = 1 	0
12855505	9114	mysql inner join different results	select distinct i.id, i.date   from `tblinvoices` i left join `tblinvoiceitems`  it on it.userid=i.userid left join `tblcustomfieldsvalues`  cf on it.relid=cf.relid   where i.`tax` = 0   and i.`date`  between  '2012-07-01' and '2012-09-31' 	0.381933670938268
12855661	14894	calculate count of rows in mysql query	select count(distinct wp_posts.id) as cnt from wp_posts inner join wp_term_relationships on (wp_posts.id = wp_term_relationships.object_id) where ( wp_term_relationships.term_taxonomy_id in (4,3) ) and wp_posts.post_type = 'post' and (wp_posts.post_status = 'published') 	0.00190203919678593
12855747	3248	mysql replace result value with another value	select name, case when re_type = 1 then 'student' when re_type = 2 then 'teacher' else 'donno' end as re_type_text from mytable 	0.00183091477224008
12855761	33705	sql query to find difference between date	select datediff(select date_add(start_date,interval 1 day),end_date); 	0.00177334348346657
12855907	39181	sql: get data between the current date and current date +15 days	select *  from tname  where datediff(makedate(year(now()),dayofyear(birthday)),now()) between 0 and 15 	0
12856406	547	tsql running totals aggregate from sum of previous rows	select name , month , (select sum(balance) from mytable     where mytable.month < m.month and mytable.name = m.name) as starting_balance from mytable m group by name, month 	0.000642230374333449
12857175	19933	returning rows of marks in groups of 10s, 20s etc	select (floor(`marks`/ 10)+1)*10 as marks,        count(*) as candidates_count from <table> group by (floor(`marks`/ 10)+1)*10; 	0.00497386666944841
12858380	22846	mysql join 2 tables but rename columns because they have the same name	select p.id as pid,         p.date_created as pricing_date,         p.type, p.value as pricing_value,        a.id as aid,         a.date_created as admin_date,        a.relation,         a.value as admin_value from pricing p inner join admin a on p.relation = a.id 	0
12858655	32432	how to get date range between two columns?	select     ccm.`date_from`,     ccm.`date_to`,     ccd.`rate` from     `currency_conversion_master` ccm inner join `currency_conversion_details` ccd  on ccm.conv_m_id=ccd.conv_m_id where '2012-10-12' between date(date_from) and date(date_to) 	0
12858922	18043	order by alphanumeric in mysql	select   num from     sortnum order by   cast(num as unsigned)=0,        cast(num as unsigned),          left(num,1),                    cast(mid(num,2) as unsigned)  	0.273123305913067
12859493	16016	find current result's position in mysql	select count(*) from related_videos where videoid >= 13 	0.000594483441854875
12859602	4689	select columns with the same value	select customer_first_name, customer_last_name, customer_zip from customers where customer_zip in    (select customer_zip from customers    group by customer_zip    having count(*) > 1); 	0.000228028024582367
12859736	13991	fetch single row if two columns in table have same values either ways	select case          when caller < callee then callee          else caller        end      as caller1,        case          when caller < callee then caller          else callee        end      as caller2,        count(*) as [count] from   yourtable group  by case             when caller < callee then callee             else caller           end,           case             when caller < callee then caller             else callee           end 	0
12859895	36677	mathematical sum of multiple rows by value	select user_name, status, sum(calls) as calls from table where status in ('cars', 'bikes', 'skates') group by user_name, status 	0.000971388274427809
12860184	31636	finding row based on the number of occurrence of the where clause	select id from a_test group by id     having count(distinct type) = 1     or count(*) = 1 ; 	0
12861520	9713	non linear, three way sum of table data	select user_name, id, min(status), sum (calls) from yourtable where status in  ('badad', 'lead', 'dnc') group by user_name, id 	0.00324114130323878
12861836	6117	select statement using and	select email from answers  where answer='male' or answer='human' group by email  having count(distinct answer) = 2 	0.556398911369389
12862360	9705	mysql selecting from two tables but the second table not always have relationship to the first	select * from users where id not in (select user_id from settings where name="hide"); 	0
12862404	697	mysql show results if any of the combination match	select   *,          (location = 'abc')        + (price between 1000000 and 5000000)        + (bedrooms between 5 and 12)        + (state = 'xyz')        + (county = 'pqr')        + (category = 'mno')            as relevance from     my_table where    (location = 'abc')       or (price between 1000000 and 5000000)       or (bedrooms between 5 and 12)       or (state = 'xyz')       or (county = 'pqr')       or (category = 'mno') having   relevance >= ?    order by relevance desc limit    ?                 	0.000929625761423811
12862968	26080	group_concat() row count when grouping by a text field	select `text` from `table` group by `text`; set session max_sort_length = 2000; select group_concat(`id` separator ', ') as ids from `table` group by `text`; 	0.0220430285427801
12865096	11351	join two different tables?	select intcolumn, varcharcolumn, intcolumn from a union select intcolumn, varcharcolumn, 0 from b 	0.00812329476207397
12865449	31258	how do i join these two tables?	select m.id matchid,     h.name hostname,     g.name guestname from match m left join team h   on m.hostid = h.id left join team g   on m.guestid = g.id 	0.069455568922202
12866473	18516	mysql multiplying field result by the number of another field	select st.* , u.username creator, count(distinct se.sentenceid) as sentences,   coalesce((select sum(v.vote)             from votes v             where st.storyid = v.storyid), 0) score,    group_concat(se.text order by se.sentenceid separator  ' ') text from stories st join sentences se on st.storyid = se.storyid left outer join users u on st.creatorid = u.userid group by st.storyid limit 30 	0
12866655	12729	sql query not in return specific result	select distinct car.car_id, part.description from car join car_parts part on (car.car_id = part.car_id) where part.part_id <> '1' and car.car_id not in ( select car_id from part where part = 1 ) 	0.129766625910686
12868607	10457	determining page count on each sql table without using dbcc?	select  object_schema_name(s.object_id) schema_name,         object_name(s.object_id) table_name,         sum(s.used_page_count) used_pages,         sum(s.reserved_page_count) reserved_pages from    sys.dm_db_partition_stats s join    sys.tables t         on s.object_id = t.object_id group by s.object_id order by schema_name,         table_name; 	0.000205759850566161
12871329	27359	sql query to find out if different rows with same 2nd columns	select  mt1.threaduid ,       count(*) as threadcount ,       (         select  count(distinct mt3.useruid)          from    messagethread mt3          where   mt1.threaduid = mt1.threaduid         ) as usersinthread from    messagethread mt1 join    messagethread mt2 on      mt1.threaduid = mt2.threaduid where   mt1.useruid = 'k1'         and mt2.useruid = 'n1' group by         mt1.threaduid 	0
12873067	34262	mysql query date ranges	select roomid,        min(date) as from,        max(date) as till,        price from periods group by price order by price 	0.0205717552948009
12873249	29758	sql select entry with maximum value of column after grouping	select      `users_sessions`.`userid`, `users_sessions`.`lastactive` , `users`.`firstname` from      `users_sessions` , `users` where      `users_sessions`.`lastactive` >= date_sub( now( ) , interval 60 minute ) and      `users`.`uidnumber` = `users_sessions`.`userid` group by      `users_sessions`.`userid`, `users_sessions`.`lastactive` , `users`.`firstname` having     `lastactive` = max(`lastactive`) 	0
12874392	36962	sql subtotaling	select b.zip       , sum(case when answer='answer1' then 1 else 0 end)as answer1      , sum(case when answer='answer2' then 1 else 0 end)as answer2      , count(*) as total from a inner join b on a.[user] = b.[user] group by b.zip 	0.787331815485192
12874647	21654	cannot see mysql count from 3rd table	select i.*, o.organ_name, o.organ_logo, vtable.* from heroku_056eb661631f253.op_ideas i join     (select         count(v.agree) as agree,         count(v.disagree = 1 or null) as disagree,         count(v.obstain = 1 or null) as abstain     from op_idea_vote v     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 	0.0112047446984872
12877885	13292	inserting a new record in the middle of the table	select * from my_table order by cityname 	4.67746937682032e-05
12878249	35272	appending mysql results together in a php loop	select states.id, states.state, locations.* from   states left join locations using(state) where  states.region = 'given_region' 	0.33094053959789
12878251	7809	mysql join 2nd table with not unique foreign key	select learning_story.* from   learning_story left join story_groups using (story_id) where  learning_story.child_id = ? or story_groups.child_id = ? 	0.000525460662818727
12878998	13065	querying table for multiple combinations and default values	select price  from your_table  where ( city = '&p_city' or city = 'default')   and ( postage = '&p_postage' or postage = 'default')   order by case when city = '&p_city' then 1 else 2 end            , case when postage = '&p_postage'  then 1 else 2 end 	0.000484450459297617
12879003	13853	mysql attribute with multiple entries in one column?	select * from friends where user_a == 'foobar' || user_b == 'foobar' 	0
12879496	13278	how to pick randome number from the number list	select top 1 whateverid from yourtable order by newid(); 	0
12882170	35081	only get active products from table related to category	select c.cid, c.name, c.active from category as c where c.cid in (select distinct t.category_id from products as t where t.active = 1) 	0
12882404	18935	how can i join 3 tables?	select    t.username,    r.region_name,    i.instituation_name from tb_user t inner join tb_region r on t.region_id = r.region_id inner join tb_institutional_profile i on t.institution_id = i.institution_id 	0.154498605951087
12882812	40773	how to return all rows when given value lies between two columns	select * from `tbl` where 35 between `min_age` and `max_age`; 	0
12883562	28326	double select narrow results	select      c1.youtube_id id,      c1.views startcount,      c2.views endcount,      c2.views - c1.views increasing,      (c2.views - c1.views) * 100 / c1.views percentchange from      charts c1     inner join     charts c2 on c1.youtube_id = c2.youtube_id where      c1.datum = '2012-10-08' and c2.datum =  '2012-10-09' 	0.503724265654872
12884372	29763	mysql: why does this select query not find row when joined table has multiple results?	select `id` from (`cronjobs`) inner join `cronjob_seeds` on `cronjob_seeds`.`cronjob_id` = `cronjobs`.`id` where `cronjobs`.`callback_model` = 'movie_suggestion_model'     and `cronjobs`.`callback_method` = 'fetch_similar_movies'     and `cronjob_seeds`.`seed` in ('seed1', 'seed2') 	0.415752401892733
12885454	30887	how to structure a mysql subquery	select user_id, count(*) as num_apts ... 	0.444903762409622
12885602	1400	sql many to many select with join	select     p.name as "place",     t.name as "firsttag"  from     places p     left join    places_tags pt1        on pt1.place_id = p.id    left join    places_tags pt2        on pt2.place_id = p.id and pt2.tag_id < pt1.tag_id    left join     tags t        on t.id = pt1.tag_id where    pt2.tag_id is null 	0.419725986570905
12885702	3531	mysql substituting one columns value for another	select     u.surname,     u.name,     u.login,     uc.users_login,     c.name,     group_concat (c.name)   from users_to_courses uc join users u on uc.users_login = u.login  join courses c on uc.courses_id = c.id group by u.surname, u.name, u.login, uc.users_login 	0.000128730294066591
12885986	10530	string to datetime in sql server	select convert(varchar(10), cast(value as datetime), 101) + ' '       + substring(convert(varchar(20), cast(value as datetime), 9), 13, 5)       + ' ' + substring(convert(varchar(30), cast(value as datetime), 9), 25, 2) as datevalue from mytable  where isdate(mytable.value) = 1 	0.164013186197047
12886423	18305	how to get results from database tables?	select p.phone_id from phones p inner join phones_state ps on ps.phone_id = p.phone_id group by p.phone_id having sum(ps.state_id = 1) >= 1 and sum(ps.state_id = 5) = 0 	0.000505055770167197
12886890	37833	create start column and end column from a single datetime column	select   cur.date_time as start_time, min(nxt.date_time) as end_time from     my_table as cur join my_table as nxt on nxt.date_time > cur.date_time group by cur.date_time 	0
12887988	28266	select data by date and sum data - sql server 2005	select sum(datapoint) as sum, dateadd(d, 0, datediff(d, 0, mytimestamp)) as date from datalog where datapoint = '27' group by datediff(d, 0, mytimestamp) 	0.0223419126094685
12888097	31238	how do you select all rows in a database where a specific column has a value?	select name,isbn,date where date is not null 	0
12890487	19671	sql query to search between two weeks from different years	select *  from   mytable  where  ( finish_week >= @finish_week1           and finish_year = @finish_year - 1 )          or ( finish_week <= @finish_week2               and finish_year = @finish_year ) 	0
12891069	20445	select distinct parent_id	select  parent_id from btree group by parent_id order by parent_id asc 	0.056020580730976
12891071	39925	favourite course in student course table query	select top 1 with ties courseid  from   studentcourse  group  by courseid  order  by count(*) desc 	0.0311984394293847
12892688	35132	using union all and order by in mysql	select s.* from     (         select  ap.*, 'advertised'  as type          from advertised_products as ap           union all         select  wp.*, 'wanted' as type          from wanted_products as wp     ) s order by s.timestamp desc  limit 3 	0.112039741960466
12892778	12191	check if table exists, using a connection object in java	select     1 from     table ; 	0.188193060117275
12893101	2906	sql : how to find where there are no entries in joined table	select id  from company  where id not in(select company_id from jobs where active != 0) 	0
12893233	25840	mysql select from different tables with if clause	select     v.`id`,      m.`maschine-name` as maschine,      v.`vorrichtung`,      v.`createdby`,      v.`datecreated`,     creator.fullname as creator,     v.`updatedby`,     case when v.updatedby is null then '0' else updator.`fullname` end as updatetor,     v.`dateupdated` from     vorrichtungen v     inner join     user creator on creator.userid = v.createdby     left join     user updator on updator.userid = v.updatedby     inner join     maschinen m on m.maschine = v.maschine  order by datecreated 	0.0131376974678001
12893875	3195	only select friday and coming monday in mysql	select * from   main fri join main mon     on fri.dayofweek(date)=6    and mon.date = fri.date + interval 3 day    and fri.emp_no = mon.emp_no where  fri.status='leave' and mon.status='leave' 	0.00905902643749395
12895040	20958	join on the same table	select     * from     fruits where   (fruit = 'apple' or type = 'dried') and     exists     (select         null     from          fruits f1         inner join fruits f2 on f1.user_id = f2.user_id and f1.fruit = 'apple' and f2.type = 'dried'     where         fruits.user_id = f1.user_id) 	0.00587199232452384
12895425	23235	how to deal with union/order by differences between hsqldb and mysql?	select * from ( select ... union select ...)a order by a.created_on desc limit 20 offset 0 	0.0204208920641786
12895579	13816	detect if a column contains special characters in postgresql table	select * from table where column1 ~* '[^a-z0-9]' or column2  ~* '[^a-z0-9]' or column3  ~* '[^a-z0-9]' 	0.0200703718953091
12896226	9307	how to fetch two different column values from two different tables inturn one value table is dependent on other table value	select a,b,c,        (select count(*)  from table2 where b=a.b and js_email_id in  (   select js_email_id    from js_initialsignup    where ucase(jsaccountstatus) like ucase('live')      and ucase(js_status) likeucase('accepted') )) as cnt from table1 a 	0
12899078	38935	filter sql query result set based on arbitrary time	select cola,colb,...   from   (        select col1,col2,...      from tables        where ... )  results   where ... group by cola,colb 	0.00117719843228139
12899838	30050	sql query to find difference in two fields	select idurl, count ( distinct assignedid )   from @table  group by idurl having count( distinct assignedid ) > 1 	0.00141631754568712
12900439	9763	combine without aggregate?	select wo,         tf,         te,         cap,         label  from   (select distinct wadoco   as wo,                          walitm   as tf,                          max(case                                when ixlitm like 'te%' then part.ixlitm                                else ''                              end) as te,                          max(case                                when ixlitm like 'cf%' then part.ixlitm                                else ''                              end) as cap,                          max(case                                when ixlitm like 'lbl%' then part.ixlitm                                else ''                              end) as label          from   part          group  by walitm,                    wadoco)t2  where  wo = 800059 	0.297022855017903
12904017	39182	using join in sql to get data from another database in the same server using an id	select myusers.id,myusercharacters.character from tableuser.dbo.[user] myusers inner join tableusercharacter.dbo.usercharacter myusercharacters on myusers.id=myusercharacters.userid 	0
12904097	17461	sql query to return maximums over decades	select   lookup.decadeid,   data.* from (   select     truncate(yearid/10,0) as decadeid,     max(hr) as homers   from     masterplusbatting   group by     truncate(yearid/10,0) )   as lookup inner join   masterplusbatting as data     on  data.yearid >= lookup.decadeid * 10     and data.yearid <  lookup.decadeid * 10 + 10     and data.hr     =  lookup.homers 	0.789976454085212
12904397	29578	mysql_fetch_row returns array9 when i only want the value 9	select a.*, count(b.category_id) as catcount     from `product_category` a     left outer join `products_has_product_category` b     on a.product_category_id = b.category_id group by a.id, a.someothercolumn, a.etc 	0.0322301467829171
12904536	8710	how to search in table of multiple parameters in mysql?	select * from offers a inner join offers b on a.offerid = b.offerid inner join offers c on b.offerid = c.offerid inner join offers d on c.offerid = d.offerid where a.parameter_name = 'price' and b.parameter_name = 'width' and c.parameter_name = 'height' and d.parameter_name = 'place' and a.parameter_value between 80 and 120 and b.parameter_value = '150' and c.parameter_value = '200' and d.parameter_value in ('left','right') 	0.0394899541035431
12905699	29838	sql server - query to return groups with multiple distinct records	select * from tablename where col1 in (     select col1     from tablename     group by col1     having count(distinct col2) > 1 ) 	0.00419524400509409
12906362	12991	timezone in getdate query is 12 hours out	select cast(cast('20120301' as datetime) as int)  select cast(cast('20120301 12:30' as datetime) as int)  select datediff(d,0,'20120301')  select datediff(d,0,'20120301 12:30')  	0.0310141876080929
12910287	38892	merging tables with duplicate data	select a.id, b.id, isnull(a.fid,b.fid) fid, isnull(a.type,b.type) type from     (select *, row_number() over (partition by type order by id) rn from a ) a         full outer join     (select *, row_number() over (partition by type order by id) rn from b ) b         on a.rn=b.rn         and a.type = b.type order by a.id 	0.0021763110869497
12910787	24134	getting data using join from 2 table and order by latest(one to many relationship)	select c.caseid, r.responseid from case c inner join response r on c.caseid = r.responseid order by r.responseid 	0.00127702261214017
12911260	3749	sql union statement	select     ep_101.cd_hfdmapnr as dossiernummer,     sum(case when ep_102.cd_bkcode = '000010' then ep_102.id_fhmbdlv else 0 end) as kosten,     sum(case when ep_102.cd_bkcode = '000020' then ep_102.id_fhmbdlv else 0 end) as griffiekosten from ep_101     inner join et_101 on ep_101.cd_hfdmapnr = et_101.cd_hfdmapnr     inner join ep_102 on ep_101.cd_hfdmapnr = ep_102.cd_hfdmapnr where ep_101.cd_mapkverw = 0      and ep_102.cd_bkcode in ('000010', '000020')     and et_101.opdrachtgever1 = '05354605' group by ep_101.cd_hfdmapnr 	0.791554241380555
12912183	16357	count duplicate column values in one row	select if(col1=col1,1,0) + if(col2=col1,1,0) + if(col3=col1,1,0) as col1values  from table 	0
12912192	37467	create index without specifying the tablespace	select username,default_tablespace from dba_users 	0.74480472061706
12912279	37268	identifying start and end of period covered - oracle 10g sql	select  t3."id", t3.f "start", t3."to" "end", t3.types from ( select sys_connect_by_path(t2."type",',') types,        connect_by_root(t2."from") f,        t2."from",        t2."to",        connect_by_isleaf is_leaf , t2."id" from (   select t.*, lag(t."from") over (order by t."from") nfrom     from table1 t    where t."id" = 'a'   ) t2 start with t2."start_code" = 's' connect by   prior t2."from" = t2.nfrom  and t2."start_code" = 'p') t3 where is_leaf=1 	0.0112287632798416
12912461	30226	sql - how can i extract all information through one statement from 3 tables?	select * from store as s     left outer join store_items as si on si.storeid = s.storeid     left outer join items as i on i.itemid = si.itemid 	0
12912537	22090	sql: how to make multiple joins to the same column of a table without overriding results?	select     matches.id,     matches.score_home,     matches.score_away,     hometeam.name home_team_name,     awayteam.name away_team_name from     matches     inner join teams hometeam on matches.home_team_id = hometeam.id     inner join teams awayteam on matches.away_team_id = awayteam.id 	0.000711241821736903
12913633	8031	grouping the rows of a table in sql server	select id, name, ntile(4) over (order by name) from @names 	0.00145688819397363
12914269	13238	mysql case-when-then (or other ways) to check values of multiple rows	select sid from your_table group by sid where (cid=2 and data='john_email') or (cid=4 and data='ok') having sum(cid=2)=1 and sum(data='john_email')=1 and sum(cid=4)=1 and sum(data='ok')=1 	7.86795128245691e-05
12914604	15832	sql unique sequencial id for resultset based on accounting entities	select   *,   dense_rank() over (order by invoiceno) as sequence from   yourtable 	0.000229520805757913
12915059	16072	inner join and select	select * from tblproducts as p     outer apply     (         select top 1 t.image from tblproductsimage as t         where t.productid = p.id         order by t.id     ) as pi 	0.749588906044045
12917494	6363	sql select distinct puzzle	select dt.typeid,dt.typename,dt.typedescription,     case         when sum(convert(int,isnull(d.documentrequired,0)))=0 then 'false/no'         else 'true/yes'     end [any required documents] from documenttype dt left join document d on dt.documenttype=dt.typeid  group by dt.typeid,dt.typename,dt.typedescription 	0.469435357533628
12917540	22478	find conversation between one or more users	select cu.`conversation_id`  from `conversation_user` cu  inner join (     select `conversation_id`     from `conversation_user`      where `user_id` in (x, y)      group by `conversation_id` having count(*) = z  ) cu2 on cu.conversation_id=cu2.conversation_id group by `conversation_id`  having count(*) = z; 	0.000377703508723866
12917711	19274	in sql 2008 r2, how do i join 2 columns from one table with 2 columns in another table?	select * from table_a as a inner join table_b as b on a.id = b.id and a.name = b.name 	0
12917829	14174	select rows where date is between [this] and [that]	select * from table where inspect_date>= '04/01/2012 00:00:00.000' and inspect_date< '10/01/2012 00:00:00.000' 	0.0182811520968986
12918061	7590	combine 2 sql select statements	select m.id 'member id', isnull(c.staffcount, 0) 'stuffcount' from tblmembers m left join (     select staffid, count(staffid) 'staffcount'     from tblclients     group by staffid ) c on m.id = c.staffid where m.cat = 'some id' order by stuffcount 	0.0631389663956629
12919613	33238	check for matching values across 2 fields	select distinct t1.tbl_id from     tbl as t1     inner join tbl as t2         on t1.tbl_row = t2.tbl_row         and t1.tbl_col = t2.tbl_col         and t1.tbl_id <> t2.tbl_id 	0.000102442417878181
12920248	19706	"merging" columns from several tables	select col1, col2 from table1 union all select col1, col2 from table2 union all select col1, col2 from table3 	0.000155956313757604
12920454	27862	select distinct group of measurements in a specified time point	select dl.* from (select dl.*,              row_number() over (partition by identifier order by tstamp desc) as seqnum       from datalog dl       where tstamp <= @yourtimestamphere      ) dl where seqnum = 1 	0.0100287125539856
12923514	29547	mysql subquery sum & limit	select t1.id      , sum(t2.value)      , t1.person_id      , count(t2.id) as cnt   from thetable as t1   left join thetable as t2     on (t1.id) <= (t2.id)    and t1.person_id = t2.person_id  group by t1.id         , t1.person_id having cnt <= 4 and t1.person_id in (23, 24, 25)  order by t1.person_id, cnt  ; 	0.561891664158957
12923987	9704	mysql count with join	select  a.id, a.tagtext, count(b.tagid) totalcount from    tags a         left join users_tag b             on a.id = b.tagid group by a.id, a.tagtext 	0.526962283404201
12924107	3766	many to many relationship show one where other matches condition	select distinct c.id, c.name from listingcategory c    join listingcategory_listings lc       on c.id = lc.listingcategoryid where lc.listingid in (<list of listings comma separated>) 	0.000163488824767732
12925820	20902	mysql round and count within nested select and count	select    floor(         round(   1 * count(action))     +   round(  .5 * count(action))     -   round(  .5 * count(action))     -   round(  .1 * count(action)))  from table limit 0,1 	0.21791636886624
12926135	2548	mysql distinct column on multiple row conditions	select distinct preset_id from item_preset  where preset_id in (select preset_id from item_preset where item_id = 1 and value = 2)  and preset_id in (select preset_id from item_preset where item_id = 2 and value = 1)  and preset_id in (select preset_id from item_preset where item_id = 4 and value = 60); 	0.0021600388160481
12926976	32008	display the title and year for all of the films that were produced in the same year as any of the sh and ch films	select m1.year, m1.title from movies m1 where exists (select 1                 from movies m2                where m2.genre in ('sh', 'ch')                  and m2.year = m1.year); 	0
12927079	2800	mysql adding value from previous row	select  a.val, (@runtot :=  a.val  + @runtot) as rt, ( @runtot := a.val ) ne from    table1 a,(select @runtot:=0) c 	9.59973008254949e-05
12927861	11625	calculating time frames between status using sql 2008/2012	select     t.person_id,     min(t.[timestamp]) as start,     calc.[timestamp] as [end],     t.in_home, t.studyng from @temp as t     cross apply     (         select top 1 tt.*         from @temp as tt         where              tt.person_id = t.person_id and tt.[timestamp] > t.[timestamp] and             (tt.in_home <> t.in_home or tt.studyng <> t.studyng)         order by tt.[timestamp] asc     ) as calc group by      t.person_id,     calc.[timestamp],     t.in_home, t.studyng order by start 	0.0177621183823053
12928004	38491	find number of conversation and total time of each conversation	select @rownum := @rownum + 1 as id,t.convo_id,t.body_xml,          str_to_date(min(t.timestamp),'%y%m%d')as          start,str_to_date(max(t.timestamp),'%y%m%d') as  end,sum(str_to_date(t.timestamp),'%i')as    duration from          messages t,(select @rownum := 0) r where t.convo_id='137' group by t.convo_id 	0
12928034	23623	get all values?	select sum(cash) from yourtable 	0.000656207974992065
12928553	1630	repeat main query for multiple values from the subquery	select tm.token_id,count(*) as msg_cnt from  token_messages tm inner join token_table t on tm.token_id=t.token_id and t.user_id in(select user_id from login_table where user_name = 'deepu') group by tm.token_id 	0.00912869499219107
12929521	16348	return distinct row in resultset in sql server 2008	select t.* from [databasename].[dbo].[tablename] t join ( select min(id) id, fileid from [databasename].[dbo].[tablename]  group by fileid )x on t.id=x.id where t.usernumber = '015578957' 	0.0183283749396297
12929899	40778	select distinct returning all values	select name from poi_example where name like '%$text%' group by name order by name asc 	0.00283193516151726
12930784	21460	top 3 results from 4+ tables	select sum(score) from ((select score from event_id_1_results_table where player_id = 1)        union        (select score from event_id_2_results_table where player_id = 1)        union        (select score from event_id_3_results_table where player_id = 1)        order by score desc limit 3) 	0.00113393821371094
12930793	2971	cross table into normal table	select product, location, '201209' as [date], table.[201209] as quantity from table union select product, location, '201210' as [date], table.[201210] as quantity from table 	0.0364391782741972
12931771	34319	mysql concat '*' symbol toasts the database	select *        from main_table m  inner join lookup_table l          on l.value = m.value inner join categories cat         on l.value = cat.id      where cat.name = 'whatever' 	0.491212611331919
12932100	12219	select first created child for parent	select     c.first_name,     c.last_name,     (         select value          from quotes q          left join quotes_contacts qc on q.id = qc.quote_id         where qc.contact_id = c.id         order by q.date_entered         limit 1     ) first_quote_value from     contacts c 	0.000378535628431855
12934746	37250	find nearest postcode to latitude longitude in mysql	select postcode, lat, lon from ( select postcode, max(latitude) as lat, max(longitude) as lon from postcode group by postcode  having max(latitude)<varlatitude and max(longitude)<varlongitude limit 1 ) as temp 	0.103893330275535
12935500	13049	how go group same kind rows in sql	select row_number() over (order by (select 0)) as id,count(*) as count,kind1 as new1,kind2 as new2,kind3 as new3 from yourtable group by kind1,kind2,kind3 	0.0367871195941617
12935755	17470	sql report - group by query for getting data from 12 months ago (this month included)	select    count(*)  from      table_x  where     date > = dateadd(year,-1,getdate()) group by  month(date) 	0.000336030943210002
12936871	9175	mysql use of group by and order by	select * from people order by priority, visits; 	0.33525778493182
12937702	20795	masking values in sql select return	select id, concat("(", name, ")") from <tablename> 	0.0290251855311637
12938332	12913	multiple count selects from the same table in one query	select sum(case when page like '%aec%' then 1 end) as taec,      sum(case when page like '%tol%' then 1 end) as ttol  from sometable 	9.38956809856282e-05
12938700	10314	retrieve rows of 1st column based on common data on 2nd column	select * from your_table where col1 in  (    select col1    from your_table    where col2 in ('0080', '0010')    group by col1    having count(distinct col2) = 2 ) 	0
12938880	39847	sql - select most 'active' time from db	select      datepart(year, the_column) as year     ,datepart(dayofyear,the_column) as day     ,datepart(hh, the_column) as hour     ,datepart(mi,the_column) as minute     ,datepart(ss, the_column) as second     ,count(*) as count from t group by      datepart(year, the_column)     , datepart(dayofyear,the_column)         , datepart(hh, the_column)     , datepart(mi,the_column)     , datepart(ss, the_column) order by count desc 	0.000189675498975946
12938973	31085	four table join in oracle 8i	select users.user_id, users.group_id, users.shift, pi."picks", pi."pick volume", pu."putaways", pu."putaway volume", re."relocates", re."relocate volume" from users, pi, pu, re where users.user_id = pi.user_id(+) and users.user_id = pu.user_id(+) and users.user_id = re.user_id(+); 	0.492942988774348
12940090	24950	how to fetch data from multiple mysql tables with common composite primary key	select distinct columna columnb from     (        select subcol0a columna, subcol0b columnb, '', '' from table0             union     select subcol1a columna, subcol1b columnb, '', '' from table1   )  as query0 where <some condition> 	0
12940678	10220	mysql count fks on other table	select m.name, m.email, count(g.memberid ) from `member` m  left join `group` g on g.memberid = m.memberid group by m.memberid 	0.00149616765307374
12940781	9798	sort data column to retrieve max textual value	select * from testing where value like 'manual%'  order by cast(right(value, length(value)-length('manual')) as unsigned) desc  limit 1 	0
12941125	35406	randomly select two disctinct rows on a table	select distinct postid  from tablename order by rand() limit 2 	4.78430137260277e-05
12944163	34788	how do i select the max date from a union of two tables?	select top 1 a.updatedtimestamp from (      select max(updatedtimestamp) as updatedtimestamp        from db1.dbo.policyrepresentationcache with(nolock)      union      select max(updatedtimestamp)       from db2.dbo.policyrepresentationcache with(nolock) ) a order by a.updatedtimestamp 	0
12944381	14532	most isolated record	select foo.d, timestampdiff(day, max(earlier.d), d) as previous, timestampdiff(day, d, min(later.d)) as next from foo left join foo later on foo.d < later.d left join foo earlier on foo.d > earlier.d group by foo.d 	0.00518870498348545
12944593	36469	mysql same max value, different instances	select * from table    join (select day,max(count) as count from table group by day) as max_rec     on table.day = max_rec.day and table.count = max_rec.count 	0
12945306	18876	how to return a sql result based on values in a boolean column	select * from products where id not in (select id from products where isnotvalid = 1) 	5.44314866717194e-05
12945479	21920	how to do a contains() on two columns of full text index search sql	select * from sys.fulltext_system_stopwords where language_id = 1033; 	0.003045360568177
12945538	18248	sql: trying to select two meta_values in one query	select meta_value from wp_postmetawhere meta_key = "bid_resource_lat" or meta_key = "bid_resource_lng" 	0.0259680201976971
12945721	17145	loop through sql records to get total meter reading over time period if meter has be swapped	select t1b.equipmentid,         t1a.readingdate as startdate,         t1b.readingdate as enddate,        case           when t1b.reading >= t1a.reading then t1b.reading - t1a.reading           else t1b.reading       end as hours from meterreadings as t1a join (select t11.equipmentid,               t11.readingdate as date1,               (select min(t13.readingdate)                   from meterreadings as t13                 where t13.equipmentid = t11.equipmentid                  and t13.readingdate > t11.readingdate             group by t13.equipmentid) as nextreadingdate        from meterreadings as t11) as rd on t1a.equipmentid = rd.equipmentid                                          and t1a.readingdate = rd.date1 join meterreadings as t1b on t1b.equipmentid = t1a.equipmentid                            and t1b.readingdate = rd.nextreadingdate order by t1a.equipmentid, t1a.readingdate 	0
12946103	11878	how to search multi-categories in mysql	select v.v_id from property_video pv     join video v     on pv.pv_v_id = v.v_id where pv.pv_p_id in (12,15) group by v.v_id having count(distinct pv.pv_p_id) = 2 	0.468552448057386
12946280	28150	combining multiple columns in 1 resultset	select id, date(now()) as `date`,        sum(if(date(`date`) = date(now()), `amount`, 0)) as todaytotalsales,       sum(if(date(`date`) < date(now()), `amount`, 0)) as otherdaysales from sales; 	0.00332820344967076
12946298	22115	best way to get blog post titles along with blog name	select b.name,        (          select ', '+bp.title          from blogposts as bp          where b.blogid = bp.blogid          for xml path(''), type        ).value('substring((./text())[1], 3)', 'varchar(max)') as blogposts from blog as b 	0.000769327953660584
12946584	1756	how can i join table on value with string added	select … from … join tableb on  tablea.col like concat('http: 	0.00777795130848174
12948009	5380	finding all parents in mysql table with single query	select t2.id, t2.title,t2.controller,t2.method,t2.url from (     select         @r as _id,         (select @r := parent_id from menu where id = _id) as parent_id,         @l := @l + 1 as lvl     from         (select @r := 31, @l := 0) vars,         menu m     where @r <> 0) t1 join menu t2 on t1._id = t2.id order by t1.lvl desc; 	0.000717787463366578
12948333	20498	how do you pass the value of one query in to another query mysql without using php	select * from (     select *     from `tablename`     order by id desc     limit 5 ) as inner_table order by rand( ) 	0.000645142644083731
12949008	37326	how in query result add 0-data for don't exist rows?	select   nvl(t.data, 0) data,   f.month,   t.year from <your_table> t partition by(t.year) right join (select level month from dual connect by level <= 12) f on t.month = f.month 	0.00366048893397584
12949358	37115	how to get latest 'n' updated row from a table	select * from      ( select *       from your_table       where cust_id=<given cust_id>      order by lastupdateddate desc )  where rownum <= 10; 	0
12950127	3755	duplicates query	select name from yourtable group by name having count(policy)=1 and max(policy)='sss' 	0.339367223519508
12950261	18017	how to join in mysql	select t1.shorttext,if(t2.c is null,0,t2.c)as c from selections t1 left join ( select s.id,s.shorttext, count(o.selectionid) as c from selections s left join opinions o on s.id=o.selectionid where  month(o.entrydate)=5  group by s.shorttext   ) t2 on t1.id=t2.id 	0.374185635501339
12950538	17266	ms sql 2008 - get all table names and their row counts in a db	select sc.name +'.'+ ta.name tablename  ,sum(pa.rows) rowcnt  from sys.tables ta  inner join sys.partitions pa  on pa.object_id = ta.object_id  inner join sys.schemas sc  on ta.schema_id = sc.schema_id  where ta.is_ms_shipped = 0 and pa.index_id in (1,0)  group by sc.name,ta.name  order by sum(pa.rows) desc 	0
12950741	24292	create table of unique values from table of duplicates	select *  from   (select symbol,                 startdate,                 externalcode,                 externalcodetype,                 row_number()                   over (                     partition by symbol                     order by startdate desc) rn          from   tablename) t  where  t.rn = 1 	0
12951931	13560	fetch monthly records by total and by detail from single query in sql server 2005	select t1.*,         t2.emp_count    from (select datename(month, appoinemntdate) month_name,                 count(*)                        app_count            from appointmenttable           group by datename(month, appoinemntdate))t1         left join (select count(*)                        emp_count,                           datename(month, appoinemntdate) month_name                      from appointmenttable                     where employeeid = 4                     group by datename(month, appoinemntdate))t2                on t1.month_name = t2.month_name 	0
12953363	23551	select messages sent by user or to user	select i.id, toid, fromid, message, `time` from     inbox i     inner join (         select max(id) as id         from inbox         where toid = 4 or fromid = 4         group by greatest(toid, fromid), least(toid, fromid)     ) s on i.id = s.id 	0.00964985897720313
12953671	41170	how to get and iterate through two dimentional list (using foreach i guess) in sql stored procedure	select t2.columnc  from table2 as t2 where     exists     (        select *        from table as t1        where t1.columna = t2.columna and t1.columnb = t2.schemeid     ) 	0.0425050353779638
12954342	6971	set all columns to `null` in a table	select  'update '+ so.name+' set '+sc.name+'= '''' where '+sc.name+' is null '    from sysobjects so join syscolumns sc on so.id = sc.id join systypes st on sc.xtype=st.xtype   where so.type = 'u' and st.name in('varchar','char') 	0.00039267513272272
12954824	27753	sql query to populate 0's for missing data	select dates.datum, employees.employee, isnull(tbl.number,0), employees.stack       from (select distinct datum from tbl) dates cross join (select distinct employee, stack from tbl) employees  left join tbl on tbl.datum=dates.datum and tbl.employee = employees.employee                   and tbl.stack = employees.stack 	0.324689500228019
12954929	9284	how to get subject names and total of missed homework in each subject from mysql/php	select      hw_subjects.name,      count(hw_homeworkmissed.id)  from hw_subjects, hw_homeworkmissed  where hw_subjects.id= hw_homeworkmissed.subjectid  group by subjectid  order by hw_subjects.name 	0
12956470	7082	full outer join on multiple tables with field concatenation in mysql	select email, group_concat(skill order by skill) skill from (     select email, skill from acting     union     select email, skill from writing     union     select email, skill from film     union     select email, skill from tech ) x group by email 	0.783584170733743
12956743	21450	postgres how to check if user has createdb permissions?	select rolcreatedb from pg_authid  where rolname = 'your user name' 	0.00566787468973605
12957175	10214	consolidating columns of like data	select employeename,         hiredate,         title,         max(mandatory30) as mandatory30,         max(mandatory90) as mandatory90,         max(mandatorypa) as mandatorypa    from table   group by employeename,            hiredate,            title 	0.0154024386608143
12959139	19375	sql multiple joins on same table such that an entity has all fields set	select bannerid, count(bannersize)  from tbl_banners   where bannersize in (16, 32, 64, 128, 256, 512, 1024)  group by bannerid   having count(bannersize) = 7 ; 	0.00055981795187543
12959160	1070	how to select next 4 consecutive rows from my resultant row?	select   abc.* from     abc join (select amount from abc where name = 'a') t where    abc.amount >= t.amount order by abc.amount limit    5 	0
12960299	39786	how can one use t-sql to select only those rows that have column b value not greater than the next greater values in column a?	select t1.a, t1.b   from tbl t1  where t1.b < isnull((select min(t2.a)                         from tbl t2                        where t2.a > t1.a), t1.b+1) 	0
12962027	12694	query to get foreign key indexes	select      sc.name + '.' + t.name as tablename,     object_name(fkc.constraint_object_id) as [fkey-name],     object_name(fkc.referenced_object_id) referencedtable,  c.name as columnname , i.name as referencedkeyname from    sys.foreign_key_columns fkc join    sys.index_columns ic on ic.object_id = fkc.parent_object_id     and ic.column_id = fkc.parent_column_id join    sys.indexes i on i.index_id = ic.index_id     and i.object_id = ic.object_id join sys.columns c on c.object_id = ic.object_id     and c.column_id = ic.column_id   join    sys.tables t on t.object_id = c.object_id join    sys.schemas sc on sc.schema_id = t.schema_id where   t.is_ms_shipped = 0 order by tablename, object_name(fkc.constraint_object_id), columnname 	0.00605023088461117
12965149	28729	lookup tables with temporary fields?	select * from #temp1, (select degree_level, [aadegree] as col1, [bachdegree] as col2 from  (select degree_completions, #temp1.degree_level, degree_level_recode from #temp1, #temp2 where #temp1.degree_level = #temp2.degree_level) as p pivot ( sum (degree_completions) for degree_level_recode in ([aadegree], [bachdegree]) ) as pvt ) as v where #temp1.degree_level = v.degree_level order by 1 	0.0592174541670516
12965549	26804	multiple select in mysql command	select name, email  from user_info where username="username"  and password="password" 	0.368459166887936
12966524	29450	mysql select group by date, arithmetic, then sum results	select date(`date`),         sum(((value*60)*10)/1000000) as value from `sub_meter_data`  where date(sub_meter_data.date) > '2012-10-01'        and sub_meterid in('58984','58985','58986','58987') group by date(`date`); 	0.0731573434948106
12967518	39416	sql querying database	select substring(abc,charindex('=',abc)+1,len(abc)-charindex('}',abc)) 	0.227325068095196
12971391	39849	mysql group by where day <= x	select      dd.ddate as day   , sum(t.units) as overall_units  from         ( select distinct               product_id           from                tbl         ) as dp     cross join         ( select distinct               date(timestamp) as ddate           from                tbl         ) as dd     join          tbl as t             on t.id =                 ( select                       tt.id                   from                       tbl as tt                   where                        tt.product_id = dp.product_id                     and                       tt.timestamp < dd.ddate + interval 1 day                   order by tt.timestamp desc                     limit 1                 )  group by      dd.ddate ; 	0.00362750310388681
12971455	26960	advances mysql group by	select distinct least(from_id, to_id), greatest(from_id, to_id) from messages 	0.637368994129927
12972320	4286	how to do an inner join on row number in sql server	select a.val,b.val  from(     select val,row_number() over (order by val) as row_num     from a)a join     (select val,row_number() over (order by val) as row_num     from b)b on  a.row_num=b.row_num order by a.val,b.val 	0.0454946927555632
12972352	14023	select rows from two tables in sql	select * from class c where classid not in (select distinct classid from classanddepartment) 	0.000310835561422172
12973215	38787	sql check if numrical value is 0 for a field where id is=333	select case when isnull(id,0) <> 333 or field1=0 then 1 else 0 end       ,other1, other2   from tbl 	0.00204115133440619
12974141	13769	sql server query order by column containing string	select * from   mytable order  by case             when mycolumn like '%xyz%' then 0             else 1           end,           mycolumn 	0.205057856872128
12974856	25580	oracle sql - change decimal dot for a comma	select to_char(10,'9g999d00', 'nls_numeric_characters = '',.''') from dual 	0.0496731844409625
12975145	35347	mysql calculate total amount of days absent	select sum(datediff(until, from) + 1) total_absences  from   absences  where  absences.user_id = 123        and absence_date_until <= '1999-12-01'         and absence_date_from  >= '2000-12-01' 	0
12977598	37305	limit select based on group	select  x.[jobnumber], x.[acttype], x.[projstatus], x.[completedate] from ( select a.[actid], a.[jobnumber], b.[acttype], b.[projstatus], a.[completedate],       row_number() over       (partition by jobnumber order by [completedate] desc ) xx from table1 a       inner join table2 b         on a.[acttypeid]=b.[acttypeid] ) x where x.xx = 1 	0.00736760484835866
12978434	30211	outputting mysql result with data from one column grouped into a single cell	select work.id as workid       ,group_concat(teamname) as teamname from work left outer join team_work on team_work.work_id = work.id left outer join team on team_work.team_id = team.id group by work.id 	0
12978574	33197	mysql join overrides original table values	select  a.id, a.name, b.value from    join_table a          left join original b             on a.id = b.id 	0.041136351144062
12981152	2432	error in sql (select and left join) how give id first table?	select *, f.id... 	0.115980668640828
12983048	16450	mysql adding more than one where with sub-select query	select day, sum(diff) as total_diff from ( select t1.sub_meterid, date(t1.`date`) as day, max(t1.value) - min(t1.value) as diff from `sub_meter_data` t1 join othertable t2 on t1.sub_meterid=t2.meterid join moretable t3 on t2.id=t3.meterid where date(t1.`date`) > '2012-10-01'    and t1.sub_meterid in ('58984','58985','58986','58987') group by t1.sub_meterid, date(t1.`date`) ) a group by day 	0.461316718571385
12983252	16609	merging two version-tracking tables while filling in values	select     coalesce(t1.rev, t2.rev) rev,     coalesce(a, lag(a, 1) over(order by coalesce(t2.rev, t1.rev))) a,     coalesce(b, lag(b, 1) over(order by coalesce(t2.rev, t1.rev))) b,     coalesce(c, lag(c, 1) over(order by coalesce(t1.rev, t2.rev))) c,     coalesce(d, lag(d, 1) over(order by coalesce(t1.rev, t2.rev))) d from     t1     full join     t2 on t1.rev = t2.rev order by rev 	0.000256657725563358
12983288	9740	manipulating a query	select top 10 prepodfamio, max(paudittime)     from prepod as pr     inner join plany as pl on pr.planyid = pl.idplany group by prepodfamio order by max(paudittime) desc 	0.501172107170152
12984396	34605	sql sum with conditions in a select case	select catalogid , sum(numitems) numitems , sum(allitems) - sum(numitems) ignoreditems from  (     select i.catalogid     , numitems allitems     , case          when          (             ocardtype in ('paypal','sofort')              or             (                 ocardtype in ('mastercard','visa')                  and                 odate is not null             )         )          and not exists          (             select top 1 1             from bookedordersids b             where b.booked = o.orderid         )         and i.oprocessed = 0         then numitems         else 0      end numitems     from orders o     inner join oitems i      on i.orderid = o.orderid ) x group by catalogid 	0.648095506247699
12986368	19330	installing postgresql extension to all schemas	select <schema>.<function>(...) 	0.022819144648561
12988212	11242	sqlite query to filter some data out with special condition	select id, item, value  from data  where value <> 0 or item in   (select item from data    group by item    having count(*) <> 2); 	0.334660729275072
12992373	1394	change the value of one column based on the value of another column	select     item,     itemtype,     case         when itemtype = 'car' then null         else size     end from table 	0
12992870	37059	counting values of a mysql table in php	select user, sum(pages) as totalpages  from users  group by user 	0.0011532544384968
12993346	3854	counting multiple entries / statistics	select drink, sex, count(id) counted from   u001 group by drink, sex 	0.000784035438285921
12993831	1374	how to do multiple sql joins so that i get back entities that match certain criteria?	select b.* from banners b inner join ( select bannerid,count(bannersize) bl from banners group by bannerid having count(bannersize) = (select count(distinct(bannersize)) cl from banners) ) ab on b.bannerid=ab.bannerid 	0.000233999777448554
12993832	24791	subtract total of one query from another query	select (sum((ta.task_average*tc.completed)/60) - sum(m.minutes/60)) as difference from ... 	0
12993917	3553	simplifying a query into cases	select   p.formeid, p.name,          case            when p.genders not like '0|_' then 'm'            when p.genders not like '_|0' then 'f'            when p.genders =        '0|0' then 'n'          end as gender from     data_pokemon p left join dex d       on p.formeid = d.formeid      and d.userid  = @userid      and d.gender  = case            when p.genders not like '0|_' then 'm'            when p.genders not like '_|0' then 'f'            when p.genders =        '0|0' then 'n'          end where    d.formeid is null order by p.formeid 	0.799644042036964
12995261	1199	compare football picks with other players across weeks	select   t.profileid                 as target,          sum(s.pick=t.pick)/count(*) as similarity from     sp6picks s     join sp6picks t using (gameid)     join sp6games g using (gameid) where    g.weekid    <= 3      and s.profileid != t.profileid      and s.profileid  = 52 group by t.profileid 	0.000341339674755334
12997588	5277	can i query mysql to return the results in the same way i sent to a bulk select query?	select *  from tbl  where var in (v1, v2, v3, v4)  order by field(var, v1, v2, v3, v4)  limit 1 	0.00078179089911751
12998610	8569	mysql view query without json from a table containing some json objects	select user_id,name, substring_index(substring(params,locate('age":"',params)+6),'"',1) as age  from table_2 	0.0149267296068095
13003251	26825	select minimum column not equal to zero	select least(          if(col1, col1, col2),          if(col2, col2, col1)        ) from   mytable 	0.00552726792362649
13003591	18607	sql: distinct based on 1 field	select a.* from tablename a (     select countryname, min(id) minid     from tablename     group by countryname ) b on a.id = b.minid  	0.000675357191115632
13003805	26077	how to join a csv list to a table column	select mt.code, mt.new_table_id from my_table mt where mt.code in (   '23000005619',   '23000019479',   '23000019759',   '23000030169',   '23000032629' ) 	0.00121694908227402
13005682	4675	oracle 11g select distinct not unique	select distinct job_id,        to_char(service_date,'yyyy-mon-dd hh24:mi:ss'),        grand_total, ... 	0.124637664628859
13006997	31705	separate items of an array over different pages	select id from table  order by id desc limit 5 offset 0 	0.000133674397628013
13007787	38433	how to use multiple columns in where clause in sql server 2005?	select id from employee  where firstname + ' ' + middlename + ' '+lastname = 'sample name here' 	0.738875505860808
13007964	35242	extend mysql date	select * from boxes where customer = '$_session[kt_idcode_usr]' and  destroy_date <= date(now()) and status = 1"; 	0.166220553760869
13009566	34161	postgresql duplicate rows counting on join	select table1.id, table2.id as aid, table1.name, table2.data, greatest(1, (select count(*)              from table2 t2              where t2.aid = table1.id              and t2.id <= table2.id)) as number from table1 left join table2 on table2.aid = table1.id order by id, aid; 	0.00342738797308875
13009709	19062	using if in mysql query	select * from status where type != "3" and userid = "'.$userid.'" and  (     interacterid is null or interacterid in (         select userid         from userfriends         where (             userfriends.userid = "'.$currentuserid.'"             or userfriends.interacterid = "'.$currentuserid.'"         )         and status = "1"     ) ) order by addeddate desc limit 1 	0.542628742652058
13009871	30320	query row values as different columns in oracle 10g	select stu_number,         max(stu_name) stu_name,         ex_name,         max(case when ex_subject = 'mathematics' then stu_score end) as mathematics,        max(case when ex_subject = 'english' then stu_score end) as english,        max(case when ex_subject = 'physics' then stu_score end) as physics,        max(case when ex_subject = 'chemistry' then stu_score end) as chemistry from exams_master_register  where stu_level = '1' and        stu_stream = 'east' and        ex_semester = 'first' and        ex_name = 'midyears' and        academic_year = '2012'  group by stu_number, ex_name order by sum(stu_score) desc 	0.000996110135672456
13010552	27895	how can i get three function for one field in different states	select  sum(case kind when 1 then qty else 0 end) kind1,  sum(case kind when 0 then qty else 0 end) kind8,  sum(case kind when 3 then qty else 0 end) kind3,  sum(case kind when 1 then qty else 0 end)  + sum(case kind when 0 then qty else 0 end)  + sum(case kind when 3 then qty else 0 end) total,  from      mytable 	0.0005630007048006
13010833	30241	inner join with condition on joined table	select *  from `table1` as `t1`  inner join `table2` as `t2`    on `t1`.`id`=`t2`.`id`       and `t2`.`name`='myname' 	0.286603714935213
13013990	23570	dynamically pick field to select data from	select *  from mytable where (chosennum in ('both', 'primarynum') and primarynum = 10)     or (chosennum in ('both', 'secondarynum') and secondarynum = 10) 	0.000352628293259269
13014590	39409	rename data from oracle column	select day, decode(item, '102', 'shoe', '423', 'orange',...), total from items 	0.00249266382648626
13015865	23229	sql selecting rows with matching values	select a.master_record_id from tablename a join tablename b using (master_record_id) where a.credit_value = 'brian j' and b.credit_value = 'katie w' 	0.00032276527247625
13015905	17561	linking information in two tables	select * from user_updates u       inner join interests i on i.username = u.username 	0.00163262827271592
13018192	36904	how to write a query in sql?	select c1.title, count(e1.sectionno), e1.semester from courses c1, courses c2, enrollments e1, enrollments e2 where c1.courseno = c2.courseno      and e1.semester = e2.semester      and e1.sectionno <> e2.sectionno group by c1.title, e1.semester 	0.601895750626454
13018220	36478	how can i join a table to return all rows right and in addition a null row?	select p.name, pa.name from partstbl p left join partattrib pa on p.name= pa.basename where p.name = 'cake' union select name, null from partstbl where name = 'cake' 	0.000398271005422757
13019387	34044	mysql replace string + next one char	select *,if(locate('14_',b)+3<=length(b),          insert(b,locate('14_',b),4,''),b) c from (   select *,if(locate('14_',a)+3<=length(a),            insert(a,locate('14_',a),4,''),a) b   from (     select *,if(locate('14_',x)+3<=length(x),              insert(x,locate('14_',x),4,''),x) a     from x   ) q1 ) q2 	0.00353144919721051
13020822	31348	summing up column values in mysql	select count(*) as total,        sum(a = 'apple') as applecount,        sum(a = 'orange') as orangecount,        sum(a not in ('orange', 'apple')) as others from fruits 	0.0146050828123444
13022510	27293	how to select and ignore whitespace or blank strings?	select distinct col_name  from table_name where trim(col_name) != '' 	0.175450920164172
13024058	30175	write a query display dept name , job name , "count of employees in job for each dept" & "count of employees in dept"	select d.dname, e.job, count(*)   from emp e join dept d on d.deptid = e.deptid group by cube(d.dname,e.job); 	0
13026334	10566	get closest date from mysql table	select    *  from    your_table  order by    abs(datediff(now(), `date`)) limit 1 	0.000142569751723911
13027708	28304	sql multiple columns in in clause	select city from user where (firstname, lastname) in (('a', 'b'), ('c', 'd')); 	0.187152894398872
13027740	3821	mysql check where field in (multiple_values)	select * from mya_projects where find_in_set( id, shared_to) order by deadline asc 	0.103056981980892
13031846	11399	manipulate results to display rows as columns	select * from (tableb) s pivot (max(staffno) for employee_class in ([full time],[part time])) p 	0.000104349382898011
13032666	26755	join a table with one table if condition1 is true and with another table if condition1 is false?	select ug.id, array_agg(     case ug.group_type          when 'a' then g_a.name          when 'b' then g_b.name          else 'n/a'      end) from user_groups ug left outer join group_a g_a on ug.group_id = g_a.id left outer join group_b g_b on ug.group_id = g_b.id group by ug.id 	0.00116757952408251
13032954	13227	merging 2 columns from different tables	select * from (     select col1, col2, col3 from messages     union all     select col1, col2, col3 from replies ) x order by col3 	0
13033645	20488	archiving large table (sql server 2008)	select null; while @@rowcount > 0      delete top (50000) from table where condition = true; 	0.740791788269998
13034324	695	how to find average gap between dates?	select avg(if (diff < 0, 0, diff)) from (     select datediff(min(t2.start), t1.end) as diff     from table1 t1     inner join table1 t2 on t1.id < t2.id     group by t1.end ) a 	7.9940142131234e-05
13036989	5539	mysql query most recent record	select act.*  from activity as act       inner join (           select user_id, max(timestamp) as max_ts           from activity           group by user_id) as a on act.user_id=a.user_id and act.timestamp=a.max_ts 	0.000470270292330898
13038116	31543	sql datediff without enddate	select count(startdate) as treatmentdays from ... where ... group by cast(startdate as date) 	0.340874420738472
13039528	33145	sql server 2012 returns different results than sql server 2008	select *, rank() over (partition by ssn, kid_dob order by kid_ssn) as seqnum from kids 	0.791156118324537
13039888	10951	sql expression that fetches data from one table but have criterias involving several	select * from table1 where var1=x union select * from table1 join table2 on table1.var2 = table2.var4 where table1.var1 <> x    and table2.var3 = x 	0.000507066765599416
13040594	37089	sql query for fetching friend list	select u.firstname from userfriends f, users u where  u.email='email@domain.com' and f.status=1 and (u.email = f.email and f.friendsemail='email@domain.com') or (u.email = f.friendsemail and f.email='email@domain.com') 	0.0858173499878677
13042478	16146	mysql query - how to count foreign key occurence from second table with three table connected?	select  b.package_id, c.price, d.totalcount from    product a         inner join package_detail b              on a.product_id = b.product_id         inner join package c             on b.package_id = c.package_id         inner join          (           select package_id, count(*) totalcount           from package_detail           group by  package_id         ) d on d.package_id = b.package_id where a.product_name = 'apple' 	0
13043759	14937	mysql group by on select if statement	select p.profileid, group_concat( if( gpro.isinfluence =0, g.genrename, null ) ) as genre, group_concat( if( gpro.isinfluence =1, g.genrename, null ) ) as influence, g.genrename from profiles p left outer join genre_profiles gpro on gpro.profileid = p.profileid left outer join genres g on g.genreid = gpro.genreid where g.genrename is not null  group by p.profileid 	0.304472327663005
13046619	40910	query to get list active queries in my sql server	select      r.session_id,     r.status,     r.command,     r.cpu_time,     r.total_elapsed_time,     t.text from sys.dm_exec_requests as r     cross apply sys.dm_exec_sql_text(r.sql_handle) as t 	0.0236567876928777
13046634	15352	selecting distinct records that has last creation date in similar records	select `id`, max(`lastmsg`) from  (   select `m`.`receiveruserid` as `id`, max(`m`.`datecreated`) as `lastmsg` from `messages` `m`     where `m`.`senderuserid` = :userid     group by `m`.`receiveruserid`     union     select `m`.`senderuserid` as `id`, max(`m`.`datecreated`) as `lastmsg` from `messages` `m`     where `m`.`receiveruserid` = :userid     group by `m`.`senderuserid` ) as table2 group by `id` order by `lastmsg` 	0
13048527	9558	db2 sql group by/count distinct column values	select * from flags where flag=1 and id not in( select id from flags where flag !=1 or flag is null) 	0.0259512393610022
13052562	2520	postgres return nothing when other rows have value	select * from usersgroups  where     username = 'tu1'     and exists (         select 1         from usersgroups         where             username = 'tu1'             and groupname like 'is_%'     )     and not exists (         select 1         from usersgroups         where             username = 'tu1'             and groupname = 'is_banned'     ) 	0.000534895292543147
13053401	31814	mysql: how to get specific row using column value?	select name, city, state from tablename where name = 'jeremy' 	0
13053521	18623	combine two queries with different numbers of columns	select tmp1.cellid, tmp1.rows, tmp2.mode_cat from (     select cellid, count(*) as rows     from rel     group by cellid )tmp1 left join (     select cellid, cat as mode_cat     from rel t     group by cellid, cat     having cat = (         select cat         from rel         where cellid = t.cellid         group by cat         order by count(*) desc, cat         limit 1     ) )tmp2 on tmp1.cellid = tmp2.cellid; 	0
13053636	254	php mysql blog archive menu by year and month	select      year(datefield) as year,      month(datefield) as month,     count(*) as total  from table  group by year, month 	0.00677530727711518
13053643	18293	add 3 colums and get the max value of that addition	select id,         l,         rl,         cl,         l+r+c as total        (select max(l+r+c) from pin) as max from pin 	0
13055194	31976	cast(0x993902ce as datetime) from sql server to mysql	select "0x993902ce" into @raw_data; select conv(substr(@raw_data, 3, 4), 16, 10) into @days; select conv(substr(@raw_data, 7, 4), 16, 10) into @minutes; select "1900-01-01 00:00:00" into @start_date; select date_add(@start_date, interval @days day) into @date_plus_years; select date_add(@date_plus_years, interval @minutes minute) into @final_date; select @final_date; 	0.0902855422772095
13055766	28452	store array into variable	select * from atable where find_in_set(bfield, @myarray); 	0.0505562328287859
13056523	8400	selecting the minimum of two distinct values	select ss2.id score_id,   ss2.studentid,   ss1.test,   ss2.subject,   ss1.score,   ss2.semester from example_students st left join (   select min(score) score, test, subject, studentid   from example_students_scores   group by test, studentid, subject ) ss1   on st.id = ss1.studentid left join example_students_scores ss2   on st.id = ss2.studentid   and ss1.score = ss2.score   and ss1.test = ss2.test where st.id = 94 order by ss2.id 	0
13056673	33116	creating a new table from two existing tables with every combination possibility	select * into #c from #a,#b 	0
13057281	7303	grouping and total issue	select name,          sum(totalcharges) [total spend],          count(devicetype) [# of devices],          sum(totalcharges)/count(devicetype) [avg spend],          count(case when totalcharges > 300 then 1 end)  [# of bills > 300]     from dbo.phone_details group by name 	0.136543932717393
13057630	26091	select data from a table where only the first two columns are distinct	select pk1, pk2, '11', max(c1), max(c2), max(c3)  from table  group by pk1, pk2 	0
13060002	35765	select distinct index names	select distinct index_name from information_schema.statistics   where table_schema = 'your_schema'     and table_name = 'your_table' 	0.028206647152301
13061615	30230	full join for 3 tables	select a. * , b. * , c. * from tbl_1 a left outer join tbl_2 b using (num) left outer join tbl_3 c using (num) union select a. * , b. * , c. * from tbl_2 b left outer join tbl_1 a using (num) left outer join tbl_3 c using (num) union select a. * , b. * , c. * from tbl_3 c left outer join tbl_1 a using (num) left outer join tbl_2 b using (num) 	0.369888782296281
13061756	17355	oracle apex report row indent	select  replace(lpad('#', level*2, '#'),'#','&nbsp;')|| ename as ename from    emp start   with mgr is null connect by nocycle prior empno = mgr 	0.225477925196549
13062133	7824	mysql query and count from other table	select     c.*, count(u.cid) as count from     cars c left join      uploads u on     u.cid=c.customer where     u.customer = 11; group by c.cid 	0.00211194033853366
13062641	12751	is it possible to return the total count of distinct ip_address for every day between a range?	select date(`datetime`),count(distinct ipaddress) as ipaddress from requests where datediff(now(),datetime)<=180 group by date(`datetime`) 	0
13062683	8652	oracle sql compare strings containing numbers, starting with 0 (zero)	select *  from parameter where  name like 'date_to'   and cast ( substr(value, 1, 2) as int ) <cast ('25' as int)  and cast ( substr(value, 1, 2) as int) > cast ('05' as int ) 	0.00135133679430075
13063395	9063	adding column to view	select *,     case when movementagedays < -90          then 'more than 90 days'          else null end as islager from rv_transaction 	0.0952287260720678
13064114	41326	selecting the row with the max in a column - mysql	select mt.first, mt.second, mt.third, mt.fourth  from mytable mt join ( select first, max(fourth) as fourth        from mytable        group by first      ) t on t.first = mt.first          and t.fourth = mt.fourth 	0.000130113989681238
13064526	26124	sorting fetched tables names from databse. mysql php	select table_name from information_schema.tables    where table_schema="yourdbname" and table_name like '" . $tbl . "_gw%'    order by create_time; 	0.000535858548292805
13065105	5966	sql display two results side-by-side	select a.name as namebyvisits, b.name as namebyspent     from (select c.*, rowid as rownumber from (select name from table1 order by visits) c) a     inner join     (select d.*, rowid as rownumber from (select name from table2 order by spent) d) b     on a.rownumber = b.rownumber 	0.0035808813227234
13065555	29130	oracle - string to number	select to_number(ltrim(prize, '0')) / 100 from table 	0.0280583744079641
13067447	31846	sql same name but different value	select distinct      p1.* from      persons p1  cross join      persons p2  where          p1.name = p2.name      and p1.value <> p2.value     and p1.description <> p2.description 	0.000293667772814678
13068185	37274	mysql - detect rows that have three columns in common	select *,total/cnt.val from `mytable`  left join (select `channel`,`order`,`code`,count(*) as val             from `mytable` group by `channel`,`order`,`code`) as cnt  using (`channel`,`order`,`code`); 	0
13068632	37978	get rows which have a higher date than a specific one in mm/dd/yyyy format	select * from xtable where xdate >= date '2011-10-21' 	0
13070244	7281	get the missing value in a sequence of numbers	select b.akey, (     select top 1 akey      from table1 a      where a.akey > b.akey) as [next]  from table1 as b  where (     select top 1 akey      from table1 a      where a.akey > b.akey) <> [b].[akey]+1 order by b.akey 	5.53805878695243e-05
13070981	16919	group by members of a comma delimited list	select r.name, <other aggregated results> from t1 join      resources r      on concat(', ', t1.resources, ', ') like concat(', %', r.name, ', %') group by r.name 	0.000791324180384742
13071035	2264	sql query to extract all wordpress posts with categories	select distinct post_title , post_content ,(select meta_value from wp_postmeta where wp_postmeta.meta_key = 'asking price (us\$)' and wp_postmeta.post_id = wp_posts.id) as "asking price (us\$)" ,(select group_concat(wp_terms.name separator ', ')      from wp_terms     inner join wp_term_taxonomy on wp_terms.term_id = wp_term_taxonomy.term_id     inner join wp_term_relationships wpr on wpr.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id     where taxonomy= 'category' and wp_posts.id = wpr.object_id ) as "categories" ,(select group_concat(wp_terms.name separator ', ')      from wp_terms     inner join wp_term_taxonomy on wp_terms.term_id = wp_term_taxonomy.term_id     inner join wp_term_relationships wpr on wpr.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id     where taxonomy= 'post_tag' and wp_posts.id = wpr.object_id ) as "tags" from wp_posts where post_type = 'post'  order by post_title , post_content 	0.00071935417861754
13071766	28001	sql server - get highest values when previous date not blank	select top 3 p.name,              player_id,              steps,              date from   steppers_step_log        join steppers_players p          on player_id = p.id where exists (    select 1 from steppers_step_log ssp    where ssp.player_id = p.id    and date = dateadd(day, -1, steppers_step_log.date) ) order  by steps desc 	4.98626597569878e-05
13071948	22352	sql: selecting 5 urls, with least visited domains as fast as possible	select      us.*,      top5.domain_count  from      url_stack us     inner join           (              select                 domainid,                 domain_count            from                 domain_stack            group by                 domain_count asc            limit 5           ) top5          on top5.domainid = us.domainid group by     top5.domain_count asc limit 5 	0.00902583961615505
13072288	12441	coldfusion array for database query	select stats_instance, ... from ... where ...  <cfif len(trim(arguments.instance))> and stats_instance in (<cfqueryparam value="#arguments.instance#" list="yes"/>) </cfif> group by stats_instance order by stats_instance 	0.71105624638605
13072515	30992	find last (first) instance in table but exclude most recent (oldest) date	select   id,   max(date) from   tablename where   date between '1/1/2010' and '3/27/2010' group by   id having max(date) < '3/1/2010' 	0
13074935	14839	can i get the sqlconnection from sqldataadapter?	selectcommand 	0.00391948245767383
13075159	16704	return rows for in query with failed look-ups returning null	select x.a, c.b from (   select 'v1' as a union all   select 'v2' as a union all   select 'v3' as a ) x left outer join c on c.a = x.a 	0.398015189429171
13076017	31838	cannot select items in mysql with "where s_id in ($array)"	select * from blah where boing in (select id from blah2 where team=1337) 	0.0958803359522462
13076565	39016	table with multiple foreign keys joining 1 foriegn key in mysql	select u.displayname as username    , po.displayname as primaryitownerusernname    , so.displayname as secondaryidownerusername from users as u inner join owners as po on u.primaryitowner = po.username inner join owners as so on u.secondaryitowner = so.username ... where u.username = 'ryan j morse' 	0.000299256822735642
13077540	3146	conditional field selection oracle	select coalesce( name1, name2, name3 ) first_name,        (case when name1 is not null               then nvl( name2, name3 )              when name2 is not null              then name3              else null          end) second_name,        (case when name1 is not null and                   name2 is not null              then name3              else null          end) third_name   from your_table 	0.564232954288338
13077664	34037	grouping based on every n days in postgresql	select     "date",     temperature,     avg(temperature) over(order by "date" rows 10 preceding) mean from t order by "date" 	0
13077797	2697	determine which join added row to result set	select a.*,        (case when b.id is not null and c.id is not null then 'both'              when b.id is not null and c.id is null then 'b'              when b.id is null and c.id is not null then 'c'              else 'a'         end) as wherefrom from tablea a left join tableb b on a.b_id = b.id left join tablec c on a.c_id = c.id where a.creator_id = 5 or b.is_active = 1 or c.can_attend = 1 	0.00292462473274061
13079403	19015	sql query help to get field "custname" as a result instead of "custnmbr"	select a.custnmbr, b.custname, sum(a.ortrxamt) as 'sales total' from rm30101 a inner join rm00101 b on b.custnmbr = a.custnmbr where b.zip = '99502'     and (a.docdate between '2011-01-01' and '2012-10-25') group by a.custnmbr,b.custname order by [sales total] desc 	0.0745339135956688
13080703	15930	sql query to join 2 tables and find the matching rows based on a criteria	select t1.userid, t1.firstname, t1.lastname, max(salesdate) as salesdate from table1 t1 join table2 t1 on t1.userid = t2.userid group by t1.userid, t1.firstname, t1.lastname having max(salesdate) < '20120601' 	0
13080721	24326	find the best car deal	select car_number, car_year   from cars c  where (select sum(car_price)           from cars          where car_year < c.car_year             or (car_year = c.car_year and car_number <= c.car_number)        ) <= :budget 	0.0290776797633993
13081309	32488	converting date to string in sql server 2005	select  datename(weekday,'10/11/2012')       + ', '       + datename(month,'10/11/2012')       + ' '       + convert(varchar,month('10/11/2012'))       + ', '       + convert(varchar,year('10/11/2012')) 	0.370677769493273
13081489	30220	sql : create extra column specifying shipping deadline date time	select orderdate as [order date],        orderid as [order id],        paymentamount as [payment amount],        totalshippingcost as [total shipping cost],        dateadd(hour, 48, orderdate) [shipping deadline]   from orders  where orderdate between '10/15/2012 00:00:00' and '10/21/2012 00:00:00' 	0.0188786181384795
13081897	15471	mysql round up to nearest 5 cents	select (<value> div 0.05) * 0.05 + if(<value> mod 0.05 = 0, 0, 0.05) 	0.083302064050337
13082272	31809	inner join of 2 tables with the same id	select     t1.somedata,     t1.somedata1,     t2x.name as xname,     t2y.name as yname from t1 as t1     inner join t2 as t2x on t2x.id = t1.x     inner join t2 as t2y on t2y.id = t1.y 	0.000625597529552179
13083666	10261	how can i select distinct on the last, non-numerical part of a mixed alphanumeric field?	select substr(col,instr(translate(col,'a0123456789','a..........'),'.',-1)+1)   from table; 	0
13083701	14766	mysql query to determine records that are related to category a and b	select p.* from products p      inner join  (     select product_id     from category_product     where category_id in (1,2)     group by product_id     having count(distinct category_id)=2 ) pc     on p.id = pc.product_id 	0
13083899	37784	how do i organise "orderdate" into first date of each week	select dateadd(d,1-datepart(dw,orderdate),orderdate) orderstartofweekdate,          sum(amt) totalamt     from tbl group by dateadd(d,1-datepart(dw,orderdate),orderdate); 	0
13084025	14939	sql query to get historic data from table	select a.*  from     history a    join (select username, max(id) 'id' from history           where date < @inputdate          group by username         ) as b    on a.id = b.id 	0.00189575612216066
13084693	20783	query to display rows having duplicate values in 2 columns	select tabl1.* from table1 inner join table2 on table1.id=table2.id and table1.name=table2.name 	0
13085655	15884	search through table names	select name   from dbname.sys.tables  where name like '%xxx%'    and is_ms_shipped = 0;  	0.0143678707510357
13089284	28663	how can i select the most recent input for each member?	select a.* from t1 as a inner join (     select mid, max(time) as maxtime     from t1     where field_1 <> 0     group by mid ) b on a.mid = b.mid and a.time = b.maxtime 	0
13089705	12529	sql query in access that lists values not in both tables	select distinct driverlist.driverid, driverlist.driverlastname, driverlist.driverfirstname from driverlist left outer join transactionreport on driverlist.driverid = transactionreport.driverid where transactionreport.driverid is null 	0.21102359128599
13090452	2478	sql query by using join only	select * from emp e1 join emp e2 where (e2.ename = 'miller' and e1.job = e2.job)  or (e2.ename = 'allen' and e1.sal > e2.sal) 	0.388211538098521
13092632	36486	how can i select nearly distinct rows including the nondistinct columns in mysql (from php)	select count(*) rcount, sum(num_guests) as gcount from (  select  field1, field2, field3, num_guests  from    your_table  group by field1, field2, field3, num_guests ) dup 	0
13094239	2253	mysql select from 2 tables as one value	select   event_avatar from   events union all select   user_avatar from   users 	6.34206446490737e-05
13099038	21162	get max of column using sum	select saleid , sum(amount) as amount from table1 group by saleid having sum(amount) =  (    select max(amount) from   (       select sum(amount) as amount from table1       where date between '10/10/2012' and '12/10/2012'       group by saleid   ) as a ) 	0.00121146595988663
13101971	37957	joining table ids	select upload.*, user.id from cc_hosts_uploads upload inner join cc_hosts_files files on upload.id = files.upload_id inner join cc_host_users user on user.id = files.user_id 	0.00210719580254287
13107979	36205	mysql: see if a value exists in the first 1000	select cme_fbid  from (select * from table1 order by something limit 1000) x where somefield = somevalue 	0.000355050724239543
13108587	15669	selecting primary keys that does not has foreign keys in another table	select u.id from users u left outer join actions a on a.user_id = u.id where a.user_id is null 	0
13108791	450	counting in sql	select    afdeling.afdnavn   , count(medlem.personnr) from   dbo.afdeling join     dbo.medlem on afdeling.afdnr = medlem.afdnr group by   afdeling.afdnavn 	0.14948081954812
13109370	16391	match two columns in sql join	select columnlists from cashstatus cs join atm a on cs.atm = a.atm and cs.device = a.device 	0.0105865047478533
13110393	17168	doing a count along with distinct to check number of times a post was read	select   read_pub_id,   read_artc_id,   count(read_artc_id) as times_read from   reads_t group by   read_pub_id,   read_artc_id; 	0
13111390	16781	how to get first female of each tool, oracle database	select  * from    (         select  row_number() over (partition by tool order by name) as rn         ,       name         ,       tool         from    yourtable         where   gender = 'f'         ) subqueryalias where   rn = 1  	0
13112411	24959	query to find records where a date is between start and end dates, where the dates might be reset to 0	select * from events     where (start_time <= 3600 or start_time>end_time) and end_time > 3600; 	0
13112701	36270	selecting rows that do not match criteria of inner join	select id from tvlinks where id not in (select l.id,     from tvlinks tvl   inner join tvshows tvs   on ( instr(tvl.name, tvs.match )   order by tvl.name ;) 	0.00265461140473119
13112758	29515	select statement subquery	select direct.duser_id, indirect.iminutes, direct.dminutes,      direct.dminutes - indirect.iminutes from     (select u.user_id as iuser_id, sum(m.minutes) as iminutes     from summary s     join users u      on u.user_id = s.user_id     join minutes m      on m.minutes_id = s.minutes_id     join tasks ta      on ta.task_id = s.task_id     where ta.task_type='indirect'     and date(submit_date) = curdate()     and time(submit_date) between '00:00:01' and '23:59:59'     group by u.user_id) as indirect join     (select u.user_id as duser_id, sum(m.minutes) as dminutes     from summary s     join users u      on u.user_id = s.user_id     join minutes m      on m.minutes_id = s.minutes_id     join tasks ta      on ta.task_id = s.task_id     where ta.task_type='direct'     and date(submit_date) = curdate()     and time(submit_date) between '00:00:01' and '23:59:59'     group by u.user_id) as direct where indirect.iuser_id = direct.duser_id 	0.789106039096051
13115889	14498	how to get distinct data along with the code of first distinct data encountered	select column4, min(column2) from tablename group by column4 	0
13115970	16273	doing a select and update inside a mysql event	select read_pub_id, read_artc_id, count(read_artc_id) as times_read from reads_t   group by read_pub_id, read_artc_id;  update reads_totals  set read_total = (select count(read_artc_id) from reads_t rt   where pub_id = rt.read_pub_id   and artc_id = rt.read_artc_id); 	0.441806314582008
13116533	8931	how can i correct my mysql database?	select * from users  join group_members on group_members.id = users.forum_rank join groups on groups.id = users.group_id where user_id = $userid 	0.79145858186084
13118483	35795	get sum of varchar field values by date	select   campaigns.name,   sum(campaign_stats.conv) as num_conv,   sum(cast(campaign_stats.cost as float)) as num_cost,   sum(cast(campaign_stats.cost_conv as float)) as num_cost_conv from   campaigns inner join campaign_stats on campaigns.id=campaign_stats.id_campaign where   date(campaign_stats.day) = date_sub(date(now()),interval 1 day) group by   campaigns.name order by   campaigns.name 	0
13118928	37418	sql new attribute join from another table	select adrid, m.mtitel as attribute from aadress,arel_adr_merk r   inner join vmerkmale m on m.mid=r.mid     where adrid in(" + listdatenids + ")", utildb.conn() 	0.000219356804729569
13121237	41307	best way to get article from a database along with connected tags	select a.id, group_concat(t.name) as tags from articles a left join connections c on c.art_id = a.id left join tag t on t.id = c.tag_id group by a.id 	0
13121742	13317	mysql query: write max(date) from whole table to each row	select  n.* from    news n         inner join         (             select  id, max(lastedited) lastedit             from news             group by id         ) x on n.id = x.id and                 n.lastedited = x.lastedit 	7.70250759383139e-05
13123985	8944	finding differences in values between two samples	select max(`value`)-min(`value`) as `delta` from `expression2` group by `experimid` order by `delta` desc limit 100; 	0.000247292030663985
13125461	25586	mysql lastest rows for multiple keys in one query	select a.* from    dials a inner join         (           select  sn, max(realreaddate) maxdate           from    dials           group by sn           ) b on a.sn = b.sn and                 a.realreaddate = b.maxdate 	0.000823067811450162
13126307	20758	sql query to include an expiration date that falls in a range, but then exclude if they have another instance of the same type	select  s.student_id,          s.fname,          s.address1,          s.lname,          s.zip,          s.state,          s.city,          s.student_type from    students s         inner join          (   select  c.student_id,                      c.cert_type,                      max(expiration) as expiration             from    certifications c             group by c.student_id, c.cert_type         ) c             on s.student_id = c.student_id where   s.student_type not in ('b', 'd', 'e', 'w', 't', 'i') and     c.expiration >= curdate() and c.expiration <= date_add(now(), interval 1 year) group by s.student_id, s.fname, s.address1, s.lname, s.zip, s.state, s.city, s.student_type 	0
13127301	37024	select mysql statement where current time is at least 60+ minutes from timestamp	select * from your_table where datecreated - interval 60 minute <= now() 	0
13127395	3290	need sql result from 3 different tables	select [buyer].username,          [seller].username,          [deals].dealname,          [actions].amount   from [deals]  left join [actions] on [actions].dealid = [deals].dealid  left join [users] as [seller] on [seller].userid = [actions].sellerid  left join [users] as [buyer] on [buyer].userid = [actions].buyerid  where [deals].dealid = 80 	0.00432817014477488
13130276	29531	joining conditionally in mysql	select * from user inner join address on address.userid = user.userid inner join address_type on address_type.id = address.addresstype where addresstype = 4  or not exists (select addresstype from user  inner join address on address.userid = user.userid  inner join address_type on address_type.id = address.addresstype  where addresstype = 4) and primaryaddress = 1 	0.142997951462327
13131110	2323	query two tables with result opposite of join like statement	select * from contacts c left outer join contacts_groups cg on c.id = cg.contact_id  where cg.contact_id is null 	0.446477101544178
13133879	20274	modifying the values in a postgresql database using a time trigger?	select ... from the_table where expiry_time < current_timestamp; 	0.0714374018111209
13134250	9741	two queries: group by column, subtract similar columns, show totals	select "a" as source, qa.org,         qa.jan, qa.feb, qa.dec, qa.total from qa union all  select "b" as source, qb.org,         qb.jan * -1, qb.feb * -1, qb.dec * -1, qb.total * -1 from qb 	0
13134540	14727	converting nested select into join	select count(*) from result r join (select distinct test_id       from test_schedule s       join users u on s.scheduler_id = u.user_id       where u.user_type = 1) s using (test_id) 	0.699687179882073
13134944	6213	sql finding out the common values in two tables	select distinct m.mtitel as attribute from merkmale as m where m.mid in (     select a.mid      from arel_adr_merk as a      where a.adrid in (252674,247354) ) 	0
13135326	21836	sql compare almost equal records	select * from (....) where match(`cross_value`) against ('+тормозн* +диск*' in boolean mode) 	0.0029231313411552
13135540	4322	finding max of two nested aggregate functions in sql	select t.movie,        t.character,        count(t.planet) as countofplanet from   timetable t group  by t.movie, t.character having count(t.planet) = (    select max(countofplanet)    from   (    select movie,           [character],           count(planet) as countofplanet           from   timetable           group  by movie, [character]) q    where  q.movie = t.movie) 	0.243145652337678
13135552	17572	oracle sql how to remove time from date	select  p1.pa_value as startdate, p2.pa_value as enddate from wp_work p  left join parameter p1 on p1.wp_id=p.wp_id and p1.name = 'startdate' left join parameter p2 on p2.wp_id=p.wp_id and p2.name = 'date_to' where p.type = 'eventmanagement2' and trunc(to_date(p1.pa_value, 'dd-mm-yyyy hh24:mi')) >= to_date('25/10/2012', 'dd/mm/yyyy') and trunc(to_date(p2.pa_value, 'dd-mm-yyyy hh24:mi')) <= to_date('26/10/2012', 'dd/mm/yyyy') 	0.00253449830531572
13135580	21868	mysql select related items based on current item	select   tblreview.*,tblusers.user_name from   (       select            max(tblreview.review_id) review_id            , tblreview.user_id       from           (             select                 distinct user_id             from                tblreview             where business_id = 10           ) reviewsb10       inner join            tblreview       on            tblreview.user_id = reviewsb10.user_id       and            tblreview.business_id <> 10       group by            user_id   ) tbllastreviewperuser inner join   tblreview on   tblreview.review_id = tbllastreviewperuser.review_id inner join   tblusers on   tblusers.user_id = tbllastreviewperuser.user_id 	0
13136490	3455	query for show nearest date descending in mysql	select * from `events` order by      case when eventstart >= '2012-10-29' then eventstart else '9999-12-31' end asc,      case when eventstart <  '2012-10-29' then eventstart else null         end desc 	0.00765677096878988
13142299	19134	can i do a count with a mysql join?	select count(distinct `products`.`sku`) as numtotal from `products` inner join `colors` on `products`.`sku` = `colors`.`sku` where `name` in ('apple_black'         ,'black'         ,'black_aubergine'         ,'black_blush'         ,'black_slate'         ,'black_turquoise'         ,'red_black'         ,'sapphire_black'         ,'multi apple'     )     and `status` = '1'     and `category` = 'sig' 	0.432113324347765
13143090	19912	showing results of multiple queries in one table	select emp.empid, ea.employeeaddress, en.employeename    from emp    left join     (       select empid, employeeaddress       from empaddress    ) ea on ea.empid = emp.empid     left join     (       select empid, employeename   from empnames    ) en on en.empid = emp.empid    order by emp.empid 	0.00236875332621032
13143483	20255	reverse effect of join	select * from person left outer join ignoredperson on person.id = ignoredperson.id where ignoredperson.id is null 	0.619870972375842
13143705	17392	select into multiple @variables mysql	select a1.id, a2.id into @photo1, @photo2 from album a1  inner join album a2 on a2.scene=a1.scene and a2.upload=a1.upload and a2.id>a1.id  where a1.uploaded = @time and a1.scene_id = new.id; 	0.0502964627464592
13148003	22595	mssql another way to write a query using in?	select groupname from grouptable  where (groupname like '%motley crue%'  or groupname like '%alvin and the chipmunks%' ) 	0.390448844713419
13149412	14306	custom query counting and grouping dates	select count(date_modified) as total, datediff(date_modified, now()) as days_ago from mytable group by date_modified; 	0.0606391605555055
13150356	15372	how to display the first row, depending on a value	select *   from ( select *, rn=row_number() over (partition by [product#] order by [datetime] desc)   from tests      ) x  where rn=1 and result = 'pass'; 	0
13150915	10083	sql - average number of records within a time period	select customer_id,  count(date_created), avg(revenue) from table t  join ( select customer_id,  min(date_created) as min_date from table t where loan_status = 'approved' group by customer_id ) s  on t.customer_id = s.customer_id  where t.date_created between s.min_date and dateadd(month, 4, s.min_date) and t.loan_status = 'approved' 	0
13151928	9422	show first instance of records with duplicate values in colum	select  a.* from    gallery_images a     inner join     (         select gallery_id, min(id) id         from gallery_images          group by gallery_id     ) b         on a.gallery_id = b.gallery_id and             a.id = b.id 	0
13154985	16062	oracle select on single table	select distinct name    from table  where name not in (select name from table where folder_name = 'popular') 	0.0159338811059257
13155049	31531	mysql select bit field, select value with 0 in front	select lpad(field,4,'0')  from `table` where value=0001; 	0.0157618028518957
13155212	35781	join tables and select entries < x hours	select  * from    games g join    prices p on      p.gameid = g.id         and date_sub(g.starttime, interval 24 hour) <= p.pricetime          and p.pricetime <= g.starttime 	0
13155462	14367	fetch posts from non blocking users	select *   from post   where user_id not in      (select blocker_id      from blockings     where blocked_id = 1); 	8.05158017722902e-05
13155988	40351	finding week number in a month in oracle	select to_char(your_date,'w') from dual; 	0
13156064	1738	my select query removing duplicate row	select tcs.tutor_id, tcs.category_id, tcs.subject_id, group_concat(s.subjects) as subjects,  t.tutor_name, t.tutor_code from tutor_category_subject as tcs inner join subject as s on tcs.subject_id = s.subject_id inner join tutors as t on tcs.tutor_id = t.tutor_id where s.subjects like '%business%' group by t.tutor_name; 	0.0304204357452621
13156353	15934	mysql, php, how many in group	select *, count(*) as count from logins group by user order by timestamp desc 	0.226080497521612
13156964	40486	how to select clients who signed contracts with all subsidiaries?	select u_r2.uid from       (select uid            , count(distinct subsidiary) as u_subs      from r2      group by uid )  u_r2   ,      (select count (distinct subsidiary) as tot_subs      from r2) sub_r2 where sub_r2.tot_subs = u_r2.u_subs; 	0.00137501627794797
13157590	4506	i want to add values from diffrent colums	select sum(no_of_days) from leave; 	0.000409610157837753
13158603	19226	select 100 records in range	select a.* from (      select row_number() over(order by table.mysortcol) as rownum,      table.*       from table ) a where a.rownum between 1 and 100 	0.00107611057092421
13159879	37174	sql select data	select pd.saleid,        pd.firstpaymentdate                               as firstpaymentdate,        (select amountdue         from   repaymentschedule         where  saleid = pd.saleid                and paymentduedate = pd.firstpaymentdate) as firstpaymentvalue,        (select top 1 amountdue         from   repaymentschedule         where  saleid = pd.saleid                and paymentduedate <> pd.firstpaymentdate                and paymentduedate <> pd.lastpaymentdate) as regularpaymentvalue,        (select amountdue         from   repaymentschedule         where  saleid = pd.saleid                and paymentduedate = pd.lastpaymentdate)  as finalpaymentvalue from   (select saleid,                min(paymentduedate) as firstpaymentdate,                max(paymentduedate) as lastpaymentdate         from   repaymentschedule         group  by saleid) pd 	0.131572772709551
13160877	12379	mysql query with two inner join returns duplicate entries in the result	select   users.id,   users.username,   maxpublished from users inner join (   select     max(articles.published) as maxpublished,     articles_users.user_id as userid   from articles   join articles_users on articles_users.article_id = articles.id   group by articles_users.user_id ) as p on users.id = userid order by maxpublished desc limit 25 ; 	0.00427100107187397
13161044	26359	checking if a given date fits between a range of dates	select startdate, enddate from yourtable where '2012-10-25' between startdate and enddate 	0
13162249	7700	sort by multiple keys a sql table and save top 10 results	select name, city, points from ( select name, city, points,    @namerank:=case                 when @name <> name then 1                 else @namerank+1 end as rn,    @name:=name as name_set from   (select @namerank:= -1) nr,   (select @name:= '-1') n,   (select * from test order by name, points desc) t   ) x where rn < 11 	0.000326912258886665
13162953	40920	simple query return the same register	select top 1 ch.recibo   from san_chavebematech ch   join san_cadastrabematech ca     on ch.credenciada_id = ca.credenciada  where ca.maquina = '000feab63d89'    and ch.impresso = 0; 	0.0750613914274632
13163357	25046	get subset of query result	select user from   request where  job in (34,35) and `fulfilled` is null  group by user having count(distinct job) = 2 	0.00518752852003379
13163955	2859	find row which has unique values with respect to some of its columns	select * from table where id in (select min(id) from temp group by value1,value2,value3,value4) 	0
13164215	20244	display column names with out datatype in mysql	select column_name from information_schema.columns where table_schema = 'db_name' and table_name = 'your_table' 	0.00060458727540363
13165785	25427	calculate hours between two dates	select (unix_timestamp(end) - unix_timestamp(start)) / 60.0 / 60.0 as hours_difference 	0
13166063	3827	multiple count based on dynamic criteria	select id, sum(t1) as table1, sum(t2) as table2 from     (select id, count(id) as t1,         0 as t2 from tab1 group by id      union all      select id,         0 as t1, count(id) as t2 from tab2 group by id) group by id having sum(t1)>0 and sum(t2)>0 	0.00318151233681262
13166352	1679	sql (access): multiple values per "id" - store as true unless any false	select internal.participantid, max(internal.internal) as maxofinternal from internal group by internal.participantid; 	0.00146005599431292
13167161	747	i want to show members where membership has been expired, i'm using two tables with a join	select      m.firstname, m.lastname,     m.socialsecuritynumber, m.mobile, m.email,     ms.todate from members as m     left outer join (         select t.memberid, max(t.todate) as todate         from memberships as t          group by t.memberid     ) as ms on ms.memberid = m.id where ms.todate < '2012-10-31' or ms.todate is null 	0.00295319895951908
13167723	32133	mysql add days to column field if on weekday	select     pmday as entereddate,     case date_format(pmday, '%w')         when 'saturday' then date_add(pmday, interval 2 day)         when 'sunday' then date_add(pmday, interval 1 day)         else pmday     end as followingmonday ; 	0
13167948	19917	exclude value of a record in a group if another is present	select    id,    case       when count(case mark when 'c' then 1 else null end) = 0       then          sum(amount)      else          sum(case when mark <> 'a' then amount else 0 end)   end from sampletable group by id 	0
13168483	19967	how to select more rows from subquery	select * from `activity`               where user_id = 1 and activity_id not in (                      select activity_id from activity where user_id = 1                                          order by activity_id desc limit 8) 	0.00669656317039896
13168557	3438	sql oracle combining multiple results rows	select  case upper(device_model)     when 'iphone' then 'ios - iphone'     when 'ipad' then 'ios - ipad'     when 'ipod touch' then 'ios - ipod touch'     else 'android'     end as device_model, count(create_dtime) as installs_oct17_oct30 from player where create_dtime >= to_date('2012-oct-17','yyyy-mon-dd') and create_dtime <= to_date('2012-oct-30','yyyy-mon-dd') group by case upper(device_model)     when 'iphone' then 'ios - iphone'     when 'ipad' then 'ios - ipad'     when 'ipod touch' then 'ios - ipod touch'     else 'android'     end order by device_model 	0.0327921216028606
13168579	7085	convert year hour date interval to number of days	select to_days('2012-11-03') - to_days('2012-01-01'); 	0
13168929	6143	sqlite syntax for "all"	select name  from table  where number >= (select max(another_number) from another_table where ...) 	0.472111728966427
13169119	34970	how to query a range of columns mysql	select column5, column6, column7 from table   	0.000769782590285867
13169131	32210	mysql query for events over the last 14 days (fortnightly)	select * from event_log where date >= date_sub(now(), interval 14 day) 	0
13171867	18943	mysql query grouping from one table, excluding results found in another sub query	select appaddon, count(id) from downloads where not exists (   select appaddon from addons   where downloads.appname = addons.appname   and downloads.appaddon = addons.appaddon) group by appaddon 	0.00027958383425754
13172228	33798	require if in where condition sql	select * from tab1 where (@key_char = 'a' and key_column='a') or       (@key_char <> 'a' and key_column <> 'a') 	0.790827332311347
13172468	36245	mysql select rows until fixed number of condition is reached	select * from tables where id <= ( select id from ( select id from tables where fruit='banana' order by id limit 2) a order by id desc limit 1 ) 	0
13173183	1922	find sql server 2008 computed column dependency	select name, definition  from sys.computed_columns 	0.0345315880344447
13173615	29257	normalizing values in sql query	select     projectid,     avg(cast(foo as decimal(29, 2))) / max(avg(cast(foo as decimal(29, 2)))) over () from tbl1 group by projectid 	0.423919934838371
13174168	18148	using select distinct with multiple columns but all columns musnt be distinct	select distinct on (a.personalid, a.fileid) a.personalid, a.fileid, a.name, a.surname, a.address from my_table a 	0.000385597353210397
13174208	8695	sql reverse column value query	select t1.* , t1.colc-t2.colc from yourtable t1     inner join yourtable t2        on t1.cola = t2.colb        and t1.colb = t2.cola where t1.cola <> t1.colb 	0.0585669330804933
13175194	17396	oracle right join 3 tables but only has to match 1	select p.id,   p.name,   a.price price_a,   b.price price_b,   c.price price_c from products p left join pricea a   on p.id = a.product_id left join priceb b   on p.id = b.product_id left join pricec c   on p.id = c.product_id where a.price is not null   or b.price is not null   or c.price is not null 	0.0100833950673492
13176420	17691	sql select query with group and status (sql server 2008)	select     g_id as groupid,     case         when min(status) = -1 then 'failed'         when max(status) = 2 and min(status) = 1 then 'in progress'         when max(status) = 1 and min(status) = 1 then 'success'     end as status from table1 group by g_id 	0.648607212328309
13176638	35371	order by most of items with join	select people.id, count(items.active) as items_count from items left join people on  people.id = items.person_id where items.active = true group by people.id order by items_count desc 	0.00454808897910668
13177192	29735	t-sql format seconds as hh:mm:ss time	select convert(varchar(10),seconds/3600)       +':'      + right('00'+convert(varchar(2),(seconds%3600)/60),2)      +':'      + right('00'+convert(varchar(2),seconds%60),2) as [hh:mm:ss]  from table1 	0.0104694246578058
13178261	24766	mysql exists return 1 or 0	select if(exists(...),1,0) as result 	0.191143158611806
13179077	14840	mysql calling a procedure with select statements from a trigger - "not allowed to return a result set from a trigger"	select fpkm, ( (rank / @row) *100 ) as percentile into fpkm, percentile 	0.411181029430491
13179681	19746	use mysql to create a string out of a subquery?	select name, group_concat(position) result from tablename group by name order by `index` 	0.158410469896817
13181101	4273	getting the sum of three rows from one column?	select user, sum(hours) totalhours from tablename group by user 	0
13181306	35903	limit sql query and rank according to total	select sales_id, totalbuy, totalsell, totalbuy + totalsell as total from (select owner_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 sales_id   where sales_id in ('sales1', 'sales2', 'sales3', 'sales4') group by sales_id)q order by total desc limit 0, 10; 	0.00329371064947307
13181692	19946	need comma seperated output for a query fetching mutiple rows	select listagg(o.candidateid) within group () ..... 	0.00361995517894436
13181966	33667	sql: comparing max dates from two different tables	select u.groupid, u.username, py.lastpaymentdate, at.lastattendencedate from user as u, (select username, max(attendencedate) as lastattendencedate from attendence group by username) as at, (select groupid, max(paymetdate) as lastpaymentdate from payment group by groupid) as py where u.username=at.username and u.groupid=py.groupid and py.lastpaymentdate < at.lastattendencedate; 	0
13182671	21050	sql server 2000 : return a value when no record is returned	select a.itemno, ifnull(i.description, 'n/a') from (     select '1500' as itemno     union all select 'part'     union all select 'numbers' ) a left outer join items i on a.itemno = i.itemno 	0.00626365599756581
13183322	14845	filter out duplicate entries in report in oracle 11g	select * from (   select score(1) relevance,   "pkey",   "date_sub",   "client",   "candidate",   "recruiter",   "sales",   dbms_lob.getlength("resume") "resume",   "mimetype",   "filename",   "position",   "availability",   "rate",   "issues",   "when_int",   "feedback",   "notes",   row_number() over (partition by candidate, recruiter order by pkey) rn   from "submittals"   where contains (resume, :p11_search, 1) > 0   )  where rn = 1  order by 1 desc 	0.00305944863746943
13184325	10996	reference 2 rows on same column/table, from a different table	select     away.name as awayteam,     home.name as hometeam from     game_schedule gs     join team away on t.id = gs.awayteam_id     join team home on t.id = gs.hometeam_id 	0
13184804	32611	setting defaults for empty fields returned in select	select c2.title as c2__title,         coalesce( nullif( c2.desc, '') , c3.desc )   as desc,         coalesce( nullif( c2.lang, '') , c3.lang  )  as lang,  from   image c  left join image_translation c2                on c2.lang = 'fr' and c.id = c2.id  left join image_translation c3               on c3.lang = 'en' and c.id = c3.id  where  ( c1.name = 'file.jpg' ) 	0.28481797485025
13186348	15828	select all rows that contain a url	select * from comments where content like '%<img%' 	0.00066743223731674
13187291	27067	oracle get first preceding and following rows ordered by time in another table	select distinct a.id, a.timestamp, b0.timestamp, b1.timestamp from a, b b0, b b1 where b0.timestamp = (select max(timestamp) from b where timestamp < a.timestamp) and b1.timestamp = (select min(timestamp) from b where timestamp > a.timestamp); 	0
13187664	4521	sql query for multiple tables (foreign keys involved)	select * from course  inner join major_courses_xref on course.id = major_courses_xref.course_id  inner join majors on major_courses_xref.majors_id = majors.id  inner join courses_semester_xref on course.id = courses_semester_xref.course_id  inner join semester on courses_semester_xref.semester_id = semester.id; 	0.00457510118964309
13188145	3099	how to order a a content in ascending order in a database field (sql)	select q.questionid,group_concat(distinct answer                                    order by answer                                    separator '') as answer     from question q     join answer an on q.questionid = an.questionid group by an.questionid 	0.00143576290286031
13188667	21567	determining most used set of words php mysql	select aword, count(*) as wordoccurancecount from (select substring_index(substring_index(concat(somecolumn, ' '), ' ', acnt), ' ', -1) as aword from sometable cross join ( select a.i+b.i*10+c.i*100 + 1 as acnt from integers a, integers b, integers c) sub1 where (length(somecolumn) + 1 - length(replace(somecolumn, ' ', ''))) >= acnt) sub2 where sub2.aword != '' group by aword order by wordoccurancecount desc limit 10 	0.00618555941472823
13189267	30212	add string to mysql result	select bk_id, bk_rtype, villas_db.v_name as villa_name, concat( 'b', bk_rtype, '-', lpad( bk_id, 5, 0 ) ) as booking_no from booking_db inner join villas_db on booking_db.bk_vid = villas_db.v_id where '2012-11-02' between bk_date1 and bk_date2 order by bk_id desc limit 0 , 30 	0.0412512282890017
13192092	8926	sql server : convert char to float and round it	select cast(value as decimal(9,2))  from workflow... 	0.273322962825373
13192736	33852	writing a select query to deduct one table from another	select  a.* from    tablea a         left join tableb b           on a.id = b.tblone_id and               b.userid = 50 where   b.tblone_id is null 	0.000619680555743497
13199425	16908	multiple conditions on select query	select pr.volume_uom  ,pr.length_mm*pr.width_mm*pr.height_mm as volume_cubic  ,pr.length_mm*pr.width_mm as volume_floor  ,pr.length_mm  ,pr.height_mm  ,pr.width_mm from costtoserve_mcb.staging.sale sa left join staging.product pr on sa.id = pr.id and pr.length_mm is not null and pr.width_mm is not null and pr.height_mm is not null 	0.157813392715219
13200445	19487	reversing yes/no field during select in access	select obsolete_flat+1 as isactive 	0.0559669380867873
13200720	30035	union select sql statement returns duplicate results	select personid,           max(case when typeid = '28321161-668e-4a56-90be-67a146fa1353'                    then phonenbr end) homenum,           max(case when typeid = '02a4125b-b968-4dc6-9734-7f75f45f7635'                    then phonenbr end) officenum     from       phonehub     where        phonehub.franid = @franid     group by personid 	0.300335048648797
13201298	37284	mysql group by and where	select monthname(birthdate) as month, count(*) as howmany from tblbday group by month(birthdate) having count(*) > 1  ; 	0.452298785247473
13202107	3405	database pool with pgpoolingdatasource?	select * from pg_stat_activity 	0.64061903209251
13205238	34094	mysql selecting certain rows depending on if/case statement	select a.id, a.status, a.gid, a.uid, a.note from notes a left join friends f on f.uid = a.uid and f.fid = $_session[uid] where (a.status = 2 and f.approved = 1) or a.status = 3 or (a.status = 4 and f.gid = a.gid) order by a.id desc limit 10 	0
13205615	7598	advanced sql sum column from a same table	select name, sum(case categ when 3 then 0-quan else quan end) as quan from thetable group by name 	0.00127424627746643
13207676	25067	get data from 2 tables (mysql)	select id,locator,name,price, tablename from  (   select a.id as id, a.locator as locator, a.name as name,       a.price as price, a.ibutik as ibutik, 'closes' as tablename      from  clothes a   union all   select b.id,b.locator,b.name,b.price,b.ibutik,'items' from items b  ) foo where ibutik=0; 	0.000213571307297719
13209021	31394	return random image sql	select distinct `item_images`.`filename` as `url` from `item_images` inner join `item_link` on `item_images`.`item_id` = `item_link`.`item_id` where `item_link`.`category_id` = 1  group by `item_link`.`item_id` order by rand() limit 4 	0.0316438927192137
13209289	33701	remove almost duplicate rows	select     t1.val1,t1.val2 from table as t1 join table as t2 on (     (t1.val1=t2.val2) and (t1.val2=t2.val1) ) where t1.val1<=t1.val2 	0.00190715399639773
13209331	31616	how to split the row value	select rtrim(substring(value, 1, charindex( 'x' , value, charindex( 'x', value) + 1) - 2)) from (select value     from table1     where len(value) - len(replace(value, 'x', '')) >= 2) as temp union all  select substring(value, charindex( 'x' , value, charindex( 'x', value) + 1) + 2, len(value)) from (select value from table1 where len(value) - len(replace(value, 'x', '')) >= 2) as temp1 	0.000211810643739755
13210405	18046	join 2 tables with known variable sorting by max(date)	select t.tid, t.pid, t.eid, e.ename, t.date   from transfers t   join equipment e on t.eid = e.eid  where t.pid = ?    and t.date = (select max(t2.date) from transfers t2 where t2.pid = ? ) 	0.0427504748052686
13211382	26024	how to display answers and text inputs within each row	select q.questionid, q.questioncontent, an.answer from question q inner join answer an on q.questionid = an.questionid where s.sessionname = ? order by q.questionid, an.answer 	0
13214601	24968	mysql query: how to sum 3 different values in a column, showing total of each value in result set	select item,    sum(case when `condition` = 'poor' then 1 else 0 end) as poor,    sum(case when `condition` = 'fair' then 1 else 0 end) as fair,    sum(case when `condition` = 'good' then 1 else 0 end) as good from inventory  group by item 	0
13215072	27385	how to find data from last week in mysql	select  studentid,          date_format(`date`, '%u') `weekno`,         count(studentid) totalmissed from hw_homework he where date_format(`date`, '%u') =  (select max(date_format(now(), '%u')-1)   from hw_homework hi   where hi.studentid = he.studentid) group by studentid, date_format(`date`, '%u') 	0
13216068	2982	mysql query to return avg	select maker, avg(hd) from pc, product where pc.model=product.model and product.maker in     (select distinct maker from product where type='pr') group by product.maker; 	0.28520699101518
13217854	19619	sql query combined column values	select t1.object from table t1     inner join table t2 on t1.object = t2.object where t1.attribute = 'country' and t1.value = 'germany'     and t2.attribute = 'position' and t2.value in (12,5) 	0.0345319021338365
13218355	16198	mysql query: retrieve some rows based on keys in another table	select t1.a1, t1.b1, t1.c1, t1.d1 from table1 t1 left join table2 t2 on t2.table1_row_id = t1.id where t2.id is null 	0
13220351	27671	mysql query to fetch records	select t.team_id  from yourtable t order by t.win + t.run_scored desc limit 1 	0.00653848096879284
13222017	9038	mysql - select grouped values	select ad_id from value where (attribute_id,value) in ((5,'yamaha mate v50'),(6,'2012')) group by ad_id having count(*)=2 	0.00765709843113835
13222602	22299	the min () to improve	select u.id, count(*) from user_ as u join order_ as o on (u.id=o.employee_id) group by u.id order by 2 limit 1 	0.566798548328136
13226070	7090	sql select all the orders for employees with minimum sales	select employees.eno, employees.ename, sum(odetails.qty * parts.price) as sales from employees join  orders on employees.eno = orders.eno join  odetails on orders.ono = odetails.ono join  parts on parts.pno = odetails.pno group by employees.eno, employees.ename 	0
13226351	8349	how to retrieve the column value based on formula	select a.id,   (case when patindex('%z1%', isnull(b.formula1,'')+isnull(b.formula2,''))<>0 then a.z1 else null end) z1,   (case when patindex('%z2%', isnull(b.formula1,'')+isnull(b.formula2,''))<>0 then a.z2 else null end) z2,   (case when patindex('%z3%', isnull(b.formula1,'')+isnull(b.formula2,''))<>0 then a.z3 else null end) z3,   (case when patindex('%z4%', isnull(b.formula1,'')+isnull(b.formula2,''))<>0 then a.z4 else null end) z4,    b.*  from table1 a inner join table2 b on a.type=b.type 	0
13226399	39005	how can i write a query that returns "between" to return alphabetic data, not just numeric?	select  customer_id, account_id,current_balance  from daily_account  where cast(right(account_id,(length(account_id)-1)) as unsigned)  between '1' and'100' 	0.0265187277642542
13227175	26639	mysql group concat single column null	select item_num,         replace(group_concat(ifnull(item_desc,' ')), ', ,', ',') as alldesc  from table1  left join table2  on table1.id = table2.oneid 	0.0668720095054586
13228375	24099	mysql query to delete results using loop id	select *  from students_subjects a  left outer join students_info b on a.student_id = b.student_id left outer join groups c on b.class_id = c.group_id left outer join teacher_groups_subjects d on c.group_id = d.group_id where b.student_id is null 	0.0780183868178593
13228447	22287	getting duplicate count and data from table	select name from table group by name having count(*) > 1 	0.000211796097039502
13229052	14951	mysql: combination of group by , order , max. get maximum value of grouped set and apply a condition	select  count(*),a.user_id,a.customer_id,    if(max(a.date_booked)>now(), b.date_booked, max(a.date_booked)) as date_booked from reservations a left join     (select max(date_booked) as date_booked,customer_id          from reservations where date_booked < now() group by customer_id) b on a.customer_id=b.customer_id where a.user_id=1  group by customer_id 	0
13232097	12459	how i can get 0 for no records using mysql?	select uq.timespan, coalesce(tsq.totalclicks, 0) as clicks from ( select '22-28 days ago' as timespan union select '15-21 days ago' union select '8-14 days ago' union select 'up to 7 days ago' )uq left join ( select case      when period >= now() - interval 4 week                 and period < now() - interval 3 week then '22-28 days ago'     when period >= now() - interval 3 week                 and period < now() - interval 2 week then '15-21 days ago'     when period >= now() - interval 2 week         and period < now() - interval 1 week then '8-14 days ago'     when period >= now() - interval 1 week then 'up to 7 days ago'            end weekperiod,             count(clicks) totalclicks from table where period >= now() - interval 4 week group by weekperiod )tsq on uq.timespan = tsq.weekperiod 	0.00293809378566007
13232206	14921	mysql query where result of one column row is added with next one	select a.app_id, (select sum(amount) from abc b where a.date = b.date and b.app_id <= a.app_id) amount, a.date  from abc a; 	0
13235491	39725	mysql find duplicates	select t1.* from mytable t1 inner join mytable t2 on t1.apples = t2.apples where t1.oranges in ('f', '-') and t2.oranges = 'p' 	0.039316452385818
13235847	24927	coalesce() for blank (but not null) fields	select ifnull(nullif(field1,''),field2) 	0.574106405878693
13237477	10541	how do i retrieve decimals when rounding an average in sql	select round(avg(cast(column_name as float)), 2) from [database].[dbo].[table] 	0.0186924357656398
13237633	23825	mysql group selected rows on select	select room,        sum(seats) as seats,        sum(occupied) as occupied from your_table group by case when room in ('b2', 'c3', 'd4')                then 'b2c3d4'               else room          end 	0.00531634971935988
13237909	3752	display days ago instead of date	select p.poll_id, p.title,  datediff(now(), c.posted) as daysold, count( c.poll_id ) as   count, u.username   from users as u   join polls as p on u.user_id = p.user_id   left join comment as c on p.poll_id = c.poll_id   limit 5 	0
13238280	1657	in sql, how do i get the awards total for each player	select a.name, count(*) as total from awards a where a.playerid = 1 group by a.name order by count(*) desc 	0
13238464	35703	group data based on certain value	select xid, repeat_status from x  group by xid,repeat_status 	0
13238580	29551	sql where condition not returning rows specified	select @command =  'select distinct c.fileid, c.filename, convert(nvarchar,c.datereported,111) as ''datereported'',  c.filedetailsplaintext, cfit.level3 as ''investigationtype'', inv.fname + '' '' + inv.lname as ''name'',  convert(nvarchar,dd,111) as ''dd'', i.firstname + '' '' + i.lastname as ''reportedby'' from casefiles c  join investigatorcasefileaccess ia on c.fileid=ia.casefileid  join casefiletimebills tb on c.fileid=tb.fileid join casefileexpenses e on c.fileid=e.fileid left join element07a_persons i on i.personid = c.personid left outer join casefileinvestigationtypes cfit on c.investigationtypeid = cfit.investigationtypeid  left outer join investigators inv on c.investigatorid = inv.investigatorid where deleted=0 and ia.investigatorid=' + convert (nvarchar(max),@investigatorid) + ' and ia.allowaccess = ''true''  and (tb.invnumber is null or e.invnumber is null)' end 	0.292505531363152
13239312	4089	return 4 separate counts for single column in ssrs dataset	select count (*) as total,    sum (case when color='bl' then 1 else 0 end) as bluetotal,    sum (case when color='rd' then 1 else 0 end) as redtotal,    sum (case when color='yl' then 1 else 0 end) as yellowtotal,    sum (case when color='gr' then 1 else 0 end) as greentotal from colors 	0.000217448813847358
13242892	11592	sql query using group by	select job, deptno, count(*) as people from emp group by job, deptno 	0.682790330199577
13244832	28982	sql server 2000 query of total value and value from max date	select  room ,sum(aphase) as totalaphase ,sum(bphase) as totalbphase  ,isnull((    select top 1 rt1.acount               from roomtable rt1               where rt1.room = rt.room                  and rt1.acount != -1              order by rt1.date desc ), 0) as acount ,isnull((   select top 1 rt2.bcount              from roomtable rt2             where rt2.room = rt.room                 and rt2.bcount != -1             order by rt2.date desc ), 0) as bcount from roomtable rt group by room order by room 	0
13245390	30700	removing parameters from where clause to display records	select project_id,    case when location = ? then 1 else 0 end +    case when flats = ? then 1 else 0 end +     case when builder = ? then 1 else 0 end as score from project order by score desc 	0.00415538549792938
13246561	2999	select data vice versa	select u.id,u.name from user u left join ( select accountid as aid , linkaccountid as sec from account union select linkaccountid as aid,accountid  as sec from account ) a  on a.aid=u.id where @searchuser in (coalesce(a.aid,u.id),coalesce(a.sec,u.id)) 	0.0427122712851314
13246598	1249	join two tables and group by xyz	select distinct ref, status from (     select ref, status     from table1     union all     select ref, status     from table2 ) x 	0.0591017943156673
13250531	37282	retrieve time from mysql as hh:mm format	select date_format(date_column, '%h:%i') from your_table 	0.000249756545886418
13250660	12504	query the second table with the result of first	select   s.* from students s inner join studentmarks m on s.studentid = m.studentid ; select   m.* from students s inner join studentmarks m on s.studentid = m.studentid ; 	0
13250851	37360	how to detect a faulty sequence column with sql?	select id,seq        from(             select id,seq,                    row_number() over (partition by id order by seq ) rn             from t_seq)a where a.seq<>a.rn 	0.131954074394616
13252567	35866	sql - how to selectively select by combining multiple conditions?	select  * from    tablename where   (type = 1) or         (             type = 2 and             saledate >= stockdate         ) 	0.0480615586356084
13252966	3068	fastest get data from remote server	select * 	0.00932647704452565
13253050	30054	mysql select row from two tables even though only one table may have the row	select col1,col2,..  from pages  where slug = 'about'  union select col1,col2,..  from posts  where slug = 'about' 	0
13253445	31280	select part of column	select right(criteriadata,               len(criteriadata) - charindex('15', criteriadata, 1) - 2) from tablename where criteriadata like '%15%'; 	0.0108684448029797
13255030	34833	how to use the data dictionary	select * from user_ind_columns 	0.100590548314956
13255566	24756	sql - select ids from two different tables	select table1_id, table2_id from  (    select id as table1_id, null as table2_id, date from table1    union all    select null as table1_id, id as table2_id, date from table2  ) order by date desc  limit 30 	0
13256947	3537	mysql subquery returning more than one result	select * from events where id_events in ( select id_events from relationship_events where id_user = ?) 	0.138231154428037
13258990	40918	oracle sql to count instances of different values in single column - continuation	select * from (   select tkey, status,      decode(status, 30, 30, 40, 30,status) as col   from tableb b   left join tablea a     on a.fkey = b.fkey ) src pivot (   count(status)   for col in ('20' as count_status20,                '30' as count_status3040,               '50' as count_status50) ) piv; 	0
13260335	22292	querying many-to-one in mysql	select co.coordinate_name, cl.name_client, s.title_solution, p.title_project from coordinate as co inner join project as p on co.project_id_project = p.id_project inner join solution as s on p.solution_id_solution = s.id_solution inner join client as cl on s.client_id_client = cl.id_client where co.date between ? and ? 	0.322104068943947
13267597	1456	an efficient way to store <select>'s options in a database?	select_name 	0.449837849843272
13269317	4616	sql selection statement	select c.actor from casts c,  join films f on c.filmid = f.filmid join remakes r on r.priorfilm = f.filmid join casts c2 on c.actor = c2.actor and r.filmid = c2.filmid 	0.728564123597327
13270733	33060	sql - distinct case-insensitive collation query - retrieve lower case row instead of first	select     min(t.col1 collate sql_latin1_general_cp1_cs_as) from dbo.table as t group by t.col1 collate sql_latin1_general_cp1_ci_as 	0.0404399749718156
13272230	2678	mysql - sum columns from multiple tables based on multiple id's	select id, id2, sum(views), sum(hits) from (     select id, id2, views, hits     from table1     union all     select id, id2, views, hits     from table2     union all     select id, id2, views, hits     from table3 ) x group by id, id2 	0
13272347	15868	sql select rows only once	select * from pro group by `category` 	0.000467082888995215
13274628	35028	sql server - count characters between two characters	select startchar, endchar, ascii(endchar) - ascii(startchar) as diff from exampledata 	0.0180230892216672
13275431	16098	finding the total amount for my query	select id, orderid, item, price from customerorders where [order] = 1 union all select null, null, null, sum(price) from customerorders where [order] = 1 order by case when id is null then 2 else 1 end, id; 	0.000563665797607588
13275706	16439	get average time between several dates for one entry	select avg(date_completed - date) from mytable 	0
13276404	32212	mysql run second query based on time stamp of an id from first query	select id, text, stamp from test  where stamp < (select stamp from test where id=1); 	0
13277549	7341	sql server exclude anything but a number	select a.value from yourtable a where a.value like '[0-9]%' 	0.041186586665022
13277646	5650	sql grouping by predefined date range	select      week(created),     sum(case when status = 1 then 1 else 0 end) status1,     sum(case when status = 2 then 1 else 0 end) status2,     sum(case when status = 3 then 1 else 0 end) status3,     sum(case when status = 4 then 1 else 0 end) status4,     sum(case when status = 5 then 1 else 0 end) status5 from contacts group by week(created), year(created); 	0.00577647643166192
13279901	34151	grouping by week in sql, but displaying full datetime?	select datepart(wk, createdon) week, createdon from tablename group by datepart(wk, createdon), createdon 	0.00927570383263472
13280016	34321	sql - how to query parent child records by descending timestamp	select c.* from comments c order by   coalesce(parentid, id) desc,   parentid is not null,   timestamp desc 	7.32848224444598e-05
13280875	7601	join on array of ids in sql	select distinct     contract_name,     room_name from     promos inner join     contracts on find_in_set(contracts.id, contract_id) != 0 inner join     rooms on find_in_set(rooms.id, room_id) != 0 where     promos.id = 1 	0.00367188121807511
13281628	33228	select into local variable undeclared?	select count(*) into @rowcount from ... 	0.435082634484173
13283044	15198	how to show data for each week in android?	select strftime('%y-%w',_id) as week_of_year, sum(value) as total         from pd_table         group by week_of_year order by _id desc 	0
13283099	8941	how to get data from table using select query	select p1.* from po_details p1 join (     select min(id) order_id,  po_id ,  part_id      from po_details     where po_id =3      group by part_id, po_id ) p2 on p1.part_id = p2.part_id and p1.po_id = p2.po_id order by p2.order_id,p1.id 	0.000641290757034927
13284054	17063	mysql query- for each date max 3 datas	select a.* from table1 a inner join table1 b on a.start_date = b.start_date and a.event_id <= b.event_id group by a.event_id,a.start_date having count(*) <= 3 order by a.start_date 	0.000180277699058829
13284410	28008	in sql how to write sub query which provides two value in where clause	select      * from      releases,     (select          min(id) as x,          max(id) as y      from         releases      where released > "2011-12-01"      ) as d    where     id between d.x and d.y limit 0,30 	0.684788189846938
13285885	5369	sql: return comments from other users that occur after my comment on a post i didn't create	select     posts.* from     posts         inner join         (             (                 select h1.parent_id, min(h1.create_dte_timestamp) as min_date                 from posts h1                 where                     h1.parent_id != -1 and                     h1.user_id = user_id and                     h1.parent_id not in                     (                         select h2.id                         from posts h2                         where h2.id = h1.parent_id and h2.user_id = user_id                     )                     group by h1.parent_id             )         ) lastpost         on posts.parent_id = lastpost.parent_id where     posts.create_dte_timestamp > lastpost.min_date and     posts.user_id != user_id 	0
13286261	33262	mysql: how can i get min value from table with duplicate rows?	select group, idx, name, price     from table     where group = 141003     order by price asc     limit 1; 	0
13288090	17087	mysql how to make negative results possible when subtracting unsigned values?	select (least(cast(`a`.`price` as signed), cast(`b`.`price` as signed)) - cast(`c`.`price` as signed)) as `diff` ... order by `diff` desc 	0.0111306496909732
13288232	7483	showing in a table the last different users	select *  from   (select operator,                 typeop          from   tbl          where  `time` > ( now() - interval 3 minute )          order  by `time` desc) as `a`  group  by `operator` 	0
13288501	31984	how to make a order list of raw database data	select product, count(*) as count from test group by product 	0.00861754451010464
13288794	20621	mysql - join and group by	select distinct recipientid from messages where senderid = 4 union select distinct senderid from messages where recipientid = 4 	0.543469811766866
13288909	4292	retrieve information from two different tables	select s.s_name, count(*)  from staff s  inner join research r  on s.s_id = r.s_id  group by r.s_id 	0
13290105	13628	selecting top results from sql count query, including table join - oracle	select * from ( select customer.company_name, count (item.pickup_reference) as "number of pickups"  from customer join item on (customer.reference_no=item.pickup_reference)  group by customer.company_name, item.pickup_reference order by count (customer.company_name) desc )  where rownum <= 10 	0.00153545576673347
13291601	40007	sql. remove from results some rows depending of one field	select user.id, campaign_id, user_id from user left join email_solus on email_solus.user_id=user.id where user.id not in (     select user_id     from email_solus     where campaign_id = 3 ) 	0
13291949	37504	union of sql tables, but only taking the first instance of an id	select id, first(c1) as c1, first(c2) as c2 from (   select * from table1 union select * from table2 union select * from table3 ) group by id 	0
13292631	39057	database query to handle when specific rows don't exist	select          team_id         ,sum(rebs) rebs     from         (             select                    case when team_id <> 100 then -999 else 100 end as team_id                 , isnull(off_reb,0)+isnull(def_reb,0) rebs             from                  v_stats_comp             where                  comp_id in (select comp_id from competitions where home_id = 100 or vis_id = 100)             union             select -999 team_id, 0 rebs         ) as vwstats     group by          vwstats.team_id     order by          vwstats.team_id desc 	0.00464480900425775
13292878	34001	mysql count 1 by 1	select s.*, @rowcount:=@rowcount+1 ‘number_stitch’ from stitch s, (select @rowcount:=0) r order by id; 	0.0591807344749931
13293497	35709	select data between december of previous year and november of current year, mysql	select date, sum(numcalls) as calltotal  from callstats_calldata where date(date)  between concat(year(curdate())-1,'-12-01') and concat(year(curdate()),'-11-01') group by date order by date; 	0
13293975	12572	month year back (sql)	select convert(varchar(6), dateadd(month, -1 , convert(datetime, cast ( 201201 as varchar(8)) + '01', 112) ) , 112) 	0.00171987222526598
13294317	18749	sql query to count in group by with specific condition	select name,      count(*) as countall,      count(case when text like 'a1-%' or text like 'a2-%' or text like 'a3-%' then 1 end) as counta1a2a3 from mytable group by name 	0.148934545032801
13295636	28467	filter out rows returned in subquery	select t.* from #temprollup t inner join (     select name, count(*) cnt     from #temprollup     group by name ) counts on t.name = counts.name where t.item <> 'totals' or counts.cnt <> 2 	0.042300359376852
13296150	29162	calculate size of sql azure database	select (sum(reserved_page_count) * 8192) / 1024 / 1024 as dbsizeinmb from    sys.dm_db_partition_stats 	0.0127726041969578
13296436	33059	do i have to list all the possible fk in the database design?	select c.customer_id, ..., p.payment_id, ... from customer c,order o,invoice i,payment p where c.customer_id = o.customer_id and o.order_id = i.order_id and i.invoice_id = p.invoice_id 	0.000668774583159739
13297593	20579	crm reports: grouping by a related entity	select mycomplainttype, ...existing sum(case) stuff from filteredcontacts c join filterednew_contacts_new_complaint_new_complaints r1 (whatever your n:n is)   on c.contactid = r1.contactid join filterednew_complaint comp   on r1.new_complaintid = comp.new_complaintid group by mycomplainttype 	0.103178646040752
13299563	32317	multiple mysql queries ordered by frequency	select   * from     my_table where    (age = 'young')       or (work = 'home')       or (eyes = 'blue') order by (age = 'young')        + (work = 'home')        + (eyes = 'blue') desc 	0.0125886507508463
13300188	35138	how to select records from one table that does exists in another	select concat('www.',name)  from db.t1 left join db.t2 on t2.name = concat('www.', t1.name) where db.t2.name is null 	0
13303498	24443	how to write sql with count and group by common fields from two tables	select    coalesce(shape, t2.pickedshape) as shape, count(shape) as available,   isnull(picked, 0) as picked, isnull(finished, 0) as finished from   store  full join    (select pickedshape, count(1) as picked, sum(case when finished='y' then 1 else 0 end) as finished     from record     group by pickedshape) t2 on store.shape = t2.pickedshape group by    shape, t2.pickedshape, picked, finished 	0.000219567141859777
13303507	2810	order by top five repeated ids	select id, count(*) as `number of repeats` from duplicate_id group by id order by count(*) desc limit 5 	0.000774017759662251
13303985	38371	garbage characters in sqldatareader.getstring() of converted timestamp	select case when isdate(convert(varchar(10), timestamp))=1 then convert(varchar(10), timestamp) else null end 	0.0557343704903754
13306100	5442	execute a query with join in two tables from different database of same mysql server	select ...   from a.table t1   join b.table2 t2 on t2.column = t1.col 	0.000285054350403258
13306282	37845	mysql select child from parent and use it in another query	select * from table_2 where category_id in (select category_id from table_1 where parent_id = 1) 	0.00131176727243923
13306301	28880	sql server list from detail table	select distinct idschool, profs from profs p1 cross apply ( select substring((     select ',' + name      from profs p2         where p1.idschool = p2.idschool     for xml path('')     ),2,1000)     as profs     ) profs 	0.001888939850578
13309075	23146	sql on how to simultaneously compare two column values in a query	select driver_name    from driver   join exam e1 on driver_ssn   join exam e2 on driver_ssn  where e1.exam_score < e2.exam_score    and e1.exam_date > e2.exam_date 	9.83454346022778e-05
13309220	16402	mysql query parsing two tables, two fields	select u.university_name, s.student_number, s.student_test_scores  from student_info as s inner join university_info as u on s.student_number = u.student_number  order by u.university_name, s.student_number, s.student_test_scores select u.university_name, s.student_number, max(s.student_test_scores)  from student_info as s inner join university_info as u on s.student_number = u.student_number  group by u.university_name, s.student_number order by u.university_name, s.student_number select avg(a.student_test_scores) from (     select u.university_name, s.student_number, max(s.student_test_scores) as student_test_scores     from student_info as s     inner join university_info as u on s.student_number = u.student_number      group by u.university_name, s.student_number ) as a 	0.00489021777959667
13309564	3	query select on timestamp field	select sw.usernumber, startdate, enddate, dateaccess, door, (h2 calculations on timestamps) as late from scheduleworker as sw    inner join securityaccess as sa on sw.usernumber=sa.usernumber   inner join (select usernumber, min(dateaccess) as access               from securityaccess                group by usernumber, year(dateaccess), day_of_year(dateaccess)) as msa on sw.usernumber = msa.usernumber and msa.access = sa.dateaccess where sw.startdate < msa.access 	0.0117094726008179
13309977	29951	return one row from a left outer join	select mcr.mat_change_req_id,         mcr.line_item_number,         r.remarks,         r.remarks_date from mat_change_req mcr     left outer join (       select mat_change_req_id,               remarks,              remarks_date,              row_number() over (partition by mat_change_req_id order by remarks_date) as rn       from mat_change_req_remarks     ) r on mcr.mat_change_req_id = r.mat_change_req_id and r.rn = 1 where mcr.contract_id = 'ir-30910'   and mcr.project_number = '0801082' 	0.0301212531689067
13310199	8914	sql for finding first period in datetime colums satysfying the condition	select * from table_name where datediff(start_col,end_col)>1; 	9.56348523780635e-05
13310511	30668	displaying datetime.now in a string column within a sql table	select replace(all_text_column, '{datetime.now}', current_timestamp) from your_table 	0.00442451189642214
13311243	4441	how to get date with aggregation t-sql?	select    count( visittracking.customerid) as #visit,    customers.title,    customers.firstname,    customers.lastname,    company.companyname,    max(visittracking.datevisited) as lastvisit,    max(convert(date,visittracking.nextvisit)) as nextvisit from visittracking    inner join customers on visittracking.customerid = customers.customerid    inner join customer_company on customers.customerid = customer_company.customerid    inner join company on customer_company.companyid = company.companyid group by    customers.title,    customers.firstname,    customers.lastname,    company.companyname 	0.0278650731761104
13311543	37745	how to catch some specific rows and sum values in them?	select parent.id, parent.subid, parent.cost + coalesce(child.cost, 0) from sometable parent left join sometable child   on parent.subid = child.id where parent.id not in (select subid from sometable where subid is not null) 	0.00011171738910712
13312302	13211	get next row value based on returned list of rows	select * from table1 where id in (select min(id) from table1 where id > 12) 	0
13312506	27673	mysql, select from different table... if	select coalesce(l.name, c.name) from cds c left join languages l on l.cd_id = c.id                          and l.language = 'de'; 	0.00112649358667574
13312585	28450	how to count tags by user in a day	select user_id,    created_at::date as "day",    count(*) as "numtags" from tags group by user_id, created_at::date order by numtags desc; 	0.000106879142508677
13313229	40718	create view from two tables with different column names	select pra.id, pra.post_id, null as reply_id, pra.user_id, pra.vote_up, pra.rank_date from post_rank_activity pra union all select rra.id, null as post_id, rra.reply_id, rra.user_id, rra.vote_up, rra.rank_date from reply_rank_activity rra 	0
13314868	25656	oracle limit and 1000 column restriction	select *   from foo f, foo2 f2  where (f.rowid, f2.rowid) in (select r, r2                                  from (select r, r2, rownum rn                                          from (select f.rowid r, f2.rowid r2                                                  from foo f, foo2 f2                                                 where f.c1 = f2.a1                                                    and f.c2 = '1'                                                 order by f.c1))                                 where rn >= aaa                                   and rownum <= bbb) order by whatever; 	0.0647790323596329
13316879	6199	select and show business open hours from mysql	select   group_concat(day order by day) as days,          date_format(f1, '%h:%i') as f_time_from,          date_format(t1, '%h:%i') as f_time_to,          date_format(f2, '%h:%i') as f_time_from_s,          date_format(t2, '%h:%i') as f_time_to_s from (   select   day,            min(time_from) as f1,            min(time_to  ) as t1,            if(count(*) > 1, max(time_from), null) as f2,            if(count(*) > 1, max(time_to  ), null) as t2   from     business_affiliate_hours   where    affiliate_id = 57   group by day ) t group by f1, t1, f2, t2 order by days 	0.000185255941575824
13319257	29544	selecting only the entries that have a distinct combination of values?	select t1.cardid  from links1 as t1  join links1 as t2  on t1.cardid = t2.cardid  where t1.abilityid = 1 and t2.abilityid = 2; 	0
13319952	5893	mysql not return result when key id is not found	select log_db.log_bid,    case when booking_db.bk_id is null then 'general'     else concat( 'b', bk_rtype, '-', lpad( bk_id, 5, '0' ) ) end as booking_no,    booking_db.bk_flg1 as flight from log_db left outer join booking_db on booking_db.bk_id = log_db.log_bid where log_db.log_stts = '1' order by log_db.log_id desc 	0.0483213530924792
13320616	31326	compare values from different rows and column to get single result	select    code from    mytable  where    name="aaa"  and    5 >= width1  and    5 <= width2  and    1000 >= parameter1  and    1000 <= parameter2 order by    least( parameter2-1000, 1000-parameter1 ) desc limit 1; 	0
13320731	13029	can't combine two statements into one in sqlite?	select tmp.code, profile.name, tmp.volatility from (select code,              round(...) as volatility,              case ... end as type       from quote       where date between '20120801' and '20121101'         and code<'07000'       group by code       order by volatility) as tmp,      profile where tmp.code = profile.code; 	0.0137347278260427
13322701	38104	group by and select first not "empty" field	select zip,         min(contact) from masterdata where contact is not null and length(contact) > 0 group by zip 	0.00816377630658086
13322704	24173	sql query with joining 2 tables	select book_id from book b inner join temp_table t on t.tag_id = tag_id group by book_id having count(distinct tag_id) = (select count(distinct tag_id) from temp_table) 	0.0808446027158642
13322816	8876	using sql to return results which match all the items in an array using joined tables	select h.hotel_id, h.hotel_name from hotels h      join packages p       on h.hotel_id   = p.hotel_id      join package_items pi on p.package_id = pi.package_id      join items i          on pi.item_id   = i.item_id      where i.item_id in (2,3,4)      group by h.hotel_id       having count (distinct i.item_id) = 3; 	0
13323351	8775	mysql joining tables and pulling information to check	select item_type, count(*) as theamount, session_date from  item left outer join order      on item.order_id = order.order_id left outer join session      on order.session_id = session.session_id group by item_type order by theamount desc limit 10 	0.00188636278616868
13323385	20139	select row from 2 table where row x ( in table a) equal some value	select  a.account_id,         a.name,          b.char from    login a         inner join char b             on a.account_id = b.account_id where   a.name='thuong1' 	0
13323419	8597	sql: joining data from multiple tables	select  a.custno as 'customer no',         a.companyname,         b.lastname from    customer a         inner join table2 b              on a.liasonno = b.employeeno 	0.00398403354426914
13324568	543	mysql moving average - 4 weeks	select   t.yearweek,          t.count,          count(*) / 4 as m_average from     my_table join (   select   yearweek(datolagttil) as yearweek,            count(*) as count   from     my_table   group by yearweek ) t on t.yearweek between yearweek(datolagttil)                       and yearweek(datolagttil + interval 3 week) group by t.yearweek 	0.000842301186764008
13326931	16981	incorrect result with mysql date comparison	select count(*) as num from items  where status='public'  and datecreated >= '2012-01-01'  and datecreated <= '2012-12-31' 	0.798947030468459
13329582	26893	how to write count and distinct from same table with different where in one sql?	select count(id), count(distinct case when sex = 'm' then name else null end) from people 	0
13329786	15014	sql query condition based on column can holded bit	select prodid,         min(qualified),        case when min(qualified) <> max(qualified)              then 'yes'             else 'no'        end as has_different_results from varann_data.dbo.tblownership group by prodid 	0.017931144604293
13331832	6514	how to display row once if all data is the same	select distinct {yourcolumns}  from  (         your current code  ) as tmp 	0
13333052	11667	sql group by on field from other table	select  sum(trans_amount),  a.ledger_name,  a.ledger_code  from transaction_ledger a inner join ledger_master b  on a.ledger_code=b.ledger_code  where a.ledger_parent='sundry debtors'  group by a.ledger_code, a.ledger_name 	0.000343856354933018
13333086	8739	joining multible tables with unequal field's in mysql	select p.id as id, p.type as type, v.video_url as video_url,         v.title as title, null as contend from post p inner join video v    on p.rel_id = v.id and p.type = 'video' union select p.id, p.type, null, null, t.contend from post p inner join text t   on p.rel_id = t.id and p.type = 'text' 	0.051324795839841
13334112	24824	joining two tables with count and where doesn't return rows with count 0	select s.idseminar,     (select count(p.seminar)     from predbiljezba p    where p.seminar = s.idseminar and p.obradjena = 1) as seminarcount from seminar s 	0.00171436330962025
13334504	24130	mysql joins over 3 tables	select modulename from module join teaches on module.moduleid = module.moduleid join staff on teaches.staffid = staff.staffid where staff.staffid = "e10010" 	0.367890449252877
13334594	10235	mysql select with statements	select rec.id, title.name from records rec left join titles title on title.record_id = rec.id and title.language='de'; select rec.id, title.name from records rec left join titles title on title.record_id = rec.id and title.language='en'; id  name 1   achtung 2   (null) id  name 1   warning 2   ambulance 	0.563504775870985
13334855	23405	mktime, date() or mysql timestamp for a forecast?	select * from tbl where mytime >= date_sub(now(), interval 30 minute) 	0.070875225438992
13335687	21877	defining the sort order of children in a hierarchy query	select rownum       ,task_id       ,sequence_within_parent       ,lpad(' ', 2 * (level - 1), ' ') || task  task from   tasks connect by parent_id = prior task_id start with task_id = 1 order siblings by sequence_within_parent / 	0.00302820502844086
13337294	25501	display result even the value is null	select ch.id, ch.studentid, st.name, ch.recordid, rc.name from checklist ch join student st   on st.id = ch.studentid left join record rc   on rc.id = ch.recordid 	0.00125131603504642
13337366	3474	turn mysql rows into columns	select    sum(if (status = 1, total, 0)) as '1'    ... 	0.000330444224910992
13337635	807	oracle: sql select date with timestamp	select * from booking_session where to_char(t_session_datetime, 'dd-mm-yyyy') ='20-03-2012'; 	0.0497545554483901
13338604	8184	split row results into columns	select      isnull(a4b.item_id, '') 'a4 black',      isnull(a4c.item_id, '') 'a4 color' from (   select    i.item_id, row_number() over(order by i.item_id asc) 'rownum'   from  agr_header ah         left join agr_detail ad                on ad.agr_header_recid = ah.agr_header_recid         left join iv_item i                on i.iv_item_recid = ad.iv_item_recid   where i.item_id like 'a4 black%' ) as a4b full outer join (   select    i.item_id, row_number() over(order by i.item_id asc) 'rownum'   from  agr_header ah         left join agr_detail ad                on ad.agr_header_recid = ah.agr_header_recid         left join iv_item i                on i.iv_item_recid = ad.iv_item_recid   where i.item_id like 'a4 color%' ) as a4c on a4b.rownum = a4c.rownum 	0.000138963561183208
13338694	3950	query to bring columns in single row	select row from (   select fruit_id, fruit_id row from fruits   union   select fruit_id, fruit_name row from fruits ) s where fruit_id = 101; 	0.0020974277875052
13338735	15409	how to get the number of buyers on each main channel based on the number of buyers on each sub-channel	select  a.channel_id `channel id`,         a.channel_title `channel title`,         count(distinct c.buyer_id) `number of buyers` from    tbl_channel a         inner join tbl_channel b             on a.channel_id = b.parent_channel_id         inner join tbl_buyer c             on  b.channel_id =  c.channel_id where   a.parent_channel_id = 0 group by a.channel_id,          a.channel_title 	0
13340499	19038	select row by column1 value to select column2 of same row	select `count` from tablename where id = 32235 	0
13342265	24071	information oracle version c#	select banner from v$version where banner like 'oracle%'; 	0.377615160093928
13343739	38306	how to create solid group sql?	select *     from tbl order by [group], value; 	0.36965135708812
13343760	20211	query with multiple select statements	select (select top 1 col1 from dbo.table2 where condition1)as col1 ,      (select top 1 col1 from dbo.table3 where condition2)as col2 from dbo.table1 	0.583418101482398
13344514	28099	how to use if and else to check the hour and run a specific query	select ... from turnover where datemodified between  dateadd(day, datediff(day, 0,dateadd(hour, -18, getdate())), '1900-01-01 18:00') and dateadd(day, datediff(day, 0,dateadd(hour, -18, getdate())), '1900-01-02 06:00') 	0.0104465479426884
13346663	15983	adding the results of a separate query to a json encoded array	select a.id, concat(b.firstname, ' ', b.secondname) as staffmember, a.linemanager, a.description    from a    left join b on (a.staffmember = b.id) 	0.00329251280356853
13346880	37704	php how to disable queries after one week later	select `listing_title`, `etc` from `ad_listing` where `date_posted` between date_sub(now(), interval 1 week) and now(); 	0.000669647659712061
13347437	12087	fetch records after a particular row value in a table column with a limit	select * from table where srt_id >= 5 order by srt_id limit 5; 	0
13347890	28645	tsql count show 0 when no row returned	select  [authorid] as "author id", rtrim([authorfirstname]) + ' ' + rtrim([authorlastname]) as "author",  count(document.id) as "number of docs authored" from      author a     left outer join document d on d.authorid = a.id         and [completedstatus] = 'yes'          and [completedon] >= dateadd(d, -365, getdate()) where     a.id in (<list of author id's>)  group by a.[id], [authorfirstname], [authorlastname] order by [number of docs signed] desc 	0.00311723939292147
13349488	3054	how to get elements from a hierarchical view with cte	select * into #tmp from tree2 ;with rollups as (     select id, parent_id     from tree2 where id=4     union all     select parent.id, parent.parent_id     from tree2 parent      inner join rollups child on child.id = parent.parent_id ) delete #tmp from rollups where #tmp.id=rollups.id ;with rollups as (     select id, parent_id     from tree2 where id=4     union all     select parent.id, parent.parent_id     from tree2 parent      inner join rollups child on child.parent_id = parent.id ) delete #tmp from rollups where #tmp.id=rollups.id select * from #tmp drop table #tmp 	0.00251374307179449
13350905	40131	access query to partition data and sum each partition?	select table1.dte, int(([tme]-1)/100) as hr, sum(table1.val) as totval from table1 group by table1.dte, int(([tme]-1)/100); 	0.0486853319376343
13350932	216	select category list from t1, then select sum from t2 which has category list given to each data	select t1.cause, count(t2.cat_code) as total from table1 t1 left outer join table2 t2 on t1.cat_no = t2.cat_code group by t1.cause 	0
13352511	20377	how to put together data from two tables in database?	select m.unique, m.last_name, m.first_name, s1.property_value as favorite_food, s2.property_value as favorite_color from table_1 m left join table_2 s1 on s1.unique = m.unique and s1.property_name = 'favorite food' left join table_2 s2 on s2.unique = m.unique and s2.property_name = 'favorite color' 	0.000123535202838321
13353804	18436	how to make stored procedure change return value on select	select top 1000 [dataid]   ,[contactserviceid]   ,[linkid]   ,itemtype = case when [linkitemtype] = 3 then 1 else [linkitemtype] end  from [bcm2010].[dbo].[entityreferences]  where dataid = 54  order by itemtype desc 	0.0247711222736608
13354585	24100	how to create a script that will copy tables from another schema into my schema using pl/sql advanced scripting in sqldev?	select 'create table ' ||table_name || '_copy as select *  from ' || table_name || ';'   from all_tables  where owner = 'hr'; 	0.00995522113895834
13354798	17985	edit:sql multiple table instances	select subscriber, name from subscription a where not exists (   select 1   from subscription b   where a.subscriber = b.name         and a.name = b.subscriber) 	0.010380505049405
13356964	26118	select range of months under where condition	select month     from months     where convert(datetime,'1-'+month+'-2012') <= getdate() 	0.000704512377655975
13357144	28748	mysql how to select data where a field has a min value	select * from pieces where price =  ( select min(price) from pieces ) 	0.00026523903141384
13359101	36850	mysql - select values in table a where all the corresponding values in table b have a specific values	select orders_id from orders where    (    select count(distinct product)     from ordered_products     where ordered_products.orders_id = orders.orders_id     and ordered_products.product_type = 1   )   =   (   select count(distinct product)     from ordered_products     where ordered_products.product_type = 1   ); 	0
13360561	21850	sql union same number of columns, same data types, different data	select *  from (     select 's1' as dataset, id, name, count(*) as resultcount from customers where x     union     select 's2',id, name, count(*) from customers where y ) s pivot (sum(resultcount) for dataset in (s1,s2)) p 	0
13360832	31898	simple sql select with all matches	select productid from table1 a where catid in (2,3) group by productid having count(*) =         (           select count(*)           from table1 b           where b.productid = a.productid         ) and          count(*) = 2 	0.18369319164892
13362751	11069	order by 2 values, using 3 tables	select  users.id,            count(user_followers.followinguserid) as follower_count  from    users         left join user_followers              on users.id = user_followers.followinguserid         left join         (             select postedbyuserid, count(*) postcount             from photos             group by postedbyuserid         ) a on users.id = a.postedbyuserid group by users.id order by follower_count desc, a.postcount desc 	0.0047649247158634
13363119	3741	set value when doing union all in myql	select *, 1 as `tab` from news union all select *, 2 as `tab` from highlight 	0.0836007656957622
13363143	30390	column name as parameter	select case @textfield          when 'text_en' then text_en          when 'text_es' then text_es          when 'text_de' then text_de        end as local_text from tablename 	0.0970680095367995
13364136	14990	matching a number pattern in sql	select product from   ( select a.word,a.location-b.location as diff,b.product from   tablea a join   tableb b on     a.word=b.word)c group by diff,product having count(*)=3 	0.00539994779383178
13364329	28100	how to write sql ...where mytable.somedate from today is older that 30 days	select * from mytable where somedate < current_timestamp - 30 days 	0
13366043	14272	removing duplicates in a query	select     mina.colb,     mina.min_a,     tblx.colc from  tblx inner join (select      colb,      min(cola) as min_a     from  tblx group by     colb ) mina on  mina.min_a = tblx.cola and  mina.colb = tblx.colb 	0.245769444257331
13366470	4244	sql hourly data	select hour(datetime)   as hour,         avg(temperature) as avgt  from   database.minute  where  datetime between ( curdate() + interval (select hour(now())) hour -                            interval 23 hour ) and now()  group  by hour  order  by ( curdate() + interval (select hour(now())) hour - interval 23 hour ) 	0.0541111060946006
13367874	38447	how to retrieve the value which corresponding to the max in an other column in sql?	select a.item, a.valuation, a.referencedate from valuations a   join (select a2.item, max(referencedate) as max_date         from valuations a2         group by a2.item   ) b on a.item = b.item and a.referencedate = b.max_date 	0
13368060	19301	alternative to temporary tables	select casos.numcasos as numcasos,  sumnum1.valcount1 as valcount1, sumnum2.valcount2 as valcount2 from casos left join (     select numos.num1 as num1, count(*) as valcount1     from numos group by numos.num1  )sumnum1  on (casos.`numcasos`= sumnum1.num1) left join  (    select numos.num2 as num2, count(*) as valcount2    from numos group by numos.num2   )sumnum2 on (casos.numcasos = sumnum2.num2)) 	0.348262247022672
13368594	15666	find total number of times a number appears in two columns	select team, count(*) from (select away as team from games union all select home as team from games) t group by team order by count(*) desc limit 20 	0
13369681	6127	mysql distinct query using sum	select date_time, sum(     case when address_id in (7,11) then rec_value          else -rec_value end) from rec_address_change  where address_id in (7,11,15)  group by date_time order by date_time; 	0.272099968987421
13371538	36589	projecting a value from having clause expression	select x.elementname, a.elemexchanges/b.totalexchanges percentage       from (     select x.elemid,            count(distinct x.exchangeid) elemexchanges       from exchanges x   group by x.elemid ) a cross join (     select count(distinct y.exchangeid) totalexchanges       from exchanges y ) b       join elements e on e.elemid = a.elemid      where a.elemexchanges/b.totalexchanges > 0.5; 	0.542841554160538
13371679	12185	getting a count of a child relation and a count of a child of the child	select     id,     (          select count(map.id)          from map           where map.client_id = client.id     ) as n_maps,     (          select count(layer.id)          from map inner join layer on (layer.map_id = map.id)          where map.client_id = client.id     ) as n_layers from client; 	0
13371681	23392	(sqlite3) is it possible to select based on cascade/recursive condition?	select filename from mytable a where flag <> -1   and not exists (select id                   from mytable b                   where substr(b.filename, -1) = '\'                     and a.filename like b.filename || '%'                     and b.flag = -1) 	0.0725895255250562
13372037	32337	tsql select random rows with running total	select     t.*  from tbltest t  join  (  select top (1)       t1.id [id1],t2.id [id2],t3.id [id3],      t1.value[v1],t2.value [v2],t3.value [v3],      t1.value+t2.value+t3.value [sum]  from tbltest t1  join tbltest t2 on (t1.id <> t2.id)  join tbltest t3 on (t3.id <> t2.id and t3.id <> t1.id)  where t1.value+t2.value+t3.value <= 15  order by t1.value+t2.value+t3.value desc,newid()   ) [a] on (t.id=a.id1 or t.id=a.id2 or t.id=a.id3) 	0.00158609259091758
13372232	34698	sql all possible round robin combinations between two tables	select p1.name person1, p2.name person2   from (select rownum rnum, name         from person) p1,        (select rownum rnum, name           from person) p2  where p1.rnum < p2.rnum 	0.00010918896696742
13373102	34203	limit sql query by repeated entries	select  a.* from    tablename a          inner join         (           select distinct name           from tablename           order by name            limit 2         ) b on a.name = b.name 	0.0199620912974608
13375312	8982	how to retrieve only unique entries from mysql table	select *  from messages m1 where m1.date = (select max(m2.date)      from messages m2      where      case when m2.fra < m2.til then m2.fra else m2.til end =      case when m1.fra < m1.til then m1.fra else m1.til end     and      case when m2.fra > m2.til then m2.fra else m2.til end =      case when m1.fra > m1.til then m1.fra else m1.til end ); 	0
13376456	25383	t-sql query a matrix table used as lifo	select  m1.x ,       m1.z ,       max(         case         when m2.minoccupiedy is null or m1.y < m2.minoccupiedy then m1.y         else 0         end         ) as firstfreey from    matrix m1 join    (         select  x         ,       z         ,       min(                 case                  when disabled <> 0 or occupiedid is not null then y                 end                 ) as minoccupiedy         from    matrix          group by                 x         ,       z         ) m2 on      m1.x = m2.x         and m1.z = m2.z group by         m1.x ,       m1.z 	0.765010784258798
13377894	26545	sql default value constraint information_schema	select object_name(object_id) as nameofconstraint, schema_name(schema_id) as schemaname, object_name(parent_object_id) as tablename, type_desc as constrainttype from sys.objects where type_desc = 'default_constraint' 	0.0173157093881241
13378275	12025	listing the data from two table	select  * from    staffdetails sd where   not exists         (         select  *         from    worklog w         where   sd.stafid = w.stfid                 and starttime is not null                 and finishtime is null         ) 	0.000358603861502195
13379208	16894	get null if non numeric or the actual numeric value in tsql	select value as actual_string , replace(value, '-', '') as numeric_value , case isnumeric(replace(value, '-', ''))   when 1 then cast(replace(value, '-', '') as float)   else null end as numeric_value_or_null from tablename 	0.00081252220001394
13380161	20278	joining two tables to be bound on a gridview	select f.firstname, f.lastname, fs.notes from family f inner join familystatus fs     on f.[status] = fs.id where f.firstname= @fn and f.lastname = @ln 	0.12026624260199
13381367	21704	using an if statement in mysql	select c.clan_name, n.nation_name,      concat(r.rarity_shorthand, " - ", r.rarity_name) as rarity_text,      t.trigger_name, s.skill_name  from `magez_cfv_cards` as cards  join `magez_cfv_clans` c on cards.clan_id = c.clan_id  left join `magez_cfv_nations` n on cards.nation_id = n.nation_id  join `magez_cfv_rarity` r on cards.rarity_id = r.rarity_id  join `magez_cfv_trigger` t on cards.trigger_id = t.trigger_id  join `magez_cfv_skills` s on cards.skill_id = s.skill_id 	0.718208900356669
13382962	23740	get most awaiting mysql	select m.movie_name, count(*) as favoritecount from favorites f inner join movie m on m.id = f.movie_id  where m.release_date > curdate() group by f.movie_id order by favoritecount desc limit 6; 	0.00736348911327013
13384316	9195	find rows in a database with no time in a datetime column	select * from table where datepart(hour, datecolumn) = 0 and datepart(minute, datecolumn) = 0 and datepart(second, datecolumn) = 0 and datepart(millisecond, datecolumn) = 0 	5.02131253733623e-05
13384509	9557	php table association	select *  from flowers f left outer join association_flowers_colors a on f.id = a.id_flower left outer join colors c on c.id = a.id_color 	0.0562450298565399
13385653	12115	multiple conditions on the same column in the where clause	select propertyval from your_table where propertyid = 7 and recordid in  (   select recordid      from your_table   where propertyid = 13 and propertyval='business development analyst'   or propertyid = 11 and propertyval = 'chicago'   group by recordid      having count(distinct propertyid) = 2 ) 	0.00578718610317402
13385889	23000	how to get statistics for grouped data	select dayname(checkindate) day,   sum(visitsperday) totalvisits,   avg(visitsperday) avgvisits,   max(visitsperday) maxvisits,   min(visitsperday) minvisits from (   select date(checkin) checkindate, count(*) visitsperday from customer_log   group by checkindate ) as visitsperdaysub group by dayofweek(checkindate) 	0.00062808596639001
13386704	23063	query based on current status of a sub item	select max(statustypeid) from (   select vse.statustypeid, vse.serviceid, vse.eventtimestamp     from v_statusevents vse,         (select max(eventtimestamp)as maxdate             ,serviceid         from   v_statusevents          where  eventtimestamp >= cast(cast(current_timestamp as date) as datetime)          and categoryid = @categoryid         group  by serviceid) maxresults     where vse.serviceid = maxresults.serviceid     and vse.eventtimestamp = maxresults.maxdate ) maxstatustype ) 	0
13386890	39457	list the the name of employee that worked on more than one projects	select e.name, w.pid from employee e, workon w where e.empid = w.empid and e.empid in ( select w.empid from workon w  group by 1 having count (*) > 1 ) order by e.name, w.pid 	0
13389486	22974	row position in mysql/php	select `rank` from (   select @rownum:=@rownum+1 `rank`, p.*    from tablename p, (select @rownum:=0) r    order by id  ) s where names = 'house' 	0.0303376810994584
13389743	15755	sql return 2 columns	select (select the_first_select) as col1, (select the_second_select) as col2 from dual 	0.0048791084567174
13390042	16428	sql server : select latest time	select * from ( select     l.user_key as id,     l.user_id as username,      gl1.char_key as char_id,     gl1.name as charname,     gl1.gatenum as server,     convert(varchar(20), l.logintime, 100) as user_time,     convert(varchar(20), gl1.occur_time, 100) as char_time,     rn = row_number() over (partition by l.user_key order by gl1.occur_time desc) from log_connect201211 as gl1     join game.dbo.char_infor as g          on gl1.char_key = g.char0_key or gl1.char_key = g.char1_key or gl1.char_key = g.char2_key     join login.dbo.user_check_login as l          on g.user_key = l.user_key where l.checklogin = 1 ) x where rn=1 order by username desc 	0.00713167173474443
13390058	30313	t-sql and xml - concatenate parent and multiple child elements into result set	select t.n.value('(car/group/text())[1]', 'varchar(10)') as [group],        (          select ','+t2.n.value('(./text())[1]', 'varchar(10)')          from t.n.nodes('insurances/optional/code') as t2(n)          for xml path(''),  type        ).value('substring(./text()[1], 2)', 'varchar(100)') as codes from @xml.nodes('/response/offers') as t(n) 	0
13390937	3852	create sql assertion that count() from one table is less than a tuple value from another table	select c.courseno, c.sectionno, c.[year], c.semester, capacity, count(*) as enrolled from classes as c   join enrollments as e   on c.courseno = e.courseno    and c.sectionno = e.sectionno    and c.[year] = e.[year]    and c.semester = e.semester  group by c.courseno, c.sectionno, c.[year], c.semester, capacity  having count(studentno) > capacity 	0
13392022	6354	doing a + between 2 column of the same table	select currentcharge + overduecharge as total_charge from the_table 	5.2983693721978e-05
13393851	11453	mysql join two tables in the same row on different column	select      org_places.plc_en as from_en,      des_places.plc_en as to_en,      concat( time_start_hr, ':', time_start_min ) as time1,      concat( time_end_hr, ':', time_end_min ) as time2,      price_adult,      price_child from `time_table_boat` inner join      option_places_db as org_places on time_table_boat.org = org_places.plc_id inner join      option_places_db as des_places on time_table_boat.des = des_places.plc_id order by time_table_boat.org asc 	0
13393958	20099	mysql sorting by checkbox array data	select * from (     select "nolisten" as "listeningmethod", count(listeningmethod) as "amount" from vat where listeningmethod like "%nolisten%"     union     select "radio" as "listeningmethod", count(listeningmethod) as "amount" from vat where listeningmethod like "%radio%"     union     select "internet" as "listeningmethod", count(listeningmethod) as "amount" from vat where listeningmethod like "%internet%"     union     select "satellite" as "listeningmethod", count(listeningmethod) as "amount" from vat where listeningmethod like "%satellite%"     union     select "mobile" as "listeningmethod", count(listeningmethod) as "amount" from vat where listeningmethod like "%mobile%" ) as vat2 order by amount desc; 	0.177583495566765
13394370	29600	mysql return most recent row for unique id	select customers.id,  customers.name,  customers."sales responsible us",  customers."sales     responsible",  customers."website",  ifnull(orders.row_invoiced, '-1'),  orders.status, max(orders.created_at)     from "customers"     left join orders on customers.id=orders.customer_id     group by orders.customer_id 	0
13394789	24761	mysql result of subquery in select to be used in where?	select      companies.id  ,      companies.name,     tcount as number_of_rides from companies left join (         select              id ,              count(*) as tcount          from orders          where orders.scheduled_at between '2012-08-01 00:00:00' and '2012-10-31 23:59:59'         ) as orders on orders.company_id = companies.id where companies.affiliate = 0 and companies.id = 346 group by companies.id  having number_of_rides != 0 	0.73221971751068
13395193	32991	mysql: select from coma separated list / list as table? "select a from (1, 2, 3)"	select 1 a union all select 2 a union all select 3 a; 	0
13396020	38149	how to mysql group by zerofill?	select count(w.c1) as count  , lpad(w.c1, 9, '0')  as color from   data w group by   w.c1 order by   w.id desc limit   50000; 	0.542546938143263
13396383	19547	get monthly report in sql	select monthname(data) as month, count(*) as logs-count, type   from table   group by month, type 	0.0128247144964786
13397020	31807	mysql return rows referencing to the same table	select     p1.id,     if(bulk_reference>0,(select product_name from products p2 where p2.id=p1.bulk_reference),p1.product_name) as product_name,     if(bulk_reference>0,(select price from products p2 where p2.id=p1.bulk_reference), p1.price) as price,     p1.bulk_reference,     p1.bulk_count from products p1; 	0.000318064984104076
13397755	19020	mysql group by in php	select groupid, group_concat(name separator ',') as groupname from table group by groupid; 	0.345241848873075
13398090	35828	how to select the first letters in a case-insensitive context?	select upper(substr(name,1,1)) as let from      (select name from t order by name desc) as x group by let order by let asc 	0.00119313095137381
13398356	25432	sql if data not found in similar date, get last date	select t.date, t.item, t.amount,        (select top(1) price           from price          where t.item=p.item and p.date <= t.date       order by p.date desc) price   from [transaction] t; 	0
13398646	13471	how to find max value in 6 columns	select studentcode, greatest(term1, term2, term3, term4, ... ) from my_tbl 	0
13399067	26800	stackoverflow-like comments voting sql query	select u.user_id, u.user_name,        c.comment_id, c.topic_id,        sum(v.vote) as totals, sum(v.vote > 0) as yes, sum(v.vote < 0) as no,        my_votes.vote as did_i_vote from comments c join users u on u.user_id = c.commenter_id left join votes v on v.comment_id = c.comment_id left join votes my_votes on my_votes.comment_id = c.comment_id                             and my_votes.voter_id = 1 where c.topic_id = 1 group by c.comment_id, u.user_name, c.comment_id, c.topic_id, did_i_vote; 	0.538358489387081
13399122	22337	how insert time_t into postgresql timestamp field	select to_timestamp(1000000000)::timestamp; 	0.00257523304999689
13399228	39454	sql sum, group by and having query	select * from products where primaryplu in  (select sku from stock  where branchid in (2,12,1,11,0,96,31,32,13,14,15)  and applicationid = @site  group by sku having(sum(case when stock < 0 and branchid = 31                then stock else 0 end)) > 0)) 	0.508268860567334
13399626	24050	mysql php query to contain count over join	select      week,      sum(items)  from      (         (select week, count(*) as items from archive_agent_booking group by week)     union          (select week, count(*) from invoice_additions group by week)     )  group by      week 	0.493882664767831
13400157	29049	is t-sql (2005) rank over(partition by) the answer?	select i.resort_id,        i.[bedrooms],        i.[kitchen],        i.[checkin],        i.[priority],        i.col_1,        i.col_2 from inventory i  join  (      select row_number(order by checkin) as rownumber, min(id) id     from inventory h     join (         select  resort_id, bedrooms, kitchen, checkin id, min(priority) as priority         from inventory         group by resort_id, bedrooms, kitchen, checkin     ) h2 on h.resort_id = h2.resort and              h.bedrooms = h2.bedrooms and              h.kitchen = h2.kitchen and              h.checkin = h2.checkin and              h.priority = h2.priority     group by h.resort_id, h.bedrooms, h.kitchen, h.checkin, h.priority ) as i2      on i.id = i2.id where  rownumber >=  @startindex and    rownumber <   @upperbound order by rownumber 	0.691762513866292
13400192	9100	how to check if one row in one table is in the other table using mysql?	select  a.col1, a.col2, count(b.col1) from table1 a left join table2 b on (a.col1 = b.col1 or a.col1 = b.col2)  and (a.col2 = b.col1 or a.col2 = b.col2) group by a.col1, a.col2 	0
13400457	7267	postgres: find "from this table" foreign keys (faster alternative)	select pgcon.conname as constraint_name,         cast(pgcon.conrelid as regclass) as table_name,        cast(pgcon.confrelid as regclass) as foreign_table_name,        pga1.attname as column_name,        pga2.attname as foreign_column_name from pg_constraint pgcon join pg_attribute pga1 on (pgcon.conrelid = pga1.attrelid                        and pga1.attnum = any(pgcon.conkey)) join pg_attribute pga2 on (pgcon.confrelid = pga2.attrelid                        and pga2.attnum = any(pgcon.confkey)) where pgcon.conrelid = cast('table_name_here' as regclass)   and pgcon.contype = 'f' 	0.0289373605466284
13401076	34682	mysql select uniques from two different tables?	select email_address, first_name, last_name,     street_address, city, postal_code, province, created_date from      (select * from entries where subscribe='1'     union     select * from entries2 where subscribe='1') as tmp group by email_address 	0.000569926188036243
13402007	11054	how to find out which rows match without having multiple results per row?	select t1.id, t1.local, t1.remote, t1.value, t2.id, t2.local, t2.remote, t2.value from (select q1.*, count(q1b.id) as rank from entries q1 left join entries q1b on q1.local = q1b.local and q1.remote = q1b.remote and q1.value = q1b.value and q1.id >= q1b.id group by q1.id) as t1, (select q2.*, count(q2b.id) as rank from entries q2 left join entries q2b on q2.local = q2b.local and q2.remote = q2b.remote and q2.value = q2b.value and q2.id >= q2b.id group by q2.id) as t2 where t1.local = t2.remote and t1.remote = t2.local and t1.value = - t2.value and t1.id < t2.id and t1.rank = t2.rank 	0
13402419	1569	summing the results of case queries in sql	select country,         sum(number) as number from (     select case               when number < 10 then 'other'               else country            end as country,            number     from ... ) t group by country 	0.23509940976571
13403016	11284	getting the date/time of the last change to a mysql database	select update_time from information_schema.tables where  table_schema = 'dbname' and table_name = 'tablename' 	0
13404249	39350	creating view to display fields from numerous select statements	select      totalmerchants,      totalrdis,     inactive,      count(distinct accountid) as totalaccounts,     count(distinct accountid) / totalmerchants as pct,     sum(case when c is null then 0 else 1 end) as isinrdi,     sum(case when c is null then 0 else 1 end)  / totalmerchants as pctrdi from     (select          count(distinct accountid) as totalmerchants     from           tblaccounts) tm,     (select          count(distinct acctid) as  totalrdis      from          tblcmrck) tr,     tblaccounts  a left outer join     tblcmrck c on     a.configid=c.configid and      a.accountid=c.acctid group by     totalmerchants,      totalrdis,     inactive 	0.0109123745769638
13404572	39805	turn query results from one query into columns of another	select k, owner, group_concat(carbrand) from owners, cars where owner.k = cars.k group by car brand 	0
13404892	13222	sql: selecting customers that haven't had an entry in past 2 weeks	select cmo.customer_id,        max(ci.created_on) as last_interaction from customer_marketing_options cmo      inner join customer_interactions ci      on cmo.customer_id = ci.customer_id where   cmo.status = 'open' group by   cmo.customer_id having max(ci.created_on) < date_sub(curdate(),interval 14 day) 	0
13405079	1575	combine 3 sql queries into 1	select  (         select count(*)  from employees as e where homephone <> ''         ) as totalempcount,         (         select count(*) from employees as e inner join orders as o on e.employeeid=o.employeeid where e.homephone <> '' and e.country='us' and o.orderdate between '11/01/2011' and getdate()         )  as usempcount,         (         select count(*) from employees as e inner join orders as o on e.employeeid=o.employeeid where homephone <> '' and country ='uk' and o.orderdate between '01/01/2011' and '12/31/2012'         )  as ukempcount 	0.012670988748146
13405434	3170	cross joining two tables	select s.boardid, s.schoolid, a.[subject], b.cnt1, b.cnt2, b.cnt3 from (select distinct boardid, schoolid from yourtable) s cross join #a a left join yourtable b     on b.boardid = s.boardid and  b.schoolid = s.schoolid      and a.[subject] = b.[subject] 	0.0510231796977176
13405572	37646	sql statement to get column type	select data_type  from information_schema.columns where       table_name = 'yourtablename' and       column_name = 'yourcolumnname' 	0.0365504178035769
13408061	41063	php mysql top 5 referers function	select ref, count(*) as num from users group by ref order by num desc limit 5 	0.261533874061893
13408819	17577	oracle : how to subtract two dates and get minutes of the result	select (date2 - date1) * 24 * 60 as minutesbetween from ... 	0
13410753	19170	bringing categories into table rows without using cursors	select namecolumn, categorycolumn, quantitycolumn from (     select categorycolumn as namecolumn, null as categorycolumn, null as quantitycolumn,         categorycolumn as _cat, 1 as _iscat     from mytable     group by categorycolumn     union all     select namecolumn, null as categorycolumn, quantitycolumn,          categorycolumn as _cat, 0 as _iscat     from mytable ) x order by _cat, _iscat desc 	0.00687020842384992
13410965	39348	retrive second highest point from table with no unique column	select  a.* from    users a         inner join         (             select distinct credits             from users             order by credits desc             limit 1,1         ) b on a.credits = b.credits 	0
13411365	19442	how to self joining table from following scenario?	select id from mytable where value = 'd' 	0.153442939508005
13412048	26954	stored procedure to generate a unique id column	select newid() 	0.00126771101625687
13413987	12510	using "is null" as a criteria based on a form	select t.atext from table1 t where isnull([atext])=[forms]![reports]![status - null] 	0.00275818732921329
13414250	12969	sql group on a combination of values	select  b.method_group,  count(1)  from tbl_methodgroup a   inner join tbl_method b on a.method=b.method group by b.method_group 	0.00514622521609787
13414709	1875	date not equals to two dates	select *   from tbl  where createdon not in (@date1, @date2); 	0.00196826157354564
13414897	21595	pass a condition in a sql query	select coalesce(e.field1, 'plop1') as field1 from table e 	0.614879482665753
13414916	28138	cf8 - sum in a loop	select     case `desc` when 'no charge (2)' then 'no charge' else `desc` end,     sum(charge) as cost,     count(*) as cnt   from     product   where length(`desc`) > 0   group by case `desc` when 'no charge (2)' then 'no charge' else `desc` end 	0.376055982785211
13418454	11314	mysql get certain rows in order	select * from tablename where empid in (72,81,55) order by field(name, 'john', 'albert', 'bob') 	0.000165235686719738
13419251	37471	sql string count	select car, (length(car)-length(replace(car, ',', ''))+1) as 'counts' from carmakes 	0.155295649045674
13419868	30065	what is the maximum number of key value pairs in a single hstore value?	select string_agg(tags::text,',')::hstore from   mapfeatures_20120813; 	0
13420508	13438	check if field is numeric, then execute comparison on only those field in one statement?	select * from purchaseorders where (case when isnumeric(purchase_order_number) = 1        then cast(purchase_order_number as int)        else 0 end) >= 7 	6.39957452751811e-05
13421046	5138	sql server 2008 - integer columns with no foreign key	select * from information_schema.columns c left join information_schema.key_column_usage k  on      c.table_catalog = k.table_catalog     and c.table_schema = k.table_schema     and c.table_name = k.table_name      and c.column_name = k.column_name where c.data_type in ('int') and constraint_name is null 	0.00296384003287749
13421107	13117	how know the last change date of a stored procedure in sql server 2008?	select modify_date from sys.procedures where object_id = object_id('dbo.yourproc') 	0.00193564090939821
13421972	33609	getting the highest number out of a select query?	select * from    (dan j's code) a order by user_id [asc] 	0
13423878	40129	calculating the peak capacity of hotels with sql	select   i.hotel,   max(i.occupiedbeds) from (   select     s.hotel,     d.dayid,     count(*) as occupiedbeds   from     sampledata s       inner join     days d       on d.dayid >= s.checkin and d.dayid < s.checkout + 1    group by     s.hotel,      d.dayid   ) i group by   i.hotel 	0.134498761715723
13424505	28181	another left join query	select * from ls_client_trans left join client on ls_client_trans.other_client = client.code_client 	0.539987269669274
13425016	4747	sql query to count events from time periods in one query	select sum(eventtime between timea and timeb) as ab_count,        sum(eventtime between timec and timed) as cd_count                    from event 	0.000217805126852035
13427719	28817	two foreign keys reference the primary key of another table	select     child.first_name,     child.last_name,     parent.first_name,     parent.last_name from relation r     join person child on r.child_personid = child.id     join person parent on r.parent_personid = parent.id 	0
13428351	29765	mysql, multiple joins on same table with different criteria. rename columns at query	select        s.schedule_id,       sl.language_name_en as schedule_name_en,       sl.language_name_zhs as schedule_name_zhs,       sl.language_name_zht as schedule_name_zht,       schedulesafename,       s.schedule_expected_arrival,       s.schedule_expected_departure,       c.cruise_id,       cl.language_name_en as cruise_name_en,       cl.language_name_zhs as cruise_name_zhs,       cl.language_name_zht as cruise_name_zht     from       schedule as s           inner join language as sl              on s.language_language_id = sl.language_id          inner join cruise as c             on s.cruise_cruise_id = c.cruise_id             inner join language as cl                 on c.language_language_id = cl.language_id    where       s.schedule_id = 1; 	0
13428993	19994	sql server compare two tables rows with identical columns and return changed columns	select p.id,p.name as orgn,t.name as altn,p.descripion as orgd,t.description as altd from product p join tmp_product t on t.id=p.id and (t.name<>p.name or t.description <> p.description) 	0
13429813	36317	how can i multiply two fields then get avg of rows	select avg(grade * unit) from ... 	0
13429814	38191	sql user defined function to split string to multiple column and rows	select     left(f.item, c.c - 1) as item1,     right(f.item, len(f.item) - c.c) as item12 from dbo.fnsplit('s1cw3733|1050105000224,s1cw4923|1050105000009', ',') as f     outer apply (select charindex('|', f.item) as c) as c 	0.0010534823262844
13431787	26488	get the same field twice with different values in the same row	select o.order_id,         ow.name as owner_name,         cl.name as client_name from orders o   join users ow on o.owner_id = ow.user_id   join users cl on o.client_id = cl.user_id 	0
13433474	9512	mysql - group by a timestamp range	select name, count(when_logged)   from user_logins   where when_logged >= curdate() - interval 14 day  group by name, date(when_logged) 	0.00515332788424552
13435259	39590	the importance of the order of mysql search query	select *  from for_sale  where message like "%2012%" or message like "%bmw%" or message like "%x3%" 	0.0226155447000841
13436122	4157	how to get value without subqueries (on sql-server)?	select cast(sum(distinct num + cast(0.00001 as number(38,19))/id) as number(18,2)) 	0.00921942387135975
13436234	38664	sql query to find users with at least 2 types of accounts	select name from customers c where exists(   select distinct aid from transactions   where cid = c.cid   having count(distinct aid)>1 ) 	0
13441082	28779	http caching via tables latest modified time	select max(joint.updatedat) from (     select max(a.updatedat) updatedat from articles a     union     select max(c.updatedat) updatedat from comments c     ) joint; 	0.00209654877217318
13443132	3792	ssis excel data extraction	select * from [sheet1$] where extractdate > ? 	0.341677666037886
13445495	24576	finding person with most frequent hit	select   p.pid,   p.name from (   select     p.pid,     p.name,     count(*)   from     players p       inner join     scores s on       p.pid = s.pid   where     result = 'hit'   group by     p.pid,     p.name   order by     count(*) desc   ) p where    rownum = 1; 	0.00294486719159727
13447729	21295	getting random values from mysql	select a.mod_name, u.user_name, a.id from type a, users u where a.id=u.mod_type  order by mod_type desc, rand(); 	0.00169682900216877
13448442	16918	finding players that played with another player that has appeared twice	select distinct p1.id1 from play p1 join (select id2       from play       group by id2       having count(*) > 1) p2 on p1.id2 = p2.id2 	0
13449844	34101	return multiple data from stored procedure from the same table	select @userid = userid ,                @isverify = isverify ,                @usertype = usertype ,               @ispremium = ispremium          from users where email = @email and password = @password 	0
13450052	7081	how to replace string (1) with 1 in mysql?	select replace(replace(col,'%20(',''),')','') from t 	0.0854319900506362
13452213	40716	sql get distinct per week	select playlist.p_title as title, stats.s_week as week, playlist.p_artist as artist, p_id from stats, playlist where stats.s_pid = playlist.p_id and s_uid =31 group by playlist.p_title, stats.s_week,playlist.p_artist order by s_week desc limit 0 , 30 	5.70526387955495e-05
13452880	29427	mysql join returns unexpected values	select c.currency_id, c.currency_name, c.currency_symbol, c.currency_active, er.exchange_rate_id, er.exchange_rate_date, er.exchange_rate_value from currencies c left join (select * from      (select er1.exchange_rate_id, er1.currency_id, er1.exchange_rate_date, er1.exchange_rate_value     from exchange_rates er1     order by er1.exchange_rate_date desc) as a group by currency_id      ) as er on er.currency_id=c.currency_id where c.currency_active='1' 	0.539828092962318
13453275	14179	optimize my two queries in to one	select rtype, date_format(iperiod, '%b %e') as period, amount  from  (select 'chat' as rtype,    count(id) as amount,     date(timestamp) as iperiod     from tblchats     where timestamp between '{$start}' and '{$end}'     and userid = 0     group by date(timestamp)  union    select 'mail' as rtype,     count(id) as mail_amount,     date(timestamp) as iperiod     from tblmails     where timestamp between '{$start}' and '{$end}'     and userid = 0   group by date(timestamp)) ilv  order by period desc; 	0.295947184904606
13454966	23733	select as subset from same table	select    t1.order_number,   t1.placed_by,   t1.placed_when,   t1.updated_by,   t1.updated_when,    (select sum(t2.qty_order <> t2.qty_rec)     from 1_purchase_orders t2    where t2.order_number = t1.order_number and t2.line_number <> 0     order by qty_order limit 1)  from 1_purchase_orders t1 where t1.supp_number = 4 and t1.line_number=0; 	0.000325521335935906
13456148	898	script for getting posts with unique role	select dt.discussionthreadid, dt.message from discussionthread dt inner join users u on u.userid = dt.createdby inner join userroles ur on ur.roleid = u.roleid group by dt.discussionthreadid, dt.message having count(distinct roleid) = 1 and max(roleid)=4 	0.0105965863571735
13456149	26995	select where count of another table is zero	select q.* from questions q left outer join answers a             on q.id = a.questionid  where a.questionid is null 	0.00185694819976715
13456528	19637	how can i select a row with max frequency from a joint table?	select t2.name as title, t2.theabstract as abstract, sub.name as subjectarea from (   select art.id, max(freq) freq from (     select   art.id, count(*) freq     from     authors_articles aa         join authors_subjectareas asub using (author)         join articles art on art.id = aa.article     group by art.id, asub.subjectarea   ) t ) t1 natural join (   select   art.id, art.name, art.theabstract, asub.subjectarea, count(*) freq   from     authors_articles aa       join authors_subjectareas asub using (author)       join articles art on art.id = aa.article   group by art.id, asub.subjectarea ) t2 join subjectareas sub on sub.id = t2.subjectarea 	5.65285158138662e-05
13458463	9310	how to query highest value from table column in sql server 2012?	select max(id) from [table] 	0.000210576054903441
13458728	11209	count from 2 separate tables	select customer_id,        sum(case when ltype = 'a' then 1 else 0 end) as loginattempts,        sum(case when ltype = 'h' then 1 else 0 end) as loginhistory from ((select 'a' as ltype, customer_id        from login_attempts       ) union all       (select 'h' as ltype, customer_id        from login_history       )       ) l where customer_id in (select customer_id from #a) group by customer_id 	0.000513398715197225
13461188	32303	oracle string manipulation	select substr('abc-123-xyz-456',1,instr('abc-123-xyz-456','-',1,n)-1)    from dual; 	0.497469917027543
13462872	31669	retrieving as much data as possible using two keys, one of which is corrupted	select sd.id_a, sd.id_b,         case when ai.id_a is null then ai2.val else ai.val end as val from   some_data sd        left join all_info ai        on ad.id_a = ai.id_a and ad_id_b = ai.id_b        left join         (select id_a, min(id_b) id_b, min(val) val         from   all_info         group by id_a         having count(*) = 1        ) ai2 on sd.id_a = ai.id_a 	0.000172900448927483
13463884	22793	how can i filter out questions that have been answered by a user?	select *, q.id qid, q.question question_text  from questions q left outer join      user_answers ua      on q.id = ua.question_id and         ua.test_id = $test and         ua.user_id = $_session[userid]  where ua.user_id is null order by rand()  limit 1 	0.00262638871012853
13464160	38995	sql server 2005 query - count of a sum	select  ua.browser_id   , b.browser_name_nm   , count(b.browser_name_nm) as browsercount from    llc.user_agent_tb as ua     left join llc.browser_tb as b on ua.browser_id = b.browser_id group by b.browser_name_nm   , ua.browser_id with rollup order by browsercount desc 	0.208623720977768
13464511	26801	combining results from 2 tables into a unified table without common data	select id, partnernumber, attributecname, attributevalue, assetfilename, orderby, null as url from #tmpbus tb union select id, name, null, null, assetfilename, orderby, url from #tmpbus1 tb1 order by orderby 	0
13464654	11126	create a new table from two existing tables	select news.post_id,        news.title,        news.blog_entry,        news.updated,        news.rating,        artists.artists_name from   news join artists on artists.id = news.artistid 	9.28534355494183e-05
13466190	33973	sql select multiple columns into one	select id, (cast([year] as varchar(4)) + ' ' + manufacturer + ' ' + model) as mycolumn  from   tablename 	0.000668685949085819
13466253	26295	double sorting sql results with php	select * from (     select        entries.permalink,        entries.title,        voting.vote      from entries      left join voting on voting.id = entries.id      where date>='$twoweeks'      order by voting.vote desc      limit 4 ) t order by entries.id;  	0.744385628033145
13469473	14752	sql view attributes	select view_name, table_name from information_schema.view_table_usage where view_name = '<giveviewname>' order by view_name, table_name 	0.279879686848757
13469842	9066	mysql query only select rows with unique result within group_concat	select t3.id_adv     , t3.data1     , t3.data2     , cast(group_concat(concat(t3.timestamp_day, ',', t3.price1, ',', t3.price2)) as char) as dateprice     from (         select t1.*             , min(t2.timestamp_day) as timestamp_day             , t2.price1             , t2.price2             from table1 t1             left join table2 t2 on t2.id_adv = t1.id_adv             group by t1.id_adv, t2.price1, t2.price2     ) t3     group by t3.id_adv; 	0.00340044240319814
13473095	38943	sql : combining 2 query to give 1 resultset	select col1  from tableb where col2 in (select col1                 from tablea                 where col3='a') 	0.0303129272655964
13474207	18123	sql query if parameter is null select all	select *  from my_table  where @parameter is null or name = @parameter; 	0.247314387156049
13474976	36264	getting all rows that have all of the entered values by querying the same column	select u.*, count(*) as `count` from `user` u      join `user_tags` ut on ut.`user_id`=u.`id`     join `tags` t on t.`id`=ut.`tag_id` where t.`name`='tag1' or t.`name`='tag2' group by u.`id` having `count` = 2 	0
13476073	24892	oracle 11g: how to merge two result sets	select   extract(month from cases.date_entered) as month_entered,   count (case when sub_category in('temp1', 'temp2', 'temp3') then 1 end) skill_count,   count (case when sub_category in('call1', 'call2', 'call3') then 1 end) training_count from cases group by extract(month from date_entered) order by month_entered asc 	0.00742311741646474
13477961	15773	sorting timestamp into intervals php	select ..., count(*) as occurences, hour(timestampfield) as hour from ... where timestampfield >= (now() - interval 24 hour) group by hour(timestampfield) 	0.00271839114561574
13478092	28714	dynamic group by in a query	select col1, sum(col2) as col2 from datatable where  col1 in (select col1 from datatable where col3 is not null) group by col1 union all select col1, col2 from datatable where (col1 not in   (select col1 from datatable where col3 is not null and col1 is not null)) 	0.65446716736428
13478324	29516	fast approximate counting in postgres	select count(*) from (   select * from table where indexed_varchar like 'bar%' limit 2 ) t; 	0.242309521348011
13478564	40084	sql query grouping two columns into one	select location, sum(case when saledate = '2012-11-12' then dollarsales else 0 end)'sale on 11/12' sum(case when saledate = '2012-11-19' then dollarsales else 0 end)'sale on 11/19' from [tablename] group by location order by location 	0.000440128105168491
13478715	21843	sql join using a mapping table	select     c.*,     p.name from     collection c     join person_collection pc on pc.collection_id = c.id     join person p on p.id = pc.person_id order by p.name 	0.485270781104418
13479178	19832	dynamic mysql query two tables	select * from table2 where id in (select id from table1) 	0.160877936639983
13481564	11624	adjacent list and recursive query using a cte, how to backfill?	select empid,mgrid,lv,         level1 = coalesce(level1,rn),         level2 = coalesce(level2,rn),         level3 = coalesce(level3,rn),         level4 = coalesce(level4,rn),         level5 = coalesce(level5,rn) from (select  empid,mgrid,lv,level1,level2,level3,level4,level5,row_number()over(order by empid) as rn from    tree)x 	0.764249387643729
13481787	30553	finding the lone occurence of a value in a table	select count(*) from   (select l_id from m group by l_id having count(*)=1) m 	5.29452381270758e-05
13482235	3299	how to search new line char in oracle table?	select * from your_table where instr(your_text_col, chr(10)) > 0; 	0.0165459253650088
13484636	18732	stcontains on geography column	select geography::stpolyfromtext( 'polygon((' +      stuff((         select ',' + cast(g.stpointn(t.i).long as varchar(10)) + ' ' + cast(g.stpointn(t.i).lat as varchar(10))         from [a]         cross join tally as [t]         where t.i <= g.stnumpoints()         order by i         for xml path('')     ), 1, 1, '') + '))'     , 4326) 	0.246998141395925
13486955	31637	how can i find the identity of two columns	select state, code, min(rate) min_rate, max(rate) max_rate   from mytable  group by state, code having min(rate) != max(rate) 	5.12731049486724e-05
13487697	4149	how to retrieve data from database monthly based on date if data not available it should display null	select  years,number as month,isnull(total,0) as total from(     select number      from master..spt_values      where type='p'      and number between 1 and 12) seq cross join (select distinct year([date]) as years from table1) y left join     (select year([date])as year,month([date])as month,sum(total) as total      from table1       group by  year([date]),month([date]))t on seq.number=t.month and t.year=y.years 	0
13490256	14578	sql order by route information	select a.* from route  a start with a.rowid = (select min(rowid) from route ) connect by prior a.t = a.f; 	0.328612840685184
13490609	34990	database design for comments and replies	select c.comment, r.comment as reply from comment as c, comment as r, replyto as rt where c.id = rt.commentid and r.id = rt.replyid 	0.0524136519958564
13491712	11545	create joins with a null value	select * from products left join orders  on products.id_products= orders.id_products where user.id = 1 	0.228463047005862
13491838	14138	joining over three table with sum() subquery	select sum(hours_worked.hours) as 'total_hours',                 companies.name                 from companies, hours_worked, projects                 where companies.id = projects.company_id                       and hours_worked.project_id = projects.id                       and hours_worked.uid = 1                       group by companies.id order by companies.name desc 	0.143186190320841
13493143	6507	return data if no data exists - populate nulls with data	select      case when reporting is null then max(reporting) over (partition by (select 1)) else reporting end as reporting ,   case when fund is null then max(fund) over (partition by (select 1)) else fund end as fund ,   portfolioid ,   ac.assetclass ,   row_number() over (partition by portfolioid order by sum(percentage) desc) as [rank] ,   cast(sum(isnull(percentage, 0)) as decimal(22,1))  as [weight] from @worktable as wt right outer join @assetclass as ac     on wt.assetclass = ac.assetclass group by wt.reportingdate, wt.portfolioid, ac.assetclass order by [weight] desc 	0.0101655788183125
13493684	31808	avoiding creating the same query twice in sql	select d.* from tbldebates d where exists (select 1  from tblsubjectalias s  where s.subjectid in (d.subjectid1, d.subjectid2) and        s.subjectalias = @subjectalias) 	0.255932828283816
13493888	10887	sql ordering ordered groups	select familycode, dateuploaded, . . . from (select t.*,              max(dateuploaded) over (parition by familycode) as maxdateuploaded       from t      ) t order by maxdateuploaded, familycode 	0.0345376021561093
13494289	13693	sql insert with inner join from list of constant strings	select rolename from   (values('viewuserspermission'),               ('modifyuserspermission'),               ('viewrolespermission')) v(rolename) 	0.035579676573218
13496462	38037	mysql, include the first child in parent	select a.id_album, a.name, count(p.id_photo) as photos, p.id_photo, p.image  from album a left join photo p on a.id_album = p.album  group by a.id_album  having photos > 0; 	0.000232113690165813
13496600	18620	select latest status grouped by user	select * from status natural join (     select userid, max(addeddate) as addeddate     from status     group by userid ) as mostrecent where userid in (     select distinct id     from users     where users.locationid = "'.$locationid.'"     or users.hometownid = "'.$locationid.'" ) and status.content not rlike "#[0-9aza-z]" and type = "5" #and userid != "'.$userid.'" order by status.addeddate desc limit 10 	7.98710921638415e-05
13496996	20429	sql - spread a value across multiple weeks	select      x.person,     w.date,     x.rate from (     select         person     from         ratings     group by         person       ) p cross join (     select          date as dateend         from         weeks ) w cross apply (        select top 1          rate     from          ratings     where          person = p.person and         date < dateadd(day,1,w.dateend)     order by          date desc ) x 	0.000959931710984008
13499432	28532	get highest and sum of values from two table	select c.account, a.username, c.name, max(c.rank) as maxrank, sum(c.time) as sumtime  from characters c left join accounts a on a.id=c.account group by c.account; 	0
13501026	1351	mysql: limit to maximum equal results of multiple queries	select t.name from      my_table as t   join     ( select max((age = 'young') + (work = 'home') + (eyes = 'blue')) as matching       from my_table     ) as m     on  m.matching > 0       and m.matching = (t.age = 'young') + (t.work = 'home') + (t.eyes = 'blue')  ; 	0.00200765327082003
13501996	12580	mysql query select distinct where	select    imageid,    count(imageid) as total_images,    sum(deleted is not null) as deleted_images from productdata group by imageid having total_images = deleted_images 	0.340841954481644
13502932	34461	sql filtering through multiple tags	select * from images   left join links as l1 on l1.ino = images.ino   left join tags as t1 on t1.tagno = l1.tagno   left join links as l2 on l2.ino = images.ino   left join tags as t2 on t2.tagno = l2.tagno   [...]   where t1.tagno = $tag1     and t2.tagno = $tag2   [...] 	0.0625935550769415
13503587	631	sql frequency counting in a dataset	select count(distinct value)   from dataset 	0.00824097920800597
13504991	35670	access(sql) - count distinct fields and group by field name	select errorcat, count(*) totalcount from tablename where erroridentified = 'yes' group by errorcat 	0.00671267833735761
13505159	11450	list the name of the employee whose salary is below the company average but the total working hours of project is over 100	select   e.name from   employee e   inner join workon wo on e.employee = wo.employee where   e.salary < (select avg(salary) from employee)   and sum(wo.hours) > 100 group by   e.name; 	0
13507252	38065	mysql query to retrieve data based on values length	select *  from cdrcost  where length(dst) = 31; 	0
13507442	4095	how to convert date.now.tostring("yyyy_mm_yy_hh_mm_ss_ms") in sql server 2008?	select cast(year(getdate()) as char(4))+'_'+        case when month(getdate())<10 then '0'+cast(month(getdate()) as char(1)) else cast(month(getdate()) as char(2)) end+'_'+        right(cast(datepart(yy,getdate()) as char(4)),2)+'_'+        replace(replace(right(convert(varchar(22),getdate(),121),11),':','_'),'.','_') 	0.785721983196189
13509739	328	mysql query for lowest price	select itemcode, price from item where price>0 order by price asc limit 1 	0.0188999912338067
13509778	17061	checking for character existence in a field	select    number from    table1 where    number not regexp '^\\+{0,1}(0|1|2|3|4|5|6|7|8|9)*$' 	0.0213697639500835
13511567	40421	how to skip sql timestamp to get records for specific date	select convert(varchar(10),getdate(),111)  select cast(getdate() as date) 	0
13512019	16853	sql convert 'ddmmyy' to datetime	select convert (datetime,  stuff(stuff('311012',5,0,'.'),3,0,'.'), 4) 	0.452043333794312
13512161	12308	using "order by" twice in a single query	select date_réserve, heure_réserve from réserve order by date_réserve, heure_réserve 	0.136563779143056
13512953	17787	when using max(column), values from other columns don't match	select a.nid ,a.revid ,a.version from   `revision_history` a join       (select nid,  max(version) as version         from `revision_history`          group by nid)b on    a.nid=b.nid and   a.version=b.version 	0
13514142	27688	bundling records in mysql select query, stored as timestamps	select date(from_unixtime(recorded_at)), count(*) totalcount from tablename group by date(from_unixtime(recorded_at)) 	0.0127301669119012
13516459	23757	conversion failed when converting the nvarchar value 'aaa' to data type int	select id, struser  from ticket  where (convert(varchar,id) = @id ) or (struser = @struser) 	0.242176712548271
13517058	33437	case statement add leading zero 0 sql	select  location,  right('0'+convert(varchar(2), case when id between 1 and 7 then '5' else '1' end), 2) as id from locations 	0.784268573603372
13517825	22504	efficient query for the first result in groups (postgresql 9)	select name, date from   (     select distinct on (name) name, date     from table     order by name, date   ) as id_date order by date limit 300; 	0.0180690661376529
13518024	32710	in sqlite, how do i exclude rows which contain certain strings?	select * from table where column not like '%|||%' 	0
13518647	2473	sql join 3 tables (based on 2 criterias?)	select     tt.id,     case when tt.tr_type = 'project' then pp.project_name          when tt.tr_type = 'task' then ta.task_name end as name,     tt.tr_proj_id,     tt.tr_type,     tt.tr_min, from time_tracking as tt    left join time_projects as pp on pp.id = tt.tr_proj_id    left join time_tasks as ta on ta.id = tt.tr_proj_id where tt.tr_min > 0 order by tt.tr_proj_id desc 	0.00100251814645086
13518709	6203	count multiple tables	select   (select count('member_id') from blogs where member_id=3) as total_blogs, (select count('member_id') from articles where member_id=3) as total_articles, (select count('member_id') from posts where member_id=3) as total_posts 	0.0471339578508776
13519317	37257	query the win32_ntlogevent class to get the errors from last week	select * from win32_ntlogevent where logfile = 'application' and (type ='error' or type ='critical') and timegenerated > '20121117000000.000000+060' and timegenerated < '20121124000000.000000+060' 	0
13519598	22957	get mutual friends from facebook friends (mysql table)	select f1.id, f1.name    from (select id, name from friends where uid=1) f1    join (select id, name from friends where uid=2) f2    on f1.id=f2.id; 	0
13519703	3788	select a column in foreign key	select t1.name from table2 t2    inner join table1 t1 on (t1.id=t2.eid)     where t2.hour=x 	0.000902242857864379
13520501	29950	shortest way to group by similar values and retain latest rows?	select a,b,max(date) group by text 	0.000188029195833531
13520504	17958	join columns from tables and merge rows with same id	select s.id, sum(sc.sum_credits), sum(smc.branch_credits), sum(smc.program_credits) from students s left join studentcredits sc on s.id = sc.id left join studentmandatorycredits smc on s.id = smc.id group by s.id order by s.id 	0
13520964	3242	need to fetch all products that have specific features with mysql	select distinct product_id as book_id, ( select value from cscart_product_features_values where product_id = book_id and feature_id =  '1' ) as publisher, ( select value from cscart_product_features_values where product_id = book_id and feature_id =  '8' ) as author from  `cscart_product_features_values`  order by product_id 	0
13524360	2397	possible select column name with filter	select substring_index(p.name,' ',1) as name, p.id from person p 	0.0522536703987953
13524386	25787	mysql searching in many-to-many	select m.movie_title, a.genre_names from movies m inner join (select gm.movie_id, group_concat(g.genre_name separator ', ') as genre_names     from genre_movies gm inner join genres g on g.genre_id = gm.genre_id     group by gm.movie_id) as a on m.movie_id = a.movie_id  where genre_names like '%horror%' 	0.431282047220652
13525428	40610	return correct records with tsql join	select distinct         outlet.ccode,     employee.cemployeenumber,     from  outlet      inner join employee on employeeoutlet.iemployee = employee.iid      inner join employee_hierarchy as eh on eh.outletcode = outlet.ccode and (eh.rsmcode = employee.cemployeenumber or eh.asmcode = employee.cemployeenumber or eh.fmcode = employee.cemployeenumber) where outlet.ccode = 123 	0.216088331829193
13525656	32471	limit a left join on the first table	select * from a       inner join ( select * from a where a.field1='x' order by a.field2 limit 10) x              on (a.keyfield=x.keyfield)       left join b on (a.field = b.field)       left join c on (a.field = c.field) 	0.0167757246726049
13526442	2580	sql multiple filter - optimal way	select name, dateofbirth, phone, email   from table  where (@a_name  = '' or name = @a_name)    and (@a_date  = '1900-01-01' or dateofbirth = @a_date)    and (@a_phone = '' or phone = @a_phone)    and (@a_email = '' or email = @a_email) 	0.573199627207382
13527230	14228	select all rows for given start_datetime and end_datetime	select id, start_datetime, end_datetime, arena_surface_id  from gce_arena_surface_booking  where ('2012-11-23 6:00' > start_datetime) and ('2012-11-23 2:00' < end_datetime) and arena_surface_id = 2 	0.000351153112250378
13528682	1258	time compare sql query	select case when cast(cast(datepart(hh,getdate()) as varchar)+ ':'+ cast(datepart(n,getdate()) as varchar) as datetime) >        cast(left('0415',2)+':'+right('0415',2) as datetime) then 'greter' else 'lesser'        end 	0.0598796495832221
13531302	38968	mysql - how do i join a sum of two counts?	select p.playerid, p.firstname, p.surname, count(*)   from players p, fisture_data f  where p.playerid='$playerid'     and (((p.playerid = f.p1home or p.playerid=f.p2home...) and f.hometeam='$teamname')         or ((p.playerid = f.p1away or p.playerid=f.p2away...) and f.awayteam='$teamname')) group by p.playerid, p.firstname, p.surname 	0.00689744689376824
13532239	34145	comparing dates in iif() in sql server	select [al].[subscriptions].id,         [al].[subscriptions].name,         [al].[subscriptions].description,         [al].[subscriptions].price,         [al].[subscriptions].iconfilename,         case when a.expirydate > getdate() then 'true' else 'false' end as issubsbyuser    from   [al].[subscriptions]    left join (select expirydate, itemid                from   [al].[usersubscriptions]               where  userid = 13259) as a      on subscriptions.id = a.itemid; 	0.148670924541669
13533114	11523	mysql - join 3 tables based on criteria	select s.idsong, s.title   from purchased p   inner join users u on u.username=p.username  inner join song s on p.idsong = s.idsong  where u.username='admin'; 	0.00161730767204931
13533237	7384	fetch some data from two tables	select id as 'id', count(1) as 'number of ratings', avg(r.rating_num) as 'average rating', i.name, i.actors, i.vote from ratings r inner join imbd i on ( r.id = i.id ) group by r.id having `number of ratings` >= 10 order by `average rating` desc limit 10 	9.86186378022644e-05
13534173	30327	max values over partition by ()	select   c.brand,   nvl(count(p.brand), 0) as reappearance_factor from (   select     brand,     rank () over (order by sales desc) as r   from     sales   where     timestamp = date '2012-02-01'   ) c     left outer join (   select     brand,     rank () over (partition by timestamp order by sales desc) as r   from     sales   where     timestamp >= date '2011-10-01' and     timestamp < date '2012-02-01'   ) p   on c.brand = p.brand and p.r <= 5 where   c.r <= 5 group by   c.brand 	0.42410076030943
13539001	14181	select only hashtag part of string from database	select substr(message, locate('#', message)) hashtag from t_haps_wall where message like '%#%' 	0.000333742088758472
13539819	15913	create data set from multiple column and compare it with another data set	select *  from table_1 join table_2   where (table_1.a_zone = table_2.p_zone) && (table_1.a_address = table_2.p_address); 	0
13541590	21052	how to return items based on a count	select item_type, item_desc, item_cost  from item join basket on theitem_id = item_id join order on order_id = ord_id where order_isgift = "true" group by item_id having count(1) > 1 	0
13543346	4541	jpa query find by parameter other than id	select r from user r where r.email = :email 	0.00823890024159133
13544709	19692	mysql select all that match a number in string	select * from testtable where instr(concat(', ', longstring, ', '), ', 2,') >0; select * from testtable where instr(concat(', ', longstring, ', '), ', 1,') >0  and  instr(concat(', ', longstring, ', '), ', 2,') >0; 	0.00012189940852158
13547047	37661	mysql left join returning wrong number of results	select        ktm.key as keyword,        ktm.data as this_month,        klm.data as last_month     from        data as ktm           left join data as klm               on klm.site_id = ktm.site_id             and klm.key = ktm.key              and klm.type = 'organic-keywords-last-month'    where            ktm.site_id = 2        and ktm.type = 'organic-keywords-this-month'     order by       this_month asc 	0.762643517241417
13547303	5677	how to get the latest row per grouping?	select * from (   select * from mytable   order by id desc) x group by country_id, location_id; 	0
13549770	19757	nested for each loop or sql duplicating results	select students.id, students.student_name, students.student_number,group_concat(classes.class_number) as student_classes from students  left join student_classes on students.student_number=student_classes.student_number  left join classes  on classes.class_number=student_classes.class_number  where students.status=1 group by students.id 	0.124849662810715
13549785	41082	order by specific value then rotate through the rest	select * from users order by id<3,id 	0.000223218746625075
13549866	6832	ordering fields by datetime from two tables	select depositno, submitdate   from (        select depositno, submitdate        from outgoingdocs        where depositno = 1       union all       select depositno, submitdate        from incomingdocs        where depositno = 1  ) tt   order by tt.submitdate 	0.000694250707721237
13551355	28992	how to join 4 tables with specific requirements?	select  a.nameoftheprocedure,         count(a.nameoftheprocedure) amountoftimesprocedurewasdonethatday,         sum(b.amountofmaterialused * d.price) +         sum(c.cost) totalprice from    proceduresdone a         inner join materialsused b             on a.nameofprocedure = b.nameoftheprocedure         inner join procedures c             on c.name = a.nameofprocedure         inner join materials d             on b.materialused = d.name where   a.date = '2012-11-24' 	0.050368788490342
13552030	5456	joining 2 mysql table and ordering by number of same rows in 1 table	select  a.photo_url, count(b.photo_id) totalvotes from    table1 a         left join table2 b             on a.photo_id = b.photo_id group by a.photo_url order by totalvotes desc 	0
13553409	33392	mysql: dynanic collums in mysql --> first, last name to full name:	select concat(firstname, ' ', lastname) as fullname from users 	0.000180322579818524
13553715	27759	1242 - subquery returns more than 1 row in subquery	select   (period_diff(date_format(now(), '%y%m'), date_format(month, '%y%m'))) as months,   pending.amount,   pending.admission_numb,   pending.month,   staff.name,   staff.class,   sums.tot from   pending join staff on pending.admission_numb = staff.admission   join  (     select class, sum(amount) as tot      from pending     where month < date_sub(curdate(), interval 1 month)     group by class   ) sums on staff.class = sums.class group by admission order by cast( staff.class as unsigned ) , staff.class 	0.562010983712468
13554145	8216	multi table not equal in access query	select vehicle.* from vehicle where not exists (select null from ownership where vehicle.veh_id= ownership.veh_id); 	0.548034475286497
13555890	16623	sql server 2008 display city name from knowing zip code	select   allcustomer.customername,   allcity.cityname from customer finder   join city findercity    on finder.zipcode = findercity.zipcode   join city allcity     on findercity.cityname = allcity.cityname     and findercity.statecode = allcity.statecode   join customer allcustomer     on allcity.zipcode = allcustomer.zipcode where finder.customername = 'william'   and allcustomer.customername != 'william' 	0.000683772726345464
13556557	21244	how to return in mysql group by the first record by date?	select  a.* from    tablename a         inner join         (             select  title, min(date) mindate             from tablename             group by title         ) b on a.title = b.titleand                 a.date = b.maxdate 	0
13557106	22842	sql - combining two queries	select   b.brand_id,   b.brand_name,   m.model_name,   c.class_name,   v.veh_id,   v.veh_year,   v.veh_price from    (((vehicle as v inner join class as c on v.class_id = c.class_id)      inner join model as m on m.model_id = v.model_id)     inner join brand as b on b.brand_id = m.brand_id)    inner join (select m.brand_id, max(v.veh_price) as veh_price               from vehicle as v                    inner join model as m                    on m.model_id = v.model_id               where                 not exists                   (select null from ownership                    where v.veh_id=ownership.veh_id)               group by m.brand_id) as derived   on (v.veh_price = derived.veh_price)   and (b.brand_id = derived.brand_id) where   not exists   (select null from ownership    where v.veh_id=ownership.veh_id) order by 7 desc; 	0.081417787109067
13557281	22815	optimal database structure for entries in flexible category/subcategory system?	select reviews.title, reviews.stub from reviews, review_in_category where reviews.id = review_in_category.review_id and category_id = $category 	0.150644447610502
13558183	5168	how to convert a jde date into a sql date within a stored proceedure	select distinct     ivlitm,    ivcitm,    iveftj,    dateadd(day, convert(int, substring(iveftj, 4, 3)), convert(datetime,convert(varchar(4), convert(int, substring(iveftj, 1, 1))*100 + 1900 + convert(int, substring(iveftj, 2, 2))) + '-01-01 00:00:00', 121)) as bcdate  from openquery(gdcjde9prodr, ' select     ivlitm,    ivcitm,    iveftj,    iveftj from  proddta.f4104 where ivxrt = ''up''  ') 	0.00238203399049733
13558440	28175	select query for exact time stamp	select date_format(time_stamp, '%y-%m-%d %h:%i:%s' ) as time_stamp    from log     where username='test' and time_stamp <= now()    order by time_stamp desc limit 1; 	0.0166707860455578
13558580	3532	selecting rows using a variable with multiple values	select column_name(s) from table_name where column_name in (value1,value2,...) 	0.00131678454466805
13559694	21165	mysql how to query list of posts and its multiple tags which are in different tables	select image_name, grp_concat(tag_name) from images, tags, tagnames where tags.image_id = images.image_id and tags.tag_id = tagnames.tag_id  group by image_name 	0
13560808	34382	categorize auto complete data	select 1 as type,tname as keyword from t                     union                     select 2 as type,sname as keyword from sub                     union                     select 3 as type,cname as keyword from c                     union                     select 4 as type,iname as keyword from i foreach($results as $result) {     switch($result['type'])     {         case 1:         $cat_1[]=$result;         break;         case 2:         $cat_2[]=$result;         break;     } } 	0.0269594175515327
13562721	3573	sql how to merge select statement	select   t1.departure as source,          t1.destination as destination1,          t2.destination as destination2   from      trktripleg t1          left outer join             trktripleg t2          on t2.t# = t1.t# and t2.leg# = 2  where   t1.leg# = 1; 	0.115186846472728
13563182	30384	sum all row exclude the negative numbers in oracle reports	select sum( case when column_name > 0                   then column_name                  else 0               end ) sum_of_non_negative   from table_name 	0
13563423	4136	check if the current date is between two dates + mysql select query	select * from `table` where active=0 and curdate() between datestart and dateend 	0
13563669	23293	mysql select query 2 where options	select *  from products  where stock > 0  order by  case when rrp != 0 then 0 else 1 end, id desc 	0.177522547785985
13563849	34756	mysql lowercase returned value or entire result	select lower(sg.group_name) group_name, lower(a.dept_name) dept_name from   `sys_groups` `sg`        inner join (select gda.group_id,        group_concat(sd.dept_name order by `dept_name`                   separator '|'                   ) `dept_name`        from   `group_dept_access` `gda`        inner join `sys_department` `sd`        on gda.dept_id = sd.dept_id        group  by gda.group_id) as `a`        on sg.group_id = a.group_id 	0.00837926669824166
13563899	7767	how to count number of records on the same time interval in past?	select     sum(if(date(mytable.date_doc) between '2012-11-03' and '2012-11-12', 1, 0)) as count_interval1,    sum(if(date(mytable.date_doc) between subdate('2012-11-03', datediff('2012-11-12', '2012-11-03') + 1) and subdate('2012-11-03', 1), 1, 0)) as count_interval2 from mytable 	0
13564219	27233	get other fields when retrieving max value from a line in mysql	select a,(select b from table1 t1 where t1.a=t2.a and t1.c=t2.c) b ,max(c) c   from table1 t2 group by a; 	0
13564369	13096	using column data as pattern for regexp match	select * from table1 t where 'cat' ~ t.reg; 	0.0495106422603042
13566117	37051	group by a nullable column	select cola, min(colb) from t where cola is not null group by cola union all select cola, colb from t where cola is null 	0.0445786897186557
13566218	14319	sql query, get a columns if another columns equal to x	select x, y from your_table where x in  (   select distinct x   from your_table   where y = 5 ) 	0
13566695	17067	select increment counter in mysql	select name,       @rownum := @rownum + 1 from your_table cross join (select @rownum := 0) r 	0.085913398634679
13567243	20208	orderby word in sql	select * from tablename order by field(`status`, 'pending','approved','rejected') 	0.462134761417797
13567694	4725	showing sum of amount based on another row value	select `year-month`,        sum(case when type = 'income' then amount else 0 end) `sum-income`,        sum(case when type = 'outcome' then amount  else 0 end) `sum-outcome`,        sum(amount) `sum-total balance` from <joins> group by `year-month` 	0
13568635	26799	pulling columns from two tables when there is a group by	select     inner.cworderid,            inner.cwcreated,            inner.organisationtype,            inner.custref,            inner.tetranumber,            inner.buildingname,            inner.streetname,            inner.posttown,            inner.postcode,            inner.country from(              select   h.cworderid,            h.cwcreated,            h.organisationtype,            h.custref,            h.tetranumber,            c.buildingname,            c.streetname,            c.posttown,            c.postcode,            c.country,            count(distinct tetranumber) over(partition by h.custref) cnt     from   cdsheader h, custandaddr c     where  h.custref = c.cwdocid         and c.addresstype = 'c'       )inner   where inner.cnt>1   order by inner.custref, inner.tetranumber, inner.cworderid; 	0.000353163871752912
13568963	28856	how can a mysql query return several records from a single row?	select * from table where field1=1 union all select * from table where field2=1 union all select * from table where field3=1 	0
13569658	16579	exists in query how to?	select  from financeaccountcurrencymapping  where ownedaccount_id in (select id from ownedaccount where legalentity_id = ??); 	0.325164032115571
13569925	4407	check for number of rows on left joined query	select  case when `second table`.joinfield is null then 'no match' else 'match' end as is_match 	0.000563086237496483
13572343	22445	how to select distinct records from two tables, combine into one column, and eliminate all records that exist in another table using sqlite?	select index_text as unique_text  from words where index_text not in (select body from sms) union select c1index_text  from words_content where c1index_text not in (select body from sms) order by unique_text 	0
13572696	32414	get last occurrence (if 1+ occurred) or first scheduled (if none occurred)	select      top 1 *  from      table  order by      started desc,     scheduled asc 	0
13572876	34824	select data where date is this week?	select * from log  where yearweek(curdate()) = yearweek(timestamp) 	0.0282886583786033
13573094	26632	how to select exact value from sql statement	select records from mytable where records like 'she %' 	0.00578334215240712
13573322	5631	using count on when creating a view	select e.name,         e."date",         b."limit",        b.allocated_amount,         (select count(member_id) from event_members) as mem_count,         e.comments from events e inner join budgets b on b.event_id = e.id inner join event_members em on em.event_id  = e.id; 	0.513579634014495
13575259	40240	is it possible to just use mysql queries to group by a time frame?	select distinct ip from logs_table group by ip, date_format(`time`, '%y%m%d%h') having count(*) > 10 	0.481890610106838
13575560	16238	how to select rows based on two distinct columns?	select * from table where id in  (   select min(id)   from table    group by  type, type_id  ) order by id desc limit 4 	0
13576402	12919	how to include count equal to 0 on this query?	select  a.state ,          coalesce(b.count, 0) as count from      (         select 'done' as state         union         select 'open' as state         union         select 'pending' as state         union         select 'draft' as state         union         select 'cancel' as state     ) a left join      (         select  state ,                  count(*) as count         from    crm_lead         group by state     ) b on a.state = b.state 	0.249564131174263
13576459	29687	how to efficiently query for an user "items" in a data base? (amazon simpledb)	select items.name from items inner join users on items.user = users.id where users.username = 'luis' 	0.00287154160833458
13578092	21627	adding two columns from tables having same structure	select date, sum(value) from (     select date, value from table1     union all     select date, value from table2 ) a group by date 	6.38335831440785e-05
13578889	14041	to return only the latest row	select    transfer_id      ,    transfer_date    ,    asset_category_id,    asset_id         ,    transfer_from_id ,    transfer_to_id   ,    stock_tag  from (    select      transfer_id      ,      transfer_date    ,      asset_category_id,      asset_id         ,      transfer_from_id ,      transfer_to_id   ,      stock_tag        ,      row_number() over (        partition by stock_tag        order by     transfer_date desc,                     transfer_id desc) rn    from transfer)  where rn = 1 	0
13579253	11606	in sql server 2008	select  tblproductmaster.*,avg(tblreviewmaster.rating) from tblproductmaster      left join tblreviewmaster      on tblproductmaster.productid = tblreviewmaster.productid        group by tblproductmaster.* 	0.739607808182405
13579312	24575	select pkg_name.function_name	select 'jk' as name,         pckg_name1.function_name1(number1,number2)  from dual 	0.385581433524547
13579763	13809	sql query to find out experience of employee in the format 'yy years mm months dd days'	select      empid, empname, department, designation,      convert(varchar(3),datediff(month, doj, getdate())/12) +' years '+     convert(varchar(2),datediff(month, doj, getdate()) % 12)+ ' months'      as experience,      empstatus as job_status  from employee 	0
13581466	32522	select datas from firsttable and order by field in secondtable in mysql	select *, (             select count(*)              from je_uservote t2              where t2.pollid=t1.pollid              and t2.choiceid=t1.choiceid) as votes from je_addchoice t1 order by votes 	0.00599570654804248
13581479	14129	order by unselected column with union	select rowtype     , id     , date     , title from  (     select 'album' as rowtype , id , date , title , time_added     from albums     where is_temp = 0 and subject_id = '3'     union all     select 'video' as rowtype , id , date , title , time_added     from videos     where is_temp = 0 and subject_id = '3'     union all     select 'story' as rowtype , id , date , title , time_added     from stories     where is_temp = 0 and subject_id = '3' ) s order by date , time_added 	0.517204053535284
13582000	13377	select all the employee in all departments which are having highest salary in that department	select      department.name,      employee.name,     max(employee.salary) from      department  left outer join employee on (employee.department_id = department.id) group by department.id 	0
13584137	37604	mysql efficient and correct linking of group by results	select cid,count(distinct raid) as as_all,sum(if(condition=1, 1, 0)) as as_active  from mytable group by cid 	0.152354444579111
13584160	1204	query for student's marks and grades in moodle	select    u.id as userid,   u.username as studentid,   gi.id as itemid,   c.shortname as courseshortname,   gi.itemname as itemname,   gi.grademax as itemgrademax,   gi.aggregationcoef as itemaggregation,   g.finalgrade as finalgrade   from mdl_user u   join mdl_grade_grades g on g.userid = u.id   join mdl_grade_items gi on g.itemid =  gi.id   join mdl_course c on c.id = gi.courseid   where gi.courseid  = :courseid and u.username = :username; 	0.412900705083887
13585056	40937	mysql filter by result of sub query	select * from  (select a.*, a.id as id_player, (select count(id) from `vd7qw_footsal_goals` where a.id = id_player and g.id = id_group) as goals,  team.* from `vd7qw_footsal_players` as a  left join vd7qw_footsal_teams as team on team.id= a.id_team left join vd7qw_footsal_teamofgroup as tog on tog.id_team = team.id 4 left join vd7qw_footsal_groups as g on g.id = tog.id_group where g.id in (select id_group from `vd7qw_footsal_groupofleague` where id_league = 2)  and (a.state in (1))) as a where goals > 0 order by goals desc 	0.315312864054052
13585179	16140	calculations on columns in mysql	select (column1+column2+columnn)/column6 from mytable order by (column1+column2+columnn)/column6 	0.0384458960005483
13586513	24539	sql view with relational table	select      a.articleid, a.name,      stuff(          (select ',' + cast(mediaid as varchar(10))           from  tbarticlemedia           where articleid = a.articleid           for xml path (''))           , 1, 1, '')  as multimediaid from tbarticle as a      inner join tbarticlemedia b         on a.articleid = b.articleid group by a.articleid, a.name 	0.400809793230343
13586677	33729	mysql reciprocal search	select one.from_node, one.to_node  from edges one  join edges other on (one.to_node = other.from_node and one.from_node = other.to_node) where one.strength > 3 and other.strength > 3     and one.from_node <> one.to_node 	0.69020062436661
13588313	20386	sql sum a count from an inner query	select sum(cnt) from     (         select count(*) as cnt         from users         group by email         having count(*)>1     ) as t 	0.182715999045348
13588409	25635	group sales by day of the week	select date(from_unixtime(time)) time,        sum(sell_price),        sum(buy_price) from tablename group by date(from_unixtime(time)) 	0
13588984	17025	is any way to convert decimal to time in mysql?	select @indexer:=instr(dateasdecimal, '.') , left(dateasdecimal, @indexer-1) * 60 + substr(dateasdecimal, @indexer+1)  as totalminutes from testtable; select @indexer:=instr(dateasdecimal, '.') , sum(left(dateasdecimal, @indexer-1) * 60 + substr(dateasdecimal, @indexer+1))  as totalminutes from testtable; 	0.0999231010471586
13589553	38717	select data from today until the last 15th of month?	select * from yourtable where yourdate > cast((             case                  when day(getdate()) < 15                     then (cast(year(getdate()) as char(4)) + cast(month(dateadd(month, - 1, getdate())) as char(2)) + '15')                 else cast(year(getdate()) as char(4)) + cast(month(getdate()) as char(2)) + '15'                 end             ) as datetime) 	0
13590373	1608	restaurant table availability check for a particular time using sql	select t.table_id from table as t left outer join booking_table as b on b.booking_table_id = t.table_id where b.booking_id is null     or date_add(now(), interval 2 hour) > b.reservation_date 	0.010673064110898
13590389	641	do something when mysql column value increments by 100	select username from `user`  where username='$username' and mod(posts,100) = 0 	0.0145048864413546
13591335	8309	combine multiple sql queries	select pk2.pubkey_hash from   pubkey pk inner join txin_corr tc on pk.pubkey_id = tc.pubkey_id left outer join txin_corr tc2 on tc.tx_id = tc2.tx_id left outer join pubkey pk2 on tc2.pubkey_id = pk2.pubkey_id where pk.pubkey_hash = (input data) 	0.134328989727784
13591603	35426	how can i combine two similar grouped result sets into one?	select [date],         datename(weekday, [date]) as [day],         sum(case when source = 1 then value else 0 end) as [total claims],        sum(case when source = 2 then value else 0 end) as [reversed claims] from (   select          1 as source,          [date],          count(*) as value    from  claimhistoryview    group by [date] union all   select          2 as source,         [date],           count(*) as value    from  claimhistoryview    where status = 2    group by [date] ) as countbyday  group by [date] order by [date] desc 	0
13591794	31723	mysql tied maxes	select  teacher_no, date, count(date) as counted from    spanish s group by teacher_no, date having  count(date) = (select count(date) as counted                        from spanish                        where teacher_no = s.teacher_no                        group by teacher_no, date                        order by counted desc                        limit 1                       ); 	0.425786500940769
13591818	22311	transpose or unpivot every other column	select   x.newcolumn1,   x.newcolumn2 from yourtable t cross apply (     values         (t.oldcolumn1, t.oldcolumn2),         (t.oldcolumn3, t.oldcolumn4),         ... ) x (newcolumn1, newcolumn2); 	0.00495870225183497
13593225	16031	how to calculate a percentage from a single table	select userid, sum(if(success = 1, 1, 0)) / count(*) * 100 as pct  from bets group by userid; 	0
13593373	20713	sql select only once of each id, chosen by earliest datetime	select   t, messageid, receiver, createddate, itemid  from   (     select        m.messageid, m.receiver, m.createddate, m.t,       i.itemid      from       items i       inner join (         select description, messageid, receiver, createddate, 0 t from messages_0          union          select description, messageid, receiver, createddate, 1 t from messages_1       ) m on m.description like '%' + i.name + '%'               and m.receiver in ('100', '200')     where       i.itemid in (1, 2, 3)   ) data where   createddate = (     select min(createddate) from (       select createddate from messages_0 where messageid = data.messageid and data.t = 0       union       select createddate from messages_1 where messageid = data.messageid and data.t = 1     )   ) 	0
13593897	31381	using coalesce to return meta title value with page information for navigation array	select   cms_page.*,   coalesce(cms_pm2.meta_id, cms_pm1.meta_id) as meta_id,   coalesce(cms_pm2.tag_name, cms_pm1.tag_name) as tag_name,   coalesce(cms_pm2.tag_value, cms_pm1.tag_value) as tag_value from   cms_pages left join cms_page_meta cms_pm1   on cms_pm1.page_id = cms_pages.page_id      and cms_pm1.location_id = 0   left join cms_page_meta cms_pm2   on cms_pm2.page_id = cms_pages.page_id      and cms_pm2.location_id = x       order by cms_pages.page_order 	0.00216777909224765
13593989	3404	what's the point of using explicit data types in pdo::bindvalue()?	select * from ... limit :intvalues 	0.225962852122268
13594610	4474	how to find max value from multiple columns mysql	select a.*  from tablea a      inner join tableb b         on a.s = b.s where b.qty = (select max(qty) from tableb) 	0
13597054	16231	mysql left join with multiple rows	select * from users where id not in (select userid from music where id=3) 	0.390173768865329
13597470	24815	show correct "most visited" date	select date(date_firstvisit) dates, count(*) totalcount from visitors group by date(date_firstvisit) having count(*) =  (   select max(s)   from(   select count(*) s   from visitors   group by date(date_firstvisit))s ) 	0.00277089857633915
13598450	40091	add column to say which table a union result is from	select * from (     select *, 'tablea' as tablename from tablea     union all     select *, 'tableb' as tablename from tableb     union all     select *, 'tablec' as tablename from tablec ) s where   colname = 'hello' 	0.000588881663313654
13599454	39068	query on a self-referential table	select  a."userid",         a."name",         b."name" as aidname from    tablename a         inner join tablename b             on a."aidid" = b."userid" 	0.0808607403029631
13599483	23780	selecting only a single row per id	select * from  (select t.*,    row_number() over (partition by id order by id) as rownumber from t ) t1 where t1.rownumber=1 	0
13600110	31632	solve query for showing top 5 selling products	select top 5 item_code, sum(quantity) from customer_invoice group by item_code order by sum(quantity) desc 	0.330024244943215
13600266	32732	oracle sql to calculate gpa from grades	select id, sum(case name                      when 'a+' then 4.5                      when 'a' then 4                     when 'b+' then 3.5                     when 'b' then 3                     when 'c+' then 2.5                     when 'c' then 2                     else 0                end                )/count(*) gpa from table  where id in ('s11','s12','s13','s14') group by id 	0.0173931462145808
13600480	39973	extract data from xml clob using sql from oracle database	select extractvalue(xmltype(testclob), '/dcresponse/contextdata/field[@key="decision"]')  from traptabclob; 	0.000937336931270052
13600710	936	mysql query distinct in paris php	select a.* from    tablename a         inner join         (             select name, max(timestamp) maxstamp             from tablename             group by name         ) b on a.name = b.name and                 a.timestamp = b.maxstamp 	0.604839360693046
13603634	33541	active subscription per month based on end date?	select year(startdate)year, month(startdate)month, sum(price)price from table group by month(startdate) 	0
13603791	31448	converting varchar to date format	select convert(datetime, '2012' + left(date_issued, 2) + right(date_issued, 2) + ' ' + left(time_issued, 2) + ':' + substring(time_issued, 3, 2) + ':' + right(time_issued, 2)) 	0.073874060750069
13604844	34129	how do i round to 3d.p in mysql	select format (price ,3) from tablename ; 	0.308040289018027
13605872	25970	mysql query for grouping data	select  country,  city,  age,  count(user_id) as age_count from user  group by country, city, round(age) 	0.214270741174393
13606263	40967	how to get non-numeric entries in a column of a database	select * from customers where isnumeric(ccexperiation) = 0 	0
13607057	40865	selecting greatest value of b for equal entries in a	select a, max(b)    from tbl   group by a   having count(a) > 1 	0
13608160	39976	sql join on split?	select * from email  left join emailname on substring(email.address, 1, charindex('@', email.address) - 1) = emailname.name 	0.13930171981269
13608461	12352	multiple tables query android	select * from article a  inner join group g on  (a.groupid = g.groupid) inner join code c on (a.codeid = c.codeid) 	0.326484415397518
13609245	4677	compute sum sqlplus	select member.member_id,        substr(member.fname, 0, 10) || substr(' ', 0, 10) ||        substr(member.sname, 0, 15) as membername,        rental.rental_id,        tool.name,        rental_line.qty,        rental_line.price,        to_char(rental_line.qty * rental_line.price, 'l9,999.99') total,        sum(rental_line.qty) over (partition by rental.rental_id) total_qty,        sum(rental_line.qty * rental_line.price) over (partition by rental.rental_id) total_sum   from rental_line  inner join rental on rental.rental_id = rental_line.rental_id  inner join member on rental.member_id = member.member_id  inner join tool_instance on rental_line.tool_instance_id =                              tool_instance.tool_instance_id  inner join tool on tool_instance.tool_id = tool.tool_id  where rental.rental_id = '&rental_id'; 	0.47275805902003
13610971	36016	math within a sql query - adding 'results' to display new 'results'	select  [agtname] ,       count(*) from    fndynamiccscagtfctbymth('09/24/2012','11/07/2012')  where   acct_mo_n = 'october'  group by          agtname order by          agtname desc 	0.0173896655278041
13611893	2667	tsql order data according to dates	select name, min(date) as startdate, max(date) as enddate, sum(points) from people where date between to_date ('2003/01/01', 'yyyy/mm/dd') and to_date ('2003/12/31', 'yyyy/mm/dd')  group by name order by points; 	0.00442405103880295
13614251	20138	consolidate rows in postgresql	select nodups.id, nodups.fname, nodups.lname, d1.data1, d2.data2 from   (select min(id) as id, fname, lname from sample group by fname, lname) nodups left join   (select fname, lname, min(data1) as data1    from (select fname, lname            , first_value(data1) over (partition by fname, lname order by id) as data1          from sample where data1 is not null) d1x    group by fname, lname   ) d1 using (fname, lname) left join   (select fname, lname, min(data2) as data2    from (select fname, lname            , first_value(data2) over (partition by fname, lname order by id) as data2          from sample where data2 is not null) d2x    group by fname, lname   ) d2 using (fname, lname) order by id ; 	0.0382852612406813
13615250	8509	turn sql server table variable into real table	select * into table  from @table  	0.017121438629928
13615370	15710	adding a filter to a having query	select f.client_id      from f_accession_daily f      join (         select client_id           from f_accession_daily          where received_date between '20120501' and '20120531'       group by client_id         having count(*) >= 40       ) a on a.client_id = f.client_id left join salesdwh..testpractices tests        on tests.clientid=f.client_id     where tests.clientid is null  group by f.client_id    having max(f.received_date) between '20120601' and '20120630'; 	0.246097662689129
13617430	36554	sql statement with multiple distinct	select     leftside.name,     leftside.description from     tablea as leftside     left join tablea as rightside on (         leftside.description = rightside.description and         leftside.name <> rightside.name     ) where     rightside.description is null and     leftside.description not like 'any%' and     leftside.description not like 'deleted%' group by     leftside.name, leftside.description order by     leftside.name 	0.482158843352827
13617494	26081	sort rows by multiple columns	select *, greatest(created, updated) as last_activity from events order by last_activity desc 	0.00101118648528304
13617611	32752	joining tables and then referencing themselves	select m.*   from movies m  where exists (select 1                  from roles r1                       inner join actors a1                          on a1.actor_id = r1.actor_id                 where r1.movie_id = m.movie_id                   and a1.first_name = 'kevin'                   and a1.last_name = 'spacey')    and exists (select 1                  from roles r2                       inner join actors a2                          on a2.actor_id = r2.actor_id                 where r2.movie_id = m.movie_id                   and a2.first_name = 'will'                   and a2.last_name = 'smith') 	0.129069933945785
13620117	24146	join two mysql tables and display data order by date	select * from  (select sr.date, if(sr.noofshares > 0, 'shares bought', 'shares sold') description,           sr.noofshares, sr.amount, '-' interest, sr.amount total  from tblsharesregistry sr where sr.empnumber = '1001'  union  select sa.date, 'interest' description, (select sum(sr.noofshares) from tblsharesregistry sr  where sa.empnumber = se.empnumber) noofshares,           sa.balance, sa.interest, (sa.balance + sa.interest) total  from tblsharesaccount sa where sa.empnumber = '1001' ) as a  order by a.date 	0.00031364879984823
13620866	19943	sql query to select data from two tables	select invitations.*, users.username from     invitations left join               users on invitations.userid = users.userid 	0.00191044262518503
13621653	37941	how to check if a column data from table exist in the same table?	select date1.* from dates date1 join dates date2 on date1.id_a = date1.id_a where date1.date2 = date2.date1 union select d2.* from dates date1 join dates date2 on date1.id_a = date2.id_a where date1.date2 = date2.date1 	0
13622603	29833	how do i get last 7 bet slips (betslipid) for the certain user	select betsliphistory.matchid,team1.name as hometeam ,                        team2.name as awayteam, betslipid , userid , tipid , matches.resulttipid ,betsliphistory.`date`                       from betsliphistory                       inner join matches on betsliphistory.matchid = matches.matchid                       inner join teams as team1 on matches.hometeamid = team1.teamid                       inner join teams as team2 on matches.awayteamid = team2.teamid                       inner join (select distinct(betslipid) tempbetslip from betsliphistory where userid =".$user."  order by `date` limit 7) temp_bethistory on temp_bethistory.tempbetslip = betslipid                           where userid =".$user." order by `betslipid` 	0
13624896	26728	find and replace value between two tables column with different datatype	select  a.custid,         b.custunqid into    #temp from    tbl_customermaster a join    tbl_customer b on         a.custid = b.custid update  tbl_customermaster set     custid = t.custunqid from    tbl_customermaster a join    #temp t on         t.custid = a.custid 	0
13626782	37891	oracle table value merging	select suppname from suppliers sp   join (select suppcode         from stocks         group by suppcode                having count(distinct storecode)>=4         order by suppcode desc   ) st on st.suppcode = sp.suppcode; 	0.00526202047694307
13627263	33816	how do i select a column which is a concatenation of two columns in the same table?	select *  from tablex  where fieldid <> empid + reason     or fieldid is null     and (empid + reason) is not null    or fieldid is not null and (empid + reason) is null ; 	0
13627639	3511	sql server query excude all null values	select  sum(case when tblname1 is null then 0 else 1 end) +  sum(case when tblname2 is null then 0 else 1 end) +  sum(case when tblname3 is null then 0 else 1 end) +  sum(case when tblname4 is null then 0 else 1 end) +  sum(case when tblname5 is null then 0 else 1 end) +  sum(case when tblname6 is null then 0 else 1 end) +  sum(case when tblname7 is null then 0 else 1 end) +  sum(case when tblname8 is null then 0 else 1 end)    from jsettings  where linktojotdata = '56211010105' 	0.0601380120550498
13631013	35102	mysql like in() and using and	select title from titles where match (title) against ('+red* +green* +yellow*' in boolean mode); 	0.735430937446198
13631424	39821	mysql 'select' limit to variable string	select * from jos_mls where mstlistbrd = '3675e4340e0560' 	0.176552441684222
13633531	16521	compare two rows to each other sql server	select     name, age, phone from     _yourtable_ where     phone in         (select             phone         from             _yourtable_         group by             phone         having             count(*) > 1         ) 	0
13635614	13625	get first or most repeated value from a group by in sql server	select substring(code,1,3) as smallcode, code, name into #tmpcode from originaltable select smallcode, name into #tmpreducedcode from (     select smallcode, name, row_number() over (partition by smallcode order by total desc) rn     from (         select smallcode, name, count(*) total         from #tmpcode         group by smallcode, name) x) y where rn=1; select distinct a.smallcode, b.name from #tmpcode a     inner join #tmpreducedcode b         on left(a.code,3) = b.smallcode 	0
13636788	38136	mysql - subtract values that exist in another table	select * from report_detail rd where rd.report_id not in (select disctinct rs.report_id from report_subscriptions rs) 	8.07471831719963e-05
13637036	30615	find values in table that only have one value	select sm.regnum from tbl_studentmodules sm left join tbl_student s on s.regnum = sm.regnum and level = $level group by sm.regnum having sum(status <> 'c') = 0 	0
13637417	30057	mysql - where clause for date comparison	select count(*) from sl_list  where type = 'pantry' and date(create_dtime) <> date(mod_dtime) 	0.77608276232897
13637579	22192	combine two sql query into 1	select    company.company_id,           users_pts.pts as companypts,           t1.ultimate_survey_code_count,           t2.reward_id_count from      company,           users_codes inner join (           select                company_id,                count(ultimate_survey_code) as ultimate_survey_code_count           from users_survey_answers           where completed = 0           group by company_id           ) as t1        on users_codes.company_id = t1.company_id inner join (           select                company_id,                sum(if(redeemed = 0, 1, 0)) as reward_redeem_zero_count,               sum(if(redeemed = 0, 0, 1)) as reward_redeem_not_zero_count           from users_rewards           group by company_id           ) as t2        on users_codes.company_id = t2.company_id inner join users_pts        on users_codes.company_id = users_pts.company_id where     company.company_id = users_codes.company_id   and     users_codes.email = "test@gmail.com" 	0.0063211733464566
13637866	7577	removing first member of a string set in mysql	select mid('15, 1, 5, 4',locate(',','15, 1, 5, 4')+1) 	0.000478171678996174
13638435	29446	last executed queries for a specific database	select deqs.last_execution_time as [time], dest.text as [query], dest.* from sys.dm_exec_query_stats as deqs cross apply sys.dm_exec_sql_text(deqs.sql_handle) as dest where dest.dbid = db_id('msdb') order by deqs.last_execution_time desc 	0.0021247686540025
13639005	31882	how to get the six week sunday's weekno in sql server 2008 r2?	select datepart(week,'18-nov-2012') 	0.00541367628432341
13639199	13647	sql: get results, but add a column starting at number 2000	select pet.member_id, concat(  'full_', pet.member_id,  '.', pet.image_ext ) as post_thumbnail, @rownum := @rownum + 1 as id from pet,  (select @rownum := 1999) r where pet.image_ext !=  "" 	0
13639362	12592	combining multiple rows data into a single row of particular column	select      name ,      id ,      group_concat(date) as `date`,      group_concat(login) as login_time,      group_concat(logout) as logout_time from mytable group by name 	0
13639503	10789	search condition mysql if (name = name, limit 1, limit 5)	select * from mlt_adr_city     where     name = 'text'     and region_id = 59     and id <> 0     limit 1 union select * from mlt_adr_city     where     name like 'text%'     and region_id = 59     and id <> 0     and not exists (select 1 from mlt_adr_city where name = 'text' and region_id = 59 and id <> 0)     limit 5; 	0.0145438565163795
13640293	32034	is it possible to nest group by statements inside of each other?	select video_id, count( distinct ip_address) as num_unique_requests from  videos group by video_id order by num_unique_requests desc 	0.0263422632277542
13641230	29100	make column values in a table have equal number of characters	select      left(fieldid, 1) +      right('000000' + right(fieldid, len(fieldid) - 1), 5) from domaindetail 	0
13643451	31384	sql server query to count	select count(*)  from invitations      left join users                                           on invitations.email = users.username where users.username is null 	0.482854569276105
13645925	23969	mysql: finding the missing values from tables	select  alldays.emp_code, alldays.date_value from    (           select date_value, emp_code           from temp_days           cross join checkin_out           group by date_value, emp_code         ) alldays         left join checkin_out c             on alldays.date_value = c.checked_date             and alldays.emp_code = c.emp_code where   c.emp_code is null 	0.000293478680429928
13647713	10570	trying to display results from mysql query of an array	select service_name from services where service_id in (1,7,3)                                                   ^^^^ 	0.000883384957306478
13651508	12345	or condition with group by	select     o.last_name, o.first_name, a.observer_id, count(a.observer_id) as animals_seen,     sum(iif(a.animal = "bear", 1, 0)) as bearcount from      animals as a inner join observer as o  on      a.observer_id = o.observer_id group by      a.observer_id, o.last_name, o.first_name having     count(a.observer_id) > 4 or sum(iif(a.animal = "bear", 1, 0)) > 0 	0.663278241800248
13651587	13584	multiple count() in 1 sql query	select ( select     count(ur.ri) from       ur, uc where      redeemed = 0  and        ur.ci = uc.ci and        e = "test" group by   uc.ci ) as ur, ( select     count(usa.usc) from       usa, uc where      completed = 0 and        usa.ci = uc.ci and        e = "test" group by   uc.ci ) as usa 	0.177744497800808
13651956	23819	multiple count in sql issue	select count(distinct tl.itemlikeid) as a, count(distinct tib.packetid) as b 	0.797328139862574
13652971	37152	how to do avg() in from count()sql	select avg(a.#visit) from (select count(visittracking.customerid) as #visit,         max(visittracking.visitid) as visitid,         customers.title as title,         customers.firstname as [first name],         customers.lastname as [last name],         company.companyname as [company name],         max(visittracking.datevisited) as [date visited],         convert(date, max(visittracking.nextvisit)) as [next visit],         customers.customerid from visittracking  inner join customers on visittracking.customerid = customers.customerid inner join customer_company on customers.customerid = customer_company.customerid      inner join company on customer_company.companyid = company.companyid where visittracking.datevisited between '11/01/2012'  and '11/31/2012'  group by customers.title, customers.firstname, customers.lastname, company.companyname, customers.customerid) as a 	0.067596268693241
13655362	7279	display a yearly summary by month in sql	select     sum(amount) as [amount]     ,month(timestamp) as [month]     ,year(timestamp) as [year] from     [mytable] group by      month(timestamp)      ,year(timestamp) 	0.000315491285352527
13655929	14720	how to write a query to find records which do not belong the field selected?	select     m.* from     module m where     m.moduleid not in (                        select cm.moduleid                            from course_module cm                        where cm.courseid = 1                       ); 	8.69764997408468e-05
13657972	20123	echoing max or last greater id in a table	select max(id) as maxid from chat 	0
13658941	31945	delete part of a string in sql	select case          when myfield rlike ' - cap\\. [[:digit:]]{1,3}$' then            left(myfield, 1              + char_length(myfield)              - char_length(' - cap. ')              - locate(reverse(' - cap. '), reverse(myfield))            )          else myfield        end from   mytable 	0.0183340743069679
13659568	22257	rounding order volumes to a limiting total	select t.*, row_number() over (partition by orderid order by remainder desc) as seqnum,        (case when row_number() over (partition by orderid order by remainder desc) <= leftover              then appliedvolint + 1              else appliedvolint         end) as newvolume from (select t.*, floor(appliedvol) as appliedvolint,              (appliedvol - 1.000*floor(appliedvol)) as remainder,              maxvol*1.0 - sum(floor(appliedvol)) over (partition by orderid) as leftover       from (select oli.orderid, oli.proposedvolume, omax.maxvol,                    sum(proposedvolume) over (partition by oli.orderid) as sumproposed,                    omax.maxvol * (oli.proposedvolume / sum(proposedvolume) over (partition by oli.orderid)) as appliedvol             from #oli oli join                  #omax omax                  on oli.orderid = omax.orderid            ) t      ) t 	0.0308864769710862
13660062	28273	reverse column values	select concat(substring_index(salary,',',-1), ',', substring_index(salary,',',1)); 	0.0229569570592242
13662917	1712	exclude assigned articles from query	select distinct c1.*  from #__content c1 left outer join #__similar s on s.fav_id = c1.id left outer join c2 on c2.catid='$catid' and c2.id = s.assigned_id where c1.catid='$catid' and c2.id is null 	0.00117362293193639
13663594	16415	how to merge two sql queries to get latest wordpress post and featured image	select    p.post_title,   p.post_excerpt,   pm.meta_value as permalink,   p2.guid as thumbnail,   p2.post_title as thumbnail_alt from   wp_postmeta pm   inner join wp_posts p on (pm.post_id = p.id)   inner join wp_postmeta pm2 on (pm2.post_id = p.id)   inner join wp_posts p2 on (pm2.meta_value = p2.id) where   pm.meta_key = 'my_permalink' and   pm2.meta_key = '_thumbnail_id' and    p.id in (select * from vwlatestpostids) 	0
13663948	34244	listing highscores for each level using mysql	select       l.lid,       l.name,       l.levelcode,       if( prequery.highscore is null, 'no score', 'score' ) as hasascore,       coalesce( prequery.highscore, 0 ) as highscore,       if( prequery.userhs > 0, 'user has score', 'no user score' ) as userhasascore,       coalesce( prequery.userhs, 0 ) as userhighscore,       if( prequery.userhs > 0 and prequery.userhs = prequery.highscore,               'use has the high score', 'not the high score' ) as doesuserhavehighscore    from       levels l          left join ( select                            hs.lid,                            max( hs.score ) as highscore,                            max( if( hs.userid = useridyouarecheckingfor, hs.score, 0 )) as userhs                         from                            highscores hs                         group by                            hs.lid ) prequery             on l.lid = prequery.lid 	0.017772075616305
13664089	18689	select list of albums of artist and display for every album tracks count which have requested artist and album in list	select artist, album, count(*) as trackscount      from tracks      where artist = 'requested_artist'      group by artist, album; 	0
13664977	29268	random order by group in random order	select ln.id, gc.id     from parent p inner join          child ch          on ch.parent_id = p.id inner join          grandchild gc          on ch.id = gc.child_id inner join          (select ln.*, rand() as rand           from lastname ln          ) ln          on p.lastname = ln.lastname     where gc.city_id = 3     order by ln.rand 	0.0626181179668117
13665309	39894	how to randomly select one row off table based on critera	select factstring   from facttable   where eventid = 1   order by rand() 	0
13665381	1420	how do i query the latest save progress of a list of users. (php/html)	select user_id,name,score from your_table where (user_id,id) in (select user_id,max(id) from your_table group by user_id) 	6.61175482579195e-05
13666365	22482	join select from multiple row values?	select p.* from product p join (select a1.product_id id from product_attributes a1 join product_attributes a2 using (product_id)       where a1.attribute_name = 'size' and a1.attribute_value = '10'         and a2.attribute_name = 'colour' and a2.attribute_value = 'red') pa using (id) 	0.00101257558891154
13667392	497	limit number of records that are counted in sql	select count(*) from (     select state, postcode, havedog     from address     where state = 'ny' and postcode = 12405     order by surname desc     limit 5 ) t1 where havedog = 1 	4.65209427152808e-05
13671268	27916	display the cab with the highest overall maintenance cost	select * from (     select ca_make,  sum(ma_cost)     from cab join maintain on ca_cabnum = ma_cabnum      group by ca_make     order by sum(ma_cost) desc     ) where rownum = 1 	0.000236706815095229
13672703	145	create table from another one with additional parameters	select custcompanyname, custcontactname, custcontacttitle, custaddress, custcity, custregion,  custpostalcode, custcountry, custphone, custfax into customer from projecttable alter table customer add id int identity(1,1) primary key alter table customer add customer varchar(10) alter table customer add constraint customer_customer_fk foreign key ( customer ) references myothertable(pkcolumn) 	0.00099248266520305
13672717	3365	display driver and number of shifts involved in that are over 1	select dr_drvname, count(sh_drvnum) from driver join shift on dr_drvnum = sh_drvnum group by dr_drvname having count(sh_drvnum) > 1; 	0
13673453	36064	mysql count multiple rows by where clause	select vote, count(users.id) as `id` from users group by vote 	0.134386333942767
13674418	25422	sql: subtracting from different tables and using group by	select      i.ingredientname as 'ingredient name',      qoh as 'quantity on hand',         qoh - sum(brewline.quantity) over(partition by i.ingredientname) as 'amount' from ingredient i inner join brewline        on i.ingredientname = brewline.ingredientname 	0.000969910792521397
13678586	24493	mysql + php - 2 mysql tables populated with rows 1-300. one table holds 298, the other 300. show missing values?	select id from items where id not in (select item_id from item_categories); 	0
13678619	26873	sql for getting top user based on rating and using result to get additional data	select  x.country as countryname,         x.code,         a.totalcount as numberofgames,         y.name as playersname,         y.id as playersid,         a.totalrating from    (             select  player_id, country, count(*) totalcount, sum(rating) totalrating             from    games             group by player_id, country         ) a          inner join         (             select country, max(totalrating) maxrating             from             (                 select  player_id, country, sum(rating) totalrating                 from    games                 group by player_id, country             ) s             group by country         ) b on a.country = b.country and                 a.totalrating = b.maxrating         inner join country x             on a.country = x.id         inner join players y             on a.player_id = y.id 	0
13679073	8547	how to find one column in another in sql	select company.name from company, person where company.name not like '%' || person.sirname || '%' and person.company_id = company.id 	0.000138600400327404
13679641	23987	fetch column2 value corresponding to column1 maximum,minimum?	select date ,  max(psq_price),min(psq_price)     from mytable      group by date 	8.05136387535113e-05
13680007	30944	mysql query multiple and	select a.post_id from meta_table as a join meta_table as b on a.post_id = b.post_id where a.meta_value = 'value2' and b.meta_value = 'value4' 	0.353228078798956
13680874	15059	using aggregate to sum rows sql	select con, min(line_no), sum(wgt), pallet from dwd_temp  group by con, pallet 	0.125912875583819
13682151	14366	calculate total seconds of time intervals	select max(totalsec) - coalesce(sum(datediff(second, t.endtime, a.starttime)),0) from <table> t cross apply (select min(starttime) starttime from <table> where t.endtime < starttime) a cross apply(select datediff(second, min(starttime), max(endtime)) totalsec from <table>) b where  not exists (select 1 from <table> where id <> t.id and t.endtime >= starttime and t.endtime < endtime) 	0
13682384	23301	find lowest date (custom) in mysql	select min(concat(y,m,d)) from tablename 	0.00610540580851529
13682450	41188	sql in query from multiple tables	select distinct addresses.email from addresses join user_group     on user_group.id_user_groups = adresses.user_id join news_group     on news_group.groupid_newsg = user_group.id_group_groups where newsid_news_good = 1 	0.0366117372777687
13684942	33358	oracle jpg metadata xpath from xmltype column	select extractvalue(p.metaexif,'/exifmetadata/tiffifd/make',         'xmlns="http: 	0.350999338862335
13686136	25695	combine mysql query?	select * from (`lb_sales`) where ((`recurring` =  '0' and `created` >= '2012-10-01 00:00:00' and `created` <= '2012-10-30 23:59:59') or (`recurring` =  '1' and `created` <= '2012-10-30 23:59:59')) and `status` =  'pending' and `type` =  'sale' and `account_id` =  '2' order by `id` asc limit 10; 	0.224810600213342
13686200	36146	check equality of n numbers in mysql	select greatest(42, 42, 42) = least(42, 42, 42) 	0.00159465131583829
13686274	8252	select all records between two datetime format	select * from cdr where date(calldate) between '20121201' and '20121203'; 	0
13686385	37081	mysql query. give closest date to present day	select     o.order_id,     o.customer_id,     o.orderplaceservertime,     o.customerordertotal from      orders o     join (         select             o.customer_id,             max(o.orderplaceservicetime) 'maxorderplaceservicetime'         from              orders o             left join order_linedetails oln              on oln.order_id = o.order_id         where              o.orderplaceservertime >= '2012-09-01 00:00:00'         and o.orderplaceservertime <= '2012-12-01 00:00:00'         and o.customerordertotal >= '50'         and oln.product_id = '75'         group by o.customer_id     ) as a     on          o.customer_id = a.customer_id and          o.orderplaceservicetime = a.maxorderplaceservicetime 	0.000373393593734049
13687462	37251	codeigniter 2.1 - join two tables and count in the same query	select       n.id_news,       n.title,       n.body,       n.date_created,       n.image,       n.category_id,       count(c.id_comments) commentcount    from       news n          left join comments c             on n.id_news = c.news_id    group by        n.id_news    order by       whatever column(s) are important to you 	0.00311143924194297
13687910	34162	change results of sql query in asp page to include links for a specific column	select account, telephone, "<a href='"+communityurl+"'>"+community+"</a>" as communitycol, status from mytable order by account 	0.000518655992818602
13688557	10148	two databases merging into solr - how to keep uniqueid for entries?	select 'table1' || id as primary_id ... from table1 select 'table2' || id as primary_id ... from table2 	0
13688720	28342	system function to find the expression of a computed column?	select      name, definition from sys.computed_columns 	0.0238367455851617
13689782	35197	changing from static date to changing date in query & issue with aggregate function - mysql	select sum(date_format(purchasedate, '%m-%y') = concat('07-',year(curdate()))          / sum(date_format(purchasedate, '%m-%y') =                           concat('07-',year(date_sub(curdate(), interval 1 year))     from sales 	0.636867489066463
13690908	7702	how to select nearest ineger, thats bigger than value you've got	select *  from yourtable  where yourcolumn > yourint  order by yourcolumn limit 1 	0.0659050122490488
13692716	29591	oracle sql query to return rows from a table matching two conditions	select   e_salary  from     employees  where    grade in ('hc_1','hc_2')  group by e_salary  having   count(distinct grade) = 2 	0
13692914	24351	sql sort that distributes results	select subq.*   from (     select rank() over (partition by seller_id order by updated_at desc) rnk,            p.*       from products p) subq  order by rnk, updated_at desc; 	0.111909603293282
13694383	14134	query to find database version with as if then?	select id,filename,tag  from databasechangelog where tag is not null 	0.0356946308922469
13694548	38495	group in one table	select table1.data from table1 union all select table2.data from table2 union all select table3.data from table3 	0.0166886249407189
13694666	15026	converting two string fields into datetime	select dateserial(val(mid(eventd,7,4)), val(mid(eventd,4,2)), val(mid(eventd,1,2))) + timeserail(val(mid(eventt,1,2)), val(mid(eventt,4,2)), val(mid(eventt,7,2))) as datetimevalue from table1 	0.00291036517148415
13695340	38158	mysqli get information from two different tables	select post.text,post.username,post.id,post.likes,post.dislikes from post  inner join users  on post.username = users.username where post.school = '$sname'  and users.username = '$user' order by post.id desc limit 0,10 	0
13697411	7671	display column and return column lov	select empno return_value, empno||': '||ename||' - '||job display_value from emp 	0.000730886669008985
13697853	30317	multi user level with parent id in mysql	select  user_id  from  my_table  where parent_id in  ( select  user_id  from my_table where parent_id in  (select user_id from my_table where parent_id in(select user_id from my_table where parent_id =?))) 	0.0131285315230465
13699286	31131	find the time difference between rows	select yt1.[timestamp] as starttime, min(yt2.[timestamp]) as endtime, datediff(s, yt1.[timestamp], min(yt2.[timestamp])) as differenceinseconds from yourtable yt1 left join yt2 on yt1.[timestamp] < yt2.[timestamp] where yt1.col1 is null or yt1.col2 is null ... or yt1.col20 is null or yt2.col1 is null ... or yt2.col20 is null  group by yt1.[timestamp] 	0
13699453	13441	mysql join return null	select  distinct(table1.subject_code),  grade,  status from table1  left join table2 on (table1.subject_id=table2.subject_id) 	0.339917512815208
13700029	30289	getting multiple column values from subquery in sql server returns null	select      p.ids,      p.pid,      a.destination,      d.deldate,      d.deltimee,      d.deltimel,     edt.edatetime as edatetime,     ec.ecode as ecode,     tdl.source as source from parcel p left join party a on p.ids = a.ids left join dateandtime d on p.ids = d.ids left join ships s on p.ids = s.shipid left join (select pid , top(1) edatetime from tgdata where ecode='i') as edt on edt.pid = p.pid left join (select pid , top(1) ecode from tgdata where ecode='i') as ec on ec.pid=p.pid left join (select pid , top(1) source from tgdata where ecode='i') as tdl on tdl.pid=p.pid where s.isfinalized='1'      and s.dcomplete='2012-11-30'      and deldate is not null order by destination asc 	0.0155670554611007
13700183	11079	sql join and repeat the result?	select      participant.id_participant,     participant.id_poste,     participant.name,     participant.email,     formation.lable  from participant inner join profile_formaion on     profile_formaion.id_poste = participant.id_poste  inner join formation on     formation.id_formation = profile_formaion.id_formation 	0.0886075382692142
13701746	15343	how to group by data and calculate at a time in mysql?	select   pid,   sum(case when inputtype='expenses' then payable else amount end) as balance1,   sum(case when inputtype='expenses' then amount else payable end) as balance2 from tbl group by pid 	0.00070984173839077
13702696	23941	sql order by price / sqm	select *  from properties order by (price / floorsize); 	0.157139982986137
13703261	21581	solution to a select in a many to many relationship	select    proj_name,    proj_descr,    proj_what_we_did,    proj_url,    proj_descr_url,    group_concat(cat_name),     foto_url from   project p,    project_per_categories pc,   category c,    foto f where  p.proj_id = pc.project_proj_id    and pc.category_cat_id = c.cat_id    and p.proj_id = f.foto_id group by p.proj_id order by p.proj_id desc limit 6 	0.211769315880872
13703337	23491	php sql join together multiple tables from different databases	select * from database_1.logs as d1 left join database_2.users as d2    on d1.username = d2.username order by d1.timestamp desc limit 10 	0.0043873748873988
13703741	19862	order varchar value mysql	select * from `table` order by field(status, 'submit', 'cancel', 'update'); 	0.0493107329357371
13705301	29133	mysql - is it possible to display empty rows?	select m.month_first, count(x.date_of_car_sale) as sales from months m left join (   select date_of_car_sale   from sales ) x on m.month_first <= x.date_of_car_sale      and m.month_last >= x.date_of_car_sale group by m.month_first order by m.month_first 	0.00687761594110091
13705860	1758	how to extract polygons from a sql server geometry value	select @result = @usa.stintersection(@bounding) 	0.00168026577918999
13707610	13428	how can i relate a id to an actual name in a database	select p.description, s.supplierid, s.suppliername from product p inner join supplier s on s.supplierid = p.supplierid where p.id = some_value; 	0.000342510140877903
13707758	35792	how to perform a select if duplicates do not exist?	select count(name_of_col) from table_name group by name_of_col  having count(name_of_col) = 1 	0.262166073096537
13708294	1207	how to round a time to the nearest 15 minute segment	select sec_to_time(floor((time_to_sec(curtime())+450)/900)*900) 	0.00132090288675348
13708665	27108	sql to compare records (status change) in table	select     row_begin_dt,     user,     c_clm,     c_sta_clm,     max(c_sta_clm) over (partition by c_clm order by row_begin_dt rows between 1 preceding and 1 preceding) as prev_c_sta_clm from claims qualify c_sta_clm <> prev_c_sta_clm 	0.000200500719543407
13709382	12405	how to get a top count for distinct records in oracle?	select field1, field2, cnt from  (select field1, field2, cnt, rank() over (partition by field1 order by cnt desc) rnk from (select distinct field1, field2, count(field1) cnt             from table1             group by field1, field2             order by field1, count(field1) desc)  ) where rnk = 1; 	0.00011659716223718
13709728	6754	rounding to a specific number of significant digits in oracle	select round(1348,-2) from dual; 	0.000956902293991874
13710862	35126	joining many tables on same data and returning all rows	select    year,   month,   col1,   col2,   col3 from (   select year, month, 'col1' as col, data from t1   union all   select year, month, 'col2' as col, data from t2   union all   select year, month, 'col3' as col, data from t3 ) f pivot (   sum(data) for col in (col1, col2, col3) ) p ; 	0
13711158	26140	mysql query select current month error	select gva14.cod_vended, gva14.razon_soci, gva14.fecha_alta from gva14 where month(gva14.fecha_alta)=month(curdate()) and year(gva14.fecha_alta)=year(curdate()) group by gva14.cod_vended, gva14.razon_soci, gva14.fecha_alta 	0.0135642974716317
13713612	5258	how get previous values form last transaction using pk and fk	select p1.paymentid, p1.customerid, p1.paymentdate, max(pp.paymentid) from payment p1  join payment pp    on pp.paymentid < p1.paymentid   and pp.customerid = p1.customerid  and p1.paymentdate = '2012-11-03' groupby p1.paymentid, p1.customerid, p1.paymentdate not test but i think this will pull in the other data select pc.*, pl.paymentdate,  pl.amount,  pl.balance,  pl.credit  from  (select p1.paymentid, p1.customerid, p1.paymentdate, max(pp.paymentid) as priorpid from payment p1  join payment pp    on pp.paymentid < p1.paymentid   and pp.customerid = p1.customerid  and p1.paymentdate = '2012-11-03' groupby p1.paymentid, p1.customerid, p1.paymentdate) as pc  join payment pl    on pl.paymentid = pc.priorpid   and pl.customerid = pc.customerid 	0
13713692	21013	t-sql datemath: for any given date, find occurrence of the dayname in month, e.g. 3rd saturday	select ((datepart(d, @input) - 1) / 7) + 1 	0
13717563	26678	selecting common value of one column for array elements of another column	select  po_bill_details_id from table where po_id in ( ) group by po_bill_details_id having count(po_id)=( ) 	0
13717868	19115	mysql query to fetch the same datetime values	select  *  from table1  inner join  ( select  calldate from table  group by calldate  having count(*)>1 )  as temp_table on (table1.calldate=temp_table.calldate) 	0.000230551096959913
13718461	6275	mysql how to join these tables?	select   p.*,   s.* from   product p   inner join store s on s.store_id = p.store_id where   exists     (select       'x'     from       spec ps      where       ps.product_id = p.product_id) and   exists     (select       'x'     from       pictures pp      where       pp.product_id = p.product_id) 	0.227597133013439
13721955	28891	format one column and get rest of all column by one select	select customer.*, date_format(start_date, '%d.%m.%y')  from customer; 	0
13722206	13051	search in php same result displays many times?	select * from vendor inner join branches on branches.vendor_id = vender.vendor_id where (     vendor.name like '%".$query."%'     or vendor.description like '%".$query."%'     or branches.city like '%".$query."%' ) 	0.00777863606243949
13725849	24799	sql server check for data being updated	select max_dt, thetype from datalog d inner join (select max(thedt) as max_dt from datalog) m on d.thedt = m.max_dt 	0.0378555150636609
13726502	33621	count rows result set data	select count(*) from (original query) 	0.00340208661661851
13728632	24617	pull spefic record in a $row	select    left(a.f_anotrimestre, 4) year,   right(a.f_anotrimestre, 2) quarter,   if(right(a.f_anotrimestre, 2)=03,'enero a marzo',   if(right(a.f_anotrimestre, 2)=06,'abril a junio',   if(right(a.f_anotrimestre, 2)=09,'julio a septiembre',   if(right(a.f_anotrimestre, 2)=12,'octubre a diciembre',   '')   ))) quarter_name,   round(a.por_rentabilidad, 2) quarterly_yield   from      dr_rent_carteras_trimestres a   where     a.id_cartera = $id_cartera   and       a.ind_rentabilidad = 1   order by a.f_anotrimestre asc   limit 1,1 	0.000648841443124138
13729427	9725	how can i modify this data extraction from two mysql table result	select ifnull( b.number >0, 0 ) purchased from 1androidproducts a left join (    select count( * ) number, product    from 1androidsales     where udid = ''    and accountid = 2     group by product ) b  on a.apptitle = b.product where a.accountid = 2  order by a.apptitle limit 0 , 30 	0.00779527693203091
13730381	5303	sql sum after count	select y, z, count(*) as count,        sum(count(*)) over () as totalcount from schema.table where (schema.table.x like '%retire%' or schema.table.x like '%obsolete%') group by y, z 	0.112011241618407
13730776	5987	freetext search contains keyword	select * from sys.fulltext_system_stopwords 	0.596220047572249
13731205	2577	delete all but last entry for each individual	select * from my_table t1 join  (select id, year, max(week) maxweek from my_table where year = 2000 and binary_flag = 1 group by id,year) t2 on (t1.id=t2.id) and (t1.year=t2.year) and (t1.week=t2.maxweek) 	0
13732026	11240	order by last 3 chars	select * from table_name order by right(name, 3) asc; 	0.0063057997456565
13732586	5550	use charindex to find value in other column always returns 1 record	select part_no from part_tbl t1 where exists (select 1 from part_tbl t2 where charindex(t1.partno,t2.lookuppart)>0) 	0.000285645068506545
13733719	4152	how can i find out which version of postgresql i'm running?	select version(); 	0.0830446028264792
13734272	17612	sql server multiple database join and sum	select   product.cdes,   stock.ccode,   sum(case when stock.source = 'a001' then stock.amount else 0 end) as a001,   sum(case when stock.source = 'a002' then stock.amount else 0 end) as a002,   sum(case when stock.source = 'a003' then stock.amount else 0 end) as a003,   etc, etc from   a001.dbo.product inner join (   select 'a001' as source, id, ccode, cqtyin - cqtyout as amount from a001.dbo.pmstock   union all   select 'a002' as source, id, ccode, cqtyin - cqtyout as amount from a002.dbo.pmstock   union all   select 'a003' as source, id, ccode, cqtyin - cqtyout as amount from a003.dbo.pmstock   union all   etc, etc )   as stock     on stock.id = product.prid group by   stock.ccode,   product.cdes 	0.342194305187434
13734976	17874	sql best way to subtract a value of the previous row in the query?	select sum(a.starttime - a.lagend) as losttime  from (select [plantid], [starttime], [endtime],               lag([plantid]) over (order by plantid, starttime) lagplantid,              lag([endtime]) over (order by plantid, starttime) lagend        from machinerecords) a  where a.plantid = a.lagplantid 	0
13737656	36914	in sql, how to change the value in the table at the time of query	select case subject                      when 'm' then 'math'                      when 'ph' then 'physics'                      else subject end from tablea 	0
13739410	21386	merge two columns then group by and sorting	select loc, group_no  from (     select loc1 as loc, group_no, group_val      from test     union all     select loc2 as loc, group_no, group_val     from test ) t group by group_no, loc order by group_no asc, max(group_val) desc, loc asc ; 	0.000604711764050419
13739427	4051	sql query to get user id having latest date time	select * from (    select user_id, date    from mytable    order by date desc ) x group by date(date); 	0
13740228	9350	sql count per type per hour	select      year, month, day, hour,      count(t) as "items per hour",      count (distinct t) as "types per hour" from      ( select datepart(year,timestamp) year, datepart(month,timestamp) month, datepart(day,timestamp) day, datepart(hour, timestamp) hour, left (barcode,9) as t from [jci_trim].[dbo].[t6_trim] ) temp  group by year, month, day, hour  order by year desc, month desc, day desc 	7.50175921945803e-05
13740717	32015	arrange data according to timestamp newer to older	select cast(post_date as date) as dated from wp_hdflvvideoshare  group by dated  order by dated desc 	9.15226879206523e-05
13740851	17687	mysql query month selection error	select gva14.cod_vended, gva14.razon_soci, gva14.fecha_alta from gva14 where month(gva14.fecha_alta)=month(curdate())     and year(gva14.fecha_alta)=year(curdate()) group by gva14.cod_vended, gva14.razon_soci, gva14.fecha_alta 	0.497384206213705
13743517	40599	mysql custom select if sum>x	select        ticketid,       sum(price) totalprice    from        table     group by       ticketid    having       sum(price) > 50 	0.728532349002644
13743661	10731	summarising output from mysql query	select extended_number, sum(fax5) fax5, sum(fax10) fax10, sum(fax10plus) 'fax10+', sum(fax_total) fax_total  from (select left(extended_number,4) extended_number, if(count(extension_id)<5,1,0) as 'fax5',               if(count(extension_id)>5 and count(extension_id)<11,1,0) as 'fax10',        if(count(extension_id)>10,1,0) as 'fax10plus', count(extension_id) as 'fax_total'       from fax_authorized fa, extension e where fa.extension_id = e.id       group by extended_number) as a  group by extended_number; 	0.310766158276139
13745423	40251	select all ended bookings	select distinct b.*     from booking as b     join sequence as se     join session as s        on (b.sequence_id=se.id and s.sequence_id=se.id )     where s.stop between '2012-09-01 00:00:00' and '2012-12-01 00:00:00')        and not exists ( s.stop < '2012-09-01 00:00:00' )        and not exists ( s.stop > '2012-12-01 00:00:00'); 	0.168446975420751
13745577	17555	search multiple fields in table with mysql?	select *from users where name like %keyword% or surename like %keyword% or email like %keyword% or pin like %keyword% 	0.0569258476421201
13746304	38998	multiple column counts by week	select   week(post_timestamp) as week,   adddate(date(post_timestamp), interval 1-dayofweek(post_timestamp) day) as startdate,   count(distinct post_id),   count(comment_id) from   posts left join comments   on comments.posts_post_id = posts.post_id group by week, startdate 	0.000919095118368164
13746707	20866	join table with composite key twice	select id, summary, owner, c1.value, c2.value from ticket t inner join ticket_custom c1  on t.id = c1.ticket and c1.name = 'x' inner join ticket_custom c2  on t.id = c2.ticket and c2.name = 'y' 	0.169271051174835
13747500	13163	calculating distances between two tables full of geography points	select   t1.*,   t2.*,   t1.geoloc.stdistance(t2.geoloc) as distanceapart from table1 t1 join table2 t2 on (t1.geoloc.stdistance(t2.geoloc) <= @distancex) 	0.0166972627606377
13748534	20527	sql: keep one record from n-records with same foreign key	select customer, min(number) from your_table group by customer; 	0
13751457	10073	compare values in two columns	select * from table where columnb like '%' + columna + '%' 	0.000172555712489032
13751993	29878	mysql group results by one column but separate for unique second column	select code, name from items where code in (     select code      from items     group by code      having count(distinct name) > 1 ) t1 order by code, name 	0
13752023	36769	select one row with the max() value on a column	select top 1 * from newsletters where isactive = 1 order by publishdate desc 	0
13753481	32986	get html codes from sql server	select replace(yourcolumn, '''', '&#39;') from yourtable 	0.0166858108448628
13754177	34726	group table by field and display other fields	select t.user_id,        max(if(t.field_id = 1, t.value, null)) as key1,        max(if(t.field_id = 2, t.value, null)) as key2,        max(if(t.field_id = 3, t.value, null)) as key3 from my_table t group by t.user_id 	0
13755674	27345	join two tables with count from first table	select accountid, "count", read from     (         select accountid, count(*) "count"         from table1         group by accountid     ) t1     inner join     table2 t2 on t1.accountid = t2.customer_id order by accountid 	0.000143549319732764
13756006	7850	sql year to date report involving 3 tables	select cli.name, sum(useddollar) as useddollar, sum(budgetdollar) as budgetdollar (select clientid, energydollar as useddollar, 0.0 as budgetdollar from tbl_invoices where year = 2012 and month <= 9 union all select clientid, 0.0 as useddollar, energydollar as budgetdollar from tbl_budgets where year = 2012 and month <= 9 ) dt  inner join tbl_clients cli on dt.clientid = cli.id group by cli.name 	0.00433013397746442
13756289	22075	list the name of employee who workon one project sponsored by his/her division and also work on one project that is not sponsord by his/her division	select e.name from employee e where     exists (         select *         from              workon w             join project p                 on w.pid = p.pid                 and p.did = e.did         where w.empid = e.empid     )     and exists (         select *         from              workon w             join project p                 on w.pid = p.pid                 and p.did != e.did         where w.empid = e.empid     ) 	0
13758483	26676	sql filter many to many relationship	select     ct.competition_id from     competitions c join competition_type ct on ct.competition_id = c.id and ct.type_id = 1  where     not exists(select * from competitions c2                       join competition_type ct2                       on ct2.competition_id = c2.id and ct2.type_id = 2                       where c2.id = c.id) 	0.115661836082222
13759280	31970	join table to get the latest rows from unique row	select e.*, s1.* from table_a e inner join  (select * from (select * from table_b order by time desc) temp group by c_id) s1; 	0
13760522	40851	sql server display decimals only if they are bigger than 0?	select case when ceiling(num) = floor(num)         then      convert(varchar, cast(num as decimal))        else      convert(varchar, num)         end 	0.000370775992562353
13760541	2028	joining multiple tables containing historical data	select a.aid,a.user_id,a.amount,a.from_timestmp,a.to_timestmp,a.value   from (select a.aid,a.user_id,a.amount,a.from_timestmp,a.to_timestmp,c.value,         row_number() over (partition by a.aid,a.user_id order by b.hist_id desc, c.hist_id desc) rn   from (select aid,user_id,sum(amount) amount,from_timestmp,to_timestmp           from table_a          group by aid,user_id,from_timestmp,to_timestmp) a        inner join table_b b                on b.aid = a.aid               and b.from_timestmp <= a.from_timestmp + (1 / 2880)               and ( b.to_timestmp >= a.from_timestmp or b.to_timestmp is null)        inner join table_c c                on c.cid = b.cid               and c.from_timestmp <= a.from_timestmp + (1 / 2880)               and ( c.to_timestmp >= a.from_timestmp or c.to_timestmp is null)) a  where rn = 1   order by a.aid, a.user_id; 	0.00677888833293358
13760753	40368	sql oracle : how to find records maching a particular id in the column	select a.* from(select r.role_id, r.role_name, r.active,  decode( r.entity_type_id, 1000, m.name, 3000, cour.name, 4000, 'ensenda' ) companyname, listagg(p.permission_id, ' | ') within group (order by r.role_id) permission_id,  listagg(p.permission_name, ' | ') within group (order by r.role_id) permission_name,  row_number() over (order by r.created_ts desc) as rn, count(*) over () as total_rows, r.created_ts rolecreated  from t_role r left join t_role_permission rp on r.role_id = rp.role_id left join t_permission p on rp.permission_id = p.permission_id left join merchant m on r.entity_id = m.merchantkey  left join courier cour on r.entity_id = cour.courierkey  where 1=1 group by r.role_id, r.role_name, r.active, r.created_ts, decode( r.entity_type_id, 1000, m.name, 3000, cour.name, 4000, 'ensenda' )  )a where rn between 1 and 100  and regexp_like(a.permission_id,'(^|\s)301446(\s|$)') order by rolecreated desc; 	0
13761267	36124	how to select count of children in a hierarchical table based on a filter in sql server	select  isnull(parent_id,this_id) id,          count(*) numparts,          max(this_date),          sum(case when filter = 1 then 1 else 0 end) numoffilter1 from    tablea group by          isnull(parent_id,this_id) 	0
13761338	21893	mysql query, select, group & sum by minutes	select    sum(donation_amount) as total_donation_amount,   extract(year from time_inserted) as year,   extract(month from time_inserted) as month,   extract(day from time_inserted) as day,   extract(hour from time_inserted) as hour,   extract(minute from time_inserted) as minute from `donation` where `time_inserted` > '2012-12-07 10:00:00'  and `donation_type` = 'em1' group by year, month, day, hour, minute; 	0.0357025829299046
13762525	30266	using joins and group by together in single sql query	select * from main_table as mt  left join (select * from (select * from followups order by next_date desc) as a group by eid) as mf on mt.eid=mf.eid  where mt.status='open'  and mf.ndate<='2012-12-07'; 	0.679110153129021
13762696	2218	get all the days of sundays in a month using mysql query?	select date_add('2012-12-01', interval row day) as date, row+1  as dayofmonth from ( select @row := @row + 1 as row from  (select 0 union all select 1 union all select 3          union all select 4 union all select 5 union all select 6) t1, (select 0 union all select 1 union all select 3          union all select 4 union all select 5 union all select 6) t2,  (select @row:=-1) t3 limit 31 ) b where  date_add('2012-12-01', interval row day) between '2012-12-01' and '2012-12-31' and dayofweek(date_add('2012-12-01', interval row day))=1 	0
13762922	38812	php mysql query to match dynamic field value with other fields dynamic match value condition based	select t1.post_id  from mytable t1 inner join mytable t2 on t1.post_id = t2.post_id  where t1.meta_key = "length_x_axis" and t1.meta_value="3000mm"  and t2.meta_key="machine_type" and t2.meta_value="combined pipe cutting" 	0
13765237	37143	how to join two table in mysql and display it using php?	select u.user_id, u.user_name, u.discription, w.worker_duty from users u inner join working w on w.worker_id = u.user_id where u.user_id = "293274"; 	0.00358107524827741
13765487	3806	sqlite. get value bound to different columns	select l.id1 as liker, l.id2 as liked, f1.id2 as mutualfriend from likes l, friend f1, friend f2  where f1.id2 = f2.id2 and f1.id1 = l.id1 and f2.id1 = l.id2 and not exists(     select * from friend f3     where (f3.id1 = l.id1 and f3.id2 = l.id2)     or (f3.id1 = l.id2 and f3.id2 = l.id1)); 	0.00085645789074496
13766564	18392	finding number of columns returned by a query	select top 0 into _mylocaltemptable from (your query here) t select count(*) from information_schema.columns c where table_name = '_mylocaltemptable' 	0.00011556125457484
13766611	3768	number of days in a month	select cast(to_char(last_day(date_column),'dd') as int)   from table1 	0
13766756	26522	split columns into rows, not classical pivot	select t1.id1 ... snip ... where t1.id1 != t2.id1; 	0.00193069684526829
13768046	11207	how to find cycles between db entries?	select ... from t as t0 join t as t1 on t0.column2 = t1.column1 join t as t2 on t1.column2 = t2.column1 where t2.column2 = t0.column1 	0.000343851949519051
13769245	7847	"no such column" on select from join	select spi.*  from spi left join dp  on spi.amount = dp.amount and lower(spi.firstname) = lower(dp.firstname) and lower(spi.lastname) = lower(dp.lastname)  where dp.amount is null ; 	0.0201032618766577
13770016	4542	postgresql send variables to a function, casting?	select updategeo2('area', (40.88)::float4, (-90.56)::float4); 	0.710828140616014
13770524	37020	sql: get all posts with any comments (include 0)	select     p.idpost,     count(c.idpost) from posts p left join comments c on p.idpost = c.idpost group by p.idpost 	0.000168282480939192
13771590	34834	convert datetime to string and display like 'yyyy_mm' in sql server	select replace(convert(varchar(7), getdate(), 120), '-', '_') 	0.0265867396815982
13772309	15694	find most recent date, firebird dbase	select a.pn,b.entry_date,c.pn from (select  pnm.pn as pn,max(cqd.entry_date) as max_entry_date   from cq_detail as cqd, parts_master pnm  where cqd.pnm_auto_key = pnm.pnm_auto_key group by pnm.pn) a inner join  (select cqd.customer_price as customer_price, cqd.entry_date as entry_date, pnm.pn as pn   from cq_detail cqd, parts_master pnm  where cqd.pnm_auto_key = pnm.pnm_auto_key) as b  on a.pn=b.pn and a.max_entry_date=b.entry_date order by b.entry_date 	0.000129495147613638
13773573	41267	sqlite possibility to join matching rows into one?	select g_name,        group_concat(p_name) from game join gameplayer on g_id = gp_g_id join player on gp_p_id = p_id group by g_name 	0.00056319792634737
13775487	2980	mysql in values from subquery	select prod_name  from ct_products  where find_in_set(id,(select prod_id from ct_recommend where cat_id=12)) <> 0        and status > 0 	0.0429488411243647
13775920	40040	sql: combine records with same referenceid	select  studentid,         max(case when semester = 'first' then grade else null end) as first,         max(case when semester = 'second' then grade else null end) as second,         max(case when semester = 'third' then grade else null end) as third from    tablename group by studentid 	0.00306525867499599
13776358	27133	search and return distinct rows with the count of their repitition	select min(username) as username,         eventid,         count(eventid) as event_count from table1 where username = 'jhon' group by eventid order by event_count desc 	7.55220160888317e-05
13776420	36575	how to split datetime into parts for use in repeating rows	select ... day(start) as day, month(start) as month, year(start) as year ... 	0.000166212219893164
13777940	25906	in 1 query: 2 results, using 2 conditions	select sum(case when type = 0             then amount            else 0             end) as income,        sum(case when type = 1             then amount            else 0            end) as expense from table 	0.0274672522011082
13778903	10737	creating an sql average for multiple tables	select cat.caravan_type,  avg(rental_amount)  from caravan c inner join category cat on c.caravan_type_id = cat.caravan_type_id group by cat.caravan_type 	0.0252793858480699
13779473	27765	dividing datetimes by date	select * from tablename where date( datetime_field ) = date( now( ) ) 	0.0111390819838302
13780222	20705	mysql select syntax gives me two rows per id output what's is wrong?	select p.id id, p.type type , v.provider provider, v.video_id video_id, null content, null url, u.name posted_by from post p left join user u on p.user_id = u.id inner join p_video v on p.id = v.id and p.type =  'video' union  select p.id, p.type, null , null , t.content, null , u.name from post p left join user u on p.user_id = u.id inner join p_text t on p.id = t.id and p.type =  'text' union  select p.id, p.type, null , null , null , i.url, u.name from post p left join user u on p.user_id = u.id inner join p_image i on p.id = i.id and p.type =  'image' union  select p.id, p.type, null , null , null , l.url, u.name from post p left join user u on p.user_id = u.id inner join p_link l on p.id = l.id and p.type =  'link' order by id desc  limit 0 , 30 	0.77204977517954
13781183	2538	multi-table selecting with count of foreign key referred rows	select table1id as id, count(*) as foocount from table2 group by table1id 	6.46900357500418e-05
13782675	41102	mysql query with grouping, a procedure and "having"	select t.*, min(t.distance) as distance from (select *, geodist(41.3919671, 2.1757278, latitude, longitude) as distance     from offers_all     where id_family=1761) as t where t.distance <= 40 group by t.id_prod order by t.pricepromo asc 	0.742225449216683
13786253	22515	sql statement to select from two tables with where	select [course id], [course name]  from courses where [course id] not in   (select course id from student_courses where [student id]=1) 	0.0231248162987229
13788600	14448	random draw without replacement	select * from box where id not in (a[0],a[1]...) 	0.634037898284891
13789422	29623	inner join multiple rows into one	select group_concat(user_services.service_id)  from users inner join user_services on users.u_id=user_services.user_id  where u_id = '76' group by users.u_id; 	0.0080922629864375
13789664	2292	getting id of the row as its being written - mysqli	select max(id) + 1 from yourtable 	0.000470756390973669
13791226	38269	join using combined conditions on one join table	select id from (     select distinct     id,     (         select         count(*) from         song_genre b         where a.id = b.song_id         and b.source = 'artist'     ) as artist,     (         select         count(*) from         song_genre b         where a.id = b.song_id         and b.source = 'blog'     ) as blog,     (         select         count(*) from         song_genre b         where a.id = b.song_id         and b.source = 'post'     ) as post,     (         select         count(*) from         song_genre b         where a.id = b.song_id         and b.source = 'tag'     ) as tag     from songs a ) aa where (aa.artist > 0 and aa.blog > 0) or (aa.artist > 0 and aa.post > 0) or (aa.tag > 0) 	0.056303243190678
13792799	27144	mysql select where if stores have x, show me everything that they have	select * from stores where storeid in (select storeid from stores where productid='p2') 	0.000227150434362914
13793063	2861	sum values from duplicated rows	select code, name, sum(total) as total from table group by code, name 	0.000139883291270244
13793399	13195	passing table name as a parameter in psycopg2	select 1 from information_schema.tables where table_schema = 'public' and table_name=%s limit 1 	0.13256252568971
13793969	9639	distinctrow by id	select productsid as pid, sum(quantitybyid)  from products group by productsid 	0.0980723475128639
13794502	40162	how do i join using a string with a comma separated value?	select  . . . from team t inner join persons p    on find_in_set(p.email, t.email_list); 	0.000810313167042698
13794782	33885	how to return null values using sql left join	select a.subject_id, b.grade, b.status, b.student_id_no from tbl_curriculum a left join tbl_enrolled_subjects b on a.course_id = b.course_id  and a.subject_id = b.subject_id where student_id_no is null or student_id_no = '05-0531' order by subject_id 	0.303965988250488
13795246	8991	mysql query to return number of photos in each album	select galleryid, count(photoid) from photos group by galleryid; 	0
13795672	11848	how to fix indeterminate top 1 result from sql select union	select top 1 c1 from  (select col1 as c1, 1 as c2 from tablea       union   select col1 as c1, 2 as c2 from tableb) as a  order by c2 	0.048306973115688
13796190	39514	remove older records from table	select distinct t1.*  from import t1 inner join import t2  on t1.sellerid = t2.sellerid and t1.sellerproductid = t2.sellerproductid  where t1.lastupdate < t2.lastupdate; 	6.12359633893087e-05
13798155	14847	php mysql how to check if record already exists when updating?	select 1 from employee where empemail = '$empemail' and id != '$myid'; 	0.00708134835314769
13798310	28886	how to find difference of two datetime fields in mysql in a specific format	select     floor(hour(t) / 24) as days,     hour(t) % 24 hours from (     select timediff('2012-12-07 12:00:00', '2012-12-14 18:00:00') t ) as t1 	0
13798677	38705	querying two tables with an union	select * from table1  where id = :id  union all  select * from table2  where id = :id 	0.065554443190797
13798750	40405	find mode in postgres sql	select      src as text,     count(*) as total from t group by 1 order by total desc limit 10 	0.152158122524463
13799951	27632	select most occurring attribute in a subquery	select top 1 politicianid, count(politicianid) as cnt from      (select distinct newsid, userid, politicianid      from votes      where userid = 1010) as tempt group by politicianid order by cnt desc 	0.00468427514625853
13800286	30663	count and sum for various ranges	select case     when t.ttt between 10 and 20 then '10-20'    when t.ttt between 21 and 30 then '21-30'    else '31-40' end trange    , count(t.aaa), sum(t.bbb) from xxx t where t.qqq in  ('3') and t.www in ('a','b','c','d') and t.eee >= to_date('2008/03/20','yyyy/mm/dd') and t.eee <= to_date('2009/03/21','yyyy/mm/dd') and t.ttt between 10 and 40 group by case     when t.ttt between 10 and 20 then '10-20'    when t.ttt between 21 and 30 then '21-30'    else '31-40' end; 	0.00234739563552136
13801450	6810	union columns vertically in sql	select      [pr].[id],     [pr].[name],     [pr].[groupid],     [gr].[title] as [group],     [pr].[categoryid],     [ca].[title] as [category],     isnull([pd].[id],     cast(-1 as bigint)) as [productdealerid],     isnull([d].id,     cast(-1 as bigint)) as dealerid,     isnull([d].name,     cast('havenotdealer' as nvarchar)) as dealername,     isnull(pd.lastsale,     cast('0001-01-01 00:00:01' as datetime2)) as lastsale,     isnull([pd].number,     cast(0 as bigint)) as salenumber from [dbo].[product] as [pr] inner join [dbo].[group] as [gr] on [pr].[groupid] = [gr].[id] inner join [dbo].[category] as [ca] on [pr].[categoryid] = [ca].[id] left outer join [dbo].[productdealer] as [pd] on [pr].[id] = [pd].[productid] left outer join [dbo].[dealer] as [d] on [pd].dealerid = [d].id 	0.197749528471158
13801817	11637	sql recursion query	select t.* from  testtable t  inner join testtable t2 on t2.id = t.id_successor where t.dt_date > t2.dt_date 	0.789276455160593
13803875	5122	multiple counts and group by	select       productname,       productcode,       count(*) as total  from table1  where productname in (select productname from table1 group by productname having count(*) > 1)  group by productname, productcode 	0.0883829349019092
13803969	27418	sql how to? select all items from one table, and fill in the gaps based on another table?	select distinct su.name, su.id, isnull(pp.canprint, cast 0 as bit) as canprint from systemuser su  left join printing permissions pp on su.id = pp.systemuserid and pp.printgrouptypeid = @targetprintgrouptypeid 	0
13803978	7051	accessing tables in different database	select b.comment from news.rss_atom a, news-backup.data b where b.source = a.id and b.feed="rss-atom" 	0.00425517295407916
13805580	4215	select where and where not	select     s.name,     l.name,     case when sl.studentid is null          then 'not follows'          else 'follows'      end as status from     student s     cross join lessons l     left join student_lessons sl         on s.id = sl.studentid         and l.id = sl.lessonid 	0.693463781357018
13806427	23493	display driver who's salary is greater than the average salary of drivers according to their driver status	select dr_drvname,dr_drvstatus,dr_salary from driver d1 where dr_salary > (     select avg(dr_salary) from driver d2     where d2.dr_drvstatus = d1.dr_drvstatus ) group by dr_drvstatus; 	0
13806791	14909	arrange fields of table in database in alplabetical order	select column_name from information_schema.columns where  table_schema = 'portal'    and table_name = 'employee' order by column_name 	0.00395163428975645
13807132	36309	how to select data that is older than 12 months?	select * from table_name where `health&safety_check` < adddate(now(), interval -12 month) 	0.000111393217800866
13807257	18217	mysql insert with autogenerated column in subquery	select count(pid) into @auto from prospect; insert into prospect(pid,pfirst,plast,paddress,pcity,pstate,pzip,eid,pdate,pnum,pprim)  select custid,cfirst,clast,street,city,state,zip,csrid,lastvisit,      @auto:=@auto+1,celphone from customer limit 140000,1000; 	0.707978141568555
13808412	24230	how to select two airport names based on two airport codes in one table?	select   flightnumber,    timeofdeparture,    da.name as 'departure airport',   aa.name as 'arrival airport' from   flight as f   inner join airport as da   on f.departureairport_iata = da.airportiata   inner join airport as aa   on f.arrivalairport_iata = aa.airportiata where    f.stopoverairport_iata is null ; 	0
13814141	7236	how to get unique values for several different time ranges where exec_datetime >= now() - interval n day?	select   count(distinct requests.ip_address) ip_addr,   days.day from   (select now()-interval 1 day as day union    select now()-interval 2 day union    ...    select now()-interval 14 day) days   inner join requests   on requests.exec_datetime >= days.day group by   days.day 	0
13814236	14486	mysql timestamp difference 48 hours	select (48 - timestampdiff(hour, timestam, now())) as hoursdifference 	0.000358502670064662
13815781	17755	how to implement a query so that i get the result as required	select `id`, `value` from `table` limit 5 union select 'total', sum(`value`) as `value` from `table` 	0.102559651479412
13816076	1577	how to get today record with unix time in php mysql	select * from <table> where date(from_unixtime(<unix_time_column>)) = curdate() 	0
13816216	16724	adding up alias with other mysql column value	select    host_name,    cnt1,    cnt2,   cnt3,   cnt4,   cnt5,   cnt6,   rh1,   rh2,   total,   ((total + rec_host) / 2) as total2 from (    select host_name,         rec_host,        sum(rank_ur) as cnt1,         sum(rank_scs) as cnt2,        sum(rank_tsk) as cnt3,        sum(rank_csb) as cnt4,        sum(rank_vfm) as cnt5,        sum(rank_orr) as cnt6,        sum(if(rec_host = 1,1,0)) as rh1,        sum(if(rec_host = 0,1,0)) as rh2,        ((rank_ur + rank_scs + rank_tsk +           rank_csb + rank_vfm + rank_orr          ) / 6) as total    from lhr_reviews     group by host_name, rec_host ) t  order by total  desc limit 0,10; 	0.0191176754527851
13816901	26622	need help on .... select where date not between	select * from a where id not in (   select a.id   from a   inner join e on a.date between e.start_date and e.end_date ) 	0.722566531879764
13817797	23646	sum data select - 2 person with this same id	select hrsystemid, firstname, surname,        sum(miesiace_przepracowane) miesiace_przepracowane,        max(aneks) aneks from (     select sba.hrsystemid as id, sba.firstname,  sba.surname,          case when sba.enddate < getdate()          then datediff(month,sba.startdate,sba.enddate)         else datediff(month,sba.startdate, getdate())          end as miesiace_przepracowane,         max(sbc.contractnumber) as aneks         from sb_applications sba join sb_contracts sbc on sba.applicationid = sbc.applicationid          where sba.isactiveyn = 1 and sba.hrsystemid != 0 and sbc.applicationstatusid = 4         group by sba.firstname, sba.surname,sba.startdate,sba.enddate,sba.startdate,sba.hrsystemid,sbc.contractnumber ) x group by hrsystemid, firstname, surname; 	0.00044455642252524
13818358	32200	can we run a loop in a column of mysql table?	select employeeid from table where username = 'user' and password = 'password' 	0.062452606449859
13818524	16700	moving average based on timestamps in postgresql	select id,         temp,        avg(temp) over (partition by group_nr order by time_read) as rolling_avg from (          select id,           temp,          time_read,           interval_group,          id - row_number() over (partition by interval_group order by time_read) as group_nr   from (     select id,             time_read,             'epoch'::timestamp + '900 seconds'::interval * (extract(epoch from time_read)::int4 / 900) as interval_group,            temp     from readings   ) t1 ) t2 order by time_read; 	0
13818785	35705	sql to query rows from parent tables with two child tables, with blank values if no child row exists	select     a.id,     a.dataa1,     a.dataa2,     b.a_id,     b.datab1,     b.datab2,     c.a_id,     c.datac1,     c.datac2 from a  left join b on a.id = b.a_id left join c on a.id = c.a_id 	0
13819251	20009	mysql select multiple rows based on specific field value and number of rows	select a.book_id from authorbook a inner join book b on a.book_id = b.book_id where b.book_title='atitle'   and find_in_set (a.aut_id,'1,2') group by a.book_id having count(distinct a.aut_id) = 2    and count(distinct a.aut_id) = (select count(distinct a2.aut_id)                                    from authorbook a2                                     where a2.book_id = a.book_id); 	0
13819289	30503	storing dropdown menu options as number in mysql	select * from select_options where select_id = 4 	0.0674752424660171
13820655	17366	how to select/count all records which happened in the last 2 hours? - mysql	select count(`ip`) from `failed_logins` where `time` > date_sub(now(), interval 2 hour); 	0
13821308	30556	how to multiple inner join same table but which different foreign keys, if its even possible?	select f.*, employee.field1 as e_field1, uploader.field1 as u_field1 ... from   file f        inner join gebruikers as employee        on f.empid = employee.gebruikersid        inner join gebruikers as uploader        on f.gebruikersid = uploader.gebruikersid where gebruikers.employee= ".$get['employeeid']." 	0
13821775	18942	mysql - count unique views per ip max 1 time per day	select product_id, sum(unique_view) unique_views from (   select product_id, count(distinct ip)  unique_view   from   tablename   group by product_id, date(time) ) x group by product_id 	0
13823122	7973	check if multipolygon contains point in postgis	select name, st_contains(latlon, st_geomfromtext('point(16.391944 48.218056)', 4326))  from bezirks 	0.241718516553289
13823820	4778	mysql: how to get a cell's value from a different row of the same table	select t1.id, t2.name, t1.name from table t1 left join table t2 on t2.id = t1.pid 	0
13824377	26114	sum and distinct dont alter results?	select (ab.agency_no || '-' || ab.branch_no) as "agency-branch",     count(ab.agency_no || '-' || ab.branch_no) as occurences,     a.agy_name as agency,     sum(ab.annual_premium) as premium from agency_book_view ab, agency a, branch b where ab.agency_no = a.agency_no and ab.branch_no = b.branch_no   and b.expiration_date = to_date('12-31-2078', 'mm-dd-yyyy')   and b.effective_date <= sysdate and b.effective_date >= sysdate - 364 group by ab.agency_no || '-' || ab.branch_no, a.agy_name order by ab.agency_no || '-' || ab.branch_no 	0.0148455000391532
13824800	14601	mysql query except	select carta_id from carta_alarme inner join alarme on carta_alarme.alarme_id = alarme.id group by carta_id having sum(year(alarme.dtocorrencia) = 2011) > 0     and sum(year(alarme.dtocorrencia) = 2012) = 0 	0.35820557801421
13826872	10411	sum until value ordered by column	select   qty,   weight from (   select     qty,     weight,     sum(qty) over(order by weight desc rows between unbounded preceding and current row) as runningqty   from     test   where     product = 'pen'   ) a where    runningqty <= 200 	0.00021714349398278
13827313	15241	mysql select distinct from tables?	select province, count(distinct email) from table group by province; 	0.00671078043471988
13827725	29286	little bit of a mysql mystery	select province, count(email_address) from (   select email_address, max(province) as province   from entries   group by email_address ) group by province 	0.787589028360962
13828123	31106	mysql finding time span between two dates/times	select min(b.dt) as starttime, notbookedtime as endtime from (select b.*,              (select min(b2.dt) from booking b2 where b2.dt >= b.dt and b2.isbooked = 1              ) as notbookedtime       from booking b      ) b where b.isbooked = 0 group by notbookedtime having date_add(min(b.dt), interval 45 minute) <=  notbookedtime 	0.000635119628196247
13828514	11735	mysql- truncating date-time in a query	select *  from player_source  where source is not null and create_dtime >= '2012-10-03' and create_dtime <= '2012-10-09' 	0.301862986707811
13829046	14821	extract last 5 products mysql	select    id, name, date from      tablename order by  date desc limit     0, 3 	5.71451880480542e-05
13829585	21072	how can i make oracle separate results with commas, not tabs?	select name || ',' || age from (     select 'bob' name, 4 age from dual     union all     select 'sam' name, 5 age from dual     union all     select 'joe' name, 7 age from dual ) 	0.498908628819373
13829896	30704	how to left join count?	select cctv_id, cctv.[name], count(cctv_id) from points_cctv left join cctv on points_cctv.[cctv_id] = cctv.[id] group by cctv_id, cctv.name 	0.60908164839908
13829905	29640	selecting count(*) while checking for a value in the results	select      count(*) as count,      sum(sch.hometeamid = 34) as hawaii_home_count ... 	0.000903756656012356
13830605	7457	sql to compare two columns where a third column is constant and return differences	select c1.*, c2.* from   chart c1        inner join        chart c2 on c1.group=c2.group where  c1.desc1<>c2.desc1         or        c1.desc2<>c2.desc2 	0
13831345	18485	mysql date appear as words in php	select date_format(date_hired, '%m %d %y') from registration 	0.0408000095497684
13831514	33568	apply distinct before where	select object_id from table group by object_id having max(date_modified) is null 	0.281092511259414
13831928	4029	how to use join with two table and a parameter	select firstname, lastname from table1 inner join table2 on table1.id = table2.id and firstname = @firstname 	0.183182356073117
13832150	32204	get the column names of a stored procedure when using bcp queryout	select 'col1', 'col2' union all select name1, max(name) over (partition by name) from table 	0.00238148296208535
13832333	18967	create a listbox that combines data from two tables for a report	select  * from    tbl_studentorderline sol inner join         tbl_books b on  sol.isbn = b.isbn where   so.studentpurchaseid = 12 	0.00129188973400157
13834147	10203	sum the timegap if consecutive timestamps are same for 10 min	select     yt1.[timestamp] as starttime,     min(yt2.[timestamp]) as endtime,     datediff(minute, yt1.[timestamp], min(yt2.[timestamp])) as differenceinminutes     into #tmp1     from     sheet1$ yt1     left join sheet1$ yt2 on yt1.[timestamp] < yt2.[timestamp]     where     yt1.twspd is null     group by yt1.[timestamp] select t1.*  into #tmp2 from #tmp1 t1 left join #tmp1 t2 on t1.starttime=t2.endtime where t2.endtime is null declare @rcn int select @rcn=1 while @rcn>0     begin        update #tmp2 set #tmp2.endtime=t.endtime,#tmp2.differenceinminutes=#tmp2.differenceinminutes+t.differenceinminutes        from #tmp1 t        where t.starttime=#tmp2.endtime        select @rcn=@@rowcount     end select * from #tmp2 drop table #tmp1 drop table #tmp2 	0
13834294	34902	how to select latest row in a table based on id from another table	select  r1.report_id, r1.report_name, r1.creation_date, r2.report_type_desc from reports r1 join report_type r2 on r1.report_id = r2.report_id  where r1.creation_date in                          (                          select max(creation_date)                           from reports                           where report_id = r1.report_id                         ) 	0
13834825	40443	mysql complex query from two tables	select u.first_name,   (   select date( c.date ) from calendar as c   where c.uid = u.id   and date( c.date ) >= curdate( )   order by date( c.date ) asc   limit 1 ) as availability from users as u group by u.id order by if( availability is null , 1, 0 ) , availability 	0.0861068195644944
13835015	14389	how to select sum, and count from diffrent tables using multiple joins	select   p.name,  sum(p.deleted) as del,  count(id)  as numbers from products as p join other as b on p.id=b.id  group by p.name 	0.00481015250628176
13835797	1565	how to fetch name in one table according to the max tax payed in other table?	select salary.employeeid,firstname,lastname, sum(tax)   from salary left join employee     on salary.employeeid=employee.employeeid group by salary.employeeid,firstname,lastname order by sum(tax) desc limit 1 	0
13837127	13189	how to add up the data with variable numbers in mysql with python?	select id, name, users_count+1 as users_count from data; 	0.021227333638784
13837691	11385	how to calculate top customer in each city with maximum order	select x.customername, max( p.totalorder ) , x.city from ( select o.customernumber, round( sum( od.priceeach * od.quantityordered ) , 2 ) as totalorder from orders as o inner join orderdetails as od on o.ordernumber = od.ordernumber group by o.customernumber order by totalorder desc )p inner join customers x on p.customernumber = x.customernumber group by city 	0
13839405	17424	skip date in mysql query if it is empty when using < and >	select sql_calc_found_rows id, datetime from message where datetime is null or datetime <> ''; 	0.742606041989429
13839771	14137	union of two select queries with different fields	select distinct em.emp_fname, 0 alloc  from tbl_empmaster em where em.emp_id not in(select emp_id from tbl_allocation) union select distinct em.emp_fname, sum(a.per_alloc) alloc from tbl_empmaster em  inner join tbl_allocation a on em.emp_id = a.emp_id  group by a.emp_id  having sum(a.per_alloc)<100 	0.00188946620025175
13839837	23481	categorize select with multiple date between	select     col1, col2, ..., coln,     date between "date[0][start]" and "date[0][end]" as first,     date between "date[1][start]" and "date[1][end]" as second from tbl where date between "date[0][start]" and "date[0][end]" or date between "date[1][start]" and "date[1][end]" order by first 	0.00895124400345822
13840521	19132	sql query to count a grouped joined table by null in a column	select products.productid , sum(  case     when  (stock.orderid is null and stock.framenumber is not null)        then 1        else 0  end case ) as count from products left join stock on products.productid = stock.productid group by products.productid 	0.000842420262107549
13842029	18929	select date range which overlap a certain date	select d1.* from   dates d1 inner join dates d2   on d2.id=1 and d1.startdate<d2.enddate and d1.enddate>d2.startdate where d1.id<>1 	0
13842529	37686	sql conditional relationship between 1 parent 3 child tables	select capacity from dumptruck c join machine p on c.dumptruckid_pk=p.machineid_pk join resource gp on gp.resourceid_pk=p.resourceid_pk where gp.model='x' 	0.00129801255100133
13843372	2804	sql.limit on the number of related tables	select  a.id     from    role a         inner join accountrole b             on a.roleid = b.roleid          inner join account c             on b.accountid = c.accountid  group by a.id having count(*) = 1 	0.000194819773671773
13846941	34733	how can i retrieve the average value for distinct combinations of elements with a mysql query?	select fruit, color,brand, avg(rating) from fruit_ratings group by fruit, color, brand; 	0
13847268	4104	sql server - create multiple rows from a single record based on time	select      bb.integer as monthdesc, cc.monthdescription, aa.mycost / datediff(mm,mydatefield, mydatefield2)     datepart(yy, mydatefield)     from dbo.tblmytableoffacts aa     inner join dbo.tblmytableofinters bb     on bb.integer between datepart(mm,mydatefield) and datepart(mm,mydatefield2) inner join dbo.tblmytableofmonths cc on bb.integer = cc.monthnumber 	0
13847666	27352	how to use multiple rank() in single query?	select code,numb,taxi_name, dstart, ranking from (select code, numb, taxi_name,dstart,              rank() over (partition by code, numb order by dstart desc) as ranking       from detail      ) d join      (select r.*,              rank() over (partition by code, numb order by rstart desc) as ranking       from requirement      ) r      on d.code = r.code and         d.ranking = 1 and         r.ranking = 1 	0.137152793116099
13847820	30242	join behavior when a table is not joined using its own key	select * from table1 a   inner join table2 b on a.key=b.key  inner join table3 c on 1=1    ; 	0.221466820705659
13848200	28186	how to select distinct value from one column only	select `key`, max(`name`) as name from `table` group by `key` 	0
13848437	39010	should a users table be in a different database than website content?	select onedatabase.table.field, someotherdatabase.table.field ... 	0.00498675936613407
13849393	40903	selecting 4 groups and sorting by a time field	select gameid, qtr, max(hscore), max(ascore) from final_score group by gameid 	0.000392157362318025
13849550	15194	query to get posts and if the user has voted for the post	select pins.id as pin_id, title, user_upvotes.id as upvote, user_downvotes.id as downvote from pins left join user_upvotes on user_upvotes.pin_id = pins.id and user_upvotes.user_id = 2 left join user_downvotes on user_downvotes.pin_id = pins.id and user_downvotes.user_id = 2 group by pin_id 	0
13850268	1003	add a row with totals for each column	select   t.id,   count(case when a between 2 and 4 then id end),   avg(case when b between 19 and 40 then b end),   count(case when c between 12 and 14 then id end) from t group by id union select   'overall',   count(case when a between 2 and 4 then id end),   avg(case when b between 19 and 40 then b end),   count(case when c between 12 and 14 then id end) from t 	0
13850605	26171	t-sql to convert excel date serial number to regular date	select dateadd(d,36464,'1899-12-31') 	0.00188857828135809
13850872	40183	mysql select max on mutiple values?	select   file, majorversion, max(minorversion) minorversion from     my_table natural join (   select   file, max(majorversion) majorversion   from     my_table   group by file ) t group by file 	0.00841534645329397
13852319	23713	fetch those mysql rows which dont have entry in another table	select roomname from room where roomid not in (     select roomid     from ttresponsibility     where period = *insert_timeperiod_to_search_for_empty_rooms_here*         and day = *insert_day_to_search_for_empty_rooms_here* ) 	0
13853972	12859	extract value from xml	select extractvalue(t.column_value, '/transactionlimitdto/idtxn') "txnid"      from mstgloballimitspackage mg,           table(xmlsequence(xmltype(mg.limits,'')                             .extract('/modifytransactionlimitrequestdto/transactionlimit/transactionlimitdto'))) t 	0.00137867272989435
13854556	27942	displaying unique attributes of table and the total value in postgresql	select stamp_type, sum(amount) amount     from tbl     group by stamp_type  union  select 'total:' stamp_type,sum(amount) amount  from tbl; 	0
13854783	35568	time out while i fetch data from sql in asp.net mvc	select * from object where text1='good' 	0.00548026014498866
13859587	40894	mysql query select row group by	select *  from (select * from statustable      group by statuscode having statuscode not in (select statuscode from statustable where brandid = 2000)     union      select * from statustable where brandid = 2000 ) as a  order by statuscode 	0.0663121908406681
13860054	11492	optimize query to find max timespan between orders	select created,previous_created,        if(tsd<>0,sec_to_time(tsd),0) as diff  from (  select created,        if(@prev<>0,timestampdiff(second, @prev,created),0) tsd,        @prev previous_created,        @prev:=created f2      from orders,(select @prev:=0) t1  where created >= '2012-06-01' order by created  ) t2  order by tsd desc limit 100 	0.00790175432233615
13861589	34192	left join to two inner joined tables	select calendar.iso_date as iso_date,        venues.venue as venue,        coalesce(events.status, 0) as booked   from calendar  cross   join venues   left  outer   join (      bookings          join events            on events.event = bookings.event           and events.status = 1        )     on bookings.iso_date = calendar.iso_date    and bookings.venue = venues.venue ; 	0.263524708835915
13861825	34559	how to address a computed column value in an sqlite query?	select f.*, strftime('%w', `date`) as `weekday` from (select `year`, `month`, `day`, `hour`, `minute`, `value`,              substr('000' || year, -4) || '-' || substr('0' || month, -2) || '-' || substr('0' || day, -2) as `date`       from foo      ) t 	0.0023818104348412
13862186	16619	sql distinct plus count	select `album`, count(*) from `mp3` group by `album` 	0.11450255069727
13862312	578	sql count on multiple columns?	select firstname, lastname, count(*) as `name count` from table group by firstname, lastname 	0.0116458680867177
13863734	37693	sql how group by fiscal quarter and year with a date field	select      year([expected arrival date]) + case         when month([expected arrival date]) in (11, 12) then 1         else 0     end as fiscalyear,     case         when month([expected arrival date]) in (11, 12, 1) then 1         when month([expected arrival date]) in (2, 3, 4) then 2         when month([expected arrival date]) in (5, 6, 7) then 3         else 4     end as fiscalquarter,     ... group by     year([expected arrival date]) + case         when month([expected arrival date]) in (11, 12) then 1         else 0     end,     case         when month([expected arrival date]) in (11, 12, 1) then 1         when month([expected arrival date]) in (2, 3, 4) then 2         when month([expected arrival date]) in (5, 6, 7) then 3         else 4     end,     [vendor name] order by     fiscalyear,     fiscalquarter ; 	0.000226944177244688
13866466	11080	filter matrix by current week	select personid, somedate from mytable where somedate >= dateadd('d', 0 - (weekday(today())-2), today()) and somedate <=  dateadd('d', 0 - (weekday(today())-6), today()) 	0.000386789901907049
13866773	33148	get data sorted by descending size according units of measurement in sqlite	select *, (cast(mytable.quantity as float) * unit_map.multiplier) as sort_field from mytable inner join unit_map on mytable.unit = unit_map.unit order by sort_field 	0
13868676	11989	php/mysql: how can i calculate value of field + other field + other field	select sum(number) as total from table; 	0
13870329	32055	sql query -- if x is shared between two strings in a primary composite key?	select itemcode, count(*) from table group by itemcode having count(*) > 1 	0.000826797106095475
13872511	25233	mysql query to return non-emty meta values from a wordpress meta table	select distinct meta_value   from wp_postmeta  where meta_key like '%genre%'        and meta_value is not null       and meta_value <> '' 	0.000680561350474966
13873701	24505	convert comma separated column value to rows	select a.[id],        split.a.value('.', 'varchar(100)') as string    from  (select [id],            cast ('<m>' + replace([string], ',', '</m><m>') + '</m>' as xml) as string        from  tablea) as a cross apply string.nodes ('/m') as split(a); 	0
13874060	12336	database connection in android	select * from quiz where flag = 0 	0.530888212776902
13877080	25185	use like for 2 columns	select * from hostel where hostel like '%$word%' or address like '%$word%' 	0.140603183019643
13879917	2617	sum of part of a column in a join statement	select ordernumber, sum(panelbuildtime) from steelorders  inner join finalizedprintedstickers  on  steelorders.ordernumber = left(finalizedprintedstickers.sn,10) group by steelorders.ordernumber 	0.00958645756194934
13882672	26137	how to count left joined rows?	select     a.id     , a.title     , count(v.id) from     articles a left join     article_views v on a.id = v.article_id group by     a.id, a.title order by     count(v.id) desc 	0.0158283354938498
13882722	15920	not getting value in mysql parameter	select substring_index('359616044513513-2574', '-', 1),         substring_index('359616044513513-2574', '-', -1) into @dev, @id; 	0.198431889699344
13883474	20204	sql get average of people's jobs' salaries for each country	select salary / count(c.name) avgsalary, c.name from people p inner join  (   select sum(salary) salary, p.country_id   from jobs j   left join people p     on j.ssn = p.ssn   group by p.country_id ) sal   on p.country_id = sal.country_id left join countries c   on p.country_id = c.country_id group by salary, c.name; 	0
13883900	31408	select intersection of two query ordered by sum of a column	select wd.document_id, (wd.count + d.count) as tcount from word_document as wd join words as w on w.id = wd.word_id join (select document_id, count from word_document  join words on words.id = word_document.word_id where words.word = "apple") d on d.document_id=wd.document_id where w.word = "blue" order by tcount desc 	9.99601969076506e-05
13885867	6506	how to select a field without the first n characters and the last m characters?	select substring(data, 4, length(data)-7) 	0
13886066	25949	order by distinct number of rows for 3 tables?	select      user_id,     count(*) as all_actions  from (     select user_id from news     union all     select user_id from content     union all     select user_id from edits ) tmp_table group by user_id order by all_actions desc 	8.80848897639247e-05
13886809	27835	select record based on max(date) accross multiple tables	select personid, assessmentdate, totalscore from (      select personid, assessmentdate, totalscore, row_number() over (partition by personid order by assessmentdate desc) as rowid      from (         select personid, assessmentdate, totalscore         from  initialassessment         where personid = 1         union         select personid, assessmentdate, totalscore         from reassessments         where personid = 1       ) a ) b where rowid = 1 	7.94669499580044e-05
13889075	40922	sql - different "order by" values for the same field	select * from t order by case        when expiry = 'unknown' then 1        when expiry >= current_date then 0        else 2 end, case when expiry >= current_date then expiry end, case when expiry < current_date then expiry end desc 	0.000121964688693622
13889368	31659	getting the count of occurances from a group by	select keyword_id,count(keyword_id) as occurance from table group by keyword_id 	0.000672067316604443
13890024	3044	calculation of percentage for rows within particular range	select concat(a.minrange, ' - ', a.maxrange) markrange, count(sl.name) noofstudents,      (select count(sl.name) / count(*) * 100 from studentslist) percentage from studentslist sl  inner join (select 1 id, 0 minrange, 20 maxrange      union      select 2 id, 20 minrange, 50 maxrange      union      select 3 id, 50 minrange, 70 maxrange      union      select 4 id, 70 minrange, 90 maxrange      union      select 5 id, 90 minrange, 100 maxrange      ) as a on sl.marks >= a.minrange and sl.marks < a.maxrange  group by a.id; 	6.01447129246985e-05
13890140	457	sql join get details from two tables	select u.user_id,        u.name,        b.billing,        s.stocks from user_details u left join billing_details b on b.user_id = u.user_id left join stock_details s on s.user_id = u.user_id 	0.00106039117456496
13894825	28070	how to find what products sell well with others in an sql server query	select p1.product_code,        p2.product_code,        count(distinct s1.sale_id) from   product p1        join product p2          on p1.product_code > p2.product_code        left join sales s1                  inner join sales s2                    on s1.sale_id = s2.sale_id          on s1.product_code = p1.product_code             and s2.product_code = p2.product_code group  by p1.product_code,           p2.product_code 	0.123737892995869
13895659	27378	oracle sql generate query	select max(ch.chan_number), max(ch.chan_name), count(srv.surv_fav_chan) from survey srv   left join channel ch on ch.chan_number = srv.surv_fav_chan group by srv.surv_fav_chan having count(srv.surv_fav_chan) > 1; 	0.47155416685392
13898392	41265	query dependent on two other tables and one column	select    pout.player_id, lout.id from       levels as lout,       players_levels_done as pout where    lout.level_order in (      select        min(l1.level_order )     from        levels as l1,       players_levels_done as p1     where       l1.id not in          (             select                level_id              from                players_levels_done              where                player_id = p1.player_id          )       and       l1.series_id =         (            select              distinct l.series_id            from              levels as l,             players_levels_done as p           where             p.level_id = l.id             and               player_id = p1. player_id         )     and p1.player_id = pout.player_id     group by p1.player_id   ) ; 	0.000107943321503249
13900022	1923	how to count rows in db for each hour?	select count(*) from your_table  where `datestamp` = '2012-12-16'  group by hour(`timestamp`) 	0
13900439	21355	select rows based on non-equality, using just one condition	select * from `table` where ifnull(`num`,0) != 5; 	9.81856481517933e-05
13901871	39338	sql sum rows in a select case	select t.id, isnull(t.m1,0)+ case when t.datem2 is not null and @date1 < t.datem2 < @date2      then t.m2      else 0 end + case when t.datem3 is not null and @date1 < t.datem3 < @date2      then t.m3       else 0 end + case when t.datem4 is not null and @date1 < t.datem4 < @date2      then t.m4       else 0 end as 'm1+m2+m3+m4' from table1 t 	0.0935308782678158
13902072	37033	combine a join/subselect query with a sum mysql query	select * from table1 t inner join (select max(id) as id, sum(item_qt) as sum_item_qt  from table1  where timestamp >= date_sub(now(), interval 5 minute)  group by member_id) as t2 on t2.id = t.id order by t.id desc limit 10 	0.315288452909568
13902859	13139	how to convert timestamps' timezones in order to compare them in oracle db?	select to_char((from_tz(to_timestamp(to_char(database_date, 'yyyy-mm-dd hh:mi:ss pm'), 'yyyy-mm-dd hh:mi:ss pm') ,'america/new_york')     at time zone 'america/los_angeles'),'yyyy-mm-dd hh:mi:ss pm tzd') as localtime     from table 	0.000833533603427073
13903065	13659	check records in a column which exceeds 4000 characters	select <columns>,length(column you have to check) from <tablename> group by <columns> having length<column> > 4000; 	0.00370613324401066
13903597	39420	how to count number of columns and rows in all tables group by table?	select u.table_name,  count(*),  u.num_rows     from user_tab_columns c, user_tables u     where   u.table_name = c.table_name     group by u.table_name, u.num_rows; 	0
13904127	30254	mysql query , calculate percentage of three grades	select   grade,   100 * count(*) / (select count(*) from table1 where pid = '480') as score  from table1 where pid = '480' group by grade order by grade 	0.00409690521226581
13904329	23297	select max(id) but need more row data	select user_event_id, event_title from user_events where user_event_id = (select max(user_event_id)                        from user_events                        where user_id = 63) and user_id = 63    	0.0452080799495227
13905941	29550	counting days by non standard days end	select   date_add(date(time),     interval case when time(time)>='16:00:00' then 1 else 0 end day) as day,     count(distinct comment) from data group by day 	0
13906849	36362	how do i select rows from a table based on a rank value	select * from ztable zt where not exists (     select *     from ztable nx     where nx.zorder = zt.zorder     and nx.zsequence > zt.zsequence     ); 	0
13907005	18232	using python to use names from one sql table to find data in another and then combining the names and data to make an html table	select name, value1, value2, value3, value4 from table2 where name in (     select name     from table1     where description like ? ) 	0
13908512	21540	mysql joing tables	select a.uid,a.username,b.user_email, b.orders_is, c. product_name from users a, users_orders b, order_products c where a.uid = b.uid and b.order_id = c.order_id and product_id = 5 	0.121677776024867
13910134	10252	mysql get count() from separate tables	select   (select count(id) from table1) as c1,   (select count(id) from table2) as c2,   (select count(id) from table3) as c3 	0.000284943658622646
13910324	28396	sql generating a new column from a new column in the same sql query	select aa.*,(amount*ekprice)  as ek,         (amount*(unitprice-((unitprice/((otax/100)+1))-odiscount-oshipcost-coupondiscount)) as vk from (     select         i.catalogid,i.itemname,i.ekprice,i.unitprice,o.otax,o.odiscount,o.oshipcost,o.coupondiscount         case when o.oshippeddate is not null and  o.oshippeddate  between @date1 and @date2              then isnull(i.f2,0)              else 0 end +         case when o.oshippeddate2 is not null and o.oshippeddate2 between @date1 and @date2              then isnull(i.f3,0)               else 0 end +         case when o.oshippeddate3 is not null and  o.oshippeddate3 between @date1 and @date2              then isnull(i.f4,0)               else 0 end as amount        from          orders o          inner join oitems i on i.orderid = o.orderid  )as aa 	0.000109612409525715
13911121	12319	sql: select distinct - without highcase/lowcase duplicate	select distinct [id], [idgroup], [description] collate sql_latin1_general_cp1_ci_as from table 	0.03183831400513
13913137	19659	how to make an order by a field but with a condition inside?	select * from table 1          left join table2 on x = y          left join table3 on z=w          where w = 1          order by case when state=1 then 0 else 1 end,q 	0.297081439546607
13915298	33118	select distinct formatted dates in sql	select monthyear from ( select distinct datename(month,datecol) + ' ' +                  convert(varchar, datepart(year,datecol)) monthyear,                  convert(varchar(6),datecol, 112) ordercol from yourtable ) a order by convert(int,ordercol) desc 	0.00780960300882519
13919509	40833	compare 2 tables and find non duplicate entries	select      t1.name  from      table1 t1  where      t1.name  not in (     select          t2.name      from          table2 t2) 	0
13919940	37385	mysql query encompassing two fields	select * from posts inner join users on users.user_id = posts.user_id where users.location = 'the location 	0.0790754946567039
13920478	38384	query data in one table based on ids from another	select * from `contacts` where `user_id` in (     select `user_id` from `users` where `username` like "%mysite.com%" ) 	0
13920590	14055	mysql query involving three stages and two tables	select * from xx_questions q join      xx_users u      on q.user_id = u.user_id where q.user_id in (<implode(',', $friend_ids_arr)>) or       q.user_id = '$user' or       u.location = (select location from xx_users where user_id = $user) 	0.105539597066769
13921721	24475	inadvertent cross join occurring in sql merge	select * from xtradecapture.staging.indexdecomposition src inner join indexdecomp.constituent c with (nolock) on  (((c.identifier = src.identifier) or (c.identifier is null and src.identifier is null)) and ((c.cusip = src.cusip) or (c.cusip is null and src.cusip is null)) and ((c.isin = src.isin) or (c.isin is null and src.isin is null)) and ((c.sedol = src.sedol) or (c.sedol is null and src.sedol is null)) and (c.identifier is not null or c.cusip is not null or c.isin is not null or c.sedol is not null)) 	0.749095490530113
13922217	9192	sql query to return all column values in a single row	select concat(concat('+', listagg(employee.name, '+')), '+') from employee where salary >= 10000 	0
13922346	9407	how can i denormalize / histogram mysql output for a small finite set of possible values?	select   votee_id   sum(case when score = 1 then 1 else 0 end) as count_ones   sum(case when score = 2 then 1 else 0 end) as count_twos   sum(case when score = 3 then 1 else 0 end) as count_threes   sum(case when score = 4 then 1 else 0 end) as count_fours   sum(case when score = 5 then 1 else 0 end) as count_fives from scores group by votee_id 	0.0966755330003106
13923573	241	mysql - separate lastname,firstname and companyname entries from a single column	select id, companyname, if(companyname like '%,%', substring_index(companyname, ',', -1), '') firstname,         if(companyname like '%,%', substring_index(companyname, ',', 1), '') lastname from company; 	0
13925803	19735	mysql three table join - user and friend pictures	select p.*, if(p.user_id = friend_2id, a.username,'$username') from friends f join active_users a on (f.friend_1id='$userid' and f.friend_2id=a.id and status=1) join pictures p on (p.user_id=f.friend_2id or p.user_id = '$userid') group by p.photo_id 	0.0435596711804193
13927532	29738	sort on foreign key table	select m.*, c.mostrecent   from message m   join (select messageid, max(comment_datetime) as mostrecent           from comments          group by messageid        ) as c on m.messageid = c.messageid  order by c.mostrecent desc 	0.000493807832623932
13928847	983	limiting the count in group by	select id,         (select count(*) from t2 where t2.id = t1.id and rownum <= 3) c_star  from   t1 	0.128734901415654
13930482	23262	mysql query to add entries of multiple rows	select   case            when p in ('a','b') then 'a'            when p in ('c')     then 'c'            when p in ('d','e') then 'd'          end as product, sum(c) from     (            select   product as p, count(*) as c            from     dashboard            group by p          ) t group by product 	8.20666274558308e-05
13931494	6567	how to get the total number of tables in postgresql?	select * from  pg_stat_user_tables ; select count(*) from  pg_stat_user_tables ;  select * from  pg_stat_all_tables ; 	0
13932478	679	mysql select, need to add to my statement	select shortname from product where active = 1 or shortname like 'blueball%' 	0.70172028493293
13933295	27524	select multi-digit zeros	select * from app where value regexp '0+'; 	0.122277539005072
13934202	24861	how to select values in multiple tables?	select  a.factory_name , c.car_model_name,         count(b.car_factory_id) totalcount from    factory a         left join car b             on a.factory_id = b.car_factory_id         left join car_model c             on b.car_model_id = c.car_model_id group by a.factory_name , c.car_model_name order by factory_name asc 	0.00424952747057647
13934995	14053	oracle sql union with no duplicate on a single column	select coalesce(a.item_name, b.item_name) as item_name,        coalesce(a.price, b.price) as price,        (case when a.price is not null then 'a' else 'b' end) as source from a full outer join      b      on a.item_name = b.item_name 	0.0051345806629661
13936405	10359	querying second mysql table from the result of another query	select distinct t2.* from mtytable1 t1 inner join table2 t2 on t1.custid=t2.custid and t1.age=t2.age where t1.itemid in ( 2762 , 2763) 	0
13936713	10031	error on query by sum and fetch row - sql	select sum(billsitems_quantity) over (partition by ) as totalq ,     sum (billsitems_itemdiscount) over (partition by ) as totald ,     sum (billsitems_itemtotal) over (partition by ) as totali ,     bills.bills_id , billsitems.billsitems_billitemserial , bills.bills_cashierid ,     bills.bills_storeid , billsitems.billsitems_unit , billsitems.billsitems_price from bills ,     billsitems  where bills.bills_id = billsitems.billsitems_billitemserial   and bills.bills_cashierid = '".$id."'   and bills.bills_storeid = '$ausers_storeid' order by billsitems.billsitems_unit 	0.0671413340331708
13936723	31633	mapping values in mysql?	select  max(case when name = 'bank_name' then p.value else null end) bank_name,         max(case when name = 'bank_date' then p.value else null end) bank_date from    o         left join o_oprop p             on o.id = p.id group by p.id 	0.130461310921684
13937088	1791	sql query in order to retrieve data	select  a.employee_lastname,         a.employee_firstname,         b.employee_lastname as manager_lastname from    emptable a         left join emptable b             on a.manager_id = b.employee_id where   a.employee_salary < b.employee_salary 	0.0252356209455074
13937387	36818	get a row by particular category sqlite android	select * from itemsdatatable where category like 'eletronic' 	0.000186253640766611
13938512	29571	sql query multiple counts	select name,surname,age  from table1  where (country = 'russia' and 'streetname' in ('new york','moscow')) or (country = 'usa' and 'streetname' = 'washington') or (country = 'ukraine' and 'streetname' = 'kiev') 	0.243141901035144
13939653	35685	sql query null data was not retrieved	select department.department_id, department.department_name, count(employee.employee_id) as employees  from department  left join employee on employee.department_id = department.department_id  group by department.department_id, department.department_name 	0.460233826348695
13939937	39184	creating a date range using today's date	select * from your_table where app_receipt_date > sysdate - (6 * 7); 	0.000776200381722464
13939975	35669	query large table with large number of matches in query	select emailaddress,        (case when bg.emailaddress is null then 'missing' else 'present' end) from tempemail te left outer join      bigtable bg      on te.emailaddress = bg.emailaddress 	0.0151370027311431
13940262	15929	how to get from a range of sequence numbers and rollover after overflow	select mod(id, 99) as trans_seq 	4.69712264634319e-05
13940339	26794	display all records in mysql	select app_id, app_name from app where app_sendto like '%' 	0.000157671296319163
13940720	20599	sql server calculation	select mo.customerid, mo.dateid, mo.ordercount*max(accountrate) +         (sum(rep.hours)+sum(adm.hours)+sum(sc.hours))*max(rt.operationrates) from monthlyorder as mo   join rates as rt                on rt.customerid = mo.customerid   left join hoursspend as rep     on rep.customerid = mo.customerid and                                      rep.dateid = mo.dateid and                                      rep.function = 'reporting'   left join hoursspend as adm     on adm.customerid = mo.customerid and                                      adm.dateid = mo.dateid and                                      adm.function = 'admin'   left join hoursspend as sc      on sc.customerid = mo.customerid and                                      sc.dateid = mo.dateid and                                      sc.function = 'sales calls' group by mo.customerid, mo.dateid, mo.ordercount 	0.681756566844284
13941413	35764	mysql multiple column select from single column table with grouping	select      date,     count(case         when rating = 1 then 1         else null     end) as star1,     count(case         when rating = 2 then 1         else null     end) as star2,     count(case         when rating = 3 then 1         else null     end) as star3,     count(case         when rating = 4 then 1         else null     end) as star4,     count(case         when rating = 5 then 1         else null     end) as star5 from     table1 where     date = '2012-10-25' group by date order by date 	0.000129906206326304
13943350	22907	mysql - join same table twice	select `b`.`bookingid` as `bookingid`,    `del`.`calldate` as `delivery`,    `col`.`calldate` as `collection` from `booking` `b` left join `call` `del` on `b`.`bookingid` = `del`.`booking` and `del`.`type` = 'del' left join `call` `col` on `b`.`bookingid` = `col`.`booking` and `col`.`type` = 'col' where `b`.`status` = 'p'; 	0.0240636215688123
13943532	22717	link one table to another through two columns in sql	select   name, attribute from   users inner join attributes   on users.qualification in (attributes.qual1, attributes.qual2) group by attribute, name having count(*)=2 	0
13944099	35729	how to select results from multiple records and tables into one row	select t1.id,   max(decode (t1.code, 'color', t2.descr, null)) color,   max(decode (t1.code, 'tone', t2.descr, null)) tone,   max(decode (t1.code, 'type', t2.descr, null)) type from table1 t1, table2 t2 where t1.code = t2.code   and t1.value = t2.value   and t1.id = 1 group by t1.id 	0
13944208	3873	mysql query - inner join using only the latest version of an entry	select  a.*, c.* from    jobs a         inner join         (             select jobid, max(time) maxval             from purchaseorders             group by jobid         ) b on a.jobid = b.jobid         inner join purchaseorders c             on c.jobid = b.jobid and                 c.time = b.maxval 	0.00120828912687255
13944214	23071	multiple sums from same table	select teamname, sum(points) from users, teams  on user.team-id = team.team-id group by teamname 	0.000433345217125972
13945282	26924	how to merge two tables in sql?	select table1.serialno,table1.recordno, table2.issueid from table1 inner join table2 on table1.recordno=table2.recordno order by table1.serialno 	0.00356428627571311
13945393	20062	how to find the missing records in track table in sql server?	select * from workitem  where workid not in  (   select distinct wit.workid    from workitemtrack wit        join workitemtrack wit1 on (wit.workid = wit1.workid) and (wit1.status=5)        join workitemtrack wit2 on (wit.workid = wit2.workid) and (wit1.status=9)   where wit.status=3 ) 	0.000894239941471237
13946223	31952	fadein only new data from mysql table not all data	select * from notes order by id desc limit 1 	4.57066054661901e-05
13948339	17071	tsql getdate() format	select convert(varchar(11),getdate(),106) 	0.349962701083111
13948407	12761	mysql replace foreign key in result table with data from fk table	select t.name, p1.name teacher_name, p2.name student_name         from t left join people p1 on (t.teacher=p1.id) left join people p2 on (t.student=p2.id) 	7.42289923345935e-05
13948499	41300	creating an alias in sql server before the from?	select emp.columnone, emp.columntwo     from employee as emp     where emp.id = 10 	0.382371155571421
13949964	3799	how find collective range in two period in database	select * from (     select max(startdate) d1, min(enddate) d2 from user ) where d1<=d2 	8.62073476688206e-05
13950308	16181	retrieve info sql query	select  * from    employee  where (department_id<>'30') and   (  employee_salary >    (select max(employee_salary) from employee  where  department_id='30')  ) 	0.0107421982309223
13950756	31926	postgis st_contains polygon one table	select st_contains(a.way, b.way) from yourtable as a, yourtable as b where      a.gid = yourfirstid     and b.gid = yoursecondid 	0.135650534672957
13951056	13781	getting similar longitude and latitude from database	select id, (3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) as distance  from markers  having distance < 25  order by distance; 	0.0224588885674985
13951183	17925	retrieve info from table	select  emp.* from    employee emp where emp.employee_salary >       (  select avg(employee_salary) from employee new1           where emp.department_id=new1.department_id           group by  department_id         ) 	0.000135217714230199
13951543	12690	mysql sum of two fields from two different table	select  l.labour_master_id,      l.amount_paid,      cc.amount_paid from (   select labour_master_id, sum(amount_paid) amount_paid   from labours    group by labour_master_id ) l left join (   select labour_master_id, sum(amount_paid) amount_paid   from labour_cashcredits    group by labour_master_id ) cc     on l.labour_master_id=cc.labour_master_id 	0
13951918	15079	left outer join between 3 tables	select seat.apeh05_person_id_k person_id       ,seat.apeh18_seat_r seatno       ,seat.apeh17_floor_k  seatfloor       ,employee.apeh15_cds_d cdsid       ,employee.apeh15_first_n firstname       ,employee.apeh15_last_n lastname       ,employee.apeh15_supervisor_cds_d ll6cdsid       ,employee.apeh15_ll5_cds_d ll5cdsid       ,employee.apeh15_ll4_cds_d ll4cdsid    from iapeh18_seat seat ,     (select * from iapeh15_vendor_employee         union all      select * from iapeh09_local_employee     ) employee    where seat.apeh05_person_id_k = employee.apeh05_candidate_k (+)    order by apeh05_person_id_k 	0.781514952330959
13952993	38572	how to get the next row in oracle sql	select bpv_date from all_dates union select bpv_date + 1  from all_dates where to_char(bpv_date, 'd') = 7   	0.000197690722640178
13953204	8023	join several tables (to fetch user info as 1 row), but one of them is optional (user avatar)	select u.uid as uid         , coalesce(f.filename, 'goatsex.jpg') as filename         , g.field_gender_value as gender_value         , c.field_city_value as city_value from drupal_users u join drupal_field_data_field_gender g on g.entity_id=u.uid  join drupal_field_data_field_city c on c.entity_id=u.uid left join drupal_file_managed f on u.picture=f.fid  where u.name='alex'          ; 	0
13954879	32502	mysql - select only rows where column has unique value	select      id,      sattellite_id,      att_type_id,      time,      roll,      pitch,      yaw  from table  group by      sattellite_id,      att_type_id,      time,      roll,      pitch,      yaw  having count(*) = 1 	0
13955444	2948	sql consolidating multiple rows	select  foo.id as foo_id ,       case          when max(case when lower(trim(bar.status)) = 'stat_a' then 1 end) = 1 then 'true'          else 'false'          end as has_stat_a  from    foo  join    bar on      foo.id = bar.foo_matching_id group by         foo.id 	0.0261156378219186
13955841	32541	counting depending on a field	select vessel,   crane_no,   count(container_no) tot_moves,   count(case when completed_on is null then container_no end) as pending,   count(case when completed_on is not null then container_no end) as completed, min(completed_on) first_m, max(completed_on) last_m from containers group by vessel, crane_no; 	0.000544862796622944
13956171	9724	select union sql	select 8 union all select 0 union all select 15 	0.41367077576165
13957170	33487	using datepart() with the group by command	select sum(totalsellingprice) from dbo.tblserviceorders group by datepart(month,dbo.tblserviceorders.datereceived) order by datepart(month,dbo.tblserviceorders.datereceived) 	0.688093844608646
13957246	26160	using subqueries with multiple results which depend on the main query	select p.id,         p.name,         p.last_name,         case p.id when m.pid_1 then m.pid_2 else m.pid_1 end as partner_id from tc_person p join tc_marriage m on p.id in (m.pid_1, m.pid_2) 	0.525852989767959
13957732	40736	sql - find entry which matches the current date	select  * from    validity_period where   valid_from <= current_date         and valid_to >=current_date     union  select *  from validity_period  where   valid_from <= current_date         and valid_to is null order by id desc limit 1 	0
13958448	17554	display the number of results of a sql query	select l.name ,count(e.pkid)  from " . hc_tblprefix . "events e  left join " . hc_tblprefix . "locations l on (e.locid = l.pkid) where date(startdate) > date(curdate()) group by l.name 	7.86942228237793e-05
13958868	29223	mysql query for fetching multiple distinct values	select date(date) dte, count(distinct answer_userkey) cnt from tbl_data  where date(date) between '2012-07-29' and '2012-08-01' group by dte; 	0.0240930662985027
13958996	9812	magento: populate column data from another table	select * from `catalog_product_entity_media_gallery_value` v inner join `catalog_product_entity_media_gallery` g on g.value_id = v.value_id 	0.000266404668561821
13962457	3955	sql only return text that contains numbers	select cc.display_name, dd.data1 as phone_number     , cc.times_contacted, cc.last_time_contacted  from contacts cc join data dd on cc._id = dd.raw_contact_id where (dd.data1 like '+44[0-9]%'        or dd.data1 like '0[0-9]%'        )      ; 	0.000723250366400792
13963624	36688	mysql: selecting max value and grouping	select status, entity_id, seconds from entities e where e.seconds == (   select max(e2.seconds)   from entities e2   where e2.entity_id = e.entity_id ) 	0.00260213139395532
13965122	8947	selecting most recent record from multiple tables	select   p1.id         ,p1.name         ,v1.followupdate         ,v1.followupinterval from    patients p1         inner join         referals r1 on p1.id=r1.fk_patient_id         inner join         visits v1 on r1.id=v1.fk_referral_id         inner join (         select  max(v.id) as id         from    patients p                 inner join                 referals r on p.id=r.fk_patient_id                 inner join                 visits v on r.id=v.fk_referral_id         group by p.id) v2 on v1.id=v2.id 	0
13965246	40050	save and display status updates like twitter and facebook?	select * from table_name where user = your_user desc limit 1 	0.626684307396726
13966942	17383	how selecting birthdays 7 days before today in mysql	select *,birthdate, concat(if(date_format(birthdate, '%m') = '12',date_format(curdate(), "%y") ,date_format(now(), "%y")), date_format(date_add(curdate(), interval 7 day), '%y')) as birthday  from users  having birthday between curdate() and date_add(curdate(), interval 7 day) 	0
13967574	40159	how to hidden / delete data in row if same from the top	select transaction.id,t.noskom,t.sum_nonpbm,t.sum_noskop,t.sum_npbp from transaction left join  (    select noskom, min(id) min_id,                 sum(nonpbm) sum_nonpbm,                sum(noskop) sum_noskop,                sum(npbp) sum_npbp     from transaction     group by noskom ) t on (transaction.id=t.min_id) order by transaction.id 	0
13968551	29110	in sql, how do i convert a date field into a string if null?	select isnull(convert(nvarchar(30), date, 121), 'insertrandomstringhere') 	0.00092565279970926
13969464	37404	how to create relationship between two non primary key entity in sql server	select *  from [patient] p inner join [othertable] ot   on p.pid = ot.patient_id; 	0.00155306909775376
13969543	30049	converting colums to row in sql server	select      distinct username,      question1 as question,      opt1 as opt,      ans1 as comment  from      tblfeedback where question1='quest1' union all select      distinct username,      question2 as question,      opt2 as opt,      ans2 as comment  from      tblfeedback where question2='quest2' 	0.0565191892618847
13970226	24277	query specific column for 2 different values in sql server	select * from tbl b where b.idindice in (10, 20) 	0.000472694720201283
13970781	15400	how to sum each table value of a data table	select  noskom,  sum (pskom) as sum_skom,  sum (pskop) as sum_skop,  sum (pnpbm) as sum_npbm,  sum (pnpbp) as sum_npbp from ( select noskom, sum (price_skom) as pskom, 0 as pskop, 0 as pnpbm, 0 as pnpbp from skom group by noskom union all select noskom, 0, sum (price_skop), 0, 0 from skop group by noskom union all select noskom, 0, 0, sum (price_npbm), 0 from npbm group by noskom union all select noskom, 0, 0, 0, sum (price_npbp) from npbp group by noskom ) as p group by noskom 	0
13972042	29610	simple query to get exact result	select  t1.empname as emoname, t2.empname as managername from   employee t1  left join employee t2 on t1.managerid = t2.empid 	0.205507177833386
13972198	3963	oracle sql: select from table with nested table	select t."id", tt.myid, tt.myname  from "t_table" t, table(t."name") tt; 	0.0770428412618155
13972284	21393	select rows which have set of values in another table	select    * from    users where   user_type = 2 and   id_user in      ( select          id_user        from (         select            id_user,            group_concat( instrument_title ) instrument_titles         from            instrument          where            find_in_set( instrument_title, 'flute,organ' )         group by            id_user ) tmp       where          length( instrument_titles ) = length( 'flute,organ' ) ); 	0
13972830	30007	create many rows and a single column from many columns	select y1 from yourtable union all select y2 from yourtable union all select y3 from yourtable 	0
13976230	32604	i try to select data from multiple tables with four indexes	select qk1.question_key_name qk2.question_key_name, qk3.question_key_name,         qk4.question_key_name, q.type, q.creation_date  from questions q  inner join question_keys qk1 on q.key1 = qk1.question_key_id  inner join question_keys qk2 on q.key2 = qk2.question_key_id  inner join question_keys qk3 on q.key3 = qk3.question_key_id  inner join question_keys qk4 on q.key4 = qk4.question_key_id; 	0.0143599553316426
13976800	35951	sql server select with multiple groupings	select    u.id,   u.name,   sum(isnull(money,0)) as totalmoneyinrange,   (select max(date) from test_payments where user_id = u.id) as lastpaymentoverall from test_users as u left join test_payments as p on u.id = p.user_id where    p.date is null or   p.date between    cast('12-11-2012' as datetime)    and    cast('12-16-2012' as datetime)  group by u.id, u.name 	0.5507927008112
13977169	520	my mysql call is only returning one value to average where it should be returning all	select date(a.created_at),        avg(timediff(b.created_at, a.created_at)/60/60) from events a inner join events b on a.target_id = b.target_id where a.created_at > '2012-10-10 12:12:12' and a.type = 'started' and b.created_at > '2012-10-10 12:12:12'  and b.type = 'completed' group by date(a.created_at) order by date(a.created_at) 	0.0239720160311372
13978726	39827	finding duplicate value pairs in sql	select uid from tablename  group by uid, name having count(*) = 2; 	0.000247236695637186
13981334	1474	how do i find the difference between today's date and x days from today?	select * from table where date(datecol) between date(now()) and date(date_add(now(), interval x day)); 	0
13982661	36116	giving each subset of records a group id	select [colour code], [size code],          row_number() over (partition by [colour code], [size code]                             order by 1/0) [group id]     from tbl order by [group id], [colour code], [size code]; 	0
13982871	9278	tsql: one row per element with for xml	select productid       ,( select * from production.product as b where a.productid= b.productid for xml path('name') ) as rowxml from  production.product as a 	0.000179288617783027
13983297	20200	sql query to find which group does not have a given value	select distinct value from tbl1 where value not in (     select distinct value     from tbl1     where nbr = 6 ) 	0.00217673855255262
13983997	36865	is it possible to union 6 columns with different tables different database and different server?	select field1 , field2 from   linked_server1.databasename.dbo.tablename_x union all select field1 , field2 from   linked_server2.databasename.dbo.tablename_y 	6.9085387605648e-05
13984084	10845	duplicating values because of sql string?	select s.*, mdb.menu_name     from stocksdb s    innrer join recipelist rl     on s.stock_id= r1.stock_id   <== this join was missing    inner join menudb mdb     on rl.menu_id = mdb.menu_id     where rl.stock_id = '" + stockid 	0.0845969907898755
13984372	6986	get the highest date with combination of day,month and year	select * from ( select punishmentid,punishmentday,punishmentmonth,punishmentyear, dateadd(dd,punishmentday,dateadd(mm,punishmentmonth,(dateadd(yy,punishmentyear,getdate())))) totaldays, row_number() over(partition by gameid order by punishmentyear, punishmentmonth, punishmentday desc) rownumber from punishment where gameid = @gameid  ) orderedpunishment where rownumber = 1 	0
13984930	41175	query for displaying related usernames that match a given username	select * from tablename where username like 'johnny%'; 	0.000218014503311761
13985141	37939	i want to retrieve certain feilds from a table using a column value where table name is unknown	select distinct table_name  from information_schema.columns where column_name in ('colom_name_to_search') and table_schema='your_database_name'; 	0
13985204	12400	how to (or can i) select a random value from the postgresql database excluding some particular records?	select *  from   employee  where  employeestatus != 2  order by random() limit 1 	0
13985310	30388	combined sequential dates	select min(shift_date) start_data,max(shift_date) end_date,           min(shift_id) shift_id from ( select t.*,if(shift_id<>@curshift,@i:=@i+1,@i) group_num,        @curshift:=shift_id  from t, (select @curshift:=0,@i:=0) t1  order by shift_date  ) b group by group_num order by group_num 	0.0299085335424468
13986820	2035	add column that contains data count based on 'where'	select top 1 cola, colb, colc, count(*) over (partition by cola) as count from mydb where cola = '1ab1' 	0
13987337	7781	query multiple tables randomly with limit	select * from core as c, parking as p where c.id=p.id " + " order by random() limit 	0.0549144745588851
13989066	8878	mysql join with same rowname	select sn.*, s.name ssname, s.url surl from shop s inner join shopnews sn on s.sid = sn.sid 	0.197020925308011
13989294	24620	compare values of cells in mysql	select *  from likes li  join likes li2 on li2.id1 = li.id2 and li2.id2 = li.id1 where li.id1 < li.id2 	0.000821708239969589
13990596	8871	how to get row id in mysql	select  l.idfeedback_store, if(@last=(@last:=idfeedback_store), @currow := @currow + 1, @currow:=1) as row_number from feedback_store l, (select @currow := 0, @last:=0) r; 	0.00024069903760149
13991440	3301	sum of datetime difference in sql (hh.mm)	select   atm,   convert(varchar(10), sum(datediff(minute, ticketraisedon, closedon)) / 60)   + '.' +   right('00' + convert(varchar(2), sum(datediff(minute, ticketraisedon, closedon)) % 60), 2) from ticket group by atm 	0.002105567077812
13991965	3579	mysql sum from two joined tables and multiple rows	select sum((ordered_items.price + ordered_items.vat) * ordered_items.qty) + orders.postage_price + orders.postage_vat as total_price from orders join ordered_items on orders.id_orders = ordered_items.order_id group by orders.postage_price, orders.postage_vat 	0
13993129	32375	oracle exist function	select           a.dw_itrack_id       from      idm_itrack a,idm_interaction_dtl_agg b    where       a.dw_dealer_id=b.dw_dealer_id and        a.dw_product_id=b.dw_product_id and       a.dw_program_type_id=b.dw_program_type_id; 	0.78633948525682
13993644	12912	enlist minimum values after joining tables	select name reviewer, title movie, stars from rating inner join movie    using(mid) inner join reviewer using(rid) where stars =    (select min(stars) from rating); 	0.00175272597416065
13993777	31083	left join, with only 1 row per left entry	select * from phone_numbers natural join (   select   person_id,            elt(              min(field(type, 'cell', 'work', 'home')),              'cell', 'work', 'home'            ) as type   from     phone_numbers   group by person_id ) t join persons on persons.id = phone_numbers.person_id 	0.00139115245206149
13995127	4710	php/mysql group and count by distinct dates and users	select userid, count(distinct date(time)) from my_table group by userid 	0.00163617229755167
13999162	75	using timestamps to combine 3 identical tables	select a.item, a.color, a.timestamp from (select ... from first  union select ... from second union select ... from third) a inner join (select item, max(timestamp) as maxtime from (select ... from first  union select ... from second union select ... from third) z group by item) b on a.item = b.item and a.timestamp = b.maxtime 	0.00061017092923378
13999615	35524	mysql - select dates that are 1 week intervals from today	select * from my_table where datediff(curdate(), my_date) % 7 = 0 	0
14000022	7632	get conflicting events in sql server 2008 query	select distinct ep1.event_id,ep2.event_id from event_participant ep1 inner join event_participant ep2 on ep1.person_id=ep2.person_id where ep1.event_id <> ep2.event_id order by 1,2 	0.069365730613978
14001486	28418	sql server 2008 foreign key confilict	select *  from cmevent c where not exists (   select *    from baseevent   where oid = c.oid ) 	0.0803160787783563
14004274	36540	how can i merge these sql queries	select  o.*,                                                 (select                                                      concat(c.firstname, ' ', c.lastname)     from         wwwpser_customer c     where         c.customer_id = o.customer_id) as customer,  c.provincia_id as payment_provincia_id               from wwwpser_order o     left join                                        wwwpser_comuna c on (o.payment_city = c.comuna_id)   where o.order_id = '20' 	0.185463335549887
14005532	11922	sql query to find multiple wives	select    distinct a.wifeid from    dbo.couple a    inner join dbo.couple b       on a.wifeid = b.wifeid       and a.husbandid <> b.husbandid        and a.startdate < b.enddate       and a.enddate > b.startdate; 	0.116557199821102
14010502	7049	select distinct field along others query while statement is done	select * from mytable group by f2 	0.0620714971861649
14011460	31409	querying sql database with subtypes, displaying it in c#	select p.prod_id,p.name,p.barcode,c.price, w.caliber_id  from product p inner join card c on  ( p.prod_id  = c.prod_id  ) inner join weapon w on  ( p.prod_id  = w.prod_id  )  where p.barcode = 'barcode' 	0.734600081818161
14012392	33287	sql joining three tables to result in two columns, based on a date condition	select    case when table_x.date_column > getdate() then table_y.some_column                                              else table_z.some_column end from table_x join table_y join table_z (insert appropriate join clauses) 	0
14012404	3138	how to check another mysql join based on a previous join?	select fbm.username2 as followed_by_mikha,    users.first_name,    users.last_name,           users.username          from connections    left join users on users.username = connections.username1    left join connections fbm on fbm.username2=connections.username1 and fbm.username1 = 'mikha'    where connections.username2 = 'maricela'    order by users.username desc limit 10 	8.36115698068465e-05
14012896	20400	sql server 2012 queries: how to query 2 tables and filter results	select users.id, users.email from users where users.id not in (select roles.user_id from roles where role > 1) 	0.271916755340314
14013371	14515	mysql select with min	select `message`,`username` from `list` where `list_id`=2 order by `number` asc limit 1 	0.237176978990594
14013997	13311	are aliases to be used outside the select in which they are declared?	select c1 from (select 42 as c1) 	0.0354775781103932
14014637	32897	sql "count" wrong results when joining more tables	select    reportedby,   count (case when t2.status = 'checking' then 1 end) as numberhaschecking,   count (distinct case when t1.status not in ('new','checking') then t1.id end) as numberdifferentfromnewchecking,    count (distinct case when t1.status = 'closed' then t1.id end) as numberclosed from   t1     inner join   t2     on t1.id = t2.t1id group by    reportedby 	0.602089844644453
14016897	10101	mysql : check date range	select * from tablename where ('2012-12-25' between date(concat_ws('-', startyear, startmonth, startday)) and                   date(concat_ws('-', endyear, endmonth, endday))) and       ('2013-01-10' between date(concat_ws('-', startyear, startmonth, startday)) and                   date(concat_ws('-', endyear, endmonth, endday))) 	0.00338580242677137
14017146	15311	use order by clause on foreign language field	select *  from countries  order by `name_czech` 	0.144987245661967
14018222	40628	find substring from a string	select (case when instr(string, '/') = 0 then "" else substr(string, instr(string, '/')) end) from ( select string from ac1_control ) 	0.00429262544912538
14018394	1890	android sqlite query - getting latest 10 records	select * from (select * from tblmessage order by sortfield asc limit 10) order by sortfield desc; 	0.000303150578585608
14019275	264	read data from sqlite where column name contains spaces in android	select "condition name" from library 	0.021846543046148
14019624	30461	sqlite query to find sum of a year by the given dates	select strftime('%y', date),sum(replace(price, ',', '')) from example group by strftime('%y', date); 	0
14022075	15626	order in mysql query	select * from (    select acolumn, 1 as sortorder from table1    union all    select acolumn, 2              from table2    union all    select acolumn, 3              from table3    union all    select acolumn, 4              from table4 ) u order by acolumn, sortorder; 	0.547128130527132
14022146	10275	get distinct results with latest records	select    c1.id,    c1.currency1_id,    c1.rate,    c1.currency2_id,    c1.`date` from currency_ex_rate_txn c1 inner join (     select currency2_id, max(`date`) latestdate     from currency_ex_rate_txn     group by currency2_id ) c2  on c1.currency2_id = c2.currency2_id      and c1.`date`       = c2.latestdate order by c1.`date` desc; 	5.8033385438849e-05
14023028	33319	how to select one row in oracle table?	select a.*          from (select b.*, rownum rn          from (select y.componentstatsid, y.name, y.status, y.location, y.type, y.powercapacitywatt, y.coolingcapacitybtu, y.minambienttemp, y.maxambienttemp,          y.operatinghamidityrange, y.dcallowedweightkg, y.dcmaximumweightkg, y.dcallowedpowerwatt, y.dcmaxpowerwatt, y.dcallowcoolingpowerbtu, y.dcmaxcoolingpowerbtu, y.datedeployed, y.dateadded, y.description         from component x, componentstats y where x.componentstatsid = y.componentstatsid and y.componenttypeid = 1000 and y.componentstatsid=35         order by %s %s) b          where rownum <= ?) a              where rn > ? 	0.000940335523451833
14023145	22100	find closest date in sql server	select top 1 * from x where x.date < @currentdate order by x.date desc 	0.0110496626604676
14023292	28392	how to get rownum like column in sqlite iphone	select      (select count(*)      from [table] as t2      where t2.name <= t1.name) as rownum,     id,     name from [table] t1 order by t1.name asc 	0.0329672995101341
14023608	8747	select duplicate values in one column in a table	select      n1.id as col1, n2.id as col2, n1.name from      names n1, names n2 where      n1.name = n2.name      and n1.id > n2.id 	0
14023812	25246	combine two mysql sum select query to one query	select sum(prc) from ( select sum(price) prc from table1 where acc_id = '555' union all  select sum(price) prc from table2 where account = '555' && active='1' ) a 	0.00325166004984019
14023942	3823	complicated sql query - select all landlords' properties and subtract costs in one query	select landlord.id as landlordid, landlord.name,         isnull(totalrent,0) as totalrent,         isnull(totalcost,0) as totalcost from landlord left join      (select sum(rent) as totalrent, landlordid       from property      group by landlordid) rents on landlord.id = rents.landlordid left join      (select landlordid,sum(cost) as totalcost      from property      inner join maintenance         on property.id = maintenance.propertyid      group by landlordid      ) maintenancecosts on landlord.id = maintenancecosts.landlordid order by landlord.name 	0.151224818385807
14024503	27807	mysql combine rows based on consecutive key values and then merge	select t.*,        (select min(returndate) from t t2 where t.bookid = t2.bookid and t2.id > t.id and t2.type = 0) as returndate from t where type = 1 	0
14027270	25528	set selectparameter from textbox in asp.net	selectcommand 	0.198924073879546
14027801	16584	php,postgresql,mysql	select  cont.name, cont.total,cp.contractor_id,cp.amount_paid,wt.id                 from                 (                   select  name,id, sum(amount_to_be_paid) as total                   from contractors group by name,id                 ) cont                 left join                 (                   select contractor_id,sum(amount_paid) as amount_paid                   from contractor_payments                   group by contractor_id                 ) cp                   on cont.id = cp.contractor_id                               left join worktypeids as wt on cont.worktypeid_id = wt.id and wt.project_id=2 	0.55174265672721
14029331	6614	select * from mytable where name='%jack%' in mysql	select * from mytable where lower(name)  like '%jack%'; 	0.248037588142942
14031348	21024	combine results of different tables to create an alphabetic list	select id,search_word as word from search_words union select id,category_name as word from categories order by word 	9.91292051403928e-05
14031644	15992	finding dependencies on a given function in oracle	select * from dba_dependencies where referenced_owner = 'your_schema' and referenced_name = 'a'; 	0.0418981937261222
14031852	38542	mysql query needed - joining 4 tables into one table	select ci.custid, ci.actoptionid, o.totalquantity totalonlineq,         o1.totalquantity totalofflineq, a.actname,         (o.totalquantity + o1.totalquantity) totalquantity   from customerinformation ci  inner join actopts a on ci.actoptionid = a.actoptionid left join (select * from (select custid, totalquantity from onlineorders order by date desc) ass a group by custid) o on ci.custid = o.custid  left join (select * from (select custid, totalquantity from offlineorders order by date desc) ass a group by custid) o1 on ci.custid = o1.custid; 	0.00937547166851596
14032319	41054	subselect and group by	select id_main, field,      (select path      from main_logs      where id_main=main.id_main      group by path      order by count(path) desc      limit 1) as most  from main  where filter in (1,3,5); 	0.647248961816718
14032472	15212	sorting distinct attributes in sql's access	select      movie_genre,      avg(runtime) from      movie group by     movie_genre 	0.536169331745679
14032705	1782	values from 2 tables in sqlite	select      a.id,      a.text,      (select count(1)               from b               where b.a_id=a.id                   and b.fresh ='yes') as fresh from a; 	0.000940812251690487
14036505	28983	mysql - fetch data where the $var = array?	select post_name from main  where by_user = 'user1' or by_user in (select subscribe_to from subscribers where subscriber = 'user1') 	0.0140144869436085
14037979	39291	merging two different table's data by sql	select t1.name state_name, t2.name country_name from state_m t1,country_m t2 where t1.countryid=t2.countryid; 	0.000283164939999502
14038413	26718	sql query to generate employee absent report for a given range of dates	select m.empid     as `empid`       , d.dt        as `absentdate`   from ( select date(t.presentdate) as dt            from transaction t           where t.presentdate >= '2012-11-21'              and t.presentdate < date_add( '2012-12-22' ,interval 1 day)           group by date(t.presentdate)           order by date(t.presentdate)        ) d  cross   join master m   left   join  transaction p     on p.presentdate >= d.dt    and p.presentdate <  d.dt + interval 1 day    and p.empid = m.empid  where p.empid is null  order     by m.empid      , d.dt 	0
14041200	40935	how to convert date into month number?	select  to_char(to_date('01-jan-12','dd-mon-yy'),'mm') from dual; 	0
14041740	23518	how do i query three tables based on a single field	select  a.*, c.* from    customer a         inner join customer_link b             on a.customer_id = b.customer_id         inner join customer_stats c             on b.product_id = c.product_id 	0.00010128746825315
14042286	14749	how can i copy a datatable while converting data types?	select upc, number, description, brand, uom, [group], cast(total_dollars as decimal(38,17)) as total_dollars, cast(total_units as int) as total_units, date into newtable from oldtable 	0.0630561392170569
14045994	24157	remove trailing zeroes using sql	select cast(round(avg(cast(k.totalnumberdays as numeric(12,2))),2) as decimal(12,2)) totalnumber 	0.369745108032984
14046399	10900	how to count from a table based on another table	select qo.question_id, qo.option_label as choice, count(*) as votesmale from question_options qo  left join session_answers sa on qo.id = sa.option_id join [session] s on s.id = sa.session_id and s.gender = 'm' where qo.question_id = 10114< group by qo.question_id, qo.option_label 	0
14047971	27314	get last line column on mysql	select * from person order by personid desc limit 1 	0
14049806	12283	mysql inner join two tables on the maximum values of the second table	select  a.* from    tablename a         inner join         (             select listing_id, user_id, max(bid_ts) maxdate             from tablename             group by listing_id, user_id         ) b on  a.listing_id = b.listing_id and                 a.user_id = b.user_id and                 a.bid_ts = b.maxdate 	0
14050558	7571	inner join 4 columns with different server .., different database ., and different table	select     account.accntid, account.accountholder, terminal.tid, branch.storeno, branch.branchname, branch1.branchid from      ecpayserv2.ecpnweb.dbo.account as account      inner join possqlserver.ecpnpos.dbo.branch as branch         on account.accntid=branch.accountid      inner join ecpayserv2.ecpnweb.dbo.branch as branch1         on account.accntid=branch1.accountid     inner join ecpayserv1.ecpndb.dbo.terminal as terminal          on account.accntid=terminal.??? 	0.000295244073910195
14052229	15546	select same data from two columns in a table, and using one sql statement to show all data	select * from em where (birth, high) in (('11/23','65'),('05/16','50')); 	0
14052456	39227	select all orders with more than one item and check all items status	select o.id  from orders o  join order_details od on o.id=od.order_id where o.status='ok' group by o.id having count(distinct od.id)>1 and sum(case when od.status not in ('s1','s2')               then 1               else 0          end) = 0 	0
14052983	18902	how to display the day on which a user born in mysql?	select dayname('2012-12-27'); 	0
14053119	10540	how to combine two sqlite select statement with two conditions	select * from tbl_questions where (id in (select id from tbl_questions where difficulty = 1 limit 0,50) or id in (select id from tbl_questions where difficulty = 3 limit 0,50)) and approved = 1 	0.00816594833892033
14055116	22792	mysql match against multiple words	select *  from products  where match(desc)        against('"iphone 4s"' in boolean mode)  limit 10 	0.0463419122549067
14056661	3793	php & mysql: use a table for a filter list for another table	select     d.* from      domains d  left join     words w on(d.domain like concat('%',w.word,'%') )  group by     d.domain having     count(w.id) < 1 	0.00101029987702297
14057190	2223	find all the related tables	select t.name as tablewithforeignkey, fk.constraint_column_id as fk_columns , c.name as foreignkeycolumn      from sys.foreign_key_columns as fk         inner join sys.tables as t on fk.parent_object_id = t.object_id         inner join sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id     where fk.referenced_object_id = (select object_id from sys.tables where name = 'customers')     order by tablewithforeignkey, fk_partno 	0.000144173111433207
14058950	31159	select rows that cant be casted	select isnumeric('2d5'),        isnumeric('+') 	0.269612190203402
14059950	9688	php insert row into database	select id_product from ps_products where id_product not in (select id_product from ps_product_supplier; 	0.00439656058964157
14061035	32041	mysql select the count of a number range	select     s.step   , coalesce(t.n, 0) as n from         ( select 1 as step union all           select 2 union all           select 3 union all           select 4 union all           select 5 union all           select 6          ) as s     left join         ( select step                 , count(*) as n            from my_table            group by step          ) as t       on t.step = s.step order by     s.step ; 	8.9230445164178e-05
14062478	37712	sql: populate a table with variables defined in another table	select  employeeid, sum(commissiontotal) as commissiontotal from      (select distinct     calls.call#,     calls.employeeid,     calls.commissiontype,     calls.typeofcall,     case      when calls.commissiontype = 'mkm' then sum(commissions.mkm)     when calls.commissiontype = 'tkm' then sum(commissions.tkm)      when calls.commissiontype = 'lo' then sum(commissions.lo)     end as commissiontotal     from calls     left join commissions      on calls.employeeid=commissions.employeeid     where typeofcall = 'dc'     group by calls.call#,     calls.employeeid,      calls.commissiontype,     calls.typeofcall) a group by  employeeid 	0.00680317835777066
14065296	5998	sql select all columns with character limit	select substr(col1,20), substr(col2,20),substr(col3,20), .... from users limit 10 	0.00784116434169105
14065730	28896	datas for report from mysql table	select locations,year,month, (select ratepersqft from report where          locations=tl.locations         and         date_format(date,'%y%m')<=tp.monthnum         order by date_format(date,'%y%m') desc         limit 1) as t        from (select distinct locations from report) tl, (select distinct year(date) year,                  monthname(date) month,                  date_format(date,'%y%m') monthnum                  from report) tp order by locations,monthnum 	0.00862264065483858
14067609	35796	very big data in mysql table. even select statements take much time	select * 	0.0883481463673914
14068780	9884	inner join select columns from table2	select     p.*      ,     s.columnname      ,     j.columnname  from     1_packages_plu as p     inner join 1_stock as s         on p.fk_products_id = s.fk_products_id         and         branch = 1     inner join 1_products as j         on p.fk_products_id = j.id where     fk_packages_id = 54 	0.014512532817398
14068853	40458	how to add hard-coded literals to a query results on sql server?	select  'column2' as columnname, count(column1) as expr1     from     table1 	0.401580249005812
14070110	32995	how to write query for comparing column having comma-separated values?	select  *  from table1 join table2  on find_in_set(table1.location_id, table2.location_id) > 0 	0.043558878620052
14070170	4213	database relation tables	select * from house h inner join neighborhood n on h.house_id = n.house_id inner join city c on n.neighborhood_id = c.neighborhood_id where c.city_id = 8 and n.neighborhood_id = 123 order by h.house_id 	0.0835209265292191
14070916	31877	odbc sql query to create two columns for debit and credit from one	select account_ref, balance as debits, null as credits from table1 where balance < 0 union all select account_ref, null as debits, balance as credits from table1 where balance > 0 	0.0013319259786481
14073688	9265	limiting results of a triple join	select * from trips t join days d on t.id = d.tripid join legs l on d.id = l.dayid where d.id in (       select id from days d where d.date > date order by d.date limit 1 ) 	0.591476437269881
14074064	4247	csv in where condition mysql	select id from tableb where find_in_set(s_id, (select id from tablea where name = 'shirts')) is not null 	0.31328622711368
14074423	7175	select one record after order by	select release_artwork.release_id, release_artwork.position, artwork.small_filename, artwork.small_width, artwork.small_height from   release_artwork   inner join artwork on artwork.artwork_id = release_artwork.artwork_id   inner join   (   select     ra.release_id as release_id    ,min(ra.position) as rap   from     release_artwork ra   group by     ra.release_id   ) mins   on mins.release_id = release_artwork.release_id     and mins.rap = release_artwork.position order by   release_artwork.release_id 	0.00237598444339686
14076744	8801	google big query on sorting unique combination of multiple columns	select referral, target, count(*) as cnt from [mydataset.referrallog]  group by referral, target order by cnt desc 	0.0029896076997661
14076758	11734	possible to add auto incrementing variable to row results of group by in mysql?	select user_id, count, sum, @row := @row + 1 as newindex from (select    count(*) as count,    user_id,    sum(earnings) as sum from ci_league_result  group by user_id order by sum desc limit ".$page.', '.$per) r cross join (select @row := 0) rr; 	0.00024862250272541
14077445	36546	mysql opposite of select max	select      listings.end_date,      listings.user_id,      listings.title,      listings.auc_fp,      listings.id,      listings.auc_image1  from listings  inner join (select                  listing_id,                   user_id,                   bid_ts maxdate             from bids             where bid_ts not in (select max(bid_ts) from bids)             group by listing_id, user_id             ) bids on listings.id = bids.listing_id where bids.user_id=$userid and listings.end_date > now() 	0.0466804104357198
14079904	35434	mysql combine columns of multiple tables	select a.name, a.surname, b.age from   (     select @row := @row + 1 rankno,            name, surname     from   table1, (select @row := 0) r   ) a   inner join   (     select @row1 := @row1 + 1 rankno,            age     from   table2, (select @row1 := 0) r   ) b on a.rankno = b.rankno 	0.000867590785900344
14081202	4499	select multiple records by short query	select * from uk_data where  comp_post_code like :comp_post_code and ( cat1 like :cat or cat2 like :cat or cat3 like :cat or cat4 like :cat or cat5 like :cat or cat6 like :cat or cat7 like :cat or cat8 like :cat or cat9 like :cat or cat10 like :cat ) 	0.117513610413913
14082524	25844	inner join more than 2 tables in a single database	select * from a  inner join b on a.id = b.id  inner join c on b.id = c.id 	0.0196232843363265
14085124	7676	inner join, count and group by to get ratios	select t.task_id,   t.task_name,   t.description,   t.deadline,   sum( if(c.status = 'complete', 1, 0)) * 1.0 /count(c.status) from tasks as t inner join completions as c on t.task_id = c.task_id  group by t.task_id having t.deadline >= curdate() 	0.344850782864878
14086041	2557	mysql join two tables to find all rows except the row with the max value	select     lst.end_date,     lst.title,     lst.auc_fp,     lst.id as listing_id,     lst.auc_image1,     b.user_id as bid_user_id,     b.bid as bid_amount,     maxbids.maxbid as maxbid_for_listing from listings lst inner join (     select listing_id, max(bid) maxbid     from bids b     group by listing_id ) maxbids on lst.id = maxbids.listing_id inner join bids maxusers on maxusers.bid = maxbids.maxbid and maxusers.listing_id = maxbids.listing_id inner join bids b on     maxbids.listing_id = b.listing_id and     b.bid < maxbids.maxbid and     b.user_id <> maxusers.user_id where lst.end_date > now() order by lst.list_ts desc 	0
14086140	21929	get the record by the lowest id	select pd.*    from page_description pd    join (select page_id,                 min(language_id) as language_id           from page_description           group by page_id) as a     using (page_id, language_id); 	0
14088172	15192	select all from first table, count instances of id in second table	select c.number, c.id, c.keyword, isnull(s.count,0) as count from campaigns as c left join (   select campaign, count(*) as count   from subscribers   group by campaign ) as s on c.id = s.campaign order by c.id asc 	0
14088443	23035	need help figuring out mysql query to count if a certain number	select fruit, count(*) numberofinstance from (     select fruit1 fruit, number1 num from table1     union all     select fruit2 fruit, number2 num from table1     union all     select fruit3 fruit, number3 num from table1     union all     select fruit4 fruit, number4 num from table1 ) s where num = 5 group by fruit 	0.0110182994809958
14089890	15529	mysql select condition	select match_id from table_name where "aaa" in (player_1,player_2) and    "bbb" in (player_1,player_2); 	0.262960381620331
14091118	29264	select from 2 tables (kohana framework)	select date(t.`date`)                                    as `date`,         sum(cast(substring(t.`package`, 16) as unsigned)) as `credit`,         sum(t.pay_amount)                                 as `paid`  from   (select *          from   table1          union          select *          from   table2) as `t`  group  by `date`  order  by `date` asc 	0.0277814304863851
14091183	18269	sqlite order by date	select * from table order by date(datecolumn) desc limit 1 	0.128242687556257
14091296	39102	mysql select distinct - show value and totals	select user1, count(*) total from yourtable  group by user1 order by total desc limit 0, 10 	0.0012087093657036
14092176	5217	query shows each row twice	select tbluser.fullname, tbluser.email, tbljobadv.advtitle, tblpersonalinfo.country,     tblpersonalinfo.city, tbljoboffer.digitalsignature  from    tbluser  left join    tblpersonalinfo on tbluser.userid = tblpersonalinfo.userid left join    tblapplication on tblapplication.userid = tbluser.userid  left join    tbljobadv     on tbljobadv.advid = tblapplication.advid    and tbljobadv.isusable = 'usable' left join    tbljoboffer on tbluser.userid = tbljoboffer.userid where    tbljobadv.userid in (select userid from tbluser where email = 'h@y.com') 	0.000811761718931359
14092641	13469	how to find the rows which are not found in another table?	select    item.id from   item left join log on (log.itemid = item.id) where   log.itemid is null   or log.status !='1' order by item.id limit 1 	0
14093795	24458	select all records from table a and join table b to get a's property	select ability.ability, if(child.idability,'+','-') from ability left join child on ability.idability =child.idability and child.name="joe"; 	0
14094327	22364	how to combine these two sql statements?	select sum(case when ws.id_workflowtype = 1 then 1 else 0 end) as cntcm_prwk      , sum(case when ws.id_workflowtype = 3 then 1 else 0 end) as cntcm_cmq from dbo.caseworkflow cw  join vew_casepersonnelsystemids vcps on cw.id_case = vcps.id_case join dbo.workflowstates ws on ws.id_workflowstate = cw.id_workflowstate where cmsuid = @nsuid 	0.0517774239227553
14096724	41115	database design for multiple user preferences?	select r.user_id from (select uu.user_id from users u right join user_location ul using (user_id) right join users uu on uu.location_id = ul.location_id where u.user_id = 1) r inner join user_preference up on up.user_id = r.user_id inner join user_preference up1 on up1.preference_id = up.preference_id and         up1.user_id = 1 group by r.user_id; 	0.100300682786315
14097470	5838	select filter terms along with their counts	select  a.text, count(b.id) totalcount from    filters a         left join items b             on b.title like concat('%',a.text,'%') group by a.text order by totalcount desc 	0.00148595232850018
14098746	10627	using min, max and avg in mysql query	select 'min', product_id  from productlist where cost = (select min(cost) from productlist) union  select 'max', product_id from productlist where cost = (select max(cost) from productlist) union  select 'avg', round(avg(cost),0) as avg from productlist 	0.399795076102666
14099928	17449	how to select row with the latest timestamp from duplicated rows in a database table?	select * from (  select pk_id,         user_id,         some_timestamp,         row_number() over (partition by user_id order by some_timestamp desc) col  from table) x   where x.col = 1 	0
14099946	10046	join clause not showing all results	select  date_format(l.created_on,"%d/%m/%y") as date from logs l left join logs_rewards lr on l.id = lr.related_log_id  left join agents a on a.id = l.agent_id  where l.log_status = "1"  and date_format(l.created_on,"%m/%y") = '12/12' and l.agent_id = '18'  group by year(l.created_on), month(l.created_on), day(l.created_on) desc 	0.547314259047863
14101422	2584	removing duplicates from a query with conditions in access 2007	select transactionid, field1, fieldn, max(interestrate) from tablename group by transactionid, field1, fieldn 	0.570503784599182
14104055	30723	ordering by specific field value first	select * from your_table order by case when name = 'core' then 1 else 2 end,          priority 	0.000208938823383002
14104269	20039	incorrect and duplicated results from a sqlite fts3 unionquery	select id from searchtable where searchtable match 'tuxedo hotel' 	0.444500189811976
14107229	14160	how to know oracle database server ip?	select utl_inaddr.get_host_address from dual; 	0.265694346937431
14109101	10586	group count results by date between two tables in mysql	select   date(created_at),   sum(case when `type` = 'votes' then 1 else 0 end) as 'totalvotes',   sum(case when `type` = 'users' then 1 else 0 end) as 'totalusers' from (     select created_at, 'votes' `type` from vote     union all     select created_at, 'users'        from users ) t group by date(created_at) order by date(created_at) desc 	0.000876188653133441
14109547	16461	select avg vote but leave out the top and bottom 5% of votes using mysql	select avg(vote) from (   select vote, @r:=@r+1 as rownum   from votes, (select @r:=0) x   where question_id = 63   order by vote ) x where rownum > @r * .05   and rownum <= @r * .95 ; 	9.70032756298364e-05
14110594	19440	unique sorting scenario	select l.*, (l.league = 'major league') as major from league_points as l      left join league_points as major          on l.player = major.player and major.league = 'major league' order by major.points desc, major desc, league desc 	0.166803821605728
14110954	19493	optimizing select query from one small table and one large table	select    u.username as username,    u.id as id,    f.no_of_messages  from users as u left join (    select user_id, count(*) no_of_messages     from users_messages    group by user_id ) as f on f.user_id = u.id order by u.id limit 20; 	0.00249554260360454
14111633	36254	get day name from timestamp in mysql	select dayname('2013-01-01 10:10:10'); 	0
14112917	815	trying to get ordered query of all records added in last 1 hour	select * from `chats` where `chat_id` = 1  and `time` >= date_sub(now(), interval 1 hour); order by `time` 	0
14113267	14541	sql select only rows where exact multiple relationships exist	select parent_id from rel group by parent_id having sum(prop_id not in (5,1)) = 0 and sum(prop_id = 1) = 1  and sum(prop_id = 5) = 1 	0.0013217828991423
14113469	11139	generating time series between two dates in postgresql	select date_trunc('day', dd):: date from generate_series         ( '2007-02-01'::timestamp          , '2008-04-01'::timestamp         , '1 day'::interval) dd         ; 	0.00201492500369678
14114801	4490	mysql query to find friends in common	select f.friend from (select rel1, rel2 as friend       from friends       where rel1 in (1, 5)       union       select rel2, rel1       from friends       where rel2 in (1, 5)) f group by f.friend having count(*) > 1 	0.00107894383220755
14115125	792	how to get distinct and lastest record with inner join query	select customer.mobileno, max(bill.idate) as idate from (customer inner join                  bill on customer.bikeno = bill.bikeno) group by customer.mobileno order by idate 	0.0106646374029311
14115664	41176	mysql finding many children of one parent	select * from child where parent_id=x; 	0
14116473	32903	in sql server, how do i select null for two specific cases (query included)	select     case when @reportparameter1 = 'all' then null                  when @reportparameter1 = 'prescreens' then null                 else crr.codes end as codes from         client_response_ranges_for_ssrs_respondent_answer crr where crr.name =  @reportparameter1 	0.145225223163503
14116627	38058	i need to join three tables, group the results by one column, and display the highest value from another column	select  a.*, b.*, c.* from    users a         inner join emails b             on a.id = b.user_id         inner join messages c             on a.id = c.user_id         inner join         (             select user_id, max(date) maxdate             from messages             group by user_id         ) d on c.user_id = d.user_id and                 c.date = d.maxdate 	0
14116860	11422	combine two rows in one table to single row using sql	select top 1 t1.id,t1.name,        t1.address,       t1.acc_number,        coalesce(t1.bookingno, t2.bookingno) as 'bookingno',coalesce(t1.amt, t2.amt) as 'amt' from testtable1 t1 join testtable1 t2       on t1.acc_number = t2.acc_number and t1.name!=t2.name 	0
14117343	22546	applying condition on parameters in sql select query	select a,b, case when (a-b) < 0 then 0 else (a-b) end as c  from table 	0.740980500632574
14118382	35260	select data from two tables with speed	select  b.* from    articles a         inner join articles_meta_data b             on a.id = b.article_id 	0.0260101568187691
14119466	7539	sql queries to find unmatched data in many to many relationship	select *   from personalias_table pa        left outer join person_table p on pa.person_id = p.person_id         and pa.uniqe_id = p.uniqe_id  where p.uniqe_id is null 	0.00686597985625025
14120189	17023	count column values sort by occurence	select  user_model, count(*) totalcount from    users group by user_model order by totalcount desc 	0.00117568307223093
14120971	24057	sql selecting from one table with where clause on the joined tables	select testtype,testname, limits  from createscripttable  inner join testoptionstable on createscripttable.testname = testoptionstable.testname  left join testresultstable on createscripttable.testname = testresultstable.testname where createscripttable.instrumenttype= 'instrument1'  and testresultstable.istestcomplete is null order by [index] asc, testname 	0.000141916272159324
14122236	14335	sql query based on complex business logic	select  result.id,          result.deviceid,          max(start.timestamp) starttime,          result.timestamp endtime,          result.measure from    t result         inner join t start             on start.deviceid = result.deviceid             and start.timestamp < result.timestamp             and start.datatype = 19             and start.measure = 1 where   result.datatype = 54 group by result.id, result.deviceid, result.timestamp, result.measure 	0.642886684648389
14125051	29857	return data on max value (without affecting result of max)	select service_availability.service_product, service_availability.specificity  from service_availability  inner join (     select service_availability.service_product, max(service_availability.specificity) as spec     from service_availability     where (service_availability.state = "tx" or service_availability.state = "cw")     group by service_availability.service_product ) max_spec   on service_availability.service_product = max_spec.service_product   and service_availability.specificity = max_spec.spec where service_availability.available = true 	0.000238415092139424
14125316	917	differentiating between 2 sql column names with the same name in a c# sqlconnection	select c.court_id,    c.court_name,    ca.court_address as cacourtaddress,    ca2.court_address as ca2courtaddress from court c " + join court_addr ca on c.court_addr_id = ca.court_addr_id " + join court_addr ca2 on c.court_postal_addr_id = ca2.court_addr_id " + ... 	0
14125647	3134	joining tables and making count operation - mysql	select  m.memberid,          count(rm.memberid) numberofrentedmovies,         sum(case when rm.returndate < curdate() then 1 else 0 end) returndata  from members m left join rentedmovies rm     on m.memberid = rm.memberid  group by m.memberid 	0.311117743856036
14126302	35277	how to delete rows which can't be cast to int	select * from mytable where (housenr !~ '^[0-9]+$') 	0.165048325817777
14127521	3922	how to write query which i can get data by month?	select ... from vendas where emissao >= '06/01/2012' and emissao < '07/01/2012' 	0.00107875520850949
14127557	2503	mysql query select where before join	select * from websites  inner join websites_statistics on website.id =  websites_statistics.website_id where websites.website = 'google.com'     limit 0,1 	0.616195376293885
14127808	16471	select parent and children in single column	select id, name, 0 as seq from cmstr union select id, name, seq from dmstr 	0.000250208522027706
14127967	9402	update table with correct currency rate	select c.ccy, c.rate/eurogbp.rate as gbpexchangerate from currency c cross join      (select rate from currency c where c.ccy = 'gpb') eurogbp 	0.205568018204329
14129109	20881	sql - select not repeated rows from 2 tables?	select * from table1    except      select * from table2 	0.000810379984169372
14131139	14779	view with sums returning partial or incorrect data set	select     `archived_items`.`arcpartnumber` as `partnum`,     `archived_header`.`ahdeliverydate` as `deliverydate`,     `archived_items`.`arctransactionnumber` as `transactionnumber`,     sum(`archived_items`.`arcordered`) as `ordered`,     sum(`archived_items`.`arcshipped`) as `shipped`,     sum(`archived_items`.`arcbackordered`) as `backordered` from     ( `archived_items`         left join `archived_header` on (             (`archived_header`.`ahtransactionnumber` = `archived_items`.`arctransactionnumber`         ))) where ((`archived_items`.`arctransactiontype` = 3)     and      (`archived_header`.`ahdeliverydate` >= curdate())) group by `archived_items`.`arcpartnumber` `archived_header`.`ahdeliverydate`, `archived_items`.`arctransactionnumber` order by `archived_items`.`arcpartnumber`, `archived_header`.`ahdeliverydate` 	0.581060987483831
14132810	1971	mysql where clauses with condition to display specific age	select column_name(s) from table_name where age between age >=20 and age <=30 	0.00252940132622662
14135175	3627	how to search a string in another string using charindex?	select     case         when charindex('333',[actype iata]) > 0 then 'big ac'         when charindex('340',[actype iata]) > 0 then 'big ac'         when charindex('332',[actype iata]) > 0 then 'big ac'         else ''     end as mycolumn from     [mytable] 	0.0366002300266162
14136057	10158	how to check current value on specific column (sql server)	select   @newid = max(convert(int,substring(status, 8, 2)))   from mytable where [status]='waiting' 	0
14136197	19787	how to assign current date with specific time to column?	select dateadd(day,datediff(day,'20010101',getdate()),'2001-01-01t08:00:00') 	0
14136984	24705	how to check data integrity within an sql table?	select userid, count(*), sum(direction * rule) from (     select userid, direction, @inout := @inout * -1 as rule     from accesslog l, (select @inout := -1) r     order by userid, accesstime ) g group by userid; 	0.0152262861550007
14139201	6727	query the next time interval	select t1.`timeto`, min(t2.`timefrom`) from   yourtable t1 inner join yourtable t2   on t1.`timeto`<t2.`timefrom` group by t1.`timeto` having   not exists (select null from yourtable t3               where t1.`timeto`<t3.`timeto`               and min(t2.`timefrom`)>t3.`timefrom`) 	0.0038240168130962
14140619	37596	ignore sql inner join if there are no records to join?	select * from products  left join @synonymtable as a on ([products].[title] like a.[synonym]) where a.[synonym] is not null        or not exists (select b.[synonym] from @synonymtable b) 	0.153002639457833
14140662	9445	selecting one item from rows based on date	select  a.itemid,          d.newprice - a.newprice `price change from 4th jan` from    tpricehistory a         inner join         (           select itemid,                   date_format(max(str_to_date(pricechangedate, '%b %d %y')),'%b %d %y') maxdate           from   tpricehistory           where  str_to_date(pricechangedate, '%b %d %y') <= '2012-01-04'           group by itemid         ) asofdateprice on a.itemid = asofdateprice.itemid and                            a.pricechangedate = asofdateprice.maxdate         inner join          (           select itemid,                   date_format(max(str_to_date(pricechangedate, '%b %d %y')),'%b %d %y') maxdate           from   tpricehistory           group by itemid          ) latestdate on a.itemid = latestdate.itemid         inner join tpricehistory d             on latestdate.itemid = d.itemid and                latestdate.maxdate = d.pricechangedate 	0
14141410	5615	how do i get the name of a user from its id (sql joins)	select u.firstname, u.lastname, m.firstname as regmanagerfirstname, m.lastname as regmanagerlastname, r.regiondesc as [desc], sum(ut.sales) as sales, sum(ut.hours) as hours from dbo.[usertime] as ut inner join dbo.[user] as u on ut.userrowid = u.userrowid inner join dbo.[region] as r on u.regionrowid = r.regionrowid inner join dbo.[user] as m on r.userrowid = m.userrowid where u.active = 1 group by u.firstname, u.lastname, m.firstname, m.lastname, r.regiondesc 	0
14141907	30444	sql select case and average	select week, avg(case when tenure > 20 then 20 else tenure end)  from table group by week order by week 	0.129186007468737
14142069	29497	selecting value from related table in mysql	select  a.*, b.* from    employer a         inner join `job` b             on a.employerid = b.employerid 	6.61123726301331e-05
14143678	24186	mysql join same table?	select fromid from <table> where toid = $member_number union select toid from <table> where fromid = $member_number 	0.0332534300312703
14144686	10657	filling in for missing latest data with last available data	select      m.month_end_date,     m.id,     m.market_cap,     case          when s.start_date is not null then s.start_date         else (select max(s2.start_date) from start_date_table s2 where s2.id = m.id)     end as start_date from market_cap_data m left join start_date_table s     on m.id = s.id     and m.month_end_date = s.month_end_date 	0
14146164	11812	finding the number of concurrent days two events happen over the course of time using a calendar table	select patid   ,min(overlap_date) as start_overlap   ,max(overlap_date) as end_overlap   from(select cte.*,(dateadd(day,row_number() over(partition by patid order by overlap_date),overlap_date)) as groupdate         from cte       )t   group by patid, groupdate 	0
14148878	20840	find all indexes in my database sql	select * from sys.indexes where name is not null 	0.0839537014389997
14149781	32503	php/mysql/pdo library - distributing information out of a database? what's the most efficient way?	select * from `table-name` order by `id` asc 	0.0100663034082279
14149882	34219	is there a way to get 2 rows from each group of rows?	select id, color from   tablename a where  (    select count(*)     from   tablename as f    where  f.color = a.color and f.id <= a.id ) <= 2; 	0
14150245	32420	group by week() malfunction for 2013	select      round(sum(sell_price), 2) as sell_price,      round(sum(buy_price/100*20), 2) as fees,      round(sum(buy_price), 2) as buy_price,      round(sum(sell_price/100*80 - buy_price), 2) as margin,      date_sub(from_unixtime(time), interval (dayofweek(from_unixtime(time)) - 1) day) as fdow      from order_items      group by fdow     order by fdow desc 	0.100634568799968
14151246	11302	adding time in sql server 2008	select     empid,     checktime,     checktype,     row_number() over(partition by empid, dateadd(dd,datediff(dd,0,cin.checktime),0), checktype order by checktime) as seq into     #preparedtable from     sourcetable select     cin.empid,     dateadd(dd,datediff(dd,0,cin.checktime),0) as checkdate,     (sum(datediff(ss,cin.checktime,cout.checktime)) / 3600.0) as hoursworked from     #preparedtable cin join     #preparedtable cout     on  (cin.empid = cout.empid)     and (datediff(dd,cin.checktime,cout.checktime) = 0)     and (cin.seq = cout.seq)     and (cin.checktype = 1)     and (cout.checktype = 2) 	0.460158353131835
14152713	13891	one is to many relationship, getting latest row	select a.phone, b.lead_sp_id, b.sp_id, b.act_time  from leadsptable a  inner join (select a.lead_sp_id, a.sp_id, a.act_time              from acttable a              inner join (select lead_sp_id, max(act_time) act_time                          from acttable group by lead_sp_id                       ) b on a.lead_sp_id = b.lead_sp_id and a.act_time = b.act_time              ) b on a.lead_sp_id = b.lead_sp_id and a.sp_id = b.sp_id 	4.95685466711656e-05
14153439	35855	display column names and add check boxes php mysql	select column_name  from information_schema.columns  where table_schema = 'dbname' and table_name = 'tablename' and          lower(data_type) = 'tinyint' 	5.77505349410923e-05
14154030	18837	how to retirve data with multiple join in my sql?	select * from user_ u inner join user_roles ur on (u.userid = ur.userid) inner join role_ r on (ur.roleid = r.roleid) inner join users_organization uo (u.userid = uo.userid) inner join organization_ o on (uo.organizationid= o.orgid) where uo.org_id =? and  r.role_name=? 	0.695555618395548
14154087	12216	return no row if max query return a null	select max(field) from yourtable having max(field) is not null 	0.00145131049636818
14155418	16966	oracle how to pivot my table	select cyname          , max(decode(ca_date, to_date('01-01-2013', 'dd-mm-yyyy'), ca_value, null)) as "01-01-2013"      , max(decode(ca_date, to_date('02-01-2013', 'dd-mm-yyyy'), ca_value, null)) as "02-01-2013"      , max(decode(ca_date, to_date('03-01-2013', 'dd-mm-yyyy'), ca_value, null)) as "03-01-2013"      , ... from my_table group by  cyname; 	0.561381685032566
14157480	32319	count occurrences of character in a string using mysql	select *   from table   where  length(name) - length(replace(name, 'a', '')) between 1 and 2 	0.0033477450352369
14158891	25757	sql multiplication query	select `daily_charge`,         datediff(end_date,start_date) as `total`,          datediff(end_date,start_date) * daily_charge as `done` from `car`,`contract` where `contract_id`='1'; 	0.677521484151625
14159792	11332	mysql select unique column where other column is max	select yourtable.* from yourtable where (serial_num, version) in (select serial_num, max(version)                                 from yourtable                                 group by serial_num) 	0.000487095846281469
14161541	36388	bringing max on sql join	select    regions.*, a.max_status from    regions join    (select id, max(status) as max_status     from auditoria where entidade_tipo = 'terceiro'     group by id) as a   on    regions.id = a.id order by regions.id 	0.384817506368213
14162138	23543	mysql: getting value from other table (left join?)	select      *  from eaters as e  left join foods as f on e.food_id = f.id group by f.id 	0.00197457408058258
14162348	5793	join table depending on value of column in main table	select * from notificationtable notification    left join commenttable comment on (notification.typeid = comment.id and notification.type == 'comment') left join eventable event on (notification.typeid = event.id and notification.type == 'accept') where notification.userid = 2 	4.58287377863662e-05
14163621	28942	how can i order by a date in string format properly?	select convert(varchar(10), create_date, 101) as 'date', count(*) as 'record count', from the_table group by convert(varchar(10), create_date, 101) order by min(create_date) desc 	0.33143209640678
14166078	27525	get rows and rows from one table sql server	select * from ls_comments c where c.itemid = 9 or       c.parentid in (select c2.commentid from ls_comments c2 where c2.itemid = 9) 	0
14166747	3636	fist time sql syntax. concatenate some string to each instance of a field in a table	select concat('https: 	0
14167854	5128	sql select join column alias	select m.[marriageid], peoplea.[personname] as aname, peopleb.[personname] as bname   from [marriages]  m join [people] peoplea on m.[personida] = peoplea.[personid]   join [people] peopleb on m.[personidb] = peopleb.[personid] 	0.597842295398376
14168244	34878	how do i get number of rows that a multi-table delete query will affect in mysql before deleting?	select * from parts p  left join binaries b on b.id = p.binaryid and b.procstat in (4, 6)  left join releasenfo rn on rn.binaryid = b.id  where rn.binaryid is null or (rn.binaryid is not null and rn.nfo is not null) or          b.dateadded < '2013-01-04 22:01:17' - interval 36 hour; delete p, b from parts p  left join binaries b on b.id = p.binaryid and b.procstat in (4, 6)  left join releasenfo rn on rn.binaryid = b.id  where rn.binaryid is null or (rn.binaryid is not null and rn.nfo is not null) or          b.dateadded < '2013-01-04 22:01:17' - interval 36 hour; 	0.000121860785448292
14168671	11004	stored procedure to check whether all year exist in table	select year from table where year between startyear and endyear. 	8.53503193858668e-05
14168800	13487	mysql query to get prescriptions statistics at end of year for store people	select p.creation_date, pr1.name1, pr2.name1, s.name, if(p.creation_date is null, 'yes', 'no') from (order_products op, stores s, products p1, products p2, orders o) left join prescriptions p on p.customer_id = o.customer_id and p.store_id = o.store_id where o.id = op.order_id and s.id = o.store_id and p1.id = op.right_product_id and p2.id = left_product_id 	0
14170820	12023	mysql distinct max column while joining two tables	select  a.*, b.* from    reward_webuid a         inner join rewards b             on a.item_id = b.item_id         inner join         (             select  aa.playerid, max(bb.reward_level) maxlevel             from    reward_webuid aa                     inner join rewards bb                         on aa.item_id = bb.item_id             where   aa.expired = 0             group   by aa.playerid         ) c on  a.playerid = c.playerid and                 b.reward_level = c.maxlevel and                 a.expired = 0 	0.00101443819291827
14171562	13976	compare two mysql tables to filter results	select      a.*,      b.*  from table1 a  join table2 b on a.contentrating = b.contentlimit 	0.00195956347540193
14172903	3738	find the max record in two tables	select answer.aid, answer.qid, answer.vote, answer.content    from answer    join (           select qid, max(vote) vote from answer           group by qid) as max_answer     on answer.qid = max_answer.qid and answer.vote = max_answer.vote    where answer.qid in (1,2)    group by answer.qid, answer.vote 	5.27983509649155e-05
14174478	28877	sql looping over data to find maximum value (special case)	select      *  from x_world as xr inner join (         select                  x,                 max(population)         from x_world as xr         group by x  ) as xt on xt.x = xr.x group by village 	0.00326462852238312
14174596	14496	mysql many-to-many join even if there is no relation	select * from students cross join quizzes left join _student_quiz on _student_quiz.student.id = students.student_id                        and _student_quiz.quiz.id = quizzes.quiz.id 	0.615032861756652
14175417	40135	what's the best way to perform count and percentage in sql server?	select gender, age, count(*) as cnt,        sum(case when agreed = 'agreed' then 1 else 0 end) as numagreed,        sum(case when agreed = 'notagreed' then 1 else 0 end) as notagreed,        avg(case when agreed = 'agreed' then 1.0 else 0 end) as numagreedratio,        avg(case when agreed = 'notagreed' then 1.0 else 0 end) as notagreedratio from mytable group by gender, age 	0.352501756010178
14175581	17478	joining votes between tables and getting a percentage	select     poster_id,     voter_id,     count(*) as votes,     count(*) * 100 / total.total_votes as percentage from table_1 join (     select poster_id, count(*) as total_votes     from table_1     join table_2 on table_1.post_id = table_2.post_id     group by poster_id ) total on total.poster_id = table_1.poster_id join table_2 on table_1.post_id = table_2.post_id group by poster_id, voter_id order by votes desc 	0.0009303113285107
14176148	13846	apply aggregate function on subset of rows	select avg(columnname) from (select top 10 columnname from tablename order by columnwhichholdsorder desc) a 	0.0804200700503198
14176259	4010	selecting multiple entries from two tables using join	select tr.video_id, v.title,    group_concat(distinct(a.title) separator ',') actors,   group_concat(distinct(d.title) separator ',') director,   group_concat(distinct(m.title) separator ',') music from term_relationships tr    inner join videos v on v.id = tr.video_id    left join actors a on tr.related_id = a.id and tr.type = 'actor'   left join musics m on tr.related_id = m.id and tr.type = 'music'    left join directors d on tr.related_id = d.id and tr.type = 'director'  where tr.video_id = 20  group by tr.video_id; 	0
14176337	33982	mysql only one message (the latest) per user in my inbox	select p.*, p.sender as sender, m.*       from `messages` p inner join (select sender,                     max(message_id) as last_message_id               from `messages`               where receiver='<current_user>' and delete2=0           group by `sender`) t2 on t2.sender = p.sender                                 and t2.last_message_id = p.message_id  left join members m on p.sender = m.member_id      where receiver='<current_user>' and delete2=0   order by p.date desc      limit 5 	5.36139132140676e-05
14176576	6850	ms access query sum up the values when certain columns match	select [shoot day], sum([total])  from table  group by [shoot day] 	0.000543666671971802
14176670	32554	select between two dates missing the last day	select * from  `table`  where timestamp between  '2012-11-30 00:00:00' and  '2012-12-07 23:59:59' 	0
14177698	9562	need sql query to obtain the following result	select a_no, max(b_type) as b_type from tablea a join tableb b on a.a_id = b.a_id group by a.a_no 	0.333565094989487
14179953	23140	need an sql query to map column value to column name	select  case selection             when 1 then c1             when 2 then c2             else c3         end val from    tablename 	0.0106142093161646
14180997	33441	select a value from mysql database only in case it exists only once	select * from `table` group by id having count(id) = 1 	6.90341321875398e-05
14181338	33939	sql - get the latest event from table	select  t_d.*, t_e.* from    dealer as t_d          inner join events as t_e             on t_d.id = t_e.did         inner join         (             select  did, max(date) maxdate             from    events             group by did         ) e on  t_e.did = e.did and                 t_e.date = e.maxdate 	0
14182221	8575	mysql left join and merge column	select * from (   select p.id, 0 x, p.message   from posts as p   left join post_replies as pr on p.id = pr.post_id   union all   select p.id, pr.id, pr.message   from posts as p   left join post_replies as pr on p.id = pr.post_id ) x order by 1, 2 	0.248864044135607
14182504	31294	invoice query per 2 weeks. the best practice	select * from user where registered > current_date() and  mod((floor( datediff( now( ) , `registered` ))),14) = 0 	0.000259217877023785
14182649	28634	mysql - how to sum counts by group	select agency.agency_name, count(ad.id) from agency left join agent on agent.agency_id = agency.id left join ad on ad.agent_id = agent.id group by agency.agency_name 	0.0494987799132644
14183817	1593	mysql: how to associate a column alias with a specific join clause	select table1.user_id, schools.value as school, languages.value as language from table1   left join table2 as schools on schools.user_id = table1.user_id     and schools.key = 'school' left join table2 as languages on languages.user_id = table1.user_id     and languages.key = 'language' 	0.565172436081651
14184601	20185	how can calculate the price for 5 days (hotel booking system)	select sum(case when dayname(thedate) = 'monday' then coalesce(r.monprice, def.monprice)                 when dayname(thedate) = 'tuesday' then coalesce(r.tueprice, def.tueprice)                 . . .                 when dayname(thedate) = 'sunday' then coalesce(r.sunprice, def.sunprice) as totalprice from (select strtodate('2013-08-01', '%y-%m-%d') as thedate union all       select strtodate('2013-08-02', '%y-%m-%d') union all       . . .        select strtodate('2013-08-11', '%y-%m-%d')      ) dates left outer join      rates r      on dates.thedate between r.date_to and r.date_from cross join      rates def      on def.season_price = 'default' 	0
14186720	34678	how to perform a sql count based on a foreign key	select housing.id, housing.capacity - count(person.id) from housing left outer join person on person.housingid = housing.id  group by housing.id, housing.capacity 	0.000113561735723553
14188080	16120	mysql php compare array of ids to table and return new array in order	select id from sometable where id in (youridlist) order by date; 	0
14189737	11838	mysql query to return all events and their photos	select event.*, group_concat(photo_thumbnail) as thumbnails from event  left join photo on event_id = photo_event  where event_user = ? group by event.event_id; 	0.000108868311838239
14190302	24046	show output in table	select t1.name, t1.price,     sum(t2.price) as running     from your_table t1 inner join your_table t2 on t1.name >= t2.name group by t1.name, t1.price order by t1.name 	0.0251098071510638
14191506	15617	how to join two tables	select     v.venueid,     v.venuename,     v.eventid,     e.eventname from     venuetable v inner join     eventtable e      on (v.eventid = e.eventid) union select     v.venueid,     v.venuename,     v.eventid,     e.eventname from     venuetable v inner join     eventtable e      on (v.venueid = e.venueid) 	0.0304643536326955
14194663	25380	finding avg value in sql query after sum - invalid use of group function	select name, avg (hsum) from (     select name,sum((number_hours)/8)*100 as hsum     from     t1     where name='person_a'     group by name,booked_date ) t 	0.57161797032919
14195520	18543	searching array element in database	select user_id from user_ports where opened_port = 80; 	0.0280448512930911
14196134	14402	mysql select on two values one column	select *   from tablename  where keywordid in (1, 12)  group by articleid  having count(*) = 2; 	0.00015656407421441
14196614	25417	join 2 tables with where that might not be present	select employees.eid, employees.fname, employees.lname, employee_reports.report from employees left join employee_reports on employees.eid = employee_reports.eid where  report_date = '2013-01-03' or report_date is null 	0.230761575262135
14197532	3216	how to filter only the date from a string stored in a varchar	select * from whatever where some_date like '02-jul-12%'; 	7.86424865149953e-05
14197560	19839	issue in making appear all database table field names	select columns.name   from sys.columns  where object_name(columns.object_id) = 'forma'  order by columns.column_id; 	0.00458264833991525
14197883	2376	how to get sum of two fields from databse	select agent_id, sum(amount + cheque)  from bill  where year(date) = year(curdate())  and month(date) = month(curdate())  group by agent_id 	0
14198223	31176	how to cast a boolean value to string by using birt	select myid,         myname,         case when myboolean = 1              then 'smart'              else 'sorry ...'          end from mytable 	0.0838476390710337
14200441	32481	subquery to return 1 result so results remain distinct	select a.id,    a.title,    a.section,    a.name,    l.user as createdby,    iif(isnull(l.time),          null, dateadd ( "s", l.time, #03/01/1980# )) as createdat from (    reports as a    left join (select id, min([time]) as mintime               from auditlog group by id) as t       on (a.id = t.id)    left join auditlog as l       on (t.id = l.id and t.mintime = l.time)  )  where a.active = 'y'; 	0.22775249228474
14201989	18937	how to group by week across year boundary in tsql	select  min(created) as 'first date', count(*) as 'count',  datediff(dd,'2012-01-02',created)/7 as week_number from items group by  datediff(dd,'2012-01-02',created)/7   order by min(created) 	0.000342551243163417
14203434	21979	mysql table join in php	select      zpc.ost_id, p.user_id, p.title, p.description, c.* from z_post_cat zpc inner join posts p on zpc.post_id = p.post_id  inner join calendar c on c.post_id = = p.post_id where zpc.cat_id = '1' 	0.265692727565743
14203821	35922	mysql: how to sum multiplied partials	select si.code, sum(si.quantity), sum(si.quantity * pl.price) as cash  from sold_items si  inner join price_list pl on pl.code = si.code and pl.size = si.size  group by si.code 	0.146328954977161
14203930	14170	is it possible to add all the others into a column in pivot of sql server	select *  from (  select  case when pet not in ('dog','cat') then 'others' else pet end pet,                  age         from pet.info) as b pivot (avg(age) for pet in ([dog],[cat],[others])) as c 	0.00054616304585958
14204186	7448	mysql select pairs of data	select d1.digit, d2.digit, s.score from digits d1 join      digits d2      on d1.group <= <groupnumber> and         d2.group <= <groupnumber> and         d1.digit < d2.digit left outer join      score s      on s.digit1 = d1.digit and         s.digit2 = d2.digit 	0.00368617636666852
14204807	1725	sql running multiple queries	select org.* from org join (select distinct salary from org order by salary desc limit(1,1)) org_salary   on org.salary = org_salary.salary 	0.548168403935838
14205948	7791	get names from different table in child-grandparent relationship	select  c.id as childid, cname.name as childname, p.id as parentid, pname.name as parentname, g.id as grandparentid, gname.name as grandparentname from category p inner join category c on (p.id = c.parent_id) left join category g on (p.parent_id = g.id) left join category_name cname on (c.id = cname.id and cname.language_id = 3) left join category_name pname on (p.id = pname.id and pname.language_id = 3) left join category_name gname on (g.id = gname.id and gname.language_id = 3) where p.parent_id is not null; 	0
14209049	26920	select column which is another table column value	select     geoname from hgeo h where     not exists (select * from flatgeo f       where       (h.levelname = 'value1' and f.value1 = h.geoname) or       (h.levelname = 'value2' and f.value2 = h.geoname)     ) 	0
14210539	9487	extract the missing row by comparing two table	select a.id_ab  from table_a a      left join table_b b on a.id_ab = b.id_ab  where b.id_ab is null 	6.12795078503329e-05
14210541	5286	mysql & pdo - select where user is null and user = :user	select * from tablename where user is null or user = :user 	0.109168033585813
14210630	18146	need to write query on two tables	select * from member join friend-requests on member.member_id=friend_requests.member_id where member.member_id=19 and not exists (select f.member_id from friend-requests f where f.mmeber_id = member.member_id) 	0.192159139063425
14211704	32821	select only months which have data for a specified year	select distinct month(dateraised) as 'month' from complaints where year(dateraised) = 2000 	0
14215999	22618	geting results from 2 database tables	select         wc.id,        wj.total from web_content as wc left join (           select                  object_id,                 count(object_id)   as total  ) as  wj on wc.id = wj.object_id order by wi.total desc 	0.00306540683993856
14216274	22843	sql server - restore database in different workgroup - fix windows users	select 'some appropriate text for this user' + name from dbo.sysusers where sid is not null 	0.730874451519403
14216358	39244	jasperreports club union result into a single row	select date, sum(amount)  from (first query union second query)  group by date  order by date 	0.0019899911765001
14216537	20397	select a number of records that are not present in another select resource	select * from questions where qid not in(select questionid from userquestions where userid = 90); 	0
14217243	31599	mysql query sum	select ifnull(fecha_alta, 'total') fecha_alta, id_vendedor, sum(lineaneto) lineaneto  from (select cp.fecha_alta, cp.id_vendedor, sum(precio * (100-cpd.bonif)/100*cpd.cantidad) as lineaneto       from crm_presupuestos cp       right join crm_presupuestosdetalles cpd on cp.id_presupuesto = cpd.id_presupuesto       group by cp.fecha_alta, cp.id_vendedor       having date(cp.fecha_alta)=curdate()) a  group by id_vendedor with rollup; 	0.344013761484802
14217461	3530	how to find parameters in oracle query received from v$sql?	select s.sql_id,         bc.position,         bc.value_string,         s.last_load_time,         bc.last_captured from v$sql s   left join v$sql_bind_capture bc           on bc.sql_id = s.sql_id          and bc.child_number = s.child_number where s.sql_text like 'delete from tablea where fk%'  order by s.sql_id, bc.position; 	0.0223329622254374
14217506	39672	mysql query for weighted voting - how to calculate with values assigned to different columns	select sum(score) as votes,name  from (select 1st_option as name, 3 as score from votes        union all        select 2nd_option as name, 2 as score from votes        union all        select 3rd_option as name, 1 as score from votes) as tbl  group by name; 	9.1837459259195e-05
14217751	9190	convert date to yyyymm format	select left(convert(varchar, getdate(),112),6) 	0.0337184727857001
14217889	15599	oracle date difference sql query	select trunc(sysdate) - purchaseddate    from table_name; 	0.107664318841578
14217944	8778	how how to calculate aggregate function sum on an alias column?	select a.question_id,         a.level,         count(a.question_id) as rank,         sum(select(rank)) as total  from   logs as a,         question as b  where  a.question_id = b.q_id         and a.level = '2'  group  by a.question_id  order  by rank desc 	0.174434599363846
14219319	8343	sql: don't show duplicates	select  mp.permitnumber,     mp.permitname,     max(mod.[createdon])as [createdon]   from    tblpermit mp   inner join dbo.[tblmodification] mod       on mod.permitid = mp.permitid   group by mp.permitnumber,     mp.permitname   order by 1 	0.0162897155480558
14219431	36727	sql counting distinct elements of overlapping sets	select count(column_alias) from ( select set1 as column_alias from table1  union  select set2 from table1 ) 	0.000167718441941104
14220306	27242	mysql - selecting from result	select row_index from (...) as alias where alias.user = 'john' and alias.score = 1400 	0.00611884757833631
14221465	22751	sqlite order of operations in a query	select akey, avalue, expensiveop(akey)  from (select * from atable where avalue < some_constant limit 99999999)  limit 99999999  select akey, avalue, expensiveop(akey) from (select * from atable where avalue < some_constant  union  select * from atable where 0 group by avalue)  select akey, avalue, expensiveop(akey) from (select * from atable where avalue < some_constant limit -1 offset 0) 	0.692822608516804
14222139	19275	mysql query - use results again in same query	select   a.* from keyword a join keyword b on (a.related_id = b.keyword_id) where (a.keyword like "%boston%"        or a.keyword like "%marathon%") and (b.keyword like "%boston%"        or b.keyword like "%marathon%") 	0.590144960722329
14222567	3659	select from 2 tables and order by 1	select id from articles a left join viewcount v on  a.id = v.article_id and v.date = 'some date here' order by v.numviews ,v.date desc 	0.00144649596330587
14222587	21703	java, counting average from database	select user.food_food_id, avg(user.rate) from user       inner join food on user.food_food_id = food.food_food_id group by user.food_food_id 	0.00163198291911498
14222795	22574	sql side by side query. matching routes	select a.orig, a.dest, a.stuff, b.orig, b.dest, b.stuff  from a inner join a as b on a.orig = b.dest and b.orig = a.dest where a.orig = 'atl'  order by a.orig, a.dest 	0.479553875348679
14223335	20572	set overlap percentage in sql	select t1.att1, t1.att2, t2.att2 as att2_other,         sum(case when t2.att3 = t1.att3 then 1.0 else 0 end)/count(distinct t1.att3) as cnt from table_name t1 join table_name t2   on t1.att1 = t2.att1 group by t1.att1, t1.att2, t2.att2 	0.0519105449397067
14227381	14560	mysql “unknown column” in subquery	select hi_proins0.proc_inst_id_  processid, act_re_procdef.name_ processname,        ifnull((select count(*) from act_hi_taskinst hi_task1                inner join act_hi_procinst hi_proins1 on hi_task1.proc_inst_id_ = hi_proins1.proc_inst_id_                where hi_proins1.proc_inst_id_ = hi_proins0.proc_inst_id_    and                       hi_task1.assignee_ != hi_proins1.start_user_id_ and hi_task1.assignee_ = hi_task0.assignee_                group by hi_task1.assignee_             ), 0 ) approvalnodecount, (    ... ) spendtime  from act_hi_taskinst hi_task0 left join act_hi_procinst hi_proins0 on hi_proins0.proc_inst_id_ = hi_task0.proc_inst_id_ inner join act_re_procdef on act_re_procdef.id_ = hi_proins0.proc_def_id_  group by hi_proins0.proc_inst_id_ 	0.681562269519281
14227619	552	php/mysql - showing newest distinct value from multiple columns	select * from (     select * from (          (select id, reciever, recieverid, message, datetime from messages where sender = '$user')        union           (select id, sender, senderid, message, datetime from messages where reciever = '$user')           ) as t        order by datetime desc     ) as t2 group by reciever order by datetime desc 	0
14228168	10679	distinct over several field but show all field sql server	select * from(     select         row_number() over (partition by [type], [div] order by [date] desc) rownum,         [date],          [no.po],          [product],          [type],          [div],          [price]      from table_name )x where rownum=1  order by [date] desc 	0.000169227187544082
14228717	25692	sql using a group by function for only one column (but selecting more than one column)	select po_number, po_quantity, shipped_wt, po_shipment_to, so_origin, so_product, supplier, po_quantity-shipped_wt unshipped      from (     select distinct po_number, po_quantity, po_shipment_to, so_origin, so_product, supplier,  sum(nvl(shipped_wt,0)) over (partition by po_number) as shipped_wt      from(     select distinct po_number,  po_tracking_no, po_quantity, shipped_wt, po_shipment_to, so_product, so_origin, supplier from vw_traffic_po_side))  where po_quantity > shipped_wt and sysdate > po_shipment_to 	0
14229291	16760	postgres rails select distinct with order	select * from (select distinct on (events.title) *       from events       order by events.title, events.copy_count desc) top_titles order by events.copy_count desc limit 99 	0.511017446893658
14229817	20762	mysql intersect query	select subjectid  from exam_subjects  where examid in (select examid from exams)  group by subjectid  having count(*) = (select count(examid) from exams); 	0.775415446542534
14230317	7843	subtract from one number dynamically	select id, num, (30000 - @sum:=@sum+num) as result from mytable, (select @sum:= 0) as a 	8.13590380972536e-05
14230648	3453	select data from the ends of a many-to-many relationship	select p.*        from posts p        join posts_tags pt         on pt.postid = p.id       join tags t         on t.id = pt.tagid      where t.tag='java'        and p.title like '%{class}%'; 	0.000804171264179625
14233871	31839	sql: get second largest value from a set of columns of a row	select t.id, t.val second_largest from (   select id, col1 val from my_table union all   select id, col2     from my_table union all   select id, col3     from my_table union all   select id, col4     from my_table union all   select id, coln     from my_table ) t where 1 = (   select count(*)    from (     select id, col1 val from my_table union     select id, col2     from my_table union     select id, col3     from my_table union     select id, col4     from my_table union     select id, coln     from my_table   ) u   where t.id = u.id   and t.val < u.val ) 	0
14233897	37390	equivalent of the query from sql server in mysql	select *,username as t from users 	0.464146646167496
14234748	5935	preserve rows order in select query as same in statement	select id from tbl where id in (2,3,1)  order by decode(id, 2, 1, 3, 2, 3) 	0.0201312007564498
14235930	33065	select from one table depending on second table without join	select  * ,       (         select  max(t2.id)         from    table2 t2         where   t2.id between t1.range_from and t1.range_to         ) as max_id_in_range from    table1 t1 	0
14236561	31466	getting mysql data from a taglist and a direct search	select a.* from tags   join taglinks on tagid=tags.id   join a on a.id=jokeid where tag="list" union select * from a where locate("list",description) 	0.00595301990434511
14237198	7489	select rows from table with date after today	select * from yourtable where   (year(curdate()) % 1000 < substring_index(date, '/', -1))   or   (year(curdate()) % 1000 = substring_index(date, '/', -1)    and month(curdate()) < substring_index(date, '/', 1)) 	0
14237492	20930	sql query to determine when threshold was reached	select top 1 t1.dateadded, t1.team from table1 t1  join table1 t2   on t1.team = t2.team     and t1.dateadded >= t2.dateadded group by t1.dateadded, t1.team having sum(t2.score) >= @threshold order by t1.dateadded 	0.180130770769854
14242330	28875	use a between statement as a group	select      left(week_id,4) as year,             sum (cur_charge_units) as "pro units" from        dw******.sls**** where       (week_id between '201201' and '201252')              or (week_id between '201101' and '201152') group by    left(week_id,4) 	0.438549495024316
14242787	32155	putting multiple mysql queries into one complicated one	select * from `threads` where `threads`.`threads_id` in (   select `threads_id` from `ktbridge` where `ktbridge`.`keywords_id` in (     select `keywords_id` from `keywords`        where `keywords`.`id` = 5 or `keywords`.`related_id` = 5     )   ); 	0.0116122584763538
14243808	139	how to retrieve values from mysql database from 3 tables?	select      u.name,     d.descone,      d.desctwo,      d.item from users as u left join items as i on i.name = u.name left join description as d on d.item = i.item where u.name = 'mary' 	0
14244029	32830	how to use a calculated column by another calculated column	select c.d as a, c.d + 2 as b from   (select 1+1 as d) c 	0.0010519904310355
14244097	27085	having trouble with joining tables in query	select * from  question q inner join answer a on q.questionid = a.questionid inner join option_table ot on ot.optionid = q.optionid inner join session s on s.sessionid = q.sessionid 	0.768223580289318
14245411	19808	returning just column names of resultset without actually performing the query (oracle and java)	select * from (     <your query here>   )   where 1=0 	0.020682379067865
14245671	26368	mysql not in from another column in the same table	select *  from films  where title not in (select collection from films where collection is not null); 	5.15179304070084e-05
14246261	19475	how to specify a dummy column in outer queries using mysql?	select id from tbl_a where fld_merchid in (   select distinct merchid   from tbl_b   inner join (     select name, max(priority) as priority     from tbl_b      where name like 'aaa.com'     group by name   ) mx on mx.name = tbl_b.name and mx.priority = tbl_b.priority ) 	0.649634447065241
14248855	34113	arranging join database results	select      social_posts.*,     users.*,     group_concat(social_tags.name) as tags,     count(social_likes.id) as likes,     count(social_responses.id) as answers from      social_posts          join users on social_posts.user_id = users.id         left join social_tags on social_tags.post_id = social_posts.id         left join social_likes on social_likes.post_id = social_posts.id         left join social_responses on social_responses.post_id = social_posts.id group by     social_posts.id 	0.359140086763291
14249204	15766	group strings together and calculate total python	select emailaddress, sum(number) as total from t group by emailaddress 	0.00300273605470505
14249947	31818	submit query to return multiple columns based off of the date?	select employeeid,      sum(         case             when strftime('%m', date) = '01'                 then invoiceamount             else 0         end) as 'jan',     sum(         case             when strftime('%m', date) = '02'                 then invoiceamount             else 0         end) as 'feb',     ...     sum(         case             when strftime('%m', date) = '12'                 then invoiceamount             else 0         end) as 'dec' from calls where date between '2013-01-01' and '2013-12-31' group by employeeid 	0
14252640	2442	mysql check if max value has duplicates	select  a.contest_id from    contest a         inner join         (           select contest_id, max(votes) totalvotes           from contest           group by contest_id         ) b on a.contest_id = b.contest_id and                a.votes = b.totalvotes group by a.contest_id having count(*) >= 2 	0.00140694390355968
14254597	5905	inner join three tables	select p.par_id, p.pat_name, p.pat_gender,     h.his_id, h.treated_by,     t.treat_id, t.treat_type, t.charges from patient p  inner join history h      on p.par_id = h.pat_id inner join treatment t     on h.his_id = t.his_id and p.par_id = h.pat_id 	0.523901095774074
14254822	34588	sql select column value where other column is max of group	select * from (    select      *,      row_number() over (partition by id order by value desc) as rn    from      unnamedtable ) t where    t.rn = 1 	0.000198650842469231
14255305	5599	select max date, then max time	select t_rate_id, t_inputdate, t_inputtime, t_sincedate from    (select         *, row_number() over (partition by t_sincedate order by t_inputdate desc, t_inputtime desc) rn      from yourtable      where t_sincedate<= sysdate) t where rn = 1 	0.0015458054709582
14255881	26976	accessing second row in result	select * from (     select dept_id, count(*) as stud_count, row_number() over (order by count(*) desc) row_num     from tbl_student_department_593932                group by dept_id ) where row_num = 2; 	0.000701243895920615
14257439	12160	how to split the data based on row and rank in sql server 2005?	select   rank = (select count(*) from mytable where rank<=a.rank and rec_type = 'ph')  ,   a.rank ranknum,   a.rec_type,   a.rec,   a.load_dt from   mytable a 	5.05121226771574e-05
14257540	13696	combine two queries	select * from   forums parent join forums child on parent.forum_id = child.parent_id where  parent.id = ? or child.id = ? 	0.0280405764943191
14258920	41223	sql matching columns between rows	select   cr.id,   cr.name,   folder.name as foldername from   cr   inner join vm on cr.id = vm.objectid   inner join vm as vmloc on vm.location = vmloc.objectid   inner join folder on folder.id = vmloc.objectid 	0.00028571598880129
14260914	32405	find a stored procedure name with its content in sql server 2000	select * from sysobjects where id in  (select id from syscomments where text like '%exec%') order by [name] 	0.071190593531194
14261253	6192	intersect two nested arrays	select count(*)    into   l_cnt    from        (          select *           from   table(v_a)        intersect           select *           from   table(v_b)       ); 	0.375041224048071
14261312	19605	sql in clause by giving just start and end numbers only	select * from abc where my_id between 3 and 8 	0.0245803415539712
14261406	30228	sql pivot to display users questionnaire responses?	select  su.id,         max(case when rp.questionid = 1 then rp.answerid else null end) question1,         max(case when rp.questionid = 2 then rp.answerid else null end) question2 from    siteuser su         inner join response rp              on su.id = rp.siteuserid         inner join answer an              on rp.answerid = an.id group by su.id 	0.0424959717387198
14262367	20375	query 3 tables one table has 3 rows i need to combine into 1 in some joint way	select t1.rid, t1.allotherdata, t2.description,        max(case when t3.item = 1 then t3.code end) as item1code,        max(case when t3.item = 2 then t3.code end) as item2code,        max(case when t3.item = 3 then t3.code end) as item3code from table1 t1 join      table2 t2 on       t1.rid = t2.rid join      table3 t3 on      t1.rid = t3.rid group by t1.rid, t1.allotherdata, t2.description 	0
14264887	32047	mysql: subqueries for normalized databases	select i.item_id, i.item_name, v.vendor_id, v.vendor_name < from item_data as i inner join vendor_data as v on i.vendor_id = v.vendor.id where i.item_id = ?  < 	0.403509725458305
14265659	27975	sql 'where statement' without joining	select name, something from table1 t1 join table2 t2 on t1.t1_id = t2.fk_t1_id join table3 t3 on t2.t2_id = t3.fk_t2_id where t3.blah = 'somestring' 	0.653432209915218
14268634	9800	php or mysql not recognizing value	select count(*) from current_season_games 	0.456712871220942
14272402	29843	using sum and max together in sql script	select sum(case when t.parameter_value = q.max_parameter_value then t.parameter_value end),         sum(case when t.parameter_value = q.min_parameter_value then t.parameter_value end),        sum(case when t.parameter_value = q.max_parameter_value then t.parameter_value end) -         sum(case when t.parameter_value = q.min_parameter_value then t.parameter_value end) as substract from tcs.parameter_values_archieve t inner join  (select meter_id, max(case when created_date <= '2013-01-01 20:00:00' then parameter_value end) as max_parameter_value,                     min(case when created_date >= '2013-01-01 08:00:00' then parameter_value end) as min_parameter_value    from  parameter_values_archieve   where created_date like '2013-01-01%' and meter_id between 1 and 16 and parameter_id = 1   group by meter_id) q on t.meter_id = q.meter_id 	0.347791212005551
14272525	30378	mysql where in query	select * from likes where (like_postid, like_type) in ((1,'status'),(2,'image'),(5,'status')); 	0.640805797913921
14274595	24763	extracting and averaging instintanous values in temporal db in postgresql	select     extract(hour from t1.dt) as hour,     t1.dt as t1, t0.dt as t0,     round(((t0.ambtemp + t1.ambtemp) / 2)::numeric, 2) as average from     n25 t0     inner join     n25 t1 on         date_trunc('minute', t0.dt + interval '1 hour - 2 minutes')         = date_trunc('minute', t1.dt) where extract(minute from t1.dt) = 41 order by t1.dt 	0.00392814765583608
14275259	2593	mysql query join to select unmatched rows from two tables	select users.*  from   users         left join users_approval b           on users.username = b.username and              b.approved_id = "3b888f52-50bc-11e2-b08b-99e5b2caddf7" where  users.role_type = "student" and        b.approved_id is null 	0.000767834808957118
14277087	33333	query in ms access for pulling data by giving parameters for current date	select t1.[ticket number], t1.[time received],     t1.[time read], t1.[time replied],     t1.[replied by], t1.[called customer?],     t1.[call duration], t1.[email duration], t1.[general issue]  from t1  where [ddate]=date() 	0.063170532048904
14279256	1120	sql dump of data based on selection criteria	select col1 ,col2  into clonetable  from mytable  where col3 = @condition 	0.0028677069026843
14280063	28033	combing two queries while using group by	select cid, crid,  sum(case when eventtype='0' or eventtype='0p' or eventtype='n' or eventtype = 'np' then 1 else 0 end) as count_1, sum(case when eventtype='c' then 1 else 0 end) as count_2 from data where eventtype in ('0','0p','n','np','c') group by crid; 	0.317866320331707
14281224	19332	having clause that filters out by max date	select r.region_id, count(*) as numareas, sum(cnt) as numreviews from (select r.region_id, r.area_id, count(*) as cnt,              max(date_finished)as maxdf       from review r       group by r.region_id, r.area_id      )  r where datediff(day, maxdf, getdate()) > 365 group by r.region_id 	0.121212969549679
14282196	22884	condition on a timestamp column to select data for a year	select *  from project  where extract(year from project_reg) = 2013 	7.07867305700314e-05
14282558	38754	min and max by id over group and other condition	select id, active, min(timestamp), max(timestamp) from (select t.*,              (select min(timestamp) from t t2 where t2.id = t.id and t2.timestamp > t.timestamp and t2.active <> t.active              ) groupname       from t      ) t group by id, groupname, active 	0.00158813882515198
14282718	23018	how to select only 1 row per unique field (with another field determining which in case of duplicates)	select  a.* from    tablename a         inner join         (             select  elem_id, max(`draft`) maxdraft             from tablename             group by elem_id         ) b on a.elem_id = b.elem_id and                 a.`draft` = b.maxdraft 	0
14283083	2444	database design: best way to store multiple options with multiple selects	select c.car_id from `car` c     inner join `car_selected_options` as o on c.car_id = o.car_id where     (o.key = 'exterior_color' and o.value = 10) or    (o.key = 'electronics' and o.value = 100) or    (o.key = 'electronics' and o.value = 101) or group by c.car_id having count(*) = 3; 	0.258672071518468
14283480	9177	selecting single xml from multiple xmls rows in a table	select xmldata as '*'  from activitytable  for xml path(''), root('rootnode') 	0
14283875	21121	selecting value once with multiple entries mysql and php	select distinct form.*, form_register.* from forms     inner join form_register on form_regiseter.form_id = form.id     where form_register.userid = '$userid' 	0
14284387	17484	php query for 2 fields from 1 table	select `e` from `furcodes` where `b` = '$redeem_code' 	0.00120551138418469
14284464	19368	getting the the number of blogs with more than x subscribers	select id, title, count(*) as subs_count   from `blogs`, `subscribers`   where `blogs`.`id` = `subscribers`.`blog_id` group by `blog_id` having count(*) >= 2 order by subs_count desc; 	9.25900195203835e-05
14284709	22865	easier way to map record names for a column?	select sum(count) as actions,          (case event              when 1 then 'web'              when 2 then 'ios'              when 3 then 'android'             when 4 then 'windows'              when 5 then 'mac'          else 'unknown' end )  as platform from metrics_weekly where event in (1, 2, 3, 4 ,5 ,6)  group by event 	0.00197820778705344
14284866	17517	ms sql - average rows with specific columns	select avg(minutestoloadoverlast10days),environment, server,exchange  from your_table_name group by environment, server,exchange 	0.000227724792738021
14285998	9808	selecting last rows of mysql table with php	select * from (select * from table_name order by id desc limit 10) t order by id 	0
14286095	27466	recursive select with conditions	select (sum(aux.price * aux.quantity) / sum(aux.quantity))     from (select    inp.price, inp.quantity, prd.product, drk.drink_num, inv.add_date                         from    invoices                                inv             inner join invoice_products inp on inp.invoice = inv.invoice             inner join products                 prd on prd.product = inp.product             inner join drinks                       drk on drk.product = prd.product) aux,     date_period dtp     where              aux.add_date between dtp.starting_date and dtp.ending_date             and aux.drink_num = 1836              and dtp.year <= 2012      group by             dtp.year,             dtp.period     order by              dtp.year desc,             dtp.period desc     limit 1 	0.715141237442031
14286463	8490	minimal number of checks in case statement to be valid over multiple column range	select id,   (      case when partial >= 2 then partial else 0 end +     case when full >= 2 then full else 0 end   ) counts from foo 	0.00464874684697016
14287011	30714	grouping by month in sql	select month(date) as "month" from dw******.sl**** group by month(date) order by month(date) 	0.0153006001738443
14287100	27290	mysql select rows with same fk but different values in other row	select * from my_table natural join (   select id from my_table group by id having count(distinct exchange) > 1 ) t 	0
14287188	23622	comparing similar columns for equality	select itemid from   itemdata group by        itemid having count(distinct retail)>1 	0.0269335728373969
14287609	2188	combine records from differing tables using join and union	select names.name, drink.wine, drink.soda, food.dinner, food.dessert, food.fruit from     (select name from food where status = 'active'     union     select name from drink where status = 'active') names left join drink on drink.name = names.name left join food on food.name = names.name 	0.00282234687740042
14290939	22056	text matching in sql query (like)	select * from   table  where soundex(name) like soundex('bhovali') ; 	0.519465383180081
14291276	6952	my sql query for selecting specified data from table	select * from tbl_name limit $i,15 	0.00669465120453762
14291468	3724	select the items in nested set	select id,name from items where cat_id in ( select cat_id from category as node,     category as parent where node.lft between parent.lft and parent.rgt     and parent.name = 'a') 	0.0300446069363178
14292497	41301	fetch only last entries using criteria(hibernate)	select i.issue_id, i.issue_description,        it.tracker_status, it.tracked_time from issues i  left join ( select it.issue_id, it.tracker_status, it.tracked_time              from issue_tracker it              inner join (select issue_id, max(tracked_time) tracked_time                          from issue_tracker group by issue_id                        ) a on it.issue_id = a.issue_id and it.tracked_time = a.tracked_time            ) it on i.issue_id = it.issue_id  where i.status = "escalate to"; 	0
14292778	7845	sql - get highest rated movie by genre	select  * from    movie m join    genre g on      g.movieid = m.movieid join    (         select  r.mid         ,       sum(rating) as sumrating         from    rating r         group by                 r.mid         ) r on      r.mid = m.movieid join    (         select  g.id as gid         ,       max(sumrating) as maxgenrerating         from    (                 select  r.mid                 ,       sum(rating) as sumrating                 from    rating r                 group by                         r.mid                 ) r         join    genre g         on      g.movieid = r.mid         group by                 g.id         ) filter on      filter.gid = g.id         and filter.maxgenrerating = r.sumrating 	0.00137644775532437
14293380	35668	postgresql, query two (or more) tables without using a secondary key	select t1.pk1,         t1.pk2,         t1.string1,         t1.string2,         t1.string3,         t2.string4,         t2.string5,         t2.string6 from table1 t1   join table2 t2 on t1.pk2 = t2.pk3 where t1.string1 ilike 'a%' 	0.0167063232354514
14293650	3109	mysql group by multiple colums and fields	select least(userid, friendid) as x,         greatest(userid, friendid) as y from   tablename group  by x, y 	0.0223074883939053
14294003	40583	sum top 5 values in mysql	select driver, sum(`position`) from (select driver, race, season, `position`,               if(@lastdriver=(@lastdriver:=driver), @auto:=@auto+1, @auto:=1) indx        from results, (select @lastdriver:=0, @auto:=1) a        order by driver, `position`) as a   where indx <= 5  group by driver ; 	0.00232511721772648
14294088	14122	two different groupping in one sql statement	select p.id, p.name, sum(if(curdate() = pv.date, pv.count, 0)) todaycnt,         sum(pv.count) allcnt from place p  inner join place_visit pv on p.id = pv.place_id  group by p.id; 	0.00817169073048117
14294288	23742	hsqlsb - select a random row from a db	select p.name as foo from playlist p order by rand() limit 1 	0.000623786751187561
14294570	28812	select multiple rows as one in mysql table	select  max(rbr) maxrbr,         id, date,         max(pr1) maxpr1,         max(pr2) maxpr2,         .... from tablename group by id, date 	0.000674743025206001
14294921	3652	how to list all constraints of 2 tables at the same time?	select constraint_name, constraint_type from user_constraints where table_name in ('tblorder', 'tblproduct','tblcustomer'); 	0
14296169	1211	sql server 2008 how to select top [column value] and random record?	select a.name, a.link_id from( select name,link_id, row_number()over(partition by link_id order by newid()) rn from dbo.tbla ) as a join dbo.tblb as b on a.link_id = b.link_id where a.rn <= b.number; 	0.000176745274158831
14296947	11350	is it possible to ignore column when using "match"?	select * from docs where docs match 'col1:linux or col2:linux or ...' 	0.354966048030571
14298846	37169	rank functions in sql	select date_visit, rank() over (partition by member_id order by date_visit) -1  as rank from ranks 	0.735133579512945
14299003	719	setting a household name field based on records in the household	select    e1.householdid,   case when p2.lastname =  p1.lastname then  p1.firstname + ' & ' + p2.firstname + ' ' + p2.lastname        else p1.firstname + ' ' + p1.lastname + ' & ' + p2.firstname + ' ' + p2.lastname end as householdname,   p1.firstname,   p1.lastname,   p2.firstname as p2firstname,   p2.lastname as p2lastname from   person p1   inner join entity e1 on     p1.id = e1.pid  left join entity e2     on e1.householdid = e2.householdid and e1.id < e2.id  left join person p2    on e2.pid = p2.id where e2.id is not null   and not exists      ( select * from entity e3        where e1.householdid = e3.householdid       and not e3.id in (e1.id, isnull(e2.id, 0))     ) 	0.00015936367390187
14303603	16084	select values from table which not match predefined	select id from table where id in (1, 10, 15, 17, 20) 	0.000434482052648673
14310219	29140	sql multiple joins to same table both inclusive and exclusive	select f.name  from foo f  inner join foo_bar_xref fb_1    on fb_1.foo_id = f.id and fb_1.bar_id = 1  left outer join foo_bar_xref fb_2    on fb_2.foo_id = f.id    and fb_2.bar_id = 2 where fb_2.bar_id is null group by f.name 	0.0111971547584032
14314471	26715	mysql get rank with filters	select student_id, numbers, if(@marks=(@marks:=numbers), @auto, @auto:=@auto+1) rank  from (select student_id, branch_id, class_id, sum(numbers) numbers       from quiz_user        group by student_id        order by numbers desc, student_id       ) as a, (select @auto:=0, @marks:=0) as b where branch_id = 5 and class_id = 1; 	0.0813646507188886
14315261	5942	mysql query rand() and order by	select * from (     select `location`, `route`     from `foo`     where `location` != ''     order by rand()     limit 8) as `temp` order by `location` asc; 	0.649413173797159
14316241	21287	mysql select random rows with order by	select * from (     select category from orders order by rand() asc  limit 10 ) as innerresult  order by innerresult.category 	0.0166121104013349
14316547	26569	average aggregation on temporal db based on measurment with 10-minute intervals in postgresql	select dt, average_temp from (     select         date_trunc('hour', ddate_ttime + interval '10 minutes') dt,         avg(ambtemp) over(             partition by date_trunc('hour', ddate_ttime + interval '10 minutes')         ) average_temp     from sample     where extract(minute from ddate_ttime) in (51, 01, 11, 21, 31, 41) ) s group by 1, 2 order by dt 	0.000177792554820074
14317443	19382	sql for following scenario	select p.person_id, max(e.entry_date) as maxentrydate from   person p   inner join entry e    on p.person_nic = e.entryid where p.state = 'nonactive'    and entry_date  between 20130101 and 20130131 group by p.person_id 	0.795137333054033
14317612	25100	how to group result in the same line : many to many relationship by using mysql	select  product.product_name, group_concat(provider.provider_name separator '/')  from  product, provider, provider_product  where product.id_product = provider_product.ref_product  and provider.id_provider = provider_product.ref_provider  group by product.product_name 	0.00114311986053375
14318950	36063	select rows from a database table with common field in sqlite	select  * from    table1 t1 join    table1 rob on      rob.firstname = 'rob'         and t1.lastname = rob.lastname join    table1 ben on      ben.firstname = 'ben'         and t1.lastname = ben.lastname where   t1.firstname in ('ben', 'rob') 	0
14322422	30301	select from every two rows in mysql, using different columns for matching	select * from channels where id in (   select min(id)   from channels   group by least(channel, bridged), greatest(channel, bridged)) 	0
14325050	15990	liquibase precondition for unique constraint	select    case when exists(     select username, count(*)     from person     group by username     having count(*) > 1 )     then 1     else 0   end 	0.0544179696685101
14325339	4305	mysql trying to get a count with a one to many tables	select count(id) from (   select p.id   from     `products` p inner join `product_attributes` as pa     on p.id = pa.product_id   where (pa.attribute='min' and pa.value>=5) or         (pa.attribute='max' and pa.value<=5)   group by p.id   having count(*)=2 ) s 	0.000542641961617784
14325955	1535	can i calculate datetime range in mysql	select ... and last_time >= (now() - interval $timeout sec) 	0.00351108917518191
14326909	28984	first start_time and last end_time from 7 sql rows to show only 1 sql result	select    concat(min(start_time), ' - ', max(end_time)),    uid,    submitid,    submitstatus,    submitdate,    submitapprover from    $times_table where    submitstatus=1  group by   uid,    submitid,    submitstatus,    submitdate,    submitapprover order by    submitid 	0
14326949	30345	mysql selecting (n) rows of each occurrance	select * from (     select sid,          state,          votes,         @prev := @curr,         @curr := state,         @rank := if(@prev = @curr, @rank+1, 1) as rank     from     (       select t1.sid, state, votes       from table1 t1       inner join table2 t2           on t1.sid=t2.sid     ) src, (select @curr := null, @prev := null, @rank := 1) r     order by state, votes desc ) src where rank <= 2 order by state, votes; 	0
14328506	8640	combine to output value ina query	select  count(h.dept_id) as deptcount, i.id as companyid, i.account as accounttotal, i.technology as it, coalesce(it.finance,'nocapacity') as school, max(it.finance) as high,  (avg(it.finance) + min(it.finance))/2 as average from institution i left join  history h on h.institution_id = i.id left join     xxxxx     yyyyy  group by i.id, i.account 	0.0526854465520276
14329526	21146	counting conditional matches in sql	select  count(*) matchcount,a.* from    person a         inner join person b             on  (a.firstname = b.firstname and                     a.lastname = b.lastname) or                     a.ssn = b.ssn group by firstname, lastname, ssn, recordid order by recordid 	0.231912073916332
14330838	10589	sql functions to match last two parts of a url	select reverse(split_part(reverse(data), '.', 2)) || '.'     || reverse(split_part(reverse(data), '.', 1)) from example; 	0.000258010185128261
14330996	4085	how to connect mysql date type with php date type using a loop	select * from events where extract(month from date) = month(now())  and extract(day from date) = day(now()) 	0.0590044014996919
14334320	27382	order mysql result set by number of matches in like clause	select            * from     ( select *,                  case                          when caption like 'hello%' or text like '%hello'                          then 1                          when caption like 'jame%' or text like 'jame%'                          then 2                                                   else 0                  end as weight          from    your_table          )          q where    q.weight > 0 order by q.weight 	0.044769994092052
14334761	25243	getting first 10 data after rearranging	select  * from    (         select  *         from    comment         order by                 comment_date desc         ) where   rownum <= 10 	0.000433464150973858
14335863	12443	how to select the first row from a query into a procedure-variable in mysql	select id    into topscorer    from game_player  where game_player.score = (   select max(score) as maxscore                                   from game_player                                   ) limit 1 	0
14337514	2077	mysql count to return zero if no match	select  t.id, count(sa.assignment_id) from    tutor t left join         student_assignement sa on      sa.assignment_tutor_fk = t.id where   t.id in (1, 2, ..., 9002) group by         t.id 	0.00502083956430676
14338401	39776	use select as value for join	select *      from propertycategory      join          (select itempropertyvalue.idproperty as propertyid              where itempropertyvalue.iditem = '10') as t         on propertycategory.idproperty = t.propertyid 	0.261409151628174
14339369	41028	how to generate a list of number in sql as it was a list of comprehension?	select row_num from sa_rowgenerator( 1, 100 ) 	7.94538786799851e-05
14340156	22567	finding items with a set containing all elements of a given set with jpql	select i from item i join i.tags t where t in :tags group by i.id having count(i.id) = :tagcount 	0
14341080	40236	date range report - aggregation	select p.product_category, c.date,         coalesce(sum(high_priority), 0) as high_priority,        coalesce(sum(med_priority), 0) as med_priority,        coalesce(sum(low_priority), 0) as low_priority from product p cross join      calendar c left outer join      product_defects pd      on pd.product_id = p.product_id and         pd.date = c.date group by p.product_category, c.date order by 2, 1 	0.0241106419742556
14341479	33189	meet both where criteria - t-sql	select * from table where (location <> 'all locations' or role = 'manager') 	0.096013163798088
14342026	38778	how to count the number of people who choose a particular location?	select l.locations, l.telephone, l.address, count (u.userid) as `location_count` from location as l left outer join users as u on l.locations = u.location_chosen group by l.locations order by `location_count` desc 	0
14347152	25658	mysql php commenting system: new database or looping through ids?	select * from images where id=192 	0.0403945780104577
14348095	40390	php - i don't want to use table with loops anymore	select p.* from table_products p  left join table_sales_dt dt on p.id = dt.product_id left join table_sales s on dt.sa_dt_coupon = s.sa_coupon where s.sa_month = 9 	0.522645629595119
14348431	26459	ok to use temp tables and table variable in the same stored procedure?	select into 	0.120050824631198
14348576	19872	mysql using * along with column names from joined tables	select table1.*, table2.column, table2.column from table1 left join table2 on table2.a = table1.a where ... 	0
14349495	7452	how to get mysql results listed in different rows by a date range?	select    billing.a_name,    billing.finaltotal,    billing_dates.paidtotal,   (billing.finaltotal - billing_dates.paidtotal) as total,    billing.timeperiod from    (select        a_name,        login_username,        sum(custotal) as finaltotal,       case          when invoicedate > date_sub(curdate(),interval 30 day) then '30'         when invoicedate > date_sub(curdate(),interval 60 day) then '60'         when invoicedate > date_sub(curdate(),interval 90 day) then '90'         else '90+'       end as timeperiod     from billing      where curdate() >= invoicedate        and cast(20120601 as datetime) <= invoicedate      group by login_username) billing   left join     (select        username,        sum(amount) as paidtotal      from billing_dates     group by username) billing_dates     on (billing.a_name = billing_dates.username)  order by a_name asc; 	0
14352534	23628	dynamic get rank by mysql query	select student_id, numbers, if(@marks=(@marks:=numbers), @auto, @auto:=@auto+1) rank  from (select student_id, sum(numbers) numbers       from quiz_user        group by student_id        order by numbers desc, student_id       ) as a, (select @auto:=0, @marks:=0) as b; 	0.20196734131739
14352898	10343	how to find the duplicate number entry in one column of the table?	select     id,     sum(amount) as amount,     count(*)    as count from mytable group by id having count(*) > 1 	0
14353173	24040	mysql query: select group_id but if any client_id in said group is = x then don't select	select g.group_id from groupp g  join membership m on m.group_id=g.group_id and m.status=1 join client c on c.client_id=m.client_id and c.status=1 where g.group_id not in (select mm.group_id from membership mm join client cc on mm.client_id=cc.client_id and cc.industry_id = $client_industry_id) and g.status=1 and g.geography_id=$target_geography and g.target_market_id=$target_market; 	0.00590354011773428
14353719	15076	mysql - returning rows between two dates/times	select * from births where date between '2013-01-15' and '2013-01-17'  and concat(date, ' ', time) between '2013-01-15 12:00:00' and '2013-01-17 17:00:00'  ; 	0.00333001417749776
14353831	40689	sql statement for group count and overall count	select student, own_80_cnt,        sum(own_80_cnt) over () total_80_cnt   from (select student,                sum(case when score = 80 then 1 else 0 end) as own_80_cnt           from mytable          group by student); 	0.401999150598487
14355149	33713	how to remove duplicate records with different columns in oracle?	select   distinct least(p1, p2), greatest(p1, p2)   from   (select   'a' as p1, 'b' as p2 from dual           union           select   'b' as p1, 'a' as p2 from dual) a; 	0
14355602	25779	mysql query match exact string or number	select  * from    tablename where   user_id like '6,%' or user_id like '%,6' or user_id like '%,6,%' 	0.0199106676699599
14356432	12524	format datetime to month - year then order desc	select      archivetravelnewsbymonth,      newsdateposted from(     select distinct top 12 substring(convert(varchar(11), newsdateposted, 113), 4, 8) as archivetravelnewsbymonth,         newsdateposted     from dbo.at_news)x order by convert(datetime, archivetravelnewsbymonth) 	0.00018606840614026
14356583	921	sql - outer join one table onto two others	select * from order_header inner join order_line on order_header.header_id = order_line.header_id left outer join inventory on order_line.product = inventory.product and order_header.location = inventory.location where order_header.header_id = xxx 	0.055422323674395
14357126	28300	get count from using multiple tables in hibernate?	select   course.name, count(*) from     classtable     join timetable on timetable.sid = classtable.timetableid     join skillset  on  skillset.sid = timetable.skillsetid     join course    on    course.sid = skillset.courseid group by course.sid 	0.0103787337217161
14357851	31268	how to select result from main query into subquery	select     cat_id,     category_name,     seo_name,     (         select count(category_name)         from ccs_coupons c2          where c2.category_name like concat('%', c1.category_name, '%')            or c2.website_name like concat('%', c1.category_name, '%')            or c2.description like concat('%', c1.category_name, '%')            or c2.url_desc like concat('%', c1.category_name, '%')     )  anyalias  from  `ccs_coupons` c1  where  category_name like 'a%' group by category_name order by category_name asc limit $page,$config 	0.0378079775204468
14360348	1511	the total no. of true rows after refreshing by year	select count(customer_column)  from   table2  where  datepart(mm, record_column) = @mymonthselected  and    datepart(yy, record_column) = @myyearselected and bitcolumn = 1 	0
14361290	18628	sql queries and results	select .... , 'writer' as type union all select .... , 'producer' as type 	0.380286464642189
14361642	18754	using rank vs max (t-sql)	select  distinct customer,         x.cl1 as tab,         x2.cl2 as tb from   (select  customer,                 rank() over (partition by customer order by cl1 desc) rk1,                  cl1         from    tablea) x join   (select  customer,                          rank() over (partition by customer order by cl2 desc) rk2,                  cl2         from    tablea) x2         on  x.customer = x2.customer where   x.rk1 = 1  and     x2.rk2 = 1 	0.747050814507521
14362767	40646	how do i limit one input to one output when there are two outputs for the one input? database	select tr.local_id, tr.fall_score, avg(tr.percentages) as avgofpercentages from tablename as tr group by tr.local_id, tr.fall_score; 	0
14363440	34942	not getting results when row count on another table is 0	select username, p.post_id, category_id, unix_timestamp(p.datetime) as datetime,    p.body, p.owner_id, count(comment_id) as number from posts p left join comments c on p.post_id = c.post_id left join user u on p.owner_id = u.`id` group by c.post_id order by number desc 	0.00135343096208095
14365662	39826	sql reorganize table for ssrs display	select l.location, max(case when l.staffid = 1 then l.location else null end) as 'john', max(case when l.staffid = 2 then l.location else null end) as 'mark' from location l group by l.location 	0.0152968562294196
14367422	9500	output parameter gives different result in sql server 2005	select @productid 	0.79045226610132
14368530	12976	how to select top records in multiple columns in microsoft access or sql?	select * from table_name where column_x in (     select top 100 column_x     from table_name      order by column_x ) and column_y in (     select top 100 column_y     from table_name     order by column_y ); 	0.0096896599202375
14371264	20198	php mysql combine cells from different row with same value	select  max(pk),          id,         `last`,          `first`,         group_concat(teacher separator ' & ') teachers from    tablename group by `last`, `first`, `period` 	0
14371778	6002	oracle: insert select from 2 views and value from param	select yr, qtr, user_code, "1_mo_pct" mo1_pct, "2_mo_pct" mo2_pct, "3_mo_pct" mo3_pct , case when "1_mo_pct" >= 85 and "2_mo_pct" >= 85 and "2_mo_pct" >= 85 then 7000 end inc, user updated_by, sysdate  updated_on from ( select m1.yr, m1.mo, m1.qtr, m1.user_code, m1.mo_perf, m2.qtr_perf from myview1 m1 join myview2 m2 on m1.yr=m2.yr  and m1.qtr = m2.qtr and m1.user_code = m2.user_code )t pivot(   max(mo_perf) mo_pct  for mo in (1,2,3)   ) 	0.000338355008221926
14371896	28518	how to insert new data while keeping most columns value but changing some values dynamically?	select *  into #newtable  from tablea; update #newtable  set termid = 'pp3',      outlet= 'p6-p8',      snum = case                 when snum = 'p5' then 'p8'                when snum = 'p4' then 'p7'                when snum = 'p3' then 'p6'            end; insert into tablea  select *  from #newtable 	0
14372140	38608	selecting column value dependent on parent id without need for php loop?	select p.id      , p.title      , pp.id      , pp.title parentitle   from pages p   left  outer   join pages pp     on p.parent = pp.id 	0.000133767986170399
14372523	14776	concat sql result	select r.r_name, sum(ug.occupants) / r.pax as percentageofroomoccupied from rooms r left join usergroups ug on r.id = ug.r_id where r.b_id = 1 group by r.r_name, r.pax 	0.437180663987394
14373482	2344	database structure for general and specific data	select users.user_name   from users u, "user book loans" ubl, "book copies" bk, books b  where 1 = 1    and b.book_name = "moby dick"    and b.book_id = bk.book_id    and bk.book_copy_id = ubl.book_copy_id    and ubl.user_id = u.user_id 	0.0482379030968821
14373586	1126	adding a new row that depends on a rows data at select command?	select sportiv,  sum( case when loc_ocupat = '1' then 10           when loc_ocupat = '2' then 8           when loc_ocupat = '3' then 5      end ) as total_puncte  from rezultate group by sportiv 	0
14373692	23610	check input value between two columns	select * from   table where  15 between coalesce(`from`,15) and coalesce(`to`,15); 	9.04849581761637e-05
14374726	758	postgresql - can't create database - operationalerror: source database "template1" is being accessed by other users	select *, pg_terminate_backend(procpid)  from pg_stat_activity  where usename='username'; 	0.0640764902081236
14374789	6887	sql - create single query to get the values for the given criteria	select pool       ,sum(case when dt between 20120101 and 20120107 then val else 0) as wk1       ,sum(case when dt between 20120108 and 20120114 then val else 0) as wk2     ...  ... from my_table group by pool 	0
14374822	2827	get hours and minutes (hh:mm) from date	select convert(varchar(5),getdate(),108) 	0
14375339	30823	count number of records with specific values	select    count(distinct case when member_1 = 'alice' then member_1 end) +    count(distinct case when member_2 = 'alice' then member_2 end) +    count(distinct case when member_3 = 'alice' then member_3 end) from tablename where 'alice' in(member_1, member_2, member_3); 	0
14376665	20152	update serial value after import	select setval(pg_get_serial_sequence('auth_event' , 'id'), (select max(id) from auth_event) ); 	0.00444699540920293
14378541	24925	error when trying to retrieve data within a date range	select * from tblcustomers where date between convert(smalldatetime, '19/12/2012', 105) and convert(smalldatetime, '1/17/2013', 101) go 	0.00406750477821483
14378748	33856	sql - can sub-query have a different condition from main query?	select t1.id, t1.desc,    ( select count(*)     from table1 t2     where t1.id=t2.id and t2.status_id=2) count  from table1 t1 where t1.status_id=6 	0.0492724624206492
14379067	23403	convert rows of data into table similar to pivot but with actual values	select  c1, max(case when c2='x1' then c3 else '' end) as `x1`, max(case when c2='x2' then c3 else '' end) as `x2`, max(case when c2='x3' then c3 else '' end) as `x3`, max(case when c2='x4' then c3 else '' end) as `x4` from t group by c1 	0
14379337	22058	group rows by 7 days interval starting from a certain date	select      1 + datediff(columndate, @start_date) div 7  as weeknumber   , @start_date + interval (datediff(columndate, @start_date) div 7) week       as week_start_date   , min(columndate) as actual_first_date   , max(columndate) as actual_last_date   , sum(othercolumn)   , avg(othercolumn) from      tablex  where      columndate >= @start_date  group by     datediff(columndate, @start_date) div 7 ; 	0
14379825	11271	combining two different jtables and adding button into jtable	select topic_title,topic_description,topic_by,        reply_content,reply_by           from forumtopics join forumreplies             on (forumtopics.topic_id=forumreplies.topic_id)  where topic_id = 1234 	0.00217608468838005
14381338	7227	how can i reference a 'parent' table in a series of joins on selects	select * from <table1>  inner join <table2>     on <table1>.datefield between <fields from table2> 	0.00541015033447909
14381395	28431	get quantity of mysql groups	select count(distinct t2.z)  from table1 as t1 inner join table2 as t2 on t2.t1_id=t1.id where t1.x=1 and t2.y=1 	0.000930222834906701
14382645	37261	how to check if a foreign column is part of a constraint with "on delete cascade" option?	select ao.name,ao.type_desc,delete_referential_action_desc,* from sys.foreign_keys fk  inner join sys.all_objects ao  on fk.parent_object_id = ao.object_id      where delete_referential_action_desc <> 'cascade' 	0.000111274008968181
14385519	31872	ssrs limit length of text but keep full words	select id, substr(field1,1, regexp_instr(field1, '[ ]', 70)) from.... union select id, substr(field1, regexp_instr(field1, '[ ]', 70)) from ... 	0.119894658854523
14386763	9825	mysql group and sort without using order by on outter most	select a.name, 'admin' as usertype, max(l.login_date) as lastlogindate from admin a left outer join      logs l      on a.id = l.id and         l.user_type = 'admin' group by a.name 	0.0251050344207815
14388288	4147	selecting users with criteria from second table	select u.id from users as u inner join users_info as ui on u.id = ui.user_id where profile_image is not null 	0
14388914	23233	trying to get the distinct values of 3 columns in sqlite db	select col1 from table union select col2 from table union select col3 from table 	0
14389418	32805	sort by closest date, then past	select   datediff(date_start, now()) as date_diff, exhibitions.* from     events  where    event.gallery_id = xx order by (case when date_diff < 0 then 1 else 0 end),          abs(date_diff) asc limit    5 	0.000366139685983436
14389452	33680	hierarchyid has descendants query	select nodecode.tostring() as nodecode, nodename,             case when (select top 1 n.nodecode                    from ##nodes                    where nodecode.getancestor(1) = n.nodecode) is null then 'false'             else 'true' end as hasdescendants        from ##nodes n 	0.154623381953881
14390007	9602	how to hide columns? mysql	select storeid from (    select storeid, sum(salary) from store    join employee    where salary < expenditure ) 	0.0160567628551022
14391268	38883	optimising search on primary key for large table	select films.film_name from `films` join popular_films   on popular_films.film_id = films.film_id; 	0.198885080461595
14392605	21209	showing balance in available stocks in inventory for every day	select i.date as date, p.resourcename as itemname, p.resourcerate as rate, coalesce(i.totalinqty,0) as inwardsquantity, coalesce(s.totaloutqty,0) as outwardsquantity, coalesce(i.totalinqty,0)-coalesce(s.totaloutqty,0) as balance, o.unitsymbol as itemunit  from unitmaster o  inner join resource_master p      on o.unitcode = p.unitcode      left join(select sum(i.qty) as totalinqty,nameofitem,min(i.date) as date  from inwards_master i where tendercode=1 group by nameofitem) i on i.nameofitem= p.resourcename      left join(select sum(s.qty) as totaloutqty,nameofitem, min(s.date) as date  from outwards_master s where tendercode=1 group by s.nameofitem) s on i.date=s.date and i.nameofitem =s.nameofitem  where p.status=1 and p.tendercode= 1 	4.7814639962701e-05
14393245	9262	joining two columns into one column from different tables	select course from (     select course, 1 ord from studentdb.dbo.student where rollno = 130     union     select course, 2 ord from studentdb.dbo.courses where course is not null ) s group by course order by min(ord) 	0
14396296	39320	join two table twice and return duplicate column name	select m.id as messageid,m.message_from,m.message_to,m.message_message,     u1.id as fromid, u1.name as fromname,     u2.id as toid,u2.name as toname from messages m inner join user as u1 on(m.message_from = u1.id)   inner join user as u2 on(m.message_to = u2.id) 	0.000146429181209102
14396418	30897	group by in ordered columns	select *  from products p  left join p_images r on (r.product=p.id)  where r.nu = (select min(nu) from p_images m where m.product = p.id) order by nu 	0.00803124597349516
14397131	4126	select all rows in a group where within the group, one column has one specific value, and another column has another specific value on the next row	select * from fruits  where fruit not in (select fruit from fruits where value1 is not null and value1 <> '' and value1 <> 'a') and exists (select fruit from fruits f2 where f2.fruit = fruits.fruit and value2 = 'x') 	0
14399197	17163	sql duration between two dates in different rows	select abs(datediff(hour, ca.thedate, cb.thedate)) as hoursbetween from dbo.customers ca inner join dbo.customers cb on cb.name = ca.name and cb.code = 'b' where ca.code = 'a' 	0
14402890	28443	how to find names with 2-byte characters, regardless of collation?	select *    from customer  where length(last_name) != lengthb(last_name); 	0.00250734445524751
14402899	2265	how to group data by date and specific time	select name, count(*), dateadd(dd, 0, datediff(dd, 0, dateadd(hour, 3, [timestamp]))) from goods group by name, dateadd(dd, 0, datediff(dd, 0, dateadd(hour, 3, [timestamp]))) 	0.001020047894242
14403017	23277	checking multiple mysql columns against a single value	select * from tablename where 2 in (columnone,columntwo,columnthree) 	0.000563226768320954
14403869	24795	neglecting the records from sql query	select * from table2  where convert(date, given_schedule) >=convert(date, dateadd(dd, -3, getdate()))  and convert(date, getdate()) <> convert(date, delivery_schedule) 	0.0149648722987828
14403943	32932	how to find the difference between two tables?	select name from table_a where name not in (select name from table_b) 	0
14404115	19739	sql select statement, datediff only if dates in between are/are not in a workdays table	select x.*, x2.daycnt  from accounttable x inner join  (     select a.accountnumber,a.startdate, b.enddate, count(b.date) daycnt      from accounttable a     left outer join workdays w          on a.startdate >= w.date and          a.enddate <= w.date and          isworkday = 'y'     group by a.accountnumber,a.startdate, b.enddate ) x2  on x.accountnumber = x2.accountnumber and x.startdate = x2.startdate and x.enddate = x2.enddate 	0.00657723084268272
14404732	1806	check for same index in two arrays: in (1,2,3) and in (a, b, c)	select   id, title from   `questions` q where   (q.id = 2 and q.answer = 'christoffer columbus') or   (q.id = 4 and q.answer = 'arnold schwarzenegger') ; 	0.000502635014357218
14405943	12587	fetching items from table a, which is linked to table c via table b. triple join?	select s.story_title from stories s, links l, media m where m.medium_name = 'movie' and s.story_id = l.story_id and l.medium_id = m.medium_id 	7.56268205370159e-05
14406266	7584	how can i apply stuff() to comma seperate this	select t.ticketid, assignment = stuff( (   select ', ' + l.name      from dbo.login as l     inner join dbo.ticketassignments as ta       on l.loginid = ta.loginid     where ta.ticketid = t.ticketid     for xml path(''), type ).value('.[1]','nvarchar(max)'), 1, 2, '') from dbo.ticket as t order by t.ticketid; 	0.520713989879544
14407042	2371	how to count rows in table join?	select      schema_name(schema_id) + '.' + t.name as tablename ,   i.rows from sys.tables t (nolock)      join sys.sysindexes i (nolock) on t.object_id = i.id          and i.indid < 2 	0.00740993431071589
14407373	28683	mysql/php storing multiple data points	select market.marketname, seller.sellername, sum(sales.amount) as "total sales" from sales join seller join sellermarketlink join market join marketzipcode on (sales.sellerid = seller.id and seller.id = sellermarketlink.sellerid    and sellermarketlink.marketid = market.id    and market.id = marketzipcode.marketid    and marketzipcode.zipcode = sales.buyerzipcode) group by market.id, market.marketname, seller.id, seller.sellername order by market.marketname, seller.sellername 	0.0874673682010178
14407681	33451	mysql query 2 tables with different columns?	select 'u'                 as source      , u.first_name        as first_name      , u.last_name         as last_name       , u.employid          as employid      , u.manager           as manager    from $user_table u  where u.username='$contextuser'  union all select 't'                 as source      , t.some_string       as first_name      , t.some_otherstring  as last_name       , 0                   as employid      , 0                   as manager   from $times_table t   where t.uid='$contextuser'    and t.submitstatus=1 	0.00163271439311271
14410334	3241	query to return list of tables in access	select name from msysobjects where (name not like "msys*") and (type=1 or type=6); 	0.0116850533929976
14410715	34458	order results by date in second table	select c.clientid , j.jobnumber , j.username , j.description , j.clientid , j.status , j.adminunread , max(p.postdate) as postedon from clients c inner join jobs j on c.clientid=j.clientid left join posts p on j.jobnumber=p.jobnumber and c.clientid=p.clientid group by c.clientid , j.jobnumber order by postedon desc, c.clientid, j.jobnumber desc 	0.00145533528051345
14411661	6454	php / mysql query: show results based on 2 conflicting conditions	select * from updates order by `year` asc, `month` asc 	0.000370159265753579
14411907	10858	squeeze two results in one row	select  u1.user_id as user_id_1, u2.user_id as user_id_2,  u1.setting_id as setting_id1, u2.setting_id as setting_id2,  from  `settings` s inner join `user` u1 on (s.pop_setting1_id=u1.setting_id) inner join `user` u2 on (s.pop_setting2_id=u2.setting_id) where id=? 	0.00107650738523895
14412080	11342	is it possible to write a query that categorize sum(amount) in 2 columns?	select     sum(case when type = 1 then amount else 0 end) amount1,     sum(case when type = 2 then amount else 0 end) amount2 from mytbl 	0.060419878946083
14412898	6935	split string and take last element	select substring( string , len(string) -  charindex('/',reverse(string)) + 2  , len(string)  ) from sample; 	0
14412967	34670	sql: find if answer exists	select case       when exists (select 1                    from   tblquestions as q                           inner join tblanswers as a                                   on q.questionid = a.questionid                    where  ( q.moduleid = @moduleid )                           and ( not exists (select 1                                             from   tblquestions as q                                                    left outer join                                                    tblanswers as a                                                                 on                                                    q.questionid =                                                    a.questionid                                             where  ( q.moduleid = @moduleid )                                                    and ( a.answerid is null )                                            ) ))     then 1  else 0     end  as allquestionsanswered 	0.06445317375648
14413203	28905	writing a function in sql to loop through a date range in a udf	select dhcp.singleday(a::date, a::date + 1) from generate_series(     '2012-11-24'::date,     '2012-12-03',     '1 day' ) s(a) 	0.399985290477762
14416733	21345	return multiple row's column values as columns of linked item	select  scancode as itemid,         receiptalias,         max(case when storefk = 1 then retail else null end) store_1,         max(case when storefk = 2 then retail else null end) store_2,         max(case when storefk = 3 then retail else null end) store_3 from    itemdata group   by scancode, receiptalias having  count(distinct retail) > 1 	0
14418592	101	sql summarize and average	select      t.avgrating,     t.count,     t.dishname,     t.dishid,     rest.restaurantid,     rest.name as restaurantname,     rest.[address],     rest.city,     rest.[state],     rest.zip,     rest.lat,     rest.lng from dbo.restaurants rest  join (select          avg(rev.rating) as avgrating,         count(1) as count,         restaurant_restaurantid,         min(dish.name) as dishname,         dishid       from dbo.dishes dish        join dbo.reviews rev on rev.dish_dishid = dish.dishid        group by restaurant_restaurantid, dishid     ) as t on t.restaurant_restaurantid = rest.restaurantid where rest.location.stdistance(@pos) <= (@dist * 1609.334) order by rest.restaurantid, t.dishid 	0.0353447533835937
14419848	32255	adding columns to get total and ranking total	select sn.roll_no,     sn.class,     sn2.total,     rank() over (partition by sn.class order by sn2.total desc) as rank from student_numbers sn join ( select    roll_no, hindi+maths+science as total from student_numbers ) sn2 on sn.roll_no = sn2.roll_no 	0
14419901	30285	from a birthday date list to an array of the total user from each individual age	select     floor(datediff(now(), `birthday`)/365) as 'age',     count(*) from `users` where floor(datediff(now(), `birthday`)/365) between 10 and 60 and `id` in (1, 3, 5, 12, 29) group by floor(datediff(now(), `birthday`)/365) order by floor(datediff(now(), `birthday`)/365) asc 	0
14423556	33980	how to select specific data from 3 tables? [postgresql 9.1]	select * from forum f join groups g on g.group_id = f.group_id join users u on u.user_id = g.group_founder  where u.user_id = 1 	0.000303217271155296
14424814	21478	grouping mysql result rows by date	select     hour(`timestamp`) as `hour`,     avg(`somevalue`) as `average` from ... group by     date(`timestamp`),     hour(`timestamp`), order by ... limit 0, 24; 	0.00494220270720082
14425576	29876	find and update the current live program in mysql with sql query	select * from tv_programs where start_time <= now() order by start_time desc limit 1; 	0.0248558034563226
14428409	33325	sql how to format time?	select date_format(now(), "%y-%m-%d %h%i%s") 	0.0630312356332185
14428599	19260	mysql: get result by user name	select `content` from `userprofile` where `userid` = (select `id` from `users` where `handle` = ? limit 1) and `title` = 'donation' limit 1 	0.00390227747453696
14428672	2772	yet another sql query	select count(distinct ident) from   ps_login_log where  user = 'someuser'    and time >= current_date - interval 5 day    and time <  current_date + interval 1 day 	0.234289196262087
14429534	27217	sql select from two tables - need join?	select * from  (   select   e.cid,    date,    name,    gender from events e left join clients c   on e.cid = c.cid) t 	0.027499484536447
14430511	31378	select rows where column values differ by more than two years	select id, product, make_date, order_datetime from tbl_order where make_date < order_datetime - interval 2 year     or make_date > order_datetime + interval 2 year ; 	0
14430523	20320	mysql get data from table without duplicates	select      ( select tt.id        from tablex as tt        where tt.number = t.number       order by rand()           limit 1     ) as id,     number from      tablex as t group by     number ; 	0.000399939331786932
14431163	8684	delete non-distinct rows based on multiple columns	select  firstname, lastname, companyname, count(*) thecount, min(id) min_id into #temp from tab group by firstname, lastname, companyname; select  a.id id, b.min_id into #temp1 from tab a, #temp b where  a.firstname  = b.firstname  and a.lastname    = b.lastname and a.companyname = b.companyname and b.thecount > 1; update tab2 set tab2.id = t.min_id from tab2, #temp1 t where tab2.id = t.id; delete t from tab t, #temp1 a where t.id = a.id and a.id <> a.min_id; 	0
14431189	9930	postgres concat all	select rtrim(ltrim(replace(tablename::text, ',', ''), '('), ')') from tablename; 	0.0549797528118351
14433598	6054	mysql merging queries	select     e.basename as basename,      s.basename as mastername,     (select count(id) from dataset where entityid < e.entityid) as parentcount,     (select count(id) from dataset where entityid > e.entityid) as siblingcount   from      dataset e      left join dataset s on s.id = e.entityid   order by      e.entityid 	0.103529037688709
14433643	36209	iterate through duplicate entries in mysql column	select date, count(*) from timerecords    where employeeid = 1 and date between date_sub(now(),interval 1 week) and now()    group by date   order by date desc 	0.000290712957650026
14433948	40082	my sql query to get middle row values using group by function	select table1.*  from table1 join (     select substring_index(substring_index( group_concat(id order by id asc), ',', ceil(count(*) / 2) ), ',', -1) as id     from table1     group by code ) t using(id) 	0.0497913056326278
14435635	4448	mysql subtract row of different table	select     staff.id_staff,     staff.name,     count(`leave`.id_leave) as leave_count,     leave_balance.balance,     (count(`leave`.id_leave) - leave_balance.balance) as leave_difference,     `leave`.leave_type_id_leave_type as leave_type   from     staff     join `leave` on staff.id_staff = `leave`.staff_leave_application_staff_id_staff     join leave_balance on       (         staff.id_staff = leave_balance.staff_id_staff         and `leave`.leave_type_id_leave_type = leave_balance.leave_type_id_leave_type       )   where      `leave`.active = 1   group by     staff.id_staff, leave_type; 	6.69710285867726e-05
14436730	24491	joining/merging two tables to create a third table in sql	select a.cat1,            a.cat2,            a.cat3,            a.value1,            b.value2     from tab1 a     left outer join       (select cat1,               cat2,               cat3,               max(value2) value2        from tab2        group by cat1,                 cat2,                 cat3) b on a.cat1 = b.cat1     and a.cat2 = b.cat2     and a.cat3 = b.cat3; 	0.00199644155980172
14436931	34596	how can i select rows which foreign key relation elements are only past in time or don't exist at all	select *    from my_table x   left   join my_other_table y      on y.id = x.id    and y.date >= now()  where y.id is null; 	0
14438466	40747	tsql - if... then else and case on dates	select client, case     when [closed] <= @givendate then 'closed'    when [closing] <= @givendate then 'closing'    when [live to terminal] <= @givendate then 'terminal'    when [prospect to live] <= @givendate then 'live'    else 'prospect'  end status from #tempoutput where [system setup] <= @givendate 	0.297673406161557
14438815	20576	best way to optimise 3 queries to a single one	select info, count(*) as info_cnt  from t where uid = 1 and info in ('a', 'b','c') group by info 	0.0574053612378043
14441744	20542	inner join on different qaunties	select  c.code ,         t1.code ,         t1.qty ,         t2.code ,         t2.qty from    ( select    code           from      dbo.table1           union           select    code           from      dbo.table2         ) c         left outer join dbo.table1 t1 on c.code = t1.code         left outer join dbo.table2 t2 on c.code = t2.code where   t1.code is null         or t2.code is null         or t1.qty <> t2.qty 	0.527153122408012
14442891	2637	date ranges using recursion	select  pat_id ,fill_date ,script_end_date ,'h3a' as h3a, coalesce(sum(case when drug_class='h3a' then distinctdrugs end),0) as h3acounts ,'h4b' as h4b, coalesce(sum(case when drug_class='h4b' then distinctdrugs end),0) as h4bcounts ,'h6h' as h6h, coalesce(sum(case when drug_class='h6h' then distinctdrugs end),0) as h6hcounts ,'h2e' as h2e, coalesce(sum(case when drug_class='h2e' then distinctdrugs end),0) as h2ecounts ,'h3a' as h2f, coalesce(sum(case when drug_class='h2f' then distinctdrugs end),0) as h2fcounts ,'h3a' as h2s, coalesce(sum(case when drug_class='h2s' then distinctdrugs end),0) as h2scounts ,'h3a' as j7c, coalesce(sum(case when drug_class='j7c' then distinctdrugs end),0) as j7ccounts ,row_number() over(order by pat_id) as rn from x group by pat_id,fill_date,script_end_date ) 	0.0386038656315988
14443181	9041	how to fetch unique records from database?	select gl.catid as gallery_cat_id, ab.albumname, gl.imagest  from   albums as ab    inner join gallery as gl   on ab.id=gl.catid  group by ab.id order by ab.albumname asc 	0
14446170	20337	concentrate many rows into list using a datareader	select t.id as teamid, t.name as teamname, p.id as playerid, p.name as playername      , p.team as teamname, p.iq, p.someotherdetail from team t inner join players p on t.id = p.team 	0.00347503982760734
14447018	121	how can optimize these instruction with mysql (subqueries for each row)?	select   d.id,          d.source_name,          d.spider_status,          s.last_success_date,          count(l.id) as total,          sum(l.id is not null and l.action='added'    ) as added,          sum(l.id is not null and l.action='extended' ) as extended,          sum(l.id is not null and l.action='duplicate') as duplicate from     deal_source d     join spider      s       on s.deal_source_id  = d.id     join spider_log  l       on l.deal_source_id  = d.id       on l.date_created   >= s.last_success_date      and l.date_created   <  s.last_success_date + interval 1 day group by d.id 	0.106366294223324
14449023	10319	mysql - private posts display	select distinct p.post_id, p.post_name from users as u join posts as p on p.user_id=u.user_id  left join private pv on pv.post_id=p.post_id where (p.private=0) or  (authorized_user_id={$logged_in_id} and p.private=1) 	0.00309042592559858
14449549	15237	how to find grandchildren?	select    p.product_id , p.model , p.sku , p.item_number , p.msrp , p.availability , p.description , grand_child.category_name as grand_child_category , child.category_name as child_category , parent.category_name as parent_category from categories parent inner join categories child  on parent.category_id = child.parent  inner join categories grand_child on child.category_id = grand_child.parent  inner join products_categories pc on grand_child.category_id = pc.category_id  inner join products p on p.product_id = pc.product_id where parent.category_id = 119 	0.0194331730726989
14450275	28454	how to make 2 sql queries 1	select statusreportid,         statusreporttime,         carnumber,         vehicleid,         drivernumber,         driverid,         vehiclestatus,         locationx,         locationy,         speed,         direction,         invalidgps  from   dbo_vehiclestatusreport  where  statusreportid >         ((select max(statusreportid) from dbo_vehiclestatusreport) - 3000) 	0.0968876529509637
14450640	17664	ordering strings that contain numbers	select mr, lname, fname  from users  where mr between 'mr20001' and 'mr20002'  order by cast(replace(mr, 'mr', '') as int) 	0.0169964704619311
14451621	36073	a one to many relationship creating a dynamic link between product and owner	select * from products left join admin on admin.caterer_id = products.caterer_id 	0.00344360451125449
14451764	4904	mysql join multiple table excluding some records	select a.author_id, a.name, b.name as bookname from author a left join publisher p on p.author_id = a.author_id inner join book b on b.book_id = p.book_id group by a.author_id having count(p.book_id) = 1 and bookname='rdbms' 	0.0026051136058836
14454526	5381	mysql - how to get data by date range given only month and year	select * from time_period where  (year(date_from) >= '2013' or (year(date_from) >= '2012' and  month(date_from) >= '10')) and  (year(date_to) <= '2013' and month(date_to) <= '12'); 	0
14455208	17251	oracle apex calendar ordering records	select ename, hiredate  +  rownum / 24 / 60 from  (select   ename, hiredate     from emp    order by ename) 	0.19466541688299
14461306	36537	retrieving a list of rows with only a single item from other table in oracle	select       p.prod_id,      p.prod_name,      t.prod_image  from      product p  left outer join(      select             pi.prod_image_id,            pi.prod_id,            pi.prod_image       from            product_image pi       inner join (            select                  min(pi.prod_image_id) as prod_image_id             from                  product_image pi            group by                  pi.prod_id      ) prod_image       on pi.prod_image_id=prod_image.prod_image_id )t on p.prod_id=t.prod_id order by p.prod_id desc; 	0
14463130	29603	get "diff" of database after a complex transaction	select current_db.tablex.id from current_db.tablex   left outer join earlier_db.tablex     on current_db.tablex.id = earlier_db.tablex.id where earlier_db.tablex.id is null 	0.00882825176334654
14463483	36503	sql query to get distinct rows from multiple tables	select c.id, c.name  from company c where exists (select 1  from branch b  where c.id = b.cid and b.profit > 100) 	0.000128439025657057
14466352	35570	what is better to use: keeping track of amount in database or counting	select count(*) from table_name where field=11; 	0.302245533684478
14466452	30156	get user with highest number of records	select username, count(*) from records group by username order by count(*) desc limit 1 	0
14468111	20922	sql cumulative previous 12 months - breakdown per month	select   periods.year ,periods.month ,measures.cnt from (     select distinct       year = year(startdate)     , month = month(startdate)     , month_running = datediff(mm, 0, startdate)      from a     group by year(startdate), month(startdate), datediff(mm, 0, startdate)  ) periods join (     select month_running = datediff(mm, 0, startdate), cnt = count(measure)      from a     group by datediff(mm, 0, startdate)  ) measures on measures.month_running between periods.month_running - 12 and periods.month_running - 1 	0
14468252	11646	filter double values in sql query	select date(`time`) as date, count( distinct ip ) as count  from table  where `time` > ( now( ) - interval 10 day )   group by date(  `time` ) 	0.321700689062174
14468665	6561	what sql query will return only distinct values in one column?	select hostname,site,rack from hardwaredb where rack like '%rack1%' group by hostname 	0.000835613923521004
14468738	18776	select some rows between 2 datetime	select * from mytable where `date` between '2008-01-01' and '2010-01-01'; 	0.00046509574251625
14470741	16051	get the last 30 records from mysql but not the very last 1	select      avg(clickers) as avgclickers from      (         select clickers          from sitelogs_daily_stats          order by id desc          limit 1,29     ) as t1 	0
14473413	36900	is there any better way to access hundreds of different record in database?	select * from table where name in ( 'xxx', 'syz', 'abc',....); 	0.0330014424669535
14475184	38000	convert a navision filter to sql where	select field1,field2...clrfunctionname(filtervalue) as fixedfiltervalue from sometable where fixedfiltervalue like '%1_3%'; 	0.455780492984546
14475260	8380	mysql - regular express to find column that starts with letters	select * from table where column regexp '^[a-za-z]' 	0.00774467270588191
14475694	10703	lob locator on new row in a trigger	select bytes    into :new.bytes    from table_b   where id = :new.ref_id; 	0.022282484453136
14475965	34673	how to find sum of qty for each month from the table that keep qty in dozen and piece at the same time?	select tbl_order.pd_id,         sum(iif([od_qty_unit]='dz',[od_qty]*12,[od_qty])) as qty from tbl_order group by tbl_order.pd_id; 	0
14477009	17442	sql query join & date manipulation	select case when p.date_of_birth < current_date - interval '12 year'        then '< 12'        else '12+'        end age_bracket,        count (*) from   person p where  exists (          select null          from   person_status_history psh          where  psh.person_id   = p.person_id and                 psh.reason_code = 85          and                 exists (                   select null                   from   person_visit pv                   where  pv.person_id          = psh.person_id and                          pv.reasses_appoint_no is not null     and                          pv.visit_date         > psh.suspend_to_date) group by case when p.date_of_birth < current_date - interval '12 year'          then '< 12'          else '12+'          end 	0.644065919659816
14478332	41164	how to convert between time zones in sql server 2008?	select cast(switchoffset(todatetimeoffset(dtdate, '-06:00'), '+05:30') as datetime) 	0.0912317268520381
14479998	10702	how to limit and order by in ms sql?	select top 5 * from tablename order by newid() 	0.459959502752678
14480625	41302	sequential numbering of data sequence	select id, obs, sum(cnt) over (order by id) as seq_num from (   select id, obs, case when obs <> (lag(obs) over (order by id)) then 1 else 0 end as cnt   from test_seq ) order by id; 	0.0112295571438593
14483396	25801	get all duplicate rows between two datetimes.	select field1, field2, logdate from logtable where logdate between "somedate" and "someotherdate" group by field1, field2, logdate having count(*) > 1 	0
14483636	31935	compare date from php and mssql to retrieve the nearest date from now	select top 1 datediff(s, [date], getdate()) from mytable order by datediff(s, [date], getdate()) 	0
14485949	24413	query to select all tables from database but not materialized views	select *   from all_tables t  where owner = user    and (owner, table_name) not in (select owner, mview_name                                      from all_mviews l                                    union all                                    select log_owner, log_table                                      from all_mview_logs) 	0.00877359000857525
14485971	11025	aggregate & count "select .... as [name]" field?	select enteredby, device, count(device) as countdev from ( select  mid(note,instr(note,"device.")-          (instr(note,"device.")-           instr(note,"pressure and"))+13,     (instr(note,"device.")-instr(note,"pressure and"))-14) as device,  mylog.enteredby from mylog where mylog.[note] like "*removed and*") group by enteredby, device 	0.0462984949702126
14486958	10401	how can i get my unioned query results to group correctly?	select     scode,     sunitcode,     name,     sum(total),     istatus,     dtmovein from (  <your first query>  union all  <your second query> ) as all_data group by     scode,     sunitcode,     name,     istatus,     dtmovein 	0.78404506063036
14488910	15801	remove sql output when value is null	select s.branchno, s.staffno, s.fname, s.lname, propertyno, p.staffno,        o.fname, o.lname, o.ownerno   from privateowner o   left join propertyforrent p on o.ownerno = p.ownerno   left join staff s on s.staffno = p.staffno  order by s.branchno, s.staffno, propertyno 	0.174042537804119
14489213	10125	calculating and grouping by great circle distance in mysql	select <c.client_ip to s.server_ip distance calc> as distance, avg(sp.speed) as avgspeed from speedtable sp join geotable c     on sp.client_ip = c.client_ip join geotable s     on sp.server_ip = s.server_ip where 1 = 1  group by <c.client_ip to s.server_ip distance calc> 	0.100579385063156
14492801	1018	loop over result in stored procedure	select d.defaultid, d.weight, d.length, d.height, d.width  from tbldefault d where customerid=@customerid and  deletedateutc is null and (exists(select 1 from tblother where customerid=@customerid and customeruserid=@customeruserid       and defaultid=d.defaultid)  or not exists(select 1 from tblother where customerid=@customerid and defaultid=d.defaultid)) 	0.771133675380943
14495869	17693	view query on parent and child table	select     sd.tax_def_id,     sd.effective_date,     sum(case when tax_type = 'i' and distribution_type = 's' then wh_rate else 0 end) i_s_wh_rate,     sum(case when tax_type = 'i' and distribution_type = 'p' then wh_rate else 0 end) i_p_wh_rate,     sum(case when tax_type = 'd' and distribution_type = 's' then wh_rate else 0 end) d_s_wh_rate,     sum(case when tax_type = 'd' and distribution_type = 'p' then wh_rate else 0 end) d_p_wh_rate from state_def sd     left join tax_detail td         on sd.tax_def_id = td.tax_def_id group by sd.tax_def_id, sd.effective_date 	0.00412388035924437
14497987	3634	summarizing many tables in mysql	select  col1 as `record number`,          count(*) as `number`,          group_concat(_name) as `table name` from (     select col1, 'table_1' as _name from table_1     union all     select col1, 'table_2' as _name from table_2     union all     select col1, 'table_3' as _name from table_3 ) a group by col1 	0.139909562638589
14499094	9336	filtering columns based on a date in a field for current week, past weeks, and future weeks	select interviewstatus,        sum(case when dateupdated >= dateadd(dd, -(datepart(dw, getdate()) -1), getdate())                      and dateupdated < cast(convert(varchar(10), dateadd(dd, (8 - datepart(dw, getdate())), getdate()), 120) as datetime)                 then 1                 else 0 end)            as numberincurrentweek from interviewtable where dateupdated >= dateadd(dd, -(datepart(dw, getdate()) -1), getdate())       and dateupdated < cast(convert(varchar(10), dateadd(dd, (8 - datepart(dw, getdate())), getdate()), 120) as datetime) group by interviewstatus 	0
14499558	31980	counting many to many association records	select  a.id, count(*) totalrecordcount from    words a         inner join definition_words b             on a.id = b.word_id         inner join definitions c             on b.definition_id = c.id         inner join         (             select  id,                     sum(language = 1) totalcount             from    definitions             group   by id         ) d on c.id = d.id and                 d.totalcount = 1 group   by a.id 	0.00205059009138944
14501893	33893	join tables with two foreign keys	select  * from    table2 t2 left join         table1 t1 on      t1.id_user = t2.id_user 	0.00240203267776368
14504997	38901	mysql count with group by	select a.statusid, a.status, count(*)  from(    select statusid,    (case when statusname = 'open' and assign is null then 'unassigned'           when statusname ='open' and assign is not null then 'assigned'          else statusname          end) as status    from ticket     inner join department on ticket.department = department.departid     inner join status on ticket.status = status.statusid    where ticket.department = 100) as a group by a.status, a.statusid 	0.30940228892525
14505519	35050	mysql select query on two tables	select * from a,b 	0.0194728910900652
14505938	37416	select from 2 tables depending on 2 columns in first table	select      r . *, p . *, s . * from     1_related as r         left outer join     1_products as p on r.fk_prod_pack_related_id = p.id         and r.fk_prod_pack_related = 0         left outer join     1_packages as s on r.fk_prod_pack_related_id = s.id         and r.fk_prod_pack_related = 1 where     r.prod_pack = 0         and r.fk_prod_pack_id = 102 	0
14506853	35674	selecting from multiple tables with multiple criteria	select sample.id, sample.date, compound.name, sample.location, method.label, sample.value, compound.unit from sample  inner join compound on compound.id = sample.compound_id  inner join method on method.id = sample.method where sample.date = '2011-11-03' and compound.name = 'zinc (dissolved)' and sample.location = "13.0" and method.id = 1; 	0.000558299843273936
14507340	22643	re-arrange columns after unpivot oracle	select id, customer_id, quantity, p from (select * from   unpivot_test unpivot (quantity for product_code in (product_code_a as 'a', product_code_b as 'b',   product_code_c as 'c', product_code_d as 'd'))); 	0.279432349686222
14508331	40816	trying to get comma delimited list but only get one	select     cat.product_id,      least(ifnull(nullif(saleprice, 0), price),price) as sort_price,     group_concat(category_id) as cats from gc_category_products cat join gc_products p on cat.product_id = p.id where cat.product_id in   (select product_id     from gc_category_products gcp     where gcp.category_id in ('31','35','30','36','37','34')) and enabled=1 group by product_id product_id   sort_price   cats 3            23           31,18 4            50           35,21 	0
14508745	23150	sql - join two queries together efficiently	select aa.userid, aa.roleid, aa.categoryid sum(aa.points) as points, sum(aa.target) as target from ( select     acs.userid,     acs.roleid,     acs.categoryid,     sum(acs.points) as points     null as target from acs union all select     tb.userid,     tb.roleid,     tb.categoryid,     0 as points     sum(         (         (datediff(dd, (case when @start >= tb.startdate then @start else tb.startdatee end),          (case when @end <= tb.enddate then @end else tb.enddate end)) + 1)      ) * tb.dailymed     ) as target from tb) as aa group by aa.userid, aa.roleid, aa.categoryid 	0.242338684782586
14509019	34683	select from table where a field does not exist in an item master table	select *  from ip24_import_images b left join sap.itemmasterskucolor im on b.sku = im.style and b.color = im.color where im.color is null 	0.000163475479740196
14509302	30485	mysql if in where condition based on select column	select      username,      message from mail where (if(username='johndoe',deletebyreceiver = 0,deletebysender =0)) limit 1 	0.00266667620231672
14514222	12032	how can i alias returned values in a query?	select decode(myfield, 1, 'red'                        2, 'blue'                        3, 'green'                           'undefined' as myfieldcolor from mytable 	0.178388725745529
14514987	35869	how to customize string return	select concat('/path/to/dir/', filename) as `file_name` from brand 	0.0653620685136398
14515235	17307	select characters and group together with joins?	select game_id from games_characters where character_id in (1,2,3) group by game_id having count(*) = 3 the above makes two assumptions 1) you know the characters your looking for 2) game_id and character_id are unique 	0.631744406367472
14516023	26594	percent of total with group by	select ma.actor      , count(1) as total      , count(1) / t.cnt * 100 as `percentage`   from movies_actors ma  cross   join (select count(1) as cnt from movies_actors) t  group     by ma.actor 	0.000975183267439287
14517213	7107	select min booking date by each customer	select       cm.customercode,       cm.customername,       min(eb.bookingdate)   from        entbookings eb  join       customermaster cm     on               cm.customercode = eb.bookingbycustomer  group by        cm.customercode, cm.customername 	0
14517384	36894	get similar queries from mysql	select id,screen_name,skip   from table  where skip=0    and screen_name in (select t2.screen_name                          from table t2                      group by t2.screen_name                     having count(*)>1                        ) 	0.00731053400696498
14517984	23101	mysql select query on name ignoring the first word if it is "the", "a", "an" etc	select ... where   title like 'r%'   or title like 'the r%'   or title like 'a r%'   or title like 'an r%'   ... 	0.00172690252240306
14518208	19675	time calculations and counts with mysql	select `name`, sum(timestampdiff(minute,`starttime`,`endtime`)-`idletime`)      from `gc_sessions` inner join `gc_users` on      `gc_sessions`.`user` =`gc_users`.`id` where gc_users.`name` like "variell" 	0.125390563247899
14521043	29128	group by date and value	select  date(`created_at`), keyword, count(*) as totalcount, sum (case when category = cat1 then 1 else 0 end) as cat1count, sum (case when category = cat2 then 1 else 0 end) as cat2count, sum (case when category = cat3 then 1 else 0 end) as cat3count from articles group by date(`created_at`), keyword order by date(`created_at`), keyword 	0.0124428794906922
14522704	15006	sorting sql string by first 2 or 3 characters	select location  from freelocations order by      case         when patindex('%[^0-9]%', location) = 1 then 9999999999        else cast(substring(location, 1, patindex('%[^0-9]%', location) - 1) as int)     end,     location 	0.00521490579851908
14522814	30004	how to carry out mysql query involving join of two tables	select  a.*, b.*        from    books a         inner join borrowed_items b             on a.`number` = b.item_number where   a.`subject area` = 'physics' 	0.0283295442092164
14524165	40882	sql select statement - return highest number value of a field	select first_name, year from users u1 where username='$username'  and year = (select max(year) from users u2 where u1.username=u2.username) 	0
14524387	40977	how to get maximum for a field based on a date and get other fields also?	select  startkey, name, min, lname, mname, id from t t1 where min =   (select max(min) from t t2 where t1.startkey=t2.startkey) order by startkey 	0
14524396	24398	selecting most recent answers efficiently	select t.eventid, t.memberid, t.timestamp, t.answer from tablename t  join (    select eventid, memberid, max(timestamp) maxtimestamp    from tablename    group by eventid, memberid ) t2 on t.eventid = t2.eventid      and t.memberid = t2.memberid      and t.timestamp = t2.maxtimestamp 	0.000224483619582094
14524825	4649	how can i get unix times for the start and end of last twelve months in a loop?	select month(date) as month, sum(amount) as amount from yourtable where year(date) = $year group by month(date) 	0
14524890	12728	how to consolidate overlap date in single	select s.id, s.start_dt, s.end_dt, s.division from sample s  join (    select s.id, max(s.end_dt-s.start_dt) as timeframe from sample s group by s.id ) s2 on s.id = s2.id      and s.end_dt-s.start_dt = s2.timeframe 	0.0038861561271136
14525079	31921	sql group patients by age range and sex	select case   when patient.birthdate  > '01-jan-1988'  then '1-25'    when patient.birthdate > '01-jan-1963' then '25-50'   when patient.birthdate > '01-jan-1938' then '50-75'    else '75+'  end as age_range,  sum(case when patient.sex = 'm' then 1 else 0 end) as males, sum(case when patient.sex = 'f' then 1 else 0 end) as females from patient group by case   when patient.birthdate  > '01-jan-1988'  then '1-25'    when patient.birthdate > '01-jan-1963' then '25-50'   when patient.birthdate > '01-jan-1938' then '50-75'    else '75+'  end 	0.00758483919344857
14525342	34806	sql query within another query	select username, (select sum(revenue) from orders where userid=c.userid) rev   from customers c 	0.166788512244085
14526093	16644	verify the columns (name and amount) returned by a sql query	select *  from tempdb.information_schema.columns  where table_name like '%#temptable%' 	0.000266941155796782
14527333	1722	inject user's selected timezone to query	select convert_tz('2004-01-01 12:00:00','utc','+2:00');  select convert_tz(now(), 'utc', '-5:30');  select convert_tz(now(), '-2:00', '+5:00') 	0.0650277979651648
14527532	629	retrieving the entire row containing maximum value of a field	select subjectarea from (   select max( copies_on_loan ) as max_copies_on_loan    from (     select       section.subjectarea as subjectarea,        sum( loanbook.copies_on_loan ) as copies_on_loan     from section       natural join items       natural join loanbook     group by section.subjectarea   ) as table1 ) as table2 join  (    select       section.subjectarea as subjectarea,        sum( loanbook.copies_on_loan ) as copies_on_loan     from section       natural join items       natural join loanbook     group by section.subjectarea ) table3 on table2.max_copies_on_loan  = table3.copies_on_loan 	0
14527779	35591	if a column has string to execute syntax	select vm.file_url from #__virtuemart_medias as vm      inner join #__virtuemart_product_medias as pm              on vm.virtuemart_media_id = pm.virtuemart_media_id      where pm.virtuemart_product_id = {$product_id}          and pm.ordering = case                               when vm.file_url  regexp 'thumb_phone01.jpg'                                  then 2                                  else 1                               end 	0.273200239174186
14527840	4133	display a given number of days as "#years, # months, # weeks, # days"	select floor(yourfield/365) + ' year(s), ' +         floor(mod(yourfield,365)/30) + ' month(s), ' +         floor(mod(mod(yourfield,365),30)/7) +' week(s), ' +         floor(mod(mod(mod(yourfield,365),30),7)) + ' day(s)' from table assumes + is valid operator in mysql for string concat. assumes 1 year = 365 days assumes 1 month = 30 days assumes 1 week = 7 days 	0
14528165	18006	finding records where one set of conditions is matched and the other isn't	select   a1.pupilid from assessment as a1   outer join assessment as a2     on a2.pupilid = a2.pupilid and a2.ncyear = '2' and a2.gradeid in('5a','5b','5c') and a2.term = '6' and a2.subject = '31' and a2.type = 'assessment'         where a1.gradeid in('1a','1b','1c')     and a1.ncyear = '1'     and a1.term = '6'     and a1.subject = '31'     and a1.type = 'assessment'     and a2.pupilid is null 	0
14528770	19724	mysql returns date out of order	select   year(`ndate`) as 'year',   month(`ndate`) as 'month',   count(`nid`) as 'count' from `weaponsnews` group by year(`ndate`) , month(`ndate`) order by year(`ndate`) desc , month(`ndate`) desc 	0.0401085425313993
14529680	34566	moving average filter in postgresql	select date_of_data,         val,         avg(val) over(order by date_of_data rows between 3 preceding and 3 following) as mean7 from mytable order by date_of_data; 	0.0110652387979638
14531457	33315	mysql: duplicate values when joining from multiple tables	select         article,         author,         item     from news     left join (       select             news.id as newsid,            group_concat(itemtitle) as item        from news        left join newsitemsrelation on            newsitemsrelation.newsid = news.id        left join items on            items.id = newsitemsrelation.itemid        group by news.id       ) items on news.id = items.newsid     left join (        select             news.id as newsid,            group_concat(name) as author        from news        left join newsauthorsrelation on            newsauthorsrelation.newsid = news.id        left join profiles on            profiles.id = newsauthorsrelation.userid        group by news.id       ) authors on news.id = authors.newsid 	0.000374788304543993
14532618	22156	sql query - find parent posts where no children posts exist	select q.* from tblquestions q  left outer join tblreplies r on q.queid = r.repquestionid where r.repquestionid is null 	0
14534787	1039	how to group and sort rows togther without hiding any rows?	select name, location      from mytable  order by location asc, name asc 	0.000916438030183324
14534908	40542	mysql join two tables and display specific records in sorted order	select adddate as date, w as withdrawal, d as deposit     from         (             select  accountnumber, '' as w, balance as d, adddate from deposit             union all             select  accountnumber, balance as w, '' as d, adddate from withdrawal         ) s     where   accountnumber = '0000102'     order   by date 	0
14537989	18843	sql join with not in column include in result	select      t1.id   , dd.date   , t1.allocation   , t2.present  from      table1 as t1                            cross join     ( select distinct date       from table2     ) as dd                                 left join     table2 as t2                                on  t2.id = t1.id       and t2.date = dd.date ; 	0.506355892940763
14538045	27430	comparing using case with user variables	select * from ( select     t.id, t.code, t.count,     @prevcount,     @prevcount - t.count difference,     case @prevcount - t.count when @prevcount - t.count >= 0 then 'equal or bigger' else 'smaller' end,     @prevcount := t.count   from     (select id, code, count from some_table where code = 'ab' order by id desc) t,     (select @prevcount := null) _uv group by t.id, t.code )x where x.difference >= 0; 	0.618014248379327
14538466	11970	using case to choose between two sentences in where clause (oracle)	select sum(     case ptipo       when 0 then (case when (a.nt = 0) then a.valor else 0 end)       when 1 then (case when (a.nt = 1) then a.valor else 0 end)       when 2 then (case when (a.nt = 1) then a.valor else -a.valor end)      end) into nresp from mov_caja a join enc_movp b on a.docid = b.docid join c_caja c on a.cajaid = c.cajaid where    c.cajaid = pcajaid and   (      (ptipo = 2 and (b.cod_compro = ncompini or b.fecha_mov between pfecha_ini and pfecha_fin)) or     (ptipo <> 2 and (b.cod_compro != ncompini and b.fecha_mov between pfecha_ini and pfecha_fin))   ) 	0.77844107597148
14538691	14628	changing group by statement to get field not being grouped	select id, date_modified, value from (     select         id, date_modified, value, row_number() over (partition by id order by date_modified desc) rn     from tbl ) a where rn = 1 	0.0127733272377592
14540701	27991	sql query - selecting distinct values from a table	select distinct fk_col from table1 minus (select distinct fk_col from table1 where col_entry='ab3' intersect select distinct fk_col from table1 where col_entry='ab4') 	0.000320970224783079
14542674	2392	relational algebra only & everywhere	select pizza as oldest_age from person join eats on eats.name = person.name group by pizza having max( age ) <24 union all select pizza as highest_price from serves group by pizza having max( price ) <10; 	0.591300905620287
14543274	19026	select value in mysql but check another database at clause where	select *    from `mc_region` as r left join         `mc_region_flags` as f on r.`id` = f.`id_region`  where r.`is_subregion` = 'false' and         r.`lastseen` < curdate() - interval 20 day and        coalesce(f.`flag`, '-') <> 'expire' limit 0, 30; 	0.00210397722124796
14549643	22769	sql order few records asc and the rest desc	select `xyz` from `your_table` order by (`abc` is null),`abc` 	0.00343328166075392
14549919	33026	mysql: grouping table per x / per y	select * from table group by column1, column2 	0
14550494	21131	mysql left join with multiple tables,having only primary key as foreign key of first table	select distinct(ur.id), ur.fname from user_profile as ur inner join user_course_rel as ucr     on ucr.user_id=ur.id left join     (select sal.student_id, sal.subject_id, sal.date      from students_attendance_lect as sal      where sal.date='2013-01-21'      and sal.subject_id = 2) as sa     on sa.student_id=ucr.user_id where ucr.course_id=1     and ucr.year_id=1     and ucr.division=3 	0
14550981	40433	sql select query returning unwanted data	select distinct      session.session_id as id,     session.anum,     student.first,     student.last,     session.why,     session.studentcomments,     session.aidyear,     support.counselorcomments from student         inner join session              on student.anum = session.anum         left join support              on session.session_id = support.session_id         where session.status in (0,2) 	0.795746287292126
14551249	25108	mysql compare rows with empty entries	select testitem      , max(case when testid = 1 then testid else null end) as testid1      , max(case when testid = 2 then testid else null end) as testid2      , max(case when testid = 1 then testresult else null end) as testresult1      , max(case when testid = 2 then testresult else null end) as testresult2 from mytable where testid in (1,2) group by testitem 	0.000170731826821504
14552090	25862	mysql join, retrieving data from other tables in a select	select products.productid,         products.name as productname,         products.description,         categories.name as categoryname from products inner join categories  on categories.categoryid = products.productcategoryid 	0.000147672333470894
14553796	13930	sql query to retrieve all products under some categories in adjacency list model	select p.id, p.title, p.qty from products p    join cats_products cp on p.id = cp.product_id where cp.cat_id in (    select c.id    from cats c    where c.title = 'electronics'    union all    select c2.id    from cats c       left join cats c2 on c.id = c2.parent    where c.title = 'electronics'    union all    select c3.id    from cats c       left join cats c2 on c.id = c2.parent       left join cats c3 on c2.id = c3.parent    where c.title = 'electronics'    union all    select c4.id    from cats c       left join cats c2 on c.id = c2.parent       left join cats c3 on c2.id = c3.parent       left join cats c4 on c3.id = c4.parent    where c.title = 'electronics' ) group by p.id, p.title, p.qty 	5.25391870082423e-05
14555711	36739	effect of more tables on database efficiency sql	select * form friends where userid=<user> 	0.248594787627021
14556965	3222	joining sql server tables	select      [movieid], [title],      stuff(          (select ', ' + b.[title]           from moviecategory a                inner join category b                   on a.categoryid = b.movieid           where  a.[movieid] = d.[movieid]           for xml path (''))            , 1, 1, '')  as categorylist from movie as d group by [movieid], [title] 	0.179074340820013
14558028	19555	join two tables but only return rows with unique values in one field	select * from currency as c left join stressvalue as s on c.diemention1 = s.groupname and s.membername <> (    select s.membername    from currency as c    join stressvalue as s    on c.diemention1 = s.membername) 	0
14558944	41281	how to query data when primary key exists twice as foreign key in another table?	select      user_id, user_fullname,      stuff(          (select ', ' + designation           from   userprofession           where  prof_id = a.user_id           for xml path (''))           , 1, 1, '')  as designationlist from userbasics as a group by user_id, user_fullname 	0
14559207	33942	sql order by numeric and string attributes	select [task], [start date] as start_date, [end date] as end_date, [priority], [time     allowance] as time_allowance, [details] from [schedulerdata0] order by (case priority   when 'very high' then 1     when 'high' then 2    when 'medium' then 3    when 'low' then 4    when 'very low' then 5 end), [start date] asc, [end date] desc 	0.118458915873443
14559403	32564	fetch single column from two table	select  a.price from    salesreturndetails a         inner join          (             select  distinct bill_number             from    salesreturn             where   session='12-13'         ) b on a.bill_number = b.bill_number 	0
14560956	1819	sql server 2008, concatenating strings?	select sb.salesid, ( select ', ' + sb2.product + ' x ' + sb2.quantity + ' @ ' + sb2.rate        from salesbody sb2        where sb2.salesid = sb.salesid         for xml path('') ) as details from salesbody sb group by sb.salesid 	0.470115469854578
14562277	16275	sql query to calculate hours spent from the the other day and ending up on the next day	select trunc(mydate / 3600) hr  , trunc(mod(mydate, 3600) / 60) mnt  , trunc(mod(mydate, 3600) / 60 /60) sec   from    (    select (to_date('01/02/2013 23:00:00', 'mm/dd/yyyy  hh24:mi:ss') -            to_date('01/01/2013 07:00:00', 'mm/dd/yyyy  hh24:mi:ss')) * 86400 mydate     from dual   )  / 	0
14562758	27241	calculate the maximum storage size of table record?	select  schema_name(t.schema_id) as schemaname,         t.name as tablename,         sum(c.max_length) as rowsize from    sys.tables t         inner join sys.columns c             on t.object_id = c.object_id         inner join sys.types s             on c.system_type_id = s.system_type_id group by schema_name(t.schema_id),         t.name order by schema_name(t.schema_id),         t.name 	0
14564226	34912	sql server multi rows query with group by	select dept from   tablename group  by dept having sum(case when [image] = 'n' then 1 else 0 end) = count(*) 	0.324018175439682
14564485	31992	mysql query to get rows with 5 minutes difference	select * from table1 a, table2 b where a.id=b.foreignid and abs(timestampdiff(minute,a.createddate,b.createddate)) > 5 	6.57221110967116e-05
14565589	3456	calculate the frequency	select thing      , count(case when other_thing = 10 then 'foo' end) x       , count(*) y     from my_table   group      by thing; 	0.00405253423343012
14566480	34847	why does the number 0 evaluate to a blank space	select cast(0 as varchar)         select cast('' as smallint)       	0.422065921591689
14567847	8010	how to select the top row of each group based on a specific ordering?	select t.primaryid, coalesce(t.parentid,t.primaryid) as parent from yourtable t  join (    select coalesce(parentid, primaryid) as parent, max(datefield) as dtmax    from yourtable    group by coalesce(parentid, primaryid) ) t2 on coalesce(t.parentid,t.primaryid) = parent and t.datefield = t2.dtmax 	0
14567911	33594	sql rank based on date	select * from   (    select deptno       , ename       , sal       , rank() over (partition by deptno order by sal desc) rnk        , row_number() over (partition by deptno order by sal desc) rno        , max(hiredate) over (partition by deptno order by deptno) max_hire_date    from emp_test   where deptno = 20  order by deptno  )  where rnk = 1 / sql> deptno  ename   sal    rnk  rno hiredate    max_hire_date  20     scott   3000    1   1   1/28/2013   1/28/2013  20     ford    3000    1   2   12/3/1981   1/28/2013 	0.00246589259924369
14569326	39403	self reference a table to get unrevised records	select * from table t1 where location = 'location'  and status in (4,5,6)  and revision = (select max(revision) from table t2 where t2.serial = t1.serial and t2.location = t1.location) 	0.00364351880166075
14569940	28576	mysql list tables and sizes - order by size	select table_name, table_rows, data_length, index_length,  round(((data_length + index_length) / 1024 / 1024),2) "size in mb" from information_schema.tables where table_schema = "schema_name" order by (data_length + index_length) desc; 	0.0429226007109005
14570422	34934	searching 2 columns and having them treated like they're 1 column	select          convert(nvarchar(1024),(isnull(columna,''))+convert(nvarchar(1024),isnull(columnb,''))   from searchtable where      convert(nvarchar(1024),(isnull(columna,''))+convert(nvarchar(1024),isnull(columnb,'')) like '%" & q & "%' 	0.00195802558996948
14573031	37647	mysql calling stored function for unique id generator	select f_id_test() 	0.459008938752003
14573515	15171	conditioning on multiple rows in a column in teradata	select id from yourtable where attribute in ('football', 'nfl', 'ball') group by id having count(distinct attribute) = 3 	0.0100370912462501
14574261	39767	conditionaly get second row from join in mysql	select runners.name,     runs.run_id,     runs.position,     races.race_id,    case       when runs.position = 1       then    runnerssecond.name       else    runnerswinner.name    end as nextcolumn from runners    join runs on(runs.runner_id = runners.runner_id)    join races on(races.race_id = runs.race_id)    left join runs runswinner on runswinner.race_id = races.race_id and runswinner.position = 1    left join runners runnerswinner on runnerswinner.runner_id = runswinner.runner_id    left join runs runsecond on runsecond.race_id = races.race_id and runsecond.position = 2    left join runners runnerssecond on runnerssecond.runner_id = runsecond.runner_id where runners.runner_id = 1; 	6.61864743635075e-05
14576073	28717	left join on column isn't in the relationship between two tables	select * from (     select distinct id, clip_state, benefit     from plans     where benefit = 'a') p left join clip_states cs on state in ('la') where (p.clip_state = cs.clip_state or (p.clip_state = 0 and cs.clip_state is null)); 	0.00645397189321751
14576535	17541	sql query that returns various rows from one table when using a condition where on another table	select  producto.descripcion, facturadetalle.precio  from producto  inner join facturadetalle on facturadetalle.productoid = producto.productoid  where facturadetalle.facturaid = 1 	0
14580073	16838	php mysql query to combine and add two equalent result	select   cl_list,   name,   value,   sum(total) as total from ( ) data group by   cl_list,   name,   value 	0.010725683767245
14581006	31881	how do i group us states by region in mysql?	select b.region, a.state, avg(salevalue) as average_sales_by_state, count(b.distributorid) from sales a inner join distributors b on a.distributorid = b.distributorid inner join us_regions c on b.state = c.state group by b.region, a.state order by b.region, average_sales_by_state desc 	0.439049724349026
14583529	4308	mysql multiple count in single table with different where clause	select      sum(category='x') as tot_x,      sum(category='y') as tot_y,      sum(category='z') as tot_z  from table where cid='290463' and category in ('x', 'y', 'z') 	0.0200651537834651
14584667	981	show name of source table(s) in select result	select *, 'schemes_discoveries' from [arachnode.net].[dbo].[schemes_discoveries] 	0.000623466124585437
14584982	447	querying for rows in a table and exempting specific rows if they exist in another	select * from tablea where item_id not in(select item_id  from tableb); 	0
14585030	17400	sql 2 statements creating a 3 statement, and joining the 2 together	select q1.repnr, q1.daystotal - q2.extern as [result] from ( select repnr, datediff(day, min(start), max(start) +1) as daystotal from tblstatus  where status in (1, 2, 3, 4, 8, 11, 20, 7, 23) group by repnr having count(*) = 2 and max(start) > getdate()-30 )q1 inner join  ( select repnr as repnr, convert(float, sum(datediff(day, start, slut))) as extern from tblstatus  where status in (5, 15, 17) group by repnr )q2 on q1.repnr = q2.repnr 	0.0482973986580914
14586739	33283	checking if a timeslot/booking is taken	select * from server where serverip not in (select serverip   from booking  where    (startat <= '2013-01-30 08:00:00' and expiresat >= '2013-01-30 08:00:00') or    (startat <= '2013-01-30 09:00:00' and expiresat >= '2013-01-30 09:00:00') or    (startat >= '2013-01-30 08:00:00' and expiresat <= '2013-01-30 09:00:00')) 	0.215074635351622
14587294	16940	count(*) on three tables	select  s.statename,          count(distinct c.dict_id) district_count,         count(distinct c.city_id) city_count from city c inner join district d     on c.dict_id = d.dict_id inner join state s     on s.stateid = d.stateid group by s.statename 	0.0241360794683046
14587906	20734	postgres: get next free id inside a table in a specific range (not using sequences)	select i from t_user right join generate_series(0,1000) as i on (c_id=i)  where c_id is null; 	0
14587974	41255	mssql join with itself	select    id,     null as copy_id from    t1  where   exists (select * from t2 where t1.id = t2.id) union all select    t1.id,    t2.related_id from    t1     inner join t2    on t1.id = t2.id 	0.697714354667224
14588675	5829	oracle join - return non-joined column	select m.id1, m.id2, r.char1, r.char2 from mapping m     join result1 r on m.id2 = r.id2 	0.293398713910187
14588799	28045	mysql sub query with multiple rows returned	select user_id, session, zip, price, city, state, post_id, category, shortdesc,  fpi  from post where zip in (select distinct zipcode from zip where  (latitude between 27.747 and 28.147) and (longitude between -82.657 and -82.257)) 	0.130199974729005
14588869	38840	how to select rows based on a column value i don't have, but that exists in the same row as a column value i do have?	select m1.* from movies m1 inner join movies m2      on m1.movie_author = m2.movie_author         and m2.movie_name='movie name' 	0
14588882	31959	select for items meeting both of two criteria in sql	select distinct t.tag_id from tag_blink_history t    join tag_blink_history t2 on t.tag_id = t2.tag_id and (t.x_location <> t2.x_location or t.y_location <> t2.y_location) where (t.locate_time > '2013-01-29 11:05:51'        and t.locate_time < '2013-01-29 11:06:56'        and ((t.y_location*3.28 > 61) and (t.y_location*3.28 < 67.5))        and ((t.x_location*3.28 > 14.5) and (t.x_location*3.28 < 17.5)))       and (((t2.y_location*3.28 > 70) and (t2.y_location*3.28 < 75))        and t2.locate_time < '2013-01-29 11:06:50' ) order by t.tag_id desc 	0.000295496249592285
14589716	33976	locks and delete in sqlserver when there are no rows to delete	select * into dbo.kablatz   from adventureworks2012.sales.salesorderheader; set nocount on; dbcc freeproccache with no_infomsgs; dbcc dropcleanbuffers with no_infomsgs; print ' dbcc traceon(1200,3604,-1) with no_infomsgs; if exists (select 1 from dbo.kablatz where orderdate < '20100101')   delete dbo.kablatz where orderdate < '20100101'; dbcc traceoff(1200,3604,-1) with no_infomsgs; dbcc freeproccache with no_infomsgs; dbcc dropcleanbuffers with no_infomsgs; print ' dbcc traceon(1200,3604,-1) with no_infomsgs; delete dbo.kablatz where orderdate < '20100101'; dbcc traceoff(1200,3604,-1) with no_infomsgs; go drop table dbo.kablatz; 	0.0111744243835046
14591746	3190	sql finding all rows where column is greater than one month and a certain date	select * from yourtable where datea < dateb   and   (     dateadd(day, 14, dateadd(month, datediff(month, 0, datea)+1, 0)) < dateb   ) 	0
14591779	24654	how to represent cross apply and split string in mysql	select   books.bookid,   books.book,   bookauthors.authorid,   bookauthors.author from books   left join bookauthors on (find_in_set(bookauthors.authorid, books.authors) <> 0) 	0.175682139051597
14592623	4486	linking tables from sql, query yields errors.	select intro.user_id, intro.date, intro.message_id, intro.intro from intro where user_id = {$uid} union select messages.user_id, messages.date, messages.message_id, messages.msg from messages order by date desc 	0.280890725514517
14593807	13432	insert into a table using the select statement and from function	select [col1],[col2],[col3],[col4],dbo.function(parameter), sysdatetime(), upper('username')   from table2 	0.0109563538182393
14594657	25048	postgresql search using only alphanumeric characters	select * from table where translate(lower(whatido), tanslate(lower(whatido), 'abcdefghijklmnopqrstuvwxyz', ''), '') = 'stacks' 	0.0950620681475287
14594890	30541	mysql find keywords in text	select * from tenktable  where 'the quick brown fox jumps over the lazy dog' like concat('%',keyword,'%') 	0.0793558607398309
14595737	1487	selecting records with only one value occurring within a range	select custacct, min(purchaseweekenddate), max(purchaseweekenddate), eggplantspurchased from (select t.*,              (select min(purchaseweekenddate)               from t t2               where t.custacct = t2.custacct and t.eggplantspurchased <> t2.eggplantspurchased and t2.purchaseweekenddate > t.purchaseweekenddate              ) as nextdate       from t      ) t group by custacct, nextdate, eggplantspurchased 	0
14596040	13336	not select bottom row	select   min ([main].[start]) as [stop_begin],   [main].[end] as [stop_end],   datediff(s, min([main].[start]), [main].[end]) as [interval_second] from (   select     [starts].[start],     min([ends].[timestamp]) as [end]   from   (     select       [timestamp] as [start]     from [alerts]     where [status] = 0   ) as [starts] left join [alerts] as [ends]   on  [starts].[start] < [ends].[timestamp]   and [ends].[status] <> 0   group by     [starts].[start] ) as [main] group by   [main].[end] order by 1 	0.0142619318711877
14596245	23373	sql - where clause matching only one condition	select  a.*,         coalesce(b.culture, c.culture) culture,         coalesce(b.name, c.name) name from    tablea a         left join   tableb b             on a.id = b.a_id and                 b.culture = 2         left join   tableb c             on a.id = c.a_id and                 c.culture = 1 	0.0205831621652428
14596456	23015	mysql sum based another calculated filed condition	select users.username, sum(lists.lists_var), from users inner join lists on users.userid = lists.user_id inner join (select list_id, sum(multiplier) mult_total from details group by list_id) d on d.list_id = lists.list_id and d.mult_total > 3 group by users.username 	0.000731378124584191
14598953	12666	query to get data from two tables in sql server	select dept.name, count(emp.id) as timesoccurring  from departments dept inner join employees emp on emp.dept_id = dept.id group by dept.name order by timesoccurring 	0.00056297644004491
14600755	6348	mysql - join 2 tables with full rows on left table	select  a.*, b.value from    attributes a         left join attribute_values b             on a.id = b.attr_id and b.uid = 1 	0.0343710937212208
14600945	25255	change these 2 queries to single query?	select id, order_name, order_ownurl, order_category, order_id,count(distinct order_id) from `order_details` where ordered_name='nikon d3200' order by ordered_price asc 	0.039176630054156
14601516	28708	find similar results to a given result from single table in mysql	select yt.* from yourtable as yt join  (select * from yourtable yt2 where id = $id) yt3 on yt.gender = yt3.gender and yt.age = yt3.age and yt.country = yt3.country 	0
14602068	15687	mysql: get count value in joins and if else	select  p.who_id, p.who_name, count( r1.give_id ) , count( r2.rec_id )  from  friends p  left join transaction r1  on p.who_id = r1.give_id  left join transaction r2  on p.who_id = r2.rec_id where  p.whom_id = 1  group by p.who_id 	0.0551538051426843
14603017	19123	select distinct rows based on 3 distinct columns	select min(id), userid, cc, cop  from table  group by userid, cc, cop; 	0
14603979	18141	how to format a sql server date according to a specific pattern?	select convert(varchar(10), getdate(), 103) + ' ' + convert(varchar(8), getdate(), 108) 	0.000566284105177996
14604399	26991	sql multiple lookups from join	select cust_country.countryname,    prov_country.countryname,    prod_country.countryname from   tblcustomer cu    inner join tblprovider pr      on cu.provid = pr.provid    inner join tblproduct po      on pr.prodid = po.prodid     inner join tblcountry cust_country      on cu.customercountryid = cust_country.countryid    inner join tblcountry prov_country      on pr.customercountryid = prov_country.countryid    inner join tblcountry prod_country      on co.customercountryid = prod_country.countryid 	0.33240702643771
14605382	26814	how to calculate total weight of all components in oracle	select componentid,          (select sum(cs.weightkg)             from component c2, componentstats cs            where c2.componentstatsid = cs.componentstatsid                start with c2.componentid = c1.componentid          connect by prior c2.componentid = c2.fkcomponentid) sum_weightkg from component c1 start with c1.fkcomponentid is null connect by prior componentid = fkcomponentid; 	0
14605754	29532	sql exclude inner join table	select distinct p.businessid from phop p    left join phop p2 on p.businessid = p2.businessid and p2.product_type <> 'a' where p2.businessid is null 	0.274802142301572
14606738	25477	grouping resultset - mysql	select ifnull( sum( if( book_status_fk > 4, 1, 0 ) ), 0), ifnull( sum( if( book_status_fk <= 4, 1, 0 ) ), 0 ) from books 	0.128453066567688
14606779	12152	query for multiple count values	select  m.id, m.display_name, count(*) totalcomments from    comments cm         inner join members m             on cm.commenter_id = m.id group   by m.id, m.display_name having  count(*) =     (         select  count(*) totalcount         from    comments         group   by  commenter_id         order   by totalcount desc         limit 1     ) 	0.0440402561364329
14607565	15346	searching text, returning multiple word matches	select id, 'word1' from message_table where filter is not null and message like '%word1%'   union select id, 'word2' from message_table where filter is not null and message like '%word2%'   union select id, 'word3' from message_table where filter is not null and message like '%word3%'; 	0.0727306895342729
14608098	5309	date_format() sql return 0 rows	select *  from (    select themeid, name,       date_format(begindate, '%m-%d'),        date_format(enddate, '%m-%d'),       date(begindate + interval (2000 - extract(year from begindate)) year) newbegindate,       date(enddate + interval (2000 - extract(year from enddate)) year) newenddate from theme ) a where newbegindate <= date(now() + interval (2000 - extract(year from now())) year)   and newenddate > date(now() + interval (2000 - extract(year from now())) year) 	0.1074556730675
14609157	5663	mysql, min date query	select   m.* from mytable as m   inner join (select         id,         min(id)           from mytable           group by id) as l     on l.id = m.id 	0.131167057867068
14612010	11569	display 'closed' if is_closed is true	select    < some column(s) here >,    case when is_closed = 1         then 'closed'         else closing_time end as closing_time_or_closed ... 	0.0189387114466942
14612299	11952	grouping by timeframes with a modifier that changes over time	select pat_id, min(cal_date), max(cal_date), min(drug_qty) from (select t.*,              cast(cal_date as datetime) - row_number() over (partition by pat_id, drug_qty order by cal_date) as grouping       from #test t      ) t group by pat_id, grouping 	0.107244338390897
14613811	28479	sql server simple find/replace on text string within a table column	select * from dbo.my_table 	0.241659522970037
14615032	2357	sql - remove duplicates from left join	select          objectid     , pkid     , t2.subdivisio,     , t2.asbuilt1 from        dbo.table1 as t1 outer apply (     select  top 1 *     from    dbo.table2 as t2     where   t1.pkid = t2.fkid     ) as t2 	0.220784853331299
14615374	5658	how to check if a view exists that uses a table	select  * from    information_schema.view_table_usage where   table_schema = 'dbo'       and   table_name   = 'yourtablename' 	0.0177056211513635
14616984	35472	limiting numbers to a maximum value in mysql	select least(score, 10) from scorestable 	0.000456701734339488
14617408	30420	mysql subqueries to join tables	select  a.*, c.*    from    tablea a         inner join tableb b             on a.id_a = b.id_a         inner join tablec c             on b.id_c = c.id_c 	0.644296529022433
14619607	15190	how can i fetch and compare time of related post from database?	select * from table_name order by col_time_stamp desc; 	0
14620833	37346	no match when using a subselect and comparing two varchar columns	select cust_number from anothercustomertable where cust_number is not null 	0.00302116320560284
14621596	18598	max function in sql	select * from t where `time` = (select max(`time`) from t) 	0.620872971131696
14621713	1309	having different between sybase and postgres	select id, version from (       select id,               version,               max(version) over (partition by id) as max_version       from local_tbl ) sub where version < max_version 	0.0264458443446821
14623246	764	sql data in one field separated by coma	select item, group_concat(size) from the_table group by item; 	0.000309741494719562
14625986	39052	getting average values with respect to the date in sql	select round(avg(rate_per_sqft)) as ratepersqft    from ratepersqft  where common_location = 'ecr' and        1 <= month(date) and month(date) <3          group by common_location union select round(avg(rate_per_sqft)) as ratepersqft    from ratepersqft  where common_location = 'ecr' and        3 <= month(date) and month(date)<6          group by common_location union select round(avg(rate_per_sqft)) as ratepersqft    from ratepersqft  where common_location = 'ecr' and        6 <= month(date) and month(date)<9          group by common_location union select round(avg(rate_per_sqft)) as ratepersqft    from ratepersqft  where common_location = 'ecr' and        9 <= month(date) and month(date)<=12        group by common_location; 	0.000190192284816019
14627335	8953	sql replace cell value with column name and avoid null values	select  pf ,       hiredate ,       replace(             iif(writing is null;'';'writing, ') +             iif(swimming is null;'';'swimming, ') +             iif(kickoff is null;'';'kickoff, ') +             iif(shopping is null;'';'shopping, ') + '$';             ', $'; '') from    agents a join    skills s on      s.pf = a.pf 	0.00196988813850748
14628410	14664	ora-01446 occurs if i try to select random rows using sample clause in oracle	select t1.columna from  (select columna from (select distinct tt1.columna,  tt2.columnc   from table22 tt2, table11 tt1  where tt2.columnc = tt1.columna) sample(1) where rownum <= 1000)  t1  join table2 t2  on (t1.columna = t2.columna)  where t2.columnb is not null 	0.0518309577411984
14629829	28167	joining two sql statements	select   tableb.entry_id, from   tableb   inner join tablea     on tableb.entry_id = tablea.entry_id     and tablea.cat_id = "" group by   tableb.entry_id order by   count(*) desc 	0.136547923939162
14630416	7854	find unused id in database using c# and sql	select      #temp.id from        #temp left join   table1 on #temp.id = table1.id where       table1.id is null 	0.0083459795449495
14630698	3970	calculate and group by billabletype?	select     sum(billingstimes.actualtotaltime) as expr1, tasks.taskname, billabletype.billabletypename from         billingstimes inner join                       aspnet_users on billingstimes.userid = aspnet_users.userid inner join                       billabletype on billingstimes.billabletypeid = billabletype.rank inner join                       tasks on billingstimes.taskid = tasks.taskid where     (billingstimes.taskid = 10045) and (aspnet_users.userid = '178db2a8-be1d-48e0-9ebc-f64f7b1ff63e') and (convert(date, billingstimes.dateofservice)                        = '01/29/2013') group by billingstimes.billabletypeid, tasks.taskname, billabletype.billabletypename 	0.0757866605373371
14631300	5974	mysql, how can i group on group_concat?	select gc_values      , count(*)   from       ( select a.id             , group_concat(v.value) gc_values          from asset a          join `values` v             on v.id = a.id         group            by a.id      ) x  group     by gc_values; 	0.513625616384742
14632566	31297	mysql: finding owner of most from list	select     `players`.`name`,     count(`lookid`) as `num_items` from `items` inner join `players` on `players`.`id` = `items`.`ownerid` where `players`.`lvl` < y and `lookid` in (81411,81421 (lots of it) 81551,81611) group by `ownerid` order by `num_items` desc limit 15 	4.90102413930582e-05
14633618	10998	sql multiple selects on same table and column for data filtering	select distinct(ld1.lead_id) from lead_detail ld1 inner join lead_detail ld2 on (ld1.lead_id = ld2.lead_id) where ld1.field_number = '4' and ld1.value = 'yes' and ld1.form_id = '1'  and ld2.field_number = '5' and ld2.value = '18-24' and ld2.form_id = '1' 	0.000882300266828635
14633720	10287	calculate profit based on first-in, first-out pricing	select s.sku,        (marginpos - sum(case when s.totalqty < p.cumeqty - p.qty then p.price * p.qty                              when s.totalqty between p.cumeqty - p.qty and p.qty                              then s.price * (s.totalqty - (p.cumeqty - p.qty))                              else 0                         end)        ) as margin from (select s.sku, sum(price*qty) as marginpos, sum(qty) as totalqty       from sales s      ) s left outer join      (select p.*,              (select sum(p.qty) from purchase p2 where p2.sku = p.sku and p2.sale_id <= p.sale_id              ) as cumeqty       from purchase s      )      on s.sku = p.sku group by s.sku, marginpos 	0.00285299430518464
14634510	39965	mysql combine groups within a single table	select distinct t1.user from mytable t1 join mytable t2 using (user) where t1.region = 10 and t1.field1 in (38, 79, 126) and t2.region = 10 and t2.field1 in (80, 126) 	0.000954144485327824
14634779	2464	sql - comment system with revision history	select     c.commentid,     c.authorid,     c.parentid,     c.created,     cc.created as updated,     cc.content from comments as c join commentscontent as cc   on cc.commentid = c.commentid inner join (   select max(created) maxdate, commentid   from commentscontent   group by commentid ) cc2   on cc.created = cc2.maxdate   and cc.commentid = cc2.commentid where c.ownerid = 1 	0.659252150741979
14635948	14956	counting and grouping same named column in different tables (mysql)	select age, count(*) from (select id, age, gender from table1 union all       select id, age, gender from table2      ) t group by age 	5.98557666440959e-05
14636693	8636	should order by change the result set?	select u.node_id from users u join (     select node_id     from users      limit 100 ) us on u.node_id = us.node_id order by u.node_id 	0.229231442632731
14641313	20153	sql - user-management --> export/import users via script	select 'drop user ' || username || ';'  from   dba_users u where  not exists (select null                     from   dba_objects o                     where  o.owner = u.username); 	0.398534054614643
14641572	29904	counting and grouping same named column in different tables (where clause from only one table)	select age, count(age) cnt from (     select         t2.age      from table1 t1         join table2 t2             on t1.id = t2.table1id     where t1.published = 1     union all     select age     from table1     where published = 1 ) a group by age 	0
14642186	23273	sql server - get ids of summed rows	select sum(amount) sum,         (         stuff((             select  distinct ',' + cast(a.id as varchar(100))             from    t_vouchers a             where   a.isactive = 1             for xml path('')             ),1,1,'')         ) ids  from t_vouchers  where isactive = 1 	0
14642957	2844	filed in mysql calculated from other calculated fields	select comp1, comp2, (comp1/comp2) as percent from( select complicated_calculation1 as comp1,  complicated_calculation2 as comp2 from table) as t 	0.000885757524614989
14642991	33353	sql how to join two different tables columns as result	select t2.*, t1.name_column  from table2 t2       inner join table1 t1 on t2.fk_id1 = id_column1  where t1.id_column1 = 1 	0.000448542917372589
14644023	11223	dynamic where in a sql select query	select* from table  where (picod=1 and dvdt= 'xxxx') or  (picod=2 and cddt= 'xxxx') or ....... (xxxx) or.... 	0.756010896517121
14644726	13805	how to select from where last record = x?	select * from dossiers b join dossiers_etat as c on b.id = c.id_dossier where b.disp = "y" and c.open = "y" and c.incharge = "-" and c.date = (select max(date) from dossiers_etat where id_dossier = c.id_dossier) order by b.id desc 	0
14645764	25657	how do i find the makers that sell one type but not another?	select maker from product group by maker having sum(case when type = 'pc' then 1 else 0 end) > 0    and sum(case when type = 'laptop' then 1 else 0 end) = 0 	0.000152631929579296
14645969	27024	how to group same field under one field using sql query	select * from t order by case when hod_code='p00212' then emp_no else hod_code end,          case when hod_code='p00212' then 0 else 1 end 	0.000459569645688925
14646000	6560	mysql sorting by most votes	select name from users inner join votes      on users.id = votes.user_id group by users.id order by sum(vote) desc 	0.0300359047865104
14646085	17558	changing the value of a `*_id_seq` table in postgresql	select setval('myapp_mymodel_id_seq', 40); 	0.00130365937574219
14646577	14691	forcing zeros to appear in count	select  r.regionname ,       v.vehiclename ,       count(res.vehiclename) as vehiclecount from    (         select  distinct regionname         from    @tbl_results         ) r cross join          (         select  distinct vehiclename         from    @tbl_results         ) v left outer join         @tbl_results res on      r.regionname = res.regionname         and v.vehiclename = res.vehiclename group by         r.regionname ,       v.vehiclename order by         r.regionname ,       v.vehiclename 	0.0605896918580353
14646584	22325	determining the actual filenames of the tables in postgresql at file system level	select t.relname, current_setting('data_directory')||'/'||pg_relation_filepath(t.oid) from pg_class t   join pg_namespace ns on ns.oid = t.relnamespace where relkind = 'r' and ns.nspname = 'public'; 	0.00113523878714359
14647221	38914	sql return row if no result found	select person.name, coalesce(car.name, 'no car') from person left outer join car on person.id = car.person_id 	0.0035582799268205
14648029	27485	non standard join	select user.user_id, j1.user_param, j1.user_value, j2.user_param, j2.user_value from user join users_info j1 on user.user_id = j1.user_id join users_info j2 on user.user_id = j2.user_id where j1.user_param != j2.user_param group by user.user_id 	0.480764175047044
14648405	15333	joining two select queries from the same table	select id, valueheading1, valueheading2 from (  select *  from dbo.test28  where valueheading in ('valueheading1', 'valueheading2')  ) x  pivot  (   max(value)   for valueheading in ([valueheading1], [valueheading2])   ) p 	5.04636229896941e-05
14649434	30357	mysql select week range from database	select text from dates where year*100 + week between $weekmin+$yearmin*100 and $weekmax+$yearmax*100 	7.92565394536343e-05
14650447	10799	select distinct without ordering the rows	select * from (select distinct column1, colum2        from table....        where....) a order by newid() 	0.0056583401933007
14652407	4119	how to count number of times a customer visited for each day in the search	select  customers.sbarcode ,         cast(floor(cast(tickets.dtcreated as float)) as datetime) as dtcreateddate ,         count(customers.sbarcode) as [number of scans] from    tickets         inner join customers on tickets.lcustomerid = customers.lcustomerid where   ( tickets.dtcreated between convert(datetime, '2012-12-01 00:00:00', 102)                             and     convert(datetime, '2013-01-31 23:59:59', 102) )         and ( tickets.dbltotal <= 0 ) group by customers.sbarcode ,         cast(floor(cast(tickets.dtcreated as float)) as datetime) having  ( count(*) > 1 ) 	0
14656105	19990	data comparison query	select newtax.[zipcode],        newtax.city,        newtax.county,        newtax.state,        newtax.combinedsalestax - oldtax.combinedsalestax as change,        newtax.combinedsalestax,        oldtax.combinedsalestax from   oldtax        inner join newtax                on ( oldtax.[zipcode] = newtax.[zipcode] )                   and ( oldtax.city = newtax.city )                   and ( oldtax.county = newtax.county ) where  nz(newtax.combinedsalestax,0) <> nz(oldtax.combinedsalestax,0) 	0.486935401729065
14656919	27561	can you union without overriding in mysql?	select name, 'person' from tablea union select workplace, 'workplace' from tableb 	0.526028284175198
14657206	10217	magento: a foreign key constraint fails after update 1.4 -> 1.7	select * from catalog_category_product ccp left join catalog_category_entity cce on ccp.category_id = cce.entity_id where cce.entity_id is null 	0.00864417254025026
14657741	19761	sql statement which aggregates last post author id	select postcounts.topic_id,        count_posts,        author_id as last_answer_by from   (select topic_id,           count(*) as count_posts,           max(id) as lastpost    from forum_posts    group by topic_id) postcounts inner join forum_posts on lastpost = forum_posts.id 	0.000225947930323564
14657786	30278	group by each year with missing years	select       yearsyouwant.requireyear as dateyear,       sum( rce.sick_size + rce.dead_size ) as cases    from       ( select @nyear := @nyear +1 as requireyear            from report_case_ext,                 ( select @nyear := year( curdate()) -5 ) sqlvars            limit 5 ) as yearsyouwant          left join             report_case_ext rce                on yearsyouwant.requireyear = year( rce.event_date )    group by        yearsyouwant.requireyear 	5.52199374353816e-05
14660181	12996	trying to find out subscription end month notification	select   count(subend) as count, curdate()  from subdur   where  status='active' and  subend between (date_sub(curdate(),interval 1 month)) and curdate()  order by subend 	0.00215959787767956
14660729	32835	how to get the last parent from table for the following scenario in sql server 2000?	select @newparent = parent_parent_id form dbo.table2 where parent_id = @currentparent; 	0
14661852	16312	query to return concatenated result in mysql	select group_concat(keyword separator ' ') from keywords 	0.0268998832333423
14662040	27082	find which entry occurs maximum number of time in mysql	select id, brand from (   select t.id, t.brand, s.totalcount,            count(*) * 1.0 / s.totalcount percentage   from   t          inner join         (           select id, count(*) totalcount           from   t           group  by id         ) s on t.id = s.id   group  by id, brand   having (count(*) * 1.0 / s.totalcount) > 0.5 ) r 	0
14662146	23568	how to drag an average result in mysql till new values are added?	select d.day as day,        sum(case when n.day = d.day then n.net else 0 end) as net,        avg(n.net) as avg from dates d left join (select day, sum(sales) as net            from file f            group by day) n on n.day <= d.day group by d.day order by day desc 	0
14662705	12108	trying to create relation in navicat	select klantid from klant left join geerdink_new on geerdink_new.dossierklantid = klant.klantid where dossierklantid is null; 	0.44637912747904
14663317	12577	sqlite - negative value by substracting months of different years	select round((julianday(date('now')) -          julianday(dates))/30) as monthsdiff from demo; | monthsdiff | |       11.0 | |        2.0 | 	0
14665117	21400	how should i alter a working table and add a column to track times?	select * from table_name where timestamp_column >= unix_timestamp(now()) - 60 * 60 * 24 * 90 	0.030694428971571
14665345	27602	selecting the authors who have published in all the years	select  * from    pubs where   author in         (         select  author         from    pubs         where   publicationyear between 2000 and 2010         group by                 author         having                 count(distinct publicationyear) = 11         ) 	0
14668319	23600	mysql avg timediff of multiple rows	select  session.why as reason,  count(session.why) as count,  sec_to_time(avg(timediff(t.fin, session.signintime))) as time from session  left join (select support.session_id, max(support.finishtime) as fin  from support  group by support.session_id) as t      on session.session_id = t.session_id  where session.status = 3   group by session.why  order by session.signintime desc 	0.00639492646565818
14669205	34960	mysqli -> num_rows always returns 1	select count(*) 	0.783757696066829
14671722	17094	sql select column as substring at first occurrence of characters?	select distinct on (split_part(table.column1, ' )', 1)) table.column2  from table  order by split_part(table.column1, ' )', 1) 	5.18214550119952e-05
14674171	26870	sql query to filter unique status records	select  secondary_idn from    tablename group   by secondary_idn having  sum(case when status = 'pending' then 1 else 0 end) = count(*) 	0.00162455459587523
14674583	16038	php mysql - selecting values from table 1 which are not in table 2	select *  from club_judges  where `club`='test club'  and `bg_number` not in (select bg_number from competition_judges where competition='test competition') order by name 	0
14674731	27005	need to select from multiple tables	select  concat(m.manufacturer, ' ', p.model, ' ', p.storagesize, ' - ',             o.name, ' - ', p.price) from    phones p join    manufacturer m on      p.manufacturerid = m.manufacturerid join    os o on      p.osid = o.osid 	0.0184064246930141
14674949	9830	mysql query for three tables	select  a.person_id,          max(c.value_id) value_id,          b.attribute_name ,           max(c.value) value from    people a         cross join attributes b                left join `values` c             on  a.value_id = c.value_id and                 b.attribute_name = c.attribute_name group by a.person_id, b.attribute_name 	0.168671637510724
14676806	12245	mysql select query with conditions	select <field list>   from table t1 join table t2 on t1.id = t2.batch_id where start_ts between <date 1> and <date 2> 	0.519043494668181
14677683	7896	selecting all rows in sql, with specific criteria	select  c.category,   count(r.rating) as totalcount from ratings as r left join items as i    on i.items_id = r.item_id left join users as u    on u.user_id = r.user_id left join master_cat as c    on c.cat_id = i.cat_id where  r.user_id = '{$user_id}' group by c.category order by totalcount desc 	7.00883877749141e-05
14678056	9016	sql getting max id field on a left join	select messages.*, t2.photo from messages left join (select userid, max(id) as maxid            from tblimages            group by userid) as t1 on messages.user_id = t1.userid left join tblimages as t2 on t2.id = t1.maxid order by messages.msg_id desc 	0.0148315417746538
14678140	19444	formatting sql result as a sum	select resdate,sum(res.address),sum(res.value) from ( select distinct     left(changes.date_time, 6) as 'date',     changes.address as 'address',     (case when changes.address in (18) then - max(changes.value * types.multiplier) else max(changes.value * types.multiplier) end) as 'value' from sensor.changes inner join sensor.types on changes.type = types.idx where     changes.address in (1, 4, 8)     and changes.date_time >= '12110100000000'     and changes.date_time <= '13050100000000' group by left(changes.date_time, 6),     changes.address order by changes.idx ) as res group by res.date 	0.497117060671517
14678869	11124	sql query - multiple count on same column with different values from nested select query	select studentid,  sum(case when unapproved =1 then 1 else 0 end) as late,  sum(case when unapproved =2 then 1 else 0 end) as absent  from results where  studentid in (select studentid from [results] where studentyearlevel='10' and date > 20130101)  group by studentid 	0.000221425434995467
14680743	26834	mysql select within select on same table	select * from insecta10000 i    join    (   select genus   from insecta10000   where pindent > 60     and coverage > 60     and qseqid in ("diaci0.9_transcript_99990000013040", "diaci0.9_transcript_99990000022677")   group by genus   having count(*) = 2   ) i2 on i.genus = i2.genus 	0.00212265844255144
14681811	32333	maximum value in column in database	select max(orderid) from proj_table; 	0.000495510185174071
14683485	30516	tag based sql query	select * from images inner join images_tags_link a on images.image_id = a.image_id_fk and a.tag_name_fk = 'blue' inner join images_tags_link b on images.image_id = b.image_id_fk and b.tag_name_fk = 'landscape' select images.image_id, images.image_name, count(*) as tag_count from images inner join images_tags_link a on images.image_id = a.image_id_fk  where a.tag_name_fk in ('blue', 'landscape') group by images.image_id, images.image_name having tag_count = 2 	0.0323673297237305
14683556	34464	sql server 2008 count	select  trid ,       tsid ,       count(*) as total ,       sum(case when failsteps = 0 and warnsteps = 0 then 1 else 0 end) as pass ,       sum(case when failsteps > 0 then 1 else 0 end) as fail ,       sum(case when failsteps = 0 and warnsteps > 0 then 1 else 0 end) as warning from    (         select  trid         ,       tsid         ,       tcid         ,       sum(case when statusid = 1 then 1 else 0 end) as passsteps         ,       sum(case when statusid = 2 then 1 else 0 end) as failsteps         ,       sum(case when statusid = 3 then 1 else 0 end) as warnsteps         from    results         group by                 trid         ,       tsid         ,       tcid         ) as testcases group by         trid ,       tsid 	0.615497986429681
14684747	34183	search the last comment in a many-to-many relation	select *   from post as p     left join post_comment as pc on (pc.post_id = p.id)     left join comment as c on (c.id = pc.comment_id)     left outer join             (post_comment as pc2                 inner join comment as c2 on (c2.id = pc2.comment_id)             ) on (bc2.post_id = p.id and c1.created_at < c2.created_at)   where c2.id is null 	0.00386314473059758
14686007	13523	combine two sql select into one	select      sum(case when t1.flag1 = false and t2.flag2 = true then 1 else 0 end) count1,     sum(case when t1.flag1 = true and t2.flag2 = false then 1 else 0 end) count2 from      table1 t1      inner join table2 t2 on t2.id = t1.rowid 	0.000509411820476553
14689238	27161	get a row, then others order by id	select * from table order by id = 5 desc, id asc 	0
14689975	29219	advance select query in mysql	select cat_id from connections c where  (id between 1 and 5 and (c.connector_id = id or c.user_id = id)    and  (c.connector_id = oid or c.user_id = oid))  or id > 5 and (oid = user_id and id = connector_id) 	0.655424555914567
14691220	17888	postgres sql, date_trunc without extra zeroes	select date_trunc(...)::date; 	0.639944588070471
14691284	21640	how to write a hql to get all records without permissions	select p from project p where p.id not in   (select authorization.project.id    from projectauthorization authorization    where authorization.user = :currentuser) 	0.00130148481023744
14692373	27800	create categories column names from one column in sql	select  id,         max(case when type = 'install date' then date end) installdate,         max(case when type = 'complete date' then date end) completedate,         max(case when type = 'closed date' then date end) closeddate from oracletable group by id order by id 	0
14693296	461	a query to show me the number of patients discharged and re-enter within 72 hours for the same cause	select distinct h1.patient from   hospital h1 join hospital h2 on h1.patient = h2.patient where  h1.[in] < h2.[in] and    h2.[in] < dateadd(hour, 72, h1.[out]) and    h1.reason_id = h2.reason_id 	8.14174279266833e-05
14694598	3493	find difference between two values for each row where "number" column value is same	select a.number, a.name, (a.price - b.price) as pdiff from table a, table b where a.number = b.number      and a.month = montha      and b.month = monthb; 	0
14694774	21706	mysql - private posts display correct count	select  t.thread_id, t.post_count,  count(if(isnull(pv.private_id) and p.private='1' and p.user_id<>'1', null, 1))  from threads as t join posts as p on p.thread_id = t.thread_id  join users as u on u.user_id = p.user_id  left join private as pv on pv.post_id = p.post_id and pv.authorized_user_id='1'  join users as auth on auth.user_id = '1' where p.user_id='3' and t.user_id='3' group by t.thread_id; 	0.00589022450759696
14695207	33114	substring of value with several 0s	select 'r' +  cast(value - 5000000 as varchar(6)) from table 	0.0195428739324572
14696566	38124	selecting 5 subcategories per category	select  parent.name as category ,       child.name as subcategory from    (         select  name         ,       parent_id         ,       @rn := if(@cur = parent_id, @rn+1, 1) as rn         ,       @cur := parent_id         from    product_category pc         join    (select @rn := 0, @cur := '') i         where   level = 2         order by                 parent_id         ,       id         ) as child join    product_category as parent on      child.parent_id = parent.id where   child.rn < 3 	7.25376714549415e-05
14696793	39135	sql join on a column like another column	select     a.first_name,     b.age from names a join ages b on b.full_name like '%' + a.first_name + '%' 	0.0183995936980318
14697348	18550	select all columns from table with 1 distinct column and a where condition	select b.*  from yourtable b inner join   (select min(veh_id) as minv,  glass_id as g    from yourtable    group by glass_id) as d   on b.glass_id = d.g and b.veh_id = d.minv where b.glass_id like  '%db00%' 	0
14698137	1218	mysql_query from multiple tables with round and math	select eit.name,         eit.type_id,         round(eit.jita_price_sell, 2) as jita_price_sell,         round(eis.price, 2)           as price,         eis.qty_avail,         eis.sation_id,         eis.type_id  from   eve_inv_types eit         join `items_selling` eis           on eit.type_id = eis.type_id              and eis.station_id = '61000746' 	0.0598709831320078
14700770	21607	natural sort with sql server	select ptnt_vst_csno  from   table_name  order  by substring(ptnt_vst_csno, 1, charindex('p', ptnt_vst_csno)),            convert(int, substring(substring(ptnt_vst_csno,                                   charindex('p', ptnt_vst_csno),                                   len(                                                ptnt_vst_csno)), 2, len(                         ptnt_vst_csno))) 	0.763139063574449
14701103	2389	getting different column names from 2 tables in sql server	select i.itemname, i.itemcost, s.salesname, s.salesdate  from item as i, sales as s; 	0
14703213	31944	how to get all values of a certain row in a "group by" in sql?	select   `entries`.`id`,    count(`reports`.`id`) as `amount`,     group_concat(`reports`.`reason` separator ', ') as `reasons`  from   `entries` cross join `reports`   on (`entries`.`id` = `reports`.`entry_id`)  group by   `entries`.`id` order by `amount` desc 	0
14704186	25264	how can i get the month number (not month name) from a date in sql server?	select datepart(m, getdate()) 	0
14704983	33936	t sql case statement with between to show all	select [from],         [to],         streetname,         number  from   t1         left outer join t2                      on t2.number >= t1.[from]                     and t2.number <= t1.[to] 	0.0727530725087958
14707262	31570	find posts of user grouped by month, unixtime	select     date_format(from_unixtime(`date`), '%y-%m') as yearmonth,     username,     count(*) as posts from   media group by     date_format(from_unixtime(`date`), '%y-%m') as yearmonth,     username 	0
14708624	33853	list all the stored procedures which have no parameters	select schema_name(schema_id) as schema_name,        name from   sys.procedures pr where  not exists(select *                   from   sys.parameters p                   where  p.object_id = pr.object_id) 	0.00135079139272309
14708995	29146	select dates where in(null,>=sysdate)	select *  from dates_tbl where dates is null or dates >= sysdate 	0.0949204755676402
14709661	10713	sqlite query for dates equals today	select * from mytable where date(datetime(datecolumn / 1000 , 'unixepoch')) = date('now') 	0.00675104595838137
14709689	9236	searching unique id in multiple tables	select case when exists(select 1 from tablec where id = @id) then '3'             when exists(select 1 from tableb where id = @id) then '2'             when exists(select 1 from tablea where id = @id) then 'one'        end as "level" 	0.00114891492143704
14712864	35848	how to query values from xml nodes?	select  b.batchid,         x.xmlcol.value('(reportheader/organizationreportreferenceidentifier)[1]','varchar(100)') as organizationreportreferenceidentifier,         x.xmlcol.value('(reportheader/organizationnumber)[1]','varchar(100)') as organizationnumber from    batches b cross apply b.rawxml.nodes('/casinodisbursementreportxmlfile/casinodisbursementreport') x(xmlcol); 	0.00390779187969425
14714002	7705	sql where clause for a named table	select * from  (  select ename as "name"       , to_char(sysdate,'yyyy') - to_char(hiredate,'yyyy') as age    from scott.emp ) where age = (select min(to_char(sysdate,'yyyy') - to_char(hiredate,'yyyy')) from scott.emp) / name    age scott   26 adams   26 	0.420989172855482
14714341	35894	sql query for all records at least 30 days old	select usernm as [userid], max(eventdt) as [last log-in date] from dbo.usreventlog where eventdt < getdate() - 30     and (usernm not like 'user1') and (usernm not like 'user2')     and (usernm not like 'user3') and (usernm not like 'user4') group by usernm, eventdt 	0
14714591	37248	mysql exists and order by	select c.* from comments c join      (select l.commentid, min(likedate) as firstlikedate, max(likedate) as maxlikedate       from likes l       group by l.commentid      ) l      on c.commentid = l.commentid order by maxlikedate desc 	0.36918376687517
14715942	33661	parsing full month and year in sql	select cast('july,1999' as datetime) 	0.00697041324252212
14716744	22448	mssql - convert milliseconds since 1970 to datetime2	select    dateadd(millisecond,            cast(datemodified as bigint) % 1000,            dateadd(second, cast(datemodified as bigint) / 1000, '19700101')) from sometable 	0.0604241442627569
14718167	22392	how to count duplicates based on other column?	select      col_1,     col_2,     row_number() over(         partition by col_2 order by col_1     ) - 1 as col3 from yourtablename 	0
14718360	27088	sum between multiple tables	select c.name, sum(s.price) from services s inner join customer_services sc on cs.service_id = s.id inner join customers c on c.id = cs.customer_id group by c.id 	0.0130498673561259
14719477	6537	pull name/value from other table where id is the same	select     ogi.itemname,     distributors.name as distributor from     ogi inner join     distributors     on     ogi.distributor = distributors.id 	0
14722386	10943	get only some newest value from database table	select e_id, f_id from [the table] where [version] = (select max([version]) from [the table]) 	0
14723027	23745	getting friends update query	select     u.member_id,     u.update_action, from members m     join member_friends f         on m.id = f.logged_user_id     join member_updates u         on u.member_id = f.friend_id where m.id = :id     and u.update_hidden <> 1 order by u.update_id desc 	0.0496099217637177
14723091	34342	how to query from calibre database?	select id, title,                (select name from books_authors_link as bal join authors on(author = authors.id) where book = books.id) authors,                (select name from publishers where publishers.id in (select publisher from books_publishers_link where book=books.id)) publisher,                (select rating from ratings where ratings.id in (select rating from books_ratings_link where book=books.id)) rating,                (select max(uncompressed_size) from data where book=books.id) size,                (select name from tags where tags.id in (select tag from books_tags_link where book=books.id)) tags,                (select format from data where data.book=books.id) formats,                isbn,                path,                pubdate         from books 	0.0499176595434343
14727838	20774	get number of fields in mysql table	select count(*) totalcolumns from   information_schema.columns where  table_name = 'table1' and         table_schema = 'databasename' 	0.000107290357643932
14728094	33577	select rows based on next row in mysql	select count(*) total from (   select type,      @row:=(case when @prev=1 and type=2 then 'y' else 'n' end) as seq,     @prev:=type    from yourtable, (select @row:=null, @prev:=null) r   order by time, type ) src where seq = 'y' 	0
14729783	618	"select" selects wrong rows when umlauts are present in table	select * from textconstraint where pattern = binary 'a' 	0.0657306849794176
14729810	14884	how to retrieve foreign key column values in sql	select * from group left join sensors on group.sensorid = sensors.id 	0
14731647	14853	non repeating monthly sql	select    a.userid,    min(extract(month from a.logintime)) as month  from login_audit a where a.logintime <= '2012-12-31 11:59:59' and a.logintime >= '2012-01-01 00:00:00' group by a.userid 	0.0149937706780285
14734584	7187	sql ignore null value if a row with the same id exists	select * from mytable t1 where playerid is not null union select * from mytable t2 where playerid is null     and not exists (           select * from mytable t3 where t2.id=t2.id and t2.type=t3.type        ) 	0
14736613	18571	sql eliminate all duplicate entries when one entry fails to meet criteria	select * from recipe r where not exists (  select * from ingredientlist il                     inner join ingredients i                         on i.ingredientid = il.ingredientid                     where il.recipeid = r.recipeid                     and i.type = 'beef') 	0
14736945	23773	sql - how to get certain column with min and max id for every department?	select d.name department_name,    e.surname first_employee,   e2.surname last_employee,   t.employee_count from (     select d.iddepartment,         count(*) as "employee_count",         min(e.idemployee) as "first_employee",         max(e.idemployee) as "last_employee"     from employees e            inner join departments d              on d.iddepartment=e.department_id     group by d.name   ) t join employees e on t.first_employee = e.idemployee   join employees e2 on t.last_employee = e2.idemployee   join departments d on t.iddepartment = d.iddepartment 	0
14738410	31041	order rows where value begins with x before those that contains x	select   id,   title from song where text is not null     and title like "%foo%" order by case when title like "foo%" then 1 else 2 end, title 	0
14740438	1072	select all data include another table even if null	select e.employeeid,e.firstname,e.lastname,s.shoename,s.shoecolor,s.shoebrand     from    employee e    left join shoe s    on e.employeeid = s.employee_employeeid 	0.000153635977889727
14740692	30912	searching for an integer value in a varchar field in mysql	select (case when '1abc' = 1 then 'a' else 'b' end) 	0.00522351841241911
14741000	4320	getting next available date from database	select user_id, max(date) - 1 from (select ud.*,              (select max(date) from upload_date ud2 where ud2.user_id = ud.user_id and ud2.date < ud.date             ) as prevdate       from upload_date ud      ) ud where date(from_unixtime(ud.prevdate)) <>  date(from_unixtime(ud.date)) - 1 or       ud.prevdate is null group by user_id 	0
14741453	18092	using select distinct or alternative with a 3 table query	select distinct weekly_timecard.week_number from    weekly_timecard,    daily_calculations,    employee_profiles  where employee_profiles.employee_number = weekly_timecard.employee_number   and employee_profiles.employee_number = daily_calculations.employee_number   and weekly_timecard.week_number = daily_calculations.week_number 	0.460234182634352
14742019	15028	mysql query returning incorrect timestamp	select    s.session_id,    s.anum,    st.first,    st.last,    c.counselor,  s.why,  sec_to_time(timediff(sup.starttime, s.signintime)) as start,    sec_to_time(timediff(sup.finishtime, sup.starttime)) as 'time with counselor',    sec_to_time(timediff(sup.finishtime, s.signintime)) as total   from session s  inner join student st     on st.anum = s.anum  inner join support sup     on s.session_id = sup.session_id inner join counselors c     on sup.cid = c.cid where s.status = 3 	0.764267042391204
14744018	32112	how to do customized group by in sql	select "id",sum(decode(type,'sell',-"amount","amount")) total from table1 group by "id" 	0.313239875854696
14744489	6886	sql query to convert area in a common base unit(hectare) and then getting its sum	select sum((t.total_area / (u.converting_unit / u.base_unit) +             (t.total_area1 / (u3.converting_unit / u3.base_unit)))) as sum_total_area,        sum((t.acquired_area / (u2.converting_unit / u2.base_unit) +             (t.acquired_area1 / (u4.converting_unit / u4.base_unit)))) as sum_acquired_area,         max(u4.base_unitcode) as base_unit from dbo.total t join dbo.units u on t.total_area_unitcode = u.unit_name                                   join dbo.units u2 on t.acquired_area_unitcode = u2.unit_name                  join dbo.units u3 on t.total_area_unitcode1 = u3.unit_name                  join dbo.units u4 on t.acquired_area_unitcode1 = u4.unit_name 	0.000128323223542502
14746849	32105	convert hh:mm:ss string to number of minutes	select datediff(mi,convert(datetime,'00:00:00',108), convert(datetime,'02:47:00',108)) 	9.83818053468457e-05
14749701	16175	how to retrieve the most recent records for all ids when grouped by date	select user_id, (select total          from t        where user_id=t2.user_id              and t.timestamp <= t2.timestamp   order by t.timestamp desc limit 1) as total, timestamp from ( select user_id,timestamp from (select distinct user_id from t) t0 cross join (select distinct timestamp from t) t1 ) t2 order by timestamp,user_id 	0
14750352	18422	to format time(0) datatype	select datediff(minute, timein, timeout) 	0.274721852109374
14753322	21277	how to count columns of sql server 2008's table using c#?	select count(*) from information_schema.columns where table_name = 'yourtablename' 	0.00780703797119119
14753436	29526	sql, multiple rows to one column	select   id,   name,   max(case when month = 'december2012' then "count" end) as "december2012",   max(case when month = 'january2013'  then "count" end) as "january2013" from tablename group by id, name; 	0.000948420024137018
14753792	4530	convert a mysql query to db2 query	select x.continent, x.name, x.population  from world x   join    (     select continent, max(population) pop     from world     group by continent   ) y on x.continent = y.continent and x.population = y.pop 	0.508564463212372
14754328	22020	ordering join results when grouping	select * from   auctions as a        left join (select auction_id from winners order by auction_id limit 1) as w on a.auction_id = w.auction_id where  a.active = 1        and a.approved = 1 group  by a.auction_id order  by a.start_time desc 	0.649261676773556
14754952	39050	select last ten items from a specific row in a table	select top 10 line_id, run_date, product_id, pallet_cd, run_qty from yourtable where pallet_cd >= '00801004718000000007' order by pallet_cd 	0
14755122	36916	sql count grouping by a sequence of numbers	select id,        count(*) as res from   (select *,                [pnum] - row_number() over (partition by [id] order by [pnum]) as grp         from   yourtable) t group  by id,           grp 	0.00487015942951029
14755896	32005	count visit and group them by company	select     count(  visittracking.customerid) as #visit                 , max(visittracking.visitid) as visitid                 ,customers.title as title                 ,customers.customerid                 ,customers.firstname as "first name"                  ,customers.lastname as "last name"                 ,company.companyname as "company name"                 ,max(visittracking.datevisited) as "date visited"                 ,visittracking.nextvisit as "next visit" from         visittracking inner join                       customers on visittracking.customerid = customers.customerid inner join                       company on visittracking.companyid = company.companyid group by visittracking.companyid,customers.customerid, visittracking.customerid, customers.title, customers.firstname, customers.lastname, company.companyname,visittracking.nextvisit 	0.00299749283200763
14756404	1689	sum function producing whole number instead of percentage	select sum(1.0*total/nullif(fin_acc,0))as sum1 	0.0319847573272646
14757045	31853	sql - return number times a value results from a query	select pl.last_name, count(*) noofpatients from dbo.pm_patient pt inner join dbo.providerlist pl on pt.provider_id = pl.provider_id where pt.last_visit_date >= '02/01/2012' and pt.last_visit_date <= '02/01/2013' group by pl.last_name 	0
14758270	37338	php script export new entries to sql table and overwrite file	select * from enquiries where date(datefield) = curdate() order by firstname 	0.000344458474006644
14760629	29312	select last distinct records in mysql	select a.bank_id,         b.amount  from   (select bank_id,                 max(id) as id          from   amounts          group  by bank_id) a         inner join amounts b                 on b.id = a.id 	0.000146281134316703
14761088	21670	how to use the result from a second select in my first select	select angajati.nume from angajati join angajari  on angajati.angajatid = angajari.angajatid join distribuire on angajari.distribuireid = distribuire.distribuireid where distribuire.locatie = 'california' 	0.000107048691480314
14763488	26101	query for disallow countries	select     userkey from     table_settings     left join table_users on (         username = 'miketyson'         and disallowcountries = usercountry     ) where     userid is null 	0.72393378395663
14764670	29565	calculating dates	select      * from (       select     customer.customer_id,     service.service_recid,     resource.date_time_start,     recurrence.recurrence_recid,     recurtype,     recurinterval,     daysofweek,     absdaynbr,     selectinterval,     nextappointmentdate=     case          when recurtype='m' then dateadd(month,recurinterval,resource.date_time_start)         when recurtype='y' then dateadd(year,recurinterval,resource.date_time_start)     else          null     end         from     recurrence     inner join resource on resource.recurrence_recid=recurrence.recurrence_recid     inner join service on service.service_recid=resource.service_recid     inner join customer on customer.customer_id=service.customerid )as x where     nextappointmentdate>=getdate() order by fields... 	0.0260037203856603
14764725	157	mysql join 3 tables on single resource id	select  resource_id,         max(case when types = 'votes' then totals else null end) votes,         max(case when types = 'flags' then totals else null end) flags,         max(case when types = 'tags' then totals else null end) tags from         (         select  resource_id, 'votes' types,                  count(distinct resource_id) totals         from    resources_votes         group   by resource_id         union         select  resource_id, 'flags' types,                  count(distinct resource_id) totals         from    resources_flags         group   by resource_id         union         select  resource_id, 'tags' types,                  count(distinct resource_tag_id) totals         from    resources_connection         group   by resource_id     ) s group   by resource_id 	0.00555957772627172
14765661	20055	dbms sql query for the project	select top 1 bookid,authorid from manuscript order by noofcopies asc 	0.58671367539577
14765765	10895	select * transform row value as table column name	select group_concat(convert(leave_type_id_leave_type,char(10))) from leave_remain group by staff_id_staff union select group_concat(convert(days,char(10))) from leave_remain group by staff_id_staff 	9.46798464585288e-05
14765988	35372	mysql ranking system based on user id	select rank from (     select if(@points=p.points, @rownum, @rownum:=@rownum+1) rank,         p.*, (@points:=p.points) dummy      from `ranking` p, (select @rownum:=0) x, (select @points:=0) y      order by `points` desc ) t where user_id = 3 	0.0012267704589285
14767988	18085	sqlite/postgres sql query distinct column	select max(case_no), first_name, last_name from table group by first_name, last_name; 	0.234014099059123
14768108	15751	how to get latest datetime from multiple same dates in mysql	select max(start_time) from times  where start_time between '2013-01-27 00:00:00' and '2013-02-02 23:59:59'  group by date(start_time) order by start_time 	0
14769187	17048	period end - variance	select py1.period_id, py1.payment - py2.payment as 'payment variance'  from paytable py1   inner join paytable py2         on  py2.pay_id = py1.pay_id         and py2.period_id = cast(cast(py1.period_id as int) -1 as varchar(10))  where  py1.pay_id = pn.pay_id 	0.0576603794619185
14769267	23248	mysql join with varchar fields	select a.*, b.*   from    table1 a         inner join table2 b             on a.ref_no = b.ref_no 	0.286297911570472
14770092	33401	returning 1 or 0 in specific sql query	select id, num,     case when names in ('jack', 'bruce') and num=0     then 1 else 0 end as mynames from mytable 	0.305314089417711
14770554	11149	join three tables in one sql query	select  o.order_id,  order_product.model, o.name,  o.value,  group_concat(o.order_id,  o.name, o.value separator ',') as options  from `order_option` as o  left join `order` as oo on o.order_id = oo.order_id left join order_product on o.order_id = order_product.order_id where oo.order_status_id = 2  group by o.order_id 	0.0824817084543779
14770829	37574	grouping timestamps by day, not by time	select date_trunc('day', user_logs.timestamp) "day", count(*) views from user_logs where user_logs.timestamp >= %(timestamp_1)s     and user_logs.timestamp <= %(timestamp_2)s group by 1 order by 1 	0.00057099645479009
14771442	31400	how to join several tables?	select *  from track inner join segment_id on track.segment_id = segment_id.segment_id  inner join road on segment_id.road_id = road.road_id 	0.0718486532195245
14772000	7275	show a zero if group by returns no value	select date_sub(curdate(), interval i day) date_created_at,         count(id)  from (select 1 i union all        select 2 union all        select 3 union all        select 4 union all        select 5 union all        select 6 union all        select 7) i left join user_accts on  date(created_at) = date_sub(curdate(), interval i day) group by date_sub(curdate(), interval i day) 	0.00205021524352457
14772739	1287	set mysql variable without using a semicolon	select a.name,             a.avscore,             @rank := @rank + 1      from   (select name,             avg(score) as avscore ,(select @rank :=0) v     from   results      group  by name) a     order  by a.avscore 	0.273559595055701
14772819	14574	select two employee names from a single table with two different employee ids in a single stored procedure	select l.leadbudget, l.companyname, l.leadtitle, l.status, leademp.name as ownername, createdemp.name as createduser from leads l      inner join employee leademp on(l.leadowner = leademp.employeeid)      inner join employee createdemp on(l.createduserid= createdemp.employeeid) where l.leadid='2' 	0
14775395	24483	query a link table using joins in mysql	select *  from user as u    join booking as b on b.user_id = u.id    join lesson_booking as lb on b.id = lb.booking_id     join lesson as l on lb.lesson_id = l.id  where u.name = 'bob'; 	0.44245827606108
14776036	31045	select into #temp.. from [query1] or [query2]	select *  into dbo.#privs  from (   select privilegeid    from   users.tblroleprivilegelink    where  roleid = @roleid and @roleid > -1   union   select privilegeid    from   dbo.fn_userprivileges(@userid)   where  @userid  > 1) 	0.0400020572159766
14777021	29689	how to extract specific value from xml in sql?	select @xml.value('(/term/productref[1]/cacheditem/@value)[1]','varchar(100)') 	0.000172449373027438
14777965	24870	sql inner join return parent row values only on first match	select case when rownumber = 1 then dept_id else null end as dept_id,        case when rownumber = 1 then dept_name else null end as dept_name,         emp_id, emp_name from dept d inner join  (select row_number() over (partition by dept_id order by emp_name) as rownumber,         dept_id, dept_name, emp_id, emp_name from emp ) t on t.dept_id = d. dept_id 	0
14778350	2787	sql - search by beginning of a word	select * from tablename where companyname like 'em%' or companyname like '% em%' 	0.0128589444419519
14778590	28313	mysql query for every next element following a pattern	select a.* from log as a where a.event = 'a' && "start" = (select event from log where id<a.id order by id desc limit 1) 	0.00220413058748297
14779324	22700	sql server version of stock valuation query	select t.*, cumetot / cumeqty from (select t.*,              (select sum(qty)               from t t2               where t2.tranctype = 'p' and t2.proid = t.proid and t2.trancdate <= t.trancdate              ) as cumeqty,              (select sum(qty*closingcostrate)               from t t2               where t2.tranctype = 'p' and t2.proid = t.proid and t2.trancdate <= t.trancdate              ) as cumetot       from t      ) t 	0.646852901775625
14780310	20679	how do i get the expression of a check constraint using tsql?	select tc.constraint_schema, tc.constraint_name, tc.table_name, cc.check_clause from [information_schema].[check_constraints] cc      inner join information_schema.table_constraints tc         on  cc.constraint_name = tc.constraint_name         and cc.constraint_schema = tc.table_schema 	0.00554679403980924
14780540	413	mysql get several column associated values in one query	select s.id, s1.val as v1, s2.val as v2, s3.val as v3 from scale s join step s1 on s.s1 = s1.id join step s2 on s.s2 = s2.id join step s3 on s.s3 = s3.id 	0
14781262	2722	how do i create a query to display checklist from the following tables?	select user.user_name, group.group_name,  case when usergroup.user_id is null then 0 else 1 end as checked from user cross join group  left join usergroup on user.user_id = usergroup.user_id    and group.group_id = usergroup.group_id 	0.000343448967133059
14781918	14976	mysql select distinct rows for same group using table1.id regexp table2.id	select a.*, b.name from titles a join (          select g.name, max(t.id) id          from titles as t, groups as g           where t.groups regexp concat('^', g.id, '')          group by g.name      ) b on a.id = b.id 	0.0100684276914872
14782174	1863	repeat rows based on range of dates in two columns	select     datetable.id,     dateadd(dd, numberstable.number, datetable.startdate) from     datetable inner join     numberstable on     dateadd(dd, numberstable.number, datetable.startdate) <= datetable.enddate order by     datetable.id,     dateadd(dd, numberstable.number, datetable.startdate) 	0
14782866	35252	limiting the number of columns in a chart in an access-report	select (format([date_consumption],"mmm")) as date_cons, consumption from cons  where date_consumption > '08-feb-2012'(if you run your report today) 	0.00195001398478347
14783566	41155	query 2 tables from 2 machines and group results	select sum(icount) as icount, logdate from (     select count(log_datetime) as icount, convert(varchar, log_datetime, 101) as logdate     from openrowset('sqloledb', 'servername1';'userid';'password',               'select * from databasename..tablename where field1 > 899')     group by convert(varchar, log_datetime, 101)         union all     select count(log_datetime) as icount, convert(varchar, log_datetime, 101) as logdate     from openrowset('sqloledb', 'servername2';'userid';'password',         'select * from databasename..tablename where field1 > 899')     group by convert(varchar, log_datetime, 101) ) as tbl group by logdate order by logdate 	0.00154962401693101
14784162	18435	conditional select using multiple if conditions	select    username  from(     select username,         case when abs(a-b)<20 then 1 else 0 end a         case when abs(c-d)<20 then 1 else 0 end b         case when abs(e-f)<20 then 1 else 0 end c         case when abs(g-h)<20 then 1 else 0 end d     from players )tmp where tmp.a+tmp.b+tmp.c+tmp.d>=2 	0.532257139047629
14784559	18357	how to add a select statement result?	select sum(hours) from resource where date = '02/08/2013'; 	0.0614706245602828
14785616	39904	ms access count distinct column	select sum(house_thanas.target)               as target,     sum(reports_db.ach_total)              as total,     (select count(*) as justonce     from (select distinct report_date from reports_db)) as workingdays   <...> 	0.161645206811992
14785752	9936	how to link table column from another table column?	select  a.*, if(a.foobar = 1, b.foo, b.bar) result from    tableb a         left join tablea b             on a.id = b.id 	0
14785901	33829	find id of all ads posted within the past three days, sql	select id from tablename where trunc(pdate) >= trunc(sysdate) - 3; 	0
14786574	25054	counting records in normalized table	select sum(cnt), nick from (select count(*) cnt, e.nick from entries e    left join magnets m on (e.id=m.eid and e.nick=m.nick)    where eid is null group by e.nick union all   select count(*) cnt, nick from magnets m group by nick) u  group by nick 	0.000950773188558673
14787211	35739	select form table a where value in table b	select `name` from `table a` inner join `table b` on      find_in_set(`table a`.`id`, `table b`.`userlist`) where `table b`.`id` = 1 	0.00042059175468762
14787466	8003	count the number of digits in a field	select headline from accounttbl where patindex('%[0-9]%[0-9]%[0-9]%', headline) > 0 	7.74638291874652e-05
14787750	28853	mysql select rows older then a week	select * from table where datediff(now(),colname) > 7; 	0
14789088	30151	mysql match against and group by multiple terms	select skill, sum(comment regexp skill) from comments,skills group by skill 	0.126627988660882
14789868	12323	sql combine two queries into one	select * from books inner join purchases using (bookid)  where authorid = ?  group by bookid  having count(bookid) > ?; 	0.00112469198272839
14791658	21548	getting events from mysql database and placing on calendar	select name, date_format(date,'%y-%m-%d') as date     from events   where date like '$year-$month%' 	0.00463995216898181
14792894	19829	writing a join to get customers within a certain distance of a given zip code	select customers.*  from customers c  inner join  (     select zipcode,( 3959 * acos( cos( radians( $la ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( $lo ) ) + sin( radians( $la ) ) * sin( radians( lat ) ) ) ) as distance      from zipcodes      having distance <$rad      order by distance limit 0 , 20 ) as relevantcodes    on (c.zipcode=relevantcodes.zipcode) 	0
14793242	26908	perform if in mysql or php	select * from user left outer join superuser left outer join specialuser 	0.779522150857796
14793326	25000	how to connect a row with another row in anoter table	select username from table1 join table2 on table1.userid = table2.userid 	0.000177748098430142
14793535	18240	postgres conditional select?	select b.box_name, b.box_cost, bp2.end_time - bp2.start_time as box_shipping_duration, bp3.end_time - bp3.start_time as box_packing_duration, bp1.end_time - bp1.start_time as box_invoice_duration from boxes b join box_processids bpid on b.boxid = bpid.boxid left outer join box_processes bp1 on bpid.parentprocessid = bp1.parentprocess and processname = 'invoiced' left outer join box_processes bp2 on bpid.parentprocessid = bp2.parentprocess and processname = 'shipped' left outer join box_processes bp3 on bpid.parentprocessid = bp3.parentprocess and processname = 'packed' 	0.540145647689163
14795577	17026	how to return multiple rows by combining two tables	select t.profileid, t.firstname, t.lastname     from ( select          p.profile_id as profileid,          p.first_name as firstname,          p.first_name as first_name,         p.last_name as lastname         from profile p     union          select          p.profile_id as profileid,          k.first_name as firstname,         p.first_name as first_name,         p.last_name as lastname          from profile p,          known_names k         where  k.profile_id = p.profile_id ) t where t.first_name='david' 	0.000127852065538321
14797068	40998	joining two tables via primary key in first table sql	select  a.*, b.* from    accomodation a         inner join holiday b             on a.locationid = b.locationid 	0
14798599	5484	mysql, return all results within x last hours	select  * from    tablename where   timestart > (select max(timestart) + interval -1 second from tablename) 	0
14800679	13071	how to fetch the last batch of updates from a mysql database	select * from 'mytable' where 'date_updated'=(     select date_updated from 'mytable' order by date_updated desc limit 1) 	0
14800908	3737	top articles with unique name	select result.id, result.name, result.rating from (     select article.id as id, article.name as name, avg(vote.rating) as rating     from article      left join vote on vote.article_id = article.id     group by article.id     order by rating desc ) as result group by result.name 	0.000765776262658987
14802462	32936	php count mysql with datetime and group	select count(id) from `unique_visitors_user` where date >= "2013-01-01"  and date < date_add("2013-01-01", interval 1 day) group by day(date) 	0.172052618032064
14803167	30255	grouping similar values into new select statement	select supplier_name,    max(case when status = 'unavailable' then count else 0 end) as unavailable,   max(case when status = 'refunded' then count else 0 end) as refunded,   max(case when status = 'shipped' then count else 0 end) as shipped from yourtable group by supplier_name 	0.005115118090717
14805851	39251	mysql - sum column value(s) based on row from the same table	select     productid,     sum(if(paymentmethod = 'cash', amount, 0)) as 'cash',     sum(amount) as total from     payments where     saledate = '2012-02-10' group by     productid 	0
14806391	17177	select inner join 4 tables	select  e.department from    dbo.fa_pc a         inner join dbo.users b         on a.userid = b.userid         inner join dbo.subdepttransfer c             on a.userid = c.userid           inner join dbo.subdept d             on c.subdeptid = d.subdeptid         inner join dbo.department e             on d.deptid = e.deptid where   a.faid = $faidf 	0.422375143116585
14809086	35519	mysql query select * from table where image!='' order by date and with different upload user	select    mytable.*  from   mytable    inner join      (select max(id) as id, id from mytable group by user_id) as m      on m.id = mytable.id  where image != ''  group by user_id  order by date desc  limit 5 	0.000330649672659802
14812091	36855	sql query for many to one relationship	select * from  (     select staffid, max(assignedfromdate) as adate    from staffdepartmentassgnment     group by staffid ) x inner join staffdepartmentassgnment y       on y.staffid = x.staffid and adate = y.assignedfromdate where departmentid = 'dept2' 	0.052915342565294
14812549	1140	add day to datetime in query	select * from my_table where startdate + interval day day >= now(); 	0.00237735338730859
14816675	23564	join - get one full table and the rest of another	select * from t1 union all select * from t2 where not exists (select 1 from t1 where t1.age = t2.age) 	0
14818395	4311	magento change database table prefix	select 'rename table '||table_name||' to '||'newprefix'||table_name||';' from information_schema.tables 	0.204892490387117
14819668	38203	select string which contains	select ... where val like '%\'efg\'%' 	0.0190266647069279
14819724	15390	where binary in oracle	select * from table1 where nlssort(column1, 'nls_sort = latin_cs') = nlssort(column2, 'nls_sort = latin_cs') 	0.434987892881912
14820381	10421	using case for a specific situation - how to	select id, a_no, b_no,             case when a_no = min_a_no then b_no else 0 end as new_b_no     from             a left join b on a.id = b.id left join            (select id, b_no, min(a_no) as min_a_no             from  a left join b on a.id = b.id             group by id, b_no) m on a.id = m.id and b.b_no = m.b_no     order by a.id, b.a_no 	0.714615432763077
14821263	4437	sql server view results different to the select	select d d.t_orno    , d.t_item    , c.t_dsca from ttdpur401100 d    inner  join ttcibd001100 c on  c.t_item = d.t_item left outer join cs.mytestpo t on d.t_item = t.t_item where t.t_item is null 	0.0281428391632169
14823476	22564	sql - count number of occurrences in a column	select     countab = sum(case when pageurl like '%ab%' then 1 else 0 end),    countcd = sum(case when pageurl like '%cd%' then 1 else 0 end) from   mytable where    pageurl like '%ab%' or    pageurl like '%cd%' 	0.000117575668030008
14824066	17114	select a grid territory/sales people/category combos where all line items have more than one quantity	select terr.name as territory, sp.name salesperson, sum(case when detail.orderqty > 1 and subcat.productsubcategoryid = 1 then 1 else 0 end) as mbikes, sum(case when detail.orderqty > 1 and subcat.productsubcategoryid = 2 then 1 else 0 end) as chains, sum(case when detail.orderqty > 1 and subcat.productsubcategoryid = 3 then 1 else 0 end) as gloves from sales.salesorderdetail detail inner join sales.salesorderheader header on header.salesorderid = detail.salesorderid inner join sales.salesperson sp on sp.businessentityid = header.salespersonid inner join sales.salesterritory terr on terr.territoryid = sp.territoryid inner join sales.specialofferproduct sop on sop.productid = detail.productid inner join production.product on product.productid = sop.productid inner join production.productsubcategory subcat on subcat.productsubcategoryid = product.productsubcategoryid group by terr.name, sp.name 	0
14825099	12294	mysql select data is many to many relationship in php	select   e.ent_seq,   e.entry,   ke.keb,   re.reb,   s.mean,   s.up_date from entry e left join (select entry, group_concat(keb) keb from k_ele group by entry) ke   on ke.entry = e.entry left join (select entry, group_concat(reb) reb from r_ele group by entry) re   on re.entry = e.entry left join (   select s.entry, mean, up_date from sense s     left join (select sid, group_concat(mean) mean from gloss_eng                group by sid               ) ge       on ge.sid = s.sid     left join (select sid, group_concat(distinct up_date) up_date from `update`                group by sid               ) u       on u.sid = s.sid   group by s.sid   ) s   on s.entry = e.entry 	0.0525935497398271
14826055	10255	how to get multiple count in sql	select rating, count(column_name) from   table group by        rating 	0.0104063480954711
14826545	30167	how to get sum of column value with inner join in one query?	select     m.medianame,     count(as.advid) as total from    a_mediatype as m inner join a_advertise as a on a.mediatypeid = m.mediatypeid inner join  a_ad_display as ad on ad.advid = a.advertiseid group by m.mediatypeid 	0.000594234603814394
14827567	33413	remove a subquery in postgresql	select dname,        avg(case when loc = 'l1' then age else null end) as "l1 avg",        avg(case when loc = 'l2' then age else null end) as "l2 avg" from dept d left join emp using (dname) group by dname 	0.401077909781682
14828356	8340	how to create a nested sql query in mysql?	select so.*       from smart_objects as so     inner join (select  st.objectid, st.issueid from smart_targets as st,smart_objects as so                   where st.objectid = so.id) as soi     on soi.objectid = so.id 	0.699527164371108
14828964	38989	sql server get maximum mdf file size	select db.name as [db_name], mf.name, mf.max_size from sys.master_files mf join sys.databases db on mf.database_id = db.database_id order by db.name 	0.00391864264552363
14829074	30636	sqlite3 performance with or of between ranges	select * from sometable where id between 10 and 11 union all select * from sometable where id between 20 and 21 union all select * from sometable where id between 30 and 31  ... 	0.296886725827555
14831266	5848	compare table rows, big data amount	select t.id, t2.id,        ((case when t1.col1 = t2.col1 then 5 else 0 end) +         (case when t2.col2 = t2.col2 then 7 else 0 end) +         . . .        ) from t cross join t2 	7.89633955993539e-05
14832092	17679	parent - child sql query with in a single table	select child.id,        child.name,        child.parentid,        parent.name as parentname from your_table child join your_table parent on child.parentid = parent.id; 	0.00206058220359903
14836259	40010	convert access query to sql server	select top 1 (select case when  datediff(year, dateofbirth, '31-aug-2012') < 18 then 'parent/guardian of:' else null  end  ) from table_name 	0.789842271029354
14837216	31579	how to use data from a different table to obtain the appropriate records in mysql	select * from users  left join holiday on users.user = holiday.user where holiday.department = 'marketing' 	5.67607241498735e-05
14837410	10870	sql sum query group	select pacontnumber, project type, sum(project_fee_amount) as project_fee_amount from dbo.vwpaprojects_summary_new_2 group by pacontnumber, project type 	0.435491977451909
14837662	7732	max date <= to date in another table	select o.orderdate     , isnull(r.effectivedate, (         select max(effectivedate) from t_rate where effectivedate < o.orderdate     ) from orderhed o left join t_rate r on o.orderdate = r.effectivedate 	0.000202528155505856
14837777	25177	include count 0 in my group by request	select  "mydates"."datevalue" as "day" ,      (select count(*) from events where   date_trunc('day', "events"."created_at") = "mydates"."datevalue" and      ("events"."application_id" = 4) and      ("events"."what" like 'action%'))  as "no. of actions"     from    "mydates"  where ("mydates"."datevalue" > now() - interval '2 weeks') and ("mydates"."datevalue" < now()) 	0.555919087852721
14839472	32675	how to find first time of day and last time of day	select  tc.dttimein         , tc.dttimeout         , e.sfirstname from    timeclock tc join    employees e on tc.lemployeeid = e.lemployeeid join    (                            select  dateadd(day, datediff(day, 0, tc.dttimein), 0) _date                     , min(tc.dttimein) dttimein                     , max(tc.dttimeout) dttimeout             from    timeclock tc             where   e.sdept in ('1', '2', '3')             group by                     dateadd(day, datediff(day, 0, tc.dttimein), 0) ) t on  t._date = dateadd(day, datediff(day, 0, getdate()), 0) and     dateadd(day, datediff(day, 0, tc.dttimein), 0) = t._date and     (t.dttimein = tc.dttimein or t.dttimeout = tc.dttimeout) where   e.sdept in ('1', '2', '3') 	0
14840686	12356	need to get the max repeated value in column ios	select * from contact where page in ( select page from contact group by page order by count(*) desc limit 1) 	0.0010659910281253
14840941	14938	sql query joining tables - oracle	select * from employees     inner join  departments on       employees.department_id=departments.department_id where departments.location_id <> 1700 	0.329645254320619
14842098	10442	counting number of unique names	select distinct servername,    (select count(distinct servername)     from yourtable    where target = 'blah') number from yourtable where target = 'blah' 	0
14842502	33050	oracle sql query -> count 2 columns under 2 different conditions	select  sum(case when resolution_date is null then 0 else 1 end) as count_resolution_date,  count(creation_date) as count_creation_date from mytable group by year order by year; 	0.000584745913220307
14842958	5548	mysql how to add/subtract two columns together based on date?	select t.y, t.m, t.c - ifnull(t2.c,0) c from (     select year(timestamp) y, month(timestamp) m, count(id) c     from table     where clause="foo"     group by year(timestamp), month(timestamp) ) t left join (     select year(timestamp) y, month(timestamp) m, count(id) c     from table2     where clause="foo"     group by year(timestamp), month(timestamp) ) t2 on t.y = t2.y and t.m = t2.m union  select t.y, t.m, (t.c * -1) c from (     select year(timestamp) y, month(timestamp) m, count(id) c     from table2     where clause="foo"     group by year(timestamp), month(timestamp) ) t left join (     select year(timestamp) y, month(timestamp) m, count(id) c     from table     where clause="foo"     group by year(timestamp), month(timestamp) ) t2 on t.y = t2.y and t.m = t2.m where t2.y is null order by y, m 	0
14844519	20313	mysql - want to minus two sum() values from two select statements	select sum(total.`price`) as clearedfunds from ( select `price` from property where `status` = 'sold' union all select (`amount` * -1) as `price` from payment1 where `status` = 'cleared' union all select (`amount` * -1) as `price` from payment2 where `status` = 'cleared' union all select (`amount` * -1) as `price` from payment3 where `status` = 'cleared' ) as total; 	0.000684945862063683
14844626	14310	how to force a query to get the results with only all the rows selected?	select p.id_product, p.name from products p     join features f on p.id_product = f.id_product      join features f2 on p.id_product = f2.id_product  where f.id_feature in (select id_feature from features where id_product = 5) group by p.id_product, p.name having count(distinct f2.id_feature) = 3 	0
14844780	7482	what is a multiple key index?	select * from mytable where user_id = 123 and created_at > '2013-02-01' 	0.492847091734962
14847031	24004	select three values based on the group by of alphabets a-z	select alphabet, name from ( select left(name, 1) as alphabet, name, @num := if(@prev = left(name, 1), @num + 1, 1) as row_num, @prev := left(name, 1) as previous from yourtable, (select @num:=0, @prev:='') v order by name ) sq where row_num <= 3 	0.000151157440730193
14847100	19524	select query from two tables with groupby function	select e.emplid, e.emp_name,   sum(((a.att_out-a.att_in)*1440)*.69) as "minutes*sal/m" from employees e  inner join attendance a on e.emplid = a.emplid group by e.emplid, e.emp_name 	0.095022716173957
14849777	6283	sql - select amount from each type	select  s.name ,       s.type from    (         select  *         ,       (@rn := if(@cur=type, @rn+1, 1)) as rn         ,       @cur := type         from    games         join    (select @cur := '') i         order by                 type         ) s where   rn <= 2 	0
14851313	35523	return last inserted id in postgresql with c#	select currval(pg_get_serial_sequence('my_tbl_name','id_col_name')) 	0.000147979038336164
14851647	17904	count distinct entries by summing values on a new column	select name,   1.0 / count(name) over(partition by name) as x from yourtable 	0
14854695	385	select available rooms	select tbl_room.roomname, tbl_timeslot.starttime  from tbl_timeslot cross join tbl_room  except  (select tbl_room.roomname, tbl_timeslot.starttime   from tbl_timeslot cross join tbl_room      full outer join tbl_booking          on tbl_timeslot.timeslotid_pk = tbl_booking.timeslotid_fk  where (tbl_booking.bookingdate = @bookingdate)) 	0.0076209961859501
14855766	29052	creating a lookup table from a column in table	select     id,     a.s category_number from     mycsvtable     cross apply dbo.split (',', mycsvtable.category_number) a 	0.0015318654466277
14855949	37222	select min and max from several bit variables	select      teacherid,     teachername,     case         when reception > 0 then 're'         when year1 > 0 then 'y1'         when year2 > 0 then 'y2'         when year3 > 0 then 'y3'         when year4 > 0 then 'y4'         when year5 > 0 then 'y5'         when alevel > 0 then 'al'         else '' end      + ' - ' +     case         when alevel > 0 then 'al'         when year5 > 0 then 'y5'         when year4 > 0 then 'y4'         when year3 > 0 then 'y3'         when year2 > 0 then 'y2'         when year1 > 0 then 'y1'         when reception > 0 then 're'         else '' end as range from     teachers 	0.0073970030534536
14857207	6808	bigquery: array of values in a field	select left( format_utc_usec(utc_usec_to_day(timestamp*1000000)),10) as date_day, avg (download_speed)avg_download, avg (upload_speed)avg_upload, group_concat(real_address)as real_address_list from [xxxxxxx:xxxxx.xxxxx] group by date_day order by date_day asc 	0.0091989548772948
14857338	5817	how to use the column name for comparison against a parameter in sql?	select      case @dayofweek         when 'sunday' then sunday         when 'monday' then monday         when 'tuesday' then tuesday         when 'wednesday' then wednesday         when 'thursday' then thursday         when 'friday' then friday         when 'saturday' then saturday     end as todaysvalue from     daytable; 	0.148735594632594
14857682	32820	sql - last 6 months (12,18,24,30) divisor by 6 months query	select  * from    t         inner join         (   select  [date] = dateadd(month, - number, @date)             from    master..spt_values             where   type = 'p'             and     number % 6 = 0         ) d             on d.date = t.lastsalesdate 	0
14858102	36425	using the result of query to get another result on the same table	select * from ( select distinct v2_modules.id,v2_modules.name, v2_modules.url, v2_modules.parentid  from v2_modules             inner join v2_roles_permissions_modules                 on v2_modules.id =  v2_roles_permissions_modules.moduleid                     inner join v2_admin_roles                         on v2_roles_permissions_modules.roleid = v2_admin_roles.roleid                             inner join admin                                 on v2_admin_roles.adminid = 89 ) as table1 inner join v2_modules on v2_modules.parentid = table1.id 	0
14859038	29302	select from two tables - sort result by foreign and primary key	select          s._id sid,         s.name,          null iid     from          section s union all select          i.section_id sid,          i.name,          i._id iid     from         item i     order by         sid, iid 	0
14860806	26254	how to set bits in an initially null char in mysql	select ifnull(your_columns_name,0) from mydb ; 	0.213248562373365
14860820	9773	how to bin arbitrarily in mysql?	select case when age between 13 and 17 then '13-17'              when age between 18 and 25 then '18-25'              else '26+' end as agegroup,     count(*) as total from mytable group by agegroup 	0.498688631887431
14861288	30216	mysql select maximum value for column a with same values in column b	select users.usr_postcode, max(point_date_pairs.pdp_point_total) from users inner join point_date_pairs on users.usr_id_pk = point_date_pairs.usr_id_fk group by users.usr_postcode asc 	0
14867686	34703	php/mysql compare uploaded files to ensure no redundant data	select id from files_table where file_hash_md5 = '78b7d929110959d1de58a32e9d331512' and file_hash_sha1 = 'cc73882a1395af392b6cb005c45d19869bfa485a' 	0.00825948353934787
14869029	38404	need solution for fetching data from two tables query	select   sum(runscored) as totalrun    from `playerbat`   where  teamid = 't02' and matchid = 'ipl11' 	0.0574567465005484
14872211	29193	sql - compare table	select nvl (a.key, b.key) as "key",        nvl (a.text, b.text) as "text",        case           when a.key is not null and b.key is null then              'insert'           when a.key is null and b.key is not null then              'delete'           when a.key is not null and b.key is not null and a.text != b.text then              'update'           when a.key is not null and b.key is not null and a.text = b.text then              'nothing'        end           "case"   from tablea a full outer join tableb b on a.key = b.key; 	0.0243165882490064
14874811	34794	sum hours from timestamp	select to_char(to_timestamp ('2013-02-14 10:07:47.000' , 'yyyy-mm-dd hh24:mi:ss.ff'),'dd-mon-yyyy hh24:mi:ss') start_date  from dual /   sql> 14-feb-2013 10:07:47 select to_date(to_char(to_timestamp ('2013-02-14 10:07:47.000' , 'yyyy-mm-dd hh24:mi:ss.ff'),'dd-mon-yyyy hh24:mi:ss'), 'dd-mon-yyyy hh24:mi:ss') start_date  from dual  /   sql>  2/14/2013 10:07:47 am select to_char(to_timestamp ('2013-02-14 10:07:47.000' , 'yyyy-mm-dd hh24:mi:ss.ff'),'hh24') start_date  from dual  /  sql> 10   select to_number(to_char(to_timestamp ('2013-02-14 10:07:47.000' , 'yyyy-mm-dd hh24:mi:ss.ff'),'mi')) minutes     from dual   /   sql> 7 	0.000200585605728381
14875084	8994	efficient time series querying in postgres	select     widget_id,     for_date,     case         when score is not null then score         else first_value(score) over (partition by widget_id, c order by for_date)         end score from (     select         a.widget_id,         a.for_date,         s.score,         count(score) over(partition by a.widget_id order by a.for_date) c     from (         select widget_id, g.d::date for_date         from (             select distinct widget_id             from score             ) s             cross join             generate_series(                 (select min(for_date) from score),                 (select max(for_date) from score),                 '1 day'             ) g(d)         ) a         left join         score s on a.widget_id = s.widget_id and a.for_date = s.for_date ) s order by widget_id, for_date 	0.0987546527855748
14875184	27052	find nonbreaking period with condition	select     a.q_date ,   a.q_hotel ,   case         when             a.q_value = 0         then             0         else         (             select                 extract                 ( day from                     min ( b.q_date ) - a.q_date + interval '1 day'                 )             from    table1 b             where   b.q_date >= a.q_date             and     b.q_hotel = a.q_hotel             and not exists             (                 select  1                 from    table1 c                 where   c.q_date = b.q_date + interval '1 day'                 and     b.q_hotel = a.q_hotel                 and     q_value <> 0             )         )     end as days_available from    table1 a 	0.0190756519447093
14875596	9510	how to choose a unique ip on days(1 unique ip in every day)?	select max(`date`),`ip` from table group by `ip`,date(`date`) 	0
14879012	20916	selecting non-unique field from table where data does not contain string	select ch.trans_id from   checkpoint ch except select ch.trans_id from   checkpoint ch,    checkpoint_data chd where  ch.checkpoint_id = chd.checkpoint_id  and upper(chd.data)like upper('%example string%') 	0.00135471624526652
14879792	37439	multiplying column values	select  case  when sum(case when mycolumn = 0 then 1 else 0 end) > 0 then 0  else  case when mod(sum(case when mycolumn < 0 then 1 else 0 end),2) = 0 then 1   else -1   end * exp(sum(log(coalesce(mycolumn,1))))  end as product from mytable where condition; 	0.00527044723303877
14879807	2003	mysql count row left	select count(id) as total_keys, sum(if(sent, 1, 0)) as used_keys from yourtable 	0.133800219355508
14879869	8009	selecting non-matching fields in mysql	select * from (     (select * from contact          where (...some dynamic stuff...)      )      union all     (select contact.* from contact inner join contact_campaign_link on contact.id=contact_campaign_link.contact_id         where ((campaign_id=31))    )  union all      (select * from contact          where (customerid=3)          and (not exists              (select * from custom_field_value cfv2                  where (cfv2.contactid = contact.id)                  and (cfv2.customfieldid =27) )) order by contact.id)             ) as tbl  group by tbl.id having count(*)=3 order by id 	0.00990431286287413
14879953	30321	not in sql query set	select *   from (select *, count(*) as counter           from applications         group by user_name, mobile) aview  where product_type = 2 and counter = 1; 	0.687693705657136
14882922	22563	left joining multiple sets of tables	select distinct u.name, (select pa1.text from possible_answer pa1, user_answer ua where ua1.user_id = u.id and ua1.answer_id = pa1.id and pa1.question_id = 1 order by ua1.id desc limit 1) as 'question1', (select pa2.text from possible_answer aa2, user_answer ua2 where ua2.user_id = u.id and ua2.answer_id = pa2.id and pa.question_id = 2 order by ua.id desc limit 1) as 'question2' from user u   group by u.id; 	0.0360269625732449
14884777	365	how to count rows on joined table	select groups.usergroupid, usergroup,        count(users.usergroupid) as howmany from groups_table as groups left join users_table as users on users.usergroupid = groups.usergroupid group by groups.usergroupid order by groups.usergroupid 	0.000429565149800396
14885836	5535	mysql multiple queries or single query - which is more efficient	select    animal,    min(weight)   min_weight,    max(weight)   max_weight,    avg(weight)   avg_weight,    sum(weight)   tot_weight,    count(weight) cnt_weight from    your_table group by    animal  order by animal; 	0.404223017320821
14886048	20660	options to retrieve the current (on a moment of running query) sequence value	select last_value from sequence_name; 	0
14892487	36618	sqlite select single colum where two tables match	select table1.colx from table1 inner join table2 on table1.ab_id=table2.ab_id; 	0.000608327448602221
14893145	9142	mysql sort query by specific letters	select dirname from yourtable order by (length(dirname) - length(replace(dirname, '\\', ''))) 	0.0144230939238688
14894193	24805	randomising numbers sql	select cast(rand(checksum(newid())) * 7 + 1 as int) 	0.146038096268176
14895842	14686	merge multiple rows to one	select  b_firstname,          pfd69.value as value69,          pfd73.value as value73,          pfd75.value as value75  from    cscart_user_profiles as up         right join cscart_profile_fields_data as pfd69         on pfd69.object_id = up.profile_id               and pfd69.field_id ='69'         right join cscart_profile_fields_data as pfd73         on pfd73.object_id = up.profile_id               and pfd73.field_id ='73'         right join cscart_profile_fields_data as pfd75         on pfd75.object_id = up.profile_id               and pfd75.field_id ='75' where   up.b_title not like ''         and up.profile_id = '4252' 	0.000476673828130379
14898298	30697	how to display multiple database rows as a single entry on web page	select name, dob, substring(emails, 1, len(emails) - 1) as emails from (     select name, dob, (select email + ', '                        from personemail                        for xml path('')) as emails     from person ) t 	0
14898357	1892	calculate business days in oracle sql(no functions or procedure)	select ordernumber, installdate, completedate,   (trunc(completedate) - trunc(installdate) ) +1 -    ((((trunc(completedate,'d'))-(trunc(installdate,'d')))/7)*2) -   (case when to_char(installdate,'dy','nls_date_language=english')='sun' then 1 else 0 end) -   (case when to_char(completedate,'dy','nls_date_language=english')='sat' then 1 else 0 end) as businessdays from orders order by ordernumber; 	0.11426359159692
14899823	17975	mysql slope (trend) of single field (line of best fit)	select         count(*) as n,         sum(unix_timestamp(logentry.date)) as sum_x,         sum(unix_timestamp(logentry.date) * unix_timestamp(logentry.date)) as sum_x2,         sum(logentry.cost) as sum_y,         sum(logentry.cost*logentry.cost) as sum_y2,         sum(unix_timestamp(logentry.date) * logentry.cost) as sum_xy     from logentry 	0.00101269763848496
14900154	21468	join the best record, if there is one, in oracle	select *   from (select t1.id,  t1.otherdata otherdatat1, t2.date, t2.status, t2.otherdata otherdatat2,                rank() over (partition by t1.id order by t2.date desc,                             case t2.status                               when '20' then 1                               when '05' then 2                               when '40' then 3                               when '70' then 4                               else 5                             end) rnk           from table1 t1                left outer join table2 t2                             on t1.id = t2.id)  where rnk = 1; 	0.0134964001859272
14901513	38644	group by column having count (column) >1 in a single column	select item_id  from inv_bin group by item_id having count(item_id) > 1 	0.000551916693576912
14904152	12684	phone number conversion and comparison	select   col1,   col2,   case when     left(       replace(replace(replace(replace(col1, '(', ''), ')', ''), '-', ''), ' ', ''),       6) = left(col2,6)     then 'true'     else 'false'   end matches from yourtable 	0.170965854581635
14904398	4722	how to join two select on same table	select author_id,    count(text) textcount,   count(case when postcounter=1 then text end) postcount from posts  group by author_id 	0.000798814229932541
14906807	9757	mysql: sum and group multiple fields by date + other field	select     concat(month(date), ' ', year(date)) as period,     sum(if(type = 0, cost, 0)) as type0,     sum(if(type = 1, cost, 0)) as type1,     sum(if(type = 2, cost, 0)) as type2 from     t1 group by     period 	0.000280664136466076
14908147	25589	orderby in sql server to put positive values before negative values	select * from table order by  case when sortcolumn<0 then 1 else 0 end ,sortcolumn 	0.000588919423263025
14909440	33978	spatial data query	select nextval('road_intersection_id_seq'),         a.road_id,         b.road_id,         st_intersection(a.road, b.road),         st_centroid(st_intersection(a.road, b.road)) from polygon_road a, polygon_road b where st_intersects(a.road, b.road)    and a.road_id < b.road_id 	0.632755602929812
14909659	30527	adding an extra condition to sql query	select count(*) totalcount  from ts_room rm where  not exists (     select 1     from ts_roompref rp     join ts_request rq on rp.request_id = rq.id and day_id = 1 and period_id = 1     where rm.id = rp.room_id) and not exists (     select 1     from ts_roompref rp     join ts_allocation a on rp.request_id = a.request_id and a.status = "allocated"      where  rm.id = rp.room_id) 	0.577874975660415
14913345	22177	showing all columns in a table except some	select  column_name from    information_schema.columns where   table_name = 'tbl_name'         and column_name not in ('col1', 'col2') 	0.000233679432457645
14913926	6005	subquery returning number rows	select b.bank_id, count(*) from      bank b         left join branches br on br.bank_id = b.bank_id group by b.bank_id order by count(*) desc limit 1 	0.023793748225009
14915030	20901	extract row with a particular scenario	select emp_name, test_result, run_date   from ( select emp_name, test_result, run_date,   row_number() over (partition by emp_name  order by test_result, run_date ) rn  from t1) where rn=1 	0.00455049462943675
14916658	22516	mysql count records from two tables in one query?	select count(distinct t.tsid) as tscount,      count(distinct p.paid) as pacount from account a      left join test t on a.acid = t.tsaccountid     left join patient p on a.acid = p.paaccountid where a.acid = 1 	4.74863264756104e-05
14916844	39210	count of distinct value within a time range	select     ((time - 12000) / 60) + 1 as minute,     count(distinct user_id) as count from ...  group by ((time - 12000) / 60) + 1 	5.72502762095258e-05
14916925	5154	how to order by other column in the group by?	select group_concat(id),         max(date) as max_date from your_table 	0.00268144998009182
14917497	5124	find my postgres text search dictionaries	select dictname from pg_catalog.pg_ts_dict; 	0.433600440582914
14918094	35559	how create a multi sum() for one table with group by and different type for one person	select staff, sum(case type when 'cash' then value else 0 end) as cash, sum(case type when 'efpos' then value else 0 end) as efpos, sum(case type when 'voucher' then value else 0 end) as voucher, sum(value) as total from <table_name> group by staff 	0
14918106	41072	how to check a empty table already in database	select id from categories where name = 'name to check'; 	0.00120950000349184
14918629	14675	display table fields in a single query	select ui.*, u.username from user_info ui join users u on u.id = ui.created_by 	0.000480832059899489
14919777	29400	sum of result generated at run time in mysql query	select x.*       , x.bank_amount-x.amount bal       , sum(y.bank_amount-y.amount) running    from amounts x    join amounts y      on y.id <= x.id   group      by id;  +  | id | bank_amount | amount | bal  | running |  +  |  1 |        1000 |    100 |  900 |     900 |  |  2 |        2000 |    200 | 1800 |    2700 |  |  3 |        3000 |    300 | 2700 |    5400 |  |  4 |        1200 |    500 |  700 |    6100 |  |  5 |        2000 |    600 | 1400 |    7500 |  |  6 |        1202 |    800 |  402 |    7902 |  |  7 |         220 |     50 |  170 |    8072 |  + 	0.0181166592903649
14920255	37129	mysql query - retrieve all devices info with latest timestamp value	select d.name, d.imei, t.latitude, t.longitude from devices d join tracking t      on d.imei=t.imei left join tracking t2      on d.imei=t2.imei     and t2.ctimestamp>t.ctimestamp where t2.imei is null 	0
14921122	35421	mysql statement to find data in two tables	select user_login from wp_users join wp_usermeta   on wp_users.id=wp_usermeta.user_id where meta_key='newsletter'   and meta_value=1; 	0.00381361255646312
14923544	13985	how to get the first process id in mysql of the current user?	select @id := id from information_schema.processlist limit 1; kill @id; 	0
14924429	18176	how can i assign a number to each row in a table representing the record number?	select row_number() over(order by id) from dbo.test 	0
14927284	15045	joining odd/even results of select for subtraction in sqlite?	select sum(case when type = 'stop' then t else -t end) from event 	0.0338843542952041
14929128	13446	extracting time and convert to column then group by date	select date_field,  max(case status when 'a' then date_time end) a, max(case status when 'b' then date_time end) b from  ( select convert(date,datefield,101) date_field,  convert(time,datefield) date_time, status from yourtable ) v group by date_field 	0.000235102662573553
14931279	38544	mysql combine two select queries	select a.products_id,a.options_values_id, b.options_values_id from (select @rownum:=@rownum+1 'rw', products_id, options_values_id from (select @rownum:=0) r, products_attributes pa left join products_options po on ( pa.options_id = po.products_options_id ) where products_id ='574' and pa.options_id!=6 and pa.options_id!=3 and products_options_type = 6 group by products_id,options_values_id order by products_id,products_options_sort_order,options_id) a, (select @rownum:=@rownum+1 'rw', products_id,options_values_id from (select @rownum:=0) r, products_attributes pa left join products_options po on ( pa.options_id = po.products_options_id ) where products_id ='574' and pa.options_id!=6 and pa.options_id!=3 and products_options_type = 2 group by products_id,options_values_id order by products_id,products_options_sort_order,options_id) b where a.products_id=b.products_id and a.rw=b.rw; 	0.0208100845480138
14933448	27797	sql join query - selecting from two tables	select person.person_id, person_name, person_address, person_alternate_id.* from person  left join person_alternate_id on person.person_id=person_alternate_id.person_id where person.person_id in (10001,10002,10003); 	0.00375644791768476
14933618	22417	select all distinct values from a merge of multiple fields mysql	select a, b, c from t group by a, b, c 	0
14934086	34039	comma separated string comparison in mysql query	select * from table where find_in_set('us', country) ; 	0.0161277273687656
14934672	39914	get values of nested query in mysql	select w.*, count(w.idwallhaswallpost) as republish, v.all_wall_idwall from admin_pw.wall_has_wallpost w join (select h.wallpost_idwallpost,               group_concat(distinct h.wall_idwall) all_wall_idwall       from wall_has_wallpost h       join follower f on h.wall_idwall = f.wall_idwall and f.user_iduser=1       group by h.wallpost_idwallpost) v on w.wallpost_idwallpost = v.wallpost_idwallpost group by wallpost_idwallpost  having republish>1; 	0.0278807083715235
14938886	25101	multiple calculations across tables	select customer.custname, sum(invoiceitem.quantity*item.itemprice) as totalvalue   from customer        inner join invoice on customer.custabn = invoice.custabn        inner join invoiceitem on invoice.invoiceno = invoiceitem.invoiceno        inner join item on invoiceitem.itemno = item.itemno  group by customer.custname 	0.0503649459769425
14939377	16911	order query by timestamp and name from two different tables	select max(p.prod_name) as prod_name, max(d.collect_ts) as collect_ts from product p join data d      on d.prod_id = p.prod_id group by p.prod_id 	5.67007616380791e-05
14939663	1259	sort by result of sub query in mysql	select  t1.*,          s.totalcount as downloads_count  from    tl_items as t1          left join         (             select  item_id, count(*) totalcount              from    tl_downloads              where   download_date > ?             group   by item_id         )  s on s.item_id = t1.id order   by downloads_count desc 	0.191438064578512
14940950	14994	cf10 concatenated mysql string as binary data	select concat(cast(co_coid as char(15)), ' - ',co_company) as idconame 	0.0129304474691415
14940954	8082	eliminate subquery in the from clause	select tag from   tagging group  by tag having count(distinct resource) > 2; 	0.256378880492243
14941236	21894	accessing array data from mysql database and php	select array_column_name from table_store_page where id=your_id 	0.00284373287255018
14943224	4480	mysql - selecting rows horizontally	select t.id from table_name t where (datakey = 'label' and datavalue = 'is_member') or (datakey = 'since' and datavalue = '20110204') group by t.id having count(datakey) = 2; 	0.0097836942163921
14943700	13125	mysql - search for entries with 3 decimal places	select * from sometable where (elws * 1000) % 10 != 0 	0.00152502516384424
14946275	21042	sql - pivot/unpivot?	select 'miles' as type, sum(case when date = lastweek then miles else 0 end) as lastweek , sum(case when date = thisweek then miles else 0 end) as thisweek sum(case when date = lastweek then miles else 0 end) - sum(case when date = thisweek then miles else 0 end) as variance from yourtable union select 'cost' as type, sum(case when date = lastweek then cost else 0 end) as lastweek , sum(case when date = thisweek then cost else 0 end) as thisweek sum(case when date = lastweek then cost else 0 end) - sum(case when date = thisweek then cost else 0 end) as variance from yourtable 	0.519851715229925
14947940	20906	changing sql query from one condition to several	select distinct rm.id as roomid from ts_room rm left join ts_roompref rp on rp.room_id = rm.id   left join ts_request rq on rq.id = rp.request_id   left join ts_allocation a on a.request_id = rq.id where building_id = :building_id   and (a.status is null or a.status in ('pending', 'failed', 'declined')) 	0.00489863121073695
14949315	7450	sql select with a yes/no column to state whether customer has associated orders	select  a.id, a.firstname, a.lastname,         case when count(b.custid) > 0 then 'yes' else 'no' end as hasorders from    customer a         left join orders b             on a.id = b.custid         group   by a.id, a.firstname, a.lastname 	0
14949470	20448	sum or count of values based on 2 column with same values in sql server	select a.color,         count(a.color) as count  from   (select colora as color          from   table1          where  status = 'yes'                 and colora is not null          union all          select colorb          from   table1          where  status = 'yes'                 and colorb is not null) a  group  by a.color 	0
14949579	25776	sql, how to get the year that an event occurs for the second time	select * from table_name as t where      (select count(*) from table_name where element = t.element and year < t.year) = 1 	0
14950701	12511	return 0 for no rows returned using sum and iif in ms access	select  sum(iif([senddate]=#2/12/2013# and mailerid = 1, iif(totalcount =  null, 0, totalcount), 0)) as mailcount   from    mailreport 	0.0449320558287822
14950965	38910	oracle query period data to month	select      id, to_char(add_months(to_date(substr(interv,1,6),'yyyymm'), i),'yyyymm') from    (select level-1 as i from dual connect by level <= 50)    join    (    select 1 as id,'201111-201203' as interv from dual    union all    select 2, '201201-201301' from dual    ) on add_months(to_date(substr(interv,1,6),'yyyymm'), i) <=     to_date(substr(interv,-6),'yyyymm') order by 1,2; 	0.00343372026237493
14951653	3542	inserting into sql server database from xml using xquery	select  table1.column1.value('flt_x0020_no[1]', 'varchar(50)'),         table1.column1.value('avno[1]', 'varchar(50)') from    @x.nodes('/table6') as table1(column1) 	0.0257297454795986
14952741	26944	where clauses in max statement	select top 1  queuenum from queue where queuenum like '1981-2-%' order by len(queuenum) desc, queuenum desc 	0.657552487566003
14953004	28000	sql server : display column states by date	select     day(creationtime) as d, month(creationtime) as m, year(creationtime) as y     ,count(case when result = 0 then 1 else null end) as r0     ,count(case when result = 1 then 1 else null end) as r1     ,count(case when result = 2 then 1 else null end) as r2 from history group by day(creationtime), month(creationtime), year(creationtime) select * from history; 	0.0032146086534992
14955670	37576	get count for each joined record	select    a.id, count(b.id) from a  inner join b on a.id = b.aid group by a.id 	0
14956621	26666	return customers with no sales	select * from customer c where not exists (          select 1            from invoice i           where i.customerid = c.customerid       ) 	0.00285335786256615
14957323	30866	how to generate script of a stored procedure based on modified date?	select name , create_date, modify_date ,sm.definition from sys.procedures sp    inner join sys.sql_modules sm  on sp.object_id = sm.object_id     where convert(date,sp.modify_date)    = convert(date, '02/19/2013') 	0.000251724468541472
14957372	9120	ms access relationship between subform and form	select firmrepid, repname from firmreps  where  firmid = forms!nameofmeetingsformhere!firmid 	0.359316150568447
14960698	22278	how to combine sql request with data in another table	select uc.id,        uc.name,        (select count            from counts_data cd            where cd.id_user = uc.id           order by date desc limit 1) as count,        ifnull((select count                   from counts_data cd                   where cd.id_user = uc.id                   order by date desc limit 1 offset 1),0) as count_before from users_counts uc; 	0.0024430828346833
14961291	24725	select records from mysql database grouped by day	select *, date(time) as date from [whatever you want] group by date 	0
14961426	33473	select information from last item and join to the total amount	select a.customer, count(a.sale), max_sale from sales a inner join (select customer, sale max_sale              from sales x where dates = (select max(dates)                                          from sales y                                          where x.customer = y.customer                                         and y.sale > 0                                        )            )b on a.customer = b.customer group by a.customer, max_sale; 	0
14961430	16071	select records with one query	select    data.id,    data.name,    count(distinct connector.id) from    data    left join supplier on (data.id = supplier.data_id)    left join connector on (supplier.id = connector.supplier_id) group by    data.id, data.name 	0.00886638198558329
14962259	35314	mysql query (fetch number of users based on their activity)	select   ym,           sum(c = 1) as `num_1`,          sum(c = 2) as `num_2`,          sum(c = 3) as `num_3`,          sum(c>= 4) as `num_4+` from (   select   date_format(datecreated, '%y-%m') as ym, count(*) as c   from     tblcomments   where    datecreated between '2012-03-01' and '2013-02-19'   group by ym, userid ) t group by ym 	0
14962546	18181	departure date greater than arrival date	select * from     (       select            arrivaldate,            dateadd(day, rand(checksum(newid()))*1.5   * lengthofstay.lengthofstay, arrivaldate) as departuredate           from              bookings, lengthofstay     ) a where a.departuredate > a.arrivaldate order by a.arrivaldate 	0.00494735888725821
14962814	36493	query date range columns with list of date parameters	select date_valid_from, date_valid_to, value  from my_table m join (select to_date('01-feb-2013') date_param from dual union all       select to_date('05-feb-2013') date_param from dual union all       select to_date('06-feb-2013') date_param from dual union all       select to_date('11-feb-2013') date_param from dual union all       select to_date('16-feb-2013') date_param from dual) d   on m.date_valid_from <= d.date_param and m.date_valid_to >= d.date_param 	0.000102064776526732
14963732	21143	how to loop through rows in two tables and create a new set based on the merged results in sql	select * from tableb union all select * from tablea where tablea.pk not in (select pk from tableb) 	0
14964051	2753	associating two nodes at the same level of hierarchy with pl/sql	select id_xml,         extractvalue(xml, '/item['||r||']', 'xmlns="xpto"' ) item,        extractvalue(xml, '/product['||r||']/@type', 'xmlns="xpto"' ) type,        extractvalue( xml , '/product['||r||']/model', 'xmlns="xpto"' ) model,        extractvalue(xml , '/product['||r||']/date', 'xmlns="xpto"' ) dte,        extractvalue( xml , '/product['||r||']/year', 'xmlns="xpto"' ) year   from (select id_xml, extract(archive, '/listitens2/*', 'xmlns="xpto"') xml, rownum r            from xml_product,                 table(xmlsequence(extract(archive, '/listitens2/item', 'xmlns="xpto"'))) nfe           where id_xml = xxx); 	0.000298464535955433
14965747	18992	select every other row in mysql without depending on any id?	select  * from    (         select  *         ,       @rn := @rn + 1 as rn         from    table1         join    (select @rn := 0) i         ) s where   rn mod 2 = 0  	0
14967599	23971	mysql inner join with multiple values in a column	select     t1.id_t1,     t1.name,     group_concat(t2.value separator ', ') as values_t_2 from     t_1 t1     inner join t1_t2 t1t2 on (t1.id_t1 = t1t2.id_t1)     inner join t_2 t2 on (t1t2.id_t2 = t2.id_t2) group by     t1.id_t1 	0.147037505389242
14967809	19944	return the data are max datetime and different identity different row - mysql	select        * from          tbl_locate as a inner join      (     select    mainid, max(datetime) as datetime     from      tbl_locate     group by  mainid ) as b on            a.mainid = b.mainid and           a.datetime = b.datetime where b.mainid in(1,2,3) 	0
14968255	36190	mysql query - one query to create table showing sales by month	select  sellername,      sum(if(reportmonth = 201206, 1.0)) as jun, sum(if(reportmonth = 201207, 1.0)) as jul, sum(if(reportmonth = 201208, 1.0)) as aug, count(*) as ytd from onlinedata group by sellername  order by sellername desc limit 30; 	0.000202111133630318
14968414	40242	mysql "truly distinct" join	select distinct subscriber.* from subscriber left outer join purchase on (subscriber.email = purchase.email and purchase.product_id = 1) where purchase.product_id is null 	0.760749264374239
14969053	5341	how to query into 2 columns the same field?	select t.*, b.uname as buyername, s.uname as sellername from transaction t join      user b      on t.buyer = b.uid join      user s      on t.seller = s.uid 	0
14969554	39465	what sql statement will return rows with a matched date and datetimes?	select pf.timestamp, tf.timestamp, date from stnrain s join      puyforecast pf      on date(pf.timestamp) = s.date and         hour(pf.timestamp) = 18 join      tacforecast tf      on date(tf.timestamp) = s.date and         hour(tf.timestamp) = 18 	0.00565449996223686
14970326	10482	on mysql 5.1, how can i query a specific partition?	select result, partition, count(id) from (     select result, id,       case when id < 10000 then p1            when id < 20000 then p2       .....       end as partition     from       table ) s1 group by partition, result 	0.735218514096248
14970466	19992	sql join if value exists in other table then count it	select a.[key], count(a.[key]) as cnt, isnull(sum(b.bcnt), 0) as [has num?] from #tablea a left outer join (     select b.userid, 1     from #tableb b     where len(b.num) > 0     group by b.userid ) b (userid, bcnt) on b.userid = a.userid where len(a.[key]) > 0  group by a.[key] 	0.00225934442384882
14971191	25572	how to select 2 table with condition and show all data	select * from store_profile sp left join store_fee sf on (sf.store_id = sp.id) 	6.87591926912747e-05
14971248	38482	how do i select the count of records, then group them by a foreign key?	select s.country, s.supplierid, s.companycame, count(*) as number_of_products_supplied from suppliers s  join products p on s.supplierid=p.supplierid where s.country in ('usa', 'uk') group by s.country, s.supplierid, s.companycame 	0
14971794	33475	how to get minimum date by each records from multiple records	select   caseno,   entry_date,   (select min(entry_date) from cases subc where subc.caseno=c.caseno group by caseno) as minentrydate from cases c 	0
14971816	36306	mysql - selecting the latest records before a given date in a join	select t2.serial, t2.t2data, t1.t1data, t1.t1date from   (select t2.serial, t2.t2data, t2.t2date,          (select max(t1date)             from test1 t1            where t1.serial = t2.serial              and t1.t1date <= t2.t2date) as t1date   from test2 t2) t2   left outer join    test1 t1 on t2.serial = t1.serial and t2.t1date = t1.t1date; 	0
14972146	36569	mysql joins and order by in php / mysql	select i.*, s.sortorder from items i, sorting s where i.id = s.itemid    and s.catid = 3  order by s.sortorder 	0.753632017202039
14972514	13173	sql selecting rows with same field value	select name, count(*) as count from (     select distinct id, name     from mytable) as sq group by name 	0
14973163	15068	mysql query to count id	select count(`id`) as reccount   from      (select `id` from table1       where tid= '101' and `status` =  1      union all     select `id` from table2       where tid= '101' and `status` =  1      union all     select `id` from table3      where tid= '101' and `status` =  1) t 	0.0364770682698381
14973871	31596	i want to compare 2 columns and mark the values that dont have a match	select     d.address,     d.type,     d.name,     iif(t.name is null, false, true) as match_found from     db_total as d     left join tagnames_ea as t     on d.name = t.name; 	0
14975037	41208	display row and count of referenced row in sql select statement	select c.categoryid, c.categoryname, count(*) as itemcount from category c inner join items i on i.categoryid = c.categoryid group by c.categoryid, c.categoryname 	0
14975058	5200	how to find out data from more than one tables in mysql	select  * from    table1         inner join table2             on table1.table1id = table2.table1id         left join table3             on table2.table2id = table3.table2id; 	0
14976058	34225	how to group by within a table that doesn't have attributes that can be grouped on sql	select      year(o.orderdate) as "year",      datename(quarter, o.orderdate) as "qtr",      c.categoryname,      sum(dbo.saleafterdiscount(od.unitprice, od.quantity, od.discount)) as "salesum" from      orders o      join      [order details] od on od.orderid=o.orderid      join      products p on od.productid=p.productid      join      categories c on c.categoryid=p.categoryid where      o.orderdate >= '19970101' and o.orderdate < '19990101'      and      c.categoryname like 'c%' group by      year(o.orderdate),      datename(quarter, o.orderdate),      c.categoryname; 	0.000975584374214057
14976817	23418	queries using temp tables	select * from geo_locationinfomajor_tbl  where geo_locationinfom_taluka in (select geo_locationinfom_taluka from #temp) 	0.262494051788359
14977874	40252	finding duplicates with two similar columns and one distinct	select * from (     select id, title, count(*) as numoccurrences     from table t     group by id, title     having ( count(*) > 1 ) ) t cross apply (     select distinct ralph     from table     where id = t.id and title = t.title ) t2 	4.87809650570675e-05
14979037	3422	returning one row from inner join right table in oracle	select c.c_unit_code as bu,'eplc' as product, a.bene_nm as customer, a.c_main_ref, a.c_trx_ref, a.pres_ccy, to_char(a.pres_amt) as pres_amt, a.pres_dt as pres_date, a.doc_stat, '' as appl_response, a.settle_status as settle_status from e_em_nego a, eplc_master c where a.cls_drwg_flg = 'no' and a.c_main_ref = c.c_main_ref      and a.c_main_ref = (      select c_main_ref from cpyt_schedule b      where b.cpyt_unpaid_flag = 't' and b.c_main_ref = a.c_main_ref and rownum=1) 	0.0569664982879316
14979392	9018	set user status based on field values	select userid, case when max_lvl = 1 then 'beginner'                     when max_lvl = 2 then 'expert'                     when max_lvl = 3 then 'master' end as certificationlevel from   (select userid, max(case when certificationlevel = 'beginner' then 1                       when certificationlevel = 'expert' then 2                       when certificationlevel = 'master' then 3 end) as max_lvl   from test   group by userid) test; 	0
14979475	11153	how can i use if statement in sql server in order to show or hide some specific columns	select id, name,      case when paymentmethod = 0 then 'in cash' else 'check' end as payby,     case when paymentmethod != 0 then paymentmethod else 0  end as serialnumber,     amount, bank from [mytable] 	0.0247069728064651
14979852	40187	mysql joining 2 tables together in one query	select distinct businesses.*  from businesses a inner join bus_parents b on a.business_id = b.bus_parent_parent  where a.business_asking_price > 1  and a.business_location = 11  order by a.business_id desc 	0.00554563036696012
14980238	12668	mysql: getting the diff between 2 dates which come from a sub select + group them by a criteria?	select name, max(date) - min(date) as date_diff from ( select    concat(sfoa.firstname, ' ', sfoa.lastname, ' ', sfoa.postcode) as name,   sfo.created_at as "date"       from sales_flat_order sfo        join sales_flat_order_address sfoa        on sfo.entity_id = sfoa.parent_id        where sfoa.address_type = 'shipping'        and sfoa.lastname = 'doe' ) d group by name having count(name) > 1 	0
14980288	7190	mysql : count row where sum of left day is less than 30	select count(*) as exp_pax  from   user_db  where exp_date<=timestampadd(day, 30, now())        and exp_date >= now(); 	0.000166067836293439
14980423	32643	join the same table	select  date,         sum(case when facility = 3 then 1 else 0 end) `facility 3 count`,         sum(case when facility = 1 then 1 else 0 end) `facility 1 count` from      badge where     xtype = 19 and                 date between 'some_date' and 'some_date' group     by  date 	0.0111762095683996
14980630	4540	how to sum query 3 tables?	select sum(coalesce(txnvolume,0)) from a inner join b on a.bid = b.bid inner join c on c.id = b.cid where c.custid = 1 and c.prodid = 1 	0.0371596812675609
14982231	22437	join multiple table on mysql	select  a.name, b.description, c.qty from    staff a         cross join services b         left join staffservices c             on a.id = c.staff_id and                 b.id = c.services_id order   by a.name, b.description 	0.101402816858796
14983042	35898	select all users that belong to a certain group, complicated query	select  `persons`.`id`,         concat_ws(\' \', `fname`, `lname`) as `full_name`,         `job_title`,         `email`,         `phone`,         `participant_group_memberships`.`memberships` from    `persons`          join `pers_department`         on (`pers_department`.`pers_rid` = `persons`.`id`)         join          (select `participant`, `name`,                 group_concat(`groups`.`name` order by `groups`.`name`                             separator  \', \') as `memberships`          from   `group_memberships`                  join `groups` on (`groups`.`id` = `group_memberships`.`group`)          group by `participant`          having sum(case when name = 'search_query_group' then 1 else 0 end) > 0         ) as `participant_group_memberships`         on (`participant_group_memberships`.`participant` = `persons`.`id`) where true . $where . ' order by `full_name` 	0.000233567047579469
14984458	25355	php picking time intervals from database?	select `timestamp`   from yourtable   where `timestamp` >= (      select max( `timestamp` ) max       from  yourtable   ) - ( 60 *15 )  	0.000518283813354309
14986616	37511	3 table sql query	select d.dname as dealname, d.description as dealinfo,      r.description as restaurantinfo, r.name as restaurant name      from deal d, restaurant r, customer c      where r.restaurantid = d.restaurantid, d.dealid = c.dealid,     c.customerid = 'whatever you want' 	0.154165004553916
14989166	39760	is there a method to list all objects such as views that use a synonym?	select * from sys.sql_expression_dependencies where referenced_id = object_id('<syn schema>.<syn name>') 	0.0623299002466695
14989297	15490	check whether set of rows exists in production	select criteriaid from criteria jbcrv1, (             select distinct jbcrv2.criteriaid as criteriaid              from wipcriteria jwbcrv1              inner join criteria jbcrv2                 on    jwbcrv1.criteriaval= jbcrv2.criteriaval                 and   jwbcrv1.criteriatext = jbcrv2.criteriatext             where  jwbcrv1.criteriaid = #{criteriaid}             group by jbcrv2.criteriaid having count(1) =                  (select count(1)                   from wipcriteria                   where criteriaid = #{criteriaid} )          ) result_table         where jbcrv1.criteriaid = result_table.criteriaid         group by jbcrv1.ben_crtr_id having count(1) =                  (select count(1)                   from wipcriteria                   where criteriaid = #{criteriaid} ) 	0.000837697364798493
14989370	36021	sql left join multiple tables and count values conditionally in each table	select     `kp_survey_id`,    coalesce( q.cnt, 0 ) as questionsamount,    coalesce( s.cnt, 0 ) as sessionsamount    coalesce( p.cnt, 0 ) as parentqamount,  from `survey`    left join                           ( select count(*) cnt, kf_survey_id as cnt        from questions       group by kf_survey_id ) q      on survey.kp_survey_id = q.kf_survey_id    left join        ( select count(*) cnt, kf_survey_id       from session       where session_status = 'started'         group by kf_survey_id ) s      on survey.kp_survey_id = s.kf_survey_id    left join                   ( select count(*) cnt, kp_parent_survey_id       from parentsurvey       group by kp_parent_survey_id ) p      on survey.kf_parent_survey_id = p.kp_parent_survey_id 	0.000260717000964525
14989927	9093	sql sliding window - finding max value over interval	select  *,         (         select  sum(value)         from    mytable mi         where   mi.tstamp between m.tstamp - '2.5 minute'::interval and m.tstamp + '2.5 minute'::interval         ) as maxvalue from    mytable m order by         maxvalue desc limit   1 	0.0381807749513669
14992373	1799	how to use a result from a query with order by clause?	select status, date    from red_table inner join blue_table on red_table.id = blue_table.id     group by 1, 2 	0.403340262460164
14994149	33692	trying to get the date of the first and last day of a week, given an arb. date	select to_char(date_col, 'iw') w, trunc(date_col, 'd') st, trunc(date_col, 'd')+6 et from your_table 	0
14994357	6716	get the top 5 of each distinct column value	select group, name from(  select group, name, rank() over (partition by group order by name desc) as rankname    from yourtable)     where rankname <= 5 	0
14995000	14960	sql inner join more than two tables	select *  from table1 inner join table2 on       table1.primarykey=table2.table1id inner join       table3 on table1.primarykey=table3.table1id 	0.208211267346945
14995233	30360	count of each rows in sql server 2008 table	select [column name],count(*) from [table name] group by [column name] 	0.000113724460671104
14995646	33190	merge related records	select      reservationday,      max(sleighseats) as sleighseats,      max(cabseats) as cabseats,      max(isfullmoon) as isfullmoon,     max(overridetext) as overridetext from (     select          day(reservationdate) as reservationday,          sum(sleighseats) as sleighseats,          sum(cabseats) as cabseats,          0 as isfullmoon,          '' as overridetext     from reservations     where month(reservationdate) = 2     group by reservationdate     union     select          day(calendardate) as reservationday,          0 as sleighseats,          0 as cabseats,          isfullmoon,          overridetext     from calendaroverrides     where month(calendardate) = 2     group by calendardate, isfullmoon, overridetext ) as subtbl  group by reservationday order by reservationday, isfullmoon 	0.0013124216868278
14996202	21870	can i do a mysql command to filter and delete duplicated entry	select t6.company_id,t6.industry from (select t5.company_id,t5.industry, row_number() over (partition by t5.company_id order by t5.company_id) rn from  (select t3.company_id,t4.industry from (select t2.company_id,max(t2.count) count from( select m.company_id,m.industry,t1.count from linkage m join (select n.industry,count(n.industry) count from linkage n group by n.industry order by count desc)t1 on m.industry = t1.industry order by m.company_id)t2 group by t2.company_id order by t2.company_id)t3 join ( select m.company_id,m.industry,t1.count from linkage m join (select n.industry,count(n.industry) count from linkage n group by n.industry order by count desc)t1 on m.industry = t1.industry order by m.company_id)t4 on t3.company_id = t4.company_id  and t3.count = t4.count)t5 )t6 where t6.rn = '1' 	0.00984349918076255
14996343	39380	getting full name query	select concat(`employee`.`f_name`,                  ' ',                   ifnull(concat(left(`employee`.`m_name`, 1),'. '),''),                  `employee`.`l_name`)    from `employee` 	0.305441364984632
14997694	3459	select specific columns by show table staus query	select * from information_schema.tables where table_name = 'mytablename'; 	0.00054586674387452
14998071	11547	grouping rows in tsql	select campaignid, [1] as rate1, [2] as rate2, [3] as rate3 from  (select campaignid, ratenumber, ratevalue from campaignrate) p pivot ( sum (ratevalue) for ratenumber in ( [1], [2], [3] ) ) as pvt order by pvt.campaignid;     go 	0.0470191237126081
14999187	36931	plpgsql function that returns multiple columns gets called multiple times	select (y).* from  (    select my_aggregate_function(border, lower_limit, upper_limit, operation) as y    from (       select (x).*, operation       from  (          select my_function(ca.timeslice_id) as x, agc.operation          from   geometry_component agc          join   volume             av  on av.id = agc.volume_id          join   volume_dependency  avd on avd.id = av.contributor_id          join   my_rowset_function('2013-02-22') ca on ca.feature_id = avd.id          where  agc.timeslice_id = 12345          order  by agc.sequence          ) sub1       )sub2    )sub3 	0.0147286750519546
15000217	25724	how to get single row form group	select table1.name1, max(table2.address) address from table1     join table2        on table1.key=table2.key group by table1.name1 	0.000323975858433988
15000924	5947	sybase sql select statement to collapse and condense rows by an id	select t1.id, t1.name, t2.dept, t1.cat  from table1 as t1      inner join table1 as t2 on (t1.id = t2.id) where t2.dept is not null and t1.name is not null 	0.0234936803735136
15001701	31323	oracle - junction tables and connect to prior	select parent_task.*      from (     select  parent_task_id, item_id, task_id, level         from (             select                  task.task_id parent_task_id,                  task_item.item_id,                  item.task_id task_id             from                  task, task_item, item             where                  task_item.task_id = task.task_id             and                  item.item_id = task_item.item_id) properly_structured_parent_table             start with task_id = :task_id         connect by prior parent_task_id = task_id      ) task_hierarchy, task parent_task where parent_task.task_id = task_hierarchy.task_id; 	0.0712339482318888
15004018	6014	how do not to round the number in sql	select   customer,   jobtype,   sum(sthours),   sum(othours),   sortmonth,   str((cast(sum(othours) as decimal)/sum(sthours) ),5,2) as ratios from    #data group by   customer,  jobtype,  sortmonth 	0.0238495693293909
15006039	27262	sql remove duplicate rows based on other rows	select * from t where not exists (select 1 from t t2                   where t2.customer = t.customer and                         t2.program = t.program and                         t2.time - t.time < 3.0/24 and                         t2.time > t.time                  ) 	0
15006183	7345	getting the count and sum of rows grouped by category in a prepared statement	select `work`, count(*) as sessions, sum(`amount`) as total from work_times group by `work`, `amount` 	8.63084796333911e-05
15008338	26527	searching column description description meta across all tables	select schemas.name schemaname      , tables.name tablename      , columns.name columnname      , extended_properties.value extendedproperties   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  inner join sys.extended_properties     on tables.object_id = extended_properties.major_id    and columns.column_id = extended_properties.minor_id    and extended_properties.name = 'ms_description'    and cast( extended_properties.value as nvarchar(max) ) like '%search%'; 	9.58324635426138e-05
15009473	3774	mysql - how to query a table, group by name and count of titles in the same table?	select name, title, count(*) titles from yourtable group by name, title 	0
15010966	1889	can the natural-join be seen as a subset of the equi-join and theta-join?	select * from r  where some_attributes in (     select some_comparable_attributes from s) 	0.732672924583707
15011130	35233	concat column value and variable with specific length in mysql	select   `products`.`id`,   `product_name`,   `category_id`,   concat(symbol, lpad(products.id,5,'0')) as code from products   inner join categories     on products.category_id = categories.id; 	0.00721518867359301
15011262	13825	sql query (and nspredicate) help: minimum value with group by	select min(id), name, min(value) from yourtable group by  name 	0.698244501294992
15011521	5296	comparing quarterly sales from q4 to q1	select a.year, a.quarter as q1, isnull(b.quarter, c.quarter) as q2, isnull(b.sales, c.sales) - a.sales as [sales increase] from sales a left join sales b on a.quarter = b.quarter - 1 and a.year = b.year left join sales c on a.quarter = 4 and c.quarter = 1 and a.year = c.year - 1 	0.0115988142783949
15012482	17916	how to run a query where it displays all items of a xml node?	select t.n.value('@id', 'varchar(10)') from a   cross apply z.nodes('/roles/role') as t(n) 	0.00349000275866856
15014189	18713	adding a loop to return individual rows that are grouped together in a select query	select  b.*, c.date2 from    (             select a.work, a.amount,                     count(*) totalcount,                     sum(amount) totalamount             from tablename a             group by a.work, a.amount         ) b         inner join         (             select a.work, a.amount, date_format(date,'%d %m %y') date2,                     date             from tablename a         ) c on b.work = c.work and b.amount=c.amount order by b.work, b.totalcount, c.date 	0
15014713	36933	mysql - count records in one table and sum records in another table	select event.name as name, count( * ) num_attendee ,amount from attendee right join event on event.id = attendee.event_id  left outer join(     select event_id,amount=sum(amount)     from gifts     group by event_id ) gifts on gifts.event_id=event.id where event.company_id =6 group by event.name,amount 	0
15014767	22096	query to eliminate duplicates and report nulls	select      scandata.barcode,      scandata.scandate,      scandata.scannerid,     barcode.productid from     scandata left join     barcode on     scandata.barcode = barcode.barcode join  (     select          barcode,          max(scandate) scandate      from          scandata      group by barcode ) latest on     latest.barcode = scandata.barcode and latest.scandate = scandata.scandate order by     barcode 	0.382412480075054
15015286	22847	how to group by hour and 30 minutes	select replace(date_format(datetime,'%h %p'),                ' ' ,                if(ceil(minute(datetime)/30)*30=60,':30 ',':00 '))  as hour_time        , action     from table1 group by 1 	0.000427122987734772
15015749	38670	sort table by three columns	select table1.buyer, qty, item_id  from orders table1,   (select buyer, count(*) as count from orders group by buyer) as table2   where table1.buyer = table2.buyer    order by count desc, qty, item_id; 	0.0027869028095162
15016214	34470	how to combine this two mysql query using group by	select station_id,sum(case when bet_void = 0 then 1 else 0 end) as bet_counts,        format(sum(case when bet_void = 0 then price else 0 end),2) as gross,        sum(case when game_type_id = 1 then 1 else 0 end) as count from bets b where date_created >= '2013-02-12 00:00:00' and date_created < '2013-02-23 00:00:00' group by station_id 	0.297941093492054
15016371	23333	sql adding two columns (datetime)	select dateadd(month, loanperiod,  checkoutdate) as lastreturndate 	0.0045691542455531
15016373	35513	calculating overall rating	select avg(score) from tbl 	0.0738870531537233
15017860	40738	concatenate a single column value depending on condition	select  b.quoteitemid,          a.quoteno,         a.customername,         b.itemcode,         c.batchlist from    quotationmaster a         inner join quoteitemdetails b             on a.quoteid = b.quoteid         inner join         (           select                quoteid,                 itemid,                stuff(                    (select ', ' + batchno                     from   quotebatchdetails                     where  quoteid = a.quoteid and                            itemid = a.itemid                     for xml path (''))                     , 1, 1, '')  as batchlist           from  quotebatchdetails as a           group by quoteid, itemid         ) c on  b.quoteid = c.quoteid  and                 b.itemid = c.itemid; 	0
15018163	16102	how to fetch the top record with in the every 15 mins slot?	select * from    (     select       dateadd(         second, -1 * datepart(second, datetime)         , dateadd(minute, mod(datepart(minute, datetime),15) * -1, datetime)       )       , feederid, vr, vy, vb       , rank() over (         partition by dateadd(           second           , -1 * datepart(second, datetime)           , dateadd(minute, mod(datepart(minute, datetime),15) * -1, datetime)         ) order by datetime desc       ) rnk    ) where rnk = 1 	0
15019448	40849	how to concatenate a selection of sqlite columns spread over multiple tables?	select a.col1 || a.col2 ||  b.col3 as 'sum' from table1 a, table2 b where a.id = b.id; 	8.08118925370108e-05
15021464	18355	how to select from two tables and display only what you want?	select * from tish_user, tish_images where tish_user.user_id = tish_images.user_id and tish_images.prof_image = 1; 	0
15024494	28995	how to select some rows from one table and some rows in another with data in trid table?	select id, name,  ifnull((select count from second s where s.id = f.id),0) as page, fourth.id_first from first left join fourth on first.id = fourth.id where fourth.id_first in (select id_first form fourth) 	0
15026244	22313	mysql order by relevance	select *,  ( (1.3 * (match(strtitle) against ('+john+smith' in boolean mode))) + (0.6 * (match(txtcontent) against ('+john+smith' in boolean mode)))) as relevance  from content  where (match(strtitle,txtcontent) against ('+john+smith' in boolean mode) )  order by relevance desc 	0.556141915317329
15027643	18481	mysql query two foreign key to one primary key	select  a.history_id,         a.message,         coalesce(a.id_klien, a.id_staf) userid,         coalesce(b.name, c.name) name,         coalesce(b.group, c.group) `group` from    history_ticket a         left join users b             on a.id_klien = b.user_id         left join users c             on a.id_staf = c.user_id 	0
15027856	38744	getting min date	select   a.id,   a.date,   b.name,   c.price from tablea a  inner join (    select id, min(date) as mindate     from tablea    group by id ) as mina on a.date = mina.mindate and a.id = mina.id inner join tableb b on a.id = b.id inner join tablec c b.id = c.id 	0.0295778622523365
15027891	29326	get maximum number of items recorded in mysql database	select city, count(city) total from roomrent group by city order by total desc limit 0, 5 	0
15028490	2403	sql create concatenated string	select      serviceentryid,      stuff(          (select '|' + cast(partid as varchar(5)) + '~' +                        partdescription  + '~' +                        coalesce(cast(servicetypeids as varchar(5)), 'null')  + '~' +                        coalesce(comment, 'null')           from tablename           where serviceentryid = a.serviceentryid           for xml path (''))           , 1, 1, '')  as resultlist from tablename as a where serviceentryid = 2 group by serviceentryid 	0.041751062910371
15029293	35130	join 2 tables with multiple distinct	select top100albums.songs, english_fm.artist, english_fm.album, english_fm.image    from top100albums, english_fm    where top100albums.songs = english_fm.album    group by english_fm.artist, english_fm.album, english_fm.image 	0.0357968345413586
15029959	8479	mysql | select distincted records	select  a.id as postid,         a.post_title as posttitle,         c.meta_value as categoryid,         d.name as categoryname,         a.post_date as date from    wp_posts a         inner join         (             select  post_title, max(post_date) max_date             from    wp_posts             group   by post_title         ) b on a.post_title = b.post_title and                 a.post_date = b.max_date         inner join  wp_postmeta c             on a.id = c.post_id         inner join wp_terms d             on c.meta_value = d.term_id where   c.meta_key = 'matchdayteamscategory' 	0.0225609412993205
15032780	37465	multiple joins between multiple tables	select m.modname, r.the_date, r.the_time, cm.modname as `mod covering name` from requests r join modid m on r.modid = m.modid join covered c on c.id = r.id join modid cm on cm.modid = c.cmodid 	0.0746812727991535
15033335	3250	sql exclude rows previously selected in another category	select min(site) as site,        data from   dbo.sample group  by data order  by site 	0
15033537	31206	sql server duplicate results to query after inner join	select     a.pk, b.pk, c.pk, d.pk .....     from table_a             a         inner join table_b   b on a.col=b.pk         inner join table_c   c on b.col=b.pk          inner join table_d   d on c.col=d.pk         ... 	0.634160172642015
15034188	33161	how to match records for two different groups?	select el.actualdate   , el.grp   , flag = case      when el.grp = 'b' then null     when prev.grp = 'b' then 1     else 0     end from event_log el   outer apply   (     select top 1 prev.grp     from event_log prev     where el.actualdate > prev.actualdate     order by prev.actualdate desc   ) prev order by el.actualdate desc 	0
15034256	24881	foreach() sql query get just unique results	select distinct(performanta_cpu) from $tbl_name order by cast(performanta_cpu as unsigned) desc 	0.0343367650689453
15034391	2153	how to join tables when primary key of one table is not the same as but contained within the primary key of the other table?	select * from table1 inner join table2 on concat('something', table1.id) = table2.id 	0
15036104	24308	querying the inner join of two tables with the same column name, column 'exname' in field list is ambiguous	select table1.name1, table2.name1, etc. 	0
15038397	40656	how to constuct a mysql query which will return a flag, either returning y or n based on the rows in another table?	select  distinct a.id,          if(c.id2 is null, 'n', 'y') flag from    foo1 a         inner join foo2 b             on a.id = b.id2          left join foo2 c             on b.id2 = c.id2 and                 c.foo = 2 	0
15039759	33757	sql select only the first row	select   [id], country, min(address), sum(price) as totalprice from     tblyourtablename group by [id], country order by [id] 	0.000134709630054089
15040340	1522	mysql: combine multiple related tables based on data in multiple rows	select ct.city, rg.region, co.country     from wp_pods_cities as ct, wp_podsrel as pr         inner join wp_pods_regions as rg             on rg.item_id = pr.related_item_id         inner join wp_podsrel as pr2             on pr2.item_id = rg.item_id         inner join wp_pods_countries as co             on co.item_id = pr2.related_item_id     where ct.city = 'albany'         and pr.item_id = ct.item_id         and pr.pod_id = 'pod_3'         and pr2.item_id = rg.item_id         and pr2.pod_id = 'pod_2'     order by co.country, rg.region 	0
15040602	16401	counting null values as unique value	select  count(distinct col1) + count(distinct case when col1 is null then 1 end) from    yourtable 	0.00045105989532323
15041935	5888	query to fetch detail of user	select  user_messages.messageid,         user_messages.message,         user_messages.sentby,         user_messages.visibility,         (             select  group_concat(  `post_images`.`image_id` separator ';')             from    `post_images`                     join user_messages                         on `post_images`.`messageid` =user_messages.messageid         )   as  `image_post_id`,         (             select group_concat(  `post_images`.`small_pic_path` separator ';')             from  `post_images`             join user_messages                 on `post_images`.`messageid` =user_messages.messageid         ) as small_pic_path,         (             select count(*)              from likes             where element_id=user_messages.messageid         ) as total_likes,          smsusers.*   from    user_messages         inner join smsusers          on user_messages.sentby = smsusers.id where   user_messages.userid= '1'; 	0.00139584057036537
15043693	17239	how can get data with multilanguage in one table (codeingiter , mysql , php )	select lp.title_post, lp.content_post, p.views_post,         group_concat(l.id_language) as l.support_language  from localization_posts lp inner join posts p on lp.id_post = p.id_post left join languages l on lp.id_language = l.id_language; 	0.00606145926303567
15046308	14579	joining results from another table	select i.*, group_concat(c.category_id) from item_table i left outer join      category_table c      on i.column_a = c.column_a and         i.column_b = c.column_b and         i.item_id <> c.category_id group by i.item_id 	0.000682001672961274
15046522	18554	mysql join 3 tables and counting another	select a.article_id, a.title, a.photo, a.date, a.description_long, a.author, group_concat(d.name) as `tag_names`, count( distinct c.comment_id ) as comments from article as a join article_tag as at on a.article_id = at.article_id left join comment as c on a.article_id = c.article_id left join tags d on at.tag_id = d.tag_id where a.article_id = 1 	0.005584371870521
15046820	37769	basic sql: how to use properties of one table as a lookup on other tables	select    case when a.cola = 'z' then z.cola else q.cola end cola,   case when a.colb = 'z' then z.colb else q.colb end colb from tablea a, tableq q, tablez z 	0.00215423731713085
15046980	37075	get averages of specific columns in a table using sqlite	select col1, avg(col2), avg(col3), avg(col4) from mytable group by col1 	0
15047156	15420	compute age in inner query then comparing with a value	select   f.facebook_id from fbuser f, wall w  where   (f.facebook_id=w.facebook_id)  and   (w.public_view='y')  and   (  (months_between( current_date, f.date_of_birth )/12)  >=24); 	0.0196947010268641
15048190	4588	mysql database - optimizing same multiple fields	select achievementnumber from tblachievements where userid = 15 	0.0500570794923751
15051068	30975	sql query for finding a guy with most friends?	select * from   (select f1.id1 as id3,                count(*) as count1         from   friend as f1         group by f1.id1) sub1 where  not exists ( select *                     from   (select f2.id1 as id2,                                    count(*) as count2                             from   friend as f2                             group by f2.id1) sub2                     where  sub2.count2 > sub1.count1); 	0.00398691670010431
15051596	94	sql query find avarage of kpi id for each employee id	select id, kpi_id, round(avg(scoure)) as avg_scoure from tmptable group by id, kpi_id; 	0
15052462	13044	sum of last month and total	select p.user_login,    sum(if(date(`when`) >= curdate() - interval 30 day,p.value,0)) sum,   sum(p.value) total_sum from user_value p join user u   on u.login = p.user_login group by p.user_login order by sum desc; 	0
15052957	20674	how to select a range of dates with each separate day	select * from ( select dates.date_from + interval a + b day dte from  (select 0 a union select 1 a union select 2 union select 3     union select 4 union select 5 union select 6 union select 7     union select 8 union select 9 ) d,  (select 0 b union select 10 union select 20      union select 30 union select 40) m, dates where dates.date_from + interval a + b day  <=  dates.date_to order by a + b ) e order by dte; 	0
15055997	25222	how to read selective data from sqlite?	select * from test where id >= 10 and id <= 20 	0.0267473268442872
15056542	4054	sql server: cast bool as integer	select (case when (column like '%string%') then 1 else 0 end)+100 	0.798058446118269
15056667	2891	picking out an id that is not related in both columns	select col2 from table where col2 not in (select col1 from table group by col1) 	0.000246522227028778
15058271	30010	sql getting monthly totals from table	select year,month,sum(price) from table  group by year,month  order by year desc, month desc 	0.000761675751177268
15058956	30971	sql query if appears more that once in one table display the other table data	select ownerid, fname, lname  from owner  where ownerid in (select ownerid                   from property                   group by ownerid                   having count(ownerid) >= 2) 	0
15060748	5105	not able to group the selected data	select * from test.college where courses_offered like concat('%',rtrim((select primary_subject from test.user where email = 'r.veer7@gmail.com')),'%')      or courses_offered like concat('%',rtrim((select secondary_subject from test.user where email = 'r.veer7@gmail.com')),'%')      or lower(location)in(select lower(location) from test.user where email = 'r.veer7@gmail.com') group by college.column_name order by college.first_column_name asc , college.second_column_name desc 	0.0665026250528878
15061462	29144	sql query latitude and longitude	select *  from [dbo].[enquirymaster]  where (latitude <= @lat and longitude <= @long        and latitude + 100 >= @lat and  longitude +100 >= @long) or (latitude >= @lat and longitude >= @long        and latitude - 100 <= @lat and  longitude -100 <= @long) or (latitude >= @lat and longitude <= @long        and latitude - 100 <= @lat and  longitude + 100 >= @long) or (latitude <= @lat and longitude >= @long        and latitude + 100 >= @lat and  longitude - 100 <= @long) 	0.696786426745035
15061675	24103	mysql: fetch limited results using group by clause on one table/view	select * from view_type where type = 'type_a' and name regexp 'ame' limit 4 union select * from view_type where type = 'type_b' and name regexp 'ame' limit 4 	0.0128810096951991
15062642	30342	sql query that fries the server	select a.* from eventos_centralita a  inner join  (     select idevent, max(fechahora)     from eventos_centralita       group by codagente ) as b on a.idevent = b.idevent 	0.45066728123867
15065785	21375	selecting data using a postgres array	select users.* from users where id in (     select unnest(a_postgres_array)     from t     where columnx = some_value     ) 	0.00904877351066272
15066534	7353	mysql concat string with result	select concat ( 'http: 	0.337081708271007
15066615	19465	mysql inner join and derived tables	select   *,   ((off_time - on_time)/(unix_timestamp('x') - unix_timestamp('y'))) as a from (select     r.equipment_id,     i.in_service,     if(time_on < 'x', unix_timestamp('x'), unix_timestamp(time_on)) as on_time,     (case when (time_off is null) then unix_timestamp(now()) when (time_off > 'y') then unix_timestamp('y') else unix_timestamp(time_off) end) as off_time       from r     left join i       on r.equipment_id = i.equipment_id) as t group by equipment_id 	0.719578099442144
15067128	35698	what is the best way to find only the non matching elements between two string arrays in postgresql	select array_agg(e order by e) from (     select e     from     (         select unnest(array[ 'a', 'b', 'c' ])         union all         select unnest(array[ 'c', 'd', 'e' ])     ) u (e)     group by e     having count(*) = 1 ) s 	0
15067808	21035	get all values from one-to-many relationship in one row	select   city.*,   group_concat(cinema_name) as `cinemas` from city   left join cinema     on cinema.city_id = city.city_id group by city.city_id 	0
15071730	10869	returning an output from two separate tables with sql	select products.product,        assets.asset,        count(assets_products.id) as count from assets cross join products left join assets_products     on (assets_products.asset_id = assets.id and         assets_products.product_id = products.id) group by products.product, assets.asset 	0.0053382959977
15072463	22742	2 conditions for the same column in a sql query	select r.date, count(*) as cnt from repinfo r    where month(r.date) = 2 and year(r.date) = 2013 group by r.date having sum(case when typeofdayid <> 2 then 1 else 0 end) = 0 	0.00200661628186412
15073018	13205	sqlite select distinct row that column is greater than another	select distinct(name) from bill where amount > payments 	0
15073449	9042	sql generate columns/data based on xml	select id,        x.n.value('(name/text())[1]', 'varchar(max)') as name,        x.n.value('(value/text())[1]', 'varchar(max)') as value into #t from t   cross apply t.xmlcol.nodes('root/item') as x(n) declare @sql nvarchar(max) declare @col nvarchar(max) select @col =    (   select distinct ','+quotename(name)   from #t   for xml path(''), type   ).value('substring(text()[1], 2)', 'nvarchar(max)') set @sql = 'select id,'+@col+'             from #t             pivot (max(value) for name in ('+@col+')) as p' exec (@sql) drop table #t 	0.00584697901802917
15073669	24152	split current query to get distinct items	select  datepart(year,f_downloadtimestamp) as var_year,          datepart(month,f_downloadtimestamp) as var_month,         datepart(day,f_downloadtimestamp) as var_day,         count(distinct f_downloadipaddress) total_downloads,         count(distinct case when f_product = 'product a'                             then f_downloadipaddress end) downloads_prod_a,         count(distinct case when f_product = 'product b'                             then f_downloadipaddress end) downloads_prod_b from tb_downloads group by datepart(year,f_downloadtimestamp),          datepart(month,f_downloadtimestamp),          datepart(day,f_downloadtimestamp) order by var_year desc, var_month desc, var_day desc 	0
15075146	32575	select count of dates older than x days	select count(distinct username) -         count(distinct case when datediff(now(), time) <= 30 then username end) as numusers from tracking 	0
15075177	38906	only get one occurance of a table row in mysql php based on id	select itemid, title from test group by itemid; 	0
15076205	672	searching inside a sql record with date limits	select order_number from t having sum(case when datediff(day, date, getdate()) < 2 and                      note like '%obc%'                 then 1 else 0            end) = 0 	0.191061958659867
15077518	21071	tsql join to get all records from table a for each record in table b?	select p.empid,   p.period,   case      when w.periodid is not null      then 'yes'      else 'no' end worked,   w.approveddate from (   select p.periodid, p.period, e.empid   from periods p   cross join (select distinct empid from worked) e ) p left join worked w   on p.periodid = w.periodid   and p.empid = w.empid order by p.empid 	0
15078716	5828	how to go through the data of a table using a where clause	select s1.[group], sum(t1.points) from table1 as t1     inner join soruce1 as s1       on s1.[group] = t1.[group]   group by s1.[group]   order by sum(t1.points) asc; 	0.0227527010058528
15084377	18468	how to iterate a string that is concatenate with select statement of sql server	select 'fields '+cast(row_number() over (order by column_name) as varchar(5))+': ' + column_name from information_schema.columns  where table_name = 'systemdefined' and table_schema = 'schemaasset' order by column_name 	0.00761299539772818
15085341	21914	specific status on consecutive days	select emp_id from ( select if((@prevdate!=(q.att_date - interval 1 day)) or (@prevemp!=q.emp_id) or (q.att_status != 2), @rownum:=@rownum+1, @rownum:=@rownum) as rownumber, @prevdate:=q.att_date, @prevemp:=q.emp_id, q.* from ( select emp_id , att_date , att_status from org_tb_dailyattendance, (select @rownum:=0, @prevdate:='', @prevemp:=0) vars where att_date between '2013-01-01' and '2013-02-15' order by emp_id, att_date, att_status ) q ) sq group by emp_id, rownumber having count(*) >= 10 	0
15085718	21088	how to join two tables with multiple rows in the one table?	select  users.userid,   h.time  from   users       left outer join hits h        on(         users.userid = h.userid     ) 	0
15085945	7914	grand total from datediff	select  sum(datediff(d,bookings.arrivaldate,bookings.departuredate)) as 'pitchnights' from    bookings where   bookings.arrivaldate >=@arrivaldate and          bookings.departuredate <=@departuredate 	0.00176434778497114
15086854	18329	totalling a multiple datediff columns	select sum(totalcapacity)     from     (         select           capacity.startdate           ,capacity.enddate           ,datediff(d, capacity.startdate, capacity.enddate) + 1 as daysopen           ,capacity.capacity           ,(datediff(d, capacity.startdate, capacity.enddate) + 1) * capacity.capacity as totalcapacity         from           capacity           where capacity.startdate >= '01 jan 2010' and capacity.enddate <= '31 dec 2010'     ) t 	0.131699056440454
15086936	13762	how to find min value in sql, if there are two identical?	select * from table where age = (select min(age) from table) 	5.25134426411348e-05
15087281	34523	in db2 how to find all the stored procedures having a given text in it	select routinename,text from syscat.routines where language='sql' and locate('<table-name>',text)>0 	0.000846692340524011
15087771	20161	export mysql column to text file and add string	select concat("http: from mytable order by id into outfile 'c:/wptitles.txt' lines terminated by '\r\n'; 	0.00667130036794911
15088124	10596	creating calendar	select c.date from data_table d          inner join      calendar_table c          on c.date between d.start_date and d.end_date 	0.60926286198778
15088216	167	working out a quiz score from two tables	select r.userid,  sum(case when find_in_set(r.value, q.value) then 1      else 0      end) as score    from responses r left join questions q on r.questionid = q.questionid where q.attribute = 'correct' group by r.userid order by score desc ; | userid | score | |  user3 |     3 | |  user2 |     1 | |  user1 |     0 | 	0.0260903578513385
15089678	5567	how to use group by on this table	select location     ,sales_contract_nbr     ,name     ,sum(abspostamt * nbpostamt) / abs(sum(nbpostamt)) postamt     ,abs(sum(nbpostamt)) nbpostamt     ,sum(abspostamt * nbpostamt) postamttotal from (      select location         ,sales_contract_nbr         ,name         ,postamt         ,abs(postamt) abspostamt         ,sum(case when postamt >= 0 then 1 else -1 end) nbpostamt     from tblmasdata      group by location         ,sales_contract_nbr         ,name         ,postamt         ,abs(postamt) ) t group by location     ,sales_contract_nbr     ,name     ,abspostamt having sum(abspostamt * nbpostamt) != 0 	0.539172739920175
15090105	6672	getting newest timestamp mysql	select * from table1 order by time desc limit 1 	0.004780380917287
15091826	12880	find tables without clustered index but with primary keys on a table	select             so.name as tablename,             si.name as indexname,             si.type_desc as indextype,             si.is_primary_key from             sys.indexes si             join sys.tables so on si.[object_id] = so.[object_id] where             si.type in (0, 2)             and si.is_primary_key=1 order by             so.name 	0.00457923896327275
15091943	24219	check for a string in a clob	select tbl3.*   from tbl1        inner join tbl2                on tbl2.art_id = tbl1.art_id        inner join tbl3                on tbl3.a1 like '%' || tbl1.project_line_id || '%'  where tbl2.type = 3; 	0.0202190110630992
15093527	32495	sql query with comma separated values	select      l.svalue     , substring((                         select c.slast + ',' + c.sfirst + ';'                         from contactinfo c                         inner join contactrole crole                         on crole.idcontactinfo = c.idcontactinfo                         where c.idcompany = '<<blah>>' and c.idcontactrole = cr.idcontactrole                         for xml path('')                     ), 1, 1000000) from contactrole cr inner join lookupdata l on cr.idlookuprole = l.idlookupdata 	0.00356478481467011
15093644	31904	get previous and next row from mysql based on rank	select  uo.*, count(*) as rank from tracks ui, tracks uo  where (ui.point, ui.id) >= (uo.point, uo.id)    and uo.id = 10; 	0
15094178	34078	sql list products that are not already ordered	select itemid, productname from products where itemid not in (     select itemid     from orders     where orderid = x ) order by productname 	0.000255664248460686
15094408	9158	select a user that has no post named foobar	select * from `users` u where not exists (     select 1      from `posts`      where title = 'foobar'     and user_id = u.id ) 	0.000437734150661145
15095258	1687	check multiple values in a single column for the same reference	select * from orders o1 where o1.city = 'austin'   and exists (select ordernumber               from orders o2               where o1.ordernumber = o2.ordernumber               group by ordernumber               having count(distinct city) >1) 	0
15095288	602	adding another select	select   count(a.aircraft) as total,   a.aircraft,   b.fullname as aircraft_name,   b.registration as reg from db_pireps as a join db_aircraft as b    on a.aircraft = b.id where pilotid = {$pilotid} group by aircraft order by total desc limit 6 	0.0218041490438472
15096632	10802	how can i create a view or table out of two tables so that their rows are not merged?	select date, description, fee, number, money from table1     union all select date, description, 0 fee, 0 number, money from table2 order by date 	0
15096891	31870	getting higher results than expected with 2 joins	select     p.id,     coalesce(c.comments,0) as comments,     coalesce(a.answers, 0) as answers from     posts_tbl as p     left join (         select post_id, count(*) as comments         from post_reply_tbl         where type in (1,3)         group by post_id     ) as c on p.id = c.post_id     left join (         select post_id, count(*) as answers         from post_reply_tbl         where type = 2         group by post_id     ) as a on p.id = a.post_id order by id ; 	0.620713573657619
15098133	25388	using pivot over a group by query	select  mainstate [state],         [1] type1,         [2] type2,         [3] type3 from (  select mainstate, customertypeid, count(1) [counter]          from customers          where customertypeid in (1,2,3)          and mainstate != ''          group by customertypeid, mainstate) as nonpivoteddataforreport2 pivot(sum([counter]) for customertypeid in ([1],[2],[3])) as pivoteddatareport2 	0.78919533882125
15101394	2952	postgresql fetch a row without knowing table detail infomation	select * 	9.90083240339844e-05
15101457	38091	select rows with matching columns from sql server	select t1.id, t1.part_type, t1.station_type from yourtable t1 where exists (select part_type, station_type               from yourtable t2               where t1.part_type = t2.part_type                 and t1.station_type = t2.station_type               group by part_type, station_type               having count(id) > 1) 	0.000254425764947109
15101941	26506	count number of distinct rows for multiple values	select distinct @pr := prop,     (select count(1) from tbl where prop = @pr limit 1),     (select count(1) from          (select *, count(*) cnt         from tbl         group by usr, prop         having cnt = 2) as tmp         where `tmp`.prop = @pr limit 1) from tbl; 	0
15103322	9982	create an oracle data dictionary of tables with more than 2 indexes	select table_name   from user_indexes   group by table_name   having count(*) > 2; 	0.0275959132573145
15103590	27805	how to query a query result?	select a.skucode, a.productcode, a.productname, a.totalorder, a.serialno from ( select top 100 tblproducts.skucode,tblproducts.productcode, tblproducts.productname, count(tblorders_products.delivered) as totalorder, tblproducts.serialno     from tblorders_products inner join tblproducts on tblorders_products.productid = tblproducts.productid     where tblproducts.productname is not null     group by tblorders_products.delivered, tblorders_products.productid, tblproducts.skucode,     tblproducts.productname,tblproducts.productcode     order by totalorder) a order by a.serialno 	0.279698848128356
15105933	2730	simple join with maximum per group?	select t.id, t.userid, t.time from (   select h1.*, count(*) pos from hits h1     left join hits h2       on h2.userid = h1.userid and h2.time <= h1.time   group by     h1.userid, h1.time) t where pos <= 2; 	0.0654723761018008
15105954	393	sql query for find out in/out time in a office	select firstname,lastname,cardnumber,department, date , min(time) as intime , max(time) as outtime , convert(varchar(8),(convert(datetime,max(time),110) - convert(datetime,min(time),110)),108) as duration from cardentryexittransactionview group by firstname, date,lastname,cardnumber,department 	0.0244542146682269
15107682	32353	query to get grouped items ranked?	select  id,          userid,          ranks from     (         select  id,                 userid,                 @group:=case when @temp <> userid then 1 else @group+1 end as ranks,                 @temp:=userid as clset         from    (select @group:= 0) s,                 (select @temp:= 0) c,                 (select * from hits order by userid, id) t     ) x order   by id 	0.000557081896837418
15110445	37645	query to get start and end date that a row changed in a table	select  id ,       value ,       date_start ,       (         select  date_start         from    yourtable yt2         where   yt1.id = yt2.id                 and yt1.date_start < yt2.date_start         order by                 yt2.date_start         limit   1         ) as date_end from    yourtable yt1 	0
15110871	14907	how generate serial number in mysql database?	select  @a:=@a+1 serial_number,          name  from    table1,         (select @a:= 0) as a; 	0.00118078197274383
15113039	19729	monthly average for datediff result	select  avg(datediff( fechas.bodega_recep_inf_1.fecha_recep, memos.sda.fecha_gen_sda )  as avg_date_difference from memos.sda inner join fechas.bodega_recep_inf_1  on memos.sda.num_sda = fechas.bodega_recep_inf_1.num_sda group by month( memos.sda.fecha_gen_sda ) 	0.00395267111762573
15113055	13648	sql server - joining two table to fetch data	select c.custid    ,c.custname    ,(select count(1) from customerorders where custid = c.custid) numberoforders    from customers c 	0.00094036915216157
15113058	436	sql server: ordering all data in alphabetical order but placing a particular item last	select * from (     select shipmethodid as useme, name as showme      from purchasing.shipmethod     union     select 0 as useme, 'n/a' as showme ) t order by (case when useme = 0 then null else showme end) 	0
15113354	19543	dynamic "insert into" query with user defined type	select     [firstname]   , [lastname]   , [birthday] from     (         select             [datarecordset]           , [datafield]           , [datavalue]         from [table]     ) data     pivot     (         min ([datavalue]) for [datafield] in         (             [firstname]           , [lastname]           , [birthday]         )     ) pvt 	0.181645392339304
15113569	3223	sql - sum of minutes between two timestamps by month	select datediff(minute, startdate, case when enddate > eomonth(startdate) then eomonth(startdate) else enddate end) from ... 	0
15115162	39498	if join return null then do following	select  a.id,         coalesce(b.name, c.altname, '-no name-') as `name`         c.start_date,         c.end_date,         a.other from    table1 a         left join table2 b             on a.nameid = b.tid         left join table3 c             on a.nameid = c.id 	0.209540303287226
15115475	33624	mysql extract average data from multiple group criteria	select instances.instanceid, location, avg(current) as avg_current,         avg(voltage) as avg_voltage, avg(current) * avg(voltage) as kw,         count(if(current > 0 and voltage > 0,                  instances.instanceid,                  0)) as instancedtime from instances inner join sets on instances.instanceid = sets.instanceid where sets.setid = arbitrary_number; group by instances.instanceid, location 	6.22080353030614e-05
15115717	27438	querying all data from mysql employees sample database	select * from  employees e join salaries s on e.emp_no = s.emp_no, join titles t on e.emp_no = t.emp_no,  join dept_emp de on e.emp_no = de.emp_no,depts, join departments d on d.emp_no = t.emp_no, join dept_manager dm on d.dept_no = dm.dept_no, join employees edm on dm.emp_no = edm.emp_no  	0.000196598458753331
15115852	28347	find out the date a cumulative sum value is reached	select reservation_property_id, min(reservation_date)  from (select if(@prevproperty != q.reservation_property_id,                  @runningtotal:=0,                  @runningtotal:=@runningtotal + payment_amount) as runningtotal,              @prevproperty := q.reservation_property_id, q.*       from (select *             from reservations r              inner join payments p                      on p.payment_reservation_id = r.reservation_id              , (select @runningtotal:=0, @prevproperty:=0) vars             order by r.reservation_property_id, reservation_date) q       ) sq where runningtotal >= 500 group by reservation_property_id 	0
15119319	39629	mysql help need for joining 2 tables with multiple results	select u.name, min(t.time_avail) from     user_table u     inner join     times_available t on u.user_id = t.user_id where t.time_avail > current_time group by u.user_id 	0.459377794368388
15124314	7855	select multiple tables with same id	select  c.date,     p.name,     c.name1,     c.name2,     t.date,     i.version,     c.price1,     c.price2,     c.price3 from calculated c, programs p, term t, imported i where c.programs_id = p.programs_id and (select imported_id from item it where c.programs_id = it.programs_id and rownum = 1) = i.imported_id and i.term_id = t.term_id; 	0.000821458526093835
15127051	34724	sql query for employee table	select e.emp_id, e.firstname, min(payment_date), et.paid_status  from emp_master e, emp_transaction et where e.emp_id = et.emp_id and et.paid_status= 'false'  group by  e.emp_id, e.firstname, et.paid_status 	0.0536424679929934
15127643	31706	i have a select query that gets me a single column as a result. now i need to put all those column values in csv format	select group_concat(timesheet_id) as timelist from   tablename into   outfile '/tmp/timeidlist.csv'   fields terminated by ',' enclosed by '"' lines terminated by '\n' 	0
15128246	3176	how do i join multible tables and sum values?	select t2.month, sum(t2.data), sum(t3.data), sum(t4.data) from table1 t1, table2 t2, table3 t3, table4 t4 where t1.data_id = t2.data_id and t1.data_id = t3.data_id and t1.data_id = t4.data_id and t2.month = t3.month and t3.month = t4.month group by t2.month; 	0.0264734708064073
15129655	28588	sql query: what groups is a given member not a member?	select * from group where id not in (   select group_id    from group_member_relations   where member_id = ?) 	0.0209485821465874
15130318	29470	how to turn string with commas into enum in sql / plsql	select dict_id as item_id from dictionary d where serial_number in  (      select to_number(regexp_substr ('1,2,3,4','[^,]+',1,level)) as id      from dual      connect by regexp_substr ('1,2,3,4','[^,]+',1,level) is not null ) 	0.0037621384699108
15130427	21524	get missed records using mysql	select   t1.id,   t1.name,   t2.category from   t1 left join t2   on t1.id=t2.id and t1.name=t2.name 	0.00590750439806583
15131116	13461	sql cast date time without hours, ordering issues also	select  ... convert(varchar, incident.createdate, 103) as entrydate, contactdetails.citycode, patient.insurance, from ...... 	0.00827909270672462
15131281	29186	inner join mysql empty entry	select cours.id as cid, cours.name as cname, date_format(cours.date,"%h:%i") as cdate, date_format(cours.date,"%a") as jour,sessions.id as sid,sessions.name as sname,sessions.restant,session_cours.session_id,session_cours.cours_id, isnull(cours.video_id) as isvid from cours,sessions,session_cours where cours.prof_id = :prof_id and sessions.prof_id = :prof_id and session_cours.cours_id=cours.id and sessions.id=session_cours.session_id and date_format(cours.date,"%y-%m-%d") >= :date_min and date_format(cours.date,"%y-%m-%d") <= :date_max and (select count(*) from cours_document where cours.id=cours_document.cours_id) = 0 group by cours.id order by date asc 	0.261587212637565
15133624	969	query to fetch data matching multiple values across db rows	select store from (   select distinct store, items   from your_table   where items in ('books','stationery','toys') ) group by store having count(0) = 3 	0
15133940	19595	using pdo and fetching links depending on usergroups	select l.id, l.title, l.pageid   from navigation_links as l  where not exists(            select lug.*               from navigation_links_usergroups as lug             where lug.linkid = l.id        ) 	0.00507401678052409
15135489	10228	first occurence of entries in table ( access )	select  * from    yourtable where   id in         (         select  min(id)         from    yourtable         where   isparent = 0         group by                 family_id         ) 	0.000189116650158396
15136345	1314	converting a string to xml datatype before querying in t-sql	select id,        t.n.value('@name', 'varchar(50)') as name from data cross apply (select cast(xmlstring as xml)) as x(x) cross apply x.x.nodes('/holidays/summer/regions/destinations/destination') t(n) 	0.163370695190043
15136909	30138	sql selecting item with "begin with"/ putting a % behind a variable's name	select   count(*) from   c_groups where   '/f1/xx' like (g_folder + '%') 	0.00156379673532948
15140494	8829	if date is null (sql server ce)	select id,          dateadded,          case when datesent is null              then (case status when 'w' then 'waiting'                                  when 'o' then 'uploaded'                                  when 'f' then 'failed'                                  when 'e' then 'expired'                                          else 'unknown'                     end)              else  convert(nvarchar(30), datesent)          end as sent from table 	0.671640471256916
15141362	37931	sql select with group by, referring back to the group	select  household_id,         count(uid) as members,          max(case when head = 1 then uid else null end) headid from    population  group   by household_id; 	0.252819860192793
15143688	7330	how to represent interchangeable columns	select * from friendships  where (friend1 = 123 and friend2 = 456) or (friend2 = 123 and friend1 = 456) 	0.0373046705509977
15144629	6918	sql multiple rows as columns with out using pl/sql	select q_id,         q_text,        (select a_text           from answers a1          where a1.q_id = q1.q_id            and (select count(*) from answers a2 where a1.q_id = a2.q_id and a2.a_id < a1.a_id) = 0) as option1,        (select a_text           from answers a1          where a1.q_id = q1.q_id            and (select count(*) from answers a2 where a1.q_id = a2.q_id and a2.a_id < a1.a_id) = 1) as option2,        (select a_text           from answers a1          where a1.q_id = q1.q_id            and (select count(*) from answers a2 where a1.q_id = a2.q_id and a2.a_id < a1.a_id) = 2) as option3,        (select a_text            from answers a1          where a1.q_id = q1.q_id            and (select count(*) from answers a2 where a1.q_id = a2.q_id and a2.a_id < a1.a_id) = 3) as option4,        (select a_text           from answers a1          where a1.a_id = (select a_id from correct_answers c1 where c1.q_id = q1.q_id)) as correct   from questions q1; 	0.0120987002957467
15144831	23232	mysql regroup results if one column result in common	select      cours.cours,      group_concat(professeurs.nom) as teachers,      classe.classe from cours join classe     on cours.id_classe = classe.id join cours_professeurs     on cours_professeurs.id_cours = cours.id join professeurs     on cours_professeurs.id_prof = professeurs.id group by cours.cours,classe.classe 	0.000465779991913321
15146318	11588	mysql: select all rows containing the id	select a.name,         b.class_id  from   classes_names a         inner join (select id,                            class_id                     from   classes_names                     where  name = 'john doe') b                 on b.class_id = a.class_id                    and a.id <> b.id 	6.74357878005636e-05
15146371	15981	is there any way to format the date of a field in a query?	select convert(char(10), @date, 110) 	0.0044732719663386
15146387	34901	query to deliver difference between two most recent dates for all products	select person, abs(date_part('epoch', p1 - p2)  from (select person,              max(case when product = 'football' then purchase_time end) as p1,              max(case when product = 'basketball' then purchase_time end) as p2       from mytable       group by person      ) p where p1 is not null and p2 is not null 	0
15146591	23932	select all rows that equal on same column (unknown) value	select distinct thread_id from tablex where thread_id in (select thread_id from tablex where user_id=1) and thread_id in (select thread_id from tablex where user_id=2) 	0
15147227	27580	number of days item present on a report	select fl.nodeid, datediff(day, fl.firstdate, fl.lastdate) [days on] from (select nodeid, min(dateadded) [firstdate], max(dateadded) [lastdate] from dailyruns group by nodeid ) fl 	0
15147712	13003	sql server get the attributes from the rollup	select p.prodcode, p.name, case when p.prodcode=p.endprodcode then p.rollup1 else pm.rollup1 end [rollup1],        case when p.prodcode=p.endprodcode then p.rollup2 else pm.rollup2 end [rollup2] from prodtable p join prodtable pm on (pm.prodcode=pm.endprodcode and p.endprodcode=pm.endprodcode) order by p.prodcode; 	0.00396694035551912
15148064	10212	is it possible to retrieve every record after one with a certain id?	select * from `mytable`     where `name` > (select name from `mytable` where `id` = 10)     order by `name` 	0
15148365	2590	how to retrieve all records after one with an id in symfony?	select * from tbl1 where name > (   select name   from tbl1   where id = 3 ) order by name 	0
15150666	24717	how can i display a result of data in order by a month-year combine column in sql?	select convert(char(3), date, 0)+'  '+right(convert(varchar, year(date)), 4) as [date] ,count(id) as count from tabletest   group by convert(char(3), date, 0)+'  '+ right(convert(varchar, year(date)), 4),month(date),year(date) order by year(date),month(date) 	0
15152370	38490	how can i make this cursor to change the column values?	select cast(cast(replace(replace(distance, 'km' , '' ), 'miles', '')as float) * 1.3 * 0.62137 as varchar) + ' miles' from customer 	0.219645224095275
15152438	37310	update from many rows to one without cursor	select test_string = t.stringcolumn + (select                             (',' + t2.concatstring)                             from                                  t1 t1                             inner join t2 t2                                 on charindex(t2.teststring,t1.stringcolumn) <> 0                             where                              t1.stringcolumn = t.stringcolumn                             for xml path( '' )) from     t1 t 	0.00135917987857867
15152587	637	find the three most sold products every day php mysql	select @rownum := @rownum + 1 rownum,         t.*    from (select @rownum:=0) r,         (select case when indicator = 1 then product else concat( indicator, ' products') end as product, sales from (select *, count(sales) as indicator from (select product,sum(no_sold) as sales from salesrows join products on products.pid = salesrows.pid where sales_date = curdate() group by salesrows.pid ) a group by sales order by sales desc) a) t 	0
15154277	40864	how to make postgresql result unique	select     md5(astext(way)) as md5,     min(osm_id) osm_id,     min(name) name,     min(highway) highway,     min(way) way from planet_osm_roads where highway is not null group by 1 having count(osm_id) > 1 	0.0599212936644607
15154644	38725	sql - group by to combine/concat a column	select      [user], activity,      stuff(          (select distinct ',' + pageurl           from tablename           where [user] = a.[user] and activity = a.activity           for xml path (''))           , 1, 1, '')  as urllist from tablename as a group by [user], activity 	0.12575980792458
15155112	24086	mysql form new optimize query	select       *  from      user where user_id not in     (          select              user_id          from              `count`          where             date_sub(curdate(),interval 14 day) <= date_column     ) and user_id not in     (         select             user_id         from             coupon     ) and user_id in     (         select             user_id         from             account     ) 	0.695726994001071
15155720	5089	removing trailing spaces from long datatype pl/sql	select regexp_substr(cis.acs_reports.f_get_varchar(:p_pfo_code), '.+[^space::]') pfo_comment 	0.640641632460406
15157126	20919	three columns - get max with sql	select  max(greatest(one, two, three)) from    t; 	0.00299129315732734
15157483	34854	how to perform a tolerant name search in sqlite db	select * from dbname where lower(name) like '%searchkeyword%' 	0.382464382006887
15157878	34017	mysql group by multiple derived tables?	select      equipment_id, service_duration, available_duration,     (available_duration / service_duration)*100 as availability     from      (             select equipment_id,             sum(service_end_time - service_start_time) as service_duration             from             (                        select equipment_id,                          (case ... end) as service_start_time,                         (case  ...  end) as service_end_time                     from t1                      ) as a             group by equipment_id     ) as b     join     (             select equipment_id,              sum(available_end_time - available_start_time) as available_duration             from              (                 select equipment_id,                   (case ... end) as available_start_time,                 (case ... end) as available_end_time                 from t2                      ) as c             group by equipment_id     ) as d     on equipment_id=d.equipment_id 	0.127265601515349
15161027	26163	db2 sql: grouping records with same id in result?	select  id,          substr(xmlserialize(xmlagg(xmltext(concat( ', ',text))) as varchar(1024)), 3) from    tablename group   by id; 	0.000462845165974568
15161240	38387	duplicate record count for null fields - is there a better way?	select  leadid,count(*)     from    #checknullcount     group   by leadid,lead 	0.0124367096957653
15161505	39716	use a query to access column description in sql	select          st.name [table],         sc.name [column],         sep.value [description]     from sys.tables st     inner join sys.columns sc on st.object_id = sc.object_id     left join sys.extended_properties sep on st.object_id = sep.major_id                                          and sc.column_id = sep.minor_id                                          and sep.name = 'ms_description'     where st.name = @tablename     and sc.name = @columnname 	0.362390695366886
15163615	28032	sql join returning multiple rows when i only want one row	select  distinct a.policynumber from    policy_office a         inner join office_info b             on a.officecode = b.officecode where   b.officename = 'acme' 	0.000638877619635085
15163793	31673	how to select integer values only from a varchar column in postgresql	select column from table where column ~ '^\d+$' 	0
15164228	13568	oracle sql: select string which must alphabet letter(s)	select * from yourtable where regexp_like(col1, '[a-za=z]') 	0.0272549327094299
15168992	27434	union two queries and flag duplicates	select color, animal, sum(duplicate_or_new) from ( select color, animal, 1 as duplicate_or_new from options union all select color, animal, 2 as duplicate_or_new from userselection ) as utable group by  color, animal 	0.060657009525431
15170947	14439	how to get how much days had the customer sumitted post?	select customers_id, sum(customers_id) as sum_days from table group by customers_id,   day(date); 	0
15171029	2490	sql get rows in '= all' style	select pc.productid from #product_category as pc where pc.categoryid in (200, 300, 400) group by pc.productid having count(distinct pc.categoryid) = 3 	0.00438064886003495
15171714	21739	select a group of records that are the last one to their own type	select lch.chequeid,max(lch.date),lch.holderid     from lcheque lch   group by lch.chequeid,lch.lchequeid 	0
15171856	6722	ordering joined data	select    h.*, d.*, t.* from handset h    left join deal d on h.id = d.handset_id    left join tariff t on d.tariff_id = t.id    where t.price=(select min(price) from tariff)    order by    h.popularity    desc limit 10 	0.0630262498245647
15172432	13262	how to find count of objects with the highest count?	select `foo_id`, count(1) as `count` from `bars` group by `foo_id` order by `count` desc 	0
15173895	36194	use column in subquery, but not in the main query's select	select  a.name from    foo a         inner join bar b             on a.id = b.foo_id group   by a.id, a.name having  count(b.foo_id) = sum(b.num > 10) 	0.780121146399853
15175716	15270	how to sort dataset by greater value of 2 columns in a row?	select       room_widths,       room_lengths,       iif(room_widths>room_lengths, room_widths, room_lengths) as longest   from       yourtable   where       <your select criteria>   order by       3 desc 	0
15175756	20412	mysqli procedural : how to perform a query to retrieve diferent posible values from the same field?	select  min , comments , p_tag , p_name  from pictures where  tag in ('father','mother','brother','sister','aunt','uncle') 	6.69804763869624e-05
15177763	35849	how to auto generate date(week end) and 0 values	select  case when sum(hours) > 0 then     cast(cast(sum(hours) as decimal(5,2))/40 as decimal(5,2)) else 0 end as [hours], [date] from resource group by date 	0.000393735266076955
15178182	1954	postgresql - how to return the last x values?	select * from table where time_column =< '2013-03-02 22:00:00' order by time_column desc limit 3 	0
15178958	31234	get data from one table using id and date ranges stored in another table	select l.*, c.* from log l left outer join      rentout ro      on l.unit_id_fk = ro.unit_id_rk and         l.datetime between ro.start_date and ro.end_date left outer join      customer c      on ro.customer_id = c.id where c.<whatever> = <foobar> 	0
15179663	30122	counting the number of overall entries from 2 different tables	select jid ,sum(gvr_count)+ sum(gos_count) as overallcount ,   sum(gvr_count) as gvr_count, sum(gos_count) as gos_count    from ((select jid, count(*) gvr_count, 0 as gos_count    from gvr     where jid is not null    group by jid   )   union all    (select jid, 0 as gvr_count, count(*) gos_count    from gos    where jid is not null    group by jid   )  ) t group by jid 	0
15180284	38208	weekly report behalf of specific date field	select week(signed_date) as week_name, signed_date as week_starting,        year(signed_date), week(signed_date), sum(case  when organization_id=1 then 1 else 0 end) as organization_1, sum(case when organization_id=2 then 1 else 0 end) as organization_2 from business where year(signed_date) = year(curdate()) group by concat(year(signed_date), '/', week(signed_date)) order by year(signed_date), week(signed_date); 	0.000464615897510737
15183148	10072	selecting max number from mysql table not working - php	select      * from tablename as t inner join (select max(sl) as sl from tablename) as r on r.sl = t.sl 	0.00471642078998685
15184792	31430	how to write a join query in mysql?	select     name,     email,     count(name) as total_count,     sum(facebook = 'y') as total_facebook_yes,     sum(case when twitter = 'y' then 1 else 0 end) as total_twitter_yes,     max(time) as last_time from `table_name` group by name, email 	0.754695994289096
15185317	27558	how to add additional column in select when using *?	select replace(aaa, 'a', 'b'), t.* from table t where id = 3; 	0.209856500983706
15185915	40257	4 table depth mysql lookup	select company.name, max(estimated_cost) as highestcost from companies  inner join projects on projects.companyid = projects.id inner join workers on workers.projectid = workers.id inner join tasks on tasks.workerid = tasks.id group by company.name order by highestcost desc 	0.0448326349641132
15188299	23052	information_schema.columns : and must be a primary key : mysql query	select table_schema, table_name from information_schema.key_column_usage where (table_schema, column_name, constraint_name)      = ('mydatabase', 'type_id', 'primary'); 	0.292571492386223
15190414	33479	selection of customer who placed order in particular year	select   customers.contactname  from customers where    customers.customerid in (     select orders.customerid      from orders      where year(orders.orderdate)=1996   ); 	0
15190751	34288	php loop getting values from second table	select tablea.id as id,        tablea.name as name,        group_concat( tableb.value ) as value from tablea   join tableb     on tablea.id = tableb.tablea_id group by tablea.id 	0.000144694505733128
15191468	9744	how to verify multiple emails and get the emails data?	select email,id from user where email in ('yao@a.com', 'yao@b.com', 'yao@c.com') 	0.000443548149151073
15191555	31743	what exactly is a database schema?	select * from [database].[schema].[table] 	0.547916846644397
15193505	30142	how to query sql for groups with the same values	select    max(animal) as animal,    listagg(name, ', ') within group (order by name) as vet_list from    specialties    left join (       select          vid,          max(spid) as spid,          row_number() over(partition by max(spid) order by null) rn       from advertising       group by vid       having count(distinct spid) = 1    ) using(spid)    left join veterinarians using(vid) where lnnvl(rn > 3) group by spid order by spid 	0.00125715584756508
15194480	16737	writing sql to find aggregation	select     creationdate,     avg(grade) from entry e inner join entry_subjects f     on e.id = f.entry_id inner join subject s     on f.subject_id = s.id where s.name = 'java'  group by creationdate 	0.406063747545208
15194560	4698	grouping by datetime column and keeping the averages	select     datepart(weekday, event_time) as dayname,     avg(count) as dayavg from     sample_date.dbo.651511 where      event_time >= '2009-01-01' and     (datepart(dw, date_created) + @@datefirst) % 7) not in (0, 1) group by     datepart(weekday, event_time) 	0.00140039406217554
15195364	9139	fetch record from cursor in sql	select identity(int,1,1) as id, patpid,fromdate,todate into #temp1 from tdp_provideraccomodationtariffplan where fk_patid =    162 and fk_pacid = 36 declare @index int declare @count int select @count = count(*) from @temp1 set @index = 1 declare @patpid int declare @fromdate datetime declare @todate datetime while @index <= @count begin   select @patid = patid,          @fromdate = fromdate,          @todate = todate   from #temp1   where id = @index   set @index= @index + 1 end drop table #temp1 	0.0029512888138907
15195731	39807	how to select urls that have not been accessed in 1 month?	select a1.url  from accesses as a1 where a1.url not in (   select a2.url    from accesses as a2   where a2.access >= date_sub(now(), interval 1 month) ); 	0.000124906047232382
15196378	1109	mysql group by vs multiple tables	select asl1.`listid`, asl2.* from `acmsonglists` asl1 inner join `acmsonglists` asl2 on asl1.listid = asl2.listid where `churchid`='".$thisid."' and `timesent` >= date_sub( curdate( ) ,interval 0 month )  group by asl1.`listid` asc 	0.428689587276288
15196891	8018	select statement for getting the later date	select laptopid, eff_to from tbl where eff_to = (select max(eff_to) from tbl); 	0.00973097864950704
15198187	23266	select n row from table1 per table2	select  a.id,          a.category,         b.description from    category a         inner join post b             on a.id = b.cat_id where    (     select  count(*)     from    post c     where   b.cat_id = c.cat_id and             b.id <= c.id ) <= 2 	0
15198661	7304	records displaying repeatedly	select  emp.empid,         emp.name,         sal.salary,         addr.address  from tbl_emp as emp  inner join tbl_sal as sal      on emp.empid = sal.empid  inner join tbl_address as addr      on addr.emp_type = sal.emp_type  where comp_id = '114'   group by empid; 	0.049262215567405
15203206	34431	mysql: calculate number using count within the select statement?	select  total_score / (select count(release_date) from movies where release_date <= curdate()) as final_score from movies where id = 12 	0.00335402506217772
15206141	20991	mysql escape line breaks exporting into csv?	select ... into outfile '/tmp/text.csv'    fields escaped by '""' terminated by ','  optionally enclosed by '"'    lines terminated by '\n'  from yourtable 	0.465378095030735
15206190	30509	sql: why does max() from multiple tables return null for everything if one table is empty?	select     (select max(tstamp) from table1) as tstamp1,     (select max(tstamp) from table2) as tstamp2; 	0.00890036270491317
15207178	27539	mysql left join doesnt returns rows from joined table	select distinct(p.id), p.purchaseid from (select *       from _impressionsdaily       union select *       from _impressionsalltime) as p group by p.purchaseid 	0.0343413017699801
15207258	1182	pull mysql data for the last 60 minutes	select * from tablename where firstadded > current_timestamp - interval 1 hour 	0
15211408	27192	sql return dates where there are no results	select q.date_column, count(f.id) from (select  generate_series(min(date_column),max(date_column), '1 day') as date_column  from mytable) as q left join mytable as f on q.date_column=f.date_column group by q.date_column order by q.date_column; 	0.00812661127372461
15214073	19417	how to count the number of production in sql	select count (a.hours * j.chg_our), e.emp_name from employee e, assign a. job j where j.job_class = e.job_class and e.emp_num = a.emp_num group by e.emp_name; having count ((a.hours * j.chg_our) >= 3000) 	0.00456004417275534
15215380	14153	sql query to obtain how many product sold for each day of a month in each product category	select date,        sum(price between   0 and  99) as '0-100',        sum(price between 100 and 199) as '100-200',        sum(price between 200 and 299) as '200-300',        sum(price between 300 and 399) as '300-400' from mytable group by date 	0
15215727	21734	check if date time is of today after 8 am server	select * from tab where      convert(varchar(11),lastupdateddate,101) > convert(varchar(11),getdate(),101) and      convert(varchar(11),lastupdateddate,108) >= '08:00:000' 	0.00532948743318258
15216220	11714	concatenate in sql server query	select visitid as value, convert(nvarchar(50),visitid)+' - '+convert(nvarchar(50),visitdate, 101) as text  from visit 	0.157951019050879
15216625	14107	food selection query	select distinct a.name as dish1, b.name as dish2 from food a, food b, throughaway c where a.name <> b.name and a.deskno = b.deskno and  (a.category = c.category1 and c.category2 = b.category) ; 	0.704402690294305
15216841	30873	finding the maximum value of year difference	select d1.id from data_diri d1 where d1.graduate_year - d1.join_year = (select max(d2.graduate_year - d2.join_year from data_diri d2)) 	0
15220934	36953	select distinct from distinct result	select distinct movie_master.moviemasterid, max(movie_version.releasedate), movie_master.displayorder, movie_classification.mc_code, movie_master.title as title, movie_master.biocast, movie_master.biodirector, movie_master.linkword, case when ((datediff(day,max(movie_version.releasedate),getdate())  <=7) and (datediff(day,max(movie_version.releasedate),getdate()) >=0)) then 'just released' else '' end as releasetag, movie_master.synopsis,movie_language.name as language, case when movie_master.distributorid = 8 then 0 else 9999 end as distributororder, movie_distributor.name as distributor ... group by movie_master.moviemasterid, movie_master.displayorder, movie_classification.mc_code, movie_master.title, movie_master.biocast, movie_master.biodirector, movie_master.linkword, movie_master.synopsis, movie_language.name, movie_master.distributorid, movie_distributor.name order by movie_master.displayorder, max(movie_version.releasedate) desc, distributororder, movie_master.title 	0.0050498940570845
15223032	38993	mysql display all date in between range	select a.date,  s.* from  (   select curdate() + interval (a.a + (10 * b.a) + (100 * c.a)) day as date   from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a   cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b   cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c ) a inner join schedule s   on a.date >= s.fromdate    and a.date <= s.todate 	0
15225353	21082	how to write a sql query that creates a separate column for each possible value of a field?	select sum(case when color='red' then 1 else 0 end) red_count       ,sum(case when color='red' then points else 0 end) red_points       ,sum(case when color='blue' then 1 else 0 end) blue_count       ,sum(case when color='blue' then points else 0 end) blue_points from yourtable 	0
15225628	33101	select only specific results in sql (postgresql)	select * from (   select id, name::tsvector @@ 'substring1 & substring2'::tsquery   from table ) as search where column = 't' 	0.010527379832608
15226574	22625	how can i convert dynamic row data to xml in oracle?	select xmlelement("data",xmlagg( xmlelement(evalname(key), val))) from my_table where id = 1 	0.0485251328110959
15227459	7485	join two sql select statements where one has single record and other has multiple records	select  a.*, b.* from    mda_alert_info a         inner join key_contacts_info b             on  a.mda_id = b.mda_id and                 a.stage_id = b.stage_id and                 a.ref_number = b.ref_number  where   b.role = 0 and         a.stage_id = 1 and          a.mda_id = 2 and          a.ref_number = '444' 	0
15229816	37619	to get date from sql	select date_sub(curdate(),interval 1 day) as yesterday ,            date_sub(curdate(),interval 7 day) as seven_days_ago ,           min(datea) as life_time_date 	0.00158284412564388
15230539	35794	retrieve a uniform data sample from a table	select * from [yourtable] tablesample(10 percent) 	0.000398149807777776
15230661	889	i want to find max number who contain series a100012345 in sql server	select `id` from `mytable` where `type` = 'b' order by `id` desc limit 0,1 	0.00031399218563328
15232428	30328	how to add variables in sql	select (select id_time from database.dim_time where id_time = a.fk_time) as yearmonth, (select sum( if( installed in (1), 1,0)) as installed from database.facts_table where fk_time <= yearmonth ) as installed from database.facts_table as a group by yearmonth order by yearmonth asc 	0.122962694745108
15232490	16992	sorting table count by sql	select u1.firstname,   u1.id,   coalesce(u2.total, 0) total from users u1 left join (   select affid, count(affid) total   from users    group by affid  ) u2   on u1.id = u2.affid order by u2.total desc; 	0.096649492438218
15233870	8945	sqlite - difference between is and = (equals) in where clause. (using jdbc preparedstatement)	select col1    , col2    , isnull(col3,'') as col3 from mytable where col1 = 'somevalue' 	0.779805839477307
15234114	22620	getting column_name different in two tables	select * from (select t.id1,t.id2, t.amt1,      p.amt1, t.amt2,      p.amt2, t.id3,       p.id3 decode(nvl(t.amt1 ,0)-nvl(p.amt1 ,0),0,'','amt1')||' '||decode(nvl(t.amt2 ,0)-nvl(p.amt2 ,0),0,'','amt2')||' '||decode(nvl(t.id3 ,0),nvl(p.id3 ,0),'','id3') difference_in_col from  table1 t, table2 p where  t.id1=p.id1 and t.id2=p.id2 ) where difference_in_col is not null; 	0.00147176609372883
15234212	36202	transpose rows to column and join table	select   a.id,   max(case when a.key_info = 'amount' then a.value_info end) as amount,   max(case when a.key_info = 'currency' then a.value_info end) as currency,   max(case when a.key_info = 'level' then a.value_info end) as level,   i.status from   attribute a   join instance i on a.id = i.id group by   a.id,   i.status 	0.00278637709057083
15234292	14605	sql:selecting rows matching certain criteria in a specific field	select project from mytable group by project having count(*) = sum(case when status = 'complete' then 1 else 0 end) 	0
15236016	31343	combine fields to make new field sql	select dept||" "||crs||sc as new from table 	0.00751831869623851
15236126	16946	select returning aggregate answer from one table based on weightings in another	select      name,      sum(col1*weighting) as weightedcol1,      sum(col2*weighting) as weightedcol2,     n.date,      [hour] from     nodes n     inner join weights w         on w.nodeid = n.nodeid         and w.date = n.date group by      name, n.date, [hour] 	0
15236758	17050	restricting columns from a union query	select r.*    from (select value1, value2            from somewhere           where somecolumn = 234          union          select value1, value2            from elsewhere           where elsecolumn = 432         ) as r   where value1 > 37 or value2 < 91 	0.0104347722383052
15237111	25990	how to force addition when a value is missing in sql?	select total = coalesce(l,0) + coalesce(j,0) + coalesce(k,0) from dbo.mytable; 	0.383615682608682
15237180	14706	how can i get the difference of two dates from different tables and generate it as a summary using sql query?	select table_1.ref,  sum(case when datediff(day, table_1.startdate, table_2.enddate) < 30 then 1 else 0 end) from table1 table_1  join table2 table_2 on table_1.ref = table_2.ref group by table_1.ref where table_2.status in ('max', 'stop') 	0
15239156	31260	mysql match against with multiple values to against	select * from test where match (column1,column2)       against ('+value1 +value2 +value3' in boolean mode); 	0.0166783356724943
15239209	24976	how to display most related content according to given keywords in a product area?	select t.*, sign(find_in_set('2',keywords))+sign(find_in_set('4',keywords)) as findweight from t where  sign(find_in_set('2',keywords))+sign(find_in_set('4',keywords))>0 order by findweight desc 	0
15239835	20037	can i use a variable as a column in a select statement?	select @maxlistid= max(materialid) where category =@category and mode='1' 	0.365191809816876
15241120	37731	sql "group by" to group rows corresponding to same pair	select least(primary, secondary)       ,greatest(primary, secondary)  from yourtable group     by least(primary, secondary)      ,greatest(primary, secondary); 	0.000247376172306681
15242033	22477	t-sql average calculation	select  product,         month,         year,         value,         avg_ytd = avg(value) over(partition by year order by month),         avg_year = avg(value) over(partition by product, year),         avg_overall = avg(value) over(partition by product) from    t; 	0.069114019878415
15245658	19484	sql server 2005 - check/validate null values and add to results	select empid  case when manager is not null and account manager is null then 1 else 2 end as count from tbl 	0.118244668192667
15247484	18300	sql related tricky count() query	select c.id, c.name, count(distinct u.id) from country as c join region as r on c.id=r.fk_country join dept as d on r.id=d.fk_region join users as u on u.fk_country=c.id or u.fk_region=r.id or u.fk_dept=d.id group by c.id,c.name; 	0.612716641194693
15247528	13012	mysql query for selecting column by the days of the week	select    case dayofweek(current_date)     when 1 then is_sunday     when 2 then is_monday     when 3 then is_tuesday     when 4 then is_wednesday     when 5 then is_thursday     when 6 then is_friday     when 7 then is_saturday   end current_day_of_wek from days_table; 	0
15247918	20656	sql counter and returner, doubles the result	select distinct  category_name, thread_category_id, threadcount from ( select categories.category_name, threads.thread_category_id, count(*)                          as 'threadcount' from threads                          inner join categories on categories.category_id = threads.thread_category_id                         group by categories.category_name, threads.thread_category_id ) a 	0.449380051150837
15248901	7775	sql - getting multiple counts with criteria	select  stores.store_id,         review.avgrating,         cv.visitslast20days,         cv.totalvisits,         cv.avgcustomerage from    stores         left join         (   select  store_id, [avgrating] = avg(rating)             from    reviews             group by store_id         ) review             on review.store_id = stores.store_id         left join         (   select  customervisits.store_id,                     [visitslast30days] = count(case when customervisits.visitdate >= dateadd(day, -30, current_timestamp) then 1 end),                     [totalvisits] = count(*),                     [avgcustomerage] = avg(datediff(day, customer.birthdate, current_timestamp)) / 365.25             from    customervisits                     inner join customer                         on customer.customer_id = customervisits.customer_id             group by customervisits.store_id         ) cv             on cv.store_id = stores.store_id; 	0.0397480928026231
15249279	17908	ordering by top result of a nested order by	select    data.asset, data.price, o.offerid from      (           select o.assetid as asset, max(o.offer) as price           from   assettable as a                  inner join offertable as o                      on a.assetid = o.assetid               group by o.assetid           ) data           inner join offertable as o               on data.asset = o.assetid               and data.price = o.offer order by  data.price desc, data.assetid 	0.101956171991634
15249447	30109	how to perform a count on a column where a value is x	select count(val='x'), count(val='y'), count(val='z') from ... 	0.00120839652596282
15250685	20730	sql iterate through arrays	select a, unnest(b) from t 	0.151101517339425
15250760	16277	sql select from same tables two times	select name.name, name2.name name2 from couple  inner join name on name.id=couple.nameid   inner join name as name2 on name2.id=couple.nameid2 	5.34412889858395e-05
15251909	7908	db2: function to merge 3 column output	select c1 concat ' ' concat c2 concat ' ' concat c3 	0.089325403760569
15252347	7493	how do i select a row based on a priority value in another row?	select d.id, min(name) keep (dense_rank first order by name_priority) name,        min(name_priority) name_priority,        min(color) keep (dense_rank first order by color_priority) color,        min(color_priority) color_priority   from yourtab d  group by id; 	0
15253128	2055	sql select value from column when another column equals to given value	select  case when u1 = sessionid then u1paid               when u2 = sessionid then u2paid              when u3 = sessionid then u3paid              when u4 = sessionid then u4paid              when u5 = sessionid then u5paid              else 'no result found'         end as paid from    payment  where   billid = billid; 	0
15253560	6929	select all but max record in sql query	select max(pn.hmy) 	0.00238505575091913
15255509	29998	get percentage keywords show up in table	select subject, count(*) as numtweets from tweets group by subject; select count(*) as totaltweets from tweets; 	0.000689315065690423
15255811	2359	mysql using order by if, ordering categories with sub categories that can be ordered at both levels	select c.* from categories as c left join categories as p on p.multicat_id = c.parent_id order by if(p.multicat_id, p.ordering, c.ordering),          p.ordering, c.ordering; 	0.0231727346958341
15256688	26202	finding rows matching positive and negative	select x1.<cols>, x2.<cols>  from dbo.yourtable as x1 inner join dbo.yourtable as x2   on x1.vendor_code    = x2.vendor_code  and x1.invoice_number = x2.invoice_number  and x1.check_number   = x2.check_number  and x1.payment_amount = -x2.payment_amount; 	5.92856505094868e-05
15258286	7432	sql - number of times each visitor has visited a tool	select tool, email, count(*) from tbl group by tool, email order by count(*) desc 	0
15259086	34439	how do i check if one table data is being referred in other processes	select distinct o.name, o.xtype     from dbo.syscomments c     inner join dbo.sysobjects o on c.id=o.id     where c.text like 'table_name_here'  	0.000335038556846249
15259201	33991	select records from oracle table where single column is unique	select id, duplicateid, name, col1, col2, col3   from (select id, duplicateid, name, col1, col2, col3,                row_number() over (partition by duplicateid order by id) rn           from your_tab)  where rn = 1; 	0
15260346	2030	mysql query with multiple counts in result	select ..... , count(*), sum(if(user.important,1,0)) as count_important, count(*) - sum(if(user.important,1,0)) as count_normal 	0.209019715853531
15262408	16975	list duplicate dates from 2 rows in one	select a.rnumber,a.pid,first_viewdate,last_viewdate from  (select rnumber,pid,viewdate as last_viewdate from table where rented='y') a, (select rnumber,pid,viewdate as first_viewdate from table where rowid in  (select min(rowid) from table group by rnumber) and rented !='y') b where a.rnumber=b.rnumber; 	0
15263579	37086	3 queries to merge and planning to create graph	select  product_name,         totalavailable,         totalsold,         totalavailable - totalsold as productdifference from         (             select  product_name,                     sum(case when status = 'available' then 1 else 0 end) totalavailable,                     sum(case when status = 'sold' then 1 else 0 end) totalsold             from    tablename             group   by product_name         ) s 	0.0755771329301403
15264377	7473	compare time using sql query	select uid,count(uid) as no_of_days from presence  where (time_to_sec(timediff(timeout, timein )) / 3600)<9   and date> $date1 and date< $date2  group by uid. 	0.0916393463699127
15265814	14685	oracle partition by group into date based sequence	select row_number() over (partition by group_id,col1 order by col2) as rnum, a3.*  from  ( select a1.*,       (select count(*) from t a2 where         a2.col1<>a1.col1         and          a2.col2<a1.col2) as group_id from t a1 ) a3 order by col2 	0.00448720523797441
15266232	25694	special for xml in sqlserver	select  'businessentityid' as 'document/field/@name' ,   businessentityid as 'document/field' ,   '' as 'document' ,   'documenttype' as 'document/field/@name' ,   persontype as 'document/field' ,   '' as 'document' ,   'title' as 'document/field/@name' ,   title as 'document/field' ,   '' as 'document' ,   'firstname' as 'document/field/@name' ,   firstname as 'document/field' ,   '' as 'document' ,   'middlename' as 'document/field/@name' ,   middlename as 'document/field' ,   '' as 'document' ,   'lastname' as 'document/field/@name' ,   lastname as 'document/field' ,   '' as 'document' from @person for xml path(''), root('documents') 	0.526373138335994
15266342	6700	how to transfer data between different sql server?	select * from test.somedb.dbo.sometable exec test.somedb.dbo.someproc 	0.0166176837291743
15266980	13913	reading multiple records related to every record in the result set at a time	select distinct m.msgid, m.msgtext, ms.senderid, ms.sendername,  mt.toname, mt.toid  from message m, messagesender ms, messageto mt where m.messageid = ms.messageid and  m.messageid = mt.messageid  and msgdate like '%20130307%'  	0
15267414	22649	split and select specific values from sqlserver table	select distinct year( convert(datetime,startdate,105))  from [kneipp].[dbo].[kn_projects] 	6.068551836674e-05
15267653	22473	how can i query this in a database?	select position=manager.details,         name=name.details,         nickname=nickname.details,         address=address.details  from   table1 t1         left outer join table2 manager                      on t1.positon = manager.detail_seq         left outer join table2 name                      on t1.name = name.detail_seq         left outer join table2 nickname                      on t1.nickname = nickname.detail_seq         left outer join table2 address                      on t1.address = address.detail_seq 	0.776770576108357
15268410	10927	determine datepart by int value in sql	select * from tbldbs_details  where      case @expirytype     when 0 then dateadd(d, @expiryvalue, @dateofissue)     when 1 then dateadd(w, @expiryvalue, @dateofissue)     when 2 then dateadd(m, @expiryvalue, @dateofissue)     when 3 then dateadd(y, @expiryvalue, @dateofissue)     end <= getdate() 	0.0591347432708454
15269769	40951	how to merge two result	select day, month, sum(total)   from (         union all )  group by day, month 	0.00471113791113307
15271231	6904	how to know which columns correspond between tables and a view	select * from sys.dm_sql_referenced_entities( 'dbo.viewa', 'object' ) ; 	0.000377927637785596
15273097	26886	sql query add a column that is a sum of rows after case	select     x.*,     "first name 1"+         "last name 1"+         "first name 2"+         "last name 2"+         "first name 3"+         "last name 3" as thesum from     (     select         case when [1  first name] = '' then 1 else 0 end as "first name 1",         case when [1  last name] = '' then 1 else 0 end as  "last name 1",         case when [2  first name] = '' then 1 else 0 end as "first name 2",         case when [2  last name] = '' then 1 else 0 end as  "last name 2",         case when [3  first name] = '' then 1 else 0 end as "first name 3",         case when [3  last name] = '' then 1 else 0 end as  "last name 3"     from         member     ) x 	0.00252610896957943
15273485	34301	mysql need to count inscription per week lasts 12 weeks	select yearweek(date_inscription) as yweek,        count(*) as cnt from person where yearweek(date_inscription) >= yearweek(curdate()) - 12 group by yweek 	0.000151465661785321
15273831	116	mysql count column values equal to another column	select a.id,    coalesce(b.id_1_count,0),    coalesce(c.id_2_count,0) from so15273831 a left outer join (   select id_1, count(*) as id_1_count   from so15273831   group by id_1 ) b on b.id_1 = a.id left outer join (   select id_2, count(*) as id_2_count   from so15273831   group by id_2 ) c on c.id_2 = a.id order by a.id; 	0.000103687996203543
15274706	8168	goup together multiple invoices	select      [customer name], [payment no],      stuff(          (select ',' + cast([invoice no] as varchar(10))           from tablename           where [customer name] = a.[customer name] and                 [payment no] = a.[payment no]           for xml path (''))           , 1, 1, '')  as invoicelist from tablename as a group by [customer name], [payment no] 	0.650638379145899
15275996	15876	difference between text references and int references in sqlite?	select * from people p        join        (         select _id from people join offices         on people.office = offices._id          and offices.name = 'beadle county'         union         select _id from people join specialtyareas         on people.specialty_area_1 = specialtyareas._id          and specialtyareas.name='customer service'        ) as matchingpeople        on matchingpeople._id = p._id 	0.00533510862189357
15278749	37771	return only first item from a related group	select pk,        a,        b,        c,        d   from( select pk,                a,                b,                c,                d,                row_number() over (partition by a order by pk asc) rnk           from your_table )  where rnk = 1 	0
15278841	19891	sql query to find max value from min results set	select top 1 dbo.tbldevices.status , l.device_id , min(l.dateandtime) as 'end date' from dbo.tbldevicelocation as l join dbo.tbldevices on l.device_id = dbo.tbldevices.device_id group by l.device_id, dbo.tbldevices.status order by min(l.dateandtime) desc 	0.000351466719514561
15278964	34757	mysql: how to return empty record when all fields are null?	select * from (     select sum(mark) as totalmark, userid, credit     from users, marks     where marks.receiverid = users.userid     and userid = '-1' ) t where t.totalmark is not null; 	0.000103304265653955
15280849	7376	sum all specific column value in datagridview	select sum(order_value) from table group by customer_id 	0.000154683767742701
15281125	3957	dynamically numbering distinct sql rows in select statement	select row_number() over(order by name), * from  (select distinct name from @table where %rules) as mytable 	0.0201211661226372
15282127	34620	query to get data from table2 based on info in table1	select t2.playername  from    table2 t2, table1 t1  where   t2.playerip = t1.serverip 	0
15282263	4409	round up the datetime to next day in t-sql?	select dateadd(day, datediff(day, 0, sysdatetime()), 1) 	0.000184035190678325
15282489	38833	mysql - selecting related items in a table	select c1.`course`,        count(c1.`course`) as c from `coursetracker` c1 inner join `coursetracker` c2 on c1.`user` = c2.`user` where c2.`course` = 'comp1409' and c1.`course` != 'comp1409' group by c1.`course` order by c desc limit 10 	0.000191606973298972
15282581	40235	selecting a single id by most recent date [mysql][php]	select order_id from table order by date_bought desc limit 1 	0
15282785	1475	mysql group by + order	select tablename.* from tablename      where tablename.counter =  (select max(counter) from tablename as f where f.groupid = tablename.groupid)      order by tablename.counter desc 	0.386621081107483
15283224	9406	aggregate by selecting last element in postgres group by	select distinct on (object_id, dimension)     object_id,     dimension,     value from pt_reading order by object_id, dimension, "timestamp" desc; 	0.000529279781622886
15283557	6011	how to merge or combine results from a query	select 1,         'other states' states,         sum([prior month]) 'prior month',         sum([current month]) 'current month' from  ( ) t 	0.00435249775870844
15285233	38584	best way to write sql and if statement comparing two items inside a database	select * from permissionsets where user like 'default' >> this will return the default set. select * from permissionsets where user like 'user1' >> this will return user1 permission set. 	0.0423811903535135
15285531	1159	max condition for a char datatype column in sql server	select  max(cast(columnname as int)) max_value from    tablename where   isnumeric(columnname) = 1 	0.0682983863644017
15288186	33104	the conversion of the varchar value overflowed an int column	select @phonenumber= case    when  isnull(rdg2.nphonenumber  ,'0') in ('0','-',null) then isnull(rdg2.nmobilenumber, '0')    when isnull(rdg2.nmobilenumber, '0')  in ('0','-',null) then '0'   else isnull(rdg2.nphonenumber  ,'0') end  from tblreservation_details_guest  rdg2  where nreservationid=@nreservationid 	0.00077011872838723
15288589	4914	how to strip out part of a bread crumb path in postgresql	select distinct split_part(crumbs,'->',2) from table1 where split_part(crumbs,'->',3)<>''; 	0.0233514960753231
15289880	39655	select last entry for every user from log table	select user_id , max(date) from alerts.alerts_log group by user_id; 	0
15290114	35744	sql combine multiple rows into one with multiple columns	select id,        max(name) name,        max(case when rn=1 then nameline1 end) address1_nameline1,        max(case when rn=2 then nameline1 end) address1_nameline2 from (select a.id,         a.name,          ca.nameline1,         rank() over (partition by a.id order by ca.id) rn  from dbo.accounts a   join dbo.addresses ca on a.id = ca.accountid  where a.name = 'test') sq group by id 	0
15290313	39042	concatenation of rows in t-sql	select      c.id, c.name productname,      stuff(          (select    ',' + b.name           from  producttags a                 inner join tags b             on a.tagid = b.id           where  a.productid = c.id           for xml path (''))           , 1, 1, '')  as taglistlist from products as c group by c.name, c.id 	0.0342707017097294
15291416	7374	select users who fits in timetable mysql	select user_id from   my_table   natural join (select 1 day_number union all select 2 union all select 3) days   join (select maketime(14,0,0) start, maketime(16,0,0) end) times     on my_table.start <= times.start    and my_table.end   >= times.end group by user_id having   count(distinct my_table.day_number) = 3  	0.0131651339997327
15291626	5082	get sql data group by month and category as column	select     month   , coalesce(cat1,0) as cat1   , coalesce(cat2,0) as cat2   , coalesce(cat3,0) as cat3   , coalesce(cat4,0) as cat4 from tbl pivot(sum(amt) for category in ([cat1], [cat2], [cat3], [cat4])) p 	0
15292268	2185	get rows from table1 missing in table2 oracle?	select    a.id,    a.name from    tablea a left join tableb b on a.id=b.id      left join tablec c on a.id=c.id where    b.id is null and    c.id is null; 	0.000152065279610687
15292488	6923	mysql query which do not display rows with not equal value	select i.* from order_history i left join order_history e         on i.id_order = e.id_order and e.id_order_state = 6 where  e.id_order_hitory is null 	0.00142507582421176
15293354	39728	using oracle 9i converting a single text column list into a 2 column list	select country, next_country from    (select country,           lead(country) over (order by country) next_country,          row_number() over (order by country) rnk    from countries   )  where mod(rnk,2)=1; 	0.000219033416321795
15295489	18261	select up to x rows of each group	select  id, name, job, rank from    tablename a where          (            select   count(*)             from     tablename as f            where    f.job = a.job and                      f.rank <= a.rank         ) <= 2; 	0
15297337	10128	t-sql query to fill the null values	select club_number = max(club_number) over      (       order by coalesce(club_number, number)       rows unbounded preceding     ),    name, number from dbo.your_table order by club_number; 	0.0173978134215471
15297392	22237	mysql query returns wrong rows	select  a1.event_id,a1.root_folder,a1.event_name,a1.date,a1.location,a2.user_id  from    own_events a1          inner join invited_events a2             on a1.columnname = a2.columnsname where   a2.user_id=$user_id 	0.691431781776477
15299483	16929	define sub select query once only for multiple selects	select masteraccnumber from  ( select masteraccnumber from ace_accsleveltran where cast(timstmp as date) = '02/06/2013'  union all select m.accountnumber from ace_invleveltran i  left join ace_invlevelmaster m i.masterinvnumber=m.invoiceno  where cast(i.timstmp as date) ='02/06/2013'  )  e group by masteraccnumber  having count( masteraccnumber) < 2 	0.0308402775143706
15301668	18734	mysql left join but need value from third table	select tests.name, testgroups.grouptype from tests left join testgroups on tests.id = testgroups.testid left join platforms on ...... where tests.platforma = 1 and platforms.name = 'platforma'; 	0.0349139174864602
15302054	1825	how to sum conditionally?	select * from ( select col1, sum(col2) col2 from table where col3 is null group by col1 union select mainset.col1, tmp.col2 from table mainset join  (     select col3, sum(col2) col2     from table     where col3 is not null     group by col3 ) tmp on tmp.col3 = mainset.col3 where mainset.col3 is not null ) fullset order by fullset.col1 	0.0619534142365805
15302725	20826	joining multiple table values into one table in order to see things clearly	select orders.orderid, case when orderdiscounts.orderid is null then false else true end, case when orderdiscounts.discounttypeid  = 1 then 'coupon'       when orderdiscounts.discounttypeid  = 2 then 'campaign'       else '' end, case when orderdiscounts.discounttypeid  = 1 then coupons.title       when orderdiscounts.discounttypeid  = 2 then campaigns.title        else '' end from orders left join orderdiscounts on orders.orderid = orderdiscounts.orderid left join coupons on orderdiscounts.discountid = coupons.couponid left join campaigns on orderdiscounts.discountid = campaigns.campaignid 	0
15303433	11205	how to affect a single status in a where clause with multiple statuses	select pol3.ct_status, sum(case      when ct_status in ('declined','quote') then 1     when ct_status = 'active' and ct_original_quote_id is not null and ct_original_quote_nsid is not null then 1     else 0     end) from contract pol3 where (pol3.ct_status = 'quote' or pol3.ct_status='active' or pol3.ct_status='declined') and year(pol3.ct_subscription_date)>= datediff(year,(dateadd(yy, datediff(yy,0,getdate()), 0)), getdate()) group by pol3.ct_status 	0.0275945293420586
15303906	1445	how can i join together two queries on the same table?	select case when post_2 = 27 then post_1 else post_2 end as post from related_post  where post_2 = 27 or post_1 = 27; 	0.00131971775976815
15304298	19745	mysql and joins	select comments.*   from forums  left join threads  on threads.forum_id = forums.id and forums.id = 4  left join comments   on threads.id = comments.thread_id  ; 	0.691616358913477
15304312	40142	how to retrieve top 10 entries?	select atheletename from table order by time limit 0,10 	0
15305628	29541	some transact-sql queries	select product.productid  from product left outer join comment on product.productid = comment.productid where comment.commentid is null 	0.558274920874171
15305738	38146	count a select result number	select count(*) from (select tbl_name, sql from sqlite_master where type='table') as data; 	0.00600555944439115
15307726	15595	count returned by a query when particular column is null and not-null in mysql	select   sum( case when studentid is not null then 1 else 0 end ) as result1 ,  sum( case when studentid is null then 1 else 0 end) as result2 from class 	0.041385553066983
15308723	34095	escaping spaces in a select result	select replace(show.file, " ", "\ ") from show, schedule where channel = 1 and start_time <= unix_timestamp() 	0.372181089096121
15309293	34335	combine table results in a relational database	select tt.tokentype_name, t.token_name  from tokens as t join tokentypes as tt     on tt.tokentype_id = t.tokentype_id 	0.0175111878474327
15309401	32753	does sql server 2008 has column display name?	select col1 as [hello world] from table1 	0.0185862465408012
15309932	16149	select random users from mysql in one row	select u1.id1, u2.id2, u1.name1, u2.name2, u1.total1, u2.total2, u1.img1, u2.img2  from  (     select u.id id1, u.name name1, u.total total1, u.img img1      from users u      order by rand() ) u1 cross join (     select u.id id2, u.name name2, u.total total2, u.img img2      from users u      order by rand() ) u2 where u1.id1 != u2.id2 and abs(u1.total1 - u2.total2) < 200 limit 0,1; 	0
15311603	36303	pgrouting shortest_path get uniqe osm_id values	select osm_id    from ways    join    (select * from shortest_path('       select gid as id,            source::int4 as source,            target::int4 as target,            length::float8 as cost       from ways',       7856,       18774,       false,       false)) as route    on    ways.gid = route.edge_id     group by osm_id    order by min(vertex_id) 	0.458456207542218
15312223	30150	mysql multiple time aggregates in query	select date(takenat) as takendate,        hour(takenat) as hourtaken,        avg(case when channelid = 1 then reading else null end) as ch1av,         avg(case when channelid = 2 then reading else null end) as ch2av,         avg(case when channelid = 4 then reading else null end) as ch4av from readings  where channelid in (1,2,4) group by takendate, hourtaken order by takenat, hourtaken 	0.477266639483184
15313353	9592	sql, select by geoposition on an area	select * from users where (user_latitude >= 1.2393 and user_latitude <= 1.5532)  and (user_longitude >= -1.8184 and user_longitude <= -1.654) 	0.161153234957985
15314124	27209	stored dates in unixtime (int 10) check interval	select * from rentals where rental_flag = 1  and unix_timestamp(now() - interval 1 day) > initiated_datime 	0.00102325223688223
15314204	19160	having sum in nested select	select t.*, sum(rt.`number`) as total  from tour as t join  reservedtour as rt on rt.`tid`=t.id where city = 'alahom' and  t.`timeout`=> '1400-12-13' and t.`capacity`-total > 4 group by t.id 	0.584630344189686
15314852	21531	sqlite "is not existing in"	select *  from categories  where categories.idcategories not in ( select category from stores )  group by categories.idcategories 	0.603346497929357
15315910	10307	sorting count in multiple tables	select r.name, count(i.id) from restaurant r left join item i on i.restaurantid = r.id group by r.name order by count(i.id) desc 	0.0556817746518942
15317614	33585	random database query once a week using php and mysql	select * from table order by rand(dayofyear(current_date)) limit 1 	0.000678915496023645
15318020	5019	sql query from minus to join	select t1.col1, t1.col2, t1.col3  from table1 t1 left join table2 t2 on t1.col1 = t2.col1 and t1.col2 = t2.col2 and t1.col3 = t2.col3 where t2.col1 is null 	0.541175984912752
15318481	11319	select sum() with conditions in mysql	select `currency_code`, sum(`principal amount`) as total  from `table` group by `currency_code` 	0.211705678929111
15318799	38178	sql query on reservation checking	select facility.[facility name], facility.[facility type]  from facility      left outer join reservation on facility.facilityid = reservation.facilityid     and memberid = '" & txtmemberid.text & "'     and [check-in date] ='" & lstdate.selecteditem.tostring & "') where reservation.id is null 	0.655385219579929
15319589	22034	how to find count of employees who have applied for timeoff	select count(*) as count_employee from (select distinct emp_id from timeoffdetails); 	0
15321428	11469	mysql : how to select record where begin date and end date between two dates of mysql	select rate_discount  from rate_eb  where rate_min_stay <= abs( datediff( reb_date2, reb_date1 ) ) and reb_date1 between rate_starts and rate_ends and reb_date2 between rate_starts and rate_ends 	0
15324380	18596	oracle sql count (or other sufficient aggregate) return zero when row not present	select   f.finish,   count(c.finish) as finish_amount from    (select '1st' as finish from dual    union all    select '2nd' from dual    union all    select '3rd' from dual    union all    select 'dnf' from dual   ) f   left join cars c      on f.finish = c.finish     and c.car = 'toyota' group by f.finish order by 1 	0.0284521640128073
15324386	24793	mysql get result of update-set in php variable	select if('$logo_value' - result_tries < 0 or '$logo_value' - result_tries = 0, 1, '$logo_value' - result_tries) as result_value; 	0.0202587420406743
15324568	13736	returning unique values in acess database with several columns	select child, min(parent) as parent, postnummer from ( select barn.förnamn+' '+barn.efternamn as child, målsman.förnamn+' '+målsman.efternamn as parent, målsman.postnummer as postnummer from barn inner join målsman on barn.postnummer = målsman.postnummer where (((målsman.postnummer) like '*23*')) ) a group by child, postnummer 	0.000570928309330071
15325669	176	mysql can i merge these two queries together?	select      year( t.orderdate ) as "salesyear", month( t.orderdate ) as "salesmonth", sum( t.ordertotal ) as "totalsales", productid from (  select 1       union all  select 2  ) as t group by     t.productid, year( t.orderdate ) , month( t.orderdate ) 	0.0442000892958814
15330858	26928	extract only 1 message from all senders	select u.uacc_username, max(m.msg_id) as latestmsg from messages m join user_accounts u on m.msg_from_uacc_fk = u.uacc_id where m.msg_to_uacc_fk = ? group by u.uacc_username 	0.000125917355533755
15332857	8624	sql, finding entries when value to one column is a or b	select * from table where col in ('foo1', 'foo2') select * from table where col = 'foo1' or col = 'foo2' 	0
15333824	29131	sorting data based on the current system date	select * from (select "weekly","quarter","sales","monthly",week_number from fiscal_calendar   where week_number <= to_number(to_char(sysdate,'iw'))    order by  week_number desc) t1 union all select * from  (select "weekly","quarter","sales","monthly",week_number from fiscal_calendar   where week_number > to_number(to_char(sysdate,'iw'))   order by  week_number) t2 	0
15338079	19365	select count of rows with joined tables	select      d.tablekey_id,      k.linkdata_id,      k.timestamp,       d.domain,      d.is_basedomain,      count(*) as 'count' from      tablekey as k       join searched_domains as d on d.tablekey_id=k.id       join searched_domains as d2 on d2.tablekey_id=d.tablekey_id where      d.is_basedomain = 1  group by      d.tablekey_id,      k.linkdata_id,      k.timestamp,       d.domain,      d.is_basedomain 	0.00058762718058363
15339309	17870	mysql query to calculate workdays between two cells in the same row	select 5 * (datediff(from_unixtime(finishtime/1000), from_unixtime(systemreceivedtime/1000)) div 7) + mid('0123455501234445012333450122234501101234000123450', 7 * weekday(from_unixtime(systemreceivedtime/1000)) + weekday(from_unixtime(finishtime/1000)) + 1, 1)x from document; 	0
15344122	11879	mysql math functions - get percentage done - (add 2 columns, divide and multiply)	select (     sum(if(checked >= 2, url_count, 0)) / count(if(checked <= 2, 0, null))   ) * 100 from table 	0.0020240370363033
15344377	22506	postgresql: levenshtein distance in a row column with comma-separated values	select distinct u.id from users as u left join (select u.id,unnest(string_to_array(u.alias, ',')) as alias from users as u) as q on u.id=q.id where levenshtein(u.name,'jill')<3 or levenshtein(q.alias,'jill')<3; 	0.00504884730855321
15344745	28298	sql select across multiple tables with max dates in each joined table	select distinct a.table1_id,                 a.table1_col1,                 b.table2_col2,                 c.table3_col3,                 d.table4_col4 from table1 a join (select t2.*,               rank() over (partition by table2_id order by table2_eff_date desc) rn       from table2 t2       where table2_active_ind = 'y') b on b.table2_id = a.table1_id and b.rn=1 join (select t3.*,               rank() over (partition by table3_id order by table3_eff_date desc) rn       from table3 t3       where table3_active_ind = 'y') c on c.table3_id = a.table1_id and c.rn=1 join (select t4.*,               rank() over (partition by table4_id order by table4_eff_date desc) rn       from table4 t4       where table4_active_ind = 'y') d on d.table4_id = a.table1_id and d.rn=1 order by a.table1_id; 	0
15345221	10163	count from inner select statement	select count(*) from (     select id, count(id) count_of_id     from [testing].[dbo].[bench]     group by id     having count(*) =5 ); 	0.252417799069204
15345690	771	sql query for calculating a monthly total out of a running total	select date_format(max(a.`date`), '%b-%y') `date`,        max(a.`flow_total`) `flow total`,        (max(a.`flow_total`) - max(b.`flow_total`)) `monthly total` from reports a left join reports b   on year(a.`date`)  =  year(date_add(b.`date`, interval 1 month)) and      month(a.`date`) = month(date_add(b.`date`, interval 1 month)) group by year(a.`date`), month(a.`date`) order by a.`date` desc; 	0
15345761	26398	select two largest values of a column	select mytable.store_id, mytable.sales_amount from mytable     left join mytable table2 on mytable.store_id = table2.store_id      and mytable.sales_amount <= table2.sales_amount group by mytable.store_id, mytable.sales_amount having count(mytable.*) <= 2; 	4.58986867075313e-05
15345982	8322	how do i avoid calling the same sql statement over and over	select sum(coalesce(somenumber,0)) myfirstnumber        ,sum(coalesce(somenumber2,0)) mysecondnumber from   table         left join (select ids.. from table ) as filter on table.id = filter.id where  filter.id is null 	0.631601656117694
15347194	2209	retrieving both a 'count where' and and overall count simultaneously	select id , count(*) totalreviews , sum(case when rating >= 3 and comment like '%taco%' then 1 else 0 end) ratings4plus , avg(case when rating >= 3 and comment like '%taco%' then rating else null end) avgratings4plus from test group by id 	0.00461256820128553
15349162	15810	get statistics from dates in one query (or in a fast way)	select   estado,   count(*) siempre,   count(case when date(modified) = curdate() then 1 end) as modifiedtoday,   count(case when datediff(curdate(), modified) = 1 then 1 end) as modifiedyesterday,   count(case when datediff(curdate(), modified) between 2 and 7 then 1 end) as modifiedlastweek,   count(case when datediff(curdate(), modified) between 8 and 30 then 1 end) as modifiedyestermonth from   apns_devices group by   estado 	0.000477076770266702
15349677	31458	conditional order by	select      row_number() over() id, * from (     select         r.routeid,         p.pointid,         label,         type,         labelstart,         labelend     from         route r         inner join         point p on p.routeid = r.routeid     where         r.type = 'e' and p.label % 2 = 0         or         r.type = 'o' and p.label % 2 != 0         or         r.type = 'a'     order by         r.routeid, r.progres, r.id,         case labelstart < labelend             when true then label             else label * - 1         end ) s 	0.718902673378256
15350890	15937	inner join from multiple tables	select `p`.`patron_num`,`date`,`time`,`tname` from `booking_for_schedule` `f` inner join `booking_by_patron` `b` on `f`.`booking_num` = `b`.`booking_num` inner join `patron` `p` on `b`.`patron_num`=`p`.`patron_num` 	0.138500775567197
15351948	8802	how to pull all from database and limit as opposed to specific id?	select top 12 from users where status = 'active' order by created_on desc 	0
15354287	21544	update a column taking data from same column	select    id,    nvl(date_column,last_value(date_column ignore nulls) over (order by id)) as date_col,    code from your_table order by id; 	0.00023728473469617
15357113	26850	mysql multiple values in 2 rows	select distinct phid from ph_pd where productid in (9,10,11) 	0.000997536678240826
15358380	37658	how to sql select a product with two status?	select productid  from products where status in (1, 2) group by productid having count(distinct status) = 2 	0.00353201167668307
15361200	1054	how to query data without repeats and minimize the time?	select distinct posts.* from posts  inner join journals_posts on journals_posts.pid = posts.pid  inner join follows on follows.jid = journals_posts.jid  where follows.uid = <userid> 	0.0164443165305235
15363239	28221	group dates based on variable periods	select t.calendertype, t.periodnumber, count(*) as incidents from table1 t inner join (   select t2.date, t2.incidents, max(t1.periodstartdate) as periodstartdate   from table2 t2   inner join table1 t1 on t2.date >= t1.periodstartdate   where calendertype = 1   group by t2.date, t2.incidents ) a on t.periodstartdate = a.periodstartdate where calendertype=1 group by t.calendertype, t.periodnumber 	0.000323857902260777
15363891	28957	sql. perfomance of count on many columns	select count(distinct col1),        count(distinct col2),        ... from   table; 	0.0265273801097924
15365422	23580	can i repeat a union join in oracle sql for different values defined by another query?	select prog_code,     user_code,     user_mark,   ntile(10) over (partition by prog_code order by user_mark desc) decile from grade_result where user_mark is not null and prog_year = '2011'; 	0.0054873854492473
15367805	35619	mysql multiple joins on the same table selects only 1 row in while loop	select m.id, m.comment, m.us1, m.us2, m.us3, p.name, o.name, t.name from posts m  left join usertable p on m.us1=p.id left join usertable o on m.us2=o.id left join usertable t on m.us3=t.id 	0.00019925903169944
15368027	20965	group by username and select sum of column	select username, sum(points) as s from t group by username order by s desc 	0.00912695315363107
15368148	18767	pull sql data from two tables	select d.name, d.dateadded   from db.info i, db.data d    where i.name = d.name     and i.status = 'n'; 	0.000374538328790553
15368483	10659	mysql select distinct row from col1 where col2=x	select type, specifically from pet_table   where type='cat'   group by specifically   order by specifically asc 	0.00559749708053699
15372526	33894	return the last entry of the 2nd table using inner join	select * from    main join   (select * from      logs where logs.id in          (select max(id) from logs group by logs.main_id)   ) as newestlogs   on newestlogs.main_id = main.id 	0
15372864	15879	remove leading zeros in a nvarchar column in sql server	select '0000000000245' + 0 	0.0377500554098419
15375249	11281	how to make a count of 0 show as null	select case when count(sterminal) = 0 then null else count(sterminal) end as terminal  from ....  where .... 	0.00883487618760244
15377158	29965	how to show clob type in a select in sql server?	select cast(clobcolumnname as varchar(50)) as clobcolumnname ; 	0.0171371894187912
15378792	33324	sum using 3 tables and outer join	select it.id,     r.month_year,     r.error_code,     coalesce(sum(error_count),0) "total errors",     sum(item_count) "total items",     coalesce(sum(error_count),0)/sum(item_count) "rate" from items it     join ref r         on (it.month_year = r.month_year)     left outer join errors er         on (r.month_year = er.month_year             and er.error_code = r.error_code             and er.id = it.id) group by it.id,      r.month_year,      r.error_code order by it.id,     r.month_year,     r.error_code 	0.633540932025972
15379637	573	how to override values if possible in mysql query	select        ifnull(working_hour_special.start, working_hour.start) as starttime,       ifnull(working_hour_special.end, working_hour.end) as endtime,       type    from        working_hour_special           left join working_hour              on working_hour.employee_id = working_hour_special.employee_id            and working_hour_special.start = date('2013-03-13')    where            employee_id = 1        and working_hour.weekday = dayofweek('2013-03-13') 	0.187653224506597
15380613	37145	sql: issue with finding unique customers of shops	select distinct customerid from tablename where shopid = 'sh1' and customerid not in (select customerid from tablename where shopid<>'sh1'); 	0.0275800916341498
15380653	14538	more efficient select	select  distinct top 15 a.webcompanyname, a.webcountryname from    webdownloadtable a   left outer join accountmatchingtable b     on a.webcompanyname + a.webcountryname = b.webcompanyname + b.webcountryname     or a.webcompanyname + ' ' = b.webcompanyname + b.webcountryname where b.webcompanyname is null order by webcompanyname, webcountryname 	0.388895127943678
15381059	35104	mysql tree table join and count rows	select     gt.gamename,     pdt.action,     count(pdt.action) as actioncount from gametable as gt inner join playerdatatable as pdt on pdt.gameid = gt.gameid inner join playerongame as pg on pg.gameid = pdt.gameid and pg.playernumber = pdt.playernumber where pg.playername = 'clement' group by gt.gameid , pdt.action 	0.0113451731943159
15381213	20414	retrieve most recent of multiple rows	select a.answer_id, a.q_id, a.answer, a.qscore_id, a.answer_timestamp from sometable a inner join (select q_id, max(answer_timestamp) as answer_timestamp from sometable group by q_id) sub1 on a.q_id = sub1.q_id and a.answer_timestamp = sub1.answer_timestamp 	0
15381694	195	sql server : join two rows. all columns from the 1st and 1 column from the second using an alias	select a.*, b.comp as rentalcomp from dbo.vwcomps as a left outer join dbo.vwcomps as b on a.propertyid = b.propertyid  and b.configurationused = 2 where (a.configurationused = 1) 	0
15381846	7224	loop through variable number of tables	select batch, avg(value) as avgvalue         from simulation                    where batch = 100         group by batch 	0.00877780367810619
15382412	9809	get sum of product quantity for product 'a' of company 'xyz' from database monthwise for whole year	select sum(inward_prodquantity),     inward_dateofdc,    inward_customername,    inward_productname from mm_inward group by month(inward_dateofdc) 	0
15384395	22854	mysql - php query	select user_id from travelled_details where user_id not in  (select distinct user_id from travelled_details where country not(2) and year(travel_date) not(2012) ) 	0.512830742731512
15384513	33431	how to search data in combination of field	select `student_personal_info`.`spi_id` as `sid` , `student_personal_info`.`spi_first_name`    as `fname` from `student_personal_info`   where concat( spi_first_name, ' ', spi_middle_name, ' ', spi_last_name ) like '%test%' order by `spi_first_name` asc 	0.0033216839856749
15386443	14363	find same records for each id	select phid, count(*) c from tablename where productid in (8,9,12,14,25) group by phid having c = 5; select phid, count(*) c from tablename where productid in (12,25,49) group by phid having c = 3; 	0
15386799	16883	mysql: count median grouped by day	select sq.created_at, avg(sq.price) as median_val from ( select t1.row_number, t1.price, t1.created_at from( select if(@prev!=d.created_at, @rownum:=1, @rownum:=@rownum+1) as `row_number`, d.price, @prev:=d.created_at as created_at from mediana d, (select @rownum:=0, @prev:=null) r order by created_at, price ) as t1 inner join   (   select count(*) as total_rows, created_at    from mediana d   group by created_at ) as t2 on t1.created_at = t2.created_at where 1=1 and t1.row_number>=t2.total_rows/2 and t1.row_number<=t2.total_rows/2+1 )sq group by sq.created_at 	0.000464362506338574
15386930	29776	split words in many columns sql	select     regexp_substr("column-desc", '\s+', 1, 1) as "return-desc1",     regexp_substr("column-desc", '\s+', 1, 2) as "return-desc2",     regexp_substr("column-desc", '\s+', 1, 3) as "return-desc3",     regexp_substr("column-desc", '\s+', 1, 4) as "return-desc4" from your_table 	0.0046366029788
15387177	41225	applying a function to an aliased field	select            t.latitude,           t.longitude,            ((acos(sin($lat * pi() / 180) * sin(t.latitude * pi() / 180) + cos($lat * pi() / 180) * cos(latitude * pi() / 180) * cos(($lon - t.longitude) * pi() / 180)) * 180 / pi()) * 60 * 1.1515) as distance      from (         select ((case when `venueid` > 0 then `venuelongitude` else `speciallongitude` end) as `longitude`, (case when `venueid` > 0 then `venuelatitude` else `speciallatitude` end) as `latitude` from gigs left join venues on ....      ) as t 	0.773850371892358
15387915	11527	join tables with different data in rows	select coalesce( a.id, b.id) id,      a.value1, b.value2 from a full join b on a.id = b.id 	0.00270943894522775
15389091	7686	how to exclude records with certain values in sql select	select distinct sc.storeid from storeclients sc where not exists(     select * from storeclients sc2      where sc2.storeid = sc.storeid and sc2.clientid = 5) 	0
15389163	35600	displaying data from multiple tables in a gridview	select * from cwiph inner join cjcms on cwiph.job_no=cjcms.job_no 	0.00156290512438625
15389678	3673	sql server query returns too many records	select  aankopenreparaties.id,         aankopenreparaties.klantenid,         aankopenreparaties.actietype,         aankopenreparaties.voorwerptype,         laptopscomputers.merk,         laptopscomputers.model,         laptopscomputers.info,         aankopenreparaties.info,         aankopenreparaties.prijs,         aankopenreparaties.lopend from    aankopenreparaties         inner join laptopscomputers             on aankopenreparaties.laptopid = laptopscomputers.id  where   aankopenreparaties.lopend = 'lopend' 	0.666864552035607
15390204	24442	retrieving single unique record from multiple repeating record	select h.hotelname, r.roomtype, r.roomrate from hotel h inner join room r on h,hotelid = r.hotelid where h.hotelname like '%park%' group by h.hotelname, r.roomtype, r.roomrate 	0
15390301	38776	sql request for some reason dublicates all content	select distinct ... 	0.0863862264427894
15390520	40505	sql - multiple select statements, one column, one query	select d.initials + ' ' + d.last_name as 'doctor name', p. initials + ' ' + p.last_name as 'patient name' from person p inner join appointment a on p.person_id = a.patient_id inner join person d on d.person_id = a.doctor_id 	0.00616396673373803
15391015	16860	join 2 tables if value of foo.column1 = x and bar.columns1 = y	select * from foo join (    select * from ( values      ('a', 'z'),     ('b', 'z'),     ('c', 'z'),   ) maptable(foocolumn,barcolumn) ) maptable on maptable.foocolumn = foo.column1 join bar on bar.column1 = maptable.barcolumn 	0.000187132643194614
15393506	31509	mysql - select rows which occur fewer/more than x months of the year	select item_code, count(distinct month(date)) as month_count from product_sales group by item_code having month_count > 1 	0
15393833	33102	avoid duplicate rows in sql query	select distinct    products.idproduct, sku, description, listprice, smallimageurl,    isbundlemain, rental, visits  from products, categories_products  where products.idproduct=categories_products.idproduct    and categories_products.idcategory="& pidcategory&"    and listhidden=0 and active=-1    and idstore=" &pidstore& "   order by description 	0.0694088598918235
15394667	25734	hourly sum of values	select store_id,          hour(ins_time) as hour_of_time,        sum(total_amount) as amount_sum from vendas201302  group by store_id, hour_of_time order by ins_time; 	0.00225092581268578
15394844	27601	get group_by values as strings	select group_concat(concat('''',asker,'''')) from questions 	0.0125974969262398
15395092	26423	selecting a set of rows with specific record data	select user.user_id, user.email, user.type,  sum(if(status = 'done',1, 0)) as done, count(*) as checks   from checks    join chk_user on checks.check_id = chk_user.check_id    join user on chk_user.user_id = user.user_id    group by chk_user.user_id    having done = checks 	0
15396493	33330	pl\sql select first row from column 1 where column 2 is unique	select min(d.ename) as ename   from emp d   group by d.deptno   order by ename asc 	0
15399150	22030	sql - need to select most recent entries from a table group by? distinct?	select airportfrom, airportto, price  from yourtable join  (select airportfrom af, airportto at, max(datetimeadded) lastupdate  from yourtable  group by airportfrom, airportto) temp on airportfrom = af  and airportto = at  and datetimeadded = lastupdate 	0
15399962	15298	sql query for returning the latest record for each id	select * from (select locid, value1, value1date,    rank() over (partition by locid order by value1date desc) as rank   from table1) t where t.rank=1 	0
15402632	11648	how to use xquery in sql server to search for character in column that stores xml data	select * from mytable where fileimage.exist('    /root/image/file_image     [contains(., " ")]') = 1 	0.0439148526635213
15402796	6828	get only the latest record within a group	select wipdata.wafernumber   ,wipdata.specname   ,max(wipdata.insertionnumber) insertionnumber   ,max(wipdata.insertionreasonname) keep (dense_rank last order by wipdata.insertionnumber) insertionreasonname   ,max(wipdata."total good dpw") keep (dense_rank last order by wipdata.insertionnumber) "total good dpw"   ,max(wipdata."accept bins b1") keep (dense_rank last order by wipdata.insertionnumber) "accept bins b1"   ,max(wipdata."accept bins b2") keep (dense_rank last order by wipdata.insertionnumber) "accept bins b2"    ...... from ( ...... ) wipdata where wipdata."total good dpw" <> 0 and wipdata."total rejects" <> 0 group by  wipdata.wafernumber,wipdata.specname order by wipdata.wafersequence; 	0
15404035	3445	group a single column in multible join query	select us.username, ro.role, ca.cartname, ca.date from users us left join roles ro on ro.roleid = us.roleid left join carts ca on ca.userid = us.id group by ca.date, us.username, ro.role, ca.cartname; 	0.102219102070029
15404490	37475	duplicating rows in an oracle query	select *  from your_data start with instr(wipdatavalue, '1') > 0 connect by level between regexp_substr(wipdatavalue, '^\d+')  and regexp_substr(wipdatavalue, '\d+$') 	0.174936283163583
15405798	37473	select defined string value with mysql query of a table	select * from photos where username like '%$username%'; 	0.00403054803039439
15408296	29513	postgresql: sql query to merge the contents from multiple rows using another column	select     msgid,     sender,     receiver,     transdate,     transtime,     array_to_string(array(         select chatcontent         from history         where msgid = h.msgid         order by row_id         ), ' '     ) chatcontent from history h group by 1, 2, 3, 4, 5, 6 order by 1 	0
15409350	14641	calculating deltas in time series with duplicate & missing values	select     logtime,     val,     last_value(val ignore nulls) over (order by logtime)        as not_null_val,    last_value(val ignore nulls) over (order by logtime) -        last_value(val ignore nulls) over (order by logtime rows between unbounded preceding and 1 preceding)        as delta   from your_tab order by logtime; 	0.00186788749231163
15409475	40714	sql select with outer join in same table	select * from table1 t1 where subject = 'eng.maths' and not exists (select null from table1 t2                 where t1.student = t2.student                 and t2.subject <> t1.subject) 	0.342658335090806
15409977	20714	obtaining counts	select      count(a.agvglst_pidm) "count_agvglst_pidm", from agvglst a where      a.agvglst_desg      = '1125' and a.agvglst_fisc_code = '2010' and not exists(             select 'x'             from                  agvglst b             where b.agvglst_pidm = a.agvglst_pidm             and b.agvglst_desg <> '1125'             and b.agvglst_fisc_code = '2010'         ) 	0.0754176185292785
15410336	734	how to select top n rows from each group id in same table	select      x.*     ,n.* from dbo.news n join (     select          pk_news         ,[rwn] = row_number() over(partition by pk_service order by pk_news asc)     from dbo.news ) x on n.pk_news=x.pk_news and x.rwn < 6 order by      n.pk_service, x.rwn 	0
15412624	18462	sql: how to get distinct value combined from row results	select page_id, max(cast(iscontentupdated as int)) from table group by page_id 	0
15413322	2679	mysql - join 2 tables to return a query with zero result	select doctor.doctor_id, count(appointment.appt_time) as no_app  from doctor left join appointment  on appointment.doctor_id = doctor.doctor_id group by doctor.doctor_id; 	0.0195052846884454
15413668	21111	finding active directory group/roles assigned on multiple sql servers	select     [srvprin].[name] [server_principal],    [srvprin].[type_desc] [principal_type],    [srvperm].[permission_name],    [srvperm].[state_desc]   from [sys].[server_permissions] srvperm    inner join [sys].[server_principals] srvprin      on [srvperm].[grantee_principal_id] = [srvprin].[principal_id]  where [srvprin].[type] in ('s', 'u', 'g') and [srvprin].[type_desc] like 'windows%'  order by [server_principal], [permission_name];  go create table #admembership (account_name sysname,  [type] nvarchar(10),  privilege nvarchar(10),  mapped_login_name nvarchar(max),  permission_path nvarchar(max)) declare @login sysname; set @login = suser_sname(); insert into #admembership exec xp_logininfo @login,'all'; select * from #admembership; drop table #admembership 	0.0030474458191751
15413750	24170	multiply a factor by the overlaps between two tables with date ranges	select    p.prod,     p.startdate as product_startdate,    p.enddate as product_enddate,    nvl(least(p.enddate, s.enddate) - greatest(p.startdate, s.startdate), 0) as xdays,    s.factor as fctr,       nvl(s.factor, 0) * nvl(least(p.enddate, s.enddate) - greatest(p.startdate, s.startdate), 0)        as time_reduction from     products p    left join slowdown s        on least(p.enddate, s.enddate) - greatest(p.startdate, s.startdate) > 0 	0
15414610	31261	sql count record with zero relation	select p.id, count(g.id) as numofgameplayed from player p left join game g  on p.id = g.id where p.name = 'jack' group by p.id; 	0.0259174688514861
15414809	34775	concat the second column value if the first column value is same	select listagg(title_of_doc_sec, ',') within group (order by tracking_num) as title_of_doc_sec       from your table     where....    select wm_concat(title_of_doc_sec) as title_of_doc_sec      from your table     where.... 	0
15415866	10700	can't get the order correct in sqlite query	select distinct      rev1.name,      rev2.name from reviewer rev1,      reviewer rev2,     (select r1.rid as r1id,             r2.rid as r2id        from rating r1,             rating r2       where r1.mid = r2.mid         and r1.rid <> r2.rid      ) as raters where rev1.rid = raters.r1id   and rev2.rid = raters.r2id   and rev1.name < rev2.name     order by asc 	0.59063063364565
15416544	37873	randomizing a specific group mysql	select *  from members  where category1="photographers"  order by      premium desc,      featured desc,      case when featured = 1 then rand() else company end asc 	0.0621829926013279
15419028	36357	mysql select rows with same table not in where clause	select t2.* from table1  inner join table2 on table2.4pp = table1.postcode4 inner join table2 t2 on t2.regio = table2.regio where table1.woonplaats = 'beetgum' 	0.0371388042086657
15419583	10595	sorting content from different mysql tables by date	select     `news_id`      as `id`,     `news_content` as `content`,     `news_pubdate` as `pubdate`,     ""             as `person`,     "news"         as `type` from `news` union select     `song_id`      as `id`,     `song_link`    as `content`,     `song_pubdate` as `pubdate`,     ""             as `person`,     "song"         as `type` from `song` union select     `interview_id`      as `id`,     `interview_content` as `content`,     `interview_pubdate` as `pubdate`,     `interview_artist`  as `person`,     "interview"         as `type` from `interview` order by `pubdate`; 	0.000344794129895571
15420069	27301	ignore duplicates?	select a.column1  from   (select column1,                 count(*) cnt          from   tbl          group  by column1          having count(*) = 1) a 	0.196422763752254
15420235	40056	sql list of all the user defined functions in a database	select name, definition, type_desc from sys.sql_modules m  inner join sys.objects o on m.object_id=o.object_id where type_desc like '%function%' 	0.00111420625455319
15420843	36690	greatest date group by tcp address	select yt.id, yt.tcpaddress, yt.analog, yt.discrete, yt.counter, yt.date  from xactions yt  inner join (    select tcpaddress, max(date) date    from xactions    where tcpaddress in ('192.168.1.161', '192.168.1.162')   group by tcpaddress  ) ss using (tcpaddress, date); 	0.0355040016469334
15420878	39071	show all rows in mysql that contain the same value (2 column filter)	select c2, group_concat(distinct c1) from table group by c2 having count(distinct c1)>1 	0
15421179	6112	remove rows with the same value in specific column from datagridview.	select * from dbo.yourtable t where exists (                        select 1               from dbo.yourtable t2               where t2.column3 = t.column3               having count(*) = 1               ) 	0
15421313	9143	sql (oracle) -how to get ratio from two count statements?	select      (select count (*) from tso_skf_nomeas_in60days_v)      /      (select count (*) from tso_skf_recent_meas) as perc from dual 	0.000480849647701568
15422066	11003	how to join rows in the same table by a shared column id with a where clause?	select t1.`parent_entry_id` as event_data_id,        t1.`child_entry_id` as user_id,        t2.`child_entry_id` as event_id from `exp_playa_relationships` as t1 inner join `exp_playa_relationships` as t2         on t2.`parent_entry_id` = t1.`parent_entry_id`            and t2.`parent_field_id` = 4 where  t1.`parent_field_id` = 5 	5.36488058316747e-05
15423195	18444	mysql validating data from multiple tables data	select * from   (select *   from stock     inner join master using (id)     inner join photo using (generalid)  where (master.brandid!=1001 and master.brandid!=1002) or stock.stock>0  ) as whatever group by master.generalid 	0.00299422338345602
15426707	31977	joining these tables	select uf.name, uf.dealeruserid,         case p.dealerid is null then 'false' else 'true' end as allowedstatus from userlist ul join userinfo uf on ul.dealeruserid = uf.dealeruserid left join carpermitted p on ul.dealeruserid = p.dealeruserid and ul.dealerid = p.dealerid where ul.dealerid = 'aaa' 	0.100236202910697
15426879	38481	count number of shared users to the given file in django?	select     files_id,     count(shared_user_id) as `shared` from mytable group by files_id order by files_id 	0
15427551	8753	result set column has value blob	select convert(column_name using latin1) from table_name; 	0.00354213196080679
15430834	25167	avoiding a for loop in sql	select base.packageid, servers.server,               (select count(*)                  from base as b1                where b1.packageid = base.packageid                  and b1.server    = servers.server) deployed   from base, servers  where base.server = 'baseline'    and deployed = 0; 	0.723490951562384
15431033	6396	sql query - filtered value from specific rows into result	select date,        (select max(kms) from invoices i2 where i2.kms < i1.kms) as startkm,         kms as finishkm from invoices i1 order by kms 	4.97806785250119e-05
15431119	754	age calculation query - optimization return time	select date_format(from_days(to_days(now())-to_days(str_to_date(m.m_dob, '%d-%b-%y'))), '%y')+0 as age   from impressions as i    inner join mariners as m     on i.sessionid = m.id where i.impression =1   and str_to_date(m.m_dob, '%d-%b-%y') is not null    and m_dob != ''    and date_format(from_days(to_days(now())-to_days(str_to_date(m.m_dob, '%d-%b-%y'))), '%y')+0 between 13 and 50  order by `age` desc 	0.470202782553436
15431698	7225	oracle: how to do multiple counts with different where clauses the best way?	select     c_unit_code,     count(case when your_conditions_for_advice_export then 1 end) as advice_export,     count(case when your_conditions_for_confirmation_export then 1 end) as confirmation_export,     count(case when your_conditions_for_issuance_standby then 1 end) as issuance_standby   from eximtrx.eplc_master   group by c_unit_code 	0.0283384168407366
15433580	12574	group by with multiple date columns	select     date_trunc('month', d) "month",     count(sent and sent_on = d or null) sent_on,     count(open = d or null) open,     count(clicked = d or null) clicked from     t     inner join     generate_series(         (select least(min(sent_on), min(open), min(clicked)) from t),         (select greatest(max(sent_on), max(open), max(clicked))from t)         , '1 day'     ) s(d) on s.d in (t.sent_on, t.open, t.clicked) group by 1 order by 1 	0.010566966363656
15433895	2957	regroup mysql query results in a single csv file	select id, type as objet, decret as type, resume as synthese from projets union select id, type as objet, decret as type, resume as synthese from articles 	0.0270263498428015
15434012	37725	get dynamic column value	select student_id, case when prefered_cell = 'cell_1' then cell_1                          when prefered_cell = 'cell_2' then cell_2                         when prefered_cell = 'cell_3' then cell_3                         else '0'                         end  as cell_value from student 	0.00512899404158162
15434934	12296	difference between the first value and the last values of the each days	select sub1.justdate, (b.volume - a.volume) as volumedifference from ( select date_format(from_unixtime(tstamp), '%y-%m-%d') as justdate, min(tstamp) as mintimestamp, max(tstamp) as maxtimestamp from tank group by justdate) sub1 inner join tank a on sub1.mintimestamp = a.tstamp inner join tank b on sub1.maxtimestamp = b.tstamp 	0
15435024	11373	return all numbers with more then 2 decimal digits in mysql	select *  from `table`  where length(substr(`summ `,instr(`summ `,"."))) >3 	0
15435239	19144	how to add aggregate value to select?	select name,         surname,         max(greatest(tbl_name.ora_rowscn, tbl_surname.ora_rowscn)) over () as max_rowscn from tbl_name, tbl_surname  where tbl_name.id = tbl_surname.id 	0.0165165946590261
15436273	3024	how to convert field to show date and time in sql	select convert(varchar(10), cast('jan  8 2013  2:47pm' as datetime), 101) + ' ' + right(convert(varchar, 'jan  8 2013  2:47pm', 100), 7) 	0.000415609246971558
15436540	8859	can mysql select into write column headers?	select * into outfile from ( select 'col1', 'col2', 'col3' union all select col1, col2, col3 from table_name) as t 	0.0213688122739022
15437631	26071	performing a join query with joins to rows that may not exist	select `gigs`.*, count(`signups`.`signupid`) as `signupspending` from `gigs` left join `signups` on `gigs`.`gigid` = `signups`.`gigid` and `signupstatus` = 4 group by `gigid` 	0.788386707095333
15437940	26146	generate series of a month by week interval in postgresql	select     greatest(date_trunc('week', dates.d), date_trunc('month',dates.d)) as start from generate_series('2013-02-01'::date, '2013-02-28', '1 day') as dates(d) group by 1 order by 1 	0
15438888	14550	mysql join with the same table without duplicates	select distinct    i1.name as name1,    i2.name as name2 from     instructors i1, instructors i2 where    i1.id < i2.id order by    name1, name2 	0.0109006469243291
15441905	31871	how can i select rows only where first digit is a number from 0 to 9?	select *  from badlydesignedtable  where answercolumn rlike '^[0-9]+' 	0
15442048	26656	sql server select max of a sum	select d.product_id p_id , d.green_sheet_id gs_id ,sum (p.prepress_amt) amt from  gs_prepress as p     inner join gs_data as d on p.green_sheet_id = d.green_sheet_id    inner join (select max(green_sheet_id) as gs_id                from gs_date                group by product_id) g on g.gs_id = d.green_sheet_id where product_id ='194456'   group by d.product_id, d.green_sheet_id 	0.0300390697065379
15442224	39120	oracle multiple subqueries return all or nothing	select    fruit, asize, product, quantity from    testtbla   full join testtblb using(code) where   code = 16 	0.526561471684301
15442280	39396	how to get data from a specific cell by specifying data from another cell in the same row	select forename, lastname from `table` where username = 'test123' 	0
15443636	24375	displaying entries with the same id from the database	select * from transactions group by order_id 	0
15443884	8773	query where a substring of an input is a part of the field	select * from `tbl`  where `id` = 'input'    or `alias` = 'input'   or 'input' like concat(`alias`,'%')   order by `id` = 'input' desc,      `alias` = 'input' desc,      (length(`alias`) - length(replace(`alias`, '/', ''))) desc limit 0,1 	0.00764330257530227
15444464	21487	extract id along with count of other columns	select customer,sum(producta),sum(productb)  from rm_saicharan_final6 group by customer 	0
15444658	26558	sql look up records in one table based on value looked up from another	select distinct o.* from inventory i    join inventory i2 on i.emi = i2.emi    join orders o on i2.itemnum = o.itemnum where i.itemnum =  12345 	0
15444736	12573	adding mysql entries together and displaying them in a table	select id, sum(minspld) as minspld from mlsstats group by id order by id asc 	0.000134704624324069
15449565	12474	select top 1 * from table fails in sybase procedure	select  employee_name from employees where employeeid > 50 having employeeid = min(employeeid) 	0.0134046547981865
15450078	5463	subselect on date	select      a.artnr     , a.txt     , a.active      , p.price     , p.prsgr       , p.prsdat from articles a inner join prices p on a.artnr = p.artnr where a.active = 'y'    and p.prsgr = 0    and p.prsdat < #02/10/2012#   and not exists (       select *          from prices nx        where nx.artnr = p.artnr         and nx.prsgr = 0         and nx.prsdat < #02/10/2012#         and nx.prsdat > p.prsdat           ) order by      articles.artnr    ; 	0.19457451286836
15451247	24362	finding at least one similar tag if possible	select u2.name, count(*) from   interests as i1         join users as u1           on u1.user_id = i1.user_id         join interests as i2           on i1.tag_id = i2.tag_id         join users as u2           on u2.user_id = i2.user_id              and u1.user_id <> u2.user_id         join tags as t           on i1.tag_id = t.tag_id  where  u1.name = 'john' group by u2.name; 	0.000523983089887607
15452164	36799	selecting from a select statement: every derived table must have its own alias	select  comment_id,         comment_message,         comment_date,         user_id,         first_name,         last_name,         profile_picture_path from (         select  c.comment_id,                 c.comment_message,                 c.comment_date,                 u.user_id,                 u.first_name,                 u.last_name,                 p.profile_picture_path         from    posts_comments c,                 users u,                 users_profile_pictures p         where   c.user_id = u.user_id                 and u.user_id = p.user_id                 and c.post_id = '82'         order by c.comment_date desc          limit 3     ) suba  order by comment_date asc 	7.22073957330378e-05
15452605	13600	get tow column from nested query	select    max(companyno) keep (dense_rank first order by count(employeeno) desc) as cn,   max(count(employeeno)) maxnum from works group by companyno 	0.0200460480901073
15452628	16092	select the last record in each group	select   r1.* from remark r1   left join remark r2     on (r1.serial_no = r2.serial_no     and r1.remark_no < r2.remark_no) where r2.remark_no is null; 	0
15453027	9797	how to concat 2 numeric fields and convert to string at the same time in sql server select	select      right('00' + cast(groupid as varchar(2)), 2) +      right('000' + cast(itemid as varchar(3)), 3) as stringid from tbl 	0
15453231	11934	select the second last record in each group	select s.serialno, r.remarkno, r.desp from (select serialno, max(remarkno) maxremark from remark group by serialno) s left join remark r on s.serialno = r.serialno and s.maxremark-1 = r.remarkno 	0
15455368	7393	select rows with max value from groups of rows grouped by multiple columns (psql)	select distinct on ("date", location_code, product_code, type)     "date",     location_code,     product_code,     quantity,     type,     updated_at from transactions t order by t."date", t.location_code, t.product_code, t.type, t.updated_at desc 	0
15457030	32896	get the count of items related to nested category in sql	select parent.title, ( select count(i.id) count from items i   where category_id in   (  select child.id from categories child where child.lft>=parent.lft and      child.rgt<=parent.rgt and child.root=parent.root  ) ) from categories parent  where parent.parent_id=@parent_id; 	0
15458663	17440	sql time extending to next day	select distinct * from map inner join mba on map.channel = mba.channel and map.product = mba.product where (map.date = mba.progdate        and advttime >= starttime        and (advttime <= endtime or endtime < starttime))       or       (map.date = dateadd(day,1,mba.progdate)         and endtime < starttime                        and advttime <= endtime) order by mba.channel asc 	0.00043684406734132
15460999	32929	mysql query for grouping column based on different conditions	select  location ,       sum(case when percentageraised >= 1.0 then 1 end) as successful ,       sum(case when percentageraised < 1.0 then 1 end) as unsuccessful from    yourtable group by         location 	0.000527344880894476
15461243	27549	time and date fields not synchronized with id field	select  a.order_id,         group_concat(concat(b.quantity, ' x ',c.name) separator ', ') itemname,         max(a.date) date,         max(a.time) time from    `order` a         inner join orderform b             on a.order_id  = b.order_id          inner join item c             on b.item_id = c.item_id  group   by a.order_id 	0.0013070839972499
15463222	5357	sql query 'not in'	select customer_name, state, postal_code  from customer_t  where state not in ('ca', 'fl', 'nj')  order by postal_code asc 	0.787812501743433
15463666	11367	sql join - need to return one product id but all variations of it (e.g. size, colour)	select p.productid, group_concat(distinct c.colourname), group_concat(distinct c.colourhex), group_concat(distinct sz.sizename), sum(s.qty) from tblproducts p inner join tblstock s on p.productid = s.productid inner join tblcolour c on s.colourid = c.colourid inner join tblsize sz on s.sizeid = sz.sizeid where p.productid = '$id' group by p.productid ; 	0.0010270664324953
15465182	29054	return most frequent occurence(s)	select top 1 *  from (select names.lastname, count(names.lastname) as countoflastname       from [names]       group by names.lastname) a order by countoflastname desc 	0.000578244604132824
15465521	33565	count rows in a join against another table	select count(offers_id) as offers, image1, product_type, product.amount, product.price, description, product.product_id   from product inner join offers on product.product_id = offers.product_id   where product_type like '%$product_type%'" group by image1, product_type, product.amount, product.price, description, product.product_id 	0.000924554734573862
15465537	41204	sql display only the highest values of a count function	select  id as personid ,       count(tid) as sales from    salestable group by          id having  count(tid) =         (         select  max(sales)         from    (                 select  count(tid) as sales                 from    salestable                 group by                         id                 ) subqueryalias         ) 	0
15466503	39316	select entries where count = 0	select rooms.room_number  from rooms  where rooms.room_number not in ( select guests.room_number                                   from guests) 	0.00552457661594713
15466982	34896	mysql 2 tables to another table	select name, max(email), phone from     (        select name, email, phone from table1        union        select name, email, phone from table2     ) a     group by name, phone     having email=max(email) 	0.000734925765265994
15467163	8045	how to get all order id which not paid in sql server 2008?	select     o.orderid from [order] o inner join (    select         orderid,        sum(soldquantity * p.saleprice) as total    from orderline    inner join product p on p.productid = orderline.productid         group by orderid ) ol on ol.orderid = o.orderid left join (     select         orderid,         sum(cashmovementvalue) as total     from cashmovement     group by orderid ) c on c.orderid = o.orderid where     o.customerid = @custid     and ( c.orderid is null or c.total < ol.total ) 	0.000791887169976147
15467531	25426	sql average time from timestamp stored as string	select [date],   convert(varchar(8),   cast((avg(cast(cast(starhour as datetime)  as float)))   as datetime) , 108)   from table group by [date] 	0.000328106542340043
15467583	24675	sum and conditional in oracle sql	select part  from your_table group by part having    sum(orderqty) - sum(shippedqty) < max(qoh) 	0.751802717697092
15471671	24581	2 inner joins in one select statement	select      i.stkid     ,   i.stkname   ,   c.cityname "supplier location" from        stockitem i, supplier s , city c where     i.suppid = s.suppid and   s.citycode = c.citycode order by    stkid asc; 	0.394833409608603
15472168	17059	mysql get latest result with specifc id?	select * from yourtablename where userid = 39 order by created_day desc limit 1 	0.000141161826074832
15474350	8465	using oracle contains clause for 2 columns	select *  from contact  where (contains(username, 'abcd', 1)> 0) and (contains(first_name, 'abcd', 2)> 0); 	0.0655500941739734
15476274	38972	combine two sql queries - count and where	select top 1 username, count(access) as count  from permissions ps where access = 1 and username in       (select username          from permissions          where itemid = 2             and access = 1       ) group by username order by count desc 	0.0371716341225632
15479129	22969	what is the query to display the contents from 2 tables without duplicate data?	select question,description,comment from   forum_t    inner join    forum_answer   on forum_t.forum_id=forum_answer.forum_id where   forum_t.forum_id={your forum id} 	0
15479566	38464	count column in mysql	select userid, paymentid, datetime,         grptotal as `order` from (   select  userid,           paymentid,           datetime,           @sum := if(@grp = userid,@sum,0) + 1 as grptotal,           @grp := userid   from    tablename,           (select @grp := '', @sum := 0) vars   order   by  userid, datetime ) x 	0.06590259264232
15480631	22721	return count of all column entries containing "keyword"	select  job_location, count(*) from    registration where   job_location like '%xyz%' group   by job_location 	0
15483892	9193	mysql searching text and linking tables	select u.* from tbl_user u join tbl_usergames ug on (u.id = ug.id_user) join tbl_games g on (ug.id_game = g.id) where     g.name like '%mario%' 	0.0365942651211526
15486131	33755	select distinct and max in the same query	select distinct(survey_id) as identifier,         (select max(survey_id) from survey) as "current"    from survey_main; 	0.00364290499429193
15487186	1439	find gaps in date ranges using sql in oracle	select     to_char(sd, 'yyyymmdd') as sd,    to_char(ed, 'yyyymmdd') as ed from    (         select          bed + 1 as sd,          lead(bsd, 1, aed + 1) over (partition by asd,aed order by bsd) - 1 as ed       from          (               select aa.sd as asd, aa.ed as aed, bb.sd as bsd, bb.ed as bed             from aa join bb on least(aa.ed, bb.ed) >= greatest(aa.sd, bb.sd)             union all             select aa.sd, aa.ed, to_date('1000','yyyy'), aa.sd - 1             from aa          )    )    where sd <= ed   order by 1 	0.00183515534254072
15487353	36860	get last row name by column, then desc	select max(id) from $tablename 	0
15487468	17096	mysql sum only 1 field and	select date, sum(value) as total from table group by date 	0.00337624930606664
15487477	2591	php/mysql contact list	select distinct `from` from `messages` where `to` = `current_user_id` 	0.033183648242383
15487597	17302	find a date from last year in sql server	select dateadd(month,-11,dateadd(mm,datediff(mm,0,getdate()),0) ) select dateadd(month,-11,dateadd(ms,-3,dateadd(mm,0,dateadd(mm,datediff(mm,0,getdate())+1,0)))) 	0
15490014	12965	if i match a text string against multiple columns, is there an easy way to know which one(s) matched?	select (txt_1 like '%foo%') as `txt1_matches`,         (txt_2 like '%foo%') as `txt2_matches`, ... from some_table where match (txt_1, txt_2, ...) against ('foo') 	0.0026038921500984
15490118	3226	sql string to query access database	select * from mytable inner join lookup l on mycolumn = l.key and l.value =  'this text string'; 	0.473319251499404
15491647	29895	round off column value in postgresql	select round( cast("num" as numeric), 2) from abc; 	0.00891732683297335
15491685	39775	how to find required unique result	select post_id, subcategory_id from subcategory as s, topic as t where     s.subcategory_id = t.subcategory_id and time = (       select max(time) from subcategory as s1, topic as t1 where           s1.subcategory_id = t1.subcategory_id and s1.category_id = s.category_id    ); 	0.00535990073714864
15492678	6386	return the name(s) of the professor(s) who taught the most number of courses in class 10	select    p.empid   ,p.name   ,count(w.courseid) as coursecount from    professor p inner join    works w on p.empid = w.empid where w.classid = 10 group by p.empid,p.name order by count(w.courseid) desc 	0
15493064	10673	php getting data from user and searching into multiple columns	select distinct * from `group` where `group_name` like '%$text%' or `admin_name` like '%$text%'; 	4.75703856486474e-05
15493411	31578	how to get data from two tables using join from my sql table	select  a.user_name, b.description, b.title from    mylearning a         inner join catalog b             on a.content_id = b.content_id 	6.36753798579548e-05
15493826	13521	group by and contact rows except the default value	select  random_id, group_concat(msg separator ' ') msg from    tablename where   random_id <> 0 group   by random_id union select  random_id, msg from    tablename where   random_id = 0 	0.000302206763090349
15494612	36906	query to select one record from multiple records	select id, employer_id     from table group by employer_id 	0
15495570	39740	sql following and followers	select          theirfollows.id, theirfollows.account_name,          theirfollows.followed_name, theirfollows.time,          m.account_name as member_name, m.status,          case              when myfollows.followed_name is null then 0             else 1         end as sessionmemberisfollowing from    account_members m         left join account_follows theirfollows           on theirfollows.account_name = m.account_name         left join              (                 select followed_name                 from account_follows                  where account_name = :session_account_name             ) myfollows             on myfollows.followed_name = theirfollows.followed_name where   m.account_name = :account_name 	0.540694716965673
15496684	11121	sql how to over-write data and then sort or filter on that data	select       (case lif_status='alive' then pet_name else 'deadpet' end) as `pet_name`              pet_species,              lif_status from         pet inner join   life on lif_pet_pk=pet_pk order by     `pet_name` 	0.000869791311726742
15497321	39104	sql - combine two columns into a comma separated list	select course.name,        stuff((select distinct ',' + convert(varchar(10), cycledate, 103)                   from (select id, date, courseid from cycles                      union                      select id, extradate, courseid from extradays) t2               where t2.courseid= course.id and t2.cycledate > getdate()               for xml path('')),1,1,'') as 'datums' 	0
15497741	13482	only one expression can be specified in the select list. in sql query	select * from tbl_searchparameters p   cross apply (                select sum(averageprice/count(1)) as averageprice,                        sum(itemssold) as itemsold,                                      sum(averageprice * itemssold) as totalsale                 from dbo.tbl_productsales                where productid in (select productid                                     from tbl_productpostions                                     where tbl_productpostions.searchid = p.searchid                                                 and saledate='2012-02-02 00:00:00.000')                group by saledate                ) o 	0.0259589638745777
15500013	38221	how can i join a with b and also b with c at one time?	select product.title, user.username, order.id from order inner join product on order.productid = product.id inner join user on product.userid = user.id 	0.000151837164327456
15501919	16463	sum of all values, based on a calculated field	select tbl_carforsale.name as 'employee name',      sum(tbl_carforsale.carprice) as    'value of cars sold'        sum(tbl_carforsale.carprice * tc.comavailable) as    'commission on cars sold'    inner join tbl_carforsale on      tbl_employee.employeeno = tbl_carforsale.employeeno inner join tbl_com tc on      tbl_carforsale.carprice >= tc.minvalue      and     tbl_carforsale.carprice <= tc.maxvalue     where tbl_carforsale.solddate between  dateadd("m", -1 ,date()) and date() and tbl_carforsale.bolsold = true  group by tbl_employee.name 	0
15502759	20441	in sql server, is it possible to include 2 columns in an in clause?	select *  from distributors where  ( city = 'springfield' and state = 'oh') or        ( city = 'springfield' and state = 'mo') or        ( city = 'houston' and state = 'tx') 	0.38869967374966
15505484	33075	storing specific datetime format in database	select date_format(timestamp_field,'%y-%m-%dt%tz') as solrdate from table; 	0.0107081934428038
15505686	39070	sql time query from 6pm at night to 6am	select count(barcode) from table1 where timestamp >= dateadd(hour,18,convert(varchar(10), getdate(),110))   and timestamp <= dateadd(hour,6,convert(varchar(10), getdate()+1,110)) 	0.0233205708217851
15505931	41331	how can i store getdate() in a varchar, but as a datetime?	select convert(varchar(50),getdate(),121) insert into table varchar_field values (convert(varchar(50),getdate(),121)) 	0.0403229208064354
15508972	40973	how do i select the most eaten portion of a food from mysql?	select rq.food, rq.amount  from (select food, amount, count(*) amcount       from eaten       group by food, amount) rq join (select food, max(amcount) maxcount from       (select food, amount, count(*) amcount        from eaten        group by food, amount) sq       group by food) mq on rq.food = mq.food and rq.amcount = mq.maxcount 	0.000183911852673272
15509638	25320	grouping in mysql with a not condition	select      case       when name like 'internet explorer%' then name       else substring_index(name, ' ', 1)     end as newname from tablea group by newname 	0.555216644911155
15509697	3173	hotel - single booking with multiple dependents in multiple rooms	select b.bookingid,        b.guestid,        d.dependantid,        d.forename as firstname,        d.surname as lastname,        br.floorno,        br.roomno from  booking b       left join bookingdependant bd       on b.bookingid = bd.bookingid       left join dependant d       on d.dependantid = bd.dependantid       left join bookingroom br        on br.id = bd.roomid and on br.bookingid = b.bookingid where b.bookingid = &bookingid; 	0.015945023440509
15512321	16394	what's the difference between sql_latin1_general_cp1_ci_as and sql_latin1_general_cp1_ci_ai	select * from r left outer join hr on hr.name = r.name collate sql_latin1_general_cp850_ci_ai 	0.0806424981730932
15513523	6639	sql query choose row for many fields	select posttown, min(postcode) from postdata group by posttown 	0.0130513744406461
15514263	27146	mysql logging a user on from one table & count occurrences from another in same statement	select a.aid,        a.aemail,        a.abio,        a.areg,        (select count(*)            from messages           where mread=0 and mreciever=a.aid) occurrences   from authors a  where a.aemail = 'email@mail.com' and a.apass = '*****' 	0
15516975	25449	selecting with multiple where conditions and multiple order clauses from two tables	select  p.* from    posts p         inner join         (             select  a.id             from    posts a                     inner join post_tags b                         on a.id = b.post_id             where   a.post like '%mmmm%' and                     b.tagname in ('#test','#iseeyou')             group   by id             having  count(distinct b.tagname) = 2         ) sub on p.id = sub.id order   by p.upvotes desc, p.unix_timestamp desc 	0.000984680854587084
15517320	30750	how to select records in a track with gaps not greater than 5 minutes between each record?	select      f.id as from_id,     t.id as to_id from     gpstable as f  join gpstable as t     on f.id = t.id-1  where     timestampdiff(second, f.date, t.date) < 300 ; 	0
15518415	28120	mysql group by with priority on some value	select   min(id) id,   code,   min(product_name) product_name,   min(supplier) supplier from   yourtable where   (code, case when supplier='supplier1' then '' else supplier end)   in (select   code, min(case when supplier='supplier1' then '' else supplier end)       from     yourtable       group by code) group by   code order by   min(id); 	0.0150237261727014
15520174	8289	percentage change based on two numbers, total unknown (mysql)	select brand_price, brand_discount_price, if(brand_discount_price > brand_price, ((brand_discount_price - brand_price)/brand_discount_price) * 100, ((brand_price - brand_discount_price)/brand_price)*100)  as percentage from brand 	0
15521317	24291	counting the total records from table in pagination mode	select sum(amount) as totalamount from tablename 	0
15521938	23936	output from select statement + suffix	select [percentage] & " %" as expr1 from [customer] where [percentage] > 10; 	0.5470813393503
15522662	14681	sqlite: convert a date to a day number in the month	select julianday(dates) - julianday(date('now','-1 month')) + 1 from table1 where dates > date('now','-1 month') 	0
15523160	23916	mysql find missing entries from duplicated rows	select product_id, count(customer_group) from table_product_options group by product_id having count(customer_group) < 4 	0
15523406	32480	is it possible to join these 2 tables	select      a.entryfrom, a.entryto, sum(value) totalvalue  from tablea a inner join tableb b on b.entry between a.entryfrom and a.entryto  group by a.entryfrom, a.entryto 	0.337320332349673
15523550	14407	count the amount of visits per hour from a visitlogs table	select  location_id, sum(case when hour(time) = 0 then 1 else 0) as '0',          sum(case when hour(time) = 1 then 1 else 0) as '1', from table group by location_id 	0
15524356	25670	mysql : assign integer value to the string values and get the average	select avg(case howistraining              when 'excellent' then 5              when 'very good' then 4              when 'good' then 3              when 'poor' then 2              when 'pathetic' then 1              else null            end) as avg_rating from feedback 	0
15524532	34656	ms-sql list of email addresses like statement/regex	select      *      , flag = case when len(field) - len(replace(replace(field,'@mycompany.com','xxxxxxxxxxxxxx'),'@','')) > 0 then 1 else 0 end  from (     select 'alice@mycompany.com, bob@mycompany.com, malory@yourcompany.com' as field union all      select 'alice@mycompany.com, bob@mycompany.com' union all      select 'malory@yourcompany.com'  ) x 	0.20124265611141
15524764	23045	php/mysql - using union, how to set variable based on selected table?	select sid as ssid, created as screated, message as smessage, recipient as srecipient, "status" as link_type  from {statuses} where created > :logout_stamp union select sid as ssid, created as screated, comment as smessage, uid as srecipient,"comment" as link_type  from {fbss_comments} fbss where fbss.created > :logout_stamp order by screated desc limit 15 	0.000710093309683125
15525892	37303	getting distinct mysql result of one field based on another field	select count(a) count, sum(av) total, sum(ap) aptotal from (     select affiliate_orders_id a, affiliate_value av, sum(affiliate_payment) as ap from " . table_affiliate_sales . " a      left join " . table_orders . " o on (a.affiliate_orders_id = o.orders_id     group by affiliate_orders_id, affiliate_value) where a.affiliate_orders_id = o.orders_id  and o.orders_status >= " . affiliate_payment_order_min_status . ") a 	0
15526864	4412	request random row in a query with left join	select y.*     from        ( select *            from questions           order              by rand() limit 2       ) x     join answers y       on y.question_id = x.question_id    order        by x.question_id; 	0.433936362847735
15527342	16629	postgres aggragator which checks for occurences	select sum(case when value = 4 then 1 else 0 end) > 0 from mytable where id > 5 	0.00851609292107142
15527682	37374	multiple rows come back of same id, just need one	select         `table_one`.`id`, `table_one`.`productname`, `table_one`.`image`, `table_one`.`quantity`,         `table_two`.`productid`, sum(`table_two`.`quantityreserved`)     from         `table_one`      left join         `table_two` on `table_one`.`id` = `table_two`.`productid`      where         `table_one`.`quantity` > 0           or `table_two`.`datereserved` + interval 5 day <= '2013-03-27'     group by `table_two`.`productid`     order by productname 	0
15528265	38738	sql server: specify column name as attribute using for xml	select name as [@name],        'number of orders over 50 pounds' as [over50/@columnname],        over50 as [over50/@value],        'orders cancelled' as [cancelled/@columnname],        cancelled as [cancelled/@value] from yourtable for xml path('customer'), root('customers') 	0.0227573778776892
15528950	8882	how to do a outer join on a query	select tablea.type, sum(b.hrereelles) as hrereellestotales,         b.noprojet_short  from tablea  left join (select * from tableb    where tableb.columnname = 'somevalue') b on tablea.idtype = b.idtype   where tablea.categorie = 'electrique'  group by b.noprojet_short,tablea.type 	0.76465011882884
15531043	17380	mysql where and last	select b.email, b.date, b.complete, b.code from   (select email,                 max(date) as date          from   users_recovery          group  by email         where  code = variable                and complete = 0) a         join users_recovery b           on b.email = a.email              and b.date = a.date 	0.0106118013487328
15533541	31924	joining two tables and selecting rows not present in the second 1	select users.username, count(mail.receiver) as count_mail from users  left join mail on mail.receiver = users.username  left join block on block.blocker = users.username     and mail.sender = block.blocked where block.blocked is null group by 1 	0
15533929	18207	mysql - looking for top 10 records by month	select * from (   select      m.merchantname,      count(r.orderno),      sum(r.commission)   from     revshare r     left join products p on r.itemid = p.pid     left join merchants m on p.mid = m.mid   where     r.eventdate between '2011-01-01' and '2011-01-31'   group by     r.itemid   order by      3 desc limit 10 ) as result1 union all select * from (   select      m.merchantname,      count(r.orderno),      sum(r.commission)   from     revshare r     left join products p on r.itemid = p.pid     left join merchants m on p.mid = m.mid   where     r.eventdate between '2011-02-01' and '2011-02-31'   group by     r.itemid   order by     3 desc limit 10 ) as result2 	6.64438433095205e-05
15534833	40314	mysql query on wordpress database	select      post.id as post_id,      post.post_title,      post.guid as post_url,      image_detail.id as image_id,      image_detail.post_title as image_title,      image_detail.guid as image_url from wp_posts as post left join (     select post_parent, min( id ) as first_image_id     from wp_posts     where post_type = 'attachment'         and post_mime_type like 'image/%'     group by post_parent     ) as image_latest      on post.id = image_latest.post_parent left join wp_posts as image_detail      on image_detail.id = image_latest.first_image_id where post.post_status = 'publish'; 	0.299374505881877
15535462	40683	how to sum a series of rows in mysql from one table, matching the info from another to get the result	select *,   if(meta = 0 or soma > meta, 100, (soma/meta)*100) percent from (  select table2.*,     (select sum(qtde)      from   table1      where  table1.cnes = table2.cnes             and table1.procedimento = table2.procedimento             and table1.mes = table2.mes             and table1.ano = table2.ano      group  by cnes,                procedimento,                ano,                mes) as soma from   table2) tmp; 	0
15536224	17815	storing the previous month as a char with a leading 0 for single digit months	select count(*) from jwemaildb.logfilerecords where     date > = dateadd(month, datediff(month, 0, getdate())-1, 0) and     date <  dateadd(month, datediff(month, 0, getdate()), 0) and     cast(right(ealertsentdate, 4) + left(ealertsentdate, 4) as date) between            dateadd(dd , 1 - day(getdate()), dateadd(mm, -1 ,getdate())) and     dateadd(dd , 1 - day(getdate()), getdate()) 	0
15536303	29851	match items in mysql imploded array to php array in query	select * from codeunits join tags on tags.codeunit_id=codeunits.id where tags.name in (:tags) and case when private=1 then creatorid=:userid else true end 	0.0129962017026679
15539065	22861	left/right join with reference to another table	select set1.item, pcs, css from set1 left join set3 on set3.item = set1.item left join set2 on set2.code = set3.code      and set2.mo = month(sysdate())      and set2.yr = year(sysdate()) 	0.0407896479905047
15539068	2348	sql:how to take substring for query	select right(inc_date, 4); 	0.233722233845468
15540769	37773	sql query getting id wise balance	select      a.id,      sum(case when a.trans_date < '01-feb-2013'           then nvl(a.amt_cr,0) - nvl(a.amt_dr,0)          else 0          end) as balamt,      p.name from table1 a, table2 p where p.id between 'c0100' and 'c0200'     and p.id = a.id group by a.id, p.name order by a.id 	0.0164345995523287
15541025	34546	sql join to get records that do not fall between two dates	select *     from discount     where id not in (         select discount.id from discount              left join discount_exception                    on discount.id = discount_exception.discount_id           where ('2013-5-1'  between discount_exception.from_date and discount_exception.to_date )                      or ('2013-5-5'  between discount_exception.from_date  and discount_exception.to_date )                     or (discount_exception.from_date between '2013-5-1' and '2013-5-5' )                     or (discount_exception.to_date between '2013-5-1' and '2013-5-5') )  ) 	0
15541799	37236	select query in oracle	select     ref,     sum(weight) over (partition by ref order by dated) as weight,    no,    address from    ... 	0.510511867657966
15542245	34467	specific search in database	select * from table where name like '% car' or name like 'car %' or name like '% car %' or name like '% car.'; 	0.0627112932059793
15543044	7605	how to do an or query in sql	select * from category c  inner join category_organisation co on co.category_id = c.category_id  and co.organisation_id = 'logged_in_users_organisation_id' or c.category_id in( select category_user.category_id from category_user where category_user.user_id = 'logged_in_users_organisation_id') 	0.6720005473857
15543204	3891	how to replace last occurrence of a substring in mysql?	select reverse(concat(                left(reverse('american corp national corp'),                     instr(reverse('american corp national corp'),reverse('corp'))-1),                substr(reverse('american corp national corp'),                       instr(reverse('american corp national corp'),reverse('corp'))+                       length('corp')))) result 	0.000132646160485738
15543433	28105	sql - select from 2 tables almost identical tables	select *, 't1' tablename from table1 union all select *, true 'active', 't2' tablename from table2 	0.000362535391054129
15544925	22743	mysql query - average amount of lines per order, on a monthly basis	select year(date)       , month(date)        , count(*) line_count        , count(distinct orderno) orders_placed    from orders   where date between '2010-01-21' and curdate()    group       by year(date)       , month(date)     order        by date; 	0
15545400	9769	select from database where some parammeter is equal to a portion of a string var	select * from table where value like '%string%'; 	0.000673581595668755
15545464	37210	select multiple columns from mutiple tables	select car.id, car.name, ci1.country as [year], ci2.country as country from car inner join car_info as ci1 on car.id = ci1.car_id and ci1.field_name = 'year' inner join car_info as ci2 on car.id = ci2.car_id and ci2.field_name = 'country' 	0.000600735540016559
15546167	1170	how can i number data blockwise in mysql?	select x.*       , count(*) ordering     from tabelle x     join tabelle y       on y.id = x.id      and y.random_nr <= x.random_nr    group       by x.id       , x.random_nr; 	0.0215166494978579
15546964	33645	combine three different conditions in a single query	select allcolumnsyouwanttouse from table you want where first union select samecolmns from table where second union select samecolumns from table where third 	0.00280327772691543
15547859	29576	reportviewer - make consecutive repeating rows become one	select date, name, id, sum(quantity) as quantity from emptable group by date, name, id order by date asc 	0.000318400956799441
15549747	36611	sql left join on two different tables	select    w.id,   isnull(h.title, w.title)   d.version,   t.size from dbo.widget as w left join dbo.widgethistory as h on w.id = h.id left join dbo.doodad as d on d.id = isnull(h.doodadid, w.doodadid)  left join dbo.thing as t on t.id = isnull(h.thingid, w.thingid) 	0.03355342074805
15549756	6818	how to aggregate data in sql within nested groups	select category, name, date_trunc('minute', sample_time) as minute, count(*)  from usage_sample  group by category, name, date_trunc('minute', sample_time) order by category, name, minute 	0.325217366425493
15551303	4589	separate multiple values	select m.*,me.*     from movies m     join movie_embeds me on (me.movie_id=m.id)     group by m.title; 	0.00839077393521343
15554061	18952	check if date exists before and after a given date in one query	select if( exists(select dayid from logbookday  where logdate < '2012-03-01' and userid = 1), 1, 0) as prev, if( exists(select dayid from logbookday  where logdate > concat('2012-03-',last_day('2003-02-05'))  and userid = 1), 1, 0) as next 	0
15555327	24203	mysql - grouping data by columns	select g.gender,        sum(case when likebread=g.gender then 1 end) likebread,        sum(case when likecheese=g.gender then 1 end) likecheese,        sum(case when likemilk=g.gender then 1 end) likemilk from (select 'girl' gender union select 'boy') g cross join ilike group by g.gender 	0.012996045979379
15556576	20232	sybase ase run query from one db on the other	select row_count(db_id("db_archive"), object_id("db_archive.dbo.table_name")) 	0.000762951387562802
15557884	28868	get a column total and a group by total	select user, sum(page_hits) as site_hits, sum(page_hits) / (select sum(page_hits) from hit_data)  from hit_data group by user 	0
15558697	24274	combine every two rows expect the every seventh(sum value, and change the age range)	select ref_date, city, province, sex, newage, sum(value) as value from (select ref_date, city, province, sex, age, value,              (case when age in ('15 to 19 years', '20 to 24 years')                    then '15 to 24 years'                    when age in ('25 to 29 years', '30 to 34 years')                    then '25 to 34 years'                    when age in ('35 to 39 years', '40 to 44 years')                    then '35 to 44 years'                    when age in ('45 to 49 years', '50 to 54 years')                    then '45 to 54 years'                    when age in ('55 to 59 years', '60 to 64 years')                    then '55 to 64 years'                    else age                end) as newage       from t      ) t group by ref_date, city, province, sex, newage 	0
15559518	1450	most required item from mysql with php	select      item_name,      count(1)  from      table_submissions  group by      item_name  order by      count(1) desc  limit 10; 	0.00133714575248949
15560830	10352	get the string with the most occurances in a column	select locations, count(*) as times from table group by locations order by times desc limit 1; 	5.87226189155797e-05
15562162	15224	creating sql without using min	select college.cname,state,gpa        from college c     join apply a on a.cname = c.cname      join student s on s.sid = apply.sid where not exists(select * from student                   where gpa < s.gpa); 	0.611219591690819
15563127	22555	mysql/mysqli select from table until a given value is found	select * from table1 where secondaryid='9' and tertiaryid='4' and `limit`='1' and primaryid<='3' and `datetime`>= (select `datetime` from table1 where secondaryid='9' and tertiaryid='4' and `limit`='0' and primaryid<='3' order by `datetime` desc limit 1) order by `datetime` desc 	0
15563567	20959	how to order by an arbitrary condition in sql	select * from   bable order  by case when name like '%$..' then 0 else 1 end,           name 	0.167740578044261
15563656	41280	convert string to date in sqlite	select datetime(substr(col, 7, 4) || '-' || substr(col, 4, 2) || '-' || substr(col, 1, 2)) from table; 	0.0363946141397473
15564656	32450	mysql - inner join with select statement to fetch sum	select ui.email, ui.userid, sum(ep.earnpoints), ep.add_date from earn_points as ep  inner join user_info as ui on ep.userid = ui.userid  where date(rc.add_date) = '2012-03-22' group by ui.email,ui.userid,ep.add_date; 	0.479712283433733
15565119	13499	how to write this self join based on three columns	select distinct        id  from    tbl_info t  left join     (select         parentid,        count(distinct id) as childs     from        tbl_info     group by parentid) as parentchildrelation     on t.id = parentchildrelation.parentid    where t.no_daughters != parentchildrelation.childs 	0.152020846057004
15565151	10264	get date of every second tuesday of a month	select  dateadd(day, 8, datediff(day, 1, dateadd(month, n, '2013-01-07')) / 7 * 7) date from  (values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11)) t(n) 	0
15566493	24745	what's the best way to check for existing entry in mysql? (simple table structure, lots of data)	select `numbers` from `phone_numbers` where `number` in('123', '456', '789') 	0.00966320744900798
15570096	39799	sqlite get rowid	select rowid, * from tbl1 where letter = 'b' 	0.129501965127819
15570356	9495	how to get values between two dates from a table which have no data some days	select cr_date      , to_char(cr_date, 'dd')   curr_day      , to_char(cr_date, 'mm')   curr_month      , to_char(cr_date, 'yyyy') curr_year  from  (  select (cr_date-1) + level as cr_date    from     (     select to_date('08.05.2013', 'dd.mm.yyyy')  end_date          , to_date('08.04.2013', 'dd.mm.yyyy')  cr_date        from dual    )    connect by level <= (end_date - cr_date)+1  ) / cr_date    curr_day    curr_month    curr_year 4/8/2013     08         04          2013 4/9/2013     09         04          2013 4/10/2013    10         04          2013 .... .... 4/30/2013    30         04          2013 5/1/2013     01         05          2013 5/2/2013     02         05          2013 ... ... 5/8/2013     08          05         2013 	0
15570665	12096	sql first() function	select min(id), max(id) from (   select id   from boardpost   where recipientid = 1   order by id desc   limit 0,5 ) t 	0.190891540443039
15572283	26354	return the count of rows grouped by week mysql	select count(*) as tweets,        str_to_date(concat(yearweek(twittimeextracted), ' monday'), '%x%v %w') as `date` from twitdata  group by yearweek(twittimeextracted) 	0
15572581	39870	merge multiple rows into one column using carriage return line feeds	select player,   replace(stuff((select distinct ', ' + cast(score as varchar(10))        from yourtable t2        where t2.player = t1.player        for xml path('')),1,1,''), ',', char(13) + char(10)) from yourtable t1 group by player 	0
15572737	698	sql oracle sort string (numbers) and (letters with numbers)	select column  from table order by    regexp_substr(column, '^\d*') nulls first,   to_number(regexp_substr(column, '\d+')) 	0.00214294017762064
15573789	5273	organizing results using order by	select    'name' as header1,   'department' as header2  union all  select    suq_query.name,   suq_query.department from (   select tb1.name,      tb2.department    from tb1 left outer join tb2 on tb1.myindex = tb2.myindex    order by name asc, department asc ) as suq_query into outfile 'file.txt'  fields terminated by '|'  optionally enclosed by '' lines terminated by '\n'; 	0.554727284537619
15575061	4345	how to strip time from datetime column	select dtvisit1, dtvisit2 from visit where convert(nvarchar(20), [dtvisit1], 101)  = convert(nvarchar(20), [dtvisit2], 101) 	0.000460363107292608
15576347	18684	sql order by behavior for other columns?	select col1, col2 from yourtable order by col2, col1 	0.0930153341265681
15576747	24112	mysql how to limit first "order by" results	select id, case, value  from tbl1  where case is not null limit 20 union select id, case, value  from tbl1  where case is null order by case desc limit 100 	0.0160848217316532
15577315	6048	get top 1 from union subquery	select top 1 tablename from (    select createdate, 'table1' as tablename from table1    union   select createdate, 'table2' as tablename from table2 ) q order by createdate 	0.00511271359537317
15579549	21429	mysql nested selected with multiple columns	select p1.id, p1.title, p1.content,     group_concat( p2.id) as 'p ids',     group_concat( p2.title) as 'p titles' from posts as p1 join tagsmap as tm1 on tm1.p_id = p1.id join tagsmap as tm2 on tm2.t_id = tm1.t_id and tm1.p_id <> tm2.p_id join posts as p2 on p2.id = tm2.p_id where p2.id <> p1.id group by p1.id order by p1.id desc limit 5; 	0.0890475867465277
15582407	2327	blank value for attribute value	select a, b from t1 where (a is null or a=x) and (b is null or b=y); 	0.000562655049071838
15583027	12359	get query count in sql	select top 100 *, count(1) over() as 'total_count' from   table1 t1 inner join table2 t2 on t1.id = t2.id where  t1......... 	0.0685656931457308
15585797	36260	how to set multiple column not equal to zero in where condition	select `id`, `user_name`, ... from `ratings`  where 0 not in (`adventure`, `beach`, `culture`, `festival`, ...) 	0.0221997640354468
15586144	23335	sqllite query on distinct or certain value	select * from table where id in ( select max(id)   from table   group by chainid   where chainid != 'none'   union   select id   from table   where chainid = 'none' ) 	0.00242061230853341
15586218	32722	table value type in sql server 2008	select * from  sys.table_types 	0.0852098350154333
15588658	13398	pearson correlation from multiple rows	select    (abs(corr1) + abs(corr2) + abs(corr3))/3 as avg_corr from (   select      corr(a.col1, b.col1) as corr1,     corr(a.col2, b.col2) as corr2,     corr(a.col3, b.col3) as corr3   from table1 a, table2 b   where a.id = b.id ) 	0.0252877633610788
15590233	34042	populating a single-dimensional array with multiple mysql column values	select count(*) from appearances inner join players on player_id where name='joe schmoe' 	0.00953812411168083
15590353	33906	selecting an id with inner join	select photos.photo_id from photos inner join loves on loves.photo_id = photos.photo_id  where loves.nick = y and photos.nick = x order by photos.photo_id desc limit 100 	0.120907850993568
15595850	40552	how to get the root ancestors in a hierarchy query using oracle-10g?	select    t1.cid,   connect_by_root(t1.pid) as root from    your_table t1   left join your_table t2     on t2.cid = t1.pid where t1.cid in (4, 8) start with t2.cid is null connect by t1.pid = prior t1.cid 	0.0102924994796381
15596153	29525	order by after limiting number of rows in mysql	select package,distance from new_travel order by distance asc limit 1,2 	0.00143413163594454
15596339	2551	returning grouped data with extra row for each group in sql server	select componame,tracktitle from ( select componame,tracktitle,componame as h,1 as sort from composition union  select componame,componame,min(componame),0 as sort from composition group by componame ) a order by h,sort,componame,tracktitle 	0.000224417537670107
15597304	22856	two foreign keys in parent table reference same child table. how to structure inner join?	select  a.pk_fight_num,         b.fighter_name firstfighter,          c.fighter_name secondfighter  from    matches a         inner join fighters b              on a.fk_fighter_id1 = b.pk_fighter_id         inner join fighters c              on a.fk_fighter_id2 = c.pk_fighter_id; 	0
15601707	9272	efficient way of filling up the table with million empty rows	select top (1000000) n = convert(int, row_number() over (order by s1.[object_id])) into yourtable from sys.all_objects as s1 cross join sys.all_objects as s2 option (maxdop 1); create unique clustered index n on yourtable(n) ; 	0.00372832834030494
15603367	28113	put together two counters with different conditions	select a.id, a.name, count(*),        sum(case when retweet = true then 1 else 0 end) as retweets from authors as a inner join tweets as t  on t.fromuser_id = a.id group by a.id, a.name order by count(*) 	0.00772760067369539
15604484	23762	select the row having the maximum value of a certain column	select * from table1 where name=mark order by str_to_date(date_registered,'%d/%m/%y') desc limit 1 	0
15605306	23850	stuck on a slightly tricky query, trying to ignore multiple results based on a single field	select distinct idnumber from testtable where idnumber not in      (select idnumber from testtable where timespent <> 0 or completed <> 'no') 	0.0220728862213117
15608738	38817	getting the sum of previous column elements in the next column in the table	select sum(expense) as totalexpense from mytable 	0
15610393	21160	how to use mysql value from previous select	select id, sendernumber, textdecoded, (select distinct a.username, a.prospectcellphone, b.cellphone, a.websiteurl from prospects a  inner join user b on a.username = b.username where a.prospectcellphone = inbox.sendernumber ) as numsite from inbox  where processed = 'false' 	0.00112282438191701
15610551	37277	find double records	select tradeno, orderno from tradefile  group by tradeno, orderno having count(*) > 1 	0.0132417343196211
15611409	1970	sql query to show only completed grouped by results	select * from yourtable where resultref = 'a' and userref not in   (select distinct userref from yourtable    where resultref != 'a') 	0.0055298606034072
15612081	12200	how to get min date of every month for six months?	select process_date, seq_no   from (select process_date, seq_no,                 row_number() over (partition by trunc(process_date, 'mm') order by process_date) rn           from yourtab          where process_date < trunc(sysdate, 'mm'))  where rn = 1; 	0
15612953	1614	convert values to top 10 scale	select   nr, rpo, rsp, rsv,   case when @row>1 then @row:=@row-1 else 1 end rsvoutput from   yourtable, (select @row:=11) rows order by   rsv desc 	0.0005130956145924
15614751	17475	if statement in select (oracle)	select (case when issue_division = issue_division_2 then 1 else 0 end) as issues   from  (      select 'carat issue open' issue_comment, ...., ...,            substr(gcrs.stream_name,1,case when instr(gcrs.stream_name,' (')=0 then 100 else  instr(gcrs.stream_name,' (')-1 end) issue_division,           case when gcrs.stream_name like 'non-gt%' then 'non-gt' else gcrs.stream_name end as issue_division_2      from ....     where upper(issue_status) like '%open%'  )  where...  	0.567384291282984
15615480	14083	mysql chat table, join user names?	select    `messages`.*,    concat(u.`firstname`, " ", u.`lastname`) as `namefrom`,   concat(u2.`firstname`, " ", u2.`lastname`) as `nameto` from `messages`        inner join       `users` u on `messages`.`from` = u.`id`   inner join       `users` u2 on `messages`.`to` = u2.`id` 	0.00611615796906205
15616511	9694	mysql - select distinct mutually exclusive (based on another column's value) rows	select domain from   test_table group by domain having sum(case when status = 'complete'                 then 0 else 1 end) = 0 	0
15616975	5081	get information from another table with join	select ca.id_imdb as imdb_id , caat.id_collection as collection_id , ca.data_name as actors_name from collection_actors as ca inner join collection_actors_assignedto as caat on ca.id_imdb = caat.id_collection where caat.id_collection = 'tt1104001' 	0.000215415145717954
15617511	32485	calculating number of times a game was played	select maf_game.name as daname , count(maf_game_attempts.id) as danum from maf_game,maf_game_attempts where maf_game_attempts.gid=maf_game.id and maf_game_attempts.status='over'; 	0.000521717941288787
15618909	22019	order sql results using a count() value from another table	select  id, username, status, coalesce(numofphotos,0) as numofphotos,coalesce(numofvideos,0) as numofvideos  from dbo.users u  left join (select [user], count(*) as numofphotos from dbo.photos group by [user]) ph on ph.[user] = u.id left join (select [user], count(*) as numofvideos from dbo.videos group by [user]) vd on vd.[user] = u.id order by status asc, numofphotos asc, numofvideos desc 	0.000183864314431709
15621285	2649	order query on count and fetch name by id in other table	select  count(*) as count, f.title,  fruit_id  from fruits_chosen fc inner join fruits f on f.id = fc.fruit_id group by  fc.fruit_id, f.title order by count desc  limit 5 	0
15622061	40226	how do you handle a child with two parent options	select a.name as activityname, c.name as parentname, c.id as parentid from category c join activity a on c.id = a.categoryid where a.parentactivityid is null union  select a.name as activityname, c.name as parentname, c.id as parentid from activity c join activity a on c.id = a.parentactivityid 	0.00178796723708846
15622377	25047	two sorted subqueries into one result	select 1 setnumber, e.id,e.title,e.locationid,p.locationid,e.departmentid,   p.departmentid,e.datecreated,e.isactive,e.ishotjob,e.requisitionid,   e.requisitionidstring,e.rewardsettingid,e.employmentopportunitystatusid from employmentopportunities e, profiles p where e.employmentopportunitystatusid = 9 and e.isactive = 1    and e.ishotjob = 1 p.id = 'c5f07ebb-ce81-4133-a462-241a5f84d418'    and (p.departmentid != e.departmentid and p.locationid != e.locationid) union all select 2, e.id,e.title,e.locationid,p.locationid,e.departmentid,p.departmentid,   e.datecreated,e.isactive,e.ishotjob,e.requisitionid,e.requisitionidstring,   e.rewardsettingid,e.employmentopportunitystatusid from employmentopportunities e, profiles p where e.employmentopportunitystatusid = 9 and e.isactive = 1    and e.ishotjob = 0 and p.id = 'c5f07ebb-ce81-4133-a462-241a5f84d418'    and (p.departmentid = e.departmentid or p.locationid = e.locationid) order by setnumber, datecreated desc 	0.000552209307618565
15622876	28744	mysql query returning column when should be value	select `id`,`name` from `users` as u where `id` not in (    select `user_id`    from `purchases` as p    inner join `books` b on b.id = p.book_id and b.title like '%money%') 	0.73036099592889
15623494	23858	convert decimal value to top 10	select min(timer.t3m) as mint3m, max(timer.t3m) as maxt3m,   min(timer.t1g) as mint1g, max(timer.t1g) as maxt1g   from round inner join timer on round.id = timer.round_id   where round.round_date = '2013-03-22'      and round.gameform = 'v65'     and round.gameform_info = 'v65-1'     and round.gameform not like "ospec"; 	0.000336930369954449
15625477	9546	count from two tables and sort it out by the number of exist sql	select tabel1.nr, count(tabel2.opp) from tabel1 join tabel2 on tabel2.opp = tabel1.opp group by tabel1.nr having count(tabel2.opp) > 3 order by tabel2.opp 	0
15628345	18907	how to query oracle dates properly?	select * from mytable where datecolumn = to_date('2013-12-01', 'yyyy-mm-dd') 	0.697690805835155
15629024	23722	obtaining a sum of values for each unique key in mysql query	select key, sum(value) as sum from table group by key 	0
15629550	3055	difference between sql statements and clause	select foo from bar join quux where x = y; 	0.330543033239941
15630574	5606	using distinct and case for two separate columns	select count(case when yearfilingdate = 2008 then 1 end) as '2008' from  (         select year(filingdate) as yearfilingdate, docketnumber   from dbo.test55   group by year(filingdate), docketnumber   ) x 	0.00764919213189683
15630791	28387	split function error - the statement terminated. the maximum recursion 100 has been exhausted before statement completion	select * from [dbo].[function_split] ( @p1 , @p2 ) option ( maxrecursion 30000 ); 	0.526548123396101
15630959	10874	how to concatenate string in sql	select  case when coalesce(b.totalcoupons, 0) > 3 then '(important) '             when ishighpriority = 1 then '(high priority) '             else ''         end + a.name as companyname from    company a         left join         (             select  name, count(*) totalcoupons             from    company             group   by name         ) b on a.name = b.name 	0.0127475628333817
15631176	14768	selecting the right data for a user	select     u.id,     u.username,     u.eid,      t.task_tom from      users u   inner join     (       select u_id, max(t_id) as t_id       from tasks       group by u_id    ) tmax   on tmax.u_id = u.id   inner join tasks t on t.t_id = tmax.t_id where u.id <> '5' 	0.0125523419122359
15631372	502	serial no based on column info required in sql	select t1.*, sno = count(*)   from table1 t1   join table1 t2     on t1.orderid = t2.orderid    and t1.design >= t2.design  group by t1.orderid, t1.design, t1.qty  order by t1.orderid, t1.design 	9.62865554352338e-05
15632649	22875	conversion of not exists to another query that uses join	select name, trans from skyplan_deploy.deploy_stars d left join (         select distinct c.star_ident, c.fix_ident         from corept.std_star_leg c         inner join (             select star_ident, transition_ident, max(sequence_num) seq, route_type             from corept.std_star_leg             where data_supplier = 'j' and airport_ident = 'kopf'             group by star_ident, transition_ident             ) b             on c.sequence_num = b.seq and c.star_ident = b.star_ident and c.transition_ident = b.transition_ident         where c.data_supplier = 'j' and c.airport_ident = 'kopf'  )tbl on d.name = tbl.star_ident and d.trans = tbl.fix_ident where tbl.star_ident is null 	0.353208059713403
15633835	13620	sql join two table together where value is between two rows and you get first row	select fg.* from lsf sf, lfg fg where sf.lid = fg.id and sf.fv = (select max(fv) from lsf where fv<=3) 	0
15634936	36882	repeat rows based on multiplication of field value	select * from  [publishedreporting].[dbo].[sheet1$]   union all select * from  [publishedreporting].[dbo].[sheet1$]   union all select * from  [publishedreporting].[dbo].[sheet1$] order by 1; 	0
15635953	35203	mysql query data and combine, group and order results	select   t1.* from   yourtable t1 left join yourtable t2   on t1.parent_id = t2.id order by   coalesce(t2.sort_order, t1.sort_order),   t1.parent_id is not null,   sort_order 	0.0889539308728197
15636325	33226	sql for filtering	select similar.book_id,         sum(ub_rank.rank) total_rank,         sum(ub_rank.rank*similar.rate) wtd_rate from ub_rank join ub similar on ub_rank.user_id = similar.user_id  left join ub target on target.user_id = 1 and target.book_id = similar.book_id and target.rate= similar.rate  where target.book_id is null group by similar.book_id order by wtd_rate desc, total_rank desc 	0.392936125127293
15639660	37705	how to know where data comes from in a union mysql query	select *  from  (      select *, 'usera' as comesfrom from usera      union all     select *, 'userb'              from userb      union all     select *, 'userc'              from userc ) as friendresult  order by create_date desc  limit 0 , 15 	0.108359386652375
15639936	16483	how to get the number of identical rows?	select name, count(*) as age from table group by age; 	0
15641362	2703	selecting data from two different tables	select idr, count(*) from recipingr group by idr 	0
15642597	25359	postgresql update column based on multiple conditions	select     c1, c2, c3, c4,         (coalesce(c1, '') = 'y')::integer         + (coalesce(c2, '') = 'y')::integer         + (coalesce(c3, '') = 'y')::integer         + (coalesce(c4, '') = 'y')::integer     total_y,         (c1 is null)::integer         + (c2 is null)::integer         + (c3 is null)::integer         + (c4 is null)::integer     total_null from t 	0.0024544002188704
15643770	2793	how to use lead() and lag() on varchar2 fields?	select  seqno,          set_a,          lag_val,          lead_val     , case      when (lag_val ) is null then '('     when (lead_val ) is null then ')'     when (lag_val = set_a) then 'and'         else  'or'     end  as menu_entry from ( select seqno,          set_a,          lag(set_a,1) over (order by seqno) as lag_val,         lead(set_a,1) over (order by seqno) as lead_val         from menu_items) order by seqno 	0.250666313316758
15644224	5140	mysql retrieve no of users a user has of user resultset	select users.id, users.name, users.email, users.joiningamount,  (select count(*) from users as children where children.parent_id = users.id ) as children_count  from users where users.parent_id = 3 	0
15645569	3915	select all users related to company	select department.manager as user_id, company.id from company join department on department.company=company.id union select company.owner as user_id, company.id from company 	0.00012841298381047
15645654	27459	how do you convert a varchar2 into a number with two decimal places?	select to_char(to_number(yourcol)/100.0, '9999999d99') yourcolformatted from yourtable 	0
15647637	15140	how to get the sum of data from a table without making multiple queries?	select    *,    count(name) as actioncount,   sum(mileage) as totalmileage  from plays  group by name order by actioncount desc limit 0, 50 	0
15648277	2100	multiple mysql queries with different result names	select     * from     artwork where      id != 37 and     name != '' order by      rand() limit 2 	0.00515611901626084
15649490	39809	getting the greater of two values in sql	select top 1 id from (         select top 1 id from order order by id desc       union all         select top 1 id from orderinprogress order by id desc     ) t     order by id desc 	0.000233777527728885
15649564	14396	select articles with different catid on joomla 2.5	select * from #__categories as category left join  #__categories as parent     on category.lft between parent.lft and parent.rgt where parent.id = 3 	0.010500760048962
15650070	18985	how to create table with data stored in columns instead of rows?	select store, sum(case when product='shirt' then quantity else 0 end) as shirts,     sum(case when product='hat' then quantity else 0 end) as hats from yourtable group by store 	9.76808540182829e-05
15650638	32161	how can i construct a query to show an auto-incremented number?	select name , state , rank() over (order by name, state) as ranking from data 	0.017464506816527
15651198	17768	mysql multi table user_id does not exist query	select u.* from user u inner join listing l using (user_id) left outer join user_billing b using (user_id) where b.user_id is null; 	0.799250415609279
15651397	23935	group by + all in ...?	select id, case when sum(trueorfalse) = count(1) then 'true'                 else 'false' end from ( select id, case  when exists (select 1 from childids where id = childid) then 1              else 0               end as trueorfalse from child ) a group by a.id 	0.170007530913951
15652542	25989	sql-ex.ru #26 selecing average from two tables	select     avg( price ) avg_price from (     (         select             pc.price         from             pc pc             join produt prod              on pc.model = prod.model         where             prod.maker = 'a'     )     union all     (         select             pc.price         from             laptop l             join produt prod              on l.model = prod.model         where             prod.maker = 'a'     ) ) q 	0.000325411068858684
15653104	30547	what is the rank of the rating in which maximum movies fell into?	select movierating, count(r.movieratingid) as rank from rating r  inner join movie m on r.movieratingid = m.rating_movieratingid group by r.movierating 	0.000300462388102299
15653521	9535	optimizing related table query	select u.id from users u inner join users_rel r     on 25 in (primary_id, secondary_id)     and (u.id = r.primary_id          or u.id=r.secondary_id) where u.id != '25'; 	0.301464459141841
15653732	5698	insert data from db to another db	select 'insert into countries (id, name) values (' + cast(countryid as varchar(50)) + ', ''' + countryname + ''')' from country 	0.000783706396496529
15656332	22810	how to give number to occurrence in sql	select  t1.id ,       t1.name         (         select  count(t2.id)         from    tablename as t2         where   t1.name = t2.name                 and t2.id <= t1.id         ) as 'visit times' from    tablename as t1; 	0.00192929316784537
15656633	34096	sql server : function sum and data from more tables	select idhrace, sum(branky) from hraci inner join ucast_zapas on ucast_zapas.id_hrace_zapas=hraci.idhrace where hraci.jmeno='smajlik' group by idhrace 	0.0516244690801291
15657664	27898	get column from 2 tables and sort by date	select event,date from table1 union select event,date from table2 order by date 	0
15657859	28225	get all related products which are not available in related product table?	select * from    product where   id not in   (select relatedproductid    from   relatedproduct    where  productid = @productid) 	0
15663361	26973	sql mulitple count query	select g.grade,         count(case mb.cat1 when g.grade then 1 end),         count(case mb.cat2 when g.grade then 1 end),         count(case mb.cat3 when g.grade then 1 end) from markbook mb cross join grades g group by g.grade 	0.472797825309285
15664301	17762	sql/linq groupby with min value and depending column	select c.couponid, c.shopid, nearest.distance from coupons c join (     select couponid, min (dbo.distancebetween (53.54613,9.98537,shoplat,shoplon)) as distance     from coupons     group by couponid    ) nearest on c.couponid = nearest.couponid           and dbo.distancebetween (53.54613,9.98537,shoplat,shoplon) = nearest.distance order by couponid, distance asc 	0.00268496220280583
15666232	13213	keep a running tally of duplicated records in mysql	select   f.rollnumber,   f.ownername,   f.ownernumber from (   select     d.rollnumber,     d.ownername,     @i := if(d.rollnumber=@last,@i+1,1) as ownernumber,     @last := d.rollnumber   from   (       select           lpad(rollnumber,6,'0') rollnumber,           ownername       from sometable       order by           rollnumber asc,           ownername asc   ) d,(       select @i:=0,@last:=0   ) v ) f; 	0.00316446117544306
15667220	3324	selecting unique records from database	select distinct number from mytable where branch=1 and number not in  ( select distinct number from mytable where branch != 1 ) 	5.06466211536894e-05
15667941	11459	group by minute and fill missing	select avg(load), min(created_at) as load  from generate_series('2013-3-20 0:00:00'::timestamp, '2013-3-30 0:00:00',                '1 minute') as minutes(minute)     left join stats on minute=date_trunc('minute', stats.created_at) group by minute 	0.0446235078925702
15672488	24988	how to run a tvf x number of times to satisfy every condition	select   t.col, t.code, f.id, f.conditionstate, f.costs from yourtable as t cross apply dbo.yourtvf(t.code) as f; 	0
15672754	20210	fetch maximum data within date range without duplicate mysql	select      pk_id,     user_id,     max(some_timestamp) from     your_table where     some_timestamp>= '13-jun-12 08:00'  and some_timestamp<= '13-jun-12 10:00' group by     user_id order by     pk_id asc 	0
15672870	21645	how to get a list that order by username if it have score in score table?	select username, score from  `score`  join  `user` on id = userid order by username asc , score desc 	0
15672875	20555	select all results where group by > 1	select a.accountnumber, a.address from accounts a left join accounts o on o.address = a.address and o.accountnumber <> a.accountnumber group by a.accountnumber, a.address having count(o.accountnumber) >= 1 	0.0183543232750206
15673934	21312	mysql: how to get data from 3 newest months in database?	select  * from    sa_cms_post where   month(createdat) between                          month(curdate()) and month(curdate() + interval 3 month) 	0
15676119	39571	how to select records where their statuses are just in a set?	select  id from    personstatus group   by id having  sum(case when statuss in (0, 1, 2) then 1 else 0 end) >= 1 and         sum(case when statuss not in (0, 1, 2) then 1 else 0 end) = 0 	0
15677350	26157	is it possible to get the sum while executing a join?	select id, p1.value as company, p2.value as budget,        sum(p2.value) over (partition by p1.value) as companybudget from  process p left join param p1 on p1.id = p.id and p1.name = 'company' left join param p2 on p2.id = p.id and p2.name = 'budget' where type = 'authorization'; 	0.275780112645716
15681367	8480	how to select data from 2 table of databace in mysql....?	select  a.*, b.* from    student_info a         inner join student_payment b             on a.student_id  = b.student_id order   by b.student_payment_date desc 	0.000175964361201723
15682842	654	nested group_concat query doesn't return all values	select      * from partners p inner join product_feeds pf on pf.partner_id = p.id inner join product_data pd on pd.feed_id = pf.id inner join product_categories pc on pc.id = pd.category_id inner join product_categories pcparent on pcparent.id = pc.parent_id and pcparent.parent_id = 1 	0.251421052322697
15684546	26661	update mysql, new data starts at unique id 1	select * from articles order by id desc; 	0
15685047	17200	tsql select from another table in the where	select      t.[tariff],      count([number]) as [number of calls] ,     sum(convert(bigint, [seconds]))/60 as [minutes],      sum([customercost]) as [customer cost],      sum([wholesalecost]) as     [wholesalecost] from [marchcalls] m inner join [tarrifs] t on m.accno=t.accno and  [tariff] in ('tariff1','tariff2', 'tariff3') group by [tariff] with rollup 	0.00117306088110522
15687139	13435	how to write a where clause that has multiple cases?	select * from table1 where     @id is null     or     (         @id is not null         and         (                   (                 exists (select * from table2 where id = @id)                 and                 table1.id in (select id from table2 where combid in (select combid from table2 where id=@id))             )              or             (                 not exists (select * from table2 where id = @id)                 and                          table1.id = @id             )         )     ) 	0.398221935107485
15687548	2881	parse number out of field and put in it's own column	select    [public number] = case when [public name] like '%(#%' then     substring([public name], charindex('(', [public name]), 255)     else '' end,   [new public name] = case when [public name] like '%(#%' then     rtrim(left([public name], charindex('(', [public name])-1))     else [public name] end,   [internal name] from dbo.table; 	0
15688119	40171	check for a date/time conflict mysql	select t.id from table t where t.start_date = '$request_start_date' and ('$end_time' > t.start_time and '$request_start_time' < addtime(t.start_time, t.duration)) and t.id <> $request_entry_id 	0.323829201110136
15689350	28529	select query with multiple sub-queries for counts	select  count(r.id) as cnt_total,         sum(case when r.action = 'notnow' then 1 else 0 end) as 'cnt_notnow',         sum(case when r.action = 'insert' then 1 else 0 end) as 'cnt_insert',         sum(case when r.action = 'update' then 1 else 0 end) as 'cnt_update',         sum(case when r.action = 'verify' then 1 else 0 end) as 'cnt_verify'         from    auto_reminders_members r where  r.reminder_id = 1        and convert(date, r.date_last_reminder) = '20130328' 	0.539359666313227
15690887	18090	need query to find all records in table1 that have multiple matches in table2	select  action.request_id,  action.action_id, action.username from [action]  inner join request on action.request_id = request.request_id where action.request_id in (   select request_id from action group by request_id    having count(request_id)>1) and request.group="my group name" 	0
15693316	36964	compare comma delimited strings in sql	select p.*  from product p cross apply(   select *   from shelfsearch ss   where patindex(char(37)+replace(ss.shelflist, ',',char(37))+char(37),p.shelflist) > 0 )shelfs 	0.0089507374033079
15694432	25176	how to find records in one table which aren't in another	select * from employees where employee_id not in ( select employee_id from job_history) / 	0
15694747	37213	mysql - two tables, compare two rows	select products.id, products.title, products.price, products_old.price from products join products_old on products.id = products_old.id where products.price <> products_old.price 	6.92197078871376e-05
15698964	14356	sql query selecting row with unique record in a table's column?	select *  from users u inner join subscription s on u.user_id = s.user_id inner join products p on p.prod_id = s.prod_id   where s.user_id in (select user_id from subscription group by user_id having count(user_id) = 1) and s.prod_id = 1 	0
15699533	20380	sql select distinct by one column and result from two tables?	select id, "code text" from (   select id, "code text", rank() over (partition by "code text" order by id) "the rank" from( select ab.id as "id", cd.code_text as "code text" from city ab, codes cd   where ab.code = cd.code)) where "the rank" = 1 	0
15699562	8357	count on sql function return value	select sum(cast(dbo.iserrormismatch(left(type, 1), left([exception code/category],2)) as int)) as mismatchcount from dbo.[all service ticket data 2012_final] 	0.0457601801516452
15700691	39336	sql query to get count of records	select  count(case result when 'pass' then 1 end) as passed,         count(case result when 'failed' then 1 end) as failed,         count(case result when 'incomplete' then 1 end) as incomplete from    mytable 	0.00116894998711193
15701472	16393	apply group by cause on as variable name	select referralname, count(id_referral) gcount from (select case (id_referral)    when 1 then 'treatment'    when 2 then 'medication'    when 3 then 'medication'    when 4 then 'diagnosis / tests'    when 5 then 'diagnosis / tests'    else 'other'   end as referralname ,   id_referral from referraldetails) tbl group by referralname 	0.609711322673378
15702769	26739	i want to get products from table1 randomly but i also want to check account company of this product is activated	select products.* from products p inner join companies c  on p.company_id = c.id and c.active = 1 order by rand() limit 6; 	0
15704210	34598	datepart some months from 2 years	select jmeno, count(ucast)   from hraci  inner join ucast_zapas on ucast_zapas.id_hrace_zapas=hraci.idhrace  inner join zapas on zapas.id_zapas=ucast_zapas.id_zapasu_ucast  inner join kategorie on kategorie.idkategorie=zapas.kategorie_zapas  where (ucast=1)    and (kategorie.idkategorie=1)    and zapas_datum >= '8/1/2013'     and zapas_datum < '9/1/2014'  group by jmeno; 	0.000121138648916998
15705160	5345	get both most recent and prior entry from database	select distinct t1.fooid, t1.barid, t1.status, t1.changedate, t3.status as formerstatus from foobarstatusupdate t1 inner join (select fooid, barid, max(changedate) as latest         from foobarstatusupdate         group by fooid, barid) as t2 on t1.fooid = t2.fooid and t1.barid = t2.barid and t1.changedate = t2.latest left join (select fooid, barid, status, max(changedate) as nextlatest         from foobarstatusupdate         group by fooid, barid, status         ) as t3 on t2.fooid = t3.fooid and t2.barid = t3.barid and datediff(day, nextlatest, t2.latest) > 0 	0
15705562	17350	sql server,use a subquery to find value in one table that is not in another	select  * from    tblblue new join    tblred old on      new.id = red.id where   new.firstnumber <> old.firstnumber 	0.000220619210843375
15706126	30386	showing the details of the student with the maximum marks in oracle 11g r2	select * from student where marks = (     select max(marks)     from student ); 	0.00313209667297417
15706559	26736	check if users match the same options	select  t1.a_id ,       t1.b_id from    yourtable t1 join    yourtable t2 on      t1.a_id = t2.b_id         and t1.b_id = t2.a_id where   t1.a_id > t2.a_id 	0.000223088424961619
15706881	13774	mysql query to get all rows from table except 2	select * from passeio where id not in  (   select * from (     select id from passeio where passeio_date > $date limit 0,1     union     select id from passeio where passeio_date < $date limit 0,1     )t ) 	0
15706952	20836	how to retrieve data using where clause from 2 different tables	select basic.f_name, basic.l_name  from basic inner join info on basic.email_id = info.email_id  where (basic.caste like '%' + @caste + '%') and (info.diet = @diet ) 	0.000104390581654095
15707819	26165	sqlite string locate	select columnname from tablename where columnname like '%string%' 	0.548684492523955
15708967	5270	compare a new value against previous value	select a.*      , round(((a.avg-b.avg)/b.avg)*100,2) pct_change   from      ( select x.*             , count(*) rank          from test x           join test y             on y.bline_id = x.bline_id            and y.id >= x.id          group             by x.id      ) a   join      ( select x.*             , count(*) rank          from test x           join test y             on y.bline_id = x.bline_id            and y.id >= x.id          group             by x.id      ) b     on b.bline_id = a.bline_id    and b.rank = a.rank+1  where a.rank = 1; 	0
15710441	18783	comparing 2 items but using a value from found item	select <fields that you want> from ((select <list of fields from domestic>, itemid as lookupitem        from domestic d       ) union all       (select <list of most fields from import>, replace(itemid, '-h', '') as lookupitem        from import i       )      ) f left join      lookup lu      on f.lookupitemid = lu.itemid 	0
15711642	33930	extract specific data from a cell, mysql	select substring_index(flavor, ' (', 1)                        as flavorname,         substring(flavor, locate('(', flavor) + 1,         ( locate('ml', flavor) + 1 ) - locate('(', flavor))     as volumne,         substring(flavor, locate(', ', flavor) + 2,         locate(' nic)', flavor) - ( locate(', ', flavor) + 2 )) as dose  from   flavors 	6.30432071296191e-05
15711660	3298	count value only grabbing 1 for each row	select t1.*, sum( if(t1.hole1 = t2.hole1_par-1,1,0) +         if(t1.hole2 = t2.hole2_par-1,1,0) +         if(t1.hole3 = t2.hole3_par-1,1,0) +         if(t1.hole4 = t2.hole4_par-1,1,0) +         if(t1.hole18 = t2.hole18_par-1,1,0) ) as birdies from scorecards t1 left join courses t2 on t1.course_id=t2.course_id group by t1.player_id order by birdies desc 	0
15712836	26653	move duplicated values into unique columns	select * from  (table1     pivot (max("phone number") for "phone number id"   in ('1' as "phone number 1",       '2' as "phone number 2",       '3' as "phone number 3",       '4' as "phone number 4",       '5' as "phone number 5",       '6' as "phone number 6"))  ) 	0
15715333	27821	how to detect if subquery returned any rows in mysql, and if not, use a placeholder for the result of the subquery?	select * from table as t1 left join  table as t2  on t1.target = t2.target and t2.phase="b" where t2.target is null or  or t1.date < t2.date 	0.0666445786854664
15717792	35786	mysql: count with multible group by	select year(date), sum(rain), count(distinct date(date)) days from $tablename where rain>0 group by year(date) 	0.341033405596952
15718694	7169	cast varchar to float to bigint	select cast(cast(@vardata as numeric(27,9)) * 100  as bigint) 	0.369740449485622
15720188	23326	select top 50 rows from a table, but display oldest to newest?	select *, date_format(timepost,'%h:%i:%s') as timepost from (select * from shoutbox order by id desc limit 50) as foo order by id asc 	0
15723709	3191	selecting with multiple where range conditions on same column	select a.item_id, a.item_name from a left join b on a.item_id = b.item_id where (b.option_id=34 and b.option_value between 1000 and 2000)       or (b.option_id=12 and b.option_value between 0 and 4000) group by a.item_id having count(a.item_id) >= 2 	0.00012047565996445
15724804	36893	sql server 2000 grouping scenario, every 3 hours	select t1.date, t2.time, avg(t2.temperature) as avgtemp from (select t.*,              (select count(*) from t t2 where t2.date < t.date or t2.date = t.date and t2.time <= t.time              ) as seqnum       from t      ) t1 left outer join      (select t.*,              (select count(*) from t t2 where t2.date < t.date or t2.date = t.date and t2.time <= t.time              ) as seqnum       from t      ) t2      on t.seqnum between t2.seqnum - 2 and t.seqnum group by t1.date, t1.time 	0.0106463252019874
15726078	32227	sql to return null rows and corresponding next rows	select col1, col2  from (   select *,     @showrow:=if(@prevcol2 is null,1,0) showrow,     @prevcol2:=col2   from yourtable     join (select @showrow:= 0, @prevcol2:= 'foo') t   ) t where showrow = 1 or col2 is null 	0
15726882	32982	mysql query returning "dialog id of specified paticipants"	select d1.dialog from dialog_user d1 join dialog_user d2 using (dialog) where d1.user = 1 and d2.user = 2 	0.0621385204599232
15727567	12172	attach query string to results	select 'searchstring' as querystring, * from table1 where column1 like '%searchstring%'; 	0.738449740322113
15728023	22890	mysql select query for getting user and follower's posts	select distinct posts.*, user_status.status_content  from posts left join      user_status       on user_status.user_id = posts.user_id left join      (select user_id, max(created_at) as maxdate       from user_status      ) usmax      on usmax.user_id = user_status.user_id and usmax.maxdate = user_status.create_at where posts.user_id = $userid or       posts.user_id in (select follower from follower where follower.user_id = $userid) order by posts.created_at desc; 	0.00776763758629668
15729256	10131	sql query percentage of occurrence	select concat(x, ':', y),        t,        count(t)/(select count(t)                    from m as m2                   where m.x = m2.x                     and m.y = m2.y) from  m group by x, y, t  order by x, y, t 	0.00743710439481263
15729738	8267	display two lists of resultsets from same table in mysql	select distinct name from mytable union all select distinct value from mytable 	0
15732161	17313	mysql query to get multiple values from 1 table based on multiple columns from other table	select   player1.pts as player1_pts,   player2.pts as player2_pts,   player3.pts as player3_pts from   teams   left join players as player1 on team.player1=player1.id   left join players as player2 on team.player2=player2.id   left join players as player3 on team.player3=player3.id where    ... 	0
15732406	27127	use distinct to retrieve only one row for a specified field	select substring(m.content,1,20) as content, m.viewed, m.sent_date, u.username  from message m inner join user u on u.userid = m.message_from where m.message_to = :userid group by u.userid 	0
15732604	27122	mysql: help querying results from three tables	select mydata.message from ( select datetime, message from table_member_comments where widgetid = 100 and active = 1 untion all select datetime, message from table_guest_comments where widgetid = 100 active = 1 ) mydata order by mydata.datetime asc 	0.121648207846018
15733944	35296	php with mysql where value range	select ... ... where nums (between ($num - 2) and ($num + 2))    and (nums <> $num) 	0.0165573386192205
15735483	35887	select where difference between now and a timestamp is less than 24 hours	select    timestampdiff(hour, yourtimestampcolumn, now() ) as hours_since,    * from     your_table  where     timestampdiff(hour, yourtimestampcolumn, now() ) < 24 	0
15735699	5736	group by a second parameter	select c.user1, c.user2, a.username as author_name, substring(m.content,1,20) as content, m.viewed, m.sent_date, m.author, c1.username as username1, c2.username as username2   from conversation c inner join message m on m.conversationid = c.conversationid inner join (select conversationid, max(sent_date) as maxsentdate from message group by conversationid) mc on m.conversationid = mc.conversationid and m.sent_date = mc.maxsentdate inner join user c1 on c1.userid = c.user1 inner join user c2 on c2.userid = c.user2 inner join user a on a.userid = m.author where (c.user1 = 33 or c.user2 = 34) group by c.conversationid order by m.sent_date desc 	0.0455207668217995
15737878	6161	mysql timestamp modification, addition, and comparison	select   q.time as original_time_check,   q.flag as flag_check,   case q.flag     when 'before' then q.nine_am_on_the_day      when 'after' then q.nine_am_the_next_day      else q.time   end as time from (     select        time,        date(time) + interval 9 hour as nine_am_on_the_day,        date(time) + interval '1 9' day_hour as nine_am_the_next_day,          case          when time < (date(time) + interval 9 hour) then 'before'          when time < (date(time) + interval 17 hour) then 'in-range'          else 'after'        end as flag     from         your_table  ) q 	0.615300165250582
15741258	17986	sql with 2 variables	select show.show_datetime from `cinema` join `theater` on `theater`.`cinema_id` = `cinema`.`cinema_id` join  `show` on  `show`.`theater_id` =  `theater`.`theater_id`  join 'movie' on `show`.`movie_id` =  `movie`.`movie_id` =  where  `cinema`.`cinema_id` = 1  and `movie`.`movie_id` = 2 	0.238969971273619
15741754	32507	mysql join across multiple tables	select u.id as user_id, u.username, ug.group_id, ug.group_name, u.firstname, u.surname, p.product_name, p.product_id, p.product_price, p.product_currency, p.is_public from user_groups ug join user_group_users ugu on ug.group_id = ugu.group_id join users u on u.id  = ugu.user_id join user_group_product ugp on ug.group_id = ugp.group_id join product p on p.product_id = ugp.product_id where u.site_id = 5 union all select u.id user_id, u.username, null group_id, null group_name, u.firstname, u.surname, p.product_name, p.product_id, p.product_price, p.product_currency, p.is_public from users cross join product p where p.is_public = 1 order by 4 desc, 6, 5, 2 	0.0968366430267301
15744831	29616	set date in create view	select ''' + cast(convert(date,sysdatetime(),110)as varchar(10)) + ''' as [import date]' 	0.0606390014185694
15745159	13082	how to get all fields from two different tables by foreign key	select * from   member m,        oddjob o where  m.memberid = o.memberid and    m.memberid = $memberid 	0
15745930	9986	how to create update from exported data?	select 'update updatetable ' +     '  set fieldtoupdate1 = ''' + sourcedata.datatoupdate1 + '''' +     '     , fieldtoupdate2 = ' + cast(sourcedata.datatoupdate2 as varchar) +     ' where updatetable.primarykeyfield1 = ' + cast(sourcedata.primarykey1 as varchar) +     '   and updatetable.primarykeyfield2 = ''' + sourcedata.primarykey2 + '''' from sourcedata 	0.0120752316934966
15746602	26563	mysql: cascade filtering by date intervals	select p.* c.* from posts p join      comments c      on p.post_id = posts.post_id join      (select post_id, max(postdate) as postdate       from comments       group by post_id      ) cmax      on cmax.post_id = p.post_id where (case when timestampdiff(minute, now(), cmax.timestamp) <= 60             then timestampdiff(minute, now(), c.timestamp) <= 60             when  timestampdiff(minute, now(), cmax.timestamp) <= 60*24             then timestampdiff(minute, now(), c.timestamp) <= 60*24             . . .       ) 	0.0468594291742824
15746749	23615	mysql calculate percentage	select group_name, employees, surveys, count( surveys ) as test1,          concat(round(( surveys/employees * 100 ),2),'%') as percentage     from a_test     group by employees 	0.0168211942590855
15747045	29580	stored procedure to grab most recent database entry with one parameter?	select top 1 * from dbo.document  where description = @yourparameter order by createddate desc 	0
15747511	10076	how to contruct most efficient mysql query	select customers.name,        messages.*   from customers   left join messages          on messages.customer_id = customers.id  where customers.id = 123 	0.181768393651099
15747918	19821	sql - selecting from two separate datasets and associating with the same user? multiple select/from statements in one query?	select users, tickets.time_spent,         (select count(tickets.id) from tickets          where tickets.assigned_to = users.id) as totaltickets from tickets left outer join ticket_work on ticket_work.ticket_id = tickets.id  join users where tickets.assigned_to = users.id 	0
15747967	27950	mysql count distinct customers from orders by period	select date_format(`date`,'%m/%y') as period,   count(distinct customer) as total from orders where year(`date`) = 2012 group by period 	0
15748290	28362	how to get count of distinct subitems per item?	select type, dept, count(*) as total from table1 where (((date) between #3/1/2013# and #3/5/2013#)) and (((user)="team1")) group by type, dept 	0
15748336	29992	two order by clauses and a limit	select * from (    select id, names    from items     order by ratings desc    limit 10    ) t order by names 	0.0879201669044629
15749105	16817	sql combine 2 tables	select a.monthyear,         a.startbalance,         a.endbalance,         sum(b.intransaction)  from   table a         join table b           on b.col = a.col              and b.transactiondate between @datestart and @dateend  group  by a.monthyear,            a.startbalance,            a.endbalance 	0.0138790338731704
15751756	27937	select last 20 latest unique urls from table mysql	select * from test inner join   (select url, max(mytime) maxtime    from test    where url not like '%/index%'     and userid = '555'    group by url) n on test.url = n.url and n.maxtime = test.mytime order by maxtime desc limit 20 	0
15753755	22276	mysql: trim number to be between x and y min/max	select greatest(least(number, 100), 1); 	0.0055513996105621
15755521	37595	mysql query for specific year and category	select year(o.orderdate) as year,        c.categoryname,        sum(o.netamount) as totsales from orders o inner join orderlines ol on ol.orderid = o.orderid inner join products p on p.prodid = ol.prodid inner join categories c on c.category = p.category where c.categoryname like 'a%' group by c.categoryname, year(o.orderdate); 	0.00118517014358648
15756664	37069	how to find out the difference of time in seconds,hours,day format from current time and timestamp in mysql	select timestampdiff (second, curdate(), your_timestamp_field) from your_table; 	0
15757207	24663	data present in rows to columns	select appno,   max(if(code = 1, location, null)) location,   max(if(code = 1, department, null)) department,   1 code1,   max(if(code = 2, location, null)) location,   max(if(code = 2, department, null)) department,   2 code2,   max(if(code = 3, location, null)) location,   max(if(code = 3, department, null)) department,   3 code3,   max(if(code = 4, location, null)) location,   max(if(code = 4, department, null)) department,   4 code4,   max(if(code = 5, location, null)) location,   max(if(code = 5, department, null)) department,   5 code5 from <table name> group by appno 	0.000271893016330733
15758273	1333	getting report with one mysql query	select      a.username,    a.mailid,     time_to_sec(timediff(b.statusdatetime, a.statusdatetime)) as diff from     tbl a  inner join    tbl b  on     a.mailid = b.mailid and     a.status = 'pull' and    b.status = 'mailsent' group by     username,     mailid 	0.128720203262589
15758981	28166	how to count total no of database in sql server	select  * from sys.databases or select  count(*) from sys.databases 	0.000766931436315123
15760564	661	t-sql/ssrs - displaying value when no rows can are available to count	select     *  from     (         select 0 as [hour]         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         union select 10         union select 11         union select 12         union select 13         union select 14         union select 15         union select 16         union select 17         union select 18         union select 19         union select 20         union select 21         union select 22         union select 23     ) dimhour     left join (     ) facts on dimhour.[hour] = facts.[hour] 	6.94265448929158e-05
15760760	27172	mysql merge rows	select country, group_concat(id separator ',') as ids  from my_table  group by country 	0.00932699263932896
15762005	9128	use distinct keyword with two tables	select distinct locationofwork, locationofposting from cand_details, locationofposting 	0.172045036443989
15763504	2317	mysql total working hours	select  id,   title,   time_format(sec_to_time(sum(time_to_sec(timediff( end, start)))), "%h:%i") as diff from   tbl1 group by    title 	0.0081331052989059
15764086	35271	conditional sql join using a 3rd table	select ... from tblequipment e left join vwcategorytree c on e.equipmenttypeid = c.equipmenttypeid join tblactionsrequired r    on (e.equipmentid = r.equipmentid or        e.equipmenttypeid = r.equipmenttypeid or        c.parentcategoryid = r.equipmentcategoryid) 	0.552061013152646
15764901	32435	mysql group by, order by, count, having min() combination	select t.* from (     select name, postcode, street, min(date_exported) as mindate, count(*) as cnt      from fulf.third_party      where client_id = '1'          and (result_code >= '0'          and result_code < '1000' and result_code != '400')       group by name, postcode, street      having cnt > 1   ) tm inner join fulf.third_party t on tm.name = t.name     and tm.postcode = t.postcode      and tm.street = t.street     and tm.mindate = t.date_exported 	0.137651453387139
15766871	21553	length of a text list in mysql (basic string manipulation)	select count(field1) + sum(char_length(field1) - char_length(replace(field1,',',''))) from table1; 	0.114350180385128
15767448	15428	how to inner join two select queries on same table	select      engineload.datetime from     (     select         d.datakey,        de.datetime             from          data d         inner join datatypename dt on data.datatypenamekey = dt.datatypenamekey             inner join dataevent de on de.dataeventkey = d.dataeventkey       where          d.value > 10 and         dt.datatypename = "engine load [%]"     ) engineload     inner join     (     select         d.datakey,        de.datetime             from          data d         inner join datatypename dt on data.datatypenamekey = dt.datatypenamekey             inner join dataevent de on de.dataeventkey = d.dataeventkey       where          d.value > 0  and         dt.datatypename = "vehicle speed [mph]"      ) vehiclespeed          on engineload.datakey = vehiclespeed.datakey <==might need to remove this line            and engineload.datetime = vehiclespeed.datetime 	0.00543259048070204
15767709	36112	rounded decimal truncating small values - rounding up	select round(ceiling(0.004 * 100)/100,2) 	0.288976303793277
15768091	30937	how possible is it to perform date ranges with date values of string data type?	select (left(claimsdate,2)  + '/' + substring(claimsdate,3,2) + '/' + case when cast(right(claimsdate,2) as int) >= 70 then '19' else '20' end + right(claimsdate,2)) claimsdate from tbltable  where  cast(((case when cast(right(claimsdate,2) as int) >= 70 then '19' else '20' end + right(claimsdate,2) + '-' + left(claimsdate,2)  + '-' + substring(claimsdate,3,2))) as datetime) between @fromdate and @enddate 	0.000271269480778384
15769470	7513	find the latest date of two tables with matching primary keys	select * into #temp from ( select      customerkey     , datecontacted from customerservice cs union select      customerkey     , datecontacted from customeroutreach cs ) select     customerkey     , max(datecontacted) from #temp group by     customerkey 	0
15770725	15345	retrieve item which is sold more than twice	select i.item_id from sale_detail sd     inner join item i on sd.items_id = i.item_id     inner join sale s on sd.sale_id = s.sale_id group by i.item_id having count(s.sale_id) > 2 	6.45721903926406e-05
15771366	38752	show complete row where one column is duplicate	select column0, column2, table.column1, columncount from table      inner join (select column1, count(column1) columncount                 from table                 where column1> 0                 group by column1 having count(column1) > 1) t2 on table.column1 = t2.column1 	0.000369101211870816
15771504	25419	two sql statements, ignore the return of the first if it has no results?	select * from table1 where ... union all select * from table2 where ... and not exists (select 1 from table1 where ... ) 	0
15772483	35358	join mysql tables based on condition?	select a.firstname, a.lastname, a.gender, a.address_id, b.address_firstline,  b_address_secondline, b.postcode, c.car_manufacturer, c.car_model  from a  inner join b on b.id = a.address_id  left outer join c on c.id = a.car_id and a.car_id > 0  where a.id = 1 	0.0105497320524681
15773466	18906	select by order	select * from image where card_id_fk=? limit 0,1 	0.229712567206982
15774918	23715	display data from database to specific users (using roles?)	select documents.* from documents      inner join doc_users on documents.number= doc_users.doc where doc_users.user = ? union select documents.* from documents      inner join doc_groups on documents.number= doc_group.doc      inner join user_groups on user_groups.group = doc_groups.group where user_groups.user = ? 	0
15778525	33967	getting %'s of the most used row values	select id, country, num, num*100/total pct from (select id,country, count(*) as num       from track group by country       order by num desc limit 5) x join (select count(*) total from track) y 	0.000219256185143608
15781452	16679	postgres: is it possible to show only one entry when duplicate occurs?	select t1.* from tablename as t1 inner join (   select name, max(created_on) as maxdate   from tablename    group by name ) as t2  on t1.name       = t2.name         and t1.created_on = t2.maxdate; 	0
15782941	17083	sum in another table plus interval of time	select threads.id, count(ratings.id) as total_likes from threads left join ratings on ratings.thread_id = threads.id where threads.date >= date_sub(current_date, interval 7 day) group by threads.id order by total_likes; 	0.000188100150247551
15783977	13506	sql request (unique route)	select a.townname, b.townname othertown   from town a   join town b on a.townname < b.townname 	0.244539288781284
15784282	12792	select distinct with count	select count(distinct p.patientid) as tablelength from patientdemographics as p left join patientclinicalinformation as pc on p.patientid = pc.patientid where pc.patientid is null and p.firstname like '%' + @input + '%'       or       pc.patientid is null and p.surname like '%' + @input + '%'       or       p.firstname like '%' + @input + '%' and pc.currentclinicalinfo = 'false'       or       p.surname like '%' + @input + '%' and pc.currentclinicalinfo = 'false' 	0.0937519494030091
15785393	19765	greater than a certain number sql	select count(*) from accountstable at where at.date > (select dateadd(day, -90,date) from currentdatetable) 	0.00016693884951711
15785844	21764	load data infile when fields real escaped fields contain \n and \"	select 'sms id', 'mobile number', 'sms text'  union      select id, ifnull(mobilenumber, 'not available'), text      from sms into outfile '/tmp/smsusage.csv'  fields termintated by ','  optionally enclosed by '"'  escaped by '"'  lines terminated by '\n'; 	0.254637646581689
15786190	25267	retrieve items matching tags, and simultaneously retrieve all tags that go along with each item	select project.*, group_concat( distinct tagname order by tagname separator ' ' ) as tags from (select projectid, count( distinct tagname ) as tagcount         from tag         inner join project_tag using (tagid)         where tagname in ( 'the', 'tags' )         group by projectid         having tagcount = 2) sub1 inner join project on sub1.projectid = project.projectid inner join project_tag using (projectid) inner join tag using (tagid) group by projectid 	0
15787634	32393	how to get the day from a datetime	select agroup, max(datetime) from mytable where to_char(datetime,'ss') <'15' group by to_char(datetime,'yyyy-mm-dd'), agroup order by agroup 	0
15789950	27819	get the last update time for each employee using oracle query	select employee_name, employee_status, update_time   from (     select employee_name, employee_status, update_time,            rank() over (partition by employee_name order by update_time desc) as rank     from employee ) where rank = 1 	0
15790054	6179	sql replace date values if date is a holiday or weekend	select distinct ecb.currency + '-' + cast(m.cutoffdate as varchar(30)) as combocurrdate,                 ecb.rate as ecbrate from (select m.*,              (select     top     1     ecb.date               from ecb                where ecb.currency = m.invoicecurrency and ecb.date <= m.cutoffdate                order by ecb.date desc              ) as ecbdatetouse       from mytable      ) m left outer join      ecb       on ecb.date = m.ecbdatetouse and         ecb.currency = m.invoicecurrency where (m.invoicecurrency not like 'eur%') 	0.0158001121581371
15791041	36642	what is the t-sql to see if a table has page locking enabled?	select allow_page_locks from sys.indexes where object_id = object_id('tablename') and type in (0,1) 	0.0740422576971174
15791195	22318	oracle - select rows with minimal value in a subset	select a.dateid, a.personid, a.date, a.max_date, a.starttime   from (select t.*,                 max(t.date) over (partition by t.personid) max_date,                row_number() over (partition by t.personid                                    order by t.date, t.starttime) rn           from table t) a  where a.rn = 1; 	0.000788263756075899
15792627	36055	wrong date from mysql in order by	select distinct column from tab where column1 = date_format(curdate(),'%d.%m.%y') and brukernavn is not null order by brukernavn; 	0.210134113992547
15792936	13520	mysql -> joinin two rows in output	select country, type, max(a), max(b), max(c), max(d), ctype from whatever_table group by country, type, ctype 	0.0163127929499365
15793038	9297	tsql: change the select result column order dynamically	select [city], [state], [country] from (fixedquery) as x 	0.0229450662848268
15793432	12671	query multiple tables including rows with null foreign keys mysql	select category.id_product, manufacturer.name, supplier.name, p.id_product from product left join category c on c.id_category = p.id_category left join manufacturer m on m.id_manufacturer = p.id_manufacturer  left join supplier s on s.id_supplier = p.id_supplier; 	0.000428495483580142
15794172	34021	how to convert xml generated from path option to a table	select  x.value('(cnt)[1]', 'int') as cnt,     x.value('(ch)[1]', 'nvarchar(10)') as ch,     x.value('(unicode_value[1])', 'int') as unicode_value from @txml.nodes('/row') as tbl( x ) 	0.00585913427435775
15794213	25348	how to select 1 row in mysql master table based on 2 conditions existing in a detailed table	select a.id, name from table_a as a left join table_b as b on b.ref = a.id where b.id in (10,15) group by a.id having count(distinct b.id) = 2 	0
15794996	4763	sql server query on joining two tables correctly	select * from claims as c where exists (     select * from edits as e1     where c.claimid = e1.claimid      and e1.ruleid=205) and not exists (     select * from edits as e2     where c.claimid = e2.claimid     and e2.ruleid=913) 	0.335633158789115
15795489	12830	how to modify my code to set sum/avg to negative if any one value is negative	select  ur.domain ,       case          when min(ur.datausageinbytes) < 0 then -99         else sum(ur.datausageinbytes)          end as sumdatausageinbytes ,       case          when min(ur.datausageinbytes) < 0 then -99         else avg(ur.datausageinbytes)          end as avgdiskusageinbytes from    usageresults ur where   ur.year = @year and ur.month = @month group by          ur.domain 	0.00263064146023013
15795771	27412	how to combine sys.dm_exec_query_stats and sys.dm_tran_locks to combine the result	select         object_name(sl.resource_associated_entity_id) as 'tablename' ,         dr.command, dest.text ,         sl.*     from         sys.dm_tran_locks as sl             left join             sys.dm_exec_requests dr             on             sl.request_session_id=dr.session_id             cross apply sys.dm_exec_sql_text(dr.sql_handle) as dest     where         sl.resource_type = 'object' 	0.00578876290996907
15796867	32685	find out "ranking" of a value in sql database	select count(*)+1 as rank from scores where value > $myscore 	0.00131471194014943
15797159	22667	doing date range in mysql	select * from financials where date >= now() - interval 30 day 	0.0363241418695274
15798207	1234	how can i see the sql sent to the database after the parameters have replaced their placeholders?	select * from customers where customerid = ? 	0.000180513932358932
15798910	20469	oracle divisor is equal to zero	select thedate, (case when denom <> 0 then round(100*num/denom) end) from (select thedate,              sum( case when trunc(activity_end_date) <= thedate                             and trunc(activity_end_date) >= add_months( trunc(thedate,'mm'), -12)                              and trunc(activity_end_date) <= trunc(activity_need_date)                              and sysdate  >=  trunc(thedate,'mm') then 1 else 0                   end )   as num,              sum( case when trunc(activity_end_date) <= thedate                          and trunc(activity_end_date) >= add_months( trunc(thedate,'mm'), -12)                          and sysdate  >=  trunc(thedate,'mm') then 1 else 0 end ) ) as otr12          from test cross join              (  select add_months(last_day(sysdate), level-7) as thedate                  from dual connect by level <= 12  )           group by thedate       ) t order by thedate 	0.262174110225026
15801996	18490	perform query for every row in different table	select    ts.s, ts.e,    (select count(id) from data   where create_dte_timestamp >= ts.s and create_dte_timestamp <= ts.e)   as c from ts; 	0.00111619372170733
15804097	23495	unble to group by date in my query	select  sauda_date ,          max(buy_qty) buy_qty,         max(sellqty) sellqty,          max(carryforward) carryforward from         (         ) x group   by sauda_date 	0.670565802602163
15804766	13406	mysql fetch data between two unix timestamps	select  *, complex_formula from    posts where   upvotes + downvotes > 0         and ts between unix_timestamp($user_time - interval 1 day) and unix_timestamp($user_time) 	0
15807635	16451	sql count() over 2 tables by a type	select     t.type ,     count(*) as amount from types as t    join test as te on t.id= te.type group by type order by t.type 	0.0181249763458287
15810361	10430	get products based on user selected options in mysql	select p.title, p.price  from products as p inner join product_options as po   on p.product_id = po.product_id where po.product_option_id in (5,1,38,39) group by p.product_id having count(distinct po.product_option_id) = 4; 	0
15811039	4239	each item wise count with conditions	select status ,status_numbers, sum(status_numbers) over (order by ordr desc rows between unbounded preceding and current row) status_numbers2 from ( select "job" status, count(*) status_numbers , decode("job", 'manager', 1, 'president',2, 'clerk', 3,'analyst', 4, 'security', 5) ordr from emp group by "job") t 	5.83387333375498e-05
15811104	26097	parsing date in sql query	select * from foclosing where trade_date >= '20130212' and trade_date < '20130213' 	0.309803199114463
15811107	15043	sql: select all from column a and add a value from column b if present	select  a.empid, a.name,         coalesce(sum(b.value), 0) totalvalue from    employee a         left join transactions b             on  a.empid = b.empid and                 b.date >= '2013-03-01' group   by a.empid, a.name 	0
15811447	12132	expand data when linked with foreign keys	select a.carname, b.partname from cars a join parts b on a.carid = b.carid 	0.00694233495077021
15812424	39328	how to check empty value in stored procedure?	select  mytable.col1,     nullif(histable.col2, '') from    mytable      left join histable         on mytable.linkcolumn = histable.linkcolumn 	0.0367171804623918
15814723	27625	combining groups in aggregate group by functions in mysql	select country, sum(duration) from ( select date, ip,         case             when country <> 'usa' and country <> 'canada' then 'everyone else'            else country        end country,        duration from trafficlog ) subsel group by country 	0.581675978233852
15815031	14666	mysql query to find the longest run in a column	select winner, max(winningstreak) from ( select winner, if(winner=@prev, @rownum:=@rownum+1, @rownum:=1) as winningstreak, @prev:=winner from yourtable , (select @prev:=null, @rownum:=1) vars )sq group by winner order by winningstreak desc 	0.00496550891773551
15815778	9098	db2 database + verification	select userfield1, userfield2,.. from   myusertable where  myusertable.username = 'uname' and myusertable.userid = userid 	0.731595916790327
15816339	14520	group by count in mysql	select o.country,        count(*)   from office o     inner join employee e on e.office_id = o.office_id   group by o.country 	0.216981783244643
15817225	29942	mysql - is today between two column values	select      * from     your_table where     first <= now()  and last >= now() 	0.000199583161670302
15817607	24321	get distinct value count in mysql select query	select number, count(distinct id) from your_table group by number 	0.00222678918365643
15818021	16089	sql for the one entry in each group that meets a condition	select ckt, max(setpt), max(clock) from progs  where feed = "80302" and day=4 and clock<"12:15:00"  group by ckt order by ckt, clock desc 	0
15818880	26523	how to separate multiple data from one column?	select column1,        substring_index(substring_index(column2,'|', nums.n),'|',-1) as column2 from table1 t1 cross join       (select (n1.n - 1) * 12 + (n2.n - 1)*3 + n3.n as n        from  (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5              ) n1 cross join              (select 1 as n union all select 2 union all select 3 union all select 4               ) n2 cross join              (select 1 as n union all select 2 union all select 3               ) n3       ) nums 	4.78537954753811e-05
15820082	29579	create a table with column names derived from row values of another table	select   concat(     'create table table_2 (',     group_concat(distinct       concat(namecol, ' varchar(50)')       separator ','),     ');') from   table_1 into @sql; prepare stmt from @sql; execute stmt; 	0
15820358	18409	reference data from another table, connected by a foreign key	select stories.* from stories join poster on poster.poster_id = stories.poster_id where poster.group_id = '$logged_in_user_group' 	0
15820482	19572	finding most common words in a column using sqlite?	select word, count(*) from ( select (case when instr(substr(m.comments, nums.n+1), ' ') then substr(m.comments, nums.n+1)              else substr(m.comments, nums.n+1, instr(substr(m.comments, nums.n+1), ' ') - 1)         end) as word from (select ' '||comments as comments       from m      )m cross join      (select 1 as n union all select 2 union all select 3      ) nums where substr(m.comments, nums.n, 1) = ' ' and substr(m.comments, nums.n, 1) <> ' ' ) w group by word order by count(*) desc 	0.00012365779986559
15821379	26188	select data between a date range	select * from hockey_stats where game_date between '2012-03-11 00:00:00' and '2012-05-11 23:59:00' order by game_date desc; 	0.000374369688459134
15822331	39191	count subcategories with a condition	select c.cat_id,   c.parent_id,   c.cat_name,   count(sp.cat_id)  as number_of_subcategories,   count(distinct p.id) as number_of_products from `categories` c left join (   select distinct s.cat_id, s.parent_id   from categories s    inner join products p     on s.cat_id = p.cat_id   where p.stock > 1 ) sp   on sp.parent_id = c.cat_id left join products p    on p.cat_id = c.cat_id    and p.stock >= 1 group by c.cat_id, c.parent_id, c.cat_name; 	0.203289184943527
15823153	22143	sql selecting records	select vehicle.model, vehicle.make, hire_agreement.start_date,     hire_agreement.termination_date  from vehicle      natural inner join hire_agreement       where    hire_agreement.terminationdate >= date() and hire_agreement.start_date <= date(); 	0.00652623194482831
15825204	23353	sub query count in mysql	select  table1.user_id,  table1.col8,  table2.col5,  user_tokens.expiry,  (select count(*)      from table         where table.user_id=table1.user_id) as ucount      from table1      inner join table2     on table1.user_id=table2.user_id     inner join user_tokens     on user_tokens.user_id=table1.user_id      where table1.col2 = '{$username}'"; 	0.645495407783492
15825247	22374	ms access information before a date	select emp_num, emp_lname, emp_fname, emp_initial, job_code, emp_pct, proj_num from employee where emp_hiredate < #01/01/1991# 	0.0717312906562313
15827214	20532	postgresql select from values in array	select * from table where id =      all((select array_agg(id) from table where some_condition)::bigint[]) 	0.00430152889757093
15829472	27643	mysql self join not all rows included	select t1.`group`, t1.`item`, t1.`data`, t2.`item`, t2.`data` from tablen t1 left join tablen t2 on t2.`group`=t1.`group` and t2.item = 200 where 1=1 and t1.item = 100 group by t1.`group`; 	0.312049289035505
15830410	9671	combine two rows in mysql to show data as one row	select   post_id,   max(case when meta_key='_billing_first_name' then meta_value end) _billing_first_name,   max(case when meta_key='_billing_last_name' then meta_value end) _billing_last_name from   yourtable group by   post_id 	0
15830445	39204	can i have two rows that have same contents except 1 column	select serialno from table where updatetag = <max update flag obtained in previous query> 	0
15831847	16427	two count to one select	select     jmeno,     sum(case when ucast = 'false' then 1 end) as count_false,     sum(case when ucast = 'true' then 1 end) as count_true from ... where (kategorie.idkategorie = 1) and datum >= '1/1/2013' and datum < '9/1/2014' group by jmeno; 	0.00239170891141606
15831879	1719	mysql exact word existence check in a table field	select * from sometable where somefield like '% age %'  or somefield like 'age %' or somefield like '% age' 	0.000585351385800513
15832306	8034	simple mysql select from 2 tables	select * from current where advert_id = 222 union select * from archived where advert_id = 333 	0.0390133623339185
15833763	1674	order by in mysql	select *    from zipcode   order       by field(state,4) desc      , case when state=4 then region end      , distance; 	0.350867722573138
15834623	1122	set operation of mysql	select a.member_id, a.name   from a inner join b  using (member_id, name) 	0.233861317751331
15837172	1749	sql query to display records with no related record within a specific date range	select *  from db.main m left outer join db.notes n on m.sysid = n.main_id      and n.[date] > dateadd(dd, -30, getdate()))  where n.main_id is null order by m.ile_number 	0
15839306	12914	mysql order results by total by weights	select     p.id,     count(distinct comments.id) as comments,     count(distinct likes.id) as likes,     count(distinct comments.id)* 6 + count(distinct likes.id)* 4 as `order` from     posts p left join comments on p.id = comments.post_id     left join likes` on likes.`post_id` = p.`id` group by     p.id order by     `order` 	0.0176756495944998
15842205	161	most recent x posts by unique authors	select * from (select *       from posts       order by date desc) p group by p.authorid order by date desc limit 5; 	0
15842301	30872	find all nodes that have children with hierarchyid	select a.* from employee as a  left outer join employee as b on a.position = b.position.getancestor(1) where b.position is null; 	0
15842799	31972	sql - visual studio - fill table if related data is empty	select * from properties  where propertyid not in     (select propertyid from propertytenants) 	0.212678006169943
15845770	35521	mysql query - 2 sums, added together	select sum(sub_total) as total     from orders    where month(date_estimated) = month(curdate() - interval 1 month)      and status_id = 65 union  select sum(final_total) as total     from orders    where month(date_estimated) = month(curdate() - interval 1 month)      and status_id > 65 	0.0439326971465199
15848686	20799	sorting child related rows consecutively after parent rows	select * from test order by coalesce(parentid,id) 	0
15850316	39394	select item number from sql table	select i.itemnumber from inventtable i  join etext e on i.itemnumber = e.itemnumber where e.rkey = 1 and e.rval =1 and e.id =2 	7.50424587984657e-05
15857724	18242	my sql count( ) 0 with only 1 table	select    username, user_id, sum(correct) as totalcorrect from    tournament_entries where    tournament_id = 1 group by    username, user_id order by    totalcorrect desc limit 0,10 	0.0366392738000561
15861474	29639	mysql multiple join with empty result line	select   s.year,   clients.name,   clients.item_a*s.sum_a,   clients.item_b*s.sum_b,   clients.item_c*s.sum_c from   clients inner join (   select     year,     sum(case when item_type='a' then value end) sum_a,     sum(case when item_type='b' then value end) sum_b,     sum(case when item_type='c' then value end) sum_c   from     prices   group by     year) s order by   s.year 	0.224929164512634
15862257	2112	how to check if a string contains any string of a column in mysql and vice versa?	select ... where column like "%string%" or string like concat("%", column, "%") 	0.000103093592327767
15862348	4243	the greatest row per group - further combining the result set with left join with other related table in hibernate - hql. is it possible?	select p  from product p  where p.productimageset is empty 	0.00605125835578729
15862762	9810	is there any functions for counting up groups in query result?	select count(distinct i_requirement_id) from points  where i_id in (1, 22, 579, 5887) and i_requirement_id is not null 	0.41830155270782
15864162	25139	mysql count different fields depending on fields value	select  sum(type = 1 and from_user = 'user_id_here') from_user,         sum(type in (4,5) and to_user = 'user_id_here') to_user from    tablename 	0
15866097	10785	sequence restrictions of select statement	select * from tbl_name where  (col_name like '%yyy%') and (col_name like '%xxx%') and ... 	0.282153016484345
15866484	15844	counting data occurence from mysql table	select sum(d1='a') + sum(d2='a') + sum(d3='a') as allsum from my_table   $result = mysql_query($sql);   $row = mysql_fetch_assoc($result);          echo $row['allsum']; 	0.000627751003503835
15867355	30788	sql query to sort table by sum	select     username,     sum(rating) from     yourtable group by     username order by     sum(rating) desc limit     10 	0.0502943246770147
15867780	3319	selecting one thing connected to several others in different mysql table	select o.id from (select c.order_id     from items     inner join c     on c.itemid = items.id     where items.item_name in ('foo','bar')     group by c.orderid     having count(distinct item_name) = 2   ) as these inner join orders on orders.id = these.orderid 	5.87737903814401e-05
15868611	13182	mysql - count rounds	select sum(case when r.status = 1 then 1 else 0 end) as won_rounds,        sum(case when r.status = 0 then 1 else 0 end) as lost_rounds   from rounds as r inner join         player as p on r.playerid = p.id   where r.playerid = <id> and r.played = 1  group by r.playerid 	0.401216933474208
15871842	4296	how to query the look up table for unique values?	select recipeid from product2recipe group by recipeid having count(distinct productid) =         count(distinct case when productid in (?,?,...) then productid end) 	0.00181663519771024
15872108	2794	searching text with mysql	select * from parts where itemname like 'processors%'; 	0.47922099977835
15873616	963	join two tables with condition	select food.type from count, food where food.segment = count.segment and food.type like '%$query%' and count.count > 0 	0.107796317338169
15874195	41084	mysql count 2 rows in one query	select   count(*) as total,   count(case when conv then 1 end) as total_conv_greater from   ... 	0.00151521111054882
15874476	30306	how to define which number from database is near (round) to getting number?	select * from table where num = 2 and temp = 44 order by abs(decimal - 46.5777) limit 1; 	0.00025099099372876
15875900	19597	return all values including null	select t1.ipaddress, t1.dnsrecord, t2.serialno, t2.ipaddress from tablea t1 join tableb t2 on t1.ipaddress = t2.networkaddress where ipaddress like '%' +@ipaddress + '%' and ( serialno like '%' +@serialno +'%' or serialno is null) 	0.00117100150722861
15877109	22650	substring of a substring	select  substring(substring(biographytext,1,10),9,2) as rebookingfirst, substring(substring(biographytext,11,20),12,3) as reinventfirst, substring(substring(biographytext,21,30),16,3) as recreatefirst, substring(substring(biographytext,31,40),20,2) as retentionfirst, substring(substring(biographytext,41,50),23,2) as referralsfirst from employs 	0.140983595223894
15878716	19535	mysql resturn value as min or plus from sum	select sum(thumb) as votes from your_table 	0.00922383429437569
15878925	20342	sql select when child table contains zero rows	select * from a where employeeid not in (select employeeid from b); 	0.000531397146859767
15879918	27163	sql combine two columns that might have null values	select 'all'= ltrim(isnull(name+' ','')+isnull(city+' ','')+isnull(cast(age as varchar(50))+' ','')  from zperson) 	8.80677746358686e-05
15880634	30855	view on a table referenced by two foreign keys from the same table	select i.serial imgid, i.text imgname,    case when t.im_left is null and t.im_right is null then 'none'        when t.im_left is null then 'right'        when t.im_right is null then 'left' else 'both' end source,   t.serial itmid, t.text itmname from image i     left join item t       on t.im_left = i.serial or         t.im_right = i.serial 	0
15881483	16745	null values turn everything into null during concatenation	select author_id,        concat_ws(' ', first_name, last_name,  patronymic) as full_name from   author; 	0.00250478826618413
15882997	25929	mysql adding a new column to label the time-series data points for each id	select yt.* , if(@prev=id, @counter:=@counter + 1, @counter:=1) as counter , @prev:=id from yourtable yt , (select @counter:=0, @prev:=null) vars order by id, `timestamp` 	0
15885398	34471	sql server bulk insert/update: checking if record exists with duplicates in source	select     case          when pk.id is null and i2.idproduct is null             then i.description         else               i.description + '_' + cast(i.idproduct as varchar)         end [newproductkey]     , i.idproduct from     inserted i     left outer join productkeys pk on pk.id <> i.idproduct and pk.productkey = i.description     left outer join inserted i2 on  i2.description = i.description and i.idproduct <> i2.idproduct 	0.0284642040312049
15891599	30811	sql aggregate function to return single value if there is only one, otherwise null	select  id,          case when count(distinct val) = 1 and count(id) = count(val)              then max(val)              else null         end only_val from    example group   by id order   by id 	0.000983053603901913
15892542	20461	sql join statement - generate data before export	select     p.products_id,     p.products_image,     max(case when language_id = 6 then products_description  end) as p_description_6,     max(case when language_id = 4 then products_description  end) as p_description_4,     max(case when language_id = 1 then products_description  end) as p_description_1 from      products p  inner join      product_description d on p.products_id = d.products_id group by      p.products_id,     p.products_image 	0.176149181100978
15892650	1531	sql - how to check for multiple values of one column while only returning one row?	select * from tablename t  where statusid = 1     and exists(select * from tablename                where applicationid = t.applicationid                    and statusid = 2) 	0
15892655	30678	mysql count sub query	select s.id as section_id, s.name as section, i.id as item_id,      i.title as item_title, item.location_id as item_location_id,     i.slug as item_slug, i.description as item_description,      i.price as item_price, unix_timestamp(i.date_added) as item_date_added,      c.id, c.city, c.particular_id, p.id, p.particular,     (select count(o.i_id) from offer as o on o.job_id = i.id) as interest from section as s inner join item as i     on s.id = i.section_id inner join city as c     on i.location_id = c.id inner join particular as p     on c.particular_id = p.id where s.id = 2 	0.65014315188409
15893427	17746	oracle query to get all entries having all caps in a column	select * from table where column = upper(column) / 	0
15894690	6144	mysql count distinct positive values but count all -1 values in table and give total?	select a + b as totalcount from         (           select count(distinct profile_id) a           from   ptb_profile_views           where  profile_id > 0         ) x,         (           select count(profile_id) b           from   ptb_profile_views           where  profile_id < 0         ) y 	0
15894785	31186	what is the best way to select the first two records of each group by a "select" command?	select a.* from tablename a where  (    select count(*)     from tablename as b    where a.group = b.group and a.id >= b.id ) <= 2 	0
15895013	16905	difference in days between two dates	select row_number() over(order by town) as 'row',  t1.surname, t1.forename, t1.town, t1.description, t1.sex, t1.dob, t1.start, t1.finish, cast(datediff(day,t1.start,t1.finish) as varchar) as difference from dbo.viewservicecontractfull t1  where t1.finish>='2013/01/01' and  t1.finish<='2013/01/31' 	0
15895676	26903	subtract values of two rows and inserting it into a new column (not subsequent rows)	select [user-name],         submissions,        [date],        place,        recency,        datediff(day,         (select top(1) [date]         from [top-design1] td1         where td1.[user-name] = [top-design1].[user-name]         and place = 1         and [date] < [top-design1].[date]         order by [date] desc), [date]) as recencywin from [top-design1] 	0
15895725	26481	union two sql queries	select  tps.product_id,         tps.name,         tps.total_products_sold,         s.total_orders from    ebay.`order` oo         inner join         (              select  o.id,                     o.product_id,                     p.name,                     count(o.product_id) as total_products_sold             from    ebay.`order` o                     inner join product p                          on o.product_id = p.id             group   by o.product_id          ) as tps on oo.product_id = tps.product_id         cross join         (             select  count(id) total_orders             from    ebay.`order`         ) s 	0.211097761756823
15897902	20769	mysql: getting items not belonging to a category	select * from `posts`      left join `post_categories` as cat on posts.id=cat.post_id and cat.cat_id=5 where  cat.cat_id is null 	0.00118527911610857
15898410	19216	optimizing a query : joining a table on itself	select sub1.x , sub2.x as last_x  from (select x from tbl order by tbl.id desc limit 1) sub1 cross join (select x from tbl order by tbl.id desc limit 2, 1) sub2 	0.178100621977489
15898935	16340	how do i count more than one column with a where clause? (sql)	select      sum(iif(committees=true, 1, 0))     , sum(iif(insurance=true, 1, 0)) from [annual questionnaire] 	0.0587325814422723
15899022	38072	sql column compare in the same table (self-join)	select * from tbl where category = 'b' and value not in (select value from tbl where category = 'a') 	0.000199733776928261
15900562	38070	select random ids based on other unique id	select id, courseid, dishid from ( select row_number() over (partition by courseid order by newid()) as n, * from table  ) t where n = 1 	0
15902890	23192	getting the last result of a bug that has been resolved	select his.date_modified, bug.id,        bug.project_id,        datediff (from_unixtime(his.date_modified), from_unixtime(date_submitted)) as dias_resolucao,        date_format(from_unixtime(his.date_modified), '%y-%m') as ano_mes from mantis_bug_table bug left join mantis_project_table pro on bug.project_id = pro.id left join mantis_custom_field_string_table cus on bug.id = cus.bug_id left join mantis_bug_history_table his on bug.id = his.bug_id where bug.category_id = 1 and       (cus.field_id=1 or cus.field_id is null) and             his.new_value = 80 and        his.field_name = 'status' and                        bug.id = 5171 and       cus.value='sim'       having his.date_modified = max(his.date_modified) 	9.54629432339607e-05
15904445	4755	determine if a field from one table is like the field from another table and if so count occurrence and if less than 3 return the name	select iteractions.plate_name, count(*) as `count` from interactions, images where interactions.plate_name like images.image group by interactions.plate_name having count(*) < 3 	0
15904763	5645	remove duplicate fields from a temp table that has no primary key	select a.* from yourtable a inner join (select [first], [last], max(dob) maxdob             from yourtable             group by [first], [last]) b     on a.[first] = b.[first]      and a.[last] = b.[last]     and a.dob = b.maxdob 	0
15905499	40370	query for mapping configuration from two tables	select isnull(tableb.id, tablea.id) as id,     tablea.name,      tablea.id as tableaid,      tablea.systemname,      isnull(tableb.value,'') as value from tablea left outer join tableb   on tablea.id = tableb.id 	0.00983444184896367
15907810	39428	can i mysql select rows only where join fails?	select * from table_a left join table_b on table_a.id = table_b.foreign_key where table_b.foreign_key is null 	0.0728349578364157
15909747	32023	sql: return row with maximum value per group	select * from table t  where views =      (select max(views) from table       where person = t.person) 	0
15910809	16618	mysql: exclude all users with at least 1 occurrence of a specific field value	select u.username, c.coursename, e.role from enrollments e join users u on user.userid = e.userid join courses c on c.courseid = e.courseid where u.userid not in (select distinct userid from enrollments where role = 'teacher') 	0
15912435	24738	avarage time between records mysql	select   unix_timestamp(max(create_time)) - unix_timestamp(min(create_time)) / count(*) as 'avg' from table where source_id = 5   and create_time between '2013-04-01 00:00:00' and now() 	0.00256694951971023
15913121	39501	select not related items	select games.* from games    left join user_games on (        games.id = user_games.id_game and        user_games.id_user = '1'    ) where user_games.id_user is null 	0.0124645148465832
15914369	32743	efficiently combine two queries with both have a common inner join	select t1.c1, t2.c1, t.c1 from audits as t1 inner join t2 on t2.t1_id=t1.id inner join (   select t1_id from t3   union   select t1_id from t4 ) as t on t.t1_id=t1.id where t2.fk1=123 order by t1.fk1 asc 	0.0055770510509422
15914561	9768	mysql - sum points from three tables	select p.facebookid,p.points,pi.facebookid,pi.points, sum(pi.points) from player as p  inner join invites as i on p.id = i.invitefromid  inner join player as pi on i.invitetoid  = pi.facebookid where p.id = 1 group by p.id 	0.00494801934962974
15914633	28294	get value from specific xml name value pair using sql	select     o.orderid,     cast(od.customdetails.query('        for $cd in /customdetails/fields/field,            $name in $cd/name         where contains($name, "address provided")        return data($cd/value)     ') as varchar(50)) as addressprovided from     dbo.[order] o on         o.orderid = s.orderid             join                 dbo.orderdata od on                             od.orderid = o.orderid 	0
15917218	35679	sql concatenate multiple values	select     column1,     stuff(     (select ',' + column2        from yourtable t2         where t2.column1=t1.column1         for xml path(''),type).value('.','nvarchar(max)'), 1, 1, '') as column2 from     yourtable t1 group by column1 	0.0050808289675029
15917235	9281	create insert query with null value in sql server	select 'insert into organizations(name, industryid, contactperson, email, website, locationid, contactnumber, mobilenumber) values(' +         isnull(''''+nameofthecompany+'''', 'null') + ', ' +         isnull(''''+industrytype+'''', 'null') + ', ' +        isnull(''''+nameofthepersonresponsibleforrecruitment+'''', 'null') + ', ' +        isnull(''''+emailid+'''', 'null') + ', ' +        isnull(''''+websiteaddress+'''', 'null') + ', ' +        isnull(''''+location+'''', 'null') + ', ' +        isnull(phonenumber, 'null') + ', ' +        isnull(mobilenumber, 'null') + ')'  from organization 	0.26437770418133
15918106	35761	sql query: retrieve columns with different condition	select  sum(case when price >= 0 price < 10 then 1 end) as 'group1',         sum(case when price >= 10 and price < 20 then 1 end) as 'group2',         sum(case when price >= 20 and price < 30 then 1 end) as 'group3',         sum(case when price >= 0 price < 10 then 1 end) as 'group4',         sum(case when price >= 10 and price < 20 then 1 end) as 'group5',         sum(case when price >= 20 and price < 30 then 1 end) as 'group6' from    table2 	0.00187098762901993
15922309	29239	get the total value of different name using 2 tables	select count(b.id), a.name, sum(b.price) from a left join b on a.pid=b.pid group by a.name 	0
15923414	18301	postgres: get count & select distinct	select min(title), min(lat), min(lng), geocoder_identifier, count(*) from entries where geocoder_identifier is not null group by geocoder_identifier order by 5 desc 	0.00565715513373994
15928154	10399	how can i merge these mysql statements	select *, max(dup_number) as dup from table1 where  contacts=1 group by field_a order by date limit 3 	0.252068758533755
15930179	14861	how to add a column for just current month data to a multimonth query?	select     *,     case         when             datepart(motnh, trandate) = datepart(month, getdate()) and             datepart(year, trandate) = datepart(year, getdate())         then totalcost         else 0     end currentmonthcost from dbo.ngpcostposition 	0
15930659	39864	retrieve unique data from mysql database	select * from your_table group by case_id having count(agency_id) = 1 	0.000128487612557965
15931049	6570	mysql: turn decimal into percent within view	select concat(a.fa_rate * 100 , '%') as rate_percent    from accounts a; 	0.00326568093917812
15932272	40757	joining on variables with two different formats	select... from x join y on x.year_of_birth = substr(y.date_of_birth, length(y.date_of_birth)-3,4) 	0.00467628766197833
15932284	27411	obtain maximum row_number inside a cross apply	select c.ordernumber, c.dateonly, c.hourminute, c.code, c.phone, c.purchases, max(o.previouspurchases) from cte c cross apply (                       select t2.dateonly, t2.phone,t2.ordernumber, t2.purchases, row_number() over(partition by c.dateonly order by t2.dateonly) as previouspurchases                       from currentcustomers_v2 t2                       where c.phone = t2.phone and t2.purchases<=c.purchases and datediff(day, t2.dateonly, c.dateonly) between 0 and 365                       ) o where c.ordernumber = o.ordernumber group by c.ordernumber, c.dateonly, c.hourminute, c.code, c.phone, c.purchases order by c.dateonly 	0.411668473883559
15934543	17382	subtract one row of two results	select    ok.qnt - deleted.qnt as qnt,    ok.name from     (select * from table1 where status="ok") ok left join     (select * from table1 where status="deleted") deleted    on ok.name = deleted.name 	0
15934552	32207	mysql search where column match with given input or given input with price between given price and price	select * from diamonds   where diamond_price between 1000 and 10000    and (diamond-color ='red' or diamond-color_pink='pink') 	0
15934709	28492	selecting with two different where statements	select      foreignid,      sum(case when accepted = 'y' then value else 0 end) as sum1,     sum(case when accepted = 'n' then value else 0 end) as sum2 from example where foreignid='1' 	0.00898824664298547
15934952	2672	how to get students whose 21th birthday is next month in sql?	select * from students where month(birthdate) = (month(now()) % 12) + 1       and       timestampdiff(year, birthdate, now()) = 20 	0
15936520	22501	mysql city name from postalcode	select     users.username,     users.birthdate,     timestampdiff(year,users.birthdate,curdate()) as age,     users.profile_text,     cities.city_name,     cities.postalcode from users, cities     where id = ? and cities.postalcode = users.postalcode 	0.00658650999738576
15937835	35466	compare yymmdd date to today	select ... where created >= date_format(now(), '%y%m%d') 	0.00158478781990211
15938180	11772	sql: check if entry in table a exists in table b	select * from   b where  not exists (select 1                     from   a                     where  a.id = b.id) 	0.000164247528323456
15938366	40640	mysql getting average of several columns with limit	select avg( d.sensor1 ) , avg( d.sensor2 ) , avg( d.sensor3 )  from  (     select sensor1, sensor2, sensor3     from temperatur     order by zeit desc      limit 0 , 60 ) d  	0.000291148854907948
15938961	39082	how can i select the rows having a longer text in one column	select date, text, number from table order by length(text) desc, number limit 1 	0.000620380844009355
15940450	16512	most efficient way to re-order my database table and display to web	select categories.*, transactions.* from categories left join transactions on categories.name = transactions.category order by categories.rank 	0.013875776823286
15940649	38111	checking user exists or not in mysql	select * from mysql.user where user='username'; 	0.581006003071094
15943149	23320	get last record from group by cakephp	select * from `login_logs`  as `loginlog`  left join `users`  as `user`  on (`loginlog`.`user_id` = `user`.`id`)  where 1 = 1  order by `loginlog`.`login_datetime` desc limit 0 ,1 	0
15943515	773	show details record with totaling	select empname,basicsalary,gradepay,ta,da,hra,gross,sum(gross) over () totalgross from tblsalary 	0.0059151200131142
15944563	26339	db2 query based on condition from same table	select groupid, name, salary, car   from tablename  where groupid in (select groupid                      from tablename                     where car = 'nissan')     and car <> 'nissan' 	0.000103463487717617
15945163	38908	sql return value as a parameter	select  comment_id,          comment_post_id,          comment_user_id,          comment_text,          comment_like,          comment_dislike,          comment_reply_to_id,          comment_date,         begendi = cast(case when likeordislike.likes > 0 or likeordislike.dislikes = 0 then 1 else 0 end as bit),         begenmedi = cast(case when likeordislike.dislikes > 0 and likeordislike.likes = 0 then 1 else 0 as bit) from    comment         left join          (   select  comment_id,                     likes = count(case when likevar = 1 and dislikevar = 0 then 1 end),                     dislikes = count(case when likevar = 0 and dislikevar = 1 then 1 end),                     other = count(case when likevar = dislikevar then 1 end)             from    likeordislike             group by comment_id         ) likeordislike             on comment.comment_id = likeordislike.comment_id order by comment_date desc 	0.0507295470651673
15945294	28364	mysql change select output with data from other row	select c.id,        case c.parent_id              when 0 then c.type             else concat(p.type,'[',c.type,']')        end as type from mytable c left join mytable p on c.parent_id = p.id 	0.000326062550413167
15946871	2182	joining multiple tables in one	select t1.bp, t1.itemcode, t21.serial as so_serial, t22.serial as dr_serial from table1 t1 left join table2 t21 on t21.itemcode=t1.itemcode and t21.basetype=17 left join table2 t22 on t22.itemcode=t1.itemcode and t22.basetype=15 	0.00637413969178806
15948129	25079	checking for date range conflicts with access	select * from bookings where carid = 7 and startdate < user_end_date and enddate > user_start_date 	0.0619146037056848
15948326	2496	extracting year from unix time in postgresql	select date_part('year', to_timestamp(1365682413)); 	0
15948567	1603	mysql join with empty count	select        p.id,        count( s.pid ) as pcount    from        products p          left join stock s              on p.id = s.pid            and s.status = 1    where        p.status = 1    group by        p.id        order by        pcount 	0.458251852666254
15948614	23818	select hardcoded values without table	select a from (     values ('foo'), ('bar'), ('foobar') ) s(a); 	0.0185093431377698
15949828	32751	trimming the results of a mysql query	select trim(trailing concat('.',reverse(substring_index(reverse(email), '.', 1))) from email) email from   users 	0.088612233092255
15950767	6703	sql - get list based on column from table	select   * from     company where    '|' + product + '|' like '%|' + '12' + '|%' 	0
15950871	36369	select all records using mysql limit and offset query	select * from tbl limit 0,18446744073709551615; 	0.0102917538936527
15950929	36533	can a table be selected in an sql query to group the result	select id, name, type, 'table1' as fromwhichtable from table1 union all select id, name, type, 'table2' from table2 limit 20 	0.0885542882999045
15952085	19755	sql query group by and count	select col1, count(col2)   from table-a    group by col1 	0.399697817740555
15953854	17504	select first appearance of item in last grouping	select t1.* from `table_name` t1 left join `table_name` t2  on t1.`sequence` = t2.`sequence` and     t1.`timestamp` = t2.`timestamp` + interval 1 minute where t1.`sequence`=2 and t2.`sequence` is null order by t1.`timestamp` desc limit 1 	0
15954333	20790	sql query with three tables	select     c.productcode,     c.productname,     count(*) ordercount from order a inner join orderitem b on a.orderid = b.orderid inner join product c on b.productcode = c.productcode where status = 'shipped' group by     c.productcode,     c.productname 	0.296048811899206
15955503	39631	special group by & sum	select id, sum(case w = w1 then s else 0 end) over(partition by id order by 1) total, w from yourtable 	0.351409172574133
15956161	28895	getting 2 different lengths for a text field in perl from a dbi query	select length(table.encryptedtext) 	0.00124221087081979
15956334	13886	select only special rows	select * from table x where x.val = 2 or not exists (select 1 from table where id = x.id and val = 2) 	0.00756509235905088
15960577	28472	how to do i group or join a query together to get the list of items i need	select  a.id invoiceid,         a.total totalinvoice,          b.totalpayment from    invoice a         inner join         (             select  invoiceid, sum(amount) totalpayment             from    payment             group   by invoiceid             having  sum(method = 'credit') > 0         ) b on a.id = b.invoiceid and                 a.total < b.totalpayment 	0.00135556399337871
15961264	18302	how to use temp tables in sql server to display the days of the week	select datename(weekday, orders.orderdate) as [weekday], orders.orderdate as [date], category.description as category, authors.state, isnull(sum(orderline.quantity),0) as [numbersold] into #booksales from books left outer join orderline on books.bookid = orderline.bookid join orders on orders.orderid=orderline.orderid join authors on books.authorid = authors.authorid join category on books.categoryid = category.categoryid where orders.orderdate between @begindate and @enddate group by datename(weekday, orders.orderdate), orders.orderdate, category.description, authors.state 	0
15961349	29900	using select result in another select	select      row_number() over( order by nett) as rank,      name,      flagimg,      nett,      rounds  from (     select          members.firstname + ' ' + members.lastname as name,          case              when menucountry.imgurl is null then                  '~/images/flags/ismygolf.png'              else                  menucountry.imgurl          end as flagimg,          avg(cast(newscores.netscore as decimal(18, 4))) as nett,          count(score.scoreid) as rounds      from          members          inner join          score newscores             on members.memberid = newscores.memberid          left outer join menucountry              on members.country = menucountry.id      where          members.status = 1          and newscores.inserteddate >= dateadd(mm, -3, getdate())     group by          members.firstname + ' ' + members.lastname,          menucountry.imgurl     ) as dertbl  order by; 	0.0167002018899212
15962386	5778	how to get table from xml on the sql server	select      cells.value('.', 'varchar(25)') from      @informe.nodes('/table/row[1]/cell') as xtbl(cells) 	0.000410835231253458
15962757	3800	mysql date wise repleat query	select * from users  where alert_date <= current_date and date_add(alert_date, interval repeat_on day) >= current_date 	0.090756699885248
15966604	27026	list of triggers for each table?	select   sysobjects.name as trigger_name  ,user_name(sysobjects.uid) as trigger_owner  ,s.name as table_schema  ,object_name(parent_obj) as table_name  ,objectproperty( id, 'execisupdatetrigger') as isupdate  ,objectproperty( id, 'execisdeletetrigger') as isdelete  ,objectproperty( id, 'execisinserttrigger') as isinsert  ,objectproperty( id, 'execisaftertrigger') as isafter  ,objectproperty( id, 'execisinsteadoftrigger') as isinsteadof  ,objectproperty(id, 'execistriggerdisabled') as [disabled]  from sysobjects  inner join sysusers  on sysobjects.uid = sysusers.uid  inner join sys.tables t  on sysobjects.parent_obj = t.object_id  inner join sys.schemas s  on t.schema_id = s.schema_id  where sysobjects.type = 'tr' 	5.8430548561741e-05
15967522	34592	remove duplicate based on condition	select column1, column2, column3 from( select column1, column2, column3, row_number() over (partition by column1, column2 order by case when column3 = 'n/a' then 999999999 else to_number(column3) end ) rn from table1) where rn = 1 	0.000550126214991907
15969465	7522	picking the maximum value from an alpha-numeric column in ms access	select max(val(mid([col],3))) from thetable; 	7.67921988786986e-05
15969820	9411	select query to return ids based on values	select  distinct f.fruitid from    dbo.fruitstable f where   f.fruitid in (             select fruit.cols.value('@fruitid', 'int') fruitid             from   @data.nodes('/fruits/fruit') fruit(cols))         and (f.isfresh in (0,1)) 	0
15971225	38737	don't repeat yourself: same sql query, but two different tables	select replace (entity_key, 'rss_user_name=cn=', '')  from    (select *            from audit_trail_archive au           union all           select *            from audit_trail au            ) au    inner join       (select rss_user_name          from rss_user         where rss_name = 'rmad'               and add_info_master like '%__47__upn=%@richemont.com%') falsch    on replace (au.entity_key, 'rss_user_name=cn=', '') =          falsch.rss_user_name where     au.rss_name = 'rmad'    and au.table_name = 'rss_user'    and au.action = 'insert'    and au.entity_key like 'rss_user_name=cn=%'    and au.origin != 'rss' 	7.7856748884481e-05
15971452	25868	mysql count distinct users in a table	select l.`date`,        count(distinct case when e.typeid=1 then e.empid end)              as specialemployeeaccesses,        count(distinct case when e.typeid=2 then e.empid end)              as regularemployeeaccesses from log l inner join employee e on e.empid = l.empid group by l.`date` 	0.00371010489113658
15971473	9255	how to structure a database with multiple join tables	select ingredient_id from recipe r join step_ingredient si on si.step_recipe_id = r.recipe_id join ingredient i on si.ingredient_id = i.ingredient_id 	0.0829755319264351
15974330	25937	sql query count	select i.idi, i.ingrdesc, count(*) from ingredient i inner join recipingr ri on i.idi = ri.idi group by i.idi, i.ingrdesc having count(*) > 10 	0.415973364692942
15974636	3958	set width of the concatenated column in oracle sql select	select      cast(t.first_name || ' ' || t.family_name as char(18))   as "trainer name" from trainer t 	0.00140551868709248
15975096	32693	sql command search for single word vs. two	select * from jos_users where name not like '% %'; 	0.271337580552537
15981730	21717	how do i join multiple columns in one table to a column in another table	select t1.name as person1, t2.name as person2 from log_points t join a_main t1 on t1.uid = t.user1 join a_main t2 on t2.uid = t.user1; 	0
15982107	17725	sql: get parent and grandparent (cte or derived table)?	select a.f_assetname, p.f_locationname as parent, gp.f_locationname as grandparent from tb_assets a left join tb_locations p on a.f_assetlocationid = p.f_locationid left join tb_locations gp on gp.f_locationid = p.f_locationparentid 	0.0388774581646036
15982538	5509	mysql: select distinct across multiple tables and order by datetime	select pid, max(`datetime`) as `datetime` from (select id as pid, `datetime` from table1       union       select pid, `datetime` from table2       union       select pid, `datetime` from table3) t group by pid order by max(`datetime`) desc limit 5 	0.00534069183014121
15986543	6955	combining multiple mysql queries into 1	select currency,        sum(amount) as total   from payments  group by currency 	0.0238687065686546
15987167	16746	mysql - sorting techniques and ordering	select count(*) as ct, imageid     from `ratings`   where rating > 3   group by imageid  order by ct 	0.605671626771545
15987418	19486	checking the db_link connection	select * from dual@link_name 	0.35700313421522
15988573	10764	mysql procedures - running total	select * from (   select    id,    qty,   @running_total:=@running_total + qty as running_total   from stock   , (select @running_total:=0) vars   where block_id=_block_id && type=2 && product_id=_product_id   order by time desc, id desc ) sq  where running_total <= $yourrunningtotallimit 	0.0489285707529153
15988976	15966	return a list of rows with my daily capital from a table with cash inflows?	select t2.date, sum(t1.amount) as sum from sometable t1 inner join sometable t2 on t1.date <=t2.date group by t2.date 	0
15990828	38601	repeating column value into row in sql	select  time_,         red,          orange,          yellow,          green,          blue from     (         select  time_, color, count         from    colors     ) orgdata     pivot     (         max(count)         for color in (red, orange, yellow, green, blue)     ) pvt 	0.000179525999523681
15994060	38202	when selecting rows based on a where clause how can i match full words?	select title   from posts   where title regexp '[[:<:]]in[[:>:]]' 	0.000787154430008522
15996739	24018	error with 'group by' from joined tables in sql server	select  table2.type, sum(population) totalpopulation  from    table1 join table2 on table2.city_code = table1.city_code group   by table2.type order   by table2.type 	0.343137803047867
15997703	26782	mysql get results with mysql only	select product_id, count(*) as i from mytable where filter_id in (2,5) group by product_id  having i = 2; 	0.00957164278096585
15999415	2084	merge the sum of 3 columns into another column in php mysql	select   price_crore        , price_lakh        , price_thousand        ,   (price_crore    * 10000000)          + (price_lakh     *   100000)          + (price_thousand *     1000) as amount from some_table 	0
16000632	8909	how to select from a table with criteria needing to match a temporary table?	select a.ean, h.tmp_price as preis  from articles as a left join haha as h     on h.tmp_eg = a.eg where h.tmp_kz = "000"     and h.tmp_kto = "0000000"     and h.tmp_preisliste = "i"     and h.tmp_length = substring(a.size,1,3)     and h.tmp_width = substring(a.size,4,3) 	0
16000962	37524	solr indexing my sql timestamp or date time field	select id,date_format(created_at,'%y-%m-%dt%tz') as created_at,... from table 	0.111651652552103
16003663	15944	sql min() & group by	select * from             (                 select metal.enum_id as `metal`, metal.product_id from product_attributes metal                 left join product_attributes price on metal.product_id = price.product_id and price.attribute_id = 37                 inner join products p on p.id = metal.product_id                 where                     metal.attribute_id = 40 and                     p.group_id = 1 and                     p.id not in (select distinct product_id from product_attributes where (attribute_id=162 or attribute_id=204 or attribute_id=205) and `value`=1)                 order by price.value+'0' asc              ) as s             group by metal 	0.296708681761248
16005978	6870	moving through tables	select t1.*, t2.* from table as t1  join table as t2    on t2.pers_type_sd > t1.pers_type_sd   and t2.pers_type_sd < t1.pers_type_ed   and t1.pers_id < t2.pers_id   order by  t1.pers_id, t2.pers_id 	0.0531366652679676
16006521	17941	retrieve records which one field value doesn't end with space	select * from mytable where '.' + ltrim(myfield) + '.' = '.' + rtrim(ltrim(myfield)) + '.' 	0
16008462	35722	how to count rows month wise	select [created by],        productgroup,        count(productgroup),        monthname([initial intl created]) from tablename group by [created by],productgroup,monthname([initial intl created]) 	0.000108280914497777
16010215	35263	joining 2 columns to create an account flow query	select date, amount as payment, null as withdrawal from payments where client = 'ana' union all select date, null as payment, amount as withdrawal from withdrawals where client = 'ana' order by date 	0.00459495914460259
16010793	1579	how can i display the record in a particular sequence	select * from empp  order by case when ename = 'name2' then 0            when ename='name3' then 1            else 2           end 	4.9624653472149e-05
16010999	5418	what is the optimum query for searching string appears in many columns in 1 table?	select c1   ,c2   ,c3   ,case when c1 in ('k1','a2','c1','n1') then 1 else 0 end   +case when c2 in ('k1','a2','c1','n1') then 1 else 0 end   +case when c3 in ('k1','a2','c1','n1') then 1 else 0 end as sortweight from thetable where c1 in ('k1','a2','c1','n1') or c2 in ('k1','a2','c1','n1') or c3 in ('k1','a2','c1','n1')  order by sortweight desc      ,c1      ,c2      ,c3 	0.00511718908724699
16011378	11663	sql for getting a queue of users - for game	select concat("group ", @group := @group + 1), concat("#", player1), concat("#", player2), matchtype from ( select a.id as player1, b.id as player2, concat("(", a.gender, " match)") as matchtype, (case when @auser = a.id then @cnt = @cnt + 1 else @cnt end) as rownum, @auser := a.id from users a inner join users b on a.gender = b.gender and a.id != b.id  inner join (select @cnt := 0, @auser := null) c order by a.id, rand()) sub1 inner join (select @group := 0) c where sub1.rownum = 0 order by rand() limit 0, 10 	0.0239794221330758
16011985	31311	how to create query who will be sum or not values from tables	select t1.name, coalesce(t1.value,0) + coalesce(t2.value,0)  from table1 t1 left join table2 t2 on t1.fk_table = t2.id 	0.00604433873153617
16013364	28933	inner join with 3 tables in mysql	select student.firstname,        student.lastname,        exam.name,        exam.date,        grade.grade   from grade  inner join student on student.studentid = grade.fk_studentid  inner join exam on exam.examid = grade.fk_examid  order by exam.date 	0.63459780023007
16013912	23003	how can i convert a nagios timestamp to datetime?	select convert(varchar(3), datename(weekday,  switchoffset(cast(date_column_name as datetimeoffset),'+02:00')), 100) + ' ' + convert(varchar(3), datename(mm,   switchoffset(cast(date_column_name as datetimeoffset),'+02:00')), 100) + ' ' + datename(day,  switchoffset(cast(date_column_name as datetimeoffset),'+02:00')) + ' ' + convert(varchar(8), switchoffset(cast(date_column_name as datetimeoffset),'+02:00'), 108) + ' cest ' + datename(year,  switchoffset(cast(date_column_name as datetimeoffset),'+02:00')) from adm_co_users 	0.0166800771816037
16015151	3069	sql select all and change the format of one column	select *, convert(varchar(100),coursestartdate,111) as myconverteddatecolumn from ethicsmanagement 	5.49829875683198e-05
16017059	22214	date conversion failed from string	select convert(datetime, '20/04/2013', 103) 	0.0385024824852777
16017410	8006	check if timestamp is today using sql	select collist from tbl where timestampcol >= unix_timestamp(curdate()) 	0.00949050324453075
16021094	27465	sql statement to compare rows	select product, client, region from yourtable t where region in('north','south')   and not exists(     select product, client, region     from yourtable tt     where t.region <> tt.region       and t.client = tt.client       and t.product = tt.product     ) 	0.0209526349445915
16023968	20913	mysql - combining two records, different fields from each record	select tt1.id, tt1.parent, maxinc, tt1.info1, tt2.info2 from  (select id, parent, maxinc, info1 from test inner join  (select parent as p, max(incr) as maxinc from test group by parent) as t1  on parent = p and incr = maxinc) as tt1 inner join (select parent, info2 from test inner join  (select parent as p, min(incr) as mininc from test group by parent) as t2  on parent = p and incr = mininc) as tt2 on tt1.parent = tt2.parent 	0
16024874	2337	need a stored procedure to use rows from a temp table as anded criteria	select c.caseid from cases c       searchcriteria sc left outer join      on sc.personnelname = c.name and         sc.personnelgroup = c.group group by c.caseid having (@flag = 'all') and (count(*) = (select count(sc.personnelname) from searchcriteria) or        (@flag = 'any') and count(sc.personnelname) > 0 	0.0175414811448418
16025173	17174	count duplicates	select store, count(distinct transaction) as numtransactions,        count(*) as numitems from t group by store; 	0.120982550552781
16026249	5238	sql joins from 2 tables, grouped by joined data from a third	select       pd.products_name as 'product',       prequery.*    from       ( select                op.products_id as 'pid',               sum(op.products_quantity) as 'sales q',               sum(op.final_price * op.products_quantity) as 'sales $'            from                orders o                  join orders_products op                     on o.orders_id = op.orders_id            where                o.date_purchased between '2012-01-01' and '2012-12-31'            group by                op.products_id ) prequery       join products_description pd          on prequery.pid = pd.products_id 	0
16030186	225	select rows where column name not equals multiple values	select *   from table  where ( ( user_id = 4 and friend_id = 5 ) or          ( user_id = 5 and friend_id = 4 ) )                  and accepted = 1 	0.000488770865638621
16031043	16135	how to pivot a table to reflect row values as columns?	select  [application],          fdate,         [calculate index] as cindex,         [cyc complexity] as cc,         [medium index] as mi from             (             select  a.app_name as [application],                     o.functional_date as fdate,                     t.type_name,                     round (v.typevalue, 2) value             from    [dbserver1].[db_a].[dbo].typetab as t,                      [dbserver1].[db_a].[dbo].appname as a,                         [dbserver1].[db_a].[dbo].datetab as o,                      [dbserver1].[db_a].[dbo].valuetab as v              where   t.type_id = v.type_id and                      t.type_index in (0,1)... (several ands)         ) org         pivot         (             max(value)             for type_name in ([index], [cc], [mi])         ) pvt 	0.000424387715943521
16031393	2929	multiple left joins on the same table, using data from previous join	select      * from datatable as d left join orgtable as o1 on o1.orgid = d.orgid left join orgtable as o2 on o2.orgid = o1.parentorgid 	0.000950480471134333
16032671	39415	php mysql matching and return value	select student id, (case when student_answer=0     then ""     else     when student_answer=correct_answer then "true"     else "false"     end ) as result     from studens_exam_answers_tbl inner join question_poll__tbl on studens_exam_answers_tbl.question_id.question_id =question_poll__tbl.question_id 	0.00329148938194512
16033239	40080	mysql: select row where column contains element from list	select * from `table` where `column` regexp '[\£\$\%\^\&]' 	0
16037111	30712	mysql select from 3 tables order by date	select name, date_added from(   select video_name as name,date_added, uid   from videos   union all   select audio_name as name,date_added, uid   from audios   union all   select image_name as name,date_added, uid   from images ) u where uid = 1 order by date_added 	0.00205036391640781
16038197	2858	concat sql query > show same column in 2 differents columns according to where clause	select  count(case when [société_id] = 1 then [id] end) as societe_1,         count(case when [société_id] = 2 then [id] end) as societe_2,         count(*) as total,         cast([créé le] as date) as datecreated from [mfilescloudreport].[dbo].[document] group by cast([créé le] as date) order by cast([créé le] as date) 	0.000100119154725339
16041030	32243	mysql update = are there any overheads in updating fields with same contents?	select * from user;  +  | user_id | username |  +  |     101 | adam     |  |     102 | ben      |  |     103 | charlie  |  |     104 | dave     |  +  4 rows in set (0.01 sec)  update user set username = 'adam' where user_id = 101;  query ok, 0 rows affected (0.18 sec)  rows matched: 1  changed: 0  warnings: 0 	0.00685705003065699
16044046	31730	how to get list of all tables that has identity columns	select    [schema] = s.name,   [table] = t.name from sys.schemas as s inner join sys.tables as t   on s.[schema_id] = t.[schema_id] where exists  (   select 1 from sys.identity_columns     where [object_id] = t.[object_id] ); 	0
16044454	32430	indicate if rows exist in joined table in mysql	select exists(select 1 from table1 where ...) 	0.00189429512268016
16045095	4477	sql find records based on two columns	select *  from users where id in (   select userid2 as id from db.friends where userid1 = 16 ) 	0
16046195	26201	counting unique occurrences of ids using mssql	select count(teacherid) as uniqueteachercount,schoolyear from ( select distinct tblteachers.teacherid, tblschoolyears.schoolyear from tblteachers inner join tblteacher_building  . . ) hlp group by schoolyear order by schoolyear desc; 	0
16047241	33773	sql query grabbing data from two tables	select a.i_id, a.i_name, case when i_status = '1' then 'complete!' else 'incomplete' end as complete_status from items a  left outer join item_collection b on a.i_id = b.i_id 	0.00104449841468675
16048445	27928	sql query to return the latest 20 results sort by datetime	select * from table_name order by whenadded desc limit 20 	7.04914343055431e-05
16049241	13450	how to compare rows in 2 different tables: mysql - what's different	select  a.pid, a.product_id from    products a         inner join catalog b             on  a.cid = b.cid and                 b.level = 2 where   a.thickness <> b.thickess 	0
16050458	25854	oracle sql query, schema given	select bid from boat where not exists (select sid from sailor where sid not in (select sid   from reserves where sailor.sid = reserves.sid)) 	0.270315411675183
16051369	15575	convert output of mysql query to utf8	select column1, convert(column2 using utf8) from my_table  where my_condition; 	0.532877801943566
16054792	7080	fetch fields from two tables in mysql	select tb2.first_name, tb2.last_name, tb1.english, tb1.maths, tb1.chemistry, tb1.bilogy, tb1.physics from exam_details as tb1 inner join students_register as tb2 on tb1.reg_number = tb2.reg_number 	0.000143684234956405
16056529	19227	sql - take data from multiple rows into single row	select setid, appcode, appeventid, eventid    ,max(valuedata1) as valuedata1   ,max(valuedata2) as valuedata2   ,max(valuedata3) as valuedata3 from (   select setid, appcode, appeventid, eventid    ,case when fieldid = 1 then valuedata end as valuedata1   ,case when fieldid = 2 then valuedata end as valuedata2   ,case when fieldid = 3 then valuedata end as valuedata3   from table_name  ) as table_name group by setid,appcode,appeventid,eventid 	0
16056935	37869	using max function	select t1.date    , t1.time    , t2.time    , t2.a    , t2.b from totaltimetable t1 cross apply (  select top(1)   t2.time  , t2.a  , t2.b from finallista t2 where t2.date = t1.date and t2.time <= t1.time order by t2.time desc ) as t2 order by t1.date,      t1.time 	0.637869401107876
16058404	29050	php and mysql query after cutoff date based on mysql timestamp	select sum(r.result_value)     from logos_results r     where r.user_id = u.user_id     and r.result_date < now() - interval $num_of_weeks week 	0.000916888317948752
16058417	36435	find index of any character from list in string	select patindex('%[ _-]%','kjhk wonderful') 	0.000793820869377093
16058843	5133	add two types of casting into single column	select top(10) 'insert into jobs(budget) values('+         cast(substring(cast(r.budget as varchar(50)), 0, patindex('%laks%', r.budget))*100000             + substring(cast(r.budget as varchar(50)), patindex('%laks%', r.budget) + 4,                                                         patindex('%thousands%', r.budget) - patindex('%laks%', r.budget) - 4)* 1000 as varchar(50))+')'     from requirementsdetailsfororganization r 	6.70832613456672e-05
16059692	31107	tsql - top and count in one select	select top 1     case when tbl_communicationelements.pk_communication is null then 0 else 1 end hasansweredcom     , tbl_communication.subject as hasansweredcomstepname from   tbl_communication  join   tbl_communicationelements on tbl_communicationelements.pk_communication = tbl_communication.pk_communication right join (values(1)) as ext(x) on (   tbl_communication.pk_ticket = @pk_ticket    and tbl_communication.isclosed = 0    and tbl_communication.pk_communicationtype = (select pk_communicationtype                                                 from   tbl_communicationtype                                                 where  name = 'query') ) 	0.00642768835060138
16062325	14473	joining two tables to get a count	select c.* from `comments` c join `pages` p on c.page_id = p.id where c.is_approved = '1' and p.page_id = '943' 	0.000395524874107806
16062640	19581	delete a row from a table if there is another row that has "better" value	select studentname, rollnumber, subject,        (case when max(result = 'pass') = 1 then 'pass' else 'fail' end) as result from t group by studentname, rollnumber, subject 	0
16064149	23270	grouping data, later getting extra fields	select pizzaname, type,        (select name from toppings t2 where t2.type = t.type and t2.pizza = t.pizza         order by order, requests desc         limit 1        ) as importanttopping from (select distinct p.name as pizzaname, type       from toppings t join            pizza p            on t.pizza = p.id      ) pt 	0.00489657622361005
16065364	28929	tsql not equal operator with respect to dates	select * from table_name where     [dateoflasttransaction] <> @p29  or [dateoflasttransaction] <> @p30 	0.569277490609195
16066398	26394	columns in pivot not in a desired sequence	select @cols = stuff((select '],[' + [description]      from dbo.vqualscoringgrade      group by [description]      order by max([orderby]), [description]      for xml path('')), 1,2,'') + ']' 	0.412752662941238
16068530	1220	mysql : help ordering a select statement and getting the middle of the set	select * from table order by column desc limit 100 , 50 ; 	0.124075068093844
16068896	30421	mysql query substring?	select ratings.* from shows inner join ratings      on shows.id = ratings.show_id where   shows.netword_id = 1 	0.596249082115626
16070184	37461	trying to perfect the query	select sum(c.cost)  from (select x.num as x, y.num as y, max(priority) as maxpriority        from numbers x        cross join numbers y        join costs c        on x.num between c.x and c.x + c.deltax        and y.num between c.y + c.deltay        where (x.value between pixelx and pixelx + deltax)          and (y.value between pixely and pixely + deltay)            group by x.num, y.num) xyp join costs c  on (xyp.x between c.x and c.x + c.deltax) and (xyp.y between c.y and c.y + c.deltay)                  and xyp.maxpriority = c.priority 	0.640733159199585
16070563	31053	query for finding a users rank in game database	select g1.id, count(distinct g2.xp)+1 rank from   game g1 left join game g2   on g1.xp < g2.xp group by   g1.id 	0.00749847669477541
16070878	10688	wordpress sql query to combine column data for all rows	select count(user_id) as totalwishes from table_name where (  (post_id like 'n,%') or  (post_id like '%,n,%') or  (post_id like '%,n')  ) 	0.000323385587835132
16071686	8112	aggregation result from sql view to gridview	select account_name,  sum(case when bonus = 'a' then value else 0 end) as a, sum(case when bonus = 'b' then value else 0 end) as b, sum(case when bonus = 'c' then value else 0 end) as c from youview group by account_name 	0.104537899602317
16071709	29736	join city_name for users and for an event	select     meetups.meetup_name,     meetups.url_meetup,     meetups.meetup_text,     users.username,     c1.city_name as meetup_city,     c2.city_name as user_city    from meetups, users, cities c1, cities c2    where url_meetup = ?  and users.id = meetups.author_id  and c1.postalcode = meetups.postalcode and c2.postalcode = users.postalcode 	0.112946893548742
16075556	34899	fetch record according to occurence in like query	select * from table where name like '%tr%' order by locate('tr', name) asc 	0.00111116666320007
16075859	19041	2 rows having unique field and recent date	select t1.* from temp t1       join (select question_id, max(`date`) as `date` from temp group by topic_id) t2         on t1.question_id= t2.question_id and t1.`date`= t2.`date`; 	0
16075880	27380	mysql: compare two tables and list rows that are new?	select partnumber from today_table where partnumber not in (select partnumber from yesterday_table) 	0
16076136	18840	want to get all data from three tables in single query with group by function	select dc.dis_cat_name,         sum(o.price) as total_price,         sum(o.dish_quantity) as total_quantity  from order o      inner join dish d on o.dish_id = d.dish_id        inner join  dish_category dc on dc.dish_cat_id = d.dish_cat_id  group by dc.dish_cat_id; 	0.000135988477624066
16076949	2414	mysql - select all time high score	select userid, name, max(score) as highscore from (     select userid, name, sum(score) as score, date(datestamp) as scoredate     from tablename     group by userid, scoredate   ) dailyscores group by userid 	0.00327194845713743
16077573	3992	counting the total number of rows depending on a column value	select vbatch_id, maxim_pn, bagnumber, ft_lot         , count(*) over (partition by ft_lot) m  from whatever ... 	0
16077696	34302	place a footer row as an header row of a group of rows	select a.rfa_yea ,         a.rfa_idx ,         a.rfa_dsp ,         a.rfa_tpr from table1 a inner join table1 c on a.rfa_idx <= c.rfa_idx and c.rfa_tpr = 'c' group by  a.rfa_yea ,         a.rfa_idx ,         a.rfa_dsp ,         a.rfa_tpr order by min(c.rfa_idx), a.rfa_tpr desc, a.rfa_idx 	0
16077701	14144	oracle 11g: union all with dbms_random	select *    from (     select * from (        select ename, job        from emp1        union all        select ename, job        from emp2     )     order by dbms_random.value() ) where rownum <= 5000 	0.489045879931252
16079045	31941	correct the query to fetch data from three different tables	select users.id as users_id, users.email, aucs.winner_id, aucs.beginner from users left join aucs on aucs.winner_id = users.id left join accounts on accounts.user_id = users.id where aucs.beginner = '1' and accounts.id is null group by users.id having count(aucs.winner_id) = 1 	0.000130537391563534
16079467	5178	get all the ip addresses for an all email addresses in a table	select     a.email,     a.ipaddress,    b.cnt from    (select email, count(distinct ip) as cnt    from record     group by email     having(c>2))b inner join    (select distinct email, ip    from record) a on    a.email = b.email; 	0
16081244	20294	sum amount by type of food in sql server	select tbl_type.type,sum((tbl_item.price * qty) - (tbl_item.price * qty * discount)) as totalafter ,tbl_inv.dateinv from tbl_type,tbl_item,tbl_inv  where tbl_inv.dateinv = '2013-03-26 00:00:00' and tbl_inv.id=tbl_item.id_invoice and tbl_type.id=tbl_item.id_type group by tbl_type.type,tbl_inv.dateinv order by tbl_inv.dateinv,tbl_type.type; 	0.0217606777031065
16081697	10038	sql server script generator cast datetime values from hex	select cast (0x00009cef00a25634 as datetime) 	0.292113109230703
16081906	22919	sum of two columns in mysql	select loger,_date, (schedule_count + segment_count) sum from (   select mguser.userid, mguser.username as loger,      date_format(trschedule.insdate,'%y-%m-%d') as _date,      count(distinct trschedule.scheduleid) as schedule_count,        count(*) segment_count   from   mguser )d 	0.00122634128602868
16082238	4165	getting max date from multiple table after inner join	select  b.id,         b.bookingid,         a.name,         b.departuredate,         b.amount from    table1 a         inner join table2 b             on a.id = b.bookingid         inner join         (             select  bookingid, max(departuredate) max_date             from    table2             group   by bookingid         ) c on  b.bookingid = c.bookingid and                 b.departuredate = c.max_date 	0.0046247559838353
16083278	24235	get only 1st duplicate record oracle	select name,     date from(     select          hsb.name,          hmb.date,         row_number() over (partition by hsb.name order by hmb.date) rnum      from hsb hsb inner join hmb hmb on hsb.hsb_no = hmb.hmb_no         and hsb.hsb_g_no = hmb.hmb_g_no      where          hsb.hsb_kod = '&kod' and          hsb.hsb_date >= '&date1' and          hsb.hsb_date < '&date2' )x where rnum=1 	7.3338243173227e-05
16084484	28908	subtract one hour from datetime rather than one day	select max(d_dtm)- interval '1' hour from tbl1 	0
16085232	23899	oracle: max value column alphanumeric	select max(regexp_replace(dumb_key                , '([a-z][0-9]{2})\.([0-9]{4})\..([0-9]{3})'                , '\2')) from your_table / 	0.00954811664783975
16085351	10041	finding averages timestamp based on two rows	select avg(timestampdiff(second, listed_time, sell_time ) ) as za_avg ... 	0
16085871	19390	get last post on each room with sql	select * from rooms as rm inner join posts as pst on pst.id_room = rm.id where pst.id in (select max(pst.id) from posts                  group by pst.id_room) 	0
16087618	28980	multiple tables ordered group by or distinct sql	select  items.id,  max(items.name) as name, max(item_flags.flagid) as flagid, max(coalesce(item_flags.timestamp, items.timestamp)) as tm from    items left join  item_flags  on  item_flags.itemid = items.id  group by items.id  order by tm desc 	0.0268471050723618
16087929	4606	mysql like matching whole numbers only	select * from level_3  where      date_end = -6  and      ccode = 'gb' and (      responsible like '%|5|%' or      accountable like '%|5|%' or      consulted like '%|5|%' or      informed like '%|5|%'     ) 	0.00468567947103339
16088416	1001	setup a mysql query to display a numeric column in particular order?	select  * from    mytable order by         abs(value - 4.0), sign(value - 4.0) 	0.00288370076109411
16090219	16668	how to find the rank of a particular row value?	select count(*) as rank from tbl where points > '%d' 	0
16090741	38087	sql statement to get daily totals	select      date(created_at) as create_date,     count(id) as total from     data_table group by      date(created_at) 	0.00764429312003031
16090934	32257	how to retrieve statistical sql results with php?	select sum(`arbeidspercentage)` as 'sum_arbeid' ... ... echo $row['sum_arbeid']; 	0.0479679064002382
16091139	36714	self-relationship query with oracle (children doesn't have the same father)	select t.id, t.parent_id from t  start with t.id = 4 connect by prior t.parent_id = t.id 	0.017711845464851
16092860	3171	how do i pivot several different groups of column values in a row into their own single columns?	select n1,n2,n3,a,b from     (select * from t1) p     unpivot (a for acol in (a1,a2,a3))as u1     unpivot (b for bcol in (b1,b2,b3))as u2 where right(acol,1) =  right(bcol,1); 	0
16093609	18605	sql server: indexed view containing greatest row per group	select userid, max(filedate) as maxdate    from files    group by userid 	0.0234207280312969
16093615	5978	aws simpledb contains value	select * from mydomain where email like '%@%' 	0.0305026449670252
16094362	11634	sql - query control record chosen by group by	select * from videos_extended video inner join (     select idmatch, country,         min(case videotype             when 'high' then 1             when 'normal' then 2            when 'low' then 3            else 4           end        ) rank     from videos_extended     group by idmatch, country ) maxtype on maxtype.idmatch = video.idmatch     and maxtype.country = video.country    and maxtype.rank = (       case video.videotype           when 'high' then 1           when 'normal' then 2          when 'low' then 3          else 4        end    ) 	0.088378819813034
16097009	33663	mysql query to get column based on dynamic data	select sum(cost) as totalcost      , sum(sell) as totalsell      , (sum(sell) - sum(cost)) as profit from orders 	0.000519073591340206
16097504	34688	relationship between rows and tables - mysql	select disease_name from (     select  a.disease_name, c.totalcount     from    ms_diseases a             inner join ms_diseases_characteristics b                 on  a.id = b.disease_id              inner join              (                 select  disease_id, count(*) totalcount                 from    ms_diseases_characteristics                 group   by disease_id             ) c on  b.disease_id  = c.disease_id      where   b.characteristic_id in (1,4,5)              group   by a.disease_name                                       ^^     having  count(*) = c.totalcount and                             ^^             count(distinct b.characteristic_id) = 3  ) s 	0.00238927899931199
16098162	27384	selecting the values of existing column as values of new columns with one row shift	select *,  (select top 1 score from [top-concept6]  where [user-name]=t1.[user-name]        and [date]<t1.[date]  order by date desc     ) recent_score from [top-concept6] t1 	0
16098488	39152	initial zeros stripped of when using max in mysql	select  lpad(max( article ), 4, '0') as article from shop; 	0.0361358148638875
16099145	17749	find max group value without using max()/greatest() function	select * from  ( select user,count(posts) cnt from dbtable  group by user ) t1 left join  ( select user,count(posts) cnt from dbtable  group by user ) t2 on (t1.user<>t2.user) and (t1.cnt<t2.cnt) where t2.cnt is null 	0.0484135261425879
16100341	11655	select query char numeric id to order by desc	select myfield from mytable order by  length(myfield) desc, myfield desc 	0.0446162860274924
16100488	19477	select unique records ordered by date	select distinct on (schedule_id) *   from scheduled_transactions   order by schedule_id, transaction_on desc 	0.000107158184116646
16102367	16617	query for roww returning the first element of a group in db2	select * from table1  where id in (select min(id) from table1 group by fld_a) 	0.00282339493705674
16102455	21511	mysql - filtering table based on most current dates	select person_id, max(r_date) as 'r_date' from tablename group by person_id 	0
16102547	18065	ms sql select where ntext-column contains specific hex string	select * from db.table where convert(varchar(max),convert(varbinary(max),convert(nvarchar(max),column_value)),2) like '%3c00%'; 	0.161163941773487
16102710	31352	how to get grouped query data from the resultset?	select * from table order by group, name; 	5.86965148772075e-05
16104035	5647	can a single column of a table be grouped and concatenated into a single cell in sql server?	select  f.facilityid, f.[address], f.countrycode, stuff( (select distinct ', '+e.mail from facility f1 inner join managementdivision md on f1.countrycode=md.countrycode inner join manager m on md.managementdivisionid=m.managementdivisionid inner join employee e on m.managerid=e.employeeid where f1.address=f.address and f1.countrycode=f.countrycode and f1.facilityid=f.facilityid for xml path (''))   ,1,2,'') as email from facility f 	0
16104900	40336	how to create a relationship between records in a sql database?	select     a.person1_id, a.compatibility, a.person2_id,     b.name as person1_name, b.surname as person1_surname, b.age as person1_age,     c.name as person2_name, c.surname as person2_surname, c.age as person2_age from table_compatibility as a left join table_people as b     on a.person1_id = b.id left join table_people as c     on a.person2_id = c.id where a.person1_id = 1 	0.000825831514041448
16106454	40261	how to find which page something starts on in a numbered pagination of sorted results?	select count(*) from users where surname<'current' 	7.83238817363422e-05
16106619	20338	facebook comments on each post	select post.posttext, post.post_id, comment.comt_id  from post  left join comment on      post.post_id=comment.post_id and user.user_id={$userid} group by comment.comment_id ; 	0.000172481876978815
16111329	8484	count and group by for products sold	select   p.productid,   dept1prodcount = count(case when t.productsoldindept1 = p.productid then 1 end),   dept2prodcount = count(case when t.productsoldindept2 = p.productid then 1 end),   dept3prodcount = count(case when t.productsoldindept3 = p.productid then 1 end) from dbo.product as p left outer join dbo.[transaction] as t on p.productid in     (t.productsoldindept1, t.productsoldindept2, t.productsoldindept3) group by p.productid; 	0.00745438017337856
16111700	12460	linq or sql to get records closest to specific time per day per account	select [date],         account,         balance  from   (select [date],             account,             balance,             row_number()               over (                 partition by convert(date, [date]), account                 order by [date] desc) as seqnum      from   balance      where  convert(date, [date]) in (select convert(date, [date])                                       from   history)             and account in (select account                             from   accountcategories)             and [date] <= dateadd(mi, 970, convert(datetime,                                            convert(date, [date])))     ) t1  where  seqnum = 1 	0
16112104	29086	join table on itself subquery	select division_name, business_name, assignment_code, assignment_desc, last_name, first_name, total_salary, assign_fte, birth_year   from table1 join   (select division_name, last_name, first_name, assignment_code, emp_id    from table1) raw on raw.year_time = year_time    where    division_name <> raw.division_name   and last_name = raw.last_name   and first_name = raw.first_name     order by last_name, first_name 	0.333402535183285
16112216	9058	combine 2 rows into one result mysql	select teacher.teacherid, group_concat(unitname) from teacher inner join unit on teacher.teacherid=unit.teacherid group by teacher.teacherid order by teacherid asc 	5.29035032457518e-05
16112339	23196	mysql display empty dates in grouping?	select a.*, b.`count`    from     (    select date(now()) as dt     union all    select date(now()-interval 1 day)    )a    left join     (    )b on (a.dt = b.`date`) 	0.00161205237469254
16113547	9628	wrong result using sum at mysql	select sum(att_member) as total from     (select attendance as att_member      from          (select              id_branch_channel,              id_member,              substring(max(concat(from_unixtime(timestamp),attendance)) from 20) as attendance,              timestamp,              id_event           from view_event_attendance           where id_event = 782           group by id_event, id_member           order by timestamp desc) as temptable      ) as total_attendance_temp 	0.532938678032885
16116086	21723	table data into pivot	select loan,  isnull(principal_d,0) principal_d, isnull(principal_c,0) principal_c, isnull(cash_d,0) cash_d, isnull(cash_c,0) cash_c, isnull(intdue_d,0) intdue_d, isnull(intdue_c,0) intdue_c, isnull(intincome_d,0) intincome_d, isnull(intincome_c,0) intincome_c from  (select loan, amount, acctghead + '_' + d_c as acctgheaddc from t) t pivot (        max(amount) for acctgheaddc in        (principal_d,principal_c,cash_d,cash_c,         intdue_d,intdue_c,intincome_d,intincome_c) ) p 	0.0256324122549693
16116559	17747	sql server : left join results in fewer rows than in left table	select * from tablea as a left join (select * from tableb where realdate = '4/20/2013 12:00:00 am') as b on a.id = b.id 	0.55535631937715
16119906	7346	select rows satisfying some criteria and with maximum value in a certain column	select distinct on (name) id, name, version from metadata where name in ('foo', 'bar') order by name, version desc 	0
16122465	33156	group by data from a text column	select substring(notes, 13, 4) filledby  , count(*) records from invoice where notes like '% ' + @date + '%' group by substring(notes, 13, 4) 	0.00483242618959787
16124550	22718	can i have a loop within an sql select statement?	select t.*  from tests t     join category c on t.category = c.id and c.section = ' . $section . ' order by t.id asc 	0.414572469924622
16130021	33587	sql date and time to datetime	select * from mytable where (date = curdate() and time >= time(now() + interval 1 hour)) or date > curdate() 	0.0147564530046755
16130049	20943	mysql, after an event occurs how to get relevant data from last three time periods	select numbered.* from select filtered.*,             if (id12 = @prev,                 @n := @n + 1,                 @n := 1 and @prev := id12) as position      from           (select     mytable.*, concat_ws('_', id1, id2) as id12           from       (select id1, id2, time from mytable where data > x) as mytablex           inner join mytable           on         mytable.id1 = mytablex.id1 and mytable.id2 = mytablex.id2           order by   id1, id2, time desc)           as         filtered      join (select @n := 0, @prev := '') as setup)      as   numbered where numbered.position < 4 	0
16130851	15679	conditional group by with enum	select right_id,        case max(mode+0)             when 1 then 'denied'              when 2 then 'read'             when 3 then 'edit'         end highest_privilege from mytable where group_id in (1,3) group by right_id 	0.647988023235479
16131219	5460	how can i use order by and group by in sql?	select  sr1 ,       sr2 ,       max(id) from    (         select  case when sender < receiver then sender else receiver end as sr1         ,       case when sender > receiver then sender else receiver end as sr2         ,       id         from    yourtable         where   42 in (sender, receiver)         ) as subqueryalias group by         sr1 ,       sr2 	0.687545019194745
16132793	26761	how to get one value from other categories in php mysql?	select  a.* from    tablename a         inner join         (             select  catid, max(date) max_date             from    tablename             group   by catid         ) b on  a.catid = b.catid and                 a.date = b.max_date 	0
16135218	166	count over multiple columns	select v, count(*) c from (     select one v from your_table     union all     select two from your_table     union all     select three from your_table     union all     select four from your_table     union all     select five from your_table     union all     select six from your_table ) q group by v order by c desc; 	0.0189037963529344
16138034	33924	sql query table of skills	select s.userid,        sum((case when s.skillid = 'business' then votes else 0 end)*0.2 +            (case when s.skillid = 'hacking' then votes else 0 end)*0.8           ) as weightedpoints from skill s group by userid order by weightedpoints desc 	0.0953773947823808
16141276	2375	when #tmp table is null ignore where	select * from foo where (foo_id in (select my_id from #tmp) or not exists(select * from #tmp)) and (foo_name_id in (select my_name_id from #tmp2) or not exists(select * from #tmp2)) 	0.593318558437907
16141796	12956	how to return a specific row to the bottom from a sql query results?	select      [businessmodel], count(*) as total  from dimhotelexpand group by      [businessmodel]  order by      case [businessmodel] when 'lead' then 1 else 0 end asc 	0
16143354	23790	mysql how to select all the questions and its answers from one table	select * from qa order by case parent_id when 0 then id else parent_id end, id 	0
16144240	32771	select username with highest date time	select username from users order by insertdatetime desc limit 1 	0.000822558869640945
16145428	29445	check if a subset exists in sql	select distinct order_id  from orders t1  where not exists (     select product_id      from orders      where order_id = 2   except     select product_id      from orders      where order_id = t1.order_id); 	0.0401447641367832
16145437	23130	count from another table with join	select lendingstatus.status, products.productname, products.serial_number,deposits.amount, lendings.deliverydate, lendings.id as lendingid, products.id as productid, lendingcomments.numlendingcomments from lendings left join products on lendings.productid = products.id left join lendingstatus on lendings.statusid = lendingstatus.id left join deposits on lendings.depositid = deposits.id outer apply ( select     count(*) as numlendingcomments     from         lendingcomments pl     where         pl.lendingid = lendings.lendingid ) as lendingcomments where personid = 561 order by deliverydate desc 	0.00354831201572664
16145508	33995	mysql query for multiple columns to be filtered?	select * from fruits where                   (name ,country) not in ( select 'apple' ,'china' from fruits)  having id < 6 	0.141181481070745
16145544	20976	whats the best way to find the "next but one newest" date in sql?	select top 1 businessdatadate  from mytable  where businessdatadate < (select max(businessdatadate) from mytable) order by businessdatadate desc 	0
16146130	21541	mysql select where number in column	select * from table where find_in_set('123', column); 	0.013142778382385
16146798	11410	date queries in monetdb?	select (current_date-interval 1 day*b) ,a,b from (select '1' as a, 2 as b) as t2; select (current_date-interval 1 day*cast(a as int)) ,a,b from (select '1' as a, 2 as b) as t2; 	0.33830646482999
16147240	24131	sql group by 3 columns with a special feature	select name,         color1,         case color2 when 'nocolor' then '' else color2 end as colour2,         case color3 when 'nocolor' then '' else color3 end as colour3 from data order by        case             when color2 = 'nocolor' then color1             when color3 = 'nocolor' then min(color1, color2)            else min(color1,color2,color3)        end,        case            when color2 = 'nocolor' then ''            when color3 = 'nocolor' then max(color1, color2)            else max(min(color1,color2),min(color1,color3),min(color2,color3))        end,        case color3            when 'nocolor' then ''            else max(color1,color2,color3)        end 	0.279599749926909
16147924	9918	mysql pivot table get first and last rows within grouping records	select     m.account_number,     sum(if(id = t.min_id, balance, 0)) as init_balance,     sum(case when m.description = '1' then m.amount end) as total_banking,     sum(case when m.description = '2' then m.amount end) as total_withdraw,     sum(if(id = t.max_id, balance, 0)) as final_balance from     account m inner join     (         select             account_number,             min(id) as min_id,             max(id) as max_id         from             account         group by account_number     ) as t on     m.account_number = t.account_number where     transaction_date between '2013-04-01' and '2013-04-30' group by     account_number order by     account_number 	0
16150336	16732	fetching data from two tables matching a criteria	select  a.name, b.incomegroupname from    person a         inner join incomegroups b             on a.income between b.minincome and b.maxincome 	0
16152457	40525	search multiple search terms	select sid, sdate, stitle, slocation, skategori, stype, sbody, slist  from job_search  where match(`stitle`, `skategori`, `slist`)  against('{$searchtermdb}' in boolean mode) 	0.471136256972139
16154653	33015	need to pull only last date in table that stores change dates sql / odbc	select somefields from sometables join (select something, max(datetimefield) maxdt from table1 where whatever group by something ) temp on table1.datetimefield = maxdt etc 	0
16154799	5364	sql select if (a="") then change b value	select  columna         , case when columna > 0 then 'greater than 0' else columnb end as columnb  from    table1; 	0.00148459488542868
16155118	18494	delete unique rows in excel file	select column1, column2, column3, ... from table1 group by column1, column2, column3, ... having count(*) > 1 	0.00418697305003235
16155200	13962	sql select items that span entire range of attribute	select * from t  where  tog = 'yes' and val in (select val from t where tog='no') union  select * from t  where  tog = 'no'  and val in (select val from t where tog='yes') 	0
16155624	33874	select xml rows without column header in sql server for xml	select x.query('*')  from   #t  for xml path(''), root('services') 	0.00966174086109659
16157013	33196	mysql - ordering facebook posts, comments, and replies correctly	select facebookfeeds.*, facebookcomments.id as cid, parentid, facebookcomments.userid, facebookcomments.name, facebookcomments.message as cmessage, facebookcomments.createdtime as ccreatedtime from facebookfeeds left join facebookcomments on facebookfeeds.id = facebookcomments.feedid where facebookcomments.accountid = 24 order by facebookfeeds.createdtime desc, if(parentid is null, cid, parentid) 	0.152168983318059
16157196	17154	sql filter null columns	select <column list::filter(where all rows are null)> 	0.0611002685369655
16158801	37355	how to search a mysql blob column for a partial hex string?	select *  from t1 where unhex(hex_col) like '%value%'; 	0.0249621547777209
16160426	36875	sql query count if datediff after grouping	select table1.name, count(table1.start) as #jobs,      sum(iif(table1.enddate - table1.startdate < 30,1,0)) as lessthan30days from table1 group by table1.name 	0.344568609675393
16161612	31667	how to place an array inside a select query	select * from traintable where trainid in {list of train ids to check} 	0.276432799026645
16161932	37652	storing current date time with milisec in varchar column - mssql	select replace(convert(varchar(max), getdate(), 103), '/', '')+ replace(convert(varchar(max), getdate(), 114), ':', '') 	0.000478647034157626
16162199	10175	difference in 2 databases, saving the different lines	select newtable.* from newtable left join oldtable using (id) where oldtable.id is null or newtable.col1 != oldtable.col1 or newtable.col2 != oldtable.col2 or newtable.col3 != oldtable.col3 ... 	0.000192477355999346
16162837	22446	compound query solutions based on no.of rows	select  a.idea_id,         a.idea_name,         count(distinct b.like_id) totallikes,         count(distinct c.comm_id) totalcomment from    td_idea a         left join td_idea_like b             on a.idea_id = b.idea_id         left join td_idea_comment c             on a.idea_id = c.idea_id group   by a.idea_id, a.idea_name order   by count(distinct b.like_id) + count(distinct c.comm_id) desc 	0.0143566204452236
16163398	7803	fetch string of all id from database using query	select group_concat(concat('a', `id`) separator ',') as idlist from `admin`; 	0
16163849	10623	sql query for latest record in one-to-many relation	select     count(distinct parent_id)  from     person  where     date between '2012-1-1' and '2012-1-30' and     status_id=1 	0.00505198225905261
16164977	21886	multiple n:m clauses	select p.id  from    product p,    product_spec s where p.id = s.product_id  group by p.id  having    sum(case when s.spec_id = 1 then 1 else 0 end) > 0 and    sum(case when s.spec_id in (2,4) then 1 else 0 end) > 0 	0.692144830994665
16165068	20683	mysql finding the end position of string within string	select @a := 'the book is on the shelf',      locate('on', @a) as pos_initial,      (locate('on', @a) + length('on')) as pos_final; 	0.000227372525054816
16165837	5701	how to make a valid request?	select f.name as f_name,  max(f.address) as f_address,  max(f.business) as f_business,  max(f.web) as f_web,  max(f.phone) as f_phone,  max(p.name) as p_name  from firm f  left join price p on p.id_service=f.id_service  and p.id_city=f.id_city and p.id_firm=f.id_firm where  f.name not in ( select top $numnext  f.name  from firm f  left join price p on p.id_service=f.id_service and p.id_city=f.id_city  and p.id_firm=f.id_firm where  p.id_firm=f.id_firm and p.id_city='73041' and p.include='1' and p.blocked='0'  and f.blocked='0' and p.id_group='44' and p.id_subgroup='266'  group by f.name order by f.name asc )  and p.id_firm=f.id_firm and p.id_city='73041' and p.include='1' and p.blocked='0' and f.blocked='0' and p.id_group='44' and p.id_subgroup='266' group by f.name order by f.name asc 	0.613619036526416
16166328	3424	finding max date if no null value in enddate?	select profileid, case when endate is null then startdate         else max(enddate) end  as `date` from tablename 	0.000240505616538295
16167452	20709	mysql slow counting primary keys with subquery	select count(*) from users u    left join clients c   on u.id = c.userid    where u.id not in (select userid from clients) 	0.778887639709463
16168395	17997	how to get column names of table at runtime in c#?	select name from sys.columns where object_id = object_id('table_name') 	0
16168820	36822	add 6 items together to give a total, but by not adding their values together	select record_id      ,            case when (photo1 is null or photo1 = '') then 0 else 1 end         + case when (photo2 is null or photo2 = '') then 0 else 1 end         + case when (photo3 is null or photo3 = '') then 0 else 1 end         + case when (photo4 is null or photo4 = '') then 0 else 1 end         + case when (photo5 is null or photo5 = '') then 0 else 1 end         + case when (photo6 is null or photo6 = '') then 0 else 1 end       as total from mytable 	0
16169445	6953	sql- sort items according to their list order	select     id from     table where     id in (414208,479516,4129769,414211,221171,3226290) order by     field(id, 414208,479516,4129769,414211,221171,3226290) 	0
16170139	37545	finding the latest entry in postgres	select  (q).*, (qp).* from    (         select  q,                 (                 select  qp                 from    query_plan qp                 where   qp.queryidx = q.idx                 order by                         ts desc                 limit   1                 ) qp         from    query q         ) qv where   (q).newplanneeded > (qp).ts order by         (q).idx limit   1 	4.98930624261311e-05
16171755	22785	parent child mysql	select t.*,        (case when t4.parent_id is not null then 5              when t4.id is not null then 4              when t3.id is not null then 3              when t2.id is not null then 2              when t1.id is not null then 1              else 0         end) as level from t left outer join      t t1      on t.parent_id = t1.id left outer join      t t2      on t1.parent_id = t2.id left outer join      t t3      on t2.parent_id = t3.id left outer join      t t4      on t3.parent_id = t4.id order by coalesce(t4.parent_id, t4.id, t3.id, t2.id, t1.id, t.id),          coalesce(t4.id, t3.id, t2.id, t1.id, t.id),          coalesce(t3.id, t2.id, t1.id, t.id),          coalesce(t1.id, t.id),          t.id 	0.0122916463736328
16172943	37386	advanced sql query to select distinct data	select  b.* from    table1 a         inner join table2 b             on a.rq_id = b.rq_id         inner join         (             select  rq_id, max(version) max_ver             from    table2             group   by rq_id         ) c on  b.rq_id = c.rq_id and                 b.version = c.max_ver where   a.user_id = 223 and a.is_good = 0 	0.36993747629645
16174628	4555	two "like" queries combined and ordered	select nvl(mytable1.name, '') || nvl(mytable2.name, '') as name,  nvl(mytable1.i, '') || nvl(mytable2.i, '') as i from  (select 1 as i, name from mytable where name like ('string%')) mytable1 full outer join (select 2 as i, name from mytable where name like ('%string%')) mytable2 where (mytable1.name is null or mytable2.name is null) and mytable1.name != mytable2.name order by i, name 	0.0450691040305229
16175298	9516	message system - how to send a group e-mail but only list one e-mail in sentbox	select * from messages where from_email = '$email' and sent_deleted = 'no' group by subject, daterecord order by daterecord desc 	0.000372586870169503
16175497	15148	sql query extract max row	select top 1 * from ( ) a order by predicted desc 	0.0115306395690316
16176015	10075	report in mysql - man sub tables	select count( articleid ) , articleid, date_format( date_purchased,  "%m %y" ) `date` , country, provstate from story_history, user_info where story_history.userid = user_info.userid group by articleid, date_format( date_purchased,  "%m %y" ) , country, provstate order by `date` , country  province 	0.769066807055319
16176470	18042	filtering a many to many (postgresql)	select brand_name  from devices d left join users_and_devices ud on (ud.device_id=d.id) where ud.user_id=1 	0.165012877893056
16176724	16786	get result from mysql with explode	select * from table_name where column_name like '%vga|nvidia%' 	0.0178369050508422
16179167	4655	summ field value from all records	select sum(views)  from   visitors  where  visited_user = '123' 	0
16179791	14699	select from a table where the column value does not exist in another table	select  id, name, lastname from customers as c left join places as p on c.customer_id = p.customer_id where p.customer_id is null 	5.76598405539101e-05
16180589	23739	sql server- update values from one column in same table to another	select * from stuff update stuff set type1 = type2 where type1 is null; update stuff set type1 = type2 where type1 ='blank'; select * from stuff 	0
16184240	33655	order by date multiple tables	select b.name, a.status, a.datetime from statuses a join users b on a.userid = b.id where a.userid in (select c.userid from people c where c.follower = :followerid) order by a.datetime 	0.0233825399782299
16187272	3762	sql query to get the correct results	select s.attributeskuid  from ma_product_attribute_sku s left join ma_product p on p.productid=s.productid where  s.productid='1' and (s.attributevalue='xl' or s.attributevalue='red') group by  s.attributeskuid having count(*) = 2 	0.0945827620062429
16187275	38523	how do i select previous date from my temp #date table in sql?	select max([date]) from #date where [date] <@todays_date 	0.000324023986188765
16187775	33940	getting record against nearest coming date for each distinct pid	select * from active where chq_date in (select min(chq_date) from active where chq_date >= sysdate group by pid) 	0
16187975	8410	getting sum of total items in postgresql	select users.id, sum(items.total) as totalprice  from "orders"  inner join "items" on "items"."order_id" = "orders"."id" inner join "products" on "products"."id" = "items"."product_id" inner join "users" on "users"."id" = "products"."user_id" where "orders"."state" = 'complete' group by users.id 	0.000111151921390024
16188573	4291	how to select on field value in mysql	select coalesce(a.column1,b.column1) as x from a,b; 	0.00238921108420303
16189343	570	many-to-many tags conditional select	select document.id from document     join documenttotag as dt1         on dt1.iddoc = document.id       join tag as t         on dt1.idtag = t.id where t.value in ('tag1', 'tag2', 'tag3')  group by document.id having count(distinct t.value) = 3  	0.280718334783148
16193920	19580	another where clause if there is no result	select sql_calc_found_rows * from products where language = 1 union select * from products where language = 2 and country = 1 and found_rows()=0 union select * from products where language = 2 and country = 2 and found_rows()=0  and not exists(select * from products where language = 1) 	0.216238641798386
16196473	24176	add total of 3 rows for specific id	select      a.studentid,     a.first,     a.last,     c.totalweight from      student a,       (          select                sum(b.maxweight) as totalweight,               b.studentid          from (              select                    max(weight) as maxweight,                   studentid,                   liftid              from                   studentlifts              group by                   studentid,                  liftid          ) b          group by              studentid      ) c where      a.studentid = c.studentid  	0
16196649	24463	sql get info from 2 tables and compare	select u.* from users u left join follow f on u.username = f.followname and f.username = 'derekshull' where f.followname is null 	0
16197783	9308	t-sql table columns to string	select        table_name = s.name + '.' + o.name     , [columns] = stuff((         select ', ' + c.name         from sys.columns c with (nowait)         where c.[object_id] = o.[object_id]         for xml path(''), type).value('.', 'nvarchar(max)'), 1, 2, '') from (     select            o.[object_id]         , o.name         , o.[schema_id]     from sys.objects o with (nowait)     where o.[type] = 'u'         and o.is_ms_shipped = 0 ) o join sys.schemas s with (nowait) on o.[schema_id] = s.[schema_id]  order by        s.name     , o.name 	0.0082368443029523
16198642	21969	need a count of status codes that occurred over last 24 hours	select statuscode as status, count(*) as count   from domain_jobarchive  where datediff(hour, utcbiginttonomtime(endtime), getdate()) <= 24  group by statuscode 	0
16201029	24859	building a sql query that doesn't include data based on hierarchy	select      customer.custname,      code.codedesc from      customer          inner join customercode as poscustomercode             on customer.custid = poscustomercode.custid         inner join code             on poscustomercode.codeid = code.codeid         left join codehierarchy             on poscustomercode.codeid = codehierarchy.dropcode where      codehierarchy.conditioncode not in (       select codeid        from customercode as negcustomercode       where negcustomercode.custid=poscustomercode.custid      )      or codehierarchy.conditioncode is null 	0.0252251354237839
16201761	8396	getting a list of data based on items associated with user	select b.item, b.item_id, a.review_id, a.review, c.category, u.username, c.cat_id  from reviews a inner join items b      on a.item_id = b.item_id inner join master_cat c      on c.cat_id = b.cat_id inner join profile_follow pf      on pf.follow_id = a.user_id where profile_follow.user_id = '{$user_id}' order by a.review_id desc; 	0
16202832	28981	mysql shopping item table with size table	select item_id, item.name, item.price, item.color, sum(size.count)  from item left join sizes  where sizes.count > 0 on sizes.item_id = item.item_id group by item_id, item.name, item.price, item.color 	0.00743183042238717
16205301	25591	mysql getting count of components viewed in given month	select v.vmonth, v.vyear, v.vcount, c.id, concat( c.component_name, ', etc. etc.' ) as component_name from components c join ( select monthname( viewed_date ) as vmonth, year( viewed_date ) as vyear, id_component, count( * ) as vcount        from viewed        group by vmonth, vyear, id_component ) v  on v.id_component = c.id 	5.46823268862525e-05
16205887	17967	mysql combine 3 queries in to 1	select a.sid, a.title, a.time, a.bodytext, a.author, a.url,        d.page_id, d.num_comments  from news.news a  inner join (select sid                from news               where approved=1               order by sid desc               limit $start, $limit) b using (sid) left join comments.pages c on a.sid = c.id left join (select page_id,is_approved,count(*) as num_comments               from comments.comments              where is_approved = 1) d on c.page_id = d.page_id 	0.0349317249345677
16205938	26796	how to join 2 tables that has 2 where clauses	select tp.topic_id , tc.user_id from tbl_topic tp inner join tbl_comment tc    on  tp.topic_id = tc.topic_id    and tp.user_id != tc.user_id 	0.0028100276180738
16206498	9206	sql select string greater than using count()	select studentgroup.gid, max(studentgroup.name) from studentgroup  inner join memberof on studentgroup.gid = memberof.groupid inner join student on memberof.studentid = student.sid group by studentgroup.gid having sum(case when student.career = 'grd' then 1                  when student.career = 'ugrd'then -1                 else 0             end) >0 	0.027941270544086
16206841	32280	in postgresql how do you join two tables select separate information	select *   from subjects s     left join enrollment e on s.subno = e.subno    where sno=9800007 	0.00273549859103163
16207543	27121	generating dates between two dates	select    a.id,    a.start_date+delta dt from    t_dates a,    (      select level-1 as delta       from dual       connect by level-1 <= (        select max(end_date - start_date) from t_dates      )   ) where a.start_date+delta <= a.end_date order by 1, 2 	0.00109964741339755
16207971	14421	select into clause in combined queries	select column_value into l_value from some_table where column_value = 'some_value' union select column_value from other_table where column_value = 'some_value'; 	0.210631696829151
16208309	20838	select query display first and last time	select  day,          date,          department,          name,         min(`time in`) `time in`,          max(`time out`) `time out` from    tablename group   by  day, date, department, name 	0
16208418	32566	sql server - how to get ip of your own server?	select        client_net_address = case when client_net_address = '<local machine>'                                  then '127.0.0.1'                                  else client_net_address                             end       , local_net_address = isnull(local_net_address, '127.0.0.1')     , server_name = @@servername     , machine_name = serverproperty('machinename') from sys.dm_exec_connections where session_id = @@spid; 	0.0512152236334447
16208565	13771	search with comma-separated value mysql	select * from imap_emails inner join customers on find_in_set(customers.email, imap_emails.to) > 0 	0.148451511702813
16208837	24921	mysql resultset should contain rows with common value in columns	select id, section, row,seat,rank from (select id, section, row,seat,        @rank:=if(@lastsection=section and @lastrow=row and @lastseat=seat-1,@rank,@rank+1) rank,       @lastsection:=section,@lastrow:=row,@lastseat:=seat       from tbla, (select @lastsection:='',@lastrow:='',@lastseat:='', @rank:=1)v       order by section,row,seat)s group by rank having count(rank)>=numberofseatdesired; 	0.000159026340387521
16209075	2778	what is the mysql query to get row which column has two specified values (4 , 7)?	select count(tbl1.defect_id)      from defects tbl1 inner join defects tbl2 on tbl1.defect_id = tbl2.defect_id     where tbl1.state = 4 and tbl2.state = 7 	0
16209302	11047	sql - select join and group	select  "col 1", "col 2", "col 3",          listagg("col 4", ',') within group (order by "col 1") as "col 4" from    tablename group   by "col 1", "col 2", "col 3" 	0.511924419798922
16210525	22060	fetch not repeated rows in hibernate	select  distinct t from table t join fetch t ....... 	0.0753109055761962
16213054	27570	inner join 2 tables with same column names	select  achievements.*,         a.name as typename,         b.name as blockname,         c.name as dataname,         d.name as valuename from    achievements         inner join stats a on achievements.type = a.type         inner join stats b on achievements.block = b.block         inner join stats c on achievements.data = c.data         inner join stats d on achievements.value = d.value where   player_id = $id 	0.00159055455260731
16213264	36587	php mysql hierarchy data group_concat	select    group_concat( sp.`slug` order by  sp.`lft` asc separator  '/' )  from     `category` sn, inner join  `category` sp    on sn.lft between sp.`lft` and sp.`rgt` where       sn.`id` =3 	0.410453050099103
16214906	22715	sql query: find each item that costs more than the average and how much more	select i.itemid,         i.description,         i.unitcost - a.avg_cost cost_diff from (select avg(unitcost) avg_cost from items) a join items i on i.unitcost > a.avg_cost 	0
16215293	19099	sql combining two columns one of which is a datetime	select ( analysisno + ' ' + '-' + ' ' + description + ' ' + '-' + ' '       + convert(varchar(20), formdate, 100) ) as columna  from       old_analysis_data  order by       formdate 	4.56752563727231e-05
16217187	40722	sql average by customer per month	select extract(month from date) month,        count(*) purchases,        sum(price*quantity) income,        sum(price*quantity) / count(distinct customerid) from     transactions where     date between i2 and i3 group by extract(month from date); 	0
16218958	2156	select from table as another table with additional characters	select concat(  ",", data,  "," )  from mytable 	0.000521614433999841
16219501	30187	my sql finding a span of dates accross rows	select employee, min(start) start, end from (   select   @end:=if(employee<=>@emp and @stt<=end+interval 21 day,@end,end) end,            @stt:=start start,            @emp:=employee as employee   from     my_table, (select @emp:=null, @stt:=0, @end:=0) init   order by employee, start desc ) t group by employee, end 	0.000360721757026308
16220554	22053	distinct merging select results in mssql keeping order of each results	select  *  from    words  where   word like @keyword or meaning like @keyword  order by          case when word like @keyword then 0 else 1 end         , word 	6.64009718884769e-05
16221019	2489	function to evaluate which rows are not null and return an int	select (case when sun=1 then 1  else 0 end)     +  (case when mon=1 then 2  else 0 end)     +  (case when tue=1 then 4  else 0 end)     +  (case when wed=1 then 8  else 0 end)     +  (case when thu=1 then 16 else 0 end)     +  (case when fri=1 then 32 else 0 end)     +  (case when sat=1 then 64 else 0 end)     as dayofweek from inputtable 	0.0236828122929792
16221860	29997	joining multiple tables and merging data in mysql	select p.p_id, p.p_price, pd.language_id, pd.pd_name, cd.c_id, cd.cd_name,  group_concat(distinct pa.a_text) as attribute from pc left join pd on pc.p_id = pd.p_id left join cd on pc.c_id = cd.c_id left join p on p.p_id = pc.p_id left join pa on pa.p_id = p.p_id and (pa.a_id=1 or pa.a_id=2) where pd.language_id = cd.language_id and (pd.language_id=1 or pd.language_id=2) group by p.p_id, pd.language_id 	0.00328215314665532
16222739	32061	single sign on and database queries	select * from schema.table1 t1 join server2.schema2.table2 t2 on t1.userid = t2.userid 	0.0645592296867782
16223719	27036	showing posts according to the level of authority in mysql	select * from  wall w,   friends f where  w.poster_id = f.user_id and (     access = "all" or     (     f.friends like '[logged_in_user_id%' or     f.friends like '%,logged_in_user_id,%' or     f.friends like '%logged_in_user_id]'     ) ) and f.user_d = w.owner_id and w.owner_id = wall_owner_id 	0.000872690214614738
16224649	10446	transpose grouped dates with mysql	select   max(case when month(date) = 1 then 'jan' else '-' end) as jan,   max(case when month(date) = 2 then 'feb' else '-' end) as feb,   max(case when month(date) = 3 then 'mar' else '-' end) as mar,   max(case when month(date) = 4 then 'apr' else '-' end) as apr,   max(case when month(date) = 5 then 'may' else '-' end) as may,   max(case when month(date) = 6 then 'jun' else '-' end) as jun,   ... and so on through december from table group by year(date) 	0.00916847976605435
16225823	34727	how to group individual dates into months	select distinct      datepart(month, convert (datetime, convert (varchar (10), signindatetime, 101))) as appended_signindate     , go.geographiclocationdescription, count(distinct acd.employeeid) as total_ftl from dbacd.detail.vwrockwelleventagentperformance as acd left outer join dbemployee.summary.vwemployeehistory as eh       on acd.employeeid = eh.employeeid       and acd.signoutdatetime between eh.startdate and eh.enddate left outer join dbemployee.config.vwgeographiclocation as go       on eh.geographiclocationid = go.geographiclocationid where acd.signoutdatetime between '2012-06-01' and '2013-03-31'  group by       datepart(month, convert (datetime, convert (varchar (10), signindatetime, 101)))    , go.geographiclocationdescription order by convert (datetime, convert (varchar (10), signindatetime, 101)), go.geographiclocationdescription 	0.000130525565300466
16227834	3937	mysql query - grouping values and aggregrating	select ta.code_ver,     ta.platform_type,     count(*)  from (select code_ver, platform_type       from   builds        where  runtype like 'test'            and platform_type not like 'total'       group  by code_ver, platform_type, category_name) as ta  group by ta.code_ver, ta.platform_type; 	0.154553459728088
16228882	34619	sql server + selecting records with sub tables items	select [p].[autoid], [posttitle], [photo] from [post] p       inner join [postphotos] pp       on [p].[autoid] = [pp].[postid]        where p.[autoid] in (select [postid] from [favorites] where [userid] = @userid)       and [priority] = 1 	0.00182049762214086
16230279	41227	spliting mysql value with default function in mysql?	select right(name, locate('.', reverse(name)) - 1) format,         count(*) totalcount from   tablename group  by right(name, locate('.', reverse(name)) - 1) 	0.305661609383404
16230554	5934	difficulty in getting data from 4 tables	select t2.kurse_namen,t3.kursraum,t4.kursleiter     from table2 t2,table3 t3,table4 t4,table1 t1     where t2.club_id=t3.club_id     and t3.club_id=t4.club_id     and t1.club_id=t2.club_id     and t2.club_id=35     and t1.tag='monday' 	0.0115482652683529
16232115	40540	ids from count query	select     count(customer) as customernilsen,     group_concat(o_id) as ids from     orders where     customer='nilsen' 	0.00219225522185846
16233257	39329	is it possible to change the values in a database column to lowercase?	select lower (field_id_90) from exp_channel_data; 	0.00736907086741618
16233420	23001	how can i get a list showing the subtraction result between current row id and previous row's id?	select   id,   id - coalesce(                  (select max(id) from foo foo2 where foo2.id<foo.id)                 , 0) as diff from foo order by foo.id desc 	0
16235456	33664	sql query to get count of records in table a and also in table b	select count( * ) from table1 where address in ( select address from table2 ) 	0
16235565	25486	mysql - subquery with multiple fields	select teama, teamb ,user  , quantity from matches m  inner join payments p  on p.idmatch = m.id  where id in   (select idmatch from payments) 	0.384687251200884
16236739	5278	sql query order date by asc, but past entries on end?	select *  from agenda  inner join organizer on agenda.agenda_organizer=organizer.organizer_id order by case when yourdatecolumn > now() then 1      when yourdatecolumn < now() then 2 end asc, yourdatecolumn 	0.000103568773203381
16237082	19554	sql agregate values in one table and combine with counts from another table	select     s.criticality,     count(*) as 'device_count' from     (select distinct criticality from dbo.vtm_duedate) d     inner join dbo.tpm_scan s         on  d.criticality = s.criticality group by     s.criticality 	0
16237778	13527	is there an efficient way to retrieve only a list of years without duplicates from db?	select distinct year(date_field) from table 	0
16237888	50	select 7-digit number in oracle	select regexp_substr(my_column, '\d{7}') from my_table 	0.065015808004062
16238057	26226	select a, b , c group by b with a from the row that has the highest c	select * from (   select name, id, source_trustworthiness   from table   order by 3 desc ) x group by id 	0
16238380	30134	how do i combine these two spatial queries for sql server 2008	select  top 10         *,         geography::point(51, -2, 4326).stdistance(location) * 0.00062137119 from    gas_stations where   location_type = 1 order by         @center.stdistance(location) asc 	0.540687824025244
16238522	8920	round number up to multiple of 10	select ceil(a::numeric / 10) * 10 from (values (100), (111), (123)) s(a);  ?column?        100       120       130 	0.000409379596669804
16239279	33965	retrieve rows where all related data meets specified criteria	select  a.id   from    job a inner join visit b on a.id = b.job_id where   a.paid = 'n' group   by a.id having  count(distinct b.status) = 1 and max(b.status) = 2 	0
16242729	22893	select on same date as timestamp	select ... where date(from_unixtime($your_unix_timestamp)) = date(date_original) 	0.000600699836413886
16243392	4908	classic asp string to display only results beginning with a certain letter	select top 5 * from reviews where artist like 'a%' order by artist desc 	0
16254564	22346	mysql intervals dates remaining	select *  from users  where freetrial=1  and from_unixtime(date_created,'%y-%m-%d') + interval 20 day = current_date() 	0.00345280990183595
16256892	17183	counting number of a certain type of value in a mysql table row	select count(othertype),othertype from tablename group by othertype; 	0
16257890	24978	limit distinct values in mysql	select * from sometable where location in (select distinct location from sometable limit 2); 	0.0397892013850971
16258839	1304	complications building result using group by given data set	select       date,cityid, cityname,hr, sum(hour1) as total from               (                 select  c.date as date,                         isnull(a.id,parent.city1id) as cityid,                         isnull(a.name,parent.city1name) as cityname,                         isnull(parent.factor,1) *                                     b.factor *                           isnull(c.hour1,0) as hour1 ,                         1 as hr                 from    tablea a                  right outer join tableb b on b.city1id = a.[id]                 left  outer join tableb parent on parent.city2id=b.city1id                 left  outer join tablec c on c.cid = isnull(b.city2id,b.city1id)             )   final  where       date is not null and cityid is not null group by    cityid,cityname,date,hr 	0.07298988757579
16260850	14755	sorting by average, then inserting into new table using hive	select a from (select a, avg(b) as avgb from as group by a) as t order by avgb; 	0.000601580521950856
16260862	27341	select by convert data to show them	select * from mp_log where trunc(start_time) = to_timestamp( '20120224', 'yyyymmdd') 	0.00129843259113939
16261934	37593	get modified result from 2 tables	select    t1.id,   t1.name,   max(case when t2.nr_name = 7 then t2.nr_val end) as 'nr7',   max(case when t2.nr_name = 9 then t2.nr_val end) as 'nr9' from table1 as t1 inner join  table2 as t2 on t1.id = t2.table1id where t2.name in (7, 9) group by t1.id, t1.name 	9.84929060844366e-05
16262056	34754	mysql three table join for user favorites system	select c.id, c.price, c.`months left in season`, i.color, i.rating  from currentfruit c left join fruitsinfo i on c.id = i.id left join userfavorites f on c.id = f.id and f.userid = 5 order by case when f.id is not null then 0 else 1 end, c.price desc 	0.459632796121571
16262421	11548	including null values in sql query	select round(avg(round((datediff(now(),dateofbirth)/365),0))) as 'average age',         propertyname  from apartment left join buyer on buyer.propertyid = apartment.propid  group by propertyname union all select round(avg(round((datediff(now(),dateofbirth)/365),0))) as 'average age',         propertyname  from house left join buyer on buyer.propertyid = house.propid group by propertyname 	0.103216370151819
16263620	14292	sql server convert for batting average	select _num, _firstname + ' ' + _lastname as name,    str(cast(_hits as float) / cast(_atbat as float) ,5,3 ) as ba,    _rbi, _triples, _doubles, _singles, _homeruns, _scores,    _strikeouts, _outatbase   from _playerstats order by _num 	0.0441356820735751
16266295	21106	getting average value of a column in group by	select *, count(*),avg(clicks)      from track group by referer order by id desc limit 15 	7.45275875441904e-05
16267377	17883	detect \n character saved in sqlite table?	select *  from mytable  where mycolumn like '%' || x'0a' || '%' 	0.0364320149947033
16270203	30755	join different tables based on condition	select        f.id,       case when userkey=0 then l.name else p.name end as username     from [feature] f     left join [liteuser] l on l.user_id = f.user_id     left join [premium user] p on p.user_id = f.user_id 	0.00113949847963284
16272870	34591	sql query for interchanging rows position as per some condition	select worker.*  from outputreportcustom worker   left outer join outputreportcustom supervisor        on worker.supervisor = supervisor.username   left outer join outputreportcustom supersupervisor        on supervisor.supervisor = supersupervisor.username order by   worker.username,   supervisor.username,   supersupervisor.username 	0.00284659141712123
16273427	35027	how to select rows where a combination of 2 columns is the same	select a.* from  tbl a  inner join  tbl b on a.variant_id =b.variant_id and a.attr_id = b.attr_id where a.id <> b.id; 	0
16274084	25235	tsql, how can i group rows?	select contact, max(phone), max(address), max(email) from table_name group by contact 	0.0693792544650185
16275766	20743	need a sql query to select the date from another table	select   l.date,   if(h.date is null , 'its not present','its present') from    ohrm_leave as l left join ohrm_holiday as h   on l.date=h.date 	0.000437010695099841
16275842	7247	return values for x and y where x-y = max(x-y)	select * from itemcodepricingdetail join ( select     itemcode, max(rrp - [sellingprice]) as bestsaving        from          itemcodepricingdetail        where      ([productgroup] = n'shoes') and ([stock flag] = n'y')                   and (rrp > 0) and ([sellingprice] > 0)        group by itemcode ) as t1  on itemcodepricingdetail.itemcode=t1.itemcode              and rrp - [sellingprice]= t1.bestsaving 	0.00312512268240573
16276189	28281	grails criteria: how to count results from a grouped subquery?	select count(*) 	0.00648684348977036
16276225	33172	mysql query (sequential records...)	select ev.date as event1, ev.user as user1, ev2.date as event2, ev2.user as user2 from  `mt_events` ev join mt_events ev2 on ev2.doc_id = ev.doc_id and ev2.event = 4 and ev2.date =     (select min(el.date) from `mt_events` el      where el.doc_id = ev.doc_id and el.event = 4 and el.date > ev.date) where ev.event = 3 and ev.date like '2013-03%' 	0.0622270893644169
16276621	38024	fectching data in oracle table which has common value in other column in same table	select columna, columnb from yourtable where columnc in (177, 178, 179, 180) group by columna, columnb having count(distinct columnc)=4 	0
16277000	9442	mysql find top results for each group	select  attribute_id, result from    tablename a where          (             select  count(*)              from    tablename b             where   a.attribute_id = b.attribute_id                      and a.result <= b.result         ) <= 5 	0.000137380341955691
16278346	39417	mysql operand should contain 1 column(s)	select * from order where br_id = (select br_id from branch where company_id ='1' ) 	0.666112487531083
16279665	16442	hiveql: find nth value in a one-to-many table	select   e1.userid,   min(e3.eventtimestamp) thirdtimestamp from   events e1 left join events e2   on e1.userid=e2.userid and e1.eventtimestamp<e2.eventtimestamp   left join events e3   on e1.userid=e3.userid and e2.eventtimestamp<e3.eventtimestamp group by   userid 	0.000354050558279621
16279700	33512	get last requirement number run by sss including not run	select  a.req sss,         max(b.datetime) datetime from    sss_req a         left join log_item b             on a.req = b.req group   by a.req 	0.00257083460905217
16280208	33502	how to do a query on a column containing comma separated values	select  b.* from    table2 b          left join table1 a             on find_in_set(b.id, a.category) where   a.category is null 	0
16281892	21735	mysql query, count and sum with two joined tables	select sum(1) as count, sum(total) as total from ( select sum(`url_count`) total from `domains` as domain  left join `backlinks` as link on link.domain_id = domain.id  where domain.id in (         select distinct(bl.domain_id)         from `backlinks` as bl         where bl.tablekey_id = 11         and bl.is_homepage = 1 ) and domain.link_found = 1 and link.is_homepage = 1 group by `domain`.`id` ) as result 	0.00687069302723058
16284357	1488	order mysql results by most common values	select colors from my_table group by colors order by count(*) desc 	0.000664516333270074
16289721	10787	returning results from a one-to-many relationship	select tablea.name, tableb.colors from tablea inner join tableb on tablea.id=tableb.a_id where tablea.id = "given tablea id" 	0.0440445304893339
16290705	10800	how to get the last record in a mysql group	select q.*, t.consultant from (select driver, count(*) as quotecount, min(date) as firstdate, max(date) as lastdate       from t       group by driver      ) q join      t      on t.driver = q.driver and t.date = q.lastdate 	0
16291695	39324	finding unlinked data in a many to many relationship	select p.personkey, pf.description as 'missingfielddescription'   from person p, personfield pf   where pf.personfieldkey not in    (select personfieldkey from personfieldvalue where personkey = p.personkey)   and (pf.isrequired = 1 or pf.islaterequirement = 1) 	0.00659775453328302
16293298	32490	how can i select the record with the 2nd highest salary in database oracle?	select * from (   select e.*, row_number() over (order by sal desc) rn from emp e ) where rn = 2; 	0
16293782	14491	default value for switch in access 2007	select switch(mytable.[mycol]='1','terrestrial', mytable.[mycol]='2','value is two',mytable.[mycol]='3','value is three', true,'error') as columnname from mytable; 	0.784542240363803
16294709	38773	sql: disjoint select to one table	select  person_id from    exam_result where   exam_type = 'type_here' group   by person_id having  count(case when exam_result = 'passed' then 1 end) = 0 	0.017886413463645
16294790	20877	to retrieve values from multiple rows into a single row from a single table under multiple columns	select      e1.id,     e1.university as uvr1,     e1.subjects as sub1,     e1.yearofpass as yop1,     e1.percentmarks as pcm1,     e2.university as uvr2,     e2.subjects as sub2,     e2.yearofpass as yop2,     e2.percentmarks as pcm2,     e3.university as uvr3,     e3.subjects as sub3,     e3.yearofpass as yop3,     e3.percentmarks as pcm3 from      education as e1 left join education as e2     on e1.id = e2.id     and e2.edutype = e1.edutype+1 left join education as e3     on e1.id = e3.id     and e3.edutype = e1.edutype+2 where     e1.edutype = 1 	0
16295759	793	select most experienced person	select  firstname,          lastname,          experience from    player where   experience = (select max(experience) from player) 	0.00616010919789696
16296915	26289	mysql query for latest high scores, not the highest high scores	select s.* from stats as s     inner join     (         select username, max(`stamp`) as `stamp`         from stats         group by username     ) as groupedstats     on s.username = groupedstats.username     and s.`stamp` = groupedstats.`stamp` order by kdr desc limit 10 	0.00159043575138772
16298230	41320	sql query to join two tables	select `date`, `time`, sum(`amt1`) as `table1-amt`, sum(`amt2`) as `table2-amt`  from (select `date`, `time`, amount as amt1, null as amt2  from table1  union all  select  `date`, `time`, null as am1, amount as amt2  from table2) v group by `date`, `time` 	0.129055381105706
16299559	942	get out a mix from both tables in mysql	select * from (select id, place1 place, date1 date         from tbl1        where date1 > curdate()       union       select id, place2 place, date2 date         from tbl2        where date2 > curdate()) tbl12 order by date desc limit 4 	0.00255166137938044
16301144	34884	sql - merge two tables content in one table/view	select id,name,country from dbo.europe union select id,name,country from dbo.usa 	0.000251030335709293
16301467	33656	sqlite query - need to get multiple values from multiple keys	select security_id,ticker from <your table name> where ticker in ('goog', 'nafc', 'aapl', 'prvt') 	0.000751596083019881
16302225	40078	array in the in operator	select into unsolvednodes array_agg(iddestination) from road where idorigin = any(solvednodes); 	0.463555976228225
16302455	12133	concat multiple rows in ssis in one column	select [all_my_other_fields], stuff(              (select '; ' + [customername]                from table2               where table2.productid=table1.productid               for xml path (''))              , 1, 1, '') as customers from table1 	0.00367982008374025
16303040	29954	how do i return rows if concatenated value is within another set of values?	select distinct u.id + u.subid as uniqueid from users as u where (u.id + u.subid) in (     select distinct t.id     from tempvals as t ) 	0
16303490	30718	how do i select clients with no valid email addresses?	select  * from    tblclient where   intpkautoclientid not in         (         select  intfkclientid         from    tblclientcontact         where   stremail > ''         ) 	0.182382811850451
16303708	28836	table has unique rows, however how can i find duplicates of certain columns?	select a.* from yourtable as a inner join (     select id, sequence      from yourtable      group by id, sequence      having count(id)>1) as b on a.id = b.id and a.sequence=b.sequence 	0
16306404	24906	calculate price between given dates in multiple ranges	select   sum(     datediff(       least(end_date + interval 1 day, '2012-09-04'),       greatest(start_date, '2012-08-31')     ) * price   ) from   rooms a where   a.room_type   = 'luxury'     and   a.end_date   >= '2012-08-31' and   a.start_date <  '2012-09-04'; 	0
16307047	28548	joining tables depending on value of cell in another table	select prog.namn, coalesce(vl.comp_name, prog.comp_name), pc.room, pc.kommentar from program as prog left join volymlicenser as vl on prog.regkey = vl.regkey left join dataorer as pc on coalesce(vl.comp_name, prog.comp_name) = pc.comp_name 	0
16307269	17980	mysql conditional select 1 of 2 fields, then group by a combination of the 2 fields	select if(company = 'xyz',billing_state,delivery_state), sum(revenue) from companies group by if(company = 'xyz',billing_state,delivery_state) 	0
16307852	14202	how to convert 3/4 character integer to 24 hour time format and combine with date ?	select dateadd(mi, floor(doctime/100)*60 + doctime%100, docdate) from opor; 	8.09226044712394e-05
16308360	22179	sql query join conditions	select s.name  from tbl_student s inner join tbl_studenthshistory tshsh      on tshsh.stud_pk=s.stud_pk left join tbl_codetails c      on c.code_detl_pk=s.gid where tshsh.begin_date < @begdate     and case when @usearchive = 1 then c.code_detl_pk else 0 end =         case when @usearchive = 1 then s.gid else 0 end 	0.784532660800036
16308508	38105	sql case statements to change values	select uid,   case columnname      when 'col1' then 'columnone'     when 'col2' then 'columntwo'     when 'col3' then 'columnthree'   end columnname,    columnresult from table unpivot (   columnresult   for columnname in (col1,col2,col3) )u; 	0.52066955203439
16308546	5784	select values in one table that don't match another table but also reference another column?	select     positid, trainid  from     posittraining  where     positid = x     and trainid not in (       select trainid from emptraining where empid = a) 	0
16309072	40199	sql server -- strip off non numeric characters	select a,b,case when a<>b then 0 else 1 end from ( select a, cast( left(substring(b, patindex('%[0-9.-]%', b), 100),      patindex('%[^0-9.-]%', substring(b, patindex('%[0-9.-]%', b), 100)+'_' )-1) as int) as b from testab ) aa  where a<>b 	0.0727090806275741
16309789	37214	mysql select unique row entries of a column as columns in a new view or table	select   max(case when field_name='your-name' then field_value end) your_name,   max(case when field_name='your-email' then field_value end) your_email from   yourtable group by   id 	0
16309883	36036	if (subquery) = something select a else select b mysql	select * from   (select 1,2,3) s where   (select count(*) from table where column=value) = 0 union all select   a,b,c from   table where   column=value 	0.432512940817329
16309990	29368	how can i concatenate fields inside of my dataset?	select ppl.firstname + ' ' + ppl.lastname as referredby 	0.015872255401827
16314527	17210	sql find sets with common members (relational division)	select distinct g.groupid, c.classid from @groups g     left join @classes c on g.tagid = c.tagid where not exists (     select *     from @groups g2     where g2.groupid = g.groupid         and g2.tagid not in (             select tagid             from @classes c2             where c2.classid = c.classid         )     ) or c.classid is null 	0.00699127995213865
16315478	11575	how do i subquery many to many in oracle?	select  e.ep_suragate_pk   from    episode e  , episode_actor ea , actor n where   ea.ref_id = e.ep_suragate_pk and     n.act_suragate_pk = ea.act_suragate_pk 	0.550452107671607
16315557	35976	convert 7.5 to 0.075	select   ..   (percentage / 100) from   tablename 	0.694289679521834
16316968	36134	sql query: create category column based on a varchar column in table containing specific values	select *,        case when description like '%colour%' then             1        else             0        end as hascolour,        case when description like '%matt%' then             1        else             0        end as hasmatt,        case when description like '%shiny%' then             1        else             0        end as hasshiny from   table_name 	0
16317169	34278	mysql 5.6 column level query	select 1 as test from all_files_info; 	0.603287781674701
16317802	16484	how to understand count number sqlite rows?	select count(*) from table_name; - (int) getnumberofrecord {     int count = 0;     if (sqlite3_open([self.databasepath utf8string], &database) == sqlite_ok)     {         const char* sqlstatement = "select count(*) from table1";         sqlite3_stmt *statement;         if( sqlite3_prepare_v2(database, sqlstatement, -1, &statement, null) == sqlite_ok )         {             while( sqlite3_step(statement) == sqlite_row )             {                 count = sqlite3_column_int(statement, 0);             }         }         else         {             nslog( @"failed from sqlite3_prepare_v2. error is:  %s", sqlite3_errmsg(database) );         }         sqlite3_finalize(statement);         sqlite3_close(database);     }     return count; } 	0.0059092040334519
16318230	22964	querying a many to many join table with hql	select n from node n         where n.id in              (select n2.id from node n2                  join n2.flags f2                  where f2.visible = :visiblevalue)        and n.id in             (select n3.id from node n3                 join n3.flags f3                 where f3.special = :specialvalue) 	0.378304151501286
16320277	27473	mysql group_concat multiple ids and names (multiple comment rows on multiple posts rows)	select a.post_id, a.post_name, group_concat(concat_ws(",", c.user_id, c.user_name, b.comment_text) separator "|") from posts a inner join comments b on a.post_id = b.post_id inner join users c on b.user_id = c.user_id group by a.post_id, a.post_name 	0
16320312	2415	how to find the nearest date?	select top 1 * from cdcl order by abs(datediff(ms, readtime, <yourdatetime>)) 	0.00159770092139267
16320536	35257	mysql for each distinct, get certain number of entries	select * from (     select        product_id,       customer, (       select count(*) as cnt from products p1            where p1.product_id = p.product_id and                 p1.date < p.date         ) rnk     from         products p     order by       p.product_id, p.date     ) a   where rnk < 3 	0
16321651	17481	selecting multiple rows from one table	select  max(case when name = 'questions' then value end) questions,         max(case when name = 'duration' then value end) duration  from    pq_examsettings 	0
16322133	20315	fetch cumulative sum from mysql table	select year(`time`),         month(`time`),         sum(gross),        (select sum(gross)          from donations          where `time`<=max(a.`time`)) cumulative_gross from donations a group by year(`time`), month(`time`); 	0.000215292961533323
16322578	38161	sql server - possible ways to find max and min in several records	select    convert(date, ordertime) as 'orderdate',    sum(total) as 'total',    min(total) as 'min',    max(total) as 'max' from order group by convert(date, ordertime) order by convert(date, ordertime) 	0.00169422651991812
16322827	16674	how can i get the list of columns from a temporary table?	select  * from    tempdb.sys.columns  where object_id = object_id('tempdb..#mytemporarytable') 	0
16322865	16886	best way to compile a dynamic adodb sql statement based on user input	select *  from table  where (prefix = a or a = '')      and (lastname = d or d = '')       and (middlename = c or c = '')      and (firstname = b or b = '') 	0.0505482615373556
16326004	243	select top records with unique ids	select top(1000) userid, [key], value  from  (select *, rn = row_number() over (partition by userid order by timestamp)   from mytable    where processed = 'false') x where rn=1 order by timestamp; 	0
16326481	9943	need to pull most recent record by timestamp per unique id	select latitude, longitude, unique_id from table inner join (select unique_id, max(timestamp) as timestamp from table group by unique_id)t2 on table.timestamp = t2.timestamp and table.unique_id = t2.unique_id; 	0
16326568	30979	mysql multiple counts and multiple joins	select `categories`.`id`, `categories`.`name`,    count(distinct topics.id) as topics,    count(distinct posts.id) as posts from `categories`  left join `topics` on `categories`.`id` = `topics`.`categoryid`  left join `posts` on `topics`.`id` = `posts`.`topicid` group by categories.id 	0.255514853245037
16329406	17620	select from table where all keys match in table2	select t1.id_recipe, t1.title   from table2 t2 join        table1 t1 on t2.id_recipe = t1.id_recipe  group by t1.id_recipe, t1.title having count(*) = sum(case when t2.id_ingredient in (1,2,3,4,6,7) then 1 else 0 end) 	5.62908720705765e-05
16330502	10982	sorting table with query	select tbl1.title,tbl1.num1,tbl2.num2, concat(tbl1.num1 , "-", tbl2.num2),(tbl1.num1 - tbl2.num2) as result  from tbl1,tbl2  order by result 	0.313408629046403
16334221	7625	(mysql) how do you get the no of unique values in a column from the resultant table of a natural join in a single query?	select count(distinct emp_dept)  from employee  natural join trial 	0
16336257	38428	manipulating data in joins	select c.customerid     , c.firstname      , sh.duedate     , max(p.productid) productid     ,p.listprice     from saleslt.customer c        inner join saleslt.salesorderheader sh         on c.customerid = sh.customerid        inner join saleslt.salesorderdetail sd         on sh.salesorderid = sd.salesorderid       inner join saleslt.product p         on sd.productid = p.productid     group by     , c.firstname      , sh.duedate     , p.listprice order by listprice desc 	0.586633988811168
16336415	30354	mysql left join and sum	select   i.id,   p.amount,   pa.amount from items as i   left join (select            id,            item_id,            sum(amount)    amount          from payments          group by item_id) as p     on p.item_id = i.id   left join (select            payment_id,            sum(amount)    amount          from payment_actions) as pa     on pa.payment_id = p.id group by i.id 	0.761463386870645
16336660	38415	where date is current or over	select * from campaigns where slut >= current_date() 	0.0266467339295749
16338553	21466	how to query for get customer account status in sql server?	select  c.name     ,totalpurchase = (         select sum(p.soldprice * d.qntty)         from orderdetails d          inner join  orderstbl o              on d.orderid = o.orderid         inner join  productstbl p              on p.prodid = d.prodid         where o.custid = c.custid )     ,totalpayments =  (         select  sum(cm.cashvalue)         from    cashmoventstble cm         inner join orderstbl o             on o.orderid = cm.orderid         where  o.custid = c.custid) from    custmrstble c 	0.000407386643777116
16338781	13772	create a table + populate it using another table in one query	select column1, column2, ...columnn     into first_table_name     from second_table_name    [where condition]; 	0.00115190510138234
16339251	34105	group by grouping multiple values as the same group	select       justweeks.`week`,       count(*) as twoweeksum    from       ( select distinct               `week`            from               data ) justweeks       join data           on justweeks.`week` = data.`week`          or justweeks.`week` +1 = data.`week`    group by       justweeks.`week` 	0.00140594010958815
16339718	39814	select from 3 tables with calculating	select * from campaigns c order by (     (select sum(price) from money where ad = c.campaign_id)     /     (select sum(id) from aktivitet where annonce_id = c.campaign_id) )desc limit 0,1 	0.00484316626104196
16339961	21919	unexpected results of join and count in jpa query	select count(tag.tagname)  from tag tag join tag.posts post  where post.user = :user  and tag.tagname = :tagname 	0.799595566298678
16340017	9701	select and order by that column using count from another table	select t.tag_name, count(at.*) as total   from tags t   join article_tags at on at.tag_id=t.tag_id  where t.tag_id in (select tag_id from article_tags at2 where at2.article_id = ?)  group by t.tag_name  order by total desc 	8.51868416524706e-05
16340165	25459	comparision of data available in one table using select query in asp	select sum(case when dir_ind = 'dir' and date between '4/1/2012' and '4/30/2012' then 1 else 0 end ) as 'currentdirect',         sum(case when dir_ind = 'dir' and date between '3/1/2012' and '3/31/2012' then 1 else 0 end ) as 'previousdirect',         rly from  punctualitymain   where  rly in ('cr', 'er', 'ecr', 'ecor', 'nr', 'ncr', 'ner', 'nfr', 'nwr', 'sr', 'scr', 'ser', 'secr', 'swr', 'wr', 'wcr')   and date >= '3/1/2012' and date <= '4/30/2012' group by rly 	0.000558450809908257
16340202	8623	while loops duplicating the results	select distinct id_user, id_ficha, avaria, observacoes, estado, id from fichas, usuarios where id_user = $id and fichas.id = usarios.id_fichas 	0.253427398050773
16340407	19915	select top ... from union	select top n ... from (select top n... from table1 union select top n... from table2) 	0.0143391343492316
16342024	26276	if i need to check if all instances of a tuple are true and return the values of those that are how should i start?	select * from staff where st_position='manager' and st_hiredate >(select max(st_hiredate) from  staff where st_position='supervisor' or st_position='assistant' ) 	0
16343386	21517	inner joining on more than 2 tables	select c.name, c.state from tourcustlink as tcl inner join customer as c on tcl.custid = c.id inner join hotel as h on c.hotelid = h.id inner join tour as t on tcl.tourid = t.id inner join bus as b on t.busid = b.id where h.name = 'hyatt' and b.make = 'hino' 	0.0243860604470747
16344338	4365	adding days and time to a timestamp in mysql	select     t1.id,      t1.start_time,     makedate(year(t1.start_time), dayofyear(t1.start_time)) - interval t2.days_prior day + interval t.2time_open hour_second from     t1, t2 where     t1.t2_id = t2.id 	0.000197776097006302
16344553	39176	quicker way of finding duplicates in sql server	select     count(*) as dupes,     f1.[encounter_num],      f1.[concept_cd],      f1.[provider_id],      f1.[start_date],      f1.[modifier_cd],      f1.[instance_num] from     [dbo].[i2b2_observation_fact] f1 group by     f1.[encounter_num],      f1.[concept_cd],      f1.[provider_id],      f1.[start_date],      f1.[modifier_cd],      f1.[instance_num] having     count(*) > 1 	0.0681421251823379
16345671	33427	sql only equal to day and month not year	select username from table_name  where month(birthday)=month('$birthday')  and day(birthday)=day('$birthday') 	0
16346214	28716	convert varchar2 to date ('mm/dd/yyyy') in pl/sql	select to_char(to_date(doj,'mm/dd/yyyy'), 'mm/dd/yyyy') from emptable; 	0.0229561050421765
16347430	16042	generate a query that show the times that questions get wrong	select question_num, count(cwa_id) total_mistakes   from countwronganswer  group by question_num 	0.000481749369154432
16351293	20052	returning any of multiple case statements in one column	select  case when col1 is not null then '<li>' + col1 + '</li>' else '' end + case when col2 is not null then '<li>' + col2 + '</li>' else '' end + case when col3 is not null then '<li>' + col3 + '</li>' else '' end + case when col4 is not null then '<li>' + col4 + '</li>' else '' end options from table 	0.0854522858060225
16351715	15209	sql: print the address of the publisher who has published only one book	select address from from publ pb  inner join  (select pubname   from   book   group by pubname   having count(*) = 1) b on b.pubname = pb.pubname 	0
16353289	5507	how to select all records after a certain record within groups in sql?	select col1, col2, eventtype, datetime  from thetable a where datetime >  (select  max(datetime) from    thetable sub where   eventtype = 3 and sub.col1 = a.col1 and sub.col2 = a.col2) 	0
16353883	19276	mysql query from hourly to 2 hourly	select date_format(from_unixtime(floor(unix_timestamp(x.time)/7200)*7200),'%y-%m-%d %h:00:00') as `two_hour`      , avg(ph) avg_ph   from ph x where time >= now() - interval 1 day  group      by `two_hour` 	0.00128550031518945
16354515	9115	matching logs with schedule on flexi-time	select * from `office_logs` as log left join `office_schedule` as sched on log.`emp_id` = sched.`emp_id` where log.`emp_id` = 1 order by (abs(sched.`time_in` - log.`log_in`) + abs(sched.`time_out` - log.`log_out`)) asc limit 1; 	0.0915387117030291
16357316	5451	tsql allocate variables from child result set to avoid repeating query	select     @var0 = max( case table_0.field_b when 1 then field_a end )     , @var1 =   max( case table_0.field_b when 2 then field_a end )     , @var2 =   max( case table_0.field_b when 3 then field_a end ) from      table_0 join     table_1      on          table_0.pk = table_1.fk 	0.0232682755022769
16357876	23690	sql query: growth of users per month in percentage	select     month, total,     (total::float / lag(total) over (order by month) - 1) * 100 growth from (     select to_char(created_at, 'yyyy-mm') as month, count(user_id) total     from users     group by month ) s order by month;   month  | total |      growth        2013-01 |     2 |                   2013-02 |     3 |               50  2013-03 |     5 | 66.6666666666667 	0
16358011	10940	sql case when statement to check if field is in temp table	select (case when xsup_id in (select id from @x) then 'yes' else 'no' end) as ins 	0.448849180432164
16358148	8580	selecting the data between two date	select price from tablename where sdate >= '2013-05-01' and edate <= '2013-05-31' 	9.27752595578332e-05
16358713	34706	debugging a sql query	select * from my_table where code='de'   and user_id=100   and user_sub_id=1   and time_used=(     select min(time_used)     from my_table     where code='de'     and user_id=100 and user_sub_id=1   ) order by "timestamp" desc  limit 1;  	0.678813662935028
16361153	32410	grouping duplicates and adding a weight column	select source, target, count(*) as weight from yourtable group by source, target 	0.00537972527617205
16362090	27467	oracle select top n rows based on values	select marks from (   select marks, dense_rank() over (order by marks desc) as marksrank   from yourtable ) where marksrank <= 4 	0
16362910	19364	divide records into groups - quick solution	select i, (row_number() over () - 1) / 50 as grp  from generate_series(1001,1213) i  order by i; 	0.0358372206289868
16363123	6963	transform xml into table variable	select  skill.n.value('@id', 'int') as skillid         , profile.n.value('@id','int') as profileid         , profile.n.value('@targetlevel','varchar(20)') as targetlevel from    @xml.nodes('/skillsprofilestargets/skill') as skill(n)         cross apply skill.n.nodes('profile') as profile(n); 	0.0281667478119077
16364187	304	combining 2 sql queries and getting result set in one	select x.a, y.b from (select * from a) as x, (select * from b) as y 	0.0025756618484131
16364732	33298	left join makes two counts from different tables the same value	select t.id,        t.name,        t.pic,        t.t_id,        (select count(*) from track_plays where a_id = e.id and e.action = 'has uploaded a track.' and e.e_id = t_id) as plays,        (select count(*) from track_likes where id = e.e_id and e.action = 'has uploaded a track.') as likes,        s.status,        g.gig_name,        g.date_time,        g.lineup,        g.price,        g.ticket,        e.action,        e.id,        e.timestamp,        e.e_id   from events e        left join tracks t        on t.id = e.id and e.action = 'has uploaded a track.' and e.e_id = t.t_id        left join status s        on s.id = e.id and e.action = 'has some news.' and e.e_id = s.s_id        left join gigs g        on g.id = e.id and e.action = 'has posted a gig.' and e.e_id = g.g_id  where e.id = '3'  group by e.e_id  order by e.timestamp desc limit 15 	6.42916177704716e-05
16365978	3772	sql if two records exist, choose which one you want to display teradata	select  sorce_claim_id         ,claim_sorce_syst_cd         ,sorce_agrmt_id         ,asgn_sorce_syst_cd from    edw_p.claim_agrmt where   sorce_claim_id = '4513049' and     asgn_sorce_syst_cd = 'clone' union select  sorce_claim_id         ,claim_sorce_syst_cd         ,sorce_agrmt_id         ,asgn_sorce_syst_cd from    edw_p.claim_agrmt where   sorce_claim_id = '4513049' and     asgn_sorce_syst_cd = 'grasn' and     source_claim_id not in (select sorce_claim_id from edw_p.claim_agrmt where asgn_sorce_syst_cd = 'clone') 	0
16366610	18144	using output of one sql query into another	select namecode, name,        (select sum(mo + tu)               from tblfielddays y          where y.namecode in (x.namecode))   from tblnames x; 	0.00206950970927207
16367944	13097	discrepance obtaining values not in inner join by difference	select * from table_b b where exists (select field1 from table_a a where a.field1 = b.field1); 	0.384369503524242
16368142	19522	getting hours worked between sets of dates	select  t1.user_id,          t1.date_event,         min(timediff((t2.date_event), t1.date_event )) as daysdiff from    yourtable t1         left join yourtable t2             on t1.user_id = t2.user_id             and t2.date_event > t1.date_event where t1.object_id = 2 and t2.object_id = 3 group by   t1.user_id,          t1.date_event 	0
16368162	33376	retrieve the last inserted row from each user in database	select * from (   select     users.*,     case when @lst=user then @row:=@row+1 else @row:=0 end row,     @lst:=user   from     users   where     user in ('ina','chris','john')   order by     user, date_ins desc ) s where   row=0 	0
16368946	35068	null column despite using coalesce	select i.item,        r.totalrating, coalesce(r.ratingsum, 0), coalesce(r.averagerating, 0),        re.totalreview from items i join (select count(*) totalrating, sum(rating) ratingsum, avg(rating) averagerating       from ratings       where item_id = '${item_id}') r on (1 = 1) join (select count(*) totalreview       from reviews       where item_id = '${item_id}') re on (1 = 1) where item_id = '${item_id}' 	0.798408672725738
16369464	19104	mysql range select	select * from mytable where start_date < '2013-06-01' and end_date >= '2013-05-01' 	0.0249174885405885
16370814	11158	sql list total orders in descending order	select customer.cid, count(order.orderid) as [# orders] from customer inner join [order] on customer.cid = order.cid group by customer.cid order by customer.cid desc; 	0.000133879999584584
16372198	17669	mysql : timestamp this month, last month and every month	select sum(amount) from yourtable where month(from_unixtime(timestamp)) in/between ...  group by month(from_unixtime(timestamp)) 	0
16372520	40167	mysql select all where value is highest	select *  from   content where  release_version = (select max(release_version) from content) 	0.00031207396985427
16373144	2222	sort comments by rating for the top two rows of the result and the rest by date?	select comment, date, rating from comments order by rating desc limit 2 	0
16373587	31100	using temp column to filter the results	select  * from    (         select  salary-2000 as deducted_salary         ,       *         from                  employeedetails          ) subqueryalias where   deductedsalary > 5000 	0.0337594215290776
16374277	25706	can i use aggregate functions and get individual results in one query with mysql?	select apartment.*, areamax, areamin, cnt from   apartment inner join (     select       idlayout, price, max(area) as areamax, min(area) as areamin, count(*) cnt     from       apartment     group by       price, layout_idlayout) ap_grp   on apartment.idlayout=ap_grp.idlayout and apartment.price=ap_grp.price 	0.278343350999815
16374559	19008	mysql request from two tables when one is empty	select      a.phone,      a.params,     u.email,      u.username,      u.name  from     `account` a left join `users` u on a.customerid = u.id limit 1 	0.00254821065588236
16375033	4348	single query to count by category by joining multiple tables	select  s.[student id] ,       s.[student name] ,       count(c.[course id]) ,       count(case when c.[difficulty level] = 1 end) ,       count(case when c.[difficulty level] = 2 end) ,       count(case when c.[difficulty level] = 3 end) from    students s left join             enrollment e on      e.[student id] = s.[student id] left join             courses c on      c.[course id] = e.[course id] group by         s.[student id] ,       s.[student name] 	0.000792549535274945
16376696	31386	sql: select average grade for all subjects for one student and print an according message	select  a.id, avg(a.grade) avg_grade from    tablename a         inner join         (             select  id, subject, max(date) max_date             from    tablename             where   id = 1                         group   by id, subject         ) b on  a.id = b.id and                 a.subject = b.subject and                 a.date = b.max_date where   a.id = 1                       group   by a.id 	0
16376773	31929	mysql now() with defined time	select * from tbl where datetimefield < date_add(curdate(), interval 2 hour) 	0.130465065087162
16377510	3209	how can i filter a table with duplicate entries to display the rows that exist the most?	select  music_id, genre_id from    tablename a group   by music_id, genre_id having  count(*) = (select count(*) total                      from    tablename b                     where a.music_id = b.music_id                     group   by music_id, genre_id                     order by total desc                     limit 1) 	0
16377632	15421	mysql multiple sum in one query - novice	select category, sum(clicks) as clicks  from wp_cb_ads_manager  group by category 	0.060040221547578
16378291	17327	get all records in sql depending on user input	select      id, name, surname, tittle  from      data  where      location = <input> or     <input> in ('all', 'world', '') 	0
16379509	3593	sql column names and comparing them to row records in another table in postgresql	select *  from questions_table  where questioncolumn in (   select column_name    from information_schema.columns where table_name='dynamic_table' ); 	0
16380085	23545	tips to make one single query from these 3 mysql select queries?	select    sum(invoice_total) as overdue1,    sum(invoice_total *     (now() between invoice_due_date + interval 1 day       and invoice_due_date + interval 30 day)) as overdue2,   sum(invoice_total *     (now() > invoice_due_date + interval 30 day)) as overdue3 from invoices where invoice_status = 'overdue' 	0.00349586308810383
16383221	12636	random selection of rows from sql result set?	select top 4 bookname  from   bookstore  where  recommend = 'true' and        year(pubdate)='2013' order  by newid() 	0.000369731888727328
16385129	13984	mysql two independent tables whose join do not exist in third table	select *  from a  where a.id not in (     select aid from c) 	0.00356339043982737
16385270	10351	column is invalid in the select list when selecting count of children rows	select a.*, b.cnt from a cross apply (select count(*) as cnt              from b              where b.parentid = a.id             ) as b 	0
16386021	29261	select only rowwith highest id value if there are identical column values	select * from people where id in (select max(id) from people group by name) 	0
16386955	2349	select and group mysql table	select   d1.dt,   count(distinct t1.recid) as departures,   count(distinct t2.recid) as returns,   count(distinct t1.recid) + count(distinct t2.recid) as total from (select departure_date as dt from yourtable       union select return_date from yourtable) d1   left join yourtable t1 on d1.dt = t1.departure_date   left join yourtable t2 on d1.dt = t2.return_date group by   d1.dt 	0.0790373181454101
16387483	19259	mysql join that returns none existing records with nulls	select ..., max(m.citizenpositionno) as positionno from   tblcitizens c left join tblcitizentype t   on c.citizentypeid = t.citizentypeid   left join tblmovementhyst m   on m.citizensocialsecuritynumber = c.socialsecuritynumber group by   ... 	0.0956276554153019
16388295	14721	mysql: how to get the max of a sum column?	select  rooms.id room_id, rooms.cnt, booked_dates.cnt, sum(booked_dates.cnt) as booked_sum from    rooms  left join         booked_dates  on      rooms.id = booked_dates.rid         and (booked_dates.start between '2013-05-06' and '2013-05-09') where   rooms.ht = 4         and rooms.id = 138  group by         booked_dates.start order by         booked_sum desc limit   1 	0.000110316253486587
16390795	31819	parse multiple $variable values from single query?	select count(*), vehicletype, vehiclelength  from my_dbase.my_table where arriveday = '08/07/2013'  and process_status = 'completed' and vehicletype  in ('t1','t2','t3','t4') and vehiclelength  in('1','2','3','3') group by vehicletype, vehiclelength  order by vechicletype 	0.00870196859990187
16390961	11750	insert table record with auto generate foreign id	select * from duty; declare @dutyname varchar(20)='cleaning' declare @staffid int declare @maxstaffid int select @staffid=staffid from duty where dutyid= (select max(dutyid) from duty); select @maxstaffid=max(staffid) from staff; print @maxstaffid; insert into duty (dutyname, staffid) select @dutyname, case   when @staffid=@maxstaffid then (select min(staffid) from staff)   else (select min(staffid) from staff where staffid>@staffid) end ; select * from duty; 	0
16391959	27405	sql server query for grouping	select plateno,[1],[2],[3],[4] from  (  select plateno,alerts from sample )p pivot  (  count(alerts)  for alerts in ([1],[2],[3],[4]) )pvt 	0.621844943874944
16392616	17276	string search in mysql query	select *   from table1  where skills like '%mysql%'      or skills like '%c%' 	0.438734919139275
16394150	6637	how to retrieve data from database table with condition in between date?	select `hotel_id`   from test  where `date` between '2013-05-06' and '2013-05-10'    and `qty` >= 2  group by `hotel_id`  having count(*) = (datediff('2013-05-10', '2013-05-06') + 1) 	0
16394854	16194	retrieving a sql some rows having first two with date difference more than 120 seconds	select top 20 * from log where dt >= (select min(dt) from log l              where exists(select * from log l2                           where datediff(ss,l.dt,l2.dt)>120                          and l.dt=(select max(dt) from log l3 where l3.dt<l2.dt)                         ) ) 	0
16396411	2321	linking 2 databases in sql server	select top 100 t1.* from [databse_name].[schema_name].[table_name] as t1 	0.0338528495390404
16397363	5869	not able to fetch data from tables	select       u_m.messageid,u_m.message,u_m.visibility,       u_m_u.sent_to,u_m_u.sent_by,u_m_u.shared_of,       u_m_u.author,u_m_u.adddate,       concat(usr.fname,' ',usr.lname) as sender_name,       p_p.small_pic_path       concat(send_to_usr.fname,' ',send_to_usr.lname) as send_to_name,       send_to_p_p.small_pic_path send_to_pic from user_message_users as u_m_u       left join user_messages as u_m         on u_m.messageid = u_m_u.messageid        left join smsusers as usr         on u_m_u.sent_by=usr.id        left join profile_pic as p_p         on u_m_u.sent_by=p_p.userid        left join smsusers as send_to_usr         on u_m_u.sent_to=send_to_usr.id        left join profile_pic as send_to_p_p         on u_m_u.sent_to=send_to_p_p.userid  group by u_m_u.messageid order by u_m_u.adddate desc; 	0.00296160412959971
16397939	23923	mysql how to select max id group by another id where boolean is false	select max(id) from table1 t group by another_id having sum(`condition`) = 0 	0.000396144173954869
16398159	9244	sorting the sql table using alias column	select acol,aval,cast(acol as varchar(3)) + aval as 'new' from abc order by 3 	0.154988449077173
16399680	22737	sql return n rows per row value	select  * from    (         select  p.*,                 row_number() over (partition by birthcountry order by birthdate desc) rn         from    persons p         ) where   rn <= 10 	0
16400434	41311	for xml path from different tables.	select * from (  select   cast(employeenumber as varchar(9)) as [employee/id],   lastname as [name/last],   firstname as [name/first],   'employee' as [persontype],   email as email  from dbo.employees as sd  where (isactive = 'y')   union  select   cast(employeenumber as varchar(9)) as [employee/id],   lastname as [name/last],   firstname as [name/first],   'contractor' as [persontype],   email as email  from dbo.employees as sd  where (isactive = 'y'  union  select   cast(employeenumber as varchar(9)) as [employee/id],   lastname as [name/last],   firstname as [name/first],   'intern' as [persontype],   email as email  from dbo.employees as sd  where (isactive = 'y')) employees  for xml path('employees') 	0.00325446903818211
16400534	24165	how can i make these two queries a single query with an inner join?	select tpolno, sum(ttsamt) as sum, keyfield1, keyfrobj from pfpostr410, cmrelatn  where      ((ttrnyy=2012 and ttrnmm=3 and ttrndd>=27) or (ttrnyy=2012 and ttrnmm>3) or  (ttrnyy=2013 and ttrnmm<=2) or (ttrnyy=2013 and ttrnmm=3 and ttrndd<=27))     and keyfield1=tpolno     and relroletc=8 group by tpolno, keyfield1, keyfrobj having sum(ttsamt)>=5000 order by tpolno asc 	0.701488567959778
16401569	33896	grouping max values per month	select max(low) as low,max(medium) as medium,max(high) as high,month as mth  from tablename  where month > 0 group by month order by month; 	0
16403165	30775	db2 select multi rows into one row	select userid, avg(number) as average from yourtable group by userid 	0.000120366531405668
16403768	37088	how to get a database datetime value as a date only?	selectcommand="select [tripid] from [bookingmaster]                where ( (cast([pickupdatetime] as date) = @pickupdatetime or @pickupdatetime is null))" 	0
16409534	6834	how create two supersets from different tables	select m.*, n.names, mt.tools from main m left outer join      (select me.mainid, listagg(e.name, ',') within group (order by e.name) as names       from mainemp me join            employees e            on e.empid = me.empid       group by me.mainid      ) n      on m.mainid = n.mainid      (select mt.mainid, listagg(mt.tools, ',') within group (order by mt.tools) as tools       from maintools mt       group by mt.mainid      ) mt      on m.mainid = mt.mainid 	0.000304041696816084
16409905	32500	mysql return first n rows and group the rest	select @rn := @rn + 1 as rn, sum(superficie) as superficie, (case when @rn <= 4 then name else "other" end) as especie from (     select name, sum(superficie) as superficie     from ciclos     join cultivos on id_cultivo = idcultivo     join tbl_especies on id_especie = idespecie     where fecha_cierre is null     group by id_especie     order by superficie desc ) as temp cross join (select @rn := 0) as const group by (case when @rn <= 4 then name else "other" end) order by superficie desc 	0
16410528	35299	the default value of column is missing when using 'select into table' to copy table in sql server	select a.clustered_id a_id, b.clustered_id b_id, b.name   from tablea a   join tableb b on .... 	0
16411257	426	select the difference between two unix timestamps from 2 rows	select  a.idtrip_data,  a.start_time, b.end_time,  (b.end_time - a.start_time) as timedifference from mytable a  inner join mytable b  on b.idtrip_data = (a.idtrip_data + 1) order by a.idtrip_data asc 	0
16412075	1994	range query from month and year	select * from upp where (year=2013) and (month between 4 and 6); 	0
16414053	31767	transaction direction row over partition minipulation	select tin.mstsq   , [date] = tin.[date]   , intime = tin.[time]   , outtime = tout.[time]   , duration = datediff(ss, tin.[time], tout.[time]) from times tin   outer apply (select top 1 *               from times tout               where tin.mstsq = tout.mstsq                 and tin.[date] = tout.[date]                 and tin.[time] < tout.[time]               order by tout.[time]) tout where tin.direction = 'in'   and (tout.direction is null or tout.direction = 'out') order by tin.mstsq 	0.692987419407308
16415258	14003	how to query data where user name is coming several time along with its permission ms sql server?	select u.user_id,u.user_name,u.user_password ,[permissions]= stuff((select ', ' + permissionname      from [userspermission] iup     inner join  permissionslist ipl on iup.permissionid=ipl.permissionid              where iup.user_id = u.user_id       order by  permissionname       for xml path('')), 1, 1, '')  from [user] u where u.user_id='2'; 	0.0025456855449424
16415771	41228	is there a fast way to find where a constraint lies in?	select * from user_constraints 	0.03730436042632
16419189	17	obtain the total uid for each type	select products product_name, count(distinct uid) total_user from purchases group by products; 	0
16419634	32349	how to call parameterized stored procedure for every row in a table without using cursor	select companyid, companyname, dbo.getcount(companyid) 'employees' from tbl_company where... 	0.239684138154263
16420256	15974	join two tables on argument1 ends with argument2	select * from [server1].[dbo].[table_a] a inner join [server2].[dbo].[table_b] b cast(right(a.name, len(a.name)-charindex('_',a.name)) as int) = b.companyid 	0.256074887318099
16421588	17346	find records with more than 1 distinct group	select t.object, count(*) from (select distinct object, group from <yourtablename>) t group by t.object having count(*) > 1 	0.00103405649068603
16421807	39351	combining 8 tables into 1 query	select * from deal d left join dealprice dp on d.id = dp.dealid left join dealmedia dm on d.id = dm.dealid left join storagefile sf on dm.id = sf.binid left join location l on d.id = l.id left join dealcategoryassoc dca on d.id = dca.dealid left join dealcategory dc on dca.categoryid = dc.id left join i18n i on dc.id = i.relatedid 	0.0193982401313377
16423292	23175	how to optimize sql query with multiple selects from the same table?	select      sum ( case when other_same_field  = 0 then same_field else 0 end) as a,     sum ( case when other_same_field  = 1 then same_field else 0 end) as b,     sum ( case when other_same_field  = 2 then same_field else 0 end) as c from same_table where other_same_field in (0, 1, 2) 	0.0169161755865657
16423300	13263	mysql select distinct and determine if only one user_id exists	select 1 from yourtable where poll_id = @yourpoll_id having count(distinct user_id) > 1 	0.000887687299585431
16423850	33252	finding a better way to do a top 1 per group	select f1.id, f1.value from #foo f1 inner join (   select id, max(entry_date) entry_date   from #foo   where entry_date < '1/1/2013'   group by id ) f2   on f1.id = f2.id   and f1.entry_date = f2.entry_date; 	0.00122069396699963
16425423	7747	flatten table into summary report with details in sql (mysql)	select cust, group_concat(concat(start,'-',end) separator ' ') from mytable group by cust 	0.0571193080385973
16425430	22397	sort result of sql query by order of field in where clause of query	select a from frais a where a.libelle = 'fret' or a.libelle = 'douane' or a.libelle = 'transitaire' order by case a.libelle when 'fret' then 0 when 'douane' then 1 when 'transitaire' then 2 end 	0.0398615953712284
16426053	27095	ssrs 2005 column chart: show series label missing when data count is zero	select      professor.name   , professorgrades.score    , student.person_id from (   select professor_id, score   from professor   cross join    (       select 'a' as score      union      select 'b'      union      select 'c'      union      select 'd'      union      select 'e'      union      select 'f'    ) availablegrades  ) professorgrades inner join professor on professorgrades.professor_id = professor.professor_id left join grades on  professorgrades.score = grades.score left join student on grades.person_id = student.person_id and                professorgrades.professor_id = student.professor_id where professorgrades.professor_id = 1 	0.0143783957624343
16427692	19690	mysql query - find dates within range by month and year	select * from events  where org='$org'      and time_start < '$year-$month-01 00:00:00' + interval 1 month      and time_end > '$year-$month-01 00:00:00' ; 	0
16428473	23820	select emp with max sal from each dept	select dept.dname, emp.empno, emp.ename, emp.sal from emp inner join dept on emp.deptno = dept.deptno inner join ( select emp.deptno, max(emp.sal) sal from emp group by emp.deptno ) ss on emp.deptno = ss.deptno and emp.sal = ss.sal order by emp.sal desc 	7.81309097041905e-05
16430234	22076	combine two unrelated tables	select [tblvisits].[visitnumber], [tblvisits].[date], ..., [tblvisits].[comments],        [tblmedications].[dateprescribed], ..., [tblmedications].[expires], [tblmedications].[lot] from [tblvisits] join [tblmedications] on [tblvisits].[patientid] = [tblmedications].[patientid]                      and [tblvisits].[date] = [tblmedications].[dateprescribed] where [tblvisits].[patientid] = '16' order by [tblvisits].[date] 	0.00128059206074133
16433337	5783	i want list of employees, if emp are having commission i want to get comm(numbers) if emp is not having a comm then sorry	select ename, sal,      (case when commission>0 then cast(commission as varchar2(20)) else 'sorry' end) as  comments     from emp     order by comission 	6.61908497758919e-05
16433661	22577	display the number of days between system date and 1st january 2011	select datediff(day, '20110101', getdate()) 	0
16433752	26774	getting news and comments at the same time	select 'n' as type, news_id, header, text, null as date from news union select 'c' as type, fk_news_id as news_id, null as header, comment as text, date from comments order by news_id, type desc 	0.000612834288438383
16434481	25409	how to convert date to iso 8601 in sql-server?	select convert(char(10), '2006-09-08 14:39:41.000',126) 	0.0692458679707801
16435447	10434	sql query base on field of migration time	select members.name , departments.name  from members  inner join (select max(id) migrateid, member_id  from migrate where update_time <= '2013-05-08'  group by member_id )a on members.id=a.member_id inner join migrate on a.migrateid=migrate.id inner join departments on departments.id=migrate.department_id 	0.00742870510857365
16436116	857	how to sort morth and year values in the same field from mysql table using php	select str_to_date(duedate,'%m \'%y') as due  from demo order by due desc 	0
16436516	11764	row with latest value by customer and month	select year       ,month       ,customer_id       ,max(account_type) keep(dense_rank first order by date_changed desc) last_acc  from (   select extract(year from date_changed) as year,          extract(month from date_changed) as month,          customer_id,          date_changed,          account_type    from history   ) group by year, month, customer_id order by year, month, customer_id | year | month | customer_id | last_acc | | 2013 |     1 |         200 |  premium | | 2013 |     2 |         300 |     free | | 2013 |     3 |         100 |  premium | | 2013 |     3 |         200 | standard | 	0
16438964	29853	sql return incremented number	select name,        row_number() over (partition by name order by name) as number from your_table 	0.00747317565331842
16440224	32691	combine data of 2 tables into 1 datatable in memory in winforms	select * from permanentbanks union  select * from temporarybanks 	8.63832945528561e-05
16440374	29434	merge 2 sql queries	select      sum(case when field_id_207 != '' then 1 else 0 end) as total_1,     count(exp_channel_data.entry_id) as total_2  from exp_channel_data  join exp_channel_titles  on exp_channel_titles.entry_id = exp_channel_data.entry_id  and status = 'open'  and exp_channel_data.channel_id = '18'  and author_id = "current_user" 	0.0377297416658498
16443549	21439	how to group by column having spelling mistakes	select soundex(area) as snd_area, min(area) as area_example_1, max(area) as area_example_2 from master group by soundex(area) order by area_example_1 ; 	0.0899485051903512
16445066	21260	date as number in sql	select current_date, current_date - date '1900-01-01' from dual; 	0.0135962212352795
16445490	27553	sql selecting x random rows within top y after ordering	select * from  ( select .... from table  order by price limit x, y ) order by random 	0
16445653	25189	select different values from one table based on another table	select u1.users_id as doctor_id,         u1.name as doctor_name,         u1.surname as doctor_surname,         u2.users_id as patient_id,         u2.name as patient_name,         u2.surname as patient_surname  from doctorpatient as d join userinfo as u1 on d.doctor_id = u1.users_id      join userinfo as u2 on d.patient_id = u2.users_id 	0
16449086	36612	how to combine two tables (with same schema) into a single table with distinct values and indicating which table each row came from?	select distinct name, sum(alpha) as 'alpha', sum(bravo) as 'bravo' from (     select name, 1 as alpha, 0 as bravo from table_alpha     union     select name, 0 as alpha, 1 as bravo from table_bravo ) x group by name 	0
16449723	22731	sql how to select a returned value in the same statement	select p.name, p.guarantor, p2.name from patients p inner join paitents p2 on p2.patid = p.guarantor 	0.00104160540598803
16450772	6319	or and and combination fail mysql	select * from `zk_posts` where `form_id` in (3,6)  and from_unixtime(published, '%y') = 2013  and (`message` like '%search%'  or `description` like '%search%'  or `name` like '%search%'); 	0.720381002786008
16452016	24708	postgresql set a table age based on a date	select name,        dob,        age(dob) as age from guy; 	0
16453327	4186	query to number the results fetched by a mysql query	select t.*, @rn := @rn + 1 as number from table_name t cross join (select @rn := 0) const where uid='4' 	0.00886165602352728
16453950	18398	compare columns from sum(case...end) in the same query	select pc.sub,     sum(if(`sheetstatus`='complete',1,0) as 'complete',     sum(if(`sheetstatus`='not started',1,0) as 'not started',     sum(if(`checksheet` like '%',1,0) as 'total'     if(sum(if(`checksheet` like '%',1,0) = sum(if(`sheetstatus`='complete',1,0),"y","n") as ready from `pc` group by pc.sub with rollup 	9.31205389006941e-05
16454576	1237	stuck with selecting distinct records with sum	select parent,sum(votes) as total from `likes`  where type = 10 group by parent order by parent asc 	0.0200987783502035
16455166	3631	find every item and the most expensive with some condition	select t.sname,max(catalog.cost) from (select  s.sname,c2.cost,c2.sid from suppliers as s, parts as p1, catalog as c1, parts as p2 , catalog as c2 where s.sid = c1.sid and c1.pid = p1.pid and s.sid = c2.sid and c2.pid = p2.pid and ( p1.color =  'red' and p2.color =  'green' ) ) t inner join catalog on t.sid =catalog.sid group by t.sid 	0
16456498	32721	mysql joining tables with special data	select t1.id,t1.q_id,t1.content,t2.w_id,t2.c_id,t2.ranking from table_1 t1 join table_2 t2 on t2.c_id = t1.id or t2.c_id = t1.content where t1.q_id = 2046 and  t2.q_id = 2046 and  t2.ranking >= 0 and  t2.w_id in (22404, 22505)  group by t1.id 	0.119096177802565
16456561	12436	add or subtract from sum based on type of vote in a mysql sql query	select   votedelm,   sum(case when votetype = 0 then 1 else -1 end) as totalcount  from votes  where country = 'us' group by votedelm; 	0
16456595	29538	finding entry with maximum date range between two columns in sql	select    x.name from     (     select         fans.name,         dense_rank() over (order by fans.checkout-fans.checkin desc) as rnk     from         fans      where         fans.checkout-fans.checkin is not null     ) x where    x.rnk = 1; 	0
16457356	37594	get a spinner list from database	select * from " + key_discount       string create_discount_table = "create table " + database_table             + " ("             + key_discount + " integer" + ")";        private static final string database_table = "discounttable"; 	0.000742202858792541
16457406	33535	compare table to itself and get the changed records	select * from prices  where id in (     select p.id from prices p      left join prices p1      on (p1.id = (select max(id) from prices pp where pp.id < p.id))      where p.price != p1.price or p1.price is null ); 	0
16458183	4032	using sql to select records based on date differences	select subq.*,    st_before.quantity quantity_before,    st_after.quantity quantity_after,     st_before.price price_before,   st_after.price price_after from (    select      max_id stock_id,      date_before,     date_after    from   (     select id max_id,max(date) date_after     from stock     group by id    ) mx   join    (       select stock.id min_id,min(stock.date) date_before     from stock      join (        select id,max(date) date_after        from stock        group by id      ) mmx     on stock.id = mmx.id     and datediff(mmx.date_after, stock.date) < 1     group by stock.id    ) mn    on  mx.max_id = mn.min_id    ) subq    join stock st_before    on st_before.id = subq.stock_id    and st_before.date = subq.date_before    join stock st_after    on st_after.id = subq.stock_id    and st_after.date = subq.date_after    order by stock_id ; 	0
16459295	30440	calculation of fuel	select (sum(me)/sum(ste))*24 as cal from [your table name ] where abs(datediff(day,cast(sysdatetime() as date),[your table name ].createddate))<=90 	0.200556149882039
16460045	22798	binary tree mapping database query	select * from zone where userid=xx 	0.276957498712594
16460222	3458	get the row at 60% of the table	select  * from    (         select  row_number() over (order by yt.length desc) as rn         ,       count(*) over () as cnt         ,       yt.*         from    yourtable yt         ) subqueryalias where   rn = round(cnt * 0.60) 	0
16461044	27348	counting same column multiple times, already grouped	select  table2.group_by_this ,       count(case when table1.flag = 'y' then 1 end) ,       count(case when table1.flag = 'n' then 1 end) from    table1  join    table2  on      table1.primary_key = table2.foreign_key group by          table2.group_by_this 	0
16463113	3934	append x amount of results from one query to x amount of results from another (with no foreign key join)	select id, dt from      (select distinct p_id as id from dwh.members) s     cross join     (select distinct date as dt from dwh.product_count) t 	0
16463401	2889	order by desc and group by on cross table query	select ft.* from feeding_types ft     join (         select type, max(id) as id          from feeding_types          group by type     ) t on t.type = ft.type and t.id = ft.id     join feedings f1 on ft.feeding_id = f1.id and f1.data_entry_id = 15758 	0.464732544781215
16464468	21555	postgresql how to limit the maximum display length of a column	select substring(longcolumn for 10) from mytable; select substring(longcolumn from 1 for 10) from mytable; 	0
16465385	39186	mysql two tables two columns count	select count(*) from teams t join schedule s on (s.team_a = t.team_name or s.team_b = t.team_name) 	0.000294048476458029
16465444	33527	sql developer pivot with unknown number of values into one column	select * from (   select id, name, country, state, "date", amount,     case        when type in ('red', 'blue', 'black') then type       else 'other' end type   from yt )  pivot (   sum(amount)   for type in ('red', 'blue', 'black', 'other') ); 	0.000803661605743106
16467366	38950	joining between several tables	select c.name from consultant c join project p on p.consultantid = c.consultantid join customercompany cc on cc.id = p.customerid where cc.address like '%london%' or cc.address like '%berlin%' 	0.00954194176634337
16468883	24261	mysql arbitrary ordering of group by	select fruit, count(*) from table1 group by fruit order by field(fruit, 'banana','apple','orange','peach','grape') 	0.0758951159580816
16469044	40767	finding records sets with group by and sum	select distinct a.groupid from table1 a  where not exists(select * from table1 b where b.hasdata = 0 and b.groupid = a.groupid) 	0.00229484809187275
16469511	15175	duplicate checks with multiple values	select columna, count(*) totalcount from tablea inner join tablea_1 on fid = hid where datecreated > '2013-05-08 00:00:00' group by columna having count(distinct columne) > 1 order by count(*) desc 	0.00306364574996393
16469666	8367	query to get a city by a truckload of possible parameters	select id, article + ' ' + city_name  + ' ' + zipcode  + ' ' + country into summary from cities 	0.00995404944441056
16470884	5926	how to display search results from different categories with php and mysql	select c.category, count(p.id) as productscount  from categories c left join products p on c.id = p.category_id group by c.category     order by c.category 	8.1758574856629e-05
16470910	22510	finding all the rows with 2 conditions using sql (separate tables)	select * from products as p where        exists (select * from rules as r where p.id = r.productid or p.sectorid = r.sectorid) 	0
16472793	11163	complicated sql figuring out how to pull most recent data	select * from order_offer offer  left join order_coupons c on offer.offer_id = c.offer_id and offer.offer_version = c.offer_version where offer.order_id = ? and offer.offer_version in (select max(offer_version) from order_offer where offer_id =      offer.offer_id) 	0.000616492173255313
16474808	39901	grouping data with flot charts	select trunc(unix_timestamp(`timestamp`)/(30*60))*(30*60) as time_chunk,         avg(`volume`) from `ticker`  where compid = 'symbol' and        date(`timestamp`) = (select max(date(`timestamp`)) from `ticker`) group by time_chunk 	0.703209193580858
16475568	26692	get maximum value	select proposalid, title, requestedamount as bugdet, researcherid from proposal where requestedamount = (select max(requestedamount) from proposal); 	0.000328010337642361
16476218	12454	sql: how to select randomly and order by higest	select id,name,point from (select id, name, point from users order by rand()   limit 5) abc order by point desc; 	0.0446425581638203
16477042	29399	conditional sum in sql, get correct sum from another table based on a condition in a field	select  a.store,         coalesce(c.totalsale, b.totalsale) as totalsale from    (select distinct store from table1) a         inner join         (             select  store, sum(sale) totalsale             from    table1             group   by store         ) b on a.store = b.store         left join         (             select  store, sum(sale) totalsale             from    table2             group   by store         ) c on a.store = c.store 	0
16477546	17309	join two tables on the basis of two case obtained from parent table	select * , coins.id as coinid from coins left join coin_owners on coin_owners.coin_id = coins.id left join transfer_detail on transfer_detail.coin_id = coin_owners.coin_id and transfer_detail.transfer_to = coin_owners.current_owner and transfer_detail.transfer_from = substring_index( coin_owners.previous_owner,  ',',  '-1' ) and coin_owners.`ownership_mode` =  'transfer' left join rewards on rewards.`coin_ids` = coin_owners.coin_id  and coin_owners.`ownership_mode` =  'reward' and status =  '0' where coins.id ='".mysql_real_escape_string(trim($_request["coinid"]))."' limit 0,1 	0
16478238	19146	check two tables and find values not in both using sql	select col1 from     (       select col1 from table_a       union all       select col1 from table_b     ) x      group by col1      having count(*) =1 	0.000776396254993743
16478475	18863	mysql pivoting - how can i fetch data from the same table into different columns?	select ( case when ps_month = '04' then ps_target_ecpm               else 0          end ) as april_target_ecmp        ,( case when ps_month = '04' then ps_actual_ecpm                else 0           end ) as april_actual_ecpm        ,( case when ps_month = '03' then ps_target_ecpm                else 0           end ) as march_target_ecmp        ,( case when ps_month = '03' then ps_actual_ecpm                else 0           end ) as march_actual_ecpm     from publisher_stats     join domain         on domain.dmn_id = ps_dmn_id     left join langue         on langue.lng_id = domain.default_lng_id 	0
16479064	23696	sql criteria set to form	select [1 cut wire & cable only].element   from [1 cut wire & cable only]  where  (            [1 cut wire & cable only].product_id = [forms]![new report]![cbproduct_id]         ); 	0.0515326449911328
16480228	10612	sql: how to select one record per day, assuming that each day contain more than 1 value mysql	select * from value_magnitudes where id in  (     select min(id)     from value_magnitudes     where magnitude_id = 234     and date(reading_date) >= '2013-04-01'     group by date(reading_date) ) 	0
16480663	32138	finding targeted columns in an fk	select k_table = fk.table_name, fk_column = cu.column_name, pk_table = pk.table_name, pk_column = pt.column_name, constraint_name = c.constraint_name from information_schema.referential_constraints c inner join information_schema.table_constraints fk on c.constraint_name = fk.constraint_name inner join information_schema.table_constraints pk on c.unique_constraint_name = pk.constraint_name inner join information_schema.key_column_usage cu on c.constraint_name = cu.constraint_name inner join ( select i1.table_name, i2.column_name from information_schema.table_constraints i1 inner join information_schema.key_column_usage i2 on i1.constraint_name = i2.constraint_name where i1.constraint_type = 'primary key' ) pt on pt.table_name = pk.table_name 	0.0130006939670012
16481424	5976	how to threshold with a new defined column in sql	select * from ( select job_name, convert(varchar(10), start_time, 101) as startdate , other_stuff from table ) new_table where startdate = '2013-05-08' order by start_time asc 	0.0132412147702392
16482905	25405	select where month= x and year= y	select * from table where month(yourcolumn) = 5  and year(yourcolumn) = 2013 	5.50197025119016e-05
16484101	35077	count(distinct column1) for only one column of multiple columns	select . . . from (select t.name, t.work,              count(t.id) as targeted,              . . .       from targets t       group by t.name, t.work      ) t left join      (select t.name, t.work,              sum(case when question_id = 96766 then 1 else 0 end) as donated,              . . .       from question q join            targeted t            on t.id = t.id       group by t.name, t.work     ) q     on t.name = q.name and t.work = q.work left join     (select t.name, t.work,             sum(case when (left(events.day,1)="5" and right(events.day,2)="13") then 1 else 0 end                ) as "events this month"     from events e join           targeted t           on e.id = t.id     ) e     on e.name = t.name and e.work = t.work 	0
16484374	19631	how to retrieve results from 'dbcc showfilestats' with odbc?	select convert(float, (sum(f.size) - sum(fileproperty(f.name,'spaceused')))) / sum(f.size) from sys.sysfiles f join sys.database_files db_f on f.fileid = db_f.file_id where db_f.type = 0 	0.00779799655339713
16485911	26347	date format change in sql	select convert(varchar(10), getdate(), 120) 	0.0623271289712515
16485999	12292	extract e-mail from db	select email from users where coins = 0; 	0.0046488293207862
16488247	17106	sql remove part of string	select replace(replace(replace(name, 'dr.', ''), 'ms', ''), '  ', ' ') from ... 	0.019473600664952
16490475	27595	get all where cases in one query	select u.name, w.weapon, w.kills from users u inner join weapons w on w.zp_id = u.id inner join    (select ww.weapon, max(ww.kills) as kills      from weapons ww      where ww.weapon between 1 and 30     group by ww.weapon) k   on w.kills = k.kills and w.weapon = k.weapon 	0.00384627035089477
16491130	37179	select dates within the last week, but not only last 7 days	select * from payforms where yearweek(date) = yearweek(now()); 	0
16493060	38449	how to find the sum of two colums with a quantity value	select sum(quantity * price_paid) as value_sum 	0
16494301	7309	teradara: casting seconds to hours, minutes and seconds	select cast(duration * interval '0000:01' minute to second              as interval hour to second) from (    select cast(8192 as decimal(18,0)) as duration    ) x 	9.87752519851911e-05
16495863	25019	ordering in sql based on 2 fields	select * from overall order by `total_level` desc, `total_xp` desc limit 30 	0.00131137817509193
16497218	23681	how to create a filter in sql through a procedure or function?	select * 	0.733554626093603
16497673	125	how do i return a row from one table with the number of matching id's from a second table in mysql?	select     d.id,     d.creator,     d.date,     d.title,     (select count(*) from r where r.discussion_id = d.id) num from      discussions d 	0
16498389	30988	best approach of mysql query: get records from multiple tables, using an id	select t1.primary_id, t1.id, t1.some_data, t2.some_data, t3.some_data from table2 t2 join table3 t3 on t2.id = t3.id cross join (select * from table1 where id = 22 order by primary_id limit 5) t1 where t2.id = 22 	0
16498410	7232	mysql subtracting values using row selected from min timestamp, grouping by id	select t.user_id, max(t.overall_exp - tprev.overall_exp) from tracker t join      tracker tprev      on tprev.user_id = t.user_id and         date(tprev.timestamp) = date(subdate(t.timestamp, interval 1 day)) group by t.user_id 	0
16498623	29822	joining table issues	select p.id, p.user_id, p.link, u.name, count(v.id) as total_votes from pictures p  join users u on p.user_id = u.id left join votes v on p.id = v.picture_id and v.user_id = ? group by p.id 	0.42905503920985
16499322	1803	sql server - select all top of the hour records	select * from mytable where datepart(mi, dateandtime)=0 and        datepart(ss, dateandtime)=0 and       datediff(d, dateandtime, getdate()) <=60 	0
16499937	3595	how to sort output by the sum of 4 columns? sql/php	select * from your_table order by (column1+column2+column3+column4) desc 	0.000233441138609784
16501375	4718	mysql complex query, user conversation	select  f.* from         (             select  *             from    messages a             where  (least(a.sender, a.receiver), greatest(a.sender, a.receiver), a.timestamp)                      in  (                                select  least(b.sender, b.receiver) as x,                                      greatest(b.sender, b.receiver) as y,                                     max(b.timestamp) as msg_time                             from    messages b                             group   by x, y                         )          ) f where   (:user_id = f.sender and f.sender_deleted != 1)     or (:user_id = f.receiver and f.receiver_deleted != 1) order   by f.timestamp desc 	0.633436776611704
16501460	21361	sql - query condition for future date time	select *  from table where    (    (date = convert(date, sysdatetime()      and starttime > convert(time, sysdatetime()    )     or date > sysdatetime()   ) 	0.039413142118281
16506741	20239	copy one table row to another using sql	select 1, name, age, city from table_b ... 	9.58495583771216e-05
16507020	586	how to put query results into comma-delimited list in a single column	select a.*, group_concat(t2.name) as using_tags from (...inner query unchanged...) a1 inner join articles a using (id) left join article_tags at2 on (a.id = at2.article_id) left join tags t2 on (t2.id = at2.tag_id) group by a.id order by x 	9.43091862444401e-05
16508492	5510	order by date mysql query ordering by day only, not full date	select headline, story, date_format(date, "%d-%m-%y") as displaydate,      name, logo, tpf_parks.park_id, url, alt, description     from tpf_news     inner join tpf_parks on tpf_news.park_id = tpf_parks.park_id      left join tpf_images on tpf_news.news_id = tpf_images.news_id      order by date desc 	0.002520968570976
16509664	10797	how to count new appearances of an item in sql?	select count(1),        to_char(firstorder, 'yyyy-mm-dd') as day from   (select min(created_at) as firstorder,                user_id         from   orders         group  by user_id) first_orders group  by to_char(firstorder, 'yyyy-mm-dd') order  by day desc 	0.000872822864959331
16511417	8762	check if 2 users are in the same room with mysql	select distinct u1.roomid as roomid from   user_to_room u1, user_to_room u2 where  u1.userid = 1 and u2.userid = 2 and    u1.roomid = u2.roomid; 	8.09084977875455e-05
16514155	5946	mysql two subrequest count call	select      sum(case when value = 2 then 1 else 0 end) as bad,     sum(case when value = 1 then 1 else 0 end) as good from _mark_as 	0.30628952763894
16514862	7317	how can i select distinct column based on max datetime (another column) also joining two tables in mysql?	select q.ticker_symbol, t.ticker_name, q.ticker_quote   from (select ticker_symbol, max(created_at) created_at           from ticker_quotes           group by ticker_symbol) m join        ticker_quotes q on m.ticker_symbol = q.ticker_symbol                        and m.created_at = q.created_at join        tickers t on q.ticker_symbol = t.ticker_symbol 	0
16515990	37636	sql server : select same colums count by date	select      *,      (select count(*) from yourtable b where b.l_date<=a.l_date) [count (<=)]  from yourtable a 	0.00215491264250541
16516207	26356	query for selecting itemnumber from table?	select * from inventtable i  inner join texttable t on t.itemnumber=i.refkey where i.id<>2 and i.filename='etable' 	0.00598085452809428
16516283	7056	how to merge 2 queries in 1	select   e.entityid   ,e.entityno    , e.name   , e.shortname     , b.firstname,b.lastname, b.email from [xxx].[xx].[entities] e cross apply (     select p.firstname,p.lastname, p.email       from [xxx].[xx].[people] p       where p.peopleid=          (           select  top 1 a.peopleid           from [xxx].[xx].[entityattentions] a           where a.entityid = e.entityid           order by a.entityattentiontypeid asc         )  ) b where   e.type = 'a'     and e.yearendmonth = 6; 	0.00613745567548465
16519663	21965	select databases which only contain specific table	select name from   sys.databases where  case          when state_desc = 'online'                then object_id(quotename(name) + '.[dbo].[mytable]', 'u')        end is not null 	0.000268267271253734
16520314	35773	sql group by doesn't work when date in two columns	select  a.agent_id, li.date, lo.date from agents a left join agents li on (li.agent_id=a.agent_id and li.log_id = 0) left join agents lo on (lo.agent_id=a.agent_id and lo.log_id = 1) group by a.agent_id, li.date, lo.date 	0.299913644392103
16521979	4303	how to get three count values from same column using sql in access?	select  condition1: iif( ),   condition2: iif(  ),  etc 	0
16522087	35758	showing proper balance amount displaying mysql rows in descending order	select x.*      , sum(y.deposit)-sum(y.withdrawal) balance    from transactions x    join transactions y      on y.bankaccount_id = x.bankaccount_id    and y.date <= x.date  where x.bankaccount_id='$id'   group      by x.date   order      by date desc; 	0.00470838508257947
16523021	15292	tsql - unpivot multiple columns	select [id],        [rownumber],        [year],        sales,        budget from   mytable        cross apply (values (2013, [sales 2013], [budget 2013]),                            (2014, [sales 2014], [budget 2014]) )                       v([year], sales, budget) 	0.126162424686049
16523653	20845	display records using cte in sql	select date, name, typeid from (   select date,           name,           typeid,          dense_rank() over (partition by name order by date) as rnk   from the_table ) t order by rnk, name; 	0.00824654571698434
16524448	34603	how do i query the results of a 'group by' query, all within the same query	select price, amount, type from yourtable where type='a' order by price asc union all select price, amount, type from yourtable where type='b' order by price desc 	0.000474975650457037
16525064	3166	sql server : find duplicates in a table based on values in a single column	select  employeename,  ids = stuff((select ','+ cast(e2.[id] as varchar(10))    from emp e2   where e2.employeename = e1.employeename   for xml path('')  ),1,1,'') from emp e1 group by employeename having count(*) > 1 	0
16525279	9309	combining sql join with count	select count(distinct registered),         count(distinct attended),         sessionid from (select attendantid registered, null attended, sessionid       from registered       union all       select null registered, attendantid attended, sessionid       from attended) sq group by sessionid 	0.459084058593994
16525741	37502	sql cartesian select boxes	select a.city, "city" type from cities a  union all select b.state, "state" from states b  union all select c.schooldistrict, "schooldistrict" from schooldistricts c 	0.52268835600548
16528726	23684	counting answers by day mysql	select date_done, sum(successful = 'yes') from mytable group by date_done 	0.00298875810122045
16528853	13129	mysql summation with condition on individual rows	select   fielda,   sum(case when fieldb = 'x' then fieldc else -fieldc end) as result from my_table group by fielda 	0.0185082441996507
16529576	11876	php mysql votes this month?	select     count(*) as num_votes from     tablename where     year(datecol) = year(current_date) and month(datecol) = month(current_date) 	0.101773510227977
16531226	12073	inner join between three tables	select a.idclientecrm, max(c.falta)  from clientescrmporlistadeclientescrm a inner join clientescrmporlistadeclientescrm b  on a.idclientecrm = b.idclientecrm inner join tareas c  on a.idclientecrm = c.idclientecrm where b.idlistadeclientescrm = 70 and a.idlistadeclientescrm = 58 group by a.idclientecrm 	0.236816477556481
16531355	7944	how to return a count(*) results from a query php	select * from votes where `year`  = year(current_date)   and `month` = month(current_date) 	0.00394837363055585
16531535	4052	sql server: merge data rows in single table in output	select      pf.id,     pf.idnum,     pf.name as pf_name,     pf.address as pf_address,     pf.age as pf_age,     dx.name as d_name,     dx.address as d_address,     dx.age as d_age from ( select     id, left(id, 5) as idnum, name, address, age from     mytable where     right(id, 3) = '-pf' ) pf left outer join ( select     id, left(id, 5) as idnum, name, address, age from     mytable where     right(id, 3) != '-pf' ) dx on pf.idnum = dx.idnum 	0.000719438272323966
16531573	269	select the database, getting all the maximum values ​​of a column	select *  from      table1          join     (select max(v) maxv, value from table1 group by value) t           on t.maxv = table1.v and t.value=table1.value 	0
16534615	9599	how to count records for each day in a range (including days without records)	select rg.day,        count(orders) from   orders_table,       (select trunc(sysdate) - rownum as day        from  (select 1 dummy from dual)        connect by level <= 365       ) rg where rg.day              <=to_date('##/##/####','mm/dd/yyyy')   and rg.day              >=to_date('##/##/####','mm/dd/yyyy')   and order_open_date(+)  <= rg.day   and order_close_date(+) >= rg.day - 1 group by rg.day order by rg.day 	0
16534719	9153	left join with condition from join	select t2.product_id, sum(amount_sold)     from table_1 t1 inner join table_2 t2     on t1.product_id = t2.product_id and t2.sale_date <= t1.max_date     group by t2.product_id 	0.798914598898901
16535569	27598	query db to show count of records done in the morning and the afternoon	select  date,          store,          sum(timestamp between date + interval 10 hour and                                date + interval 13 hour) morning,         sum(timestamp between date + interval 13 hour and                                date + interval 24 hour) afternoon from    walkin2012    group   by date, store 	0.0029591211039851
16536082	31470	substract two alias column in sql server	select a.*,inn-outt as [diffvalue] from     (     select productname,inn=isnull((select sum(orderqty) from purchasing.purchaseinvoicedetail where productfk=production.product.productid ),0),         outt=isnull((select sum(orderqty) from sales.salesinvoicedetail where productfk=production.product.productid  ),0)          from production.product         ) as a 	0.223121883874813
16536571	20711	sql1 to get names and sql2 to get impressions, i need to sort names by impressions	select t1.id as name, count(distinct t2.column1) impressions from table1 t1 left join table2 t2   on t1.id=t2.column2 where t1.column1 = 1   and left(date,10) between '2013-01-01' and '2013-12-31' group by t1.id order by impressions desc 	0.000162910708938085
16538034	32622	list unique values from column based on an id field	select      *,      stuff((select ',' + origfilename        from xyz b where b.uniqueattchid=a.uniqueattchid         for xml path(''),type).value('.','nvarchar(max)'),1,1,'') as [udattch] from abc a 	0
16538037	24643	mysql - get lowest bid from table group by product (results weird)	select  a.* from    tbl_products_bid a         inner join         (             select  product_id, min(bid_price) min_price             from    tbl_products_bid             group   by product_id         ) b on  a.product_id = b.product_id and                 a.bid_price = b.min_price 	0.00465563824636135
16538400	7077	replacing text in a mysql query?	select concat('1000',substring_index('35921 john doe',' ',1))x; + | x         | + | 100035921 | + 	0.43852273192145
16539441	11282	appending trailing zeros to a oracle number in oracle	select rpad(to_char(atm_card_nbr),16,'0') as new_atm_nbr,        atm_card_key  from atm_card_dm    where length(translate(to_char(atm_card_nbr),'1234567890.-','1234567890'))=14; 	0.0324127919928502
16539648	5314	select query with a condition in sql	select a.id from tablea a where a.id not in (     select b.id     from tableb b     where b.tno = 2 ) 	0.496657539100408
16540120	34036	sql query: how to group items correctly?	select t1.post_title,        max(case when meta_key='name1_class' then meta_value end) as name1,        max(case when meta_key='url1_class' then meta_value end) as url1   from (select pm.post_id as id, pm.meta_key, pm.meta_value, p.post_title, t.slug          from wp_2_postmeta pm         inner join wp_2_posts p on pm.post_id = p.id         inner join wp_2_term_relationships tr on tr.object_id = p.id             inner join wp_2_term_taxonomy tt             on tr.term_taxonomy_id = tt.term_taxonomy_id         inner join wp_2_terms t on t.term_id = tt.term_id         where post_type='footercolumn' and post_status='publish' and pm.meta_key                like '%class') t1 	0.423137496177849
16540995	37219	duplicate mysql rows	select d1.id,d2.id from datesbooked d1    inner join datesbooked d2 on        d1.cottageid=d2.cottageid       and d1.from = d2.from       and d1.to = d2.to       and d1.id<d2.id 	0.00666975344561343
16543785	7550	select values based on distinct dates	select * from table name group by date,number 	5.37246619176451e-05
16544801	15382	sql: date difference between two separate rows	select id, max([date a]) as 'maxdate' from table group by id 	0
16546233	14844	t-sql to xml - can multiple values per attribute be listed on their own line?	select     'fruits' as [attribute/@name],     '' as [attribute],     'apple' as [attribute/value],     '' as [attribute],     'orange' as [attribute/value],     '' as [attribute],     'grape' as [attribute/value] for xml path (''), root('customproduce'), type 	0
16547224	26764	sql: how to select ids according to a condition?	select * from table where id not in (select id from table where if = 1) 	0.000459498068134244
16547247	31098	return records from a table which have a match on all records of another table	select c.id from customer c inner join orders o on o.cust_id = c.id inner join product p on p.id = o.prod_id group by c.id having count(distinct p.id) = (select count(id) from product) 	0
16547990	4088	creating a sql query with two tables	select a.name ,        a.account ,        a.borrowed  - coalesce(sum(p.paymentamt),0) as [still owes],        coalesce(sum(p.paymentamt),0) as paid,        a.borrowed from          accounts  a        left join payments p        on a.id = p.acctid  group by        a.name ,        a.account ,        a.borrowed 	0.188354470315785
16550325	19894	sql server - generate script without primary key	select 'insert into table (field1) values (''' + field1 + ''')' from table 	0.0852054912839353
16550703	33199	sql get the last date time record	select filename ,        status   ,        max_date = max( dates ) from some_table t group by filename , status having status = '<your-desired-status-here>' 	0
16552032	11443	how to create a subquery	select    ct.title as title,    t.phoneid as imei,   t2.tid from transactions as t inner join exp_channel_titles as ct on ct.entry_id = t.restaurant_id inner join (   select et.imei as imei, max(from_unixtime(et.timestamp)) as tid   from exp_terminal_log as et   group by et.imei ) as t2 on t.phoneid = t2.imei where t.cardid != '88888888'    and t.cardid > 0   and ct.status= 'open' group by ct.entry_id; 	0.301671406170528
16555066	33928	mysql concat and search on multiple tables	select p.* from products as p  left join categories as c on p.category_id = c.category_id  where p.description like '%rainbow%'     or c.category like '%rainbow%' group by p.product_id 	0.11663230115977
16555523	9178	how to search where some data is in table 1 and other data is in table 3 with both having a uuid the same	select  a.* from    salestable a         inner join customertable b             on a.customeruuid = b.customeruuid         inner join contracttable c             on b.contractuuid = c.contractuuid where   c.variabled = 'valuehere' 	0
16557783	27987	sql difference calculation from two table or views	select s.suplist , (s.workdays - isnull(a.absentdays,0)) as presentdays from supervisertable s left join absenttable a on s.suplist=a.suplist 	0.00336699372953892
16560054	38032	using dynamic subqueries as column header	select * from table1 t1 inner join table1 t2 on t1.foo != t2.foo where t1.bar = t2.bar  and t1.baz = t2.baz 	0.703866590087752
16560105	34909	getting total elapsedtime (time) in sql	select sum(time_to_sec(elapsedtime)) from tablename  where transactioncode in ('code1', 'code2') and timefiledate = `date` 	0.00441313500841902
16560264	5482	search query to compare a particular word from a string to values of another string in mysql	select users_profile.*, users_profile2.id as other_id,    users_profile2.language as other_lang from users_profile   inner join users_profile as users_profile2 on     users_profile.language rlike        replace(users_profile2.language,",","|")      and users_profile.id != users_profile2.id; 	0
16560310	41030	how to get sql string result from stored procedure and save it in c# windows application string variable	select @result 	0.402555077465894
16560346	11117	mysql - inner join - take only the last id from the second table	select a.id,         (select max(l.date)         from logs l         where l.hash_key = a.hash_key) date from articles a 	0
16561531	38871	using in with multiple columns	select col3,col1,col4 from table where exists (     select 1     from (values         ('item1')         , ('item2')         , ...         , ('itemn')     ) as it(m)     where it.m in (col1, col2, ...) ) 	0.062611992722378
16562043	26145	how to get initials from fullname in mysql?	select   fullname,   concat_ws(' ',     substring_index(fullname, ' ', 1),     case when length(fullname)-length(replace(fullname,' ',''))>2 then       concat(left(substring_index(fullname, ' ', -3), 1), '.')     end,     case when length(fullname)-length(replace(fullname,' ',''))>1 then       concat(left(substring_index(fullname, ' ', -2), 1), '.')     end,     case when length(fullname)-length(replace(fullname,' ',''))>0 then       concat(left(substring_index(fullname, ' ', -1), 1), '.')     end) shortname from   names 	0.00353815430838049
16562195	33920	multiple subqueries when combined return too many results	select     v. [analysisname],     sum(case when [company] = 'money' then 1 else 0 end) cmttrans,    sum(case when [company] = 'forex' then 1 else 0 end) cfltrans from vmaincusttrans as v group by v.[analysisname] order by v.[analysisname] 	0.770747422717057
16563116	29447	how to count the number of records from an union operation in sql?	select count(column1) from table1 where condition1 or condition2 	0.000154091161220026
16564607	1910	mysql, concat on specified length	select case when length(mystring) <= 10 then        mystring    else        concat(left(mystring, 7), '...')    end as mycol   ... 	0.163417914556728
16565656	14823	selecting two fields recursively for each month	select     username, month(start), sum(bytes_send+bytes_received) from     mytable where     start >= '20130101' and start < '20140101'     and     username = 'admin' group by     username, month(start) 	0
16565662	34211	select multiple columns from multiple tables?	select p.prdnum, s.brand, q.data from ptable p join stable s on p.prdnum = s.prdnum join qtable q on p.prdnum = q.prdnum where q.pid != 2 	0.000515283155833972
16566491	29898	mysql select count distinct	select mobility_theme, count(*) as numusers from (select ca.user_id, min(co.mobility_theme) as mobility_theme       from courses_apply ca left join            dy41s_courses co            on ca.course_id = co.id        where ca.submission is null and ca.`call` like  '1b'        group by ca.user_id      ) caco group by mobility_theme 	0.0708312656285195
16567722	22071	how to search data using "like" in sql server	select   asicccodeid,asiccdescription              from     asicccodemaster  c              where    c.asiccdescription like '%boat%' order by case when c.asiccdescription like 'boat%' then 0 else 1 end, c.asiccdescription 	0.69211057181163
16568353	20256	sql query to retrieve sum in various date ranges	select sum(totalprice), year(date), month(date) from sales group by year(date), month(date) 	0.000151337933005731
16570582	37566	mysql newest 5 per group with fulltext search	select * from (select @rn:=if(@pv=source, @rn+1, 1) as rid, 'a' t_name,id,title,@pv:=source,description,date,fullindex  from table1 a1 join (select @pv:=0, @rid:=0)tmp where match (fullindex) against ('+bool' in boolean mode) order by source, date)a where a.rid <=5; 	0.0167770607981045
16570774	15051	pulling timediff from created columns in mysql	select  date_format(punchdatetime, '%w') day, max(case when punchevent = 'clockin' then date_format(punchdatetime, '%t') end) as 'clock in', max(case when punchevent = 'breakout' then date_format(punchdatetime, '%t') end) as 'break out', max(case when punchevent = 'breakin' then date_format(punchdatetime, '%t') end) 'break in', max(case when punchevent = 'clockout' then date_format(punchdatetime, '%t') end) 'clock out', (timediff(max(case when punchevent = 'clockout' then date_format(punchdatetime, '%t') end), max(case when punchevent = 'breakin' then date_format(punchdatetime, '%t') end))) as total from timeclock_punchlog where empid = 456 group by date_format(punchdatetime, '%w') order by punchdatetime; 	0.000868218509336671
16571101	16322	comparing column values between two tables	select distinct bundle_lanes.cable_no  from bundle_lanes left outer join cabletypes on       (bundle_lanes.cable_no = cabletypes.cable_no)  where cabletypes.cable_no is null order by bundle_lanes.cable_no 	0.000118526751287837
16571272	33959	mysql join query on multiple tables	select * from contacts left join work on contacts.con_work_id = work.work_id left join country c1 on contacts.con_country_id = c1.country_id left join country c2 on work.work_country_id = c2.country_id 	0.227840429643412
16573301	11102	t-sql list tables, columns	select * from mydatabasename.information_schema.columns order by table_name, ordinal_position 	0.00570182373936963
16575455	13301	count only where certain fields are unique? (multiple group bys)	select count(distinct username) as dailycount from highscores where date(date) between curdate() - interval 3 day and curdate() group by date(date) 	0
16576286	6720	sqlite getting empty result from any query	select 0 where 0; 	0.0439362217798927
16576778	15856	get distinct combinations along with count	select col1, col2, col3, count(*) as ct from   tbl group  by 1, 2, 3 order  by 1, 2, 3; 	0.000176917459257025
16576973	13701	sql query that selects all rows with a certain date (the most recent date, prior to a given date)	select *     from <table name here>     where asofdate = (select max(asofdate)                               from <table name here>                              where asofdate <= <input date here>) 	0
16577591	2781	combine multiple rows for unique column into single row	select computer,        max(case when date = '2013-05-15' then returncode end),        max(case when date = '2013-05-16' then returncode end),        max(case when date = '2013-05-17' then returncode end) from returncodes group by computer 	0
16577845	37751	sql query of sum and count from multiple tables	select staff,     sum(finalsellingprice) as gross,     sum(finalnett) as cost,     sum(finalsellingprice - finalnett) as profit,     sum(adultno+childno) as pax,     count(1) as bookings from blist b inner join bhandle bh on b.bookingid = bh.bookingid where b.bookingdate >= fromdate     and b.bookingdate <= todate     and bh.ticketingstatus = 'cp' group by staff; 	0.00268001882516853
16578038	662	avoid repeating records displaying in mysql / php	select distinct country from dealers 	0.0349512899758152
16579210	29318	how to order tag filtering search result	select count(pid) as matches from tagged_table where tid in (1,2,3,4) order by matches desc 	0.148051213365867
16579229	15960	sql query to fetch results via comma seperated	select object_id,  group_concat(event_level) as meta_value,  name, event_level, event_temp_id from  wp_em_meta, wp_terms, wp_em_events  where wp_em_meta.meta_key = 'category-image'  and wp_em_meta.object_id in ($eventtid) and wp_em_meta.object_id = wp_terms.term_id  and wp_em_meta.object_id = wp_em_events.event_temp_id group by object_id 	0.00238135118545841
16581229	30508	get record according to year range	select * from tblstudent s where @year >= datepart(year, startdate) and @year <= datepart(year, enddate) 	0
16587386	1528	how to filter xml nodes in sql server?	select c.value('@tray','varchar(max)') from @l_xml.nodes('/xdoc/doc[@type = ("q", "s")]') t(c) 	0.152854437547254
16588027	3856	unlike rows in tables with no relation	select     * from     table1 t where t.employerno not in (     select         a.employerno     from         table1 a inner join table2 b         on a.employerno = b.payer_id) 	0.0178137254547865
16588149	21166	how to create view with variables inside?	select      u.[id]     , g.[naam]     , w.[omschrijving]     , u.[datum]     , case           when u.status = 1 then convert(varchar,100)+'%'            when u.status = 0 then convert(varchar,100)+'%'            else null       end as 'status'     , w.[norm]     , w.id from [werkzaamheden] w         right join [uitgevoerd] u on u.[taak] = w.[id]         full join [gebruikers] g on g.[naam] = u.[naam] where     u.status = 0 or u.status = 1 or u.status is null 	0.672436671129238
16588237	37049	postgres: detect orphaned rows	select f.* from     file f     left join     userfile u on f.id = u.file_id where u.file_id is null select f.* from file f where not exists (     select 1     from userfile u     where u.file_id = f.id ) 	0.0554225662612295
16590671	16917	in hive, count time between two time	select v.begin_time as "time",        count(*) as "visitors"   from visits v   join visits o        on v.begin_time between o.begin_time and o.end_time  group by 1 	0.00467929230962814
16592213	35556	can't get data from database since i linked my tables (php)	select `user_id`,`username` from `users` select user_id, username from user 	0.00929891305121458
16593906	6226	oracle sql query to get column values without space	select test_col from a where regexp_like(test_col, '^[^ ]{2}.*$'); 	0.00851547852596572
16595023	16599	conditionally return column values from a joined table - oracle	select dt.name,         dt.age,        coalesce(mt.address, dt.address) from datatable dt   left join mappingtable mt           on mt.name = dt.name; 	5.43535876929286e-05
16595915	1226	select row by id except a variable number from the end	select `user_id`,`message`,`created_time`  from ".$supportmessagestable."  where `ticket_id`=?  order by created_time desc limit 11, 10 	0
16596289	9473	how to use a subquery to get the result i want	select   c.idclientecrm,          ifnull(t.fcierre, t.falta) ultima_tarea,          d.nombre from     tareas c     join (            select   idclientecrm,                     max(fcierre) fcierre,                     max(falta  ) falta            from     tareas            group by idclientecrm          ) t using (idclientecrm)     join resultadosdetareas d using (idresultadodetarea) where    if(t.fcierre is null, t.falta=c.falta, t.fcierre=c.fcierre) group by c.idclientecrm 	0.0448239967177174
16596508	20995	how to get distinct column data on the basis of latest date time from sql server 2008 r2	select * from (     select *,rn=row_number() over (partition by username order by logindate desc)     from login ) x where rn=1 order by username; 	0
16599136	21696	sql query for sales report by date	select marketer, date_set, count(id)  from lead group by marketer, date_set; 	0.0589726182776355
16606247	28644	combine data from multiple tables in a single xml tag	select tb1.rndstring+' '+cast(tb2.time as varchar(5))  from tb1,tb2 for xml path ('strconcat'), root ('data') 	0.00012258158317629
16606357	14825	if array contains value	select * from table where arr @> array['s']::varchar[] 	0.00843107271834211
16606908	36038	join of two tables as to get entire records	select * from table2 inner join table1 on table2.user_id= table1.user_id 	0
16609554	8366	retrieve results from regexp_matches as one row	select array_agg(i) from (    select (regexp_matches('aassdd', 'a', 'g'))[1] i  )  t 	5.58097647937742e-05
16610934	39751	table coulmn merged query	select question, correct_answer, case when answer1 != correct_answer then answer1 else answer2 end as incorrect1, case when (answer1 != correct_answer and answer2 != correct_answer) then answer2 else answer3 end as incorrect2, case when (answer1 != correct_answer and answer2 != correct_answer and answer3 != correct_answer) then answer3 else answer4 end as incorrect3 from questions 	0.0451878118853354
16611836	12842	how to code sql statements from generated crystal	select ...    from order_table    where order_date = current date and         status_code in ('e', '1', 'x') and         user = 'bloggs'; 	0.377232378273096
16613274	23468	join table on already joined table	select *  from favorites  join beers     on favorites.fk_beer_id = beers.beer_id join breweries     on beers.fk_brew_id = breweries.brew_id 	0.00244581872284337
16615534	24267	joining three tables in sqlite	select c.content_common_name, l.name, v.value from userneed_comparison_labels l left join tbl_comparison_values v on l.id = v.userneed_comparison_label_id left join tbl_content_commons c on c.id = v.tbl_content_common_id where c.id in (1, 2, 3) 	0.0579359298357964
16616023	22335	how to group similar records by single value	select         user.user_id,         user.last_name,         user.first_name,         student.sis_id,         organization.`name`as school,         count(*) as count     from         user     join student on user.user_id = student.user_id     join x_user_group on _user.user_id = x_user_group.user_id     join group on _x_user_group.group_id = group.group_id     join organization on group.owner_id = organization.organization_id group by         user.user_id,         user.last_name,         user.first_name,         student.sis_id,         school order by         user.last_name,         user.first_name 	0.000365798264015154
16620711	29	how to select rows with 10% of the votes here?	select * from votestable v where v.votes > (select                    votes                  from votestable v1                  where v1.id = v.parent) * 0.1 	0.000581300009670382
16622172	32574	sum the different date total	select     cast(dateadd(hour, -5, tran_date) as date) as sdate,     sum(amount) from tran_table group by cast(dateadd(hour, -5, tran_date) as date) 	7.71962737337563e-05
16622213	15285	how to get the corresponding data of a max value in mysql	select count( order_id ) as orders, date( date_added ) from  `order`           where year(date_added) = year( now( ) )           group by date( date_added ) order by orders desc limit 1 	0
16622867	34816	associative values in mysql result	select moviename, director, language,           group_concat(actor) as actors     from movies group by moviename, director, language 	0.0614159475759464
16623676	519	mysql query to get a mutual friend count and display it in a table in php	select    f.profile_name,    f.friend_id,    count(distinct m2.friend_id1) as count_mutual from     friends as f    left join myfriends as m1      on (m1.friend_id1 = f.friend_id)    left join myfriends as m2      on (m1.friend_id2 = m2.friend_id1 and m2.friend_id2 = '$friendid') where     f.friend_id <> '$friendid'     and f.friend_id not in(select                             friend_id2                          from                             myfriends                         where                             friend_id1= '$friendid') group by     f.friend_id 	0.000161718032592227
16623704	22714	mysql equal to x and greater than y	select * from gg_crates    where minutes = -1       or minutes >= x 	0.00107703919402795
16623808	5269	get related rows in one table using a table with relations	select num, value from content where id in (   select id_foreign   from relations   where id_local = ( select id from content where num = '222' )   )   and num = '222'  	0
16624620	35994	analog of "select level from dual connect by level < 10" for sybase?	select row_num from sa_rowgenerator( 1, 255 ); 	0.0992343927261265
16624930	16413	query in a like-tree table	select t1.des from table t1 left join table t2 on t1.idcat = t2.idparent where t2.idparent is null 	0.231276267601504
16628194	9624	select row for every key in in statement even if they are equal	select t.* from database.table as t inner join (   select 6230 as id union all   select 206 union all   select 4259 union all   select 24761 union all   select 26736 union all   select 219 union all   select 281 union all   select 281 union all   select 516 union all   select 495 union all   select 10371 ) as x on x.id = t.id 	0
16628263	26444	truncate function for sqlite	select substr(1.999, 1, instr(1.999, '.') + 1); 	0.595045997541515
16630378	5327	sql count from one table where condition from another table is true	select a.c, count(*) from tablea a join tableb b on (c = d) where e group by a.c order by count(*) desc 	0
16633720	13865	select records from table with inner join and where condition	select distinct id,name from   (   select a.id,a.name      from ".$supportusertable." a     where  a.status='2'    union (    select a.id,a.name        from  ".$supportuserperdepatable." b       left join  ".$supportusertable." a           on a.id=b.user_id        where b.department_id=? and  a.id is not null    ) ) as  tab  order by tab.id asc, tab.name asc 	0.0296579782429806
16633966	9844	joining and printing search results of a column with multiple values in a cell	select *, group_concat(t2.genre separator ', ') as genre_result  from books_db as t1  join genre_link_db on genre_link_db.id_books = t1.id join genre_db as t2 on genre_link_db.genre_id = t2.genre_id where books_db.book_title like '%' group by t1.id; 	0.000147376082064255
16634699	34718	create or replace table in oracle pl/sql	select count(*)   into ncount   from user_tables   where table_name = 'foobar'; if ncount <> 0 then   execute immediate 'drop table foobar'; end if; execute immediate 'create table foobar(...)'; 	0.573414443906623
16635921	30933	employees and departments with groups database schema advice	select * from employee where employee.dep_link  in (select dep_id_link from departments_group inner join groups      on groups.id = group_id_link and groups.name = 'all') 	0.133669353113508
16636805	3987	mysql subquery to reverse order	select *  from (select users.id, users.nome, users.email,users.foto,               comments.content, comments.id cid       from users, comments        where comments.posts_id=1 and comments.users_id=users.id       order by comments.id desc limit 5) as dummy order by cid asc 	0.705329325373452
16637583	32717	a query to find duplicates but exclude set	select   emp_id,   work_date from (   select     emp_id,     work_date,     min(element) min_element,     max(element) max_element,     count(*) rows_counted   from     mytable   where     work_date = :p_workdate   group by     emp_id,     work_date   having     count (*) > 1) where   rows_counted > 2 or   (min_element,max_element) not in (select 'element1' el1, 'element2' el2 from dual union all                                     select 'element3' el1, 'element4' el2 from dual) 	0.00288998953771899
16641777	21034	how to know which column is matched when filter the records by multiple columns compare	select     name,      case     when col1=1 then 'col1'     when col2=1 then 'col2'     when col3=1 then 'col3'     when col4=1 then 'col4'     else null end as col_match from table1 where (col1=1 or col2=1 or col3=1 or col4=1) 	0
16642797	9387	process entier db to fetch data	select table_name       , column_name       ,to_number(extractvalue(        xmltype(dbms_xmlgen.getxml(        'select count(*) c from '||owner||'.'||table_name ||' where extract(year from ' || column_name || ') < 1753'        ))        ,'/rowset/row/c')) as count1 from all_tab_cols where data_type = 'date' and owner = 'owner_name' 	0.0153207776546782
16644109	9750	find name of least experienced employee	select top 1 name, doj  from programmer order by doj desc 	0.000245592727522022
16644445	38114	fetch duplicate rows with sql	select * from  table where keyword in (select keyword  from table group by keyword  having count(keyword)>1) 	0.00155775644133966
16644469	29770	how to get multiple rows with order by and limit	select s1.*  from `salary_log` as s1 inner join (     select name, max(create_date) as maxdate     from salary_log     group by `name` ) as s2  on s1.name        = s2.name          and s1.create_date = s2.maxdate; 	0.00236632234137898
16645008	28658	how to save my login form from sql injection	select * from tbl_user     where (uname = '$username' or eemail = '$username')        and password = '$hashedpassword'" 	0.71868690190543
16645191	24210	join two sql queries into one	select    description,   max(     case          when column1 = 'a'          then (             case                  when checkbox2 = '2' then '2'                 when checkbox2 = '1' then '1'                 when checkbox2 = '0' then '0'                    when checkbox1 = '1' then '1'                 when checkbox1 = '0' then '0'             end         )      else '-'      end   ) 'a' from    table1 join table2     on table2.id = table1.id left join table3      on table2.id2 = table3.id2 where      table1.id = var1 group by description 	0.0100873911533634
16645280	11509	fetch data from more than one tables using group by	select c1.*, p1.*   from customer c1   join orders o1 on o1.customer_id = c1.id   join product p1 on p1.id = o1.product_id  where c1.id in (select c.id                    from customer c                    join orders o on o.customer_id = c.id                   group by (c.id)                  having count(distinct o.product_id) >= 2) 	0.000106753085880642
16645608	26002	selecting distinct records not considering one field	select cod_ltn,        cod_cana,        cod_fam_pro,        cod_ctg_pro,        cod_pro,        min(cod_cfg_prm_pro),        cod_fam_prm_pro   from prm_statico_pro  where cod_pro = 53  group by cod_ltn,           cod_cana,           cod_fam_pro,           cod_ctg_pro,           cod_pro,           cod_fam_prm_pro; 	8.31761662567383e-05
16647708	1114	find most number of languages used	select top 1 developin, count(developin) as 'total'  from software  group by developin order by count(developin) desc 	0.000406176178589323
16647740	6301	only select/count verified and not banned users	select u.username, count(u.username)  from users u left outer join banned_users b on b.username = u.username where u.status = '1' and b.username is null group by u.username 	0.0198198906700145
16647972	19613	how i can create one column in my select output with sequence and seed	select * from     (     select top (5)         row_number() over(order by s.id) as rownumber          ,s.subscribenumber as sn     from billing.subscribe as s     union all     select top 5         row_number() over(order by s.id) as rownumber           ,s.subscribenumber as sn     from billing.subscribe as s     order by s.id     offset (5) rows     fetch next (5) rows only     ) x order by (rownumber-1)%5, rownumber; 	0.0360706081216296
16648129	8807	sql / add 2 zeros to string	select unix_timestamp (now()) * 100 	0.00586851649680281
16649767	37455	selecting values based on value	select distinct    nullif(b1, -1) as b1,    nullif(h1, -1) as h1,    nullif(f1, -1) as f1,    nullif(a1, -1) as a1,    nullif(u1, -1) as u1 from    mytable where    areaid = 120 	0
16651423	30179	sql - select multiple users from a table asoiciated with multiple options aka relations division	select `user` from tablename  where `option` in ('a', 'd') group by `user` having count(distinct `option`) = 2; 	0.00223418941527872
16651667	7528	mysql: how to implement history of product price and units	select * from product   join product_state ps on product.id = ps.product_id where ps.id = (select max(ps2.id)                   from product_state ps2                  where ps2.product_id = ps.product_id)  order by ps.id desc; 	0.0319762351336879
16651686	16775	how to select n characters from an as400/db2 database column	select substr(columndata, 1, 4) as year, substr(columndata, 5, 2) as month . . . 	0.000398843684394515
16652442	28083	sql : how to find leaf rows?	select id,        refid from   mytable t where  not exists (select 1                    from   mytable                    where  refid = t.id) 	0.00205076949726718
16652824	37968	return only the first result for a date	select y1.* from your_table y1 inner join  (   select patientid, min(readingtimestamp) as ts   from your_table   group by date(readingtimestamp), patientid ) y2 on y2.patientid = y1.patientid       and y2.ts = y1.readingtimestamp 	4.70281863634904e-05
16652985	31656	conditionally joining a table	select * from     products p     left join     reviews r on r.product = p.product and p.show_reviews ; 	0.0263213493112326
16653060	38640	check for new messages with sql [facebook like chat]	select m.* from messages m join rooms r on m.roomid = r.roomid     join room_to_user ru on r.roomid = ru.roomid where ru.userid = @userid and m.time > @timesincelastread 	0.262207199806248
16653480	39318	how to retrieve data using "or" operator	select p.firstname, p.lastname, p.email, s.courseidnum from people p inner join registration r  on p.peopleid = r.peopleidnum inner join section s  on r.sectionidnum = s.sectionid inner join school sc  on p.schoolidnum = sc.schoolid where (s.courseidnum=11 and s.courseidnum!=12)   or (s.courseidnum!=11 and s.courseidnum=12) 	0.168107001402899
16654694	22007	postgresql: call a function more than once in from clause	select f0.*, f1.* from     foo(0) as f0 (a int, b int),     foo(1) as f1 (c int, d int); 	0.306936400733675
16654865	6820	sql server query displaying null instead of 0 using count and groupby	select pr.name, isnull(ps.totalsales, 0) totalsales, isnull(ps.truesales, 0) truesales from product pr left join ( select produdtid, totalsales = count(transaction.id), truesales = count(distinct case when .transaction.exceptioncode  = ' ' then transaction.id end) from [transaction]  where    (responsetime < '2013/05/16 01:53:52' and  requesttime > '2013/05/11 01:53:52') group by productid) ps on ps.providerid = pr.providerid 	0.366987782862649
16654953	24478	selecting all data from all columns in a mysql database	select id, attribute, '' as attribute1 from db1.table1 union all  select id, attribute, attribute1 from db1.table2; 	0
16655786	24838	sql query returns results for all districts but i need only one district to show up	select max(p.firstname),         max(p.lastname),         max(p.email),         max(s.courseidnum) from people p inner join registration r  on p.peopleid = r.peopleidnum inner join section s  on r.sectionidnum = s.sectionid inner join school sc  on p.schoolidnum = sc.schoolid where s.courseidnum in (11, 12)    and s.districtidnum = 5    and r.completed='y' group by p.peopleid having count(distinct s.courseidnum)=1 	0.00142474608082113
16656556	28599	mysql: count instances of values in several columns and get the result as a specially formatted table	select '1a' as grade_name, `1a_grade` as `grade`, count(*) as `count`     from grade     group by '1a', `1a_grade` union all select '1b' as grade_name, `1b_grade` as `grade`, count(*) as `count`     from grade     group by '1b', `1b_grade` union all select '1c' as grade_name, `1c_grade` as `grade`, count(*) as `count`     from grade     group by '1c', `1c_grade` union all select '2a' as grade_name, `2a_grade` as `grade`, count(*) as `count`     from grade     group by '2a', `2a_grade` union all select '2b' as grade_name, `2b_grade` as `grade`, count(*) as `count`     from grade     group by '2b', `2b_grade` union all select '2c' as grade_name, `2c_grade` as `grade`, count(*) as `count`     from grade     group by '2c', `2c_grade` 	0
16656912	31920	sql select from generate_series, filtering by user_id removes series?	select      distinct date_trunc('day', series.date)::date as date,     sum(coalesce(reps, 0)) over win,     array_agg(workout_id) over win as ids      from (     select generate_series(-22, 0) + current_date as date ) series  left join (     exercises inner join (select * from workouts where user_id = 5) workout      on exercises.workout_id = workouts.id )  on series.date = exercises.created_at::date  window     win as (partition by date_trunc('day', series.date)::date) order by date asc; 	0.0346831132829253
16659149	30648	how to select rows with exactly 2 values in a column fast within a table that has 10 million records?	select   email, max(ffid) from     testfi group by email having   count(*)=2 and count(fiid)=1 	0
16659897	3881	mysql select where polygon contains point always false	select     * from      users where     mbrcontains(         geomfromtext('polygon((0 0,0 100,100 100,100 0,0 0))'),         geomfromtext('point(50 50)')) = 1; 	0.512685390159388
16660702	4145	finding unique emails across two tables	select a.mail from a where not exists (select 1 from b where a.mail = b.mail) 	0.000141624346373479
16661927	27417	retrieving data from two mysql tables where the second table depends on the first	select ways.id_way, ways.start, ways.end, ways.date, users.*  from ways join users using (id_user) 	0
16661949	1447	join table and filter and take aggregrate function sql access	select d.itmcde,        sum(d.qnt) as qnt,        sum(d.price) as price   from inv_summary s inner join inv_details d      on d.invnum = s.invnum   where s.date between #3/4/2013# and #5/16/2013#   group by d.itmcde  order by d.itmcde 	0.796138575538726
16663938	16624	how to select a column from one table and two columns from another table when both the tables have no relation in t-sql?	select t1.column1, isnull(t2.column2,0) as column2,  isnull(t2.column3,0) as column3 from table1 t1 left outer join on table2 t2 on t1.column9=t2.column9 where .... 	0
16664354	16183	how to select row data as column in oracle	select * from (       select t1.ah_id, t1.ah_description, t2.att_id, t2.att_dtl_str_value       from t1          left outer join t2 on t1.ah_id = t2.ah_id      ) pivot (max(att_dtl_str_value) for (att_id) in (1)); 	0.00278631949552976
16664980	20374	function format number and how to use it in sql statement	select to_char(price, 'fm9,999,999.99')   from a; 	0.679124195622145
16665268	39717	how to only return in certain increments of days	select distinct      convert(varchar,month(time_stamp)) + '/' +          convert(varchar,day(time_stamp)) from report where      time_stamp like '%2011%'      and           datepart(dayofyear, time_stamp) % 14 = 0 order by 1 	0
16667283	12244	getting last record from the database with some conditions	select  * from    (         select  *,                 row_number() over (partition by mobilenumber order by year desc, month desc, recordid desc) rn         from    mytable         ) q where   rn = 1 	0
16667335	2058	sum by rows (include all columns) in oracle	select  t.*,         coalesce(monday, 0) +         coalesce(tuesday, 0) +         coalesce(wednesday, 0) +         coalesce(thursday, 0) +         coalesce(friday, 0) as total from    mytable t 	0.000279544915842144
16667648	12076	mysql sum 0 when not in another table	select   u.id,   u.name,   coalesce(sum(p.amount), 0) as totalpoints from (   select *    from users   where club_id = 4 ) as u left join (   select *    from points   where club_id = 4 ) as p on p.user_id = u.id  group by u.id,           u.name; 	0.0373483469745451
16667877	29753	remove the null value from the result generated from max() used in query sql	select max(dt_logdate) from   ums_logentry_dtl where  c_inputmode='r' and vc_deviceid=10 having max(dt_logdate) is not null 	0.000130510525929595
16668234	19513	t-sql: get top n records by column	select t.userid, t.attributeid, t.itemid from ( select userid, attributeid, itemid, rowid = row_number() over (         partition by userid order by dateventdate          )  from rankeddata ) t where t.rowid <= 75 	0
16668685	26905	sql merging multiple records into one record	select user_id, group_concat(tags) from tablename group by user_id 	0
16671495	33990	counting a number of purchases with the same data values in oracle	select count(purchaseno) from purchase group by servicetype, paymenttype, gst having count(purchaseno) >= 1000 	0
16671598	28235	sql - filtering out certain types of duplicates	select * from mytable where email in ( select  email from mytable t group by email having count(email) = 1 or exists (select 1 from mytable st                                              where t.email = st.email                                              and st.flag = 'yes') ) and email != '' 	0.00111697020913416
16673723	38658	storing most frequently used values in an array from database	select emailfrom  from (     select emailfrom, count(emailfrom) as mycount     from details     group by emailfrom      order by mycount desc     limit 3     ) temp 	0.00065592760125944
16673891	16380	counting the number of job orders per company	select c.name,        count(cj.joborder_id) from company c,      joborder jo,      candidate_joborder cj where c.company_id=jo.company_id   and jo.joborder_id=cj.joborder_id   and jo.status = 'active'   and cj.status=700 group by c.name; 	0
16675770	13102	error in querying concatenation of 2 fields in libreoffice base sql	select "ward name" || ', ' || "prefecture name" as "wrd_pref", "ward id" from "prefectures" inner join "ward" on "prefectures"."prefecture id" = "ward"."prefecture id"; 	0.134553253975853
16679908	38970	replacing json formatted string in sql	select * into #demo from (select * from parsejson('{"inputdirection":0,"mask":"aa","formatstring":null,"autocompletevalue":null,  "filtered":"0123456789","autocomplete":false,"readonly":true} ')) a select * from #demo declare @myhierarchy jsonhierarchy; insert into @myhierarchy select * from #demo; select dbo.tojson(@myhierarchy) drop table #demo 	0.114250775279875
16680974	7751	mysql left join many to one row	select r.name as room_name,     group_concat(p.name separator ',') as people_name,     group_concat(t.name separator ',') as things from rooms r  left join people p on p.fk_rooms = r.id left join things t on t.fk_rooms = r.id group by r.id 	0.0520009923259152
16683461	16030	ordering across multiple table only using and in mysql	select * from trucks where make = 'volvo' and current_partlist_id in (select id from    parts_list where carb_model = 'hirsch') 	0.00843297371459147
16684468	18696	sql join in oracle	select      t1.item item,     t1.desc desc1,      t2.parentitems pitem     ,t1_2.desc desc2 from tab1 t1 left join tab2 t2 on t1.item = t2.item left join tab1 t1_2 on t2.parentitems = t1_2.item 	0.75945264366193
16687579	5210	use case statement to check if column exists in table - sql server	select case     when exists (       select 1        from sys.columns c        where c.[object_id] = object_id('dbo.tags')           and c.name = 'modifiedbyuserid'    )     then 1     else 0  end 	0.653582954878703
16687706	535	convert decimal to hh.mm format in sql server	select floor(06.85) + cast(((06.85 - floor(06.85))*100) as int) / 60 + cast((cast((06.85 - floor(06.85)) * 100 as int) % 60) as float) / 100  select floor(06.60) + cast(((06.60 - floor(06.60))*100) as int) / 60 + cast((cast((06.60 - floor(06.60)) * 100 as int) % 60) as float) / 100 	0.0531832312711503
16687842	7163	how to find regions where total of their sale exceeded 60%	select    min(int_rate),    max(int_rate)  from    (     select        int_rate,          nvl(sum(total_balance) over(         order by total_balance desc         rows between unbounded preceding and 1 preceding       ),0) as part_sum     from interest_summary   ) where    part_sum < (select 0.6*sum(total_balance) from interest_summary) 	0.000114872439132718
16687853	14597	sql query to find duplicates	select *  from file  where hash in (select                 hash                 from file                group by hash                having count(*) > 1) 	0.0734098217982968
16688214	20570	retrieve different values in order if empty	select tund.id_unit, round(sum(     case when isnull(t1.measure, 0) > 0 then t1.measure else      case when isnull(t2.measure, 0) > 0 then t2.measure else     case when isnull(t3.measure, 0) > 0 then t3.measure else 0      end end end end /1000),3) as mymeasure from calendar left outer join units_table tund on tund.id_unit in (252, 107) left outer join measures_table t1 on t1.id_measure_type = 6      and t1.datebid = dt and t1.hour = h and t1.id_uf = tund.id_uf left outer join measures_table t2 on t2.id_unit = t1.id_unit      and t2.datebid = t1.datebid and t2.id_measure_type = 1      and t2.id_unit = tund.id_unit  left outer join measures_table t3 on tcnt.id_unit = tufi.id_unit     and t3.datebid = t1.datebid and t3.id_measure_type = 4      and t3.id_unit = tund.id_unit  where dt between '03/23/2013' and '03/24/2013'  group by tund.id_unit 	0.000347348079855559
16689784	40184	mysql equally distributed random rows with where clause	select r1.*     from         (select  person_id,                  @currow := @currow + 1 as row_number         from persons as p,              (select @currow := 0) r0         where points>0) r1     , (select count(1) * rand() id        from persons        where points>0) r2     where r1.person_id>=r2.id     order by r1.person_id asc     limit 1; 	0.139608116154992
16690277	25387	determine all columns used to execute some sql on sql server 2008	select distinct   object_name(objs.referencing_id) as referencing_entity_name,   cols.referenced_entity_name,   cols.referenced_minor_name from   sys.sql_expression_dependencies objs   outer apply sys.dm_sql_referenced_entities( object_schema_name(objs.referencing_id) + n'.' + object_name(objs.referencing_id), n'object' ) as cols where   objs.referencing_id = object_id(n'myschenma.mystoredprocedure') order by   object_name(objs.referencing_id)   cols.referenced_entity_name,   cols.referenced_minor_name ; 	0.0416018382005169
16691357	2079	join two tables using common column in postgres	select   r.*,  table_three.name  from table_one r inner join table_two s on s.id           = r.table_two_id inner join table_three on table_three.id = s.table_three.id; 	0.00204642584510527
16692013	9243	group query records by proximity of value	select t1.myrowid, t1.contractid, min(t2.timestamp) - t1.timestamp as deltat from mytable t1 inner join mytable t2 on t1.contractid = t2.contractid and t2.timestamp > t1.timestamp group by t1.myrowid, t1.contractid having min(t2.timestamp) - t1.timestamp > "60 seconds" 	0.00245430759297378
16694379	14061	how to use variable value inside another variable in ssis?	select (functionpreviousbusinessday(),112) 	0.171552976304295
16694616	10302	detect if database and table exist on the same query	select schemata.schema_name as `database_name`, tables.table_name from information_schema.schemata schemata left join information_schema.tables tables    on schemata.schema_name = tables.table_schema   and tables.table_name = "table_name" where schemata.schema_name="database_name" 	0.00178330563341333
16695861	7491	separate 1 column data to 2 column	select businessday = cast(dateadd(hh,-5,trandate) as date)       ,amount = sum(case when datepart(hh,trandate) >  4 then amount else 0 end)       ,amount_before_5am =         sum(case when datepart(hh,trandate) <= 4 then amount else 0 end) from table group by cast(dateadd(hh,-5,trandate) as date) 	0.000192939427831344
16696101	25398	rankings using sql	select standings.teams, standings.w,        (select count(*)+1         from standings as temp          where temp.w > standings.w        ) as wins_rank from standings order by standings.w; 	0.552012740493753
16696874	10609	replace last two characters in column	select replace(period, substring(period, len(period) - 1, 2), '12') from @b_s_summary where period like '%13' 	0.000383787977003084
16697215	7564	mysql - count number of unique values	select  count(distinct(email)) from orders 	0.000141940613761797
16698224	24674	counts using a greater than sign	select cat_code, cat_desc, count(distinct case when mthtrn > 0 then member_id end), count(ltmtrn) from my_temp_table group by cat_code order by mthsls desc; 	0.0508036535263475
16698431	7915	column 1 with names and column 2 with values	select col1, sum(col2) from tablename group by col1 	0.000110645234406266
16700004	10898	differences between 3 table	select ipaddress, hostname,     sum(case when tbl = 'a' then 1 else 0 end) tablea,      sum(case when tbl = 'b' then 1 else 0 end) tableb,     sum(case when tbl = 'c' then 1 else 0 end) tablec from (     select ipaddress, hostname, 'a' tbl     from tablea     union all     select ipaddress, hostname, 'b' tbl     from tableb     union all     select ipaddress, hostname, 'c' tbl     from tablec ) d group by ipaddress, hostname; 	0.00187576556325211
16702324	4495	how to create a dummy value column in mysql depending on the table specific information was selected from?	select current_users.lastname,         current_users.firstname,         current_users.id,         new_users,lastname,         new_users.firstname,         new_users.id,        case when new_users.id is null then 0 else 1 end as dummy_column 	0
16702882	17982	mysql max statement not returning result	select * from user_messages inner join(select from_username, max(id) as id from user_messages where user_link = '33' group by from_username order by status, id desc) t2 on user_messages.id = t2.id and user_messages.from_username = t2.from_username 	0.709575523578956
16703674	34343	division by a second query	select  count(*) / crss.totalcount as result from    pparsdb.application         inner join pparsdb.planning_scheme             on application.planning_scheme = planning_scheme.ps_code         cross join         (             select  count(*) totalcount             from    pparsdb.planning_scheme              where   markus_ra = 'ga'         ) crss where   planning_scheme.markus_ra = 'ga' 	0.0622272522856872
16706156	14871	joining two table by mask	select * from page join site on page.url like site.domain_url || '%' 	0.0142868326425372
16706202	29369	how to split time left in days,hours,minutes,seconds in query	select title,        `date`,        subject ,        timestampdiff(day, convert_tz(now(),@@session.time_zone, '+05:30'), `date`) as dayleft,        timestampdiff(hour, convert_tz(now(),@@session.time_zone, '+05:30'), `date`)        - timestampdiff(day, convert_tz(now(),@@session.time_zone, '+05:30'), `date`)*24 as hourleft,        timestampdiff(minute, convert_tz(now(),@@session.time_zone, '+05:30'),  `date`) -        timestampdiff(hour, convert_tz(now(),@@session.time_zone, '+05:30'), `date`)* 60 as minuteleft,        timestampdiff(second, convert_tz(now(),@@session.time_zone, '+05:30'), `date`)-         timestampdiff(minute, convert_tz(now(),@@session.time_zone, '+05:30'),  `date`)*60 as secondleft from jos_holidays where `date` > convert_tz(now(),@@session.time_zone, '+05:30') 	0.198006245448888
16707576	27994	how to count maximum duplicate cell on the behalf of date in a table	select top 1 form ,date, count(1) msgcount from  group by form ,date order by 3 desc 	0
16708746	24094	how to use other table field in sql where clause	select *    from work x join employee e     on e.availability = x.availability    and e.empid = x.empid 	0.0750073318981682
16709867	27590	perform a "union" of two tables using "join" operator	select coalesce(a.a_name, b.b_name) from a full join b on 1=0; 	0.595279186937062
16711402	377	sql query to match records with/without all defined many-to-many matches	select     `posts`.* from     `posts` where     exists (       select 1 from `posttags`        where `posttags`.`postid` = `posts`.`postid`         and `posttags`.`tagid` = 2     )     and     exists (       select 1 from `posttags`        where `posttags`.`postid` = `posts`.`postid`         and `posttags`.`tagid` = 3     )         and not exists (       select 1 from `posttags`        where `posttags`.`postid` = `posts`.`postid`         and `posttags`.`tagid` = 5     ) 	0.00124204788342462
16711804	28996	select newest entry by timestamp	select * from(     select       id,      timestamp_1,      timestamp_2,      row_number() over(partition by id, timestamp_2 order by timestamp_1 desc) as rnum     from tablename )x where rnum=1 	0.000368367034782403
16713012	31480	mysql: how to check if a string contains a value within the same row	select name, couple from yt  where couple like concat('%', name, '%'); 	0
16713930	15910	sql select query to return only if a record has a field of a single value	select policynumber, fplan, feffyy, feffmm, feffdd, finstp, clientnum, firstname,  midname, lastname, birthdate from pfcasbene  inner join cmrelatn on policynumber = keyfield1  inner join cmperson on clientnum = clientid where (fpsflg='i' or fpsflg='p') and clientnum not in ( select clientnum from pfcasbene  inner join cmrelatn on policynumber = keyfield1  inner join cmperson on clientnum = clientid where finstp <> 'f') order by clientnum asc 	0
16716995	13664	partition data in percentile range and assign different value for different range	select customer_id,sum,case  when pct_row<=0.10 then 1 when pct_row>0.10 and pct_row<=0.20 then 2 when pct_row>0.20 and pct_row<=0.60 then 3 when pct_row>0.60 then 4 end as customer_label from ( select customer_id,sum,(@currow := @currow+1)/c as pct_row from temp t  join (select @currow := 0) r join (select @currow2 := 0) r2  join (select count(*) c from temp) s order by sum desc) p; 	0
16717861	28794	counting the number of successful bitwise matches	select     count(nullif(fa.value & 1, 0)) as 'neurology'     ... 	0.00383364194977865
16718360	4953	mysql select records from one table that don't exist in another table	select distinct   flrhost_mls.mlsdata.mls_listing_id from flrhost_mls.mlsdata inner join flrhost_forms.ft_form_8  on flrhost_mls.mlsdata.mls_agent_id = flrhost_forms.ft_form_8.nar_id   where flrhost_mls.mlsdata.mls_agent_id = '260014126'   and flrhost_forms.ft_form_8.transaction_type = 'listing'    and flrhost_mls.mlsdata.mls_listing_id not in (select b.mls_id from flrhost_forms.ft_form_8 b) 	0
16719288	4264	combine rows into one result and add results as different values in sql	select p.cert_id,   max(case when p.type = 'owner' then p.name end) owner_name,   max(case when p.type = 'seller' then p.name end) seller_name,   max(case when p.type = 'buyer' then p.name end) buyer_name,   array_agg(distinct i.item_name) items from people p inner join items i   on p.cert_id = i.cert_id group by p.cert_id; 	0
16719516	25493	sql merging two text columns into single column	select t1.user_id, concat(t1.tags, ', ', t2.tags) as tags from table1 as t1 inner join table2 as t2 on t1.user_id = t2.user_id 	0
16720923	18601	compare strings by matching words	select count(*) from ( (select distinct unnest(string_to_array(upper('the quick brown fox jumps over the lazy dog'),' '))) intersect all (select distinct unnest(string_to_array(upper('the pen lies over the table'),' '))) ) t3 	0.00294418080295622
16724363	14509	excluding row from mysql query if id is blocked	select * from whatever where posting_user_id not in (select blockedid from blocklist where blockerid = <<current user viewing the page>>) 	0.000830805123038983
16725236	39797	trying to get count statistics for simple db table	select name, sum(num_kills) num_kills, sum(num_deaths) num_deaths from (     select _from name, count(*) num_kills, 0 num_deaths     from wiretaps     where message like '%pvp:%'     group by _from     union all     select _to name, 0 num_kills, count(*) num_deaths     from wiretaps     where message like '%pvp:%'     group by _to) x group by name 	0.0322041151374948
16726797	29075	sql query for retrieving data by combining two queries	select name, firstname, lastname, employee_id, location from salary where employee_id = isnull(@employee_id, employee_id) and lastname  like '%' +  isnull(@lastname,lastname) + '%' 	0.00839341713899399
16727517	27475	how to get sql server process id with c#	select serverproperty('processid'),serverproperty('productversion') 	0.0131297051053661
16728657	8811	how to compare two table in same database in mysql?	select t1.* from table1 t1     left join table2 t2 on          substring_index(t2.path, '/', -1) =  substring_index(t1.path, '/', -1)          and t2.frn = t1.frn          and t2.byte = t1.byte     where t2.path is null or t2.frn is null or t2.byte is null 	9.25943211319882e-05
16731277	17401	pivoting with multiple column	select  user_id ,max(case when order_id=1 then service end) as service_1 ,max(case when order_id=2 then service end) as service_2 from  table group by user_id 	0.0730516973770239
16731487	2057	php count same data in database	select     `t`.`product_name`,     count(`t`.`order_detail_id`) as `count` from `table` as `t` group by `t`.`product_name` 	0.00547064596943742
16733538	479	sql query: retrieve list which matches criteria	select s.fname, s.name, s.level from student s  where level =  (select top 1 level from student where fname = "jaci" and lname = "walker") 	0.000619346609395927
16734492	18341	order query results by part od column text	select t.*, c.alias as calias from jos2_tabs t join jos2_tabs_category c on c.id=t.category_id where (category_id = 43             or category_id in (select id from jos2_tabs_category where parentid = 43)             ) and state=1  order by str_to_date(substr(terms, 0, 10),'%d.%m.%y') asc 	0.202621156874167
16735885	36356	select xpath values as separate rows in oracle sql	select extractvalue (x.column_value, 'xpath-expression')   from table (           select xmlsequence (                     xmltype (column).extract ('xpath-expression'))             from t) x; 	0.00661182404203031
16736933	29881	sql between dynamic	select tablea.dnsname, tablea.ipaddressstr, tableb.osname  from tableb  inner join tablea    on tableb.assetosid = tablea.assetosid  inner join ipranges    on (ipranges.configid = @configid)  and (assets.ipaddress between ipranges.startipaddress and ipranges.endipaddress) 	0.359725023425608
16737849	16314	how to get sum of column, where another column has count = 1	select  sum(noboxes) as total from info join      (select trackingnumber       from info       where carrier = 'ups' and errored = 0      group by trackingnumber having count(*) = 1) as a on info.trackingnumber = a.trackingnumber where info.processdatetime>{ts '2013-05-22 00:00:00'} and        info.processdatetime<{ts '2013-05-23 00:00:00'} 	0
16738024	31043	how to truncate a number in sybase ase?	select number = floor ( 455.443 ) select number = cast ( 455.443 as int ) select number = convert ( int, 455.443 ) select number = 455.443 - ( 455.443 % 1 ) 	0.00569543294519319
16738066	39841	how to select multiple rows in sql server while filling one column with the first value	select name, sum(value), const.date from table cross join      (select top 1 date from table) const group by name, const.date 	0
16738519	1481	using where, group by and order by	select min(totaltime), raceid from racestimes group by raceid order by min(totaltime) asc 	0.559790480833575
16738899	12444	how to retrieve the rsexecrole name of the sql server name using the sql query?	select members.name as username, rtrim(ltrim(roles.name)) as rolename  from sys.database_principals members    inner join sys.database_role_members drm      on members.principal_id = drm.member_principal_id    inner join sys.database_principals roles      on drm.role_principal_id = roles.principal_id  where members.name <> 'dbo' order by members.name 	0.000397193285836289
16741551	1906	how to join two tables and make default value zero if one doesn't have it	select coalesce(table1.itemid, table2.itemid), coalesce(val1, 0), coalesce(val2, 0),      coalesce(val3, 0), coalesce(val4, 0), coalesce(val5, 0) from table1 full outer join table2      on table1.itemid = table2.itemid 	0.000520677330592193
16741807	33099	sql alias select	select s.name, s.column1, s.column2, ... from table as s 	0.679003243482786
16742874	5766	redundant data or two queries?	select first_name, last_name, email from users, cards, charges where users.id = cards.user and cards.id = charges.card and charges.id = 5; 	0.204538366866221
16743239	25791	in sql, how can i create a query that shows all the elements of a table that are in one set and not in another?	select personid from formssubmitted where      [type]="a"      and      [month]="june"     and     personid not in (         select personid from formssubmitted         where [type]="b" and [month]="august"     ) 	0
16743713	30407	ms sql 2005 - replace null values with linear interpolation	select * from tests where value is not null union all select t.date   , t.shortname   , t.longname   , value = p.value + (n.value - p.value)     * (cast(datediff(dd, p.date, t.date) as decimal(16,1)))     / (cast(datediff(dd, p.date, n.date) as decimal(16,1))) from tests t   cross apply   (     select top 1 p.date, p.value     from tests p     where p.value is not null       and t.shortname = p.shortname       and t.date > p.date     order by p.date desc   ) p   cross apply   (     select top 1 n.date, n.value     from tests n     where n.value is not null       and t.shortname = n.shortname       and t.date < n.date     order by n.date   ) n where t.value is null order by shortname, date 	0.791419815275377
16743847	21145	how to count and group items by week	select sales,         yearweek(date) as week_date,         sum(total) as week_total from sls_ord group by sales, yearweek(date) 	0.000306224634934922
16744183	28318	two oracle sum functions in one query	select building_id,        (select sum(floor_sqft)           from floor f          where f.building_id = b.building_id) sum_of_floors,        (select sum(room_sqft)           from rooms r          where r.building_id = b.building_id) sum_of_rooms   from building b 	0.0980517717044044
16745519	28857	how to properly use mysql to select * from table where column='any_value_in_array'	select * from `series` where `id` in (select `seriesid` from `userfollowsseries` where `userid`=$user_id) 	0.69437443529323
16746028	1633	counting/grouping with mysql	select * from table where `group` in       (select `group` from table        group by `group`       having count(*) < 3) 	0.751252735472663
16749168	31973	find records in one table which does not have a matching coulmn data existing in another table	select * from second table where column_id not in(select column_id from first table); 	0
16749814	20346	confused selecting info from two db	select   bsh.sabthazineid,  bsh.hazineid,  bsh.endusername,  bsh.tedad,   bsh.sabthazinedate,   bsh.describtion,   coalesce( bh.hazinename, h.hazinename ) as [hazinename],   coalesce( bh.mablagh, h.mablagh ) as [mablagh]   from agencybackupdb.dbo.sabthazine as bsh      left outer join    agencybackupdb.dbo.hazine as bh on bh.hazineid = bsh.hazineid     left outer join   dbo.hazine as h on h.hazineid = bsh.hazineid 	0.00185564713022124
16753062	18522	oracle sql how to find missing value for different users	select tb_user.id, tb_question.id as "q_id" from tb_user, tb_question minus select id_user, id_question from tb_answer 	0.000272418575817541
16759867	23557	getting users with highest scores without having users id in the scores table	select u.id,         u.username,        count(s.voter_id) as votes   from users u        images i,        scores s  where i.user_id = u.id    and s.image_id = i.id  order by 3 desc  limit 10 	0
16761724	27271	order by different column if results are the same	select * from test order by score desc, name asc 	0.000102391509264301
16761991	19762	how to order group by and get first row?	select * from (select a.*,          p.filename,          m.`first name`, m.`last name`, m.`mobile number`, m.`status`, m.`email address`  from map a  join members m on a.members_id = m.id  join pictures p on m.pictures_id = p.id  where a.active = 1  order by a.members_id, a.`date added` desc) sq group by members_id; 	0.000167479006059912
16762640	3637	why two completely different strings are seen as equal by sql server?	select case      when n'ܐܪܡܝܐ' collate latin1_general_bin = n'አማርኛ' collate latin1_general_bin      then 1 else 0 end 	0.0787735047293693
16763571	23439	detect double value in mysql	select if( (select count(*) as cnt from person where firstname = p.firstname) > 1            , concat(firstname, " ", substring(lastname, 1))           , firstname) from person  where id = 4711 ; 	0.183658529015307
16764120	8093	sql command that count number of rows after group by c# winforms	select count(distinct id) from order 	0.000601277727068647
16764765	39654	how to get rows from table which are not mentioned in another table	select *   from users  where id not in (select user_id                     from user_links) 	0
16765447	10605	dense rank in both ways	select p.staff,     max(w.work_time) keep (dense_rank first order by w.work_time desc),    p.start_time, p.end_time,    min(w2.work_time) keep (dense_rank first order by w2.work_time) from pause p    join work w       on p.staff = w.staff          and p.start_time >= w.work_time left join work w2    on p.staff = w2.staff       and p.end_time <= w2.work_time group by p.staff, p.start_time, p.end_time 	0.30935338516118
16766096	22615	mysql: perform logical check to the grouped query result	select job_id, min(status) > 0 as isfinished from mytable group by job_id; 	0.159971709078707
16766469	26797	looping through another table and using values as variables for select query	select  rangename,         count(d.customer) cnt from    ranges r left join         delays d    on  d.daysdelayed between r.lowerend and r.upperend group by rangename 	0.00326792406305347
16767331	7062	how to make a single query with like	select fci.*   from {node} as fci   inner join {url_alias} on fci.nid = replace(source, 'node/', '')   left join {node_access} as fdfp on fci.nid = fdfp.nid   where source like 'node/%' and fdfp.nid is null   limit 11 	0.505227446104626
16769886	17223	sql select count of multiple relationships with left join	select      b.id    ,count(distinct o.id) as ordercount     ,count(distinct p.id) as productcount  from branches b  left join orders o      on (o.branch_id = b.id) left join products p     on p.product_id=b.id) group by      b.id 	0.351861405707061
16770169	32063	find max id with the largest number of occurrence of an attribute	select      student, count(1)   from        exam  e join studenttable  s on e.student=s.id_student   where result='true'   group by student    order by 2 desc   limit 0,1 	0
16772183	4707	ordering mysql results when having fixed position for some items	select     tmp.pos from (     select          collectionspositions.pos,         if( collectionspositions.pos is null , 0, @c := collectionspositions.pos )     from itemtocollection      join item on itemtocollection.item_id = item.id     left join collectionspositions            on col_id = 1 and item_id = itemtocollection.item_id     where itemtocollection.collection_id = 1     order by         ifnull(collectionspositions.pos,@c) ) as tmp 	0.0102271801781314
16774325	22601	get result from a mysql db table by matching a id in another table (plus) little authentication	select table2.sub1marks, table2.sub2marks, table2.sub3marks, table2.userid from <tablename2> table2 inner join <tablename1> table1 on table2.userid = table1.userid where table1.userid = <userid> and table1.dateofbirth = <dob> 	0
16775115	15794	counting non-zero values in sql	select drivername,      count(nullif(over_rpm,0)) as rpmviolations,      count(nullif(over_spd,0)) as spdviolations,      count(nullif(brake_events,0)) as brakeevents from performxbydriverdata group by drivername; 	0.0285841333010795
16776596	3268	mysql select 3 entries, skip next two, select next 3 etc	select ...   from ...   where mod(...,5) not in (4,0); 	0
16776946	9232	how to do count(*) from subquery	select count(*)  from  (   select *    from firms ) f  	0.064343862802566
16776967	24436	how to get a boolean result sql query	select i.imageid, count(l.likeid) as numoflikes , count(likes2.*) likesbyuser from images as i left join likes as l using (imageid) left join likes likes2 using (imageid, userid) where i.userid = '16' group by i.imageid order by i.datecreated desc 	0.0574948373378229
16778603	6093	selecting values of a column from multiple rows of the same table as different columns	select vehiclenumber,       max(case when duetypeid = '1' then duedate else null end) typ1duedate,       max(case when duetypeid = '2' then duedate else null end) typ2duedate,       max(case when duetypeid = '3' then duedate else null end) typ3duedate,       max(case when duetypeid = '4' then duedate else null end) typ4duedate,       max(case when duetypeid = '5' then duedate else null end) typ5duedate,       max(case when duetypeid = '6' then duedate else null end) typ6duedate  from due d join vehicle v       on v.vehicleid = d.vehicleid   group by v.vehiclenumber 	0
16780427	1980	how to use where clause after a group by result in mysql	select username, min(authdate)  from radpostauth  group by username having min(authdate) > now() - interval 12 hour 	0.748016979729281
16781110	4275	how to get unique count from subquery?	select count(distinct oi.id) as itemcount,         concat(a.firstname, ' ', a.lastname) as name,         oi.status, a.id as adminid,         (select count(oi2.id) as olditemscount                 from bl_orderitems oi2,                      bl_researcher r2                where oi2.status='pending' and                       r2.id=oi.researcherid and                       r2.researchermanagerid=a.id and                      date(oi2.regdate)=date_sub(curdate(), interval 3 day))                as olditemcount from bl_orderitems oi,         bl_researcher r,        tbladmins a  where oi.status in ('pending', 'qa') and        r.id=oi.researcherid and         r.researchermanagerid=a.id  group by        name, adminid, oi.status; 	0.000911557997825497
16782039	10922	best way to select sum and a unique value from table	select p.postid, sum(v.value) as charge, v.value as currentvote from posts p,      users u,      votes v where p.userid=u.userid   and v.postid = p.postid group by p.postid; 	5.20291855575349e-05
16783020	9056	getting the correct price per activity using mysql	select a.card_id, a.clock, p.price from activity a inner join price p on hour(a.clock) = hour(p.time) 	0.00718836791676132
16783026	38881	t-sql get file extension name from a column	select case           when filepath like '%.%' then right(filepath, len(filepath) -                                                         charindex('.', filepath))           else filepath         end filepath  from   tbl1 	0.00023342693461483
16783661	20071	select values from multiple tables where value = x	select u.userid, u.username, u.useravatar, u.accesslevel,  al.titlecolor from cms_accesslevels al inner join cms_users u on u.accesslevel = al.accesslevel where u.userid = 3 	4.90059311905228e-05
16784557	24508	two rows into one row in sql	select itemcode,    sum(case when trntype = 'issued' then qty else 0 end) as issuedqty,    sum(case  when trntype = 'received' then qty else 0 end) as receievedqty from  [view_new] group by itemcode order by itemcode 	0
16786455	19789	copy foreign key constraints from one db to other	select  'alter table '+object_name(a.parent_object_id)+     ' add constraint '+ a.name +     ' foreign key (' + c.name + ') references ' +     object_name(b.referenced_object_id) +     ' (' + d.name + ')' from    sys.foreign_keys a         join sys.foreign_key_columns b                   on a.object_id=b.constraint_object_id         join sys.columns c                   on b.parent_column_id = c.column_id              and a.parent_object_id=c.object_id         join sys.columns d                   on b.referenced_column_id = d.column_id             and a.referenced_object_id = d.object_id where   object_name(b.referenced_object_id) in     ('tablename1','tablename2') order by c.name 	0
16788690	19578	oracle - different count clause on the same line	select nb_lines,nb_val_1,nb_val_0, nb_val_1/nb_val_0 from  (select count (t1.id) nb_lines,          count (case                 when t1.val = 1                   then 1                 else null                end) nb_val_1,          count (case                 when t1.val = 0                   then 1                 else null                end) nb_val_0    from tabless t1); 	0.00293096144346394
16788711	14703	extract required data with details from sql data table	select (row_number() over ( order by [path]))   as [sr.]        ,replace ([path],'mb\dbi','')            as [name]}        ,[path]                                  as [value]} from  tbl_pathvalues 	0.00159172432848434
16789484	16197	mysql finding products viewed by others	select product, count(id) num from the_table where     visitor_id in  ( select distinct visitor_id from the_table where product='5' and visitor_id!='this_visitor_id' ) and     product != '5' group by product order by num desc 	0.00158285738540586
16790758	35225	joining two tables, but only need top row from foreign table	select  `series`,  `thumbnail`, (select `ref` from `videos` as `v` where `v`.`sid` = `s`.`id` limit 0,1) as `ref` from `series` as `s` order by `series`.`id` desc limit 0,5 	0
16791062	20497	attached db version	select name, compatibility_level from master.sys.databases 	0.200752426186482
16791879	3575	is there a way to get some selected data first & rest data in ascending order through sql query	select country from tbl  order by case   when country='united state' then 0   when country='canada' then 1   when country='india' then 2   else 3 end, country; 	0
16792221	14522	how to get next 9 week numbers from current date in sql?	select     year(dateadd(week, x.y, basedate)),     datepart(iso_week, dateadd(week, x.y, basedate)) from     (select cast('20151231' as date) as basedate) d     cross join     (     values (0),(1),(2),(3),(4),(5),(6),(7),(8)     ) as x(y); 	0
16793427	31713	sum total rows of hours	select sec_to_time( sum( your_time_field ) ) from sohy_works where ..... 	0
16794686	27369	insert datetime in specific format in ms sql server	select convert( char(10), getdate(), 105) +  ' ' + convert( char(8), getdate(), 108) 	0.0966178930266109
16797684	13793	selecting from postgresql tables, excluding an array item	select * from your_table where 'certain tag' != all (tags); 	0
16797815	37550	mysql query to find items without matching record in join is very slow	select name, sum(e) count_entries from  (select name, 1 e, 0 c from entries   union all   select ent_name name, 0 e, 1 c from entry_categories) s  group by name  having sum(c) = 0 	0.0757418254832466
16798636	4071	query to limit number of requests per day	select count(*) from table_name where date_field >= curdate() 	0
16799155	1584	display duplicate row info as extra column	select r.resource_id, r.serve_url, r.title, r.category_id,  group_concat(ar.server_id) as server_id from active_resources ar left join resources as r on (ar.resource_id = r.id) where hr.resource_id = (     select id from resources     and id < 311     order by date_added desc     limit 1 ) group by r.resource_id, r.serve_url, r.title, r.category_id ; 	0
16800998	15361	need a query returns the records which contains different characters of a list	select * from [table] where [field] like '%[^a-za-z0-9öçşğüıöçşiğü-\& \.]%' 	4.61214542229229e-05
16801040	18702	getting a list of records with only one related record	select t.id, t.name from teams t join players p on t.id=p.team_id group by t.id having count(distinct p.id) = 1; 	0
16801603	21558	sql search and compare function	select a.hpd_ci as hpd_ci_grouped       ,a.submit_date       ,count(*)  from hpd_help_desk a join tiempos_grupos b   on a.hpd_ci = b.hpd_ci     and b.submit_date between a.submit_date and dateadd(day,6,a.submit_date) group by a.hpd_ci, a.submit_date 	0.410687650245204
16802139	21019	select without duplicate from a specific string/key	select email.* from email  join domain on email.foreign_key = domain.foreign_key                and substring_index( email.email, '@', -1 ) = domain.domain 	0.000765419788524162
16803076	20014	select records whose id does not appear in multiple tables	select *  from child  where id not in (select child_id from par1) and        id not in (select child_id from par2) 	0.000583225694802299
16805677	28136	price rounding to nearest 5c	select floor(price_after_discount * 20) / 20 as price from table 	0.0700931371729809
16806503	26010	retrieve data from tables having many-to-many relationships?	select t2.project_title from table2 as t2 join table3 as t3 on t3.project_id = t2.project_id where t3.tm_id = 10; 	0.000777687125059163
16808381	11411	postgresql: update my user table via java	select * from "user"; 	0.383582915818055
16808473	19791	invalid object name 'table1'	select db_name() 	0.433172862809933
16808802	12375	how to join single table multiple time on single column in sql server	select pe.*, c1.citizenname as patientname, c2.citizenname as doctorname      from tbpatientepisode pe     join tbpatient p on pe.patientidf = p.patientidp     join tbdoctor d on pe.doctoridf = d.doctoridp     join tbcitizen c1 on p.citizenidf = c1.citizenidp     join tbcitizen c2 on d.citizenidf = c2.citizenidp 	0.000531461702392124
16808917	20578	sql two columns of one table reference same column in another table	select l.link_desc,         s.[desc] description1,        s2.[desc] description2   from tbl_link l left join tbl_structure s      on l.fid_a = s.pid left join tbl_structure s2      on l.fid_b = s2.pid  where s.pid = 1 	0
16809395	5515	how to find out if an oracle column is securefile	select * from dba_lobs where securefile = 'yes' 	0.0252539394873748
16809882	234	what is universal sql way to obtain names of columns in primary key?	select pk.table_name, c.column_name primary_key   from information_schema.table_constraints pk    join information_schema.key_column_usage c     on c.table_name = pk.table_name     and c.constraint_name = pk.constraint_name  where constraint_type = 'primary key' 	0.000415234001608554
16811183	30813	applying a query as a filter on another query's result mysql	select  a.meta_value, a.meta_id  from `wp_postmeta` a inner join wp_posts  b on meta_id = id where a.`meta_key`= 'destination' and b.post_status = 'publish'  group by   a.meta_value 	0.0540852460750629
16811419	32927	how to write this stored procedure to return many row as a single string	select jobcode,           jobtitle,           experiences,           stuff((             select ', ' + e.educationname              from   tbleducation              where  educationid = je.educationid             for xml path('')          ), 1, 2, '')  as edu,           l.location,          ts.technicalskills,           jobdescription    from   tbljobs j           inner join tbljobs_education je                   on je.jobid = j.jobid           inner join tbljobs_locations jl                   on jl.jobid = j.jobid           inner join tbljobs_technicalskill jts                   on jts.jobid = j.jobid           inner join tbleducation e                   on e.educationid = je.educationid           inner join tbllocations l                   on l.locationid = jl.locationid           inner join tbltechnicalskills ts                   on ts.technicalskillid = jts.technicalskillid    where  j.jobid = @jobid 	0.0636933308407049
16812309	40041	order a record by date field's month	select    id         , f_name         , l_name         , f_name_english         , l_name_english         , gender         , experience         , b_date         , passport  from your_table order by month(b_date) 	7.79331625898117e-05
16812784	35626	query to find diff between two records	select  d1.movie_id , d1.rating as user1rating , d2.rating as user2rating , abs(d1.rating - d2.rating) from details d1 inner join details d2 on d1.movie_id = d2.movie_id where d1.user_id = 1 and d2.user_id = 2 	8.55979209445567e-05
16814435	14066	multiple left joins off of an id	select b.bid, b.name, numclicks, numexits, numreg from banner b left outer join      (select bid, count(*) as numclicks       from clicks       group by bid      ) c left outer join      on c.bid = b.bid join      (select bid, count(*) as numexits       from exits       group by bid      ) e      on e.bid = b.bid left outer join      (select bid, count(*) as numreg       from postregistered       group by bid      ) r      on r.bid = b.bid 	0.108866664776197
16815954	6028	sql select from table with inner join on itself	select a.id from mytable a join mytable b on b.id=some_special_value where a.x1 + a.x2 + a.y1 + a.y1 + b.x1 + b.x2 + b.y1 + b.y2 < 0 	0.109366535080142
16817639	34517	sql select values from joined table where value and value appears	select t.name  from track t join station_track st on t.id=st.id_track  join station s on s.id=st.id_station and s.name in ('first','second') group by t.name having count(distinct s.name)=2 	0
16818636	15460	fill one table with information from another	select date, month, dayname, workers_id,   case dayname     when 'monday' then monday_hours     when 'tuesday' then tuesday_hours   end as hours_to_work from table_1 cross join table_2 	0
16818691	1626	oracle get day name returns wrong name	select to_char(mydatecolumn, 'day'), mydatecolumn  from mytable  where mydatecolumn = to_date('01/04/2013','dd/mm/yyyy') 	0.00607769316149874
16821495	17519	t-sql regarding current sales and previous sales	select datepart(m,s1.saledate) as month, sum(s1.saleamt) as currentsales, (select sum(saleamt)  from sales where datepart(m,saledate)=datepart(m,s1.saledate)-1) as previoussales from              sales s1 group by datepart(m,s1.saledate) 	0.000386785763648239
16823000	41321	how would i query a sql database to find a date that a record first appeared?	select date, mail_date, dealer_id  from tablename  where date_diff(mail_date, date)>=5 	0
16824747	35768	check if n users are in same room	select roomid from user_to_room where userid in (2,5)   and roomid not in (select roomid                      from user_to_room                      where userid not in (2, 5)) group by roomid having count(distinct userid) = 2; 	5.00243826677239e-05
16831286	18538	mysql 2 queries combine into 1 query	select usr_id,        sum(if(coin_type = 1,coins,0)) as coinppv,        sum(if(coin_type = 3,coins,0)) as coinmly,         sum(coins) as total from `coin_tbl`  where coin_type in (1,3) group by usr_id 	0.00882513314911224
16831908	20387	how to do group by and order by in one query?	select s.* , f.* from tb_student s  inner join     (select email, max(created_on) as created_on     from tb_fees     group by email) sub1 on s.email = sub1.email inner join tb_fees f  on s.email = f.email and sub1.created_on = f.created_on where s.class = 6 	0.0566597979284557
16833399	36871	sql query to get data from single row as multiple rows	select   department_name,   'owner' from test where owner_id = 1234567 union all select   department_name,   'approver' from test where approver_id = 1234567 	0
16834068	34593	sql query with multiple tables, possible to apply group by only to count(*)?	select b.*, (select count(*) from pos where job_id=o.job_id) as count  from bookjobs b, publishers p, pos o  where b.cust_id=p.cust_id     and b.job_id=o.job_id     and b.jobtype='n'     and p.creditcode='c'; 	0.062617970212716
16835011	30513	selecting rows with repeating values in one column	select      max(t1.id) as id,      t1.code,      t1.sequence_number from mytest t1 inner join mytest t2 on t1.id <> t2.id and t1.code = t2.code and t1.sequence_number = t2.sequence_number group by t1.code,      t1.sequence_number     order by id 	0
16835669	22180	sql pivot columns and rows	select item_descr, [shop1], [shop2] from  (   select item_descr, shop_id, times   from [order]   )p pivot  (   sum(times)   for shop_id in ([shop1], [shop2]) )pvt; 	0.0168041220144448
16837351	17789	id ranges and incrementing	select max(id) from mytable where id between 1 and 9999 	0.00143869263967789
16837478	26340	partial enumeration of rows with sql/mysql	select a.*,        (select count(*)         from a a1         where a1.code = a.code and               a1.customer <= a.customer        ) as partial from a 	0.00602065484215618
16838228	31900	retrieve records using join query	select  a.day_name,         coalesce(b.totalcount, 0) totalcount from         (             select 'sunday' day_name, 1 ordby union all             select 'monday' day_name, 2 ordby union all             select 'tuesday' day_name, 3 ordby union all             select 'wednesday' day_name, 4 ordby union all             select 'thursday' day_name, 5 ordby union all             select 'friday' day_name, 6 ordby union all             select 'saturday' day_name, 7 ordby          ) a         left join         (             select  dayname(timestamp) day_name,                      count(*) totalcount             from    `emp_info`              where   date(timestamp ) > date_sub(curdate( ) , interval 1 week )              group   by dayname(timestamp)         ) b on a.day_name = b.day_name order   by a.ordby 	0.0164638121537889
16838522	28805	crm 2011 - sql query to retrieve text of option set?	select firstname, lastname, gendercodename from filteredcontact 	0.0188028294515502
16839941	21685	how to use select query multiple times on same column, sql	select   s1.author_id as questioner,   (select group_concat(distinct author_id separator " ") from students s2 where s2.post_type = 'answer' and s2.thread_id = s1.thread_id) as answerers from   students s1 where   s1.post_type = 'question' 	0.00195515457780169
16840148	30952	t-sql convert datetime and count entries for each date	select convert(varchar, datecreated, 2) as date, count(1) as qty from apps group by convert(varchar, datecreated, 2) order by date desc 	0
16840150	4732	sql join and sort	select * from ((select matches.*, teams.*, outcomes.against as goals from matches,teams,outcomes where     matches.home_team_id=11     and matches.away_team_id=teams.team_id       and matches.score_id=outcomes.outcome_id ) union (select matches.*, teams.*, outcomes.for as goals from matches,teams,outcomes  where matches.away_team_id=11     and matches.home_team_id=teams.team_id       and matches.score_id=outcomes.outcome_id )) as union_table order by goals, date desc limit 0,20; 	0.380630763567559
16840434	20053	how to get the column value prefrence over the other table value	select  f.email_address,             isnull(h.title,p.title) title,             isnull(h.first_name,p.first_name) first_name     from #tempfinal f     left join htc h         on f.email_address = h.email_address     left join pea p         on f.email_address = p.email_address 	0
16840755	32370	mysql - 3 different tables with the same column join in 1 column	select name from investigators where name like 'a%' union select name  from anientones where name like 'a%' union select name from monsters where name like 'a%' 	6.02746060596575e-05
16840850	9847	oracle select table name with results	select order_num, 'table_a' as table_name, part_num from table_a union all select order_num, 'table_b', part_num from table_b; 	0.0582895651987554
16842288	20067	query for comparing payments to remaining balance	select customer_no, payment_date, payment_amt, rem_balance, prev_bal from (     select customer_no, payment_date, payment_amt, rem_balance,          lag(rem_balance, 1,  0) over        (partition by customer_no order by rem_balance desc) prev_bal,     rownum r     from customer_payments     order by rem_balance desc ) where r > 1 and prev_bal + payment_amt <> rem_balance order by customer_no, rem_balance desc 	0.157327074306042
16844206	36689	get records from table a, that are not in table b	select tablea.id from tablea left outer join tableb on tablea.`full_name` = tableb.`full_name`    and tablea.adress = tableb.adress where tableb.`id` is null group by tablea.id 	0
16845687	26044	repeating an attribute value in sql	select  dt.year ,     db.dist_code ,     db.dist_name ,     db.s_code ,     db.s_name ,     fl.zip ,     sum(fl.num_births) over (partition by dt.year, db.dist_code),     total_enrollment  from    dbo.fact_enrollment_school as fs     inner join dbo.dim_building as db on fs.building_key = db.building_key     inner join dbo.dim_time as dt on fs.time_key = dt.time_key     left outer join dbo.fact_live_birth as fl on dt.time_key = fl.time_key                                             and db.building_key = fl.building_key; 	0.00433537796031281
16847473	4129	select identity without 'into"	select  row_number() over (order by newid()) ,       a.* from    table_1 a 	0.022101827573744
16848053	33650	unknown column on subquery	select allc.tc_code, allc.phy_prov_no,        count(allc.phy_pln_cd), sum(bcare.x12_cost_high),         total_low-sum(bcare.x12_cost_low),        total_high-sum(bcare.x12_cost_high),          avg_within_fac-sum(bcare.x12_cost_ave)  from final_mop_professional_sp_2013_bcare bcare join final_professional_sp_2013_bcare_allcounts allc on allc.phy_prov_no = bcare.phy_prov_no and allc.tc_code = bcare.tc_code group by allc.tc_code, allc.phy_prov_no 	0.494415905591851
16848825	7283	counting authors with just one article	select count(*) from      (      select autid      from authors_articles      group by autid      having count(distinct articleid) = 1     ) x 	0.00174773022806118
16851755	1334	sum daily total by category in mssql	select u.datetime, u.amount, u.country  from ( select datetime, sum(amount) as amount, country from table1 group by datetime, country union select datetime, sum(amount) as amount, 'total' as country from table1 group by datetime) u order by u.datetime, case when u.country = 'total' then 0 else 1 end, u.country 	0.000113563979766017
16853027	2516	sql server + 'merging results'	select userid, vehicleid, sum(searchcount) as searchcount from (select userid, vehicleid, count(vehicleid) as searchcount from membersearches  group by userid, vehicleid  union all select f.userid, v.autoid as vehicleid, count(v.autoid) as searchcount from favorites f left join [sellpost] sp on (f.postid = sp.autoid) left join [vehicle] v on (sp.carid = v.autoid) group by f.userid, v.autoid ) t group by userid, vehicleid 	0.131883715054524
16853647	12457	select rows from one tables which are not available in the second table	select * from table1  where not exists (   select host, user, name   from table2   where table2.host = table1.host and          table2.user = table1.user and          table2.name = table1.name ) 	0
16856553	15094	select total count from one table when field isn't found matching in another table	select t1.ip, count(t1.timestamp)  from t1 left outer join t2 on t1.ip = t2.ip where t2.ip is null group by t1.ip 	0
16861609	17153	oracle compare two count() different tables	select coalesce(a.progid, b.progid) progid,   coalesce(a.atotal, 0) atotal,   coalesce(b.btotal, 0) btotal from (   select progid, count(*) atotal   from tablea   group by progid ) a full outer join (   select progid, count(*) btotal   from tableb   group by progid ) b   on a.progid = b.progid where coalesce(a.atotal, 0) <> coalesce(b.btotal, 0); 	0.000489353655787674
16862517	26290	find the maximum consecutive years for each id's in a table(oracle sql)	select   id,   ayear,   byear,   yeardiff from (   select     a.id,     a.year ayear,     b.year byear,     (b.year - a.year)+1 yeardiff,     dense_rank() over (partition by a.id order by (b.year - a.year) desc) rank   from     years a     join years b on a.id = b.id          and b.year > a.year   where     b.year - a.year =        (select count(*)-1          from years a1         where a.id = a1.id              and a1.year between a.year and b.year) ) where   rank = 1 	0
16863332	23144	sql get a result comparing aggregate functions	select 1 from bookings where slot="given slot" and indate <= "given date" and outdate > "given date" 	0.206339797375976
16865061	31214	mysql query to count number of records 2 layers deep in query	select t.*, q.loan_count    from tblcustomer t join  (  select c.pkcustomerid, count(*) loan_count     from tblcustomer c left join  tblloan l       on c.pkcustomerid = l. fkcustomerid   where l.outstandingcurrentamount is not null      and l.outstandingcurrentamount > 0   group by c.pkcustomerid ) q on t.pkcustomerid = q.pkcustomerid 	0.000451278236992368
16867378	31774	mysql match up two tables using two columns with different value presentation	select ad_id, agent_id from agents join ads on gender_id = 1 or gender_id = (if (gender = 'female', 2, 3)) 	0
16868650	32962	sql sum off of parameters	select p.valueid,p.date_created,v.valuename,v.value,v.maxweekvalue, case when sum(v.value) < v.maxweekvalue then sum(v.value) else v.maxweekvalue end as sumd  from `points` as p  inner join `users` as u on u.id = p.userid inner join `values` as v on p.valueid = v.valueid where p.date_created  between subdate(curdate(), 7)  and curdate() 	0.10889679988682
16871065	33219	return all rows from a table for which the cat_id cannot be found in another table	select * from table_1 where table_1.id not in (select table_2.id from table_2) 	0
16871134	10674	how to link the tables mysql	select progress.id, progress.mark, subject.pname  from progress left outer join subject on (progress.id_subject= subject.id) where   progress.id_student = 1; 	0.016298420433492
16871300	24120	postgressql - temporal difference between first and last revision of a report	select r.*, rh.max_updated, rh.min_updated from report as r   join (      select report_fk,              min(updated_datetime) as min_updated,             max(updated_datetime) as max_updated      from report_history      group by report_fk   ) as rh on rh.report_fk = r.pk; 	0
16873056	36572	mysql query to exclude duplicate records	select agp_blog_id from wp_agp_settings_data where         agp_user_id = 2         and agp_blog_id not in(                 select agp_blog_id from wp_agp_settings_data where agp_keywords like "%keyword1%")         and agp_keywords_date between 1369872000 and 1370044800 group by agp_blog_id 	0.00142388721588504
16877305	12293	sql query to produce xml result	select xmlelement("country"    , xmlagg(     xmlelement("countryinfo"       ,xmlforest(ctry.name "name", ctry.districts "districts")        , xmlagg(         xmlelement("state",xmlforest(st.st_name "statename", st.st_population  "statepop")          )        )      )    )  ) from country ctry inner join states st on (ctry.name=st.country) group by ctry.name ,ctry.districts 	0.523426108009475
16878074	13795	how to extract numbers within a specified range from a column?	select * from t where right(col, 4) between '1.63' and '1.75' 	0
16878381	14416	mysql get max value with count for every row in group by	select site_id, max(download_date) as download_date, count(*) from pages_urls group by site_id; 	0
16878902	32908	even after specifying that users id not equal to 15 still it being shown in mysql results	select u.uid, u.religion    from users_profile u left join partner_prefrences p      on u.uid=p.uid and concat(',',p.religion,',') like concat('%,',u.religion,',%')   where u.uid != 15 	0.0036320390200575
16879568	36367	how can i convert the following flat records to a hierarchical structure in sql server?	select  l1        ,l1desc        ,cast(null as varchar(50)) as parent from    t1 union all select  l2        ,l2desc        ,l1desc from    t1 union all select  l3        ,l3desc        ,l2desc from    t1 union all select  l4        ,l4desc        ,l3desc from    t1 union all select  l5        ,l5desc        ,l4desc from    t1 union all select  l6        ,l6desc        ,l5desc from    t1 	0.095058724688875
16880415	34779	when select cursor sql get force close	select min(time), move, grid from highscore3; 	0.63285852699837
16880554	26099	sqlite query command to find all the entry starting with capital letter	select * from table1 where meaning glob '[a-z]*' 	0
16882126	14455	sql group type of query	select  department_id,              count(*)       from  employee      where  salary > 10000   group by  department_id     having  count(*) > 1 	0.256078185733833
16882511	19284	sql query to retrive matched words	select *, (colomn like "%$key1%") + (colomn like "%$key2%") + (colomn like "%$key3%") as match_rate from table where (colomn like "%$key1%" or colomn like "%$key2%" or colomn like "%$key3%") order by match_rate desc; 	0.0405480088277512
16882541	15627	how do you get other tag to increase intersection constraint?	select tag.idtag, tag, count(*) as nombre from tag join questtag on tag.idtag = questtag.idtag join (       select question.idquestion, count(*) tags       from question q2 join questtag qt2 on q2.idquestion = qt2.idquestion        and idtag in (1)       group by question.idquestion   )  temp on temp.idquestion = questtag.idquestion where tags = 1 group by tag.idtag, tag order by nombre desc, tag limit 0, 24 	0.000558028298881207
16882585	28301	mysql, find all employees of a "manager"	select dept.name as dept, loc.address1 as loc, emp.* from staff as mgr inner join department_staff as mgr_dept     on mgr_dept.staff_id = mgr.staff_id inner join departments as dept     on mgr_dept.dept_id = dept.dept_id     inner join location_staff as mgr_loc     on mgr_loc.staff_id = mgr.staff_id inner join locations as loc     on mgr_loc.loc_id = loc.loc_id     inner join (   select emp.*, dept.dept_id, loc.loc_id   from staff as emp   inner join department_staff as dept     on emp.staff_id = dept.staff_id   inner join location_staff as loc     on emp.staff_id = loc.staff_id   where emp.user_role = "employee" ) as emp   on emp.loc_id = mgr_loc.loc_id    and emp.dept_id = mgr_dept.dept_id where mgr.staff_id = 2 	7.69143405551792e-05
16886515	10928	sql: count from same table/field, but different values	select c.countryname as country,         count(case m.idmedal when 'gold medal' then 1 end) as cntg,        count(case m.idmedal when 'silver medal' then 1 end) as cnts,        count(case m.idmedal when 'bronze medal' then 1 end) as cntb from game g inner join participant p on p.fkgame = g.idgame inner join country c on p.fkcountry = c.idcountry inner join medals m on m.fkmedalist = p.idparticipant where g.name = "2012 summer olympics"  group by c.countryname order by cntg desc, cnts desc, cntb desc 	7.05558449896513e-05
16888410	33578	collecting data from mysql connected tables	select t1.* from t4 inner join t3 on (t4.cat_id = t3.cat_id) inner join t2 on (t3.d_id = t2.d_id) inner join t1 on (t2.id = t1.id) where t4.category_name = 'cancer'; 	0.00388026969340126
16889454	6202	how to find the total numbers of hours of 2 dates in mysql query	select      timediff(date_borrowed, date_returned) as diff from     tablename 	0
16889470	26073	sort one table by two rules	select * from table  order by rank desc, length(str) asc; 	0.00113586965500535
16890102	25557	sas datastep/sql select latest record from multiple records with same id	select id,max(date) from yourtable group by id; 	0
16890290	13872	display maximum match at first using like query in sql	select 1 as [i], * from tbl_book where book_name like '%"+strposition+"%' union select 2 as [i], * from tbl_book where book_name not like '%"+strposition+"%' and "+strpositionlist 	0.000150956667540474
16890911	11973	sql pull values from "last month" when dates have already been declared	select *  from orders where to_char(orderdate,'mm') = to_char(add_months(sysdate,-1),'mm') 	0
16891646	22277	mysql similar search with multiple keywords - sorting by most keywords in string	select     if( instr(your_column, 'dog')>0 ,1,0) +    if( instr(your_column, 'cat')>0 ,1,0) +    if( instr(your_column, 'house')>0 ,1,0) as my_rate,    * from     ... order by my_rate desc ; 	0.0384771871966624
16892159	7831	writing a mysql query that counts entries uniquely	select count(distinct area) from t_log where user_id = 5 	0.00749679661269798
16893097	20547	mysql combined query, ids from comma seperated list	select * from post a, meta b where find_in_set(a.id, b.linked)>0 and b.post_id= $id_post; 	0
16895354	22880	select and group mysql column by certain word in result	select  substring_index(browser,' ',1) as browser,  count(substring_index(browser,' ',1)) as count  from browsers group by substring_index(browser,' ',1) 	0.000722556464333354
16898454	27336	select where year = specific range of years	select  * from    yourtable where   [start year] <= 2006          and 2005 <= [end year] 	0
16899022	19361	select 1 record where two records have the the same values in different columns	select "station_1_i", "station_2_i" from mytable intersect select "station_2_i", "station_1_i" from mytable               where "station_2_i" < "station_1_i" 	0
16899139	26987	sql server 2012 aggregate on split date time?	select     t.dateutc, t.timestart, t.timeend, isnull(sum(a.actioncount), 0) from     @timetable t     left join     @actiontable a on t.dateutc + cast(t.timestart as datetime) <= a.datetimeutc and a.datetimeutc < t.dateutc + cast(t.timeend as datetime) group by     t.dateutc, t.timestart, t.timeend order by     t.dateutc desc, t.timestart desc; 	0.163292050757771
16899558	6033	using sql join and count	select `users`.`id`, `users`.`name`, r.numreceipts   from `users` inner join (    select count(`receipts`) as numreceipts    from `receipts`    group by `receipts`.`id` ) as r on r.uid = `users`.`id` order by r.numreceipts desc 	0.559913786482855
16901167	30348	postgresql : extract(epoch function over multiple rows	select     id id,     min(case rd.to when 'open' then "time" end) open_time,     min(case rd.to when 'close' then "time" end) close_time  from raw_data rd group by id 	0.430466713794662
16901622	38375	how does one construct a query that only returns this months rows, based on timestamp?	select * from tbl where  month(timesp) = month(now()) and  year(timesp) = year(now()); 	0
16902059	6241	sql statement keeps returning all rows instead of a few	select *   from dbo.lookup_test_tbl  where (contact = @contact and contact is not null) or       (shiptoname = @shiptoname and shiptoname  is not null)..... 	0.00954754812702739
16904723	28062	invert rows and cols sqlite	select sum(t1) as nbjoker, sum(t2) as nbplayed, sum(t3) as nbpause from ( select statvalue as t1,o as t2,0 as t3 from table_x where statname='nbjoker' union all select 0, statvalue, 0 from table_x where statname='nblayed' union all select 0, 0, statvalue from table_x where statname='nbpause' ) 	0.0575755643409538
16905230	4910	working of mysql query	select * mytable  where column1 not in (5, 8, 12) and column2 <> 300  and column3 = 200; 	0.799748458091291
16905848	28687	how can i join 2 tables together and unpviot from both into one column?	select bk, search, ckey, dn from  (   select t1_bk_no as 'bk',           t1_full_key as 'ckey',           cast(t1_info1 as varchar(100)) as [1],          cast(t1_info2 as varchar(100)) as [2],          cast(t1_info3 as varchar(100)) as [3],          cast(t1_info4 as varchar(100)) as [4],          cast(t1_info5 as varchar(100)) as [5]    from dbo.firsttable ) pnt unpivot( search for dn in ( [1],[2],[3],[4],[5] ) ) as upv where search not in ( '0', '999999999', '') and search is not null union all select bk, search, ckey, dn from  (    select t2_bk_no as 'bk',           t2_full_key as 'ckey',           cast(t2_info1 as varchar(100)) as [6],          cast(t2_info2 as varchar(100)) as [7],          cast(t2_info3 as varchar(100)) as [8]    from dbo.secondtable ) pnt unpivot( search for dnin ( [1],[5],[7] ) ) as upv where search not in ( '0', '999999999', '') and search is not null; 	5.97371431012112e-05
16905993	31287	select based on table name w/ sql for time series tables?	select userid, count(*) as numactions from actiontable where actiondate bewteen @date1 and @date2; 	0.000156338260888562
16906489	19299	getting the count in a single table mysql	select count(*), club_id     from members group by club_id   having count(*) > 1 	0.00197012141027216
16908338	9732	postgres sql group by without limiting rows	select a.id,         a.name,         array_to_string(array_agg(c.name), ',') tags_string,         case when strpos(array_to_string(array_agg(d.is_reminder), ','), 't') > 0 then 'overdue' else '' end overdue   from contacts a left join taggings b      on b.contact_id = a.id left join tags c      on b.tag_id = c.id left join tasks d      on a.id = d.contact_id  group by a.id 	0.0692922719772921
16908831	22196	how to pass array as arguments	select l.host, l.user, l.name, case when ml.host is null then 1 else 0 end is_to_highlight from logs l left outer join master_list ml on l.host = ml.host  and l.user= ml.user  and l.name = ml.name 	0.504867462018066
16909566	3865	sql pivot grid (rows to column	select idno,     max(case when field = 'gender' then value end) gender,     max(case when field = 'age' then value end) age,     max(case when field = 'school' then value end) school from mytable group by idno 	0.0291457402216355
16911139	28159	combined two mysql query into one	select      s.serialno,      s.productid,      s.description,      s.in_quantity,      s.uom,      s.shiptype,     s.receiveddate,      s.project_id,      if(exists(             select                  so.serialno              from                  stockout so              where                  so.serialno = s.serialno         ),         1,         0     ) as movementhistory,     so.out_quantity,      so.serialno,      so.siteid,      so.employee_id,      so.deliverytime,      so.receivername  from      stockin s left join  stockout so     on so.serialno = 'a23001rk3n'     and if(exists(                 select                      so1.serialno                  from                      stockout so1                  where                      so1.serialno = s.serialno             ),             1,             0         ) = 1    where      s.productid = 'ukl40114/11hp' 	0.00286334597521858
16911793	3034	select all rows that ends in 1 hour	select *     from konkurrencer          where slutter < date_add(now(), interval 1 hour)             and slutter >= now() 	0
16912070	1316	sql rent due at different frequencies	select  firstdate ,frequency from sampledata where case   when frequency = 'week' then datediff(dd,firstdate,getdate()) % 7         when frequency = 'fortnight' then datediff(dd,firstdate,getdate()) % 14         when frequency = 'month' and day(firstdate) = day(getdate()) then 0         when frequency = 'year' and day(firstdate) = day(getdate())                                 and month(firstdate) = month(getdate()) then 0 end = 0 	0.129286596514618
16914503	23123	having different order by for each column	select   last_value(field_info_1) over (     order by field_a range between unbounded preceding and unbounded following   ),   last_value(field_info_2) over (     order by field_b range between unbounded preceding and unbounded following   ) from table_1 	0.000259408183827219
16914542	32698	how to to branch the query among multiple tables	select  nvl(ee.name, nvl(ie.name, se.name)) from    mainemployees me left join         externalemp ee on      ee.emp_id = me.emp_id left join         internalemp ie on      ie.emp_id = me.emp_id left join         specialem se on      se.emp_id = me.emp_id where   nvl(ee.name, '') <> ''         or nvl(ie.name, '') <> ''         or nvl(se.name, '') <> '' 	0.00925126804327637
16915812	40913	unknown column error even though clearly the same name column exists in table	select `projects`.`proj_id`,`title`,`man_id`,`desc`  from `projects` , `assigned`  where projects.proj_id=assigned.proj_id   and assigned.user_id=1 	0.0229050346886622
16917859	36573	selecting latest record from multiple table of each category	select * from (                 select b.*,                         p.large_url                  from     books b                      left join book_pictures p                          on b.book_id = p.book_id                  order by b.amended desc                 ) as x  group by book_sub_category_id 	0
16919633	40276	if my resultset consists of grouped and summed records, how can i then sum/avg these?	select avg(weight) as average, sum(weight) as total from (     select          sum(a.weight * a.qty) as weight     from         `line` as a     left join         `order` as b on a.order_id = b.id     where         b.datetime > date_sub(now(), interval 6 month) and b.status = 'p'     group by a.order_id ) a 	0.000255466618086017
16919649	15954	how to split a row into many equals rows by a value in a column?	select id, tmpshoppingcart_id, storesku_id, o.quantity, [enabled] from [dbo].[tmpshoppingcartitem] t  cross apply (              select 1              from master..spt_values v              where v.type = 'p' and v.number < t.quantity              )o(quantity) 	0
16920162	29148	physical_name without master access	select name, filename from sysfiles 	0.365374930088396
16920318	4237	sql matrix query	select a.account_id, b.follow_up_count, c.callback_count, d.service_count from tworkorderevent a left outer join (     select account_id, count(eventname) as follow_up_count     from tworkorderevent     where eventname like 'follow up'     group by account_id )b on a.account_id = b.account_id left outer join (     select account_id, count(eventname) as callback_count     from tworkorderevent     where eventname like 'callback'     group by account_id )c on a.account_id = c.account_id left outer join (     select account_id, count(eventname) as service_count     from tworkorderevent     where eventname like 'service'     group by account_id )d on a.account_id = d.account_id 	0.618181763830543
16920852	25198	sum up each row of database sqlite	select sum(column) from table; 	6.82857690416187e-05
16922962	23873	mysql count occurrences of special character in a field	select length('aa:bb:cc:dd')-length(replace('aa:bb:cc:dd',':','')); 	0.00217253944422597
16923096	35381	how to sum totals from a subquery using mysql	select concat(pe.first, ' ', pe.last) as name,        tp.empid as 'empl id',        date_format(tp.punchdatetime, '%m-%d-%y') as 'punch date',        truncate(           (sum(unix_timestamp(punchdatetime) * (1 - 2 * `in-out`)) / 3600),           3)           as 'hours worked'   from timeclock_punchlog tp left join prempl01 pe on tp.empid = pe.prempl  where tp.punchdatetime >= '2013-5-1' and tp.punchdatetime < '2013-5-28' group by tp.empid; 	0.0344930883434102
16923486	19947	daily export mysql table to folder/url	select * into outfile "data/mostrecent.csv" fields terminated by ',' optionally enclosed by '"' lines terminated by "\n" from surveytable; 	0.00720509515982997
16923635	23531	tsql program to find if we have more than one deptno in that location display the first one	select top 1 deptno, dname from yourtable where loc = 'yy' order by deptno 	0
16925048	5856	return xml document from sql server 2008	select * from table for xml raw 	0.060233486115575
16926774	7708	how to query date range using between in varchar(10) format mm/dd/yyyy	select docnum, datedue   from prod_po_list  where str_to_date(datedue, '%m/%d/%y')        between date_sub(curdate(), interval 365 day)        and curdate() 	0.00132453452621278
16927415	30885	ssrs report with multiple child tables	select wo.wonum, wo.description as workorderdescription, wo.location, l.regularhrs, l.laborrate, l.totalcost, m.description as materialdescription, m.quantity, m.unitcost, m.totalcost as materialcost, s.description as servicedescription, s.hours, s.laborrate, s.totalcost as servicecost from workorder as wo inner join labor as l on l.refwo = wo.wonum inner join material as m on m.refwo = wo.wonum inner join service as s on s.refwo = wo.wonum where billable = 1 and status = 'comp' 	0.0333293735512174
16927833	4245	how do i get a count of results from a query?	select count(soh.stockcode)   from dbo.stock_items soh  where soh.stockcode in (               select sli.stockcode                 from stock_loc_info sli                where sli.qty > 0                   and sli.location in(1,2,3,9,11)                        ) 	0.000556559543344361
16928007	25036	need view to calculate difference even if there is no child record	select `alphabase`.`bill_ing_sheets`.`invoice_no` as `invoice_no`, `alphabase`.`bill_ing_sheets`.`total` as `total`, (case when `alphabase`.`bill_pay_allocations`.`amount` is not null then `alphabase`.`bill_pay_allocations`.`amount` else 0 end) as `amount`, (case when `alphabase`.`bill_pay_allocations`.`amount` is not null then `alphabase`.`bill_pay_allocations`.`amount` else 0 end) - `alphabase`.`bill_ing_sheets`.`total` as `difference`  from `alphabase`.`bill_ing_sheets` left outer join `alphabase`.`bill_pay_allocations`  on `alphabase`.`bill_pay_allocations`.`billing_id` = `alphabase`.`bill_ing_sheets`.`billing_id`  left outer join `alphabase`.`bill_payments`  on `alphabase`.`bill_payments`.`payment_id` = `alphabase`.`bill_pay_allocations`.`payment_id` 	0.000328332090376399
16928340	9144	how to export table data to csv where date 'today'	select 'title', 'date', 'count' union all select title,date,count from sales_com where date = curdate() into outfile 'u:/csv-livedb-upload/sales_com/data.csv' fields terminated by ',' enclosed by '\"' lines terminated by '\r\n'; 	0.000177510089843316
16929312	17117	mysql - get ids of summed rows	select `finish_id`,            sum(`finishing_sf`)   as `sum`,            group_concat(`id`)    as `item_ids`        from `quote_items`   group by `finish_id` 	0
16929600	6591	how to use access data in a table that's connected thru a join?	select * from sections where section_id in (select section_id from accesscontrol where user_id=39) 	0.319650948845524
16933482	18163	generate multiple sums from the same query	select   sum(case when person_id = 101 then total_amount else 0 end) as person_101,   sum(case when person_id = 102 then total_amount else 0 end) as person_102,   sum(case when person_id = 103 then total_amount else 0 end) as person_103 from   my_table where   date_time ='2001-12-11' 	0.000436982030288868
16934372	14399	selecting customer with maximum orders	select     * from     my_table order by     numoforders desc limit 1 	0
16935404	10753	mysql row with table name	select id, title, release_date, 'tv shows' as table_name from `tv shows` union all select id, title, release_date, 'movies' as table_name from `movies` 	0.00777436522076029
16935438	14536	mysql count query across multiple tables	select     d.dept_name,    sum(if(re.grade='a', 1, 0)) as 'a',    sum(if(re.grade='b', 1, 0)) as 'b',    sum(if(re.grade='c', 1, 0)) as 'c',    sum(if(re.grade='d', 1, 0)) as 'd' from     dept d inner join     users u on     u.dept_id=d.dept_id inner join    report_info ri on     ri.uid=u.uid inner join     report_eval re on    re.report_id=ri.report_id group by     d.dept_name 	0.0445068758206661
16936181	5389	mysql order by date field which is not in date format	select ... from ... order by str_to_date(yourdate,'%d-%m-%y') desc 	0.00817114934620054
16936719	33842	count(*) column to the right of the data?	select name,count(*) from db.db group by name order by name desc 	0.00459813135965858
16936734	34649	sql remove duplicates on oldest date	select *  from [granite].[dbo].[report_app_transactions] r1 inner join  (     select barcode, max(date) as mdate     from [granite].[dbo].[report_app_transactions]     group by barcode ) r2 on r1.barcode = r1.barcode and r2.mdate = r1.date where r1.transactiontype='pick' 	0.0051972321804493
16937393	24914	duplicate row if: ora-01427: single-row subquery returns more than one row	select s.sub_project_id,          a.activity_no,        p.resource_id from s     join a on s.sub_project_id = a.sub_project_id and a.project_id = s.project_id    left outer join p on p.activity_seq = a.activity_seq where s.project_id = 'propstot' 	0.00128442868640063
16938436	36667	query not returning all the rows using inner join	select table1.* , table2.value  from table1  left join table2  on table1.id = table2.id  and table2.label = "currency" 	0.219316958403823
16939232	32002	word (along with space) search in t sql	select count (*) as [count], 'strings with 1' as [comment] from a  where transaction like cast (@transaction as varchar(50)) +'???1%' union all select count (*) as [count], 'strings with 0' from a  where transaction like cast (@transaction as varchar(50)) +'???0%' 	0.0727604558528846
16943196	25700	postrgresql 8.4: summation by account numbers	select substring(a.acctno from 1 for g.g) as level, sum(a.credit)     from account a, generate_series(1,5) g where length(a.acctno) >= g.g group by 1 order by 1 	0.110778003826033
16944448	3174	select from different table with different column in one query	select  a.priority,a.ticket_status ,a.title, b.name ,c.department_name, tu.mail,tu.name  from  razorphyn_support_list_tickets a,  razorphyn_support_users b,  razorphyn_support_departments c, razorphyn_support_list_tickets lt, razorphyn_support_users tu where  a.enc_id=?  and b.id=a.user_id  and c.id=a.department_id  and tu.id=lt.operator_id limit 1; 	0
16945974	23152	concatenating a column within the same column in sql server	select s1.orderid, stuff(         (select ','+p.productname as [text()]         from salesorder s             join product p on p.productid = s.productid and p.onhold = true         where s.orderid = s1.orderid         group by s.orderid         for xml path (''))     ,1,1,'') as productsonhold from salesorder s1 group by s1.orderid 	0.000693386868813308
16947074	35402	sql select users who age is 17 between date range	select * from users  where birthdate between dateadd(year, -18, '2013-03-05')                        and dateadd(year, -17, '2013-06-05');   select * from users  where birthdate between dateadd(year, -18, '2012-02-10')                        and dateadd(year, -17, '2013-06-05');   	0
16947512	30140	add the column's with alias name in sql server	select teamprojectsk, new + active + resolved + closed as total_count, new active, resolved, closed from ( select teamprojectsk,        sum(case when d.system_state = 'proposed' then 1 else 0 end) as new,   sum(case when d.system_state = 'active' then 1 else 0 end) as active,   sum(case when d.system_state = 'resolved' then 1 else 0 end) as resolved,   sum(case when d.system_state = 'closed' then 1 else 0 end) as closed        from   (    select w1.system_id, w1.teamprojectsk, w1.system_state, w1.system_rev,    row_number() over(partition by w1.system_id, w1.teamprojectsk, w1.system_state order by w1.system_rev desc) rn    from dbo.dimworkitem w1          ) d    where rn = 1    and d.system_rev = (select max(w2.system_rev) from dbo.dimworkitem w2 where w2.system_id =   d.system_id)    group by teamprojectsk ) a    order by teamprojectsk desc 	0.042164318778315
16948949	19525	how to select the total unique number in sql	select count(distinct group) from table where type = 'a' 	0
16950322	29206	how to get data for each month from current date sql query	select year(createstamp), month(createstamp) count(r.regid) as totalcount  from registration r group by year(createstamp), month(createstamp) order by year(createstamp), month(createstamp) 	0
16950857	5528	separate data using php/mysql based on table name	select * from ( select "matches" as source, m.title as matchtitle,  c.casteralias as matchcaster, m.dateadded as matchdate, comp.eventname  from matches m left join casters as c on c.casterid = m.casterid left outer join competitions as comp on m.eventid = comp.id where m.title like '%".$search."%' union select "caster", m.title,  c.casteralias,m.dateadded, comp.eventname  from matches m left join casters as c on c.casterid = m.casterid left outer join competitions as comp on m.eventid = comp.id where c.casteralias like '%".$search."%' union select "event", m.title,  c.casteralias,m.dateadded, comp.eventname  from matches m left join casters as c on c.casterid = m.casterid left outer join competitions as comp on m.eventid = comp.id where comp.eventname like '%".$search."%') alllikes order by matchdate desc 	8.35642249661766e-05
16951616	24644	grouping values from dynamic columns	select * from tab2 a join     (select id1, id2, min(root), name from tab2         group by id2, id1, name) b    on a.id1 = b.id1 and b.id2 = a.id2 and a.name = b.name 	0.00227636496597509
16953384	21479	multiple substrings with table and column aliases	select pagerequested,     count(pagerequested) as hits from (     select substring_index(substring_index(origcmd, '.', -2), ' ', 1) as pagerequested      from weblog) temp group by pagerequested order by hits desc 	0.053611984568194
16953748	32969	combining results in two tables	select a.customerno, b.customername, sum(a.amount)  from  (     select customerno, amount from table1    union all     select customerno, amount from table2 ) a  join customers b on a.customerno = b.customerno group by a.customerno, b.customername 	0.0113741249095791
16954908	4255	comparing value with comma separated values in select statement	select field1 from table where ',' + replace(commaseparatedlist, ' ', '') + ',' like '%,aaa,%' 	0.000129798706287569
16955044	10289	print mysql rows only once	select distinct(htno),name,fname from resbook where htno=:id 	0.000148264245752386
16955589	37430	select an xml attribtute of parent node with condition for child node	select cfg.session_xml.extract('/ns1:configurationsession/ns1:products/ns1:product[ns1:configid=5621507]/@qty', 'xmlns:ns1="http: from vz_cfg2_sess_xml cfg 	0.0031048496230245
16958908	35143	php and mysql group_concat with separator comma and search where concat by comma	select      products_id ,      group_concat(options_values_id separator ',') as ops  from      products_attributes  group by      products_id having     find_in_set('1',ops)     or find_in_set('3',ops) 	0.53453019568091
16960753	24282	mysql search multiple records in the same table with the same first part of primary key	select sale_code, sum(price * quantity)     from sale_item     group by sale_code     order by sum(price * quantity) desc     limit 1; 	0
16960909	35613	mysql relational schema planning	select player, "competition1" from players where competition1_eligible = 1    union all select player, "competition2" from players where competition2_eligible = 1    union all select player, "competition3" from players where competition3_eligible = 1    union all select player, "competition4" from players where competition4_eligible = 1 	0.749797174706374
16961555	21014	ms sql query to select distinct product_id	select fp.fcast_product_id, fp.id, fp.customer_id, pm.product_name  from  f_product as fp  left join product_master as pm  on fp.customer_id=pm.customer_id  and pm.product_id =fcast_product_id where fp.customer_id = '10004' 	0.425929259246121
16963508	18820	get stats for each day in a month without ignoring days with no data	select `date`, count(*) from input_calendar c left join data d on c.date=d.date group by `date` 	0
16963940	35622	group by including 0 where none present	select lists.id as list_id, count(posts.list_id) as num_posts from lists left join posts on posts.list_id = lists.id group by lists.id 	0.0840247266804497
16964100	36872	how to sql query for unique values but include an extra date field?	select report_numbers, min(creation_date) mincreationdate from reports group by report_numbers order by mincreationdate 	0.000629329241258707
16964556	25913	mysql : select sum(value)	select     day_col,     if (         (select count(value_col) from mytable as subt where subt.day_col < t.day_col) >= 3,         (select sum(value_col) from mytable as subt where subt.day_col < t.day_col and date_add(subt.day_col, interval 3 day) >= t.day_col),         '     ) as total from     mytable t 	0.445071290752215
16965457	26693	mysql rows to columns query	select acccode, sum(case when acccode ='hon' then 1 else 0 end) purchasedhonda, sum(case when acccode='yam' then 1 else 0 end)  purchasedyamaha, ... sum(case when acccode='vic' then 1 else 0 end)  purchasedvictory from _emarsys_vehiclessold where acccode<>''  group by acccode 	0.00736780093295779
16967199	15402	fetch multiple rows and store in 1 variable - oracle stored procedure	select listagg(student_name,',')  within group (order by student_name) from student.student_details where class_id= 'c'; 	0.0164196973573914
16969737	37312	sql query join for more than 2 tables	select state,     table1.section_number,     maint_charge,     (maint_charge / total_maint_charge),     (fee * (maint_charge / total_maint_charge)) from table1     join table3 on table1.areacode=table3.areacode     join table2 on table1.section_number=table2.section_number; 	0.123305457496509
16971119	14062	mysql select and fetch table data starting from specific value	select * from `table` where     concat(`class`, `group`, `name`) >= '2amarcus' 	0
16973533	32418	how to select data based on the joint results of subquery	select a.value from a join      b      on a.dates = b.dates and a.name = b.cc where b.date between date1 and date2 	0.000311447263635392
16975136	16983	mysql database structure to represent one user following another?	select pst.userid, pic.title     from pictures pic       inner join posted_by pst on pic.title = pst.title       left join followers flw on pst.userid = flw.userid where pst.userid = <userid> or flw.followerid = <userid> 	0.00321283603124808
16977230	3643	how to convert milliseconds to date in sqlite	select strftime('%y-%m', millisfield / 1000, 'unixepoch') from mytable 	0.0104163412345465
16979521	26720	mysql retrieve products and prices	select p.*, q2.*   from  (   select product_id     from price    where `start` >= '2013-05-01' and `end` <= '2013-05-15'    group by product_id   limit 0,10 ) q1 join  (     select *       from price      where `start` >= '2013-05-01' and `end` <= '2013-05-15' ) q2 on q1.product_id = q2.product_id join product p      on q1.product_id = p.id 	0.0010822668240736
16979540	26964	mysql: column values as column name in select result	select       sum(if(activity = 'form',1,0)) as 'form',     sum(if(activity = 'login',1,0)) as 'login',     sum(if(activity = 'reg',1,0)) as 'reg' from      tbl_tracking where      id = 141      and variant = 2 	0.000860889105018506
16983010	8665	unusual results from mysql in clause	select year(from_unixtime(mt.`date_created`)) as 'year', month(from_unixtime(mt.`date_created`)) as 'monthnumber', monthname(from_unixtime(mt.`date_created`)) as 'monthname', weekofyear(from_unixtime(mt.`date_created`) ) as 'week', `at`.`group_name`, count(`mt`.`mt_id_pk`) as 'record_count'  from `my_table` as `mt`  inner join `another_table` as `at` on `mt`.`at_id_fk` = `at`.`at_id_pk`  where `at`.`group_name` in ('something1','something2','something3') and year(from_unixtime(mt.`date_created`)) = year(now()) group by `at`.`group_name`, `monthnumber` order by `monthnumber` desc 	0.462178676911536
16983793	23325	mysql - select statement, if condition fail return empty string	select agent.name,agency.title from agent left join agency on agent.titleid = agency.titleid where agent.id = "1" 	0.419640453220566
16984502	40562	compare avg(integer) with avg(integer) of a category	select productname, price, categoryid from `products` p where price > (select avg(price) from `products` where  categoryid = p.categoryid) 	0.00342256276459926
16984662	9491	mysql union with different columns applying default value?	select col1, col2, col3, null as col4   from table1 union all select col1, col2, null, col4   from table2 	0.00318977033285124
16987445	14391	how did this number become this datetime?	select datediff(d,'1969-12-31','2013-06-05') 	0.223260647265829
16987452	7749	json_encode for two columns with same name in php	select faculty.name as facultyname,sector.name as sectorname from faculty inner join sector     on faculty.sector_id=sector.id 	0.000531437181277309
16987772	15857	select or do i need an update	select zooanimals.mopid, zooanimals.mopserviceimpacted "type", '          ' as found_this,     zoonotes.mopnote, case when zoonotes.mopnote like '%fttt%' then 'fttt was triggered' else '' end, case when upper(zoonotes.mopnote) like '%aardvark%' then 'aardvark was triggered' else '' end, case when upper(zoonotes.mopnote) like '%zebra%' then 'zebra was triggered' else '' end from mopuser.zooanimals inner join mopuser.zoonotes on zooanimals.mopid=zoonotes.mopid where zooanimals.mopstart between sysdate and (sysdate+14) and upper(zooanimals.mopstatus) != 'complete' and upper(zooanimals.mopstatus) != 'cancelled' and ( zooanimals.mopserviceimpacted like '%fttt%'     or     (     upper(zoonotes.mopnote) like ''%aardvark%'     or upper(zoonotes.mopnote) like '%zebra%'  )  ) 	0.783711782777202
16987991	24673	how can i select tags from mysql sorted by creation_date and name but remove duplicate name?	select name, max(created_at) from yourtable group by name order by max(created_at) desc 	0
16988211	9563	select distinct out of distinct	select  etar.emplkey, min(emp.emplfullname)  from employeetarget etar  inner join dimemployee emp on emp.emplkey = etar.emplkey  inner join dimbranch br on br.branchid = etar.branchid  where etar.branchid = 8  group by etar.emplkey 	0.00998890853544345
16988326	81	query all table data and index compression	select [t].[name] as [table], [p].[partition_number] as [partition],     [p].[data_compression_desc] as [compression] from [sys].[partitions] as [p] inner join sys.tables as [t] on [t].[object_id] = [p].[object_id] where [p].[index_id] = 1 select [t].[name] as [table], [i].[name] as [index],       [p].[partition_number] as [partition],     [p].[data_compression_desc] as [compression] from [sys].[partitions] as [p] inner join sys.tables as [t] on [t].[object_id] = [p].[object_id] inner join sys.indexes as [i] on [i].[object_id] = [p].[object_id] where [p].[index_id] = 2 	0.0200678200076289
16988663	32602	sum multiple columns but one in mysql query	select     sum(xxs) as xxs,     sum(xs) as xs,     sum(sm) as sm,     sum(md) as md,     sum(lg) as lg group_concat(other separator '|-|') as other, style, color from orders where id in(list...) group by style, color order by style, color; 	0.0035604703834751
16988850	29726	sql select random from multiple table and order by specific criteria on one table	select top 1(a.id), a.mls_number, a.parcel_name, a.property_type, a.ownership_type,     b.filename, b.photoorder, c.county_name from property as a inner join (select listingid , filename, photoorder from listingphotos where photoorder = 1        ) as b on a.id = b.listingid  left join counties as c on a.county_name = c.id where a.iscommercial = 'true' order by newid() 	0
16990034	24407	sum database values grouped by a second table keys	select buildingcode, sum(amount) from bill join billpayments on bill.barcode = billpayments.barcode group by buildingcode 	0
16993543	18864	sql searching a string for numbers between different criteria	select * from test where document mylist like '%-c0[2-5]%' 	0.00045026545297235
16993639	15531	select records that have top n counts for one column	select t.id, t.a, t.b from (select t.*, dense_rank() over (order by idcnt desc, id) as seqnum       from (select t.*, count(*) over (partition by id) as idcnt             from t            ) t      ) t where seqnum <= 2; 	0
16994871	9581	sql. is there any efficient way to find second lowest value?	select price from table where price in (     select          distinct price      from      (select t.price,rownumber() over () as rownum from table t) as x      where x.rownum = 2  ) 	0.000781371977418589
16995161	1030	sql: couple people who assisted to the same event	select distint ae.id_evn,      p1.nom_pers persona, p2.nom_pers personb  from assieted_to ae      join people p1          on p1.id_pers = ae.id_pers       join people p2          on p2.id_pers = ae.id_pers            and p2.id_pers > p1.id_pers 	7.02990468597481e-05
16997734	13979	how do i order by max(date) in a subquery in mysql?	select sa.pathname,        sa.id_user,        so.id id_song,        so.name song_name from songs so join (select id_song, max(`date`) as maxdate from samples group by id_song) mx   on so.id = mx.id_song join samples sa    on mx.id_song = sa.id_song and mx.maxdate = sa.`date` where so.finished = 'false' order by mx.maxdate 	0.571723404462607
16998873	18052	random join in sql server	select *, (select top 1 webpath from productimage pi  where pi.productid = p.productid order by newid()  ) as webpart from product p 	0.480398999988133
16999326	7567	how to write loop statement in sql to get values in one parameter	select @param = min(p.value) + ' ' + max(p.value) from    vendors v join    pconfig p on v.vendorid = p.vendor_id join    configitems c on p.configid = c.configid  where   v.description = @vendor and     itemname in ('xps_paid', 'xps_unpaid') 	0.027487197491471
17001697	634	mysql pick pieces of data which have the same value in their column	select group_concat(concat(`name`, ' ', `surname`)), count(*) as cnt from tbl group by idd having cnt > 1 	0
17001969	7029	mysql sum alias	select (`number_of_rooms`) as total, id_room_type,      count( fk_room_type ) as reservation ,       sum(number_of_rooms - count( fk_room_type ) ) as result  from room_type      left join room_type_reservation           on id_room_type = fk_room_type  group by id_room_type  having sum(number_of_rooms - count( fk_room_type ) ) > 10 	0.576786363062419
17003283	374	query for a string containing a particular character	select * from person_info where name like '%k%' 	0.0256583825118893
17005241	9457	dividing and multiplying columns in mysql	select    i.id,   c2.cur,   i.price * c2.toeur / c.toeur from itms i   join conv c on i.cur = c.cur   join conv c2 on c2.cur = 'gbp' order by i.id 	0.00798934702671336
17005277	21729	select value if it appears elsewhere in table	select t1.* from table1 t1 join table1 t2  on t1.col1 = t2.col2  and t1.col2 = t2.col1 	0.00744492178754586
17007039	22039	sql grouping within a table	select *   from default_ps_products p  order by manufacturer_id,            field(coalesce(sort_order, 0), 0),           coalesce(sort_order, 0) 	0.0611180454429715
17007226	40106	how to write a sql statement to get a value from all users?	select users.id, users.username, count(orders.number) as units  from users inner join orders  on orders.user_id = users.id  group by users.id,users.username; 	0
17007525	34263	stat report combining data from 3 tables - join or subquery	select p.name,         count(m.matchid) matchplayed,         sum(s.goals) totalgoals,        max(s.goals) highestscore,        sum(s.minutes) minutes,        sum(case when s.goals >= 3 then 1 else 0 end) hattrick   from tbl_matchdetails m join tbl_matchstat s     on m.matchid = s.matchid join tbl_player p     on s.playerid = p.playerid  where m.tournament = 'cl'  group by p.name 	0.167586655450333
17008079	18883	sql - complex query using foreign keys	select     sum(p.p_sl_value * p.p_sl_quantity) as sales_monthly_income,     month(s.sale_date) from p_sale p inner join sale s on s.sale_code = p.sale_code group by month(s.sale_date) 	0.346427233104596
17009811	28030	mysql merge timestamps from union into one timestamp column	select id, t.teimestamp, 1 from tracks t union all  select id, s.teimestamp, 2 from status s union all  select id, g.teimestamp, 3 from gigs g 	0
17010105	16913	mysql doing two counts with two different wheres from the same table	select * from    (select count(id) as count_one from table where id = 1) a,   (select count(id) as count_two from table where id = 2) b 	0
17010555	5152	comparing multiple columns in mysql	select * from  stream_view  where (event = '$event'  and e_id <> '$e_id')  or  event<> '$event'; 	0.011955613533128
17011252	4668	select without displaying null	select * from your_table where sub_qua != 0 	0.13751397690936
17014508	36440	sql join and union all	select       a.customerid, a.firstname, a.lastname, a.address, a.emailaddress, b.customerid, b.date, b.memberid, c.customerid, c.lengthofstay from table1 as a left join table2 as b on ( a.customerid = b.customerid) left join table3 as c on ( a.customerid = c.customerid) 	0.19460578020795
17017089	36408	php/mysql table named "int"	select * from `int` where ... etc. 	0.0491176870528087
17017509	24801	join tables with aggregate value	select        a.name     , value1 = isnull(value1, 0)     , value2 = isnull(value2, 0) from (     select            name         , value1 = sum(value1)     from dbo.[table-a]     group by name ) a left join (     select            name         , value2 = sum(value2)     from dbo.[table-b]     group by name ) b on a.name = b.name 	0.248631382851545
17017696	31888	php pdo weird row results	select count(distinct company.id) from ... 	0.50666576601745
17019399	15252	postgres - how to choose last transactions per user_id, per transaction type?	select distinct on (user_id,msg_code)        * from  raw_data where record_time > '2013-05-28 17:06:01' and record_time < '2013-05-30 17:06:01' order by user_id, msg_code asc, record_time desc 	0
17019708	521	translate query from mssql to mysql	select       v.localcol     , v.funktion_heizband_verdunster1b     , m.funktion_ventilatoren_verdampfer_msr     , m.funktion_glykolpumpe1_tankverbindung from verdunster1b_digital as v join maschinenraum_digital as m on m.localcol = v.localcol where v.localcol between '20130609' and '20130610'        and v.reasoncol = 'zeit ein'        and minute(v.localcol) in (0, 15, 30, 45) limit 0, 7500 	0.514955237897104
17020384	17684	retrieving result from multiple many to many relation tables with limit	select distinct ven.venue_id, ven.name, e.event_id, e.event, t.type_id, t.type, s.style_id, s.style from (select * from venues v limit 0,5) ven left join venue_events ve on ven.venue_id = ve.venue_id left join events e on e.event_id = ve.event_id left join venue_types vt on ven.venue_id = vt.venue_id left join types t on t.type_id = vt.type_id left join venue_styles vs on ven.venue_id = vs.venue_id left join styles s on s.style_id = vs.style_id 	0.000964658872997939
17021659	39521	sort table by group with highest sum and displaying individual entries	select   yourtable.* from   yourtable inner join (   select name, sum(score) as score from yourtable group by name )   as totalscores     on totalscores.name = yourtable.name order by   totalscores.score desc,   yourtable.name,   yourtable.score   desc 	0
17023840	10448	display second maximum salaried employee details using joins	select e.eno,e.name,e.dept,e.desig,s.sal from emp_mstr e  inner join sal_mstr s  on e.eno=s.eno where s.sal= ( select max(sal) from  sal_mstr where sal not in (select max(sal) from  sal_mstr)); 	8.35352124034958e-05
17024518	28797	joining many tables together using key from first table for all joins?	select a.*,b.*,c.* from tablea a  left join b on a.id = b.id left join c on a.id = c.id 	0
17025345	37466	year-to-date summary by month in access sql	select format(t1.completiondate,"mmm-yy") as [month], (         select sum(t2.amount)         from projects as t2         where month(t2.completiondate) <= month(t1.completiondate)     ) as [amount] from projects as t1; 	0.0621009965619106
17025493	36707	sum on calculated field is doubled	select    invoices.*,   sum(invoice_items.quantity * invoice_items.price_cents) as total, t.amount_paid from invoices left join invoice_items    on invoice_items.invoice_id = invoices.id left join (select invoice_id, sum(transactions.amount_cents) as amount_paid from transactions group by invoice_id) t   on invoices.id = t.invoice_id group by invoices.id 	0.0685167641737213
17026954	25329	how to sort data according to value of data in descending order	select * from (select "web technologies html", skill_web_html skill_level       from student_skills       where student_id = @id       union       select "web technologies css", skill_web_css       from student_skills       where student_id = @id       union       ...       select "web technologies j-query", skill_web_jquery       from student_skills       where student_id = @id       union       ...) all_skills order by skill_level desc 	0
17030340	26503	what is the best way to select a rows by comparing enum and set columns	select * from `tabname` where `enum_field` = 1 or `enum_field` = 2 	0.000460202772156803
17030887	13960	selecting values through mapping table.	select t_sendertable.namefull as "sendername"      , t_recievertable.recievername as "recievername"    from dbo.t_sendertable as t_sendertable  inner join maptable     on t_sendertable.id = maptable.senderid  inner join t_recievertable as t_recievertabler     on maptable.recieverid = recievertable.id 	0.00439914693877178
17031974	9529	sql column names and values	select cols.colname,        (case when cols.colname = 'recid' then recid              when cols.colname  = 'date' then date              when cols.colname  = 'time' then time              when cols.colname  = 'firstname' then firstname              when cols.colname  = 'lastname' then lastname         end) as value from t cross join      (select 'recid' as colname union all       select 'date' union all       select 'time' union all       select 'firstname' union all       select 'lastname'      ) cols 	0.00220346186414881
17033810	13538	how to signify which table a certain row comes from?	select "table1" which, colx the_col from table1 where ... union select "table2" which, coly the_col from table2 where ... ... 	0
17034071	39469	mysql do inner join if specific value is 1	select      e.*, u.name as event_creator_name  from `edu_events` e      left join `edu_users` u          on u.user_id = e.event_creator  where      where e.event_date_start between date('2013-06-01') and date('2013-07-01')     and (         e.event_type = 1 or         exists             (select 1 from `edu_event_participants`              where participant_event = e.event_id             and participant_user = 1)     ) 	0.0989565106788869
17034698	39966	conversion error with null column and select into	select 'hello' as greeting,             cast (null as varchar (32)) as name into #temp 	0.537969953269462
17035059	23774	count data from multiple year and group by location	select if(a.region = 'region1', city, region) as area,        sum(year(b.date) = 2011) as `2011`,        sum(year(b.date) = 2012) as `2012`,        sum(year(b.date) = 2013) as `2013` from mmr a join mrpp b on a.rm = b.rm where b.date >= `2011-01-01` group by area 	0.000207053621895138
17035205	4203	query to return the distinct first characters for given text column	select distinct(substr(name, 1, 1)) as indexchar from mytable order by indexchar 	4.99818839568609e-05
17035579	29955	pl/sql how to count an escape sequence as 1 character	select dbms_xmlgen.convert ('abc&amp;def',1)       ,length(          dbms_xmlgen.convert ('abc&amp;def',1)        ) from dual; abc&def  7 	0.459168320157679
17036391	11277	efficient ways to count the number of times two items are ordered together	select   product1, product2, count(*), sum(quantity1), sum(quantity2) from (   select     t1.product_id as product1,      t2.product_id as product2,      t1.quantity as quantity1,      t2.quantity as quantity2   from table as t1, table as t2   where t1.order_id=t2.order_id   and t1.product_id<t2.product_id ) group by product1, product2 	0
17036789	5414	mysql combining data from columns with identical names	select * from (select item_name, date       from videos       where item_active = 1       union       select item_name, date       from photos       where item_active = 1) x order by date desc 	6.6569104176692e-05
17038955	24370	how to list unused items from database	select count(a.account_id), b.meal_id, b.meal_name from mdw_meals_menu b  left join mdw_customer_accounts a        on b.meal_id=a.meal_id and           a.start_date between to_date('01-apr-2013','dd-mon-yyyy')                            and to_date('30-jun-2013','dd-mon-yyyy') group by b.meal_id, b.meal_name order by count(a.account_id) desc, b.meal_id; 	0.000238879751751988
17039613	15781	join 2 tables using the combination of 2 columns	select t1.orderno, t1.operationno, t2.description from table1 t1 inner join table2 t2           on t1.orderno = t2.orderno and              t1.operationno = t2.operationno 	0.000155548371780831
17039808	11947	trouble with date fields & combining data from 2 tables	select   month(s.date) month, sum(p.quantity * p.value) from     jeweller.sales s     join jeweller.product_sales p on p.sale_id = s.id where    s.date >= '2013-01-01' and s.date < '2014-01-01' group by month 	0.000944683924306229
17039932	1947	getting cast and case together	select     tbl.uinv,     (         tbl.uinv+         cast(acc_id as varchar) + ' / ' +          cast(transactiontype as varchar) + ' / ' +          cast(reference as varchar) + ' / '     )      as label  from (     select top 25     uinv = (case          when exported = 1 then 'sent to accounts'          when queued = 1 then 'finalised'          when reviewed = 1 then 'pro forma'          when started = 1 then 'new'      end),     tablename.acc_id,     tablename.transactiontype,     tablename.reference     from tablename ) as tbl 	0.793931242743851
17041066	26795	product search across 3 database tables	select     p.productid from     products p left join categories c     on c.categoryid = p.catid left join sub_categories sc     on sc.categoryid = p.subcatid where     p.shortdescription like '%keyword%'     or p.longdescription like '%keyword%'     or c.categoryname like '%keyword%'     or sc.categoryname like '%keyword%' 	0.0134999136030125
17041286	28798	how to convert returned values to decimal and sum mysql?	select sum(cast(replace(value, ',', '') as decimal(10,2))) from   meta_bs where  bs_id = 361 	0.00245690394346737
17044223	14867	select .. select in mysql	select * from user where  (`user_name` like '%tom%' or `user_name` like '%an%' and `login_datetime` between '2013-01-01 00:00:00' and '2013-02-31 23:59:59') or not (     (`user_name` like '%php%' or `user_name` like '%ba%' and `login_datetime` between '2013-02-01 00:00:00' and '2013-03-31 23:59:59') or    (`user_name` like '%sun%' or `user_name` like '%moon%' and `login_datetime` between '2013-03-01 00:00:00' and '2013-04-31 23:59:59') ) or not (     (`user_name` like '%raj%' or `user_name` like '%muth%' and `login_datetime` between '2013-04-01 00:00:00' and '2013-06-31 23:59:59') and    (`user_name` like '%bag%' or `user_name` like '%lap%' and `login_datetime` between '2013-05-01 00:00:00' and '2013-07-31 23:59:59') ) 	0.15943099665746
17044409	9454	mysql query to return receipients list of a user	select s.rcvr person from yt s where s.sndr = 'admin' union  select r.sndr from yt r where r.rcvr = 'admin'; 	0.00451353322973233
17045065	25258	how to fetch a single row from two rows in mysql	select   max(case when phone_number_description='main' then phone_number end) phone_number,   max(case when phone_number_description='fax' then phone_number end) fax_number from   store_concat where   destination_id=287 group by   destination_id 	0
17046498	38	how do you retrieve the latest value from an oracle table	select t."node",t."timestamp",t."max_user_cpu_pct", t."max_system_cpu_pct"  from (select * from dw.kpx_cpu_detail_hv t where t."node" like 'servera%' order by t."timestamp" desc) t  where rownum = 1 	0
17047313	30207	sql query from three tables, using the results from the first table	select t1.id, t1.tag,        t2.color, t2.shade, t2.tint,        t3.sequence, t3.length, t3.width from table1 t1  left join table2 t2 on t1.id = t2.id and t1.tag = t2.tag left join table3 t3 on t1.id = t3.id and t1.tag = t3.tag where t1.[top weight] = '22' and t1.[bottom weight] = '44' 	0
17047914	39221	is this the best way to get a bounded, random result, uniformly distributed over a column value?	select y.zip_code from (     select            zip_code         , zip_code_zone         , row_number() over (partition by zip_code_zone order by dbms_random.value(0,100000)) as row_number     from  zip_code_table     where country_code = 'us' ) y where y.row_number <= 10 order by        y.zip_code     , y.row_number ; 	0.00140967514688908
17048375	17224	search mysql database for string in schema	select      `column_name` from      `information_schema`.`columns`  where      `table_schema` = 'database_name'  and      `table_name` like '%search%' 	0.271148808324479
17050094	15378	mysql group two column with where clause on both two group	select tell,sum(faktorhaprice) faktorhaprice, sum(paymentprice) paymentprice  from (select tell, price as faktorhaprice, null paymentprice       from user_faktorha       union all       select username as tell, null as faktorhaprice, price as paymentprice       from `u_payment` where active='1') sq  group by tell order by faktorhaprice asc; 	0.027333665008128
17050225	18344	mysql order by or group by	select s.id_competitor  from ( select    id_competitor,    sum(case        when score = 'win' then 100000        when score = 'loser' then -100000        when score like '%+' then score * 100 + 99        else score * 100        end) as score from mytable group by id_competitor) as s order by s.score desc 	0.58614176623964
17050242	3101	how to order by smallest value in 3 different columns?	select     l2.a,     l2.b,     l2.c from (     select         l1.a,         l1.b,         l1.c,         l1.smallestcolumn,         l1.largestcolumn,         case             when l1.a > l1.smallestcolumn and l1.a < l1.largestcolumn then l1.a             when l1.b > l1.smallestcolumn and l1.b < l1.largestcolumn then l1.b             else l1.c          end as middlecolumn     from (         select             a,             b,             c,             least( a , b , c ) as smallestcolumn,             greatest( a , b , c ) as largestcolumn         from table_a     ) l1 ) l2 order by     l2.smallestcolumn,     l2.middlecolumn,     l2.largestcolumn; 	4.75222001198123e-05
17050660	13200	recursive sql- how can i get this table with a running total?	select h.*, sum(i.debit) as debsum, sum(i.credit) as credsum, sum(i.debit) - sum(i.credit) as rolling_sum from have h inner join have i on h.id >= i.id group by h.id, h.debit, h.credit order by h.id 	0.0712687139285613
17051069	27840	getting two counts and then dividing them	select a.num, a.denom, cast(a.num as float)/cast(a.denom as float) 	0.00043004737776627
17052878	22669	mysql: substract timestamp for different ids	select   id,      datediff(     max(case when event=2 then timestamp end),     min(case when event=1 then timestamp end)) as days_lent from   schedule group by   id 	0.000378398301026578
17053338	6323	date format in sql query	select name from table where date like '1990-04%' 	0.163262678693115
17054779	14537	leading zero's + concatanation in sql	select right('00000' + convert(varchar(5), mynumber), 4) + char(9) + char(9) + rtrim(name)      as myfield  from mytable order by myfield 	0.323196365403171
17056145	2624	php/mysql how to select data from two tables which only first row of second table is selected for one row of first table	select * from table1 as t1 join table2 as t2 on t1.tab1_id=t2.id group by t1.tab1_id ; 	0
17056172	13383	android sqlite select one row from table where qualifier is in other table.	select tblmessage._id, tblmessage.categoryid, tblmessage.messagetext,          tblmessage.messagehidden from tblmessage, tblcategory           where tblmessage.categoryid = tblcategory._id and tblmessage.messagehidden="f"        and tblcategory.categoryhidden = "f" order by random() limit 1; 	6.60862078557995e-05
17056761	19849	t-sql how to count amount of money from another table and uncertain rows dates	select t.seqno,        sum(case when thecode = 'code1' then numbers end) as code1,        sum(case when thecode = 'code2' then numbers end) as code2,        . . .        sum(case when thecode = 'code9' then numbers end) as code9 from (select rt.*,              (select top 1 code               from #anothertable at               where at.date <= rt.m_getdate and at.seqno = rt.seqno               order by at.date desc              ) as thecode       from #resulttable rt      ) t group by t.seqno 	0
17057792	9125	mysql search between two date	select * from users u where date(now()) between u.from_datetime and u.to_datetime 	0.00822722711148359
17058034	15763	sql display records matching lookup table first then all other records	select  s.*, s.songid thesongid, f.*   from su_songs as s  left join su_member_favourites_lookup as f  on f.songid = s.songid and f.memberid = " . $memberid . "  order by f.songid is null, s.songtitle asc 	0
17059361	14637	how to export sql a table structure and data in mysql?	select concat(     "insert into `input` (`input_id`, `input_type`) values(",     input_id,     ", '",     input_type,     "');" ) as data from input 	0.0139014841663176
17060044	979	how to transpose a table from columns to rows in oracle sql	select id, date, 'test_1' as test, test_1 as score from table union all select id, date, 'test_2' as test, test_2 as score from table union all select id, date, 'test_3' as test, test_3 as score from table 	6.19374533186542e-05
17061264	34671	how to merge two rows into one for checking the status	select   convert(nvarchar(20),cin.logtime,108) as clockin         ,convert(nvarchar(20),( select min(cout.logtime)                                  from table1 cout                                  where cin.logtime < cout.logtime                                  and cout.statusid = 2                                  and not exists (select * from table1 cin2                                                  where cin2.logtime > cin.logtime                                                  and cin2.logtime < cout.logtime                                                  and cin2.statusid = 1                                                 )                                 ),108) as clockout from table1 cin where cin.statusid = 1 	0
17063401	39511	fetching monthwise data from a database with a year's record in postgres	select     date_trunc('month', submittedon) "month",     count("status") total from "mydata"   group by 1 order by 1 	0
17064190	31171	how to compare each row from table with all rows?	select t1.id,t1.heading,t2.id,t2.heading from mytable as t1, mytable as t2 where t1.id > t2.id and not exists (select t3.id from mytable as t3 where t3.id<t1.id and t3.id>t2.id) and (t1.timestamp > t2.timestamp -10 or t1.timestamp < t2.timestamp +10) and (t1.heading > t2.heading -15 or t1.heading < t2.heading +15) 	0
17066634	53	mysql: is it possible to concatenation multiple rows of record into one row	select group_concat(firstname separator '###') as firstnames,        group_concat(lastname separator '###') as lastnames from your_table 	0
17067165	7266	how to do aggregation of column in sql?	select    `table`,    group_concat(`column name`),    group_concat(`description name`) from    `mytable` group by    `table` 	0.0450798795131727
17067523	34177	mysql query to create columns based on other tables	select      tr.object_id,      tr.term_taxonomy_id,      p.id,      p.post_date,      p.post_title,      p.post_excerpt,      p.guid,      t.term_id,      case when tt.taxonomy = 'category' then t.name else null end as category_name,     case when tt.taxonomy = 'post_tag' then t.name else null end as post_tag_name     from      wp_116_term_relationships as tr,      wp_116_posts as p,      wp_116_terms as t     left join wp_116_term_taxonomy as tt on tt.term_id = t.term_id     where      p.post_type = 'post'     and p.id = tr.object_id     and tr.term_taxonomy_id = tt.term_taxonomy_id     and p.post_date > '2013-06-01' 	4.80255706842215e-05
17068194	15543	is it possible to sum values grouped by month?	select year([calendar date]) as [year],        month([calendar date]) as [month],        sum([working day] as [working days] from [calendar] group by year([calendar date]),           month([calendar date]) 	0.000838394916638378
17069514	2535	sql query regarding favorited authors of each user	select distinct user_favorited_by,   a.name   from information a   join interactions b   on a.name = b.name  where  favorited = 'yes' 	0.00367734910395398
17070484	39593	oracle, how to get created/last ddl time for synonym	select *   from all_objects  where owner = 'owner_name'    and object_name = 'isempty'    and object_type = 'synonym' 	0.00671997555564995
17070757	26926	sql query that return all table fields after check if the value exists on 3 tables	select idpontasturisticos, otherfielda1, otherfielda2, otherfieda3 from pontosturisticos where (latitude=41.158764 and longitude=-7.784906 and nome='restaurante1')  union  select idrestauracao, otherfieldb1, otherfieldb2, otherfiedb3 from restauracao where (latitude=41.158764 and longitude=-7.784906 and nome='restaurante1')  union select idalojamento, otherfieldc1, otherfieldc2, otherfiedc3 from alojamento where (latitude=41.158764 and longitude=-7.784906 and nome='restaurante1') 	0
17072581	35987	match string to array of strings in postgres database column	select pub_title from temp_table where 'men' = any (pub_tags) 	0.000720064050295557
17073641	31484	sql how to find progress	select t.*  from (   select strengthid, date, total, high,           average - @prev_avg progress,            @prev_avg := average average                from   (     select s.strengthid,             s.date,             sum(ss.weight) total,             round(sum(ss.weight)/count(ss.weight),1) average,             max(ss.weight) high       from mm_strength s join mm_strength_set ss         on s.strengthid = ss.strengthid      where s.exerciseid = '31' and s.customerid = '4'      group by mm_strength.strengthid       order by mm_strength.strengthid      limit 5    ) q, (select @prev_avg := 0) n ) t order by strengthid desc 	0.0289770023972947
17073715	37782	how to sort in mysql	select * from buildingobjects order by id desc limit 9 	0.0879421580455967
17075298	14189	how could i write a query to find duplicate values within grouped rows?	select * from locations group by contract_id, order_position having count(*) > 1 	0.000182973382843645
17076281	25204	getting record from mysql	select idstudent  from monitoring.progress  where hasfirstattestation = 0 and hassecondattestation = 0  and semester = (select max(semester) from monitoring.progress, monitoring.student  where progress.idstudent = student.idstudent); 	0.00285720457673831
17076602	7884	compare 2 columns from different tables and return different values of 2nd table	select * from table1 where id not in (select id from table2) 	0
17077516	12367	mysql - selecting rows that do not have a match or that have with a condition	select id, name from students where id not in (     select stud_class.students_id from stud_class, class     where stud_class.class_id = class.id     and class.courses_id = 2 ) 	0.000177468959621178
17079051	32163	sql max with group by getting wrong non-grouped field	select t1.total_votes as total, t1.spot_id, t1.vote_type, t1.video_id  from      (     select count(*) as total_votes, spot_id, video_id, vote_type      from spot_video_votes      group by spot_id, video_id, vote_type     ) as t1 join      (     select max(total_votes) as max_total_votes, spot_id, vote_type, video_id      from          (         select count(*) as total_votes, spot_id, video_id, vote_type          from spot_video_votes          group by spot_id, video_id, vote_type         ) as t     group by spot_id, vote_type     ) t2 on t1.total_votes = t2.max_total_votes             and t1.spot_id = t2.spot_id             and t1.vote_type = t2.vote_type 	0.771635443789567
17079606	15738	how to find the child project of a parent project which is passed in the 'where' clause and also, to find the duplicate objects	select a.projectname as parent,count(a.projectname) as parentprojectcount,      b.projectname as child, count(b.projectname) as childproject from psprojectitem  a inner join psprojectitem b  on a.objecttype = b.objecttype  and a.objectid1 =b.objectid1  and a.objectvalue1 = b.objectvalue1  and a.objectid2 = b.objectid2  and a.objectvalue2 = b.objectvalue2  and a.objectid3 = b.objectid3  and a.objectvalue3 = b.objectvalue3  and a.objectid4 = b.objectid4  and a.objectvalue4 = b.objectvalue4  where a.projectname in  (select projectname from psprojectdefn where lastupdoprid <> 'pplsoft')  and a.projectname <> b.projectname  and a.projectname = 'aaaa_job_kj'  order by b.projectname 	0
17080172	28503	sql - selecting multiple results using avg	select groupnumber, sum(score), avg(score), min(score), max(score)  from players group by groupnumber; 	0.0952509118872164
17080602	1774	ranking on same date sql	select a.*  from (     select x.*, row_number() over (partition by id, dateadd(dd, 0, datediff(dd, 0, date)) order by date desc) rownum       from table1 x ) a 	0.0105161270994585
17080742	20966	mysql joins & count	select  u.* from    users u left join     bookings b  on  u.id = b.user_id left join     lessons l   on  b.lesson_id = l.id             and l.date > curdate() and l.date <= (curdate() + interval 7 day) where   l.id is null 	0.58261200442882
17082125	5232	oracle php update no response	select for update nowait 	0.696534352953892
17082169	9575	how can i create sub query i have already left join in my first query	select   t1.id,   t1.die_name,   t1.part_name,   t1.drawing_number,   t1.drawing_part_number,   t1.sub_letter,   t1.specs,   t1.file_path,   idrawing_type_tbl.drawing_type,   idie_type_tbl.die_type,   irevision_tbl.revision,   irelay_type_tbl.relay_type from   imaster_tbl t1   left join idrawing_type_tbl on     master_tbl.drawing_type_id=idrawing_type_tbl.drawing_type_id   left join idie_type_tbl on     imaster_tbl.die_type_id = idie_type_tbl.die_type_id   left join irelay_type_tbl on     imaster_tbl.relay_type_id=irelay_type_tbl.relay_type_id    left join irevision_tbl on     imaster_tbl.revision_id = irevision_tbl.revision_id  where   revision = (     select       max(revision)     from       imaster_tbl t2     where       t2.drawing_part_number = t1.drawing_part_number   ) 	0.516752608557257
17082306	24063	mysql: select changed row where	select a.snapdate, a.value  from (    select t1.*, count(*) as rank    from changes t1   left join changes t2 on t1.snapdate >= t2.snapdate    where t2.uid=t1.uid and t2.uid=2   group by t1.snapdate  ) as a  left join (    select t1.*, count(*) as rank    from changes t1   left join changes t2 on t1.snapdate >= t2.snapdate    where t2.uid=t1.uid and t2.uid=2   group by t1.snapdate  ) as b on a.rank = b.rank+1 and a.value = b.value  where b.snapdate is null order by a.snapdate desc; 	0.0214014122223398
17082352	22344	how to find records that are associated to the same group more than once?	select t.group_id, t.record_id from [your_table] t group by t.group_id, t.record_id having count(*) > 1 	0
17084123	31909	mysql query to get the top two salary from each department	select emp1.departid , emp1.salary from department emp1 where ( select count(distinct(emp2.salary)) from department emp2 where emp2.salary > emp1.salary and emp1.departid  = emp2.departid ) in (0,1) group by emp1.departid , emp1.salary 	0
17084224	13691	mysql query to assign values to a field based in an iterative manner	select abbrevnames, cast(pagenumber as signed) as pagenumber from (     select     abbrevnames     , if(@prev = abbrevnames, @rows_per_abbrev:=@rows_per_abbrev + 1, @pagenr:=@pagenr + 1)     , @prev:=abbrevnames     , if(@rows_per_abbrev % 250 = 0, @pagenr:=@pagenr + 1, @pagenr) as pagenumber     , if(@rows_per_abbrev % 250 = 0, @rows_per_abbrev := 1, @rows_per_abbrev)     from     yourtable     , (select @pagenr:=0, @prev:=null, @rows_per_abbrev:=0) variables_initialization     order by abbrevnames ) subquery_alias 	0.000248225541594575
17086873	19510	database query for mulitple instances	select zipcode  from (        select zipcode         from temp        group by zipcode, state_abbr       ) as t  group by zipcode  having count(*) > 1 	0.0652515516171636
17087317	40884	how to select the duplicate rows / records in a large table	select ("every column but id") from yourtable group by ("every column but id") having count(*) > 1 	0
17087654	2199	mysql select based on enum values	select distinct suppliers.id, suppliers.company_name            from suppliers,                 supplier_mappings mapa,                 supplier_mappings mapb,                 supplier_mappings mapc           where suppliers.id = mapa.supplier_id             and suppliers.id = mapb.supplier_id             and suppliers.id = mapc.supplier_id             and mapa.entity_type = 'key_service'  and mapa.entity_id = '55'             and mapb.entity_type = 'speciality'   and mapb.entity_id = '218'             and mapc.entity_type = 'standard'     and mapc.entity_id = '15'; 	0.000496029208488574
17088327	3927	sql - select top averages	select      venue_id     , avg(stars) as avg_rating from mytable  group by venue_id order by avg(stars) desc limit 2 	0.011647102967245
17089807	31763	getting the values of a mysql enum using only sql	select distinct substring_index(substring_index(substring(column_type, 7, length(column_type) - 8), "','", 1 + units.i + tens.i * 10) , "','", -1) from information_schema.columns cross join (select 0 as 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 as 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 where table_name = 'mytable'  and column_name = 'mycolumn' 	0.000395493481546454
17090423	37611	inner join when only one match exists	select  a.town,         b.zip from    contact a inner join cities_extended b on a.town = b.town where a.town not in (     select  town     from    (         select  town,                 count(*)         from    cities_extended         group by town         having count(*) > 1     ) t ) union all  select  distinct         a.town,         null from    contact a inner join  cities_extended b on a.town = b.town where   a.town in (     select  town     from    (         select  town,                 count(*)         from    cities_extended         group by town         having count(*) > 1     ) t ) 	0.0731896975754514
17092232	32795	postgres update with previous row	select     created_at,     "value",     "value" - lag("value", 1, 0) over(order by created_at) consumption from metervalues order by created_at 	0.0067381825596279
17093105	23556	sql timestamp subtraction to get number of days	select  count(case when assignment = 'crosby' and severity = 4 and datediff('day',getdate(), opentime) between 0 and 30 then p_number end) as crosby_sev4_030, count(case when assignment = 'crosby' and severity = 5 and datediff('day',getdate(), opentime between 0 and 30 then p_number end) as crosby_sev5_030, count(case when assignment = 'crosby' and severity = 4 and datediff('day',getdate(), opentime between 31 and 60 then p_number end) as crosby_sev4_3160, count(case when assignment = 'crosby' and severity = 5 and  datediff('day',getdate(), opentime between 31 and 30 then p_number end) as crosby_sev5_3160, count(case when assignment = 'crosby' and severity = 4 and  datediff('day',getdate(), opentime > 60 then p_number end) as crosby_sev4_60, count(case when assignment = 'crosby' and severity = 5 and  datediff('day',getdate(), opentime > 60 then p_number end) as crosby_sev5_60 from dashboard.dbo.smthings where assignment in('crosby')   and severity in(4,5) 	0
17093330	11711	how to get a way to distinguish the queries with union	select id, 'image' as type from image order by date desc union select id, 'text' as type from text order by date desc 	0.0271207740675605
17095551	38418	mysql query to group by and use distinct row	select pattern, cost, trunks  from sms_prices  where cost = (select min(cost) from sms_prices where pattern = 1) group by pattern; 	0.106093544382713
17095763	37474	mysql joining results of queries	select    t1.id as id, t2.id, t3.id, b.id  from     (table1 t1   inner join table2 t2 on t2.id=t1.id  inner join table3 t3 on t3.id=t2.id)  right join table4 b on t1.id = b.id where b.col1 is not null and b.col2 in (1, 2)) 	0.0744248457523805
17096321	789	sql distinct for two column	select sender_id, receiver_id, message, time from ( select sender_id, receiver_id, message, time from mytable  where sender_id = 123 or receiver_id = 123 order by time desc ) a group by (case when sender_id = 123 then receiver_id    else sender_id end); 	0.0126012588599028
17099015	35458	putting together a mysql query	select e.*, ss2.left_side, ss2.right_side, ss2.start_datetime from exp8 e left join stimuli_schedule ss on ss.start_datetime <= e.date_time left join stimuli_schedule ss2 on ss2.start_datetime <= e.date_time group by e.id, ss2.id having ss2.start_datetime = max(ss.start_datetime) or ss2.start_datetime is null; 	0.291716161140298
17099306	41147	sql join - displaying data where partial result contains a null column	select foo, bar, id from table1 outer join table2 on table2.foo = foo.foo 	0.0121764900837012
17099883	22405	select column values not present in group by clause	select customer,transdate,salenum,store,transtyp,sum(price) from table1  group by customer,transdate,salenum,store,transtyp 	0.0452095258561393
17100526	27109	sorting selected rows in sql server	select * from table where (...expression...) order by case when column='r2' then 1 when column='r4' then 2 when column='r3' then 3 when column='r1' then 4 else 9 end,column 	0.0376417340272359
17100943	33191	how to remove " no duplicate" records from a row, in my-sql	select something_2 from mytable group by something_2 having count(*) > 1 	0
17101679	14093	mysql - calculate rank of students on multiple conditions	select u.id as uid,    sum( utq.marks_obtained ) as total_marks,   sum( (utq.test_section_id = 1)*utq.marks_obtained ) as section1_marks,   sum( (utq.test_section_id = 2)*utq.marks_obtained ) as section2_marks,   sum( (utq.test_section_id = 3)*utq.marks_obtained ) as section3_marks,   u.birthdate from user_test_questions utq join user_tests ut on ut.id = utq.user_test_id join users u on u.id = ut.user_id where ut.test_schedule_id = 1 group by utq.user_test_id, u.id, u.birthdate order by total_marks desc, section1_marks desc, section2_marks desc, section3_marks desc, u.birthdate 	0.00107725540965798
17101740	4259	retrieve records from 2 tables	select *   from dbo.enquirymaster as em   left join dbo.requirement as r     on em.enquiryid = r.enquiryid  where r.mobileit is null     and r.phoneit is null    and em.rservice ='no requirement'    and em.rsubservice ='no requirement'    and em.date >= dateadd(day, -15, getdate()) 	0
17106183	1175	how to sort recent data along with count using mysql	select * from news  where your_date_column >= unix_timestamp((curdate() - interval 2 day)) and news_category_id=1 order by views desc 	0.000250787474081938
17107646	32683	mysql count() with multiple joins	select i.name, c.name, c.instructors_needed, ctr.coursecount from courses c left outer join  link on c.id = link.course_id left outer join   instructors i on link.instructor_id = i.id left outer join   (select link.course_id, count(*) as coursecount from link group by link.course_id) ctr on link.cid = ctr.course_id 	0.576027583510062
17108049	20588	sql query: group time into timeslices then group by loginname then count distinct loginnames per timeslice	select     to_timestamp(extract('epoch' from starttime)::int / 600 * 600) as timeslice,     count(distinct loginname) total from request where starttime >= '2013-06-11 00:00:00' and starttime < '2013-06-11 01:00:00' group by timeslice order by timeslice asc 	0.000325429180732204
17109659	24524	order by unique cases sql	select first_column, max(second_column) from your_table group by first_column 	0.156682360435655
17110052	34874	ms sql select into table auto generate uniqueindentifier for every row	select newid() as id, *  into #temp from yourtable 	0
17110124	19422	group by date sql	select assignment,severity,[days],sum(numberofthingies) from ( select assignment,severity,1 as numberofthingies,  case when datediff(day,open_time,getdate) <= 30 then '0 - 30' case when datediff(day,open_time,getdate) <= 60 then '30 - 60' else 'more than 60' end as [days] from dashboard.dbo.smtickets where assignment in('crosby') and severity in (4,5) ) dummyname group by assignment,severity,[days] 	0.134415621502923
17111033	20996	sql how to select product where each data has a duration less than 300000 ms	select  r.upc ,r.id, res.isrc , res.duration ,count( res.isrc) from release r  inner join releaseresource rr on rr.releaseid=r.id inner join resource res on res.id=rr.resourceid inner join releaseterritory rt on rt.releaseid=r.id where   not r.owningterritoryid in (31,201,41,125) and  r.trackcount=11 and rt.isdeleted=0 group by r.upc ,r.id, res.isrc , res.duration having count( distinct rt.territoryid)=10  and max(res.duration)<5*60000 order by r.upc 	6.9604575147661e-05
17111338	27030	oracle doesn't save time of date. why?	select to_char(date_field,'yyyy/mm/dd hh24:mi:ss') date_field from table_name; 	0.755244914900448
17111494	25111	mysql - returning values based on 2 fields	select * from   messages where ( user_one = yourid and user_one_deleted = 0 )    or ( user_two = yourid and user_two_deleted = 0 ) 	0.000180511309041601
17112102	5754	mysql: query to get the count of each table in a db?	select table_rows, table_name      from information_schema.tables       where table_schema = 'db_name' 	0
17112693	1996	sql server - scripting create user without login	select suser_name(), user_name(); go create user loginless_user_4test     without login go execute as user = 'loginless_user_4test' go select suser_name(), user_name(); go revert   go 	0.204420594392741
17112908	3930	mysql - getting count of distinct values from 3 tables	select count(*) from  ( select 1 from complete_shifts where date="2013-06-13" union all select 1 from incomplete_shifts where date="2013-06-13" union all select 1 from incomplete_shift_register where date="2013-06-13" )t 	6.38667026977258e-05
17113928	16571	many to many sql query	select     r.id,     us.username,     ua.username,     uc.username from     requests r     join users us      on r.submit_id = us.id     join users ua     on r.assign_id = ua.id     join users uc     on r.complete_id = uc.id 	0.362741060116828
17113956	34291	sql get data from column(yyy0) with same number as different column(xxxx0) with the maximum date	select id, case when yyyy0 > yyy1 and yyy0 > yyy2 ... and yyy0 > yyy9 then xxx0 when yyy1 > yyy2 ... and yyy0 > yyy9 then xxx1 ... else xxx9 as labelx, case when yyyy0 > yyy1 and yyy0 > yyy2 ... and yyy0 > yyy9 then yyy0 when yyy1 > yyy2 ... and yyy0 > yyy9 then yyy1 ... else yyy9 as labely, ... 	0
17114296	33683	i have two selects and i want the result table to be a union of the two	select ext.idroom,     existingcomputers as 'existing computers',     computersused as 'computers used' from     (select          room.idroom, count(*) as existingcomputers     from         room,         computer     where         room.idroom = computer.idroom     group by room.idroom) as ext inner join     (select          room.idroom,         count(*) as computersused     from         room,         session,         computer     where         room.idroom = computer.idroom             and computer.idcomputer = session.idcomputer             and session.logout is null     group by room.idroom) as usd on ext.idroom = usd.idroom and ext.existingcomputers = usd.computersused 	0.000199615411979285
17115454	30154	sql select from two tables, using a distinct value between the two if it exists, otherwise only using value from the first table?	select distinct       roomlist.room,       userlist.room,       roomlist.totaldesks,       count(distinct userlist.desk) as desksused,       roomlist.totaldesks-count(distinct userlist.desk) as desksopen       from roomlist           left join userlist on roomlist.room=userlist.room      group by roomlist.room,           userlist.room,           roomlist.totaldesks 	0
17116138	23167	filter by multiple members of an hierarchy	select      non empty {([dim 1].[member 1].[member 1])} on columns     ,non empty         {(           [dim 2].[hierarchy 3].[member 3].&[value 3]            ,[dim 2].[member 2].[member 1]        )} on rows from [cube 1] where (     {        [dim 4].[hierarchy 4].[member 4].&[value 2]        ,[dim 4].[hierarchy 4].[member 4].&[value 4]        ,[dim 4].[hierarchy 4].[member 4].&[value 8]     }     ,([measures].[measure 1]) ) 	0.0189684402035427
17117275	26996	change a number value to negative based on another separate textbox value	select ordertype,   case when ordertype = 42 then -quantitysold else quantitysold end as quantitysold   from stuffthatwassold 	0
17120287	3797	sql. how to map two columns frequencies?	select pjno from project group by pjno having count(taskno)>1; 	0.0034823093389
17121625	20072	how to sort sql result	select *  from table1 where colorname like '%red%' order by nullif(colorname , 'red') nulls first 	0.0795610601268404
17123371	17593	sql query table filtering	select distinct meal from newtab nt where not exists     (select 1 from newtab where neededqty>availableqty      and nt.meal = meal); 	0.272290784175858
17123415	25945	get total rows from join based on value from join table	select ar.user_id, a.status, count(*) total from article_reviewers ar inner join articles a on ar.article_id = a.id group by ar.user_id, a.status 	0
17126664	25363	how to display all fields in mysql join statement if other does not have value	select issuemail.borrowernumber,     issuemail.cardnumber,     issuemail.firstname,     issuemail.surname,     issuemail.title,     issuemail.author,     issuemail.barcode,     issuemail.issuedate,     issuemail.date_due,     amount.amount     from issuemail left join     amount on amount.cardnumber = issuemail.cardnumber and amount.barcode =     issuemail.barcode 	0.000155104545229194
17127363	4949	combining data from 2 tables?	select tweets.*, credentials.h_file, credentials.picture, credentials.name      from tweets join credentials on tweets.h_token=credentials.h_token      order by time desc limit 7; 	0.00102558805660398
17127627	8877	mysql : random sort than sort by a specific column	select * from infos where category=... order by rate desc, like desc, rand(); 	0.000465501247175862
17127773	32731	sql server: select values from two different tables	select       pub.name,      case when (pub.name = priv.name ) then priv.value else pub.value end as value from      publicsettings pub      left join privatesettings priv on (pub.utype = priv.utype) where      priv.[uid]=1 	0.000119723624623799
17129711	11113	is there a way to run min on an entire table in a mysql range query?	select user_id, min(date_created) as first_date from user_transactions group by user_id having first_date between '2013-04-01' and '2013-05-30' ; 	0.00430887798780136
17133195	17946	count 3 values in single column in sql server	select sum(case when s.isverified = 0 then 1 else 0 end) no , sum(case when s.isverified = 1 then 1 else 0 end) yes , sum(case when s.isverified = 2 then 1 else 0 end) waiting from tbl_squad s join tbl_group g on s.groupid = g.groupid where g.adminid = 1468 	0.00285408997101091
17133881	15514	postgres query to find all dependent tables	select 'pg_statistics'::regclass;  select 2619::regclass;             # select refclassid::regclass from pg_depend where classid = 'pg_class'::regclass group by refclassid;   refclassid    pg_namespace  pg_type  pg_class 	0.00269498107142992
17136361	4987	get records with month and year - sql	select * from tbl where from <= '$year-$month-01'    and to >= '$year-$month-01' 	0
17139004	15474	correct way to get a non null count join in stored proc	select coalesce(p.addoncount, 0) as addoncount 	0.56985959537733
17141970	23312	group and sort sqlite records	select     _id, body, category, is_readed, date from (     select         _id, body, category, is_readed, date     from          table     group by         is_readed, category     order by         category asc, is_readed desc, date desc ) group by     category 	0.0182911893530071
17141990	9380	select where date is 5 days before the maximum date in sqlite	select productid from kproducts where datecreated > date((select max(datecreated) from kproducts),'-5 days'); 	0
17144195	7322	access sql query: return records with two or more checkboxes checked	select * from resources  where (literacy + numeracy + poverty + behaviour + ani + rpae + cad019 + leadership + curriculum + assessment + wellbeing) < -1 	0.411037081299889
17145261	30068	mysql: get distinct values from two columns and check whether they occur in two other columns of the same table	select count(*) as `recruits` from     (      select  childid1 from fam      where childid1 in       (select parentid1 from fam         union        select parentid2 from fam)      union      select childid2 from fam      where childid2 in       (select parentid1 from fam       union      select parentid2 from fam)     )t; 	0
17145496	10310	mysql - multiple min values from multiple groups in table	select country, duration, price, departure, hotelname, otherdata from  (     select a.country, a.duration, a.price, a.departure, a.hotelname, a.otherdata,      @counter := if(a.country = @prevcountry, @counter + 1, 0) as countrycounter,     @prevcountry := a.country     from (select * from sometable order by country, duration, rand()) a     cross join (select @counter:=0, @prevcountry:='') sub2 ) sub1 where countrycounter < 6 	0.000154426520272033
17146662	35411	selecting age groups using sql	select  agegroup ,       count(*) from    (         select  case                 when  age between 13 and 17 then 1                 when  age between 18 and 21 then 2                 ...                 end as agegroup         from    (                 select  round(datediff(cast(now() as date),                             cast(birthday as date)) / 365, 0) as age                 from    yourtable                 ) as subqueryalias         ) as subqueryalias2 group by         agegroup 	0.00457750621091051
17147294	4040	how to find associated rows when i only know the primary key?	select id, first, last from tbl_1 t1 join tbl_1 t2    on (t1.last = t2.last and t1.id = your_id); 	0
17149130	784	check if column is not null	select columnproperty(object_id('dbo.aud'),'actname','allowsnull') as 'allowsnull'; 	0.160722249906294
17149626	37602	how do i show only one record - the record with smallest value?	select distinct l.locationid, c.courseid,  c.coursename,  c.capacity_seating - (select count(*)        from tbltrainings t1       where l.locationid = t1.locationid and c.courseid = t1.courseid) as availableseats, d.dateid, d.trainingdates,  d.trainingtime,  c.coursedescription, i.instructorname,  l.location, l.seating_capacity                      from tbllocations l                     inner join tblcourses c on l.locationid = c.locationid                     left join tbltrainings t on l.locationid = t.locationid and c.courseid = t.courseid                     inner join tbltrainingdates d on c.dateid=d.dateid                      inner join tblcourseinstructor ic on c.courseid = ic.courseid                       inner join tblinstructors i on ic.instructorid = i.instructorid 	0
17149742	38247	mysql : different behaviors depending on where result	select      count(if(seg.my_seg1 >= 30, 1, 0)) as res1,     count(if(seg.my_seg1 >= 11 and seg.my_seg1 < 30, 1, 0)) as res2 from (     select count(distinct cp.conference_id) as my_seg1      from a.account a             join a.conferenceparticipant cp on a.account_id = cp.user_id             join a.conference cf on cf.id = cp.conference_id     where          cf.`status` = 0     and date_sub(curdate(), interval 30 day) <= cf.creation_timestamp     group by a.account_id ) as seg 	0.00305327871996095
17149744	39247	empty result set from multi-part query	select pt_no     , med_rec_no     , pt_age     , pt_name     , days_stay     , case         when days_stay < 1 then 0         when days_stay = 1 then 1         when days_stay = 2 then 2         when days_stay = 3 then 3         when days_stay between 4 and 6 then 4         when days_stay between 7 and 13 then 5         when days_stay >= 14 then 6       end as lace_days_score     , case         when plm_pt_acct_type = 'i' then 3       end as acute_admit_lace_score from smsdss.bmh_plm_ptacct_v where dsch_date between @sd and @ed 	0.454123393588998
17150184	32886	sqlite - multiple random result sets with unions	select * from (     select cola, colb, colc     from tablea     order by random() limit 10  )  union all  select * from (     select cola, colb, colc     from tableb     order by random() limit 10  ) 	0.354443209777182
17151723	9518	mysql - query to find sum accrued per hour per day	select date_add('2013/06/17', interval thehour hour), count(teamslot_schedule.id) from shifthours left outer join teamslots on date_add('2013/06/17', interval thehour hour) between starttime and starttime and endtime left outer join teamslot_schedule on teamslots.id = teamslot_schedule.slotid group by date_add('2013/06/17', interval thehour hour) 	0
17153467	35221	how to count the teams with no foreign players	select count(distinct teamname) from teams t1 where not exists  ( select * from teams t2    where t1.teamname=t2.teamname and t2.country like '%england%') 	0.000822364525620489
17156041	22544	use sql to select all data in row where first column equals something	select * from mytable where field1 = 'matchthis' 	9.36535904186387e-05
17157715	17544	sql count more than 1 value accross multiple tables	select    p.project_id,   m.members,   i.issues from projects as p left join    (       select project_id, count(user_id) as members        from project_members        group by project_id   ) as m on p.project_id = m.project_id left join    (       select project_id, count(issue_id) as issues        from project_issues       group by project_id   ) as i on p.project_id = i.project_id where members > 10 and issues > 10 order by members, issues; 	0.00203179321679924
17158031	20779	mysql multiple in clauses linked by and clauses in the same field	select            pr.*        from            vprice_range pr              join versiontrim windows                 on pr.version_id = windows.version_id                and windows.trim_id in ( 139, 152, 237, 265, 266 )              join versiontrim hasair                 on pr.version_id = hasair.version_id                and hasair.trim_id in ( 39 )              join versiontrim airbags                 on pr.version_id = airbags.version_id                and airbags.trim_id in ( 45, 55, 154 )    group by       pr.version_id 	0.0059831617423613
17158487	15761	count number of instances, and put them in a column while grouping by another column	select userid,     sum(case when logindate between '2013-01-01' and '2013-01-31' then 1 else 0 end ),    sum(case when logindate between '2013-02-01' and '2013-02-28' then 1 else 0 end ) from table group by userid 	0
17158818	33420	sql query for many to many mapping	select e.id, e.title, e.name, e.text, e.emailaddress, group_concat(k.text) keywords from entries e left join keyentries ke     on e.id = ke.entryid left join keywords k     on k.id = ke.keywordid group by e.id; 	0.523202339767139
17159277	26933	sql return the row only with the later date	select * from (   select user_id,          school_id,          row_number() over (partition by user_id order by graduation_date desc) position   from user_school ) us, [user] u where us.user_id = u.user_id   and position = 1 	0
17159351	37500	select all data with no duplicate data	select name, country, max(status) as status from ( select top 100 percent * from namecountry order by name asc, country asc, status desc ) g group by g.name, g.country order by g.name, g.country 	0.000412602931327144
17159714	22356	sql implicit join joining 3 tables	select e.name from employee e,employeeskills es,skill s where e.id = es.employeeid   and es.skillid = s.id   and s.title=’dba’; 	0.472425375197367
17160139	30672	concatenate multiple row into single row	select distinct  resvid ,stuff((select ','+vehtype from tabelname a where a.resvid =b.resvid   for xml path('')),1,1,'') as vehtype from tabelname b 	0
17161071	16753	query to get data between months of a financial year	select name, sum(amount) as amount, datename(month, datecolumn) as month from table group by name, datename(month, datecolumn) 	0
17163776	25620	display upcoming birthday of user	select id , name , birthday_column      from users      where month(birthday_column) = month(now())      and   day(birthday_column)   = day(now())      order by birthday_column 	0.000149006093114405
17164299	4087	access sql query: find the most recent date entry for each employee for each training course	select t1.* from      training t1      inner join      (         select [employee id], [course id], max([course date]) as maxdate          from training          group by [employee id], [course id]     ) t2          on t1.[employee id]=t2.[employee id]              and t1.[course id]=t2.[course id]              and t1.[course date]=t2.maxdate 	0
17164592	30338	oracle sql view: multiple rows to one with help of foreign key	select a.pk_id,a.value, max(case when b.key='key1' then b.value else '0' end) as key1, max(case when b.key='key2' then b.value else '0' end) as key2, max(case when b.key='key3' then b.value else '0' end) as key3 from table_b b  left outer join table_a a on a.pk_id = b.fk_id group by b.fk_id,a.pk_id,a.value order by b.fk_id asc 	0.00140165869991346
17165021	13283	fetch records of single id only not of any other	select * from `table` where id = 1 and oid not in (select oid from `table` where id != 1) 	0
17165254	22627	get db owner's name in postgresql	select d.datname as "name", pg_catalog.pg_get_userbyid(d.datdba) as "owner" from pg_catalog.pg_database d where d.datname = 'your_name' order by 1; 	0.0125479346688782
17165294	14258	sql to get a particular thread based on two user	select a.message_id,     a.message_title, a.message_body,     a.message_sent_date,     z.member_userunique from message a inner join thread_participant b on a.thread_id = b.thread_id and b.member_id = 1 inner join thread_participant c on a.thread_id = c.thread_id and c.member_id = 959 inner join member z on a.message_author = z.memberid order by a.message_sent_date desc 	0
17165381	34977	sum of unique records - better performance than a cursor	select    name, entity,    count(case when status ='broken' then 1 else null end) as broken,    count(case when status ='fixed' then 1 else null end) as fixed,    count(case when status ='stolen' then 1 else null end) as stolen from table_name group by entity,name order by name; 	0.0741520311354398
17165602	18103	with mysql how to distinguish between a null value and a non-existent value	select     m.id, m.column1,     case when s.id is null               then 'not exists'          when s.column2 is null              then 'null value'          else s.column2     end as column2 from      maintable as m   left join     secondtable as s       on s.id = m.id ; 	0.000855965052926091
17166114	3811	sql select values with or	select a,b from database where source = 2 union select c,d from database where target = 2 	0.196861520727062
17166362	29747	how to combine the following queries result in mysql	select * from table_1 t where value = (select max(value) from table_1 s where t.id = s.id) and t.id = 900 	0.0489798799444237
17166731	15309	sql select duplicates on specific day	select        username     , date_created  from  (   select         username     ,  date_created     ,  count( *) over ( partition by username, trunc( date_created, 'dd') ) cnt   from the_table ) where cnt > 1 ; 	0.000553648791827884
17167866	28735	display mysql data using php based on certain dates	select * from maintenance where to_date <= date_add(now(), interval 2 day)     and from_date >= date_sub(now(), interval 2 day) order by from_date asc 	0
17168235	10670	postgres:get the latest record from a table	select distinct on (remainingphase_time)     g_190049.logger_timestamp,     g_190049.msg1_recd_timestamp,     g_190048.distance ,     g_190048.remainingphase_time,     g_190048.current_phase  from     g_190049     inner join     g_190048 using(id, begin_calc_timestamp) where     g_190048.intersection_id = 100     and g_190048.matched_nr = 1     and g_190049.logger_timestamp between '1370246100000' and '1370253364000' order by remainingphase_time, g_190049.logger_timestamp desc 	0
17168465	38157	need group by counter as column returned	select *   , [index] = dense_rank() over (order by name) from tbl 	0.212875808434482
17168609	24314	how to select columns that are similar values and calculate quantity and sum of prices	select ducumentnumber,count(quantity) as quatity,sum(price) from table1 group by ducumentnumber 	0
17169484	8105	filter and merge inner table data	select id,    max(field1) as field1,    max(field2) as field2,    max(field3) as field3,    max(field4) as field4,    max(field5) as field5 from yourtable group by id; 	0.0303137533361314
17169678	36162	sql query for distinct user id on the basis of highest column value	select t1.*  from your_table t1 inner join (   select ref, max(set) as mset   from your_table   where user_id = 1   group by ref ) t2 on t2.mset = t1.set and t2.ref = t1.ref 	0
17170697	35724	sql query list of months between dates	select distinct i.id, c.month   from calendar c   join itemsinuse i      on c.shortdate between i.startdate and i.enddate 	0.000270763528540929
17170782	9118	tsql - combine from one table into another with single row	select  newsid,  title,  stuff((select ', '+ s.sectionname   from tblsectionitems si   inner join tblsections s on s.sectionid=si.sectionid   where si.newsid= n.newsid   for xml path('')  ),1,2,'') as ids from tblnews n 	0
17170856	37410	using the not in operator on a column with null values	select *  from employee e where (e.company not in ('abc', 'def')        or e.company is null) 	0.196294839853999
17171186	36225	sql : query that only contain one word	select name  from employee  where charindex(' ',name) = 0 	0.00276050112574136
17171637	13796	creating an entity from a query?	select new com.company.publisherinfo(pub.id, pub.revenue, mag.price)     from publisher pub join pub.magazines mag where mag.price > 5.00 	0.451460222735444
17173198	8552	add extra columns for mysql export to csv?	select 'colname1', 'colname2', 'colname3', 'new column' union all select    colname1   ,colname2   ,colname3   ,cast(cast((colname1 * colname2) as dec(5,2)) as char) from yourtable into outfile '/path/outfile' 	0.00326275952033313
17174514	22361	replacing two minus/except queries	select    value1, value2, value3,   sum(decode(uploadid, 'afterturning', 1, 'beforeturning', -1)) as diff from table1  group by value1, value2, value3 having sum(decode(uploadid, 'afterturning', 1, 'beforeturning', -1)) <> 0 	0.157582203030553
17174657	24295	sql how to filter a table with two ranges in another table	select * from table_one where not exists  (select * from table_two  where table_one.bill = table_two.bill  and table_one.subrow between table_two.iinitialrange and table_two.finalrange) 	0
17174848	34339	sql display today only between start date and end date	select * from mytable where date() >= startdate and date() =< enddate and datefield = date() 	0
17175501	12255	mysql: manipulate dates and strings in selection query	select miles, hours + minutes from ( select   cast(left(distance, first_space) as decimal(5,2)) as miles,   cast(substr(distance, distance_split_loc+1, hour_loc-distance_split_loc-1) as unsigned) * 60 as hours,   cast(if (hour_loc = 0,     substr(distance, distance_split_loc+1, min_loc-distance_split_loc-1),     substr(distance, space_after_hour, min_loc-space_after_hour)) as unsigned) as minutes from (select    distance,    locate(' ', distance) first_space,    locate('/', distance) distance_split_loc,    locate('hour', distance) as hour_loc,    locate('min', distance) as min_loc,    locate(' ',distance,locate('hour', distance)) as space_after_hour  from distance) as temp_table) as timecalc order by miles; 	0.0855508812355168
17177435	30447	sql type conversion failure still exists outside of set	select * from @mytable where case when isnumeric(value)=1 then value else 0 end       between 1 and 1000 	0.528856391463354
17177758	3962	ms sql server select random rows with no duplicates	select top 25 percent * from  (    select      max(imgid) imgid,       image   from [table]   group by [image] ) x order by newid(); 	0.0241571813917022
17177803	36148	how to get multiple rows fit into one cell in xmlattributes	select    xmlelement("ul", xmlattributes('dropdown-menu' as "class"),       xmlagg(xmlelement("li",                         xmlelement("a",                         xmlattributes(url as "href"),title) as "menu element"                         )              )           ) as menu     from att1 where upper_lvl = 1 	0
17177870	20950	left join count on tables	select * from     t1     left join     (         select personidref, count(*) total         from t2         group by personidref     ) s using(personidref) order by puid 	0.373013323231683
17178443	5788	find members primary store	select trn_soln, count(*) as totaltrans from trans where trn_mbrid = @did   and trn_purdate >= date_sub(curdate(), interval 1 year) group by trn_soln order by totaltrans desc limit 1 	0.00646347358777659
17178988	30597	search a database table from a dataset using wildcard symbols	select * from customer where ((name like '%'+@query+'%') or (surname like '%*+@query+'%') or (telephone like '%'+@query+'%')) 	0.0526421474348258
17179231	5822	finding difference between two tables in sql	select *  from   new_data as n  where  not exists (select *                     from   old_data as o                     where  n.opportunity_id = o.opportunity_id                            and n.sales_stages = o.sales_stages                            and n.sales_values = o.sales_values) 	0.000366534954337874
17180349	27710	i need get all records from table joined where at least one case with condition	select     p.id as id_projeto,      p.nome as nome_projeto,      p.id_tipo_projeto,       p.dhpostagem,        hp.id as id_habilidade_projeto,       h.nome as nome_habilidade from cp_projecto p join cp_habilidade_projeto hp on p.id = hp.id_projeto join cp_habilidade h on h.id = hp.id_habilidade where p.id in ( select cp_habilidade_projeto.id_projeto                  from cp_habilidade                  join cp_habilidade_projeto on cp_habilidade.id = cp_habilidade_projeto.id_habilidade                 where cp_habilidade.nome like '%css%' ) 	0
17181100	21379	sql: select foreign records using complex join	select just the fields you need from (     select companies.company_name, sites.id id     from sites     inner join company_sites on company_sites.site_id = sites.id     inner join companies on companies.id = company_sites.company_id     where sites.active = 1     and sites.stage_id = 5     group by sites.id     order by rand()     limit 1 )a join channels on channels.site_id = id 	0.0971842408014549
17183475	6687	find records with an exact number of children	select rid from retsau_attribute where aid in (a1, a2, a3) group by rid having count(*) = 3 	0
17183708	36896	auto number by grouping column in oracle	select row_number () over (partition by columna order by columnb) as "auto",        columna, columnb   from table; 	0.00127674041415334
17183977	835	group by on postgresql date time	select code, to_char(date, 'yyyy-mm'), count(code) from employee where  group by code, to_char(date, 'yyyy-mm') 	0.0273833955360156
17184503	17108	mysql left join - how to get count of records found in 2nd table	select t1.name, ifnull(count(t2.id2), 0) from table1 t1 left join table2 t2 on t1.id=t2.id group by t1.id 	8.41226614699369e-05
17185200	32453	how to return columns before update using returning?	select s.column1,        s.column2 into v_column1,v_column2 from cards s where s.column3= in_column3; 	0.0100517861753331
17185264	11653	creating stored procedure in mysql to generate roll numbers in each batch	select u.id, u.name, u.batch, if(@batch = (@batch := u.batch), @rollno := @rollno + 1, @rollno := 1) rollno from usertable u, (select @batch:='', @rollno:=1) a order by u.batch, u.name 	0.000954062916240163
17185387	38630	simplest way to select a column in table a that need info from table b?	select personalmsg.content, u2.name from personalmsg  inner join userdb u1 on userdb.user_id=personalmsg.receiver_id  inner join userdb u2 on userdb.user_id=personalmsg.sender_id  where u1.name = '$username' 	0
17186456	27734	sql select/view : can i display data with a "reorganization" of the table?	select code, max(case when month='jan' then value else null end) as jan max(case when month='feb' then value else null end) as feb max(case when month='mar' then value else null end) as mar from table_name group by code order by code 	0.000888883761417836
17186467	27771	how in mysql do i select a specific column followed by all columns?	select column2 new_name, t.*   from table_name t 	0.000131500708480192
17186699	12878	mysql count() on groups returns wrong number of rows	select floor(id/5) as block, min(`value`) from (select (@id:=@id+1) as id, `value`       from `values`, (select @id:=-1) as a) as b group by block; 	0.00166459889685299
17187124	19550	how to select all columns, and a count(*) in the same query	select a.cntr, c.* from customer c     , (select count(*) cntr      from customer b      where b.name like 'foo%' ) a where c.name like 'foo%' 	0
17188867	21266	sql query inner joins and limit to max 3 most recent	select *  from (select *        from (select *, if(@shop = (@shop:=p.shop_id), @id:=@id + 1, @id := 1) temp              from `product` p, (select @shop:=0, @id:=1) as a              order by p.shop_id, p.updated desc) as b        where temp <= 3) as c inner join `shop` s on c.shop_id= s.id; 	0.0315408704769121
17190995	5014	select max with group by on other table	select users_item.user_id, item_id, maxrate from user_items  join item_rates on users_item.item_id = item_rates.rate_item_id join (select max(rate) as maxrate, user_id        from users_item join item_rates on item_id = rate_item_id       where user_id in (1,2)       group by user_id) as maxis on users_item.user_id = maxis.user_id where item_rates.rate = maxrate 	0.0032391053325328
17191177	19113	how to fetch records categorywise from same table by cross join	select t1.name, t21.name, t22.name from table1 t1 join table2 t21 on t21.catid=1 join table2 t22 on t22.catid=2 order by t1.name, t22.name, t21.name 	8.75047065918896e-05
17191256	24842	sql query: grab data from a multiple columns conditionaly	select table2.location, table1.productfamily, forcast2012, forcast2013, forcast2014, forcast2015 from table1  inner join table3 on table1.productfamily = table3.producttype inner join table2 on table3.[building plant] = table2.location 	0.000209202037447833
17191898	8692	multiply value from multiple tables mysql	select  h1.sid, date(`tm`),          (max(svalue)-min(svalue))* ss.evalue  from    table1 as h1         join table2 as ss         on h1.sid = ss.sid group by date(`tm`), h1.sid; 	0.000713824315401087
17191908	2105	use multiple while loop to fetch muliple data from multiple database table	select title, image, list from title t, image i, list l where t.id = i.id and t.id = l.id 	0.000606977202341917
17192345	5586	how to make more than 2 conditions in where clause?	select matches.tournament_id 't_id', matches.localteam_ft_score,    matches.visitorteam_ft_score, matches.match_time, matches.match_status,    matches.match_date, matches.localteam_id, matches.visitorteam_id,    matches.match_id, matches.id, matches.static_id,matches.localteam_name,    matches.visitorteam_name, matches.halftime_score,  tournaments.tournament_id,    tournaments.league_link, tournaments.full_league_tr, countries.country_name    from matches    inner join tournaments on tournaments.id = matches.tournament_id    inner join countries on tournaments.country_id = countries.country_id    where match_status in('aet','ft','pen.','awarded')    and countries.country_name='worldcup' and str_to_date(matches.match_date,'%d.%m.%y') between '2013.05.19' and '2013.06.19' 	0.383953403385887
17192432	33640	mysql filter by multiple entries from same table	select e.id,        e.name,        e.entry from   entries e        left join filters a               on a.eid = e.id                  and a.name = 'author'        left join filters v               on v.eid = e.id                  and v.name = 'view_count' where  a.value = 'admin'        and v.value > 300 	0
17193463	27199	sql:using data from two tables with the same column name... and more	select b.[cusip number],        b.[current factor],        a.[current factor]/b.[current factor] mynewfieldname from dbo.mbs012013 a, dbo.mbs022013 b where a.[cusip number] = b.[cusip number] 	0
17193478	26735	mysql table transformation with counts	select     author,     sum(category='history') as 'history',     sum(category='fiction') as 'fiction',     sum(category='sport') as 'sport',     sum(category='travel') as 'travel' from books group by author 	0.200544261048156
17194829	33787	select matching records from table 1 if table 2 has records, otherwise select all from table 1	select  t1.* from    table1 t1 left join         table2 t2 on      t1.id = t2.id where   t2.id is not null          or not exists          (         select  *         from    table2         ) 	0
17199287	9213	how to fetch data from past week in sql	select convert(varchar(25),postdate,107) as duration, count(*) as posts  from mdbdetails   where datediff(week, postdate,getdate()) = 1  group by  convert(varchar(25),postdate,107)  order by duration 	0
17201794	24412	return a mysql table column according to column conditions	select distinct route_id from mytable as myalias where exists ( select * from mytable where route_id = myalias.route_id and stop_name = 'stop1' )   and exists ( select * from mytable where route_id = myalias.route_id and stop_name = 'stop2' ) 	0.000217745886881705
17202593	26772	sql - group by a column, then sort by the 'count' results	select count(a.review_id) as total, a.review_id from vote a inner join reviews b on a.review_id = b.review_id group by a.review_id order by total asc 	0.00268138897757289
17203648	38963	running a sql multiple times with changing parameter	select * from ( select *, case when weekno(tableweeks) < week(tablex) then 1 else 0 end 'valid' from tablex cross apply tableweeks ) where valid = 1 	0.188857512495378
17204655	38174	database schema for posts with multiple tags	select distinct         p.post_id ,         substring(( select  ',' + t.tag_tagname as [text()]                     from    dbo.pt pt                             inner join dbo.tag t on pt.pt_tagid = t.tag_id                     where   p.post_id = pt.post_id                   for                     xml path('')                   ), 2, 1000) [tags] from    dbo.post p 	0.00595220090828201
17204797	7552	sql to get all values from look up and corresponding values from master table	select d.studentname,d.subjectname,isnull(c.marks,0) as marks  from tablec c right join (select * from tablea a,tableb b ) d on c.studentid = d.studentid and c.subjectid = d.subjectid 	0
17207025	24826	how to select id, first_not_null(value1), first_not_null(value2).. on postgresql	select id, max(col1), max(col2) from (     select 1 as id, null as col1, 'test' as col2     union      select 1 as id ,'blah' as col1, null as col2 )  x group by id 	0.0185349258591399
17209561	39499	select all and some on the same query	select   tool,   count(user_id) cnt,   count(case when time_diff>2 then user_id end) cnt2 from   foo group by   tool 	0.000565058419579952
17209728	6669	query pl/sql record type in a simple sql	select * from table(mypackage.myfunc()); 	0.568340781243461
17209749	35037	sql query involving two tables	select m.[msgid]   ,u1.firstname  as sentby   ,u2.firstname as sentto   ,m.[msg] from tbl_msg m inner join tbl_user u1 on m.fromid = u1.id inner join tbl_user u2 on m.toid = u2.id where m.toid = 42 	0.140601244174728
17211729	3196	a better way to count multiple columns	select answernum, answerval, count(answerval) from (select n.num answernum,         case n.num             when 1 then a.answer1             when 2 then a.answer2             ...         end answerval  from (select 1 num union select 2 union ...) n  cross join `questionnaireanswers` a  where questionnaireid='$questionnaireid') sq group by answernum, answerval 	0.0490417274682897
17211932	15912	month closest actual month	select  top 3 * from    yourtable where   datepart(month, birthday) = datepart(month, getdate()) 	0
17213625	18252	sql server patindex to match exact string	select * from sys.columns      where name not in (       select column_name       from information_schema.columns       where table_name = 'xxxx'       and charindex(column_name + ';', 'abc;xyz;') > 0     ); 	0.420566040874199
17213771	6200	take max from subquery	select  * from    (         select  row_number() over (partition by hsw order by cnt desc) rn         ,       *         from    (                 select  count(*) over (partition by hsw, nazwa) as cnt                 ,       *                 from    from _katalogi.dbo.zbior_nazw                  ) as subquery1         ) as subquery2 where   rn = 1  	0.0195031504620051
17214194	7738	mysql: search in combined columns	select * from your_table where concat(first_name, ' ', inserts, ' ', last_name) like '%search_string%' 	0.0464114764288835
17214956	34888	get the difference between two values	select a.name, b.value - a.value, a.date  from a inner join b on a.name = b.name and a.date = b.date 	0
17218969	13207	taking a very efficient join between two tables in oracle	select * from post p join (select *       from comment       where comment_creation_date > ? and comment_creation_date < ?               and 'stringlist' like '%'||comment_type||'%'      )c on c.post_id = p.post_id 	0.420154351241764
17219140	35454	how to count rows in one table based on another table in mysql	select d.abbreviation, count(*) num from departments d inner join courses c on c.section like concat(d.abbreviation, "%") group by d.abbreviation 	0
17220345	14553	matching rows of same table using visual basic	select  id,          datetime,          onoff,          param,          (             select top 1 datetime              from signalraw              where id = sr.id                  and param = sr.param                  and onoff = 'off'                 and cast (datetime as date)>= '1/1/11'                 and cast (datetime as date) >= cast (sr.datetime as date)             order by datetime         ) offtime  from signalraw sr  where cast (datetime as date) between '1/1/11' and '2/1/11'      and onoff = 'on' 	0.00499045639648254
17221965	29109	selecting a value from xml data type	select configuration.value('(/configuration/dosrequestanalysis/windows/window[@name="smallest"]/@duration)[1]', 'smallint') 	0.000221220234563199
17222411	28137	comparing current date in stored procedure	select * from table where datecol = cast(getdate() as date) 	0.00542649467386915
17223128	11577	how to get difference between dates in the same column in oracle using only sql	select start_date,        (lead(start_date,1) over (order by start_date)-start_date)*24              as hours_to_next_start from mytable 	0
17223169	14244	php-mysql help on selecting records from two tables to make journal (in accountancy)	select date, perticular, bill_no, debit, credit, balance   from (   select date, perticular, bill_no, amount debit, null credit, null balance, 1 ord     from outward    where cust_id = 1    union all   select date, payment_mode, null, null, amount, null, 2     from receipt    where cust_id = 1 ) q order by date, ord 	0.000805003017527619
17224482	32813	add value to a subquery mysql	select distinct spentits.id from `spentits` where `spentits`.`user_id` in     (select following_id      from `follows`      where `follows`.`follower_id` = 5717        and `follows`.`accepted` = 1      union all      select 86) order by id desc limit 1000 offset 0 	0.0438492214261305
17224617	34306	mysql select pageid based on count	select pageid, count(*) from test.comments group by pageid order by count(*) 	0.00481574355297661
17225257	28639	how do i select top 5 from a mysql database	select * from data order by likes desc limit 5 	0.000854137862707652
17225855	14523	select values with latest date and group by an other column	select id, uid, greatest(left_leg, right_leg) as max_leg   from network   where (uid, `date`) in (select uid, max(`date`)                             from network                             group by uid)     and (left_leg > 500 or right_leg > 500) 	0
17226174	17038	how to use result set from one query in second query on same table	select meta_value from ih_postmeta where post_id in (select post_id                   from ih_postmeta                   where meta_key = '_edd_discount_uses'                   and meta_value > '0')      and meta_key = '_edd_discount_code' 	0
17227127	10202	random select after filter in mysql	select v.name, v.site, v.siteid, v.id from video v join      video_tag vt      on vt.id_video = v.id where vt.id_tag in ('1','2') group by v.id having count(distinct vt.id_tag) = 2 order by rand() limit 4; 	0.0512791001188256
17227890	13828	how to extract minimum and maximum time from a table in oracle?	select    username, trunc(login_time), min(login_time), max(logout_time)   from table_name  group by username, trunc(login_time)  order by username, trunc(login_time); 	0
17228733	34159	calculating the average of 2 columns and writing the result in an existing column	select gemetende1, gemetende2, (gemetende1+gemetende2)/2 as gementendeavg from mytablename 	0
17230271	3989	filter text column by its equivalent date value	select * from table1  where concat(right(month_year,4),left(month_year,2)) between '201304' and '201403' 	0.0159714681086517
17231454	38804	mysql select not duplicated values with condition	select a.* from `aukcje_przedmioty` a  join  (   select opis,user_id   from aukcje_przedmioty   group by opis,user_id   having max(aktywne) = 0 ) x  on  x.user_id = a.user_id and  x.opis = a.opis where user_id = 6 	0.0738369437561652
17231824	25982	equal field in sql	select top 1 candidateserials.mobileno      from candidateserials  inner join employerserials on candidateserials.id = employerserials.id and candidateserials.city = employerserials.city where employerserials.mobileno ='000000000' 	0.0629423507865413
17232203	1101	mysql: is it possible to make a select statement, when the value in the db is seperated with commas?	select * from productinfo where find_in_set ('66523', products); 	0.0263319505039167
17232621	34513	converting dates sql server	select     convert(varchar(30), convert(datetime, salesdate), 101)  from [ole db destination03] 	0.29410084629363
17233137	33558	how to search commented string in sql server stored procedures?	select p.* from sys.procedures p where object_definition(p.object_id) like '% 	0.402109973492961
17235360	16891	select row if sub string exist in column otherwise select all rows	select * from table  where fruit = 'apple' or 0 = (select count(1) from table where fruit = 'apple') 	0
17236154	10205	one select on two tables with null and not null	select id       ,name       ,color       ,company_short_nr from table1      left outer join table2 on ( company_short_nr = short ) 	0.00660680298945163
17236461	32803	convert varchar to 3 (sometimes 4) chars in t-sql	select (case when adr_komp_vl like '%[a-z]%'              then right('0000' + convert(varchar(4),replace(adr_komp_vl, ' ','')), 4)               else right('000' + convert(varchar(4),replace(adr_komp_vl, ' ','')), 3)          end) 	0.106168365053402
17238858	13361	sql sort by count with condition, show history	select a.`date`, count(*) cnt, a.ip  from fwlog a join (select ip, count(*) today_count       from fwlog        where `date` = date(now())        group by ip) t   on a.ip = t.ip and t.today_count > 100 group by a.ip, a.date order by t.today_count desc, a.ip, a.`date` desc 	0.0379601288103276
17239515	29583	sql min and max relations in select case	select * from ( select *, row_number() over (order by mondayhourlyamtimes desc) 'booking1'                , row_number() over (order by mondayhourlyamtimes ) 'booking2'        from table        where common criteria      ) where booking1 = 1 or booking2 = 1 	0.47594095018528
17239835	31193	mysql left join only on some rows?	select ... from sometable left join jointable on (sometable.field = jointable.field and (action in (2,3))) 	0.0276983487372246
17240326	24668	only show unvisited links	select * from links where id not in (     select link_id     from out_log     where user_id = <user_id> ) order by id desc limit 0, 10 	0.00241272822806235
17240456	33923	select random x of top y records	select top 5 * from (select top 100 * from cars order by price desc) [a] order by newid() 	0
17240472	25099	selecting data from different rows in the same table with a single statement	select borrowmax, holder, id from mytable where    id = (select holder from mytable where id = 2 )     and category = 3 	0
17241547	29841	trying to select all records where two fields are distinct (but the rest don't have to be)	select      chock_id,      roll_type,      chock_service_dt,     chock_id_dt,      chock_seq_num,      chock_service_cmnt,      total_rolled_lineal_ft,      total_rolled_tons,      chock_usage_cnt,      chock_insert_dt,      record_modify_dt,      next_chock_service_dt_act,     previous_alarm_value,      upload_complete_yn    from (      select         chock_id,         roll_type,         chock_service_dt,        chock_id_dt,         chock_seq_num,         chock_service_cmnt,         total_rolled_lineal_ft,         total_rolled_tons,         chock_usage_cnt,         chock_insert_dt,         record_modify_dt,         next_chock_service_dt_act,        previous_alarm_value,         upload_complete_yn,        row_number() over (          partition by chock_id, roll_type          order by chock_service_dt desc        ) rn      from        tp07_chock_summary_row    ) where rn = 1 	0
17242718	14274	counting new customers per month	select yr, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] from (select datepart(month,mindate) mth, datepart(year,mindate) yr, count(*) cnt  from (select min(orderdate) mindate, max(orderdate) maxdate        from tblorder        group by email) sq  where datediff(month, mindate, maxdate) > 0  group by datepart(month,mindate), datepart(year,mindate)) src pivot (max(cnt)   for mth in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]) ) pvt 	0
17242779	32247	sum aggerate in sql query	select        pdetail.plu, sum(pdetail.detail_for_qty) as detail_for_qty, plu.plu_desc,       plu.last_price from            pdetail inner join                      plu on pdetail.plu = plu.plu_num where        (pdetail.dept = 26) and (pdetail.storenumber in (1, 2, 3, 4, 7, 8, 10, 12, 14, 16)) and (pdetail.time_stamp between convert(datetime,                       '2013-06-20 00:00:00', 102) and convert(datetime, '2013-06-20 23:59:59', 102)) group by pdetail.plu, plu.plu_desc, plu.last_price, pdetail.detail_for_qty order by plu.plu_desc, pdetail.plu 	0.709283319813658
17242905	40352	get sum of delta values per row	select t1.id, sum(t2.timestamp_delta) + 100 from badtable t1 join badtable t2 on t2.id <= t1.id  group by t1.id 	0
17243113	30437	how to select records in one table based on a common id value from another table?	select decsription     from ca_list_item_labels join ca_list_items using (item_id)     where list_id = 41 	0
17243941	34554	mysql - get all %char% and %text% columns with value length of at least x?	select * from information_schema.columns where (data_type = '%char' or data_type like '%text') and character_maximum_length > 10 	0
17244066	15670	duplicate items in sql view/query	select outerf.filename, outerf.filepath,          outerd.providerid, outerp.companyname,      outerd.id as requireddocumentid, outerf.adate,         outerf.auser from  dbo.providers outerp inner join dbo.reqdocuments outerd on outerp.id = outerd.providerid  inner join dbo.uploadedfiles outerf on outerd.id = outerf.reqdocumentsid where (outerd.documentid = 50) and outerf.adate = (     select top 1 innerf.adate     from  dbo.reqdocuments innerd     inner join dbo.uploadedfiles innerf on innerd.id = innerf.reqdocumentsid     where innerd.providerid = outerp.id     and innerd.documentid = outerd.documentid     order by innerf.adate desc) 	0.0202277340176365
17244631	30651	how can i grab the alias of every field with "select *"?	select t.name +'_' + c.name     from sys.columns c inner join          sys.tables t on c.object_id = t.object_id     where t.name = 'residents' 	0.00308673898286733
17244723	3718	sql select where and and	select product.name, size, price from active_product, product, category where product.pid=1 and size=10  and category.name="pen" limit 1 	0.361016297802287
17244791	5416	within a sql server view - how to combine multiple column results into one column	select description as [id], table1id from         (select     table1.description, table2_1.id as table2id_1, table2_2.id as table2id_2, table2.id as table2id_3               from         table1 left outer join                                     table2 on table1.id = table2.table1id3 left outer join                                     table2 as table2_2 on table1.id = table2_2.table1id2 left outer join                                     table2 as table2_1 on table1.id = table2_1.table1id1) as pvttbl      unpivot ( table1id for id in (table2id_1, table2id_2, table2id_3)) as unpvttbl order by description, table1id 	0.000109292853001057
17245742	39222	search from a table using values of a column of another table	select two.*   from two  where (select count(*) from one) =        (case when col1 in (select * from one) then 1 else 0 end +         case when col2 in (select * from one) then 1 else 0 end +         case when col3 in (select * from one) then 1 else 0 end +         case when col4 in (select * from one) then 1 else 0 end        ) 	0
17246003	35238	mysql query data transformation	select driver.qtryr, count(*) as totalperformers,        sum(performance_level = 'high') as highperformers,        sum(performance_level = 'medium') as mediumperformers,        sum(performance_level = 'low') as lowperformers from (select 2007 as yr, 1 as qtr, 'q1-2007' as qtryr union all       select 2007 as yr, 2 as qtr, 'q2-2007' as qtryr union all       select 2007 as yr, 3 as qtr, 'q3-2007' as qtryr union all       select 2007 as yr, 4 as qtr, 'q4-2007' as qtryr       ) driver left outer join      table1 emp      on year(emp.start_date)*4+quarter(emp.start_date) <= driver.yr*4+qtr and         (emp.termination_date is null or          year(emp.termination_date)*4+quarter(emp.termination_date) > driver.yr*4+qtr         ) group by driver.qtryr 	0.528124083677054
17246201	19251	how to select 2 variables from another table sql server query	select table2_1.username as username1, table2_2.username as username2 from table1 join table2 as table2_1 on table1.id1 = table2_1.id join table2 as table2_2 on table1.id2 = table2_2.id 	0.000827666999072761
17247245	1639	mysql - sum/count different columns from different tables	select p.id, p.title, r.rating, v.views   from product p left join (    select product_id, sum(rating) rating     from product_rating    group by product_id ) r on p.id = r.product_id left join (   select product_id, count(*) views     from product_view    group by product_id ) v on p.id = v.product_id order by r.rating desc 	0
17248246	33756	mysql select : how to include a field from another table?	select * from profile natural join country where fullname='cindy' 	6.52297459108905e-05
17248584	8611	how to get the combinations of three columns of a table in pl/sql?	select *   from (select a from mytable),        (select b from mytable),        (select c from mytable); 	0
17249100	39035	mysql search for duplicates across multiple columns	select group_concat(id) ids,q1a text,1 col  from mytable group by text having count(*)>1 union select group_concat(id),q2a text,2  from mytable group by text having count(*)>1 union select group_concat(id),q3a text,3   from mytable group by text having count(*)>1 union select group_concat(id),q4a text,4   from mytable group by text having count(*)>1 union select group_concat(id),q5a text,5  from mytable group by text having count(*)>1 	0.010824260747276
17250487	21326	count rows grouped by condition in sql	select id, count(itemid) as itemcount  from yourtable  group by id  having count(itemid) > 1 	0.00540429383747381
17252322	30806	recreating whole sql server database with relations	select 'alter table '+s.name+'.'+t.name+ ' alter column '+c.name+' nvarchar('+convert(varchar(11),c.max_length/2)+') go' from    sys.tables as t inner join sys.schemas as s on t.[schema_id]=s.[schema_id] inner join sys.columns as c on t.[object_id]=c.[object_id] and c.system_type_id=239 	0.746326646940223
17254756	28363	query in mysql between 2 tables	select cp.productid, producttitle from cms_products cp left join cms_group_products cgp on (cp.productid = cgp.productid and gid = 1000) where cgp.productid is null 	0.0210533112881733
17258140	26408	mysql join same table twice on same column with different value returning most recent row only	select i.id,          i.address,         i.status,        p.max_date contract_date,         p.basis_value contract_price,         e.max_date estimate_date,         e.basis_value estimate_value   from instructions i left join (     select q1.instruction_id, max_date, basis_value       from estimates e join     (         select instruction_id, max(basis_date) max_date           from estimates          where basis = 'customerestimate'          group by instruction_id     ) q1 on e.instruction_id = q1.instruction_id and e.basis_date = q1.max_date ) e on i.id = e.instruction_id left join (     select q2.instruction_id, max_date, basis_value       from estimates e join     (         select instruction_id, max(basis_date) max_date           from estimates          where basis = 'contractprice'          group by instruction_id     ) q2 on e.instruction_id = q2.instruction_id and e.basis_date = q2.max_date ) p on i.id = p.instruction_id 	0
17258723	2983	how to get data from mysql with a specific word?	select * from posts where lower(post_body) like '%#walking%'; 	0.000124818437605486
17259716	34483	selecting specific row number in sql	select orderingcolumn  from (     select orderingcolumn, row_number() over (order by orderingcolumn) as rownum     from mytable ) as myderivedtable where myderivedtable.rownum between @startrow and @endrow 	0.000139695413646395
17260548	21799	how to build that query (sum,group by)	select id,  sum(case when type = 0 then amount else 0 end) as "cash", sum(case when type = 1 then amount else 0 end) as "credit",  sum(amount) as "total" from your_table group by id 	0.313861069712074
17261632	17719	sql server select query to display all records sorted by latest record inserted or updated	select     * from employee order by      case       when login_time > logout_time then login_time        else logout_time     end desc 	0
17262968	31078	return one value if true, return another value if not true	select      id, type, price, code, date  from      tblproduct tbpr where      (code = '1234' and date in (select max(date) from tblproduct where type= tbpr.type    and code = '1234')) or date in (select max(date) from tblproduct where type= tbpr.type           and not exists(select code from tblproduct where type= tbpr.type  and code is  not null) ) 	0
17263764	20401	mysql count() in php	select  drager       , count(*) as number_of_dragers       , sum(price) as price_of_dragers from    your_table group by drager 	0.216516958529162
17265181	14021	sql server: rank by sum of points and order by ranking	select rank() over (order by points desc) as rank ,name,points,games_played,average_points from ( select min(name) as name,email,sum(points) as points ,count(*) as games_played,avg(points) as average_points from @a group by email ) a  order by rank 	0.103415538481928
17268193	41333	selecting random triplicates (or more) from database	select *  from students s  join (     select student_id      from student_grades      group by student_id      having count(*) >= 3      order by rand()      limit 1 ) rs      on rs.student_id = s.id  join      student_grades sg      on sg.student_id = s.id 	0.00492887436325541
17268626	31313	search products from word by word	select  * from [products] p where   not exists(select 1 from split(@keyword,' ') words where (p.name not like '%' + words.items +'%')) 	0.00359688237516876
17270020	6122	custom sorting in php/mysql	select *,col1+col2 p from test order by p; 	0.547986181474156
17271274	12858	is there much additional overhead when retrieving an additional row from a sql server table	select * from questions inner join answers on questions.id = answers.questionid 	0.0129310651916129
17271316	12482	order by month and year in sql with sum	select     { fn monthname(orderdate) } as monthname, year(orderdate) as year, sum(totalvalue) as profits from         [order] where     (year(orderdate) = @year) group by { fn monthname(orderdate) }, month(orderdate), year(orderdate) order by year(orderdate),month(orderdate) 	0.00143390878993605
17271807	1024	get data with join in mysql	select   item.id,   item.item_name,   group_concat(tel) contact_tel from   item left join contact   on find_in_set(contact.id, replace(item.contact_id, ';', ',')) group by   item.id,   item.item_name 	0.0740639232499363
17271947	3624	count all database entries separated by days	select   date(from_unixtime(date)), count(*) from     offers_consumers_history group by date(from_unixtime(date)) 	0
17272027	40339	how to subtract as value from as value in a extra as column in mysql	select q.a, q.b, q.a-q.b as c from   (select    (     select          #group_concat(in_quantity),          sum(in_quantity) gp from stockin where serialno = 'aaa1'   ) a,   (     select          #group_concat(out_quantity),         sum(out_quantity) sop from stockout where serialno = 'aaa1'   ) b ) q 	0
17272405	4853	using left outer join get get all links from the table	select coalesce(p.permalink, '') from languages l left join dbo.product p on p.idlanguage = l.idlanguage where p.idproduct = 1 or p.idproduct is null order by l.idlanguage 	0.000366484126242856
17273372	35007	sql select count values negativ positiv and zero values	select date, sum(case when value > 0 then 1 else 0 end) as pos, sum(case when value < 0 then 1 else 0 end) as neg, sum(case when value = 0 then 1 else 0 end) as zero from yourtable group by date 	0.00594681975570205
17273476	32402	find most recent row from two tables in mysql	select t.user_id     , cast(substring_index(group_concat(t.earning order by t.created_date desc), ',', 1) as decimal) as latest_earning     from (         select user_id             , created_date             , earning             from tablea         union all         select user_id             , created_date             , earning             from tableb     ) t     group by t.user_id; 	0
17274335	9525	select from multiple rows where and join the language column if id matched	select  `article_id` , group_concat(  `language_id` )  from  `article`  group by  `article_id`  limit 0 , 30 	0
17278220	13418	calculate percentage in mysql query	select   machine , count(distinct machine) as "nb" , count(distinct     if(qc_gsr = "green"    and qc_hr = "green"    and qc_acz = "green"    and qc_bre = "green"     ), machine, null)   ) as "green_nb" , count(distinct     if(qc_gsr = "green"    and qc_hr = "green"    and qc_acz = "green"    and qc_bre = "green"     ), machine, null)   ) / count(machine) * 100 as "%" from rtcdb.session where project = "csc032" group by machine ; 	0.0333976975254164
17279899	21905	add column to datatable and populate with query against same datatable in vb.net	select id, startdate, codeid, param, endtime, datediff(ms,endtime,startdate) as yourdiff from dtb 	0.0197225470768306
17280011	25342	include the table name in a select statement	select 'table1' as tablename, col1, col2 from anytable; 	0.0161800631458336
17281438	24832	select min date after selected date	select t1.obj, t1.time as start, min(t2.time) as stop from thetable t1 left outer join thetable t2 on t1.obj = t2.obj and t2.description = 'stop' and t2.time > t1.time where t1.description = 'start'  group by (t1.obj, t1.time, t1.description, t2.description) 	0.00198027231130852
17282494	130	extract multiple decimal numbers from string in t-sql	select   cast(left(r, charindex('%', r) - 1) as float) as minval,   cast(replace(right(r, charindex('-', r) - 1), '%', '') as float) as maxval from ( select '22.45% - 42.32%' as r ) as tablestub 	0.000516413855267106
17284617	31209	query in sqlite3	select task._id, task.name, task.idcompany, task.idemployee,      company.name as namecompany, employee.name as nameemployee from task left join company on task.idcompany = company._id left join employee on task.idemployee = employee._id 	0.605377320927023
17285164	13193	select following friday date	select dateadd(day,6-datepart(weekday,the_dt),the_dt)  + case when datepart(weekday,the_dt) = 7 then 7 else 0 end from table 	0.100009625127596
17285723	15808	mysql: anagram query to pull every possible word with any letters	select `word`, 0+if(`a` > 0, `a` - 0, 0)+if(`b` > 0, `b` - 0, 0)+if(`c` > 0, `c` - 0, 0)+if(`d` > 0, `d` - 0, 0)+if(`e` > 1, `e` - 1, 0)+if(`f` > 0, `f` - 0, 0)+if(`g` > 0, `g` - 0, 0)+if(`h` > 0, `h` - 0, 0)+if(`i` > 1, `i` - 1, 0)+if(`j` > 0, `j` - 0, 0)+if(`k` > 0, `k` - 0, 0)+if(`l` > 0, `l` - 0, 0)+if(`m` > 0, `m` - 0, 0)+if(`n` > 1, `n` - 1, 0)+if(`o` > 0, `o` - 0, 0)+if(`p` > 0, `p` - 0, 0)+if(`q` > 0, `q` - 0, 0)+if(`r` > 0, `r` - 0, 0)+if(`s` > 1, `s` - 1, 0)+if(`t` > 2, `t` - 2, 0)+if(`u` > 0, `u` - 0, 0)+if(`v` > 0, `v` - 0, 0)+if(`w` > 0, `w` - 0, 0)+if(`x` > 0, `x` - 0, 0)+if(`y` > 0, `y` - 0, 0)+if(`z` > 0, `z` - 0, 0) as difference from `twl06` where length(`word`) <= 8 having difference <= 2 	0.00625275757875132
17285750	22197	getting specific index from sql	select *, row_number() over(order by [youordercolumns]) as [rownum] from [youtable]     where [rownum] between @index and @index + 4 	0.0196307362408475
17286534	34981	select four concurrent events meeting a criteria mysql	select soundconsole, st.crewstarttime, count(*) from (select distinct crewstarttime, soundconsole       from tc_event      ) st join      tc_event e      on st.crewstrattime between e.crewstarttime and e.crewendtime and         st.soundconsole = e.soundconsole group by st.crewstarttime, tc.soundconsole having count(*) >= 4 	0.00325204120760678
17290266	40897	selecting from two table using joins	select f.favcolorid, c.color, case when c.colorid = f.colorid then 'yes' else 'no' end isfavorite from tblcolours c, tblfavcolours f order by 1 	0.00300760995840631
17291390	17655	how to add a column as a result of date function in pl/sql?	select temp.*,to_char(adate,'dd/mm/yyyy') d from temp, ( select (sysdate + rownum -1) adate   from dual connect by rownum <= 7 ) t order by temp.a,temp.b,temp.c,temp.h,t.adate 	0.00353859406066032
17292062	17672	how to skip rows in mysql query	select  n.newsid,         n.headcaption,         (select name from newscategory           where newscategoryid = n.headlinecategoryid) category,         n.picurl,         n.creation,         substring((fnstriptags(n.description)),1,75) as shortdescription from    news n inner join         (select  headlinecategoryid, max(newsid) max_id          from    news                     group   by headlinecategoryid) n_     on n.headlinecategoryid = n_.headlinecategoryid and       n.newsid = n_.max_id order by n.viewindex desc   limit 6 limit 6; 	0.019656326424611
17293504	9012	transact-sql: display two sum() from differents tables?	select code, sum(v1), sum(v2)   from (select code, value v1, null v2           from table1         union         select code, null v1, value2 v2           from table2)  group by code 	0.000128046905254709
17293751	13196	finding maximum values in a table	select * from orders where employeeid  = (select max(employeeid) from orders); 	0.000115339042261483
17294088	39023	multiple inner join on different tables in ms access	select p.study_id,         h.text_data as hospital,         g.text_data as gender from (patientinformations as p     inner join (select text_data, value_data                 from mstmasterlookup                 where is_active and table="hospital") as h     on p.hospital_id=cstr(h.value_data))     inner join (select text_data, value_data                 from mstmasterlookup                 where is_active and table="gender") as g     on p.gender=cstr(g.value_data); 	0.338149659783146
17294933	30099	sql table with multiple rows per account	select * from accounttable where accountid not in (select distinct accountid from account_actioncode where actioncode = 'code001') 	0.000270331345773319
17295314	4881	find for each people_id corresponding role_id with maximum count	select a.person_id, a.role_id, a.count from table a inner join  (     select person_id, max(count) as maxcount     from table     group by person_id ) sub1 on a.person_id = sub1.person_id and a.count = sub1.maxcount 	0
17295549	19772	how to add a user defined column with a single value to a sql query	select product_id, order_quantity, 999 as user_value from product_table group by sales_day 	0.000224567005349123
17297106	8814	find a list in a list	select * where (key1=c1 or key1=c2 or key1=c3 or key1=c4) and                 (key2=c1 or key2=c2 or key2=c3 or key2=c4) and                 (key3=c1 or key3=c2 or key3=c3 or key3=c4) and                (key4=c1 or key4=c2 or key4=c3 or key4=c4) 	0.00115319140438572
17297783	3431	show number of similar records in sql recordset	select     createdate,     a,     b,     c,     d,     e,     duplicatescount =      (         select count(*) as c         from table as t2         where dateadd(minute, 10, t1.createdate) > getdate()            and t2.b = t1.b and t2.c = t1.c and t2.d = t1.c     )     from table as t1 	5.35898980546877e-05
17300728	17901	return only one row from oracle sql, using outer join and case statement	select t."date", t."site", t."result",         sum(case when a.type = 'act1' then a.count else 0 end ) as act1,         sum(case when a.type = 'act2' then a.count else 0 end ) as act2 from   sample left outer join activity         on (activity.sample_id = t.sample_id) where  sample.date is between then and now 	0.109706781501962
17300990	30899	how to find out if a numeric(18,2) contains decimal places?	select case     when cast(mycol as int) = mycol then 'b'      else 'a' end 	0.000686390611676529
17300993	19093	combining two distinct oracle queries	select distinct reservationgroupname as \"entry\", 'groupname' as \"type\" from eventdatatable     union select distinct bookingeventtype as \"entry\", 'eventtype' as \"type\" from eventdatatable 	0.0495769769816798
17301323	13583	why are my view's columns nullable?	select attrelid, attname, attnotnull, pg_class.relname from pg_attribute inner join pg_class on attrelid = oid where attname like 'something%' 	0.337756404102171
17301779	1514	return 'something' instead of null	select f.name from firms f where f.id = @{_firmid} union select 'wrong id' as name from firms  where @{_firmid} not in (select id from firms) 	0.0570474106135365
17301912	28455	sql query for aggregate on multiple rows	select name from tablename where indicator in(1, 2) group by name having count(distinct indicator) = 2; 	0.134258967004689
17302310	39345	how to create a query two or more values?	select      c.car_id     ,c.car_year     ,count(p.peo_id) from car c inner join people p on c.card_id = p.car_id group by    c.car_id ,c.car_year having  count(p.peo_id) > 3 order by c.car_year 	0.0134639756608893
17302426	1766	mysql avergae and max number	select max(bid), avg(bid) from sometable group by veh_id 	0.0251582541539296
17303755	31109	sql: calculating number of days between dates of one column in different rows	select  * ,       datediff(day, min(date) over (partition by [id number]), date) from    yourtable 	0
17305561	24098	php/mysql targeting only month from date field	select * from tablename where date_column_name like '2013-06%' 	0
17307619	34104	mysql retrieve lowest value in multi-table query	select sku, purchase_price, order_number from (     select min(purchase_price) as purchase_price, sku     from purchase_ord_contents     join purchase_orders using (order_number)     where purchase_orders.order_status = 1     group by sku ) as min_sku_price  join purchase_ord_contents using (sku, purchase_price)  join purchase_orders using (order_number) where purchase_orders.order_status = 1 	0.00701859292851715
17308116	19106	sql get first row of each unique id and each row with that id within x time after the first	select a1.* from   actions a1 inner join (select   userid, min(date) first_action                          from     actions                          group by userid) a2   on a1.userid = a2.userid and a1.date <= first_action + interval 24 hour 	0
17308652	25842	select not exist	select * from category where sid = 3 and bid = 0  and name not in (select name from category where sid = 3 and bid = 8) 	0.374006096116422
17308667	16636	sql stored procedure to obtain top customers	select top 2 c.id_customer, c.name, sum(s.total_with_tax) from customer c join sale s on c.id_customer = s.id_customer group by c.id_customer, c.name order by sum(s.total_with_tax) desc 	0.0251462485574197
17310126	9504	count number of records with matching values in separate fields	select t.*, tsum.mycount  from mytable t join      (select orig_id, count(name) as mycount       from mytable       group by orig_id      ) tsum      on t.id = tsum.orig_id; 	0
17310615	19766	is there any way to retrieve both aggregated and non-aggregated values without subquery?	select       stock_code     ,[1st week] = sum(case when [date] >= getdate()-7 then amount else 0 end)     ,remainder = sum(amount) from data group by stock_code 	0.0131810520438225
17310679	31704	separating variables inside an array	select sum(distance)  from table  where (origin='a' and destination='b')     or (origin='b' and destination='c')    or (origin='c' and destination='d') 	0.632844413261581
17312335	20268	find employee tenure for a company	select fk_project_id,e.emp_id,min(start_date) as emp_start_date ,max(end_date) as emp_end_date,     e.competency,e.first_name+' '+e.last_name+' ('+e.emp_id+')' as name,'period'=         case              when datediff(month,min(start_date),max(end_date))<=12 then '<1 year'             when datediff(month,min(start_date),max(end_date))>12 and datediff(month,min(start_date),max(end_date))<=24 then '1-2 years'             when datediff(month,min(start_date),max(end_date))>24 and datediff(month,min(start_date),max(end_date))<=36 then '2-3 years'             when datediff(month,min(start_date),max(end_date))>36 then '>3 years'         else 'na'         end       from dp_project_staffing ps     left outer join dp_ext_emp_master e          on e.emp_id=ps.emp_id     where fk_project_id=@proj_id     group by fk_project_id,e.emp_id,e.competency,first_name,last_name 	0.00185744151391191
17314626	9837	mysql query with multiple tables for autocomplete	select distinct name as name  from products_names a join products b on a.id_product = b.id  where ((name like '%$q%' and language_code = 'pl') or (name2 like '%$q%' and language_code = 'pl')) and status = 0 	0.744011981835747
17315054	19523	select random user from database table and store in another table	select userid, firstname, surname, email from users where not exists (select * from winners                 where users.userid = winners.userid) order by rand() limit 1; 	0
17315067	28675	create row with every csv value	select          a.id,                 substring(',' + a.dates + ',', n.number + 1, charindex(',', ',' + a.dates + ',', n.number + 1) - n.number - 1) as [value]                 , [qty], [secs], [daypart] from            table1 as a inner join      master..spt_values as n on substring(',' + a.dates + ',', n.number, 1) = ',' where           n.type = 'p'                 and n.number > 0                  and n.number < len(',' + a.dates + ',') 	0.000325694643653785
17316255	29420	insert a unique dummy column when creating view with union	select row_number() over ( order by request_id, request_type ) as id      , a.*   from ( select d.delivery_request_id as request_id               , 'delivery' as request_type            from delivery_request d           union all          select i.invoice_request_id as request_id               , 'invoice' as request_type            from invoice_trx i                 ) a 	0.182215774692801
17316350	39373	select distinct and trim on the fly	select distinct(lower(trim(city_name, '&nbsp'))) from cities_object where published = '1' union select distinct(lower(trim(city_name, '&nbsp'))) from cities_firms where published = '1' union select distinct(lower(trim(city_name, '&nbsp'))) from cities_other where published = '1'; 	0.0111181218951136
17317550	20847	get mysql image size stored in blob	select octet_length(att) from table 	0.0577046573845505
17320549	23184	return all columns with distinct on multiple columns in sql table	select col1, col2, col3, max(col4), min(col5)  from tbl  group by col1, col2, col3 	0
17320566	35834	multiple selection from a table	select   packages.status,   picklocation.name,   picklocation.address,   picklocation.zip,   picklocation.city,   picklocation.id,   droplocation.name,   droplocation.address,   droplocation.zip,   droplocation.city,   droplocation.id from packages  inner join locations as picklocation on packages.pick_id = picklocation.id inner join locations as droplocation on packages.drop_id = droplocation.id where packages.client_id = 5 	0.00829894248071245
17320692	37991	inner join query returning all null result when it should return no result	select a.account_id, a.first_name, a.second_name, a.points, c.body, c.creation_time, avg(t.rating_overall) from comments as c inner join accounts as a on c.account_id=a.account_id inner join ratings as t on t.blogger_id=a.account_id where c.blog_id = ? group by a.account_id, a.first_name, a.second_name, a.points, c.body, c.creation_time order by c.creation_time asc 	0.773332998923329
17321088	14184	how can i check if a column exists into a table from a database?	select * from information_schema.columns  where table_schema = 'db_name' and column_name = 'column_name' 	4.82576829310318e-05
17321934	35060	getting duplicates after using distinct	select mer.store_name      , mpr.merchant_code       , mpr.terminal_num       , mpr.rec_fmt       , mpr.bat_nbr       , mpr.card_type       , mpr.card_num       , mpr.transaction_date       , mpr.settle_date       , mpr.approval_code       , mpr.intnl_amt       , mpr.domestic_amt       , mpr.transid       , mpr.upvalue       , mpr.merchant_trackid       , mpr.msf       , mpr.service_tax       , mpr.edu_cess       , mpr.net_amount       , mpr.debit_credit_type       , mpr.udf1       , mpr.udf2       , mpr.udf3       , mpr.udf4       , mpr.udf5       , mpr.seq_num       , mpr.arn_no   from mpr_reports mpr   join storename_tid sid     on sid.terminal_num = mpr.terminal_num   join merchantreports mer     on mer.store_name = sid.store_name  where mpr.rec_fmt in ('cvd','bat')  ; 	0.0567609245182856
17323507	11728	mysql query to return multiple summed columns	select   category,   sum(case when date = '2013-05-01' then count end) as `2013-05-01`,   sum(case when date = '2013-05-02' then count end) as `2013-05-02`,   sum(case when date = '2013-05-03' then count end) as `2013-05-03` from dbtable group by category 	0.00452623813386864
17324648	3830	query to return multiple values from a single column based on value of another column	select startdt.entrydate as startdate,        enddt.entrydate as enddate from table startdt inner join table enddt on startdt.id = enddt.id where startdt.checklistday = 1 and enddt.checklistday = 10 	0
17325014	30377	subtract debit and credit column	select top (100) percent accounting.topica.codea, sum(accounting.documentdetail.debit) as deb, sum(accounting.documentdetail.credit) as cred, case when sum(accounting.documentdetail.credit) - sum(accounting.documentdetail.debit) < 0 then sum(accounting.documentdetail.debit) - sum(accounting.documentdetail.credit) else 0 end as neg, case when sum(accounting.documentdetail.credit) - sum(accounting.documentdetail.debit) > 0 then sum(accounting.documentdetail.credit) - sum(accounting.documentdetail.debit) else 0 as pos, accounting.topica.description from accounting.topica  inner join accounting.documentdetail  on accounting.topica.codea = substring(accounting.documentdetail.topic, 1, 2) group by accounting.topica.codea, accounting.topica.description order by accounting.topica.codea 	0.0287068394252388
17325587	12410	multiple ands from multiple columns in an inner join	select        p.id,       p.product_name,       p.price    from        products p          inner join fieldvals fv1             on p.id = fv1.product_id              and fv1.fielddef_id = '7'             and fv1.value = 'value expected for 7'          inner join fieldvals fv2             on p.id = fv2.product_id              and fv2.fielddef_id = '8'             and fv2.value = 'value expected for 8'          inner join fieldvals fv3             on p.id = fv3.product_id              and fv3.fielddef_id = '9'             and fv3.value = 'value expected for 9'          (continue same "join" sample above for as many           criteria conditions you need to add... just keep           incrementing the alias ... fv1, fv2, fv3, etc...)    where        p.product_name like '%your criteria%' 	0.26941054941704
17325861	24306	join only if column is null	select t.id        ,coalesce(tt.title, t.title) as title from tag t left join tag_translation tt     on t.id = tt.tag_id     and tt.locale = 'fr'; 	0.0580591483775622
17326248	13740	sql: return additional column from inner join subquery with 2 tables	select  custom.proj_id, custom.proj_name, finaldb.acct_id from    deltek.proj_custom custom inner join  ( select  distinct proj_id, acct_id from    deltek.psr_final_data ) finaldb on      finaldb.proj_id = custom.proj_id where   custom.proj_id like '61000.001.[a-z]%'; 	0.0712268177910677
17326984	35502	sql- select a value within a cursor loop	select unique count(status) into result from    src_table st, bucket_table bt, many_table mt where   st.id = bt.st_id and    bt.mt_id = mt.id and status = 1 	0.106765011503508
17328485	33917	select different fields from more than one table in sql server using inner join	select         l.accounttype      , l.[status]      , r.usrflname      , r.usremail      , e.empid      , s.stuid      , e.empdept      , f.frarea      , f.frname  from dbo.registration r join dbo.imslogin l on r.regid = l.regid  left join dbo.students s on r.regid = s.regid  left join dbo.employee e on r.regid = e.regid  left join dbo.franchise f on r.regid = f.regid 	0.00154005820313711
17329920	18991	select query with join multiple tables in sql server	select sum(quantity) totalquantity, sum(quantity * rate) totalamount, sum(quantity) / sum(quantity * rate * 1.0) result from (    select uid, cid, quantity, rate    from a    union all    select uid, cid, quantity, 1 rate    from b    union all    select uid, cid, quantity, rate    from c ) t where    t.uid = 1     and t.cid = 1 	0.561301116376523
17331384	29815	mysql - grouping into ranges based on a sum	select id, lmh from (     select id, sum(round(revenue)) as total_rev, 'low' as lmh        from revenue        group by id        having total_rev > 0 and total_rev <= 5     union all     select id, sum(round(revenue)) as total_rev, 'med' as lmh        from revenue        group by id        having total_rev > 5 and total_rev <= 20     union all     select id, sum(round(revenue)) as total_rev, 'high' as lmh        from revenue        group by id        having total_rev > 20) as subquery     order by id 	0
17331940	20134	select data from one table, check against and pull values from second table	select a.action_id, a.action_type, a.action_details, a.action_int, a.action_time, q.section_id  from actions a left join questions q on a.action_int = q.id  where a.user_id = '".$id."'     and a.action_type = 'other'     and a.action_details in('random question', 'review')      and q.section_id in (2,3,4,5,6,7,8); 	0
17332021	16339	combining consecutive sql rows, every other one, with a caveat	select          a.employee,         a.timey,         b.timex     from table1 a         cross apply         (             select top(1) t.timex                 from table1 t                 where a.[date] = t.[date]                     and a.employee = t.employee                     and a.timey < t.timex                     and t.[type] = 'b'                 order by t.timex asc         ) b     where a.[type] = 'a'     order by a.employee asc ; 	0
17332492	2087	join two tables and get number of rows	select count(*) from posts join topics t on (topic_id = t.id) where forum_id = 1 	0
17332676	19897	sql query how to get the next row date using the temp field value?	select seq, @i := @i + 1 i, fld_date, next_date from (   select seq, @d next_date, @d := fld_date fld_date     from lms_savings, (select @d := 0) d   order by seq desc ) q, (select @i := 0) n  order by seq 	0
17333967	266	dynamic sql select	select (         case id              when 1                    then id + ' (auto)'               else id end) as id  from example 	0.556996081483295
17334912	4584	how to get timestamp of mysql table in relative time on website	select *, case when creation between date_sub(now(), interval 60 minute) and now() then concat(minute(timediff(now(), creation)), ' minutes ago') when datediff(now(), creation) = 1 then 'yesterday' when creation between date_sub(now(), interval 24 hour) and now() then concat(hour(timediff(now(), creation)), ' hours ago') else date_format(creation, '%a, %m/%d/%y') end as date from sample 	4.99871149081065e-05
17335285	13197	mysql select with case not retrieving other column value?	select age_range, count(*), a.location from (         select case             when yearsold between 0 and 5 then '0-5'             when yearsold between 6 and 10 then '6-10'             when yearsold between 11 and 15 then '11-15'             when yearsold between 16 and 20 then '16-20'             when yearsold between 21 and 30 then '21-30'             when yearsold between 31 and 40 then '31-40'             when yearsold > 40 then '40+'             end as 'age_range', b.location             from (                 select year(curdate())-year(date(birthday)) 'yearsold',                 location                 from event_participants             ) b     ) a     group by a.location, age_range 	0.00617335329254048
17335772	24053	reverse query for hierarchical data	select i.id, l.lev1 as name, null as parent from idtable i       join leveltable l on i.name = l.lev1 union select i.id, l.lev2 as name, (select j.id from idtable j where j.name = l.lev1) from idtable i       join leveltable l on i.name = l.lev2 union select i.id, l.lev3 as name, (select j.id from idtable j where j.name = l.lev2) from idtable i       join leveltable l on i.name = l.lev3 	0.545069981823545
17336349	7614	get count of duplicate records from database	select id,name, count(*) as dupecount from name group by id,name having count(*) > 1 order by id 	0
17336749	15001	joining 3 tables using inner join in sql server	select       bill.bill_no as billno     , count(room_no_info.room_number) as totalroom     , convert(varchar(11), room_no_info.in_date, 106) as indate     , convert(varchar(11), room_no_info.out_date, 106) as outdate     , bill.total as amount     , isnull(advance_cost.total_amount, 0) as advance     , isnull(advance_cost.total_amount, 0) as paid     , bill.balance as balance from room_no_info inner join bill on bill.bill_no = room_no_info.bill_no left join advance_cost on bill.bill_no = advance_cost.room_bill_no       and bill.date = '26-jun-13' group by       bill.bill_no     , room_no_info.in_date     , room_no_info.out_date     , bill.total     , advance_cost.total_amount     , bill.balance 	0.689986482600985
17336854	3436	join two queries to form an result set	select * from ecart_orders inner join(   select     orderid,   group_concat(distinct(categoryid) order by orderid separator ', ')  as catid   from   `ecart_product` inner join ecart_orderdetail   where ecart_orderdetail.productid =   ecart_product.id group by orderid) as c    on ecart_orders.id=c.orderid 	0.0551931672467633
17337194	27414	sql, select from two tables without getting all the rows	select c.id,         c.userid,         ch.text,         ch.timestamp from comment c inner join commenthistory ch   on ch.commentid = c.id where ch.timestamp = (select max(ch2.timestamp)                       from commenthistory ch2                       where ch2.commentid = c.id ) order by ch.timestamp desc 	0
17337302	19451	how to compare two records	select * from newtable except select * from oldtable 	0.000390569613872788
17338196	32588	sort by month expressed by a string in sql	select time, ordervalue from orders order by convert (datetime, '01 ' + time, 104) 	0.00413850830936848
17339498	30884	subtotal of all items in a query	select i.fk_purchase_order poid,        description         item,        quantity            itemqty,        price               itemprice,        quantity * price    itemtotal,        s.subtotal          subtotal   from purchase_order_items i join (   select fk_purchase_order, sum(quantity * price) subtotal     from purchase_order_items    group by fk_purchase_order ) s on i.fk_purchase_order = s.fk_purchase_order 	0.00103426209118681
17340808	16094	group by in subquery?	select       datepart(wk, oh.exportdate) as wk     , datepart(dw, oh.exportdate) as day     , ro.name     , pallets = sum(oh.pallets)     , box = sum(n) from dbo.orderheadpdaevent ohpe left join dbo.orderhead oh on oh.id = ohpe.id_orderheader left join dbo.[route] ro on oh.id_route = ro.id left join (      select n = count(number), id_orderhead      from dbo.orderitem      group by id_orderhead  ) t on t.id_orderhead = oh.id where id_route = '00000000-0000-0000-0000-000000000000'      and oh.exportdate between                           dbo.getstartofday('2012-08-01 14:35:00.000')                           and                           dbo.getendofday('2013-08-08 14:35:00.000') group by       oh.exportdate     , ro.name order by wk 	0.643133016585301
17340860	37552	sql-i want to reduce the execution time	select date_format(max(login_time),'%y-%m-%d')     from user as u     inner join aaa as a        on u.user_id = a.user_id     group by a.user_id     order by a.user_id 	0.742256312370938
17342005	21151	conditional selecting rows based on a column value	select * from tablename where flag=1  union  (select * from tablename a where  (select count(*) from tablename b  where a.range_id=b.range_id  and b.flag=1)<1) 	0
17343290	33380	asc order in number column	select * from  bonus order by cast(points as int) asc; 	0.0153677991349492
17343887	29123	format date as month dd, yyyy?	select datename(mm, getdate()) + right(convert(varchar(12), getdate(), 107), 9) as [month dd, yyyy] 	0.000843193424919951
17344504	25924	how to match with like in other table and count	select eacode, substring_index(substring_index(area, '-', 2), '-', -1) as area, count(*) `count`, teamleader from f12 join areas2013 on area like concat(eacode, '-%') group by eacode 	0.00794165046731411
17344567	10266	joining of 5 tables	select bill.bill_no,bill.total,bill.discount,bill.to_be_paid,        isnull(service_bill.total_amt,0) as servicecharge,        isnull(damage_cost.total_amt,0) as damagecost,        isnull(extraperson_cost.total_amt,0) as extracost,        isnull(advance_cost.total_amount,0) as advance  from   bill  left join advance_cost           on bill.bill_no=advance_cost.room_bill_no  left outer join service_bill     on bill.bill_no=service_bill.room_bill_no  left outer join damage_cost      on bill.bill_no=damage_cost.room_bill_no  left outer join extraperson_cost on bill.bill_no=extraperson_cost.room_bill_no where  bill.bill_no='57' 	0.00568992691035334
17345510	1709	sql server find duplicate dates with the same id	select [uniqueid], [requirementid], [number], [description], [dtmexecuted], [amount] from (select t.*,              count(*) over (partition by requirementid, dtmexecuted) as cnt       from mytable t      ) t where cnt > 1 	0
17345716	25290	loop through xml to return all nodes	select  doc.value('./orderitemid[1]/text()[1]','nvarchar(255)') as 'orderitemid',         doc.value('./quantityordered[1]/text()[1]', 'int') as 'quantityordered'  from    @xml.nodes('/listorderitemsresult/orderitems/*') as ref ( doc ) 	0.0065403915122409
17345746	37732	how to select the last distinct record in sql server	select  cod,id,balance,[date] from ( select row_number() over(partition by cod,id order by [date] desc) as row, cod,id,balance,date from table) t where t.row=1 	6.83290059692554e-05
17346710	4885	sql multiple where's assigns a new table column	select sum(case when coord = 'alfa' then [total $] end) as t01,        sum(case when coord = 'beta' then [total $] end) as t02,        sum(case when coord = 'gamma' then [total $] end) as t03 from pfin_base 	0.00631027530839661
17347418	20286	joining id's for a combobox	select table5.id, table5.field1  from table5  union  select table6.id, table6.field1  from table6 left join table5 on table6.[field1] = table5.[field1]  where (((table5.field1) is null)); 	0.00512751816664983
17347728	14247	how to get distinct values from a column with all its corresponding values in another column	select cname, group_concat(survey_id) as survey_ids from categories  group by cname 	0
17348364	3303	inserting a new indicator column to tell if a given row maximizes another column in sql	select product_id_1, product_id_2 ,score, (case when b.score= (select max(a.score) from tablename a where  a.product_id_1=b. product_id_1)  then 1 else 0 end) as is_max_score_for_id_1   from tablename b 	0
17349247	39047	assigning results of sql query to local variables	select @address = address ,         @serialnumber = serialnumber  from dummytable where id = 10 	0.743940097683964
17349693	1721	how to sort the result by displaying parent id first then all the children id underneath it	select   * from     mytable order by case when parent=0 then id else parent end, id 	0
17351514	11384	mysql won't order by int	select * from faq order by `order` 	0.736199633313213
17353481	16628	sql server date calculations in stored procedures	select dateadd(s,-1,dateadd(mm, datediff(m,0,'2014-03-01'),0));                                               ^^^^^^^^^^ 	0.543216544720775
17354605	7302	mysql php array - find values from array that do not match query	select job_id from table where user_id = '$user_id' and not exists    (select *    from table    where user_id = '$user_id'    and job_id in ($job_id)) 	0.000335786634293936
17354665	40408	stored procedure for each unique value, do calculation and store result	select salesrepid, sum(ticketpricetotal) as 'sum(ticketpricetotal)', renewalgroup  from ticketrenewals   group by salesrepid, renewalgroup 	0.000437202480867527
17354837	21535	need sql query for recent status	select * from orders o    join status st on o.id=st.id    join employees em on o.created_by = em.id   where st.date = (        select max(date)           from status          where id=st.id          group by id        ) 	0.0417420728830449
17354881	19329	removing part of text before and after specific character in sql server table	select substring(description, charindex ('~', description, 1)+1, charindex ('~~', description, 1)-charindex ('~', description, 1)-1)  from item 	0.00324477834752028
17355130	6824	limit sql query to only the top two counts per group	select    state,    flv,    total from (select          row_number() over ( partition by state order by count(initcap(trim(flavor))) desc ) rownumber,          state,          initcap(trim(flavor)) flv,          count(initcap(trim(flavor))) total       from favorite_flavor       group by state, initcap(trim(flavor))       ) dt where rownumber <= 2 order by state asc, total desc 	5.26822335672138e-05
17355775	32952	inner join and null value	select name, subject, class  from table1     left join table2 on table1.subjectid = table2.subjectid     left join table3 on table1.classid = table3.classid where studentid = 3 	0.44224216999134
17356465	25124	sqlite3. select only highest revision using fks, max() and group by	select i.* from income i     inner join (         select id, max(revision) maxrevision         from businessday         group by id     ) t on i.businessday_id = t.id and i.businessday_revision = t.maxrevision 	0.000218764420260251
17356887	6688	implementing a where clause within a subquery for the value of a pivot column?	select      content.id as id, content.alias as alias,     (          select modx_site_tmplvar_contentvalues.value from modx_site_tmplvar_contentvalues          where modx_site_tmplvar_contentvalues.tmplvarid = 324          and modx_site_tmplvar_contentvalues.contentid = content.id       ) as featured,      date_values.value as date     from modx_site_content as content      left join          modx_site_tmplvar_contentvalues as tv_values         on tv_values.contentid = content.id     left join         modx_site_tmplvar_contentvalues as date_values         on date_values.contentid = content.id where content.parent = 1842      and content.published = 1      and date_values.tmplvarid = 289     and date_values.value >= curdate()  group by tv_values.contentid  order by featured desc, date asc 	0.229106935729816
17356918	41057	select maximum n records from table with at most one record per group	select user_id, max(score) from table group by user_id order by max(score) desc limit 3; 	0
17357417	40591	filter rows based on a value of a column	select *  from table1  where name='abc' or party<>'ind'; 	0
17358090	3618	oracle parsing string for separators	select * from table_name  where '|' || column_name || '|' like '%|' || 'search_string' || '|%'; 	0.674325135889018
17359514	25948	how to calculate running total (balance) per group	select id, credit, debit, time, balance from (   select t.*, @n := if(@g <> id, 0, @n) + coalesce(credit,0) - coalesce(debit, 0) balance, @g := id     from table1 t, (select @n := 0) n, (select @g := 0) g    order by id, time ) q 	0.000124462156122042
17359822	8421	sum the highest scores per user and track	select userid, sum(highscore) from (     select userid, trackid, max(highscore) highscore     from mytable     group by userid, trackid   ) s group by userid 	5.00550690761749e-05
17359962	6530	getting last messages by receivers in sms app - sql request	select s.receiver, s.message, i.name, temp.last_sent, i.id from sms s inner join (     select receiver, user_id, max(created_at) as last_sent         from sms         where user_id = ?         group by receiver, user_id     ) temp on s.receiver = temp.receiver and s.user_id = temp.user_id and s.created_at = temp.last_sent left outer join indexes i on s.receiver = i.phone_number  and i.user_id = ?  order by temp.last_sent desc 	0.0123102177994646
17360433	33723	how to formating in sql server	select class,        max(case              when subject = 'chemistry' then               total              else               0            end) as chemistry,        max(case              when subject = 'biology' then               total              else               0            end) as biology,        max(case              when subject = 'physics' then               total              else               0            end) as physics,        max(case              when subject = 'maths' then               total              else               0            end) as maths   from your_table_name  group by class 	0.609301476527673
17362111	5792	join but return all records from table	select  *  from    `table1` left join          `table2` on table1.messageid=table2.messageid  where   `venue_active` = 1 	8.30751323091148e-05
17362444	18800	mysql subquery select all id	select count(distinct id_reparacao) repaircnt, lojas.nome from reparacoes inner join lojas on lojas.id = id_loja  group by lojas.id 	0.0110910695250683
17363650	31601	how to select a specific entry in a list from db?	select project from person p left join fetch p.projects as projs where                         p.name := username and  projs.projectname =: projectname 	0
17363995	24404	match data in a multiple column	select * from yourtable where   case when 18 in (col1, col2, col3, ...col20) then 1 else 0 end + case when  3 in (col1, col2, col3, ...col20) then 1 else 0 end + case when 15 in (col1, col2, col3, ...col20) then 1 else 0 end + case when 16 in (col1, col2, col3, ...col20) then 1 else 0 end + case when 11 in (col1, col2, col3, ...col20) then 1 else 0 end + case when  5 in (col1, col2, col3, ...col20) then 1 else 0 end + case when 41 in (col1, col2, col3, ...col20) then 1 else 0 end + case when 61 in (col1, col2, col3, ...col20) then 1 else 0 end + case when 43 in (col1, col2, col3, ...col20) then 1 else 0 end + case when 80 in (col1, col2, col3, ...col20) then 1 else 0 end = 10 	0.00628921612769966
17365250	2051	generate series of quarters in postgresql	select * from generate_series('2008-01-01 00:00'::timestamp,                               '2009-01-01 12:00', '3 months'); 	0.0163059042516952
17365587	29517	csv of ids to csv of values	select id, things = stuff( (   select ',' + t2.thing       from table2 as t2     inner join table1 as ti     on ',' + ti.ids + ',' like '%,' + convert(varchar(12), t2.id) + ',%'     where ti.id = tout.id     for xml path, type ).value('.[1]', 'nvarchar(max)'), 1, 1, '') from table1 as tout order by id 	0
17366553	28720	select records with date in the last 24 hours	select * from my_table where date > date_sub(now(), interval 24 hour)   and date <= now() 	0
17366712	36147	how to split a column into 2 columns in sql	select substring(parms,1,6) as media  from your table; 	4.63747621552107e-05
17367822	353	use order by field for certain field, but keep order in date field - mysql php	select * from table order by field(request_status, 'wait', '2edit', 'ok', 'no'), `date` asc|desc 	0.00013697710952259
17368172	41081	sql get latest records of the month for each name	select name, date, nua, nub, nuc, nud from (select *, row_number() over (partition by name, datepart(year, date),  datepart(month, date) order by date desc) as ranker from table ) z where ranker = 1 	0
17368279	2176	how to best do a sql left join null check where all must be null?	select p.*  from persons p  inner join person_book pb on pb.person_id = p.id left  join book_subject bs on bs.book_id = person_book.book_id group by p.id having count(bs.book_id) = 0 	0.50550893564456
17371514	40157	query to return the difference of dates between records	select pol_nm, sum(days) from  (    select pol_nm, next_date-min(st_date) as days    from     (       select pol_nm, st_cd, st_date,         min(case when st_cd not in (5,6) then st_date end)          over (partition by pol_nm                order by st_date               rows between current row and unbounded following) as next_date       from tab       qualify st_date <> next_date      ) as dt    group by pol_nm, next_date  ) as dt group by pol_nm 	0
17371602	34672	limit each group in group by	select answer, count(*) num_answers from (select answer, yearmonth,              @rn := case when @prevmonth = yearmonth                          then @rn + 1                          else 1                     end rn,              @prevmonth := yearmonth       from (select @rn := null, @prevmonth := null) init,            (select answer,                    year(from_unixtime(timestamp))*100+month(from_unixtime(timestamp)) yearmonth             from tblanswers             where qid = 220             order by timestamp) x) y where rn <= 3 group by answer 	0.00597045573371791
17371994	22648	how to get the unformated timestamp from mysql table?	select unix_timestamp(col1) from   yourtable 	9.05162836964712e-05
17374839	1567	joining poorly designed sql tables?	select     a.journal, a.account, a.debit, a.credit, a.sequence, b.label, b.artist from (     select         *,          row_number() over(partition by journal, account order by sequence) as idingroup     from a ) as a join (     select         *,          row_number() over(partition by journal, account order by sequence) as idingroup     from b ) as b on     a.journal = b.journal     and a.account = b.account     and a.idingroup = b.idingroup 	0.719442735338442
17376150	22702	find number of rows for each hour	select hour(`time`) as hour_of_day, count(*) from track_log  group by hour_of_day 	0
17378470	4808	is there a limit on the number of where conditions in a select statement?	select * from table where column not in('asd', 'bsd', 'csd', ...); 	0.011103249425479
17378726	776	select a record with highest amount by joining two tables	select top 1 * from (select salesid id, rate, quantity, 'sales' transactiontype  from sales  union all  select purchaseid id, rate, quantity, 'purchase' transactiontype  from purchase) order by rate * quantity desc 	0
17381065	18312	sql server dynamic selection of output column	select  fruit, case when fruit = 'apple' then value else null end as quantitative, case when fruit = 'orange' then value else null end as qualitative from mytable 	0.328894313310185
17382324	16705	find lowest value for each row of db - sql	select item, least(supplier1, supplier2, supplier3) from your_table 	0
17382518	7748	sql - include this record if these other records are included	select p.*, o.*  from policy p     join otherpolicyfile o on o.policyid = p.policyid      left join otherpolicyfile o9or10          on o9or10.policyid = p.policyid and o9or10.status in (9,10) where o.status in (9,10)     or o.status = 11 and o9or10.policyid is not null group by <whatever key you need> 	0.00236667423181857
17382699	39875	sql server : take 1 to many record set and make 1 record per id	select c.claim_id, c.ac_name,         cp1.plan_name as plan_name_1, pa1.pending_tally as pending_tally1,        cp2.plan_name as plan_name_2, pa2.pending_tally as pending_tally2,        cp3.plan_name as plan_name_3, pa3.pending_tally as pending_tally3, from company_claims c left join claim_plans cp1 on c.claim_id = cp1.claim_id and cp1.planid = 101 left join claim_plans cp2 on c.claim_id = cp2.claim_id and cp2.planid = 102 left join claim_plans cp3 on c.claim_id = cp3.claim_id and cp3.planid = 103 left join pending_amounts pa1 on cp1.claim_id = pa1.claimid and cp1.planid = pa1.plainid left join pending_amounts pa2 on cp2.claim_id = pa2.claimid and cp2.planid = pa2.plainid left join pending_amounts pa3 on cp3.claim_id = pa3.claimid and cp3.planid = pa3.plainid 	0
17382836	26553	sql - choose column if the sum of other columns is above total	select   name from     yourtable group by name having   sum(price)>500 	0
17384241	5499	sql query required with respect count in a particular format dealing with null and not null values	select role_cat,        count(syn_code) count1,        count(*) - count(syn_code) count2   from table1  group by role_cat 	0.259005538714542
17384646	21288	sql : show data with condition in another table	select distinct th.transactionid,convert(varchar,th.transactiondate,20)[tanggal] from transactionheader th  join transactiondetail td on th.transactionid = td.transactionid  where td.medicineid  in  ( select md.medicineid from msmedicine md join msmedicinetype mmt on mmt.medicinetypeid = md.medicinetypeid where mmt.medicinetypename not like 'syrup' and md.medicineprice > 15000 ) 	0.0017662298330485
17389226	7121	mysql - perform checks on groupings of records	select r.*  from my_result_set r join (select reference_id       from my_result_set       group by reference_id       having sum(case type when 'a' then 1 end) = 1 and              sum(case when type in ('d','e') then 1 end) >= 1) s   on r.reference_id = s.reference_id 	0.0118033634692424
17390427	10633	multiple foreign keys on same column	select a.id, b.full_name, c.full_name, d.full_name, e.pet_name, a.date, a.some_text from results as a  left outer join user as b on a.user_id1 = b.id left outer join user as c on a.user_id2 = c.id left outer join user as d on a.user_id3 = d.id left outer join pet as e on a.pet_id = e.id where a.id = 3 	8.13640937913891e-05
17391922	4701	mysql doesn't separate between e and è	select tablea.value, tableb.value from tablea inner join tableb on tablea.value = binary tableb.value 	0.778207452308957
17393499	24786	find top 10% students in a class using mysql	select floor(100 * 0.1) into @my_limit; prepare stmt from 'select * from alphatable limit ?'; execute stmt using @my_limit; 	0.000528220181667822
17396346	34417	how can i echo variable ordered by something	select * from  (select * from table order by `time` desc) t1 group by `sender` 	0.0574492311838465
17397202	32461	sql server sum union	select sum(xxx) as xxx,sum(yyy) as yyy from (     select '' as xxx,pawn.propawn_price as yyy from product_pawn pawn     inner join product_history history on history.propawn_id = pawn.propawn_id     and history.prohistory_status = '0'     union      select pawn.propawn_price * 8/100 as xxx,'' as yyy from product_pawn pawn     inner join product_history history on history.propawn_id = pawn.propawn_id     and history.prohistory_status = '1'     union     select pawn.propawn_price + pawn.propawn_price * 8/100 as xxx,'' as yyy      from product_pawn pawn     inner join product_history history on history.propawn_id = pawn.propawn_id     and history.prohistory_status = '2'     union     select prosell_pricesell as xxx,'' as yyy from product_sell     where prosell_status = '5') t 	0.512573501232767
17397515	7762	sorting results in mysql	select * from table_name order by votes desc, rating_percent desc 	0.314760497810211
17399835	32170	selecting rows from one table using values gotten from another table mysql	select * from film where id in    (select filmid from film_rating_report where rating = 'ge'); 	0
17400570	5708	counting number of working days and weekends using php/ mysql	select sum(if(weekday(date) >= 5, 1, 0) as weekendcount,        sum(if(weekday(date) < 5, 1, 0) as weekdaycount from jobcards 	0.000602701137262646
17401520	8144	select last record from database on the basis of primary key	select top 1 appointmentdate from   tbappointment where  mid = @mid order  by id desc 	0
17401534	5641	get records from one table to other table in sql server	select * from orders where customer_invoice_id in              (select top 100 customer_invoice_id from customer_invoice) 	0
17401860	3649	date in mysql select	select   a.date,   coalesce(b.price, a.price) from   a left join b on a.date=b.date 	0.0661065409075397
17402182	20880	group by results as individual column names	select sum(case when gender = 'male' then 1 else 0 end) as 'male', sum(case when gender = 'female' then 1 else 0 end) as 'female', sum(case when gender not in ('male','female') or gender is null then 1 else 0 end) as 'none' from staff; 	0.00200967256007214
17402280	6391	how to retun a value depending on two column values in sql server select statement?	select friend from mytable where user = 2 union select user from mytable where friend = 2; 	0
17402656	11533	auto generate id in java	select id from cust where city='nasik' order by to_number(substr(id,2)) desc; 	0.00391489657615804
17402667	5254	mysql php multiquery	select subproductid, c1.colorhex as color1,c1.colorname as colorname1,c2.colorhex as    color2,c2.colorname as colorname2     from subproducts inner join      colors c1 on c1.colorid=subproducts.subproductcolor1 inner join      colors c2 on c2.colorid=subproducts.subproductcolor2 inner join      where productid='$product_id' 	0.364480535469327
17404381	16264	find if systime lies between two times -oracle sql	select to_char(sysdate,'hh24') || ' is in the timeframe'  as result from dual where to_char(sysdate,'hh24') > 21 or to_char(sysdate,'hh24') < 9 	0.00085251670607474
17405000	10092	mysql left join with where and greater than	select * from `product` left join `stock` on `product`.`product_id`=`stock`.`pid` where `stock`.`qty` > 0 order by `product`.`rank` asc 	0.733074001848095
17405736	16350	mysql subtract sum(amount)debitaccount from sum(amount)creditaccount if debitaccount == creditaccount	select     a.accountnumber,     ifnull( d.amount, 0 ) - ifnull( c.amount, 0 ) as amount from 18_7_chartofaccounts as a left join (     select         debitaccount,         sum( amount ) as amount     from 2_1_journal     group by debitaccount ) d on a.accountnumber = d.debitaccount left join (     select         creditaccount,         sum( amount ) as amount     from 2_1_journal     group by creditaccount ) c on a.accountnumber = d.creditaccount 	0.401461381070297
17405890	2477	merging sql data?	select      date,      sum(total1) as total1,      sum(total2) as total2,      sum(total3) as total3 from (      select           date,           total1,           total2,           total3      from          set1      union all      select           date,           total1,           total2,           total3      from          set2 ) subqueryalias group by      date 	0.0393065260927915
17407481	142	check if a time is between two times (time datatype)	select * from mytable where cast(created as time) >= '23:00:00'     or cast(created as time) < '07:00:00' 	0.000128294637789427
17408021	40621	query optimization with rows referring to parents	select id, parentid, createddate from (         select id, parentid, createddate, row_number() over(partition by isnull(parentid, id) order by createddate desc) rownumber         from customercomplaint    ) t  where     t.rownumber = 1 	0.685070035339898
17408436	35805	how to get the stddev() of groups of items without the min() and max() of the group	select bottle, stdev(d.count) from drd.inks d join      (select bottle, min(count) as minc, max(count) as maxc       from drinks       group by bottle      ) dsum      on d.bottle = dsum.bottle and         d.count not in (dsum.minc, dsum.maxc) group by d.bottle 	0
17410071	37297	creating a dynamic date range in sql	select dateadd(month,6,dateadd(yy, datediff(yy,1,getdate())-1,0)) as startdate       ,dateadd(month,6,dateadd(dd,-1,dateadd(yy, datediff(yy,0,getdate()),0))) as enddate 	0.0674892051299468
17411594	22465	gathering counts of multiple tables in a single query	select max(case when sourcetable = 'revenue' then total else 0 end) as revenuecount,        max(case when sourcetable = 'constituent' then total else 0 end) as constituentcount from (     select count(*) as total, 'revenue' as sourcetable     from revenue     union     select count(*), 'constituent'     from constituent ) x 	0.00228215909073297
17414215	34160	sqlite only get element if it contains specific element in row	select from movies where genre = 'comedy' 	0
17414766	13561	last x entries for a set of users	select x.*        from audit_table x       join select user_id, max(trans_id) max_trans_id from audit_table group by user_id) y         on y.user_id = x.user_id         and y.max_trans_id = x.trans_id      where x.user_id in (1,2,3); 	0
17415529	30023	how to organize variable ids that depend on each other in mysql	select * from cards c join cardeditions ed   on ed.cardid = c.cardid join edition e   on e.editionid = ed.editionid where c.cardname = 'some awesome card' and e.editionname = 'ultimate' 	0
17416735	13321	how to get the the sum using variable sql	select sum(cbu) cbu,         format(sum(balance), 2) balance,         sum(ndays) ndays,         format(sum(tbal), 2) tbal   from ( select seq,         @i := @i + 1 i,        weekofyear(fld_date) wn,        fld_date,        next_date,        cbu,        coalesce (@balance := @balance + cbu, 0) balance,        (@ndays := coalesce (datediff(next_date, fld_date),0)) ndays,        @tbal := coalesce (@balance * @ndays, 0) tbal  ) z 	0.00574626939193328
17417109	19331	write sql query to fetch data from below table	select a.column3 + b.column3 from mytable a, mytable b where a.column1 = b.column2 and a.column2 = b.column1; 	0.0084131196059634
17418942	7668	finding the last week report from database	select * from `your_table_name` where date >= curdate() - interval dayofweek(curdate())+6 day and date < curdate() - interval dayofweek(curdate())-1 day 	0
17420858	7529	how to sum up data into one in dates query?	select trunc(rgs_dtm, 'mm'), count(pkg_sno) student_pkg_count, count(shared) shared_count, count(non_shared) non_shared_count from (select pkg_sno,              case when shar_yn = 1 then pkg_sno end shared,              case when shar_yn = 0 then pkg_sno endnon_shared       from lrms.v_lrpm_pkg       where use_yndcd = 1            and mngt_prdn_yn = 'n'            and parn_pkg_sno = 0            and to_char(rgs_dtm, 'yyyy.mm.dd') between #startdt# and #enddt#) group by trunc(rgs_dtm, 'mm') 	0.000377522127998107
17421000	34440	how to get the grouped value	select     datepart(year, a.spdate) as 'year',    month(a.spdate) as 'month',          sum(coalesce(a.value,0)) as 'value' from patient a  join dp account on (a.id = d.id) where   a.id not in (select id from doctor)  group by datepart(year,a.spdate),month(a.spdate) 	0.000173553252017604
17421252	36378	replace spaces that are between a specific pattern with some other character	select      left(url,charindex('>',url))+     replace(substring(url,                       charindex('>',url)+1,                       charindex('</',url)-charindex('>',url)-1),             ' ', '%20') +     right(url,len(url) - charindex('</',url) + 1)   from t1 	0.000375155283496124
17421814	38287	mysql fetching rows based on condition within condition	select t1.* from   yourtable t1 left join yourtable t2   on t1.id = t2.id and t1.flag=0 and t2.flag=1 where   t2.id is null 	0.000566667052848347
17422112	31412	oracle sql merge row values to separate columns	select   id, name, max(a) a, max(b) b from  (   select      project.id, project.name,     case when program.type like 'a' then program.name else null end as a,     case when program.type like 'b' then program.name else null end as b   from      project     left join project_program on project.project_id = project_program.project_id       left join program on project_program.program_id = program.program_id    ) x  group by  id, name 	6.80445616514381e-05
17422223	29937	oracle query to calculate current age	select   case when substr(dob, -2, 2) > 13   then floor         (             months_between             (                 sysdate             ,   to_date(substr(dob, 1, 7) || '19' || substr(dob, -2, 2), 'dd-mon-yyyy')             ) / 12         )   else        floor(months_between(sysdate,to_date(dob,'dd-mon-yy'))/12)   end from birth 	0.00075084824564631
17422320	21831	select unique data from a table with similar id data field	select d.* from order_status_data2 d join (select max(id) mxid from order_status_data2 group by order_id) s    on d.id = s.mxid 	0
17422766	38796	exclude results from mysql query if customer already present in same table albeit fulfilling different criteria	select a.* from cart a left outer join cart b on a.customer_email = b.customer_email and a.order_id != b.order_id where a.order_status = '' and a.date_ordered = '0000-00-00' and a.customer_email is not null and a.date_added > subdate(current_date, 1) and a.date_added < current_date and a.brand is not null and a.customer_email != ' ' and b.customer_email is null group by a.customer order by a.date_added desc; 	0
17422812	22122	how do you identify a foreign key constraint from its name?	select       sa.name as fkname     ,so.name as tablename from     sys.all_objects sa         inner join sys.objects so on sa.parent_object_id = so.[object_id] where     sa.[type] = 'f' 	0
17424333	26151	select max dates plus id value	select * from (     select          *,          row_number() over (partition by userid, testid order by somedate desc) rnum      from @tmp )x where rnum=1 	0.000177882023739508
17424770	5538	get 50 average values out of 1000	select     avg(value) from     table group by     floor(unix_timestamp(savedon) / 72) 	0
17424880	13689	sum over column based on distinct row groups selected for another column	select count(distinct sampname),        (select sum(ss)         from (select distinct sampname,                               sampsize as ss               from test_table as t2               where t2.tc_id = t1.tc_id)        ),        tc_id from test_table as t1 group by tc_id 	0
17425450	3133	merge two select statements from same table?	select       count(*) as expr1,       sum(case when case_status = 'open' then 1 else 0 end) from dbo.cases 	9.16400608517019e-05
17425677	3136	mysql inner join on same table	select t1.*, t2.* from table1 as t1 inner join table1 as t2 on t1.somefield = t2.somefield 	0.0809654627464433
17426316	25170	mysql query join	select  *  from listings l left join bookings b on b.listing_id = l.id and b.checkin between your start date and your_end_date where b.id is null 	0.724110026477687
17427024	30044	selecting random data from a predefined list	select * into myrand from ( select 'q1654' as val union select 'f2597'union select 'y9405'union select 'b6735'union select 'd8732'union select 'c4893'union select 'i9732'union select 'l1060'union select 'h6720') b; create view vmyrand as  select top 1 val from myrand order by newid(); create function getmyrand () returns varchar(5) as begin declare @retvalue varchar(5) select @retvalue = val from vmyrand return(@retvalue) end; 	9.58664684621104e-05
17427869	18602	how do i lock database records from java?	select for update 	0.0721427504545566
17428119	16029	join temp table and actual table with same columns	select * into #temptable from user where user_key= @user_key set @query = '                   alter table #temptable drop column ' + @cols + '                   select distinct p.*, xyz.*                    from                   (                     select                       e.user_key,                       e.field_name,                       e.previous_data as data                       from temp e                 ) x                 pivot                  (                     max(data)                     for field_name_audit in (' + @cols + ')                 ) p                 inner join user xyz on xyz.user_key = p.user_key'          exec sp_executesql @query; 	0.000288641607786903
17429637	9993	need to insert rows into table based on information pulled from table	select customer_id, trans_type, trans_status into a from (       select customer_id           , "sold" as trans_type           , switch (sold = 0, "false", sold > 0, "true") as trans_status         from b       union all       select customer_id           , "purchased" as trans_type           , switch (purc = 0, "false", purc > 0, "true") as trans_status         from b       union all       select customer_id           , "exchanged" as trans_type           , switch (exch = 0, "false", exch > 0, "true") as trans_status         from b       order by customer_id, trans_type  ) 	0
17429907	26463	oracle sql dividing two self defined columns	select completed_callbacks / completed_within_2hours * 100 from   (select count(case                        when status = 'færdig' then 1                      end) as completed_callbacks,                count(case                        when solved_seconds / 60 / 60 <= 2 then 1                      end) as completed_within_2hours         from   yourtable         where  ...) 	0.0921760798873407
17430096	3120	distinct two columns and sum a third column	select id,name,sum(actioncount) from mytable group by id,name 	0.000107942482912873
17430497	22046	search for ascii values in sql server table	select count(id)   from #testcomments   where comments like('%' +  char(13) + char(10) + char(13) + char(10) + '%')      or comments like('%' +  char(10) + char(10) + '%')      or comments like('%' +  char(13) + char(13) + '%') 	0.182738325230294
17430755	4333	selecting data from two different tables without using joins	select table1.name, table1.description,  table2.name, table2.description  from table1 inner join table2 on  table2.id=table1.id and table2.`type`=22 	0.000161518289819184
17430946	8763	how to specify column name to an if exists	select    case      when exists(select 1 from tabs t where t.marker_id = m.marker_id)       then 1     else 0   end multimedia,   ... 	0.0218788218193586
17431533	22289	mysql : all in one query	select snapdate,      count(distinct case when tid =1 then uid end) as t1,     count(distinct case when tid =2 then uid end) as t2,     count(distinct case when tid =3 then uid end) as t3 from table  group by snapdate  order by snapdate desc  limit 7 	0.0118970144904076
17431707	18041	splitting datetime into two columns in t-sql	select      as_key as [key:],      as_name as [server name:],     convert(varchar(10),as_introdate,101) as [date added:],     convert(varchar(8) ,as_introdate,108) as [time added:] from automationstations where datediff(d,as_introdate,getdate()) <= 4 order by as_introdate desc 	0.000525381885749341
17432890	2019	into a single query	select 1  from tab  where (unam='john' and fnam='alex')      or (fnam='john' and unam='alex')  limit 1 	0.0240677697301886
17434678	16951	find overlapping or conflicting time intervals	select    t1.id,   t1.start,   t1.end from table_name t1 join table_name t2 where   t1.start < t2.end and   t2.start < t1.end and   t1.id <> t2.id and   t1.date = t2.date 	0.000767296038583133
17434929	26627	joining two tables with specific columns	select e.empname, e.address, s.name, s.address, s.project from tbemployees e join tbsupervisor s on e.id = supervisorid 	0.000412845400997899
17436612	7902	sql show only rows from both tables when joined pk count is greater than a criteria	select adult.adname, children.chname from adult inner join children on children.adult_id = adult.id where adult.id in (select adult_id  from children group by adult_id having count (children.adult_id) > 2) 	0
17436694	33555	mysql equal string returns 0 rows and like string returns 1 row	select id from up_categorys where trim(category_name) = 'xbox live' limit 0 , 30 	0.00337364271632832
17436722	34858	is it possible to return the results of a select statement with an in clause?	select    case       when 'hi' in ('hi') then 1 else 0   end as hi 	0.458632268405138
17439025	13586	join and display 2 columns from one table refer by another table	select a.username as user_1, b.username as user_2 from table_a t join table_b b on b.id = t.id_b join table_b a on a.id = t.id_a 	0
17440245	32350	mysql distinct group eliminate onlye one result	select client_name, group_concat(distinct(group_name)) merge_group , count(distinct(group_name)) as num_groups from table1 t1 join table2 t2   on t1.group_id = t2.id group by t1.client_name order by t1.id having num_groups>1 	0.0201498016008455
17441907	21846	mssql 2012 - returning multiple columns in a subquery	select a.name, b.score, ... from (select id, name, ... from table1 where ???) a left join (select id, score, ... from table2 where ???) b on (a.id = b.id) where clause 	0.537517011087138
17441964	4599	select multi rows from one query row acording to rows date oracle	select process, from_date + n from (     select process, fromdate, todate from     (        select 'a' as process, to_date('03.04.2013','dd.mm.yyyy') as fromdate, to_date('06.04.2013','dd.mm.yyyy') as todate        union        select 'b' as process, to_date('06.04.2013','dd.mm.yyyy') as fromdate, to_date('10.04.2013','dd.mm.yyyy') as todate     ) s join      (select level -1 as n from dual connect by level < 100) a on (s.from_date+n < s.todate) 	0
17442582	39897	count how many barcodes per day per product	select product, count( barcode_id ) as count, date(  `timestamp` ) as date from barcodes left join barcodes_entered on barcodes.id = barcodes_entered.barcode_id group by date(  `timestamp` ) asc, product 	0
17442904	13875	determine if date range fulls within another date range	select * from table where $variable_start between time_from and time_till or $variable_end between time_from and time_till 	0
17442970	29569	float casting to nvarchar with constraint max size	select     replace(str(myfloatcolumn, 8, 0), ' ', '0') from     mytable; 	0.0588830578026905
17443415	25720	how to calclate users points	select name, sum(points) as total_points from table1 group by name 	0.0320438420864607
17445260	33239	sql query not returning data from where clause	select * from #premodulealldata with(nolock) where (@country   = 'default' or @country   = '' or ([language] = @country )) and   (@usertype  = 'default' or @usertype  = '' or ([usertype] = @usertype )) and   (@group     = 'default' or @group     = '' or ([company] = @group )) and    (@codeusage = 'default' or @codeusage = '' or ([user code]= @codeusage )) 	0.776999729735694
17446536	35011	how to retrieve values from table where joining key is not in joined tables	select * from user_venues inner join users on users.user_id = user_venues.user_id inner join venues on venues.venue_id = user_venues.venue_id left join venue_quotes on venue_quotes.user_venue_id = user_venues.user_venue_id where venue_quotes.user_venue_id is null limit $offset, $limit 	0
17447270	16182	datetime function to get specific dates 12:00am time	select cast(cast('2013/07/03 01:34am' as date) as datetime) 	0.00097958491905312
17449940	21388	group results of grouped query	select daily_user_count, count(*) from ( select count(*) as daily_user_count from activity group by entity_uid, date ) z group by daily_user_count 	0.0318104861547435
17450325	19981	php - plpgsql calling stored procedure and fetching result set	select * from user_read_all(); 	0.69089640041931
17451825	6119	get column information for a user-defined table type	select tt.name, c.name from sys.table_types tt inner join sys.columns c on c.object_id = tt.type_table_object_id order by c.column_id 	0.00262826863581995
17451909	16899	total work hours	select startlog.emp_id, startlog.log_date,  sum(datediff(minute,stm, etm))/60.0 from (     select emp_id, log_date, min(log_time) as stm      from tbllogs     where log_action = '1'     group by emp_id, log_date     ) as startlog inner join      (         select emp_id, log_date, min(log_time) as etm          from tbllogs         where log_action = '4'         group by emp_id, log_date     ) as endlog     on startlog.emp_id = endlog.emp_id and startlog.log_date = endlog.log_date 	0.01149826288745
17451945	32166	how to sum 2 or more fields and insert the result in another table?	select id, name,    iif([day01] > 0, 1, 0) + iif([day02] > 0, 1, 0) + iif([day03] > 0, 1, 0) +   iif([day04] > 0, 1, 0) + iif([day05] > 0, 1, 0) + iif([day06] > 0, 1, 0) +   iif([day07] > 0, 1, 0) as totaldays from workersw_attendance; 	8.02569033471923e-05
17457463	284	c# mysql select users by distance	select latitude, longitude, sqrt( pow(69.1 * (latitude - [startlat]), 2) + pow(69.1 * ([startlng] - longitude) * cos(latitude / 57.3), 2)) as distance from users having distance <= 10 order by distance; 	0.0459083893742279
17457702	27065	tsql for xml path - how can i include a subquery container element even if the subquery is empty?	select     (         select             'john doe'         where 1 = 0         for xml path('patient'), type     ) for xml path('patients'), root('hospital'), type 	0.519969640857431
17462543	34156	concating rows in sql	select no,   listagg(name, ',') within group (order by name) as name from tablename group by no 	0.084620913851101
17464584	16465	one way relationships	select  greatest(name,friend),least(name,friend) from friends group by greatest(name,friend),least(name,friend) having count(1)=1 	0.0539240715313189
17467299	39703	mysql left join add condition on other table	select principaltable.x, secondtable.art, secondtable.dett  form principaltable pt,secondtable st,thirdtable tt where pt.x = tt.x and pt.art = st.art and st.id = tt.id 	0.0413002977110543
17468438	13811	sql query - join two tables bringing back only lowest price from table 2	select boat_data.*,        t.min_price from boat_data   join (      select pricingref, min(price) as min_price      from boat_prices      group by pricingref   ) t on t.pricingref = boat_data.pricingref; 	0
17468853	2120	oracle - treat join on null as true	select columns  from table t  left join other_table ot on o.col1 = nvl(ot.col1, o.col1)     and o.col2 = nvl(ot.col2, o.col2)     and o.col3 = nvl(ot.col3, o.col3)     and o.col4 = nvl(ot.col4, o.col4) 	0.540289794010589
17468988	25881	sql to select rows distributed over time	select * from ints; + | i | + | 0 | | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | + now let's say i wanted to return approximately 5 evenly distributed results from across this table... select x.i   from ints x    join ints y      on y.i <= x.i   group      by i  having mod(count(y.i),round((select count(*)/5 from ints),0)) = 0;  + | i | + | 1 | | 3 | | 5 | | 7 | | 9 | + 	0.0100637018607965
17470712	22259	row average in mysql - how to exclude null rows from the count	select avg(var1) as var1, avg(var2) as var2, avg(var3) as var3, (  sum(ifnull(var1,0))+  sum(ifnull(var2,0))+  sum(ifnull(var3,0)) ) / (count(var1)+count(var2)+count(var3))  as metric_total from test 	0
17471488	9460	mysql union statement	select a.id, a.branch_code, sum(c.amount) as totamount,        sum(case when c.transac_type = 0 then c.amount end) as trans0_amount,        sum(case when c.transac_type = 1 then c.amount end) as trans1_amount,        d.category, e.branch_commission  from control_panel_client_create as a right join sales_add_h as b on a.id = b.branch_code_id  right join sales_add_i as c on b.id = c.sales_h_id  right join control_panel_item_create as d on c.item_code_id = d.id inner join control_panel_client_create as e on b.branch_code_id = e.id where c.transac_type in (0, 1) group by d.category, b.branch_code_id order by sum(c.amount) desc 	0.746807491535565
17474270	4315	changing format of csv from mysql db using php	select fldfirstname as 'first name', fldsurname as 'surname',    fldgmcnumber as 'gcnumber', flddestdept as 'dept',    fldstartdate as 'start date', fldenddate as 'end date',    'introduction' as 'module', fldmodule1 as 'status' from records union select fldfirstname,fldsurname,fldgmcnumber,flddestdept,fldstartdate,fldenddate,   'theory',fldmodule2 from records union select fldfirstname,fldsurname,fldgmcnumber,flddestdept,fldstartdate,fldenddate,   'fire safety',fldmodule3 from records union select fldfirstname,fldsurname,fldgmcnumber,flddestdept,fldstartdate,fldenddate,   'governance',fldmodule4 from records order by surname, `first name`, module; 	0.00417105469346371
17476596	23362	query to retrieve top row without using top except plain sql	select * from contests where contestid = (select max(contestid) from contests) 	0.000188258833012269
17477724	32534	return employee's who were hired in first half of the month	select    * from   employee e where   to_number(to_char(e.datehired, 'dd')) <= 15 	0
17478000	27215	multiple table counts in one query	select    ( select count(*) from table1 ) as table1,    ( select count(*) from table2 ) as table2,    ( select count(*) from table3 ) as table3,    etc... ) 	0.00756733117460592
17478172	30898	join tables with parent id	select     deletionlog.primaryid,     deletionlog.type,     thread.forumid,     deletionlog.dateline from     deletionlog inner join     thread on     deletionlog.primaryid=thread.threadid where     deletionlog.type='thread' group by     deletionlog.type having     max(deletionlog.dateline) union select     deletionlog.primaryid,     deletionlog.type,     thread.forumid,     deletionlog.dateline from     deletionlog inner join     post on     deletionlog.primaryid=post.postid inner join     thread on     post.threadid=thread.threadid where     deletionlog.type='post' group by     deletionlog.type having     max(deletionlog.dateline) 	0.0123508123350795
17478209	30945	mysql - how to average returned votes from inner joined table results	select avg(rating.rate) as avg_rating, names.name    from rating    join names      on rating.id = names.id group by names.name order by avg_rating desc limit 0, 25 	0.000137482676125368
17478928	15041	mysql displaying results from a many-to-many relationship	select title,group_concat(mood_name separator ' ') as moods from films  join films_moods on films.id=films_moods.film_id join moods on films_moods.mood_id=moods.id group by title 	0.0180602272506733
17481969	4753	move value from line to another line?	select a.month_str,a.money,ifnull(b.moneystock,0) moneystock,         a.money+ifnull(b.moneystock,0) total from (select siire_code code,month_str, sum(money) money         from yourtable         where siire_code = 384         group by siire_code,month_str)a  left outer join          (select zaiko_code code, month_str, sum(money) moneystock         from yourtable         where siire_code =560          and zaiko_code =384         group by zaiko_code, month_str) b on (a.code = b.code and a.month_str = b.month_str) 	7.30946632241715e-05
17482948	28006	filter table that i do a left join with	select *  from a left join  (    select b.*    from b      inner join c on b.c_id = c.id and c.id > 10  ) as b on b.a_id = a.id 	0.391413176742887
17483151	8487	sql syntax to retrieve votes strangely misses some results	select id_activity,activity_name,id_post,v_count from( select id_activity,activity_name,id_post,v_count  ,@rownum := if(@prev_value=id_activity,@rownum+1,1) as rownumber ,@prev_value := id_activity   from ( select a.id_activity,a.activity_name,p.id_post,v.v_count from activities a left join posts p on p.activity=a.id_activity left join (   select id_post,count(*) v_count from votes v1   group by id_post ) v on v.id_post=p.id_post order by a.id_activity, v.v_count desc) as tmp ,(select @rownum := 0) r ,(select @prev_value := '') y )tmp2 where rownumber=1 	0.54458123394466
17483163	4481	joining two queries using join in mysql	select     pv.name,pv.domain_id,pv.counter as page_visits, v.ip, v.counter as visits from (     select  `domains`.`name` ,  `pageviews`.`domain_id` , count(  `pageviews`.`domain_id` ) as counter     from  `pageviews`      left join  `domains` on (  `domains`.`id` =  `pageviews`.`domain_id`      and  `domains`.`user_id` =  '129' )      where  `pageviews`.`user_id` =  '129'     group by  `pageviews`.`domain_id`      order by count(  `pageviews`.`domain_id` ) desc  ) as pv left join (     select  `domains`.`name` ,  `visitors`.`ip` ,  `visitors`.`domain_id` , count(  `visitors`.`domain_id` ) as counter     from  `visitors`      left join  `domains` on (  `domains`.`id` =  `visitors`.`domain_id`      and  `domains`.`user_id` =  '129' )      where  `visitors`.`user_id` =  '129'     group by  `visitors`.`domain_id`      order by count(  `visitors`.`domain_id` ) desc ) as v     on pv.domain_id = v.domain_id 	0.207655970316509
17485599	29966	sql: take only the latest entry for each "group"?	select t1.`index`, t1.`index2`, t1.`somenumber` from test t1 inner join (select `index`, `index2`, max(`date`) date from test group by `index`, `index2`) t2 on t1.index = t2.index and t1.index2 = t2.index2 and t1.date = t2.date 	0
17486671	31222	select sum of items based on their monthly entry date	select entrydate, items from (select year(entrydate)'year_',month(entrydate)'month_',cast(entrydate as varchar(12))'entrydate',items,1 'sort'       from inventory       union all       select year(entrydate)'year_',month(entrydate)'month_','total',sum(items)'items',2 'sort'       from inventory       group by year(entrydate),month(entrydate)       )sub order by year_,month_,sort 	0
17486791	24852	mysql select rows which not having specific value in other table	select a.* from users a left outer join permissions b on a.id = b.user_id and b.area_id = 5 where b.id is null 	0
17487217	2	retrieving last comment from joining 3 tables	select comment, jobid from (select max(date) as maxdate, jobid from comments group by jobid) x inner join comments c on c.jobid = x.jobid and c.date = x.maxdate 	0
17487235	3257	mysql group_concat comma separated ids to match names	select group_concat(distinct(c.name)) as s,        v.name as v   from link_products_lists_vendors l   join categories c on l.category_id = c.id   join vendors v on l.vendor_id = v.id  group by v.name; 	0
17487809	30645	sort table by reputation and select rank + limit to print above and below rows	select sub1.rank, sub1.user_email, sub1.reputation  from  (     select @rank2:=@rank2+1 as rank, user_email, reputation      from accounts, (select @rank2 := 0) r      order by reputation desc      limit 0,7 ) sub1  inner join (     select rank, user_email, reputation      from      (         select @rank:=@rank+1 as rank, user_email, reputation          from accounts, (select @rank := 0) r          order by reputation desc          limit 0,7     ) t      where reputation = '5' ) sub2 on sub1.rank between (sub2.rank - 2) and (sub2.rank + 2) 	0.000545904441432731
17489388	39533	pdo query on joined tables when column names are the same	select table1.id as t1id, table2.id as t2id 	6.23589385793429e-05
17489469	7203	find the last time table was updated	select name, [modify_date] from sys.tables 	0
17491427	38917	count number of occurrences by name	select name,        sum(case when play = 'homerun' then 1 else 0 end) as homerun,        sum(case when play = 'hit' then 1 else 0 end) as hit,        sum(case when play = 'bunt' then 1 else 0 end) as bunt,        count(*) as total from baseball bb group by name; 	0.000141347824837828
17491640	18270	postgresql function - how to return dataset of rows	select col1, col2, col3 from getallwidgets(); 	0.0056748372859818
17491749	21642	querying for top contributor using mysql	select userid, count(*) as changes from yourtable group by userid order by changes desc limit 5; 	0.190382752739726
17494317	34485	tsql first of last month - date only	select convert(char(10), dateadd(month, datediff(month, 0, getdate())-1, 0), 111) select convert(char(10), dateadd(month, datediff(month, 0, getdate())-1, 0), 120) 	0
17494635	14060	count rows with same colum value for certain date	select    renterid  , count(distinct bookid) from    your_table where      dateofrental = 'the_date' group by    renterid ; 	0
17495184	38147	table join returns every row from entire table	select gbg.manual_grade,                 gbm.title,                 u.user_id,                 gbl.grade from gradebook_grade as gbg     join course_users as cu on gbg.course_users_pk1 = cu.pk1 join users as u on cu.users_pk1 = u.pk1 join gradebook_main as gbm on gbg.gradebook_main_pk1 = gbm.pk1 join course_main as cm on gbm.crsmain_pk1 = cm.pk1 join gradebook_log as gbl        on gbm.pk1 = gbl.gradebook_main_pk1          and u.pk1 = gbl.users_pk1   where (cm.course_id) = 'huma-1301-057in-s12013' and (u.user_id) = 'bpugh' 	0
17495421	34444	auto increment value on sql select when duplicate	select     firstname + '.' + lastname         + isnull(cast(nullif(row_number() over(partition by firstname + '.'  + lastname order by id) - 1, 0) as varchar(10)), '') from     tablename 	0.000178371933542816
17495739	8538	mysql query to get row where column ellipse number >= 1	select content from mytable where posts >= (1 + "yournumber") limit 10; 	0.000252865812514826
17497962	23088	include like clause value in result list	select addr.*, case when addr.line like '%one%'  then 'one'   when addr.line like '%two%'  then 'two'   when addr.line like '%three%'  then 'three'   when addr.line like '%four%'  then 'four'    else 'unknown'    end as address_type   from address addr where  addr.line like '%one%'  or addr.line like '%two%' or addr.line like '%three%' or addr.line like '%four%'; 	0.145289948118526
17498886	30347	php/mysql - join/union the results of two tables	select c.*, coalesce(x.cnt, 0)  from companies c     left join     (         select company, count(*) as cnt         from reviews         group by company     ) x on x.company = c.company_id  where c.company like '%...%' 	0.00262424745813965
17499713	30689	sql: reduce query results to single item	select charstat_game from `character_main` where charstat_last_activated = ( select  min( charstat_last_activated )  from `character_main`  where charstat_player =11 and charstat_active =1 and charstat_game >0 ) and charstat_player =11 and charstat_active =1 and charstat_game >0 	0.0347025198063694
17500904	38115	if records exist with similar unique key then show there sum else show record value	select   invoicenumber, amount = sum(amount) from   invoice group by   invoicenumber 	0
17500963	22941	how to compare the below specified table and assign the status?	select distinct   user_id,    user_id in      (select user_id from orders where order_status='completed') "good standing" from orders; 	0
17501840	8955	how can i find out what foreign key constraint references a table in sql server?	select     object_name(f.parent_object_id) tablename,    col_name(fc.parent_object_id,fc.parent_column_id) colname from     sys.foreign_keys as f inner join     sys.foreign_key_columns as fc        on f.object_id = fc.constraint_object_id inner join     sys.tables t        on t.object_id = fc.referenced_object_id where     object_name (f.referenced_object_id) = 'yourtablename' 	0.000216781135841108
17502174	12266	select age from mysql and display it in chart control	select age , count(age) from (   select date_format(from_days(to_days(now())-to_days(str_to_date(birthday, '%d/%m/%y'))), '%y')+0 as age from users ) t group by age 	0.00260685591017394
17503080	18183	comparing with two maximum of columns get one row	select id from   books order  by year desc, month desc limit  1 	0
17503656	36257	select top error	select * from produse order by id_produs desc limit 2 	0.54456994553187
17508701	14897	mysql row variable out of order	select if(@prev != date, @rownum := 1, @rownum := @rownum + 1) as row,         @prev := date, salary   from  (select d.date,e.salary            from employee e, time d           where e.age >= 18              and e.age <= 25              and e.tid = d.id              and d.date >= '2002-01-01'              and d.date <= '2003-01-01'        order by date, salary) a, (select @rownum := 0, @prev := null) r; 	0.0177900786852948
17508743	17089	select data from table without multiple of the same user id	select distinct user_id from table where x_id = 1; 	0
17512745	33670	create a mysql view with merged rows	select g2.id_rel, g1.id_art, g1.id_fam, g1.id_cat, g1.id_scat,        g2.id_marca, g2.id_model, g2.id_year from mytable g1 join mytable g2 on g1.id_art = g2.id_art and g2.id_fam is null where g1.id_marca is null 	0.0183009023800933
17513203	40047	sort and join two tables by date	select *  from comments c join posts p on c.post_id = p.post_id  order by p.posts_date,c.comments_date asc 	0.0053095640298084
17513619	9059	using regexp,sum and having clause in more than one condition	select user_id,          sum(if(job like '%j1%',years,0)) yearsjob,          sum(if(skill like '%s1%', years,0)) yearsskill     from yourtable group by user_id   having yearsjob>2      and yearsskill>3; 	0.635490570910756
17513983	16186	mysql: find rows, where timestamp difference is less than x	select t1.user, t1.date d1,t2.date d2 ,t1.date-t2.date   from  (select @val:=@val+1 rowid,user,  date            from mytable,(select @val:=0) a        order by user,date) t1,         (select @val1:=@val1+1 rowid,user,  date            from mytable,(select @val1:=1) b        order by user,date) t2  where t1.rowid = t2.rowid    and t1.user = t2.user    and t1.date-t2.date < 1300; 	0
17514035	11042	is it possible to combine mysql queries to multiple tables into a single query based on the results from one of the queries?	select distinct s.ownerid, s.message  from statusupdates s  left join friends f on ($userid = f.requestfrom)  left join friends f on ($userid = f.requestto) order by s.createddate; 	0
17517996	21964	mysql query find substring	select *   from country   where 'russian federation' like concat('%', name, '%') 	0.171998405313772
17519785	27757	how to match datetime column by passing date only in sql server	select *  from datetimetable  where convert(char(10), datetimecolumn, 103) = '25/12/2013' 	0.00127980487553111
17520953	34855	populate dates for each outlet	select a.date , b.name from dates as a , outlets as b 	0.000713727780139484
17521383	5472	how to fill a varchar with a number of occurences of a pattern	select id,     concat(amounts, repeat('|', 5 - groupcount)) as amounts,     concat(issuedates, repeat('|', 5 - groupcount)) as issuedates,     concat(bonusamounts, repeat('|', 5 - groupcount)) as bonusamounts from (     select         p.id,           group_concat(t1.amount separator "|") as amounts,           group_concat(t1.issuedate separator "|") as issuedates,            group_concat(t2.amountineuro*100/t1.amountineuro separator "|") as bonusamounts,         count(*) as groupcount      from transaction t1      join player p      on p.id = t1.player_id      inner join (select player_id, count(*) from transaction where issuedate between '2010-07-03 00:00:00' and '2013-07-03 23:59:59' group by player_id) tr     on tr.player_id = t1.player_id     left outer join transaction t2     on t2.id = t1.deposit_id and type = 3     where t1.type = 0      and t1.status = 0      group by t1.player_id      having groupcount <= 5 ) sub1 	0
17521462	29375	mysql group_concat filtering	select client_name, group_concat(distinct(group_name)) merge_group , count(distinct(group_name)) as num_groups from table1 t1 join table2 t2  on t1.group_id = t2.id group by t1.client_name having num_groups > 1 and merge_group like '%group1%' 	0.665512371428713
17521581	10317	numbering duplicates record in mysql	select  id, name, age, (  case name  when @curtype  then @currow := @currow + 1  else @currow := 1 and @curtype := name end ) + 1 as sequence_no from student, (select @currow := 0, @curtype := '') r order by  id,name; 	0.0105814227531079
17521735	21283	retrieving float value from table	select * from url_key_weight where round(bid, 2) = 2.95 	0.000199021754663749
17523279	12570	mssql group by and "image" field type	select link,pictures._fld8035 as 'picture'      from     (     select         max(sprnomenklatura._idrref) as 'link'         from _reference62 sprnomenklatura         group by sprnomenklatura._idrref     ) as a     left join _inforg8032 pictures         on pictures._fld8033rref = a.link 	0.0630491114450893
17524235	28217	delete large number of rows	select col1, col2, ... into #someholdingtable             from mytable where ..condition..  truncate table mytable  insert mytable (col1, col2, ...)            select col1, col2, ... from #someholdingtable 	0.000862062615888366
17524669	32684	group by null and not null values	select sum(case when facebookid is null then 1 else 0 end) as nbusers , 'no' as facebook from usertable union all  select sum(case when facebookid is null then 0 else 1 end) as nbusers , 'yes' as facebook from usertable 	0.213827574593051
17524677	10159	mysql query not returning specific rows with max(id) data	select max(id) from yourtable where result = 'pass' group by `group`; 	0.0786459270677507
17524780	33957	union all command in sql	select  a.vpnid||'|'||a.publicnumber||'|'||a.privatenumber||'|'||'null' from  virtualterminal a  union all select  b.vpnid||'|'||b.publicnumber||'|'||b.privatenumber||'|'||b.profileid  from terminal b; 	0.243452822139168
17525546	18962	mysql union with calculated row	select ifnull(table_name,'total'), sum(row_count)        from (select 'table_1' table_name, count(*) row_count             from table_1             union              select 'table_2' table_name, count(*) row_count             from table_2             union              select 'table_n' table_name, count(*) row_count             from table_n ) temp    group by table_name with rollup; 	0.0786008673136265
17525649	20273	how to get details of row with an aggregate function without subquery?	select id, low, op, yc, tc, volume, atimestamp from (   select      id,      low,      op,     yc,     tc,     volume,      atimestamp,     rank() over (partition by id order by atimestamp desc) as rank from somedata ) a where a.rnk = 1 	0.0724395673675819
17526150	32679	select distinct value when count = 1 in sql	select fid_a from tbl group by fid_a  having max(fid_b)=1 and min(fid_b)=1 	0.0131075048704185
17527074	31965	accumulating in sql	select     id,     value,     accvalue = sum(value) over (order by id                                  rows between unbounded preceding                                           and current row) from      @temptable ; 	0.681542312146626
17527180	6863	joining tables to get the number of occurences with another column	select      `sub`.`phone` as `phone`,     count(`sushi_service`.`sushi_service_id`) as occurences         from      `subscriptions` as `sub` left join `service_sushi_service` `sushi_service` on `sushi_service`.`sushi_service_id` = `sub`.`sushi_service_id` where      date(`sub`.`added`) >= '2013-01-01' group by `sub`.`phone` having occurences > 2 	0
17530574	16262	add a zero to the returned value if there is no zero	select case left(mobileno,1)      when '0' then mobileno     else '0' + isnull(mobileno,'')     end as mobileno from person 	0.000495910318678576
17531100	2745	oracle sql get last sunday and last saturday	select trunc(sysdate) as todays_date,        trunc(sysdate)-8 as previous_sunday,        trunc(sysdate) - (interval '1' day + interval '1' second) as previous_saturday   from dual 	0
17533139	21480	get max minutes from query in sql server	select max(datediff(minute,issued,getdate()))as maxwaittime from tbldata  where  (dateadd(day, datediff(day, 0, issued), 0) = dateadd(day, datediff(day, 0, getdate()), 0)) 	0.00163139445257194
17533568	10744	mysql select data from multiple tables	select t.* , t2.* , t3.* from images t    join boxes_items t2  on t.item_id = t2.item_parent_id    join boxes  t3 on t3.box_id = t2.box_id   where t2.item_id = '$image_id' 	0.00352621894107373
17533989	2151	select statement with result even if there isn't in the db	select      comm.no_com,      case when attachement.entityid is null or attachement.ats_categoryofattachmentcode='dessin'         then attachement.filename         else ' '     end as dessin from comm left outer join attachement on comm.coh_id=attachement.entityid and attachment.kind = 'desiredkind' 	0.358929590536232
17535242	19507	sql join with multiple rows of a single table	select      issues.id,      issues.column1,      issues.column2,      text.value column3,     text2.value column4 from      issues left outer join text on text.id = issues.id and text.field = 'a'     left outer join text as text2 on text2.id = issues.id and text2.field = 'b' 	0.00165807619182832
17535579	17779	select pairs in mysql	select t.*    from table1 t join (   select guid     from table1    group by guid   having count(*) = 2 ) q on t.guid = q.guid 	0.0337964343887022
17536889	41141	writing a query for figuring out non-existent parent ids in sql	select column1 as table2id, id as table1id from table1 union all select column2, id from table1 union all select column3, id from table1 	0.00952574053762335
17538330	11403	having pairs of friends in table, how to make a view that would abstract getting list of user's friends?	select subject, friend from (select      `user_id1` as subject,     `user_id2` as friend,     from `friends`      use index (`index_on_user1`) union select     `user_id2` as subject,     `user_id1` as friend,     from `friends`      use index (`index_on_user2`) ) where friend = <some number> 	0
17539207	6627	compare two columns in sql?	select ssn from table1 where        ssn not in (select cssn from table2) 	0.00161054033563679
17539304	27346	mysql query with two tables php	select columns    from table1, table2    where table1.field = table2.field 	0.0911052801291381
17540066	8550	how can i join the count in mysql?	select p.custid from purchase p inner join car c on p.carid=c.carid where c.maker like '%honda%' group by custid having count(p.carid)=     (select count(*) from car c where c.maker like '%honda%') 	0.198037763869353
17540891	28707	retrieve another field whose row is selected by an aggregate function	select first_field,second_field,third_field from ( select a.*,        row_number()           over (partition by a.first_field                  order by second_field)          as rn from a ) b where b.rn=1; 	0.000109435107768534
17542111	35276	how to select a record from one table and count the number of which appears another table and count it	select    teacher_id   teacher_name   nvl(num1, 0) + nvl(num2, 0) + nvl(num3,0) as num_selected_by_stu from    teacher t   left outer join ( select count(*) as num1, tearcher1_id from student group by tearcher1_id ) t1 on t1.tearcher1_id = t.tearcher_id   left outer join ( select count(*) as num2, tearcher2_id from student group by tearcher2_id ) t2 on t2.tearcher2_id = t.tearcher_id   left outer join ( select count(*) as num3, tearcher3_id from student group by tearcher3_id ) t3 on t3.tearcher3_id = t.tearcher_id ; 	0
17543642	36600	how to get current identity number of specific table in sql server compact	select autoinc_seed  from information_schema.columns  where table_name='tablename'  and column_name='columnname' 	0
17543771	40650	sql query with specific order by format	select * from temp order by  case operationcode       when 'repl' then 1      when 'r&i' then 2      when 'ovrh' then 3      when 'refn' then 4 end, operationorder 	0.212059381697172
17544566	5993	sql and number combination search	select * from temp where 'n1' in (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10)   and 'n2' in (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10)   and 'n3' in (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10)   and 'n4' in (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10) 	0.0346104051136483
17544922	18412	sum of a secondselect statement - php - mysql	select                     p.pid,     p.name,        group_concat( gc.leaguepoints order by leaguepoints desc ) as leaguepoints,      sum(gc.leaguepoints) as totalleaguepoints from golf_player p left join  (     select pid, leaguepoints, @sequence:=if(@prevpid = pid, @sequence + 1, 0) as asequence, @prevpid := pid     from     (         select pid, leaguepoints         from golf_card          order by pid, leaguepoints desc     ) sub1     cross join (select @prevpid := 0, @sequence := 0) sub2 ) gc on p.pid = gc.pid and asequence < 20 group by p.pid order by p.name desc 	0.249104550638009
17545799	11945	firebird - self join on one table	select a1.id_ppstartstoppoz as action_0,        a2.action_1,        datediff (minute, a1.data ,a2.data) from startstop a1 join  (   select id_ppstartstoppoz as action_1,          data,          (select max(id_ppstartstoppoz)            from startstop            where id_ppstartstoppoz<t.id_ppstartstoppoz                 and                 action=0) as prev_action   from startstop t   where action=1  ) a2 on a1.id_ppstartstoppoz=a2.prev_action where action = 0 order by a1.id_ppstartstoppoz 	0.149927610268532
17547106	4058	mysqli select instead of if	select a.`productid`, a.`productname`, b.`subproductid`, b.`subproductname` from `products` as a, `subproducts` as b where  b.`productid`=a.`productid` group by  a.`productid` 	0.081375077843539
17547539	32758	create a view and concatenate more than one field to single field name	select a.asset_name as asset_name        concat(a.fname, ' ', a.mname, ' ', a.lname) as incharge from asset a, members m where a.member = m.id 	0
17547604	37367	how to ignore the "the" in a product title asp.net/sql	select title from dbo.product where title like 'r%' or title like 'the r%' 	0.00370911276330848
17548743	26126	select row values where max() is column value in group by query	select table1.a , table2.b , table1.c from  (     select max(a) as a,c      from mytable      group by c ) as table1  inner join ( select * from mytable ) as table2 on table1.a = table2.a 	0.000520805312378532
17548964	347	sqlite: get all dates between dates	select date_entry  from vacation  join all_dates on date_entry between from_date and to_date group by date_entry order by date_entry 	0
17549237	10321	join - left join with a filter on both tables, return zero if no match	select        a.[batch no_],                b.[lot no_],                b.[open],                a.[current stock],                isnull(b.amount,0)                a.[batch value] from            [sb] as a left outer join                 [ile] as b on a.[batch no_] = b.[lot no_]                 and 1 = b.[open] where        (a.[current stock] = 1) 	0.0379812692607579
17549472	27363	mysql regex() alternation match order?	select * from people where name regexp(bob|robert) order by name desc 	0.757392937998782
17550105	22608	how to replace returned column value in sql select query?	select ib.incident_id,    ib.incident_status_id,    st.name from cs_incidents_all_b ib inner join cs_incident_statuses_tl st on st.incident_status_id=ib.incident_status_id where st.name in          ('accept order',           'order accepted',           'address retrieved',           'analyze',           'entered',           'information retrieved',           'retrieve address',           'retrieve information',           'returned')); 	0.0127028871478893
17550401	30181	selecting only one copy of a row with a specific key that is coming from multiple tables	select [nonscrumstory].[incidentnumber],         [nonscrumstory].[description],         max( [dailytaskhours].[activitydate]),         max( [application].[appname]),         max([supportcatagory].[catagory]),         max([dailytaskhours].[pk_dailytaskhours]),         [nonscrumstory].[pk_nonscrumstory]  from [nonscrumstory],       [dailytaskhours],       [application],       [supportcatagory]  where ([nonscrumstory].[userid] = 26)  and ([nonscrumstory].[pk_nonscrumstory] = [dailytaskhours].[nonscrumstoryid])  and ([nonscrumstory].[catagoryid] = [supportcatagory].[pk_supportcatagory])  and ([nonscrumstory].[applicationid] = [application].[pk_application])  and ([nonscrumstory].[deleted] != 1)  and [dailytaskhours].[activitydate] >= '1/1/1990' group by [nonscrumstory].[incidentnumber], [nonscrumstory].[description],[nonscrumstory].[pk_nonscrumstory]    order by 3 desc 	0
17550496	40519	multiple 'in' clauses	select b.* from serie b inner join l a on (a.serie_id = b.serie_id) inner join clusterserie c on (c.serie_id = b.serie_id)  where c.cluster_id like 'rf%' and a.l_value = 33 and a.i_value >= 0 	0.293697741134984
17550675	33461	how to sum cells in a column if a condition is met in another column in sql	select year(order_date) as order_year,        month(order_date) as order_month,        sum(sales_price) as tot_price,        group_concat(cust_name) as customers_in_month from mytable group by order_year, order_month 	7.35388738791625e-05
17550821	37813	access limit value as column in mysql	select *, @rank := @rank + 1 from your_table, (select @rank := 100) r limit 100, 5 	0.060433536008284
17551326	21829	conditional sql join based on column contents	select es.event_session_id,       coalesce(spk.first_name, usr.first_name)        + ' ' + coalesce(spk.last_name, usr.last_name) as submitted_by_name,       coalesce(spk.email, usr.email) as submitter_email  from event_session es      left outer join speakers spk       on es.session_submitter_type = 'speaker' and spk.speaker_id = es.session_submitted_by                             left outer join users usr       on es.session_submitter_type <> 'speaker' and usr.user_id = es.session_submitted_by 	0.00821431475524662
17551760	35960	how to sum total between two given dates in sql server 2008	select datepart(month, invoicedate), datepart(year, invoicedate), count(1)  from table1 where invoicedate between '1/1/2012' and '7/31/2013' group by datepart(month, invoicedate), datepart(year, invoicedate) 	0
17551908	21935	how to take count of records using mysql	select company_code ,  sum(case when product_code = 10 then 1 else 0 end) as product_10 ,  sum(case when product_code = 20 then 1 else 0 end) as product_20 from product group by company_code 	0.000770938058148538
17552278	23957	sql get data from multiple tables	select a.date, a.title, 'article' category from articles a where date > :date union all select date, title, 'column' category from columns where date > :date union all select date, title, 'report' category from reports where date > :date 	0.000760922534155278
17553559	37586	mysql intersect query on one table	select t1.table_id from table t1 inner join table t2 on t1.table_id = t2.table_id     where t1.table_eventnum = 3 and t2.table_eventnum = 2     and not t1.table_finishdate is null 	0.0616399041492648
17553986	7986	use select to have two records (rows) in result 'table' in mysql	select 'nathan' as name union all select 'josh' as name union all select 'hao' as name 	5.75989715449682e-05
17556497	3395	get posts that i have commented on with new comments?	select distinct p.* from posts p inner join comments c on c.post_id = p.id where c.comment_timestamp > (    select max(c2.comment_timestamp)    from comments c2    where c2.post_id = c.post_id    and c2.user_id = $current_user_id ) 	0
17556774	30660	how to put logic in 2 different mysql table?	select * from user where  id  not in (  select b.userto  from user as a inner join follow as b on a.id = b.userfrom  where username = 'rko'  union all   select id  from user as a  where username = 'rko'   ) 	0.00274540501217391
17559461	21069	sqlite find total row count for database	select count(*) from tablename 	8.71154235818528e-05
17560004	22432	look through multiple tables with a date field and get all that are past a certain date	select count(*) from ( select date dd from t1 union all select date from t2 )dt where dd>2013/8/1 	0
17560541	1495	select from mysql where it does not equal row in other table	select * from `faq` where `section` not in (select `sectionname` from `sections`) 	0.00367592836538004
17560757	7396	sql design for notification of new registered users	select *  from notification inner join user on (     user.date >= notification.date and     (notification.gender is null or notification.gender = user.gender) and     (notification.haircolor is null or notification.haircolor = user.haircolor) and     (notification.eyecolor is null notification.eyecolor = user.eyecolor) and     (notification.company is null or notification.company = user.company) ) 	0.00842968435722798
17560849	24816	sql to group and aggregate based on different record-types	select adatetime, agroupname,        sum(case when arecordtype = 'a' then avalue else 0 end) as calcval1,        (sum(case when arecordtype in ('b', 'c') then avalue else 0 end) -         sum(case when arecordtype in ('d', 'e') then avalue else 0 end)        ) as calcval2 from t group by adatetime, agroupname 	0.0065511566946482
17563688	15053	concatenating mutiple rows in postgresql into single rows	select  array_to_string(array_agg("column"),',') as yourcolumn from table1 	7.77277025022238e-05
17564559	34674	mysql - count where id contained in a string	select count(*) from `table` where find_in_set(89,`content`); 	0.0172909215485196
17566435	32792	search by first three letters from multiple tables	select movie_name as name from movie_table where movie_name like 'g%' union all select serial_name as name from tv_serial where serial_name like 'g%' 	0.000139581747743789
17566601	25985	get the follow posts based on date	select * from follow join posts on (follow.friends = posts.uid or follow.uid = posts.uid) where follow.uid = {user_uid} 	0
17567157	38025	select distinct column sql	select produtos.designacao, produtos.marca,produtos.categoria, lojas.superficie, lojas.localizacao, produtos_lojas.preco  from produtos_lojas  inner join lojas on lojas.id = produtos_lojas.id_loja  inner join produtos on produtos.id = produtos_lojas.id_produto  where produtos_lojas.preco= (   select min(pl.preco)    from produtos_lojas pl   inner join lojas l on l.id = pl.id_loja    inner join produtos p on p.id = pl.id_produto    where produtos.designacao = p.designacao ) 	0.0455063886474373
17568770	25458	sql - selecting all latest unique records	select * from table1 where my_id in (    select max(my_id) from table1 where phase='close' group by your_id) 	0
17569738	6271	how to extract sequence ddl in oracle db	select dbms_metadata.get_ddl('sequence', 'seq_name') from dual; 	0.0194524800116799
17569871	4472	rename for column names in inner join	select c.*,         i1.name as name_1,         i2.name as name_2   from c    inner join i as i1       on c.item_1 = i1.id    inner join i as i2       on c.item_2 = i2.id 	0.0263506664870008
17570795	23020	select statement combining multiple rows	select max(accessid) as accessid,  max(accesstype) as accesstype from audit_log  where status in (335,66) group by eventtime 	0.0301012533820396
17571529	3940	how would i combine these two sql queries into one?	select name, sum(case when dayaci = 'sunday' then 1 else 0 end) as sunday,        sum(case when dayaci = 'monday' then 1 else 0 end) as monday,        sum(case when dayaci = 'tuesday' then 1 else 0 end) as tuesday,        sum(case when dayaci = 'wednesday' then 1 else 0 end) as wednesday,        sum(case when dayaci = 'thursday' then 1 else 0 end) as thursday,        sum(case when dayaci = 'friday' then 1 else 0 end) as friday,        sum(case when dayaci = 'saturday' then 1 else 0 end) as saturday,        count(*) as total, max(cap.prevtotal) as prevtotal  from caraccident ca left outer join       (select cap.name, count(*) as prevtotal        from caraccidentprev cap        where cap.accident = 'near-miss'        group by cap.name       ) cap       on cap.name = ca.name  where accident = 'near-miss'  group by name; 	0.00498494830399324
17571627	3993	mysql - retrieve many rows and count affected rows in one query	select var1, var2,         (select count(*) from tablename where columnname = 1) as `count` from   tablename where  columnname = 1 	0
17572752	15968	sql query resultset, i need sum(quantity) column grouped by day	select count(`p`.`id`) as `quantity`, date_format(`p`.`created_time`,'%y-%m-%d') as `day` from `product` as `p` inner join  ( select      `productid` as `id`,     count(id) as pagesnr  from      `page` group by      `productid` having count(`id`) >= 10 ) as  `pg` using (`id`) where     `p`.`created_time` between '2013-07-03 00:00:00' and '2013-07-10 23:59:59' and     `p`.`group` = '101' group by      `day` order by      `created_time` 	0.002812143612898
17572817	512	register of table1 where not have in table2	select     t1.registers    from     table1 t1 where     not exists (select *          from table2 t2          where t1.id = t2.id_table1) 	0.0128438835353499
17572848	31514	is it possible to dynamically select a column name in mysql where the column name is 1 of n known values?	select column_name from information_schema.columns where table_name='your_table_name' and column_name in ('name', 'label', 'title') into @colname; set @table = 'your_table_name'; set @query = concat('select ',@colname,' from ', @table); prepare stmt from @query; execute stmt; 	0
17574671	24315	how to ignore specific values in group by in sql	select distinct id, str_replace(convert(varchar,start_time,102),'.','-') [date],  min(convert(varchar(8), start_time, 108)) [start time], max(convert(varchar(8), start_time, 108)) [end time], max(o) [o], max(a) [a], case when error_msg != '(null)' then isnull(error_msg,'null') end [error?], from table  group by id order by id desc 	0.00839781837787204
17574869	39673	selecting data in access by conditional merging	select studyid, textdata, max(soption) as soption2 from mytable group by studyid, textdata order by studyid, textdata 	0.048787641259588
17575297	28504	split a string into formatted letters for where in query	select * from table_name where locate(identifier, "mysql")>0 	0.00138942548257592
17576807	7241	php sql - json - message list	select * from messages a left join messages b     on a.fromuser = b.fromuser     and a.date < b.date where b.date is null and a.touser = '$enduser'  order by lower(a.fromuser) 	0.185724314973347
17577173	10573	mysql: selecting all fields based on data in particular field	select * from yourtable where yourtable.field1 in (    select distinct field1    from yourtable    where field2 = 'a' ) as childquery 	0
17577421	11451	how to get the closest value of date from table? input parameter is 2012-02-10	select * from t order by abs(datediff(date, date('2012-02-10'))) limit 1 	0
17580979	5162	sql - group by query	select   count(customerid) as number_customers,   number_products from (   select customerid,    count(productid) as number_products   from tablename   group by customerid ) subquery group by number_products 	0.576087973847006
17581003	31568	how to performs combination of rows with same values as a group?	select a.date adate, a.name aname, a.marks amark,  x.date xdate, x.name xname, x.marks xmarks from a a, a x  where a.name < x.name and a.date = x.date order by aname, xname, adate, xdate 	0.000202915425298781
17583950	25522	determine if a certain number is greater than a requirement	select p1.* from prices p1 join (select name, min(cost) mincost       from prices       group by name       having mincost > 3) p2 on p1.name = p2.name 	0.000211411684196196
17584072	3584	t-sql how to translate multiple sub-strings to new values	select   mixid, [contains], stuff((           select ':' + color           from table1 a           where ':'+b.[contains]+':' like '%:'+a.fruit+':%'                 for xml path('')             ), 1, 1, '') as color from table2 b group by mixid, [contains] 	0.0208901229521391
17584194	7618	comparing the average in mysql	select shirt.color, shirt.size from shirt inner join (select color, avg(size) size from shirt group by color) as table2 on shirt.color = table2.color where shirt.size >= table2.size 	0.00378242872884022
17586601	16352	sql server how to get count of a field for the current quarter from date?	select count(fieldname) as hits  from tablename where datepart(q,dateposted) = datepart(q,getdate()) and year(dateposted) = year(getdate()) 	0
17586920	10327	how to make query for that	select     datepart(m, month_start) + ' ' + datepart(yyyy, month_start)     , max_temp_days     , case         when denominator = 0 then 0         else (max_temp_days / denominator) * 100       end as percent_max_temp_days     , min_temp_days     , case         when denominator = 0 then 0         else (min_temp_days / denominator) * 100       end as percent_max_temp_days from (     select          dateadd(month, datediff(month, 0, recording_date), 0) month_start         , sum(case when max_temp <= 0 then 1 end) max_temp_days         , sum(case when min_temp <= 0 then 1 end) min_temp_days         , count(*) denominator     from temperaturerecordings     where recording_date between '2013-01-01' and '2013-03-31'     group by dateadd(month, datediff(month, 0, recording_date), 0) ) t order by month_start 	0.254501816534051
17590233	67	how to prevent 3 nested mysql queries from timing out	select name2, max(t1.id)  from t2 inner join t1 on t2.t1_id = t1.id where name1="xxx" and user_id='$id' 	0.0943858537247819
17590737	34233	difference between two recordsets in tsql	select           studentid,          courseid from dbo.applications except select           studentid,          courseid from dbo.enrolments 	0.0135923423950158
17594263	34408	add created column to search critera?	select @where = ' or u.[forename] + '' '' + u.[surname] like ''%' + replace(@searchstr, '''', '''''') + '%''' 	0.0332549728032953
17595591	15712	same value in two columns of same table	select codigo, referencia, descricao   from estoque  where convert(varchar(max),codigo) = referencia 	0
17596378	13271	mysql schema design advise	select users_roles.user_id, documents_roles.document_id from documents_roles  join users_roles using (role_id)  left join documents_users on     documents_users.document_id = documents_roles.document_id and     documents_users.user_id = users_roles.user_id  where     documents_users.user_id is null  ; 	0.782920052619007
17596775	40880	joining over an interim table sql server	select   p.productid,   p.producttypeid,   m.margin,   d.biggestdiscount,   m.margin - d.biggestdiscount as adjustedmargin from product p inner join discounts m on (p.productid = d.productid) inner join (   select     producttypeid,     max(discount) as biggestdiscount   from sellingpricerules   group by producttypeid ) d on (p.producttypeid = d.producttypeid) where p.productid is not null 	0.430530352133081
17597785	22326	sql server using pivot/unpivot in a new table	select buildingname, january, february, march, april from (   select buildingname,     datename(month, billingmonth) month,     consumption   from yourtable ) d pivot (   sum(consumption)   for month in (january, february, march, april) ) piv; 	0.160775812681793
17598001	3931	sql set variable to a value in the current row	select @agentid = agentid from agenttable where @index = rowid; 	0
17598139	30964	how to do the row to column sumif in ms sql server	select person,            sum(part)as part,            sum(case when status='a' then 1 end) as status-a,            sum(case when status='b' then 1 end) as status-b,            sum(case when status='c' then 1 end) as status-c             from table-a            group by person; 	0.0144105800539813
17598166	21710	combine three tables and count a specific value with mysql	select customer, group_concat(concat(pname, ' (', pcount, ')')) products from (     select         c.name customer,         p.name pname,         count(*) pcount     from         company c     inner join         serial s     on         c.id = s.cid     inner join         product p     on p.nr = left(s.serial, 3)     group by customer, pname) x group by customer order by     customer desc 	0.000367121669507063
17598350	9842	sql server : select query: select value if condition	select   stock.name,       case           when stock.quantity <20 then 'buy urgent'          else 'there is enough'       end from stock 	0.101190667790378
17598889	21613	mysql get last result for each where	select u.* from update u join (select type, max(date) maxdate       from update       where type in ('1', '2', '3')       group by type) m on u.type = m.type and u.date = m.maxdate 	0
17599482	12660	sql: selecting a value based on values from a number of rows in another table	select     case          when circuitcount is null      then 'nostatus'         when greencount = circuitcount then 'greenstatus'         when greencount = 0            then 'redstatus'         else 'yellowstatus'     end as network_status from networks as n left join (   select  count(*) as circuitcount,             count(nullif([status],'redstatus')) as greencount,             network_id     from    network_circuits     group by network_id )   as c    on n.network_id = c.network_id 	0
17601382	40548	mysql select with the same column appearing twice with different where clauses	select user_id,    max(if(district='north', start, null)) as no_st,   max(if(district='north', end, null)) as no_en,   max(if(district='south', start, null)) as so_st,   max(if(district='south', end, null)) as so_en from `nooneevernamestheirtableinsqlquestions` group by user_id; 	0.000829334156960126
17601834	24517	sql query for finding pairs that share the exact same set of values	select a.employee_name,b.employee_name from tasks as a, tasks as b where a.employee_name>b.employee_name group by a.employee_name,b.employee_name having group_concat(distinct a.task order by a.task)=group_concat(distinct b.task order by b.task) 	0
17602515	18640	looking for missing rows t-sql	select pt from mytable group by pt having count(itm) < 3 	0.16541020155419
17603268	27437	populate dropdown based on row values one time	select distinct `date` from `yourtable`; 	0
17603365	14290	mysql query to find child record where 2nd child table entries do not match	select s.description from structure s inner join structure_version sv on sv.structure_id = s.id inner join structure_version_range svr on svr.structure_version_id = sv.id inner join structure_version_range_partner svrp on svrp.structure_version_range_id = svr.structure_version_id inner join item_version iv on iv.structure_id = s.id left join item_version_partner ivp on ivp.item_version_id = iv.id and ivp.partner_id = svrp.partner_id where ivp.partner_id is null 	0
17603737	40996	how to select the highest score of more than one same courses in mysql?	select emplid, max(conv_grade_off), mast_cat from mast_cat_hs group by elplid, mast_cat 	0
17604534	20238	cast varbinary(8)/timestamp column to varchar(max) get empty string?	select convert(varchar, @b, 1), @b 	0.0232501974056266
17609243	28778	how to find out 2nd highest salary of the employee using postgresql query	select salary  from (    select salary,           dense_rank() over (order by salary) as dense_rank     from geosalary ) as t   where dense_rank = 2 	0
17609793	38925	sql query for each day	select time      , @tot_qty := @tot_qty+qty as tot_qty from table1  join (select @tot_qty := 0) d order by time 	0.000326810025433882
17610591	25898	sqlsrv: group by one column and sum by month	select area, subarea, sum(case month(date) when 1 then 1 else 0 end) as jan, sum(case month(date) when 2 then 1 else 0 end) as feb, sum(case month(date) when 3 then 1 else 0 end) as mar, sum(case month(date) when 4 then 1 else 0 end) as apr, sum(case month(date) when 5 then 1 else 0 end) as may, sum(case month(date) when 6 then 1 else 0 end) as jun, sum(case month(date) when 7 then 1 else 0 end) as jul, sum(case month(date) when 8 then 1 else 0 end) as aug, sum(case month(date) when 9 then 1 else 0 end) as sep, sum(case month(date) when 10 then 1 else 0 end) as oct, sum(case month(date) when 11 then 1 else 0 end) as nov, sum(case month(date) when 12 then 1 else 0 end) as [dec] from stops group by area, subarea 	0.000670293208295835
17612920	22600	lpad with leading zero	select lpad(numer,6,'0') as numer from ... 	0.47834934927773
17613038	13792	check if name from table 1 exists in table 2	select * from table1 where table1.name in (select table2.name from table2) 	5.46131269652386e-05
17614280	40155	import a .mdb to sqlserver via stored procedure	select * into #yourworktable from opendatasource (‘microsoft.jet.oledb.4.0′, ‘data source=\\server-name\mdbs\test.mdb’)…[tablename] 	0.595036435925603
17615153	31102	sql query - percentage of sub sample	select t1.id,         t1. groupid,         (t1.profit * 1.0) / t2.grp_profit as percentage_profit from table t1 inner join  (    select groupid, sum(profit) as grp_profit    from table    group by groupid ) t2 on t1.groupid = t2.groupid 	0.346225750939303
17616958	7633	sql count: how to get a count on identical values in a table	select        [measurement name]     , [smp id]     , [fail count] = sum([fail])     , [not fail count] = sum([not fail])     , [fail %] = 100 * sum([fail]) / sum(1) from [measurements] cross apply (select [fail] = case when [status] = 'fail' then 1 else 0 end) [x_fail] cross apply (select [not fail] = case when [status] <> 'fail' then 1 else 0 end) [x_not fail] group by [measurement name], [smp id] 	0
17617629	24243	how to sum a column after it is filtered by a where clause	select sum (convert (float,(dbo.performance_2012q2.[current actual unpaid principal balance]))) from dbo.performance_2012q2  where dbo.performance_2012q2.[current interest rate] >= 3.00 and dbo.performance_2012q2.[current interest rate] < 3.10 and dbo.performance_2012q2.[monthly reporting period] = '03/01/2013' 	0.204997955578525
17618143	15726	my sql merging rows	select `date`, max(`long`) `long`, max(short) short from yourtable group by `date` 	0.0382704892604822
17619514	3443	postgresql-select one row from table where value in many table matches?	select * from department d where exists (    select * from employee e    join badges b on b.person_id = e.person_id and b.badge = 'eotm'    where e.dep_id = d.dep_id    and e.gender = 'f'    ); 	0
17622127	22538	sql join query for multiple tables	select      cust_info.cust_id,     cust_name,     bill_amount,     paid_amount,     bill_amount - paid_amount as balance from cust_info inner join (     select cust_id, sum(bill_amount) bill_amount     from bill_info     group by cust_id ) bill_info on bill_info.cust_id = cust_info.cust_id inner join (     select cust_id, sum(paid_amount) paid_amount     from paid_info     group by cust_id ) paid_info on paid_info.cust_id = cust_info.cust_id 	0.416998121434617
17622412	39862	order two separate tables by date	select id, title, date   from table1 union select id, saying, date   from table2 order by date 	0.00137419011395087
17623189	18585	combining rows in sql server	select c1,        max(c2) as c2,        max(c3) as c3 from   yourtable group  by c1 	0.0586954042496254
17623416	1188	join data from two many-to-many sql structures	select *, group_concat(distinct ambiencename separator ' ') as ambiences,  group_concat(distinct specificname separator ' ') as specifics  from films as f  left outer join films_ambiences as fa on f.id = fa.film_id           left outer join ambiences as a on a.id = fa.ambience_id left outer join films_specifics as fs on f.id = fs.film_id           left outer join specifics as s on s.id = fs.specific_id group by title 	0.0106490184293045
17623461	193	select dates between this monday and this friday	select `date` from horoscopes where week(`date`) = week(now(), -1); 	0.223323952021462
17624704	5112	group by county sql query	select a.county, count(*) 'number of responses' from ( select     sr.response,     county =     (         select             qpa.possibleanswertext         from caresplusparticipantsurvey.questionpossibleanswer as qpa         join caresplusparticipantsurvey.surveyresponse as sr1 on qpa.id = sr1.questionpossibleanswerid         where (sr1.questionid = 1 and sr.surveyid = sr1.surveyid)     ) from caresplusparticipantsurvey.surveyresponse as sr where (sr.response is not null and cast(sr.response as int) < 6) and (sr.questionid = 8) ) a group by a.county 	0.746677366015767
17627811	26393	database size calculation?	select table_schema "database name"      , sum(data_length + index_length) / (1024 * 1024) "database size in mb" from information_schema.tables group by table_schema 	0.228248719944013
17630227	3886	how to combine(full join) two unrelated tables in mysql	select t2.date, t1.name from table1 t1 cross join table2 t2 	0.00882905217895338
17635464	960	select from 3 possible columns, order by occurances / relevance	select id from (   select id,      (keywords like '%cute%') + (title like '%cute%') + (content like '%cute%') total    from wp_ss_images   ) t where total > 0 order by total desc 	0.00533543052191021
17635670	36966	mysql count row /adding together 2 different result on 1 query	select count(id) from productx where ... wheres for brand, gender, and category ... and subcategory in ('sandalet', 'nightshoes') 	0.000257735094817951
17635976	24626	select rows that are a multiple of x	select * from `table` where (`id` % 10) = 0 select * from `table` where (`id` mod 10) = 0 select * from `table` where !mod(`id`, 10) 	0
17636406	24012	how to select only duplicate records?	select state from area group by state having count(*) > 1 	0.000184800927659265
17639168	38053	sql incremental id for every user_id	select     user_id, user_login_date,     row_number() over(         partition by user_id         order by user_login_date     ) as date_id from users order by user_id, date_id 	0.0017074684568515
17639655	14314	2 listagg in one sql select in oracle	select  id,    listagg(case when pass = 1 then course end, ',') within group (order by course) passed,   listagg(case when pass = 0 then course end, ',') within group (order by course) failed from table1 group by id 	0.0580293817865559
17641120	18642	return no or yes if time difference is greater than 5min	select id      , comment      , comment_date      , case            when comment_date < date_sub(now(), interval 5 minute)               then 'yes'               else 'no'            end as answer from comments; 	0.00367638330869941
17645672	14135	how can i know how many rows will update sql affected before i execute it	select count(id) as will_affect_rows_count from products where products_id = '1' 	0.109231114071706
17646503	40844	mysql schedule collision data	select s1.idcourse, s2.idcourse, s1.day from schedule s1 join schedule s2 on s1.day = s2.day and s1.room = s2.room and s1.idcourse != s2.idcourse where s1.begin between s2.begin and s2.end 	0.30211276211946
17648828	26967	using current year in string to date function	select str_to_date(concat(year(now()), ' ', 'jul 15 12:12:51'), '%y %b %e %t'); 	0.000701872271129491
17650398	40598	sql multiple conditions method	select * from o order by case field1 when 'a' then 1 else 2 end,          case field2 when 'b' then 1 else 2 end,          rowid 	0.674290296575159
17652529	25160	mysql single statement to merge two tables	select u.id, u.hash, uf_f.value as firstname, uf_l.value as lastname from user as u  left join user_field as uf_f on uf_f.user_id = u.id and uf_f.key = 'firstname' left join user_field as uf_l on uf_l.user_id = u.id and uf_l.key = 'lastname' 	0.00317745778062126
17652668	31178	how to extract specific word from string in postgres	select   id,          split_part( prodname, ' ' , 1 ) as size,   split_part( prodname, ' ', 2 ) as brand   from products where ({0} is null or split_part( prodname, ' ' , 1 )= {0} ) and     ({1} is null or split_part( prodname, ' ', 2 )= {1} ) 	0.000197373114754429
17653444	4667	retrieving the latest record from a table (oracle sqlplus)	select * from (   select userid,           threadid,           posttime,          threadtype,          topic,           detail,          row_number() over (partition by userid order by posttime desc) as rn   from thread   ) t where rn = 1 order by userid; 	0
17653702	5534	get results that are between (inclusive) a and d	select * from table where word regexp '^[a-d]'; 	0.00108109600081358
17653872	11465	using function least and greatest on timestamp in postgresql	select * from some_table where plc_time = greatest(timestamp '2013-07-15 14:55:00', timestamp '2013-03-01 17:43:00'); 	0.063308203953916
17655040	5195	count multiple values in sql	select sum(if(status=1,1,0)) as status_1, sum(if(status=2,1,0)) as status_2, sum(if(status=3,1,0)) as status_3, sum(if(status=4,1,0)) as status_4 from foo 	0.0323690145287339
17656097	9969	sqlite concat select statement	select name || ' ' || surname as user_name from users 	0.682164025341943
17656482	2965	order by size postgres bytea	select length(the_image_column) as the_size from t order by 1 desc 	0.516474460364564
17656570	39868	sql groupby multiple columns	select e.charityname, c.firstname, c.lastname,  sq.my_count from entrytable e inner join contestanttable c on e.id = c.entryid inner join (   select entryid, count(*) as my_count from contestanttable group by entryid   ) sq on e.id = sq.entryid 	0.0928460986949967
17657250	16095	select single row per unique field value with sql developer	select customer_id, max(company) as company, count(sales.*) from customers <your joins and where clause> group by customer_id 	0
17657846	14140	how many unique titles?	select count(distinct title) from table; 	0.0196160832149086
17658986	16607	multiple sum functions with different scope on same query	select *   , studentgroupcredits = sum(case when complete_courses_alert = 'complete' then credits else 0 end) over (partition by studentid, groupname)   , studenttotalcredits = sum(case when complete_courses_alert = 'complete' then credits else 0 end) over (partition by studentid) from courses 	0.0302414996775665
17660035	36345	select field alias condition and multiple joins	select coalesce(tabletwovalue, tablethreevalue, tablefourvalue)  as extrafield from ... 	0.517945104468442
17660228	26213	how to find a specific foreign key of a table through t-sql?	select * from sys.foreign_keys where name like '%yourforeignkeyname%' 	0
17661342	5130	mysql - left join all tables	select temp_table.* from     (select 'asdf', '123' ... from dual) temp_table left join table1 on (     new_condition ) left join table2 on (     condition1 ) left join table3 on (     condition2 ) where (     main_condition ) 	0.182845122166494
17663115	37665	concatenate multiple fields on multiple rows with commas	select s.ip,  group_concat(distinct i.name order by i.name asc separator ", " ) as instances from servers as s join serverinstances as si on s.id = si.sid join instances as i on si.iid = i.id  group by s.ip; 	8.88967499077837e-05
17663995	41146	get date range in mysql after group by	select name, count(*),       case when count(*) > 1 then concat(min(work_date), ' - ', max(workdate)          else work_date end as  daterange    from footable  group by id; 	0.000723657633490116
17664298	37525	google chart add each day on the between sql string	select      from_unixtime(timestamp, '%e %b %y') as somedate,      count(*) as 'searchtotal' from logs where from_unixtime(timestamp, '%e %b %y') between '$from_date_string' and '$to_date_string' group by somedate 	0
17664812	37477	sql server distinct columns	select * from ( select  aps.serv_acct , aps.account , row_number() over (partition by aps.serv_acct order by aps.inv_date desc) [row]     from tblapsdata aps     inner join tblmep_meters mep       on aps.serv_acct = mep.serviceaccount     inner join tblmep_sites site       on site.siteid = mep.id     inner join tbl_mep_projects proj       on proj.id = site.projectid       and proj.customerid = 8        and proj.type = 1      inner join tblmep_customeraccounts custacc       on custacc.accountnumber = aps.account       and custacc.customerid = @customerid       and custacc.utilitycompanyid = @utilitycompanyid where aps.inv_date > dateadd(month, -6, getdate()) ) data where   data.row = 1 	0.0509979550661259
17667599	26253	combine multiple results as columns, not rows	select * from (   select count(id) as undeliveredsms   from   (    select id    from incomingsms    where id not in (select incomingsmsid                     from deliveryattempt                     where status = 'delivered' or status = 'failedpermanently')   ) ) cross join (   select count(id) as undeliveredemail from   (    select id    from incomingemail    where id not in (select incomingemailid                     from deliveryattempt                     where status = 'delivered' or status = 'failedpermanently')   ) ); 	0.00183613693682785
17669310	21235	mysql search events between dates?	select event_id, event_name from events where start_date <= 2013-07-30 and end_date >= 2013-07-16 	0.00573300964283732
17669705	41025	separate column based on condition in same table in sql	select wtccommentid, wtctransactionid, wtctaskid,  wtcuserlogin,  wtccommentdatetime,  case when wtctaskid!=0 then wtccommenttext end as wtccommenttext,  case when wtctaskid=0 then wtccommenttext end as transcommenttext from   dbo.tblworkflowtransactioncomments (nolock) where  wtctransactionid = 141248 	0
17670073	13605	retrieving values from 3 one-to-one relationship table (oracle)	select u.userid, s.studentid, t.teacherid   from user u left join student s on s.userid = u.userid   left join teacher t on t.userid = u.userid 	0.000703941240070235
17670597	16359	group by aggregate	select       locationid = max(l.locationid)     , l.code     , [description] = max(l.[description])     , m.routingcode     , fano = max(m.fano)     , namebg = max(m.namebg) from dbo.scanlog s left join dbo.locations l on l.barcode = s.linebarcode left join dbo.machines m on m.barcode = s.machinebarcode group by         l.code      , m.routingcode 	0.635806879335456
17671307	11364	sorting alphanumeric in mysql?	select string,        @num := convert(string, signed)                            as num_part,        substring(trim(leading '0' from string), length(@num) + 1) as rest_of_string from   table1 order  by num_part,           rest_of_string 	0.287137730666309
17672153	37301	display single column wise record for multiple row wise records	select ssn,    nvl (max (case id when '10' then 'y' else null end ),'n') as id_10_indicator,    nvl (max (case id when '20' then 'y' else null end ),'n') as id_20_indicator,    nvl (max (case id when '30' then 'y' else null end ),'n') as id_30_indicator from table1 group by ssn ; 	0
17672347	30001	how to get the latest value of a field from the table in db2	select id from schema.table order by tstamp desc fetch first row only 	0
17672794	20449	how do i write an sql to get a cumulative value and a monthly total in one row?	select name, sum(sales) as total_cumulative_sales ,        sum(              case trunc(to_date(date_created), 'mm')               when  trunc(sysdate, 'mm') then sales               else 0             end         ) as  total_sales_current_month from tab group by name 	0
17673394	3350	find rows with different values	select count( distinct color  ) as color, count( distinct shape  ) as shape, count( distinct material) as material from $table; 	0.000178174224418688
17673453	38660	mysql query to retrieve friendships only works one way?	select `accounts`.*, `f1`.`sender`  as `sender`,`f1`.`recipient`  as `recipient`,`f1`.`date_sent`  as `date_sent`,  `f1`.`date_reviewed` as `date_reviewed`,`f1`.`accepted`    as `accepted` from `accounts`   join `friendships` as `f1` on (`accounts`.`id` = `f1`.`sender`   or `accounts`.`id` = `f1`.`recipient`) where    if(`f1`.`recipient` = 1, `f1`.`sender` , if(`f1`.`sender` = 1, `f1`.`recipient` , 0)) = `accounts`.`id`; 	0.0165985372419068
17673859	17164	mysql using same table/fields multiple times in a single query	select order_id,  c1.customer_id as customer_id, c1.customer_name as customer_order_name , c2.customer_id as customer_from_id, c2.customer_name as customer_from_name from orders o left join customers c1 using (customer_id) left join customers c2 on o.customer_from_id = c2.customer_id; 	0.0031003782793966
17674699	861	codeigniter fetching records from more than two tables	select s.cover_title   from storytag_invitations si, storytags s  where s.id != si.storytag_id    and s.user_id != si.user_id    and si.user_id = 3 	0.000120767602106957
17675048	37489	sql: how to find minimum in minimum set with joins efficiently	select     school, class, dob, stu_id from     (     select         school, class, dob, stu_id,         dense_rank() over (partition by school order by class, dob) as rn     from         mytable     ) x where x.rn = 1 	0.00322832178819441
17675375	35893	populating missing dates and max date	select    t1.date_  , t1.product   , case      when t1.due_date is not null then t1.due_date     else (            select max(due_date)            from sot t2            where t2.product = t1.product              and t2.due_date <= t1.date_             and t2.date_ > t1.date_           )     end                                                      as due_date , t3.max_date from      sot t1     left outer join (  select product, max(date_) keep (dense_rank first order by due_date desc)  as max_date                         from sot                         where due_date is not null                        group by product                     ) t3     on (t3.product = t1.product) order by product, date_; 	0.00641741791057933
17675384	3263	how to find the first and last id of mysql table enteries for a specific date?	select min(id), max(id) from tablex where entrydate = 'yyyy-mm-dd' 	0
17677270	2289	mysql query for multi join two tables on multiple colums	select *, round(((3959 * acos(cos(radians(51.1080390)) * cos(radians(latitude)) * cos(radians(longitude) - radians(-4.1610140)) + sin(radians(51.1080390)) * sin( radians(latitude)))) * 2),0)/2 as `distance` from `properties` as prop left join `offers` on prop.code = offers.the_property         or prop.county = offers.the_county         or prop.region = offers.the_region having distance <= 2.5 order by `sleeps` asc, `distance` asc limit 0, 10 	0.0164680788649755
17677465	17196	sql server group and count	select routingcode, name, count(1) from machines  left outer join log on log.machinebarcode = machines.barcode where (log.linebarcode = 100000000001) or (log.linebarcode is null) group by routingcode, name 	0.38631808634952
17678768	35064	remove text from column in sql database	select      charindex('usercomment:', metadata),     charindex(' ', metadata, charindex('usercomment:', metadata)),     left(aaa, charindex('usercomment:', metadata)-1) + right(metadata, len(metadata) - charindex('     ', metadata, charindex('usercomment:', metadata)))   from dbo.metadata 	0.00620038600625741
17679009	31761	convert datetime to us and european	select convert(nvarchar, @datetime, 101) + n' ' +convert(nvarchar, cast(@datetime as time(0)), 109) 	0.130094093154658
17679301	39468	oracle help on selection of data	select * from     sal_info where     (deptno, sal)     in     (         select              deptno, max(sal)          from sal_info         group by deptno     ) 	0.479259419542211
17679975	531	set mysql field according to substring comparison	select if(locate('house', `url`) > 0, 'house',if(  locate('appartement', `url`) > 0, 'appartement', 'other')) as property_type 	0.0259075372954199
17680091	6704	sql - same value in one field in output	select a,(select top 1 b from #temp where id=t.id and d='r') as b,c,d,id from #temp t 	0.000369093269779981
17680626	28023	oracle sql dynamically select column name	select case to_char(sysdate,'hh24')            when '08' then hh08            when '09' then hh09            when '10' then hh10            when '11' then hh11            when '12' then hh12            when '13' then hh13        end outputvalue from tablename where name = 'steve' 	0.0570375961688273
17682175	25080	how do i compare dates in one sql table to a range defined in another table?	select      t1.name, t1.dob from      t1     join t2 as startdate on (startdate.code = 'yearstart')     join t2 as enddate on (enddate.code = 'yearend') where      stuff(convert(varchar, t1.dob, 112), 1, 4, '') between          stuff(convert(varchar, startdate.[date], 112), 1, 4, '')         and         stuff(convert(varchar, enddate.[date], 112), 1, 4, '') 	0
17683140	13443	need to add a column to signify active or termed status	select case when enddate is not null then 'termed'              when startdate is not null then 'active'              else 'unknown' end as empstatus from employee 	0.00330209756787867
17690027	2216	how to select all records from a special table order by desc?	select  s.*,         @currow := @currow + 1 as row_number from    s join    (select @currow := 0) r order by row_number desc; 	0.000109430985802999
17690941	30574	filter a sql statement using its column values	select  *  from    table1  where   getdate() between startdatetime  and enddatetime 	0.0180329227692904
17691883	18682	adding rows automatically based on previous rows	select top (100) percent room,     subject,     count(subject) as expr1 from dbo.timetable group by room,     subject union all select top (100) percent room,      'not used',     60 - count(subject) as expr1 from dbo.timetable group by room order by t.room 	0
17695671	12179	add zero to the count where ever there no data for field	select     tab1.id,    tab1.name,tab2.design,    sum(case when tab1.id=tab2.id then 1 else 0 end) as count from     tab1 cross join tab2 group by     tab1.id,tab1.name,tab2.design order by     tab1.id 	0.00182261732294137
17696484	20221	returning three columns from stored procedure	select      sum(case when t.startdate between '2013-7-17' and '2013-7-18' then 1 else 0 end) as daycount,     sum(case when t.startdate between '2013-7-14' and '2013-7-20' then 1 else 0 end) as weekcount, from calendaritem t  left join company c on t.companyid = c.companyid and c.enabled = 1  inner join calendaritemtype tt on tt.calendaritemtypeid = t.calendaritemtypeid  left join request r on r.requestid=t.workrequestid  where t.deleted = 0 	0.029700000718144
17698029	32363	how do i rank search results by best match in mysql/php?	select name, sum(relevancy) as sumrelevancy from (     select a.name, min(c.relevancy) as relevancy      from professionals a     inner join linktable b on a.id = b.professionalid     inner join     (         select qualificationid, levenshtein('ca', qualificationname) as relevancy from qualifications     ) c on b.qualificationid = c.qualificationid     group by a.name     union all     select a.name, min(c.relevancy) as relevancy      from professionals a     inner join linktable b on a.id = b.professionalid     inner join     (         select qualificationid, levenshtein('ba', qualificationname) as relevancy from qualifications     ) c on b.qualificationid = c.qualificationid     group by a.name ) sub1 group by name order by sumrelevancy 	0.134227153911178
17698915	1619	if in mysql query	select case when image_path like 'http%' then 'something' else 'somethingelse' end 	0.428258375110089
17700023	21530	rows multiplication needed	select t.* from inventory t join (select level n from dual        connect by level <= (select max(qty_on_hand) from inventory))  on n <= t.qty_on_hand 	0.415899379797217
17700364	26152	random "select 1" query in all requests on rails	select 1 	0.0366831217197127
17701381	28991	two sql if statements	select    * from table where     (@user = 'bob' and id = 1)     or     (@animal= 'cat' and id = 50) 	0.178844301348625
17702403	16397	using max in group by	select c.store,d.node_name category, max(x.txn_dt) max_date, x.txn_tm time, count(c.txn_id) buyer     from pos_swy.5_centerstore_triptype c     join pos_swy.3_txn_itm t on c.txn_id=t.txn_id     join pos_swy.1_upc_node_map d on t.upc_id=d.upc_id     join pos_swy.3_txn_hdr x on t.txn_id=x.txn_id     group by node_name     order by max_date desc  	0.238356012720412
17703215	6113	sql selecting maximum based on minor-major scheme	select * from (     select *, row_number() over (partition by [serial number] order by revmajor desc, revminor desc) versionrank     from table ) t where versionrank = 1 	9.80696859069197e-05
17703549	19956	sql to get latest objects	select     max(object_id) as maxobjectid from table group by system_id 	0.00106892798214617
17703647	10918	mysql : select on timestamp column, change seconds to 00 and round minutes down to nearest 10	select date_sub(date_sub(ticktick, interval mod(minute(ticktick),10) minute), interval second(ticktick) second) from `table` 	0
17703813	32690	how to structure this db in sqlite?	selected topic | associated question key question key | question # | question 	0.729345042429089
17704720	2603	how to join compound tables	select l.locationname, group_concat(distinct c.classname) from locations l inner join classes c on c.locationid = l.id  group by l.locations 	0.292499677290556
17706576	40723	not able to create pivot for following data.. table in below format	select * from (         select t2.id,                t2.name,                t1.class,                left(datename(month,t1.date),3)as [month],                t1.rate         from tbl_fee_rates t1 inner join tbl_students t2         on t1.class = t2.class ) p pivot ( sum(rate) for [month] in (jan, feb, mar, apr,may, jun, jul, aug, sep, oct, nov, dec) ) as pvt 	0.399658837699069
17707014	35253	getting the number of connect data while skipping the duplicates	select count(distinct date) from day where name like 'peter' 	0.000191492493374983
17708051	31498	count number of records with same column	select  did ,       count(*) over (partition by did) from    yourtable 	0
17709114	20967	using iif to mimic case for days of week	select     weekdayname(weekday(incidentdate)) as dayofweek,     count(*) as numberofincidents from incident group by weekdayname(weekday(incidentdate)); 	0.00458886487113845
17711944	22218	build dialogs list from mail database	select distinct    least(     `owner_user_id`,     `viewer_user_id`   ) as first_user,   greatest(     `owner_user_id`,     `viewer_user_id`   ) as second_user from   `mail` 	0.092586689650617
17712203	17716	getting records with unique phone number	select id,         name,         address,         phone  from   clients  where  state in ( 'mo', 'la', 'ct' )         and foo > 40         and id in         (           select min(id) from clients group by phone        ) order  by foo 	0.000274657096814057
17712346	33013	excluding record non unique field data	select id,         name,         address,         phone  from   clients  where  state in ( 'mo', 'la', 'ct' )         and foo > 40         and phone not in         (           select phone            from clients            group by phone           having count(*) > 1        ) order  by foo 	4.74470160454607e-05
17713841	1096	mysql select date range from table where there's only one column for date	select emp_name, team, min(start_date) start_date, end_date   from (     select t1.emp_name, t1.team, t1.start_date, min(t2.start_date) end_date       from table1 t1  left join table1 t2         on t1.emp_name = t2.emp_name        and t1.team != t2.team        and t1.start_date < t2.start_date   group by t1.emp_name, t1.team, t1.start_date) t3 group by emp_name, team, end_date order by start_date 	0
17715024	29082	mysql match letter/number field with letter field without duplicates	select p.* from product p join collection c on p.product_code regexp concat('^', c.collection_code, '[0-9]+$') 	0.00146328673853861
17716001	31619	one to one result in mysql query	select c.id,c.name as name ,cd.id as cdl_id,cd.career_id,cd.name as dtl_name from career_details cd  inner join careers c  on c.id=cd.career_id and cd.id in (select max(id) from career_details group by career_id); 	0.00843080551117014
17716214	40953	date conversion error in sql on one computer, but the code works on another?	select * from [db].[dbo].[stg_table] where [change_date] >  cast(convert(char(8),dateadd(day, -3, getdate()),112) as numeric(8,0)) 	0.57148276289529
17716854	29184	group by one column and show all results from another column	select regno, group_concat(name separator ', ') names from mytable group by regno 	0
17717190	26866	how to compare one table's column against another?	select * from table a inner join table b on ( where a.column1=b.column2 	0
17717666	20800	distinct created_by and sum total_amount for each created_by	select o_mst.created_by, sum(o_mst.amount) from o_mst inner join i_mst on i_mst.inq_mst_id = o_mst.inq_mst_id  where i_date between '2013-01-01' and '2013-08-01' group by o_mst.created_by desc limit 0 , 5 	0.00880651006489185
17717719	31200	date time difference get hour:minutes:seconds	select convert(varchar(10),datediff(hour,t.paydate,t.deldate))+'hr:'        +convert(varchar(10),datediff(minute,t.paydate,t.deldate)% 60) + 'mnts:'        +convert(varchar(10),datediff(second,t.paydate,t.deldate)% 60) +'seconds'        as 'diff in hh:mm:ss' from transaction_tbl t  where t.transactid=19 	0.000985389848282508
17718084	20159	how to get data with multiple references to single table	select c.id category_id,         c.name category_name,         p.name product_name,         i1.name category_image,         i2.name product_image   from category c join product p     on c.productid = p.id left join image i1      on c.id = i1.refid left join image i2     on p.id = i2.refid 	0.000148555519141892
17718435	24066	sql query for average big record	select     100*floor(race_number/100) race_number_group,     avg(speed) average_speed from user_test group by floor(race_number/100); 	0.00928574054277745
17718639	26191	combining multiple rows in sql server	select users.id, username, refname,  cards = (     select         stuff((             select ', card' + cast(row_number() over (order by cards.id) as varchar)                    +': '+ color + '(' + cast(number as varchar) +')'            from                users_cards               left join cards on dbo.users_cards.card_id = cards.id            where users.id = users_cards.user_id            for xml path('')), 1, 1, '')    ) from users left join referees on users.refereeid = referees.id 	0.0368988119407242
17719626	35585	joins in postgresql	select prd.name, pkg.name, si.name    from products prd join product_package_link ppl     on prd.id = ppl.product_id join packages pkg     on pkg.id = ppl.package_id left join service_link sl     on ppl.id = sl.product_package_id left join service_items si     on si.id  = sl.service_item_id  where ppl.id = '3' 	0.763745353034228
17720674	9074	oracle + jpa - querying with interval	select x from myentity x where cast((systimestamp - (1/24/60) * 10) as timestamp) between lastupdated and systimestamp 	0.66585876411462
17722734	12413	how to compare starting time and end time of a 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
17723370	6995	trigger after on insert, error table mutation upon inserting record	select sum(price) into amount from learnerenrollcourse_view where learnerid = :new.learnerid and paid = 'n'; 	0.0633438000643739
17723581	3717	discard last 3 characters of a field	select reverse(substr(reverse(code), 4)) as code from yourtable; 	0.000261706440977914
17723750	7425	mysql order by the highest score	select   fl_poll.id_player, fl_player.lastname, fl_poll.score, 1 as type   from     fl_player       join fl_poll on fl_poll.id_player = fl_player.id   where    fl_poll.score >= (              select min(score) from (                select score from fl_poll order by score desc limit 3              ) t            ) union   select   fl_poll.id_player, fl_player.lastname, fl_poll.score, 2 as type   from     fl_player       join fl_poll on fl_poll.id_player = fl_player.id   where    fl_poll.score < (              select min(score) from (                select score from fl_poll order by score desc limit 3              ) t            ) order by case when type = 1 then score end desc, lastname 	0.00142242108593315
17723921	2241	sql statement for join but not in other table	select * from customer where id not in (     select customer_id from mailing where mailing_id = @mailing_id ) 	0.282168318335404
17724551	1653	eliminating duplicates.. and more fun	select distinct [loan identifier], [original unpaid principal balance (upb)] from totalacquisition 	0.720852387134737
17725418	2456	get a timestamp from concatenating day and time columns	select extract(epoch from (day || ' ' || time)::timestamp); 	0
17727058	10011	select data (join?) from only one table using an id from another table	select * from t1 where t1.id in (select distinct id from t2) 	0
17727206	27723	no column was specified for column [x] of [table] and invalid column name	select [monthlyavg] = avg(totals) from ( select [dateof] = [date] , [totals] = sum(assets)  from assets inner join funds on assets.fundcode = funds.fundcode where feegroupid = 17     and (([date] >= '1/1/2013')      and ([date] <= '4/1/2013'))      and ((funds.enddt >= '4/1/2013') or (funds.enddt is null)) group by [date] ) as monthlytotals 	0.000123524873819055
17728477	40881	checking against existing data before selecting	select item_no, barcod from table_2 where barcod not in     (select barcod from table_1) 	0.00542183663342621
17729889	31867	mysql group by with sorting	select d.*  from data_teste d inner join (    select `time`, max(provider) mp    from data_teste    group by `time` ) x on x.mp = d.provider      and x.`time` = d.`time` order by  `time` asc,            provider desc 	0.496736811565976
17730288	30227	mysql joins count matched record from another table	select t1.id, t1.name, count(*) as `count` from table1 t1 join      table2 t2      on t1.id = t2.ref group by t1.id, t1.name; 	0.00013827776326673
17730626	37972	how to pivot two date columns and fill in the gaps with multiple overlapping date periods	select a.employeenumber, b.date, a.absencetype, a.approved from table1 a join calendar b    on b.date between a.firstdayofabsence and a.lastdayofabsence 	0
17731979	29673	sum of count from external table	select d.id, d.title, sum(g.hits) from games g join      developers d      on g.id_dev = d.id group by d.id, d.title; 	0.00252149055856139
17732484	35913	sql server show only rows (all columns) with a distinct column name	select distinct rowid, ordernum, cdescription, thickness, ulltimberthickness, width, ulltimberwidth, length from yourtable 	0
17734650	33147	how to join a table multiple times using same column but related different tables? (mysql)	select     `sender_cities`.`city_name` as `from_city`,     `receiver_cities`.`city_name` as `to_city`,     count(*) as `count` from      `shipments` `ship`     inner join `senders` `s` on (`ship`.`sender_id` = `s`.`sender_city`)     inner join `cities` `sender_cities` on (`s`.`sender_city` = `sender_cities`.`city_id`)     inner join `receivers` `r` on (`ship`.`receiver_id` = `r`.`sender_city`)     inner join `cities` `receiver_cities` on (`r`.`receiver_city` = `receiver_cities`.`city_id`) group by      `from_city`,     `to_city` order by      `count` desc 	0
17735091	2122	join values in different rows into one cloumn	select `date`, `time`, `incident`, group_concat(`unit`)  from table group by `incident` 	0
17737027	12801	many to many represented as columns	select e.employee_id,        max(case when p.profile_name = 'employee' then 1 else 0 end) as employee,        max(case when p.profile_name = 'manager' then 1 else 0 end) as manager,        . . .  from employees e left outer join      employee_profile ep      e.employee_id = ep.employee_id left outer join      profile p      on ep.profile_id = p.profile_id group by e.employee_id; 	0.0290615499108077
17738599	22689	how to join mysql table	select distinct * from {$this->prefix}category c    left join {$this->prefix}category_description cd      on (c.category_id = cd.category_id)    left join {$this->prefix}category_to_store c2s      on (c.category_id = c2s.category_id)    left join {$this->prefix}url_alias u      on u.query = concat('category_id=', c.category_id) where c.category_id = '" . (int)$category_id . "'    and cd.language_id = '" . (int)$this->config->get('config_language_id') . "'    and c2s.store_id = '" . (int)$this->config->get('config_store_id') . "'    and c.status = '1' 	0.144134620104044
17738878	1704	date of monday of a given week, independent of nls	select trunc(sysdate, 'iw') - 7 previous_monday from dual 	0
17738938	26308	sql server query: how to select customers with more than 1 order	select  customerid ,       count(*) as order_count from    orders group by         customerid having  count(*) > 1 	0.0586694974593625
17739807	40300	oracle - select all where one of the columns satisfies predicate	select * from table where column is not null 	0.000318224000702074
17740132	13289	how to join 2 tables to get 1 tables?	select  p.productid,         b.name as buyer,         s.name seller from    table2 p left join         table1 b    on  p.buyerid = b.userid left join         table1 s    on  p.sellerid = s.userid 	0.000551331637056586
17740677	22492	mysql calculations avoiding duplicate values	select htno,         sum(total)               tech,         round(sum(total) / 2, 2) divi,         sum(tempcr)              cred,         sum(tempcr <= 0)         log,        sum(tempcr >  0)         pass,         sum(externals >= 0)      atm,         sum(externals <  0)      tot   from  (    select distinct *      from table1     where htno = 12 ) q 	0.0578263662876364
17740720	37076	getting the highest value of a status	select    a,    b, min(record_start_date) over (partition by a, b) as  min_record_start_date, record_end_date as max_record_end_date, status from tbl qualify     row_number()     over (partition by a,b           order by record_end_date desc) = 1 	0
17742157	8440	how do i get opening and closing balance for each productcode	select   (select top 1 balance as openingbalance     from stocktransfer     where productcode = st.productcode and transfertype = 'product'     and transactiondate between '2013-03-17' and '2013-03-22'    ) as opening balance,   (select top 1 balance as closingbalance     from stocktransfer     where productcode = st.productcode and transfertype = 'product'     and transactiondate between '2013-03-17' and '2013-03-22'     order by transactiondate desc    ) as colosing balance from   stocktransfer  st  where  transactiondate between '2013-03-17' and '2013-03-22'  group by productcode 	0.00249819350238536
17744137	32942	sql table how to adding array of numbers fetched from sql table	select sum(money) from customers    where country !="usa"; 	0
17748104	9815	get category on topic id	select topics.topic_cat,        topics.topic_id,        categories.cat_id,        categories.cat_name from topics, categories where topics.topic_cat = categories.cat_id       and topics.topic_id =:topid 	0.000170546995971867
17748893	16363	exclude myself from friendship page - mysql	select user.name_surname, user.id, friendship.receiver_id, friendship.sender_id from user join friendship on user.id = friendship.sender_id or user.id = friendship.receiver_id where (friendship.receiver_id =".$_session["ses_user_id"]." or friendship.sender_id  =".$_session["ses_user_id"].")  and is_approved='1' and user.id != ".$_session["ses_user_id"]." 	0.0389666805409847
17749591	29940	select rows where some values are not in other table	select t1.a, t1.b, t1.c from t1 inner join t2 on t1.x=t2.x where not exists (    select 1 from t3    where t3.a = t1.a and t3.b = t1.b ) 	0.000119757434963127
17750052	22869	aggregating data between two tables in mysql	select t1.zipcode, t1.keys, t2.character from table_1 t1 full outer join table_2 t2 on t1.keys = t2.keys 	0.00292450106301049
17750763	39223	"subquery returned more than 1 value" for select subquery	select      fh.shipdate,      avg(case             when vendorname = 'atlantic trucking'             then fh.[dist freight]             else null          end) as [atlantic freight charge],       avg(case             when vendorname != 'atlantic trucking'             then fh.[dist freight]             else null           end) as [non-atlantic freight charge] from      dbo.vw_freighthistory as fh group by      shipdate order by      shipdate 	0.075712765552216
17751712	37762	fetch id's that are related to a specific set of items, but not others	select service_id from t1 group by 1 having    sum(case when product in ('traffic', 'weather', 'travel') then 1 else -1 end = 3 	0
17752178	18559	if condition for date in mysql query with more tables	select u.user, 'sales',  case     when s.dateadded = s.dateupdated     then 'inserted'     else 'updated' end, case     when s.dateadded = s.dateupdated     then s.dateadded     else s.dateupdated end from users u join sales s on u.id = s.created_by 	0.0966425271566917
17753911	30679	how to get data from 3 tables in mysql?	select * from locations inner join country on `country`.`country.id` = locations.`country.id` inner join state on `state`.`state.id` = locations.`state.id` inner join city on `city`.`city.id` = locations.`city.id` 	0.000231387202730561
17756574	30269	tsql change grouping / count based upon dates	select         teams.code,        count(tasks.taskid) from      tasks      inner join teams on teams.teamid = tasks.teamid      inner join (                      select teamid, min(case when dateclosed < datesignedoff then dateclosed  else datesignedoff  end) mindateneeded                      from tasks                      group by teamid                 ) as firstcondition on firstcondition.teamid = teams.teamid where    tasks.duedate >= firstcondition.mindateneeded group by    teams.code 	0.000568749487718948
17757372	13613	use of double left join in a query returns different values	select id, paid, debit from table1 left join      (select reg_no, sum(debit) as debit       from table2       group by reg_no      ) table2      on table1.id = table2.reg_no left outer join      (select reg_no, sum(paid) as paid       from table3       group by reg_no      ) table3      on table1.id = table3.reg_no  order by table1.id 	0.415571324656687
17758346	24107	order rows of data table based on non null values of different columns in sql	select *  from table  where colc = 7 or colb = 2 or cola = 10 order by colc desc, colb desc, cola desc 	0
17759639	7231	get average of sum of the date difference in sql	select sum(datediff(mi,t.paydate,t.deldate)) as sum_min,        avg( convert(numeric(18,0), datediff(mi,t.paydate,t.deldate) ) ) as avg_min from transaction_tbl t where t.locid=5 group by t.vtid 	0
17760976	31919	subquery that uses a value from the outer query in the where caluse	select * from `tbl1` t1     where t1.`max_count` < (     select count(*) from `tbl2` t2     where t2.`id` = t1.`id`     ) 	0.46207437483562
17762514	19204	mysql search single and multiple subselects	select t0.* from test t0, test t1 where t1.id_user=1 and t0.id_user !=1  and abs(t1.x-t0.x) <= t1.y 	0.526008064517014
17762663	17182	find duplicate rows/records from table	select a.row_id, a.content, a.niche, cnt from table_name a join (   select min(row_id) m, count(*) cnt, niche,content   from table_name   group by content,niche   having count(*)>1 ) b   on a.niche=b.niche  and a.content=b.content 	0.000329219087782422
17762814	13323	group by and sort by biggest groups	select comment_id , count(*) as count from spam_reports  group by comment_id   order by count desc 	0.00829047707558711
17762817	16123	one record 27 times	select * from users where users.id = wall.author 	0.00214982901944283
17763727	35004	mysql selfjoin on minimal difference	select    p1.time as time1,   p1.lat as lat1,   p1.lon as lon1,   p1.rank as rank1,   p2.time as time2,   p2.lat as lat2,   p2.lon as lon2,   p2.rank as rank2 from (   select position.*,     @currank1 := @currank1 + 1 as rank    from position , (select @currank1 := 0) r    order by time desc) p1 join (   select position.*,     @currank2 := @currank2 + 1 as rank    from position , (select @currank2 := 0) r    order by time desc) p2 on p1.rank = p2.rank -1 	0.0146603979785513
17765137	30705	users with most comments from drupal + phpbb	select name, sum(commentcount) as totalcommentcount from (   select u.name, count(c.cid) as commentcount   from dr_users as u   inner join dr_comments as c on u.uid = c.uid   group by u.name   union all   select u2.username as name, count(c2.post_id) as commentcount   from phpbb_users as u2   inner join phpbb_posts as c2 on u2.user_id = c2.poster_id   group by u2.username ) temp group by name 	0.000617778351476475
17766418	10533	select query from xml data	select stuff((select ',' +  x.c.value('.', 'nvarchar(max)')  from (select cast(xmlstring as xml) as data from #temp) as t outer apply t.data.nodes('/response/error') as x(c)for xml path('')), 1, 1, '') as errors 	0.0264411889440681
17768567	26280	sql statement group by	select sp.name, sum(op.orderquantity) as totalqty  from sm_orderedproduct op     inner join sm_payment p on op.orderid = p.orderid      inner join sm_product pr on op.productid = pr.productid     inner join sm_sellerproduct sp on sp.productid = pr.productid where month(str_to_date( dateofpurchase, '%d/%m/%y' )) = 7 group by sp.name order by sum(op.orderquantity) desc  limit 4; 	0.691318188644685
17769326	25993	how to increment count in php with two conditions?	select id, position   from (   select id, if(@p = perc, @n , @n := @n + 1) position, @p := perc     from table1 t, (select @n := 0, @p := 0) n    order by perc desc ) q 	0.00733064302113199
17769500	41269	select messages, calculate the votes average and know if an user already have voted it	select  m.*, ( select count(1) from messages m1 where m1.id=m.id and m1.userid=@userid ) as votedalready, avg(votes) as average_valuation from messages m  group by m.id 	0
17769747	36361	sum of fields in condition of another filed duplicate ?	select item,sum(num) as num from yourtable group by item 	0.000456960093371231
17771079	23286	sql select query across 3 tables	select s.seatnum,        t.username   from q802d_vikevents_orderseats s,        q802d_vikevent_users vu,        mystery_third_table t  where vu.id = s.uid    and t.id = vu.ujid; 	0.0540264453641394
17771267	15272	putting math into the sql query	select fk_playerid, fname, lname, points, holes, points-2*holes diff from (     select  sum(ls.points) points             count(ls.dk_playerid) holes,             ls.fk_playerid, u.fname, u.lname     from {$prefix}_livescore ls     inner join {$prefix}_users u     on ls.fk_playerid = u.userid     where fk_gameid = $gameid     group by fk_playerid) x order by diff desc 	0.201434763900122
17773694	33678	returning results within latitude / longitude rectagle	select * from addresses where addresses.longitude between -80.33313094482423 and  -79.5290690551758 and addresses.latitude between 32.6420709033305 and 32.91052662576775 	0.784465710788089
17774773	39224	mysql query with one-to-many	select modelid, max(styleid),min(sequence) from mytable  group by modelid 	0.71412610196839
17775530	26065	select current option in select menu	select id, name from forums order by disp_position asc 	0.0148513062695094
17775961	29228	mysql query adding another condition	select photos.* from photos left outer join follows on photos.userid=follows.followingid where follows.followerid = $myid or photos.userid = $myid order by photos.id desc limit 10 	0.0899535330712074
17778512	31772	configure float with decimal in sql or force string to show decimal	select convert(decimal(9,2), price) from table 	0.118995860306698
17779368	355	select sum of a column between two dates	select dateadd(dd, 0, datediff(dd, 0, p_date)) [date],        sum(p_amount) [sum]   from tbl_payments  where dateadd(dd, 0, datediff(dd, 0, p_date)) between '20130701' and '20130731'  group by dateadd(dd, 0, datediff(dd, 0, p_date)) 	0
17780380	2431	how to get records of last month of this year,	select empcode,eventdate1 as eventdate,intime, case when outtime is null then 'n/a' else outtime end as outtime from     tms_hourcalc where  datepart(m, eventdate) = datepart(m, dateadd(m, -1, getdate())) and datepart(y, eventdate) = datepart(y, dateadd(m, -1, getdate())) and empcode='13658' group by empcode, intime,outtime, eventdate1,intime1      order by intime1; 	0
17780694	14243	oracle checking for existence of rows in a large table	select count(*) from   x where  id1 = :1 and        id2 = :2 and        rownum = 1; 	0.00199971723004869
17780868	31267	mysql - get days remaining	select * from tblpremiumlistings where created_date + interval `days` day >= curdate() 	0.000325425319194278
17781311	17389	select from three table on condition basise in mysql	select d.id, d.list_ref, coalesce(s.unit, r.unit) unit   from details d left join sale s      on d.list_ref = s.ref left join rent r     on d.list_ref = r.ref 	0.00573736633063409
17781438	21889	use like to search exact word in mysql	select * from table_name where column_name like 'ink %'      or column_name like '% ink'      or column_name like '% ink %' 	0.67624735023309
17784931	23067	display 3 maximum values of a column, include duplicate values	select name, mark  from mytable as t1      inner join          (select distinct(mark) as best_marks from mytable order by mark desc limit 3) as t2     on t1.mark = t2.best_marks order by mark desc, name asc; 	0
17786175	33276	decompose one row into multi rows according conditions	select id,a_kode as kode from t where a_kode<>0 union all select id,b_kode as kode from t where b_kode<>0 union all select id,c_kode as kode from t where c_kode<>0 union all select id,0 as kode from t where a_kode=0 and b_kode=0 and c_kode=0 	0
17786553	459	different results from grouping query	select t.col1, t.col2 from tbla t inner join (        select col1          from tbla         group by col1        having ((count(col1))>1);       ) tbl on tbl.col1=t.col1 	0.00849250803428633
17786622	32044	mysql how to get records to show in chat conversation list	select * , ( r.from + r.to ) as dist from ( select *  from  `cometchat` t where ( t.from =2 or t.to =2 ) order by t.sent desc )r group by dist order by r.sent desc 	0
17786633	28196	how to concat values which retrieved from database	select cast(datepart(dd,getdate()) as varchar(10))   +cast(datepart(mm,getdate()) as varchar(10))   +right(cast(datepart(yy,getdate()) as varchar(10)),2) 	0.00075469033588208
17787181	8467	how to get union of two tables with different alias	select a as first , null as second  from table1  union all  select null as first , a as second  from table1 	0.000646663874463952
17787817	20220	selecting each nth row does not work	select * from  (   select id,           @x := @x + 1 as rank   from realvalues, (select @x := 0) t ) a where rank mod 3 = 0 	0.00269774610745542
17788491	21715	converting two column result to one column result in sql	select hh=convert(varchar(10),(convert(decimal(10) ,@dec/60)))+':' +convert(varchar,@mns) 	0.000914041812108109
17789275	1270	how can i combine multiple rows into one during a select?	select stuff((select',' + col7 from #test for xml path('')), 1, 1, '' ) as col7 	0
17790036	30003	sql: find records with matching values on a set of columns	select m1.accid, m1.accname  from   mytable m1 join   ( select accid,accname           from mytable            group by accid,accname          having count(1) = 2          ) m2 on   m1.accid   = m2.accid              and  m1.accname =  m2.accname 	0
17792120	12335	sql statement to get a total for a given date range	select    cast(bookingdatetime as date) [date],    count(*) [bookings],    sum(bookingfare) [value] from t group by cast(bookingdatetime as date) 	0
17792354	31844	how to change a column name and display with special characters?	select ip_name, concat (first_name, ' ' ,last_name) as contact, ip_utilization as `usage_%` from database_name; 	0.00101763615757016
17792614	10206	trending sum over time	select distinct      date, user_id, sum(count) over (partition by user_id order by date) as count    from actions where   action in ('call', 'email'); 	0.0902768411130466
17794456	20179	left join and show the non-foreign key	select u.userid      , u.blah      , a.userid  as a_userid      , a.blah    as a_blah   from users u    left   join addresses a    on ... 	0.122784887739182
17794609	29005	query to find users who share same account number	select id, a.account from users u, (select account from users group by account having count(*)>1) a where u.account=a.account order by u.account 	0
17794870	35552	select from a sql table starting with a certain index?	select from table offset 50 limit 50 	9.26831084805406e-05
17795074	28280	create view with different names than the tables they are created from	select code as table1.code, value as table1.value from table1 	0
17796766	21040	how can i modify this query to add total count of 'questions' per survey, total correct and percentage correct?	select sq.question,        sc.choice,        sq.correctanswer,        sa.score,        count(*) over (partition by sq.surveyid) as totalanswers,        count(case when sq.correctanswer = 'right answer' then 1 else null end) over (partition by sq.surveyid) as correctanswers  from survey s  inner join surveyquestions sq on s.surveyid = sq.surveyid   inner join surveychoices sc on sq.questionid=sc.questionid  inner join surveyanswers sa on sc.choiceid = sa.choiceid  inner join tbllogin tl on sa.username = tl.username  where tl.username = 'johnsmith' and sq.surveyid = 12  order by sq.questionid 	7.66704879987388e-05
17799416	32834	calculating the percentage across multiple columns	select racerid, firstname, lastname, count(races.winningracerid) * 100.0 / (select count(1) from races) as winningpercentage  from     racers     left join races on racers.racerid = races.winningracerid  group by     racerid, firstname, lastname 	0.00049196935038303
17799501	26107	select only parents with one child	select top 4000 users.id from users join streams on users.id = streams.userid join playlists on streams.id = playlists.streamid where playlists.firstitemid = '00000000-0000-0000-0000-000000000000' and (select count(playlists.id) from playlists where playlists.streamid = streams.id) =1 	0.00038899367222081
17801819	10523	how to view the details of any specific item from database?	select products.*,product_description.* from products inner join product_description on (products.product_id=$id and product_description.product_id=$id) this will work definitely 	0
17804603	15775	mysql group by fetch last row	select * from (select * from conversation_1  left join conversation_2 on conversation_1.c_id = conversation_2.c_id     left join user on conversation_2.user_id = user.user_id     left join message on conversation_1.c_id = message.c_id     where conversation_1.user_id=1 order by conversation_1.c_id desc) finaldata group by message.c_id 	8.51237638787145e-05
17805684	39720	is there any better code (mysql or php) where i can fetch two table in one statement or query?	select e.votes, e.views, e.id, u.username from   election e join userinfo u using (id) where  e.electionid = ? 	0.624986803888747
17806193	40234	sql query to get the data	select s.student_id,        max(s.student_name) student_name,        max(s.father_name) father_name,        max(s.mother_name) mother_name,        count(distinct a.student_address_id) total_addresses,            count(distinct p.student_phone_id) total_phones from students s left join student_phones p on s.student_id = p.student_id left join student_addresses a on s.student_id = a.student_id where s.student_id = 7 group by s.student_id 	0.0143954258441825
17809246	28499	query on last modified time without a last modified column	select pid    from product   where scn_to_timestamp( ora_rowscn ) > '${dih.last_index_time}' 	0
17811522	17494	is there a function to get a minimum or the value in mysql?	select greatest(-1,1); -> 1 select greatest(20,1); -> 20 	0.00423415618549183
17811856	4065	flag / mark highest ranking record	select      team,     statcount,     teamrank,     (         case              when statcount = (select max(statcount) from @rank)                 then 'true'             else                 'false'             end     ) as 'highscore' from @rank order by team desc 	0.000310203353508659
17811896	36729	mysql - displaying unwanted repeat results in one-to-many relationship	select company.company_name, jobs.job_id, company.caddress,  jobs.job_name, jobs.job_description from company join company_job on company.company_id = company_job.company_id join jobs on jobs.job_id =  company_job.job_id order by company_job.job_id; 	0.281952431236092
17812142	7365	join table with order by and group by	select * from (     select c_id, user_id, message, state, time      from message      where receive=1      order by message_id desc) as t  left join user on user.user_id=t.user_id  group by c_id 	0.335981926276588
17812384	38904	use distinct with two columns (or something that works)	select distinct state, stateid from table 	0.339587740717295
17812449	4736	how can i concatenate(or merge) values from 2 result sets with the same pk?	select id,        case          when t1.flag is null then t2.flag          when t2.flag is null then t1.flag          else '(' || t1.flag || '/' || t2.flag || ')'        end as merged_flag   from table1 t1   full outer join table2 t2     using (id)   order by id 	0
17812997	14474	access data source using sql to show most recent entry per site	select top 1 ... 	0
17814342	26539	sql skip or ignore a specific cells	select nullif(column1, 999999999),         nullif(column2, 999999999),         nullif(column3, 999999999) from table 	0.0213613236576063
17814349	21665	trying to use id in mysql subsubquery	select rk.* from report_keywords rk inner join (     select campaign_id, sum(conv) as sumconv     from      (         select campaign_id, conv, @sequence := if(campaign_id = @campaign_id, @sequence + 1, 1) as asequence, @campaign_id := campaign_id         from report_keywords         cross join (select @sequence :=  0, @campaign_id := "") sub1         order by campaign_id, conv     ) sub2     where asequence <= 10     group by campaign_id ) sub3 on rk.campaign_id = sub3.campaign_id and sub3.sumconv >= 30 where rk.report_id = 231 	0.247276062689327
17814771	15914	dynamic navigation from database	select * from categories     inner join subcategories on subcategories.parentcatid = categories.catid and subcategories.active = 1 where categories.active = 1 group by categories.catid 	0.100174259712536
17816555	2115	count distinct elements and return only one	select  count(distinct data) as cnt, (select data from data_table group by data     where param='xxx'     order by rand() limit 1) as random from data_table where param='xxx' 	0
17819327	3280	best approach to handle multiple select statements in a single trip to the database	select [your selected columns] from (select * from table1 where [conditon for table1]) t1 inner join (select * from table2 where [condition for table2]) t2 on 1=1  inner join (select * from table3 where [condition for table3]) t3 on 1=1 	0.0585188052275421
17819707	9836	combining rows and taking averages	select sector, max1,avg1,max2,avg2,numb from tab where sector not in ('m','n') union all select 'x' as sector, max(max1),avg(avg1),max(max2),avg(avg2),avg(numb) from tab where sector in ('m','n') 	0.00592006346982543
17819796	11834	is there a way to query a column for the number of times the current records value for that column exists?	select a.id, a.col1, b.expr1 from mytable a inner join (     select col1, count(col1) as expr1     from mytable     group by col1 ) b on a.col1 = b.col1 	0
17820190	200	group rows by value but only displaying the newest row in group result	select    user_id,   count(user_id) total_apps,    sum(case  when approved = 0 then 1 else 0 ) unapproved_apps  from applications group by user_id 	0
17821270	36899	run a query so that all values in any category that contains "important" come first	select my_table.* from my_table join (   select   category, sum(importance='important') number_important   from     my_table   group by category ) t using (category) order by t.number_important desc, category, importance 	0
17821974	35451	count value from table column	select count(*) total   from pivot   where category_id in (1, 2)    and color_id in (    select color_id     from color    where color = 'black'        or color2 = 'black' ) 	0.000326925781826631
17822531	19050	query, where field contains 2 t's	select * from table where field like '%t%t%' and field not like '%t%t%t%' 	0.0452388453350711
17822716	30555	simple aggregation/ joining of tables	select account_number, count(*)-1 as flag from (   select account_number from a     union all   select account_number from b ) ab group by account_number; 	0.356322602469599
17824235	13484	combine columns from different tables (sql server)	select isnull(ab.id, c.id) as [id], ab.col_a, ab.col_b, c.col_c from (     select isnull(a.id, b.id) as [id], a.col_a, b.col_b     from @a a     full outer join @b b         on a.id = b.id ) ab full outer join @c c     on ab.id = c.id order by isnull(ab.id, c.id) 	0.000211247455941409
17825216	21794	querying using two attributes in xml column	select documentstoreid, doctemplateid, personid, document from documentstore where datacache.exist('/componentcache/component[contains(@name, "encount_dxdesc")][@value="def"]')=1 	0.00883719630041761
17826424	21202	using % is in condition	select * from table where column like  '%val%' or column like '%ab%'; 	0.570227595216703
17828018	37578	how to select record in msql which starts with a name and folowed with digits	select * from yourtable where yourcolumn regexp '^name[0-9]+' 	0.000197109634702034
17828064	18273	how to get the row in some column in one table	select year,month,date, rain, tmax,timin       from yourtable  where location='air' and id_stat='98212'; 	0
17828883	17220	how do i select the first odd/even numbered primary key in a sql database	select id from table where mod(id, 2) = 1 order by id limit 0, 1 	0.000472350635821162
17829280	24313	need a query to insert 'level' into an adjacent list	select id,        node,        parentid,        dense_rank() over(order by parentid) as level         from table_name 	0.0779486989771643
17829383	8376	mysql - multiple incorrect date format stored	select case when a.rentalstart like "%/%/% %:%"             then str_to_date( a.rentalstart, '%d/%m/%y %k:%i' )             when a.rentalstart like "%.%.% %:%"             then str_to_date( a.rentalstart, '%d.%m.%y %k:%i' )             else cast(a.rentalstart as datetime)        end as rentalstart_good,        a.* from ... 	0.510945513144214
17830941	10190	mergin one stored procedure to another in sql	select @keylocation= e1.ename  from transaction_tbl t join employeemaster_tbl e1 on e1.ecode = t.ecode and t.status = 1  or e1.ecode=t.delecode and t.status=4 	0.0417431555062707
17832199	29733	migrate data from relational db to nosql	select * from 	0.0440401267409694
17832906	21780	how to check if field is null or empty mysql?	select if(field1 is null or field1 = '', 'empty', field1) as field1  from tablename 	0.0550226005836623
17833176	25777	postgresql: days/months/years between two dates	select age('2010-04-01', '2012-03-05'),        date_part('year',age('2010-04-01', '2012-03-05')),        date_part('month',age('2010-04-01', '2012-03-05')),        date_part('day',age('2010-04-01', '2012-03-05')); 	0.00583624128432637
17833515	35944	mysql select boolean based on whether record exists in another table	select entity.*,           case when userssavedentity.user_id = '$user_id'                 then 1                 else 0            end as favourite from entity  left join (select *             from savedentity where savedentity.user_id = '$user_id')             as userssavedentity            on entity.id = userssavedentity.entity_id 	0
17834271	35846	show a colum of the last row of table?	select top 1 id from $table order by id desc limit 1 	0
17834350	1952	mysql crosstab wrong sum total	select prtype , a , b , c , sum( a +b +c) as total from (       select ifnull(prtype,'total') as prtype ,       sum(if(office ='a',`data`, 0)) as a,       sum(if(office ='b',`data`, 0)) as b,       sum(if(office ='c',`data`, 0)) as c       from tblgetdataall_1       group by prtype ) t       group by prtype 	0.256876711972677
17835643	25645	check if table contatins a sepecific value in one of the columns	select * from table where [column 1]='eee' or [column 2]='eee' or [column 3]='eee'; 	0
17836047	14199	select a column and add its amount with other rows	select sum(yourcolumn) as sum from yourtable 	0
17836215	40182	using a cursor to create a counter in sql	select yt.*, @counter := case when @prev_x != x_id or @prev_date != `date` then 1 else @counter + 1 end as counter, @prev_x := x_id, @prev_date := `date` from yourtable yt , (select @counter:=1, @prev_x:=null, @prev_date:=null) vars order by x_id, `date`, num, p_id 	0.547022727334636
17836634	13214	.net convert the contents of a datatable to another datatable with a different schema	select   cast (locationnamelocationname as varchar(...) as locname , locx  as xcoord , ... from sourcetable 	0.000348622135295276
17837131	31768	mysql ignore query results with column that appears more than once	select name, gross from   daysheet d1 where  gross = 50 and    1 in (select count(name)              from daysheet d2              where d2.name = d1.name) 	0.00186982856437231
17837138	31840	float values in sqlserver	select case isnumeric(col_1)     when 1 then cast(cast(col_1 as decimal(20,10)) as varchar(50))     else col_1 end 	0.0528175533593647
17837730	18995	join a string and a column	select 'test', column_name from table1 	0.0586251855798431
17838175	3978	faster way of selecting a row from 3 tables using same id#	select   address_contact.id,   address_contact.lastname,   address_contact.firstname,   address_contact.primaryaddtype,   address_address.id,   address_address.phone1,   address_address.phone2,   address_address.line2,   address_email.id,   address_email.email from   address_address   left join address_contact on address_address.id = address_contact.id    left join address_email   on address_address.id = address_email.id                     where address_contact.id = (     select id from address_contact order by lastupdate desc limit 1   ) 	0
17838944	32172	how to get the count of group	select 1 as [num], 'a' as decode, count(*) as [count] from my_table where [group] like '%1%' union select 2 as [num], 'b' as decode, count(*) as [count] from my_table where [group] like '%2%' union select 3 as [num], 'c' as decode, count(*) as [count] from my_table where [group] like '%3%' union select 4 as [num], 'd' as decode, count(*) as [count] from my_table where [group] like '%4%' union select 5 as [num], 'e' as decode, count(*) as [count] from my_table where [group] like '%5%' 	0.00137419771275125
17841402	9451	how to/possible to generate string of table based row values for contains search string?	select *  from table1 t1 where exists(     select 1 from table2 t2     where t1.firstname like t2.attribute ); select t1.*,        ( select listagg( ''''||t2.attribute||'''', ' or ' ) within group (order by t2.attribute )          from table2 t2          where t1.firstname like t2.attribute        ) contains_argument from table1 t1 	0
17842033	26698	querying xml rows for new non-xml rows	select  nodes.child.value('@key','varchar(100)') from    ##xml a         cross apply a.value.nodes('/animals') as nodes(child) 	0.00127687562453666
17842104	18210	show two colum from two tables in mysql with a union	select  receipts.datenew as date,  tickets.ticketid as ticketid,  payments.payment as payment,  payments.total as total,  customers.name as name,  (select adjustments.adjustment_reason from adjustments where adjustments.adjustment_type != 'adjustment' and adjustments.adjustment_reason != '') as reason from receipts  inner join tickets on receipts.id = tickets.id  inner join payments on receipts.id = payments.receipt  inner join customers on tickets.customer = customers.id where  (payments.payment = 'debt'  or payments.payment = 'debtpaid') union select   adjustments.date as date,  adjustments.ticket_no as ticketid,  adjustments.adjustment_type as payment,  adjustments.adjustment_amount * -1 as total,  adjustments.customer_name as name,  adjustments.adjustment_reason as reason from adjustments  order by name asc, date desc 	0
17842188	16081	tagging hierarchy and search	select     tags.id,     tags.tag,     parent_tags.id,     parent_tags.tag,     parent2_tags.id,     parent2_tags.tag, from     tags inner join     tags as parent_tags on     tags.parentid = parent_tags.id inner join     tags as parent2_tags on     tags.topparentid = parent2_tags.id where     tags.id=$id 	0.717707104085451
17842285	8476	sql left join: selecting the last records	select projects.id from projects   left join     (select comments.projectid         from comments       group by comments.projectid       having datediff(now(), max(comments.postedon)) < 30) as c   on projects.id = c.projectid   where c.projectid is null; 	0.000487342275194715
17844590	39624	sql group by two columns using sum on one column	select   'npi' as company         , b.acct_desc as description          , left(a.mn_no,5) + '-' + left(a.sb_no,4) as account         , right(left(a.trx_dt,6),2) as month         , sum(a.trx_amt) as total from data.dbo.gltrxfil_sql gltrxfil_sql a join data.dbo.syactfil_sql syactfil_sql b      on   a.mn_no = b.mn_no       and  a.sb_no = b.sb_no  where   a.trx_dt>=20130101     and a.trx_dt<=20130630      and b.fin_stmt_tp = 'p' group by  b.acct_desc         , left(a.mn_no,5) + '-' + left(a.sb_no,4)         , right(left(a.trx_dt,6),2) order by  left(a.mn_no,5) + '-' + left(a.sb_no,4)         , right(left(a.trx_dt,6),2) 	0.000184273873131274
17844684	28071	mysql select distinct column a with the min value of column b and relevant column c	select columna, columnb, columnc from table where columnb = (select min(columnb)         from table as t         where t.columna = table.columna) 	0
17844904	35833	comparing a variable to a column's default value in oracle procedure	select table_name||'.'||column_name, data_default into tablevariable, defaultvariable from all_tab_columns where table_name=:mytable and column_name=:mycolumn and data_default is not null 	0.00334582191975358
17845175	37582	select list of element and if they have same date, take the most current	select name, idperson from person   inner join period   on person.idperiod = period.idperiod where period.startdate =  (   select min(startdate)   from period as per     inner join person as p    on p.id = per.id   where p.name = person.name ) 	0
17845232	4151	what table a column is keyed to	select       [column name] = c.name     , [data type] = t.name     , [max length] = c.max_length     , c.is_nullable     , [primary key] = isnull(i.is_primary_key, 0)     , isfk = isnull(fkc.parent_object_id / fkc.parent_object_id, 0) from sys.columns c with(nowait) join sys.types t with(nowait) on c.system_type_id = t.system_type_id and c.user_type_id = t.user_type_id left join (      select i.[object_id], ic.column_id, i.is_primary_key      from sys.indexes i with(nowait)      join sys.index_columns ic with(nowait) on ic.[object_id] = i.[object_id]            and i.index_id = ic.index_id      where i.is_primary_key = 1 ) i on c.[object_id] = i.[object_id] and c.column_id = i.column_id left join sys.foreign_key_columns fkc with(nowait) on fkc.parent_object_id = c.[object_id]       and fkc.parent_column_id = c.column_id where c.[object_id] = object_id('table_name') 	0.17678628211783
17845555	33185	mysql max value from 3 different columns	select id from tablex where greatest(column1, column2, column3) > 69 	0
17846165	19703	sql server combine multiple queries on same table into single resultset	select a.ldtime      , avalue = max(case when a.parameteridx = 18 then a.value end)      , bvalue = max(case when a.parameteridx = 19 then a.value end) from         table7 g inner join table1 a inner join table2 b on a.datasetidx = b.datasetidx inner join table3 c on b.retrievalidx = c.retrievalidx on g.actionidx = c.actionidx inner join table4 d on g.spatialrefidx = d.spatialrefidx inner join table5 e inner join table6 f on e.stationidx = f.stationidx on d.spatialrefidx = e.spatialrefidx where f.stationidx = 1 and a.parameteridx in (18, 19) and a.ldtime between '2013-7-24' and '2013-7-25' group by a.ldtime order by a.ldtime 	7.08236429663523e-05
17846173	20791	mysql query countdown until date expiration	select datediff(expiry_date,now()) as days  from my_subscriptions where user_id = '[user_id]'; 	0.0312678154689972
17846414	13417	mysql: sql and db for product with multiple categories	select * from  (     select * from category_map      where category_id=1 ) as map  inner join products  on products.id = map.product_id; 	0.0601290496437398
17846609	37737	mysql - php select table with calculated relation	select username,    sum(case when module = 1 then value*percentage/100 end) as module1,   sum(case when module = 2 then value*percentage/100 end) as module2,   sum(case when module = 3 then value*percentage/100 end) as module3 from tablename group by username 	0.0764581079338996
17846916	36819	curdate() +7 days as a constraint	select order_no,         so_line,         date_item_prom,         date_ship,         part,         qty_ordered,         qty_shipped   from v_order_lines   where date_item_prom < curdate() - interval 7 day 	0.00062663821758726
17847130	33155	php/mysql create sort algorithm data schema	select r.*, a.* from reviews r inner join authors a     on r.authorid = a.id where reviewtext like '%str%' order by     if(lastedited >= current_date, lastedited, '0000-00-00') desc,     (some expression evaluating date and reputation) desc 	0.0509980539624224
17848143	40077	when accessing a db2 database via cobol, how can one set the isolation level, fetch size, scroll type and concurrency? (among other performance tips)	select * from my.testtable with ur; 	0.00496048195657378
17848886	5425	sql server group by sum function	select     code,     sum(itemcount) itemcount,     type,     (select sum(amount) from yourtable) amount from     yourtable group by code, type 	0.782787410976577
17848903	15602	query to show foreign key	select (select protocal from radio where id=equipemnt.radio1 ) as radio1, (select protocal from radio where id=equipemnt.radio2 ) as radio2, (select protocal from radio where id=equipemnt.radio3 ) as radio3 from equipment 	0.00186084656245793
17849274	16488	sql query to show data that exactly match criteria in another table's column	select t1.user,t3.matchid,t3.itemtype as itemtype,t2.item as item  from table1 t1 inner join table2 t2 on t1.item = t2.item inner join table3 t3 on t3.itemtype = t2.itemtype inner join (select user,matchid from  (select group_concat(itemtype order by itemtype) as typestomatch , matchid from table3 group by matchid) abc inner join (select a.user, group_concat(distinct b.itemtype order by b.itemtype) as typesofpeople from table1 as a inner join table2 as b on a.item = b.item group by a.user order by b.itemtype) def on abc.typestomatch = def.typesofpeople) xyz on xyz.user = t1.user and xyz.matchid = t3.matchid; 	0
17850031	21144	joining three sql tables?	select *  from    tenant_statements t inner join          (             select *              from leases             group by tenant_id             order by lease_id         )l on t.tenant_id = l.tenant_id inner join         tenants ts  on  t.tenant_id = ts.tenant_id where   t.date = '$date' and     t.property = '$property' order by    t.balance desc 	0.0666111262303883
17850422	21557	sql selecting random records to fulfill category	select    x.* from    (values       ('easy', 5), ('medium', 15), ('hard', 5)    ) d (difficulty, qty)    cross join (values       ('math'), ('science'), ('language'), ('history')    ) s (subject)    cross apply (       select top (d.qty)          q.*       from          dbo.questions q       where          d.difficulty = q.difficulty          and d.subject = q.subject       order by          newid()    ) x 	0.000148107367030756
17850623	33233	all conditional data required in mysql	select      z.id,     a.name,     a.value,     c.bcd,     b.abc from      (         select             distinct y.id id         from             (                 select id from a                     union all                 select id from b                     union all                 select id from c             ) y          ) z     left join a on z.id = a.id     left join b on z.id = b.id     left join c on z.id = c.id where z.id = 3 	0.16187836141993
17850846	26074	how i get all brothers in 1 sql or 2?	select * from `p` main left join `p` helper on helper.categories_id = main.categories_id where main.id = 3 	0.0017514743296279
17851794	17783	how get file name from full path in select?	select right('d:\akagane2\source\submodule\extracttext.vb', position('\' in reverse('d:\akagane2\source\submodule\extracttext.vb')) -1 ); 	0.00267934572452813
17852444	1546	select distinct multiple columns mysql	select make, model, year, count(distinct color) as number from colors group by make, model, year limit 10 	0.00892646909864845
17852886	31804	count and rownumber	select * from     (select cusid,row_number() over (order by cusid) r, count(case status when 'paid' then 1 else null end)  as numoforderspaid from table1 group by cusid) x where x.r between 1 and 2; 	0.489318031787695
17853863	27223	how to get combined output from a inner subquery?	select      a ,   b ,   c ,   case a when 773 then d else null end as d ,   case a when 808 then e else null end as e ,   case a when 809 then f else null end as f from table_name ; 	0.0375672122786093
17853888	2648	sql query count elements in other table	select         p.*      , cnt = isnull(m.cnt, 0) from dbo.projects p left join (      select proid, cnt = count(1)       from dbo.milestones      group by proid ) m on m.proid = p.proid 	0.00172882713373414
17853916	6791	self joining table view	select l1.* from lead l1 left join lead l2 on l1.date < l2.date and l1.lead_id = l2.lead_id where l2.id is null 	0.38735481162392
17854509	32745	how do i get the cummulative total of equation in mysql statement	select     *,     <formula> as ranking     <formula> / (         select sum(<formula>)          from table         where field = :field     ) as rankingpercentage from table where field = :field group by id 	0.00534262779170505
17854610	1034	get total number of rows from subquery?	select row1, row2, @rn as numrows from (     select b.row21, count(b.row21) as hits, @rn := @rn + 1     from table2 b cross join          (select @rn := 0) const     where b.row22 = 'foo' or b.row22 = 'bar'     group by b.row21     having hits = 2 ) as b inner join table1 as a on (b.row21 = a.row1) where row2 = 123 limit 10; 	0
17854763	18331	making sql query to get first id of a tourist and then all of it's surcharges	select t.tourist_id, t.name,    stuff((     select cast(',' as varchar(max)) + cast(tec.extra_charge_id as varchar(max))     from tourist_extra_charges tec     where tec.tourist_id = t.tourist_id     order by tec.extra_charge_id     for xml path('')     ), 1, 1, '') as charges from tourist t; 	0
17859043	27191	mysql: getting a count of all the data, daily, for the last 365 days	select count(*) as totalrows, date_formate("%y-%m-%d",firstcreated) as firstdate      from table_name            where date_formate("%y-%m-%d",firstcreated) in ("2012-01-01" and "2012-12-31")           group by firstcreated; 	0
17859310	22403	outer reference error when grouping month and years	select      f.name,     month(cddh.dategiven) as date_month,     year(cddh.dategiven) as date_year  from calculateddrugdistributionhistory cddh inner join facilityindividuals fi on fi.facilityindividualid = cddh.facilityindividualid inner join facilities f on fi.facilityid = f.facilityid group by      f.name,     month(cddh.dategiven),     year(cddh.dategiven)  order by     f.name,     date_month,     date_year 	0.278310845545856
17861502	10512	"group" some rows together before sorting (oracle)	select t.id      , t.date   from mytable t   join ( select s.id               , max(s.date) as most_recent_date            from mytable s           where s.date is not null           group by s.id        ) r     on r.id = t.id  order     by r.most_recent_date      , t.id      , t.date 	0.0360905159205703
17862823	10515	suppress a duplicate row in sql server 2005 based on condition and list remaining rows that don't meet the condition	select shpmnt_no, tot_weight, max(hazard) as hazard from mytable group by shpmnt_no, tot_weight 	0
17863580	34324	grab stream from specific user id	select idphoto, iduser, title from photos where iduser = $iduser; 	0.000116729814235481
17863752	22800	how do i find which rows don't have at least one column marked true, grouped by another column	select binnumber from mytable group by binnumber having max([primary]) = 0 	0
17864848	19222	sql select distinct values from multiple tables	select distinct *  from old a join new b on a.manname = b. manager_name and a. mannumber = b. manager_number 	0.000858578370133616
17865618	32867	subtracting timestamps in oracle db	select * from table where last_time_used - prev_time_used >= interval '2' hour 	0.00957445096332269
17866031	39145	combining 2 tables with no dates in common	select * from ( select  rc1.caseid,  rce.ecodat as date,  rce.grossoil,  0 as productionamount from phdrpt.reportcaselist_465 as rcl  inner join phdrpt.rptcaseeco_465 as rce   on rcl.reportruncaseid = rce.reportruncaseid union  rc1.caseid,  cmp.productionmonth as date,  0 as grossoil,  cmp.productionamount from phdrpt.reportcaselist_465 as rcl  inner join casemonthlyproduction as cmp   on rcl.casecaseid = cmp.casecaseid ) order by date 	0.000186282995507875
17866113	1403	convert a date to timestamp in a join with interpolation	select     b.code, b.t, a.item_id from b left join (select a.t::date, a.code, a.item from a) a on a.code = b.code     and b.t interpolate previous value a.t; 	0.0282791516794934
17866284	17607	check if two ids exist in a mysql table	select iduser, followingid from following where iduser = $id and $followingid = followingid 	0.000105704098340891
17866395	32976	error while getting values between dates	select  convert(varchar,creation_date,105) as 'creation_date', count(pat_id) from patient_ref_master where           (convert(varchar(10),patient_ref_master.creation_date,111)  between '2013/07/23' and '2013/07/25') group by creation_date 	0.0284149131321672
17866569	17970	copy the result set into another table	select basescore, count(*) cnt  into log2 from log      group by basescore 	0.000119898768129273
17869060	39969	sorting records on the basis of number of items in a group- sql server	select product_id, item_name, item_description, item_number from product  order by count(1) over (partition by product_id) desc 	0
17869510	7258	mysql: select multiple if(field='x' max(time) / if(field='y' min(time)) values in a single statement	select agent,        date,        min(dur)                       as total_duration,        timediff(min(maxt), min(mint)) as time_difference_between_login_and_out,        min(maxt)                      as logout_time,        min(mint)                      as login_time from   (select agent,                date,                if(agent_state = 'ready', sum(time), null)     as dur,                if(agent_state = 'logged-in', min(time), null) as mint,                if(agent_state = 'logout', max(time), null)    as maxt,                agent_state         from   t_cisco_agent_state_details         group  by agent,                   date,                   agent_state) as subq group  by agent,           date 	0.735355596628806
17870695	9318	how can i return a result set of records with duplicate columns in sql	select first_name, last_name, count(*) as dupecount  from table group by first_name, last_name having count(*) > 1 	0
17871145	6442	sql avg (average) returns lots of digits	select cast(avg(price) as decimal(6, 2)) from product where productname = 'shoe'; 	0.0175822662130325
17872133	27509	summarizing three variables using sql	select t1.author as author1, t2.author as author2, t1.year, count(*) as `count` from t t1 join      t t2      on t1.book = t2.book and         t1.author < t2.author group by t1.author, t2.author, t1.year order by t1.author, year; 	0.510565304541753
17872167	25007	combining 2 tables to produce 1 output - sql	select temp.candidate_no,        c.candidatename,        temp.[sum],        temp.rank from candidate c inner join (select   sum,candidate_no,@currank := @currank + 1 as rank from        (select      sum(score) / 5 sum,candidate_no           from        score            where category_no='$category_no1'           group by    candidate_no         ) a, ( select @currank := 0 ) r order by    sum desc,candidate_no desc limit 5) as temp on c.candidate_no=temp.candidate_no 	0.0281438683449302
17872655	14330	mysql same query multiple tables	select d.docdate, a.total totala, b.total totalb   from (   select docdate      from tablea    union   select docdate      from tableb ) d left join  (   select docdate, count(*) total     from tablea    group by docdate ) a on d.docdate = a.docdate left join (   select docdate, count(*) total     from tableb    group by docdate ) b on d.docdate = b.docdate  order by d.docdate 	0.0206581156654488
17873135	553	java query for retrieving records not in the foreign key table	select room_no    from room   where room_no not in          (select room_no             from booking            where hotel_no = singapore_hotel_no) 	0.000156372073732693
17873186	6166	mysql, reformat data inside select sentence	select a.comlum_01,  date_format(str_to_date(a.comlum_01, '%m/%d/%y'), '%y%m%d') as new_comlum  from table_01 a; 	0.70962776290053
17875144	1790	how to select one value group with mysql	select min(article_id) as `article_id`     from `table1`    group by `string_value` 	0.00480060617993519
17876617	16046	select rows where dates are equal and id's are equal and count these rows as one	select brand_name, count(*) as num  from (select substring_index(new_name, ':', 1) as brand_name  from table  where date<='".$american_today."' and date>= '".$two_weeks_ago."'  group by day(date), products_id)  as brands  group by brand_name order by num desc limit 5 	0
17877110	36275	repeated results on mysql joins	select distinct companies.id, companies.business_number, companies.country_iso_3, companies.profile_img, companies.short_url, companies_details_en.company_name from companies join companies_details_en on companies_details_en.company_id = companies.id left join companies_main_activity_tags on companies_main_activity_tags.company_id = companies_details_en.company_id where ( companies.id = '1' or companies.id = '3' or companies.id = '4' or companies.id = '5' or companies.id = '7' or companies.id = '20' or companies.id = '21' or companies.id = '22' ) and ((companies_main_activity_tags.val like '%xxxx%') or (companies_main_activity_tags.val like '%yyyy%') or companies_main_activity_tags.lang = 'en') and companies.id = companies_details_en.company_id and companies.id = companies_main_activity_tags.company_id limit 0 , 30 	0.41343888777931
17877209	8936	sql query for converting string to date in gridsql 2.0	select to_char(to_date(start_date,'dd-mon-yyyy'), 'dd-mon-yyyy') from table_name order by to_date(start_date,'dd-mon-yyyy') asc 	0.0591687052818066
17879250	29329	php + dynamic sql queries	select column_name  from information_schema.columns  where table_schema = 'database_name' and        table_name = 'table'; 	0.744806943315276
17879615	5042	sql select rows but remove records with duplicated phone number	select a.* from (select limit 10000 phonenumber, max(applicationid) as maxaid       from application a       group by phonenumber       order by max(aid) desc      ) list join      application a      on a.applicationid = list.maxaid order by applicationid desc; 	0
17879971	35437	mysql select users wich have birthday current month	select     * from     yourtable where     month(str_to_date(yourdatefield, '%d/%m/%y')) = month(now()) 	0
17881760	4256	is this mysql query correct for getting data from two tables	select r.root_cat_name,     r.root_cat_id,     s.sub_cat_name,     s.sub_cat_id from root_category as r inner join sub_category as s on r.id = s.root_cat_id order by r.id desc 	0.0913339269423348
17882148	18613	collect the sum of combined values	select     c.id, m.balance, sum(chg.balance) as combinedbalance from      customer c         inner join     chargetemplate chg         on c.id = chg.customerid group by      c.id, c.balance having      m.balance != sum(chg.balance) order by     c.id asc 	0.00147580925960962
17882982	15062	mysql count within select or count within subquery	select `p`.`id`,         `p`.`parentid`,         `p`.`commenterid`,         `p`.`userid`,         `p`.`post`,         `p`.`date`,         `p`.`tags`,         case           when ( `p`.`userid` = `p`.`commenterid`                  and `p`.`parentid` is null ) then 'true'           else 'false'         end as ismain ,         cnt.count1 from   `wallposts` `p`         left join `wallposts` `c`                on `c`.`parentid` = `p`.`id`         left join `users`                on `users`.`id` = `p`.`commenterid`         left join (select count(`p`.`id`) as count1,parentid from `wallposts` `p` where parentid is not null group by parentid) cnt on                    cnt.parentid = p.id group  by `p`.`id`  having `ismain` = 'true'  order  by `p`.`date` desc  limit  20 ; 	0.366713497501521
17883436	40577	how to get the following join query	select t1.col1, t2.col2, t2.col3   from table1 t1   left join table2 t2 on t1.col1=t2.col1 ; 	0.0852051218245024
17884096	9848	join with 3 tables linked as parent child	select *  from m_trd trd left outer join c_sub    sub on trd.sk_trd = sub.sk_trd  left outer join c_subdet det on sub.subid  = det.subid 	0.00885773230882185
17886292	12895	sql aggregation query	select firstdate, rank, sum(vote) votes from (     select @first_date := case when rank = @prev_rank                                then @first_date                                else date                           end firstdate,            @prev_rank := rank currank,            data.*     from (select @first_date := null, @prev_rank := null) init     join (select date, rank, vote           from mytable           order by date) data     ) grouped group by firstdate, rank 	0.728622682006419
17887637	1723	getting month from a table according to the selected month	select * from patient_ref_master where month(creation_date)=1  	0
17889632	5533	using group by in mysql join table	select q.* from ( select patient . * , visit.uid as visit_uid from patient left join visit on patient.uid = visit.patient_id order by visit_uid desc  ) q group by q.uid order by q.visit_uid desc  limit 0 , 10 	0.364946453076056
17890215	20250	mysql averaging joined table	select sr.salon_id, sr.category_id, avg(sr.rank) from salon_ranks sr inner join categories c on sr.category_id = c.id group by sr.salon_id, sr.category_id 	0.0152926156250587
17892591	3270	proportional where statement in mysql applying to datetime field	select `rows`.* from `rows` where timestampdiff(second, updated_at, created_at)<timestampdiff(second, now(), created_at)*25/100; 	0.606833543797573
17892865	8657	mysql - ordering by a factor obtained by moltiplying a related column by a habtm	select * from (select p.*, computed       from photos as p       left join (select pt.photo_id, sum(count) total                  from photos_tags pt                  join visits v                  on v.tag_id = pt.tag_id                  group by photo_id) as pt       on p.id = pt.photo_id       where p.id not in ( )       order by computed       limit 30) as t1 order by rand() 	0.336335956208709
17894558	38153	sql query - getting the sum of different varchar values	select string, count(*) as count  from table group by string 	0.000430357734387979
17895069	23272	group by id, select only the newest record for each	select   dailymean.station,   dailymean.flow,   dailymean.sortdate from   dailymean   inner join (     select station, max(sortdate) as maxdate from dailymean group by station   ) as tmp on dailymean.station = tmp.station           and dailymean.sortdate = tmp.maxdate 	0
17896785	16615	mysql get records from last 7 days	select     coalesce(sum(a.x), 0) as x,     coalesce(count(*), 0) as num from a as a where (a.`time` >= date_sub(curdate(), interval 7 day)) group by day(a.time) 	0
17897811	30027	sql/sql-lite - counting records after filtering	select id,        name,        (select count(*)         from sales_order         where customer_id = customer.id) as orders from customer where id in (select customer_id              from sales_order              where sales_representer = '100') 	0.00958538262577525
17898592	5595	retrieve records through inner join	select ru.* from rruser ru inner join rruser_group rg on ru.id = rg.user_id inner join rrgroup_permission rgp on rg.group_id = rgp.group_id inner join rrpermission rp on rgp.permission_id = rp.id where ru.active_flag='y' and rp.name='write' 	0.0225747225769705
17899009	7207	how to display dynamic mysql vertical data to horizontal using php	select  roleid as role, group_concat(distinct permid order by permid asc separator '|') as permissions  from role_perm  group by roleid  order by roleid 	0.00355153699055445
17901676	13068	query on postgres totaly holds down server	select p.part_name_id,        sum(p.quantity) as allquantity,         sum(p.price * p.quantity) as allprice  from parts.spareparts p group by p.part_name_id 	0.796915751911919
17902528	25401	get "non-existing" values from database	select   pfc.contentid as pfc_contentid,   pfc.content as pfc_fieldcontent,   pfc.fieldid as pfc_fieldid from pages p left join pagefields pf   on p.pageid = pf.pageid left join fields ptf   on pf.fieldid = ptf.fieldid left join pagesfieldcontents pfc   on p.pageid = pfc.pageid   and pf.fieldid = pfc.fieldid where some where-statement order by somefield desc 	0.000283872411625908
17903708	34573	sql match against multiple words	select * from contacts where match(firstname,middlename,lastname) against ('adam dustin') 	0.0588785019483129
17905691	13770	merge range into single column for mysql?	select verses_range.*, group_concat(verses.description) from verses_range inner join verses on     verses_range.chapter = verses.chapter where start<=verse and verse<=if(isnull(end),start,end) group by  id,chapter,start,end 	9.26320718566864e-05
17907494	36711	how to get sequence id of last inserted record in oracle 11g xe with php?	select id.currval from dual 	0
17908352	8483	double mysql request	select chat_from buddy from chat where chat_to=$username union select chat_to buddy from chat where chat_from=$username 	0.714332808700209
17908497	32520	join type for comparing two rows	select t1.person from   (select *    from attd    where status = 'member')t1 inner join   (select *    from attd    where status = 'not')t2 on t1.person = t2.person where datediff(dd,t2.date,t1.date)<=7 	0.00589831709043006
17912237	40571	mysql - find most popular two column value combination and sort by popularity	select count(*) as `rows`, food, brand    from `foods`      group by food, brand      order by `rows` desc 	0
17912707	11007	mysql sum and groupby in same query	select sum(amt), year, type from yourtable group by year, type 	0.100600275314466
17912970	19305	mysql query group by with multiple sum values	select year,    sum(case when type='a' then amt else 0 end) typea,   sum(case when type='b' then amt else 0 end) typeb from yourtable group by year 	0.0795928348783082
17914163	18158	how to add values that has the same id	select product_id, sum(sales) from table    group by product_id order by product_id 	0
17914496	6651	create a table with every possible input in sql server	select * from      (select distinct columninfo as foo     from testfilecolumnheaders  h     inner join dbo.testfilecolumninfo i on h.columnid = i.columnid     where columnname = 'foo') foo cross join      (select distinct columninfo as bar     from testfilecolumnheaders  h     inner join dbo.testfilecolumninfo i on h.columnid = i.columnid     where columnname = 'bar') bar cross join     (select distinct columninfo as baz     from testfilecolumnheaders  h     inner join dbo.testfilecolumninfo i on h.columnid = i.columnid     where columnname = 'baz') baz; 	0.0355284797351754
17914905	7032	sql query to subtract and sum in same time	select sum(value1-value2) as result  from tbl 	0.00198650311732212
17915547	22781	mysql join multiple columns with corresponding id	select u.user_id, t1.team_name as team_name1, t2.team_name as team_name2,        t3.team_name as team_name3 from users u left outer join      teams t1      on u.selection1 = t1.team_id left outer join      teams t2      on u.selection2 = t2.team_id left outer join      teams t3      on u.selection3 = t3.team_id; 	0.00170793380806558
17916266	881	mysql query - get total of sum from three different tables	select t.srecordid,sum(t1.fees)+sum(t2.fees)+sum(t3.fees) `sum fees` from srecords t left join cfees t1 on t1.feeid=t.srecordid left join ofees t2 on t2.feeid=t.srecordid left join ifees t3 on t3.feeid=t.srecordid group by t.srecordid 	0
17916656	29754	get total of columns if date is the same mysql	select `date`,sum(upsrc+updst) as  upstream ,sum(dnsrc+dndst) as downstream from flows_monthly_summary         where date >= '2013-07-01'          and date<='2013-07-04'  group by [date]         order by date desc 	0
17918222	26325	sub-select on mysql	select sum(case when f.cf_991 = '1' or g.cf_990 = '1' then a.totaltime end) as total_time , b.user_name, monthname(a.date) , sum(case when f.cf_991 = '0' or g.cf_990 = '0' then a.totaltime end) as total_time_2 from a  join c on c.id = a.id                                                                     join b on b.userid = c.userid     left join d on a.projid = d.projectid                                                                        left join e on a.account_id = e.salesorderid                                                           left join f on e.salesorderid = f.salesorderid                                                       left join g on d.projectid = g.projectid                                                                      where c.deleted != "1"  and year(curdate()) = a_column_containing_a_date and (        ( f.cf_991 = '1' or g.cf_990 = '1')       or        ( f.cf_991 = '0' or g.cf_990 = '0')     ) group by user_name,monthname(a.date); 	0.544916270057746
17918499	17666	count and join using access database	select companies.rep, companies.company, count(*) as [quote count]  from companies     inner join quotes on companies.ref = quotes.companyref  group by companies.rep, companies.company  order by count(*) desc 	0.603135905074246
17919468	16395	how to speed up mysql query? loading data from 3 tables	select a.*,         p.attribute_code,         p.attribute_value,         p.kategoria     from atributy a    join (select *            from atributy_value          inner join produkty              on produkty.attribute_value like concat('%', atributy_value.valuecode, '%')            and attributecode = '$atribut_kod'             and kategoria in ('$kategoria_sql')          group by atributy_value.value) p      on p.attribute_code like concat('%', a.code, '%')    and kategoria in ('$kategoria_sql')   group by a.value 	0.175962926978701
17920567	10063	select to include null or empty in the result	select id_extend, result     from  fq_account_extend_result     where id =5 and     id_extend in(1,2,3,4)     or result is null     order by id asc 	0.0780278920233621
17920604	33257	pulling data from a table using max and group by	select  * from    time_entries te join    (         select  user_name         ,       max(entry_datetime) as maxdt         from    time_entries         group by                 user_name         ) filter on      filter.user_name = te.user_name         and filter.maxdt = te.entry_datetime 	0.00077216204554818
17923211	24580	extracting values from xml in oracle pl/sql	select extractvalue(l_resp_xml                   , '                   , 'xmlns="http: into l_response_result from dual; dbms_output.put_line ( 'result> nonexistingwaybills=' || l_response_result); 	0.00411221489613138
17923437	6109	how can i retreive data from single table using group by clause	select  date(`datetime`) as dateonly , count(case when message= 'accepted images' then 1 else 0 end ) as accepted_image_count, count(case when message= 'rejected images' then 1 else 0 end ) as  rejected_image_count from customer_1.audit_trail where message in ('accepted images','rejected images')  group by dateonly  order by dateonly asc limit 100; 	0.00362738222340464
17923643	19117	merge two tables "below" eachother	select * from  table1 union select * from table2; 	0.0121461104780573
17923728	31975	ajax: get last row from database	select * from tablename order by tableid desc limit 1 	0
17926542	7197	how to create sql script that generates insert statements with tables data in mysql/mssql	select concat ("insert into `country` (`country`) values (\"", country, "\");") from country order by id; 	0.255900454920258
17927206	30608	how to calculate date range in sql using interval	select [icps].[dbo].[tickets].t_vrm,[icps].[dbo].[tickets] .t_zone_name, [icps].[dbo].[tickets] .t_street_name from  [icps].[dbo].[tickets]  inner join        [icps].[dbo].[ticket_events] on [icps].[dbo].[ticket_events].[te_system_ref] = [icps].[dbo].[tickets].[t_number]  where[icps].[dbo].[tickets].[t_camera_ticket] = '0' and  [icps].[dbo].[tickets].[t_date_time_issued] >= convert(datetime,'2012/10/01',101)       and [icps].[dbo].[ticket_events].[te_event_code] = '300' and       datediff(dd, [icps].[dbo].[tickets].[t_date_time_issued], [icps].[dbo].[ticket_events].[te_date]) >50) 	0.000533143400040789
17928175	5951	compare start and end dates across multiple rows	select * from subscription s0 where not exists (     select 1     from subscription s1     where         s0.contact_id = s1.contact_id         and s1.start_date = s0.end_date ) order by contact_id, id 	0
17929103	34065	how can i have a date field in mysql that will be update auto by a server?	select curdate() 	0.00110076465967054
17930245	4337	top n results grouped oracle sql	select brand, model, sales  from(     select brand, model, sales,row_number()over(partition by brand order by sales desc) rn     from (         select tv.brand, tv.model,sum(tv.sales) as sales,         from tv_table as tv         group by tv.brand,tv.model     )a )b where rn <= 10 	0.00328014130038623
17930498	21907	mysql extracting data from 3 tables	select *  from photovote v inner join photogallery g on v.photoid = g.id inner join registration r on g.user_id = r.id where v.status = 1  and g.status = 1 	0.000674607975422026
17930532	33408	get rows matching the combination of ids in sql server 2008	select * from t2 t21 inner join t2 t22 on t21.id = t22.id inner join t1 t1 on t21.combiids = t1.combi1 and t22.combiids = t1.combi2 	0
17931248	20802	how to query for only email values?	select *   from tablename   where email like '%@%.%'     and email not like '% %'; 	0.00452420738019106
17933081	32469	count using a case statement to find range	select "i.  category       " + "number" + char(13)+char(10) + "ii.   "iii. high:            " + cast((select count(1)                                  from tabdata                                  where  advance > 10000) as varchar) + char(13)+char(10) + "iv. low:            " + cast((select count(1)                                from tabdata                                where  advance >= 5000                                  and advance <= 10000) as varchar) + char(13)+char(10) + "v.  moderate:    " + cast((select count(1)                             from tabdata                             where advance < 5000) as varchar) + char(13)+char(10) + "vi. n/a              " + cast((select count(1)                                 from tabdata                                 where  advance is null) as varchar) 	0.0533268341879495
17933850	11177	access, lookup unused values across multiple fields	select * from [devices] where [devices].[id] not in ( select slot1 from pdus where slot1 is not null union all select slot2 from pdus where slot2 is not null union all select slot3 from pdus where slot3 is not null union all select slot4 from pdus where slot4 is not null union all select slot5 from pdus where slot5 is not null union all select slot6 from pdus where slot6 is not null ) 	0.0119308329021082
17935357	36912	sql max() over(partition) returning multiple results	select *, max(mt.version) over (partition by mt.partitiongroup) from mytable mt where mt.id = 'some uuid'; 	0.421913105504825
17939198	33651	row number per group in mysql	select    id,               crew_id,               amount,               type,              (                  case type                  when @curtype                  then @currow := @currow + 1                  else @currow := 1 and @curtype := type end               ) + 1 as rank     from      table1 p,               (select @currow := 0, @curtype := '') r    order by  crew_id,type asc; 	0.000282378584771091
17939208	11935	sql: display distinct record from a column	select [logid],         [orderno],         max([maxdate]) maxdate,         [anotherdate],         [status]  from   logs group  by [logid],            [orderno],            [anotherdate],            [status] 	0
17939389	40588	specific character in sql	select  left(emailcolumnname,charindex('@',emailcolumnname)-1) as username  from tablename 	0.103556935736429
17939533	14201	to find the duplication of values	select colvalue, count(colvalue) as cnt   from table1 where colvalue in (1,2,3) group by colvalue  having cnt>1 	0.00111346699137705
17939711	24624	how to only exclude two matching fields?	select * from table where            field1 = 1 and field2 = 0              and (                   (field3 = 1 and (field4 = 4 or field4 = 5 or field4 = 6))                      or                    (field3 = 0)                 ) 	0
17940072	23755	build table in with clause from csv	select trim(x.column_value.extract('e/text()')) columns from t t, table     (xmlsequence(xmltype('<e><e>' || replace(valuestring, ':','</e><e>')||    '</e></e>').extract('e/e'))) x   ); 	0.176360485730457
17940332	27535	including a row in the result of a select for which the select didnt recover any data	select type              as "orders",         count(date_order) as "total",         nvl(sum(case                   when (date_order between sysdate - 10 and sysdate) then 1                   else 0                 end), 0)  as "0_10_days",         nvl(sum(case                   when (date_order between sysdate - 20 and sysdate - 11) then 1                  else 0                 end), 0)  as "10_20_days",         nvl(sum(case                   when (date_order between sysdate - 30 and sysdate - 21) then 1                  else 0                 end), 0)  as "20_30_days",         nvl(sum(case                   when (date_order <= to_date(sysdate - 30)) then 1                   else 0                 end), 0)  as "plus_30_days"  from   (select type, date_order          from t_orders          where type in ('x', 'y', 'z')         union all         select decode(level, 1,'x', 2,'y', 3,'z') type, null date_order          from dual         connect by level <= 3         ) sq group  by type 	5.98135249606139e-05
17941584	30110	oracle sql : regexp_substr	select initcap(nvl(regexp_substr(word, '[^-]+', 1,3),regexp_substr(word, '[^-]+', 1,2)))  from your_table; 	0.546353989746969
17942508	8326	sql split values to multiple rows	select   tablename.id,   substring_index(substring_index(tablename.name, ',', numbers.n), ',', -1) name from   numbers inner join tablename   on char_length(tablename.name)      -char_length(replace(tablename.name, ',', ''))>=numbers.n-1 order by   id, n 	0.000814154805426805
17942845	9573	mysql group by two columns	select user_id, max(correct_answers) maxs ,level_id    from score    group  by level_id,user_id 	0.00925027591500729
17943147	29055	use except with taking into account the number of duplicate	select id,a,b,c from  ( select *, row_number() over (partition by id,a,b,c order by id,a,b,c) as row from t1 except select *, row_number() over (partition by id,a,b,c order by id,a,b,c) as tow from t2   ) t 	0.000236706224618434
17943331	38474	multiple queries to fill one datatable	select 1 as priority, field1, field2 from ...  union  select 2 as priority, field1, field2 from ...  order by priority 	0.00851908516258369
17943655	18364	including a condition dynamically in sql(oracle)	select  from table a left outer join ....c where  ((a.column='123') and (c.column='456')) or c.column is not null 	0.25405412542322
17944549	4525	find only max data records	select *   from #tmp b where emp_no in ('e44920','e39787') and   [count]=(select max([count] from #tmp a where a.emp_no =b.emp_no ) 	0.000104946386129691
17944971	22241	how do i combine two booleans columns into one varchar columns in a select query?	select  case     when master = 0 and edition = 0 then 'u'     when master = 1 and edition = 0 then 'm'     when master = 0 and edition = 1 then 'e'     else '???'  end  from mytable 	0
17946753	26888	get the latest value on each date	select t1.*,        (select top 1 value         from @table2 t2         where t2.idcolumn = t1.idcolumn and               t2.datecolumn <= t1.datecolumn         order by t2.datecolumn desc        ) t2value from @table1 t1; 	0
17947676	5707	search query for multiple date filters	select *  from table1  where column1< isnull(@finishdateforcolumn1,'31/dec/2099')  and column1 > isnull(@startdateforcolumn1, '01/jan/1971') and column2< isnull(@finishdateforcolumn2,'31/dec/2099')  and column2 > isnull(@startdateforcolumn2, '01/jan/1971') 	0.196467265680935
17948439	16111	max attempts count	select   emp_id,   case when max(value)>0 then count(*) else 0 end attempt_count from   tablename group by   emp_id 	0.102905671312372
17948883	11184	select record from joined table if it exists	select t2.id, t2.description from table2 t2 union all select t1.id, t1.description from table1 t1 where not exists (select *                    from table2 t2                   where t2.id = t1.id) 	0.000432825505314348
17948935	18657	how to find correlated values in oracle?	select foreign_key from table group by foreign_key having     abs(1 - count(case status when 'new' then 1 end)) +     abs(count(1) - 1 - count(case status when 'approved' then 1 end)) = 0 	0.0998804916556229
17949243	30120	looking for an alternative sql command to find the same values in two tables	select distinct t1.names  from table1 t1, table2 t2 where t1.names = t2.names 	0.00140205700492412
17949487	6224	sql: select all the fields from the second biggest id	select * from pontos where idponto = (select idponto from pontos order by idponto desc limit 1,1) 	0
17950060	10007	make calculations in sql query for selecting records with a rating	select * from users where round(vote_score / vote_count, 2) >= 3; 	0.0186770742155192
17952067	26875	python - extracting a sql server database schema to a file	select * from sys.tables select * from sys.all_columns select * from sys.views select * from sys.syscomments 	0.0866971087667612
17955843	30733	assign values of a column in subquery in sql	select    producer = p.producer_name,    products = stuff((     select ',' + pr.product_name        from dbo.product as pr       where pr.producer_id = p.producer_id        for xml path('')).value('.[1]','nvarchar(max)'),1,1,'') from dbo.producer as p; 	0.00335270242997294
17956281	5405	how to flip/reorganize the data retrieved from an sql select statement?	select     school,     [ms. smith],     [mr. rogers],     [mr. berkenheim],     [ms. roberts],     [mr. ashby],     [ms. robinson] from <data_table> as d pivot (     sum(numberofstudents) for teacher in ([ms. smith],[mr. rogers],[mr. berkenheim],[ms. roberts],[mr. ashby],[ms. robinson]) ) p 	0.0102086808679598
17956322	18897	sql: count records if all columns are equal	select count(*) from   (    select orderno    from products    group by orderno    having min(status) = 'active' and max(status) = 'active'  ) as dt 	0
17956354	32797	order prices according to currency	select   lowmoney,   topmoney,   currency from thetable order by   (lowmoney + (topmoney / 100)) *   case currency      when 'eur' then 1.3266     when 'usd' then 1   else     null   end desc 	0.00947064132792134
17958017	34340	sql server joining the results of two tables	select id, siteid from tblcontrols_rooms where siteid in (@origsiteid, @newsiteid) 	0.00306692659222947
17959342	5577	using output of function from select in where clause	select id, count(id) as count_id from table1 group by id having count(id) = 3; 	0.588287790450692
17960263	31144	how to write a query to show multiple output in same column	select e.emp_name,   [empsal/details] = case      when s.empsal > 0 then convert(varchar(12), s.empsal)     when s.emp_id is not null then 'new joinee'     when s.empsal is null then 'contractor'   end from dbo.tbl_emp as e left outer join dbo.tbl_empsal as s on e.emp_id = s.emp_id; 	0.00270093230982548
17960524	2972	count number of occurrences based on user id	select sum(leadtype_c = 'referral') as referrals,        sum(leadtype_c = 'vm') as vms,        sum(leadtype_c = 'email') as emails,        users.`first_name`, users.`last_name` from users join     `leads`      on  users.`id` = leads.`assigned_user_id` inner join      `leads_cstm`      on `leads`.`id` = `leads_cstm`.`id_c` group by users.id; 	0
17961261	41279	how to get record in one table with conditional in two tables - php and mysql	select t1.id,t1.name from t1 left join t2 on t1.id = t2.uid where t1.type = 1 or t2.type = 1 	0
17963130	22694	need sql query to coallate data from two tables in a desired format	select branch,         stuff((select ',' + clientids                from   clientdetails a                where  a.branch = t.branch                for xml path('')), 1, 1, '') as clientid  from   clientdetails t  group  by branch 	0.0225934717640971
17964494	8614	mysql - grouping and counting	select a.placement_id, p.name as placement_name, count(l.status) from actions a inner join placements p on p.id = a.placement_id  inner join leads l on l.id = a.lead_id  group by a.placement_id, p.name 	0.0818403114828577
17967498	2585	mysql query to select last value in column 1 and max value from last 5 rows in column 2	select (select column_1  from table1  order by timestamp desc limit 1) as column_1, (select max(column_2)   from   (    select column_2     from table1     order by timestamp desc     limit 0,5   ) as t1) as column_2 from table1 limit 1; 	0
17967635	37678	an axis number cannot be repeated in a query	select  {     [measures].[internet sales amount],     [measures].[internet freight cost]  }on columns from [adventure works] where      (          [date].[calendar].[calendar quarter]. & [2003] & [2],         [product].[product line].[mountain],         [customer].[country].[australia]      ) 	0.54658680564284
17968623	1493	using multiple like in mysql on multiple join	select * from table1 join table2  where table1.town=table2.town and table1.car=table2.car and ( table1.name like "%search-term%" or table2.car like "%search-term%" ) order by table1.name 	0.64603355290103
17969134	3742	count all items on which a user is the high bidder	select count(distinct(item_sales_bids.user_id)) as total, sum((sale.list_date + (sale.duration * 86400)) - unix_timestamp()) as endtime from item_sales_bids inner join item_sales sale on item_sales_bids.sale_item = sale.id inner join (     select sale_item, max(id) as latestbid     from item_sales_bids     group by sale_item ) sub1 on item_sales_bids.sale_item = sub1.sale_item and item_sales_bids.id = sub1.latestbid where user_id = 1 group by item_sales_bids.sale_item having endtime > 0 	8.82202981653343e-05
17971164	29780	how to join a view on an array_agg column in postgresql?	select s.groupid, a.somedata from sampleview as s join anothertable as a on a.akey = any(s.keyarray); 	0.316647629516532
17971643	25460	grouping of top 80% categories	select (case when cumcntdesc < totalcnt * 0.2 then 'other'              else color         end) as color, sum(cnt) as cnt from (select color, count(*) as cnt,              sum(count(*)) over (order by count(*) asc) as cumcntdesc,              sum(count(*)) over () as totalcnt       from t       group by color      ) t group by (case when cumcntdesc < totalcnt * 0.2 then 'other'                else color           end) 	0.00554010999822872
17973410	4207	filter out similar data sql server 2008	select data,max(id) from tablename group by data 	0.316556240296054
17973724	30799	calculate price from two different table + using php and mysql	select trip.trip_id as new_tripid,destination, leave_date, return_date,     date(last_updatedate) as updateddate, flight_estimate , registration_fee,     sum(hotel_cost, breakfast_cost, lunch_cost, dinner_cost, parking_cost, taxi_cost,      rental_car_cost, mileage, fuel_cost, other_cost) as total_cost from trip, expense where trip.username='$user' and trip.trip_id = expense.trip_id group by trip.username 	0
17974256	15707	trouble using join on sql with 3 tables	select  t.cod,         coalesce(sum(c.valor), 0) as [valorsum],         coalesce(sum(j.valor_justificativa), 0) as [valorjustsum] from tag_ug t inner join contas c on c.ug = t.cod inner join justificativas j on j.cod_contas = c.cod where c.conta_monitorada = 'sim' group by t.cod,         c.ug 	0.751149840599795
17975518	4982	retrieve only the first row with order by	select * from   (select epi.inc_amt from emp_pay_inc epi order by epi.inc_date desc) where rownum = 1; 	0
17977562	20831	sql query to add values from column x for every entry that has y	select x, sum(z) total_z from table where y = 123 group by x 	0
17980105	16511	counters in teradata while inserting records	select    name    ,amount    ,date_col    ,sum(flag)     over (partition by name           order by date_col           rows unbounded preceding) as "dense_rank" from  (    select       name       ,amount       ,date_col       ,case           when amount = min(amount)                         over (partition by name                                order by date_col                               rows between 1 preceding and 1 preceding)           then 0            else 1        end as flag    from dropme  ) as dt; 	0.0791964822114266
17982994	673	count repeated records in a table of a specific column	select [newsitemtitle], count(1) as xx from [mobileserviceextra].[activity] where [location] = 'newyork' group by [newsitemtitle] order by xx desc 	0
17985336	30339	concatenate strings of rows according to column	select msgid , group_concat(msg separator ' ') as msg from table1 group by msgid; 	0
17985522	36281	select sum from two other tables	select p.pid,p.product_name,totstock, totsale from tblproducts p left join (select pid, sum(qty) as totstock from tblstocks group by pid)  s on s.pid=p.pid left join (select pid, sum(qty) as totsale from tbls group by pid) sl on sl.pid=p.pid 	0.000129159102677569
17985599	32523	tsql - find the minimum in the range	select  si.num_phone phone,  su.start_time sulstarrttime , si.case_create sistarttime, datediff(hour, 0, su.start_time - si.case_create)  diffinhours from siiis si  cross apply (select top 1 * from sulls su  where  si.xfff= su.xfff  and su.start_time > si.case_create  and dateadd(hour, 3, si.case_create) > su.start_time  order by start_time ) su where si.case_create between '20130301' and '20130531'  	0.000173035429237509
17985921	26166	sql count/sum displaying column as rows	select 'column1' as "category", sum(column1) as "value" from my_table union select 'column2', sum(column2) from my_table union select 'column3', sum(column3) from my_table 	0.0151306412742672
17986621	33953	find a word in stored views of mysql	select table_name from information_schema.views where view_definition like '%your_word%'; 	0.0106874694440726
17987660	12357	how to have a count when using groupby?	select country,count(*)   from table         group by country; 	0.150723493638523
17988552	17786	get 10 latest post	select top 10 f_com.id_post, f_com.id_user, f_pos.contenido,  f_com.contenido, f_com.fecha  from f_comentario f_com inner join f_post f_pos on  f_pos.id_post = f_com.id_post  order by fecha desc 	0
17988593	16898	how to select only one field where id number is the same sql	select bugid,        name,        description,        stuff(( select ',' + comment                    from table1 i where i.bugid= o.bugid                 for                   xml path('')                 ), 1, 1, '') from   table1 o group by bugid,        name,        description 	0
17988835	36423	elegantly appending a set of strings (.txt file) to another set of strings (.txt also)?	select t1.*, t2.* from t1, t2 	0.000102174148457366
17989701	28591	sql ranking and ties	select value,  count(*) over (partition by value)/2 + rank() over(order by value) as ranking1,  count(*) over (partition by value) + rank() over(order by value) -1 as ranking2  from table 	0.399130737874867
17989953	22210	sql query to find a column value with specific text available	select column_name from table_name where patindex('%sample_text%', column_name) != 0 	0.000123810161478187
17990579	25828	compare time portion of datetime values in sql	select model  from sales  where    cast(@saledate as time) between cast(workstart as time) and cast(workend as time)    and ctrl = @key 	0.00014313202813445
17991560	16533	how to strip/change certain characters in a column sql server	select distinct     name,      bugid,      summary,      description,      reporteddate,      versionid,      versionname,      bugresolution,      issuestatusid,      bugstatus,      bugtype,      bugpriority,      componentname,      reportedby,     comment.value('.', 'varchar(max)') comments,     code,      issueresolutionid        from        (select          name, bugid, summary, description, reporteddate, versionid, versionname, bugresolution, issuestatusid, bugstatus, bugtype, bugpriority, componentname, reportedby,         cast(stuff(( select ',' + comment                        from lbbugnet.dbo.report_view i where i.bugid= o.bugid                     for                       xml path('')                     ), 1, 1, '') as xml) as comment,         code, issueresolutionid              from        lbbugnet.dbo.report_view o     where        bugid between @fromid and @toid) a order by      bugid asc 	0.00286201736124104
17991877	39357	add some char to field until x field length mysql	select lpad(field1, 3, '0') from table1 	0
17993225	29336	select only one of the identical rows (specific) between two tables in a union	select column_name(s) from t1 union select column_name(s) from t2  where not exists (select 1                   from t1                   where t1.col1 = t2.col1 and t1.col2 = t2.col2 and . . .                  ) 	0
17993422	31571	mysql select all orders with values from last revision	select r.name, r.material, r.producer, r.color from revisions r join      (select r.id_order, max(date) as maxdate       from revisions r       group by r.id_order      ) rmax      on rmax.id_order = r.id_order and         rmax.maxdate = r.date; 	0
17993457	21305	selecting <br/> in for xml path query in sql server	select stuff((     select ', <br />' + s.[title]     from dbo.tblsectors s     where sector_id in (             select sector_id             from dbo.trelbusinesssector             where business_id = 2517         )     for xml path(''), type).value('.', 'varchar(max)'), 1, 2, '') 	0.251763144172555
17993911	12408	mysql join conditional to check integer against comma delimited list	select  from     order o,     order_product op,     product p where      o.id = 20 and o.id = op.orderid and op.productid = p.id 	0.0311156034926416
17994449	20998	compare two table in mysql	select table1.* from table1 left outer join table2 on table1.id = table2.id where table2.id is null 	0.00324578541037077
17996252	18789	sql table getting info from another table based on a if statement with stored procedure	select t1.name, t1.age, t2.grantreturn from table1 t1 join table2 t2 on t1.grant = t2.grant 	0
17997927	7350	sql for stacking queries together without aggregating the data	select t.* from (     select [date], [eggs], null [colour], [qty] from table1     union all     select [date], null [eggs], [colour], [qty] from table2 ) t order by t.[date] 	0.156304351235359
17997990	36040	sql get all records older than 30 days	select * from profiles where to_timestamp(last_login) < now() - interval '30 days' 	0
18000362	30871	removing duplicate key but unique rows with priority using sqlite3 in python	select b.symbol, b.title, b.link, b.pubdate   from bar b join (   select title, max(pubdate) pubdate     from bar    group by title ) q on b.title = q.title     and b.pubdate = q.pubdate 	0.000696574638816922
18001920	4192	mysql - get number of occurrences from "diferent" query results	select name,        count(distinct rank) as ranks          from tablename        where rank=1 or rank=2         group by name 	0
18002338	28287	sql search for only one left item	select     sum(vd_ab.menge) as amount,     artikel.artikelnummer as artikelnummer, from artikel     inner join vorgangdetails as vd_ab on         vd_ab.auftrag like 'af-%' and vd_ab.artikel = artikel.artikelnummer     left outer join vorgangdetails as vd_l on         vd_l.auftrag like 'lf-%' and vd_l.artikel = artikel.artikelnummer and         vd_l.weiterfuehrungvonpos = vd_ab.recid     left outer join vorgangdetails as vd_rvl on         vd_rvl.auftrag like 're-%' and         vd_rvl.weiterfuehrungvonpos = vd_l.recid and         vd_l.auftrag is not null     left outer join vorgangdetails as vd_rvab on         vd_rvab.auftrag like 're-%' and         vd_rvab.weiterfuehrungvonpos = vd_ab.recid where vd_rvab.auftrag = '' and vd_rvl.auftrag = '' group by artikelnummer 	0.00455239024698945
18003236	27762	how do i select or place data from multiple rows into a single row or column?	select     c.userid,     stuff(         (             select ', ' + t.color             from table1 as t             where t.userid = c.userid             order by t.color             for xml path(''), type         ).value('.', 'nvarchar(max)')     , 1, 2, '') from table1 as c group by c.userid 	0
18003490	4934	many-to-many relationship select checkboxes in form php	select distinct b.id, c.a_id from b left join c on b.id=c.b_id and c.a_id=2 group by b.id 	0.176419556892416
18003650	603	ways to calculate rolling subtotal	select id,         dt,         val,         (         select sum(val)/12          from mytable t2          where t2.id = t.id           and t2.dt > dateadd(mm, -12, t.dt)            and t2.dt < t.dt        ) val12monthavg  from mytable t 	0.0122715219873982
18004033	4097	insert multiple rows into temp table with sql server 2012	select @@version 	0.026085135311144
18004060	19177	regexp_substr : extracting portion of string between [ ] including []	select  regexp_replace('select userid,username from tablename where user_id=[req.uid] and username=[reqd.vp.uname]' ,'.*(\[.*?\]).*(\[.*?\]).*','\1\2') from dual ; 	0.00134966633527
18004509	3273	find the last time a record was used	select s.selection_key, s.selection_name, min(t.tkt_date) from food_selection s inner join food_tkt_item i on i.selection_key = s.selection_key inner join food_tkt t on t.tkt_key = i.tkt_key order by t.tkt_date desc 	0
18005369	40906	sql date range queries	select sum(datediff(dy,                      case when '2013-01-01' > start then '2013-01-01' else start end,                     case when '2013-07-01' < [end] then '2013-07-01' else [end] end) / 30) total_months   from table1  where '2013-01-01' between start and [end]    and '2013-07-01' between start and [end] 	0.0168295498753329
18005669	30808	joining two columns but keeping multiple instances in sql	select t3.name, t3.age from table3 t3     join (         select distinct name, age         from table1             left join table2                 on table1.id = table2.id     ) t on t3.name = t.name and t3.age = t.age 	0.000292980402558292
18006384	22307	sql finding the previous date from another row matching query	select a.show_date, a.show_id,    b.song_name, a.song_id, (   select     max(show_date)   from tbl_shows as c   where a.show_date > c.show_date and a.song_id = c.song_id   ) as prevdate   from tbl_shows a, tbl_songs b   where a.song_id = b.song_id   and a.show_id = 899 	0
18006661	36978	how do i get columns from a joined table in php?	select * from table     inner join chair  on table.table_id = chair.table_id      where chair.id = "' . $chairid . '" 	0
18007187	20018	sql for xml with subroot	select '<?xml version="1.0" encoding="us-ascii"?>' + (select          (select radioid as [name], rtrim(unit_code) as [alias],[guid] as [id]           from @temp ani          order by unit_code          for xml auto, root('anialias'),elements, type) for xml raw('configuration')) 	0.779562213207342
18008960	6459	how to merge two columns in sql	select financialid,         applicationid,         isnull(upper (interestsubsidyfinancialdetail.bankname),'') +          isnull(bankmaster.bankname,'')         as bankname,             interestsubsidyfinancialdetail.bankid  from   interestsubsidyfinancialdetail  left join bankmaster on bankmaster.bankid = interestsubsidyfinancialdetail.bankid 	0.00108371583200535
18010472	38346	how to get the space consumed by a set of records in a table?	select 4*5 + 1 * 3 + (length(tablename)+2) + (length(modifyby)+2) + ...  from hugetable  where tid = 'myvalue'; 	0
18010944	31124	sql how to order by statement in one column	select datepart(day,blg_date) as dday,       datename(month,blg_date) as dmonth,        datepart(year,blg_date) as dyear ,        (select count(*)           from [blg]            inner join [acc]  on [blg].acc_id=[acc].acc_id           where [blg].acc_id='1'and [blg].blg_date like '%2013%') as icount from [blg]  inner join [acc]  on [blg].acc_id=[acc].acc_id  where [blg].acc_id='1'and [blg].blg_date like '%2013%' 	0.0385365652343747
18011427	3929	postgresql - how to select results depending on results of another query	select     t1.*,     case when t2.user is not null then 1 else 0 end is_mutual from test as t1     left outer join test as t2 on t2.user = t1.friend and t2.friend = t1.user 	0.000190772385901095
18011491	23663	order by null values with mysql	select id, description, status, login from dev order by status is null, status desc, login is null, login desc 	0.145952437087414
18011804	1141	postgresql-simple: get a list of table names in a database	select schemaname, tablename from pg_tables; 	0
18011883	32639	how to increase perfromance of sql query for selecting from 2 tables	select pa.code from parametrickevyhladavanie pa where exists ( select 1 from produkty p join  product_info as pi on    p.proid = pi.produktid where pi.attribute_code = pa.code and pi.attribute_value = pa.valuecode and p.kategoria in ('mobily')) group by pa.code 	0.000397589858628107
18012471	12430	i need a query to find all the combinations of wrong entries	select t.*   from table1 t join (   select fk, preference     from table1    group by fk, preference   having count(*) > 1       or preference < 1       or preference > 3 ) q  on t.fk = q.fk      and t.preference = q.preference 	7.67940843129732e-05
18013311	41325	fetch all rows until a special one matched	select * from logtable a where not exists (     select 1     from logtable b     where b.date <= a.date     and b.type = 3 ) 	0
18014272	5189	hql - only return single object for each object property sorted by how recently the object was updated	select p from playlistdaystats p  where not exists(     select 'next'     from playlistdaystat p2     where p2.playlist = p.playlist     and p2.updated > p.updated     and p2.user = p.user ) and p.user = yourvariable 	0
18014318	37533	oracle select query for link table	select      l.partyid_a,             pa.sk_party,             l.partyid_b,             pb.sk_party from        link_party l inner join  tbl_party pa on l.partyid_a = pa.partyid inner join  tbl_party pb on l.partyid_b = pb.partyid 	0.132768339554608
18019433	26694	search through multiple tables	select p.*, pc.*  from pages p join page_content pc on p.page_id = pc.content_page_id  where p.page_status != '99'    and (p.page_title like '%" . mysql_real_escape_string($words) . "%' or pc.content_text like '%" . mysql_real_escape_string($words) . "%')  group by p.page_id  order by p.page_onlinedate desc; 	0.109708680600625
18020605	13673	mysql query (multiple counts)	select abc, def, count(*) as c,   (select count(1) from (         select abc, def, count(*) as c         from xpto a         group by abc, def     ) b   group by abc   having c.abc=b.abc   ) ic from xpto c group by abc, def order by ic desc, c desc 	0.199696428285486
18021974	19734	how to select a records with timestamp ranges?	select * from table where time > unix_timestamp(date_sub(now(), interval 1 week)) select * from table where time > unix_timestamp(date_sub(now(), interval 1 year)) select * from table where time > unix_timestamp(date_sub(now(), interval 1 month)) 	0.000170372929327747
18023950	35135	how to query sql for a isbn with dashes against one with no dashes.	select t.* from t where replace(t.isbn, '-', '') = @myisbn; 	0.616929484386399
18023963	25334	changing top rows parameter from code behind	select top (@rows) * from dbo.mytable order by something 	0.00694024153221026
18023970	34212	average temperature grouped by serial number with day intervals	select      sensor.serial,     date_format(sensor_data.dtg, '%m/%y/%d') as dtg_day,     sensor.elevation,     sensor.room,      sensor.system,     avg(sensor_data.reading),     count(1) reading_count from      sensor     natural join sensor_data group by     sensor.serial,     dtg_day,     sensor.elevation,     sensor.room,      sensor.system 	0
18024108	18417	prevent the same row pulled from mssql database across multiple sessions	select yourperson from yourtable with (rowlock, xlock) where yourpersonid = 1; 	4.80557004341943e-05
18024170	21211	group by using a sum	select sum(counter) as counted, id from t group by id; 	0.196300571477501
18025834	33135	sql: how to get an occurrence count of unique values from a query complicated by joins?	select count(cc.class_id) from (select distinct cc.class_id, count(*) as `records`     from content_class cc     left join content c on c.id = cc.content_id     left join content_category ccat on c.id = ccat.content_id     where cc.class_id is not null     group by cc.class_id'); 	0.000137499695695421
18026925	2724	query optimazation	select c.id, c.title, c.duration, c.visible, v.id as vid, v.title as video_title,         v.chapter_id, v.duration as video_duration, v.video_token, count(*) as viewed from chapters as c left join      videos as v      on c.id = v.chapter_id left join      viewed_videos vv      on vv.video_id = v.id and member_id=32 where c.tutorial_id = 19 group by c.id, v.id; 	0.774548191734413
18027569	17816	combining sql statements into single statement	select tb.aid       from d td inner join c tc on ( tc.id = td.cid ) inner join b tb on ( tb.id = tc.bid )      where d.id = :value          ; 	0.125117528206501
18029373	31327	how to get count_id and rating_evarate from table?	select id      , count(id) count_id      , avg(rating) as rating_average from rating group by id; 	0.000941133045150678
18030140	33916	drop all tables sql developer	select 'drop table ' || table_name || ';' from user_tables where table_name like 'tbl_%' 	0.0423398747272762
18031671	38743	find the last record by person	select p1.* from tblpayment p1 left join tblpayment p2 on p1.name = p2.name and p1.id < p2.id where p2.id is null; 	0
18032694	11789	display value of second gridview from first gridviw	select id, (totaldimension - useddimension) as available from box where (totaldimension - useddimension) < @somevalue 	0
18033817	21793	asp error: multiple-step operation generated errors. check each status value. (object required)	select convert(price,char) as price from table; 	0.128159290805172
18037280	15840	selecting from xml field where xml field = x	select     id,     newvalue = xitem.value('(newvalue)[1]', 'varchar(50)') from      t1 cross apply      xmlfield.nodes('/items/item') as xtbl(xitem) where     xitem.exist('field[.="payment method"]') = 1 	0.000101678561566427
18038325	133	selecting a users forum activity while limiting results based on permission	select count(*) from forum_threads thr join forum_topics top    on thr.topic_id = top.topis_id  join forum_categories fc on top.cat_id = fc.cat_id  where thr.user_id = $user_id     and fc.role_id in ( 0,     24, 55, 888, .... list of user roles ... ) 	0.000802506032036237
18039188	26406	sql replace() table join only replaces trailing text	select initialstring, replacementtarget, replacementvalue,         replace(initialstring, rtrim(replacementtarget), rtrim(replacementvalue))              as replacedstring from   stringtable cross join replacementtable 	0.252889739605834
18041939	17146	filter nullable column for nullable parameter sql	select startdate, enddate from table1 where     (@dtfrom is null or startdate is null or startdate >= convert(datetime, @dtfrom)) and     (@dtto is null or enddate is null or enddate <= convert(datetime, @dtto)) 	0.109431261712212
18042538	22404	get count of two column in access 2007	select aqcode,aqdescribe,sum(cno),sum(cyes) from ( select aqcode,aqdescribe,'0' as cno,count(result) as cyes from tblaquestion aq,tbluserresult r where aq.aqcode=r.aqcode and r.result='1' group by aqcode,aqdescribe union select aqcode,aqdescribe,count(result) as cno,'0' as cyes from tblaquestion aq,tbluserresult r where aq.aqcode=r.aqcode and r.result='0' group by aqcode,aqdescribe ) group by aqcode,aqdescribe 	0.00502578784616069
18043833	14118	how can i add the array to the array of arrays in sql (postgres)	select '{{1,a, 1},{a,b,c},{45,46,47}}'::text[] || '{z, t, null}';                 ?column?                   {{1,a,1},{a,b,c},{45,46,47},{z,t,null}} 	0.000420453450949546
18047589	39854	mysql union selects with 1 distinct condition	select   id,   program_id from(   select     id,     program_id,     @rank := if(@program = program_id, @rank + 1, 1) as rank,     @program := program_id   from(     select       id,       program_id     from users     where program_id in(1, 2, 3)       #and [other conditions]     order by       program_id,       rand()   ) as derived   join (select @program := 0, @rank := 0) as var ) as derived where rank <= 100 order by   program_id,   id desc 	0.384755443547756
18049292	14739	selecting element which refer to other elements in the same table	select t.id, t.parent, @parent := parent from (select @parent := 7) const join      t      on t.id = @parent; 	0
18054866	10367	change sql script to output to own fields instead on one field	select sum(case when numberofdayssinceorderdate < '40' then 1 else 0 end) as lessthan40      , sum(case when numberofdayssinceorderdate between '40' and '70' then 1 else 0 end) as between40and70      , etc... 	0.00125720309606776
18057590	36755	delete mysql column index without knowing its name	select distinct index_name, table_name, table_schema from information_schema.statistics; 	0.00372943084426104
18058312	14852	two joins between two tables	select [details]       ,[addressid]       ,[cityid]       ,c.[placename] as cityname       ,[areaid]       ,a.[placename] as areaname from [mydb].[dbo].[address]       left outer join [mydb].[dbo].[places] c          on [cityid] = c.[placei]       left outer join [mydb].[dbo].[places] a          on [areaid] = a.[placei] 	0.00626166126824627
18059333	12404	clause order by	select *  from table1 order by  case     when col2>=100 then 1    else 0 end, col1, col2 	0.735142131564218
18059512	454	mysql simple if statement based on current_time	select     if(unix_timestamp() between p.promo_start and p.promo_end, p.promo_price, p.price) as real_price from products p  where p.id = 1 	0.489124282149955
18060606	17076	mysql query a table with a set condition and if a 2nd conidtion is met grab a row(s) from another table and continue	select    ifnull(nbp.id,nb.id) as id,   ifnull(nbp.title,nb.title) as title,   etc....   from cms_navbar nb   left join cms_navbar_preview nbp on nbp.live_hash= <parameter> and nb.id=nbp.id     where nb.visible=1     and nb.parent=1     order by nb.position asc 	0
18061297	17497	sql query for data and time field minus five hours	select `field` - interval 5 hour from `your_table` 	0.0014110862176778
18061911	37560	how to return only one query result from two query	select a.file_path, b.object_uid, b.object_utitle from images a, (select  object_uid, object_utitle     from object_table     where object_status = 2 and object_place like "%some_keyword%") b where image_id in (   select image_id   from temp_images   where object_uid in (b.object_uid) ) 	7.82573688719857e-05
18065971	21787	sql sub query when joining table	select a.userid, a.fname, a.sname,   max(b.logindate) from     users a     left outer join lastlogin b on a.userid = b.userid group by a.userid, a.fname, a.sname 	0.569074293068775
18067726	26802	show count of columns distinct values	select  county            ,sum( switch( тgte = 'l', 1, tgte = 'h', 0 ) ) as [l_count]            ,sum( switch( тgte = 'h', 1, tgte = 'l', 0 ) ) as [h_count]    from    mytable    group by            county; 	7.29841700761341e-05
18070038	7982	insert results of db query into a variable in controller - codeigniter	select f.id, f.name, count(v.confirmed) as votes from finalists as f inner join votes as v   on f.id = v.finalist_id where v.confirmed = 'yes' group by f.id 	0.0724019282706318
18070177	30371	how to get current instance name from t-sql	select @@servername 	0
18072097	19412	how to display number of records every month according to datetime format c# asp.net	select count(*)  as numberofrecord, datename(month, dateregistered) as monthregistered   from tablename group by datename(month, dateregistered) 	0
18073661	31129	how to get specific number of row data in sql server 2005	select   id,   name,   takendatetime from (select   row_number() over (order by id) as row,   * from tablename) t where t.row = 5 	0
18074429	30748	multiple select statements, not the same amount of columns	select     case        when row_number() over(partition by pos.positionid order by pos1.pdopsreportline) = 1 then            pos.positionid        else            null     end as [topmost],     pos1.positionid as [reportline] from positiondata as pos     left outer join positiondata pos1 on pos.positionid = pos1.pdopsreportline where pos.pdopsreportline is null order by pos.positionid, pos1.pdopsreportline 	0.000110509596474172
18074690	34379	get records count from multi tables in sql	select boxid, count(distinct documentid) from      documents          inner join batches     on documents.id = batches.documentid where     isdeleted = 0 group by boxid 	0.000178974186315165
18075758	893	mysql group by having	select date_format(time, '%d-%m-%y'), ip  from testtable group by date(time), ip; 	0.456143678044989
18076266	6733	get data from two table	select coalesce(t1.id, t2.id) [output] from table1 t1 full join table2 t2 on t1.id = t2.id order by [output] 	0.000111582847875922
18077810	35947	get last week info from sqlite database	select * from mytable where date(timestamp) >= date('now', 'weekday 0', '-7 days'); 	0
18078164	36866	make comma separate values with single column in mysql	select id, group_concat(name) as names from your_table group by id 	0.000713273212280637
18080840	31847	mysql group by last slno (latest version)	select slno,title,date_added from files,   (select max(slno) as mslno,comp_name from files where cat=:cat group by comp_name) t1  where cat = :cat     and slno=mslno    and files.comp_name=t1.comp_name order by files.comp_name desc limit 12 	0.000441460788903412
18082506	20554	creating a yes/no column for an sla report	select requiredsladate,         case when requiredsladate > eventcompletedate then 'no'              else 'yes'         end as metsla from (    select eventcompletedate,            case when doc            as requiredsladate    from table  ) as source 	0.363613177206546
18083190	27487	selecting several sums in sql	select timestamp,sum(electricity) from the_table where siteid in(98,100) group by timestamp 	0.0152224389108523
18083443	27261	finding least loaded live agent using a single t-sql statement	select bjs.hostname hostname, bjs.servicename servicename,   sum(case when bjw.workstatustypeid in (2,3,4) then 1 else 0 end) as inprogress   from backgroundjobservice bjs   left join backgroundjobwork bjw          on bjw.allocatedagenthostname = bjs.hostname         and bjw.allocatedagentservicename = bjs.servicename   where bjs.agentstatustypeid = 2   group by bjs.hostname, bjs.servicename   order by inprogress 	0.154222126315648
18084175	12371	select xml element values and display multiple rows oracle 11g	select xtab.billingamount, xtab.description               from jason_xml jx, xmltable('/results/return'                passing jx.xml_content                columns billingamount varchar2(4000) path '                       description clob path '                       )xtab; 	6.34929773569365e-05
18087524	4728	mysql join and get 2 values?	select t1a.word, t1b.word from  table2 t2 join table1 t1a on t2.word1 = t1a.id join table1 t1b on t2.word2 = t1b.id 	0.00423413972891007
18087659	571	sql query to group by month part of timestamp	select month('timestamp'), sum( electricity ) as electricity,  `siteid`  from table where ( month(  `timestamp` ) =10) group by siteid, month('timestamp') 	0.00106381005240086
18088340	5000	comparing tables in sql?	select distinct table1.col1, table1.col2 ,table2.col1 as col3 ,table2.col2 as col4      from table1     left join      table2     on table1.col1 = table2.col1     and table1.col2 = table2.col2 	0.0771484959096271
18088964	19756	querying two tables based on a third that relates them	select letter_dbid ,  fruit_dbid from linking  left join table2 on table2.`fruit_id` = linking.`fruit_id`  left join table1 on table1.`letter_id` = linking.`letter_id` 	0
18090120	11330	how to join mysql tables using a nullable column?	select * from a join b on a.c <=> b.c 	0.0347392232182532
18090285	27375	using postgres rank function to limit to n top results	select * from (     select the_year, vendor_id, amount,         row_number() over(             partition by the_year             order by amount desc         ) as rn     from (         select             date_trunc('year', the_date) as the_year,             vendor_id,             sum(amount) as amount         from ap         group by 1, 2     ) s ) s where rn <= 10 order by the_year, amount desc 	0.0274855680088398
18091101	12072	add an attribute to the xml column from another column in the same/another table	select orderid,        ordercode,        dateshipped,        shipmentxml into #order from [order] update #order set shipmentxml.modify   ('insert attribute dateshipped {sql:column("dateshipped")}      into (/order/item)[1]') update o set shipmentxml.modify   ('insert attribute trackingnumber {sql:column("t.trackingnumber")}      into (/order/item)[1]') from #order as o   inner join tracking as t     on o.ordercode = t.ordercode select orderid,        ordercode,        shipmentxml from #order drop table #order 	0
18091803	15847	find all distinct alternate usernames by an ip in a single query	select distinct   joins2.player_id,   ips.ip from joins join ips   on ips.ip_id          = joins.ip_id join joins             as joins2   on joins2.ip_id       = ips.ip_id  and joins2.player_id  != #player_id where joins.player_id   = #player_id 	0.000998971128442365
18091965	41191	sql/hive count distinct column	select columna,columnb,count(distinct columnc) no_of_distinct_colc from table_name group by columna,columnb 	0.0391703217932257
18094236	34351	how to use alias in select	select *,      (sub_total - discount_total) as total from ( select sql_calc_found_rows  `bookings`.`id`, `bookings`.`client_id`, `bookings`.`vehicle_id`, `bookings`.`vehicle_hire`,  (insurance_driver_1 + insurance_driver_2 + insurance_driver_3) as insurance_total,  `bookings`.`bedding_qty`,  `bookings`.`bedding_price`,  `bookings`.`promo_discount`,  `bookings`.`promo_is_percent`,  `bookings`.`promo_code`,  (vehicle_hire + insurance_driver_1 + insurance_driver_2 + insurance_driver_3) +  (bedding_qty * bedding_price) as sub_total, case      when promo_is_percent = 1          then (((vehicle_hire + insurance_driver_1 + insurance_driver_2 +    insurance_driver_3) + (bedding_qty * bedding_price)) / 100) * promo_discount      when promo_is_percent = 0          then promo_discount  end as discount_total from `bookings` where `bookings`.`status` = 'quote' ) as src order by  src.`id` desc limit 0, 10 	0.705228920135278
18094396	8933	how do i get an ngram from hiveql into postgresql?	select explode(ngrams(sentences(lower(val)), 2, 10)) as x from kafka; 	0.00371022319294246
18095340	19540	list sub query columns	select tab1.memno, tab3.col2   from tab1   inner join tab3     on tab1.sid = tab3.col1  where not exists (select 1 from tab2                    where tab2.memid = tab1.memno); 	0.0607362248071479
18096058	22314	check missing values across two tables	select i.* from items as i where     not exists     (          select *           from categories as c          where c.item_id = i.item_id and c.cat_id <> 0     ) 	0.000642704607904943
18096219	22599	how to convert mysql query into sql server query?	select * from  (select name , row_number() over(order by name) rn from user ) a where rn > 5 and rn<= 15 	0.287259828125352
18098045	298	how to get the count from joined table when grouping by on the first	select d.objectid, count(*) total_facts   from fact f join dimention d     on f.dimentionkey = d.id  group by d.objectid 	0
18098266	13083	join table on xml column with multiple values	select     fgz_leveranciers.*,     xmldata.i from     fgz_leveranciers     left join     (                         select x.t.value('.','int') i         from fgz_merken             cross apply lst_leveranciers.nodes('lst_leveranciers/lst_leveranciers/value') as x(t)       ) xmldata     on fgz_leveranciers.i = xmldata.i 	0.00613885236942956
18098907	28163	get rows between specific day and month irrespective of year	select * from tbl where (month(dt) = 8 and day(dt) >= 16) or (month(dt) = 9 and day(dt) <= 19) 	0
18101308	38698	mysql join query help to show 2 seperate records	select        c.id,       c.coursecode,       m.`title`,       a.author_name,       q.quality,       m.comments,       s.status,       u.id,       m.material    from        sc_courses c          join sc_status s             on c.statusid = s.id            and s.status= 'offering'          join sc_c_materials m             on c.id= m.courseid             left join sc_authors a                on m.authorid = a.id             left join sc_quality q                on m.qualityid = q.id          join users u             on c.userid = u.id    where       c.userid in (select userid                  from sc_courses                  where id='3'                 group by userid) 	0.0235290578172203
18101457	8323	sql server sql syntax - selecting rows between and ordering	select * from (         select id,row_number() over (order by id) as row         from order where           (shopkeeper=116363) and           (status > 0) and (status <> 2) and           [creationdate] >= convert(datetime,'06/07/2013 00:00:01',103) and           [creationdate] <= convert(datetime,'20/07/2013 23:59:59',103) ) a      where row between 1 and 100      order by a.id 	0.124370009196036
18101646	18439	mysql query to retrieve record using between for two dates	select * from `rooms` where "2013-08-02" between date1 and date2 union  select * from `rooms` where "2013-09-03" between date1 and date2 	0
18105746	29230	select another attribute if the original attribute is null (conditional select)	select coalesce(val1, val2) from test_table 	0.000306752922013669
18106093	7386	converting rows to columns in oracle sql with parametrization	select listagg (''''||parameter||'''', ',') within group (order by rownumber) as parameter, from (select trunc((rownum - 1) / 8) as grp, t.*,              rownum as rownumber       from sr0_crtl_sl_ol_psm_parameter t      ) t group by grp; 	0.0537440337886258
18109810	14726	paid amount greater than total amount paid	select eligibility.phid & '-' & eligibility.sid as memberid, claims.diag_code1, round(sum(claims.paid_amt)) as totalpaid, round(sum(iif(format(serv_beg_date,'yyyy')='2011',claims.paid_amt,0))) as 2011totalpaid, round(sum(iif(format(serv_beg_date,'yyyy')='2012',claims.paid_amt,0))) as 2012totalpaid, round(sum(iif(format(serv_beg_date,'yyyy')='2013',claims.paid_amt,0))) as 2013totalpaid, count(*) as expr1 from (claims inner join eligibility on (claims.[sid] = eligibility.[sid]) and (claims.[phid] = eligibility.[phid])) inner join ***(select phid, sid, count(ndc) as rxcount from pharmacy group by phid, sid order by phid, sid)  as pharmacy*** on (eligibility.sid = pharmacy.sid) and (eligibility.phid = pharmacy.phid) group by eligibility.phid & '-' & eligibility.sid, claims.diag_code1 ***having count(iif([claims].[rev_code]='450',1,0))>1*** order by eligibility.phid & '-' & eligibility.sid; 	0
18110000	35153	how to sort time ( in am / pm ) in sql?	select   login_time from   tablename order by   str_to_date(login_time, '%l:%i %p') 	0.702774150331736
18111398	11162	how do i generate combinations based on column values in sql? (is this even possible?)	select t1.value ||':'|| t2.value from my_table t1 cross join my_table t2 where t1.id = 1 and t2.id = 2; 	0.000505829219506225
18112897	14478	order by proirity with specific value	select * from members  order by   case role      when 'scientific staff' then 1      when 'postdocs'         then 2      when 'supporting staff' then 5      when 'pnut'             then 6      when 'visiting researchers' then 4      when 'secretary'        then 3      when 'ph.d. students'   then 8      when 'students'         then 7      when 'other'            then 9      else   10   end 	0.0255195745034148
18114427	39939	no results returned for row_number() query	select referer      from (select row_number() over (order by ct.referer asc)      as rownum, ct.referer, ct.lastmodified     from clicktrack ct      join ordertrack ot on ot.clicktrackid = ct.clicktrackid         where ct.lastmodified between '07/06/2013' and '08/05/2013'               group by ct.referer, ct.lastmodified     having len(ct.referer) > 0) as num      where rownum = 1 	0.429773619208055
18119035	25879	mysql search with two tables, one table for count only	select m.*, count(mo_member_id) mo_count    from cd_members m left join cd_members_offers mo      on mo.mo_member_id = m.m_id   where (m.m_fname like '%richie%' or m.m_lname like '%richie%' or m.m_email like '%richie%')    and m.m_signupdate >= '2013-08-07' and m.m_signupdate <= '2013-08-10'    and m.m_add_state = 'qld'   group by m.m_id having mo_count between 0 and 5 	0.000176174856090368
18119999	9887	how could i update a table each time a materialized view is refreshed?	select mview_name , last_refresh_type,last_refresh_date from all_mviews; 	0.00821653222894506
18120365	2938	get array of unique elements from mysql	select id, forum_theme, owner, enter_time, main_topic  from forum_message  where main_topic in (1,2,3) group by main_topic order by enter_time desc limit 3 	0
18122248	20676	mysql left join with distinct or limit. need to left join only one value	select      transactionpartnername, amount from 18_8_chartofaccounts     left join 2_1_journal on accountnumber = debitaccount     left join 18_6_transactionpartners on transactionpartnername = companyname where vatreturnrownumberfordebitturnover = '61' and amount = 55 group by transactionpartnername; 	0.528973919693001
18122786	18379	how to find min and max of two columns from two different tables?	select t1.agent, t1.firstcall, t1.lastcall, t2.login, t2.logout from table1 t1     inner join table2 t2 on         t2.agent = t1.agent and         to_char(t1.firstcall, 'yyyymmdd') = to_char(t2.login, 'yyyymmdd') 	0
18123498	29036	unable to get result from mysql stored procedure/function to jpql	select funct() 	0.0953605035630667
18126026	13580	sql - join two fields in the same table to a single field in another table	select c.name,        g1.lookup_name,        g2.lookup_name from   contacts c        left join lookup g1 on g1.lookup_id = c.group_1        left join lookup g2 on g2.lookup_id = c.group_4 	0
18126756	33657	select based on mulitple conditions	select ta.name      , count(distinct t2.val)   from yourtable t1    left   join yourtable t2     on t2.id = t1.id     and t2.val in (30)    left   join ta      on ta.id = t1.id   where t1.val in (10)   group     by name; name count(t2.val) a    1 b    1 c    0 	0.00727660635980316
18126855	16372	create a due date not including weekends from a column given specific sla days	select      categoryname,  doccategory, daysuntildue,  trannbr,  logtime, dateadd(day, a.n, loggedday) duedate from queue  inner join wqmtransactions on queue.trannbr = wqmtransactions.trannbr  inner join serviceq on queue.categoryid = category.categoryid and queue.tranid = serviceq.tranid inner join categorylist on serviceqn.tranid = categorylist.tranid  inner join category on categorylist.categoryid = category.categoryid  cross apply ( select coalesce(max(number)+1, 0) n from( select top (daysuntildue) number from  master..spt_values where type = 'p' and datediff(day, -number-1, loggedday) % 7 not in (5,6) order by number )  a)  a 	0
18127509	20054	how to select multiple email addresses from sql query?	select stuff((select '; ' + emailcolumn from tablename where somecolumn = @conditionvalue     and emailcolumn is not null for xml path('')), 1, 2, '') 	0.0235542839536873
18129695	13955	oracle statement performance: retrieve primary keys exluding combined foreign keys	select yourfields from yourtables where whatever and somefield in  (select somefield  fromyourtables  where the conditions are the same as above  minus  select the same field  from whereever  where you want to exclude it) 	0.0093120841703031
18130129	26823	select only the words that are capitalized	select *  from location  where cities like 'city 1'  collate latin1_general_cs_ai 	0.00102603904607354
18131967	29638	can we create a table which can insert leading zeros on operation	select right('0000'+convert(varchar(5), zip), 5) 	0.0478332362954613
18132204	15887	return queries result like two cols	select      date(d1.date) as date,      d3.country_name as country_name,      sum(case when d3.gender = 'm' then 1 else 0 end) as male,     sum(case when d3.gender = 'f' then 1 else 0 end) as female from f1 inner join d1      on f1.id_start_date = d1.id_start_date inner join d2      on f1.id_end_date = d2.id_end_date inner join d3      on f1.id_user = d3.id_user  group by date, country_name order by country_name 	0.0828228781640631
18132548	31167	how can i combine repeating rows without only returning a single instance of repeating data?	select id, `time`, metadata from  (select @cnt := 0, @previous := '' from dual) dummy join (   select  id, `time`,       metadata, @cnt := if(metadata = @previous, @cnt + 1, 1) occurence,       @previous := metadata from trytable ) a where occurence = 1; 	0
18133321	7938	android sqlite getting distinct name and * amounts	select name, sum(amount) from trans group by name 	0.0368839757221956
18133590	12659	exporting mysql to excel with dates in desired format	select ....date_format(lastvisit, '%m/%d/%y') as lastvisit, date_format(ddate, '%m/%d/%y') as ddate .... 	0.307049453615563
18134556	30270	order by character varying time strings?	select blah , case when timefield = "earlier than 1am" then 1 when timefield = "1-2 am" then 2 etc else 20 end sortby etc order by sortby 	0.0977043715958369
18135031	28319	displaying a sorted dataset from two tables	select  itemid         ,price from    active union select  itemid         ,price from    archive aa where   aa.archivedate = (select max(archivedate) from archive aa1 where aa1.itemid = aa.itemid) and     not exists (select 1 from active a where a.itemid = aa.itemid) 	0
18135301	37400	passing query result into subquery	select     alert,     max (created_at) as latest from     alerts group by     alert; 	0.482973804877102
18135792	36464	how to retrieve several columns from table b	select           rc.contype,      rc.concile,     rc.conamtt,     c.conipk,     c.concycle,     c.ttlid from contract c   left join  (      select          row_number() over (partition by r.conipk order by ???) rownum,         r.conipk,         r.contype,         r.concile,         r.conamt          from rules r          join contract c2 on r.conipk = c2.conipk ) as rc       on  c.conipk = rc.conipk         and rc.rownum = 1 	0
18136541	18487	list all products with no prices in mysql	select * from table1 where not exists (     select * from table2     where prod_price_active = 1     and prod_id = table1.prod_id) 	0.000313930369469511
18138923	7519	mysql order by two columns if one is grater than timestamp	select * from ads order by (case when ad_sponsored_date > $timestamp then ad_sponsored_date end) desc,          ad_date desc; 	0.000253632256968528
18139713	9670	sql query returning same value for both tables colums	select sum(visitscount) + sum(votescount) as total,  sum(visitscount) as visits, sum(votescount) as votes from (   select count(id) as votescount, 0 as visitscount, 1 as gr   from votes   union    select 0 as votescount, count(id) as visitscount, 1 as gr   from visits   ) t  group by gr 	0.00157525391165112
18140788	41105	how to combine result of two queries in one resultset	select     sum(if(rating=1,1,0)) up,     sum(if(rating=0,1,0)) down from rating where cab_id=101 	0.000138470541263226
18141691	4297	how to get year in format yy in sql server	select right(year(creation_date), 2) yy    from asset_creation   where ... 	0.00292335127470619
18142277	9002	mysql: given a row and multiple strings. find the string(s) that are contained in the row	select q.keyword   from table1 t cross join (   select 'oh' keyword union all   select 'xxx' union all   select 'foo' union all   select '41' ) q  where instr(concat_ws(' ', firstname,                              lastname,                              anothercol1,                              anothercol2), q.keyword) > 0 	0
18142466	25157	subquery - return data from unrelated table?	select affiliateid, password, companyname, contactname, loginattempts, lastattempttime from (     select '$user' user  ) u left join affiliates a      on u.user = a.email left join (     select attemptedusername, loginattempts, lastattempttime       from lockoutrecord       where accounttype = 'affiliate'  ) l on u.user = l.attemptedusername 	0.00151790782635481
18143594	19768	sql select. involving count	select     table1.id,     table1.name,     count(table3.table2id) as table2idcount from     table1     left join table3 on table1.id = table3.table1id group by     table1.id,     table1.name 	0.315161519700013
18144307	25373	select items that don't have matching items in another table	select *  from items left join readstatus on  items.itemid = readstatus.itemid where (readstatus.status != 1 or readstatus.status is null); 	0
18147778	35621	compare all rows in a mysql table	select number, count(1) as cnt from table group by number having cnt > 1 	0.000113239243838685
18148188	18039	query sum for two fields in two different tables	select sum(prijs) as sumofprijs, sum(amount) as sumoffees, sum(prijs)+sum(amount) as    total, year(vertrekdatum) as year from tbl_vluchtgegevens vg left join      (select f.gegevenid, sum(amount) as amount       from tbl_fees f       group by f.gegevenid      ) f      on f.gegevenid = vg.gegevenid where vertrekdatum <=now() group by year(vertrekdatum); 	0.000175931113263768
18148836	15376	mysql timediff negative value	select time(timediff('2013-07-21 00:04:50','2013-07-20 23:59:59')); + |time(timediff('2013-07-21 00:04:50','2013-07-20 23:59:59')) 	0.00978069699360785
18149359	33053	sql query - sum of order tha contain an item	select sum(price) as total_price from orders where prod_order in        (select prod_order        from orders        where product_id = 1) 	0.0150761405323112
18150283	14527	combine selecting a record with count	select *, coalesce((a.magnitude / g.generated), 0) as result    from        (            select      count(*) as generated            from        logs            inner join  generated_logs            on          generated_logs.log_fk = logs.log_pk             where       logs.department_fk = ?            and         date(generated_logs.generated_time) = ?        ) as g,        (             select count(generated_logs.log_fk) as magnitude, logs.name             from        logs             inner join  generated_logs             on          generated_logs.log_fk = logs.log_pk             where       logs.department_fk = ?             and         generated_logs.acknowledged = 1             and         date(generated_logs.generated_time) = ?             group by    generated_logs.log_fk             order by    magnitude desc             limit 1         ) as a 	0.000815713697922723
18150968	22588	how to adjust the sum() of a group using the sum() of a subgroup()	select  a.cpny,         a.acct,         sum(a.cost + isnull(t.adjustment, 0)) as total   from  assets a     left join (select  cpny,                        assetid,                        sum(amt) as adjustment                  from  transactions                  group by cpny, assetid) t       on t.cpny = a.cpny and t.assetid = a.assetid   group by a.cpny, a.acct 	0.000765932991562619
18153077	3083	sql ranking dates to get year over year order	select    t.yearmonth,    rank() over (order by r.rnk asc, d.yearnumber desc) as [rank],    d.monthnumber, d.yearnumber from table1 as t     outer apply (         select              month(getdate()) as curmonthnumber,             cast(right(t.yearmonth, 2) as int) as monthnumber,             cast(left(t.yearmonth, 4) as int) as yearnumber     ) as d     outer apply (         select             case                 when d.monthnumber <= d.curmonthnumber then                     d.curmonthnumber - d.monthnumber                 else                     12 + d.curmonthnumber - d.monthnumber             end as rnk           ) as r 	7.98675112016282e-05
18153176	22394	convert time - t-sql	select convert(varchar(15), cast('05:00 am' as datetime), 108)   , convert(varchar(15), cast('5:00 am' as datetime), 108)   , convert(varchar(15), cast('00:05:00 am' as datetime), 108)   , convert(varchar(15), cast('00:5:00 am' as datetime), 108)   , convert(varchar(15), cast('5 am' as datetime), 108) 	0.160685508690392
18153361	35360	display all managers and employees without a manager	select employee, managerid from your_table where managerid is null  or managerid = id 	0.000107808413674408
18153792	27331	mysql selecting max total with date and id	select s.record_id, s.run_date, s.ttl_count from tblstatsindividual s inner join (     select year(run_date) as yr, month(run_date) as mon, max(ttl_count) as ttl     from tblstatsindividual     group by date_format(run_date, '%y %m')  ) maximums  on maximums.yr = year(s.run_date)      and maximums.mon = month(s.run_date)      and maximums.ttl = s.ttl_count group by ttl_count order by run_date desc 	0
18155349	27747	concatenate a single column into a comma delimited list	select    sp.salespersonid,    sp.salespersonname,    regions = stuff   (     (       select ',' + r.regionname        from @region as r        inner join @salespersonregion as spr        on r.regionid = spr.regionid        where spr.salespersonid = sp.salespersonid        order by r.regionid        for xml path(''), type     ).value('.[1]','nvarchar(max)'),     1,1,''   ) from @salesperson as sp order by sp.salespersonid; 	0
18155659	2215	xquery to order with header values in the way	select thexml.query('   element table {     /table/@*,     /table/tr[th], (: copy header :)     for $r in /table/tr[not(th)] (: exclude header :)     order by $r/td[1] (: $r/td[2] to sort on rts col :)     return $r   }') from xmldata 	0.0547685497761435
18156152	12845	filter in pivot table keys	select a.id, a.ads_title,        min(case when v.key_id = 1 then v.value end) `km`,        min(case when v.key_id = 3 then v.value end) `year`   from ads_values v join ads a     on v.ads_id = a.id   group by a.id, a.ads_title having sum(case when v.key_id = 4 and v.value = 1 then 1 else 0 end) > 0 	0.0790131830901241
18156696	34499	get repeated values	select number, count(*) from (     select number, city     from t     group by number, city ) s group by number having count(*) > 1 order by number 	0.00473078855786605
18158932	18249	mysql count based off of two tables	select sum(t2.qty) from table1 t1 join table2 t2 on t1.pid = t2.pid where t1.date = '2008/08/21' 	8.83054591314272e-05
18161078	8143	select data based on another table	select d.* from db_players d left join players p   on p.player_id = d.id   and p.career = 1 where p.id is null 	5.53264725054094e-05
18161306	35878	how to retrieve mysql eav results like a relational table	select prod1.products_idproduct       , prod1.value as 'field1'      , prod2.value as 'field2'      , prod3.value as 'field3'      , prod4.value as 'field4' from meta prod1 left join meta prod2    on (    prod1.products_feeds_idfeed = prod2.products_feeds_idfeed       and prod1.products_idproduct = prod2.products_idproduct)      left join meta prod3   on (    prod1.products_feeds_idfeed = prod3.products_feeds_idfeed       and prod1.products_idproduct = prod3.products_idproduct)      left join meta prod4   on (    prod1.products_feeds_idfeed = prod4.products_feeds_idfeed       and prod1.products_idproduct = prod4.products_idproduct) where       prod1.products_feeds_idfeed = 1   and prod1.entity_identity = 1   and prod2.entity_identity = 2   and prod3.entity_identity = 3   and prod3.entity_identity = 4; 	0.0292791894256011
18163157	36000	cant update and delete data - sql	select * from table 	0.482407571764928
18164530	11328	stock system - sql not showing out of stock items	select name, status, sum(case when status in (0,3) then 1 else 0 end) as count from stock_item  group by si.name, si.status order by count asc; 	0.0250636966101559
18164915	18600	mysql random select query with limit returning different number of results (undesired)	select name from (select rand() temp, name  from randomnames) a order by  temp   limit ? 	0.00398679955789246
18166219	6768	calculating relative frequencies in sql	select     m.object_id, m.token_id, m.freq,     t.token_size, t.token,     cast(m.freq as decimal(29, 10)) / sum(m.freq) over (partition by t.token_size, m.object_id) from mapping as m     left outer join token on m.token_id = t.id where m.object_id = 1; 	0.100245639562835
18168148	4277	sql query to average, after grouping by date part of millisecond	select date(millis / 1000, 'unixepoch') as date,        avg(num) as avg from mytable group by date 	0.00132336692083826
18168192	17858	mysql return all rows where a value exists in a column	select pid from tablename where column1 = 'a' 	5.08638070816826e-05
18173993	17134	php code to display current date infor only from sql	select * from e_track_access_log where member_id>0  and datetime_accessed < getdate ( ) order by datetime_accessed desc limit 0,10 	0
18176416	5959	join fields in the same table	select t.id, p.name as name1, t.name from table t join table p on p.id = t.idparent; 	0.0034786389784764
18176660	1526	select group by count	select   f.name,   sum(p.downloads) as downloads from files as f   inner join permission as p on p.file_id = f.id group by f.name order by sum(p.downloads) desc limit 5 	0.132612985876158
18176686	25729	many to many relationship without duplicates	select articleid,           stuff((select distinct ',' + a.authorfname + ' ' + a.authormname + ' ' + a.authorname                    from articleauthor aa join author a                      on aa.authorid = a.authorid                   where aa.articleid = aa2.articleid                     for xml path('')) , 1 , 1 , '' ) authors   from articleauthor aa2  group by articleid 	0.0539164952851162
18177277	24419	mysql: join based on multiple colums	select      case when user1.winnings > user2.winnings then user1.user     when user2.winnings > user1.winnings then user2.user     else null end from table_2 games join table_1 user1 on games.user_1 = user1.user join table_1 user2 on games.user_2 = user2.user 	0.00415351309809871
18180045	37701	comma separation in sql server	select left(column, charindex(',', column)-1) as column1,         right(column, len(column)-charindex(',', column)) as column2  from table 	0.161091862140312
18180114	21141	mysql select dublicated rows where 2 or 3 column values are reapeated	select id, name, surname from users t1 where    exists(select id from users t2              where t1.id <> t2.id and                    t1.name = t2.name and                    t1.surname = t2.surname) 	0.000344202917075522
18180701	22569	how to merge two order by statements in sql	select * from employeeb37 order by job_id asc, salary desc 	0.0298829028547127
18181037	13688	sql query: current lowest price of products	select l.linkproductid, min(linkprice + linkshippingprice) as minprice   from linkproductseller l,        (select linkproductid, linksellerid, max(linkdatetime) as linkdatetime           from linkproductseller           group by linkproductid, linksellerid) m  where l.linkproductid = m.linkproductid    and l.linksellerid = m.linksellerid    and l.linkdatetime = m.linkdatetime  group by linkproductid 	0
18183032	11014	sql query for a key referencing pk	select  e.empid , e.empname , e2.empname from tableemp e left join tableemp e2 on e.managerid = e2.empid 	0.394903910327349
18183045	37288	query to get price from one record and date from another	select row_number() over (order by cte3.update desc) as row_num,         (select innerquery.update from last_two_items as innerquery          where innerquery.idorder = 1 and           innerquery.toy_id = cte3.toy_id         ) as update,         cte3.price_previous as price_previous,         cte3.price_current as price_current,         cte3.id as id,         cte3.toy_id as toy_id from last_two_items as cte3 where idorder = 2 	0
18183363	4695	insert in other table from other table with a fix value	select @newid ,        string  from   [dbo].[stringsplit](@selectedtables,',') 	5.78934756345004e-05
18183744	38331	postgresql, getting min and max date from text column	select max(to_date(nullif(mydatetxt,''), 'dd.mm.yyyy')),        min(to_date(nullif(mydatetxt,''), 'dd.mm.yyyy')) from table_name; select max(to_date(nullif(mydatetxt,''), 'dd.mm.yyyy')),        min(to_date(nullif(mydatetxt,''), 'dd.mm.yyyy')) from table_name where date_part('year',to_date(nullif(mydatetxt,''), 'dd.mm.yyyy')) = 2012; 	0.000813018101453522
18187360	3701	select all ids that have that value in mysql	select group_concat(item) as group_item from (select table1.id, table1.item, table1.date        from table2 table2 inner join table1 table1       on (table2.item = table1.item) where table2.item like "a%"        order by table1.id, table1.date, table2.item) as temp group by id having group_item like '%f45%' order by id 	0
18188586	10077	mysql select records having difference of hours	select t.* from t where exists (select 1               from t t2               where t2.id <> t.id and                     t2.date between t.date - interval 36 hour and t.date + interval 36 hour              ); 	7.89377991276125e-05
18190275	4392	mysql select rows using cross reference but omit on a condition	select *  from newsletter_subscribe as a, newsletter_subscriber as b where (a.group_id = 1 or a.group_id = 4) and (a.subscriber_id = b.subscriber_id) and (b.subscriber_id not in (select subscriber_id from newsletter_subscribe where group_id = 3)) 	0.0349624864459242
18190463	4561	selecting only integer data within a column with characters	select * from mydb where isnumeric(sku) = 0x1 	0.000295378427933497
18190535	21204	sql return name of most popular / unpopular category	select category_name, count(apps.app_category) from categories left join apps on apps.app_category = categories.category_id group by category_name order by count(apps.app_category) 	7.03400498588215e-05
18192445	19192	how to convert the now() to timestamp	select unix_timestamp( now() ); 	0.00397411928235161
18193365	16285	count of non-null columns in each row	select     t.column1,     t.column2,     t.column3,     t.column4,     (         select count(*)         from (values (column1), (column2), (column3), (column4)) as v(col)         where v.col is not null     ) as column5 from table1 as t 	0
18193400	19908	sql command to find when a document was last printed?	select doc_name, max(date_printed) from your_table group by doc_name; 	0.00173257764164333
18193771	105	obtaining a value from 2 different case statements	select description, case_1, case_2, case_1 - case_2 from  (select p.description as description    case ( when s.monthid between 201301 and 201307 then sum(s.amount) else 0 end) as case_1    case ( when s.monthid between 201303 and 201305 then sum(s.amount) else 0 end) as case_2  from sales s, product p  where s.productid = p.productid   and p.productid in ('1, '2', '5')  group by p.description ) 	0.0015138231807372
18194481	18940	sql query, how to get all elements from one list and only the similar ones from another table	select `sheet1$`.enspieceid, `sheet1$`.`part number`, `sheet1$`.description,`sheet1$`.titretype, `sheet1$`.utilization, `sheet2$`.notes, `sheet2$`.justification from `sheet1$` `sheet1$` left join `sheet2$` `sheet2$` on `sheet1$`.enspieceid = `sheet2$`.enspieceid 	0
18194950	9225	mysql query to group by date range?	select time_logged,        date_format(start_date - interval 12 day, '%y-%m') as `month_logged` from work_log group by month_logged; 	0.0148842833794466
18195047	20214	sql server inserting a previous value into the new column	select t.customername, isnull(tp.billdate, '20130701') as cyclestartdate from table1 as t    outer apply (        select top 1 t2.billdate        from table1 as t2        where t2.customername = t.customername and t2.billdate < t.billdate        order by t2.billdate desc    ) as tp 	5.09075483981403e-05
18196262	9996	pulling a blank result	select distinct company  from `roster`  where length(company) > 0  order by company asc; 	0.0350797627343654
18196792	23786	sql server date insert	select convert(datetime,'jul 14 2005 12:00:00:000am') 	0.170673608162293
18199125	30795	how to get sum with different description in column	select name,          sum(total) total_sum     from tablename group by name 	0.000186671762819949
18199393	13519	mysql query to determine if member is a friend of a friend to another member	select * from profiles where id in (select viewers friends ids) and id in (select the viewed users friends ids); 	0.00013678577274269
18199731	27778	compare between strings in query statement in oracle	select sum(value), max(value), min(value) from my_table where id between 'aa000001' and 'aa000007'; 	0.133154851983921
18199770	14033	how can i group by the difference of a column between rows in sql?	select grouping, min(created_at), max(created_at) from (select t.*, sum(groupstartflag) over (order by created_at) as grouping       from (select t.*,                    lag(created_at) over (order by created_at) as prevca,                    (case when extract(epoch from created_at - lag(created_at) over (order by created_at)) < 130                          then 0 else 1                     end) as groupstartflag             from t            ) t      ) t group by grouping; 	6.14018898155511e-05
18202551	10390	concatenate the result of multiple case when statement	select   case when t1.field is not null then 't1,' else '' end + case when t2.field is not null then 't2,' else '' end + case when t3.field is not null then 't3,' else '' end as result from t1  left outer join t2 on ... left outer join t3 on ... 	0.0742857543391628
18204592	29076	sql multiple from select adding count	select t1.count, t1.date, t1.active, user_profile.id 'user_id', user_profile.name, user_profile.avatar, package_content.* from (    select count(package_comment.package.id)'count', 'package_id', package.user_id 'user_id', package.date 'date', package.active 'active'    from package    left join package_comment on package_comment.package_id = package.id and package_comment.view_by_package_author  = 0    where package.user_id = 3    group by package.id    order by package.id desc    limit 0,20 )t1 left join package_content on package_content.package_id = t1.package_id left join user_profile on user_profile.id = t1.user_id order by t1.package_id desc, package_content.order_id asc 	0.0161599349483903
18204714	37700	intersect table with different column value	select num from your_table where num not in (   select num   from your_table   where type = 'b' ) 	0.00288067796969456
18206408	38205	sql: how to return max and min in one row?	select      a.outletcode,      a.productid,      latestdate,     min(cost) as minprice from     (     select max(costingdate) as latestdate,     outletcode,     productid       from accountscosting     where outletcode = 'c&t01'     group by outletcode, productid     ) a     left join      from accountscosting b     on     a.outletcode=b.outletcode     and a.productid=b.productid       and a.latestdate=b.costingdate     group by a.outletcode, a.productid, latestdate 	0.000358406758281548
18208578	6713	how to return one row from group by multiple columns	select id, customer,division, address from  ( select  id, customer,division, address, row_number() over (partiton by customer order by id) as rn from t ) t1 where rn=1 	0
18210019	28400	mysqli fetch only a specified amount of chars from row?	select id,byid,left(content, 25) as cut,date_added from articles where id='1' limit 10"; 	0
18210724	31198	how to use select column aliases in subqueries?	select year,        trainees,        nct,        ndt,        nct / (nct + ndt) ratio   from (  select count (case when t.id_status = 5 then 1 end) nct,                  count (case when t.id_status in (6, 7) then 1 end) ndt,                  (select count (ti.id) trainees                     from trainings_inscriptions ti                    where ti.id_training = t.id)                     trainees,                  date_format (t.date, "%y") year             from trainings_trainings t         group by date_format (t.date, "%y")) 	0.772221648374016
18210939	27373	t-sql finding percentage/ratio of two rows	select      org_code_prov,     the_date,     100.0 * sum(case the_number when 'invalid' then amount else 0 end) /     nullif(sum(amount),0)     from  (      select * from yourquery ) results group by     org_code_prov,     the_date 	0.000778977509626359
18213362	1800	php sql output issue adding a third table to a query	select * from     `venues` as table1 left join `follows` as table2 using (venue_id) left join `stats` as table3 using (venue_id, user_id) where table2.user_id = $userid 	0.535486001053034
18213678	2639	sql joining corresponding values in a table	select      b.id, a.cusip_id1 no_indx_cusip, max(abs(a.cor)) maxcor, dt.dt_pnts from       tbl1 a inner join     tbl2 b on         a.cusip_id1 = b.cusip_id inner join     (select cusip_id1, cor, dt_pnts from table1) dt on a.cusip_id1 = dt.cusip_id1 where     a.dt_pnts > 10 group by a.cusip_id1, b.id, dt.dt_pnts, dt.cor having dt.cor = max(abs(a.cor)) 	0.00140077529548929
18214340	31666	column as content with for xml path query in sql server	select      p.cfprojid,      p.cfacro,     (         select             pt.cflangcode as [@cflangcode],             pt.cftrans as [@cftrans],             pt.cftitle as [text()]         from cfprojtitle as pt         where pt.cfprojid = p.cfprojid         for xml path('cftitle'), type     ) from cfproj as p for xml path('cfproj') 	0.363536300115139
18214407	40503	create multi column view from single column data	select eventid  , min(p_num) as p_num1, min(pn_namecount1)  pnc1, min(pn_name) as pn_name1 , max(p_num) as p_num2, max(pn_namecount1)  pnc2, max(pn_name) as pn_name2  from table  group by eventid 	0.000512397255181854
18215551	36138	how do i execute the contents of a field as a statement in mysql?	select concat('update a set b = ', c, ' where d = ', e, ';') as query    from x into outfile '/tmp/update_a.sql'; source '/tmp/update_a.sql'; 	0.00859705770863648
18216959	28771	grouping mysql data by which day of the week it is	select dayofweek(date), count(*) from table group by dayofweek(date) 	0
18217881	15469	sql server 2005 similar to split	select ope_autoventaid, substring(ope_name, charindex('latitud:',ope_name)+8,                     charindex('|longitud:',ope_name)-9)     as latitud, substring(ope_name, charindex('longitud:',ope_name)+9,                     charindex('|timegps:',ope_name)-9-charindex('longitud:',ope_name))     as longitud, substring(ope_name, charindex('timegps:',ope_name)+8                   , len(ope_name)-charindex('timegps:',ope_name))     as timegps from mytable; 	0.198575025971937
18218578	16255	priority of an or statement sql	select top (1) * from  (   select top (1) *, o = 1   from person   where workgroupid = 2    union all   select top (1) *, o = 2   from person    and roleid = 2 ) as x order by o; 	0.425363673930764
18219808	5098	search for all strings that have a space in between using sql query	select col_name from table_name where col_name like '% %'; 	0.00457986988854105
18221869	4898	search for multiple values, sort by relevance (php + mysql, no full text search)	select ((col like 'term1') +         (col like 'term2') +          . . .         (col like 'termn')        ) as nummatches from t having nummatches > 0 order by nummatches desc; 	0.147189733331525
18221999	16336	group by having max date	select n.*  from tblpm n  inner join (   select control_number, max(date_updated) as date_updated   from tblpm group by control_number ) as max using (control_number, date_updated); 	0.0721623114474279
18222574	17512	get single data from table that has multiple values	select distinct ruper from bsl_ruang b join mr_ranap_dokter d on (b.noregis=d.noregis) where d.dokter = '11111' 	0
18224165	15256	number of occurrences above a certain number sql	select id , count(order id) from yourtable group by id having count(order id) > 4 	0
18225405	19622	sql inner join on two tables	select users.name,         users.user_id  from   users         inner join managers             on users.user_id = managers.user_user_id  where  managers.manager_user_id=1000011 	0.201532198458852
18227191	34991	datetime string to date, in time and out time	select nip,        nama,        date_format(date_time, '%y-%m-%d') as date,        case min(date_time)           when max(date_time)            then ''           else date_format(date_time, '%h:%i:%s')         end as intime,        date_format(max(date_time), '%h:%i:%s') as outtime   from attd  group by nip,        nama,        date_format(date_time, '%y-%m-%d') 	0.00124600957066406
18228340	37959	select statement having multiple conditions over multiple columns	select count(*) from dual where exists (                select 1                  from mytable                 where (key = 'a' and value = 'v1')                                      )  and exists (                select 1                  from mytable                 where (key = 'b' and value = 'v2')                                      ); 	0.0750081739175572
18230019	12049	combine several row into one row	select     t1.count_no   t1.desc   ifnull(t2.desc2,t1.desc2) as desc2   t1.amount from t t1 left join t t2 on t1.count_no=t2.override 	0
18230064	36645	sql select query	select <what you need>   from menus, menu_item, products  where menus.uid = menu_item.uid     and menus.uid = product.uid     and menu_item.ref_id = 1 	0.448716452127667
18232627	26565	sql query to show all column values as a single statement adding some strings related to each other	select x.ename||' is a ' || x.job||' and his manager is '||y.ename||' having salary '||x.sal||' from department '||d.dname from emp x, emp y, dept d where x.mgr = y.empno(+) and x.deptno = d.deptno 	0
18233310	34235	sql - calculate consumption of materials based on recipe	select recipes.id_raw_materials,             sum(orderscontent.qnt) as qnt_sum,            sum(products.price * orderscontent.qn)) as value        from orders, orderscontent, products, recipes, rawmaterials       where orders.id = orderscontent.id_order         and products.id = orderscontent.id_product         and recipes.id_product = products.id         and recipes.id_raw_material = rawmaterials.id       group by recipes.id_raw_materials 	0.000847063532081174
18233325	19809	select results from one query to another	select a.* from table2 a join table1 b   on a.id = b.id where b.name like 'test%' 	0.000558368382751434
18235007	41069	select all values from table that match all values of subquery	select * from table where tableid in(select tableid  from table1  where tableid like '%this%') 	0
18235179	39733	fetching data into local table type	select new my_obj( field1, field2, field3)     bulk collect into v_temp_table     from table1; 	0.00999417141394622
18236076	36355	mysql select count of multiple ids occurring in another table	select   tool.description,   count(case when purpose.id = <id for class> then 1 end) as `purpose: class`,   count(case when purpose.id = <id for student club> then 1 end) as `purpose: student club`,   . . . and the rest of the purpose.id values from user_tools left join tool on user_tools.tool_id = tool.id left join purpose on user_tools.purpose_id = purpose_id group by tool.description 	0
18238720	28612	match sentences containing a given word	select * from yourtablename      where sentencecol like 'your-search-word %'      or sentencecol like '% your-search-word %'      or sentencecol like '% your-search-word' 	0.0073793584419407
18239449	23981	complex sql query (sum entries)	select  o.id,         o.tax,         sum(od.price) sum_price,         group_concat(itemname) all_names from    orders o inner join         detailorders do on o.id = do.id group by o.id,          o.tax 	0.137877741126679
18240767	34475	mysql find first and last rows of rows with matching values in the same column	select  id         ,date         ,unique_id from    (         select  min(id) as id                 ,min(date) as date                 ,unique_id                 ,count(id) as rec_count         from    table         group by                 unique_id         union         select  max(id) as id                 ,max(date) as date                 ,unique_id                 ,count(id) as rec_count         from    table         group by                 unique_id         ) sq where   sq.rec_count > 1 	0
18242477	28461	order by within join ordering	select w.*  from  [dbo].[scores] as w join @scorestable as s on s.areaid = w.areaid where [id] = @id order by s.areaorder, w.score 	0.589352270413225
18242498	35026	merge multiple queries excluding common results	select distinct id from table1 where zonename="name1" 	0.00123424374360061
18247702	31443	join 3 tables using foreign keys, with two separate fields returned from the same table	select  concat(p.lname, ', ', p.fname)         u.number         concat(pv.lname, ', ', pv.fname)         v.time_in         v.time_out from    units u left join         people p    on  u.resident = p.id left join         visits v    on  u.id = v.unit left join         people pv   on  v.vis_id = pv.id 	0
18249469	2169	select records for a certain year oracle	select *   from sales_table  where tran_date >= to_date('1.1.' || 2013, 'dd.mm.yyyy') and         tran_date < to_date('1.1.' || (2013 + 1), 'dd.mm.yyyy') 	5.54682165347696e-05
18249596	9070	checking if a date falls in given date range using mysql query	select (now() >= code_valid_from_date and now() <= code_expiry_date) as valid from mycodes 	8.26518450557767e-05
18250097	4968	php mysql join three tables and sum item of same id	select    a.productid,    sum(a.quantity),    b.serial,    b.name,    (select sum(mquantity) from matrequest c where c.matid = b.serial) from    order_detail a  left join    products b        on a.productid = b.serial  group by    b.name 	0
18250367	36685	sql order by an as variable	select a,          b as myb,          c - z,           d + f + g     from mytable order by myb asc,                 3 desc,                  d + f + g asc,           case                       when (a > b + c) then              1            when (a > b)  then              2            else                  3          end desc 	0.592874405359773
18251744	25874	how to prioritise a busy queue so low priority items get processed too?	select * from queue order by priority*( now() - created_at ) desc 	0.0418943544004665
18254694	8544	using a select case statement to compare field values	select isnull(.. massive subquery here..., firstname) 	0.0286642243001635
18258763	24597	how to select data in same table on different line that are empty?	select download_md5_hash from downloads join virustotals on download_md5_hash = virustotal_md5_hash where virustotal in (select virustotal                      from virustotalscans                      group by virustotal                      having count(virustotalscan_result) = 0) 	0
18259130	1985	how to find data between specific range of dates	select number_used  from table_name where '14-4-2013' >= `allocation_date ` and `deallocation_date` >= '2-4-2013' 	0
18259292	30694	a more concise way to format count result with thousands separator?	select replace(convert(varchar, cast(count([id]) as money), 1), '.00', '') from tbl 	0.313487899278394
18259888	8333	mysql joining data from 2 tables based on foreign key in a third, without duplicates or group by	select   p.id  , p.fname  , p.lname from  people as p left join  units as u on  p.id = u.resident  where  u.resident is null 	0
18260594	8246	sql getting data three columns from one table and one from another	select customer_details.cus_name, (sum(sales.bill_amount) - sum(sales.recived_amount)) as       subtract,customer_details.cus_id  from sales inner join customer_details on customer_details.cus_id=sales.cus_id  where sales.cus_id = 1   group by customer_details.cus_name,customer_details.cus_id  order by cus_id 	0
18261542	15289	how to best use sql to find common ids that match multiple where clauses	select t1.id from propertytable t1 join propertytable t2 on t1.id = t2.id where         t1.propertyname = 'color' and t1.propertyvalue = 'blue'     and         t2.propertyname = 'size' and t2.propertyvalue = 'large' 	6.61190311259653e-05
18264750	19069	get distinct results in sql statement and order by random	select * from      (select distinct on (mem_id) mem_id, media_id      from battle_entries      where active='1' and mem_id!=1) s  order by random() limit 2; 	0.0246545163162196
18267318	3256	join with datetime and latest value from another table	select  s.id,         s.name,         r.value,         r.timestamp from    station as s         inner join reading as r         on s.id = r.station_id where   r.timestamp = (     select max(timestamp)     from reading     where reading.station_id = s.station_id ) 	0
18268027	7352	finding and deleting duplicate rows in table where multiple occurances of records is allowed	select count(booknumber), booknumber, customerid from tablename group by booknumber, customerid having count(booknumber)> 1 	0
18268810	2230	sqlite - selecting records that don't have a counterpart in another table	select distinct p.id,                 p.[first name],                 p.[last name] from people as p join [course enrolment] as ce on p.id = ce.[person id] join courses as c on ce.[course id] = c.id left join [course participation] as cp on cp.[person id] = p.id and                                           cp.[course id] = c.id where cp.[date taken] is null    or cp.[date taken] < date('now', '-' || c.[course refresh rate] || ' year') 	0
18269490	10849	php mysql sum with decimal format	select format(sum(cast(replace(replace(col,',00',''),'.','') as signed)), 2)    as sumofcolumn     from tab 	0.128299731433536
18269681	7331	select rows in master table which have no join in subtable	select * from result where not exists (select 1 from confirmation where confirmation.result_id = result.result_id) 	0.000235709324999924
18270658	556	using sql to query an xml data column	select [value].query('data(eform/page/belief/item[@selected="true"]/@value)') from test 	0.157521803796496
18272719	16947	selecting range of records with mysql	select  @currow := @currow + 1 as row_number,     mytable.id from mytable  limit 5 offset 6; 	0.000181881049040691
18274656	28116	query where row contains a variable's data	select * from brand where ? like concat(brand_name, '%') 	0.0237231622316517
18277856	30573	append color values to query results	select t.locationid, t.totalsales, t.dbaname,c.color from @t t join @colors c on t.locationid=c.locationid 	0.0510023770349842
18279067	20824	order of multiple columns in index by value diversity	select * from t where c1 = 'foo' and c2 = 'bar' select * from t where c1 = 'foo' 	0.00470070439435418
18280138	6469	select rows the the second highest value in a column	select max(time) from yourtable where time < (select max(time) from yourtable) 	0
18281958	28154	how do i compare 2 records in the same table with wildcard?	select `t1`.*, `t2`.`value` as `url_path` from `catalog_category_entity_varchar` as `t1` left join (     select `catalog_category_entity_varchar`.`value`,         `catalog_category_entity_varchar`.`entity_id`,         `catalog_category_entity_varchar`.`attribute_id`     from `catalog_category_entity_varchar` ) as `t2` on `t1`.`entity_id`=`t2`.`entity_id` where `t1`.`attribute_id` = 43 and `t2`.`attribute_id` = 57 and `t1`.`value` != `t2`.`value` 	7.62580834198463e-05
18282596	13100	mysql database how to select column with repeated entires after inner join	select   article.id,   article.name,   count(*) as tagcount from article join article_tag on article.id = article_tag.article_id join tag  on tag.id = article_tag.tag_id where tag.name  in ('science', 'technology', ... ) group by   article.id,   article.name order by   tagcount desc 	0.364710957965439
18285206	15804	oracle sql minus on 3 tables	select c.clientid, c.clientname   from booking b join client c     on b.clientid = c.clientid join motel m     on b.motelid = m.motelid  where m.motelname = 'motelone' minus select c.clientid, c.clientname   from booking b join client c     on b.clientid = c.clientid join motel m     on b.motelid = m.motelid  where m.motelname = 'moteltwo' 	0.282853469798375
18285903	20716	find out the nth-highest salary from table	select * from 'tblname' where salary = (select * from (select * from (select * from (select distinct(salary) from 'tblname' order by salary desc) where rownum <= nth) order by salary asc) where rownum <= 1) 	0.000112179709661411
18286084	13840	php/mysql multiselect from tables	select   t1.* from   activity as t1   join friends on t1.activity_user=friends.fr_id where   friends.user_id='$user_id' order by t1.id desc limit 10 	0.0233203630007419
18287802	25838	how to collect mysql base path using jpql?	select @@basedir 	0.234034964699278
18291185	34933	how to combine many to many join?	select c.cust_id, sum(b.amt) - sum(p.amt) as due_amt from cust c left join bill b on b.cust_id = c.cust_id and b.status = 'open' left join payment p on p.bill_id = b.bill_id group by c.cust_id 	0.0626014606132193
18291196	40777	sql - compare a non related table	select a.name, a.salary, b.salary_grade from a join b  on a.salary between b.lower_bound and b.upper_bound 	0.0015314686806799
18292024	11845	mysql use result of subquery	select id, sum(points) as summary from my_table group by id having summary >= (select sum(points) from my_table where id=1234) order by summary desc 	0.5762178486349
18292702	37039	mysql select sum with limit and where	select sum(points)  from  (select points from user_table  where city=1 and group =5 order by points desc limit 2)  as t1 	0.330278009128257
18294085	13922	simple select query returning empty result set?	select * from `votes` where `user_id` = 8 and `image_id` = 5; 	0.765119467166178
18295261	26648	check for capitalization of second word in mysql field	select t.*, substring_index(substring_index(column1, ' ', 2), ' ', -1) second_word    from table1 t  where char_length(column1) - char_length(replace(column1, ' ', '')) > 1 having binary left(second_word, 1) = binary upper(left(second_word, 1)) 	0.000522888189402272
18301194	30094	and query a m-to-n table	select a from table1 where b in ('x', 'y') group by a having count(distinct(b)) = 2 	0.210579056327977
18303004	10358	how to find total of sum of rows in mysql?	select sum(s) as score from (select sum( mark_score ) / sum( full_mark ) *50 as s     from nuexam     where regd = '22'     group by subject) table 	0
18304622	19478	sql multiple select ... where id in and a distinct	select distinct tp_test_info.id, tp_test_info.name from tp_test_info join tp_test_sections    on tp_test_sections.test_id = tp_test_info.id join tp_test_questions    on tp_test_questions.section_id = tp_test_sections.id join tp_student_answers    on tp_student_answers.question_id = tp_test_questions.id where tp_student_answers.student_id = 751 	0.0107496072704052
18305920	7935	empty table causing in null in all select fields	select max(aaa) as aaa, max(bbb) as bbb, max(ccc) as ccc from ( select max(ifnull(chata.postorder,0)) as aaa, 0 as bbb, 0 as ccc from `chata` union all select 0 as aaa, max(ifnull(chatb.postorder,0)) as bbb, 0 as ccc from `chatb` union all select 0 as aaa, 0 as bbb, max(ifnull(chatc.postorder,0)) as ccc from `chatc`)  as derived_table; 	0.0124026618109448
18305946	26167	showing all categories for every product for which it belongs to in one query	select a.products_id, a.products_name,  group_concat(convert(b.categories_id,char(8))) as products_to_categories from a,b  where a.products_id = b.products_id group by a.products_id, a.products_name 	0
18307830	910	mysql count unique grouped items in a table	select partno, count(entry) from table_name where po = 'specific_po' group by partno; 	8.47018870342777e-05
18308466	1987	combining 3 output from 3 queries in mysql and do some calculations	select round(sum(incorrect/answered)/count(*), 3) as result from ( select qa.questionid,  sum(if(qa.rightanswer <> qa.responsesummary, 1, 0)) as incorrect , count(*) as answered from mdl_question_attempts qa     inner join mdl_question_attempt_steps qas     on qa.id = qas.questionattemptid where qas.userid = $user group by qa.questionid having incorrect > 1 ) as totals 	0.0194735478448843
18309368	38992	count number of occurrences in table	select      l.title,     count (a.id) as cnt from      listings l inner join      ads a on a.userid = l.userid where      l.listingtype = 2 group by l.title 	0.000119866361557545
18310355	17075	getting the sum from other tables rows based off a remote foreign key value in original table	select *, labor + parts as total from (select unit as vehicle,              date,              po,              invoice,              (select total(extended)               from vehicle_service_labor               where invoice = vehicle_service_invoice.invoice              ) as labor,              (select total(extended)               from vehicle_service_parts               where invoice = vehicle_service_invoice.invoice              ) as parts       from vehicle_service_invoice) order by date,          invoice 	0
18311074	1621	select a row based on a particular condition	select distinct custid from t as t1 where visittime between '2013-01-01 00:00' and '2013-01-31 23:59' and not exists (select t.custid from t                         where t.custid=t1.custid and visittime < '2013-01-01') 	5.37034369448881e-05
18311416	13500	get row numbers for mysql query, then filter where row number between values	select * from (     select l.id, l.name, l.value, @currow := @currow + 1 as row_number      from (         select * from $table          order by name asc     ) l      join (         select @currow := 0     ) r ) t  where row_number between $start and $end 	0
18311697	25029	mysql inner join of 2 different tables on 2 different coloumns that are part of both said tables	select tbl1.*, tbl2.*  from tbl1 inner join tbl2  on tbl1.id=tbl2.customer_id  where whateverconditions  group by tbl1.firstname, tbl1.lastname, tbl2.room 	0
18313330	16934	recursive sql query. select last entry grouping by	select x.*      from carrier_fares x      join           ( select destination                , max(effective_date) max_date              from carrier_fares             group                by destination         ) y        on y.destination = x.destination        and y.max_date = x.effective_date ; 	0.00308923975057488
18314357	10440	sql of a daterange without empty spaces	select driver.timestamp, coalesce(t.value, 0) as value from (select distinct timestamp + n.n as timestamp       from t cross join            (select 0 as n union all select 1 union all select 2 union all select 3            )      ) driver left outer join      t; 	0.131679601391043
18315866	10548	how to create a stored procedure with a combination of 3 columns as the parameter?	select * from table where name+surname+number+age = @reportparam 	0.00425987416900223
18316722	14563	count subselect elements according to parent id	select  t1.article_id,         t1.user_id,         t1.like_date,         count(*) as totallike from liketbl t1 inner join liketbl t2 on t1.article_id=t2.article_id where user_id = 1 group by t1.article_id,t1.user_id,t1.like_date; 	0.000168986593972597
18316893	18672	how to estimate the size of one column in a postgres table?	select     sum(pg_column_size(the_text_column)) as total_size,     avg(pg_column_size(the_text_column)) as average_size,     sum(pg_column_size(the_text_column)) * 100.0 / pg_relation_size('t') as percentage from t; 	0.000169541096615268
18317833	8935	summarize log data into change history with sql statement	select t1.* from t as t1     outer apply (         select top 1 t2.*         from t as t2         where t2.worktime < t1.worktime         order by t2.worktime desc     ) as t2 where     t2.worktime is null or     t2.department <> t1.department or     t2.worktitle <> t1.worktitle 	0.253255418775543
18318315	40161	rating for users	select name     from respondent_user     where rating = (select avg(answer.user_rating)                          * count(answer.user_rating)                           / datediff(minute,                                      sysdate() - 7 day,                                     sysdate()                                    )                     from question                      join answer                        on [some condition]                  ) order by rating asc 	0.0267429382243035
18319914	38452	hana timestamp query - age of tracefile	select *, seconds_between(current_timestamp, file_mtime) from m_tracefiles 	0.0131543724648755
18322488	25066	transpose/pivot rows to columns and sum	select    peakrange,   coalesce([day 0], 0) [day 0],    coalesce([day 1], 0) [day 1],    coalesce([day 2], 0) [day 2],   coalesce([>2 days], 0) [>2 days],   peak_total from (   select peakrange, daysofreq, total,     sum(total) over(partition by peakrange) peak_total   from requirementrange ) d pivot (   sum(total)   for daysofreq in ([day 0], [day 1], [day 2],                     [>2 days]) ) piv order by peakrange; 	0.00197625676026492
18325389	761	sql server query for values within same table	select clientid  from table1  where (parameter='street' and value='evergreen') and clientid in (select clientid from table1 where parameter='zip' and value='75244') 	0.00765131292371568
18328697	38524	how to get records in mysql where first letter equals 'x', when dealing with spanish characters?	select * from recording where title regexp '^[^a-za-z]*[pp]' 	0
18329769	27806	select inside select statement returns 0 count	select count(distinct concat(date_reserve, ' ', start_time)) as my_count, date_reserve,borrowerid,start_time,end_time from schedule where borrowerid = 'bobi' 	0.660482679213364
18330866	1318	concat sql result rows on scertain fields	select min(id),        mark,        cost,        substr( xmlserialize( xmlagg( xmltext( concat( ' ', comment ) ) ) as varchar( 1024 ) ), 3 )   from t1  group by mark,           cost; 	0.0170876991654097
18333421	4194	mysql query select from one table and join results with other table	select * from messages  left join users on users.user_id=messages.user_id where `1st number` between $x and $z  and `2nd number` between $x and $z order by time desc 	0.000289615523482124
18333516	40140	need to join 3 tables on different columns	select name from gc where google_id = (     select google_id from c2g where category_id = (         select max(category_id) from p2c     ) ); 	0.00320652906853728
18333795	38459	selecting dates till current date - mysql	select       @curday := date_add( @curday, interval 1 day ) as calendarday    from       ( select @curday := date_add( date_format(now(),          '%y-%m-01'), interval -1 day) ) sqlvars,       anytableinyourdatabasewithatleast31records    where       @curday <= now()    limit       31 	0
18333952	21251	duplicate topic title search from 1 poster	select topic_poster_id, topic_title, topic_time, forum_id, topic_first_post_id, topic_first_poster_name, topic_id, topic_poster, count( * ) totalcount from phpbb3_topics group by topic_poster_id, topic_title having count( * ) >1 	0.00123492826119203
18338232	29751	sql get n last unique entries by date	select *  from t  where id in (select top 10 id              from t              group by id              order by max([date]) desc             ) 	0
18339136	6225	mysql sort column based on field from another table	select p.product_id,         p.title,         p.brand_name,         p.price,       (p.price*(1-ifnull(b.discount,0) * 0.01)) as discounted_price from products p left join brands b     on p.brand_name = b.brand_name order by discounted_price asc 	0
18342262	38093	select all years that greater than 5 years ago from year today	select * from table1 where b > year(current_timestamp) - 5 	0
18343636	24149	how do you query for something in sql and exclude the results from a sub query?	select * from  ( select row_number() over (order by t0.name asc, t0.accountid) as rownumber, t0.accountid as pkt0 , t0.name as cn , t0.name as c1 , t1.name as c2 , t1.homephone as c3 , t1.mobilephone as c4 , t1.officephone as c5 , t1.contactid as pkt1 from [account] as t0 left join [contact] as t1 on t0.primarycontactid = t1.contactid where  (t0.shippingaddresslatitude >= 33.3293500798248 and t0.shippingaddresslatitude <= 34.7751179201752 )  and not( t0.shippingaddresslatitude >= 33.6907920399124 and t0.shippingaddresslatitude <= 34.4136759600876 ) and (t0.shippingaddresslongitude >= -119.11615629035 and t0.shippingaddresslongitude <= -117.37121370965 ) and not (t0.shippingaddresslongitude >= -118.679928573928 and t0.shippingaddresslongitude <= -117.807441426072 ) and (t0.deleted = 0)) ) _tmpinlineview where rownumber > 0 	0.0463775061556276
18344603	23662	creating 2 columns from 1 main column in the same table	select top 1000 [variable]  case [variableid]   when 1 then 1   else 0 end as val1,      case [variableid]   when 4 then 1   else 0 end as val2                        from [onlineqnres].[dbo].[tmp_datasets] where [variableid] = 1 or [variableid] = 4 	0
18346739	9091	how do i return only those customers who owe me money (in mysql)?	select customer.firstname, customer.lastname, customer.accountnumber, sum(amount) as balance from customer join payment on customer.cid = payment.cid group by customer.accountnumber having sum(amount) > 0 	0.000293246732105389
18347859	15964	select statement where id is in other table	select s.* from shares s, followers f where f.follower_id = :user_id   and s.user_id = f.following_id 	0.00805226106785383
18347989	32877	how to know if a row has a foreign key on other table	select * from table1 t1 where not exists (select * from table2 t2 where t2.personid=t1.personid) 	0
18348905	8203	return whether an array of values exists in a column?	select case when t.val is null              then 0 else 1 end value_exists   from  (   select 400 val union all   select 200 union all   select 100 union all   select 700 union all   select 900 ) a left join table1 t      on a.val = t.val 	8.51318664949575e-05
18348924	32612	get last updated time for all items grouped by category	select * from `my_table` a where not exists (     select 1 from `my_table` b     where b.`category_id` = a.`category_id`     and b.`updated_timestamp` > a.`updated_timestamp` ) order by `updated_timestamp` 	0
18352137	20710	select from a select mysql	select cont, count(id)  from  (     select *     from protable     where match (prodtitulo) against ('art' in boolean mode) ) as t    group by cont 	0.0178443292468794
18353291	16852	retrieving data from table that not have any id	select     t.transactid,     t.tbarcode,     l.locname,     v.vtype,     t.dtime,     t.plateno,     ps.ps,     pc.platecode,     p.comments,     (select top 1 emailsubject from emailsubject_tbl ) as emailsubject from dbo.policerecord_tbl p inner join dbo.transaction_tbl t on t.psid = p.psource and t.pcdid = p.pscode and t.plateno = p.pnumber join dbo.location_tbl l on l.locid = t.locid join dbo.vtype_tbl v on v.vtid = t.vtid join dbo.platesource_tbl ps on ps.psid = t.psid join dbo.platecode_tbl pc on pc.pcdid = t.pcdid and t.status in (0, 1)     and t.tbarcode not in (         select tbarcode         from dbo.emailsendlog_tbl     ) and p.deleted = 0 end 	0
18356472	38175	getting rows from this date to this date	select * from bill_detail where datetimeofbilling > '2013/08/18 12:00:00 pm' and datetimeofbilling < '2013/08/20 12:00:00 am' 	0.0122777845069043
18356694	9453	mysql avg on multiple inner join	select round(avg(x.quote_price),2) as avg_value from ( select  quotes.id, sum(p.price) quote_price from    quotes          inner join `system_users`         on quotes.created_by = system_users.id         inner join quote_items s         on s.quote_id = quotes.id         inner join new_products p         on p.id = new_product_id group by quotes.id ) x; 	0.766915863250339
18356917	31938	where in to join how?	select t1.* from table1 as t1 inner join  (    select id    from table1    group by id    having count(*) = 2       and max(awaiting) = 1 ) as t2 on t1.id = t1.id and t1.awaiting = t2.awaiting where t1.awaiting = 1; 	0.482101178410556
18357290	10742	is there a way of discovering which public constants are defined in a package header?	select ui.object_name,         ui.name,        ui.type   from user_identifiers ui  where ui.object_type = 'package'   and  ui.usage       = 'declaration'   and  ui.type in ('constant', 'variable') order by ui.object_name,           ui.name / 	0.142278157342093
18357494	6574	how calculate a value based on the sum of rows to get a value	select t.*, (case when [reg hrs jc] > 40 then [reg hrs jc] - 40 else 0 end) as [ot hrs jc] from     (select [co code], [empl no], [task cd], [day no], [fund co code], [job no], [equip cost cde], sum([reg hrs jc]) as [reg hrs jc] from dbo.mis_fttimecard_ot    where ([date worked] between '8/11/2013' and '8/17/2013')    group by [co code], [empl no], [task cd], [day no], [fund co code], [job no], [equip cost cde]) as t 	0
18358817	2089	compare two large table for unique record	select tablea.unique_ssn from tablea where tablea.unique_ssn not in (select tableb.unique_ssn from tableb) 	5.25570120238304e-05
18359746	39892	how to select items according to their sums in sql?	select sales.name, sales.sales  from sales  join (select name from sales group by sales.name having sum(sales) > 0) as sales2 on sales2.name = sales.name 	4.94819116546022e-05
18360878	2878	postgresql: free time slot algorithm	select * from  time_slots ts where agentid = 7    and userid = -1    and not exists (select 1                   from time_slots ts_2                  where ts_2.userid <> -1                     and (ts.datet, ts.datet + interval '1 hour' * ts.duration) overlaps                        (ts_2.datet, ts_2.datet + interval '1 hour' * ts_2.duration)) 	0.0508097329488923
18362260	3074	a sql query to select a string between two known strings	select substring(@text, charindex('the dog', @text) , charindex('immediately',@text) - charindex('the dog', @text) + len('immediately')) 	0.000862685909471285
18362887	27184	object or column name missing	select distinct table_name  from .information_schema.columns c  inner .sis.tables t  on c.table_name = t.name order by table_name 	0.112583307806748
18364467	4583	sql server aggregates and sum	select  prvdr_num,sum(itm_val) as sumreimb from hha2011num inner join hha2011rpt on hha2011num.rpt_rec_num = hha2011rpt.rpt_rec_num  where wksht_cd='d000000' and line_num = '01201' and clmn_num in('0100','0200') group by prvdr_num order by prvdr_num 	0.697909485312648
18364890	34153	sql query to match events that occur between a set of 30-second time segments	select id, videotime from commands where participant = 2       and exists       ( select time         from (select videotime                from codes               where participant = 2                      and (retrospective ='y' and forks > 0)) as times         where commands.videotime - times.videotime >= 0               and commands.videotime - times.videotime <= 30       ) 	0.000291109512971556
18365797	29182	parse xml with attributes and values	select     t.c.value('@name', 'nvarchar(max)') as name,     t.c.value('text()[1]', 'nvarchar(max)') as descr from @data.nodes('workflow/meta') as t(c) 	0.0778409636637248
18365823	25610	adding escape characters into select	select '(''' + firstname + ''',' as firstname, ... 	0.231783455091667
18366051	17454	sql query flattens order and top order items	select     o.orderid,     max(case when row_num = 1 then oi.productcode end) as productcode1,     max(case when row_num = 1 then oi.quantity end) as quantity1,     max(case when row_num = 2 then oi.productcode end) as productcode2,     max(case when row_num = 2 then oi.quantity end) as quantity2 from order as o    outer apply (        select top 2            oi.*, row_number() over (order by oi.productcode) as row_num        from orderitem as oi        where oi.orderid = o.orderid    ) as oi group by o.orderid 	0.0332023771812076
18366530	29465	regular expression matching a url of pdf in sql select	select links from mytable where links like 'http: 	0.405232773843018
18367267	8037	return results of same id from 2 tables	select per.* from person_per per inner join person_custom cus on cus.per_id = per.per_id where cus.c3 = 2 	0
18367296	15581	select count of 0 from a table	select c.column_name + ' = 0 and '   from information_schema.columns c  where c.table_name = 'table' 	0.00100974207119004
18367817	15820	combining / sorting two datetime tables/arrays/lists	select t1.timestamp, t1.col1, t1.col2, t1.col3, null as col4 from table1 union all select t2.timestamp, t2.col1, t2.col2, t2.col3, t2.col4 from table2 order by timestamp 	0.0331715459668014
18369568	24848	get records which have time filed in next 5 min	select * from `table` where timediff (utc_time, time) < '00:05:00'; 	0
18370417	31000	column split to another column	select substring(fld_detail, 1, charindex(':', fld_detail)-1 ) where isnumeric(substring(fld_detail,1,1)) = 1 	0.000399264230339899
18370657	40993	how to display relational tables	select t1.fieldname1, t2.fieldname2 from `database1`.`table1` t1 join `database2`.`table2` t2 on (...) where ... 	0.00519789029716295
18371270	24690	sql - 3 table mash up (select all left, all right, show status of middle)	select q.product_name, q.account_name,        case when r.product_id is null then 'no' else 'yes' end status   from  (   select product_id, product_name, account_id, account_name     from product p cross join account a ) q left join ranging r     on q.product_id = r.product_id    and q.account_id = r.account_id  order by q.product_name, q.account_name 	0.000216363601031966
18373693	21408	sql group with sum	select name,        sum(amount) as amount,        sum(case when country = 'us' then 1 else 0 end) as us_count,        sum(case when country = 'us' then 0 else 1 end) as non_us_count,        sum(case when country = 'us' then [no. item] else 0 end) as us_no_item,        sum(case when country = 'us' then 0 else [no. item] end) as non_us_no_item from   table group by name,        country 	0.372233862671504
18373891	23032	combining 2 select query in 1 mysql	select usr.custid, usr.fname     from customertbl usr     where usr.createdate < '01-01-2011'      and not exists ( select 1 from orderdate where custid = usr.custid and orddate > '01-01-2011' ) 	0.039392447532708
18376805	7808	mysql count of group by result	select count(*) from user group by userid where name like '%hhh%' 	0.0495436141010573
18377057	7343	select column names that start with x	select `column_name`  from `information_schema`.`columns`  where `table_name`='producten' and `column_name` like 'pweb%' and data_type = 'int' 	0.000207963422756291
18378029	4383	get list of same numbers by date difference	select distinct number from   my_table a join my_table b using (number) where  b.date between a.date and a.date + interval 5 day 	0
18378751	17674	querying for bit/boolean values in vba	select a lot from a lot where t0001_orders.t0001_active is null select a lot from a lot where t0001_orders.t0001_active =0 select a lot from a lot where t0001_orders.t0001_active =1 	0.462771174658547
18380608	29961	how to format now function in mysql	select date_format(now(),'%y%m%d%h%i%s') 	0.309591756835201
18381759	13578	how i select record that not appear in another table	select movies.* from movies left join rating on movies.mid = rating.mid where rating.mid is null 	0.00035250579609565
18382750	11141	remove time from datetime values returned in query	select convert(char(10), datalog.timestamputc, 120) as timestamputc,  metertags.name,datalog.data from datalog inner join metertags on datalog.metertagid = metertags.metertagid where datalog.timestamputc between cast(getdate() - 1 as date) and cast(getdate() as date) and       datalog.metertagid between 416 and 462; 	0.000542335057055357
18384501	8210	mysql: join three tables and show total count	select u.userid, m.themsg, count(mc.commentid) from user u,  left join usermsg m on u.userid = m.touserid left join usermsgcomment mc on m.msgid = mc.msgid group by u.userid, m.themsg 	0.000616050851509099
18384822	24459	how to aggregate the result of an expression?	select sum(docbal) from (select    docbal =  case d.doctype when 'ad' then -d.docbal                            else d.docbal end,   cpnid   from vendor v    inner join apdoc d    on v.vendid = d.vendid    where        d.perpost = 201307       and d.doctype in ('vo','ap','ad')       and d.opendoc = 1       and acct = 210110) a group by cpnid 	0.354191679773848
18384950	17258	getting the sum of a value for two seperate date ranges in a single mysql query	select `empid`      , sum(if(`date` between '2013-08-04' and '2013-08-10',`ttime`,0)) as a      , sum(if(`date` between '2013-08-11' and '2013-08-17',`ttime`,0)) as b   from `table`  where `date` between '2013-08-04' and '2013-08-17'  group by `empid`; 	0
18385683	37719	writing a mysql query that involves 3 tables	select cli.agentid, sum(cfi.commissionamount)     from invoice as ii         inner join clientagent as cli             on ii.clientid = cli.clientid         left outer join creditfee as cfi             on cfi.clientid = ii.clientid and (cfi.issuedate between ii.startdate and ii.enddate)         where ii.invoiceid = cfi.invoiceid and cli.clientagentid = cl.clientagentid         group by ii.clientid 	0.640398828030663
18385819	1489	php & mysql - how to check if two or more rows have the same field value	select min(title) as firsttitle, description, identifier   from table_name   where identifier in (select distinct identifier from table_name)   group by description, identifier. 	0
18386057	33301	denormalize a table	select fred, barney, pebbles, wilma from flinstones join (select fred, max(wilma) maxwilma from flinstones were whatever group by fred) bedrock using (fred) where whatever and wilma = maxwilma 	0.0804998037411156
18386827	6457	having issues returning number of rows along with datetime stamp	select     clientid,     min(timestamp) as timestamp_start,     max(timestamp) as timestamp_end,     count(*) as cnt from tblhistory where    timestamp >= dateadd(hh, -24, getdate()) group by clientid 	0.000401249045838345
18386865	27869	php mysql get position of record in ordered recordset	select count(id) from leaderboards where score >= (     select score from leaderbords where id = $myid ) 	0
18388618	28152	find if something was committed every 6 months	select c.contactkey,c.firstname, c. lastname , ed2.enddate'second most recent', ed.enddate'most recent'  from stma_cm.dbo.contact c inner join (select * from                    (select *,rank() over (partition by contactkey order by enddate desc) as 'rn'                    from eventdefinition                    where wftaskkey in( 120) and eventstatusid=16) as s                         where s.rn =1)  ed on ed.contactkey = c.contactkey left join (select * from                    (select *,rank() over (partition by contactkey order by enddate desc) as 'rn'                    from eventdefinition                    where wftaskkey  in (173,120) and eventstatusid=16) as s                         where s.rn =2)  ed2 on ed2.contactkey = c.contactkey   where  ed.activeind=1 and ed2.activeind=1 order by contactkey 	0.000509884185381745
18389769	2201	join three tables sql	select sum(p.price) - sum(p.cost) as profit from sales s inner join order_detail as o on s.order_id = o.order_id inner join product_details as p on o.product_id = p.product_id where s.date between '15.08.2013' and '16.08.2013' 	0.252305337364427
18390003	25395	return a crosstab to its original table format	select 'person1' as idperson, color, person1 as activated from yourtable union all select 'person2' as idperson, color, person2 as activated from yourtable union all select 'person3' as idperson, color, person3 as activated from yourtable 	0.00424184524308717
18390165	7	difference of total in the same column	select id, year, 'taken' as columndesc,        sum(case when columndesc = 'taken' then amount                 when columndesc = 'not taken' then - amount                 else 0            end) as amount from t group by id, year; 	0
18392124	28457	sql, how to select a column from mysql with a "/" in it	select `post/zip_code` 	0.0109339938267506
18392765	16260	how can i search and replace a string from an undetermined number of columns and tables using mysql?	select concat('update ',tablename, 'set ', column_name,'= replace (',column_name, '''%oldstring%'', ''newstring'') where url like ''%oldstring%''') from information_schema.columns where table_name like  '%somecriteria%' and column_name like '%somecriteria%' 	0.000132538926576327
18393158	2712	sql server selecting records with most recent date time	select t.*  from (     select t.mykey, t.mydatetime     , row_number() over           (partition by t.mykey order by t.mydatetime desc) as keyordernbr     from table t ) a inner join table t     on a.mykey = t.mykey      and a.mydatetime = t.mydatetime where a.keyordernbr = 1 	0
18394682	12486	how to find the longest memo field in any table of my database?	select name from sqlite_master where type = 'table' 	0.000191001001064104
18395080	7166	showing output from two tables but matching them via 3rd table	select w.wine_name, v.variety_name   from wine_variety wv join wines w     on wv.wine_id = w.wine_id join varieties v     on wv.variety_id = v.variety_id 	0
18395831	21115	how to filter results in a select statement in mysql	select distinct `contact` from test.test where `contact`  not in      (select `contact`      from test.test     where `username` = "csmith"); 	0.170429861152884
18396060	37102	query within another query to count amount of items from another table	select p.*       ,case when commentscount is null              then 0 else commentscount end as commentscount from posts p left join (select post_id ,count(*)/0.5 commentscount               from comments group by post_id) as c on p.id = c.post_id; 	0
18396121	36597	one query for every number in row	select * from table_name where column_name in (1,2,3,7,15,25,64,346); 	0.000102284423801984
18396237	14500	compare date and month in sql server for alert system	select * from   table where  datediff(dd,dateadd(yyyy,-datediff(yyyy,birthday,getdate()),getdate()),birthday) between 0 and 7        or datediff(dd,dateadd(yyyy,-datediff(yyyy,anniversary,getdate()),getdate()),anniversary) between 0 and 7 	0.0129704593491473
18396513	32728	selecting maximum column and row id	select max(a.seq), (select id from t1 as b where b.ident=a.ident and max(a.seq) = b.seq limit 1) as id from t1 as a group by a.ident; 	0
18397057	11310	sql separate columns by rows value (pivot)	select module,        sum(case when year='2011' then count else 0 end) as [2011],        sum(case when year='2012' then count else 0 end) as [2012] from t group by module 	0.000501921691135201
18397265	11939	how to order data to the right instead of to the bottom in oracle?	select staff,        sum(case when jobtype=1 then 1 else 0 end) as "1",        sum(case when jobtype=2 then 1 else 0 end) as "2",        sum(case when jobtype=3 then 1 else 0 end) as "3",        sum(case when jobtype=4 then 1 else 0 end) as "4",        sum(case when jobtype=5 then 1 else 0 end) as "5" from t group by staff 	0.00314323118979327
18397388	12223	how to get a count even if there are no results corresponding mysql?	select  months.id as `month` , count(`reports`.date_lm) as `count` from  (   select 1 as id union select 2 as id union  select 3 as id union select 4 as id    union     select 5 as id union select 6 as id union select 7 as id union select 8 as id    union     select 9 as id union select 10 as id union select 11 as id union select 12 as id ) as months left join `reports` on months.id=month(`reports`.date_lm)                        and                         (status = 'submitted')                         and (date_lm > 2012-08) group by months.id  order by months.id asc 	0.000131327688562209
18397940	28994	-sql- summing by other column value	select sum(euro) as euro,merchant_id from  table_name group by merchant_id 	0.00131031077553896
18398164	16854	select on two other queries in oracle	select query1.a,         query2.b  from   (            select q as a             from   somewhere        ) query1,         (               select g as b             from   elsewhere        ) query2 	0.00702464717727752
18398383	1065	concatenating and grouping results from a mysql query	select code,         group_concat(model) as model,         title,         group_concat(colour) as colour from your_table group by code, title 	0.0208254603802359
18398664	17193	sorting over two columns in entity-attribute-value schema	select entry.id as entry_id,         v_brand.value as brand,        v_year.value as year  from entity   join entry      on entity.id = entry.entity_id   join value v_brand      on v_brand.parameter_id = 1      and v_brand.entry_id = entry.id   join value v_year      on v_year.parameter_id = 2      and v_year.entry_id = entry.id where entity.name = 'car' order by year desc, brand asc 	0.0516202519994859
18399505	24466	selecting records with single quotes escaped by double backslashes only	select * from my_table where my_column rlike '[\\]{2}'; 	0.0129288397497857
18400535	39497	how to get start and end rows for null recods in table in sql	select min(datetime) as start_date,         max(datetime) as end_date,         max(datetime) - min(datetime) as days from (   select datetime,          v1,          v2,           sum(case                 when v1 is null and v2 is null then null                else 1              end) over (order by datetime) as group_flag   from foo ) t group by group_flag order by 1 	0.00012147884133719
18400584	14148	how to select where in(other table) but with modification	select *  from pmthist where replace(confirmation, 'voided', '') in(     select str1 as confirmationcode     from @conflisttable ) 	0.439861679868438
18400673	7447	mysql - selecting rows who's id is not present as a foreign key in another table	select distinct d.id, d.name, d.device_id, d.multiuse  from device_ports d  left outer join circuits c on c.physical_port_id = d.id  where   (c.physical_port_id is null and d.device_id = 6)   or (d.multiuse = 1 and d.device_id = 6)   order by d.id 	0
18400856	21310	mysql select if exists (from different table)	select crm.lead_id, crm.id, url, contact, info, status_id, added, last_edited, callback_date, user.user, status.status, crm_updates.status_info from crm inner join user on crm.lead_id = user.id inner join status on crm.status_id = status.id left join crm_updates on crm.id = crm_updates.crm_id  where url like  '%$search%' or contact like  '%$search%' or info like  '%$search%' or status_id like  '%$search%' or added like  '%$search%' or last_edited like  '%$search%' or callback_date like  '%$search%' or user.user like  '%$search%' 	0.00134670834438856
18401219	36251	how do i get last result in group by mysql query (not the first)	select lt_user, max(lt_time_stamp), lt_activity_operation  from log_table  group by lt_user, lt_activity_operation  order by lt_time_stamp desc; 	6.14593056544258e-05
18401505	26682	postgresql - select results if related conditions where not existent	select p.* from partners p where not exists (select 1                    from calls c                   where c.name = p.name                      and c.date between date '2013-05-01' and date '2013-06-01'); 	0.432363310757332
18401809	21515	sql: find a value based on effective date	select e.*,        (select top 1 eh.role         from employeehistory eh         where e.employeeid = eh.employeeid and               e.date >= eh.effectivedate         order by eh.effectivedate desc        ) as role from event e; 	0
18401810	11276	multiple counts in single mysql query	select     sum(fruit like '%06201%') as `apple`,     sum(fruit like '%02206%') as `pears`,                                         ^                                         here from grocery 	0.0504678068666942
18402079	13306	in mysql how do i find rows whose id are not referenced in any other rows in the table?	select parents.* from mytable parents left join mytable childs on parents.id = childs.parent_id where childs.id is null 	0
18404588	20733	mysql- how to get data from 3 table?	select table3.* from table1 left join (table2, table3)  on (table1.gid=1 and table2.uid=table1.uid and table3.cid=table2.cid) 	0.000186148374307274
18404717	29553	query criteria from another form's text boxes?	select [forms]![frmquarter]![startquarterdatetextbox] as start_date; select [forms]![frmquarter]![endquarterdatetextbox] as end_date; 	0.00609142339660244
18404838	37896	php mysql returning result two times (double)	select distinct *    from 32r07,        32r07names   where 32r07.htno = 32r07names.htnon     and 32r07.htno = '$name' select distinct *    from 32r07names   where htnon = '$name' 	0.0438305731231428
18406768	32497	mysql max value for each condition	select gender, max(score) from players group by gender 	0.000357256715544062
18408495	40931	sql join statement based on date range	select a.*, b.* from cdrlogs a inner join employees b   on a.src = b.empext   and a.calldate between b.extstartdate and coalesce(b.extenddate,getdate()) 	0.00224135019020814
18408570	27868	concat group a select in another select	select     id,    genre.name,    group_concat(title) as title,    userid,    status  from     songs  inner join     genre  on     song.id=genre.songid  group by     genre.name  order by     id asc 	0.0214661200485017
18408636	5576	oracle sql - comparing rows	select * from yourtable t where custid in (select custid                  from yourtable                  group by custid                  having min(location) <> max(location)) 	0.0437957441863357
18408763	14046	distinct,regexp apply to field and concat_group in mysql to remove repeated words to stored procedure	select substring_index(substring_index(concat(country,','),',',1),',',-1) as fld   from mytable having fld <> ''  union select substring_index(substring_index(concat(country,','),',',2),',',-1) as fld   from mytable having fld <> ''  union select substring_index(substring_index(concat(country,','),',',3),',',-1) as fld   from mytable having fld <> ''  union select substring_index(substring_index(concat(country,','),',',4),',',-1) as fld   from mytable having fld <> ''  union select substring_index(substring_index(concat(country,','),',',5),',',-1) as fld   from mytable having fld <> ''  union select substring_index(substring_index(concat(country,','),',',6),',',-1) as fld   from mytable having fld <> ''  order by 1 	0.188315031056974
18409535	22123	fm executesql returns different results than direct database query	select count(distinct(ltrim(rtrim(imv_itemid)))) from imv 	0.0786293292061437
18410351	1856	mysql return all unique values in a column along with the last date associated with each	select  `id`, min(`date`), max(`date`) from `relative`.`datatable` group by `id`; 	0
18411182	13255	how to know the value of the int sequential i just inserted in sql 2008 r2	select scope_identity() 	0.00243657681369647
18412441	9271	calculate a variable using 2 mysql tables and make a select based on that variable	select league_id from standings s join teams t on t.id = s.team_id and t.active group by 1 having count(*) < 5 	7.99481793134912e-05
18413615	10964	proper join for adding a 4th table to a query	select  p.pid     , p.title     , c.cid     , c.comment     , c.statustype      , coalesce(cnt.hasclaim, 0) as hasclaim     , pa.fname as pfname     , pa.lname as plname     , ca.fname as cfname     , ca.lname as clname from tblposts p       left join tblusers pa on pa.uid = p.uid       left join tblcomments c on p.pid = c.pid       left join tblusers ca on ca.uid = c.uid       left join (           select pid, count(*) as hasclaim           from  tblcomments            where statustype = 1           group by pid         ) cnt on cnt.pid = p.pid order by p.pid, c.cid 	0.647314701462145
18414182	14688	mysql combine query results from multiple tables	select id, name, sharer, type from (             (select s.id as id,              s.name as name,              s.sharer as sharer,              s.type as type,              s.date as date         from shares s         where id = :id order by s.date desc)         union     (select f.follower as id,              f.following as name,              f.following as sharer,             f.type as type,             f.date as date         from followers f          where f.following = :id order by f.date desc))          order by date desc limit 0,25; 	0.00686591547744456
18420528	7362	sql query - how do i convert a text field containing dollar sign to decimal only (strip out dollar sign)	select id,         cast(replace(replace(ifnull(amount,0),',',''),'$','') as decimal(10,2))  from table1 where cast(replace(replace(ifnull(amount,0),',',''),'$','') as decimal(10,2)) > 0 	0.00938287816111205
18422010	27798	mysql query - grabbing all the records that meet the criteria 3 or more times	select dp.* from delinquent_property dp join      (select parcel, count(*)       from delinquent_property       where year in ('2013', '2012', '2011', '2010', '2009') and            cast(replace(replace(ifnull(due,0),',',''),'$','') as decimal(10,2)) > 0      group by parcel      having count(*) > 2     ) p3     on dp.parcel = p3.parcel where cast(replace(replace(ifnull(due,0),',',''),'$','') as decimal(10,2)) > 0 order by parcel; 	0
18422819	22888	order by 2 columns with sqlite	select u.id as id, u.name as name, 0 as creator from user u  join moderator m on m.forumid=@forumid and m.userid=u.id  union  select u.id, u.name, f.creator from user u  join forum f on f.id=@forumid and u.id=w.creator  order by creator, name 	0.0227851953660109
18423938	17990	mysql selecting max with multiple joins	select a.user_name, a.meeting, a.place_name, a.date    from  (   select a.user, a.meeting, m.date, p.name place_name, u.name user_name     from attended a join meetings m       on a.meeting = m.id join places p       on m.place = p.id join users u       on a.user = u.id ) a join  (   select a.user, max(m.date) date     from attended a join meetings m       on a.meeting = m.id    group by user ) q      on a.user = q.user    and a.date = q.date  order by user_name 	0.130573338781493
18424783	15641	how to echo value from a different table?	select u.name, sender from actions a join      users u      on a.sender = u.id where recipient = 'alice'; 	0
18426467	3463	can you join 2 databases in mysql using php?	select db1table.columniwant, db2table.columniwant from db1.appropiatetable as db1table join db2.tabletojoin as db2table on db1table.id = db2table.id 	0.269249170581174
18426843	39846	mysql select count values from a single column	select `key`, count(*) from `test` group by `key`; 	0.000149050420596587
18427873	19089	sql:using the data as a column	select      p.id,      name,      ford.platenum,      toyota.platenum from     person p     join cars ford on p.id = ford.p_id and ford.car_brand = 'ford'     join cars toyota on p.id = toyota.p_id and toyota.car_brand = 'toyota' 	0.00799238470440046
18429241	36524	how to find common rows in two sets of query results?	select * from hmdb where shamsidate match '1376/05/24 1385/11/12' intersect select * from hmdb where hmdb match 'content:red or keyword:red v_other:true' 	0
18432600	38184	use multiple tables to find a record mysql	select e.* from event e join registration r on (r.event_id=e.event_id) where r.user_id=123 and e.date < current_date() order by e.date asc 	0.0022595197625637
18434146	34010	count tables with the same id in a column and display the highest	select t1.subject from mytable t1 join mytable t2 on t2.thread = t1.id where t1.thread is null group by 1 order by count(*) desc limit 5 	0
18434156	3862	how to perform mathematical formulas on separate query sets	select coalesce(b.gps_coords, c.gps_coords) as gps_coords,        coalesce(b.year, c.year) as year,        coalesce(b.value, 0) + coalesce(c.value, 0) as value   from (   select d.gps_coords, d.year, sum(d.value) as value     from data d join regions r       on d.gps_coords = r.gps_coords    where d.metric = 5 and r.region_id = 1    group by d.gps_coords, d.year ) b full join (   select d.gps_coords, d.year, sum(d.value) as value     from data d join regions r       on d.gps_coords = r.gps_coords    where (d.metric = 4 and r.region_id = 3)    group by d.gps_coords, d.year ) c     on b.gps_coords = c.gps_coords    and b.year = c.year  order by gps_coords 	0.4226498978979
18435348	13942	friend in common query mysql	select u.* from (select id_user_sender as id1, id_user_receive as id2       from frienship f       union all       select id_user_receive as id1, id_user_send as id2       from frienship f      ) f join      users u      on f.id1 = u.user_id group by id1 having max(id2 = 1) > 0 and        max(id2 = 2) > 0; 	0.052579380436705
18438433	32440	count distinct same names	select     firstname, count(*) from table1 group by firstname 	0.000933065499923847
18438494	39906	mysql query sum values into multiple rows	select t.id, q.value   from table1 t join (   select id, sum(value) value     from table1    group by id ) q on t.id = q.id 	0.000974456882890206
18438727	10253	join other table to get count	select item.id, item.type, item.user_id, count(*) from items item inner join items_votes iv on item.id = iv.item_id group by item.id 	0.00142787065178781
18440246	36327	mysql select table and column name	select      concat('t1.', t1.id) as id,      concat('t2.', t2.user) as user, from t1 inner join t2 on t1.user_id = t2.id 	0.00691928778383475
18441327	13637	select statement without including duplicate data	select distinct name, pid from shoe; 	0.0198866249960238
18442346	26141	how can i count different values stored in one cell in sql?	select money,        count(*) from   [table] group by money 	0.000184079727960194
18442693	27680	select multiple values to the same key in multiple tables	select t1.uid from tabl_1 t1 inner join tabl_2 t2 on t1.uid = t2.uid and t2.meta_key = 'location' and t2.meta_value = 'ny' inner join tabl_2 t3 on t1.uid = t3.uid and t3.meta_key = 'school' and t3.meta_value = 'nyu' 	0
18442854	10126	difference between two datetime entries	select hour (eta - sta) from `schedule` where `num`="5567"; 	0
18445333	12499	mysql query that gets all rows until the sum(column) is bigger than x	select     user_id,     days,     date from     (     select         user_id,         days,         date,         @sum_days := @sum_days + days as sum_days     from         mytable     order by         date desc     ) t     cross join (select @sum_days := 0) const  where     sum_days < x  	4.82903973406178e-05
18445794	38479	group returned result by mysql	select name, repeat_status      from `x`      where labref = '111'      group by name ,repeat_status; 	0.143080527821042
18446051	26445	sql between clause returns rows for values outside bounds	select    zipcodelow ,   zipcodehigh ,   zipextensionlow ,   endingeffectivedate ,   beginningeffectivedate ,   addressrangelow ,   addressrangehigh ,   streetname ,   city ,   zipcode ,   zip4,   zip4high   from boundtable   where    ('68503' between zipcodelow and zipcodehigh) and    (convert(numeric,'4929') between [addressrangelow] and [addressrangehigh]) and   ([streetname] = '32nd') and   (getdate() between [beginningeffectivedate] and [endingeffectivedate]) 	0.0233705040116577
18446545	39942	mysql join statement - referenced field in same table	select *  from   yourtable a         inner join yourtable b                 on a.reference_id = b.order_id  where  b.reference_type > 0; 	0.0106401440820906
18446721	7292	oracle 10g pl/sql connect by prior returning child and parent on same row	select last_name "employee", connect_by_root last_name "manager",    level-1 "pathlen", sys_connect_by_path(last_name, '/') "path"    from employees    where level > 1 and department_id = 110    connect by prior employee_id = manager_id; employee        manager         pathlen path    higgins         kochhar               1 /kochhar/higgins    gietz           kochhar               2 /kochhar/higgins/gietz    gietz           higgins               1 /higgins/gietz    higgins         king                  2 /king/kochhar/higgins    gietz           king                  3 /king/kochhar/higgins/gietz 	0.000427163951451781
18446950	29655	mysql 2 columns data in a group	select * from   tablename where  (least(a, b), greatest(a, b), id) in  (     select  least(a, b) as x,              greatest(a, b) as y,              max(id) as id     from    tablename      group   by x, y ) 	0.00329242786423551
18447586	7704	select column by different column function in access query	select a.* from table as a inner join (     select breaker, min(rating) as min_rating     from table     group by breaker ) as b on a.breaker = b.breaker and    a.rating = b.min_rating; 	0.0690231591450947
18448929	38267	how to count duplicate values in one table?	select parentid,        chilid,        count(*) countchildid from yourtable group by parentid,          chilid having count(*) > 1 	9.12772377654548e-05
18449472	6026	mysql count results without duplicating	select   users_profiles.account_num, count(cases_visits.patient_visit_type), max(cases_visits.created_dt) from `users_profiles` join cases on cases.doctor_id = users_profiles.user_id join cases_visits on cases_visits.case_id = cases.id where cases_visits.patient_visit_type = 'np' group by users_profiles.account_num 	0.161705299387547
18449677	33698	limiting sql results	select t.*  from (select distinct userid from t limit 2) as u  inner join t using (userid); 	0.445995825357952
18449842	36775	how to add foreign key data to the primary key data and display it	select * from employee left join department on employee.department_id = department.department_id where emp_id =$id 	0
18450192	38530	postgresql query returning multiple rows based on id	select * from table where id in (1, 2, 3) 	0.000237973498300877
18450581	40141	schedule compliance query	select agentid, dayid, t2.starttime,    case when t1.statestart > t2.starttime then t1.statestart else t2.starttime end as statestart,    case when t1.stateend < t2.endtime then t1.stateend else t2.endtime end as stateend from tab as t1 cross join times as t2 where t1.statestart < t2.endtime and t1.stateend > t2.starttime 	0.796225948809863
18451375	18975	sql query to return all items who have a particular id	select itemid,         itemdesc,         isnull(groupdesc, '') groupdesc  from   itemtable t1         left join grouptable t2                on t1.groupid = t2.groupid  where  itemid = @chosen 	0
18451909	41109	show hourly clicks of a mysqli query for one day	select visitor_date, count(*) from visitors_table where visitor_date = curdate() group by visitor_hour 	0
18452569	12112	sql server: convert varchar to decimal (with considering exponential notation as well)	select cast(cast('1.61022e-016' as float) as decimal(28, 16)) 	0.574976858957456
18454739	4326	efficient sql to calculate # of shared affiliations	select pairs.from_person, pairs.to_person, count(*) from links pairs join      grp_affil fromga      on fromga.person_id = pairs.from_person join      grp_affil toga      on toga.person_id = pairs.to_person and         toga.grp_id = fromga.grp_id group by pairs.from_person, pairs.to_person; 	0.0355207516006406
18456026	4125	postgres pg_toast in autovacuum - which table?	select n.nspname, c.relname  from pg_class c  inner join pg_namespace n on c.relnamespace = n.oid where reltoastrelid = (     select oid     from pg_class      where relname = 'pg_toast_15404513'      and relnamespace = (select n2.oid from pg_namespace n2 where n2.nspname = 'pg_toast') ) 	0.0699943302329025
18456113	10178	how to get only incoming edges on mysql graph?	select uidfrom, uidto from graph g where not exists (     select * from graph rev where rev.uidfrom=g.uidto and rev.uidto=g.uidfrom ) 	0.00197496493653298
18457779	24123	display multiple data from multiple different table	select l.leave_type, e.emp_name, d.dept_name      from leave l          join employee e on l.emp_id = e.emp_id          join department d on e.dept_id = l.dept_id      where l.leave_id = '1'; 	0
18458012	7262	oracle jdbc: how to know which row throws unique key constraint?	select col from bd_vehicles_temp intersect select col from bd_vehicles_temp_1; 	0.00321275526346123
18458963	41110	oracle sql query for displaying values?	select amount,debit,credit,description  from tablename  where amount = 500 and amount = 600  group by amount,debit,credit,description; 	0.185091550662492
18459028	34869	reduce amount of case result per row	select coalesce(sum(bedrag), 0) from betalingenfactuur where factuurnummer=f.factuurnummer 	0.00115676376737583
18459331	23813	display result of mysql in braces	select place, group_concat(value) from  (select c.place, concat(a.type, '(', group_concat(b.name),')') as value from place c inner join menutype a on c.id=a.id inner join menuname b on a.menuid=b.menuid group by a.type) tmp group by place 	0.0054628960822438
18459818	37756	how to sum multiple columns with different grouping criteria	select currency, sum(total1) as total from ( select currency_a as currency, sum(a_amount)  as total1 from table1 group by currency_a union all select currency_b, sum(b_amount) as total2 from table1 group by currency_b union all select currency_c, sum(c_amount) as total2 from table1 group by currency_c ) t group by currency 	0.000335449820425403
18460917	19775	mysql select from multiple colums from tables	select s.personid, q.qualificationname, s.score   from score s   inner join qualifications q on q.personid = s.personid and q.qualificationname ='human resource management'   inner join address a on a.personid = s.personid and a.province ='western cape'   where s.jobid = 58   order by s.score desc   limit 0,20; 	0.000334178250794117
18460928	19931	order by two columns	select y.id      , y.name     from my_table x    join my_table y      on y.name = x.name   group      by name      , id   order      by max(x.id) desc      , id desc; 	0.00854150473908432
18461176	25306	sql select value by maximum time per day	select  currencyid, cast(exchangedate as date) as exchangedate , (           select   top 1 rate           from     table t2           where    cast(t2.exchangedate  as date) = cast(t1.exchangedate  as date)           and      t2.currencyid = t1.currencyid           order by exchangedate desc) as latestrate from    table t1 group by currencyid, cast(t1.exchangedate  as date) 	0
18461281	31116	how to join the tables	select student_f_name,        student_m_name,        student_l_name,        std_entry_master.id,        std_entry_master.student_id,        section_id,        contact_name from   std_entry_master        left join std_parent_info          on std_entry_master.student_id = std_parent_info.student_id where  std_entry_master.student_id = 'stu00000060'; 	0.0655986903517446
18461586	39061	join distinct id on non-distinct id (mysql)	select t.id, t.val_string, t.val_int, t.val_datetime from table1 as t     left join (subquery) as v_table         on t.id = v_table.id 	0.00150217501472198
18463785	2394	how to know the table name inside a fetch_array	select 'table1' as t, ... from table1 union select 'table2' as t, ... from table2 ... echo $row['t']; 	0.0345444419312153
18468131	38852	substring with delimiter in sql	select substring('abilene, tx',charindex(',','abilene, tx')+2,2) 	0.401087307697474
18470433	6895	query with 3 tables and a max	select a.id_user, r.username, b.pontuacao, b.nivel from resultados a inner join utilizador r on a.id_user=r.id_user  inner join (select u.nivel, max(u.pontuacao) pontuacao             from resultados u             group by u.nivel) b on a.nivel = b.nivel and a.pontuacao = b.pontuacao 	0.0625637183349002
18470470	7658	sql server insert/update trigger concatenate date string	select top 1 @date = datepart(d, datenextshipment) from inserted select top 1 @year= convert(varchar(4),datepart(yyyy, datenextshipment)) from inserted select top 1 @month = convert(varchar(2),datepart(mm, datenextshipment)) from inserted @newdate = convert(datetime,@year+'-'+@month+'-'+'25') 	0.0257654062740216
18470599	26999	php mysql undefined index: timestamp	select date_format(`timestamp`,'%d-%m-%y') as "timestamp" from statistics 	0.633277273193275
18470690	14747	find duplicate items in the specific column and update the item which has min row number with '-'	select cte.rn, (case   when c1.starttime = c1.stoptime     then '-'   else convert(varchar, c1.starttime, 120)   end) as starttime,    case when c1.stoptime = c2.starttime then '-' else convert(varchar, c1.stoptime, 120) end as stoptime from cte c1 left join cte c2       on c2.rn = c1.rn + 1 order by c1.stoptime 	0
18471474	18406	curtime returns 2 hours ahead no matter what	select convert_tz(now(), @@global.time_zone, '-5:00');  select date(convert_tz(now(), @@global.time_zone, '-5:00'));  select time(convert_tz(now(), @@global.time_zone, '-5:00')); # the second value gets the time of the server so it knows what to convert from. # the third value is your timezone you want to display # it can either be an offset, or name (if table is installed):  # 'utc', 'pst', 'met', and so on 	0.0183680866508701
18473467	31069	how to update top n rows in ms access from c# using parameters for n?	select top 	0.000255995784828975
18473719	8637	oracle sql -- remove partial duplicate from string	select regexp_replace    (input,     '(.{10,})(.*?)\1+',     '\1') "less one repetition"     from tablename tn where ...; 	0.00161813637988186
18473985	10049	mysql multiple query setup	select      (select count(pin.app_uid) from pmt_insp_normal pin where pin.app_status = "to_do" and pin.date_completed is null) as `type a outstanding`, (select count(psn.app_uid) from pmt_sign_normal psn where psn.app_status = "to_do" and psn.date_completed is null) as `type b outstanding` 	0.686834499793995
18474254	10361	counting and joining serialized data with mysql	select   table1.carid,   table1.car,   count(*) from   table1 inner join table2   on table2.value like concat('%"', table1.carid, '"%') group by   table1.carid,   table1.car 	0.105033062071487
18474301	28180	select rows that have a value matching any one of multiple rows from a second table	select *  from follows f join events e on e.user = f.user where f.user = $userid 	0
18476704	11938	combining records in counts	select max(fld1),         count(*) from tbl1  group by replace(replace(fld1, ' ', '' ), '.', '') 	0.00767649818504441
18478026	37970	how can i get the value of non-aggregated column with an aggregated column?	select caseno,date,remarks, (select max(cast(date as datetime)) from tblcasedev subc where subc.caseno=c.caseno group by c.caseno) as maxentrydate from tblcasedev c  order by caseno 	0
18481416	37456	group by column and display count from all tables in mysql	select type, max(count_table1) as count_table1, max(count_table2) as count_table2 from ( (     select type, count(*) as count_table1, 0 as count_table2     from table1     group by type ) union (     select type, 0 as count_table1, count(*) as count_table2     from table2     group by type) ) as tmp group by type 	0
18481425	34577	how to select rows from one table and order it by the sum of a column from another table?	select   members.member_id,   total_xp.sum_xp from   members    left join      (select         member_id,         sum(value) as sum_xp       from         member_experience       group by         member_id) as total_xp      on members.member_id = total_xp.member_id order by   total_xp.sum_xp 	0
18483656	19221	grouping an outcome in mysql	select      (case         when u.postcode_area in ('bt') then 'northern ireland'         when u.postcode_area in ('cf','ch','gl') then 'wales'         when u.postcode_area in ('ab','dd','dg','eh','fk') then 'scotland'         else 'other') as country,     count(*)  from     users as u group by country 	0.204512868964807
18483717	4170	get sum of row whose datatype is varchar & first character is £	select sum(cast(substring(total, 2, ( len(total) ))as decimal(10, 2))) as total from   tbl_preorder 	5.83820011776073e-05
18483755	30203	mysql select in different table with condition	select t2.*, t1.color from t2 inner join t1 on t1.color = t2.data and t1.id = '$id' 	0.0187314733391954
18483825	3570	mysql paste a long list of values	select name from users where id in (1,2,3,4 .....) ; 	0.0294900547415829
18483847	39647	how to search for an id from a group of id using mysql?	select * from friendslist where find_in_set( $id, users_id ) <> 0 	0.000180523893503808
18483936	37628	sql query to produce email list based on specific requirements	select       pf.email     ,pf.postid from       postfollowers pf inner join       postcomments pc on       pf.postid = pc.postid where           pc.notification_sent = 0       and pf.userid != pc.userid 	0.00119886540250101
18484476	36482	index on foreign keys	select  docmvenum1.sid, docenum1.value   from  docmvenum1     join  docenum1      on  docenum1.valueid = docmvenum1.valueid 	0.0132482675461596
18485502	27873	sql looping temp table and reading data	select @name = name, @marks = marks from @mytable 	0.0184034178971251
18485577	15484	mysql select record that should have today and tomorrow date	select property_id from yourtable where date in (curdate(), curdate() + interval 1 day) group by property_id having count(distinct date)=2 	0.00102727155161796
18486409	26386	t-sql - query filtering	select * from table1 where id in (     select  id       from table1     group by id     having count(distinct [customer no_]) > 1 ) 	0.612698503342023
18486554	31866	how to find value which includes semicolon(;) sign in sqlite?	select * from list where value like '%; banana%' 	0.00388377515049123
18488786	28258	xml to sql - need a few more data from the xml	select x.variable.query('name').value('.', 'varchar(25)'),    x.variable.query('value').value('.', 'varchar(30)'),    x2.variable.query('machine').value('.','varchar(30)'),    x2.variable.query('date').value('.','datetime') from (  select cast(x as xml) from openrowset(  bulk 'c:\20130828_1237_zsk40-2.xml',  single_blob) as t(x)  ) as t(x) cross apply x.nodes('collecteddata/variable') as x(variable) cross apply x.nodes('/') as x2(variable); 	0.0112162926010561
18489761	10029	get reference to master select row in nested select	select c.name, c.type, c.value from test as c inner join (select name, type             from test             where type = "type1"             and value = 3) as d on c.name = d.name and c.type = d.type; 	0.00167842217862417
18490679	20439	get total row count in entity framework	select count() 	0.00306705902310637
18492060	3959	group by in single row with different columns	select location_id ,max(case when coordinate_type = 'lng' then value else null end) as 'lng' , max(case when coordinate_type = 'lat' then value else null end) as 'lat' from table1 group by location_id 	0.000209301411597138
18492084	4918	count of dates that are 5 days from the previous	select tbl1.users_id, count(tbl2.date) from (select users_id, date, @counter:=if(users_id = @previd, @counter + 1, 1) as sequencectr, @previd:=users_id from atable cross join (select @counter:=0, @previd:=0) sub1 order by users_id, date) as tbl1 left outer join (select users_id, date, @counter:=if(users_id = @previd, @counter + 1, 1) as sequencectr, @previd:=users_id from atable cross join (select @counter:=0, @previd:=0) sub1 order by users_id, date) as tbl2 on tbl1.users_id = tbl2.users_id and tbl1.sequencectr + 1 = tbl2.sequencectr and tbl2.date > date_add(tbl1.date, interval 5 day) group by tbl1.users_id; 	0
18492544	36293	mysql - get daily counts for unique keys	select `key`,        sum(day(timestamp = 9)) as `09`,        sum(day(timestamp = 10)) as `10`,        sum(day(timestamp = 11)) as `11`,        sum(day(timestamp = 12)) as `12`,        sum(day(timestamp = 13)) as `13`,        sum(day(timestamp = 14)) as `14`,        sum(day(timestamp = 15)) as `15`,        count(distinct date(timestamp)) as accessdays from t group by `key`; 	8.56676058477088e-05
18492655	36178	select from named query	select stop.tageoid as tageoid,               trip.tripno as tripno        from ((((trip                 inner join btstoptimes on trip.tripno = btstoptimes.tripnumber)                inner join tripstxt on (trip.tripno = tripstxt.trip_id                                        and left(tripstxt.shape_id, 3) <> 'eld'))               inner join patterndetail on trip.patternid = patterndetail.patternid               and btstoptimes.sequence = patterndetail.stopsortorder)              inner join stop on stop.geoid = patterndetail.geoid) 	0.043237373207319
18493961	34950	merging two schedule rows into one in sql	select academicperiod , buildingnumber , roomnumber , dayofweek        max(930a) as 930a,        max(945a) as 945a,        max(1230p) as 1230p,        max(1245p) as 1245p   from {yourresultset}   group by academicperiod,            buildingnumber,            roomnumber,            dayofweek 	4.92533187151657e-05
18494346	151	php mysql search start & end dates fields for todays date if it falls inside range	select * from iwia_events where event_start< now() and event_stop > now() 	0
18494619	6413	selecting for the absence of value in a one-to-many table design	select  a.id,          a.`name`,         group_concat(`tags`.`tag`) as tags  from   articles a        left join tags                 on tags.id = a.id  where   not exists( select 1 from tags                      where id = a.id                     and tag = 'search term') group  by articles.id, articles.`name`; 	0.000303922321471191
18494836	35373	sql - order by ascending date difference from now()	select advertise_id,         qr_startdate,        qr_enddate,         datediff(now(), t1.qr_enddate) as d  from `adv_qr` t1  inner join advertise_table t2      on t1.advertise_id = t2.lid  order by d asc 	0.000421519118484353
18495134	40395	find the time difference between two datetime columns stored as varchar	select str_to_date('06-08-2013 22:30:18', '%d-%m-%y %h:%i:%s'); # 2013-08-06 22:30:18 	0
18495219	15630	finding a list of un-compilable packages	select 'alter '||decode(object_type,'package body','package',object_type)||        ' '||object_name||' compile '||decode(object_type,'package body','body;',';')   from user_objects where status = 'invalid' 	0.00358174303133897
18496115	7127	select records with a column with specific value on specific date sql server 2000	select cola, colb, colc from yourtable where cola not in (select cola                    from yourtable                    where colb = 'a'                      and colc < '2013-08-28'); 	0
18496924	9898	sql query to list all the items in a group in one record	select group_concat(name) from table 	0
18497359	25816	oracle sql trying to get percentage of columns	select t1.lifename, t1.monthstatus, (t1.monthstatus / t2.total * 100) as prcent from  (  select     decode(grouping(life), 1, 'total', life) as "lifename",   sum(case      when task is not null and to_char(datee, 'mm') = '08'        and to_char(datee, 'yyyy') = '2013'      then 1      else 0    end) as "monthstatus" from life_lk, task_c where life_lk.life_id = task_c.life_id group by rollup(life) ) t1  , (select sum(monthstatus) as total from life_lk) t2 ; 	0.000985285900451884
18498894	35020	how to reference an aliased column in where clause that contains a grouping function	select count(distinct idomainid) as totinfile, ifilegroup from domains.`apachevirtualhosts` group by ifilegroup having count(distinct idomainid) < 10; 	0.52105133616902
18501518	11377	sql join two record into one row with multiple column	select ca1.staffid,        ca1.projectdepartment as prev_deptid, ca1.startdate, ca1.enddate,         ca2.projectdepartment as new_deptid, ca2.startdate, ca2.enddate from emp_hist as ca1 join      emp_hist as ca2      on ca1.staffid = ca2.staffid and and         cast(ca1.startdate as date) <> cast(ca2.startdate as date) and         cast(ca1.enddate as date) <> cast(ca2.enddate as date) and         cast(ca2.startdate as date) = dateadd(day, 1, cast(ca1.enddate as date)); 	0
18502967	24526	mysql group_concat returning all values instead of values per column	select countrycode, group_concat(language separator "|") as "official languages" from countrylanguage where isofficial = 't' group by countrycode 	0
18504200	18150	sql select statement - multiple tables allow null values	select     s.id, s.name, st.name, p.firstname || ' ' || p.lastname, f.name,     f.store_date, bdt.name, bd.comment from system as s     left outer join systemstatus as st on st.id= s.status_id     left outer join role as w on w.system_id = s.id     left outer join person as p on p.id = w.person_id     left outer join document as bd on bd.system_id = s.id and bd.role_id = w.id     left outer join documenttype as bdt on bdt.id = bd.type_id     left outer join file as f on f.id = bd.file_id 	0.155303107239092
18504292	17632	how to merge rows of two tables when there is no relation between the tables in sql	select col from (   select cola as col         ,row_number() over (order by cola) as order1         ,1 as order2   from tablea   union all   select colb         ,row_number() over (order by colb)         ,2   from tableb ) order by order1, order2 	0
18505251	11344	mysql count respondent and total participant	select event_id,         count(participant_id)  as total_resondents,         (select count(*)          from   participants) as participants from   respondents  group  by event_id 	0.0146360148788482
18505268	16244	join three tables with sum of column in access query	select ml.monthlist, sum(a.amount_received), mt.monthf_l from tbl_monthlist ml left join tbl_month_target mt on mt.monthid = ml.monthid left join tbl_amount a on ml.month_id = ml.monthid  group by ml.monthlist, mt.monthf_l 	0.0732610046479725
18505753	17343	sql: all records from one table, and all records from another, including null	select      #crosstable.languageid,      #crosstable.moduleid,     count(#userspassed.userid) as users  from      #crosstable left join     #userspassed on        #crosstable.languageid = #userspassed.languageid       and #crosstable.moduleeid = #userspassed.moduleid group by #crosstable.languageid, #crosstable.moduleid 	0
18506403	23108	multiply numbers using sql and if else statement	select ds.perstel , dw.ad , dw.soyad ,         ds.refphoner   , ds.product , ds.tree_level , case       when ds.tree_level in (-1) and ds.product like '%face%' then count(ds.tree_level) * 2     when ds.tree_level in (-1) and ds.product like '%fast%' then count(ds.tree_level) * 2     when ds.tree_level in (0,1,2,3,4,5) and ds.product like '%face%' then count(ds.tree_level) * 3      when ds.tree_level in (0,1,2,3,4,5) and ds.product like '%mobil%' then count(ds.tree_level) * 3      when ds.tree_level in (0,1,2,3,4,5) and ds.product like '%fast%' then count(ds.tree_level) * 2      else ds.tree_level  end as answer1  from dw_prod.frtn.dig_sefer  as ds  inner join dw_prod.dbo.dw_must as dw  on dw.cep_tel = ds.perstel     group by ds.perstel , dw.ad , dw.soyad , ds.refphoner   , ds.product , ds.tree_level 	0.362813670506675
18506923	11358	how to create a list about my tables from sql server?	select name  from   databasename.sys.tables  order  by name 	0.128136481944341
18507443	9726	how to reset a custom id to 1 at the beginning of each month	select id, recorddate  from table where id = (select max(id) from table)  where datename(yyyy ,getdate()) = datename(yyyy ,recorddate())  and datename(mm ,getdate()) = datename(mm ,recorddate()) 	0
18507622	28408	search across multiple columns	select fieldname,  match (fieldname) against (+"bill new york" in boolean mode) as relevance from mytable where match (fieldname) against (+"bill new york" in boolean mode)  having relevance > 0 order by relevance desc 	0.015666831767408
18509575	3525	how to capture the parameters being sent to a particular stored procedure?	select parameter_name,data_type from information_schema.parameters where specific_name = 'storedprocname' 	0.0361968780762142
18512656	22612	mysql sum of disctinct rows	select fruit, count(fruit) from fruits_table group by fruit 	0.00453531471716781
18512742	34309	sql select - some rows won't display	select files.id, count(payments.fileid) as numpays from files left outer join payments on files.id=payments.fileid group by files.id order by numpays desc 	0.00599756858443715
18514819	13497	page number index	select t1.vendor,t1.category,        csvpages = replace( (select convert(varchar(12),page) as [data()]                             from mytable t2                             where t2.vendor = t1.vendor and                                    t2.category = t1.category                             order by t2.vendor                             for xml path('')                            ), ' ', ',') from mytable t1 group by t1.vendor,t1.category ; 	0.0458829693805275
18516047	724	mysql order all rows with null x column alphabetically by y column, then all rows without null x column alphabetically by y column	select *   from table1  order by (x is null) desc, y 	0
18517220	27727	execute query that normally runs on a single id for every id	select abs(timestampdiff(minute, now(), (select max( ` time ` )                                           from   ddhistorical                                           where  id = a.id                                           group  by id)))  from   ddhistorical as a  group  by id 	0.000282045514133623
18518529	14207	select latest 10 rows except the first	select * from `table` order by `id`  desc limit 1,10 	0
18519147	33828	group by in sql combining values	select    case when col1 in ('a','b') then col1 else 'other' end,    count(*) from tab group by case when col1 in ('a','b') then col1 else 'other' end 	0.0579126459674451
18519537	6236	count something from database	select count(user_id) from stiri where user_id = '.$_session["user"]["nume"] 	0.0367032038772448
18519675	16204	join query results	select   coalesce(i.partno,o.partno) as partno,   isnull(i.qty,0) as [in],   isnull(o.qty,0) as [out],   isnull(i.qty,0) - isnull(o.qty,0) as [total] from   (select partno, sum(qty) as qty from intable where date = '1/1/2013' group by partno) i   full join   (select partno, sum(qty) as qty from outtable where date = '1/1/2013' group by partno) o on i.partno = o.partno; 	0.640602084419362
18520222	21006	how to use count() to parse individual words in a nvarchar field?	select top 50 tags.s tag, count(tags.s) as listings from job cross apply [dbo].[splitstring](tags,' ') tags where not job.tags is null and datepart(year,job.datecreated) = 2013 group by tags.s order by listings desc 	0.0148360704680219
18520531	19480	retrieving newest item when using group by and where	select * from messages  where to_id='9876'   and date = (select max(date) from messages where to_id='9876') 	0.00180981274776211
18521049	35244	mysql select where values are repeated	select a.*   from bigcities a inner join bigcities b     on a.city = b.city    and a.town = b.town    and a.id != b.id    and   (a.code1 = b.code1        or a.code2 = b.code2        or a.code3 = b.code3        or a.code4 = b.code4         or a.area1 = b.area1         or a.area2 = b.area2         or a.area3 = b.area3         or a.area4 = b.area4          ); 	0.0168913781449689
18521962	39741	sql select query, multiple tables	select * from posts where id not in ( select post_assoc from images ) 	0.149008117405861
18524280	31635	sql query help finding missing pair	select min(user_id) user_id,        min(friend_id) friend_id   from table1  group by least(user_id, friend_id),           greatest(user_id, friend_id) having count(*) = 1 	0.668743237946027
18525303	10762	selecting a distinct primary key and getting a count of values for them	select menu_id,count(*) as count from table group by menu_id 	0
18530442	6521	how to query a second table for each result from a first table?	select     img.image_id,     img.name,     img.square_id,     count(vot.vote_id) as numbervotes,     vot.vote_type from     images img         join votes vot             on img.image_id=vot.image_id group by     img.image_id,     img.name,     img.square_id,     vot.vote_type 	0
18531467	28721	two sk's in one table	select currency_sk_from,        (select currency_name             from currency             where currency_sk = currency_sk_from) as currency_name,        currency_sk_to,        (select currency_name             from currency             where currency_sk = currency_sk_to) as currency_name_to,        conversion_rate     from conversion_rate_table; 	0.00352139259669318
18533818	24922	mysql sum + inner query in same table	select *, purchase - sale as balance from (   select     assetid,     sum(if(fromtype='bank', amount, 0)) as purchase,     sum(if(fromtype='asset', amount, 0)) as sale   from foo f1   group by assetid ) f2 	0.0636907785785766
18533906	21999	multiple join on @onetomany with condition on each	select product from product product     join product.servingtimeavailablities as servingtimeavailablities     join product.styles as styles     join product.locationavailabilites as locationavailabilites     where servingtimeavailablities.someproperty = :somepropertyvalue1     and styles.someproperty = :somepropertyvalue2     and locationavailabilites.someproperty = :somepropertyvalue3 	0.00537030160876848
18534712	9879	select multiple values and order by relevance	select user_id      , sum(case when subject_id in(1,2) then 1 else 0 end)ttl    from user_subjects   group      by user_id; 	0.0560447325478425
18535181	36948	limiting number of results received based on a column value group without group by	select vans,icollaborate_id from table_name where icollaborate_id in( select * from (select distinct icollaborate_id from table_name limit 3) as t); 	0
18535726	23579	sql - concatenate results from 2 tables	select * from movies where title like '%string&' order by case when title='string' then 1 else 2 end limit 10 	0.000444839880744339
18536438	26998	in sql, how can one change a value using a case statement?	select  users.username, users.phone, users.email, users.status, case when users.group_id=3 then 5 else users.group_id end as roleid ... 	0.10629816986983
18539395	1452	mysql selecting average rating per date between two dates	select date, avg(rating) avg_rating from table where date between :start and :end group by date 	0
18542722	39172	how do i recursively nest two queries from the same table in sqlite?	select a.name from data a where a.id in (select b.id from data b where b.name = 'bob'); 	0.000613800688420612
18542973	31072	query using email address to get user id as key to query a second table	select * from user, purchases  where user.userid = purchases.userid  and user.useremail = 'user@email.com' 	0
18543614	35107	mysql how to combine two select statement	select count(*),         date(date_time),         sum(case when rssi_val<100 then 1 else 0 end),         sum(case when rssi_val<100 then 1 else 0 end)/count(*) as percentage from tablea  where hostname='hosta'  and date(date_time) between '2013-07-01' and '2013-07-31'  and time(date_time) between '06:00:00' and '18:00:00'  and dayofweek(date_time) not in (1,7)  group by date(date_time); 	0.0242112380289314
18544406	21410	sql server over query	select userid, taskname, first, last, email, valuedate, analysis from (select userid, taskname, first, last,  email, valuedate, analysis, row_number() over(partition by userid, taskname order by valuedate desc) as rk from mytable) as l where rk = 1 	0.748527747816639
18545347	17706	mysql join two tables in resultset and add new coloum acording to first table	select e.serial_no, d.designation, e.name, e.epf_no, e.appointment_date, e.nic, e.dob  from employee e, designation d  where e.designation = d.number and e.nic = 'the_number_you_want' 	5.28918647574074e-05
18551372	3572	calculate avrage of mysql result php	select avg(stars) as avg_stars from feedback 	0.0177950091198752
18553751	10157	multiple query with sqlite 2nd query gives only first result	select tm.quantity, tm.materialtypeid , t.typename       from invtypematerials tm inner join invtypes t on t.typeid = tm.materialtypeid      where tm.typeid=12743 	0.00740067630083255
18553759	20897	return multiple rows from plpgsql function	select * from function1(); 	0.00758737901177673
18554059	14828	mysql selecting data from 2 tables	select * from members a where not exists (   select 1   from team_members b   where b.member_id = a.member_id   ) 	0.000268889594246968
18554793	20905	mysql subquery sum of votes	select  id, name, title,  sum(case when value > 0 then value end) up, sum(case when value < 0 then value end) down  from ideas left join votes on ideas.id = votes.idea_id group by id; 	0.135976687724337
18555286	40945	query sql combine multiple tables	select a.name_applicant,        s.plan as siteplan,        b.date,        concat(d.name,' : ',d.value) as detail from applicant a inner join book b on b.idapplicant = a.idapplicant inner join siteplan s on s.idsiteplan = b.idsiteplan inner join detail d on b.idbook = d.idbook 	0.0743487551803043
18555603	35563	joining different tables based on column value	select distinct n.id  from notifications n  join (      (select b.id, 'book' as type from books b where b.is_visible = 1)   union      (select i.id, 'interview' as type from interviews i where i.is_visible = 1) ) ids on n.parent_id = ids.id and n.parent_type = ids.type where n.user_id = 1 	0
18556497	8188	retrieve two highest values in a table	select value   from records  order by value desc  limit 2 	0
18557539	24189	get years from articles	select group_concat(distinct year(ins_dt)) as `year`  from articles  order by ins_dt desc; 	6.43214548050719e-05
18559174	26633	cassandra cql3 select row keys from table with compound primary key	select distinct row from foo 	0.000238002277269512
18559418	3052	joining four tables with mysql and get values from two of them	select    q.quote_eng,   a.author from quotesbytopic  as qt  inner join topicmap as t on qt.topicmap_id = t.topicmap_id inner join quotes   as q on qt.quotes_id   = q.quotes_id inner join authors  as a on a.author_id    = q.author_id where t.topics_eng = 'age' 	0
18561153	33750	how to get last item for specific category in mysql	select t.* from t where category = 320 order by id desc limit 1 	0
18561319	7872	month vs month query (data in the same table)	select   t1.source,   t1.version,   t1.[sales model],   t1.destination,   t1.period,   t1.volume - t2.volume as volume from   table t1     inner join   table t2     on       t1.source = iif(t2.source mod 100 = 12, t2.source + 89, t2.source + 1) and       t1.version = t2.version and       t1.[sales model] = t2.[sales model] and       t1.destination = t2.destination and       t1.period = t2.period 	0
18561674	8755	in a product database, how to calculate pricechange from two periods, and group by category	select p.*,        (p.price -          (select p2.price          from product p2          where p2.id = p.id and p2.period < p.period          order by period desc          limit 1         ) - 1        ) * 100 as percentagechange from product p order by category; 	0
18563744	4269	select certain columns from multiple rows	select products_model, products_name, products_price, products_quantity      from orders_products as products     join orders as orders on products.order_id = order.order_id     where products.order_id = {whatever order id you are trying to find} 	0
18564195	12683	why should operand contain only one column?	select t1.f1, t2.f2, t2.f3 from (select 1 as f1) as t1, (select 2 as f2, 3 as f3) as t2 	0.74614355223576
18564485	7907	select/sum of a column with different conditions in 1 query	select  count(*) total, sum(val = 1) pos, sum(val = -1) neg from    score_history  where   content_id = '46083'; 	0.00608647661447219
18564680	15218	left join. column 'product_id' in field list is ambiguous	select a.product_id,time_id,customer_id,promotion_id,store_id,store_sales,store_cost,sum(unit_sales) total_unit_sales from sales_fact_1997 a left join product p on (a.product_id = p.product_id) group by a.product_id order by total_unit_sales; 	0.480508548338486
18566365	36749	mysql generate this type of query for get result	select price   from code  where '11220' like replace(code, '*', '_')  order by char_length(replace(code, '*', '')) desc  limit 1 	0.0585319705936815
18566454	3105	getting data from multiple tables in mysql	select g.id group_id, g.name group_name,        a.last_written, a.total_articles, a.total_done,        c.last_comment   from groups g left join  (     select `group`,              max(case when done = 1 then written end) last_written,             count(*) total_articles,             sum(done) total_done       from articles      where active = 1        and user_id = 1      group by `group` ) a      on g.id = a.`group` left join  (     select a.`group`,            max(date_added) last_comment       from commants c join articles a         on c.article_id = a.id      where a.active = 1        and a.user_id = 1      group by a.`group` ) c     on g.id = c.`group`  where  user_id =  1 	0.00266178774218238
18566856	15939	how to get top 10 results and order by the most common one	select top 10 column1, column2 from (     select column1, column2, cnt = count(*)      from [table]     where column2 = 2     group by column1, column2  ) t order by t.cnt desc 	0
18567662	21433	display column name and number of null values present in that particular column in oracle	select      sum(case when cust_id is null then 1 else 0 end) cust_id,     sum(case when cust_name is null then 1 else 0 end) cust_name,      sum(case when cust_add is null then 1 else 0 end) cust_add,     .....  from     customer 	0
18568410	2526	how to convert date to a format `mm/dd/yyyy`	select convert(varchar(10), cast(ts as date), 111) from <your table> 	0.00478026235532648
18568512	319	why postgresql is not accepting while group by on one table and selecting towards another tables	select non-aggregating-attr-1, non-aggregating-attr2, non-aggregating-attr3, sum(attr4) from table group by non-aggregating-attr-1, non-aggregating-attr2, non-aggregating-attr3 	0.00583984504608337
18568642	37878	concatinate all rows of a column into single value	select @allnames = stuff((select distinct ',' + name                       from table1                       for xml path(''), type                      ).value('.', 'nvarchar(max)')                          , 1, 1, ''); 	0
18568744	24339	improve query that count and join many tables	select o.id,   count(distinct a.organization_id) organization_count,   count(distinct a.domain_id) domain_count,   count(ho.hostname_id) hostname_count,   count(ho.error_id) errors_count from operation o    left outer join hostname_operation ho on o.id=ho.operation_id   left join hostname h on h.id=ho.hostname_id   left join accepted a on a.id=h.accepted_id group by o.id order by o.id 	0.65941214222907
18569571	36465	select some but count all mysql	select   artist,   title,   count(*) how_many_tot,   sum(easytosing='yes') how_many_easy from   tracks group by   artist, title having   sum(easytosing='yes')>0 	0.00814041003937774
18571682	35357	select a row with least value of a column using where and group by	select grade_id, count(grade_id) from sample_table st where time_stamp = (select min(time_stamp) from sample_table stt where stt.grade_id = st.grade_id) and user_id = 100 group by grade_id; 	0.000160659798319966
18572002	38332	hsqldb : get table indices	select * from information_schema.system_indexinfo 	0.0563733658438121
18572269	12324	sum and group by and difference of colums	select ag_name, sum(ag_end - ag_start) from the_unknown_table group by ag_name 	0.00255251686138312
18572942	33429	select x last rows before like in mysql	select     sq.title,     shows.name,     shows.id,     sq.news_id,     sq.created_on from (     select         news_feed.title,         news_feed.news_id,         news_feed.created_on     from        news_feed     order by  news_id desc limit 50 ) as sq join shows on sq.title      rlike concat('(^|[[:blank:][:punct:]])', shows.name, '($|[[:blank:][:punct:]])') 	0.000151636252060397
18573717	9793	sql : check if primary key is foreign key	select tab.table_name, 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 ' intersect select tab.table_name, 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 = 'foreign key ' 	0.000607093880616216
18574757	30391	grabbing mysql data from one table and showing it for a specific user with a specific id	select users.*, vehicles.*  from users inner join vehicles on users.user_id=vehicles.user_id 	0
18578216	8971	finding products that customers bought together	select c.original_sku, c.bought_with, count(*) as times_bought_together from (   select a.sku as original_sku, b.sku as bought_with   from items a   inner join items b   on a.order_id = b.order_id and a.sku != b.sku) c group by c.original_sku, c.bought_with 	0.000209260211486533
18579145	24215	how to generate a specific query in sql server 2012	select model,         gender,         color,         sum(case               when month(order_date) = 1 then 1               else 0             end) jan,         sum(case               when month(order_date) = 2 then 1               else 0             end) feb,         sum(case               when month(order_date) = 3 then 1               else 0             end) mar,         sum(case               when month(order_date) = 4 then 1               else 0             end) apr  from   product_models t1         inner join product_types t2                 on t1.product_model_id = t2.product_model_id         inner join product_orders t3                 on t2.product_type_id = t3.product_type_id         inner join orders t4                 on t3.order_id = t4.order_id  group  by model,            gender,            color 	0.199770339712001
18579445	40799	sql - select sum() by distinct intervals (date)	select name,         sum(case               when cast(date as date) = '2013-01-01' then value               else 0             end) [2013-01-01],         sum(case               when cast(date as date) = '2013-01-02' then value               else 0             end) [2013-01-02],         sum(case               when cast(date as date) = '2013-01-03' then value               else 0             end) [2013-01-03]  from   table1  group  by name 	0.00289828090512757
18581360	41021	join where one row should be duplicated	select color, avg(price)   from a, b  where a.value between b.min_value and b.max_value  group by color 	0.160154430057708
18582789	33248	table with columns table_name and number_columns in oracle	select table_name, owner, count(*) as number_columns from all_tab_cols group by table_name, owner; 	0.0307259014757804
18584093	22227	join two table show all record on left table if right table exists, use right table	select       a.cola,     isnull(b.colb, 0) as b_colb from    dbo.tablea a left join dbo.tableb b on a.cola = b.cola 	0.000565961458619385
18584960	19764	select haschildren in a table that has parentid	select *,  case when exists (select * from [dbo].[catalogs] c where c.parentid = p.id)        then 1 else 0 end as haschildren from [dbo].[catalogs] p 	0.00578138478415435
18584988	12099	one view using two tables with data that might not be in both tables, oracle sql	select a.form_journal_id,         a.company_id,         a.retail_price as retail,         a.whole_sale_price as wholesale,         nvl(b.individuals,0) as individuals,         nvl(b.entities,0) as entities,         nvl(b.complex,0) as complex   from tablea a, tableb b  where a.form_journal_id = b.form_journal_id (+)    and a.company_id = b.company_id (+) union select b.form_journal_id,         b.company_id,         nvl(a.retail_price,0) as retail,         nvl(a.whole_sale_price,0) as wholesale,         b.individuals,         b.entities,         b.complex   from tablea a, tableb b  where b.form_journal_id = a.form_journal_id (+)    and b.company_id = a.company_id (+); 	0.0155147563405578
18586860	29482	re-order before group by mysql	select * from (select  * from  table1   order by   field(bvox,'yes') desc, track_id desc) abc group by artist, title 	0.304011789753083
18586873	11023	giving default values for columns in join condition in oracle sql query	select    u.userid, u.username, isnull(r.rolename, 'none')  from    users u   left join user_role_map ur on     ur.userid = u.userid   left join roles r on     r.roleid=ur.roleid 	0.335707927301464
18587626	29704	how would i modify this mysql query to find a rank?	select                 s.squad_id as squad_id, s.ladder_id, s.team_id as team_id,                 x.experience_id, x.squad_id, sum(x.value) as total_exp,                 @i:=@i+1 as rank             from league_squads as s             left join league_experience as x on (s.squad_id = x.squad_id),             (select @i:=0) as foo             where s.ladder_id = 1             group by s.squad_id, s.ladder_id, s.team_id, x.experience_id, x.squad_id             order by total_exp desc 	0.732308776179087
18588875	30760	searching for a record in mysql using query browser	select * from yourtable where user_name ='user name here' and password = 'password here'; 	0.152590678440576
18589451	34900	how to turn these n queries to one	select ltr.*, group_concat(lt.wordform separator ' ') from midia_lemmatized_text ltr join      midia_lemmatized_text lt      on ltr.`wordform` = 'rivolgimento' and         lt.position between ltr.position - 10 and ltr.position + 10 and         lt.idfile = ltr.idfile group by ltr.idfile, ltr.position; 	0.00122069518621154
18590028	12911	mysql/php sort with natural sort	select * from fltable   order by case when downloads = 'n/a' then 1               when downloads is null then 2               when downloads = 'unlimited' then 4               else 3          end desc,           downloads * 1 desc 	0.473680268365427
18592005	14182	need help on calculate percentage of failure of all columns in very large mysql table	select id, count(*),  sum(case when col1 between 0 and 10 then 1 else 0 end) col1_yes, sum(case when (col1 not between 0 and 10) and (col2 between 0 and 10) then 1  else 0 end) col1no_col2yes  from table  group by id; 	0.00286151960472083
18592447	3172	search matching prefix of every word in field in sqlite	select * from table where field match 'phrase*'; 	0.00107430502586834
18593107	35588	accessing a server from sp_addlinkedserver	select top 5 * from servera.<your database>.<schema name>.<table name> 	0.0381224311731895
18593539	3883	mysql group by date and convert from unix timestamp	select from_unixtime(`date`, '%d.%m.%y') as ndate,        count(id) as post_count from your_table group by ndate 	0.000297162909915043
18593895	15535	how to query a c# data table in a odbccommand	select columns from   tablename tb1        inner join [otherserver].[databasename].[dbo].[tabelename] tb                                          on tb.column=tb1.column 	0.0415954968295396
18595157	20347	sql : which dates contain time between 12:00 and 22:00	select rectime,         case when cast(rectime as time)                   between '12:00:00' and '22:00:00'              then 1 else 0 end foo   from table1 	0.00231038656864106
18596777	28555	mysql: possible to apply the or operator across multiple selected rows?	select u.name, sum(r.basement_access) as basement_access, sum(r.user_directory_access) as user_directory_access from users  u   left join positions p on u.userid=p.userid   left join roles r on r.roleid=p.roleid  where u.userid=123 group by u.userid; 	0.0926435708341708
18597226	39711	find relationships within three products	select i1.sku as sku1, i2.sku as sku2, i3.sku as sku3, count(*) as bought_together from items i1 join      items i2      on i1.order_id = i2.order_id and i1.sku <> i2.sku join      items i3      on i1.order_id = i3.order_id and i3.sku not in (i1.sku, i2.sku) group by i1.sku, i2.sku, i3.sku; 	0.00317559747623936
18597599	39895	don't return the lowest value if	select min(case when product.promotionalprice = 0         then product.originalprice else         least(product.promotionalprice, product.originalprice)         end) as minproductprice,    max(case when product.promotionalprice = 0         then product.originalprice else         least(product.promotionalprice, product.originalprice)         end) as maxproductprice from products as product inner join markets on product.market = markets.id and markets.situationid <> 3 where product.name = 'playstation 3'; 	0.000209985588783897
18600916	12656	how to do a custom sort of sql data using cursor & loader?	select distinct t.name from (select *, 1 as sec from items where name like 'd%' union select *, 2 as sec from items where name like '%d%') as t  order by t.sec asc 	0.22046773423463
18602455	23586	short-circuit union? (only execute 2nd clause if 1st clause has no results)	select * from a    where conditions   union   select * from b    where not exists (     select * from a        where conditions) and conditions 	0.0804531407236212
18603138	1977	how to get data from date 15th to 15th	select userid, month, sum(...) as totaltime, sum(...) as totalnormaltime.... from ( select t.*,  case when day(starttime) > 15 then datename(month, starttime) + '-' + datename(month, dateadd(month, 1, starttime)) else datename(month, dateadd(month, -1, starttime)) + '-' +  datename(month, starttime) end as month from timebilling t ) tx group by userid, month 	0.000163481263000528
18605347	9396	need to join double precision foreign key with integer primary key	select ... from table_with_integers n inner join table_with_doubles d    on cast(d.double_column as unsigned integer) = n.integer_column ... 	0.00542046195806846
18605591	2407	sql command to calculate from amount and id, total weight	select orderid,        sum(weight*quantity) as totalweight from orderproducts as a join othertable as b on (b.orderid=b=id) where b.status = "finish" group by orderid 	0
18606449	19796	mysql select records from one table if their id and username do not appear in a second table	select *  from   logbook  where  logbook.username not in      (select read_logbook.username       from   read_logbook       where  read_logbook.username='jmd9qs') and logbook.id not in     (select read_logbook.logbook_id      from   read_logbook); 	0
18607110	5224	get last 12 months data from db with year in postgres	select to_char(revision_timestamp, 'yyyy-mm'),        count(b.id) from package a join package_revision b on a.revision_id = b.revision_id where revision_timestamp >       date_trunc('month', current_date) - interval '1 year' group by 1 	0
18607179	9669	group by while getting the ids of the columns that meet the condition	select t1.id  from test t1 inner join (    select site_id, min(date) as mdate    from test    group by site_id ) t2 on t1.site_id = t2.site_id and t1.date = t2.mdate 	0
18608505	27344	mysql - calculate soundex difference between two strings	select *  from   song  order  by substr(pre_calculated_soundex, 1, 1) =                      substr(soundex("aaaa"), 1, 1)                                                   + substr(pre_calculated_soundex                      , 2, 1) =                      substr                      (soundex("aaaa"), 2, 1)                      + substr(pre_calculated_soundex, 3, 1)                      = substr(soundex("aaaa"), 3, 1)                        + substr(pre_calculated_soundex, 4, 1                        )                        = substr(soundex("aaaa"), 4, 1) 	0.000611773018032189
18609549	5789	how to create a view which has consolidated information from multiple tables?	select  *  , case when exists      (select * from dbo.member m where m.teamid = t.teamid and m.age > 35)     then 1 else 0 end as isabove35  , case when (select sum(earned) from job j where j.teamid = t.teamid) > 0    then 1 else 0 end as hasearnings , case when exists     (select * from job j where j.teamid = t.teamid and status = 'complete')     and not exists      (select * from job j where j.teamid = t.teamid and status <> 'complete')    then 1 else 0 end as alljobscomplete from dbo.team t 	0.000130742738107861
18610047	13281	sql select distinct entity - union all - order by another entity's column	select *    from (     select ff.*, b.dato as dato     from forslag ff        inner join forlag f on ff.forlag_id = f.forlag_id       inner join loggbehandling b on ff.forlag_id = b.forlag_id       inner join kontrollpanel p on f.uhrpumote_id = p.saksbehandleruhrpumote_id     where b.status_id = 7     union all     select distinct ft.*, b.dato     from forslag ft       inner join tidsskrift t on ft.tidsskrift_id = t.tidsskrift_id       inner join loggbehandling b on ft.tidsskrift_id = b.tidsskrift_id       inner join kontrollpanel p on t.uhrpumote_id = p.saksbehandleruhrpumote_id     where  b.status_id = 7   ) as resulttable   order by resulttable.dato desc 	0.00334403878433882
18612808	10152	mysql php order by	select * from fractions; + | fractions | + | 100/40    | | 12/1      | | 25/5      | | 50/20     | + select fractions      , substring_index(fractions,'/',1)/substring_index(fractions,'/',-1)x    from fractions   order      by x desc; + | fractions | x    | + | 12/1      |   12 | | 25/5      |    5 | | 100/40    |  2.5 | | 50/20     |  2.5 | + 	0.366943011337942
18612892	10976	i need to group years and select last five years with the averages of each year so that i have average and year output	select sub.yr, sub.ap from (     select year as yr, avg(askingprice) as ap     from tbltest     group by yr     order by yr desc     limit 0,5 ) sub order by sub.yr asc 	0
18614771	24631	read xml root values into table	select     t.c.value('local-name(.)', 'nvarchar(max)') as category,     a.c.value('local-name(.)', 'nvarchar(max)') as property,     a.c.value('.', 'nvarchar(max)') as value from @xml.nodes('     outer apply t.c.nodes('./@*') as a(c) 	0.0081505637412893
18616931	1213	mysql not exists returns empty set	select unit_id from today_unit_names where name_type_id <> 4 and unit_name = '' 	0.546051162321453
18617625	34480	mysql column can't be found	select       distinct (`m`.`match_id`),        `m`.`competition_id`,        `m`.`date`,        `h`.`team_name` as "hometeam",       `h`.`team_id` as "hometeamid",        `a`.`team_name` as "awayteam",       `a`.`team_id` as "awayteamid",        `o`.`for`,        `o`.`against`  from `single` bs       join `matches` m on bs.match_id = m.match_id       join `outcomes` o m.score_id = o.outcome_id        join `teams` t          join `teams` `h` on `m`.`home_team_id`=`h`.`team_id`        join `teams` `a` on `m`.`away_team_id`=`a`.`team_id`  where  `actual_return` is not null 	0.705912953463606
18619471	11623	join two tables and compare two columns to see if they are equal	select e.claim_name, e.grant_number, y.stakingdate \ from everything2013 e inner join yukon_claims_govt  y on e.[grant_number]=y.[grant_number] where e.expiry_date=y.claimexpirydate; 	0
18620236	15104	how to get the max result even if the max is different	select a.employee_id, a.accept_international_assignment, a.plan_year from  dbo.v_sc08_cd_employee_availabilities a inner join (select employee_id, max(plan_year) maxplanyear             from dbo.v_sc08_cd_employee_availabilities             group by employee_id) m    on a.plan_year = m.maxplanyear and a.employee_id = m.employee_id 	6.49357820630142e-05
18621802	25994	sorting mysql results by several columns	select name, wins, losses, points, (wins - losses) as "diff" from teams order by points desc, diff desc 	0.0190455287087548
18622051	14862	restrict joined and grouped sql results	select saledetail.article, sum(saledetail.quantity) as pieces from saledetail join sales on sales.id = saledetail.id where sales.date between '10-01-2013' and '20-01-2013' group by saledetail.article 	0.0254766010034197
18622384	25321	combining (concatenating) date and time into a datetime	select convert(datetime, convert(char(8), collectiondate, 112)    + ' ' + convert(char(8), collectiontime, 108))   from dbo.whatever; 	0.000476296670486339
18622420	36518	sql: using case and returning only max value	select     t1.[closing date], t2.[price date],     case         when t1.[closing date] = t2.[price date] then 'match'         else 'nonmatch'     end as [match] from table1 as t1     outer apply (         select top 1 t2.[price date]         from table2 as t2         where             t2.[price date] <= t1.[closing date] and             t2.[price date] >= dateadd(day, -5, t1.[closing date])         order by t2.[price date] desc     ) as t2 	0.0834230021357774
18623052	15570	sql: filtering a query with multiple conditions	select x.p1.user.office,  x.p1.user.loc_no,  x.p1.user.name,  x.p1.user.code,  x.default_freq,  x.last_paycheck from (select  p1.user.office,  p1.user.loc_no,  p1.user.name,  p1.user.code,  p1.user.default_freq as default_freq,  (select distinct max(p2.pay.paycheck_paydate)  from p2.pay where p1.user.client_tas_cl_unique = p2.pay.cl_uniqueid) as last_paycheck from pr.client  where  p1.user.client_end_date is null and p1.user.client_region = 'z' and p1.user.client_office <> 'zf' and substring(p1.user. code,2,1) <> '0') x where (       (x.default_freq = 'w' and (datediff ( d , x.last_paycheck , @currentdate) >= 7))       or (x.default_freq = 'b' and (datediff ( d , x.last_paycheck , @currentdate) >= 14))     ) 	0.488442272006639
18623867	4430	dateadd with abbrevation from column	select (case when periodtime = 'day'              then dateadd(day, row_number() over (order by mt.id), mt.starttime)              when periodtime = 'month'              then dateadd(month, row_number() over (order by mt.id), mt.starttime)              when periodtime = 'year'              then dateadd(year, row_number() over (order by mt.id), mt.starttime)         end) as increment from mocktable mt 	0.0781229057992578
18625827	23530	sql: joining 3 tables	select      database_courses.user_id  from      database_all  join     database_users  on database_all.userid=database_users.userid2 join     database_courses  on database_users.userid2=database_courses.userid where     database_all.date='2013-09-03' and database_all.college='harvard' and database_courses.num_courses < 3 	0.0585221606264898
18626035	26510	a record self referencing in mysql	select * from employee where employee_id=1 union select * from employee where manager_id=1 	0.337670545345707
18626070	14625	how to find logical reads per second in oracle database	select * from v$sysmetric where metric_name = 'logical reads per sec'; select * from v$sysmetric_summary where metric_name = 'logical reads per sec'; select * from v$sysmetric_history where metric_name = 'logical reads per sec'; select * from dba_hist_sysmetric_summary where metric_name = 'logical reads per sec'; 	0.00205975342869643
18626530	39053	get all the friends of friends list	select f2.friend_id   from friendship f1 join friendship f2     on f1.friend_id = f2.user_id   where f1.user_id = 1 	0
18627592	41213	select id from group by group if the group satisfied criteria	select lot_id   from table1  group by lot_id having sum(iif(shipping_date is null, 1, 0)) = 0 	0.000647548629266519
18628236	13402	get all columns exposed by views in a database	select      [schema] = s.name,      [view]   = v.name,     [column] = c.name   from sys.views as v   inner join sys.schemas as s     on v.[schema_id] = s.[schema_id]   inner join sys.columns as c     on v.[object_id] = c.[object_id]   order by [schema],[view],c.column_id; 	0.000131965225990659
18628979	20926	join two tables with max aggregation on one table	select c.id, d.bookprice, d.pricedate  from material as c inner join     (select materialid, bookprice, pricedate       from price as a      where pricedate =            (select max(pricedate)             from price as b             where a.materialid = b.materialid           )     ) as d  on c.id = d.materialid 	0.00188727677832179
18629300	38946	pass value from query 1 to query 2	select a.accno, b.name, b.id, c.maximum  from transaction as a  inner join account as b  on a.accno = b.accno left join (select staffid, max(amount) as maximum from sales group by staffid) as c  on c.staffid = b.id where b.status = 'active' 	0.00663674612208395
18630397	2399	insert data in datatable with sql query	select t.id, l.reffid, coalesce(t.somedata, '-') somedata   from (   select reffid, rnum     from   (     select distinct reffid       from table1   ) q cross join    (     select 1 rnum union all     select 2 union all     select 3 union all     select 4   ) n ) l left join  (   select id, reffid, somedata,           row_number() over (partition by reffid order by id) rnum     from table1 ) t    on l.reffid = t.reffid   and l.rnum   = t.rnum 	0.410001549439258
18630480	22787	how to display records from table based on single word from multiple words in mysql	select `did`, `brand_name`, 'paracetamol' as `generic`, `tradename`,  `manfactured`, `unit`, `type`,  `quantity`, `price` from table1 where  find_in_set ('paracetamol',generic)  or find_in_set (' paracetamol',generic) 	0
18631238	15549	postgresql inherits from 9 tables to one table to read in geoserver	select * from data."wc" union all select * from data."nw" .... 	0.00645934987575434
18632845	16950	how to get minimum value from a set of values returned by select query?	select min(data)  from tab1 where id<5; 	0
18635692	15044	getting events from database that spans multiple days	select t0_.name as name0, t0_.start as start3, t0_.end as end4  from events t0_  where      not(         t0_.end < '2013-09-05 00:00:00'         or t0_.start > '2013-09-06 23:59:59'     ) 	0
18635702	6378	mysql query for conditions on related tables	select house_id    from house_rooms   where (room_id=2 and size>=450 and size<=550)      or (room_id=1 and size>=350 and size<=450)   group by house_id  having count(distinct room_id)>1 	0.0369031701964233
18636647	10263	mysql date subtraction	select * from user where timestampdiff(minute,now(),user_last_login)<=10 	0.121990399572919
18637266	5125	need a solution for mysql select data where until	select * from table_conversation c where user_id = 222 and       message_id > (select max(message_id) from table_conversation c2 where user_d = 555); 	0.481424891771993
18637595	35808	sort sql based on two fields and extra constraint	select  name         , status_id  from    mytable  order by          case when status_id = 2 then 1 else 0 end desc         ,status_id         ,name 	8.51473300823468e-05
18638159	635	how to list data with mysql query for ci and list only posted employer and job which is not expire	select * from users u            inner join employer-profile e on u.id = e.u_id           inner join employer-post-job epj on e.u_id =epj.e_id           where epj.expire date > '".date('y-m-d')."' 	0.00881796969558164
18638522	8620	ssrs matrix show hierarchy	select hs1.modellname as modell,      hs1.attributename as [level 1],     hs2.attributename as [level 2],     hs3.attributename as [level 3],     hs4.attributename as [level 4],     hs5.attributename as [level 5],     hs6.attributename as [level 6] from hierarchy_ssrs hs1     left join hierarchy_ssrs hs2 on hs2.parentattributeid = hs1.attributeid     left join hierarchy_ssrs hs3 on hs3.parentattributeid = hs2.attributeid     left join hierarchy_ssrs hs4 on hs4.parentattributeid = hs3.attributeid     left join hierarchy_ssrs hs5 on hs5.parentattributeid = hs4.attributeid     left join hierarchy_ssrs hs6 on hs6.parentattributeid = hs5.attributeid where hs.parentattributeid is null order by modell,     levelname,     [level 1],     [level 2],     [level 3],     [level 4],     [level 5],     [level 6] 	0.0950021429208298
18638687	2150	mysql, select top 5 results then group the rest to "other"?	select case when v2.page is not null                then v1.page                else 'other'         end,         count(*) from visits v1 left join  (   select page, count(*) as pcount   from visits   group by page   order by pcount desc   limit 5 ) v2 on v1.page = v2.page group by case when v2.page is not null                then v1.page                else 'other'           end 	0
18640841	39675	mysql join two tables with dynamic variables	select *     from (select *, match(name) against('*mcdonalds*' in boolean mode) as `score_name_0`,              match(`city`) against('mcdonalds*' in boolean mode) as `score_city_0`,         (3959 * acos(cos( radians(".$lat.")) * cos(radians(pinpoints.lat)) * cos(radians(pinpoints.lng) - radians(".$long.")) + sin( radians(".$lat.")) * sin(radians(pinpoints.lat)))) as distance         from `stores`              join pinpoints on stores.id=pinpoints.id         where stores.id=pinpoints.id              and (match(name) against('*mcdonalds*' in boolean mode) or              match (`city`) against('mcdonalds*' in boolean mode)) ) as tmp_tbl where distance < 25  order by distance asc, (`score_namn_0` + `score_stad_0`) desc 	0.35527964525543
18640981	8118	add leading zero and convert as varchar to a float	select '0' + ltrim(rtrim(str(wallet_sys))) as wallet_sys from newsysdata1; 	0.0132983028690335
18641648	38098	trying to select row from mysql then in same select see if value exists	select p.*, (select count(id) from page_names where parentid=p.id and ispublished =1) haschild from page_names p where p.ispublished =1 order by p.orderout 	0
18642150	36439	using 'group by' while preferring rows associated in another table	select   tbl_entries.id,   col1,   col2,   col3,   cola,  from ( select coalesce(min(entid), min(tbl_entries.id)) as favid from tbl_entries left join tbl_reviewlist on entid = tbl_entries.id group by col1, col2, col3 ) as a join tbl_entries on tbl_entries.id = favid left join tbl_reviewlist on entid = tbl_entries.id 	0.000284560733100706
18642307	9170	sql scanning previous records in database	select * from mytable as t1 where (select col_1        from mytable as t2        where t2.index = t1.index + 1       ) in (select col_2             from mytable as t3             where t3.index < t1.index) 	0.00455255358530328
18642616	6892	sql query (or join) for 3 tables	select distinct m.name from students s inner join mentor_ralationships mr on mr.student_id=s.student_id inner join mentors m on m.mentoir_id=mr.mentor_id where s.teacher_id=1; 	0.592246201509537
18643631	4727	db2 sql - how to check if an employee reached age 70 years and 6 months in current year?	select * from empleyees where birstday >= '1942-07-01' and birstday  <= '1943-06-30'; 	0
18643840	2870	sql server: select only one row of rows that has the same id on some coulmn	select distinct m.from,m.to from mytable as m; 	0
18647114	5697	tracking row numbers in oracle	select table_name, num_rows from user_tables 	0.0356906027732129
18649013	2497	union on 2 tables returns one almost empty result every time	select * from (     select g.id as gallery_id,  'photo' as type, p.id as id, p.filename, p.caption, null as title, null as service, null as embed, null as width, null as height, p.display_order from galleries g          join photos as p on p.gallery_id = g.id         where g.id = {$this->id}     union     select g.id as gallery_id, 'video' as type, v.id as id, null as filename, null as caption, v.title, v.service, v.embed, v.width, v.height, v.display_order from galleries g          join videos as v on v.gallery_id = g.id          where g.id = {$this->id} ) as u order by display_order; 	9.27533897192358e-05
18649500	24879	compare two tables and give the output record which does not exist in 1st table	select t2.name from table2 as t2 where not exists (select * from table1 as t1 where t1.name = t2.name) 	0.000119439424489904
18650065	12174	postgresql - strategy on grouping a query	select   u.creationtime::date as date,  d.driver_statuses_city_id as id,  count(u.usersid) as applied from  users u  join  driver_status d  on  u.usersid = d.driver_id where  (u.role = 'partner' or u.role = 'driver') and d.driver_statuses_city_id in  (select id from driver_statuses_city where city_id in ({{city_ids}})) and u.creationtime::date > '2013-09-01' group by date, id 	0.39158877575608
18652865	25208	fetch the colum and row which has the max value for the row	select column_name country,        case column_name        when 'us'  then us        when 'in'  then `in`        when 'sa'  then sa        when 'chn' then chn        when 'au'  then au        when 'eu'  then eu        end clicks   from table1 t cross join (   select column_name     from information_schema.columns    where table_name = 'table1'      and table_schema = schema()      and column_name <> 'name' ) c    where name = 'john' having clicks > 0  order by clicks desc 	0
18653543	29993	see all tables referencing a primary key	select table_name   from all_constraints  where r_owner = 'owner'    and r_constraint_name = 'your_primary_key' 	0.00153040784807365
18653762	8511	how to see when view was modified in oracle db	select object_name, object_type, created, last_ddl_time  from user_objects where object_name = '<my_view_name>'; 	0.154741167846544
18655531	4766	mysql - convert result to string	select id, name, if(state = 1, 'no', 'yes') 	0.0897661207252365
18656933	18491	sql query to find the depending index of a column	select  indexname = i.name from    [sys].[index_columns] ic         inner join [sys].[columns] c             on ic.[object_id] = c.[object_id]             and ic.[column_id] = c.[column_id]                   inner join [sys].[indexes] i             on i.[object_id] = ic.[object_id]             and i.[index_id] = ic.[index_id] where   ic.[object_id] = object_id('dbo.tablename') and     c.name = 'columnname'; 	0.000369584683429515
18657321	17528	mysql db query for comma separate values	select * from t where skillsid regexp '(^|,)5($|,)' 	0.00554846249390727
18659024	17978	nested sql queries: how to get mutiple counts on same elements based on different criterias	select   'servercount' conformity,   count(case when compliancepercentage >= 0 and compliancepercentage <20 then 1 end) per00_19,   count(case when compliancepercentage >= 20 and compliancepercentage <40 then 1 end) per20_39,   count(case when compliancepercentage >= 40 and compliancepercentage <60 then 1 end) per40_59,   count(case when compliancepercentage >= 60 and compliancepercentage <80 then 1 end) per60_79,   count(case when compliancepercentage >= 80 and compliancepercentage <100 then 1 end) per80_100 from yourtable; 	0
18659506	30171	calculate mean number of rows per item per month in mysql	select    count(*) / count(distinct item_id) as tag_average,   year(tag_month),   month(tag_month) from   t group by   year(tag_month),   month(tag_month) 	0
18662316	11449	returning unique valued entities with their count?	select tag, count(*) `count`   from table1  group by tag  order by `count` desc 	0.0966605585670024
18662853	9532	how to link the column name of foreign key's table on searching in sql query?	select  from  member_booking mb inner join event e on mb.e_id = e.e_id  inner join member m on mb.mem_id = m.mem_id where  mb.ref_codes like '%$keyword%'  or e.e_title like '%$keyword%'  or m.mem_username like '%$keyword%'  or m.mem_email like '%$keyword%' ** 	0
18663029	41080	order in union all don't works	select id, nombre from listaambos  union all select id, nombre from listax86 order by nombre collate nocase asc; 	0.269354542897628
18663492	14575	mysql condense group by two columns into group by one column with breakdown	select type, sum(color_count),    group_concat(concat(color_count, ' ', colour) separator ', ') as colour_breakdown from (     select type, colour, count(colour) as colour_count     from ocean     group by type, colour ) as subt group by type 	9.74598905400011e-05
18663905	37587	find column values that are a start string of given string.	select * from urls where "www.example.com/foo/bar/baz/here.html" like concat(url, "%"); 	0
18664822	23126	efficient tsql query	select div as division       ,room as roomlocation       ,form as forms       ,nums as totalnumberlocations from aview  where id = '1' and div in ('a','g','r') group by div, nums, room, form order by forms asc, totalnumberlocations asc 	0.79231759853294
18667657	37098	join in multiple mysql tables in php	select u.id, u.fname, u.lname, u.email from users u inner join users_to_team ut on u.id = ut.users_id 	0.216519226112168
18667776	22939	mysql - double join (one from same table, one from different table)	select m.member_name as memb, c.member_name as corp,   (select max(b.billing_expiration) from billing b   where b.member_id = c.member_id   or b.member_id = m.member_id) as expiration from member m left outer join member c on c.voter_id = m.member_id 	0
18668179	6737	joining versus union on two mysql tables with group by and order by conditions	select m.threadid, m.uidto, m.uidfrom, m.last_activity, m.last_message, c.threadid, c.uidto, c.uidfrom, c.last_activity, c.last_message from messages m join chat c on m.threadid=c.threadid  group by threadid order by last_message (select m.threadid, m.uidto, m.uidfrom, m.last_activity, m.last_message from messages m union all select c.threadid, c.uidto, c.uidfrom, c.last_activity, c.last_message from chat c) group by threadid order by last_message 	0.152934366772084
18668656	39408	mysql return field names from multiple foreign keys	select t.task_id,        tt.name,        p.name,        e.name,        ts.name,        t.hrs,        t.note from task t inner join tasktype tt on tt.tasktype_id = t.tasktype_id inner join project p on p.proj_id = t.proj_id inner join employee e on e.empl_id = t.empl_id inner join taskstatus ts on ts.taskstat_id = t.taskstat_id where t.taskstat_id = 1 	0
18671761	7048	divide result of one query on result of another query	select name, avg(grade) from `table` group by name 	0.000184036405419561
18671837	15013	replace values in the result set using a select query	select  name ,       case gender         when 1 then 'male'         when 2 then 'female'         end as gender from    yourtable 	0.0262094289110178
18672886	18333	how to count many-to-many relations in postgresql	select ab1.a as a1, ab2.a as a2, count(*) from a_b ab1 join      a_b ab2      on ab1.b = ab2.b and ab1.a <> ab2.a      where ab1.a < ab2.a group by ab1.a, ab2.a 	0.221651446062065
18675928	15335	two simple count columns without subqueries	select d2f.id,        sum(case when ft.name = 'pdf' then 1 else 0 end) as pdf_count,        sum(case when ft.name = 'xml' then 1 else 0 end) as xml_count from document2file d2f join      file f      on d2f.file_id = f.id join      filetype ft      on f.filetype_id = ft.id group by d2f.id; 	0.200382479953849
18677361	2977	row-number in between sub query	select * from( select     row,    booktitleid,     booktitle,    callnumber,    fullname,    copiesonshelves from (   select         book.booktitleid,        booktitles.booktitle,        booktitles.callnumber,        fullname = lastname + ', ' + firstname + ' ' + middlename,        copiesonshelves = count(case status when 'onshelf' then 1 else null end),          row = row_number() over (order by booktitle)   from     book         left outer join      booktitles         on booktitles.booktitleid = book.booktitleid          left outer join     authors         on authors.authorid = booktitles.authorid     group by book.booktitleid, booktitles.booktitle, booktitles.callnumber,      lastname, firstname, middlename ) sub ) sub2 where row between @start and @end 	0.789072097057802
18678333	23606	counting rows in select clause with db2	select t.*, g.tally   from mytable t,        (select count(*) as tally           from mytable        ) as g; 	0.0806196206975597
18678620	12290	sqllite order by date	select jobno, ondate from reports order by substr(ondate,7)||substr(ondate,1,2)||substr(ondate,4,2) 	0.12506690650115
18679872	2488	how to make order by a_datetime more important that datetime?	select *    from forum_question left join forum_answer      on forum_question.id = forum_answer.question_id  where category =  '7'    and  `sticky` =0  group by forum_question.id  order by (reply = 0),        case when reply > 0 then a_datetime             else datetime        end desc 	0.157313344852775
18680030	16211	mysql query to treat a column as positive or negative depending on another value	select sum(           case type           when 'deposit' then amount           when 'withdrawal' then -amount           end            ) as balance from $table where userid = $id 	0
18680094	29056	randomised rows & specific row	select id, if(id = 2, -1, rand()) as sort from my_table order by sort limit 20 	0.00103589748374402
18681784	8493	mysql: joining different tables based on an if/case statement	select coalesce(t2.id, t3.id) id,        (t2.id is not null) flag,        coalesce(t2.name, t3.name) name,        coalesce(t2.data1, t3.data1) data1   from table1 t1 left join table2 t2     on t1.dec_id = t2.id left join table3 t3     on t1.rec_id = t3.id 	0.00230720398579144
18682791	32584	join on a lookup table, to display the whole of one table where id's match?	select   planner.cell_id , planner.recipe_name , planner.day , ingredients.quantity , ingredients.measurement , ingredients.description from    planner inner join lookup     on planner.recipe_id = lookup.recipe_serial   inner join ingredients      on lookup.ingredient_serial = ingredients.serial where planner.is_populated = 1 order by   planner.cell_id , ingredients.serial 	0
18683321	7817	check if two date intervals intersect	select * from `events` as e  where '2013-09-09 08:00:00' between e.ev_date_start and e.ev_date_end or e.ev_date_start between '2013-09-09 08:00:00'and '2013-09-09 11:00:00' 	0.00226387683307637
18683525	24417	how to retreive grouped messages ordered by date sql	select (case when receiver = 'dave' then sender else receiver end) from messages m where 'dave' in (receiver, sender) group by (case when receiver = 'dave' then sender else receiver end) order max(date) desc; 	0.00029767527139548
18683698	26279	find all nodes within a subtree that has 0 or 1 children	select t1.*, t2.numchildren from user_tree t1 left join ( select parent_id, count(*) as numchildren             from user_tree             group by parent_id ) t2 on t1.id = t2.parent_id where t2.numchildren is null or t2.numchildren = 1; 	0
18685858	24808	join two tables without subquery	select a.idcontactowner, b.whateverfields, count(a.idcontactowner) as counter from contacts a, customers b where a.idcontactowner=b.id  group by a.idcontactowner  having counter>5; 	0.194947241230725
18687858	10218	join two queries into one	select * from post p join post_category pc on p.fk_post_category = pc.id join post_category pc2 on pc.postid = pc2.postid left join post_plus pp           on ( p.id = pp.news_id )  where approve = 1  and pc.categoryid in ( 130, 3, 4, 5 )    and pc2.categoryid = 73   order  by fixed desc,        date desc  limit  0, 7; 	0.00673473635893357
18688916	21453	ending a user's turn after completing a quiz	select   totalpoints from   tblquestionsanswered where   userid = $userid and   questionid = $thisquestionid 	0.0303276789757321
18692793	8733	how to optimize mysql queries that has calculations	select      round(            (             sum(`i_talk_time_sec`) +              sum(`hold_time_sec`) +              sum(`i_work_time_sec`) +              sum(i_aux_out_time_sec)            ) / sum(`calls_handled_ct`)          ) as time_spent,       year(month_date) stats_year,       month(month_date) as stats_month  from `enterprise_rep_agent_stats` where `employee_id` = '$id' group by stats_year, stats_month; 	0.368731493393142
18694094	38622	select only rows by join tables max value	select u.classno, u.userno, max(b.enddate) from libuser u join book b on b.id = u.bookid group by u.classno, u.userno 	0.000172607241956095
18694717	40555	sql query to get max id	select `id`,`test_no` from `tab` where `test_no` = (                   select max( `test_no` )                   from `test`                 ) 	0.00426082820319412
18694721	3430	mysql getting tables info where	select u.uid, f.url, f.title, f.favicon from u_feed u inner join feed f on f.id = u.fid where u.uid = '2' 	0.0208259699308614
18695322	39119	sql select .... not in query	select * from [194.0.252.151].onlinedb.dbo.customers  where customerid  not in  (select customerid from localdb.dbo.customers) 	0.700868471943958
18695330	13170	sqlite select from tablea if not match in tableb	select * from tablea left join tableb on tablea.someid = tableb.someid where upper(name) like @name limit 1 	0.200215232830683
18695517	25920	pl/sql - how to return variables as cursor?	select output1 as myoutput1, output2 as myoutput2, output3 as myoutput3, output4 as myoutput4 from dual 	0.370638060139892
18698457	21192	upcoming date of birth issue in query before 1970 with unix time stamp with mysql	select date_format(from_days(to_days(now())-to_days(date_add(from_unixtime(0), interval dob second))), '%y')+0 as age from hrs_employee_details 	0.00135104663747837
18699086	37206	sql server : select columns not by name	select column_name,ordinal_position   from information_schema.columns  where table_schema = ...    and table_name = ...    and ordinal_position <= 5 	0.0659382077188913
18699796	16979	sql only return value if condition is met with duplicate info	select distinct item  from data where item not in(select item                    from data                    where myvalue between 6 and 9); 	6.86135462856486e-05
18700703	34110	counting the number of rows which do not match	select count(*) from   ##table1 t1        join ##table2 t2          on t1.id = t2.id             and exists (select t1.*                         except                         select t2.*) 	0
18701864	37204	select first and last occurrence of repeated colums in sql server	select t1.name, min(t1.date) as mindate, max(t1.date) as maxdate from table t1 group by t1.name 	0
18702288	6865	how to format query result in oracle?	select case job when 'clerk' then 'new clerk' else job end as job from your_table 	0.261561073437541
18702615	10447	oracle sql select from a large number of tables	select *  from   (   select * from ps_jrnl_copy_req union all   select * from other_table_1    union all   select * from other_table_2    union all   ... and so on for 2,997 more) where oprid = 'jle0010' and run_cntl_id = 'copy_jrnl'; 	0.00100925848277819
18703702	35522	how to mark tables in select?	select id, alife, login, 'players' as `table`     from players     union all     select id, alife, (         select players.login         from players         where players.id = id         limit 0 , 1     ), 'attempts' as `table`     from attempts     order by `alife`     limit 0 , 30 	0.0152767256528715
18704039	37132	sql server group by order by where	select top 3 userid, documentid, max(createddate) from mytable where userid = 71 group by userid, documentid order by max(createddate) desc 	0.709612353262706
18704272	17185	return two identical rows in mysql	select o.info from orders o inner join links l on o.id = l.orderid 	0.000722876843354272
18704589	4375	joining select variable into different table columns | follow suggestion	select u.uid, u.username from users u where u.uid not in (select friend_two from user_friends where friend_one = :uid)  and u.uid not in (select friend_two from user_friends where friend_one = :uid) order by rand() 	0.00150949596754324
18705472	13619	mysql find duplicates + one other field	select s.username      , s.acctsessionid   from (          select r.username            from radacct r            where r.acctstoptime is null           group by r.username          having count(1) > 1        ) d   join radacct s     on s.username = d.username  where s.acctstoptime is null  order     by s.username      , s.acctsessionid 	0.000139681917858128
18707037	8413	how to find what foreign key references an index on table	select     f.name,     object_name(f.parent_object_id) from     sys.foreign_keys f         inner join     sys.indexes i         on f.referenced_object_id = i.object_id and            f.key_index_id = i.index_id where     i.name = 'idx_duplicate' and     i.object_id = object_id('[dbo].[mytable]') 	0.000542022618352478
18708180	14772	check if the id of one table is used as a foreign key in another	select * from game g where exists     (     select 1     from ticket t     where g.id = t.gameid     ) 	0
18708638	41328	list mysql data grouped together and show num_rows for each group	select *, count(category) as my_groupcount from tickets echo $result["category"].' ('.$result["my_groupcount"].')<br>'; 	0
18709126	40104	mysql select records where date is from last month or older	select * from payments where request_date < date_format(now(),'%y-%m-01 00:00:00') 	0
18711246	28765	how to get min date using oracle database date table	select e.event_name,     min(dt.start_date) as start_date,     min(dt.start_date)||'-'||max(dt.end_date) as fromto from event e join     date_table dt on e.e_id = dt.e_id where dt.start_date >=sysdate group by e.event_name; 	0.000396940418630011
18711616	27585	mysql join query result filtered by tags	select u.url_id, u.url, d.domain, u.hits, u.version, group_concat(distinct(t2.label)) as tags      from urls as u      inner join domains as d         on (u.parent_id = d.domain_id)      left join url_has_tag as ut on u.url_id = ut.url_id      left join url_has_tag as ut2 on u.url_id = ut2.url_id      left join tags as t on ut.tag_id = t.tag_id      left join tags as t2 on ut2.tag_id = t2.tag_id where t.tag_id in (7,8) group by u.url_id order by u.hits desc 	0.20774939027846
18712254	29774	how to build a query that returns exactly n number of rows	select level  from dual  connect by level <= 100 	6.28492407798681e-05
18713340	21220	retrieve data from sql table according to described scenario	select count(*) as cnt,        year(date) year_of_date from your_table group by year_of_date 	0.000392644599708502
18713499	3526	sql select statements - more than one output column	select sum(case when timestamp between '01.08.13 06:00:00'                                     and '01.08.13 10:00:00'                 then 1                  else 0             end) as morning,        sum(case when timestamp between '01.08.13 10:00:00'                                     and '01.08.13 14:00:00'                 then 1                  else 0             end) as noon,        sum(case when timestamp between '01.08.13 14:00:00'                                    and '01.08.13 18:00:00'                 then 1                  else 0            end) as evening from table 	0.0293515046428301
18714003	30973	get entries which are mostly available	select *   from t  inner join (select timestamp                 from t                group by timestamp             order by count(*) desc             limit 1) t2   on t.timestamp = t2.timestamp 	0
18714145	30288	count(*) returning false results when no applicable rows	select *, count(iup.user_id) as user_plans_count from #__iop_user_plans iup inner join #__iop_plan ip on iup.iop_id = ip.id where `iup`.`state` = 1 and `iup`.`user_id` is not null  and `iup`.`accepted` = 0  having user_plans_count>0 	0.0404574703016873
18714682	20983	add a timestamp to file name	select convert(varchar(30), getdate(),112) +         replace(convert(varchar(30), getdate(),108),':','') 	0.00311359286369113
18718326	36319	get the average from two distinct columns joining other tables in mysql	select avg( loc) as loc,avg(qty) as qty from tbl1  where month not in (concat(ucase(date_format(date_add(now(), interval -1 month),'%b')),',',          ucase(date_format(date_add(now(), interval -2 month),'%b')),',',          ucase(date_format(date_add(now(), interval -3 month),'%b')))) group by type 	0
18718581	37327	select query in which a column values come as column headers	select stdname,   max(case when subname = 'english' then subjectmark end) english,   max(case when subname = 'hindi' then subjectmark end) hindi,   max(case when subname = 'science' then subjectmark end) science,   max(case when subname = 'math' then subjectmark end) math from yourtable  group by stdname; 	0.000134460814923941
18718884	28509	when joining tables duplicate data is being returned from sql server	select  em.ename from    dbo.email_tbl e         join dbo.employeemaster_tbl em on em.ecode = e.ecode where e.plcid = 25 	0.00519650979307353
18718925	34181	calculation of late arrival / early arrival from in / out time	select timediff(addtime(in_date,shift_in), addtime(out_date,in_time)) as late_time 	0.0178500430751134
18720753	7348	how to select all the columns without the timestamp and date types?	select column_name from user_tab_columns where table_name = 'mytable1'        data_type not in ('date' . . .) 	0
18721607	13833	how can i select the rest of the row with distinct?	select * from (   select      users.*,     (select `message` from messages       where      (case when `user_to_id` = 1 then `user_from_id` else `user_to_id` end) = users.user_id      and (`user_to_id` = 1 or `user_from_id` = 1)      order by `time` desc limit 1      ) as message   from users ) a  where message is not null 	8.57036690137371e-05
18722099	17354	mysql grouping and getting newest rows	select      u.usernickname,     u.userfbid,     m.didread,     m.messageid,     m.messagecontent,     m.srcuserid,     m.destuserid,     m.messagesenddate  from      users u,      messages m  where      (u.userid = m.srcuserid or u.userid = m.destuserid)  and  case      when m.srcuserid='122' then u.userid= m.destuserid     when m.destuserid ='122' then u.userid= m.srcuserid     else -1 end  and  m.messageid in (select max(m.messageid) from users u, messages m where (u.userid = m.srcuserid or u.userid = m.destuserid) group by u.usernickname); 	0.00162276088712944
18722976	21259	how to sum rows after paging?	select calendar.datefield as date, sum(contract.time_slots) as slots_taken from contract right join calendar on calendar.datefield between contract.start_time and contract.end_time group by date limit 600 , 30 	0.0886506582241321
18724131	6405	how can i select every other row?	select * from table_name where mod(id,2) = 0 order by id desc 	0.000282885237573925
18724358	31660	select both ways from mysql	select     loans.*, ifnull(ul.name, ub.name), ifnull(ul.id, ub.id) as uid  from     loans     left join users ul on ul.id = loans.lender_id      left join users ub on ub.id = loans.borrower_id where     (loans.lender_id = 2 ) or (loans.borrower_id = 2 ); 	0.0256933521877853
18724867	33113	sql insert if missing value	select p.itemid ,c.colorid ,i.iteration ,0 as rating from (select distinct itemid from process) p cross join (select distinct colorid from color) c cross join (select distinct iteration from process) i left join process e on p.itemid = e.itemid and c.colorid = e.colorid and i.iteration = e.iteration where e.rating is null 	0.0552262749257593
18725109	19723	how do i find what ids are missing from a table when "those" ids are the result of a query?	select c.supplier1 from customer c left join supplier s on c.supplier1 = s.supplier_id where s.user_id is null 	0
18726334	25130	simple access union - comparing 2 queries	select manufacturingrequest.reqdate,          count( case when [mfgapproval] = true then manufacturingrequest.reqid else null end ) as resolved,         count( case when [mfgapproval] = false then manufacturingrequest.reqid else null end ) as unresolved from manufacturingrequest inner join qualityassuranceapproval on manufacturingrequest.reqid = qualityassuranceapproval.reqid where (qualityassuranceapproval.qualityapproval and) and manufacturingrequest.reqdate is not null group by manufacturingrequest.reqdate order by manufacturingrequest.reqdate 	0.760089088255795
18726462	27866	mysql select columns which has two matches in other table	select g1.id  from groups g1, memberships m1, groups g2, memberships m2 where m1.group_id = g1.id and m1.user_id = 1 and m2.group_id = g2.id and m2.user_id = 2 and g1.group_id = g2.group_id; 	0
18726492	17331	selecting data interval	select date,id from table1 group by week(`date`, 1) 	0.00902599226233123
18727583	11235	returning rows that have a one hour difference in date	select  paymentid       , invoiceid       , created from    payment p where   exists ( select invoiceid                  from   payment p2                  where  p.invoiceid = p2.invoiceid                  group by invoiceid                  having datediff(hour, min(created), max(created)) > 1 ) 	0
18730223	18165	multiple joins onto same table	select s.studentname as [student], t.teachername as [teacher], a.teachername as [advisor] from students s  left join teachers t on s.teacherid = t.teacherid left join teachers a on s.advisorid = a.teacherid order by 1, 2 	0.0494724001633667
18732738	39747	how to mysql_fetch_assoc for two select statement which is given in or operator to select form either tables	select name1 as name,email1 as email, mobile1 as mobile from table1 where id=1 union all  select name2 as name,email2 as email, '' as mobile from table2 where id=1 	0.0525167575114219
18733510	24574	mysql group by, but show all and order by date	select f.* from feeds f inner join (select parent_id, max(post_date) as ordered group by parent_id) o on f.parent_id = o.parent_id order by o.ordered 	0.00139321517686157
18733891	19810	sql query for two select statement	select m.*, f.name from membership_det m inner join faculty f on m.fid = f.fid where m.updatedate  between @start and @end and m.fid =@fid ; 	0.318346202305798
18734080	40024	get all second highest values from a mysql table	select    `name`,   `score` from    `score` where    `score`=(select distinct `score` from `score` order by `score` desc limit 1,1) 	0
18735015	29455	mysql : get unique substrings from string	select   group_concat(word order by min_n separator ' ') from (   select     id,     min(numbers.n) min_n,     substring_index(substring_index(tablename.st, ' ', numbers.n), ' ', -1) word   from     numbers inner join tablename     on length(st)>=length(replace(st, ' ', ''))+numbers.n-1   group by     id, word   ) s group by   id 	0.000213861991427215
18736673	3464	trying to merge a count query in to an existing select query	select contact.id_contact, contact.cname, contact.cemail,  contact.trading_id, trading_name.trading_name,customeralertcounttotal from contact inner join trading_name  on contact.trading_id = trading_name.id_trading_name left join (select count(alertid) as customeralertcounttotal,alerttradingid  from customer_support_dev.customer_alerts )as count on count.alerttradingid=contact.trading_id where (char_length(contact.cname) > 0) order by contact.cname 	0.0417098112458534
18736785	28086	how to export a mysql data table search query into csv using php?	select * from tablename into outfile '/tmp/filename.csv' fields terminated by ',' enclosed by '"' lines terminated by '\n' 	0.00402661255312162
18736837	11500	sql query from a single table	select  country,sex ,       sum(amountgold) as totalgold from yourtable group by          country,sex order by          country,sex 	0.00721051888043464
18737264	35120	convart varchar to date format with a twist	select convert(varchar(50),(convert(datetime,'2013-09-07 00:00:00.000')),106) 	0.0318913527617034
18738135	8268	sql selecting minimum value in a sub query when exact value is unknown	select distinct name from table1 natural join table2 where table2.code =  (select code from rate where rate=(select min(rate) from rate)) 	0.00660139251260795
18738852	38838	sql query - how to use exist and not exist conditions at the same time	select distinct a.* from tablea a      inner join tableb b on a.newvalue = b.value where a.oldvalue not in (select value from tableb) 	0.0132454936429792
18739763	24224	select matching rows where two columns reference each other	select * from   temp t1 join temp t2       where t1.follower=t2.followed       and t1.followed=t2.follower 	0
18740189	33501	migrating multiple linked server from one server to another on sql server 2008 r2	select     serv.name,     serv.product,     serv.provider,     serv.data_source,     serv.catalog,     prin.name,     ls_logins.uses_self_credential,     ls_logins.remote_name from     sys.servers as serv     left join sys.linked_logins as ls_logins     on serv.server_id = ls_logins.server_id     left join sys.server_principals as prin     on ls_logins.local_principal_id = prin.principal_id 	0.0425965006517415
18740914	15785	get the location which has max distance from another location	select loc1id, loc2id, distance from   (select loc1id, loc2id, distance,  rank() over(partition by loc1id order by distance desc) rn from distance) a where rn =1 	0
18741081	27379	check if row used by another table	select ea.*,efrom, eto, ifnull(efrom,0)+ifnull(eto,0) as count  from emails_accounts ea  left join  (select email_from,count(email_from) as efrom    from email_templates group by email_from) as e_from on ea.id=email_from left join  (select email_to, count(email_to) as eto    from email_templates group by email_to) as e_to on ea.id=email_to 	0.000678430836322065
18741592	32756	how to in mysql order rows by number of matches in associative table?	select r.id, count(i.id) as ing_cnt  from recipes r left join recipes_ingredients ri on ri.id_recipes = r.id left join ingredients i on ri.id_ingredients = i.id group by r.id order by ing_cnt desc 	6.53805214874283e-05
18742645	19903	get last five record form each category	select * from (   select a1.*, count(*) cnt from tbl_article a1   left join tbl_article a2     on a1.article_category_id = a2.article_category_id and a2.article_id <= a1.article_id   group by     a1.article_category_id, c1.article_id ) t where cnt <= 5; 	0
18743071	30190	select rows combining join & count	select  a.id, a.title, a.description, a.user_id, a.timestamp,         b.id replyid, b.reply_text, b.user_id, b.discussion_id,          b.timestamp replytimestamp,         coalesce(c.totalreplies, 0) totalreplycount from    discussion a         left join         (             select  a.*             from    reply a                     inner join                     (                         select  discussion_id, max(timestamp) timestamp                         from    reply                         group   by discussion_id                     ) b on  a.discussion_id = b.discussion_id and                             a.timestamp = b.timestamp         ) b on  a.discussion_id = b.discussion_id         left join         (             select  discussion_id, count(*) totalreplies             from    reply             group   by discussion_id             ) c on a.discussion_id = c.discussion_id 	0.0210611240125801
18745198	19984	trying to select multiple columns where one is unique	select * from (select row_number() over (partition by b order by a) no ,* from tablename) as t1 where no = 1 	0.000994792798911208
18751251	26499	how to find all objects used inside oracle triggers	select * from user_dependencies where type = 'trigger'; 	0.0305328466298355
18752790	22866	select * from table where id != long_list	select * from table where table_id not in (select table_id from cleared_table where user_id=user_id) 	0.00238352973522571
18752880	26366	what command should i use to get the actual value of a parameter in toad for oracle?	select *  from v$parameter where upper(name) = 'optimizer_secure_view_merging' 	0.161839466614961
18754955	32082	sql list number of people born every year	select year, count(*) as 'number of people born' from sometable group by year order by year asc 	0
18760434	3351	mysql: how to check field has data in mysql?	select distinct     cal.carlistingid,     cal.listingnumber,     cal.caption,     cal.year,     cal.km,     cal.color,     cal.price,         concat((select name from city where cityid in (select cityid from county where countyid = cal.countyid)),'/', (select name from county where countyid = cal.countyid)) as region,     cal.creation,     ( case when  ci.imageurl is null then 'asdf' else  ci.imageurl             end) from     carlisting as cal left join carimage as ci on ci.carlistingid = cal.carlistingid         inner join user as u on u.userid = cal.createdby inner join carlistingcategory as clc on clc.carlistingid = cal.carlistingid order by cal.creation; 	0.0023716893614133
18760618	38406	getting multiple values in a single mysql query	select group_concat(name) as name from people where age='20' 	0.00682906492252712
18762630	39026	optimizing the query into one	select     upity.wid,     webit.email,     count(*) as count from     uptime upity         join website webby             on upity.wid=webby.webid where     upity.time_stamp>=date_sub(now(),interval 10 minute)      and upity.status<>200 group by     upity.wid,     webit.email having count=2 	0.0732240836870317
18764936	3949	removing single quotes from comparison in select statement	select     if(         replace("john's favorite","'","") = "johns favorite" ,         "found",        "not found"    ) 	0.166998989713817
18765000	28885	select query to get those result where for every unique value of column 3, column 2 has bothval1 and val2	select t.*  from your_table t inner join (     select id, min(type) as mint, max(type) as maxt     from your_table     where type in (6,7)     group by id     having count(distinct type) = 2 ) x on x.id = t.id and t.type in (x.maxt,x.mint) 	0
18765085	11234	sql search to return if several user inputs are empty	select * from coursestaught c where c.section = :section union select * from coursestaught c where c.semester=:semeste 	0.00432488304686341
18765633	4257	get the per-row number of keys of hstore data in postgresql	select hstore_column,         array_length(akeys(hstore_column), 1) as num_keys from the_table 	0
18766796	27237	how to query multi 'or' and a and in sql?	select distinct a.project from table a, table b where a.project= b.project and     ( a.tag = 3 and b.tag = 4 ) or      ( a.tag = 0 and b.tag = 4 ) 	0.502638234150583
18768891	16045	combining 2 rows	select * from (     select cla.caseserviceid,         cla.servicetypeprogkey,         sum(cla.claimamount) claimamount,         max(cla.paidamount) paidamount,         max(cla.claimquantity) claimquantity     from claim cla     group by cla.caseserviceid,         cla.servicetypeprogkey     ) as srcservicetype pivot(max(servicetypeprogkey) for servicetypeprogkey in (             [flatbed],             [dtv tow]             ) as pvtservicetype) 	0.00520200402750986
18776579	2981	how to get lgwr lag from oracle database	select * from dba_hist_system_event where event_name ='log file parallel write' 	0.0153322160440108
18777725	11517	multi columns using union query	select  a as "utilizations a",          b as "utilizations b"  from    (select  utilizations as a,             0 as b     from tablea     union all     select 0 as a,            utilizations as b     from tableb   )as t 	0.250442141045513
18779842	2542	mysql show record not in other logins group	select group_id, group_name, login_id from group_member join groups on group_member.group_id = groups.id where group_id not in     (select group_id from group_member     where login_id=1) 	0.00066219649109801
18780194	16510	how to regex in a sql query	select trecord from `tbl` where (trecord regexp '^ala[0-9]') 	0.590770127267522
18780208	16437	return 0 is count for particular condition is null	select date(feed_date) as fdate,         sum(id = 8671) as count  from table  group by fdate 	0.0554339807436485
18783134	25860	sql query two tables	select id  from messages  where id not in (     select id      from messagesread      where username = 'your_input_name'); 	0.071950370749351
18785270	24645	mysql regex selecting string and incremental number	select * from tablename where email like 'newuser%' order by cast(substr(email from 8) as unsigned) desc limit 1 	0.00340192594917718
18786124	14531	how to retrieve specific rows from sql server table?	select * from (   select     row_number() over (order by columnname asc) as rownumber     from tablename )  as temptablename where rownumber in (2,5) 	0
18789580	29282	joining to same column but getting no rows	select  * from table 1 join table2 2 on 2.id = table1.id union select  * from table 1 join table2 22 on 22.parentid = table1.id 	8.31938182134128e-05
18789589	39110	getting a sum of datetime differences of a joined table	select c.id            ,c.clockdatetimein as 'date'             ,datename(dw, c.clockdatetimein) as 'dayofweek'            ,c.userid            ,c.clockdatetimein as 'clockintime'            ,c.clockdatetimeout as 'clockouttime'            ,sum(convert(time,(b.timeout - b.timein))) att_time            ,sum(datediff(mi, clockdatetimein, clockdatetimeout)) att_minute            ,sum(datediff(hh, clockdatetimein, clockdatetimeout)) att_hour       from clockinlogs c       join breaks b          on c.id = b.cid       join users u          on cid=id   group by c.id            ,c.userid            ,c.clockdatetimein            ,c.clockdatetimeout 	0
18790078	52	sql query to fetch data from 4 different tables	select cm.companyname as companyname, u.email as user, ts.status as status, ts.comments as comments, ts.createdate as createdate, ts.updatedate as updatedate from   taskstatus as ts  left join taskdetails as td on td.taskid = ts.taskid  left join company as cm on cm.cloudid = td.cloudid  left join users as u on u.userid = ts.updatedby where  ts.createdate>'2013-08-01' and ts.updatedby!=1 and ts.status='completed' group by cm.companyname, u.email; 	0.000155597765349687
18790217	31361	getting the quickest times from a database	select (`end_date`-`start_date`) as `time` from `table` order by `time` asc 	0.001271334036152
18791307	3841	removing duplicate in a column	select v.id, max(c.image_type_id), max(vp.x),  max(vp.y), max(vp.z) from v, vp, c, where v.id = vp.id    and v.id = c.id group by v.id; 	0.0101306852119639
18791408	35627	united states as first value in alphabetical table	select country      from countries  order by case when country = 'united states'                then '0'                else country end; 	0.000824705870213138
18793582	3092	verify or not the column in where clause	select * from table where column1 = $_get['id'] and       (column2 is null or column2 = $_get['id']); 	0.688029724793871
18793815	9327	returning all parent table rows but return null for child table rows that don't match the where clause with mysql	select * from classes as c left join class_responses as cr on c.id = cr.class_id and cr.user_id = 7 	0
18794515	2300	zip xml nodes using xquery?	select @x.query('     element cols {       for $c in /cols/col         return           <col>            { $c/name }            { element value { text {/values/*[local-name()=$c/name/text()[1]]} } }           </col>     }   '); 	0.187209769974608
18796011	23952	use query result row in another query	select * from messages where to_user in (select username from users1 where email = '$param') 	0.0422823846931296
18796434	21012	retrieve all records from one table even if a related record can't be found in a related table	select ws.wastetype, sum(ws.recordedweight) totalweight, sum(ws.percent) totalpercent, wt.id, wt.category, wt.defrecycling, fw.tonnes  from c1skips.forecastwaste fw join c1skips.wastetypes wt on (wt.id = fw.wastetype) left join c1skips.wastestream ws on (ws.contractid = fw.contractid) and (ws.wastetype = fw.wastetype) where fw.contractid = '602' group by ws.wastetype; 	0
18797900	20787	error trying to use temporary columns, mysql	select *, (finalresult = "winner") as win from (select userid, pickid, nflp_picks.gameid, visitorid, visitorresult, homeid, homeresult,              if (pickid=visitorid, visitorresult, homeresult) as finalresult       from nflp_picks       join nflp_schedule       on nflp_picks.gameid = nflp_schedule.gameid       order by gameid, pickid, userid       limit 0, 200) x 	0.766018320555136
18800467	2424	how can i select from more than one table in a sqldatasource asp.net	select * from tb1 union all  select * from tb2 union all select * from tb3 order by id desc; 	0.00311689141167379
18801324	20960	retrieve database value based on year?	select * from   holidays where   year(`date_field`) = year(now()) 	0
18802299	11265	mysql : multiple counts in one query	select  worker, count(*) totalproducts from    tablename where   company = 2 group   by worker 	0.0312448623271448
18802552	1289	mysql join query that needs to return negative set	select * from users u where not exists (     select * from tasks t     where t.user_id = u.user_id     and t.status = 'complete'     ); 	0.0735832781881066
18803117	24929	return date of max value for a particular id	select * from t join (select id, max(value) as value from t group by id) as max_t using (id, value) 	0
18805811	20087	error when using sum on a text value	select sum(case when cast(column1 as varchar(max)) = 'sometext' then 1 else 0 end) from table1 	0.438394200328407
18806494	26746	counting the number of columns in the database	select count(*) from `information_schema`.`columns`  where `table_schema`='yourdatabase'      and `table_name`='yourtable'; 	0
18807178	24452	postgresql running sum of previous groups?	select     seq,     amount,     lag(amount::int, 1, 0) over(order by seq) as previous from (     select seq, sum(amount) as amount     from sa     group by seq ) s order by seq 	0.00480921825141561
18809182	27770	select from string field , separated sqlserver	select * from table1 where       str like '%,' + @input + ',%' or       str like @input + ',%' or       str like '%,' +@input or        str = @input 	0.000289021715893091
18809897	29025	merge rows data in tsql	select '' + [data]  from table1 for xml path ('') 	0.00528828530036699
18809976	20391	select mysql field that contains a substring	select  keyword  from    table  where   ('tell me about admission info' like concat('%', keyword, '%')) 	0.0101684325529134
18811342	21230	sql query: is it possible to select or get the records of a column that has the same values without any parameter to compare?	select ... from ... where column1 in (select column1 from table group by column1 having count(*) > 1) 	0
18812219	28617	field null in sql	select count(*) from regular where path is null 	0.147235038434929
18812711	17618	selecting all rows where a column has an specific id	select  userid, username from    tablename where find_in_set('1', following); 	0
18812979	29280	mysql select data across 4 tables (multiple conditions)	select r.form, s.value as email,        (case when max(l.listid is not null) then 'yes' else 'no' end) as inlist33 from subrecords s join      records r      on s.record = r.id and r.name = 'question-form' left outer join      subscriber_schema ss      on ss.email = s.value left outer join      listsub l      on ss.subid = l.subid and         l.listid = '33' where s.title = 'email' group by s.value, r.form; 	0.00656558023627558
18819519	20030	oracle sql select the table and cumulative calculate the score by the date	select distinct id, term, avg(score) over (partition by id order by term) from foo; 	0
18821041	28264	oracle, split a time duration row by one hour period	select greatest(start_time, trunc(start_time+(level-1)/24, 'hh24')),  least(end_time, trunc(start_time+(level)/24, 'hh24')) from log_table  connect by level <= floor((dt1-dt2)*24)+1; 	0
18821471	26436	mysql: count number of ids in one column matching multiple defined ids (rows) in another column	select count(*) from  ( select object_id    from test_term_relationships    where test_term_relationships.term_taxonomy_id in (3,11)    group by object_id    having count(*) > 1  ) dt 	0
18823154	6980	sql - sum based on another column	select horsename, sum(prizemoney) totalprizemoney from yourtable yt group by horsename having sum(prizemoney) >= 110 	0.000174729693282958
18823950	8804	mysql group by and average for non zero values	select                     carrier,              avg(duration)       from tablename        where duration>0      group by carrier;     	0.00098757655276985
18824950	26192	sql for the wordpress database	select p2.meta_value email   from wp_postmeta p1 join wp_postmeta p2     on p1.post_id = p2.post_id    and p1.meta_key = 'opt_in'    and p2.meta_key = 'email'  where p1.meta_value = 1 	0.161611284092156
18826062	24347	mysql select one row with unique attribute value	select t.product_id, t.warehouse_id, t.balance, t.date   from table1 t join  (   select warehouse_id, product_id, max(date) date     from table1    where date <= '2013-09-25'    group by warehouse_id, product_id ) q     on t.warehouse_id = q.warehouse_id    and t.product_id = q.product_id    and t.date = q.date 	0
18826128	34644	postgresql concatenate two tables on each row	select  table_one.val || '_' || table_two.val from  table_one  cross join table_two 	0
18826457	6098	mysql count on joined table	select u.username, p.postscount, recomm.recommcount, recomm.likescount from users u  join  (    select author_id, count(*) as postscount    group by author_id  )  as p on u.id = p.author_id join  (    select recommendedbyuserid as rid, count(*) as recommcount, sum(u.likes) as likescount    from users u     group by recommendedbyuserid  ) recomm on recomm.rid = u.id order by recomm.recommcount desc 	0.0108281355885936
18827988	12136	how to take all values from sql table column on condition?	select  * from [vwmydata]  where path like '%' + @path + '%' and ((@status is null )or (status = @status or status is null)) 	0
18828002	16808	how to check if a given data exists in multiple tables(all different column names)	select user.id, a.director, b.faculty, c.member, d.advisor, e.student, f.user from user     left join alpha a on user.id = a.director     left join beta b on user.id = b.faculty     left join gama c on user.id = c.member     left join ththa d on user.id = d.advisor     left join epsilon e on user.id = e.student     left join pi f on user.id = f.user 	0
18828187	25464	mysql select all except where two columns have specific data together	select *  from table  where not (duration = 'd' and timestamp = '2013-09-15 12:00:00'); 	0
18828498	7509	ssis- set multiple variables via a single sql task	select 1 as one, 2 as two 	0.327041028605783
18830949	12022	sql query finding field with multiple rows	select emp  from z_insur  where insur_type = 'm' group by emp  having count(*) > 1; 	0.00482895788582564
18831482	16007	sql server update permissions	select count(*) from person where ptrackid = 20  and pwebid like 'rtlr%'; 	0.525306506221285
18831990	28092	add a record on the fly sql server2008	select * from tblname union all select 6, <fill-in-other-columns> 	0.000729020921216685
18832209	13906	get concatenated list of id's for same product	select distinct concat(a.custid, ',', b.custid) from customer a join customer b on a.prodid = b.prodid where a.custid < b.custid 	0
18832852	10344	mysql query counting on multiple tables	select u.id,count(distinct ruid),sum(p.likes) from users as u left join (select recommendedbyid as rid,id as ruid from users) as r on r.rid = u.id left join posts p on p.author_id = ruid group by u.id 	0.0312728276967151
18833654	16342	how do i order by within a left join?	select p.[define fields here, never use select * in production code], o3.isprimary, o3.startdate, o3.orgname, o3.title  from `profiles` as p left join      (select o.id, o.isprimary, o.startdate, o.orgname, o.title      from  `orgs` as o     join (select id, max(startdate) as startdate from   `orgs` group by id) as o2       on o.id = o2.id and o.startdate = o2.startdate) as 03 order by p.id, o3.isprimary 	0.742459118190498
18833700	1548	postgres sql select combination of two columns	select *  from p  where (option_type, value) in ( ('x' ,'a'), ('x','b'), ('y','d') ) 	0.000761872134483621
18834204	16611	mysql custom order excluding values	select * from yourtable order by case when name = 'home' then 1               when name = 'logout' then 3          else 2          end asc,          name asc 	0.0637745445249991
18834654	11077	how do i combine multiple queries?	select max(most_recent_active), max(most_recent_inactive), key_value, min(status_id) from (select null as most_recent_active, max(set_date) as most_recent_inactive, key_value,statusid from status_history where base_table = 'userinfo'   and statusid = 10 and set_date > to_date('2012-10-01', 'yyyy-mm-dd') group by key_value,statusid     union all select max(set_date) as most_recent_active, null as most_recent_inactive, key_value,statusid from status_history where base_table = 'userinfo'   and statusid = 11 group by key_value,statusid order by key_value) group by key_value 	0.0785260947860274
18835176	25752	sql - select max between multiple rows	select f.*  from foo as f inner join maxforgroup(     select max(count_of_items) maxc, item_type      from foo     group by item_type ) as m on f.count_of_items=m.maxc and f.item_type =m.item_type 	0.00299858115043862
18835205	18636	query multiple records of a group that has max date....sorta	select * from  (    select  id, name, date,        rank() over (order by cast(date as date) desc) my_rank    from @table  ) dt where my_rank = 1 	0.000567292443376767
18835316	21902	need mysql to group by one column based on the order of another	select distinct d.diid, d.name, d.type from (     select d2.type, min(d1.sortorder) as srt     from dashboard_item_controls d1         join dashboard_items d2 on d1.diid = d2.diid     where d1.status = 'on'     group by d2.type     ) t join dashboard_items d on d.type = t.type         join dashboard_item_controls dd on dd.diid = d.diid where dd.status = 'on' order by t.srt asc, dd.sortorder asc 	0
18836459	22144	aggregating 2 tables in tsql	select user, sum(hits) hits from (select user, hits from tbl1 union all select user, hits from tbl2) a group by user 	0.0500099942684905
18836466	3658	optimize a query over several tables with default	select distinct cb.customers_id, c.customers_firstname, c.customers_lastname, c.customers_email_address, sc.datemodified as last_contacted from customers_basket cb  inner join customers c on c.customers_id = cb.customers_id left join scart sc on cb.customers_id = sc.customers_id where cb.customers_basket_date_added < 20130916    and cb.customers_basket_date_added > 20130101   and cb.customers_id not in(select sc.customers_id                             from scart sc                     where sc.datemodified >20130816) order by cb.customers_id desc 	0.535770358437856
18836497	22857	query on three tables returning duplicate rows	select  c.carmake,      c.cartype,      i.totalkms,     i.endingkms,     convert(varchar(10), convert(int,100.0*( isnull( i.incomepricetotal, 0) - isnull( e.expenseamounttotal, )) / c.carbuyprice)) +'%' as incomepercentage,      e.expensesum from cars c outer apply (     select  sum(i.incomekmend -i.incomekmstart) as totalkms,             max(i.incomekmend) as endingkms,             sum(i.incomeprice) as incomepricetotal from incomes i  where i.carid = c.carid  and i.incomedatefrom between '20130101' and '20140101' ) i outer apply ( select  sum(e.expenseamount) as expenseamounttotal,          sum(case when e.paymenttype like '%extra%' then e.expenseamount else 0 end) as expensesum from expenses e  where e.carid = c.carid  and e.expensedatefrom between '20130101' and '20140101' ) e 	0.00204420118293721
18836524	20269	combining rows of data with the same date	select r.[name], p.[name], s.[number], t.[name],    sum(case when datepart(dw, d.activitydate) = 1 then d.[hours] else 0 end) as monday,    sum(case when datepart(dw, d.activitydate) = 2 then d.[hours] else 0 end) as tuesday,    sum(case when datepart(dw, d.activitydate) = 3 then d.[hours] else 0 end) as wednesday,    sum(case when datepart(dw, d.activitydate) = 4 then d.[hours] else 0 end) as thursday,    sum(case when datepart(dw, d.activitydate) = 5 then d.[hours] else 0 end) as friday,    sum(case when datepart(dw, d.activitydate) = 6 then d.[hours] else 0 end) as saturday,    sum(case when datepart(dw, d.activitydate) = 7 then d.[hours] else 0 end) as sunday from dailytaskhours d inner join task t on d.taskid = t.pk_task inner join story s on t.storyid = s.pk_story inner join sprint p on s.sprintid = p.pk_sprint inner join product r on p.productid = r.pk_product group by r.[name], p.[name], s.[number], t.[name] 	0
18836562	12909	sql server - query with multiple joins dependent of first or second join	select t1.field1, t4.field1 from t1 left join t2      on t1.field1 = t2.field1 left join t3      on t1.field1 = t3.field1 left join t4      on coalesce(t2.field1, t3.field1) = t4.field1 	0.0838278081433286
18836894	32443	mysql group by and where	select id1, id2, status,    (select max(value) from test1 t2 where t1.id1 = t2.id1) value  from test1 t1 where status = 'vn' 	0.452298785247473
18837462	911	how to total results within the query	select cb.customers_id, cb.products_id, p.products_model, pd.products_name, cb.customers_basket_quantity, p.products_price, (p.products_price * cb.customers_basket_quantity) as product_total, (select sum(p.products_price * cb.customers_basket_quantity)  from customers_basket cb, products p where cb.customers_id =194075 and cb.products_id = p.products_id group by cb.customers_id) as cart_total from customers_basket cb, products p, products_description pd where cb.customers_id =194075 and cb.products_id = pd.products_id and p.products_id = pd.products_id 	0.00304669326542559
18838140	25089	multi table join adding columns sql server	select t2.fid, t2.[office name], sum(t3.totalinvoice)  from table2 t2 join table1 t1 on t2.fid = t1.did join table3 t3 on t1.fid = t3.fid group by t2.fid, t2.[office name] 	0.0893327212549715
18840557	10946	mysql concat("string",longtext) results in hex string	select concat("abc",cast(t.longtext_value as char),"cde") from mytable t 	0.468133321605731
18840558	25972	rows to columns gets nulls in mysql	select        `receiverid`,        sum(if(strategies="emotionalnegative", counts, 0)) as en,        sum(if(strategies="rationalpositive", counts, 0)) as ep from strategiesused group by receiverid 	0.00418209784328288
18840750	14295	cast number of bytes from blob field to number	select id,         ((ord(substr(`data`, 1, 1)) << 24) +         (ord(substr(`data`, 2, 1)) << 16) +         (ord(substr(`data`, 3, 1)) << 8) +          ord(substr(`data`, 4, 1))) as num from test; 	0.000110771159644203
18842166	39115	find numbers of weeks in date range(from date-to date) in sql server	select     sum(counter),     datediff(day, @fromdate, cdate) / 7 as ddiff from weekdate where cdate >= @fromdate and cdate <= @todate group by datediff(day, @fromdate, cdate) / 7 	8.74244894533247e-05
18842629	13457	mysql intersection	select u.id, u.first_name, u.last_name from users u join answers a   on a.user_id = u.id join questions q   on a.question_id = q.id join question_options o   on a.option_id = o.id where (q.question = 'language known' and o.option in ('french','russian'))    or (q.question = 'height' and o.option = '1.51 - 1.7') group by u.id, u.first_name, u.last_name having   sum(case when (q.question = 'language known' and o.option in ('french','russian')) then 1 else 0 end) >=1 and    sum(case when (q.question = 'height'         and o.option = '1.51 - 1.7')          then 1 else 0 end) >= 1 ; 	0.317125287843838
18845489	21291	check in mysql db whether column is filled out with one specific value	select * from comments where controle = 'ok' order by id desc 	0
18845888	17776	use columns from select statement as parameter in function when joining	select taskid,fromitemid, ihv_from.nodepath as frompath from view_tasks with (nolock)  outer apply fn_item_hierarchy(fromitemid) ihv_from where ... ; 	0.456340350887561
18846196	16961	oracle sql to check online performance based on log in and log out	select *, (record_date - lag(record_date, 1, 0) over (partition by dev_id order by record_date)) *24*60 min from device_log 	0.183979348641485
18846373	7958	create query in access to have new id in each item	select  left([partid], instr([partid], "0")-1) & right(max(cint(right([partid],4)))+10001,4) as npartid, tblparts.partname from tblparts group by tblparts.partname, left([partid], instr([partid], "0")-1) 	0
18846730	604	duplicate table data but modify one column	select * into #temp from mytable where year=@curent_year update #temp set year=year+1 insert into mytable select * from #temp drop table #temp 	0.000257130434630214
18846952	13309	convert mysql date (now()) to bigint	select unix_timestamp(now( ) ) 	0.0702655202199294
18848419	31999	sorting results based on different criteria in mysql	select quote   from quote q, users u, followers f   where q.user_id = u.id   and q.user_id = f.follower union select quote   from quote q, users u, followers f   where q.user_id = u.id   and q.user_id <> f.follower 	0.000406927020350327
18848440	22188	retrieve individual character from varchar field in sql server	select  case when charindex('a', columnname, 1) > 0 then 1 else 0 end has_a,         case when charindex('b', columnname, 1) > 0 then 1 else 0 end has_b,         case when charindex('c', columnname, 1) > 0 then 1 else 0 end has_c,         case when charindex('d', columnname, 1) > 0 then 1 else 0 end has_d from    tablename 	0.000317174622201773
18849729	4611	find last record in db for each repeated field(oracle query)	select *  from   (    select ccd.*, sd.*, row_number() over (partition by login order by begdtu desc) rn    from stat.cause_code_descriptions ccd    inner join stat.stat_dial sd       on ccd.code = sd.cause    where called like '%3623.1348'   ) dt where rn = 1  order by begdt desc 	0
18849986	25386	sql create category path/tree/hierachy	select coalesce(down3.id, down2.id, down1.id, root.id), root.name  as root_name  , down1.name as down1_name  , down2.name as down2_name  , down3.name as down3_name 	0.0708631075879357
18850010	25291	find emails in the same table that having %40 in mysql	select * from table group by replace(email, '%40', '@') having count(*) < 2 and email like '%\%40%'; 	0.000333108261921911
18851527	4388	how do i generate row number without using rownum() in sql server	select *, (     select count(*)     from prd p2     where p1.prdid >= p2.prdid ) as cnt from prd p1 	0.00449458855241201
18852823	24440	find max amount and second max amount for each listings	select t1.item_id,  max(t1.price) as max1,  (select t2.price from table as t2 where t2.item_id = t1.item_id order by t2.price desc limit 1,1) as max2  from table as t1  where t1.date > 2013-01-01  group by t1.item_id 	0
18854544	3936	in oracle, how to select unique together indexes for table along with affected columns	select i.index_name,          c.column_position,          c.column_name,          i.uniqueness   from sys.all_indexes i,         sys.all_ind_columns c    where i.table_name  = 'my_table'      and i.owner       = 'me'      and i.uniqueness  = 'unique'    and i.index_name  = c.index_name      and i.table_owner = c.table_owner      and i.table_name  = c.table_name      and i.owner       = c.index_owner    and c.index_name in (select index_name from sys.all_ind_columns where column_position = 2); 	0.00038938026171402
18854976	35841	oracle sql how to calculate if a birthdate is in 2 months from sysdate	select * from account_info where to_char(sysdate,'yyyy')-to_char(birth_date,'yyyy') = 25 and to_char(add_months(trunc(sysdate), 2),'mm') = to_char(birth_date,'mm'); 	5.35692822738935e-05
18856197	11472	sql - restrict the number of rows returned based on a count of rows	select * from  (   select item_id, group_id, count_of_items,    row_number() over(partition by group_id order by count_of_items desc)    as rn   from items_in_groups ) a where rn <= 2 	0
18857781	926	how to get the smallest value from the top 3 rows of the table in mysql	select min(low) from(     select         `low`      from `stocksdata`      where         `stocksymbol` = "msft"      order by          timestamp desc limit 3) ltd 	0
18861019	25552	mysql query 7 days prior to say days ahead	select     * from     mytable where     mytimestamp >= date_add(mytimestamp , interval -7 day)     and     mytimestamp <  date_add(mytimestamp , interval  7 day) 	0
18863631	39006	count no of occurences of elements in single row	select table_name.*,        case score1 when -1 then 1 else 0 end +        case score2 when -1 then 1 else 0 end +        case score3 when -1 then 1 else 0 end +        case score4 when -1 then 1 else 0 end +        case score5 when -1 then 1 else 0 end         as score_count   from table_name; 	0
18864476	39800	how to concatenate data from a sql server xml query?	select     stuff(         @data.query('             for $i in row/urlsegment return <a>{concat("/", $i)}</a>         ').value('.', 'varchar(max)')     , 1, 1, '') as url,     stuff(         @data.query('             for $i in row/shortenedurlsegment return <a>{concat("/", $i)}</a>         ').value('.', 'varchar(max)')     , 1, 1, '') as shortenedurl 	0.00307945261342999
18865356	40812	return mutiple value for on column in sql select	select customer , group_concat(product separator ',') as product from tablename group by customer 	0.00174430232307151
18867738	21990	database cell with multiple values?	select * from diseases where disease_id in (select disease_id from diseases_vs_symptoms where symptom_id = my_symptom); 	0.00442597840313627
18869086	34229	mysql join with and condition	select *   from questions join        (select ceil(rand() *                     (select max(question_id)                        from questions where uid='$user_id')) as question_id         ) as r2        using (question_id) ; 	0.675515947250476
18869432	8470	how to use subquery to populate column in access query	select need_rows.id , need_rows.qty , need_rows.product_id , (select top 1 price  from prices  where need_rows.product_id = prices.product_id  and need_rows.use_date >= prices.valid_from  order by prices.valid_from desc) as currentprice from need_rows; 	0.758522457469117
18869976	36746	sql server 2005 : how to check for empty string	select nullif(mobileareacode, '')+nullif(mobile, '') as mobileareacodemobile from yourtable 	0.142006407559476
18870422	32084	mysql query to select only one unique name on a criteria	select t.* from your_table t inner join (     select name, min(hobby_number) as minh     from your_table     group by name ) x on x.name = t.name and x.minh = t.hobby_number 	0
18870589	511	looped count query(oracle)	select trunc(dt) as dt, count(*) as cnt from stat.jurnal  group by trunc(dt); 	0.369122392651931
18870970	7687	merge two tables and get sum without select all from huge table	select n.[user], n.award + isnull(sum(h.award),0) as award from useraward_new n left join useraward_his h on h.[user] = n.[user] group by n.[user], n.award 	0
18871358	37125	date range between two date columns	select * from task_schedule_times where `end_dt` >= "2013-09-18 14:00:00" and       `start_dt` <= "2013-09-18 16:00:00" 	0
18872824	4449	mysql query with multiple sub queries for each row	select   a.*,   ad.*,   vs.date as steponedate from applications a   left join verification_status vs     on vs.application_id = a.id     and vs.verification_step_id = 1   left join application_details ad     on ad.application_id = a.id where ad.application_status_id != 1   and ad.application_status_id != 2; 	0.00484855594411121
18873467	9029	how to calculate running balance of banking table using mysql	select userid, sum(credit)-sum(debit) from balance group by userid 	0.0123585107494395
18874518	17360	select users who have made the most positive contributions	select       count(artc_status) as stats ,       count(case when artc_status=1 then 1 end) positive,            artc_user[contributing user]  from      contributions  group by      artc_user  order by  stats desc; 	4.92150019327377e-05
18876134	6008	how to get date_of_highest_points	select nick, sum(frags) sumfrags, sum(points) sumpoints, sum([hours]) sumhours, max(lastdate) lastdate, max(points) highest_points   into #t1   from hraci  group by nick select t1.*, x.lastdate date_of_highest_points   from #t1 t1          outer apply        (select top 1 lastdate            from hraci t          where t.nick = t1.nick and t.points = t1.highest_points          order by t.lastdate desc) x 	0.0293066950712035
18876416	26885	how to create an empty anonymous table in postgres?	select null::text as a, null::int as b limit 0 	0.0617018851612861
18876801	17399	mysql count with several criteria coloumn one table	select *, count(*) from table_name group by month, year, type, color;   	0.00155725183631203
18877293	36620	join count and sum queries into single dataset	select * from  (select count(polnum) as polcount, datepart(wk, submitdate) t1week from policy inner join product on policy.prodid = product.prodid where (year(submitdate) = year(getdate())) group by prodcat, submitdate) as t1 inner join  (select sum(prem) as sumprem, datepart(wk, submitdate) t2week from policy inner join product on policy.prodid = product.prodid inner join  prem on pol pol.polnum = prem.polnum where (pend = 1) group by prodcat, submitdate) as t2 on t1.t1week = t2.t2week 	0.00623853085381751
18878005	22776	subquery the same table in select statement	select item_num, sum(i.price) + sum(nvl(x.ingred_price,0))   from invoices i left outer join      (select parent_item_id              , sum(price) ingred_price           from invoices          where parent_item_id is not null        group by parent_item_id) x on x.parent_item_id = i.item_id where i.parent_item_id is null       group by item_num 	0.0365955348580835
18879465	373	best method of organizing database?	select   *  from    classes  join    subjects_per_class  on    classes.id = subjects_per_class.class_id join    subjects  on    subjects.id = subjects_per_class.mat_id 	0.366035482584064
18880279	7848	mysql join and return the longest url per domain	select link.id, link.page_href, dom.domain_name from(    select domain.id, domain.domain_name, max( length( link.page_href )) max_len   from `google_sort_backlink_domains` as domain   join `google_sort_backlinks` as link on link.domain_id = domain.id   where domain.tablekey_id = 22   group by domain.id, domain.domain_name ) dom join `google_sort_backlinks` as link on  link.domain_id = dom.id    and length( link.page_href ) = dom.max_len 	0.00120561158776886
18880432	30844	mysql - selecting usernames based on work submitted (two-variable)	select username, count(username) as occurences, sum(difficulty) as difficulty   , sum(difficulty)/count(username) as share_times_difficulty from shares group by username order by share_times_difficulty desc 	0.0121584851131527
18880935	20677	how do i group by all non-null values and do not group null values	select itemname, sum(whatever) from tab where itemname is not null group by itemname union all select itemname, whatever from tab where itemname is null 	0.000932022542325255
18881110	39203	sql query to match all row with other row on same table	select    p.id productid, s.id serviceid, p.title producttitle, s.title servicetitle from (select id, title from tbl where typeid = 1) p cross join (select id, title from tbl where typeid = 2) s order by p.id, s.id 	0
18882426	22508	display data once if same	select     usergroup.name   , group_concat(user.name separator '<br />') 'users' from   user inner join   usergroup on  user.usergroup_id = usergroup.id where   user.rights = 2 group by    usergroup.id 	5.1723576221983e-05
18883203	24659	sql - using sum but optionally using default value for row	select     ds.date,     100 - 100 * sum(         case             when he.asset_id is not null then 86400              when dh.num_error_seconds is null then 0              else dh.num_error_seconds         end     ) / 86400 / count(a.id) as percent  from     date_sequence ds         cross join     asset a         left outer join     daily_history dh          on a.id = dh.asset_id and            ds.date = dh.date         left outer join (             select distinct                  asset_id             from                 historical_event he             where                 he.end_date > in_end_time         ) he         on a.id = he.asset_id     where     ds.date >= in_start_time and     ds.date <= in_end_time  group by     ds.date 	0.00405241021023253
18883366	28760	group by only rows with a certain condition and date	select  transaction_date, transaction_type, sum(transaction_amount) from    tablename group   by transaction_date,             case when transaction_type = 'refund' then 1 else rand() end order   by transaction_date desc 	0
18885070	4748	finding the child table for a cascading delete	select     db_name() as constraint_catalog, user_name(c_obj.uid) as constraint_schema, c_obj.name as constraint_name, db_name()                        as table_catalog, user_name(t_obj.uid) as table_schema, t_obj.name as table_name,                        case c_obj.xtype when 'c' then 'check' when 'uq' then 'unique' when 'pk' then 'primary key' when 'f' then 'foreign key' end as constraint_type,                        'no' as is_deferrable, 'no' as initially_deferred, mt_obj.name as parenttable from         sysobjects c_obj, sysobjects t_obj, sysforeignkeys sf, sysobjects mt_obj  where     permissions(t_obj.id) != 0 and t_obj.id = c_obj.parent_obj and c_obj.xtype in ('f') and sf.constid = c_obj.id and sf.rkeyid = mt_obj.id 	0.000883150948794436
18885437	12962	column is invalid in select	select      cnt, c.cusid, cuslname, cusfname, cusmname, cusaddress, cusemailadd from customer c  join (     select           count(orderid) cnt, cusid     from order o      group by         cusid ) o on     c.cusid = o.cusid order by     c.cusid 	0.579604858378456
18885698	13576	mysql - select from id to id	select * from your_tbl  where column1 between 60000 and 200000; 	0.000275148790747482
18887959	39276	mysql - how to reorder records depending on counted quantity	select c.* from c  inner join (   select city, count(*) as cnt from c group by city ) a on c.city = a.city order by a.cnt desc, c.name asc 	8.34003079385809e-05
18888776	21784	select total members and amount they paid - sql	select   org.name,          sum(pmt.amount) as revenue,          sum(if(pmt.transferred_at is null, pmt.amount, 0)) as untransferred from     organisations org     join members       mem on mem.organisation_id = org.id     join payments      pmt on pmt.member_id       = mem.id group by org.id 	0
18889056	205	finding a 'run' of rows from an ordered result set	select * from  (    select the_date, name, grp,       count(*) over (partition by grp) as cnt    from     (       select the_date, name,           sum(flag) over (order by the_date) as grp       from        (          select the_date, name,              case when lag(name) over (order by the_date) = name then 0 else 1 end as flag          from orders          where               the_date between                   to_date('2013-09-18',..) and                   to_date('2013-09-22', ..)        ) dt     ) dt  ) dt where cnt >= 3 order by the_date 	0
18891351	24518	mysql multiple references between tables	select components.*  from components  join product_components   on components.id = product_components.component_id where product_components.product_id = <some product id> 	0.0125758171960926
18891453	3588	mssql - select from another table if no results from the first table	select top 1 price from (     select 1 as qorder, price from customer_price where price > 0 and customer='walmart' and product='whitebread'     union     select 2 as qorder, price from default_price where price > 0 and customer='walmart' and product='whitebread'     union      select 3 as qorder, 0      ) as sq order by qorder 	0
18891511	27110	group by with string postfix	select    *  from    project  group by    if(substr(name, -3)='_qa', left(name, char_length(name)-3), name); 	0.507460765210972
18891709	29044	mysql print data between dates	select * from sccp_raw  where dt between curdate() - interval 11 day           and curdate() - interval 4 day limit 5; 	0.00185970810226759
18892081	19120	how to group by with a sql that has multiple subqueries	select f.groupproducttype,        min(j.creationdate),        sum(case when j.invoicedate < '1990-01-01' then j.grossexclvat else 0            end) as product1 from sc_jobs inner j join      sc_frames f      on f.jobid = j.jobsid where j.creationdate between :startdate and :enddate group by f.groupproducttype order by min(j.creationdate); 	0.106561157615665
18892733	5895	get the list ordered by how many times it appears in another table	select user.name, count(class.id) as count  from userbundle:user  as user join userbundle:class as class on class.attenduser = user.id group by user.id order by count desc 	0
18892818	35837	how to merge/combine 2 select statemenst based on a condition	select name, surname,identifier,        convert(varchar,(min(case when str_direction = 'entry' then transit_date end)),114) as [entry],        convert(varchar,(max(case when str_direction = 'exit'  then transit_date end)),114) as [exit],        convert(varchar(10),transit_date,103)as [date]     from [10.230.0.15].[scat].[dbo].[ha_transit] a    where str_direction in ('entry', 'exit')    and a.identifier = '20045619'    and str_transit_status = 'granted'    and transit_date between @completesdate and @completeedate    group by name, surname,identifier,convert(varchar(10),transit_date,103) 	0.000852721170745431
18893103	14644	mysql query joining three queries into sigle query	select  distinct c.id,          v.sel_category,         c.curr_tittle ,          c.curr_desc,          v.videos_desc  from    wp_curriculum c         inner join wp_curriculum_category cat             on c.id = cat.curr_id         inner join wp_career_vidoes v             on v.sel_category  = cat.curr_category where   cat.curr_category in (2,3) 	0.165292502785625
18893810	20197	mysql - one sql request instead two (both request include diffrent count(*)	select product,         count(*) as total_count        sum(          case when opinion='pos' then 1           else 0 end        ) as pos_count from the_table group by product; 	0.00581945315091378
18895796	14497	block user registration by country ip range	select `country_iso2` from `countryip` where `ip_from` <= inet_aton('$ip') and ip_to >= inet_aton('$ip') 	0.00400761852981439
18896202	3356	how do i get total count of result set to appear in every record of output?	select  col1, col2, col3, count(*) over () as total_rows from    mytable 	0
18896612	25712	sql condition on unioned tables	select *  from ( select * from a        union        select * from b ) temp  where condition 	0.150408881843476
18897960	1499	mysql joining data from a diffrent table	select `u`.`id`,concat(`first-name`," ",`last-name`) as `name`, group_concat(`g`.`group-name` separator ', ') as `groups`, concat('|',group_concat(`g`.`id` separator '|'),'|') as `groupids` from `application-users` as `u` join `groups` as `g` on (`g`.`assigned-users` like concat("%|",`u`.`id`,"|%")) where `u`.`status` = "active" && `u`.`type` = "business development"  group by `u`.`id` 	0.00161459427785834
18899731	25060	cast records to columns with grouping	select date,         sum(case when type = 'ticket' then amount else 0 end) as ticket,        sum(case when type = 'market' then amount else 0 end) as market,        sum(case when type = 'free' then amount else 0 end) as free from yourtable group by date 	0.00781773688909061
18899876	28291	selecting and compare one value with values in 2 columns of the db	select city from my_cities where zipcode between zipcode_start and zipcode_end 	0
18902066	5410	mysql query and compare values if multiple rows found	select balance, date from $registrar where date between '$starting_date' and '$ending_date' order by balance desc 	0.000569644059560495
18902163	23824	return null from xml explicit subquery where no rows exist	select distinct      p.[projectid],     p.[projectname],     case when (p.projectid = c.projectid) then      (   select *         from (                 select                     1 as tag,                     null as parent,                     null as 'codes!1',                     null as 'code!2!!element',                     null as 'code!2!split'                 union all                 select                     2 as tag,                     1 as parent,                     null,                                        c.[code],                     c.[split]                 from [codes] c                 where c.[projectid] = p.[projectid]              ) as [codexmldata]         for xml explicit     ) else null end as [codesxml] from [projects] p left join [codes] c on  c.[projectid] = p.[projectid] 	0.0187883588896805
18902375	39577	mysql - multiply column by value depending on that column	select      count(distinct(id)) as 'total # of opps',      avg(         case size             when 1 then 15             when 2 then 30             when 3 then 50             when 4 then 100             when 5 then 250         end     ) as 'averageestimatedcompanysize' from persontable as pojt inner join opportunity on pojt.id = opportunity.id where opportunity.timestamp >= '2012-01-01' and opportunity.timestamp <= '2012-12-31' and pojt.jobtitleid in      (select id     from job     where categoryid in          (select id         from job_category         where name in ('sc', 'ma', 'co', 'en', 'tr'))) 	0
18904061	13391	find entries of a column in a database in all entries of another table	select s.fname, s.lname from student s join enrolled_in e on s.sid = e.sid join course c on e.cid = c.cid join department d on c.did = d.did where d.name = 'comp' group by 1, 2 having count(*) = (     select count(*)     from course c     join department d on c.did = d.did     where d.name = 'comp') 	0
18908484	3733	oracle sql query with additional summation columns	select     user_id     sum(amount) total,     sum(least(amount,0)) total_negs,     sum(greatest(amount,0)) total_pos from     my_table group by     user_id 	0.544588684319624
18911431	3098	how to count total medal of sports	select      state,             sum(point) as medal,             sum(case when point = 7 then 1 else 0 end) as goldcount,             sum(case when point = 5 then 1 else 0 end) as silvercount,             sum(case when point = 4 then 1 else 0 end) as bronzecount from        [sheet2$] group by    state  order by    sum(point) desc 	0.00509146158425499
18911629	2770	how to sort multiple columns in mysql	select id,stars1, stars2 ,stars3 from(   select id,stars1, stars2 ,stars3, (stars1+stars2+stars3) as sum    from tblclient    group by id   order by sum desc) as sorted; 	0.00625175131096701
18911714	34018	sql query same column count?	select uniform, size, count(uniform) from thetable group by uniform, size 	0.0183571641903773
18912326	32125	filter mysql query by duplicates and row count	select     o.id        as iorderid,     o.code      as sordercode from     orders as o join     (select order_id, count(distinct pnr) as cnt      from order_air      where issued = 1        and change_status != 0        and issued_date between now() - interval 12 month and now()      group by order_id) oa_count on o.id = oa_count.order_id where oa_count.cnt >= 2    and o.status = 11 limit 20 	0.0227294382584279
18912767	20110	how to fetch data from table based on column value and group by its name	select t.*  from your_table t inner join  (   select name, min(visible) as minv   from your_table   group by name ) x on x.name = t.name and x.minv = t.visible 	0
18912807	10743	best practice for storing a neural network in a database	select id from nodes a, numericattributes b where a.attributename = $name   and b.value within $range   and a.id = b.id 	0.435646752420558
18914698	1620	sql left-join on 2 fields for mysql	select a.ip, a.os, a.hostname, a.port, a.protocol,        b.state from a left join b on a.ip = b.ip             and a.port = b.port 	0.0511345581466189
18915445	7503	how can i fetch last 30 days left joined with values from my own table?	select     d.date as date,     dayname(d.date) as weekday,     if(t.user_id is not null, 'true', 'false') as has_done_action from (     select subdate(curdate(), 1) as date union     select subdate(curdate(), 2) as date union     select subdate(curdate(), 3) as date union     select subdate(curdate(), 4) as date union     select subdate(curdate(), 5) as date union     select subdate(curdate(), 6) as date union     select subdate(curdate(), 7) as date     ) as d left join track_user_action t on t.date = d.date 	0
18915607	6571	how to get the last timestamp for a given date?	select some_columns from table_1 t1 join table_2 t2 on t1.column_name = t2.column_name where date(times_stamp) = :date order by times_stamp desc limit 1 	0
18916068	32762	counting the number of rows in sql server 2008	select sum(rows) from sys.partitions where object_id=object_id('my_table') and index_id in(0,1) 	0.000732740299707382
18916141	22947	how to get zeros for no values in sql	select      distinct identy,      count(clnt_ntnlty) over (partition by identy) counts from (         select 0 val, 'aboriginal' identy union         select 1 val, 'torres strait islander' identy union         select 2 val, 'both aboring & torres strait' identy union         select 3 val, 'neither aboring or torres strait' identy      ) x left join dbo.clientinfo t on t.clnt_ntnlty=x.val 	0.000805313780946412
18916996	32694	how to add a column with auto-incremented values to a table of mysql database?	select  a.col1,          a.col2,          (             select  count(*)             from    tablename c             where   c.col2 = a.col2 and                     c.col1 <= a.col1) as rownumber from    tablename a order   by a.col2, rownumber 	4.66856433377547e-05
18917871	12471	how to compare timestamp in where clause	select users.username, users.id, count(tahminler.tahmin)as tahmins_no  from users  left join tahminler on users.id = tahminler.user_id   where timestamp >= '2013-09-01' and timestamp < '2013-10-01' group by users.id  having count(tahminler.tahmin) > 0 	0.0516426535646952
18917934	12224	mysql count values from two tables	select     mac_address,     sum(logins_mac_count) as logins_mac_sum,     sum(visits_mac_count) as visits_mac_sum from (         select mac_address, count(*) as logins_mac_count, 0 as visits_mac_count         from logins         group by mac_address     union         select mac_address, 0 as logins_mac_count, count(*) as visits_mac_count         from visits         group by mac_address ) as t group by mac_address 	0.000362495327808587
18918478	13539	how to use union in mysql	select a, b from table1 union all select a, b from table2 	0.596137508583201
18918547	28436	group columns into one column	select b.bookingid, c.custname + ' ' + c.custemail + ' ' + c.custadd as cust from  booking b inner join customer c on b.custid = c.custid 	0.000351836474774932
18920337	40596	how to optimize query that has the same subquery twice?	select 'total_amount', sumtotal, case when sumtotal > 100000  then 'good' else 'not good' end  from dbo.businessunits bun  outer apply (select sum(total)  from dbo.invoices i where i.bu = bun.bu) ca(sumtotal) 	0.052285552084557
18920906	14311	sql query - two group bys on intermediate result in a query	select  item_id,         count(distinct shop_id),         count(distinct case when sold = 1 then shop_id end) from    my_query group by         item_id 	0.284858561533551
18922447	980	database table for items have same relation	select sku, name, make, model, year, concat(start_year, '-', end_year) years, quantity from car c join car_part cp on cp.car_id = c.id join part p on p.id = cp.part_id 	0.000173853425678938
18923015	10693	how to construct mysql query with bias with items that appear multiple times	select i.* from item i join (select categoryid, count(*) cat_count       from preference       where categoryid in (20081, 79)       group by categoryid) p on i.categoryid = p.categoryid order by cat_count*rand() desc 	0.010385467132758
18923240	23943	an sql statement	select username from tblusers order by date asc,score desc 	0.734808821466662
18923970	40145	sum rows of varchar datatype or time datatype in mysql	select  sec_to_time( sum( time_to_sec( `timespent` ) ) ) as timesum   from caltime 	0.00354863183633189
18924775	23744	check for multiple tables existence using single exists query?	select  1  from    systable st         inner join sysuserperm sup              on st.creator = sup.user_id where   sup.user_name = 'test' and          st.table_type = 'base' and          st.table_name in ('table1', 'table2') group   by sup.user_name, st.table_type having  count(distinct st.table_name) = 2 	0.00896509771596343
18925020	9124	divide by zero with sql	select p.patient_id, p.person_firstname, p.person_lastname     , h.height     , w.weight     , case         when  h.height != 0 then w.weight / (h.height * h.height)         else null      end as bmi from      view_billpatient p     left join h on p.patient_id = h.patient_id     left join w on p.patient_id = w.patient_id 	0.188785173169237
18925381	19189	mysql query to group results by date range?	select userid, groupnum, min(ping) as start_date, max(ping) as end_date, max(ping) - min(ping) as duration from ( select *, @groupnum := if(@prevuser != userid, @groupnum + 1, @groupnum), @groupnum := if(ping - @prevts > 60, @groupnum + 1, @groupnum) as groupnum, @prevuser := userid, @prevts := ping from table1 t , (select @groupnum:=1, @prevts:=null, @prevuser:=null) vars order by userid, ping ) sq group by userid, groupnum 	0.0118361549618631
18927093	32371	mysql - order by certain strings	select *  from player  order by find_in_set(position,'forward,midfielder,defender,goalkeeper') 	0.0104703333005966
18928780	14304	sql sum by group name with inner join present	select vapp.name          ,sum(memcpu.[mem_size_mb]/1000) as [mem_size_mb]          ,sum(memcpu.[num_vcpu]) as [num_vcpu]          ,sum(convert(bigint, hdd.capacity)) as capacity   from [vcenterserver].[dbo].[vpx_vm] as memcpu     inner join [vcenterserver].[dbo].[vpx_guest_disk] as hdd       on memcpu.id = hdd.vm_id     inner join [vcenterserver].[dbo].[vpxv_resource_pool] as vapp       on memcpu.resource_group_id = vapp.resourcepoolid   group by vapp.name; 	0.362788699140216
18930839	14008	how to select not-wellformed data	select * from your_table where your_column not regexp '^[0-9][a-za-z]{3,3}$' 	0.0681156334497834
18931754	28413	compare between two dates in sql query	select top 1 hotel_id, rate from roomtype r where '2013-11-09' between startseason and endseason or startseason is null and endseason is null order by case when startseason is null and endseason is null then 2 else 1 end 	0.00121190694485601
18934297	28388	query to fetch record without duplication	select distinct d1.name, d1.age, concat(d1.city, ' , ' ,d2.city) as city  from details d1 join details d2 on d1.name = d2.name and d1.age = d2.age and d1.city != d2.city and d1.id < d2.id 	0.00846934942977151
18936272	16193	mysql inner join on same table and pairs	select s1.col1, s2.col1  from table1 s1 inner join table1 s2    on s1.col2 = s2.col2 and s1.col1 <= s2.col1 	0.00901469253391827
18937301	19909	mysql select multiple rows using group concat and join	select p.* ,    u.username,    u.picture,    group_concat(t.tag separator ',') as tags from `posts` as p inner join `users` as u on u.blog_id = p.blog_id left join `tags_relation` as tr on p.id = tr.post_id left join `tags` as t on t.id = tr.tag_id where p.blog_id =1   and p.status = 'publish' group by p.id order by p.timestamp desc limit 0,10; 	0.121222963093801
18937539	21587	sql select entries in other table linked by foreign keys	select distinct p.id, p.username from players p inner join accounts a on (p.id = a.account_id)                inner join purchases pc on (a.id = pc.account_id) where (pc.price > 30); 	0
18938036	26962	return values from multiple rows as columns with group by on multiple colum	select   orderdate, [1], [2], [3], [4], companyid, typename  from test pivot (   max(quantity)   for quantitytypeid in ([1], [2], [3], [4]) ) as p 	0
18938605	6998	to select all from a table using one distinct value in sql server 2008	select * from table1 where [sl no] not in (select [sl no] from table2) union select * from table2 	0
18941643	23921	return string based on values within the string without truncating	select  * from    car where   right(carprofile, 4) =         (select max(right(carprofile, 4))          from car) 	4.87186662175896e-05
18941808	22943	add similar dynamic rows in sql query access 2007	select     tag     ,sum(qty)     ,sum(price_of_unit) from     table group by     tag 	0.618281856760841
18941852	6220	mysql, how to select only if exist	select id, option, value from options  where exists  (select option_id from products where products.category="watches" and products.option_id=options.id); 	0.0110377991495667
18942774	14461	how to select specific value from text column containing an xml string?	select convert(xml,my_col).value('(/rootelementname/@recommended)[1]', 'bit') rec from  my_table 	5.8665088757401e-05
18942906	5819	search with result priority based on different condtions	select id, name from     (          select id, name, 1 as searchrank from tables where (primary filter)          union           select id, name, 2 as searchrank from tables where (secondary filter)          union           select id, name, 3 as searchrank from tables where (tertiary filter)     ) results group by id, name order by min(searchrank) 	0.000967635047126685
18951071	24016	postgres return a default value when a column doesn't exist	select id, title, case when extra_exists then extra else 'default' end as extra from mytable cross join ( select exists (select 1  from information_schema.columns  where table_name='mytable' and column_name='extra') as extra_exists) extra 	0.00536217866341658
18951635	31653	mysql get latest 10 from each group	select * from (     select @row_num := if(@prev_value=m.thread_id,@row_num+1,1) as rownumber,             m.*,            @prev_value := m.thread_id     from messages m,          (select @row_num := 1) x,          (select @prev_value := 0) y     where thread_id in (1,2,3)     order by thread_id ) t1 where rownumber <= 10; 	0
18951810	29002	find the first record which caused sum to become 0	select min(sequence)   from ( select t1.sequence            from table_name t1            join table_name t2              on t2.category = t1.category             and t2.sequence <= t1.sequence           where t1.category = ...           group              by t1.sequence          having sum(t2.value) <= 0        ) ; 	0
18952105	31688	how to select rows which are repeated (opposite to distinct)?	select a_id from mytable group by a_id having count(a_id) > 1 	0.000340057472898948
18952144	36233	how to search a date in sql only in month	select *  from tablename where month(date_stamp)=2; 	0.000333819410989982
18955739	15816	mysql: ordering by two columns	select couponid, couponcode, dateadded, priority  from (    select couponid, couponcode, dateadded, priority     from coupon    where isfeatured=1     and isapproved=1     order by dateadded desc    limit 12 ) x order by priority desc 	0.0120217921263984
18956286	23460	mysql: get multiple data from other table matching the ids	select b.battle_id, b.user_id, b.competitor_id, u1.user_name as 'user_name', u2.user_name as 'competitor_name' from `battle` as b join `user` as u1 on u1.id = b.user_id join `user` as u2 on u2.id = b.competitor_id 	0
18956534	12107	sql stuck with data structure in a table	select      empl     , dt from      (          select             dt,             id1,             id2,             id3         from              data ) d unpivot (      empl for epl in ( id1, id2, id3 )  ) u order by      empl,      dt 	0.401210338244276
18956732	12871	create table merging two tables ms sql server	select sp.name,cb.col from table1 as cb join table2 as sp on cb.nale= sp.name 	0.00581969673263382
18957392	30101	query to get data in ascending interval format	select  col from (         select '1' col  from dual union all         select '10-20'  from dual union all         select '3-5'    from dual union all         select '5-3'    from dual union all         select '25-34'  from dual union all         select '20-25'  from dual union all         select '2'      from dual union all         select '4-8'    from dual ) order   by         to_number(regexp_substr(col, '\w+', 1, 1)) ,       to_number(regexp_substr(col, '\w+', 1, 2)) 1 2 3-5 4-8 5-3 10-20 20-25 25-34 	0.00120739643431632
18957662	1375	mysql selecting data from different tables and doing the average	select    avg(q7),   avg(q8)  from   (select      q7,     q8    from     day1    where day1.user = 'test'    union   select      q7,     q8    from     day2    where day2.user = 'test') 	0
18957762	7952	multiple selects into one select	select distinct   userid , ( select count(*) as counttoday from hitstable h2     where h2.userid = h1.userid        and convert(date,hitdate) = convert(date,getdate())   ) as counttoday , ( select count(*) as countlatweek from hitstable h2     where h2.userid = h1.userid        and hitdate between dateadd(dd, -(datepart(dw, getdate())-1)-7, getdate())                       and dateadd(dd, 7-(datepart(dw, getdate()))-7, getdate())    ) as countlastweek from hitstable h1 	0.00717120864030621
18958046	8370	how to group in a sequence <db2>	select min(from_id), to_id, to_id - min(from_id) +1 as quantity, amount from ( select from_id, max(to_id) as to_id, amount from ( select t1.id as from_id, t2.id as to_id, t1.amount from       foo t1 inner join foo t2 on t1.amount = t2.amount and t2.id >= t1.id where not exists     (     select * from foo t3     where  t3.id > t1.id     and t3.id < t2.id     and t3.amount != t1.amount     )   and exists     (     select * from foo t3     where ((t3.id = t1.id            and t3.id = t2.id)       or (t3.id = t1.id +1 and           t3.id = t2.id))     and t3.amount = t1.amount     ) ) x group by from_id, amount ) y group by to_id, amount ; 	0.127076848015491
18959724	20657	sqlite select query - group concat column based on another column's value	select oute.candidate_id,          oute.first_name || ' ' || oute.last_name as 'name',         (             select group_concat(inne.score)              from scores inne             where inne.candidate_id = oute.candidate_id                 and inne.category_id = 1              order by inne.judge_id         ) as score_list from scores oute      join candidates          on candidates.id = oute.candidate_id 	0
18959759	7534	multiple left join if item has many (dynamic) attributes	select      *  from      `products` where      `products`.`status` = 1      and `products`.`sold` = 0      and `products`.`deleted` = 0      and `products`.`categories_id` = 30     and      (         (select               count(*)           from `pattributes`          where               `pattributes`.`products_id` = `products`.`id`              and               (                  (                    `pattributes`.`attributes_id` = 4                    and `pattributes`.`values_id` = 14                  )                  or                  (                    `pattributes`.`attributes_id` = 5                    and `pattributes`.`values_id` = 10                  )              )          ) = 2     ) group by `products`.`id` order by `products`.`top` desc, `products`.`id` desc 	0.042202433286372
18960121	6603	sql order by first, then next	select studentname from table1 order by isedited, ismanuallyadded, studentname 	0.00126408562217651
18961311	26266	join returns multiple results	select memberid, count(*)    from table   group by memberid  having count(*) > 1 	0.453912735710728
18961564	11378	sql use cte and pivot to make calender of months	select a1, sum( case when datepart(dw, a) = 1 then 1 else 0 end ) as sunday , sum( case when datepart(dw, a) = 2 then 1 else 0 end ) as monday from cte where cte.b2 = '12'  and datepart(m, a) = datepart(m, dateadd(m, -1, getdate())) option (maxrecursion 0) group by a1 	0.67218832890059
18961665	5588	using distinct on joined table	select       sum(amount)  from       loften where      loanid in (          select loanid from loan_approvals      ) 	0.0119599164142246
18962097	32419	how to run a query for each row from a table?	select * from table when advertiser_name in   (select distinct name    from tbladvertiser    inner join tblavertiserbrand on advertiserid=id) 	0
18963203	32104	grouping by titles that are the same with the same (and then different) composers	select title, count(*)  from piece group by title  having count(*) > 1  minus select title, count(*) from piece p2  join composer  c2 on p2.cno = c2.cno  group by title, c2.cno having count(*) > 1 	0
18964709	2142	how to find difference between two mysql tables using mysql statement?	select *   from mytablea  where imageurl not in (select imageurl from mytableb) 	0.000704343682635852
18966494	27025	sql select based off multiple values	select     link from       table group by   link having     sum(case when code = 'c' then 1 else 0 end) = 0 	0.000789883994708992
18967863	30609	how to know the stored procedure parameters in php?	select p.name from   sys.objects o inner join sys.parameters p on  p.[object_id] = o.[object_id] where o.[name] = 'stored_proc_name' and o.[type] = 'p' 	0.58245528051571
18970766	1624	pulling the following information with a single select	select page_id, count(*), date  from table_name  group by page_id, date 	0.0043101941675982
18972947	41000	join two queries together with default values of 0 if empty in access	select original_staff_data.*, transaction_data_by_staff.total_rev, transaction_data_by_staff.total_profit from transaction_data_by_staff right join original_staff_data on (transaction_data_by_staff.year = original_staff_data.year) and (transaction_data_by_staff.month = original_staff_data.month) and (((transaction_data_by_staff.[staff_uid])=[original_staff_data].[staff_uid])); 	0.0167995798358516
18974198	14245	how to use sub query in where condition of another query?	select address, state from table1  inner join table2 on table1.id=table2.id  where concat_ws(',',name,age) = '$result' 	0.358098574796907
18975566	22758	sql distinct values between different queries	select distinct  people.id from people inner join incident i1 on people.id = i1.peopleid  where  i1.service in(4,5,6) and people.id not in ( select  i2.peopleid from incident i2 where  i2.service = i1.service and i2.serviceinterrupt != 0 ) 	0.00221854847069031
18975787	17500	how to get count of distinct rows in mysql?	select tblclass.classname, count(tblattendance.id) as counter  from tblclass,tblattendance  where tblclass.classcode=tblattendance.classcode and tblattendance.attdate='2013-07-01' group by tblclass.classname 	0.000154542313471797
18975841	28562	sql select with 'in' casting from string to tinyint	select * from mytable where charindex(cast(mycol as varchar), @myvar) > 0 	0.0788871247120718
18975940	30746	selecting the highest id number in an sql stored proc	select replace(c_invoice,char(13) + char(10), ''), c_uom1, c_uom2      from @invoice_table as invoice     inner join @uom1_table as uom1 on invoice.id = uom1.id     inner join @uom2_table as uom2 on uom1.id = uom2.id     where uom1.id = (select max(id) from @uom1_table) 	0.000123400152500681
18976397	31048	sql query to select row in db who's publish time and end time should not overlap	select question_id from questions where '".$publish_date."' between publish_date and end_date and '".$publish_time." between publish_time and end_time 	0.011359124256879
18976417	12097	group by : to get the column value	select min(item), booking from your table group by booking having count(distinct item) > 1; 	0.000477205946489729
18976576	18558	getting two completely different columns in one query	select sum(case when atlinestat = 1 then 1 else 0 end) 'oas',        sum(case when atlinestat = 2 then 1 else 0 end) 'ofs'  from atmterminalfile (nolock)  where atstatu='2'  and atlinestat in (1,2) 	0.000133654938395027
18977649	16697	sql - summarise single column in result set	select distinct bbl.bill_num,         bb.tran_type,         hm.clnt_matt_code,         bb.tran_date,         bb.period,         sum(cd.billed_amt) as [disb billed],         fees_amt   from blt_bill_amt bb   join hbm_matter hm on bb.matter_uno = hm.matter_uno   join blt_billm bbm on bbm.billm_uno = bb.billm_uno   join blt_bill bbl on bbl.tran_uno = bbm.bill_tran_uno   left outer join cdt_disb cd on cd.bill_tran_uno = bbl.tran_uno  where bb.tran_type in ('wo', 'wox')    and bb.period = '201401'   and bbl.bill_num = 231728 group by bbl.bill_num,         bb.tran_type,         hm.clnt_matt_code,         bb.tran_date,         bb.period,        fees_amt order by  bb.tran_type, bbl.bill_num 	0.0137066912383007
18978214	23261	concatenate field data with previous and next rows	select  isnull(( select stuff((select   isnull(tblbefore.word, '') + ' '                                from     tbl tblbefore                                where    tblbefore.id between t.id - @before and t.id                                         - 1                         for   xml path('') ,                                   type).value('.', 'varchar(max)'), 1, 0, '') as childvalues                ), '') + t.word + ' '         + isnull(( select   stuff((select   isnull(tblbefore.word, '') + ' '                                    from     tbl tblbefore                                    where    tblbefore.id between t.id + 1 and t.id                                             + @after                             for   xml path('') ,                                       type).value('.', 'varchar(max)'), 1, 0,                                   '') as childvalues                  ), '') from  tbl t 	0
18981027	7337	plsql return table set	select r.pid    from reports r, persons p    where r.report_type = 'f' and r.pid = p.pid    and p.cur_status = 'f'    and p.pid = 100; 	0.0370121829134055
18981362	35322	sql cant include column table after sum column table in select syntax	select form_no, sum(qty) as qty from seiapps_qty where form_no = '1' and status_qty='ok' group by form_no 	0.073409876450048
18983266	26225	manipulating attribute values in mysql table	select     case          when vala = 0 and valb = 0 then 'a'         when vala = 0 and valb = 1 then 'b'         when vala = 1 and valb = 0 then 'c'         when vala = 1 and valb = 1 then 'd'         end as result from      table 	0.00384459862884261
18983561	12171	adding year and month to a group by sql query	select year(yourdatecolumn) as 'year', month(yourdatecolumn) as 'month', c.name, count(distinct d.id)   from driverlic d      inner join clov c with (nolock) on d.cid = c.cid  group by      year(yourdatecolumn), month(yourdatecolumn), c.name 	0.00145063006382909
18983636	17476	select statement to always return 3 rows on execution	select t.color,coalesce(sum(clrcount),0) colorcount from tmp  right join           (values('red'),('amber'),('green')) as t(color)      on tmp.color = t.color group by t.color 	0.0689134990418153
18984229	39735	group by and order by in mysql	select a.*, b.cost as future_cost, b.start_date as future_date from (select * from (select * from testdata order by start_date) x group by pattern) a left join (select * from testdata order by start_date) b     on a.pattern = b.pattern and a.id != b.id group by a.pattern 	0.335675409785634
18984702	35640	mysql data must exist in two columns to be returned	select p.id from products p join cats_selected s on s.product_id = p.id where s.cat_id in (16372, 9) group by p.id having count(distinct s.cat_id) = 2 	0.0042852274421712
18986774	33522	sql left join across two columns with filter	select    id, food, side, value,   case when     side.side = people.side      then 1     else 0   end as match_flag from   tbl_people as people left join   tbl_sides as sides on people.food = sides.food 	0.0745346129602337
18990867	19374	find rows with same value of a column	select t1.what from table t1 join table t2 on t1.why = t2.why and t1.what != t2.what 	0
18992119	28553	getting an average of the entire table when using group by	select departmentid from workers group by departmentid having min(salary) > (select avg(salary)                       from workers) 	0.00017960928291068
18992252	17726	returning a set of the most recent rows from a table	select * from (     select *, rnum = row_number() over (       partition by #tmp.foreignkeyid       order by #tmp.startdate desc)     from #tmp ) t where t.rnum = 1 	0
18996186	29723	select newest topic for each subject in sql server 2008	select s.idsub, s.titlesub, a.numtopic, isnull(b.newesttop, '') as [newest topic],    isnull(b.iduser, '') from subject s    inner join (select idsub, count(*) as numtopic from topic group by idsub) a      on s.idsub = a.idsub   left join (     select t.idsub, t.titletop as newesttop, t.iduser as [iduser]      from topic t        inner join (         select idsub, max([time]) as tm from topic group by idsub       ) x on t.idsub = x.idsub     where t.[time] = x.tm   ) b on s.idsub = b.idsub 	0.00119769042506372
18996705	24822	listing parent and child values together	select * from table order by  nvl(parent_menu_id,menu_id),menu_id; 	0.00134317103755866
18997471	9089	retrieve data from database with column name "name_en-gb"	select * from table where `name_en-gb` = 'name'; 	0.00016629061084289
18997523	5400	rows to customized xml	select (        select t.name as [@name],               t.type as [@type],               t.value as [*]        from (values               ('employeeid', 'int',    cast(e.employeeid as varchar(10))),               ('firstname',  'string', e.firstname),               ('lastname',   'string', e.lastname),               ('title',      'string', e.title),               ('deptid',     'int',    cast(e.deptid as varchar(10)))             ) as t(name, type, value)        for xml path('item'), root('root'), type        )  from myemployees as e 	0.0362196914749044
18997961	4713	how to get count of this query - select count (*) from (select accountid, * from account) as countrecord	select count(*) as countrecord from account 	0.00018730203281067
18998198	28015	sql query to get id from multiple inputs	select t1.id from table t1 inner join table t2 on t1.id = t2.id where   t1.inputid = 1 and t1.value = @input1 and   t2.inputid = 2 and t2.value = @input2 	0.000623247527820211
18998389	20732	how to set order clause	select datename(month,liftingdate) as [month],sum(liftingbirds)[liftingbirds],    round(sum(totalweight),0)[tot.weight],    round(sum(totalamount),0)[tot.amount],    round(sum(totalweight)/sum(liftingbirds),2)[avg.weight],    round(sum(totalamount)/sum(totalweight),2)[avg.rate]    from k_liftingentryrecords where    (liftingdate between '2013-04-01 00:00.000' and getdate())    group by datename(month,liftingdate) ,month(liftingdate)     order by month(liftingdate) 	0.461046491571118
19002052	11433	filter not working on a join between three tables	select  inmuebles.title     ,   inmuebles.descripcioni     ,   inmuebles.id     ,   inmuebles.precioventa     ,   inmuebles.imagen     ,   min(x.propertyid) as propertyid  from inmuebles left join (select anonymouscart.propertyid            from anonymouscart join temppropertylist              on anonymouscart.temppropertylist_id = temppropertylist.id            and temppropertylist.sessionid = 'uuoawmav4jhi3hy3g3v4vr3o'            ) x on inmuebles.id = x.propertyid where tipodemanda = 'venta' and onhold = 0 group by         inmuebles.title     ,   inmuebles.descripcioni     ,   inmuebles.id     ,   inmuebles.precioventa     ,   inmuebles.imagen 	0.436783224340453
19002204	30201	sql: want to alter the conditions on a join depending on values in table	select  bt.name ,       coalesce(eav1.value, eav2.value) as value1orvalue2 from    basetable bt left join eavtable eav1 on      eav1.id = bt.id         and eav1.type = 1 left join eavtable eav2 on      eav2.id = bt.id         and eav2.type = 2 	0.00016260136058706
19002341	25240	sql server: group by a column and get the first group	select top 100 * from scheduledsms where groupid = (select top 1 groupid from scheduledsms order by dateadded) 	0.000567587711216547
19003215	10412	how to see list of tables and list of trigger(and sequences)?	select table_name,        trigger_name as object_name,        'trigger' object_type  from all_triggers 	0.000122309435499996
19003517	23111	select randomly and sort the records	select id,name,level from sample order by level desc,newid() 	0.000493177505075386
19003609	29824	partially distinct select	select distinct on(utm)     utm, tracking_id, column1, column2, ... from t order by utm, tracking_id 	0.0536883195571433
19004752	5700	sql query to show count of same results	select score,count(score) as cnt  from responsedata where scoreguid='baf5dd3e-949c-4255-ad48-fd8f2485399f' group by score 	0.00166276079344769
19006238	25169	mysql order by sum of subqueries	select *,  (select count(id) > 0 from places_users where places_id = places.id) as verified_bool, (select count(id) > 0 from places_services where places_id = places.id) as services_bool from places order by (verified_bool + services_bool) desc  limit 0, 10 	0.302846679497386
19006368	19304	joining rows with columns mysql	select u.email, concat_ws(',', group_concat( s.name),                  group_concat( s.value)) as allvalues from `user` u inner join `settings` s on u.id = s.usrid group by email limit 0 , 30 	0.00431403444143747
19007924	23659	how get rows and get count rows for each unique param in one sql?	select  name, count(name) as records  from    hist_answer where   id_city='$id_city'      and id_firm='$id_firm'      and id_service='$id_service' group by name 	0
19007935	24234	selecting * from max id when grouping by parentid (mysql)	select t1.* from atable t1, (select parentid, max(id) as id  from atable group by parentid) t2 where t1.id = t2.id and t1.parentid = t2.parentid 	0.000258704403737416
19009476	25786	converting a pivot table to flat table in oracle sql	select t.employee_id, t.employee_name, c.data, decode (c.data, 'address', t.address_old, 'income', t.income_old) as old, decode (c.data, 'address', t.address_new, 'income', t.income_new) as new from test_table t cross join (   select 'address' as data   from dual   union all   select 'income'   from dual  ) c 	0.308537428604408
19009913	8164	how to select all columns for rows where i check if just 1 or 2 columns contain duplicate values	select *  from yourtable a where exists(select 1               from yourtable              where col1 = a.col1              group by col1              having count(*) > 1) 	0
19010382	8502	mysql convert string to date calculate age and order by age	select  extract(year from (from_days(datediff(now(),str_to_date(birthday, '%m/%d/%y'))))) + 0 age,         count(*) totalcount from    tablename group   by extract(year from (from_days(datediff(now(),str_to_date(birthday, '%m/%d/%y'))))) + 0 order   by totalcount desc 	0.000121486649718151
19010701	3558	use union result rows in subselect	select city, sum(id_employe is not null) as num from (   select city_empl as city, id_employe   from employers   union all   select city_dpt as city, null as id_employe   from departaments ) as intbl group by city 	0.448002399190051
19011320	37354	how to tell what computer a query came from in a trigger	select      host_name()  modifiedbyhost,      system_user  modifiedbyuser,     app_name()  modifiedbyappname 	0.657766840582938
19011918	22638	an oracle select with time	select * from recent_activity where systimestamp-lastactivity < interval '5' second; 	0.267374961749886
19013623	15145	how to return the number of records in a join for a given month?	select t.topic_id as topicid, p.date as date, sum(t.weight)/s.month_ct as value from posts p join theta t   on t.post_id = p.id join (select year(date) as yr, month(date) as mnth, count(id) as month_ct         from posts         group by year(date), month(date)        )s   on    year(p.date) = s.yr     and month(p.date) = s.mnth group by year(p.date), month(p.date), topicid; 	0
19014973	12916	count by column name	select store, count(*) as transt from table where date = '9/01/13'  group by store 	0.0192898666675741
19017865	6822	show data that are linked to each other in seperate tables	select catcolours.id, cats.cat_name, catcolours.colour from catcolours inner join cats on catcolours.id = cats.id 	0
19018955	12409	need to return last purchase date for items that have not been purchased for more than 180 days	select     inventory.localsku,      inventorysuppliers.suppliersku,      max([order details].detaildate) from                 inventory inner join     inventorysuppliers on inventory.localsku = inventorysuppliers.localsku      inner join     [order details] on inventorysuppliers.localsku = [order details].sku      cross join     pohistory where          getdate() >= convert(date,dateadd(day,180,[order details].detaildate))     group by             inventory.localsku,              inventorysuppliers.suppliersku,  order  by     max([order details].detaildate) desc 	0
19019453	26880	mysql transpose row into column and column into row	select month,        max(case when unit = 'cs-1' then value end) `cs-1`,        max(case when unit = 'cs-2' then value end) `cs-2`,        max(case when unit = 'cs-3' then value end) `cs-3`   from (   select unit, month,          case month              when 'jan' then jan             when 'feb' then feb             when 'mar' then mar             when 'apr' then apr             when 'may' then may             when 'jun' then jun          end value     from table1 t cross join   (     select 'jan' month union all     select 'feb' union all     select 'mar' union all     select 'apr' union all     select 'may' union all     select 'jun'   ) c ) q  group by month  order by field(month, 'jan', 'feb', 'mar', 'apr', 'may', 'jun') 	0
19020805	12898	php mysql query for fetching datas from 2 tables	select users.*,games.game_names,games.id as games_id from users  left join games on find_in_set(games.id,users.games) 	0.00205188135744164
19021562	8312	regexp_substr return full string in case comma delimiter is part of the string	select regexp_substr('141001,update prdtbl set a10=''141001'' where a03=''62'' and fix_flt=''1'' and substr(txn_id,1,2)=''ln'' and a05=''n'',62,1,ln,,,,n,fxl business (m),fixed loans - others,,dba,2013-09-25,dba,2013-09-25',  '([^,\(]*(\([^\)]*\)[^,\(]*)*)(,|$)', 1,2, 'i', 1) from dual; 	0.00951182385784786
19023933	29980	priority address list when retrieving companies	select * from companies c join company_addresses ca on ca.company_id = c.id where c.name = 'fake company' and ((ca.main is true) or (ca.main is false and ca.name = 'main')) 	0.0034325604046941
19024222	13675	how to try and display users that do no have entries for latest week in database	select t1.eventdate, t1.userid, t1.activity from yourtable t1 where t1.eventdate = '2013-09-16' union select t1.eventdate, t1.userid, 'no update yet' as activity from yourtable t1 where t1.userid not in (select userid from yourtable where eventdate = '2013-09-16')     and t1.eventdate =          (select top 1 t3.eventdate from yourtable as t3 where t3.userid = t1.userid) group by t1.userid, t1.eventdate order by eventdate desc 	0
19024764	16678	returning duplicated values only once from a join query	select distinct ll.id_no as person_id_number,     lly.job as person_job from dbo.employeeinfo as ll left outer join      employeejob as lly on ll.id_no = lly.id_no where lly.job_category = 'cle' 	0.000201340599306294
19025118	35525	how to retrieve all child elements for all parent elements from xml in sql	select a.b.value('(../parent-name)[1]','varchar(50)') as parent   , a.b.value('(.)[1]' ,'varchar(50)') as child from @myxml.nodes('people/parent/child')a(b) 	0
19025598	7255	array contains null value	select nr, case d when '20990101' then null else d end d from (     select nr,     case max(isnull(enddate, '20990101') d     from mytable     group by nr ) 	0.0133711584503862
19027436	33932	how do i aggregate over ordered subsets of rows in sql?	select x, z, min(y), max(y) from (   select b.* , sum(switch) over (order by rn) as grp_new    from(     select a.* ,             case when grp = (lag(grp) over (order by rn))            then 0             else 1 end as switch     from          (select x,y,z,                  dense_rank() over (order by x, z) as grp,                 row_number() over (order by x, y, z) rn          from t     )a   )b )c group by x, z, grp_new order by grp_new 	0.00669010313948503
19028157	28704	possible to check if a particulor field exist or not in select query	select c.uid,c.cust_id,c.cust_name,a.phone  from customer c     left join address a on c.uid = a.uid 	0.241206390246605
19029522	35087	sql select with join also records with no correspondence on second table	select     users.id,     users.email,     users.active,     users.last_alert,     data.active,     data.active_from from users     left join data on (         data.id_user = users.id and data.active = 1     ) order by users.id asc 	9.11965086583796e-05
19029798	649	sql server joining 3 tables	select tblclientinfo.acctnum,         tblclientinfo.fname,         tblclientinfo.fname,         tblreservation.unitnum,         tblbillingsched.billnum,         tblbillingsched.duedate,         tblbillingsched.monthlyamort,         tblbillingsched.totalbalance  from   tblclientinfo         join tblreservation           on tblclientinfo.acctnum = tblreservation.accountnum         join tblbillingsched           on tblclientinfo.acctnum = tblbillingsched.accountnum  where  tblbillingsched.accountnum = 'c0000000021'         and tblbillingsched.duedate between '1/1/2014' and '1/30/2014' 	0.100471932313143
19030499	15973	select mysql field depends on other field value	select case currency.name when 'usd' then currency_date.usd when 'eur' then currency_date.eur end as cur_val from cost left join currency on currency.id = cost.id_currency left join currency_date on currency_date.id = cost.id_currency_date where cost.id = 1 	5.15555196629557e-05
19031191	13324	filtered sum in oracle	select trunc(data_dt),sum(bqwp) from tasks  group by trunc(data_dt) 	0.270512067744278
19031196	12120	how to search in sqlite by date?	select current_date from mydatabase where current_date like '2013-09-25%' 	0.077495623708999
19031780	31997	how to retrieve sql server check constraint dependency columns	select cu.* from information_schema.constraint_column_usage cu inner join information_schema.check_constraints c on c.constraint_name=cu.constraint_name where c.constraint_name='ck2' 	0.000444744262381053
19032610	29276	how to get name from another table when using a key in select?	select a.name, a.regionid, b.name from countries a    join regions b        on b.id = a.regionid order by a.name asc 	0
19032793	10879	split row_number() over partition over multiple columns	select    product,    price as price1,    min(price)    over (partition by product          order by price desc          rows between 1 following and 1 following) as price2,    min(price)    over (partition by product          order by price desc          rows between 2 following and 2 following) as price3 from tab qualify     row_number()     over (partition by product          order by price desc) = 1 	0.135522885166316
19034871	35924	mysql select. only selecting rows where entity != multiple values	select contact_id  from contact_tags  where contact_id not in (     select contact_id from contact_tags where tag_id in (1,2) ) tmp 	0.00025044479463178
19034994	21648	how do i add a 0 to null values from sql server?	select right('000000000'+convert(varchar(9), number), 9) 	0.0041183339642747
19035081	8554	teradata sql pivot multiple occurrences into additional columns	select id,     max(case when seq =1 then result end) result1,     max(case when seq =2 then result end) result2,     max(case when seq =3 then result end) result3 from (     select id, res, row_number() over(partition by id order by result) seq     from yourtable ) d group by id order by id; 	0.00641245667288616
19035157	39825	selecting triple unique(or distinct) value from mysql	select max(date), pardavejas, model_id from kainosn group by pardavejas, model_id 	0.0043869890387043
19035291	2549	sql previous week total	select sum(total_cost)as "total"     from purchases `datetime ` >= date_sub(now(),interval 14 day)  and `datetime ` < date_sub(now(),interval 7 day) 	7.74515125459731e-05
19035904	23728	how to remove special charectors in a table dynamically	select replace( replace( replace( replace( @str, '!', '' ), '#', '' ), '$', '' ), '&', '' ); 	0.0384076407172679
19036367	39884	how to compare a table with itself under a condition in mysql	select t1.company, t2.company, t1.price  from sells t1  join sells t2 where  t1.company != t2.company and t1.price = t2.price group by t1.company, t1.price; 	0.0033892759411149
19036507	13135	how to get max matched output	select userid  from tab where contentid in (      select contentid from tab      where userid= 31    )    and userid <> 31 group by userid order by count(*) desc; 	0.00440600767197215
19037199	3199	using year and sum case when	select   tng_mda_typ_cd,   sum2010 = sum(case when datepart(year, rec_eff_stt_dt) = 2010 then len_hrs_st else 0 end),  sum2011 = sum(case when datepart(year, rec_eff_stt_dt) = 2011 then len_hrs_st else 0 end),  sum2012 = sum(case when datepart(year, rec_eff_stt_dt) = 2012 then len_hrs_st else 0 end) from  dbo.col_tbl_vcourse_new group by tng_mda_typ_cd 	0.262789142669293
19039025	10979	i have three tables in a many to many relationship want to get results as raw data boolean	select users.id, roles.id,      case when usersroles.roles_id is null then 0 else 1 end as has_the_role from users inner join roles left join usersroles on users.id = usersroles.users_id and roles.id = usersroles.roles_id 	0.000432702343888516
19039169	4238	sql server 2008 pivot query - replace output based on if there is a record and value from other field	select    serial_id,    isnull(test_1, 'inc') test_1,    isnull(test_2, 'inc') test_2,   isnull(test_3, 'inc') test_3,   isnull(test_4, 'inc') test_4,   isnull(test_5, 'inc') test_5,   isnull(test_6, 'inc') test_6 from (   select     serial_id,     isnull(fail_code, test_result) fail_code,      test_area   from (     select       f1.serial_id,       f1.fail_code,       f1.test_area,       f1.test_result,       row_number() over (         partition by            f1.serial_id,           f1.test_area         order by            f1.test_date desc       ) seq     from        dbo_tbl_dm_test_results_flex f1     where       f1.test_date > '2013-07-01'      ) d   where      seq = 1 and      test_result in ('fail', 'pass')    ) d pivot (     max(fail_code)     for test_area in (test_1, test_2, test_3, test_4, test_5, test_6) ) piv; 	5.13107895918259e-05
19040345	8406	how to exclude something from this mssql/php query?	select top 100      idnum,      idname,      nation,      (select          sum(loyalty)      from          userdata      where          userdata.knights = knights.idnum          and userdata.authority in(1, 2)     ) as clanloyalty  from      knights  where     knights.idnum not in (21,22) order by      clanloyalty desc 	0.303660253810016
19040685	17044	how do i cast a string value formatted like "$400,000.88" to a decimal	select cast(cast('$400,000.88' as money) as decimal(10,2)) 	0.0253635853045509
19042475	32035	sql - retrieve field from sub-query	select  a.party_id, a.party_name, a.status         ,a.object_version_number, a.party_number, c.last_update_date from    hz_parties a join hz_cust_accounts b                         on b.customer_type = 'r'                            and a.party_id = b.party_id                      join ra_customer_trx_all c                         on b.cust_account_id = c.bill_to_customer_id                           and c.last_update_date < sysdate-100 where   a.party_type = 'organization' and     a.status = 'a' and a.party_id = 4402 and     a.created_by_module in ('hz_cpui','tca_v1_api','tca_form_wrapper') 	0.00502367714567116
19042926	34709	is it possible create a sql view from "horizontal" to "vertical"	select period, value, category from     (select vendorid, charcge,nocharge    from table) p unpivot    (value for category in        (charge,nocharge) )as unpvt; 	0.0622263467551573
19043086	13021	how to identify a column with name exist in all tables?	select table_name    from information_schema.columns  where table_schema = schema()    and column_name = 'name'  	0.000279582694935019
19043399	9984	sql server select a.*, count(b) group by	select a.*, x.number from tablea a inner join    (select b.a_id, count(b.number) number    from tableb b    group by b.a_id) x on x.a_id = a.id 	0.619382286818467
19043737	34249	order data within group by that has 2 different columns in mysql	select   * from     tbl_notification natural join (            select   notification_topic,                     notification_user_id,                     max(notification_date) as notification_date,                     count(*)               as topic_count            from     tbl_notification            where    notification_user_id = 2            group by notification_topic,                     notification_user_id          ) as t order by notification_date desc  limit    8 	5.63019047178687e-05
19045175	8293	select value against minimum value in group by	select q1.*,q2.ucode from (yourquery) q1 left join adsalarypreparationdtl q2 on q1.ac=q2.ac and q1.bn=q2.bn and q1.minlvl=q2.lvl 	0.000657102595169456
19046470	5313	order number which dosnt exists in other table	select contract_number from contract_table minus select distinct contract_number from order_table 	0.0011837455009712
19048551	10070	group values and get percentage from database	select user_result_bet.match_id,count(*) as 'qty', count(if(`home_score` > `away_score`,1,null))/count(*)*100 as home_percent, count(if(`home_score` < `away_score`,1,null))/count(*)*100 as away_percent, count(if(`home_score` = `away_score`,1,null))/count(*)*100 as draw_percent from wherever group by 1 	0.00016016458792773
19051544	14285	sum of date time difference in a mysql query	select, min(starttime), max(stoptime),  sum(time_to_sec(time_diff(stoptime - starttime))/3600) total_hours from mytable 	0.00151586167440739
19051569	14733	how to check whether an element is present in the database table or not?	select distinct 1 from product_meta where categorie_heading="material"; 	0.000413818613752431
19053074	32582	mysql fetch 10 randomly rows where 3 predefined rows needs to be part of the results and be at the beginning	select   id   from   (     select       id,       if(id in (5,6,7),1,0) as priority       from tablename   ) t   order by priority desc, rand()   limit 10 	0
19053340	29151	sql join, replace id with value	select tickets.numint, tickets.type, tickets.title, tickets.description,        tickets.priority, tickets.status, tickets.date,        users.name as user_name, companies.name as company_name, case when tickets.assignation=0 then 'not-assigned' else users1.name end as assignation from tickets left join users on tickets.user_id = users.numint left join companies on users.company_id = companies.numint left join users as users1 on tickets.assignation = users1.numint 	0.0601349735363867
19053863	528	subquery returns more than one row even with max function	select memberfk as lmfk, contractnr, contractbegin as lc, contractend as lce from contracts as v  where  maincontract=1 and description not like '%mitarbeiter%' and description not like '%kind%' and description not like '%teen%' and description not like '%kid%' and contractnr =  (select top 1 max(v1.contractnr) from contracts as v1 where  (v1.description like '%gold%' or v1.description like '%silber%' or v1.description like '%bronze%' or v1.description like '%executive%' ) and v1.contractend>v1.contractbegin  and v1.memberfk =v.memberfk) 	0.0710814459590402
19054038	28977	mysql query with count and join column from another table	select v.*, count(t.verdict_id) as cnt from  (       select month, id as verdict_id        from            (select distinct month from table1 where (month = 201307)) m ,            verdicttable ) v left outer join table1 t on v.verdict_id = t.verdict_id and v.month = t.month group by v.verdict_id, v.month 	0.00203496688587226
19054846	32818	oracle sql addition of columns using dates	select trunc(bill_date),         sum(amount) from bill group by trunc(bill_date); 	0.0145256604350723
19055158	31497	how to retrieve sum of 5 top score from a table in mysql	select team_id as  `team` , (   select sum( score )    from  `table`    where team_id =  `team`    order by score desc    limit 5 ) as  `score`  from  `table`  group by team_id order by  `score`  desc 	0
19055751	20077	include referenced rows without referencing rows	select derp.* from derp  left join herp on herp.id=derp.id where derp.approved!=2 or (derp.member='462' or herp.approver='32523') order by member,startdate 	0.00282837661497424
19055788	27685	mysql query through many layers of one to many relationships	select c.* from     institution i     inner join department d on d.institutionid = i.institutionid     inner join forums f on f.departmentid = d.departmentid     inner join `user` u on u.forumid = f.forumid     inner join post p on p.userid = u.userid     inner join comment c on c.postid = p.postid where     i.institutionid = 42 	0.00897159574748693
19058168	18933	mysql - given multiple associations, how to get latest association for several records?	select p.page_id, p.page_key, pv.page_version, pv.page_title, pv.page_content  from page_versions pv inner join (select page_id, max(page_version) as page_version     from page_versions group by page_id) as max_page_versions    using (page_id, page_version) inner join pages p using (page_id); 	0
19060339	30091	how to query group by 2 condition?	select agebrackets.age as age, sum(gload1) as gload1, sum(gload2) as gload2, sum(gload4) as gload from  (select '15-20' as age, 15 as stdt, 20 as eddt union select '21-25', 21, 25 union select '26-30', 26, 30) as agebrackets join member on member.age between agebrackets.stdt and agebrackets.eddt group by age order by age; 	0.100587147217042
19060368	24618	get the greatest number of the products	select product, count(product) from yourtable group by product order by count(product) desc limit 10; 	0
19060734	35973	how to update exactly one record and select updated row in a single db2 query	select column3 from final table (      update mytable      set    column1 = 'r'     where  column1 = ''         and column2 = ( select column2                          from mytable                          order by column2                          fetch first 1 row only)     skip locked data  ) 	0
19065852	22468	how can i select flowid with bigger createdate for each detailid	select * from t a where dt = (select max(dt)             from t b where a.detailid = b.detailid) order by 1 	0.00990954342904159
19067675	26180	search string mysql db that can have spaces, be in another string, etc	select * from mytable where replace( `productcode` , ' ' , '' ) like '%searchparam%' 	0.0170491255051177
19069856	36506	sql new daily table based on range of dates	select allevents.totalcount as c,   ev.eventid,   cast(c.date as date) as date,   ev.sysname   from complete_ev ev right join calendar c on c.date between ev.start and ev.end inner join (select count(eventid) as totalcount, eventid from complete_ev group by eventid) as allevents on ev.eventid = allevents.eventid where ev.type = 's'    and ev.eventid = 6881; 	0
19070888	14074	get distinct rows when filtering and using dynamic order by	select p.productid, p.name from production.product p inner join purchasing.productvendor pv on p.productid = pv.productid inner join purchasing.vendor v on v.businessentityid = pv.businessentityid inner join production.productdocument pd on p.productid = pd.productid inner join production.document d on d.documentnode = pd.documentnode where  (@safetystocklevel = '' or p.safetystocklevel = @safetystocklevel) and (@status = '' or d.status = @status) group by  p.productid, p.name 	0.019716450569537
19073942	24956	mysql joined tables no duplicates	select * from members m join (select s.*       from submits s       join (select submid, max(sub_last_update) lastud             from submits             where approved = 't'             group by submid) l       on s.submid = l.submid and s.sub_last_update = l.lastud) s on m.mid = s.submid order by s.sub_last_update desc limit 15 	0.0142439003268536
19074527	11830	selecting data and specific value from two different values	select s.*, r.name, r.description from salessummary s join rsales r on s.receipt = r.receipt where s.register_mode = 'sales' and s.date between '$a' and '$b' 	0
19075386	11966	how to multiply two columns and store their result in single column and then do the sum of new column generated?	select price*quantity as subtotal,  sum(price*quantity) as grandtotal  from productinfo 	0
19076377	29798	mysql get data from three tables using one id	select food.*,ingridients.*,tags.* from food               join ingridients                 on food.id=ingridients.food_reference             join tags                 on food.id=tags.food_reference             where food.id=1 	0
19076485	40979	sql select data if only data exist	select * from table where username="abc" and password="abc"; 	0.00439402782299212
19076724	33580	select from and insert into	select count(*) as recent_posts from bloopp  where email=? and (unix_timestamp(now()) - unix_timestamp(send_time))<600; 	0.00496069052579888
19076978	12449	joining results from two select stataments each with their own where criteria and grouping	select q1.caseno, q1.feeearner,             q2.fees as [fees],             q1.fees as [billed],            (q2.fees - q1.fees) as wip     from     (     select *      from tblallocations     where allocid in     (     select max(allocid)         from tblallocations     where feeearner = 'klw'     and [date] <= '2013-12-31'     group by feeearner, caseno     )     ) as q1,     (     select userid, caseno, sum(fees) as [fees]     from tbltimesheetentries     where userid = 'klw'     and [date] <= '2013-12-31'     group by userid, caseno     ) as q2     where q1.caseno = q2.caseno 	0
19077837	12706	get avg for every ro in sql	select pracownicy.nazwisko, avg(wyplaty.kwota) from pracownicy inner join wyplaty on pracownicy.nr_prac = wyplaty.nr_prac group by pracownicy.nazwisko; 	0.0140069603769281
19080591	7549	how can i match a complex pattern in sql server?	select * from yourtable where @input like replace(yourtable.savedformat, '^', '%') 	0.72003116458951
19081260	2888	delphi - sql - determining when no updates across multiple detail records within a time frame	select distinct first, last from   athlete a join   programs p on     p.athlete_id = a.id where  a.active = 1 and    p.program_id not in (select program_id                             from   usage                             where  athlete_id     = a.id                             and    created_date   >= dateadd(dd, -14, getdate())                             or     scheduled_date >= dateadd(dd, -14, getdate())                            ) 	0.00192799772891883
19082807	32531	sql order by hardcoded values	select 'junior' as type, value, 1 as sortorder from mytable union select 'intermediate' as type, value, 2 as sortorder from mytable union select 'senior' as type, value, 3 as sortorder from mytable order by 3 	0.173319634978863
19083217	29023	sql - selecting records based on a count of related entries in a separate table	select e.id, count(v.id) as numvotes from entry as e join vote as v on v.entry_id = e.id where e.deleted = "0000-00-00 00:00:00" and v.deleted = "0000-00-00 00:00:00" group by e.id order by numvotes desc limit 10 	0
19083349	4208	query for time ranges of values from beginning-dates of values	select value, min(startdate) start_date, nextdate end_date from (   select value   , startdate   , (     select min(startdate)      from #t t2      where t2.value != t1.value     and t2.startdate > t1.startdate    ) nextdate   from #t t1 ) y group by value, nextdate order by start_date 	0
19084671	23475	unordered list from specific table column	select distinct `gallery_name` from `photographs` 	8.17385907391921e-05
19085163	10937	how to group by on oracle?	select article.noarticle, sum(quantite) from article left join lignecommande on article.noarticle = lignecommande.noarticle group by article.noarticle 	0.177584883216735
19086747	18405	random data from mysql	select id from questions  order by rand() limit 20; 	0.00827992882064763
19088934	2943	sql count columns group by id	select [cityid],  count([scity]), sum([scity]), count([mcity]), sum([mcity]), count([bcity]), sum([bcity]), [flag] from table1 group by [cityid], [flag] 	0.00361363389097172
19091036	23097	mysql: getting latest transaction made for a row from another table	select tt.*, result.* from tbl_trans tt inner join (select description, max(t.trans_id) as trans_id ,i.`code`,    group_concat(t.`type`) types from tbl_invty i left join tbl_trans t on i.code = t.code group by i.`code` having not find_in_set('idle',types)) result on tt.trans_id = result.trans_id; 	0
19091146	34843	filter duplicate column results in two column mysql	select m.*     from my_table m    join        ( select b              , c              , max(date) max_date           from               ( select b,c,date from my_table where b = 2                union                select c,b,date from my_table where c = 2              ) x          group              by b              , c        ) n       on ((n.b=m.b and n.c=m.c) or (n.b=m.c and n.c=m.b))      and n.max_date = m.date; 	0.000542196216125407
19091391	21320	12 months rolling data from previous month in sql	select      avg(aebill.[totalcost])     ,aeenc.providerid             ,aeenc.date     into #totalcostaccutecareae     from encdetail aeenc     inner join [encbilling] as aebill     on  aebill.[sk_encid] = aeenc.[sk_encid]             and aebill.providerid = aeenc.providerid             where aeenc.date <= dateadd(year,-1,getdate())     group by aebill.providerid 	0
19091762	32177	how can i retrieve same column with two different alias?	select group_concat(case when rank > 0 then answer end) as pos_answers,        group_concat(case when rank < 0 then answer end) as neg_answers from answers 	0.00011051436905816
19092492	38637	how to display rows that when added together equal zero	select *  from ( select tbis.client_ref ,tbis.supplier_key,tbis.client_amount,   sum(tbis.client_amount) over (     partition by tbis.client_ref, tbis.supplier_key) as total_client_amount   from [xxxx].[dbo].[transaction] tbis    where tbis.client_amount !=0  ) where total_client_amount = 0 	7.61116194792986e-05
19093852	9122	mysql select * from a where doesnt exist in b	select *     from        bokningar           left join tilldelade              on bokningar.bok_id = tilldelade.bok_id            and tilldelade.tilldelad = '2013-09-30'    where            bokningar.datum <= '2013-09-30'        and bokningar.datum_end >= '2013-09-30'        and bokningar.typ >= '2'        and bokningar.weektype = '1'        and bokningar.monday = '1' ## monday this is dynamically changed to current date        and bokningar.avbokad < '1'        and tilldelade.bok_id is null 	0.0269355235652321
19094145	15265	get returned values from table-valued function using sqldatasource	select * from mytablevaluedfunc() 	0.0210689152848896
19094186	25827	sort mysql result. order by col1, group by col2	select tablename.id, tablename.name from tablename inner join  (     select name, max(id) as maxid from tablename group by name ) as tmp on tmp.name = tablename.name order by maxid desc, id desc 	0.191175063308121
19095848	36104	distinct and return one value from where clause	select    max(id) as id,    fid,    role  from source  where role = 16 group by   fid,    role 	0.00149324980107268
19096589	39909	sql server: only return records where non unique return per multiple events w/ some duplicates	select test.col1,test.col2,test.col3 from test, (   select col1,col3 from test      group by col1,col3      having count (distinct col2)>=2 ) table2 where test.col1=table2.col1 and test.col3=table2.col3 	0
19096768	29643	using the result of a statement in another	select a.fleet, (operating / delay ) as calculated_col from (select fleet, sum(hours) as operating        from table       where cole = 'operating'        and start_time >= '2012-01-01'       and end_time<='2013-01-01'        and fleet is not null       group by fleet) a join (select fleet, sum(hours) as delay       from table       where cole='delay'       and start_time>='2012-01-01'       and end_time<='2013-01-01'       and fleet is not null       group by fleet) b        on a.fleet = b.fleet order by a.fleet asc 	0.00997827353902178
19096780	28442	changing position of characters in a string separated by commas	select regexp_replace( '-7.820420745913251,-38.221914235592905;-7.838209448558699,-38.206725420257172;-7.90608019095979,-38.238334576496392;-7.905396010088811,-38.163485189211315;-7.929205504398873,-38.168137619133972;-7.940015562160337,-38.155001346411183;-7.940973415379707,-38.154590837888591;-7.941520760076489,-38.154180329366007;', '([^,]*),([^;]*);','\2,\1;') result   from dual; result -38.221914235592905,-7.820420745913251;-38.206725420257172,-7.838209448558699;-38.238334576496392,-7.90608019095979;-38.163485189211315,-7.905396010088811;-38.168137619133972,-7.929205504398873;-38.155001346411183,-7.940015562160337;-38.154590837888591,-7.940973415379707;-38.154180329366007,-7.941520760076489; 	9.2072797041751e-05
19096848	28338	jpa query on bean field from collection	select company from company company      join company.companysecusers user      where user.id = <id> and user.isread = 1 	0.148215521630743
19096875	32234	count records from a single table with different status code	select decode(status, 'e', 'entry', 'a', 'authorised') as status , count(*)  from table where unit_code = '03'  and crd_dt > to_date('12-may-2013', 'dd-mon-yyyy')  and status in ('a', 'e') group by status; 	0
19097003	38758	how do i filter my results	select * from companies where distance <= 100 	0.461177377585282
19100979	7198	mysql joining two table without in common	select 'http:            replace(title, ' ', '+') + '/' + r.region_name + '/' + c.city_name    from city c         join region r on r.id = c.id_region         join country n on n.id = c.id_country        cross join param p    where n.uused = 1       and p.active = 1 	0.00100064196909634
19101550	34609	mysql join two tables with comma separated values	select  a.nid,         group_concat(b.name order by b.id) departmentname from    notes a         inner join positions b             on find_in_set(b.id, a.fordepts) > 0 group   by a.nid 	0.000212265505204172
19102184	32605	sql join, compare two column values, match col values	select tb1.* from table1 as tb1 left join table2 as tb2         on tb1.xid = tb2.id where tb2.id is null 	8.76473424261693e-05
19103261	26076	how to get data from table by like query	select *  from   appcp_vocalize         join appcp_sound_attributes        on instr(appcp_vocalize.attributes, appcp_sound_attributes.name) > 0 	0.00276347602267392
19103351	31021	can you divide 2 completely different query results into 1 result	select (     select count(distinct(table1.id)) as count_1     from table1          inner join op          inner join org          on table1.eid = op.id              and op.orgid = org.id     where table1.titleid = 123         and op.brandid = 1          and op.start <= now() and op.end >= now() ) / (     select count(distinct user.id) as count_2     from table1 inner join user inner join ur         on table1.eid = user.id and ur.userid = user.id     where          user.brandid = 1          and table1.titleid = 123         and ur.role = 0         and user.inactive = 0 ); 	0.000749932982976969
19104356	26881	get maximum number of consecutive duplicate records in mysql	select distinct programmer_id  from (     select     programmer_id,     @beercounter := if(@prev_programmer != programmer_id or type_of_drink != 'beer', 1, @beercounter + 1) as how_many_beer_in_a_row,     @prev_programmer := programmer_id     from     your_table y     , (select @beercounter:=1, @prev_programmer:=null) vars     where time_finished >= now() - interval 6 hour     order by programmer_id, time_finished ) sq where how_many_beer_in_a_row >= 5 	0
19104913	24377	how to search a column in multiple tables in sql server 2005	select column_name, table_name  from information_schema.columns  where column_name like '%columnname%' 	0.0611125575576956
19105386	40899	values in same row of groupwise maximum	select tbl.file, tbl.color, tbl.count from tbl left join tbl as lesser on lesser.file = tbl.file and tbl.count < lesser.count where lesser.file is null order by tbl.file 	0
19109405	39366	oracle sql selecting data from one table that relates to another	select distinct a.user_fname, a.user_lname, b.user_id, b.friend_id from users a, userfriend b  where a.user_id=b.user_id or a.user_d=b.friend_id 	0
19109438	27949	trying to sum top 1 of subquery	select    case when i.issimcheckout=1 then max(id.saleprice)+min(id.saleprice)   else sum(id.saleprice) as result   from invoice i join invoicedetail id on i.invoiceid=id.invoiceid   group by i.invoiceid, id.invoiceid, i.issimcheckout 	0.0274877391384205
19109486	28918	how to select all pairs of id except when ids are the same or the pair already exist (even in reverse order)	select a.id first, b.id second from myrelation a, myrelation b where a.id < b.id; 	0
19109546	29742	query for getting country name which has less then 3 city	select c1.countryname   from country c1 left join city c2 on c1.countryid=c2.countryid  group by c2.countryid,c1.countryname,c1.countryid having count(*)<3 	0.000111561255244113
19109781	5336	count coalesce to count from two columns	select   coalesce(productactual, product) as product,   count(*) as productcount from atable group by   coalesce(productactual, product) ; 	0.00122747325965964
19109972	37815	mysql query to sum the rows and get the max value	select product, sum(quantity) as sum_quantity from products group by product order by sum_quantity desc limit 1 	0
19111277	5315	mysql: join multiple tables - replace multiple userid's with user names	select o.id, o.user_id, o.editor_id, u1.name as user_name, u2.name as editor_name, o.reason, o.amount  from orders o  inner join users u1 on o.user_id = u1.id  inner join users u2 on o.editor_id = u2.id where o.id = "requested order id" 	0.0155442716618052
19112905	39803	select multiple joins to display using more than 3 tables	select c.id, c.name from client c      join clientarticle ca on c.id = ca.clientid     join article a on ca.articleid = a.articleid     where a.value = 'y' 	0.00424840196494833
19114861	18427	select data from future date	select * from tablename where dateupdated < curdate() - interval 13 day 	0.00114328474788083
19114994	15802	how to use group concat to get the 'other' duplicate values?	select  t.id,         t.thevalue,         group_concat(t2.id) as theids from    t         left join t t2             on t2.thevalue = t.thevalue             and t2.id != t.id group by t.id, t.thevalue; 	0.000115042502984443
19115040	41091	replace null with blank value or zero in sql server	select coalesce(total_amount, 0) from #temp1 	0.343348595776899
19115952	3909	sql grouping / contract value	select agentid, accountid from table t inner join (   select agentid, parentaccount   from table   group by agentid, parentaccount   having sum(tcv) >= 10000 ) t1   on t.agentid = t1.agentid      and t.parentaccount = t1.parentaccount 	0.0580429127763277
19118416	24385	mysql: what is the most efficient way to retrieve all permissions from rbac database?	select   `user`.id,   permission.* from   `user`     left join user_role_list on `user`.id=user_role_list.user_id     left join role_permission_list on user_role_list.role_id=role_permission_list.role_id     left join permission on role_permission_list.permission_id=permission.id where   `user`.id=$user_id 	0.000274804444519519
19118889	18779	sql view returning filtered data from unnormalized table	select distinct on (transponder, country, system) * from some_table order by transponder, country, system, time desc 	0.0423314304483714
19119036	12384	oracle - performing operation on each row of result set	select object_name as view_name,        to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from "'||owner||'"."'||object_name||'"')),'/rowset/row/c')) as row_count from dba_objects where object_type = 'view'   and owner = 'admin' order by 1; 	0.000398303202998364
19119421	38795	sql - average distance per day	select id_car, date, avg(table_distances.distance)  from table_distances inner join table_cars  on table_distances.id_car = table_cars.id where table_cars.license = 'paris' group by id_car, date order by id_car, date 	0
19120496	24899	postgres set select value in if	select  user_id,  case when (min(mode) <> max(mode)) then     'multiple'  else     min(mode) end as "start mode" from sessions group by user_id 	0.0130543686403355
19120549	26977	sql: multiple minimum values	select a,b,c, min(d) from mytable group by a,b,c order by a,b,c 	0.00859947950108731
19120606	10306	combine columns in result from sql select	select smpl_time, coalesce(float_val, num_val, str_val) as merge_val     from ... 	0.00113310308756138
19121041	32799	ms access query joining two tables	select t1.id, t1.customer_id, t1.date, t2.type_name from tableone t1 left join tabletwo t2 on t1.type_id = t2.type_id; 	0.165641450448887
19121501	39254	how to filter sql join to records that have multiple matches only	select [user_id]  from userrole ur where role_id in (1,2,3) group by [user_id]  having count(distinct role_id) = 3 	0.000101948899857299
19121565	2137	oracle first_value(partition) break sequence	select    working_days,  date_type, seq_start,    first_value(working_days) over (partition by grp order by working_days) "rank" from (   select      working_days, date_type, seq_start,     sum(front) over(order by working_days) as grp   from (     select        working_days, date_type, seq_start,       decode(seq_start, lag(seq_start)over(order by working_days), 0, 1) as front     from t1   ) ) where date_type = 'l' order by 1 	0.659144428844936
19122995	24586	mysql join get latest valid row	select u.email, q.status from users as u left join (   ( select max(mq.id) as id     from questions as mq     where mq.isvalid = 1     group by mq.userid   ) as maxq   inner join questions as q on q.id = maxq.id ) on u.id = q.userid order by u.id asc 	0.00123187455374982
19124213	34964	hibernate select relevent data in one query	select  id , name ,age , sex from user  where (name,age) in (('amit','20'),('ram', '26'),('mohan', '22'),('sita', '19')); 	0.239422530793182
19124891	23138	oracle unpivot columns to rows	select * from ( select  transacion_id, case when c.lvl = 1 then 'gross'      when c.lvl = 2 then 'disc' end type, case when c.lvl = 1 then gross_amount      when c.lvl = 2 then discount_amount end amount from t cross join (select level lvl from dual connect by level<=2) c      ) where amount is not null order by 1 	0.0180431466154524
19125301	10924	select where field has more than 2 non duplicated records sql	select distinct o.customers_id, o.customers_email_address   from orders o join (   select customers_id     from orders    group by customers_id   having count(distinct customers_email_address) > 1 ) q     on o.customers_id = q.customers_id  order by o.customers_id; 	6.21221044852514e-05
19126048	3533	getting data from multiple tables	select     shop.lat   , shop.lng   , shop.id   , potato.date_time as potato_date   , potato.price as potato_price    , tomato.date_time as tomato_date   , tomato.price as tomato_price from shop left join potato on potato.id = shop.id left join tomato  on tomato.id =  shop.id  where  st_dwithin(st_geomfromtext('point(xx.xxxxxx yy.yyyyyy)',4326), shop.geom,10*1000, true ); 	0.00232792641614364
19126148	32197	pl/pgsql return query gives psuedo-type record rather than table	select * from st_fishnet(rows, columns, geo-table, the_geom) 	0.030305005177647
19126477	31517	mysql join two tables where date between two dates	select difference from productionlog where systemid = '$id' and date(updated) between '$weekstart' and '$weekend' union all select difference from productionlog_today where systemid = '$id' and date(updated) between '$weekstart' and '$weekend' order by updated 	0.00021793032984425
19128125	30834	select group by from same table	select u1.id, u1.user, count(u1.id) cnt from mlm_users u1 join mlm_users u2 on u1.id = u2.refid group by u1.id, u1.user 	0.00104426841131119
19128747	28279	filter rows based on condition sql server 2008	select opid, manual, tt from (   select *, row_number() over (partition by opid order by manual, tt desc) rn   from yourtable ) v where rn = 1 	0.00530969942046566
19129997	38643	mysql, select two different rows with same id but different values in another column	select post_id,        max(case when meta_key = '_fb_count' then meta_value end) `_fb_count`,        max(case when meta_key = '_permalink' then meta_value end) `_permalink`   from wp_postmeta  where meta_key in('_fb_count', '_permalink')  group by post_id 	0
19130575	21085	how to find rows that match all these conditions	select a.orderid from table_a as a  inner join table_b as b on a.orderid = b.orderid group by a.orderid having sum(b.status = 2) >= 1 and sum(b.status in (4,6)) = 0 	4.98336188856732e-05
19130908	6595	how to insert a character inside the values of the select query in mysql	select insert(item, ,2, 0, '-') item from tbl 	0.00421300635713531
19132787	38826	how to use regexp in mysql to aquire specific columns	select code, txt_gb, txt_de from table where code like '%chol%' or txt_gb like '%chol%' or txt_de like '%chol%' order by code 	0.0363259542365759
19133403	29787	collect a specific text string from a very large text string in sql server	select      case when charindex('(', [path])>0          then left([path], charindex('(', [path])-1)      else [path] end [path] from(     select          case when charindex('\', [path])>0 then             replace(right([path], charindex('\', reverse([path])) - 1), '.jpg', '')          else [path] end [path]     from          kyc_path )x 	0.0256795673304838
19134036	39617	counting groups of 3? possible?	select count(distinct(sub.member_id, sub.portfolio_number)) as count_result from exp_submissions as sub left join exp_judging_portfolios as jud1 on sub.entry_id = jud1.entry_id_1 left join exp_judging_portfolios as jud2 on sub.entry_id = jud1.entry_id_2 left join exp_judging_portfolios as jud3 on sub.entry_id = jud1.entry_id_3 where jud1.entry_id_1 is null and jud2.entry_id_2 is null and jud3.entry_id_3 is null and sub.member_group = 6 and sub.type_id = 1 group by sub.member_id, sub.portfolio_number having count(sub.portfolio_number) = 3 	0.00629635205758337
19134587	12091	postgresql find inconsistency record in the row	select salesman from sales group by salesman having count(distinct phone) > 1 	0.000427598001622818
19134710	6081	sql group by percentage increments	select t.pcbracket as [% bracket], count(*) as [numwithmark] from (   select case       when mark between 0 and 9 then ' 0- 9'     when mark between 10 and 19 then '10-19'     when mark between 20 and 29 then '20-29'     when mark between 30 and 39 then '30-39'     else '40-100' end as pcbracket   from testresults) t group by t.pcbracket 	0.05551925736631
19134920	38933	retrieving list of companies with no main addresses	select distinct c.name from company c inner join  ( select company_id, sum(case when main=1 than 1 else 0 end) as totals form companyaddress  group by company-id having sum(case when main=1 than 1 else 0 end) <1 )  ca on ca.company_id = c.id order by c.name asc 	0.00443754001995712
19135161	36043	django.db.utils.integrityerror: duplicate key value violates unique constraint "django_content_type_pkey"	select setval('django_content_type_id_seq', (select max(id) from django_content_type)); 	0.000150896063750743
19135747	28774	mysql fulltext search sort best results then sort again by other item	select * from  (     select *,      match(md.keywords) against('$meta[keywords]') as score     from          meta_data as md      inner join         sites as si on md.domain = si.domain     where         match(md.keywords) against('$meta[keywords]')     order by score desc     limit 25 ) x order by x.views 	0.00325786590703705
19135753	33521	ms sql subquery returned more than 1 value	select  ltrim(c.value('n[1]','varchar(50)')) as item1 from    (   select  x = cast('<myxml><nodes><n>' +                                  replace(firsat_personeller_id,',','</n></nodes><nodes><n>') +                                  '</n></nodes></myxml>' as xml)             from    firsatlar         ) t         cross apply x.nodes('/myxml/nodes') cols (c); 	0.101712164447596
19136542	20615	mysql count rows where max	select outerq.player, coalesce(subq.wins, 0) as wins from table1 outerq left join (   select   ot.player,   count(*) as wins   from (     select     *     from     table1 t     where points = (select max(points) from table1 st where st.tournament = t.tournament) ) ot group by ot.player ) subq on outerq.player = subq.player group by outerq.player order by wins desc 	0.0209924610016417
19136641	38684	sql - relationship between actors	select m.actor from movies m  where  m.movie = 'pulp fiction' and not exists (   select 1   from movies m1      join movies m2 on m1.movie = m2.movie        and m1.actor <> m2.actor        and m2.movie <> 'pulp fiction'        and m2.actor in (select actor from movies where movie = 'pulp fiction')   where       m.actor = m1.actor  ) 	0.153535980851072
19137338	14476	how to find column names from table with specific confitions?	select * ,case     when ( answer1 =1)   then 'answer1'     when ( answer2 =1)  then 'answer2'     when ( answer3 =1)   then ' answer3'     else 'nobody' end as selected_answer from q where  q.userid=1 and (q.answer1=1 or q.answer2=1 or q.answer3=1) 	0
19139857	16712	get max(id) and all values as array from database, mysql and php	select *,  (select max(id) from table1) from table1 order by name asc; 	4.95075241673591e-05
19140578	812	grouping counts according to a given field in sql-server	select    location,    appointments = count(*) from dbo.appointment where start_datetime >= '20130902'   and start_datetime <  '20131003' group by location order by location; 	0.000197888343272443
19141168	24169	query to multiple each row's cost times quantity and sum	select sum(quantity*cost) as sum from table 	0
19142326	34481	sql 2008 subtract	select (select) - (select); 	0.182935095715914
19144547	29727	filtering records based on two other tables	select activecustomers.*, tbladdress.* from  (   select customers.name, customers.customerid,   (     select count(intakedate)      from intake      where customers.customerid = intake.customerid and len(intakedate & '') > 0   ) as intakecount,   (     select count(exitdate)      from exit      where customers.customerid = exit.customerid and len(exitdate & '') > 0   ) as exitcount   from customers  ) as activecustomers inner join tbladdress on activecustomers.customerid = tbladdress.customerid where intakecount > exitcount and tbladdress.currentaddress = true 	0
19146298	29923	sql - union, priority on the first select statement when doing order by	select *, 0 as priority from (   select distinct a.productref   from germandb.dbo.locations as a inner join germandb.dbo.items as b on a.productref =   b.productref    where b.active=1   ) ta   union select *, 1 as priority from   select distinct c.productref   from bostondb.dbo.locations as c inner join bostondb.dbo.items as d on c.productref =   d.productref    where c.active=1 (c.productref not in    (select productref from germandb.dbo.items where active=1))   ) tb   order by priority, productref 	0.10347700555296
19148323	28782	sql where null values	select *  from table1 a     left join table2 b on a.customerid= b.customerid  where (b.comment<>'returned' and b.comment not like 'three%')         or (b.customerid is null) 	0.181943976298769
19148982	12065	mysql count distinct days in a month	select extract(year_month from dateofreport) as ym,     count(distinct dateofreport) as count from table1 group by ym 	5.33384446097498e-05
19150392	17503	select without negative values in sql qurey	select dealercode, paymenttype, total from del_purchases  where dealercode='a0686p' and total > 0 	0.022256446015483
19152224	26598	how to see profile assigned to a user	select profile from dba_users where username = 'test_user'; 	0.00368100357856695
19154196	6823	compare two string column and result in third column sql server	select *, case when patindex('%'+strnew+'%',stroriginal)>=1       then replace(replace (stroriginal,strnew,''),',,',',')       else stroriginal  end final_string from table1 	0.00023888928800875
19154387	18542	sql server inner join on same column with two tables	select categoryid, coalesce(a1_items.name, a2_items.name) as name from categorizeditems left join a1_items on a1_items.itemid = categorizeditems.linkid and categorizeditems.type = 'a1' left join a2_items on a2_items.itemid = categorizeditems.linkid and categorizeditems.type = 'a2' 	0.0185143996038136
19154448	15134	search for orders that have two products, one with specific reference, other with specific description	select ordernumber from `order` where id in (     select orderid from orderdetail od1     inner join orderdetail od2     using (orderid)     where od1.reference = 'f40' and od2.description = "epee" ) 	0
19154767	12940	how to construct a list of products recursively in sql?	select * from (     select *, rank() over (partition by p.make order by      case        when colour = 'red' then 1       when age < '2' then 2       when category1 = 'x' then 3       else 4     end) as priority     from products p  ) ranked where priority = 1 	0.00788886723768037
19155056	31552	matching items in one table that don't match in a subset of a second table	select p.name from product p left join (select product_id, user_id            from cart where user_id = 1) c on p.id = c.product_id where c.product_id is null; 	0
19155420	1672	android sqlite join not showing data	select a._id as a_id, b._id as b_id 	0.788051125960781
19158148	15693	calulating the hours and minutes between clock in and clock out timestamps	select emp ,sum(datediff(hour,cast([in] as datetime)        ,cast([out] as datetime)) )  from table1 group by emp 	0
19158353	37853	how to count values in a query result	select sum(closing_fee+closing_fee_int+closing_ins+closing_int+closing_other) as bal, max(total_closing_balance) as total_closing_balance from isql.vw_300_statement where brand = '1'and dat = '2013-01-18 00:00:00.00000'and ins_type =''group by brand,dat 	0.016126615937576
19160222	18295	order before grouping in joined results	select  u.user_id,   u.firstname,   pn.programme_name,    e.exp_start,   en.firstname as name  from    edu_users u    left join (select exp_user, max(exp_start) as maxexpstart from edu_experience group by exp_user) e1 on e1.exp_user = u.user_id    left join edu_experience e on e.exp_user = u.user_id and e.exp_start = e1.maxexpstart   left join edu_users en on en.user_id = e.exp    left join edu_programmes pn on pn.programme_id = e.exp_position  order by    exp_start desc 	0.0414952013111249
19160853	26067	parse openxml and get a name value collection for given node	select replace(name,'__',' ') as name, value              from openxml (@idoc, '/user/additionalfields/*',1)              with (                           name  nvarchar(4000) '@mp:localname',                 value  nvarchar(4000) './text()'                   ) 	0.000986589771135702
19161236	37757	mysql multi group by	select p.*,  (case when  g.gid is not null then g.gid else -1*p.id end) as temp_group_id from product as p left join g_product as g on p.id = g.fk_prod group by temp_group_id 	0.398876536273451
19163901	14150	sql: counting and grouping rows	select id, userid, exerciseid, date, time, weight, distance, reps,        count(*) as count from `exercises` where userid = 1 and date < now() group by id, userid, exerciseid, date, time, weight, distance, reps 	0.010855681864311
19164698	2754	how to select a row based on its row number?	select * from  (     select        row_number() over (order by somefield) as rownum     , *     from thetable ) t2 where rownum = 5 	0
19164775	8593	get date range between dates having only month and day every year	select cash = case when right(convert(varchar(8),[date],112),4)                between '0701' and '1031' then cash*2               else cash end  	0
19166061	24969	join two tables or select queries in mysql	select ct1.teamname as team1 ,ct2.teamname as team2  from clm_schedule cs  left join clm_team as ct1    on ct1.teamid = cs.team1 left join clm_team as ct2   on ct2.teamid = cs.team2; 	0.138514273712679
19166645	15030	join 3 tables, only use data from 2?	select m.first_name, m.last_name, p.effective_date, p.expired_date from mortal m   inner join policy p     on p.policy_id = i.policy_id   inner join insured i     on i.mortal_id = m.mortal_id 	0.00108208515601641
19168560	22837	mysql single-query count	select sum(`numrecip`) as `total`  from `messaging`  where `type`='response'  and `datetime`>='2013-09-01 00:00:00' 	0.28340756673987
19169001	17773	find rows only present in the result of one of two queries	select id from dbo.table1 inner join dbo.table2 on ... except select id from dbo.table2 inner join dbo.table3 on ...; 	0
19170749	39565	boolean check for empty date field	select top 1 orderstable.startdate, orderstable.enddate , iif(orderstable.enddate is null, "yes", "no") as isempty from orderstable  where orderstable.customerid=1  order by orderstable.startdate desc; 	0.012191885854704
19170889	10272	how to use group by to get only one row	select l.unit_id, l.created, l.activity_id from unit_log l join (select unit_id, max(created) as maxc       from unit_log       group by unit_id) m on l.unit_id = m.unit_id and l.created = m.maxc 	0.000105901711286723
19172795	15645	sql returning results based on an indirect criteria	select id1,sales from table1 where id1 in(select id1 from table2 where id3 in (select id3 from table where id2=0)) 	0.0102471661977451
19173043	30661	how calculate daily moving average (20dma) of every row of close values where multiple rows available in historical data table in single query	select h1.ndate, avg(h2.high) as averagehighlast20rows (select ndate, rank() over (order by ndate) as ranked from historicalstockdetails) h1 inner join (select ndate, high, rank() over (order by ndate) as ranked from historicalstockdetails) h2 on h2.ranked between h1.ranked and h1.ranked - 20 group by h1.ndate 	0
19173894	29198	how to retrieve imagepath value with count() who has max upvote value	select imagepath from uploadimage where upvote in (    select max(upvote) from uploadimage ) 	0
19174675	17034	how to sort this data by in ascending order?	select pid from `patient_list` t1, patient_info t2  where replace(pid, "*", "") + 0 > 2000 and t2.id = t1.id  order by replace(pid, "*", "") + 0 limit 1 	0.0621980061476851
19174803	26507	sql query taking between specific sysdate?	select * from test_table where test_execution_date between  to_date('9/2/2012', 'dd/mm/yyyy') and to_date('7/2/2013', 'dd/mm/yyyy') 	0.0480807041869703
19175411	3751	group by and order by on different columns	select   col1,           sum(col2) group by col1 order by min(colnotinselect); 	0.00305261326078072
19177027	35639	sorting update history in mysql table	select * from table1 order by cast(substring_index(version, '.', 1) as decimal) desc,  cast(substring_index(substring_index(version, '.', 2), '.', -1) as decimal desc, cast(substring_index(version, '.', -1) as decimal) desc; 	0.150140429643319
19180142	14470	mysql select query using if, sum & multiplication	select column1, column2, column3,         if (column1='cr', column1 * 8, 0) +         if (column1='config', column1 * 6, 0) +         if (column2='bs' and column3='ft', column3 * 4, 0) +         if (column2='bs' and column3='mj', column3 * 2, 0) +         if (column2='bs' and column3='md', column3 * 5, 0) +         if (column2='bs' and column3='mi', column3 * 3, 0) +         if (column2='lf' and column3='ft', column3 * 2, 0) +         if (column2='lf' and column3='mj', column3 * 1, 0)  from tbl_ut 	0.394500778574565
19181591	27995	trouble with script getting last action using nested queries	select o.order_number ,last_id ,finish_id ,last_id into #temp1 from [customer] [c] join [site] [s] on c.customer_id=s.customer_id join [order] [o] on s.site_id=o.site_id join [item] [i] on o.order_id=i.order_id join (select     max(action_id) as [start_id], a2.item_id     from [action] [a2]     join [allowed_action] [aa2] on a2.allowed_action_id = aa2.allowed_action_id     where aa2.description='start'     group by a2.item_id) as [d] on i.item_id=d.item_id join (select     max(action_id) as [finish_id], a3.item_id     from [action] [a3]     join [allowed_action] [aa3] on a3.allowed_action_id = aa3.allowed_action_id     where aa3.description='finish'     group by a3.item_id) as [f] on i.item_id=f.item_id join (select     max(action_id) as [last_id], a4.item_id     from [action] [a4]     group by a4.item_id) as [l] on i.item_id=l.item_id select order_number from #temp1 where last_id>finish_id and  finish_id>start_id 	0.425631334412332
19183101	499	mysql select from multiple tables where two items match	select r.country,c.id, c.countryname, c.countrycode from resorts as r left join country as c    on r.country = c.countryname 	8.71921549253381e-05
19183549	10798	mysql query within a query on same table	select perioddate,         sum(quantity) as totalquantity  from your_table where perioddate between '2013-07-02' and '2013-07-05' group by perioddate 	0.0150071103454645
19184534	6430	subselect with mulitple results	select * from accounts a, transactions t where t.account_id=a.id and other_id=500 	0.756317642082462
19184892	1736	case when for both columns true not showing data	select locationname     ,branchname     ,addline1     ,addline2     ,tel1     ,case          when locationtype = 'cc'             then 'call center'         when locationtype = 'cl'             then 'operation'         end as 'location type'     ,case          when ispurchase = 1 and ishomedelivery = 0             then 'purchase'         when ispurchase = 0 and ishomedelivery = 1             then 'home delivery'         when ispurchase = 1 and ishomedelivery = 1             then 'purchase and home delevery'         end as 'type' from pescalocation 	0.245799167467001
19185363	21709	check and compare column values in sql server table	select t.student, t1.student from    prefrences_table t   inner join prefrences_table t1     on t.student = t1.preferences        and t.preferences = t1.student        and t.student < t1.student 	0.000597829910262693
19187780	40645	selecting rows based on max column in group by	select scores.score, scores.team, users.name from users join scores   on users.id = scores.user_id where not exists    (select *    from scores scores2    where scores2.score > scores.score      and scores2.user_id = users.id) 	0
19187851	18464	search database for string of text, possibly tags	select * from table_tags where match(tag_text) against('boy gets girl'); 	0.027363521376883
19188911	31699	sql syntax to combine tables	select i.ticker, i.[year], i.period, i.net_income,     b.total_assets, c.net_cash_flow_operating  from (income_statements as i     inner join balance_sheets as b     on (i.ticker = b.ticker) and (i.[year] = b.[year]) and (i.period = b.period))     inner join cash_flow_statements as c     on (b.ticker = c.ticker) and (b.[year] = c.[year]) and (b.period = c.period) where i.period <= #" & quarter & "#     and i.[year] <= #" & year & "#" 	0.451104882797025
19189501	12239	select distinct after "removing" trailing spaces	select distinct trimmed from (     select rtrim(ltrim(myid)) as trimmed     from dbo.sourcetbl ) a 	0.119941700523439
19189722	7325	count repeated fields value	select     p1.name,     p1.age,     (select count(p2.name) from person as p2 where p1.name == p2.name) as qtdname from person as p1 	0.00665989677915006
19189886	4484	calculate balance by symbol	select x.*      , case when x.openposition = 0 then sum(y.financialvol) else '' end desired   from my_table x    join my_table y      on y.symbol = x.symbol and y.time <= x.time   group      by x.symbol, x.time; 	0.0851222693056973
19191460	15228	how do i eliminate duplicatesin sql?	select distinct event.event_id,event.event_name,count(student_class.student_id) as 'total students'    from student_class, event    where student_class.class_id = '10'    and event.class_id = '10'       group by event.event_id,event.event_name,student_class.student_id 	0.448237646298591
19193556	17678	mysql convert date to age in a select statement	select profile_username,profile_gender, date_format(now(), '%y') - date_format(profile_birthdate, '%y') -  (date_format(now(), '00-%m-%d') < date_format(profile_birthdate, '00-%m-%d'))  as age from logintable where id=1000; 	0.0143554775947811
19194940	37232	selecting data and joining fields	select food_name from foods  join categories using (category_id) where category_slug = :slug 	0.00327660693816376
19195665	29803	to combine two summary queries that use a common group by into one query in ms access	select dates, sum(increases), sum(decreases) from {     select dates, count(closingbal) as increases, 0 as decreases from tablename      where closingbal >[ openingbal] group by dates     union all     select dates, 0 as increase, count(closingbal) as decreases from tablename      where closingbal <[ openingbal]group by dates  } groupby dates 	0.000460204262148207
19196070	9302	sql:server group data by date ignoring time	select * from mytable  group by convert(date, dateadded) 	0.0137280125341456
19196195	41138	how to get all record from a table where particular column exists on another table	select * from candidateexam ce where not exists      (select * from paperdetails pd where ce.candidateid = pd.candidateid) 	0
19196633	1847	remove duplicate rows on multiple joins	select m.movementid, m.orderid, m.pickupdate, m.pickupnotes,  b.bin_size, b.bin_type,  l.address, l.suburb, l.postcode, l.state,  if(r.run_id is null, 0, 1) as active_on_pick from bb_movement m inner join bb_bins b on b.bin_id = m.bin_id inner join bb_location l on l.locationid = m.locationid left join bb_runsheet rs   on rs.movement_id = m.movementid     and rs.run_action = 'pick' left join bb_run r    on r.run_id = rs.run_id     and (r.run_state = 'active' or r.run_state='ready') where m.mvtstate = 'active' order by m.locationid, m.pickupdate 	0.00366217602009519
19197912	4658	how to select only workday	select date, price from table where date between @start and @end and weekday(date) < 5 	0.0225388398612402
19198254	1669	mysql count mutual friends between multiple users	select r1.user_id as first_user , r2.user_id as second_user , count(r1.related_to) as mutual_friend_count from relations r1 inner join relations r2 on r1.related_to = r2.related_to and r1.user_id <> r2.user_id group by r1.user_id, r2.user_id 	0.00059426904750523
19198558	8377	mysql count occurances of value on multiple fields. how?	select numbers_table.number as number   , count(tbldraw.pk_record) from numbers_table left join tbldraw  on numbers_table.number = tbldraw.pick_1    or numbers_table.number = tbldraw.pick_2    or numbers_table.number = tbldraw.pick_3    or numbers_table.number = tbldraw.pick_4    or numbers_table.number = tbldraw.pick_5 group by number order by number 	0.000389143745921353
19199076	14097	find unique values when comparing 2 datasets	select    case      when v.version_id = 410 then v.version_id     else ''   end  as left_version   ,case      when v.version_id = 410 then v.trim_id     else ''   end  as left_trim_id   ,case      when v.version_id = 410 then t.trim     else ''   end  as left_trim   ,case      when v.version_id = 411 then v.version_id     else ''   end  as right_version   ,case      when v.version_id = 411 then v.trim_id     else ''   end  as right_trim_id   ,case      when v.version_id = 411 then t.trim     else ''   end  as right_trim from(select trim_id, count(*)      from versiontrim      where version_id in (410,411)      group by trim_id      having count(*) = 1) as vt join versiontrim as v  on v.trim_id = vt.trim_id    and v.version_id in (410,411) join trims as t  on v.trim_id = t.trim_id group by v.trim_id order by v.trim_id; 	0.000121463947560969
19201503	15977	mysql - find row value based on another value in same row	select * from tbl where row_id = $id 	0
19202198	31590	sql - how to get specific value of cell?	select b from table_name where a = 'a'; 	0
19203814	24866	sql: getting specific row values on a column after a join	select         "metacae"."family",         parentmetacae."name",         count(1) as "count"     from         "userhistoryprofessional"     inner join         "company_metacae"             on (                 "company_metacae"."id_company" = "userhistoryprofessional"."id_company"             )     inner join         "metacae"             on (                 "metacae"."id" = "company_metacae"."id_metacae"             )     inner join                                        (select family, name           from metacae          where level = 1) parentmetacae            on (parentmetacae.family = metacae.family)     where         "userhistoryprofessional"."dateuntil" is null     group by         "metacae"."family"     order by         "count" desc; 	0.000106519683585232
19206080	7463	cast and sum functions	select id, cast(sum(calculated_quantity) as number(10)) qty  from dw.sample 	0.743779347390094
19206205	31878	comparing dates by month and year in mysql	select * from your_table where year(start_date) = year(curdate()) and month(start_date) = month(curdate()) and end_date <= curdate() + interval 30 day 	5.84808026871664e-05
19206549	10283	find number of visits on each day	select doctor_id from your_table group by doctor_id, date_of_visit having count(*) = 3 	0
19207136	8451	getting the last result using limit in sql	select max(id) from (     select id      from this_table      where value = 'some_value'     order by id     limit 10 ) x 	0.00202723666684103
19207193	3855	mysql multiple tables select last 7 days	select abb1.date, sum(abb1.credit) as daily_total from     (select date, credits     from table1     union all      select date, credits     from table1     union all      select date, credits     from table2) as abb1 where date >= date_sub(curdate(), interval 7 day) 	0
19207329	1882	choice of tables for handling attendance	select student_id, class_name, date, class_attended from attendance as abb2     left join classes as abb1 on abb1.id = abb2.class_id 	0.786540051093002
19207638	5719	microsoft access sql to query a date range ignoring the year	select * from user  where (month(birthday) * 100) + day(birthday) between 0131 and 1231 	0.00550103393955732
19208036	40068	trying to get a list of unique forum posts, not working	select   f.title,   f.id,   fm.url_path from forum_posts as f inner join forum_master as fm  on f.forum_id = fm.id  where deleted = 0 and blacklisted = 0 and (select id      from forum_posts      where title = f.title      order by id desc      limit 1) = f.id order by f.id desc limit 5 	0.00143926735487217
19210432	30427	how to get image path of highest vote	select    if(image1vote >= image2vote, image1, image2) as path,   greatest(image1vote, image2vote) as votes from imagetable 	0
19213633	30699	create a rolling sum over a period of time in mysql	select r1.date, r1.time_spent, sum(r2.time_spent) as rolling_week_total from rolling_total as r1 join rolling_total as r2     on datediff(r1.date, r2.date) between 0 and 7 group by r1.date order by r1.date limit 8 	0.000691213834504155
19216965	36089	sql joining rows after using count	select   p.id,   concat_ws(', ', substr(p.fname, 1, 1), p.lname) name,   coalesce(eg_goals.goals, 0) goals,    coalesce(eg_assists1.assists, 0) + coalesce(eg_assists2.assists, 0) assists,   coalesce(eg_goals.goals, 0) + coalesce(eg_assists1.assists, 0) + coalesce(eg_assists2.assists, 0) points from players p left join (   select g_id, count(g_id) goals from events_goals   group by g_id ) eg_goals on p.id = eg_goals.g_id left join (   select a1_id, count(a1_id) assists from events_goals   group by a1_id ) eg_assists1 on p.id = eg_assists1.a1_id left join (   select a2_id, count(a2_id) assists from events_goals   group by a2_id ) eg_assists2 on p.id = eg_assists2.a2_id where p.team = 1 	0.0198232366489861
19217328	20977	mysql count field values before left join	select  t0.`contract` as contract, count(distinct t0.`id`) as rec_num, count(t1.`id`) as tr_num, avg(t1.`response_delay`) as rd_avg, count(distinct case when t0.`status`='status1' then t0.id  end) as s1, count(distinct case when t0.`status`='status2' then t0.id  end) as s2, count(distinct case when t0.`status`='status3' then t0.id  end) as s3 from  records as t0 left join transactions as t1  on (t0.id = t1.record_id) group by contract order by t0.`id` desc 	0.0700780978452172
19220131	36731	sql identifying the first occurance in a list	select    breakfast  , case when rn = 1 then 1 else 0 end as first_occur from (        select           breakfast        , row_number() over (partition by breakfast order by id desc) as rn        from your_table      ) as x 	0.000554776405930478
19221451	35965	add an extra column while select from two tables	select * , 'web' as source from web where name='abc' union select *, 'mail' as source from mail where name ='abc' 	0.00031913364359358
19222431	2462	opencart sql query order id dublicates	select part3.order_id,        part3.name,        part3.quantity,        part3.value from ( select coalesce(part2.order_id,order_option.order_id) as order_id, part2.name, part2.quantity, order_option.value from ( select coalesce(part1.order_id,order_product.order_id) as order_id, order_product.name, order_product.quantity from ( select coalesce(order.order_id,order_product_id.order_option_id) as order_id from order left join order_product_id on order.order_product_id = order_product_id.order_option_id )part1 left join order_product on part1.order_id = order_product.order_id )part2 left join order_option on order.order_id = order_option.order_id )part3 where part3.order_id in (".$orderid.") 	0.312090550122165
19223201	1321	sql how can i select data between dates?	select     e.eventcode, e.eventdate,     d.timestamp, d.deviceid, d.value from      devicesignal as d   outer apply     ( select top (1) e.eventcode, e.eventdate       from events as e       where d.timestamp <= e.eventdate       order by e.eventdate     ) as e ; 	0.00545609378019409
19223836	36883	how to update the column in whole database?	select        'update '       || owner       || '.'       || table_name       || ' set empcode = substr ( empcode, 1, 3); ' from       sys.all_tab_columns where       owner = '{owner}'       and column_name = 'empcode'; 	0.00819084670926394
19226208	27836	sql server determine if values are monotonous	select case when count(*) = 0 then 1 else 0 end as ismonotone from (     select row_number() over (order by measdate) as rownum, measvalue     from measurements ) t1 inner join (     select row_number() over (order by measvalue) as rownum, measvalue     from measurements ) t2 on t1.rownum = t2.rownum where t1.measvalue <> t2.measvalue 	0.0290509435349613
19226547	21232	sql joining tables based on ids	select ti.title_name, te.team_name from link l inner join title ti on l.title_id = ti.title_id inner join team te on l.team_id = te.team_id 	8.27721524611169e-05
19227598	5664	how to obtain many-to-many relationship querys in oracle?	select aircraft.aname,avg(employees.salary) as average  from  aircraft inner join certified on    certified.aid =aircraft.aid  inner join employees on employees.eid = certified.eid where aircraft.cruisingrange > 1000   group by aname 	0.165982009332345
19228427	14632	double quotes at end of concatenated tsql string	select null as [dbnull], n'ldkjf' as [string], len(n'ldkjf') as [len] select null as [dbnull], n'' as [empty_string], len(n'') as [len] 	0.0112383409043243
19229823	18726	group by calculating the non-breaking periods from two (from and to) values	select     field_id,     min(field_from),     max(field_to) from (     select         field_from,         field_to,         field_id,         sum(willsum) over(partition by field_id order by field_from) as gid     from (         select             field_from,             field_to,             field_id,             case when field_from                     = lag(field_to) over(partition by field_id order by field_from)                  then 0 else 1 end as willsum + 1         from             rj_mytest         )     ) group by     field_id,     gid order by     field_id,     min(field_from); 	0
19230560	3630	how to select multiple rows by multi-column primary key in mysql?	select      *  from      data t1 natural join      (          select              city,              state,              max(date) as date         from              data         group by              city,              state     ) t2; 	0.00112491547621679
19230601	30644	oracle rounding down	select round(3.9123458543845474586, 1) round from dual;      round       3.9 	0.639271043596731
19230800	27957	checking rows that are not numbers in a varchar column for mysql query	select * from mytable where concat('',col1 * 1) != col1 	0.000505051935895346
19231545	11261	combining 2 queries into 1 query	select b.oprid  from   ps_z_emp_benft a,         psoprdefn b,         ps_z_emp_yan c  where  a.emplid = b.emplid         and a.emplid = c.emplid         and a.z_pend_cover = 'y'         and oprid like 'zz%'         and c.z_yan_action_id = 1 	0.0153529043567979
19232384	11317	how can i show the counts of distinct values and include zeros?	select location, count(nullif(name,'')) as count from table group by location; 	0
19232753	29632	sql query to find number of trailing zeros across columns	select id,    length(@k:=concat(day1,day2,day3,day4,day5&&1))      - length(trim(trailing '0' from @k)) as trailing_zeros  from days_table 	6.24341706462777e-05
19232791	23846	sql-using joins to get the values from three tables	select    om.ownername,   count(vm.vehicleid) total,   sum(case when vm.vehicleid is not null              and cv.vehicleid is not null then 1 else 0 end) runnng,   sum(case when vm.vehicleid is not null              and cv.vehicleid is null then 1 else 0 end) notrunnng from ownermaster om left join vehiclemaster vm on om.ownerid = vm.ownerid left join customervehicle cv on vm.vehicleid = cv.vehicleid group by om.ownername 	0.0002054879713428
19233016	22622	generate serial number which resets for a particular condition using mysql query	select outlet,itemname,id, quantity, `value`,        @i:= if(outlet = @last_outlet, @i + 1, 1) as result,        @last_outlet := outlet from (select  @i := 0, @last_outlet := null) h join (select outlet, itemname, id, sum(quantity) as quantity, sum(`value`) as `value`       from browsekot       group by itemname,outlet       order by outlet) i 	0.000553204917675879
19234264	24009	mysql counting total number of zeros	select id, (day1=0)+(day2=0)+(day3=0)+(day4=0)+(day5=0) total_zeroes from table 	0
19234467	30827	select latest product code	select account_no, product     from table as t1     where (t1.account_no, t1.date) in (select account_no, max(date) from  (select account_no, date from table t2 where t2.account_no = t1.account_no)) 	0.013174330990637
19235876	10994	need help numbering rows	select dense_rank() over (order by col1) as orderby, col1 from deleteme order by col1 	0.479260775319107
19239533	36358	sql statement except	select      prodname, prodsupplier, prodcategory, prodinvqty from        product where       (prodinvqty  >= 5  or          prodsupplier = 'spaulding') order by    prodsupplier, prodinvqty; 	0.542163624410098
19239712	5340	how do i get all tags for a query?	select b.id,        alltags.*,        (select group_concat(t1.name order by t1.name separator ',')         from   tag t1) as alltags from   tagmap bt,        bookmark b,        tag t where  bt.tag_id = t.tag_id        and ( t.name = 'apple' )        and b.id = bt.bookmark_id group  by b.id 	0.000824373043348224
19240275	1413	mysql query returns string instead of numeric value	select case faulttype when faulttype='business' and faultseverity='fatal' then 1*4 else 0 end as rez from tbl_fault where product='das' and faultdistribution='missed' 	0.0200199906876273
19240539	6906	fetch zero if even there are no matching records	select    nvl(y."role", '0') "role",     case when y."role" is null then 0 else  count(*) end cnt  from(       select 'e3400' employee_number from dual   )x left join emp_details y on x.employee_number=y.employee_number group by "role" 	0
19241567	38361	sql find in string separated by commas	select * from table  where find_in_set(21, demo) > 0 	0.00059083664578691
19241817	25251	how to get orphans from a join table in mysql	select * from products p  left join product_categories pc on p.id=pc.product_id  where pc.product_id is null 	0.00170148676981884
19242540	27311	selecting from multiple tables vs join	select      fixture.* from     sport_team_player as team_player     cross join sport_team as team      inner join sport_fixture as fixture      on (team_player.team_id = fixture.team1_id or team_player.team_id = fixture.team2_id) where    team_player.team_id = team.team_id and team_player.player_id = '16' 	0.0288162843499848
19244574	25295	sql query to get multiple records in one row	select     ss.[desc],     (select '|' + us.field1     from xyz us     where us.[desc] = ss.[desc]     for xml path('')) [field1],     (select '|' + us.field2     from xyz us     where us.[desc] = ss.[desc]     for xml path('')) [field2],     (select '|' + us.field3     from xyz us     where us.[desc] = ss.[desc]     for xml path('')) [field3],     (select '|' + us.field4     from xyz us     where us.[desc] = ss.[desc]     for xml path('')) [field4] from xyz ss group by ss.[desc] order by 1 	6.64228639518497e-05
19245965	12936	sql displaying wrong records in or condition	select *   from workitems  where system.title like '%defect%'    and system.workitemtype in ('incident', 'bug')    and (errorclass = 3 or microsoft.vsts.common.priority = 3)        and customer = 'xyz'  order by system.workitemtype 	0.537690555729779
19246520	36784	how to combine a column name into mysql "like" clause	select * from t_cities as a   join temp_table as b   on a.name   like concat("%",b.token); 	0.0222262731026761
19247179	19186	mysql select union all value for date incorrect	select datamiele,          nomemiele,          codicemiele,          dataconfmiele,          '' as nomeconfmiele,          0 as  codiceconfmiele   from miele  union all  select  dataconfmiele as datamiele,           '' as nomemiele,           0 as codicemiele,           dataconfmiele,          nomeconfmiele,          codiceconfmiele   from confmiele 	0.0177603017015849
19248079	25085	how to filter rows based on data from multiple rows	select    device from (    select       device,      max(case when property = 'code'     then value else null end) as code,      max(case when property = 'old_code' then value else null end) as old_code    from inventory    group by device ) as t where code <> old_code; 	0
19248437	36283	how do i exclude some names from my top list	select * from entries where entries_id<>150 and entries_id<>92 order by votes desc 	8.91980265159204e-05
19248761	15594	join query by date and primary	select p.* from projects p left join projects_status_projects psp on (psp.project_id = p.id) where created_at = (select max(created_at)                      from projects_status_projects where                     project_id = p.id) 	0.146483680413221
19251823	3638	is it possible to let user update database only for 2 days?	select timestamp(adddate(:creation_date, :nb_days_to_add)) > timestamp(now()) as isdatevalid 	0.000572201218769098
19252403	17155	how to count over several relations in sql	select gp.id,        gp.name,        count(distinct c.id) from   grandparents gp        inner join parents p                on p.grandparent_id = gp.id        inner join children c                on c.parent_id = p.id group  by gp.id,           gp.name 	0.0908606931069555
19254885	39597	joining four tables and concatenating results of one - mysql	select bid, title, users.name, group_concat(tags.tag) from blogs inner join users on blogs.uid=users.uid inner join blogtags on blogs.bid=blogtags.bid inner join tags on tabs.tif=blogtags.bid group by bid, title, users.name 	0.00046165239620876
19256584	6853	sql sever fetch alias name for query	select  e1.empid, e1.empname, e2.empname from  emp e1 left outer join emp e2  on e1.mngrid = e2.empid 	0.28611338554835
19257493	1784	mysql get the sum of two columns	select   aaa,   bbb,   aaa+bbb ccc from (   select     sum(aaanum) aaa,     sum(bbbnum) bbb   from mytable ) x 	5.06975927259881e-05
19258647	33255	select most recent date	select     dbo.team.id, dbo.team.comment, max(dbo.team.date) latestdate, dbo.teamname.name, dbo.contacts.contactname  from       dbo.team  inner join dbo.teamname on dbo.team.id = dbo.teamname.id  inner join dbo.contacts on dbo.team.contactid = dbo.contacts.contactid    where      dbo.teamname.idstatus = 'active' group by   dbo.team.id, dbo.team.comment, dbo.teamname.name, dbo.contacts.contactname 	0.000334647475120955
19258749	28404	get list of column names from a firebird database table	select rdb$field_name from rdb$relation_fields where rdb$relation_name='your-table_name'; 	0
19264210	22051	show rows that have values occur a certain number of times	select distinct c.*, a.account_code from campaign c join account a on c.account_id = a.account_id where c.account_id in (   select account_id from campaign   group by account_id   having count(*) >= 2 ) 	0
19264427	28484	getting row number in sql	select @rownum:=@rownum + 1 as row_number,         t.* from (     < your original query goes here > ) t, (select @rownum := 0) r 	0.00287798274417688
19265155	3145	how to i find duplicate rows , and at the same time distinct?	select mobilenumber, count(*) from   (          select distinct mobilenumber, firstname, lastname          from   yourtable        ) as q group by        mobilenumber having count(*) > 1 	0
19265494	36390	sum of row values depending on the id	select cid, sum(adult) as adult, sum(child) as child  from sales  group by cid 	0
19265977	30717	complicated query - few tables with grouped columns	select     worker.name,     boxsize.name,     sum(case when boxcolor.id=0 then 1 else 0 end) as boxcolor_0,     sum(case when boxcolor.id=1 then 1 else 0 end) as boxcolor_1,     sum(case when boxcolor.id=2 then 1 else 0 end) as boxcolor_2     from     worker     join box         on worker.id=box.id_worker     join item         on item.id_box=box.id     join boxcolor         on boxcolor.id=item.id_boxcolor     join boxsize         on boxsize.id=item.id_boxsize group by     worker.name,     boxsize.name 	0.06582040062103
19266043	3583	select rows with id larger then lowest id from query	select logid, userid, updated, updatedbyid from users_updatelog where userid = 548 and logid > (select min(logid) from users_updatelog where userid = 548) order by updated desc 	0
19267493	37541	how get results where column type=image,null not empty?	select * from farm f where f.name=2 and f.colum=12 and f.image is not null 	0.0349748809078869
19268483	35161	sqlite select max query and sorting	select *  from table where product_price = (select max(product_price) from table) order by id desc limit 1 	0.262072641283444
19268534	32999	how to select @domain from email and match from another table with mysql	select      f.fo_name, f.fo_email, d.user_id, d.substr_email from     foundation f         inner join     (select          d_users.user_id,         right(user_email, (length(user_email) - locate('@', user_email) + 1)) as substr_email     from         d_users     where         d_users.user_id = '1') d on f.fo_email = d.substr_email; 	0
19269778	14442	how to show barchart value by year from mysql database using php	select year(date) as date, sum(amount) as amount from $tablename group by year(date) 	6.58517857366089e-05
19270150	13272	mysql regexp not matching with 2 commas	select numbers from table where numbers regexp '^[^,]+, $' 	0.0467797534253178
19270710	34920	sql server show non matching records	select  *  from #test a where exists (     select *      from      #test b     where a.name = b.name and (a.tag <> b.tag or a.checkval <> b.checkval) ) 	0.00100662346302143
19271036	24621	how can i get categories that share at least one product with another given category?	select distinct p2.categories_id from p2c p1 inner join p2c p2      on p1.products_id = p2.products_id and         p1.categories_id <> p2.categories_id where p1.categories_id = 1 	0
19272100	22911	loop in select query	select u.id,       u.name,       year(p.created_at) as create_year       sum(case when p.approved = 1 then p.ratings else 0 end) as approved_rating,       sum(case when p.approved = 0 then p.ratings else 0 end) as rejected_rating from users u left outer join posts p on p.user_id = u.id group by u.id, u.name, create_year 	0.488139016423596
19273383	12203	how to extract month and year from mysql?	select date_format(curdate(), '%b-%y') 	0
19273955	19071	left join, but exclude if joined table contains entry	select * from user where id not in (select iduser from group_members where idgroup = 1) 	0.00143598507549423
19274530	11513	extract month , calculate and put it in a column	select tipe,         extract(month from dateissued),         (select count(distinct( extract(month from dateissued) )) as totalmonth          from   qwe)  from   qwe  group  by tipe,            dateissued; 	0
19275550	22677	sum of grouped value	select from, to, sum(duration), count(*) from table group by from,to; 	0.00126449502701926
19276470	35423	mysql query show results based on multiple filters/tags	select p.*  from `photos` as p where p.`description` like "%test%" and    and exists       ( select 1 from `photostagsxref` as pt         inner join `photostags` as t on pt.`tagid` = t.`id`         where pt.`photoid` = p.`id`           and t.category = 'firstcattosearch'       )      and exists       ( select 1 from `photostagsxref` as pt         inner join `photostags` as t on pt.`tagid` = t.`id`         where pt.`photoid` = p.`id`           and t.category = 'secondcattosearch'       )      and exists       ( ...       )          ... 	0.00211735197027494
19276746	29926	fill db field with two datas (foreign keys)	select salutation  from anrede      inner join link_name_anrede on anrede.id = link_name_anrede.anrede_id where name_id = 3 	0
19280426	14901	create select distinct query with criteria of having the latest date	select status_point_designation, max(adj_date) as latestdate, count(status_point_designation) as observations from __all_adjustments group by status_point_designation; 	0.000121146698995439
19281492	28902	getting timeout errors with sqltransaction on same table	select 1 from ysl00 with (nolock) where serlnmbr = @slnr 	0.51778973924996
19282957	16291	get the minimum non zero value across multiple columns	select least(         nullif( number1, 0 ),          nullif( number2, 0 ),          nullif( number3, 0 ),          nullif( number4, 0 ))  from numbers 	0
19283527	27531	how to get all parameters in mssql stored procedure	select ordinal_position, parameter_name, data_type, parameter_mode  from information_schema.parameters where specific_name='proc_name' 	0.0453383576880019
19283949	23349	linking tables through sql and showing the row	select p.* from tpayments as p left join tjobs as j on p.job_no = j.job_no where j.location = 'qatar'; 	0.00133846364916028
19284311	20857	getting a sum of rows and retaining each row data	select     t.date,     round(sum(t.amount), 2) as total from invoice t group by t.date union all select     t.date,     round(t.amount, 2) from invoice t order by date 	0
19289820	4376	combining 2 queries into one query	select   * from     wp_booking_transaction where          date(launched) >= "2013-10-10"  and      date(launched) <= "2013-11-10" and      type = 2  and      student_id = 81569 and          ((action = 1 and status = 1) or (action in(20, 21) and status = 0)) order by launched desc 	0.00406350388286874
19291306	17081	top 1 not return null	select   (   select top 1 column5    from table2    where table2.column1id = 5   ) as column5 	0.052390533757561
19292165	929	how can i select the first time a number shows up in more than one column in mysql?	select id, group_concat(city order by city) cities from (     select city, min(id) id     from (         select origin city, min(id) id         from flights         group by city         union         select destination city, min(id) id         from flights         group by city) u     group by city) x group by id 	0
19292429	3519	compare values in a column and find if there is an increment	select  monthid,     case when sales < (select sales from testtable where monthid = tt.monthid - 1) then 'decremented' else 'incremented' end from testtable tt 	0.000115528167175839
19293535	39902	finding dublicates in table with different sql queries yields different results	select a.number, count(*) from (select * from numbers as a inner join numbers  as b     on a.number = b.number  and a.id < b.id) c group by a.number 	0.00350524273944734
19293749	1454	getting last row of each group in mysql	select messages.id, messages.body, messages.sender, sub1.mid, sub1.conc from messages inner join message_receivers  on messages.id = message_receivers.message_id inner join (     select          if(messages.sender>message_receivers.receiver,             concat_ws(',',messages.sender,message_receivers.receiver),              concat_ws(',',message_receivers.receiver,messages.sender)) as conc,         max(messages.id) as mid     from messages     join message_receivers      on messages.id = message_receivers.message_id     where message_receivers.receiver = '4'      or messages.sender = '4'     group by conc ) sub1 on sub1.mid = messages.id and sub1.conc = if(messages.sender>message_receivers.receiver,             concat_ws(',',messages.sender,message_receivers.receiver),              concat_ws(',',message_receivers.receiver,messages.sender)) 	0
19293920	28351	mysql check the value of the next row	select id,      date_add(datetime, interval 5 * (id -          (select min(id) from mytable t2 where t2.datetime = t1.datetime)     ) minute) as datetime,     data ) from mytable t1 	0
19294023	9555	how do i combine these 3 queries into one mysql query?	select date(`date`),        count(`page`) as indexcount,         sum(`page` = 'index.php') as idx_count,         sum(`page` <> 'index.php') as not_idx_count from `tracking` where `date` between date_add(now(),interval -30 day) and now() group by date(`date`) 	0.00608238249769297
19294313	24013	combine separate sql queries together filling in the blanks	select  mbrid, sum(messagecount), sum(notificationcount), sum(requestcount) from    (             select mbrid, messagecount, 0 as notificationcount, 0 as requestcount             from tblmessages             where messagecount > 0             union             select mbrid, 0 as messagecount, notificationcount, 0 as requestcount             from tblnotifications             where notificationcount > 0             union             select mbrid, 0 as messagecount, 0 as notificationcount, requestcount             from tblrequests             where requestcount > 0         ) temptable group by mbrid 	0.0066263161269338
19297406	33617	getting every record in one-to-many relationship in one row	select      s.sessionid         ,   a1.answerdetail as answerdetail1         ,   a1.iscorrect as iscorrect1         ,   a2.answerdetail as answerdetail2         ,   a2.iscorrect as iscorrect2         ,   a3.answerdetail as answerdetail2         ,   a3.iscorrect as iscorrect2 from        sessions as s inner join  sessionanswers as sa1          on  sa1.sessionid = s.sessionid         and sa1.questionnumber = 1 inner join  answers as a1         on  a.answerid = sa1.answerid inner join  sessionanswers as sa2          on  sa2.sessionid = s.sessionid          and sa2.questionnumber = 2 inner join  answers as a2         on a.answerid = sa2.answerid inner join  sessionanswers as sa3          on  sa3.sessionid = s.sessionid          and sa3.questionnumber = 3 inner join  answers as a3          on  a.answerid = sa3.answerid 	0
19299369	10295	select rows where field in joining table not same value in every row	select cake_id from tbl_cake_piece group by cake_id having count(distinct share) > 1 	0
19299750	18888	how to get results from one table where id from another table is not in the one table	select id  from attny_practice_groups g where not exists (select 1 from attorneys where atty_id = g.atty_id) 	0
19300918	8384	query to identify which browsers people are using	select date(logintimestamp) as logindate,        group_concat(distinct browser) as useragents from adminlogins  group by logindate 	0.011924601524564
19301947	31586	mysql table identifiers in insert statements	select p.rid, o.userid from {$this->dbtable}_orders as o inner join {$this->dbtable}_product as p on p.productid = o.productid and p.status =   'active' where o.oid = %d and o.transaction_id = %s limit 1 	0.354634653934412
19302385	5106	query that groups by a substring, returning the substring result and ordering by aggregates on the group	select substring(textdata,1,25),     count(*) as howmany,     sum(duration) as totaltime  from [tmp].[dbo].[tmp2]  group by substring(textdata,1,25) order by 3  	0.0455221290487623
19304873	24222	selecting two columns in subquery	select   office,   count(office) as tot_part,   sum(completion_status in ('started', 'complete')) as total_resp from trespondent  where completion_status <> 'new'  group by office  order by office 	0.00412416127040503
19305880	36655	select all values in column that don't contain the character in another	select * from mytable where instr(mystring, mychar) <> 0 	0
19305905	11758	how to list just people managers?	select *  from yourtable  where gnumber in (     select distinct(managergnumber)      from yourtable ); 	0.00638993856548841
19306255	25245	how to find number of references given another table in sql?	select acc1.acc_id, acc2.acc_id as reference  from accidents acc1 inner join accidents acct2 on acc1.pid = acc2.pid and acc1.acc_id <> acc2.acc_id inner join people on people.pid = acc1.pid where people.phone <> "" 	0
19307028	27611	joining tables in sql server 2008	select s.namecolumn, s.any_other_column, astf.any_other_column, .... so on from staff s inner join [assigned staff] astf on s.staffid = astf.staffid 	0.355253450045184
19307455	15523	converting varchars into two points decimal value by using sql	select      cast(         concat(substring(test_value,1, length(test_value) -2),                '.',                substring(test_value, length(test_value) -1, 1))     as decimal(7,1)) from test where substring(test_value, length(test_value)) = 'a'  || substring(test_value, length(test_value)) = 'h' 	0.00378511573934384
19308949	33769	sql select ids that is not on another table, unless that register has certain column data	select        o.id     from        order o           join order_payment op              on o.entity_id = op.parent_id            and op.method in ('paymethod_a', 'paymethod_b', 'paymethod_c')           left join payment_method pm             on o.id = pm.order_id    where           o.state='new'        and o.created_at between '2013-05-14' and '2013-10-11 00:19:09'        and ( pm.order_id is null            or pm.status = 0 ) 	0
19309084	16690	sql finding two duplicated strings	select s.* from stackoverflow as s inner join (select stack1, count(*) from stackoverflow group by stack1 having count(*) > 1) as dups on s.stack1 = dups.stack1 	0.00382875217607475
19309098	29717	get a column from each table	select sum(q.sales), sum(q.expense), sum(q.sales)-sum(q.expense) as winnings from (     select sum(sales.total) as sales, 0 as expense from sales         union all     select 0 as sales, sum(expenses.costs) as expense from expenses ) as q 	0
19309246	38859	comparing 2 different columns of 2 different rows in oracle 11g	select    t.* from   test t   inner join test t2     on t.uid1 = t2.uid2         and t.uid2 = t2.uid1 where   t.uid1 < t2.uid1; 	0
19309278	13318	percent on a count sql	select  attribute       , count(attribute)*1.0 / sum(count(*)) over() * 100 as topissues from    audits  where month(transactiondate) = month(getdate()) group by attribute order by count(attribute) desc 	0.0196876760138074
19310604	34646	oracle sql - naming the result of a join	select info.* from (select * from pc natural join product) info; 	0.227170699658038
19310759	19349	how should i get the dummy columns using the query in sql server (like 'select name from dual' in oracle)?	select paytype = 'pdc' union all select paytype = 'nopdc' union all select paytype = 'ecs' 	0.025974935871242
19311220	29299	sql date in format mmmyy	select replace(right(convert(varchar(9), getdate(), 6), 6), ' ', '') as [mmyy] 	0.13299787949201
19311432	12250	use unix timestamp as a condition in mysql	select *   from table  where date > unix_timestamp() 	0.0353772328112025
19312185	8969	sql query to find values based on selected date, but will find the latest value if there's no value on the selected date	select a.user_id, a.product_code, a.uom, max(a.inventory_date), a.account_id, a.branch_id, (   select beginning_inventory from test    where user_id = a.user_id   and product_code = a.product_code   and uom = a.uom   and inventory_date = max(a.inventory_date)   and account_id = a.account_id   and branch_id = a.branch_id ) as beginning_inventory from test as a where a.inventory_date <= '2013-09-29' group by a.user_id, a.product_code, a.uom, a.account_id, a.branch_id 	0
19312686	30677	return authors by latest published book + authors with no published books	select distinct     authorname,      booktitle,      datepublished,      author  from(     select          authors.authorname,          books.booktitle,          books.datepublished,          books.author,          row_number() over (partition by authors.authorid order by datepublished desc) rnum     from authors left outer join books on authors.authorid = books.author )x where rnum=1 	0
19315293	28571	can get some counts in one sql query?	select count(*) as total_count,        sum(status = 'open') as status_open_count,        sum(status = 'close') as status_close_count,        sum(status = 'pause') as status_pause_count from table 	0.00551283818968839
19317041	10975	sql count on large recordsets with conditions	select count(*) from table where communityid=123 	0.494691543931332
19317123	20767	query to display the only the most recent message of each thread	select m.message_id m_id       , m.sender_id s_id       , m.thread_id t_id       , m.subject       , m.message       , m.date_sent       , s.firstname sender       , r.firstname recipient    from message m    join message_recipient n      on n.message_id = m.message_id    join user_public_info s      on s.user_public_info_id = m.sender_id    join user_public_info r      on r.user_public_info_id = n.recipient_id    join (select thread_id, max(max_message_id) max_message_id from message group by thread_id)x      on x.thread_id = m.thread_id and x.max_message_id = m.message_id; 	0
19317676	6205	how to fetch all the variants, of each products, with out fetching product name multiple time	select a.product_name, group_concat(c.variant_name) from table_products a inner join table_product_varients b on a.product_id = b.product_id inner join table_varients c on b.variant_id = c.variant_id group by a.product_name 	0
19317928	16174	select rows with the same count in a column from a table	select name from person where ssn <> 1 group by name having count(petname) = (select count(petname) from person where ssn='1') 	0
19318765	41237	sql join issues: third table's fields not displaying in excel but in sql	select cast(cust_ratioid.detail_des as varchar(8000)) as details_des 	0.758492018996678
19319249	16661	get maximum price from a group by in sql server	select *  from submissions s inner join livedata l      on s.invoicenumber = l.invoicenumber      and l.part_price =          (select max(part_price)          from livedata          where invoicenumber = l.invoicenumber) 	9.35818489659421e-05
19319266	38215	prevent ssrs filter criteria from removing results with a blank field	select name as territory from            territory union select 'unknown' 	0.00284740711035541
19320375	21117	how to select and join on a query with a table	select * from     (select 'source1' source from dual      union select 'source2' from dual      union select 'source3' from dual      union select 'source4' from dual      ) s     cross join (       select 'o' status from dual       union select 'c' from dual      ) x     cross join (       select       to_date('09/30/2013','mm/dd/yyyy') - 1 + level dt       from dual       connect by       level <= ( to_date('10/05/2013','mm/dd/yyyy')            - to_date('09/30/2013','mm/dd/yyyy')) + 1      ) d left join      mytable y on y.err_sts_cd = x.status 	0.0585053898065881
19320634	15139	query doesn't select the different value	select distinct(id_user)  from post_comment  where id_user <> 1 and id_user <> 5 and id_post = 2 	0.011179609348015
19320953	10403	mysql join two queries	select opr,         count(case when field = 'yes' then 1 end) as number_of_transactions,        max(case when field = 'no' then category end) as category from table  group by opr ; 	0.233590929089046
19322076	17160	sql get the 5 last items inserted based on 2 table join	select pr.*,  (   select pm.image from project_media pm   where pr.project_id = pm.project_id   order by pm.project_media_id desc   limit 1 ) as image from  (   select p.project_id, p.completed    from project p   order by p.completed desc   limit 5 ) as pr 	0
19322322	27917	sql group by on created column?	select     detail.[datetime],     status.[your human readable name],     sum(detail.[rawstatus]) as clients from     [solarwindsorion].[dbo].[custompollerstatistics_detail]         as detail     inner join [solarwindsorion].[dbo].[custompollerstatus]         as status         on left(detail.[rowid], len(detail.[rowid]) - 2) = status.[rowid] where     detail.[custompollerassignmentid] = '6c4e621b-a7d3-439c-8402-d692be67743a' group by     detail.[datetime],     status.[your human readable name] 	0.0753585315879075
19324067	17102	sql count of return users	select count(distinct user_id) from (   select   user_id   from     t1   group by user_id, action_type   having   count(*) > 1 ) t 	0.00524253795153571
19324685	6975	no rows returned using count in having clause	select file_name from mytable where per_id in (     select per_id from mytable group by per_id having count(*) > 1 ) 	0.0729507566978018
19325666	35762	inner subquery need to check in the same group but not across all groups	select groupid,count(distinct groupprogramyearparticipantid)as [childaddedcurrent]   from #temp1  where (monthflag = 0) and (participanttypename = 'child')   and (groupprogramyearparticipantid not in  (select distinct groupprogramyearparticipantid  from #temp1 t where (t.monthflag = 1) and (t.participanttypename = 'child') and t.groupid = groupid))  group by groupid 	0.00565099514651151
19325862	20050	mysql ordering by categorizing number range, then alphabetically in individual categories	select case when amount > 1000 then 4             when amount > 500 then 3             when amount > 150 then 2             else 1        end tier,        team, amount from table order by tier desc, team 	7.16437978594681e-05
19327390	22481	how to count total comment?	select  p.post_id,count(*) 'comment_count' from fss_post p left join fss_comment c on p.post_id = c.post_id group by p.post_id 	0.00402470155461872
19327817	18411	mysql - select last value by day for the last 7 days using multiple tables	select p.name,        s.scount,        s.ts from profiledata p inner join users u on u.profileid = p.profileid inner join stats s on s.profileid = p.profileid inner join (select max(ts) as maxts, profileid             from stats             where date(stats.ts) >= date(date_sub(now(), interval 7 day))             group by profileid, date(ts)) as mx          on s.profileid = mx.profileid and mx.maxts = s.ts where u.userid = 1337 	0
19330034	15451	group rows based on id and then return the row with the lowest date per id grouping	select id, user, date from originaldata od where date = (select min(date)                from originaldate od1                where od.id = od1.id) 	0
19330913	18963	i need to find the lead time/no.of days it took from bill sent to payment received from the table	select account_id,date_bill,date_pay,datediff(day,date_bill,date_pay) 'lead time'  from     (         select account_id,             (select transactiondate from t_account_details x where actiontaken='billsent' and x.account_id = account_id) date_bill,             (select transactiondate from t_account_details x where actiontaken='paymentreceived' and x.account_id = account_id) date_pay         from t_account_details     ) t order by account_id 	0
19330951	12089	selecting a column as a different column name with a condition	select e.id emp_id, e.name emap_name, e.role emp_role, m.name manager_name from employees_info e inner join employees_info m on e.managerid = m.id where e.name='john' 	0.000100672372756632
19331409	11700	postgresql multiple count() where conditions in a single query	select a.type, count(b.type)  from (values ('fruit'), ('vegtable'), ('other'), ('misc')) as a(type)     left outer join bag as b on b.type = a.type group by a.type 	0.110528410467226
19332137	21933	how can i query all records in mysql where field is not empty or null?	select * from `a` where `products_name` is not null and `products_name` != ''; 	0.0320368715645625
19332722	40632	group by clause to get comma-separated values in sqlite	select group_concat(eng), hindi from enghindi group by hindi; 	0.0434687247864263
19333476	11778	obtain substring in sql	select (regexp_split_to_array(registrationno, '\.'))[3] from subscriber 	0.209065089877404
19333652	21281	mysql product filters with multiple options	select `p`.`id`, `p`.`name` from   `products` `p` where   `p`.`id` in (select     `ae`.`product_id`                      from       `attributes_entity` `ae`                      inner join `attributes` `a` on `ae`.`attribute_id`=`a`.`id`                      inner join `attributes_values` `av` on `ae`.`value_id`=`av`.`id`                      where       ((`a`.`name`='samsung' and `av`.`value`='samsung') or                                   (`a`.`name`='smartv' and `av`.`value`='yes'))                      having count(*) >= 2                      ); 	0.213053534542507
19333734	39426	datetime to year + week in sql	select (cast(year(yourdatetimecolumn) as varchar(4))+'-'+cast(datepart(wk,yourdatetimecolumn) as varchar(2))) weekstamp from yourtablename 	0.000541310189389925
19335014	16703	sql query multiple columns distinct on one column	select     main_table.housenumber,     main_table.streetname,     max(main_table.rent)     houses.houseid,     houses.path,     houses.rooms from main_table left join houses on main_table.housenumber = houses.housenumber and main_table.streetname = houses.streetname group by     main_table.housenumber,     main_table.streetname,     houses.houseid,     houses.path,     houses.rooms 	0.00069989070125065
19335787	9608	mysql select with condition preference	select * from user  where surname='jack'    or  school='st'    or college='austin'    or city='mit' order by (   if(surname='jack', 1, 0)   + if(school='st', 1, 0)   + if(college='austin' , 1, 0)   + if(city='mit', 1, 0) ) desc; 	0.460063017109284
19339876	11466	returning field name when using max and count queries	select `variabletype `,        count(`variabletype `) as `value_occurrence`  from   `my_table` group by `value` order by `value_occurrence` desc limit    1; 	0.0504058641098032
19341003	24958	mysql: how to select data from a column in another table	select * from (     select     items.id,     items.name as item_name,     items.tobuy,     items.list_id,     items.note,     items.unit,     nullif(packages.ppu, 0) as mppu,     packages.price as mprice,     items._deleted   from     items   inner join     lists on lists.id = items.list_id     and lists.user_id = 1    left join     packages on packages.item_id = items.id   where     items._deleted = '0'   order by     tobuy desc,     item_name,     ifnull(mppu, 999999)) x group by   x.id order by   tobuy desc,   item_name 	0
19341436	27845	tsql query to filter configuration dates list	select * from configurationdate where year > 2012 or ( year = 2012 and month >= 9 ) order by year,month asc 	0.0180061709025777
19341742	10696	retrieve mysql data that doesn't contain number	select list_col from list_table where list_col not regexp '[0-9]' 	0.000803090885647413
19342893	22897	how do i search from various tables with a common unique key and display respective values from each table	select a.case_name, a.case_type, a.case_date,         b.bill_id, b.bill_name, b.bill_date,         c.staff_id, c.report_id, c.report_name,         d.hh_id, d.hh_name, d.hh_type from tablea a join tableb b on a.file_id = b.file_id join tablec c on a.file_id = c.file_id join tabled d on a.file_id = d.file_id 	0
19345622	30392	mysql inner join where table2 child_id is like table2 id	select      t1.id img_id, t1.nav_id img_nav_id, t1.name img_name, t1.img_title img_title, t1.img_text img_text,     t2.id nav_id,t2.parent_id nav_parent_id, t2.name nav_name, t2.directlink nav_directlink,     t3.name nav_parent_name from images t1 inner join navigation t2   on t2.id=t1.nav_id inner join navigation t3     on t2.parent_id = t3.id order by rand() limit 0,101 	0.794071951939225
19345797	23849	how to measure accurate time offset from sql server?	select 1 	0.380220286721225
19347192	4478	php count and add each values from mysql table row	select sum(visits)as visitcounts from (    select visits from tablename ) v 	0
19348155	13453	group by messages mysql	select mostrecent.mainperson as mainperson   , mostrecent.otherperson as otherperson   , mostrecent.sent as sent   , if(wp_bp_my_chat.recd = 0, 'unread','read') as status from wp_bp_my_chat join (     select 'user_1' as mainperson        , if(msgs.`from` = 'user_1',msgs.to, msgs.`from`) as otherperson        , max(msgs.sent) as sent     from wp_bp_my_chat as msgs     where msgs.`from` = 'user_1' or msgs.`to` = 'users_1'     group by mainperson, otherperson) as mostrecent   on (wp_bp_my_chat.`from` = mostrecent.mainperson or wp_bp_my_chat.`to` = mostrecent.mainperson)     and (wp_bp_my_chat.`from` = mostrecent.otherperson or wp_bp_my_chat.`to` = mostrecent.otherperson)     and mostrecent.sent = wp_bp_my_chat.sent order by sent desc 	0.221429513276729
19350014	31016	json parsing in mysql while selecting	select count(*) from `items` where `fields` like '%"id":"2","value":"2"%' 	0.111408747472194
19351070	18260	sql calculate week number from a date column	select reportno,reportname,to_char(to_date(load_date,'yyyymmdd'),'ww') from facts 	0
19352715	11584	find matching row based on multiple columns (sequence of columns doesn't matter)	select id,name,  case when itemid1 is not null then  convert(varchar(10), itemid1) + ','  else '' end  +  case when itemid2 is not null then  convert(varchar(10), itemid2) + ',' else  ''  end  +  case when itemid3 is not null then  convert(varchar(10), itemid3) + ','  else ''  end +  case when itemid4 is not null then  convert(varchar(10), itemid4) + ','  else '' end    as itemid from emp 	0
19353556	14019	select 2 concatenated columns in mysql disregarding all spaces	select concat(fname, ' ', lname)       from people  where concat(replace(fname, ' ', ''),  replace(lname, ' ', '')) like "%johncraigdesmith%" 	7.8557786396443e-05
19356061	1478	exporting large amount of data into csv in codeigniter	select id, client, project, task, description, time, date into outfile '/path/to/file.csv' fields terminated by ',' optionally enclosed by '"' lines terminated by '\n' from ts 	0.000823895444525019
19356150	25869	sum time in varchar/nvarchar data type field	select convert(decimal(18, 2), convert(decimal(18, 2), ppt.hour) + convert(decimal(18, 2), convert(decimal(18, 2), ppt.minute/ 60)) + convert(decimal(18, 2), convert(decimal(18, 2), ppt.second / 3600))) as hours, ppt.[column] from (select sum(convert(decimal(2),left([column], 2))) as hour, sum(convert(decimal(2), left(right([column], 5), 2))) as minute, sum(convert(decimal(2), right([column], 2))) as second, [column] from [table] group by [column]) as ppt 	0.00774420581403778
19356629	12560	sub query(select top1 order bydesc) not selecting 1 but returning all records in that category	select  * from customerstable ct inner join cellphonetables celltbl on ct.customerid =    celltbl.customerid  inner join maintainancetable mt on mt.customerid = ct.customerid and mt.checkdate in       (select top(1) checkdate                            from   maintainancetable                            where (customerid = ct.customerid)                            order by mt.checkdate desc) 	0.0003071631677787
19356903	33089	sql row value depending on other row value	select   t1.name,  case when t1.groupid is null then '' else   (select q.text from    (select rownum as counter,name,text from tablename where groupid=1)q   where    q.counter = (select max(rownum) from tablename t2 where groupid=1 and   t2.name<=t1.name))end as text,  t1.groupid  from   tablename t1  where   (t1.groupid<>1 or t1.groupid is null); 	0
19357614	31735	oracle query to fetch the last 4 records from the table	select * from ( select * from tablename order by id desc ) where rownum <= 4; 	0
19358092	15678	querying the same table for a list of databases in ms sql server	select name into #versions from sys.databases where name like 'test%' declare @sql as varchar(max) = '' select @sql = @sql + 'insert into sometable select top 1 * from ' + name + '..sourcetable order by somedate desc; ' from #versions exec (@sql) drop table #versions 	0.000532703822813956
19359822	36514	aggregate to count values equal to a constant	select       count(case when col='x' then 1 end) as xcount,       count(case when col='y' then 1 end) as ycount,      count(case when col='z' then 1 end) as zcount   from table 	0.0166671545374903
19359962	22275	sql how to pivot 6nf tables	select     d1.dim1, d2.dim2,     sum(case when m.month = 1 then c.cost end) as [1],     sum(case when m.month = 2 then c.cost end) as [2],     sum(case when m.month = 3 then c.cost end) as [3],     sum(case when m.month = 4 then c.cost end) as [4],     sum(case when m.month = 5 then c.cost end) as [5],     sum(case when m.month = 6 then c.cost end) as [5],     sum(case when m.month = 7 then c.cost end) as [7],     sum(case when m.month = 8 then c.cost end) as [8],     sum(case when m.month = 9 then c.cost end) as [9],     sum(case when m.month = 10 then c.cost end) as [10],     sum(case when m.month = 11 then c.cost end) as [11],     sum(case when m.month = 12 then c.cost end) as [12] from entrycost as c     left outer join entrymonth as m on m.entryid = c.entryid     left outer join entrydim1 as d1 on d1.entryid = c.entryid     left outer join entrydim2 as d2 on d2.entryid = c.entryid group by d1.dim1, d2.dim2 	0.45503572841071
19361452	28554	how to select just the row in the second table?	select t1.date, case when t3.idclient is not null then t3.value else t2.value end as value from table1 t1 inner join table2 t2 on t1.idclient = t2.idclient inner join table3 t3 on t1.idclient = t3.idclient 	0
19362969	198	tsql: standard deviation of days between transactions	select id, stdev(datediff ( dd , '1/1/1900' , enddate )) from table  group by id  with dateorder as  (select [fieldid], [value],          row_number() over (partition by [fieldid] order by [value]) as row    from [docsvdate]) select do1.fieldid, stdev(datediff(dd, do1.value, do2.value))   from dateorder as do1   join dateorder as do2     on do1.fieldid = do2.fieldid     and do2.row = do1.row + 1  group by do1.fieldid 	0.00215287114837931
19363551	24721	return row counts for field that appears more than x times	select statecode, count(*) as statecodecount from zipcodeterritory group by statecode having count(*) > 300 	0
19364751	20567	divide the value of each row by the sum of this column	select investmentname, weight / (select sum(weight) from records) as adjweight from records; 	0
19365268	3061	group the rows and display all values in groups	select * from [tbl_name] order by sub_id, score 	0
19365347	30302	mysql joining three tables for posts, user info, and ratings	select post_id,coalesce(score, 0) score  from posts  left join ratings on postid=post_id  left join users on userid=posts.user_id  group by post_id order by coalesce(score, 0) desc  limit 10 	0.000106844677900535
19366048	35166	how do i take data from one table, and overwrite it from another table, with a select statement in mysql?	select     i.barcode,     ifnull(c.title, i.title) as title,     i.runtime,     i.username from     movieitems i          left join movieitems_custom c          on i.barcode = c.barcode and i.username = c.username 	0
19366057	13876	mysql multiple duplicate rows - return only one	select song, artist, tracknum, min(trackid) as first_track_id from wp_tracks group by song, artist, tracknum 	0
19367090	39930	assign column name of max value to row based on comparison across columns	select     t.[oid], t.[hos1], t.[hos2], t.[hos3],     c.maxv, c.maxh from table1 as t     outer apply (         select top 1 *         from (values            (hos1, 'hos1'),            (hos2, 'hos2'),            (hos3, 'hos3')         ) as a(maxv, maxh)         order by a.maxh desc     ) as c 	0
19367479	10618	using max function in oracle to find a record	select e.name,e.ssn,count(*) from employee e  inner join car c on e.ssn = c.owner group by e.name,e.ssn 	0.0198886855147981
19367583	31207	how to get top 5 amounts from mysql table?	select code, amount from table where id > 1 order by amount desc limit 0, 5; 	0
19367720	7226	how can i sum two rows from two different tables?	select     s.id as showroom_id,     sal.amount as total_salary,     exp.amount as total_expense from showroom as s     left outer join (         select sum(t.amount) as salary, t.showroom_id         from staff_salary as t         group by t.showroom_id    ) as sal on sal.showroom_id = s.id     left outer join (         select sum(t.amount) as salary, t.showroom_id         from expense as t         group by t.showroom_id    ) as exp on exp.showroom_id = s.id 	0
19368635	36049	mysql limit using match against	select  * from  ( select videos.id_video as idvideo, 1 as idcanal, match (nombre_prog, programas.descrip_larga) against ('escuela') as relevancia from videos inner join programas_videos on videos.id_video = programas_videos.id_video inner join programas on programas_videos.id_prog = programas.id_prog where match (nombre_prog, programas.descrip_larga) against ('escuela' in boolean mode) order by relevancia desc  ) as x limit 5,5 	0.236246843367213
19369938	4894	multiple sql counts into single result set	select (select count(id) from producta_t where created between '<date>' and '<date>' and productstatus = "<successful>") as counta (select count(id) from productb_t where created between '<date>' and '<date>' and productstatus = "<successful>") as countb (select count(id) from productc_t where created between '<date>' and '<date>' and productstatus = "<successful>") as countc 	0.00269181359991999
19370588	27650	sql to get user's first picture and most common item	select     u.id_user,     u.name,     (select p.filename from user_picture as p where p.id_user=u.id_user and ord=1) as userpicture,     (select max(s.id_sticker) from user_sticker as s where s.id_user_to=u.id_user) as userstickerid from user as u where u.id_user = $$$$ 	0
19372687	18496	find the most popular minor of student in cs	select stuid.dno, count (*) from stuid inner join student on stuid.stuid = student.stuid  where student.major in (550, 600) group by stuid.dno order by count (*) desc 	0.000151574551546368
19373112	28728	how to find similar binary string in mysql database?	select * from my_table order by bit_count(cast(conv(record,2,10) as unsigned integer) ^ cast(b'11...0' as unsigned integer)) limit 1; 	0.00409835185546491
19373420	37333	ordering two columns ascending php mysql sequencing	select * from torder order by least(col1, col2), greatest(col1, col2) 	0.00331495955830074
19374536	20900	get count and sum on multiple conditions in a single sql statement	select    count(*),    sum(n.credit) as totalcredit,   sum(case when q.question_level = 1 then n.credit else 0 end) as level1_sum,   sum(case when q.question_level = 2 then n.credit else 0 end) as level2_sum,   sum(case when q.question_level = 3 then n.credit else 0 end) as level3_sum,   sum(q.question_level = 1) as level1_count,   sum(q.question_level = 2) as level2_count,   sum(q.question_level = 3) as level3_count from    notifications n  left join questions q    on q.id = n.question_id where    n.user_id = u_id 	0.00283741695054817
19375225	13014	retrieve matching rows using join	select id, name,   count(case when snumber = 123 then 1 end) total,   count(case when snumber <> 123 then 1 end) othertotal from t group by id, name order by id 	0.00156469682002173
19375672	35440	fetch distinct values of two mysql tables	select userid from user where userid not in (select userid from network); 	6.50658724792506e-05
19375833	19701	using sql case in a union select to combine two tables with no like fields	select 'authors' as [type]        , city,state        from authors union  select 'publishers' as [type]        , city,state        from publishers 	0.0798739299471494
19377153	26552	mysql - ordering by number of times value found within 'in' statement	select a.id  from   transactions a where  a.metaid in (3,4,5,6)  group  by a.id  order  by count(a.metaid); 	0.000591535323475711
19377679	32551	select from oracle table where field like p & l	select * from student_master_table where stu_middle_name like '%p &'||' l%'; 	0.164788252811057
19378299	38827	sql query to filter many-to-many	select user_id from users_groups ug where group_id in (1,2,3) group by user_id having count(distinct group_id) = 3 	0.536331846690105
19378969	33648	how can i select all data from table sales for user	select user,         sum(amount_sales) as sum_sales,         sum(total) as sum_totals from table group by user 	0
19379418	16156	mysql - user's total points count in different ranges	select     case      when points <= 50 then '0-50'      when points between 51 and 100 then '51-100'      when points between 101 and 150 then '101-150'      else '> 150'    end as `range`    ,count(*) as `count`    ,case      when points <= 50 then 1      when points between 51 and 100 then 2      when points between 101 and 150 then 3      else 4    end as `sort` from (      select user_id, sum(points) as points      from tbl      group by user_id      ) as summary group by `range`, `sort` 	0
19381513	24809	sql splitting up email data by comma separated email address	select a.name,        split.a.value('.', 'varchar(100)') as cvs   from   (     select name,            cast ('<m>' + replace(email, ',', '</m><m>') + '</m>' as xml) as cvs       from  #temp  ) as a cross apply cvs.nodes ('/m') as split(a) 	0.000217029534282277
19383150	6082	sqlite can't find a way to avoid cartesian product	select name,        (select sum(warengruppevk.netto)         from kunde         join pbsrow on kunde.pk = pbsrow.kunde         join warengruppevk on pbsrow.pk = warengruppevk.pbsrow         where kunde.admitarbeiter = adm.pk           and pbsrow.jahr = 2012        ) as vj_netto,        (select sum(pbsrow.sollfracht)         from kunde         join pbsrow on kunde.pk = pbsrow.kunde         where kunde.admitarbeiter = adm.pk           and pbsrow.jahr = 2012        ) as vj_sollfracht        (select sum(warengruppevk.netto)         from kunde         join pbsrow on kunde.pk = pbsrow.kunde         join warengruppevk on pbsrow.pk = warengruppevk.pbsrow         where kunde.admitarbeiter = adm.pk           and pbsrow.jahr = 2013        ) as j_netto,        (select sum(pbsrow.sollfracht)         from kunde         join pbsrow on kunde.pk = pbsrow.kunde         where kunde.admitarbeiter = adm.pk           and pbsrow.jahr = 2013        ) as j_sollfracht from adm 	0.734132992572619
19384628	38845	results from two tables	select a,b,c from table1 [where condition] union select a,b,c from table2 [where condition] 	0.00276588843298644
19385324	2700	all fields plus additional ones in sql statement	select   thc_main.*,   to_char(thc_main.ourstart, 'yyyy-mm-dd hh24:mi') as som,   to_char(thc_main.ourend, 'yyyy-mm-dd hh24:mi') as eom from ouruser.thc_main 	0.0280177935883524
19385738	21237	distinguish duplicates in a foreach loop from sql	select j.*, c.appl_count from jp_applications j     inner join (select user_id, count(1) as appl_count from jp_applications             where application_status = "awaiting response"             group by user_id) c on c.user_id = j.user_id where j.application_status = "awaiting response" order by j.job_id 	0.23623064288984
19387066	1694	same value is shown only one, how make it?	select   case r when 1 then p.id end as id,   case r when 1 then name end as name,   case r when 1 then surname end as surname,   description,   contact from   person p, (     select       id,       row_number() over (partition by id) as r,       description,       contact     from       contact   ) c where p.id = c.id; 	0.000539040880777283
19387214	9997	sql asp.net - convert nvarchar to int if numeric	select *  from [peopletable] p where cast(p.[dbo] as int) = 32 and isnumeric(p.[dbo]) = 1 	0.558922454379097
19388295	34839	where clause with information that might not exists	select * from #temp t join log l   on t.phone = l.phone where (l.changedate < = @date and  l.status = 'added')       and (    (l.changedate > @date and l.status = 'removed')   or not exists(        select 'removed'        from log l2        where l2.phone = t.phone        and l2.changedate > @date and l2.status = 'removed'     )   ) 	0.779035684952332
19388771	17004	set default to 0 where no default exists in mysql alter table	select concat('alter table `', table_name,    '` alter column `', column_name, '` set default = 0;') as _sql  from information_schema.columns where column_default is null  and (table_schema, table_name) = ('mydatabase', 'mytable'); 	0.0154333420613418
19388993	27291	how to process a select on a multiple row returning select	select * from `users` where uid in (select uid from `users_roles` where rid= 6 ) 	0.00204611688995419
19390086	17788	sql join two rows in one by an identificator. query	select t.id, max(t.prov1), max(t.prov2)  from mytable t group by t.id 	0.0120241543281212
19390581	598	counting fields with same value	select vt.*, vtij.nome_count from view_teste vt     inner join (select nome, count(1) as nome_count from view_teste         where [additional_filter_conditions]             group by nome) vtij on vtij.nome = vt.nome where [additional_filter_conditions] 	0.000801021924600547
19390817	38508	count only the id's which are not counted in earlier group	select groupid, count(distinct groupparticipantid) as cnt  from #temp1 a where a.groupparticipantid not in ( select groupparticipantid    from #temp1 b   where a.groupid > b.groupid ) group by groupid 	4.67246239373348e-05
19391043	41037	mysql query to display one record before today's date	select * from games where gamedate < now() order by gamedate desc limit 1 	0
19392736	21280	selecting partially matching data	select * from ( select name as 'asset' from table1 where name not like '%.%' ) as a  join  ( select name as 'files' from table1 where name like '%.%' ) as b  on a.asset = substring(b.files, 1, instr(b.files, '.') - 1) 	0.00162055940090107
19392840	12302	convert oracle string to date wtih timezone	select to_timestamp_tz('2013-10-15t17:18:28-06:00'                       ,'yyyy-mm-dd"t"hh24:mi:sstzh:tzm') from dual; 15/oct/13 05:18:28.000000000 pm -06:00 	0.11174732430383
19393316	6195	where to filter 'deleted' rows in a query	select * from tablea a    join tableb b        on b.id = a.pkid          and a.deleted is null          and b.deleted is null    join tablec c       on c.id = b.pkid          and c.deleted is null 	0.0228646857519951
19393362	8727	format datetime column into dd month yyyy	select cast(day(getdate()) as varchar(2)) + ' ' + datename(mm, getdate()) + ' ' + cast(year(getdate()) as varchar(4)) as [dd month yyyy] 	8.26620183674353e-05
19393605	39579	how can i join these 2 join queries?	select username from login  inner join friends  on (login.id = friends.userid2 and friends.userid1 = 41)     or (login.id = friends.userid1 and friends.userid2 = 41) 	0.532557738942549
19393849	32009	sql server 2008 join and count	select  shipment_no from    package group by shipment_no having count(distinct truck_no) > 1 	0.788173823165061
19393936	22683	how can i sum up multiple int columns in the order by part of a mysql request?	select * from feeds order by (select (sum(column1) + sum(column2)) from feeds) desc limit 1 	0.00147660737857772
19395136	34520	mysql month over month totals compared to previous month	select thismonth.month, thismonth.year, thismonth.total, prevmonth.month as previous_month, prevmonth.year as previous_year, prevmonth.total as previous_total from (     select month(start_date) as `month`,             year(start_date) as `year`,             extract(year_month from start_date) as yearmonth,             sum(amount) as total     from trackings     group by `month`, `year`, yearmonth ) thismonth left outer join (     select month(start_date) as `month`,             year(start_date) as `year`,             extract(year_month from date_add(start_date, interval 1 month)) as yearmonth,             sum(amount) as total     from trackings     group by `month`, `year`, yearmonth ) prevmonth on thismonth.yearmonth = prevmonth.yearmonth 	0
19397195	4892	ms sql combine columns in select	select member_id, case [proc]   when 'y' then 'proc, '   else '' end + case [50k_12_mths]   when 'y' then '50k,'   else '' end + case [100k_12_mth]   when 'y' then '100k, '   else '' end  as [group] from members 	0.0276901145143458
19397426	24606	database table join not returning proper result	select moviename from moviemaster  inner join dvdbinslotinfo on moviemaster.movieid = dvdbinslotinfo.movieid where kioskid='901' and status='dvd' 	0.772667458919708
19397850	16595	combine two queries in one, sql ms access 2007	select     firms.name,     sum(iif(firms.balance in (1500, 1502),firms.amount,0))/100 as aggregate1,     sum(iif(firms.balance in (1400, 1401),firms.amount,0))/100 as aggregate2,     sum(iif(firms.balance in (1300, 1301),firms.amount,0))/100 as aggregate3 from firms where firms.date >= #12/6/2012 3:54:15 pm#   group by firms.name; 	0.186482474091147
19398245	34103	how to add hours to current date in mysql	select * from timetable where date (date) = date(now()+interval 8 hour) 	0
19400920	21137	order by sql how to deal with same values?	select * from table order by value1 desc, value2 asc 	0.0147037135216638
19400922	4921	how can i get sql result column as csv without 'for xml'-clause?	select    a ,   max( case seq when 1 then (b) else '' end )   + max( case seq when 2 then (', ' + b) else '' end )    + max( case seq when 3 then (', ' + b) else '' end )    + max( case seq when 4 then (', ..') else '' end )   as b from (select          t1.a       , t1.b       , (select count(*) from t t2 where t1.a = t2.a and t2.b <= t1.b) as seq        from t t1) as temp group by a 	0.0064184828986109
19401268	7245	joining two mysql tables to fetch names for multiple columns	select mt.member_id, mt.parent_id, mt.sponsor_id, m.member_name,  m1.member_name as parent_name , m2.member_name as sponsor_name  from `member_tree` mt  left join  `member` m on mt.member_id = m.member_id  left join  `member` m1 on mt.parent_id = m1.member_id  left join  `member` m2 on mt.sponsor_id = m2.member_id  where mt.`member_id`  in (1000015,1000016,1000017,1000018,1000019,1000020,1000021,1000022,1000023,1000024,1000025,100    0026,1000027,1000028,1000029,1000030 ) 	0
19402080	38999	sql: show only the percentile	select * from  ( select min([dealercode]) as mindealercode        ,[201309]        ,rownum = row_number() over(order by [201309])        ,rnk = rank() over(order by [201309])        ,densernk = dense_rank() over(order by [201309])        ,ntile4  = ntile(100) over(order by [201309])        ,bm = rank() over(order by [201309])*0.7  from [sa_sew].[dbo].[sew_ytd_composite$]    where ratio_id = 'fi02u' and dealercode like '%vw%'     group by [201309] ) as t where ntile4  = 70; 	0.00165245920488944
19402083	28051	concatenate as a and choose either a or b according to their fks	select idowner as idoutput,        coalesce(firstname || ' '  || lastname, companyname) as name from owner left join contacts on owner.idcontacts = contacts.idcontacts left join company  on owner.idcompany  = company .idcompany 	0
19403088	7981	sql query to get data group by customer type and need to add default value if customer type not found	select country.maincountry, customertype.customertypeid, count(t.customerid) as customercount from   (select distinct maincountry from customers) as country        cross join (select distinct customertypeid from customers) as customertype        left join customers t          on country.maincountry = t.maincountry          and customertype.customertypeid = t.customertypeid              and t.createddate > convert(datetime, '1/1/2013') group by country.maincountry, customertype.customertypeid order by maincountry, customertypeid 	0
19404095	16884	getting a snapshot of records where an "event" can mean several entries on the same date	select events.* from events inner join (     select employeeid, max(date) as latestdate     from events     where events.date < [date entered]     group by employeeid) as s   on (events.employeeid = s.employeeid) and (events.date = s.latestdate) 	0
19404651	40472	group a group and count query	select      domaincode         ,   count( customercode )         ,   sum( callcount ) from       (                 select      [330].domaincode                         ,   [329].customercode                         ,   count([329].customercode) as callcount                 from        330                 inner join  329                         on  [330].domaincode = [329].accrediteddomaincode                 where       (   (   ( [329].callstatus ) = 'n'                                 or  ( [329].callstatus ) = 'p'                                 or  ( [329].callstatus ) = 'x'                             )   )                 group by    [330].domaincode                         ,   [329].customercode             ) as custperdomain group by    domaincode; 	0.269331272952232
19404821	20085	joining different tables with one table coumn name and another table's coumn values	select t.*, g.grp_id from (select * from emp_det unpivot (   rating for group_name in ("plsql", "adf") )) t join "group" g on t.group_name = g.grp_name 	0
19405214	30246	how to use a column from joined table in a join with a subquery	select * from maintable m inner join joinedtable j on j.foreignid = m.id cross apply (select top 1 *             from subquerytable sq             where  sq.foreignid = j.id             order by versioncolumn desc) sj 	0.0107914085682834
19405637	20861	get the unique number of entries in column two from table two, where the first column of both tables match	select distinct pid from eid_pid where eid in tmp_cid_eids; 	0
19405779	36062	mysql distinct select on multiple columns grouped by latest entry	select id      , created_at      , from_user_id      , to_user_id      , subject      , text    from message m   join       ( select max(id) max_id          from message         group            by least(from_user_id,to_user_id)             , greatest(from_user_id,to_user_id)      ) x     on x.max_id = m.id; 	0
19405959	5810	sql switch rows result to columns	select f.desprefettura as desprefettura,  count(case when  a.flagprefetturaquestura=0 then    a.idaccordo else null end) as tot01, count(case when  a.flagprefetturaquestura=1 then a.idaccordo else null end) as tot02 from accordo a inner join prefettura f on f.idprovincia = a.idprefetturasottoscrizione group by f.desprefettura order by f.desprefettura 	0.0206395999013098
19406611	9774	oracle duplicate entries bases on two columns	select a.acol2, a.acol3, b.bcol3     from a, b    where a.acol4 = b.bcol2 group by a.acol2, a.acol3, b.bcol3   having count (*) > 1 	0
19409521	33752	convert to datetime mm/dd/yyyy hh:mm:ss in sql server	select convert(varchar(10), getdate(), 101)                          + ' ' + convert(varchar(8), getdate(), 108) 	0.034539045679983
19409635	40963	sql/php select a follower that you don't follow from someone who follows you	select a.naar_id from wievolgtwie a, wievolgtwie b where a.van_id = $row[0]     and b.van_id = $_session[id]     and a.naar_id != $_session[id]     and a.naar_id != b.naar_id     and b.vaan_id not in (select vaan_id                             from wievolgtwie                            where naar_id = a.naarid) limit 0, 1; 	0.0124803688184223
19410996	19607	select all projects from last week - sql	select * from projects  where project_date between now()  and date_sub(now(), interval 7 day) 	0
19412025	5237	how do i determine the column position in a compound key	select i.name as indexname,    object_name (ic.object_id) as tablename,    col_name (ic.object_id, ic.column_id) as columnname,    ic.key_ordinal as columnorder from sys.indexes as i    inner join sys.index_columns as ic       on i.object_id = ic.object_id and i.index_id = ic.index_id where i.is_primary_key = 1 order by ic.object_id, ic.key_ordinal 	0.00294210893027803
19412610	25014	sql query help, grabbing dates, counts, averages	select avg(totalpaid),    count(number),    month(datepaid),    year(datepaid) from payhistory group by     month(datepaid),    year(datepaid) 	0.0384573883568665
19413942	24588	query string with spaces	select id_group from groups where title like '% %'; 	0.467752825916343
19415308	36825	select from multiple tables with group by clause	select shtimeid_fk,count(*) as cnt  from dbo.ticketrow as tr inner join dbo.ticket as t on tr.ticketid_fk=t.id where t.paid='ok' group by shtimeid_fk having count(*)>1 	0.0718953700090673
19416010	32516	subquery - listing both courses	select first_name, last_name, phone from student d,enrollment f,section g,course h where d.student_id = f.student_id and f.section_id = g.section_id and g.course_no = h.course_no  and h.description = 'systems analysis'  intersect select first_name, last_name, phone from student d,enrollment f,section g,course h where d.student_id = f.student_id and f.section_id = g.section_id and g.course_no = h.course_no  and h.description = 'project management' 	0.631019724501113
19418356	7170	how to find duplicate columns which are having same values in more than one columns(column names are given)	select * from students s inner join (select roll_no, date_of_join from students group by roll_no, date_of_join having count(student_id)>1) rd on s.roll_no = rd.roll_no and s.date_of_join = rd.date_of_join order by s.roll_no, s.date_of_join 	0
19419468	35490	need to create a query for monthly data	select * from table_name where created_date between  date_format(now(),'%y-%m-20') - interval 1 month  and date_format( now(),'%y-%m-20') 	0.0520389116283828
19419637	33912	subquery to find the customers that have placed an order	select cust_id, cust_name from customer_table where cust_id in (select cust_id from orders_tbl  where prod_id in  (select prod_id from products_tbl where cost > 6.5)) 	0.00070772716058678
19419925	23290	sql server 2008 array query	select n from (values(1),(2),(3),(4),(5),(6)) as nums(n) except select recoveryid from table1 	0.745379385802161
19420267	21711	display hierarchy information from cte in horizontal manner	select  t1.name as [1],     case 2      when t2.roleid then t2.name       when t3.roleid then t3.name      when t4.roleid then t4.name      when t5.roleid then t5.name      else null end as [2] ,     case 3      when t2.roleid then t2.name       when t3.roleid then t3.name      when t4.roleid then t4.name      when t5.roleid then t5.name      else null end as [3] ,     case 4     when t2.roleid then t2.name       when t3.roleid then t3.name      when t4.roleid then t4.name      when t5.roleid then t5.name      else null end as [4] ,     case 5     when t2.roleid then t2.name       when t3.roleid then t3.name      when t4.roleid then t4.name      when t5.roleid then t5.name      else null end as [5]  from table1 t1 left join table1  t2 on t1.immediatesupervisor  = t2.ecode  left join table1  t3 on t2.immediatesupervisor  = t3.ecode  left join table1  t4 on t3.immediatesupervisor  = t4.ecode  left join table1  t5 on t4.immediatesupervisor  = t5.ecode  where t1.roleid = 1 	0.00106124160221562
19420388	36695	finding entries where at least 2 rows have a value of x	select sub.entry_id from exp_judging as jud left join exp_submissions as sub on jud.rel_id = sub.id  where jud.stage_2 is null and jud.stage_1 = 1  and sub.member_group = 5 group by jud.rel_id having count(*) >= 2 	0
19420776	16516	wordpress: how to get_results from the database and display sorted in a table	select columnname from tablename order by columnname asc|desc 	0
19423094	40232	join two tables with similar columns in mysql	select        concat('t-',timeline.timelineid), timeline.usuarioid, timeline.timelinefecha, "" timeline, timeline.evento, timeline.juegoid, 0 timelinepadre    from        timeline    union    select       concat('tp-',timeline_personal.timelineid), timeline_personal.usuarioid, timeline_personal.timelinefecha, timeline_personal.timeline, "0" evento, "0" juegoid, timeline_personal.timelinepadre    from       timeline_personal    order by usuarioid 	0.00921373027886678
19424960	21060	sub query in select line	select    action.actionid,   max(partex.stockmake) as partexmake,    max(partex.stockmod) as partexmod from action  inner join event  on action.eventid = event.eventid  left join eventstocklink on eventstocklink.eventid = event.eventid left join stock  on stock.stockid = eventstocklink.stockid  and stock.statusid = '5' where actiondate2 between 20130601 and 20131031  and event.siteid = 1  and action.typeid = 1  group by action.actionid 	0.446169504759229
19425570	26051	using output of one query as where clause of another -- sql server 2008	select * from tblfilms  where tblfilms.filename in (select distinct filenames from tblfiles); 	0.128746482138505
19425586	1827	mysql: order by next date in schedule	select e.id,e.name,e.description, sc.nextdate from events left join    (    select s.eventid,        min(timestamp(s.date,s.time)) nextdate    from schedules s         where timestamp(s.date,s.time)>now()     group by s.eventid   ) sc on e.id=sc.eventid order by sc.nextdate 	0.0110469878821673
19427195	7287	select the row with maximum value for a column mysql	select  *  from employee  where city = 'new york'  order by salary desc limit 1 	0
19427246	5242	mysql order based on concat list	select distinct attributes.* from attributes, products      where exists(select 1 from products where      find_in_set(attribute_id, product_attributes) is not null); 	0.00470449112757652
19427767	17402	remove characters when creating mysql view	select substring_index(projects.col_82,':',-1) as hunter where projects.col_82 is varchar(255) 	0.545626150110396
19429280	17051	get prev row in mysql results with php	select col1, col2,         col1 - @prev1,         col2 - @prev2,        @prev1 := col1, @prev2 := col2 from tablename, (select @prev1 := 0, @prev2 := 0) r 	0.00692146421524381
19429612	26121	how to select a filtered result of logins of users?	select l.`id`, x.`user`, x.`maxtime`, x.`ip` from      `logins` l,     (select `user`, max(`time`) as `maxtime`, `ip` from          `logins` group by `user`, `ip`) x      where l.`user` = x.`user` and l.`ip` = x.`ip` and l.`time` = x.`maxtime`; 	0.000176345570633531
19433911	5459	complications while using except in mysql	select customerid from orders where year(orderdate)<>1977; 	0.450991318089455
19434324	25663	retrieve data from database based on radio button value	select itemprice from items where itemname = $_post['itemtype'] 	0
19435426	15680	return all rows from one table, and match with a subset of rows from another table?	select rp.rsrpid as id, rp.rsrpname as name, ri.rsrisesdid   from resourcepool rp    left outer join resourcesintroduced ri on (ri.rsrirsrpid = rp.rsrpid and ri.rsrisesdid = 243) 	0
19436895	41298	sql: how to to sum two values from different tables	select region,sum(number) total from (     select region,number     from cash_table     union all     select region,number     from cheque_table ) t group by region 	0
19438324	12582	sql query select max min value from resultset query	select id, amountincurrency, extractiondate,        min(extractiondate) over () as minextractiondate,        max(extractiondate) over () as maxextractiondate from table; 	0.00396963958188952
19439326	6755	sql server 2008: how to order column with null values to show up in the end	select firstpart,secondpart  from exhibit_table d, exhibittype a  where d.case_id ='13-05' and d.exhibittypeid = typeid and d.complianceno = '0' and active = 1 order by case when firstpart is null and secondpart is null then 0 else 1 end, convert(int, firstpart), secondpart 	0.0022650268141731
19444052	38275	how to select data from postgres sql on rails 3	select * from books; 	0.0121591670466658
19446321	7311	count days within a month from date range	select   datediff(     least(d_end, '2013-10-31'),     greatest(d_start, '2013-10-01'))+1 days from   ranges where   d_start<='2013-10-31' and d_end>='2013-10-01' 	0
19447278	8715	want to select data from two tables, where i need to count a column and join	select b.id, b.name, count(w.name) as workers from block b left join block_worker w on w.block_id = b.id group by b.id, b.name 	0.000705629527312753
19448464	28701	taking data from multiple tables in single query	select  (select count(barcode)                       from localbarcode                     where int([timestamp])= format(cdate('10/18/2013'))),              (select count(isupload)                       from localbarcode                     where isupload=0),              (select count(barcode)                       from barcodecancel                     where int([timestamp])= format(cdate('10/18/2013')))       from dual 	0.00444289553280171
19450680	10108	identifying auto scaled azure instances?	select       e.connection_id,       s.session_id,       s.login_name,       s.last_request_end_time,       s.cpu_time,       s.host_name from       sys.dm_exec_sessions s       inner join sys.dm_exec_connections e       on s.session_id = e.session_id 	0.00496922004671215
19451245	1760	oracle: determine partition size	select partition_name, bytes/1024/1024 "mb" from dba_segments where segment_name = 'mytable' and segment_type = 'table partition'; 	0.508200648974203
19452363	24344	mysql inner join 2 tables to match user number to user name	select * from bets inner join users on bets.userid = users.userid where gameid = '$ngnumber' order by draworder 	0.000365398970507907
19455658	12287	find second max in a table using mysql query	select id from `user` order by id desc             limit 1                      offset 1 ;                   	0.00113658728954782
19457721	9709	mysql joining 2 counts in one select	select q1.supplier, q1.scp, `volume loaded`, `volume useable`   from ( query 1 ) as q1   join ( query 2 ) as q2     on q1.supplier = q2.supplier and q1.scp = q2.scp 	0.00197213208259472
19458933	9117	extract records from table	select distinct f2.facil_identifier, f2.facil_addr_line1, trim(f2.facil_city) as facil_city, f2.facil_zip from import.facil_xx_20131016 f2 left join import.facil_xx_20131016 f on f2.facil_identifier = f.facil_identifier where f2.facil_identifier is not null and f.facil_identifier is null 	0.000234265842781532
19460394	31252	selecting orders with multiple line items but not when one or more line items contains a defined list	select o.id, o.storeid from [order] o join psd_serviceticket st   on o.id = st.workorderid   and o.storeid = st.storeid where o.storeid = 101 and o.time >= '10/1/2013' and o.time <= '10/18/2013' and o.id not in (select orderid          from orderentry oe          inner join [order] o             on o.id = oe.orderid             and o.storeid = oe.storeid          where oe.storeid = 101          and o.time >= '10/1/2013'          and o.time <= '10/18/2013'          and oe.itemid in ( 60,856,857,858,902,59,240,57,217,853,855,854,41 )         ) and (st.servicetypeid = 1 or st.servicetypeid = 4 ) 	0
19460745	31574	mysql return 'i found it' string if found in table	select if((select count(value) from table where (value = 'jerry')) > 0 ,'i found him','he is missing!') 	0.0149370863531043
19460777	4422	sql: join tables excluding duplicates in second table	select distinct t1.id, t1.value1,    (     select st2.value2      from table2 st2      where t1.id = st2.id     order by st2.value2     limit 1   ) as value2,    (     select st3.value3      from table2 st3      where t1.id = st3.id     order by st3.value3     limit 1   ) as value3  from table1 as t1 	0.00134485731050443
19463727	14076	mysql group result value if null	select ifnull(notes,'sell') n,sum(total) from records group by n; 	0.0461033020367382
19464461	34711	sql query to get total payments by customer type (1,2,3,4,5) in each month of given year	select      2013 as year,     months.monthno,     amount = isnull(sum(o.amount),0),     c.customertypeid   from     customers c           cross join          (select number monthno from master..spt_values where type='p' and number between 1 and 12) months          left join payments o      on o.customerid = c.customerid      and year(o.paymentdate)=2013      and month(o.paymentdate) = months.monthno group by     months.monthno, c.customertypeid order by     months.monthno, c.customertypeid 	0
19465079	19719	separating infrequently accessed fields from a table	select role from user where username = ? 	0.00266805597351736
19465328	40720	get the current month number in sql server, 1 for january, 12 for december	select month(getdate()) 	0
19467689	18218	select query with constant variable	select    t.keyname,   tt.constvalues from tbl t   cross join   (values ('r1'), ('r2'), ('r3'), ('r4')) tt(constvalues) 	0.466829304502741
19467867	25582	sql sum and link fields in multiple tables	select table1.plantid, table1.itemname, sum(table1.qty), coalesce(t2.num_sum, 0), coalesce(t3.qty_sum, 0) from table1 left join (select plantid, itemname, sum(num) as num_sum       from table2       where wk >= 41 and wk <= 45       group by plantid, itemname) t2 on table1.plantid = t2.plantid and table1.itemname = t2.itemname left join (select plantid, itemname, sum(qty) as qty_sum       from table3       where table3_wk >= 41 and table3_wk <= 45       group by plantid, itemname) t3 on table1.plantid = t3.plantid and table1.itemname = t3.itemname where table1.plantid = 1 group by plantid, itemname 	0.010124471600394
19469154	9867	how to compare dates in datetime fields in postgresql?	select * from table where update_date >= '2013-05-03' and update_date < ('2013-05-03'::date + '1 day'::interval); 	0.000836403572637992
19469869	16788	select columns from table where value of columns not equal 'myvalue'	select username from users u, friends f where username = f.friend and f.friend <> 'user1' union select username from users u, friends f where username = f.you and f.you <> 'user1' 	0
19470126	15886	mysql query join two tables with same value?	select id, title, posts from artist, 'artist' as type union all select id, title, posts from news, 'news' as type 	0.00335060429814278
19470230	29855	sql selecting all but the last row in a table?	select ... from mytable where id < (select max(id) from mytable) 	0
19470786	23449	select books having specified authors	select   b.name from books b   join authors a     on b.authorid = a.id where a.name in ('x', 'y') group by b.name having count(distinct a.id) = 2 	0.056213461444147
19471211	4282	how to write if statment if at least in one row is number "1"?	select * from mytable where (math=1 or english=1); 	0.000118098533201972
19471391	35937	mysql transform data	select id, name,  sum(case when state="open" then amount else 0 end) as `open`, sum(case when state="closed" then amount else 0 end) as `closed` from <yourtablename> group by id; 	0.14571553138954
19471607	14375	php, mysql - get rows matching all items from an array	select day,hour from yourtablename where class in ('9b3','9b4','9b5') group by day,hour having count(class) = 3; 	0
19473586	6458	counting fields in a group by, and generating a greport with ms access	select test.city, =sum(iif(status="cancelled",1,0)) from test group by test.city 	0.664676137972937
19476098	16033	where col in() clause for geometry column in mysql	select id, astext(latlng) from `points` where astext(latlng) in ('point(35.80684 51.427820000000004)') 	0.645499144188319
19476288	35069	mysql query for getting data from different table and using it for distance calculations	select wp_events.*,         wp_zipcode.lat,         wp_zipcode.lng,        ( 3959 * acos( cos( radians(34.070358) ) * cos( radians( wp_zipcode.lat ) ) * cos( radians( wp_zipcode.lng ) - radians(-118.349258) ) + sin( radians(34.070358) ) * sin( radians( wp_zipcode.lat ) ) ) ) as distance   from wp_events    left join wp_zipcode      on wp_zipcode.zip = wp_events.zip having distance < 25   order by distance   limit 0 , 20 	0.00233151096109891
19477335	21299	sql to extraction xml form column	select        t.p.value('param[1]','varchar(20)') as param,       t.p.value('value[1]','varchar(20)') as value  from t005 cross apply activitydetail.nodes('/root/parameter') t(p) 	0.0422649863429118
19477579	16825	sqlite - daydifference between two date fields	select guests.[guest_name],guests.[guest_surname],guest_data.[start_date],guest_data.[end_date], julianday(guest_data.end_date) - julianday(guest_data.start_date) as days_interval from guests inner join guest_data on guests.guest_id=guest_data.guest_id order by  guests.[guest_surname] asc 	0.00272876420722677
19479522	2693	sql (sybase) return sum of calculated rows	select sum(a.total) from (   select (sum(credit) - sum(debit)) as "total"   from a_sales_ledger   where document_date <= '2013-09-30'   group by customer_id   having sum(credit) - sum(debit) > 0   ) a; 	0.00251962169174476
19480075	2439	what is the easiest way to getting distinct count in sql server	select count(*) from (     select distinct empid, empname, salary from employee ) x 	0.711156527134445
19481066	38226	how can i limit the selection of items with sql per value?	select distinct thread from pms where to-id = '".$_session['id']"' order by id asc 	8.89580093734926e-05
19482806	5016	sql query to replace record of table with another	select lastname, firstname,  case when (workphone is null) then homephone  else workphone end as workphone  , homephone  from members; 	0.00178032692114055
19483086	38751	sql: how to count occurrences in tablea, join with tableb and then order by occurences?	select `user_r_group`.`user_id`, count(`activities_attended`.`id`) as attendings             from `user_r_group`             inner join `activities_attended`                     on `user_r_group`.`user_id` = `activities_attended`.`user_id`             where `user_r_group`.`group_id` = 1                     group by `user_r_group`.`user_id`                     order by attendings desc 	0.0185704696991533
19483108	19060	turn update/join into query	select t1.`parentid` = t2.`id` from `table1` as t1 inner join `table2` as t2   on t2.`name` = t1.name 	0.0818325680121662
19484382	6479	sql group by - different colors	select "objectname",   count("object_id") as totalquantity,   sum(case        when "color" = 'red'         then 1       else 0       end) as quantityred,   sum(case        when "color" = 'blue'         then 1       else 0       end) as quantityblue from "table1" where "projectname" = 'projectone'   and "projectleader" = 'mr.smith' group by "objectname"; 	0.121817601700337
19484641	12619	set value to a column on the row where its id exists in another table	select *,        case when exists (select * from table2 as t2 where t2.linked_id=t1.id)              then 1              else 0        end as photo_exist from table1 as t1 	0
19484740	8977	i need to use count in access sql, and calculate average price	select product.product_desc as description, count(*) as countitems, avg(item.item_price) as [average price] from item inner join product on item.product_id = product.product_id group by product.product_desc having count(*) > 10 	0.00952029438922845
19486638	18354	how to remove both duplicates in ms access	select documentdate, abs(accountnetamount) , count(*) from yourtable group by documentdate, abs(accountnetamount) having count(*) = 1 	0.164684339971074
19487076	36614	latest date from date, month, year	select * from your_table order by year, month, `date` desc limit 1 	0
19487787	22369	how to make customised auto increment primary key in mysql	select `table1`.`id` as `id`,concat('id-',`table1`.`id`) as `custom_auto_inc` from `table1` 	0.0040291317487584
19489087	3604	date greater than a specified date (date, month, year)	select dateofbirth from customer where dateofbirth  between date('1004-01-01') and date('1980-12-31');   select dateofbirth from customer where date(dateofbirth)>date('1980-12-01'); select * from customer where date(dateofbirth) < date('now','-30 years'); 	0
19489478	24237	copy date from table to another table in a different db	select * into [dbname].[dbo].table from thistable 	0
19490507	40791	how to get dates of current month or as specified month using sqlite query?	select date(julianday('now', 'start of month')+d1*9+d2*3+d3) as days from (     select 0 as d1 union select 1 union select 2 union select 3 ) join (     select 0 as d2 union select 1 union select 2 ) join (     select 0 as d3 union select 1 union select 2 ) where strftime('%m', days)=strftime('%m', 'now') order by days; 	0
19490554	13467	multiple select in insert into query	select dtime , sum(case when varname = 'var1' then value else null end) as [var1] , sum(case when varname = 'var2' then value else null end) as [var2] , sum(case when varname = 'var3' then value else null end) as [var3] from tab group by dtime 	0.0475093275392697
19492612	30647	conditionaly set value of column in mysql select query	select age,        case when age < 18              then 'minor'              else name         end as name from members 	0.00201728649592847
19492664	23983	select also zero-values while performing select count with group by	select     count(u.id) as ile,     d.day from generate_series('2013-09-23'::date, '2013-09-29'::date, '1d') as d(day)     left outer join users as u on u.date_created >= d.day and u.date_created < d.day + '1d'::interval group by d.day 	0.0591798914430105
19492744	2853	return query with nested lookup to associated table	select case when subject_entries.entry_id = 36  then subject_entries.entry_id = true else null end as entry_id from subject_entries 	0.0861061959382799
19493462	32326	sql reference to alias name in the where clause	select * from  (select *, (     select isnull(sum(stocklevel), 0)     from itemstock     where item_id = itemstock_itemid ) as stock_count from items where item_id = <cfqueryparam value="#url.item_id#"> ) derived_table where stock_count > 0 	0.738885134051085
19494545	22583	mysql - add column with precalculated values using closest representation from other table	select value.*,mapping.*    from value   join mapping   join      ( select value.id             , min(abs((value.value1+value.value2)-mapping.value))min_abs           from value          join mapping         group             by id      ) x     on x.id = value.id    and x.min_abs = abs((value.value1+value.value2)-mapping.value)  order     by id; 	0
19494870	3258	sql count of distinct records against multiple criteria	select appid, licenseid, count(distinct userid) from usage where dateused between @from and @dateto group by appid, licenseid 	0.000643618625287781
19496525	39873	multiple fields for one item in mysqli query that need to go into one textbox with php	select b.id,b.title, group_concat(sss.title) as subject  from books b left join book_subjects bs on b.id = bs.book left join sub_subject ss on ss.id = bs.sub_subject left join sub_sub_subject sss on bs.sub_sub_subject = sss.id where b.isbn13 = 9780596515898 	0.000159013132007586
19496642	27496	mysql counting rows with loop	select  p2c.pid as productnumber,         p.name as productname,         count(*) as registered,         sum(date_add(from_unixtime(purchased), interval 5 year) >= curdate()) as inwarranty,         sum(date_add(from_unixtime(purchased), interval 5 year) < curdate()) as outofwarranty,         date_format( max( from_unixtime(purchased) ), '%d.%m.%y') as lastpurchased,         date_format( date_add( max( from_unixtime(purchased) ), interval 5 year), '%d.%m.%y') as warrantyuntil from products2customers p2c join products p on p.id = p2c.pid group by p2c.pid order by inwarranty desc 	0.0365457380457711
19496780	30567	mysql table changes rowcount on each page refresh in phpmyadmin	select count(primary_key) from table 	0.00615272631800994
19497281	40379	query to compute the difference between a sum and previous sum, group by discontinuous dates	select      d1.recdate,      totalval,      totalval - nz(totalval2,0) delta from (     select recdate, sum(mval) as totalval     from dailyval     where recdate >= datevalue("1/1/2013")     group by recdate) d1 left join (     select recdate, sum(mval) as totalval2     from dailyval     where recdate >= datevalue("1/1/2013")     group by recdate) d2 on d2.recdate = (select max(recdate) from dailyval where recdate < d1.recdate) ; 	7.511309689674e-05
19497729	21243	t-sql select null values from join	select      preventable,      warrantable  from      bo_hro      left join bo_hro_ext on bo_hro.ro_no = bo_hro_ext.ro_no  where      (preventable = 0 and warrantable = 0 )     or (bo_hro_ext.ro_no is null) 	0.0319447732994584
19498907	647	sql multiple column in selections	select *  from table t where (juiced <> 'no') or (juiced like 'yes' and                                              (exists (select size, colour                                                       from [table] a                                                       where a.apples = t.apples and 	0.319420938418109
19499284	20525	select a record using a date between the same colum	select top 1 * from [tablename] where [load] >= @date order by [load] desc 	0
19499398	28723	how can i get a corresponding maximum and minimum id in mysql?	select simulation_id, first.id as first_ts_id, last.id as last_ts_id, num_steps from (select simulation_id, min(step) minstep, max(step) maxstep, count(*) num_steps       from simulations_ts       group by simulation_id) as g join simulations_ts first on first.simulation_id = g.simulation_id and first.step = g.minstep join simulations_ts last on last.simulation_id = g.simulation_id and last.step = g.maxstep 	0
19501789	40328	get average time between record creation	select  a.userid,         avg(cast(datediff(minute,b.createdate,a.createdate) as float)) avgtime from #yourtable a outer apply (select top 1 *              from #yourtable              where userid = a.userid              and createdate < a.createdate              order by createdate desc) b group by a.userid 	0
19503149	15664	dates of past 12 months in oracle	select trunc(sysdate) - rownum + 1 the_date from   dual connect by level <= (trunc(sysdate) - add_months(trunc(sysdate),-12)) 	0.000133229671524099
19503930	25910	return column1 if all values in column2 are a specific value	select column1 from table group by column1 having count(distinct column2)=1 and min(column2) = 'x' 	0
19504361	40363	calculate sum of single column on the basis of another column in mysql	select     custid,     sum(if(type=0,amount,0)) as amount1,     sum(if(type=1,amount,0)) as amount2 from     tbl group by     custid; 	0
19504426	23210	how to duplicate only the first row of sql query?	select 'column1name','column2name' union select * from tablename; 	0
19504939	18044	how to get the count and display only one row	select tblcustomer.customerid, tblcustomer.customername, tblordertype.ordertypename,  count (tblorder.orderid) asordercount from tblcustomer  inner join tblorder  on tblcustomer.customerid = tblorder.customerid inner join tblordertype  on tblordertype.ordertypeid = tblorder.ordertypeid group by tblcustomer.customerid,  tblcustomer.customername,  tblordertype.ordertypename 	0
19506556	35925	sql select query help. maximum sum of consequtive four rows.	select max(lne1in  + lne4in )                    as peakhourin,        max(lne2out + lne3out)                    as peakhourout,        max(lne1in  + lne2out + lne3out + lne4in) as peakhoursum from   (          select t1.lne1in  + t2.lne1in  + t3.lne1in  + t4.lne1in  as lne1in,                 t1.lne2out + t2.lne2out + t3.lne2out + t4.lne2out as lne2out,                 t1.lne3out + t2.lne3out + t3.lne3out + t4.lne3out as lne3out,                 t1.lne4in  + t2.lne4in  + t3.lne4in  + t4.lne4in  as lne4in          from   my_table t1            join my_table t2 on t2.datetime = t1.datetime + interval 15 minute            join my_table t3 on t3.datetime = t2.datetime + interval 15 minute            join my_table t4 on t4.datetime = t3.datetime + interval 15 minute          where    time(t1.datetime) between '07:00:00' and '08:00:00'          group by t1.datetime        ) t 	0.00596339968278699
19506737	32226	how to write subquery in sql to map dictionary values	select substring(d2.stringvalue,5,7) as "you"     from dictionary d1, dictionary d2, dictionary d3, table t1   where d1.stringvalue='where' and         d1.id=table.col1 and          substring(d2.stringvalue,,3) ='are' and         substring(d2.stringvalue,5,7) ='you' and         d2.id=table.col2 and          d3.id=table.col3; 	0.37853745225355
19507074	23847	sql: get parent if and only if children have a certain property	select id  from asset a  inner join resource r on a.id = r.asset_id  where not exists (      select 1       from resources r2      where a.asset_id = r2.asset_id      and r2.status <> '1' ) 	0
19507619	18504	mysql query return first match of each result	select m.id,   m.msgfrom,   m.msg,   m.active,   m.replied,   u.username,   u.online,   u.admin,   u.imagename from messages m  inner join users u on u.users.id = m.msgfrom inner join (select max(id) as id, msgfrom             from messages             group by msgfrom            ) m2     on m2.id = m.id and m2.msgfrom = m.msgfrom where messages.msgto = '$_session[id]' 	0
19507823	11645	sql query to calculate weighted points	select a.user_id,sum(new_points) from ( select user_id,        case when grade = 'a'             then points=3             when grade = 'b'             then points=2             when grade = 'c'             then points=1             end as new_points from table_post ) a    group by a.user_id; 	0.0703017694682856
19508786	8027	how can i calculate grand total.	select sum(amountcolumnname) from yourtable 	0.000834970370743258
19509412	6324	distinct values of an sql table	select username, userlastname, userid, max( score )  from  `highscores`  group by userid order by max( score ) desc  limit 10 	0.00438174066777444
19509987	20292	sql query to get exactly the last day result	select * from mytable where mydate >= dateadd(day, -1, convert(date, getdate()))  and mydate < convert(date, getdate()) 	0
19510743	3246	multiple count based on value mysql	select sum(if (alarmtype = '1',count,0)) as  alarmtype1, sum(if (alarmtype = '2',count,0)) as  alarmtype2, sum(if (alarmtype = '3',count,0)) as  alarmtype3, alarmhour from 'table1' group by time 	0.000465805290472994
19511132	26211	multiplying across row in a query	select exp(sum(log(bet_odd))) as odds from betting 	0.00690301946219767
19511567	38837	mysql query to find occurence of one field into another	select * from mytable  where instr(parent_names, name) > 0 	0
19513371	9221	how to add a name to a column that shows (no column name) on the result pane	select t1.cardid,         t1.name,         min(t2.record) as yourpreferedname  from   t2         inner join t1             on t1.tag = t2.tag  group by t1.cardid, t1.name 	0
19516414	39365	how to get present date and next dates fromm stored db	select distinct(date) from `shows` where movid='$id' and date >= current_date() order by date 	0
19516474	1651	grabbing last order date, total orders and total amount with one query?	select     max(date_created) as last_order_date,      sum(total_count) as total_sum,      count(id) as total_orders  from     `orders`  where     `user_id` = '96838'      and     `status` in ('new', 'delivered') 	0
19519350	31942	how to group in two tables in sql server?	select r.branch_name,         count(r.request_id) as num_of_requests,         sum(i.price) as total_price  from requests r left join requests_items i on i.request_id = r.request_id   group by r.branch_name 	0.0343117857024125
19521422	23223	change subquery to join on two columns in oracle view	select distinct      ... from      person ,     address ,     owner ,     object ,     registrations reg where      person.personid = address.personid     and person.personid = owner.personid (+)     and owner.objectid = object.objectid     and owner.objectid = object.objectid     and owner.personid || owner.objectid = reg.personid (+) || reg.objectid (+)     and     (        object.reg_required not in        (           'y'        )        or        (           reg.approved in ('y','v'))        )     ) 	0.0595310854038485
19521649	24281	sql query to return rows in multiple groups	select      number as month, sum(amount)     from  (     select number      from master..spt_values      where type='p'        and number between (select min(firstmonth) from yourtable)            and (select max(firstmonth+nomonths-1) from yourtable) ) numbers     inner join (select       firstmonth,       firstmonth+nomonths-1 as lastmonth,       value / nomonths as amount   from yourtable) monthly     on numbers.number between firstmonth and lastmonth group by number 	0.00388373155670228
19522938	29142	mysql group by "group" and order by largest id	select scenario_id, max(id) as max_id from tree  where user_id = 1 group by scenario_id 	0.00713636003102069
19523484	3111	select 10 random records from table without quering number of records	select * from table order by rand() limit 10 	0
19523688	2271	sql apply formula to avg values	select (avg(case when tag = 'a' then read end) + avg(case when tag = 'b' then read end)) 'result', data from tbl group by data 	0.446082597801984
19523749	30926	sql matching up values in same row	select *   from [users] where cast(userid as varchar) = cast(paypalid as varchar) 	0.000214507076959236
19524783	26617	oracle how to select intervals	select employeeid,eventdate,entry_time,exit_time from (select employeeid,eventdate,entry_time,exit_time, rank() over (partition by employeeid,eventdate,exit_time order by entry_time asc) et from (select t.employeeid,t.eventdate,t.eventtime entry_time, o.eventtime exit_time,  rank() over (partition by t.employeeid,t.eventdate,t.eventtime order by o.eventtime asc) mt  from entries t,exits o where t.employeeid = o.employeeid and t.eventdate=o.eventdate and t.eventtime < o.eventtime) where mt =1)where et=1 	0.0343790234257286
19527780	20195	how to check if a column a in (3,4,5) and a not in (1,2)	select v.visitid from visits v where exists(select *     from visitdocs d    where d.visitid = v.visitid    and d.doctype = 3)    and not exists(select *                    from visitdocs d                   where d.visitid = v.visitid                   and d.doctype in (1,2)) 	0.00804409515113934
19531513	5161	can i add multiple columns to totals	select     sub.a,     sub.b,     (sub.a + sub.b) as c, from (     select          case when x > 4 then 4 else x end a,         (select count(*) somethingelse) b     from mytable  ) sub order by c 	0.00441137040243529
19532540	9366	union all - but with non-simultaneous execution of its parts	select a, b, c, count(*) cnt into #tmp from ... group by a,b,c alter table #tmp add constraint pk_#tmp primary key clustered (a,b,c) merge into #tmp x using (     select a, b, c, count(*) cnt     from ...     group by a,b,c ) i on x.a = i.a and x.b=i.b and x.c=i.c when matched then update set x.cnt= x.cnt + i.cnt when not matched then insert (a, b, c, cnt)     values (i.a, i.b, i.c, i.cnt); select * from #tmp 	0.0269306677290864
19532598	40330	(sql) selecting a row which has 2+ specific values associated with it	select * from tblarticles, (    select indarticle from tblarticlestagsrel    where indtag in(1, 2)     group by indarticle      having count(indarticle) = 2 ) where (pkindex = indarticle)  and (sname = "title"); 	0
19535007	15619	mysql find data that is between fields	select a.* from sometable a inner join sometable b on a.range_1 between b.range_1 and b.range_2 and a.range_2 between b.range_1 and b.range_2 and (a.range_1 != b.range_1 or a.range_2 != b.range_2) 	0.00151130712448626
19536435	11570	how calculate the time difference for multiple timestamp values for specific groups?	select x.*        , min(y.timecode) pair       , sec_to_time(time_to_sec(min(y.timecode))-time_to_sec(x.timecode)) diff    from my_table x    join my_table y      on y.name = x.name     and y.status <> x.status     and y.timecode > x.timecode   where x.status = 'on'   group      by x.name       , x.timecode; 	0
19536815	34927	mysql multiple left joins on same table	select    xxx,    p1.name as p1name,    p2.name as p2name from table1 left join table2 as p1 on table1.worker1 = p1.id left join table2 as p2 on table1.worker2 = p2.id where ... 	0.105811436235029
19536869	9034	get current rank joining another table, mysql	select a.item_id, a.category, @rank:=@rank + 1 as rank from table_details a inner join table_totals b on a.item_id = b.item_id cross join (select @rank:=0) sub1 where category = 'arcade' order by b.user_rating desc 	0
19536960	21551	join the same statement without where clause	select  (select max(id) as max from posts), (select  max(id) as old_max  from posts where time <      date_sub(now(), interval 1 hour)); 	0.566733083186268
19536987	7165	fininding and grouping max data	select agent,max(talk_time) as talk_time,max(updt_time) as updt_time from table  group by agent 	0.066841783382847
19537239	20631	mysql db join query	select      edetails.id,     edetails.name,     edetails.age,     edetails.dept,      edesig.desig,     edetails.basic,     edetails.pf,     edept.dept      from edetails          inner join edept on edetails.dept=edept.id inner join edesig on edesig.id=edetails.desig 	0.677478239513794
19537410	9964	group and order	select    id,    userid,    sendid,    left(mess,35),    sub1.maxtid,    status,    bild,    sendname,    sendinfo  from mailbox  inner join (     select sendid, max(xdatum) as maxtid     from mailbox      where userid='" &session("userid")& "'      group by sendid  ) sub1 on mailbox.sendid = sub1.sendid and mailbox.xdatum = sub1.maxtid where userid='" &session("userid")& "'  order by maxtid desc 	0.341903120334104
19540810	38466	how can i display parent-child-grandchild relationship without using with clause?	select t.id, t.name, t.parent, g.name as grandparentname from table1 as t     left outer join table1 as p on p.id = t.parent     left outer join table1 as g on g.id = p.parent order by t.id asc 	0.203105517384869
19541099	37057	sum multiple counts from multiple tables	select lookuptable.id,lookuptable.description, sum(cnt) as number  from lookuptable join (     select column1 as cid, count(*) as cnt from table1 group by column1     union all     select column2 as cid, count(*) as cnt from table2 group by column2     union all     select column3 as cid, count(*) as cnt from table3 group by column3     union all     select column4 as cid, count(*) as cnt from table4 group by column4 ) t1 on lookuptable.id =t1.cid  group by lookuptable.id,lookuptable.description  order by number desc 	0.00162983774947009
19542359	34527	how to pivot a query in mysql	select name,   sum(case when year = 2012 then revenue else 0 end) revenue2012,   sum(case when year = 2012 then qty else 0 end) qty2012,   sum(case when year = 2013 then revenue else 0 end) revenue2013,   sum(case when year = 2013 then qty else 0 end) qty2013 from yourtable group by name 	0.489109466343518
19545627	33606	returning non sequential records	select * from (select top 10 tbldata.* from    tbldata where   pk <= 5481 and dev_id = 'rec1' and code_id = 'fmu' and     cast(event_date_time as date) = '10/18/2013' union select  top 10 tbldata.* from    tbldata where   pk >= 5481 and dev_id = 'rec1' and code_id = 'fmu' and     cast(event_date_time as date) = '10/18/2013') a order by pk asc 	0.0201807591636322
19545750	4117	two occurrences of criteria in mysql	select listingagentfullname, listingagentmlsid, listingagentnumber from resi where searchprice >= 250000 group by listingagentfullname, listingagentmlsid, listingagentnumber having count(*) >= 2; 	0.000598249211504841
19546161	6142	what is the average response broken down by row?	select q.id, avg(s.survey_response) from survey_questions q inner join survey_responses s on q.id = s.survey_question_id group by q.id 	0.0526610467718876
19546744	26613	count amount of rows in database with the same value in two columns - use amount of top 5 rows to set width of 5 different divs	select  t.company_id,  t.company_name,  count(*) from  tble t group by  t.company_id, t.company_name, t.size_of_company order by  count(*) desc limit 5 	0
19546755	20669	sql - group based on multi - columns	select area_code as a_code,        count(*) as count_a_code,        sum(case when status = 1 then 1 else 0 end) as code_count_sts1,        sum(case when status = 2 then 1 else 0 end) as code_count_sts2,        sum(case when status = 3 then 1 else 0 end) as code_count_sts3,        sum(case when status = 4 then 1 else 0 end) as code_count_sts4,        sum(case when status = 5 then 1 else 0 end) as code_count_sts5 from your_table group by area_code 	0.00201859113690742
19546818	35003	sql group by date difference	select max(id), c1, c2, max([date]) from tbl group by c1, c2, dateadd(minute, datediff(minute,0,[date]) / 5 * 5, 0) 	0.0304283511895738
19547082	15221	join with the highest value in oracle	select s.id, s.name, sy1.grade, sy1.year from school_year sy1 left join school_year sy2   on sy1.student_id = sy2.student_id and sy1.grade < sy2.grade join students s on sy1.student_id = s.id where sy2.grade is null 	0.0043362567433389
19547318	23912	mysql join where occurs more than once in initial table	select      r.emailaddress as ag_email,      count(r.emailaddress) as `acount`,     e.listingagentfullname as ag_name,      r.officename as ag_office_name      from resi      e left join activeagent r      on e.listingagentnumber=r.membernumber     where searchprice >= 250000;     group by r.emailaddress     having acount >=2 	0.0017884288190962
19548527	28882	how do i combine these two queries?	select q.date, count(q.date) from (     select date, username     from table1     where date>='9/1/2013'     group by date, username ) q group by q.date 	0.0317950732987536
19548966	24041	is there a way to show this sql query on 1 line?	select co, [1] as checkdate1, [2] checkdate2, [3] checkdate3, [4] checkdate4, [5] checkdate5 from ( select cc.co,  row_number() over (partition by cc.co order by cc.co) as checkdatenum, checkdate  from ccalendar cc     inner join cinfo ci on cc.co = ci.co  where checkdate between '01/01/2014' and '01/31/2014'      and ci.enddate is null and ci.status in ('live', 'conversion') ) as t1 pivot (max(checkdate) for checkdatenum in ([1],[2],[3],[4],[5])) as checkdate 	0.318316205753418
19549208	41235	select from 3 tables and "in"	select a.`id`, a.`name`, a.`user_id`, a.`time`, a.'posts' as `what` from `posts` a join feeds_time b on a.user_id = b.user_id where a.`user_id` in (select `follow_id`                     from users_follow where user_id = posts.user_id) and a.time > b.time 	0.00569204567443956
19549372	38960	which method is better to store related data in table(s)	select     `user`.`uid` as `user`,     group_concat(`friendship`.`friend_id`) as `friends` from     `user` left join `friendship` on `user`.`uid` = `friendship`.`uid` group by     `user`.`uid` 	0.0886534254522402
19550162	11736	sql order with union	select mainq.* from  (   (select * from mytable as t1 where myfield = 1)   union    (select * from mytable as t2 where myfield = 2) ) as mainq order by mainq.tableid 	0.685509933826811
19551153	27492	best practice to store mixed type of numbers (percents and flat values)	select (original_value * ajustement_ratio + ajustement_absolute) as adjusted_value from ... 	0.00718189866792778
19551385	12446	how to get id of a newly created sql server database	select database_id from sys.databases where name = n'testdb1'; 	0.000669572621726003
19551686	39651	mysql: how to group the count of rows for each given time period?	select date_format(yourdate, '%y-%m-%d %h:00:00') hr, count(*) group by hr 	0
19553112	30319	conditional table selection in mysql	select   if(a.table1_type='b',b1.some_value,     if(a.table1_type='c',c1.some_value,       if(a.table1_type='d',d1.some_value,         if(a.table1_type='e',e1.some_value,           null)))) as table1_value,   if(a.table2_type='b',b2.some_value,     if(a.table2_type='c',c2.some_value,       if(a.table2_type='d',d2.some_value,         if(a.table2_type='e',e2.some_value,           null)))) as table2_value from a   left join b as b1 on a.table1_type='b' and a.table1_id=b1.id   left join c as c1 on a.table1_type='c' and a.table1_id=c1.id   left join d as d1 on a.table1_type='d' and a.table1_id=d1.id   left join e as e1 on a.table1_type='e' and a.table1_id=e1.id   left join b as b2 on a.table2_type='a' and a.table2_id=b2.id   left join c as c2 on a.table2_type='b' and a.table2_id=c2.id   left join d as d2 on a.table2_type='c' and a.table2_id=d2.id   left join e as e2 on a.table2_type='d' and a.table2_id=e2.id where [condition for a]; 	0.473203158860626
19553515	31528	check if database exists and current login can access	select has_dbaccess('yourdatabasenamehere') 	0.00612686429757521
19554364	27196	how can i select rows from mysql without including duplicates across two columns	select   min(id),   country,   domicile,   count(*) as domnum from (   select     min(id) as id,     country,     domicile,     count(*) as counum   from users   group by country   having counum=1 ) as base group by domicile having domnum=1 	0
19556618	8958	getting count of each category filtered by another table's field	select     `cat_table`.`id`,`cat_table`.`name`,`cat_table`.`level`,`cat_table`.`parent`,      count(`ad_table`.`id`)      from       `cat_table`      left join  `ad_table`      on         `ad_table`.`cat_id`=`cat_table`.`id`     and        `ad_table`.`type`='0'       where      (`cat_table`.`id`='c0100' or `cat_table`.`parent`='c0100')     group by   `cat_table`.`id` 	0
19557024	2256	last value selection in sql-server	select top 1 * from test order by id desc 	0.00121443254212085
19557689	5749	write a query which selects user name associated with a session id	select q116001, group_concat(log2002) from q116 group by q116001 	0.00206289194020413
19557879	18514	how to extract data from mysql to a csv file?	select * into outfile '/tmp/products.csv' fields terminated by ',' enclosed by '"' escaped by '\\' lines terminated by '\n' from products 	0.000374735980117155
19557966	30074	mysql groupby based on multiple fields	select count(*), min(startdate), max(startdate), item, type from (   select   startdate, item, type,            @group     := @group + 1 - (                            type      <=> @last_type                        and item      <=> @last_item                        and startdate <=> @last_date + interval 1 day                          ) g,            @last_type := type,            @last_item := item,            @last_date := startdate   from     productinfo, (              select @group     := 0,                     @last_type := null,                     @last_item := null,                     @last_date := null            ) init   order by type, item, startdate ) t group by g 	0.00482821745661664
19558443	30061	comma separated string of selected values in mysql	select group_concat(id)  from table_level where parent_id=4 group by parent_id; 	0
19560481	17271	value return null row from query sql server	select top 1 * from  (   select count(lhid) as noofdue   from dbo.tblloanhistory    where (lhemipaid=0 or lhemipaid is null)    and lhacno='010575100000114'    group by lhemi   union    select 0 as noofdue ) x order by noofdue 	0.00191603988885831
19560980	14143	how to make custom query from multiple tables	select u.id, u.name, status.status_name  from user u left join daily_status as ds on u.id=ds.user_id and ds.date='24/10/2013' left join status_types as status on ds.status_id=status.id where u.department_id=1 	0.0780593183363778
19561635	30935	oracle select like as column	select name,         (case when (name like '%adam%') then 1 else 0 end) as score from names  order by score desc 	0.405116715791848
19561953	38674	finding the count of columns in sql server under different conditions	select lib.name, count(*), sum(case when pub.price > 0 then 1 else 0 end) as 'paid publication count',  sum(case when pub.price = 0 then 1 else 0 end) as 'freepublication count'  from library lib inner join publication pub on lib.id = pub.fk_library_id group by lib.name 	9.34142844917782e-05
19562493	17249	if inside where mysql	select   if(path is not null, concat("/uploads/attachments/",path, "/thumbnails/" , nome), "/uploads/attachments/default/thumbnails/avatar.png") as avatar_mittente from prof_foto   where profilo_id = 15  and if( path != "/uploads/attachments/default/thumbnails/avatar.png",           foto_eliminata = 0 and foto_profilo = 1,         foto_eliminata like '%' and foto_profilo like '%'         ) 	0.73027768905902
19562595	1265	mysql how to sum subgroup first then sum total	select a.id_1, sum(b.num)+sum(distinct a.num)   from table_1 as a    left join table_2 as b     on find_in_set(b.id_2, a.ids_2)   group by a.id_1; 	5.46010940815708e-05
19564136	21094	mysql select * from last 5 days from a datetime field	select  *  from  'mytable'  where 'datetime' >=       (            select             `datetime`            from mytable            group by date(`datetime`)            order by `datetime` desc 4,1         ) 	0
19564184	2333	make a select query with group by	select a.id,        a.path,        a.category,        a.sector_id,        a.ddate from yourtable a inner join   (select category,            max(ddate) as ddate    from yourtable    group by category) b   on a.category = b.category     and a.ddate = b.ddate 	0.582005554910951
19564989	2583	how to extract table definitions using sql or toad	select * from all_tab_cols where owner = 'cco'; 	0.0654675791769606
19569419	17984	i have created a view. but i want to call it from my database instance	select * from [msdb].[dbo].[vwconfirmemailsent] 	0.117285876845563
19570102	39679	how do i display data from a count() query?	select count(distinct member_extension) as num_extensions foreach ($sql as $rs) {     echo '<tr>';     echo '<td>' . $rs['queue_name'] . '</td>';     echo '<td>' . $rs['queue_account_id'] . '</td>';     echo '<td>' . $rs['num_extensions'] . '</td>';     echo '</tr>';     } 	0.000634158056184972
19572445	18168	iss with distinct values	select  distinct (collections) from audios order by collections desc limit 40 	0.0687954868504451
19572921	30470	select distinct column and then related columns in php/sql	select sender, receiver, message, timestamp, parent from messages  where receiver='$log_username' or sender='$log_username'  group by parent order by timestamp desc 	0.00034477823017728
19573084	34112	sql table - name each row	select 'daily' as ' ', [new orders],[cancels],[net] from [dailyfigures] where [uid]  in    (select top 1 [uid] from [dailyfigures] order by [uid] desc)  union all select 'weekly' as ' ', [orders],[cancels],[net] from [weeklyfigures] where [uid]  in    (select top 1 [uid] from [weeklyfigures] order by [uid] desc) union all select 'monthly' as ' ', [orders],[cancels],[net] from [monthlyfigures] where [uid]  in    (select top 1 [uid] from [monthlyfigures] order by [uid] desc)  union all select 'quarterly' as ' ', [orders],[cancels],[net] from [quarterlyfigures] where [uid]  in    (select top 1 [uid] from [quarterlyfigures] order by [uid] desc)  union all select 'annually' as ' ', [orders],[cancels],[net] from [annuallyfigures] where [uid]  in    (select top 1 [uid] from [annuallyfigures] order by [uid] desc)  union all select 'total' as ' ',      sum([orders]) as orders,      sum([cancels]) as cancels,      sum([net]) as net  from [annuallyfigures] 	6.4756522614202e-05
19573892	36831	sql query grouped by contigious foreign key values	select  z.vendorid, z.groupid,         min(z.datereceived) as datereceivedstart,          max(z.datereceived) as datereceivedstop,          sum(z.quantity) as sumofquantity from (     select  y.vendorid,             y.rownum1 - y.rownum2 as groupid,             y.datereceived,             y.quantity     from      (         select  *, row_number() over(order by x.datereceived) as rownum1,                    row_number() over(order by x.vendorid, x.datereceived) as rownum2         from    @mytable x     ) y ) z group by z.vendorid, z.groupid order by datereceivedstart 	0.000802793310741081
19573940	5593	sql query to return null instead of sum when null exists	select     y,     case when count(x) <> count(*) then null else sum(x) end from test group by y 	0.0977174549211196
19574049	26884	sql smallest value with left join	select * from   article left join (          images natural join (            select   article_id, min(position) as position            from     images            group by article_id          ) as t        ) using (article_id) 	0.306579110969138
19574410	11048	mysql top10 list with counter using only one query	select   invitor.name, count(*) as invites from     table_users invitor     join table_users invitee on invitee.invited_by = invitor.user_id group by invitor.user_id order by invites desc limit    10 	0.0176929916191819
19574872	13890	trouble with mysql query across multiple tables	select p.name from users u join security s on u.security_id=s.id        join pages p on s.id=p.security_id where u.username='currentuser'  and    (select level from security s join users u on  s.id=u.security_id where u.username='currentuser' group by level ) >= (select level from security s join pages p on  s.id=p.security_id join users u on  s.id=u.security_id where u.username='currentuser' group by level) 	0.511371295981011
19578020	6287	sysmail_sentitems is not populating even email has been sent.	select * from msdb.dbo.sysmail_mailitems select * from msdb.dbo.sysmail_log 	0.0784731398218545
19578136	4978	combine data of two tables	select sdate, sum(tevent) as tevent,  sum(tschedule) as tschedule, sum(tlog) as tlog from ( select date_format(sdate, '%m-%d-%y') as sdate,  sum(type='event') as tevent ,  sum(type='schedule') as tschedule, 0 as tlog from table1 group by sdate union select date_format(dtime, '%m-%d-%y') as sdate , 0 as tevent,0 as tschedule, count(id) as tlog from table2  group by sdate  ) s group by sdate; 	0.000750344887910076
19579724	9614	how to test for null in sql query	select user_name, user_second_choice  from tbl_user where user_assigned_project is null 	0.534024849413237
19580567	23548	oracle converting string(date with timezone) to date	select to_date(substr('1980-10-05t23:30:00+08:00', 1, 19), 'yyyy-mm-dd"t"hh24:mi:ss' ) from dual; 	0.728862420136262
19580751	26327	removing groups of similar records in mysql query	select fruit  from fruitnames  group by fruit having sum(`date` = curdate()) = 0 	0.00321357114600788
19581881	27814	returning value from select statement	select a.name, a.addres,       case when a.amount is null then 0 else 333 end amount   from table_main a  wher a.id=3345 	0.0268051840711457
19582239	6155	how to search for records between two dates when date is in varchar without seperators in database?	select *,         left(convert(varchar, t.[parseddate], 120), 10) as parseddate2  from   (select *,                 convert(datetime, stuff(stuff([startdate], 3, 0, '-'), 6, 0, '-')                 , 105)                        as                 parseddate          from   mytable) as t  where  t.[parseddate] between '2013/10/10' and '2013/10/20' 	0
19582967	7784	how to handle large mysql queries	select  p2c.pid as productnumber,         p.name as productname,         count(*) as registered,         sum(date_add(from_unixtime(purchased), interval 5 year) >= curdate()) as inwarranty,         sum(date_add(from_unixtime(purchased), interval 5 year) < curdate()) as outofwarranty,         date_format( max( from_unixtime(purchased) ), '%d.%m.%y') as lastpurchased,         date_format( date_add( max( from_unixtime(purchased) ), interval 5 year), '%d.%m.%y') as warrantyuntil from products2customers p2c join products p on p.id = p2c.pid group by p2c.pid order by inwarranty desc 	0.455183627647669
19583212	30857	distinct value from multiple tables in mysql	select distinct id from ( select id from table1 join table5 on table1.id=table5.id where table5.team='alfa' union all select id from table2 join table5 on table2.id=table5.id where table5.team='alfa' union all select id from table3 join table5 on table3.id=table5.id where table5.team='alfa' union all select id from table4 join table5 on table4.id=table5.id where table5.team='alfa' ) t1 	0.000885042459838869
19583635	15031	making mysql 'in' search returning all related rows	select  a.id,         a.name,         group_concat(distinct c.appname order by a.id separator ',') result from    interface a         inner join inetrapp b             on a.id = b.interid         inner join app c             on b.appid = c.appid         inner join         (             select  distinct a.interid                  from    inetrapp a                     inner join app b                         on a.appid = b.appid             where   b.appname in ('sap1')         ) d on  a.id = d.interid group   by a.id, a.name 	0.00498225842058874
19584338	30158	query the so data explorer for questions with 4 close votes within a specific tag	select   posts.id from    posts   inner join votes on posts.id = votes.postid where   posts.posttypeid = 1   and posts.tags like '%c#%'   and votes.votetypeid = 6 group by   posts.id having count(distinct votes.id) > 4 	0.0526792842938996
19584957	32964	sql server desired output from tables	select      case when isnull(secondtable.id,0) = 0          then firsttable.dept          else ''     end as department,      case when isnull(secondtable.id,0) = 0          then manager.name           else ''     end  as manager,      firsttable.name from mytest as firsttable left join mytest as secondtable on     secondtable.id = (select top 1  mytest.id                       from mytest                        where mytest.manager = firsttable.manager                         and mytest.dept = firsttable.dept                         and mytest.id < firsttable.id                       order by mytest.id desc)  left join mytest as manager on manager.id = firsttable.manager  where firsttable.manager <> 0 order by firsttable.dept, firsttable.id 	0.238761698275938
19585692	359	sql query to get total orders (count) by customer type	select  2013 as [year],         months.number,         amount = sum(coalesce(o.total,0)),         c.customertypeid from    customers c cross join (select number from master..spt_values where type='p' and number between 1 and 12) months left join [orders] o on c.customerid = o.customerid and year(o.orderdate) = 2013 and month(o.orderdate) = months.number group by months.number, c.customertypeid  order by months.number, c.customertypeid 	0
19586226	866	diplaying records of last month and year	select * from tablename where   (year, month) = (select year, month                    from tablename                    order by                      str_to_date(concat_ws(' ', '01', month, year), '%d %m %y') desc                    limit 1) 	0
19587400	28460	display latest entry from different mysql table	select * from (select col1, col2, date       from table1       order by date desc       limit 1       union       select col1, col2, date       from table2       order by date desc       limit 1       union       select col1, col2, date       from table3       order by date desc       limit 1) u order by date desc limit 1 	0
19587976	32315	tsql - joining two tables without columns in common	select *  from inf join score on (inf.results between score.ratio_start and score.ratio_end); 	0.000202666934006678
19588044	34348	getting custom xml from t-sql	select     f.n, t.l, grp.n, cat.n, col.n,     (select col_value for xml path(''), type) from fc      inner join f on f.idfc = fc.idfc     inner join t on t.idf = f.idf     inner join grp on grp.idt = t.idt     inner join cat on cat.idgrp = grp.idgrp     inner join col on col.idcat = cat.idcat     inner join col_value on col_value.idcol = col.idcol for xml auto, root('fc') 	0.121552676591187
19588785	15510	get result for table having two foreign key of same table	select a.p_id f1, a.p_name f1_name, b.p_id f2, b.p_name f2_name from people a join friendship f on (f.f1 = a.p_id) join people b on (f.f2 = b.p_id) 	0
19588841	882	how to display record or data of single item from 3 joins	select  pm.prod_name,  am.attribute_name,  pa.product_attribute_value  from product_attrib_master pa  left join attribute_master am  on pa.attribute_id = am.attribute_id  left join product_master pm  on pa.prod_id=pm.prod_id where pm.prod_name ='nokia lumia 925'  and prod_id = 12  order by pa.prod_id; 	0
19589365	6802	sql query to get default value as 0 for a particular column	select  2013 as [year],         months.number,         amount = sum(coalesce(o.total,0)),         c.customertype from    customers c cross join (select number from master..spt_values where type='p' and number between 1 and 12) months left join [orders] o on c.customerid = o.customerid and year(o.orderdate) = 2013 and month(o.orderdate) = months.number group by months.number, c.customertype  order by months.number, c.customertype 	0.000260474581376286
19589810	19359	update column using comma-separated values in sql server	select id,skillsetrequired       from #table1      open @curskillupdate      fetch next      from @curskillupdate into @id,@skills      while @@fetch_status = 0      begin         set @result = ''                     select @result = @result + ltrim(rtrim(skillname)) + ',' from  #table2 where id in(         select substring(items, 0 + 1, charindex('-', items, 1) - 0 - 1)  from split(@skills,','))                   update #table1 set skilldesc=@result where id=   @id      fetch next      from @curskillupdate into  @id,@skills      end 	0.0808667482083302
19590183	26863	sql select join on xml field with xpath expression	select     f.id, children.p.value('./speed[1]','float') from files as f     outer apply (select cast(f.data as xml) as xml) as x     outer apply x.xml.nodes('root/children') as children(p) where      f.id in (1005,51,968,991,992,993,969,970) and      children.p.value('./name[1]','nvarchar(max)') = 'something' 	0.785500702849496
19590598	18564	getting the decriptions of the tables and columns via a sql statement	select      t.name as tablename    , td.value as tabledescription   , c.name as columnname   , cd.value as columndescription from sys.tables t inner join sys.columns c on t.object_id = c.object_id left join sys.extended_properties td      on td.major_id = t.object_id     and td.minor_id = 0     and td.name = 'ms_description' left join sys.extended_properties cd      on cd.major_id = t.object_id     and cd.minor_id = c.column_id     and cd.name = 'ms_description' 	0.00103396031041913
19591901	16361	create a union query that identifies which table the unique data came from	select     customer_id,     min(source) as sourcetable,     count(*) as tablecount from     (         select distinct             customer_id,              "tblone" as source         from tblone     union all         select distinct             customer_id,             "tbltwo" as source         from tbltwo     ) group by customer_id 	8.92316349279139e-05
19592861	18276	adding days to a start date to create and ending date	select    start_date,    duration,    date_add(start_date, interval duration day) as end_date 	0
19592874	6836	sql help extracting data from one table and based on a backup table, inserting that data	select *  from fiberstrandhas fsh inner join (select * from fibersplice fs where endstrand not in (select id from fiberstrand ft)) es on (fsh.id = es.endstrand) 	0
19593307	29741	share of invoiced in total (sum group by)	select *,invoiced/total as colname from ( select   salesid,linenum,itemid,salesstatus,name,lineamount ,(select sum(case when salesstatus=3 then lineamount else 0 end from t.saleslines) as invoiced ,(select sum (lineamount)from t.saleslines group by salesid) as total from t.saleslines) source group by salesid,linenum,itemid,salesstatus,name,lineamount,invoiced,total 	0.000909913481561698
19593630	22420	getting specific number on specific episode for patients	select  pct.patient_id, pct.episode_id, pct.axis_i_ii_3, pct.proc_chron, pct.clinic_id from patient_clin_tran pct join patient p on pct.patient_id = p.patient_id join ( select patient_id, max(proc_chron) maxdate from patient_clin_tran where whatever group by patient_id ) temp on temp.patient_id = pct.patient_id and pct.proc_chron = maxdate etc 	0.000189780369974109
19594993	18001	replacing multiple unique ids with login name from fact table	select table.id1, fk1.name      , table.id2, fk2.name    from table    join fk as fk1      on fk1.id = id1    join fk as fk2      on fk2.id = id2 	0
19595233	9708	get name of person having activity in every month - oracle sql	select distinct employeeid from (     select employeeid,            count(distinct trunc(eventdate,'month'))                      over (partition by employeeid) as emp_months,            count(distinct trunc(eventdate,'month'))                      over () as all_months,     from transactions     ) where emp_months = all_months; 	0
19595330	8371	how to get maximum value of two fields from two different tables in oracle	select max(uid_proc) from( (select max(uid_proc) as uid_proc from log_mig) union all (select max(uid_proc) from log_mig_error) ) 	0
19596125	35281	selecting data from three tables	select films.movie_title, films.rating, films.actor, reviewed.review, users.name   from films   left join reviewed on films.movie_id=reviewed.movie_id   left join users on films.user_id=users.user_id 	0.000610017593186626
19596878	18224	how to count specific words using php and mysql	select sum(server1 = 'yes') as s1_yes,        sum(server2 = 'yes') as s2_yes,        sum(server1 = 'no') as s1_no,        sum(server2 = 'no') as s2_no from your_table 	0.0161096789987184
19597659	6616	how to compare a column with comma seperated numbers and a specific number using regexp in mysql	select find_in_set('24','24,25,26 '); 	0
19597800	14590	how to order mysql rows in custom order?	select ... order by  case substr(one_column,1,1)    when 'n' then 0    when 'y' then 1    when 'f' then 2    when 'p' then 3    when 'u' then 4    else 5 end 	0.0898130188567804
19597908	22190	how to return true or false from tsql using case when	select isgeneric = case when p.[genericcatalogid] > 0 then cast(1 as bit) else cast(0 as bit) end              from storefront.project p with(nolock)              where p.id = @projectid; 	0.429902959673372
19599267	21876	returning table.column in a sql select statement	select deal.deal_id "deal.deal_id" from deal  where deal.deal_id= '1'; 	0.78591921724645
19603087	25903	how to query for >= to <= in for column values in mysql	select * from your_table where cast(extension as signed) > 00 and cast(extension as signed) < 11111 	0.0138474636158822
19604940	21066	ignore field used in having clause on select	select id,         name,        level,         count from (   select parent.id as 'id', parent.ca_name as 'name', node.level as 'level',  midpoint.level as 'midpointlevel', sum(ad.id is not null) as 'count'   from   category as parent,   category as midpoint,   category as node   left join ad on ad.id=node.id   and ad.status='a'   where (node.`left` between parent.`left` and parent.`right`)   and (node.`left` between midpoint.`left` and midpoint.`right`)   and midpoint.id='1'   group by parent.id   having if(midpoint.level=0, node.level < 2, node.level > 0)   order by parent.id ) subquery 	0.401771250280945
19605175	31511	get top rated item using avg mysql	select a.title, avg(d.rating) as rating from in8ku_content a   join in8ku_content_ratings d on a.id = d.article_id group by a.title  order by rating desc 	0.000737613116660393
19605781	613	sql query to get top customer according to joining date	select top 20 *  from customers where year(createddate) = 2013 order by createddate 	0
19608013	8405	merge 2 selects into 1	select g.naam,g.gebruikerid ,g2.naam,g2.gebruikerid from gebruiker g , gebruiker g2, vriend v where g.gebruikerid = v.gebruikerid_jezelf  or g2.gebruikerid = v.gebruikerid_persoon and g.gebruikerid in(select gebruikerid_jezelf from vriend)  or g2.gebruikerid in(select gebruikerid_persoon from vriend); 	0.0031892115581272
19610760	29924	sorting through the logic of available units in a reservation system	select unit from unit u  left join reservations r on r.unit = u.id and r.arrival <= $departure and r.departure >= $arrival where r.unit is null 	0.156593455355451
19612022	19352	retrieve one id referred by two ids	select tu1.thread_id from thread_users as tu1 inner join thread_users as tu2   on tu1.thread_id = tu2.thread_id   and tu1.user_id <> tu2.user_id left outer join thread_users as tu3   on tu1.thread_id = tu3.thread_id   and tu1.user_id <> tu3.user_id   and tu2.user_id <> tu3.user_id where tu1.user_id = 1   and tu2.user_id = 2   and tu3.user_id is null 	0
19613003	34536	how do i join two tables and then select two different columns?	select    m.match_id,    f1.fightr_namn as fighter1name,    f2.fightr_namn as fighter2name  from matches m inner join fighters f1 on m.fightr_id1 = f1.fightr_id inner join fighters f2 on m.fightr_id2 = f2.fightr_id 	0
19613567	21317	query database for list of records intersecting with relational table	select movie.name from movie join moviehascast mc on mc.movieid = movie.id join cast on cast.id = mc.castid where cast.name in (@actor1, @actor2) group by movie.name having count(1) = @numberofactorssearched 	0.00121762027024379
19613718	14627	mysql - get row and average of rows	select   i.* from     items_table i join (            select   category, avg(score) as averagescore            from     items_table            group by category          ) t using (category) order by i.score/greatest(5, t.averagescore) desc limit    1 	0
19614591	30638	mysql: multiple sums counting combined values where condition	select article_id,    sum(case when vote >0 then vote else 0 end) as postive,   sum(case when vote <0 then vote else 0 end) as negative from article_vote group by article_id 	0.0083250403913732
19615323	10407	sql statement: how to retrieve and display each user and the many items they purchase	select c.*, i.* from (select * from customers limit 0, 3) c join customer_item ci on c.customer_id = ci.customer_id join item i on ci.item_id = i.item_id order by c.customer_name, i.item_name 	0
19617942	26361	select sql query from table	select * from bikedata where price (between value1 and value2) and name like pattern; 	0.030443670049246
19618734	6900	joining two tables with more connections to the same table in a row	select   tb.num 'num',   ta1.name 't1',   ta2.name 't2' from   tableb tb inner join tablea ta1 on tb.t1 = ta1.value             inner join tablea ta2 on tb.t2 = ta2.value where   ta1.value <> ta2.value 	0
19623980	9320	retrieve matching data twice from same left join table?	select cards.*, main_name.name, enemy_name.name  from cards  left join list as main_name on cards.main = main_name.id left join list as enemy_name on cards.enemy = enemy_name.id where cards.id = 1 	5.79791442313876e-05
19624075	31582	ms sql grouping by day then count result for each day	select     visitdate,     sum(case when customertype = 'a' then 1 else 0 end) as typea,    sum(case when customertype = 'b' then 1 else 0 end) as typeb,    count(*) as total from (     select distinct          customer,          cast(visitdate as date) as visitdate,          customertype from activity     ) x group by      visitdate 	0
19626779	35610	how to get non-aggregate value from a record while using max()?	select * from ( select symid, current_price, row_number() over (partition by symid order by price_date_time desc) as rn from tblhistory ) as t where rn = 1 	5.23622835193938e-05
19627697	17833	sql to check string contains with where clause	select string from commasplit(@srch,'') where string  in (select * from commasplit(@srch) 	0.367656259953625
19628590	11395	select field by next month(char6)	select   code,   name,   (select state    from dbo.shiftlist     where month = cast(year(dateadd(month, 1, getdate())) * 100                 + month(dateadd(month, 1, getdate())) as char(6)) ) as slnm from dbo.shops 	0.00615259278863182
19628791	11096	mysql, order by subquery count	select * from  (select      id, user_id, roi,      (select count(id) from main_ub u where u.user_id=w.user_id and u.cons > 0) as count  from      main_stats w  where      week=43 and year=2013 and votes > 2) res  where res.count >= 20 order by      res.roi desc limit 1 	0.560837471486154
19629677	8831	sum of dynamically generated fields in mysql query	select    @rank1 := 5 * (`mean (all)` +0.01735568 )/(0.07268901) as rank1,     @rank2 := 5 * (`cvar 95` +0.51612 )/(0.53212) as rank2,     @rank3 := 5 * (`hurst` - 0.2 )/(0.7717653) as rank3,     @rank4 := 5 * (`maxdd` +6.200000762939453 )/(16.200000762939) as rank4,     @rank5 := 5 * (`positive % 12` - 0.3 )/(1) as rank5,    @rank1 + @rank2 + @rank3 + @rank4 + @rank5 as rank from `quant1` 	0.0280009087361431
19630504	4492	mysql like on one row, like on multiple row inner joined tables	select *  from kill_list a join kill_list_designation b on a.id=b.kill_list join targets c on b.target=c.id where a.batch_name like concat('%', 'query term', '%')     or a.execution_date like concat('%', 'query term')     or a.status like concat('%', 'query term', '%')    or c.firstname like concat('%', 'query term', '%')     or c.laststname like concat('%', 'query term', '%'); 	0.00129869916314139
19632458	13867	how to determinate if the element 'word4' of the string 'word1;word2;word3;word4' is in the string 'word4','word5','word6','word7'?	select a.*, l.relevance from article as a inner join (     select ac.articleid, count(ac.categoryid) as relevance     from articlecategory as ac     inner join category as c     on ac.categoryid = c.categoryid        where c.name in ('cat','dog','donkey','chicken')     group by ac.articleid ) as l on a.articleid = l.articleid order by l.relevance desc, name 	0.000967795452960568
19632862	17433	mysql query to search to match a single word	select `text` from `tbl_strings` where `text` regexp '[[:<:]]pencil[[:>:]]' 	0.0209654220191612
19633019	5062	need a query to get top n rows from mysql database based on a condition	select * from yourtable where `status` = "pass" limit 3; 	0
19633277	24301	select if string is like a field in database	select * from tbl_yourtable t where t.columnname like '%' + @searchstring + '%' 	0.0767065273071615
19634548	19951	use same column in a sql query twice	select  electricitymachinepaneldetails.machinedescription as "machine name", readingvalue as "last day meter reading", readingvalue as "last day meter copy" from electricitydailymeterreadingdetails inner join electricitymachinepaneldetails on electricitymachinepaneldetails.machinepanelid = electricitydailymeterreadingdetails.machinepanelid inner join readingtypesdetails on electricitydailymeterreadingdetails.readingtypeid = readingtypesdetails.readingtypeid where readingcategoryid = 'rc001' and readingtypesdetails.readingtypeid = 'rt001' 	0.0546585556168363
19634633	26743	a keyword to specify in where clause to get all the data without filtering the field	select * from user where @status is null or status = @status 	0.000826781818911384
19634661	20789	mysql - join users latest level, not any level?	select coalesce(z.elevation,1) elevation      , u.id   from users u   left    join       ( select user             , elevation          from rights x          join              ( select user,max(starts) max_starts from rights group by user ) y            on y.user = x.user           and y.max_starts = x.starts         where '$time' between starts and ends      ) z     on z.user =  u.id 	0.0706835254516626
19634950	6355	sql query to get top records with highest value of 2 columns	select  top 10         sum(orders.businessvolumetotal) as bv,         sum(orders.commissionablevolumetotal) as pv,         isnull(customers.firstname,''), customers.lastname from    customers inner join orders on customers.customerid = orders.customerid where   orders.orderdate >= convert(datetime, '1/1/2013 12:00:00 am')         and orders.orderdate < convert(datetime, '12/31/2013 12:00:00 am') group by customers.firstname, customers.lastname order by sum(orders.businessvolumetotal) + sum(orders.commissionablevolumetotal) desc 	0
19636318	38788	mysql: find "last modified" date from two tables	select r.id, r.staff_member_id, ...,        greatest(r.date_time, coalesce(c.date_time, 0)) last_modified   from tech_requests r left join  (   select tech_request_id, max(date_time) date_time     from comments c    group by tech_request_id ) c     on r.id = c.tech_request_id  order by last_modified 	0
19637423	3261	implementing count() and group by() in mysql using two tables	select tbl_name.*, count(tbl_parent.member_id) as child from tab_name left join tbl_parent on tbl_name.member_id = tbl_parent.parent_id group by tbl_name.member_id 	0.122063115480634
19637642	8606	mysql distinct results of a set of distinct results	select tape, mask, count(*)     from wafer_name_table     group by tape, mask; 	0.00179489492961755
19638977	18378	handling null values on select query mysql	select * from users u left join stockholders s on u.user_id = s.user_id where u.user_type = 1 and (s.election_id <> 1 or s.election_id is null) 	0.476161293196998
19640162	35518	find the place of decimal point in decimal number	select charindex('.', cast(123567.89 as varchar)) 	0.000165256411276541
19641071	27043	classic asp form giving sql server conversion failed when converting the varchar value '%%' to data type int	select * from jobs where jobid like '%yourvalue%'. 	0.765095284204785
19641457	8559	select all sql records within hour range	select * from morecrimes where datepart('hour',date)>=22 or datepart('hour',date)<6 	0
19642811	36744	combine 2 column values in 1 to many into new row in new table - sql	select     account_number,     max(case          when descriptor like 'company: %' then substr(descriptor, 10, 1000)      end) company_description,     max(case          when descriptor like 'cost center: %' then value      end) cost_center_value from     test  group by     account_number 	0
19643232	9571	formating a phone number in the postresql query	select   '(' || substring((phonenumber, 1, 3) + ') ' || substring(phonenumber, 4,3) || '-' || substring((phonenumber,7,4) 	0.0982473609095661
19643700	4895	sql - find the closest pair of numbers to a provided pair	select   * from     my_table order by abs(2.5-num1) + abs(10.2-num2) limit    1 	9.65649424797936e-05
19644252	18458	sql: how to get relational data from two tables? (using join ?)	select customers.id, customers.customer_name, to-dos.task  from to_dos inner join customers  on to_dos.customer_id = customers.id where customers.company_contact = 1 	0.00358634634897866
19645453	33063	how to extract dates with datatye datetime from colum a in table x and put them into table y while changing datatype into date	select   incidentid from incidents where reportingdate >= '20131005'     and reportingdate < '20131006' 	0
19645928	36130	mysql tables relationships	select com.comment from collection col   inner join image i     on i.collection_id = i.collection_id   inner join comments com     on com.image_id = i.image_id where col.user_id = {user_id}  	0.102287290020364
19646400	16100	get data sorted even if some references are null	select p.desc, p.price, m.title from products as p left join manufacturer as m on m.id = p.manufacturer_id order by m.title 	8.40506031496253e-05
19646540	4545	mysql/php/wordpress - php result object contains members with function names - how to dereference?	select date1, monthname(date1) as `month`, weekday(date1) as `week` from my_table 	0.0363955948916943
19646680	1945	join a list of ids in a string with another table	select * from tblorder  where ',' + replace(@varcharwithcommaseparatedvalues, ' ', '') + ',' like '%,' + convert(varchar(10), orderid) + ',%' 	0
19647275	6785	checking for certain data across servers in mysql	select count(*) from table1 where userid = 'some_value' and user_level = 3 	0.00191236188113545
19647544	709	mysql: concat_ws to select from other table	select group_concat(          concat_ws(' - ', t1.item, t2.item)          separator '\n'        ) from   t1 join t2 on ... 	0.00370859976617667
19648012	39698	sql server - find top n customers with maximum orders	select distinct co.customerid, co.orderid from  (   select top(2) cos.customerid, count(distinct cos.orderid) as nooforders   from custorders as cos   group by cos.customerid   order by count(distinct cos.orderid) desc, customerid  desc ) as com  inner join custorders as co   on com.customerid = co.customerid 	0
19648642	20167	how to select only 1 unique data when joining two tables, if the table structure is one to many?	select count(distinct tablea.productid) from   tablea  join   tableb on tablea.productid = tableb.productid; 	0
19649202	37047	sql server how to combine multiple results in one row?	select  companyname  = (select top 1 companyname from dbo.customers), lastname = (select top 1 lastname from employees), categoryname = (select top 1 categoryname from dbo.categories) 	0.00104596722695304
19649983	14381	sql getting a row with min(col a) if 2 row exist then min(colb)	select top 1 cola, colb from table1 order by cola, colb 	0.000214581723822431
19650317	23	to get correct ascending order using sql query	select  substring(bundle_code,0,charindex('b',bundle_code,0) + 1) as bundle_code from item_bundle where item_code='f-4x10al' and branch ='kochi' order by cast(substring(bundle_code,0,charindex('b',bundle_code,0)) as int) 	0.103837561227846
19653692	4015	mysql select last 2 elements ascending followed by 1st element	select id   from (   (     select id, 0 sort_order       from table1      order by id desc      limit 2   )   union all   (     select id, 1 sort_order       from table1      order by id       limit 1   ) ) q  order by sort_order, id 	0
19655536	2629	average numbers in my sql query	select enquete_vraag,avg(enquete_antwoord) enquete_antwoord,docent,vak,semesterstart  from enquete_antwoord  left join kdv on enquete_antwoord.kdv_id = kdv.kdv_id  left join docent on kdv.docent_id = docent.docent_id  left join vak on kdv.vak_id = vak.vak_id  left join enquete_vraag on enquete_antwoord.enquete_vraag_id = enquete_vraag.enquete_vraag_id  where docent.docent_id = variabledocentid and vak.vak = variablevak  group by enquete_vraag, docent,vak,semesterstart 	0.0407817250890677
19656396	4429	not ordering all column values	select qm.sipara,         prayed = count(qp.sipara)  from quranmaster qm left join       quranprayed qp on (qp.sipara = qm.sipara and qp.timestamp >= '2013-10-27 19:59:00.000' and qp.timestamp <= '2013-10-28 20:00:00.000') group by qm.sipara,qm.orderid  order by qm.orderid 	0.00725266276470191
19656484	36892	how can i count my users, and sum them as i go?	select a.date1,sum(b.id) as mark from tab a cross join tab b where b.id <= a.id group by a.id,a.date1 	0.0199366321877366
19656486	27502	stored procedure always returning one row result in sql server	select * from transaction_tbl  t inner join transactdamageassign_tbl tr on tr.transactid = t.transactid inner join damagetype_tbl dt on dt.dtid = tr.dtid inner join damageside_tbl ds on ds.sid = tr.sid where t.tbarcode=@carid 	0.117753762642225
19656503	2186	fetch the records from current month	select total_price from cust_cart_table where user_id      = '"+userid+"' and (trunc(purchased_date) between trunc(sysdate, 'mm') and trunc(last_day(sysdate))); 	0
19656593	7660	conditions in sql subqueries	select companyname, count(orders.orderid) orders    from customers join orders on customers.customerid = orders.customerid    where country in('germany','brazil')     group by companyname     having count(orders.orderid) >= 10    order by orders asc; 	0.786293346396151
19657952	2436	mysql subtotal based on duplicate	select t1.col1, sum(t2.col2) from table1 t1 left join table2 t2 on t1.team = t2.team group by t1.col1 having count(t1.team) > 1 	0.00126901409486603
19661595	15106	aggregate on the max element of a join table	select mu.*      , m.id as message_id      , m.conversation as message_conversation      , m.from as message_from      , m.text as message_text      , m.date_created as message_date_created      , fromuser.type as user1_type      , fromuser.name as user1_name      , fromuser.email as user1_email      , fromuser.avatar_blob_key as user1_avatar_blob_key  from message_user as mu     left join message as m         on m.id = mu.message             and m.date_created =    (                                     select max( m1.date_created )                                     from message as m1                                     where m1.conversation = m.conversation                                     )     left join user as fromuser         on fromuser.id = m.from where mu.to = <some user id> group by m.conversation order by mu.message desc; 	0.00445779420461895
19661954	23706	sql merging cells	select t1.s_id,        stuff(            (select '; ' + symbol as [text()]                from   (                       select t.s_id,                              d.symbol                       from   t                       inner join d on  t.d_b_id = d.id                       where t.s_id = t1.s_id                                             ) x             for xml path('')            ), 1, 1, '') from t t1 group by t1.s_id 	0.0285395575034498
19663862	23636	mysql: how to select rows which have the lowest value in a field?	select * from tablename where pointer = (select min(pointer) from tablename) 	0
19665478	35769	how to retrieve all records from one table in join with current month records	select users.name  from users left join payments   on users.id = payments.userid where payments.paydate = <date you are looking for> 	0
19668608	41003	need a blank value returned if no subquery results	select spriden_id,            spriden_last_name,            spriden_first_name,            gorpaud_pin  from spriden left outer join   (select a.* from gorpaud a    where to_char(a.gorpaud_activity_date, 'yyyy-mm-dd hh24:mi:ss') =      (select max(to_char(b.gorpaud_activity_date, 'yyyy-mm-dd hh24:mi:ss'))         from gorpaud b        where b.gorpaud_pidm = a.gorpaud_pidm         and b.gorpaud_chg_ind = 'p'          and b.gorpaud_pin is not null)) t on spriden_pidm = t.gorpaud_pm 	0.0501275504396606
19669102	8022	how to count records and display those counted records?	select cast(cast(count([assigned to]) as varchar(10)) + ' - ' +  [assigned to] as varchar(50))  as usercount from dbo.ecrsurvey group by [assigned to] 	0
19670031	6066	left join with multiple tables and conditions	select o._id,        o.titel,        o.beschreibung from   `objekt` as o        join `objekt_einzel` as oe on o._id = oe.objekt_id        join `objekt_einzel_immobilie` as oei on oe._id = oei.objekt_einzel_id        join `objekt_art` as oa on o.objekt_art_id = oa._id        join `verortung` as v on o.ort_id = v._id        left join `person_bauträger` as pb on oe.bauträger_id = pb._id        left join `person` as p on pb.person_id = p._id where  oei.justimmo_objekt_id = "0"        or oei.justimmo_objekt_id is null        or oei.justimmo_objekt_id = "" order  by p.firmenbezeichnung asc 	0.657341882295074
19671161	24640	select records from 2 weeks prior using timestamps in mysql	select     * from     yourtable where     datefield<=unix_timestamp()     and datefield>=(select unix_timestamp()- 60*60*24*14) 	0
19673409	16846	how to get last value and sum a group of values in sql?	select p.type_money, sum(i1.net_insurance) total from (   select max(id) id from insurances   group by policy_id ) i2 join insurances i1 using (id) join policies p on p.id = i1.policy_id group by p.type_money 	0
19674245	19084	use a computed column in another column which is a query itself	select   convert(date, requestedon) as [date],    count(*),    sum(case when <other_static_conditions> then 1 else 0 end) as [count] from calculatorlog group by convert(date, requestedon) order by [date] desc 	0.00118467171463938
19675904	36103	how to get the record with the smallest date value	select type_code,brand_code,model_code,serial_no, min(assign_date)  from yourtable group by type_code,brand_code,model_code,serial_no 	0
19676437	20736	tsql join and group xml column values	select     sum(a.value1),     sum(a.value2),     sum(a.value3),     sum(a.value4),     sum(a.value5),     stuff(         (             select ',' + t.c.value('.', 'varchar(400)')             from table as b                 outer apply b.[xml].nodes('r/p') as t(c)             where b.[datetime] = a.[datetime]             for xml path(''), type         ).value('.', 'nvarchar(max)')     ,1,1,'') from table as a group by a.[datetime] 	0.0725454790544909
19676993	1187	how to create table and insert values in one statement	select round(a.km, 4) as km, round(x.y - a.y, 4)  as diff into resultstable1_diff from sourcetable_1_hq100 as a inner join sourcetable_2 as x on round(a.km, 4)  = round(x.km, 4) 	0.00205707674855394
19677333	2814	sql count - advance, get the total of each record	select t.* from your_table t inner join (    select title, min(new_date) as mdate    from your_table    group by title ) x on x.title = t.title and x.mdate = t.new_date 	0
19677886	7991	mysql query with if	select class.* from   class inner join users   on class.grade = users.grade      or users.access_level>=3 where   user='username'; 	0.547721036309094
19679157	516	mysql: select all orders from today (converting unix timestamp)	select date_format(from_unixtime(`entrydate`), '%y-%m-%d') as entrydate, id  from customers_orders where date_format(from_unixtime(`entrydate`), '%y-%m-%d') = curdate() 	0
19679302	29000	building hierarchical order rows from hierarchical table structure	select [level],val from ( select '0' as [level], [col001] as ord, [col001] as val  from @datasource union  select '1' as [level], [col001]+[col002] as ord, [col002] as val  from @datasource union  select '2' as [level], [col001]+[col002]+[col003] as ord, [col003] as val  from @datasource union  select '3' as [level], [col001]+[col002]+[col003]+[col004] as ord, [col004] as val  from @datasource ) as t1 order by ord,[level] 	0.0791505276704576
19680787	18868	getting the most recent of a group of repeated rows	select name, library, max(accessedtime) as 'accessedtime' from userlibrary group by name, library 	0
19681566	4962	postgresql timestamp select	select * from public."table1"   where "registrationtimestamp" between              to_timestamp('22-10-2013 00:00', 'dd-mm-yyyy hh24:mi')         and to_timestamp('22-10-2013 23:59', 'dd-mm-yyyy hh24:mi') 	0.0675052521960927
19682915	9588	multiple month columns without inline subqueries	select year(`date`) as `year`,  sum(case when month(`date`)=1 then `value` else 0 end) as `jan`,  ...  group by year(`date`) 	0.0632764286030966
19684042	29693	assign value to a column based on values of other columns in the same table	select    dateid,    orderid,    trunc((row_number() over (partition by dateid order by orderid) +1 ) / 2) as batch from mytable; 	0
19688187	6644	mysql append inserted data to column	select d.id, d.title,  group_concat(concat(a.lastname,', ', a.initial, '.')               order by a.lastname, a.initial separator ' ') authors from documents d inner join authorships ash on ash.document_id = d.id inner join authors a on ash.author_id = a.id group by d.id, d.title 	0.00431664171623067
19688397	29093	count results with condition in the select part of the query	select count(case when word like 'a%' then 1 end) as a       ,count(case when word like 'b%' then 1 end) as b .........       ,count(case when word like 'z%' then 1 end) as z from words 	0.00972160439196993
19689056	25006	mysql insert and select rows with insert id	select a, b, c from mytable where primary_key_col < '$insertid' and a = 200 order by primary_key_col desc limit 10 	0.00233003415975686
19690522	12231	left join with 3 tables	select u.unit_name, ur.unit, ur.rate, ur.tax  from units u  left join reservations r on r.unit = u.id and r.arrival <= 2013-10-11 and r.departure >= 2013-10-01 join unit_rates ur on ur.unit = u.id where r.unit is null 	0.625778276782721
19692571	26519	mysql query to get data of child and master table	select order.order_id, coalesce(round(sum(order_detail.qty * order_detail.price),2),0) as grandtotal from order  left join order_detail on order_detail.order_number = order.order_id  group by order.order_id 	5.38997751773091e-05
19693845	27982	conditionally populating a column with select	select selected.id, case when u_likes.user_id is null then '0' else '1' end as liked, selected.name, selected.description, concat('$image_base_url/products/', selected.image) as icon, concat('$image_base_url/products_full/', selected.full_image) as full_image from (select * from products where menu_id = ? and menu_is_section = ?) as selected left join (select * from product_likes where user_id = ?) as u_likes on selected.id = u_likes.product_id where utc_timestamp() between selected.initial_time and selected.final_time order by selected.initial_time desc 	0.0463570339857493
19695505	8806	get the name of resource from table depending on the id	select  extract(day from timestamp), resource.name, count(transactions.id)  from transactions inner join resource      on transactions.resourceid = resource.id where timestamp between '01-oct-13' and '10-oct-13' group by resource.name, extract(day from timestamp) order by extract(day from timestamp); 	0
19696804	23832	how to do keyword query in mysql with big data amount?	select * from articles where match (title, body) against ('bc'); 	0.112781527732575
19696877	39333	adding a new empty column to sql select query	select column1,column2,1 as column3 from mytable 	0.0238067712695888
19696905	27029	grouping amount by date and person id	select     lge.emp_num, lge.emp_lname, lge.emp_fname,     lgs1.sal_from, lgs1.sal_amount from (     select emp_num, max(sal_from) maxdate from lgsalary_history     group by emp_num ) lgs2 join lgsalary_history lgs1 on lgs1.emp_num = lgs2.emp_num and lgs1.sal_from = lgs2.maxdate join lgemployee lge on lgs1.emp_num = lge.emp_num where lge.dept_num in ('300') order by lgs1.sal_amount desc 	0.000108271436958899
19697348	35201	finding all marks and show their prize	select t.name, t.marks, t.school,        if(prize=1,'first', if(prize=2,'second', if(prize=3,'third',null))) as prize   from     mytable t,     (select m.marks, @prize := @prize + 1 as prize       from (select distinct marks                from mytable               where school= 's1'                order by marks desc             ) m,             (select @prize := 0) p     ) as mp   where t.marks = mp.marks     and t.school= 's1' order by t.marks desc 	0.000139934831180503
19697727	39319	sql combine two tables in a view	select a.id, c1.fullname as aperson, c2.fullname as bperson from tablea as a   left join tablec as c1 on a.fk_persona = c1.id   left join tablec as c2 on a.fk_personb = c2.id union select b.id, b.fullname1 as aperson, b.fullname2 as bperson from tableb as b 	0.0104409298523642
19698757	25955	selecting records as paired parent child	select     seqnno,     narration,     pairkey,     scndleg   from (     select p.*, least(seqnno, scndleg) related_leg_min_id       from pairs p   ) start with scndleg is not null connect by pairkey = prior seqnno and scndleg is null order by connect_by_root(related_leg_min_id), scndleg desc nulls last, pairkey ; 	0.00010788591196293
19698850	40764	php messaging system with mysql. one table and query for total new messages	select * from messages as m      left join (select id as total_last_id, parent_id as total_parent_id, count(*) as total      from messages where recipient_id = 51 or sender_id = 51 group by parent_id) as cm       on total_parent_id = m.id      left join (     select id as new_last_id, created as new_last_created, parent_id as new_parent_id, sum(status) as new from messages      group by parent_id) as new      on new_parent_id = m.id where m.recipient_id = 51      group by m.conversation_id, m.parent_id having (m.parent_id is null) order by m.created desc; 	0.00622265787572398
19700987	4107	select query in sql with testing on each row	select favorite_id,mo,name, b.image_id, image_path = case when b.image_id ='0' then i1.image_path else i.image_path end from buddies b, registration r  left join images i  on b.image_id=i.image_id left join images i1 on r.image_id=i1.image_id where b.reg_id=@regid and  r.reg_id=@regid 	0.00361486583581127
19701039	17152	using one tables values as another table's columns	select set_id,         num,         case when type_id = 1 then id end as id_1,        case when type_id = 2 then id end as id_2,        case when type_id = 3 then id end as id_3 from your_table group by set_id, num 	0
19701156	33280	how to get regular customer list	select * from customer_mst where id in (     select custid from order_mst     where createddate <= (now() - interval 2 month) and createddate > (now() - interval 3 month) ) and id in (     select custid from order_mst     where createddate <= (now() - interval 1 month) and createddate > (now() - interval 2 month) ) and id in (     select custid from order_mst     where createddate <= now() and createddate > (now() - interval 1 month) ) 	0.0008279339160577
19701348	28567	select count of distinct column in table	select   action, count(*) from     your_table where    user_id = 1 group by action 	0.00127806844306987
19702070	30896	column name for display in case	select       favorite_id,      mo,      name,      image_id,      case image_id           when 0 then (select image_path from images where image_id in (select           default_image from registration where reg_id=9))          else (select image_path from images where image_id=b.image_id          and active=1)      end as alias_name_here   from buddies b where reg_id=9 	0.0131349211802702
19702315	2390	getting the previous month on the last day of the month.	select count(order_id) as added_orders from `order`  where date_added > date_add(curdate(), interval -31 day) and order_status_id != 0   and month(date_added)= month(date_add(curdate(), interval -1 day)) 	0
19703641	25345	subquery returns more than one row - mysql	select count(*) as citycount, answer  from b inner join a on b.answer = a.city group by answer 	0.0238291586313084
19705446	19323	how to simplify the result of union all	select m.title as thread, m.author as starter, max(mm.postcounter) as posts from mytable m inner join mytable mm on m.title = mm.title where m.postcounter = 1 group by m.title, m.author 	0.0638492973948466
19705462	33439	how can i view which employees are available across within any of the 3 different databases with 3 tables	select distinct     column_name from     select          column_name, count(*) over (partition by column_name) num     from(         select column_name from database1.resourcetableus union all         select column_name from database2.resourcetableuk union all         select column_name from database3.resourcetableaus     )x )xx  where num>1 	0
19708519	18307	problems with conversion from unix time	select from_unixtime(1382839200) as a, from_unixtime(1382842800) as b; 	0.271526959986148
19709369	18259	complex query regarding last run date	select * from (select distinct taskid from tbl_archive  where rundate <= dateserial(year(now), month(now), 1) and taskid not in  (select taskid from tbl_archive where rundate > dateserial(year(now), month(now), 1)) )   as sub inner join tbl_task on sub.taskid = tbl_task.taskid where (((tbl_task.frequency)="monthly")); 	0.392540429391984
19709600	19287	join two rows together if they share the same value?	select a.name, a.totalqty, b.totalbilled from (  select name, sum(quantity) as totalqty  from yourtablehere  group by name  ) a inner join (  select name, sum(billed) as totalbilled  from yourtablehere  group by name ) b on a.name = b.name 	0
19709755	27702	display an account as "subheader" in select statement?	select account,        transaction_date,        short_description from ( select distinct 0 ord , account ordacc,                   account,                    null transaction_date,                   null short_description from t union all select 1 ord , account ordacc,                   null account,                    transaction_date,                   short_description from t ) t1 order by ordacc,ord 	0.0235849083685386
19711852	30617	join 2 tables from different databases	select a.col from [db1].[dbo].[table1] a inner join [db2].[dbo].[table] b on a.col = b.col 	0.00100638045238174
19711976	37664	sql displaying data by joining 3 tables when data exits in 2 out of 3 table	select student.studnum, student.studname, count(application.appcncsenum) as coursenum from student join application on student.studnum  = application.appcnstudnum group by student.studname; 	5.36351998550672e-05
19712045	17955	in a sql server view, get the "as" info for the columns in the view	select object_definition (object_id('yourschema.yourviewgoeshere')) as objectdefinition; 	0.000145375010176186
19712105	33679	sql to get the next upcoming event from a number of event entries based on event date	select * from your_table where `event date` > current_timestamp and `event status` = 'active' order by `event date` asc fetch first 1 rows only 	0
19713858	16163	sql count() child rows based on values from parent	select p.eventkey as eventkey , p.eventname as eventname, count(c.assignee) as assignee_count from parent p left join child c on p.eventkey=c.eventkey  group by p.eventkey,p.eventname 	0
19714019	20237	php/sql select all with join when two tables have the same id	select   t1.id as t1_id,   t2.id as t2_id,    t3.id as t3_id from   table1 as t1 left join table2 as t2 left join table3 as t3 	0
19715294	25926	retrieving records from mysql database	select * from newstudent as s inner join grades as g on s.id=g.id 	0.000442161649274984
19715607	22835	mysql count where row = 0	select count(*) as personid from users where deleted=0 	0.0492252523000502
19715934	12048	results from 2 tables with unique rows depending on field value	select t1.id, t1.telephone, t1.name,t2.address1,t2.address2             , case                      when t2.status = 'good' then 'yes'                     else 'no'             end as active     from table1 t1     join table2 t2         on t1.id=t2.table1id         and t1.id in     (         select tableid1         from table2         group by tableid1         having (count(distinct id) =1)     ) 	0
19717161	29196	show count of rows between 2 dates	select count(*) from your_table where created_at >= '2013/10/01 00:00:00' and created_at <= '2013/10/30 00:00:00' 	0
19717534	32111	select both uppercase and lowercase from column	select name from users where upper(name) like 'j%' 	0.00496566169829692
19718097	31402	reference joining	select distinct t.* from tickets t left join tickets_references tr on tr.ref_ticket = t.ticket_id where t.ticket_database = 1 or (tr.ticket_database is not null and tr.ticket_database = 1) order by t.ticket_opened 	0.161375263947791
19720236	5836	rounding to 2 decimal places in sql	select to_char(92, '99.99') as res from dual select to_char(92.258, '99.99') as res from dual 	0.0209266821916891
19720601	34579	how can i use sql to combine columns into one column	select    course_id,   listagg(first_name||' '||last_name, ',')      within group (order by course_id) as list  from  (   select course_id, primary_instructor_id   from p_course   union all   select course_id, instructor_id   from p_course_other_instructor )x    inner join p_instructor y    on x.primary_instructor_id=y.instructor_id group by course_id 	0.000330587433057782
19721294	2525	alias on the left side of my avg result	select      'average is:' as grade_type_code,     avg(grade) as grade from (     select avg(numeric_grade) as grade from grade where student_id = 5 and section_id = 17 group by grade_type_code ) myinnertable; 	0.799234610822732
19722725	21483	select rows before and after matching row in specified order	select * from ( select * from ( select * from t where vote_count<=                       (select vote_count                          from t                          where username ='user5') order by vote_count desc limit 3  ) as t1   union select * from ( select * from t where vote_count>                       (select vote_count                          from t                          where username ='user5') order by vote_count asc limit 2  ) as t2 ) as t3 order by vote_count desc 	0.00011773462876817
19723045	12711	selecting a distinct value and the sum of times it shows up in a column	select  @a:=@a+1 as `place`, name, count(userid) as `total` from `your_table`, (select @a:= 0) as a group by userid 	0
19723905	5352	mysql filter results by month and year	select count(*) as `count`,       `region`,         year(`date`) as `year`,        month(`date`)  as `month`    from my_stores.stats          where  year(`date`) in (2012,2013)  group by `region`, year(`date`),month(`date`) 	0.000711438353226373
19724279	3819	how to get last two characters before a letter in sql?	select left(right(your_column, 3), 2) from your_table 	0
19724528	2378	sql count records held in all-time records from a personal best table	select a.contender, count(*) from pb_scores a inner join (     select specie, namefish, max(drams) as maxspeciesweight     from pb_scores     group by specie, namefish ) b on a.specie = b.specie and a.namefish = b.namefish and a.drams = b.maxspeciesweight group by a.contender 	7.59572366809997e-05
19724658	240	tsql select based on a condition	select * from display where (@prd > 5 or period in (1, 2, 3, 4, 5)) 	0.00734462996569944
19725588	7967	left join mysql with three table	select distinct d.debtor_trans_no bill_no               , d.stock_id item               , d.unit_price unit_price               , d.quantity qty               , d.description               , t.debtor_no reg_no               , t.type                , t.ov_amount total_amount               , t.tran_date tran_date               , c.memo_            from `0_debtor_trans_details` d            join `0_debtor_trans` t               on t.trans_no = d.debtor_trans_no             join `0_comments` c              on c.id = t.trans_no            where t.type = 10              and c.type = 10             and d.description = 'fine'           order               by d.debtor_trans_no               , d.stock_id               , d.unit_price               , d.quantity               , d.description               , t.debtor_no               , t.type               , t.ov_amount               , t.tran_date               , c.memo_; 	0.638533262203727
19725817	35448	multiple category join with group_concat and category search	select a. * , group_concat( c.b_type_name )  from business a inner join business_what b on b.business_id = a.business_id inner join business_type c on c.b_type_id = b.b_type_id where b.business_id in ( select business_what.business_id from business_type join business_what on business_type.b_type_id = business_what.b_type_id where business_type.b_type_name like  '%hotel%' ) group by a.business_id 	0.0561898405498651
19726501	33615	select all products and related products for a categoryid in sqlite	select p1.itemid from products p1 left join childproducts cp on p1.itemid=cp.childitemid left join products p2 on cp.parentitemid=p2.itemid   where p1.categoryid=1         or          p2.categoryid=1 order by coalesce(p2.itemid,p1.itemid),p2.itemid 	7.93896359782347e-05
19727326	36250	select from two tables and always return from one	select a.*, b.* from disp_ofer a left join ofer_detl b        on b.disp_ofer_data = a.disp_ofer_data and b.esta_cod = a.esta_cod where  a.esta_cod = 'lelis'  and a.disp_ofer_data = '2013-10-30 16:07:20' 	0
19728880	24108	how to query postgresql for all records where hstore is empty?	select * from widgets where properties is not null   and array_length(akeys(properties),1) > 0; 	0.0120756044092931
19729065	28148	count the sum of a column where data is contained in multiple columns	select   t.id,          t.name,          sum(t.id  = d.winnerid) as w,          sum(t.id != d.winnerid) as l from     debates as d     join teams   as t on t.id in (d.hostid, d.visitid) where    d.visitid != -1        and d.debatedate < curdate() group by t.id order by w desc 	0.000194157283385824
19730189	29217	sql sum data by hour	select   trunc(timestamp, 'hh24') as hour, count(*) as totalcalls from     some_table group by trunc(timestamp, 'hh24') 	0.0100412168825097
19730462	18079	aggregation of unique rows in sql	select t.name, t.change, t.number_of_sales from your_table t inner join (         select tt.name, max(tt.number_of_sales) as max_number_of_sales          from your_table tt          group by tt.name     ) tm on t.name = tm.name and t.number_of_sales = tm.max_number_of_sales 	0.00439827208544335
19731570	23271	formatting calculated field in sql	select cast(x.percentchange as varchar) + '%', x.oteherfield, ... from(     *query goes here, percentchange defined here*      ) as x where x.percentchange >50 	0.341197349486303
19732602	14355	how to retrieve all data from joining table using parent key	select u.firstname, u.lastname, up.poststatus from userposts as up     inner join users as u on u.userid = up.userid where     up.userid = @userid or     exists (         select *         from followers as f         where f.followerid = up.userid and f.userid = @userid     ) 	0
19733619	23948	sql join on values not in table primary keys	select b.id from batch b left join user u on u.batch_id = b.id where u.id is null   and b.submitted = 0   and b.project_id = ? 	0.0133544027310064
19733792	17097	sql: using case to select certain elements from two different tables	select     s.game_id,      case         when g.score_type = low  then min(s.score)         when g.score_type = high then max(s.score)     end as score from game_scores s inner join games g on s.game_id = g.id where s.user_id = 1 group by s.game_id, g.score_type 	0
19734457	18454	sql - select record count from column value in separate table	select * from purchase_order where number_of_assets > (     select count(*)     from asset     where asset.purchase_order_key = purchase_order.purchase_order_key ) 	0
19735019	38254	extracting simple attribute from xml fields in sql server 2008 table	select productname.value('(/locale/@en-us)[1]', 'nvarchar(max)') as productname  from mytable 	0.00592004690305689
19735656	25406	sql creating new columns from computed values	select part_code, description, on_hand * price as on_hand_value from parts where ... 	0.000382163923966857
19736284	2607	how to replace id in one table with corresponding value from another table?	select     name, color, shape from     table1       inner join           table2 on table1.color_id = table2.color_id       inner join           table3 on table1.shape_id = table3.shape_id 	0
19737420	1574	where date for specific condition only	select      op.order_number,      m.name as brand,      op.name as model,      op.product_grade as grade,      o.date_added  from      order o,      op.order_product_veri,      manufacturer m,      product p  where      opv.product_id = p.product_id and      p.manufacturer_id = m.manufacturer_id and     (         op.order_status = '2' or          (op_order_status = '1' and date(o.date_added) >= '2013-10-22' and date(o.date_added) <= '2013-11-02'     ) 	0.00462170995757058
19737911	3346	how to combine these two queries	select grade_type_code, round(to_char(numeric_grade),2) as grade from grade where student_id = 10 and section_id = 5 union all select 'average is:' as grade_type_code,avg(grade) as grade from (     select avg(numeric_grade) as grade from grade where student_id = 10 and section_id = 5 group by grade_type_code ) myinnertable order by 1 desc, 2 desc 	0.0187094655163787
19738007	7946	sum in asp .net report viewer based on condition	select pk, spk, name, case when spk = 0 then sum(d1) over(partition by pk) else d1 end as d1 mt 	0.0738318014249361
19738148	36548	get conditional sum in first row	select pk, spk, name, case when spk = 0 then sum(d1) over (partition by pk) else d1 end as d1 from table order by pk, spk 	0.000842658275459983
19739169	40784	sql server : get name for each id in a row from another table (asp.net)	select table2.name as choice1name, table2_1.name as choice2name, table2_2.name as                                                                                                                                                                                                                                                                                                choice3name        from  table1 inner join              table2 on table1.choice1 = table2.id inner join              table2 as table2_1 on table1.choice2 = table2_1.id inner join              table2 as table2_2 on table1.choice3 = table2_2.id 	0
19740873	1	how to compare dates in sql query?	select tahminler.match_id, tahminler.tahmin_text,matches_of_comments.match_id from tahminler inner join matches_of_comments on tahminler.match_id = matches_of_comments.match_id where ( month(str_to_date(matches_of_comments.match_date , '%m/%d/%y'))=  '07'  and year(str_to_date(matches_of_comments.match_date , '%m/%d/%y'))=  '2013' ) and tahminler.user_id =12 	0.0118679831483543
19741110	29406	mysql query where second words starts with a letter	select     substring_index(outputname, ' ', -1) as secondword    from users     where substring_index(outputname, ' ', -1) like 'a%'    order by secondword asc 	0.00163707411016315
19741627	6562	oracle sql: how to determine total ranking using cursor with in and out params	select     a.userid,     sum(decode(a.rank, 'su', 25, 'ex', 9, 'vg', 5, 'g', 3, 'f',1) * b.tokens)         / sum(b.tokens) ranking from     a         inner join     b         on a.gameid = b.gameid group by     a.userid 	0.116773576369373
19743030	4954	how to join two tables ids with auto increment	select t1.userid, t1.name, t1.f_name, t2.userid, t2.work, t2.study from table1 t1 inner join table2 t2 on t1.userid = t2.userid 	0
19743440	3154	mysql left join table not between dates	select student.* from student join course   on course.id = 3     and student.available_start <= course.`start`      and student.available_end >= course.`end` where not exists   (select *    from student_to_course    join course as c      on student_to_course.course_id = c.id     where student.id = student_to_course.student_id        and (course.`start` between c.`start` and c.`end`              or             course.`end` between c.`start` and c.`end`              or             c.`start` between course.`start` and course.`end`)); 	0.177607594012422
19743850	15023	get records from last hour	select field1, orderfor, writeback, actshipdate, orderstatus, receivedate, receivetime     from orderinfo, shippinginfo     where orderinfo.orderid = shippinginfo.orderid     and shippinginfo.custid = '37782'     and receivedate =  date(now())      and receivetime > dateadd(hour, -1, getdate()) 	0
19744419	13857	how to display random 10 record from database?	select top 10 * from table order by newid() 	0
19744656	10535	sort table by difference of datetimes of rows with same name	select username,hour(timediff(max(accesstime),min(accesstime))) timedifference from table group by username order by timedifference 	0
19745042	37494	select value where the value in the same row but another column is the same	select t2.regnr   from table1 t1 join table1 t2     on t1.samenr = t2.samenr    and t2.type = 'plane'  where t1.id = ? 	0
19745704	11894	working with mysql date range	select * from data where str_to_date(`date`,'%m/%d/%y') between '11/02/13' and '11/31/13' 	0.182298693578588
19745781	7122	how to find same as using sub-query and set operation	select distinct z.first_name,z.last_name,z.phone from student s join enrollment e on s.student_id = e.student_id join section w on e.section_id = w.section_id join instructor z on w.instructor_id = z.instructor_id and s.zip = z.zip 	0.0380059775314713
19747597	7574	how to display table result of counted rows in sql server	select student, count(*)  from studentgradetracker  where grade > 0  group by student 	0
19747895	20546	how do it get all data from 2 tables	select l.teamguid, l.league, l.country, lp.point from leagues l  inner join leagues_point lp on l.teamguide = lp.teamguid 	0
19747925	7329	sql query to get records that match all the criteria	select * from (     select          p.patientid,         hs.hospitalcode     from         patient p         inner join hospital h on (p.patientcity = h.hospitalcity)         left join hospital_stay hs on (p.patientid = hs.patientid and h.hospitalcode = hs.hospitalcode)     order by 2 ) as tmp_table group by 1 having not isnull(hospitalcode) 	0
19750302	36159	mysql employee and dependent	select   e.fname  e.minit  , e.lname  , dependent_name  from employee as e   inner join  dependent  on substring(e.minit,1,1) = substring(dependent_name,1,1) and    e.sex=dependent.sex and essn=e.ssn 	0.0737681275690813
19750486	34163	getting marks contribution based on sum not working	select t.name,t.marks,t1.sum,cast(t.marks as float)/t1.sum from dbo.total_marks as t cross join (select sum(marks) sum from dbo.total_marks) t1 order by marks desc 	0.140617309121309
19753360	40249	mysql order by and min	select   t.name,   minprices.minprice,   sum(t.qty) as sumqty from   (select min(price) as minprice, name from t group by name) as minprices   left join     t on minprices.name=t.name     and     minprices.minprice=t.price group by   t.name 	0.238480892287276
19757760	38323	how would you handle grouping by weeks across different years?	select     cast(datediff(current_date(), registration_date) / 7 as unsigned) `cohort`,      count(id) `count` from     account  group by     `cohort` 	0.000667042351743064
19758677	14172	mysql query for multiple tables	select u.fname,u.lname,u.email,u.contactnumber,c.fname,c.lname,uc.relationship_type,uc.relationship_state  from user as u inner join user_contact as uc on u.user_id=uc.user_id inner join contact as c on uc.contact_id=c.contact_id where u.user_id=<userid> 	0.17495927931742
19761045	32538	query to display all tables and views	select 'table' as object_type, table_name from all_tables where owner = '<owner>' union all select 'view' as object_type, view_name from all_views where owner = '<owner>' order by table_name; 	0.00070741158988801
19761677	5604	mysql get range of serial numbers	select user, min(sn) range_start, max(sn) range_end   from (   select user, sn, @r := if(@g = user, @r, @r + 1) range_num, @g := user     from table1 cross join (select @r := 0, @g := null) i    order by sn ) q  group by user, range_num 	0
19762233	33550	getting the count of records without group by	select     tagno, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, coreno,     totalcores = count(*) over(partition by tagno) from      dbo.yourtable 	0.00084833724073332
19763458	29800	find diseases from users suffering for a specific disease	select distinct d1.id from diseases as d1    join treatments as t1 on d1.id=t1.disease_id    where exists (     select t2.id from treatments as t2        where t2.disease_id = 250 and t2.user_id=t1.user_id   ) and d1.id <> 250; 	0.000425049164465772
19765194	29973	how do i create list of unique records from a mysql table, and then use those records to calculate means	select bed, bath, type, suburb, postcode,avg(price)  from rent_suburbs group by bed, bath, type, suburb, postcode 	0
19770268	21227	query or sql to return multiple columns with one unique column	select t.patient_number, t.date_of_visit, t.bmi from t inner join      (select patient_number, max(date_of_visit) as maxdate       from t       group by patient_number      ) tmax      on t.patient_number = tmax.patient_number and t.date_of_visit = tmax.maxdate; 	0.000373408233057809
19773731	39446	sql query between two times on every day	select * from yourtable where time(created_at) between '08:00:00' and '15:00:00' 	0
19773925	16995	sql select only when there is two way relationship for user	select f1.asked_user_id as friend_id from friends as f1 join friends as f2     on f1.asked_user_id = f2.asker_user_id    and f1.asker_user_id = f2.asked_user_id where f1.status = 1 and f2.status = 1 	0.0132717665790544
19774914	13270	mysql query logic involving the same column	select *, count(hash) as hash_count from files where  cname = 'h1215'  and path like 'c:\\\\temp\\\\%' and hash in  (select hash from files where cname = 'h1216')  group by hash 	0.0958633423207748
19775680	16286	how to select pending friend requests from database mysql	select f1.asker_user_id as friend_id from friends as f1  left join friends as f2     on f1.asked_user_id = f2.asker_user_id     and f1.asker_user_id = f2.asked_user_id    where f1.status = 1 and f2.status is null and f1.asked_user_id = 2 	0.00496887764313056
19778950	7136	sum of multiple counts on different tables	select   reviews.username,   count(distinct reviews.id) as userreviewnum,   count(dictinct reviewvotes.id) as reviewvotesnum,   count(distinct reviews.id) + count(dictinct reviewvotes.id) as userrating from    reviews    left join reviewvotes on reviews.username = reviewvotes.username  group by reviews.username order by userrating desc  limit 10 	0.000335055327605436
19778971	3633	how to create crosswalk table to match people with different id's?	select table1.id as table1id, table2.id as table2id from table1 inner join table2 on table1.name = table2.name    and table1.address = table2.address    and table1.zip = table2.zip    and table1.phone = table2.phone 	0
19782560	26849	sql statement filtering	select t1.route_id  from route_stop_list t1 join route_stop_list t2 on t1.route_id=t2.route_id where  t1.stop_id=1 and t2.stop_id=2 	0.690820731308987
19784165	17596	rank base on a column in one table	select t1.id,  (select count(*) from user t2 where t2.age < t1.age) as rnk from user t1 order by rnk ; 	0.000306542182230873
19784304	13036	mysql if statement to select multiple rows	select server_key from overserver where right(from_unixtime(300 * floor(unix_timestamp(now())/300)) - interval 10 minute, 8) = '23:50:00' union all select server_key from server where right(from_unixtime(300 * floor(unix_timestamp(now())/300)) - interval 10 minute, 8) != '23:50:00' 	0.0329579359762562
19784874	19722	how can i query a table between two dates that can be null?	select * from kkmail  where (mail_date >= @start_date or @start_date is null) and (mail_date <= @end_date or @end_date is null) 	0.00210986788981392
19786950	10201	myql - sql left join select null records not found on other table	select  a.qty purchasequantity,          b.qty salesquantity from         (             select  @rank1 := @rank1 + 1 rank1,                     a.qty             from    tablename a, (select @rank1 := 0) b             where   a.type = 'purchase'             order   by a.id         ) a         left join         (             select  @rank2 := @rank2 + 1 rank2,                     a.qty             from    tablename a, (select @rank2 := 0) b             where   a.type = 'sales'             order   by a.id         ) b on a.rank1 = b.rank2 order   by a.rank1 	0.0311779356860112
19787202	401	how to order by a formula in mysql	select      location from (       select          locations.id as location,          1609.34 * 3956 * 2 *                  asin(                     sqrt(                         power(                             sin(                                 (55.170000 - abs(locations.latitude))                              * pi() / 180 / 2), 2) +                              cos(55.170000 * pi() / 180 ) *                             cos(abs                                 (locations.latitude) * pi() / 180) * power(sin((-7.400000 - (locations.longitude)) *  pi() / 180 / 2), 2)                 )                  ) as result      from locations order by result asc limit 10 ) as l 	0.350583475801406
19787549	26313	get data from 3 relational tables	select s.id, s.name, s.address       from student s        inner join studentsguardian sg on s.id = sg.student_id         where sg.guardian_id = 'somespecific_id' 	0.000700484586234625
19789451	26820	query for retrieving most popular video	select * from   videos  inner   join (         select videoid              , count(*) as number_of_likes         from   likes         where  status = '0'         group             by videoid        ) as likes     on likes.videoid = videos.videoid 	0.00390207763800895
19792969	25984	mysql best approach to having one table tied to multiple tables?	select * from uploads where typeid = 2 and objectid = [catid] 	0.00242172928092712
19795217	28147	select from many-to-many with groupby	select distinct   c.name cue_name,   b.name reaction_name,   (select   count(*)   from    rdb_freqs a1   where    a1.cue_id =  a.cue_id and    a1.reaction_id = a.reaction_id    ) as count from    rdb_freqs a    inner join rdb_reaction b on a.reaction_id = b.id   inner join rdb_cue c on a.cue_id = c.id   order by count desc 	0.182126137557299
19795560	49	first record of a table by creation date with 2 more conditions	select request_id from tab qualify    row_number()     over (partition by request_id          order by create_ts) = 1  and corresp_type=3  and corresp_status=4 	0
19797142	32883	i have the same column in multiple tables, and want to update that column in all tables to a specific value. how can i do this?	select 'update ' + table_name + ' set createddatetime = ''<<new value>>'' ' from information_schema.columns  where column_name = 'createddatetime' 	0
19797220	18226	select orderid if it has both items bought	select orderid  from itemsbought where itemid in (1,2) group by orderid having count(orderid) = 2; 	0.00155130017628639
19797281	34403	how to add check for january in sql statement	select   ... from   ... where   ...   and   (     (       (month(current date) > 1) and       (year(enterdate) = year(current date) and month(enterdate) = (month(current date)-1))     )     or     (       (month(current date) = 1) and       (year(enterdate) = year(current date) - 1 and month(enterdate) = 12)     )   ) 	0.100997018101478
19798278	29102	sql return exactly one row or null in a select sub-query	select t1.x  ,t1.y  ,t1.z  ,t2.w from table1 as t1 left outer join (     select x       ,w     from table2     group by x,w     having count(x) = 1 ) as t2 on t2.x = t1.x; 	0.00803528856688003
19798393	35167	best way to search this type of database structure?	select o.id as id, d.id as order_id, last_name, date_time, status  from orders_users as o left join orders_details as d  on o.id = d.id where last_name like '%query%' 	0.512031152854334
19799331	29378	mysql: select * where first and last name starts with the same letter	select * from `people` where upper(left(first_name, 1)) = upper(left(last_name, 1)) 	0
19802633	38099	select first purchase for each customer	select h.transaction_no, h.customer_id, h.operator_id, h.purchase_date from sales_transactions_header h inner join     (select customer_id, min(purchase_date) as first_occurence     from sales_transactions_header     group by customer_id) x on h.customer_id = x.customer_id and h.purchase_date = x.first_occurence 	0
19803049	9174	join sql function results with multiple where from one table	select a, b, sum(c),        avg(case when c = 1 then d end) from table group by a, b 	0.0636579824306246
19803930	14480	how can i group by 2 fields and having by an interval type?	select   id,   month,   sum(extract ('epoch' from hours)/3600) from   hours group by   id,   month 	0.0182491529620089
19803987	35906	find repeated battles	select     t1.battle_id,     t1.winner,     t1.loser from     your_table t1 where     exists (              select                  1              from                  your_table t2              where                  ( ( t1.winner = t2.winner                  and t1.loser = t2.loser )                  or ( t1.loser = t2.winner                  and t1.winner = t2.loser ) )                  and t1.battle_id <> t2.battle_id     ) 	0.0555009708471704
19804164	24091	is it possible to store the values of array as one new variable?	select name, date, group_concat(menu) as menu     from table group by name, date 	0.000930045611076376
19805508	3632	mysql query to get the row with condition that the reduction between 2 field from different table is more than 0	select a.code, a.`any else` from product a inner join stock b on a.no_produk = b.no_produk left outer join (select id_stock, sum(qty) as sumqty from transaction group by id_stock) c on b.id_stock = c.id_stock where b.stock - ifnull(c.sumqty, 0) > 0 	0
19806644	21407	how can i filter by date in mysql with the same data entry using php?	select * from delivered where dateord >='$a' and dateord<date_add('$b',interval 1 day) 	0.000220843859704073
19809328	7526	mysql - select in ( ) order by in ( )	select id  from users  where id in(3,4,8,1) order by field(id, 3,4,8,1) 	0.631368218763085
19809690	13522	how search word in sql?	select * from table where name like '% test %' or name like '% tests %'; 	0.232721094672419
19810877	15479	how do i count the occurences of the values in each row of a joined table?	select   first_name, last_name, customer.email, visits from     customer join     (select   email_, count(*) as visits           from     bookings           group by email_) v on       customer.email = v.email_ 	0
19812618	18579	mysql count, melt(reshaping) variable	select distinct   a.flight_number,a.row_number,   f1.passenger as passenger_a,   f2.passenger as passenger_b from (   select flight_number,row_number from flight    group by flight_number,row_number having count(*)=2   ) a join flight f1    on (f1.flight_number=a.flight_number and f1.row_number=a.row_number) join flight f2    on (f2.flight_number=a.flight_number and f2.row_number=a.row_number) where f1.passenger>f2.passenger 	0.547046568175533
19816300	4417	how to join the tables for multiple condition?	select c.country,   o.exrate,   (select exrate     from exrates     where `from` = 'eur'   ) as eur from country c inner join exrates o on c.country = o.country 	0.0470439036934535
19816476	32748	mysql select unique product id and order by stock id desc	select  a.* from    stock a         inner join         (             select  product, max(id) id             from    stock             group   by product         ) b on  a.product = b.product                 and a.id = b.id order   by a.id desc 	0.000194921240809939
19816557	15730	sqlite3 - merge multiple rows and multiple column into one column without duplicates	select idimp,        group_concat(causconc, '') as conc from (select idimp,              cer || '-' || group_concat(caus, '-') || ';' as causconc       from mytable       group by idimp,                cer) group by idimp 	0
19817314	16785	retrieving maximum of one column for each unique value from another	select t.type, t.pid, t.distance from table t inner join (select type, max(distance) as distance from table group by type) as m on t.type = m.type and t.distance = m.distance order by t.type 	0
19818164	34055	is there any way to get the result with conditions without where clause?	select distinct companyyid, companyname  from company c join location l on c.companyid = l.companyid and c.companyid >= 3 	0.371209059598395
19820500	31010	best way to do search word structure?	select original_table.* from original_table as abb2     join new_table as abb1 on abb1.product_id = abb2.id where search_word = "your search term" 	0.267379908063904
19820529	10842	mysql: sum joined table on limited selection of rows	select sum(rr.points), a.id  from athletes_raceresult as rr  inner join athletes_athlete as a on rr.athlete_id = a.id where (   select count(crr.points)   from athletes_raceresult as crr    inner join athletes_athlete as ca on crr.athlete_id = ca.id   where ca.gender = 'm'    and crr.year between 2012 and 2014    and crr.athlete_id = a.id and crr.points >= rr.points ) <= 4 and a.gender = 'm'  and rr.year between 2012 and 2014  group by a.id 	0.000256517377171878
19821534	35475	sql select records having count > 1 where at lease one record has value	select  participantid  from    contact where   exists         (   select  1             from    contact c2             where   c2.participantid = c.participantid             and     contacttypeid = 1             group by participantid             having count(*) > 1             and count(case when iscurrent = 0 and isactive = 1 then 1 end) >= 1         ); 	0
19821757	30666	using regular expressions with numeric value	select * from table where trans_amt = floor(trans_amt); 	0.751994519071749
19822890	5055	sql substring a range of data	select substr(emailjson, (instr(emailjson,"type":"other"', 'ess":"')+6), (instr(emailjson,"type":"other"', '","type') - (instr(emailjson,'ess":"')+6))) from respondents; 	0.00531953720004385
19823552	20335	merge uneven tables using sql	select country, year, srcname as combinedcol, value from tbl1 union all select country, year, progname as combinedcol, value from tbl2 	0.103271087527695
19824606	13501	mysql search where 3 columns for row have the same value	select id   from your_table where id = in_id   and nat_id = in_id ; 	0
19825162	5436	i can't get mysql to return last row when using the aggregate min	select underlying,volatility,price from shares where (id,price) in (     select id,min(price) from shares     where date(issuedate) >= date(now())     group by id ) order by price asc limit 1; 	0.000496936823499485
19826209	10726	sql convert multi level xml with attribute into table	select      tbl.col.value('../@itemid', 'nvarchar(16)') as [itemid],       tbl.col.value('@objid', 'nvarchar(16)') as [objid]      from      @x.nodes('root/items/item/obj') tbl(col); 	0.00972282388596185
19829210	9432	joining two tables and finding the sum of marks for each student	select   student_id,           subject_id,           result_id,           year,          sum(mark)     from result_view group by student_id,           subject_id,           result_id,          year 	0
19830086	13737	sql case when to narrow results, change field	select orderhed.ordernum,        (case when sum(shipdtl.orderline) > 1 then 'mixed' else max(shipdtl.partnum) end) as [item#] from dbo.orderhed, dbo.shipdtl where shipdtl.company = orderhed.company  and shipdtl.ordernum = orderhed.ordernum group by orderhed.ordernum 	0.609961672060053
19830107	36826	sql to select a single random row with a where condition	select * from xyz where (`long`='0' and lat='0') order by rand() limit 1 	0.00321880873831552
19830336	9428	mysql: have internal query reference external column on same table	select id, (select count(*) from t      where date(starttime)=date(t1.starttime)           and            starttime<t1.starttime   ) as  countnumidsbeforethisidonsameday, (select count(*) from t      where date(starttime)=date(t1.starttime)           and            endtime<t1.starttime   ) as  countnumidsthatendedbeforethisidonsameday from t as t1 order by starttime 	0.00394729674468956
19831111	28290	sql select the first column to match criteria of many columns in a single row	select  case when qrygroup1 = 'y' then 'qrygroup1' when qrygroup2 = 'y' then 'qrygroup2' when qrygroup3 = 'y' then 'qrygroup3' when qrygroup10 = 'y' then 'qrygroup10' else '' end as [selectedbp] from ocrd 	0
19833093	11756	need oracle query - get a list of differnet attributes from a column	select distinct column_value from table 	0.000218362670977983
19833334	17347	selecting null columns for script output in sql developer	select   c.cid,    c.cname,   cast(null as varchar2(1)) as continent,    null as hemisphere,    null as something,    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.0883688890563494
19834035	8456	a query to return a mix of sum and count in 5 joined tables	select *, (select count (*) from applications as a1 where a.id = a1.adid ) as applicants, (select count(*) from referrals as r where a.id = r.adid ) as referrals, (select count(*) from subscribers as s where a.id = s.adid ) as subscribers, (select count(*) from views  as v where a.id = v.adid ) as views from ads as a 	0.000576015896874036
19837120	5279	how to select own entries and entries of friends in one query	select c.* from users a left outer join relation friend on a.id = friend.user1_id join comments c on (c.user_id = a.id or c.user_id = friend.user2_id) where a.id = 1 group by c.id; 	0
19837184	27647	counting items tagged as required and that are missing or partly existing in another table	select ((select count(*) from devices_types_document_types where device_type_id = d.type_id)-(select count(*) from devices_documents dc, devices_types_document_types dt where dc.device_id = d.id and dt.device_type_id = d.type_id and dc.document_type_id = dt.document_type_id and dt.document_required = 1)) as missing_documents, d.* from devices d 	0.000127827909630763
19837482	30374	selecting distinct rows on all but one column	select min(id), date_f, date_t, num_n, num_d, mn, is  from t group by date_f, date_t, num_n, num_d, mn, is 	0
19838540	15443	mysql: order by value from second table, use default if value not set	select p.id, p.post_title, p.post_type, p.post_date,      ifnull(m.meta_value, 'default val') as meta_value from wp_posts as p left join wp_postmeta as m on p.id = m.post_id      and m.meta_key = 'mykey' 	6.85240358820749e-05
19839395	31324	retreive the last record for each group respecting some criteria	select ee.* from email_errors as ee cross join (     select ee.group as grp, max(ee.id) as max_id     from email_errors as ee     cross join     (         select group as grp, max(date_t) as max_date           from email_errors           where status <> 0           group by group     ) aux     where ee.group = aux.grp     and ee.date_t = aux.max_date     group by ee.group ) outer_aux where ee.group = outer_aux.grp and ee.id = outer_aux.max_id 	0
19839587	6552	sql select from one table twice field related to single table	select   t1.id,   t1.duree_freq_id,   td.libfrequence as duree_freq,   t1.posol_freq_id,   tp.libfrequence as posol_freq from table1 t1 left join table2 td on (td.idfrequence = t1.duree_freq_id) left join table2 tp on (tp.idfrequence = t1.posol_freq_id); 	0
19839801	21686	remove duplicates in table without primary key. several conditions	select t.*  from ( select (      case cid      when @curcid      then @currow := @currow + 1      else @currow := 1 and @curcid := cid end   ) as rank,   p.* from      mytable p,(select @currow := 0, @curcid := '') r order by cid,changedate desc,changetime desc,operator desc ) t where rank =1 	0.00107464470645201
19839954	40523	sql find duplicate sets	select * from (   select setid, setitemuniquestring,          count(*) over (partition by setitemuniquestring) as cnt   from   (     select s.setid,       (select ',' + i.itemid        from tblsetitem i        where s.setid = i.setid        order by u.itemid asc        for xml path('')       ) as setitemuniquestring     from tblset s     group by s.setid   ) sub ) sub2 where cnt > 2 	0.00652354709432008
19840704	1888	sql: group by, order by and concat the results	select    cast('2014-01-03' as date) as tape_date   ,'alice' as empl      ,'k' as val into #temp_table; insert into #temp_table values('2014-01-08', 'bob', 'a'); insert into #temp_table values('2014-01-01', 'bob', 'g'); insert into #temp_table values('2014-01-02', 'bob', 'd'); insert into #temp_table values('2014-01-05', 'bob', 'e'); select empl, substr(list(val order by tape_date), 1, 5) from #temp_table group by empl; select    empl   ,max(case rank when 1 then val else '' end)      + ','      + max(case rank when 2 then val else '' end)     + ','      + max(case rank when 2 then val else '' end) from ( select   rank() over (partition by empl order by tape_date) as rank   ,*   from #temp_table) a where rank <= 3 group by    empl 	0.268626764964909
19841507	24206	match relevance for records spanning multiple rows (cannot use group_concat with match together)	select sum(score) as total_score,        foreign_id   from (      select table_id,             match(some_string) against('beer lunch') as score,              foreign_id         from phrase        ) as scores  group by foreign_id  order by total_score desc 	0.0616726451275703
19841606	2723	finding unmatched zip codes where address matches	select [permissive export_old 1].accountno, [permissive export_old 1].keyno, [permissive export_old 1].name1, [permissive export_old 1].name2, [permissive export_old 1].address1, [permissive export_old 1].address2, [permissive export_old 1].city, [permissive export_old 1].state, [permissive export_old 1].zipcode from [permissive export_old 1], [permissive export_old 1] as [permissive export_old 1_1] where ((([permissive export_old 1].address2)=[permissive export_old 1_1].[address2]) and (([permissive export_old 1].zipcode)<>[permissive export_old 1_1].[zipcode])) group by [permissive export_old 1].accountno, [permissive export_old 1].keyno, [permissive export_old 1].name1, [permissive export_old 1].name2, [permissive export_old 1].address1, [permissive export_old 1].address2, [permissive export_old 1].city, [permissive export_old 1].state, [permissive export_old 1].zipcode; 	0.0158786452014988
19843106	6780	aggregate on relative daterange in oracle sql	select     count(*) as num_elements,     sum(some_value) as like_to_sum,     trunc(sysdate) - trunc(your_date) as rel_date from the_large_table group by trunc(sysdate) - trunc(your_date); 	0.730072878391959
19843383	30103	get all rows from table whose key isn't matched in another table	select product_description.*  from `product_description` left outer join product       on product_description.product_id = product.product_id where product.product_id is null 	0
19843487	12215	php database table select limited	select pvpkills,char_name from characters order by pvpkills desc limit 0,100 	0.0345049810953372
19844427	21547	sql query to retrieve woocommerce orders grouped by state	select     state,     sum(order_tax_sum),     sum(order_total_sum) from (     select         (select meta_value from wp_postmeta pm1 where p.id = pm1.post_id and meta_key = "_billing_state") as state,         (select meta_value from wp_postmeta pm2 where p.id = pm2.post_id and meta_key   = "_order_tax") as order_tax_sum,         (select meta_value from wp_postmeta pm3 where p.id = pm3.post_id and meta_key   = "_order_total") as order_total_sum     from         wp_posts as p     where post_type = "shop_order" ) a group by a.state 	0.000809372262554099
19845188	16061	sql select - optional date check in where clause	select top 1 *  from myview  where valid_from is null or getdate() between valid_from and valid_until order by case when valid_from is not null then 1 else 2 end 	0.702885516133249
19846094	27694	mysql concat and group by	select author, count(*) from people, writings  where concat (people.name, ' ',people.secondname) = writings.author  group by author  order by count(*) desc  limit 3 	0.452558724368786
19847814	30040	sql consolidate data and turn them into columns	select t.teamnumber, t.teamname,        sum(case when d.round = 1 then d.points1 + d.points2 else 0 end) round1,        sum(case when d.round = 2 then d.points1 + d.points2 else 0 end) round2,        sum(case when d.round = 3 then d.points1 + d.points2 else 0 end) round3   from data d join teams t     on d.teamnumber = t.teamnumber  group by t.teamnumber, t.teamname 	0.000165930468349749
19848410	7930	sql query select only one row from multiple rows	select [postingid]       ,[employerid]       ,[jobtitle]                         ,min(pin.[industryid])          from [posting] p inner join [city] c   on p.cityid = c.cityid left outer join postingindustry pin   on p.postingid = pin.postingid where (c.cityid = @cityid or @cityid is null)    and (p.stateprovinceid = @stateprovinceid or @stateprovinceid is null)    and (pin.industryid = @industryid or @industryid is null)    and    (      (p.[description] like '%' + @keyword + '%' or @keyword is null)       or (p.[jobtitle] like '%' + @keyword + '%'  or @keyword is null)   )    and p.streetaddress is not null    and p.showonmap = 1 group by [postingid],[employerid],[jobtitle] 	0
19848821	26100	getting a count from multiple columns with set values in sql and ms access	select 0, sum(iif(coffee = 0, 1, 0)) as coffee, sum(iif(tea = 0, 1, 0)) as tea,        sum(iif(water = 0, 1, 0)) as water, sum(iif(hot_choc = 0, 1, 0)) as hot_choc from drinks d union all select 1, sum(iif(coffee = 1, 1, 0)) as coffee, sum(iif(tea = 1, 1, 0)) as tea,        sum(iif(water = 1, 1, 0)) as water, sum(iif(hot_choc = 1, 1, 0)) as hot_choc from drinks d union all select 2, sum(iif(coffee = 2, 1, 0)) as coffee, sum(iif(tea = 2, 1, 0)) as tea,        sum(iif(water = 2, 1, 0)) as water, sum(iif(hot_choc = 2, 1, 0)) as hot_choc from drinks d; 	0.000936817345993231
19850622	5174	convert text to number in ms access 2010 select statement	select [organization legal name], [number of group practice members], city, state   from massivetable   where iif(isnumeric([number of group practice members]), clng([number of group practice members]), 0) >10   and state='ct'; 	0.695140850819401
19850698	6068	sql display based on count of other table	select productnr from deliverable group by productnr having count (deliverernr)=1 	0
19851451	13326	'not greater than' condition mysql	select userid, max(createdon) createdon   from table1  group by userid having createdon < '2013-09-08' 	0.206228387226391
19852868	37539	mysql query for total online time based on login/logout entries	select     player_name,     time_format(sec_to_time(             if(sum(time) < 0,              sum(time) + to_seconds(now()),              if(sum(time) > 63000000000, sum(time) - to_seconds(now()), sum(time))         )     ),'%hh %im') as total_time from (     select          to_seconds(c.date) * - 1 as time, c.player_name     from player_playtime c     where join_or_leave = 'join'     union     select          to_seconds(date) as time, player_name       from player_playtime     where join_or_leave = 'leave' ) t group by player_name with rollup ; 	0
19853763	30889	combine 3 different mysql queries in to one	select t.id, r.name, u.email from track t inner join resource r on r.task = 2 and r.track = t.id inner join users u on u.id = r.name where t.name like 'html'; 	0.00118158760213542
19853990	22317	why is this query (potentially) only returning posts that are questions?	select count(*) from users u    join posts p on p.owneruserid = u.id    join posts q on q.id = p.parentid    join posttags pt on pt.postid = q.id    join tags t  on t.id = pt.tagid where u.id = ##userid## and t.tagname in (##tag1:string##) 	0.452855527726192
19854834	35881	best way to get right n digits from number in sql server (ce)	select 123456 % 10000 	0.000956584580897898
19855038	16773	query to output files in sybase ase	select * from sometable go output to 'c:\temp\sometable.csv' format ascii delimited by ';' quote '' 	0.393313173874432
19856557	7589	combine value from two tables for a given username	select * from users left join users_custom on users.userkey = users_custom.userkey where users.username = "name"; 	0
19856763	5744	how to query to get top two questions based on no of persons answered for each sections	select * from answers a where (   select count(*) from answers b where a.code = b.code and a.`count` <= b.`count`   ) <= 2 	0
19858074	31887	result of a sql table on a single line (sqlserver)	select tps.distributeur_id,    tps.receptiondate,    sum(case when tps.status_champ_id = 3 then 1 else 0 end)[total_where_status_3],    sum(case when tps.status_champ_id = 1 then 1 else 0 end)[total_where_status_1], from total_par_statut tps where tps.receptiondate between '06-10-2013 00:00:00' and '06-10-2013 23:59:59'        and tps.distributeur_id = 1         and status_champ_id in (1,2,3,9,10,11,7) group by tps.distributeur_id, tps.receptiondate 	0.000923806184796771
19859071	625	count value variation from 0 to 1 in mysql table	select count(*) from mytable curr where curr.digital_bit = 1 and (     select digital_bit     from mytable prev     where prev.timestamp < curr.timestamp     order by timestamp desc     limit 1 ) = 0 	0.000490666194644052
19859157	14364	how can generate a insert statement having now() method in value using a procedure in mysql	select concat('insert into table_name (col1, col2, creation_date) values (1, 1, \'', now(), '\') as output_dml     into outfile ', url, file_name, ' lines terminated by \'\\n\'     from another_table_name;'); 	0.26838189165401
19860832	20750	mysql max value correspond	select x.*   from my_table x   join       ( select `cntryd`             , `type`             , `desc`             , max(date) max_date          from my_table         group            by `cntryd`             , `type`             , `desc`      ) y     on y.cntryd = x.cntryd    and y.type = x.type    and y.desc = x.desc    and y.max_date = x.date; 	0.0141848046260492
19861065	4846	mysql: count votes for users	select   u.user_name,           count(*) from (          select news_id,                 user_id          from   news          where  user_id = 2          union all          select news_id,                 user_id          from   companion          where  user_id = 2 )        sq join     vote v  on       v.news_id = sq.news_id join     user u on       sq.user_id = u.user_id group by sq.user_id; 	0.0239042977337843
19862289	17078	duplicate records being pulled from sql 2008 query	select     tl.jobid,      timetaken as 'hourssold',     sum(datediff(n, clockdatetimein, clockdatetimeout) / 60) hours_difference,     sum(datediff(s, clockdatetimein, clockdatetimeout) / 60) minutes_difference from      timelogs tl         inner join     jobs j          on tl.jobid = j.id         left join     clockinlogs cil          on tl.userid = cil.userid where      tl.userid = 10000 and      clockdatetimein between dateadd(wk, datediff(wk,0,'11/08/2013'), 0) and     dateadd(wk, datediff(wk,0,'11/08/2013'), 6) group by      tl.jobid,      tl.timetaken 	0.00672868011867233
19862576	39067	how to get number of rows with timestamp between 10am and now?	select count(*) from *yourtable* where timestamp_closed between cast(getdate() as date) and getdate() 	0
19864299	2911	sql returning duplicates	select t1.jobid as jid, sum(distinct(timetaken)) as 'hourssold', sum(distinct(s.costprice * mfj.quantity)) as 'totalstockcost' from timelogs tl left join materialsforjob mfj on mfj.jobid = tl.jobid and mfj.userid = tl.userid inner join stock s on s.id = mfj.stockid where      tl.userid = 10000 and      tl.dateentry between dateadd(wk, datediff(wk,0,'11/07/2013'), 0) and     dateadd(wk, datediff(wk,0,'11/07/2013'), 6) group by jid 	0.375665039895856
19864523	40115	how to apply own sorting logic for elements display in listview?	select ...  from ...  where ...  order by      trim(key_bl_sender, "_*~ #$")      collate nocase asc; 	0.00795310822487937
19865067	8758	date subquery php and mysql	select distinct e.eid, e.eqid, e.name, m.pid, m.hours, m.date  from      equipment e     join (         select eid, max(date)  date         from meter         where              month(date) = $month         and year(date) = $year         group by eid     ) maxdate on maxdate.eid = e.eid     join meter m on m.eid = e.eid and m.date = maxdate.date order by e.eqid asc 	0.309112927542804
19865216	7003	output from sql query needs to be in the same order as the input	select      t.cli customer,      (b.curr_bal + b.curr_bal_v) balance from table b         join (             select                  level,                 regexp_substr(custreflist, '[^ |,]+', 1, level) cli             from dual             connect by level <= regexp_count(custreflist, '[^ |,]+')         ) t on b.column = t.cli where b.column = 5 order by t.level 	0.0235779475024189
19865826	29380	select last message of each conversation	select a.body as mensagem,      a.fromjid,      a.tojid,     a.sentdate from ofmessagearchive a inner join (     select fromjid, tojid, max(sentdate) as maxsentdate     from ofmessagearchive     group by fromjid, tojid ) b on a.fromjid = b.fromjid and a.tojid = b.tojid and a.sentdate = b.maxsentdate where ta.ojid = '1945' order by a.sentdate desc limit 5 	0
19866075	10347	select a certain item unless is null in sql server	select    ...   , [contract fr seller] = (select top 1 fa.receiveddate                       from fileactions fa                       where fa.fileid = fm.fileid                           and  fa.actiondefid in (238,550)                           and fa.live = 1                           and fa.receivecoordinatortypeid = 2                       order by fa.actiondefid                         )                                  from filemain fm ... 	0.00301996434752319
19866132	40551	how to remove repetitive rows in mysql when using join	select distinct candy.id, candy.name from candy right join candytype on candy.user_id = 1 and candytype.candy_id = candy.id; 	0.119697768070154
19871293	5921	select row from a table that does not exist in other table	select images.name from images    left outer join images_viewed      on images.name = images_viewed.name    where images_viewed.any_other_field is null and images_views.ip = {$ip} 	0.000101647590876858
19871681	18021	sql not matching string	select length(title), hex(title), title    from tbl_movie   where title like '%movie%' 	0.134931621306964
19872199	14773	how to sum of two column into third column for all rows	select order_id, english, maths, english + maths as grand_total from table 	0
19873685	23860	possible to exclude some query from mysql query cache?	select sql_no_cache whatyouwant 	0.134586252772954
19873758	19337	how to get avarage time 'xx:xx:xx' on mysql?	select id, timeonsite,visits, sec_to_time(time_to_sec(timeonsite)/visits) as avgtime from t 	0.00420657298300781
19876853	8539	how to only retrieve data if the count of a column is over a certain amount	select news.*, x.[followers] from news inner join (     select news.id, count(followers.id) as [followers]     from news      inner join followers on news.artist_id = followers.artist_id      group by news.id     having count(followers.id) > 10) as x on x.id = news.id 	0
19878394	17806	mysql: how to join 2 columns from same table and use another table for reference	select   concat(t1.name, ' ', t1.lastname) as reciever,   concat(t2.name, ' ', t2.lastname) as sender from   tablea inner join tableb t1 on tablea.reciever=t1.id   inner join tableb t2 on tablea.sender=t2.id 	0
19878415	2578	concatenating date and time column in sql server 2000 with different data type	select    dateadd(hour, cast(left(thetime,2) as int),    dateadd(minute, cast(substring(thetime, 4,2) as int),    dateadd(second, cast(right(thetime, 2) as int), thedate))) as datetimepst 	0.00154068589912922
19879998	41129	mysql select dates between	select * from `prices` where date_format(prices.`from`,"%y-%m") <=     date_format(str_to_date('01,10,2013','%d,%m,%y'),"%y-%m") and date_format(prices.`to`,"%y-%m") >=     date_format(str_to_date('01,10,2013','%d,%m,%y'),"%y-%m") order by prices.`from` asc 	0.0117478889616128
19881416	6894	how select value which will have a maximum occurrences in the table.?	select val from test group by val order by count(*) desc limit 1 	0
19882226	13879	sql query return data after a date. date set as varcher	select employee_id, emp_firstname, emp_lastname, custom79 as  'first pay date', custom6 as  'agency', custom56 as  'country of homebase' from  `hs_hr_employee`  where custom6 like  'brookfield' and custom61 like  'active-oam' and str_to_date(custom79, '%d-%m-%y') > '2012-07-13' 	0.0037313172978735
19886979	15235	how to group reply messages to original message	select m.subject, r.message, r.from_id, r.to_id from message m join replies r on m.reply_id = r.id where ((m.from_id = `user_1_id` and m.to_id = `user_2_id`) or (m.from_id = `user_2_id` and m.to_id = `user_1_id`)) order by r.date_sent asc 	0.169767843854375
19887345	31291	count on condition in same column	select student_id,         class_id,         sum(att_status='p') as present,        sum(att_status='a') as absent,        sum(att_status='l') as leave from attendance group by student_id, class_id 	0.00358277234294449
19887456	6013	select the count of records by id in the last week	select username , count(viewid)    from tablename    where  date(time) >= date(date_sub(now(), interval 7 day))    group by username; 	0
19887950	21018	calculate payment according to the number of children	select count(*) from child c inner join parent par on c.parentid = par.parentid where par.userid = ? 	0
19888203	6350	join two queries become one subquery	select c.customername, a.qty,(select sum(case when (pd.date between '2010-03-15' and @date) then s.qty else 0 end)                  from period pd full join sales s on pd.timeid = s.timeid full join customer c on s.customerid = c.customerid                 group by c.customername, c.customerid                  ) as totalqty from customer c join (select s.customerid, pd.date, s.qty      from period pd join sales s on pd.timeid = s.timeid) a on c.customerid = a.customerid where @date = a.date 	0.0556435014238399
19888760	5207	remove everything before the first / in a field and output it	select substring(url, instr(url, '/') + 1) from mytable; 	0.000509248832241642
19889178	12438	filter projection of select statement	select * from (select distinct on ("trainingmatrix".payroll, "trainingname", "institute")"gendata"."employee name","gendata"."position", "gendata"."department",  "trainingmatrix".* "          ^^^^             "from "trainingmatrix" "             "join "gendata" on "trainingmatrix".payroll = "gendata".payroll "             "order  by payroll, "trainingname", "institute" ,"trainingdate" desc nulls last) a where "trainingmatrix".payroll='40612010' ;"                                                                                              ^ ^^^^^ 	0.239593896482073
19889316	24202	calculate fields from multiple tables?	select t1.code,t1.datetime as date,hour(timediff(t2.datetime,t1.datetime)) as workhour from table1 t1 join table2 t2 on t1.code=t2.code group by t1.code 	0.00053675750684179
19895079	23749	return filtered like results in sqlite using fmdb	select * from [foo] where a = substr('delicious and tasty fruit and cinnamona', 1, length(a)) order by length(a) desc 	0.797051659091448
19897467	10779	select first row/transaction based on 3 columns	select dateadd(dd, 0, datediff(dd, 0, evnt_dat)) evnt_dat,         evnt_descrp, panel_descrp, lname, fname, cardno   from (   select evnt_dat, evnt_descrp, panel_descrp, lname, fname, cardno,          row_number() over (partition by evnt_descrp, panel_descrp, lname, fname,                              dateadd(dd, 0, datediff(dd, 0, evnt_dat)) order by evnt_dat) rnum     from ev_log ) q  where rnum = 1  order by evnt_dat, evnt_descrp, panel_descrp, lname, fname; 	0
19899706	14902	choose rows based on two connected column values in one statement - oracle	select * from sample where (upper(supplier),upper(buyer)) in (('a','x'),('a','y'),('a','z'),('b','x'),('b','y'),('b','z')); 	0
19900216	442	getsqlmapclienttemplate().queryforlist() is not returning any list of result	select file_name from rou_merge_batch where file_name in ('abc.txt') 	0.234805254799506
19900665	26767	need to obtain total children count for all parents in oracle tree hierarchy	select link, count(*)-1 as "result count"   from (     select connect_by_root(link_id) link     from my_table     connect by nocycle parent_link_id = prior link_id     start with parent_link_id is null) group by link order by 1 asc 	0
19900710	501	mysql select top n rows whilte count x<y	select     test.id,    test.itemcount  from     test       left join         (select           id,           @sum:=@sum+itemcount as current_sum          from            test            cross join(select @sum:=0) as init) as sums       on test.id=sums.id  where sums.current_sum<=15; 	0.000666767219724896
19900789	28587	how to get count total occurance from different tables in mysql	select p.id, p.user_id, sum(p.mark) from performance p  left join internal activities ia on p.id=ia.id left join other activities oa on ia.id=oa.id  group by p.user_id; 	0
19901198	31080	mysql count similar rows in a select	select a.org,a.kundnrnr,count(1) as sum from(     select organisation.organisation as org, kund_nr as kundnrnr     from anv_data     inner join organisation on organisation.id = anv_data.organisation_id     inner join anvandare on anv_data.anvandare_id = anvandare.id     where anv_data.indatum<='2013-10-31' and anv_data.indatum>='2013-10-01' and anv_data.rp = '0'     group by month(anv_data.indatum), anv_data.anvandare_id order by anvandare.anstallningsnr      ) a group by a.org,a.kundnrnr 	0.00779438358120956
19902048	3409	sql server 2012 - ranking orders by year, month, supplier and location	select    year(pickup_date) as 'pickupyear',    month(pickup_date) as 'pickupmonth',    supplier_id,   location,   count(*) from mytable group by      year(pickup_date),    month(pickup_date),    supplier_id,   location 	0.000829128634327374
19903940	12975	mysql query group by where in	select *,case when type_id in (2,8) then 'yes' else 'no' end as `type` from yourtable 	0.652739487168579
19904393	24841	insert aggregated records in oracle sql developer	select date, id1 as id from mytable union select date, id2 from mytable 	0.088634588757408
19905612	36451	mysql - select 2 latest comments for each posts	select p.content post_content,        c.content comment_content from posts p left join comments c on      (p.id=c.post)     and      c.id>     (select id from comments           where post=p.id         order by id desc limit 2,1) 	0
19907296	34911	cartesian product between mysql records	select l1.entry_id   ,l1.value_id as l1_value   ,l2.value_id as l2_value   ,l3.value_id as l3_value   ,l4.value_id as l4_value   ,l5.value_id as l5_value   ,concat(l1.value_id,      coalesce(concat(',',l2.value_id,                    coalesce(concat(',',l3.value_id,                                   coalesce(concat(',',l4.value_id),                                            coalesce(concat(',',l5.value_id),''),'')                                   ),'')                    ),'')) as listvalue from vw_entries_levels as l1 left join vw_entries_levels as l2   on l2.value_level_id = 'l2'     and l1.entry_id = l2.entry_id left join vw_entries_levels as l3   on l3.value_level_id = 'l3'     and l1.entry_id = l3.entry_id left join vw_entries_levels as l4   on l4.value_level_id = 'l4'     and l1.entry_id = l4.entry_id left join vw_entries_levels as l5   on l5.value_level_id = 'l5'     and l1.entry_id = l5.entry_id where l1.entry_id = '3'   and l1.value_level_id = 'l1' order by listvalue 	0.0155712032648783
19907911	39858	return the number of rows expected for a group by query	select count(distinct idusersexecby, lastexecuseripv4) from proj1_db.testrunsteps 	0.0051575475194855
19908022	23219	one to many relationships in t-sql	select * from personnel p where not exists    (select * from address a where a.personnelid = p.id and a.isprimary = 1) 	0.0346133011916691
19908669	37271	how to phrase sql query when selecting second table based on information on first table	select item_table.item_name, c1.name as catname, c2.name as parentcatname from item_table join category_table c1 on item_table.categoryid=c1.categoryid  left outer join category_table c2 on c2.categoryid = c1.categoryparentid 	0
19909192	8445	a column aggregation function that determines if all of the values are equal to a constant in sybase iq	select   key   ,sum(case when value = 'pass' then 1 else 0 end) as num_passed   ,count(*) as num_tests from mytable group by key having num_tests = num_passed 	4.58973119233804e-05
19911054	11604	how to convert a number into timestamp in oracle/sql	select to_timestamp( to_char(20131108) ,'yyyymmdd') from dual 	0.000509259963490615
19911146	29650	mysql - pass field value into subquery	select *      from(            select             x.name as deptname            , x.id as deptid            , wt.sortposition as deptsortposition          from departments x          join web_taxonomy wt on (wt.deptid=x.id and wt.classid=0)          where x.web=1         order by sortposition     ) as d       left join (         select             c.name as classname            , c. id as classid            , c.department            , wt.sortposition as classsortposition            , wt.deptid         from classes c join web_taxonomy wt          on wt.classid=c.id and wt.subclassid=0         where web=1 order by classsortposition       ) as c on c.department=d.deptid and c.deptid = d.deptid  	0.0298328473040991
19911318	36559	sql server, get all week numbers by a given year?	select datepart(wk,dateadd(wk,t2.number,'2011')) as weeknumb from master..spt_values t2 where t2.type = 'p' and t2.number <= 255 and year(dateadd(wk,t2.number,'2011'))=2011 	0
19911647	12595	row number with random order of other field	select @rownum:=@rownum+1 'rank',  r1.* from     (select  pgid, picfile from pages,              (select @rownum:=0) as r2      where pos= 23       order by rand()  limit 5    ) as r1 order by rank 	0
19912275	18495	mysql query printing double records	select    sales.id as id,   sales.salehatsh as hatsch,   sales.timestamp as date,   sales.gatepass as gatepass,   sales.pname as pname,   sales.description as description,   sales.balance as balance,   'sale' as transanctiontype from sales where sales.timestamp = '2013-11-11' union  select    purchase.id,   purchase.purchasehatsh,   purchase.timestamp,   purchase.gatepass,   purchase.pname,   purchase.description,   purchase.balance,   'purchase' from purchase where purchase.timestamp = '2013-11-11' 	0.20138968551163
19912390	34085	how to add the sum of a column to the same sql query	select id,         weight,        (select sum(weight) from your_table) as sumofweight from your_table 	5.52839863049296e-05
19912538	9388	nested count in one query	select message_type,        count(message_type) as message_type_count,        sum(unread = 1) as unread_count from messages  group by message_type 	0.280898614656958
19913009	20438	mysql get count of each column where it equals a specific value	select sum(col1), sum(col2), sum(col3) from polldata 	0
19913422	36621	sql statements in access database	select firstname, lastname, phone, hours from ((trainers t inner join trainerplan tp on t.id = tp.trainerid) inner join fitnessplans fp on tp.planid = fp.id) where fp.id = 1; 	0.745188141818293
19913541	39423	oracle: select time in hh:mi format eg: 30:00	select to_char(trunc(runtimecol/3600),'09') || ':' || to_char(trunc(mod(runtimecol,3600)/60),'09')  from yourtable 	0.767407057802752
19913724	32931	i want to get the max(ha) and max(total) of grouped by 'subject' for all students for the given table	select sem,section,subject,usn, name, max(ha), max(total)     from table     group by sem, section, subject, usn, naam 	0
19914820	35057	email column in sql	select      di.docname as documentname,      di.uploadfile as fileuploaded,      d.deptype as department,      di.uploadedby as uploadedby,      at.approvetype as status,     u.email as useremail from dbo.documentinfo di         inner join dbo.approval a         on di.docid = a.docid         inner join dbo.approvetype at        on a.approveid =  at.approveid         inner join dbo.userss u        on u.userid = di.userid         inner join dbo.department d         on di.depid = d.depid        inner join dbo.doctype  dct        on di.doctypeid = dct.doctypeid where di.depid= @depid 	0.0820299031490006
19915665	20972	counting comments with one level of nesting	select count(*) from comments left join comments as parents on comments.parent_id = parents.id where comments.post_id = 123 or parents.post_id = 123 	0.0280222309997362
19916353	29431	php, sort an array from mysql	select      quiz_name,      quiz_attempts,      cumulative_score,     (cumulative_score/quiz_attempts) as score_avg from scoredata order by score_avg desc 	0.0189008484192617
19916680	28537	get the sum by comparing between two tables	select tb.id, tb.nom, tb.proddate, tb.qty, tb.stockrecno, sum(sd.quanite) from prodbiscuit as tb join stockdata as sd   on tb.id = sd.prodid where sd.status > 0 and sd.matcuisine = 3 group by tb.id, tb.nom, tb.proddate, tb.qty, tb.stockrecno 	5.36698158166524e-05
19918772	591	group table in terms of 2 column	select * from table group by hotelid, hotelname 	0.00320504180726139
19918912	1238	how to select from the db where version field is the recent one	select p.* from pricing p     join          (             select distributor, max(version) as ver              from pricing              group by distributor         ) mx on mx.ver = p.version and p.distributor = mx.distributor 	0
19922359	17654	data base query	select state_name,district_name from tablename where id='jk-01' 	0.0813173185760794
19922918	13799	pattern match in sql server	select document_id from document_master where document_id like 'apj1.000753%' order by len(document_id) - len(replace(document_id, '_', '')), document_id 	0.268059672571781
19925146	17052	return 1 or 0 as a subquery field with exists?	select [fields],        case when exists (select <criteria> from <tablename> ) then 1              else 0              end as subqueryresult from <tablename>      where a=b 	0.179975786637557
19927847	14233	sql server amalgamating datetime columns into one	select  stvs.id as 'sessionid', stbe.datetimeselected as 'searchtime', stbe.bedrooms as bedrooms, null as dogs, null as duration  from stats_visitorsessions stvs left join stats_bedrooms stbe on stbe.sessionid=stvs.sessionid union all select  stvs.id as 'sessionid', stdo.datetimeselected as 'searchtime', null as bedrooms, stdo.dogs as dogs, null as duration  from stats_visitorsessions stvs left join stats_dogs stdo on stdo.sessionid=stvs.sessionid union all select  stvs.id as 'sessionid', stdu.datetimeselected as 'searchtime', null as bedrooms, null as dogs, stdu.duration as duration  from stats_visitorsessions stvs left join stats_duration stdu on stdu.sessionid=stvs.sessionid 	0.00130993187000193
19928235	36175	sqlite substract sums (with group by) with join and duplicates	select     t2req.typeid,     t2req.quantity,     t2stock.quantity,    t2req.quantity - t2stock.quantity as diff  from      (select typeid, sum(quantity) quantity from t2req group by typeid) t2req join      (select typeid, sum(quantity) quantity from t2stock group by typeid) t2stock          on t2req.typeid = t2stock.typeid  order by diff desc; 	0.489858709716781
19929763	39231	using varchar parameter in exec()	select * from products where vouchertype=@vouchertype and    (@productid=-1 or  productid=@productid)   and    (@brandid=-1 or  brandid=@brandid) 	0.796639215802948
19930070	9553	mysql query to select all except something	select ro.email from registerorder ro  inner join food f on f.namea = ro.namea group by ro.email having sum(f.type <> 'vegtables') = 0 	0.0437657915951116
19930889	26079	mysql queries - selecting from 2 tables and if exists in the other check field	select p.id  from products  left join product_ranges pr on pr.product_id = p.id where (pr.product_id is null or pr.other_id = 16) 	0
19932497	31024	dynamically change ssrs variable into fact table id	select *  from lis_results r inner join lis_results_log l on l.order_testid = r.order_testid where r.sampleid = 1311120001 	0.00185921016131231
19932600	5378	mysql - multiple sum functions in query	select amount - (select sum(amountused) from tblamountused) as amountleft from tblamount having amountleft > 0 	0.636601771794963
19932704	14754	group by results sets in one row ms access query	select schools.schoolsname,             count(schools.[organization]) as organization,             count(schools.[city]) as city,             count(schools.[agent]) as agent,             count(schools.schoolsname) as total,             sum(iif((schools.[organization]) like 'yes', schools.[dollaramount],0)) as organization_award,             sum(iif((schools.[city]) like 'yes', schools.[dollaramount],0)) as city_award,             sum(iif((schools.[agent]) like 'yes', schools.[dollaramount],0)) as agent_award       from schools   group by schools.schoolsname; 	0.034224418649514
19932938	30263	sql server get latest value in table x before date for not distinct rows in table y	select     x.patentid,     x.startdate,     x.dateval,     x.decval from (     select         t.patientid,         t.startdate,         p.dateval,         p.decval,         row_number() over (             partition by t.patientid, t.startdate             order by p.dateval desc         ) rn     from         patienttreatment t             inner join         patientdata p             on t.patientid = p.fk_patientid      where         p.fk_paramsettingid = 68 and         t.startdate > p.dateval     ) x where     x.rn = 1 	0
19932996	33271	adding column to group by clause messes up counting	select v.sessionidtime, v.correlationid, total from voipdetailsview v inner join (select correlationid, count(correlationid) as total from voipdetailsview where responsecode = 200 group by correlationid) agg on v.correlationid = agg.correlationid 	0.255038427705596
19933437	5845	sql conditions, one definite others variable	select * from usertags inner join events on usertags.e_id=events.e_id where id = 2 and (tag='coffee' or tag='breakfast_brunch' or tag='scandinavian') 	0.0631119666653447
19934424	29795	sql to get last reply of certain user type	select t.tid, tr.reply_date, tr.rid, u.display_name, u.user_type from ticket t inner join (   select tr_last.tid, tr_last.reply_date, tr_last.rid, tr_last.uid   from ticket_reply tr_last   inner join (     select tid, max(reply_date)     from ticket_reply     group by tid     ) tr2 on tr2.tid = tr_last.tid and tr_last.reply_date = tr2.reply_date   ) tr on tr.tid = t.tid left join user u on u.uid = tr.uid and u.user_type = "user" where t.status != "closed"   and date_sub(curdate(), interval 10 day) >= tr.reply_date; 	0
19934446	18590	select values from multiple tables where certain value is zero	select lastname, count(goal.player_id) "goals" from player left outer join goal on player.player_id = goal.player_id and goal.owngoal = 0 group by lastname order by "goals" desc; 	0
19935189	29921	select query (one table)	select one.name from (select name from pruza where sifvu = 1) one join (select name from pruza where sifvu = 2) two on (one.name = two.name) 	0.0193357477063134
19936315	27053	get the persons, who are in both sets	select pc.person_id   from person_club_data pc   inner join group_clubs gc on (gc.club_id = pc.club_id)  where gc.group_id = 2  group by pc.person_id  having count(pc.person_id) >= (      select count(gc.club_id)        from group_clubs gc2       where gc2.group_id = 2  ) 	0.000105827336083108
19937295	36895	select name and rowcount?	select s.id, count(*) from schools s inner join students ss on ss.schoolid = s.id group by s.id 	0.0935325197828486
19937576	15521	check if value in column is date, and then do something with it	select distinct person_id,  case    when isdate(description) = 1 then ''   else description end as refusereason     from person 	0.00320652241731843
19937596	18848	count rows without issuing a separate count	select a, b, c, count(*) over() as total from dbo.tablea where x = 123 and y = 'abc' and z = 999; 	0.00204323644109856
19938162	7611	sql query to find linked records in a single table	select  * from    customertable c join    customertable p on p.id = c.linkedid where   p.customer = 'a' 	0.000442848063034462
19938263	30862	counting values from a column and grouping and sorting by a second value	select  year,     count(case when score = 1 then 1 end) as `1`,     count(case when score = 2 then 1 end) as `2`,     count(case when score = 3 then 1 end) as `3`,     count(case when score = 4 then 1 end) as `4` from table group by year 	0
19940329	13614	sql table order by with the column name having numbers	select * from mytable order by cast(substr(mycolumn, 7) as int) 	0.00291447603775758
19942240	22047	i am trying to do a mysql query to get the suppliers who only supply a red part?	select     sid from     suppliers s where     exists (         select              'x'         from             catalog c                 inner join             parts p                 on c.pid = p.pid         where             s.sid = c.sid and             p.color = 'red'     ) and     not exists (         select             'x'         from             catalog c                 inner join             parts p                 on c.pid = p.pid         where             s.sid = c.sid and             p.color != 'red'     ) 	0.00249994134913155
19942699	29972	mysql query to find mobile phone numbers	select * from mytable where phonenumber like '01%'; 	0.0205106281558181
19942771	26270	get postion of group in mysql	select     t.id,     t.datum,     t.rank,     t.name from (      select         s.id,         s.datum,         s.name,         s.points,         if(@datum <> s.datum, @rank := 1, @rank := @rank + 1) as rank,          @datum := s.datum     from         score_table s             cross join (             select                 @rank := null,                 @datum := '1980-01-01'         ) as r      order by         s.datum,         s.points desc     ) as t order by      t.id,     t.rank; 	0.0168650620862203
19945247	9176	select repeated data based on column value	select distinct t.col1 as colx, t.col2 as coly, level as colz from tablee t connect by level <= t.col3 order by t.col1, t.col2, level 	5.14299335045356e-05
19946084	17141	sql fetch results by concatenating words in column	select * from table where replace(store_name, ' ', '') like '%'+@search+'%' or  store_name like '%'+@search +'%' 	0.00296593534514491
19946599	37220	mysql multiple fields referring to one table	select   a.producta,   b1.type as typea,   a.productb,   b2.type as typeb from   a     left join b as b1 on a.typea=b1.id     left join b as b2 on a.typeb=b2.id 	0.00407265282621756
19947596	40324	retrieving names from 2 tables with same column names	select patient.firstname, ctaker.firstname  from mortenu8.patient patient, caretaker ctaker  where ctaker.firstname = patient.firstname; 	0
19950693	17899	listing duplicated records using t sql	select distinct t1.*  from table as t1      inner join table as t2     on t1.firstname = t2.firstname         and t1.lastname = t2.lastname        and t1.id <> t2.id 	0.0203452672755653
19951628	22466	add record for every single id when join table	select t1.id,t2.anotherid,        coalesce(t3.amount,0) as amount from tablea as t1 cross join (select distinct anotherid from tableb) as t2 left join tableb as t3 on (t1.id=t3.id)                            and                            (t2.anotherid=t3.anotherid) order by t2.anotherid,t1.id 	0
19951663	20694	sql running percentage	select x.*      , sum(y.choice)/count(*) * 100 pct    from film_choice x    join film_choice y      on y.film <= x.film   group      by x.film; 	0.268133313622912
19953760	3472	how to do an intersect of two subqueries using mysql	select threads.id from threads  inner join thread_user on thread_user.thread_id = threads.id inner join messages on messages.thread_id = threads.id where thread_user.user_id = 1 and threads.draft = false and messages.user_id != 1 	0.313139650578024
19954607	35531	mysql selecting information	select r.door_nr,         r.space - sum(p.name is not null) as free from rooms r left join people p on p.door_nr = r.door_nr group by r.door_nr, r.space having free > 0 	0.0200391569751112
19955193	19153	mysql optimizing left join for large data query with same table	select      max(case datacolumn when 'firstname' then datavalue else '' end) as firstname,     max(case datacolumn when 'lastname' then datavalue else '' end) as lastname,     max(case datacolumn when 'age' then datavalue else '' end) as age from      large group by datarow 	0.773331035380594
19957276	11927	t-sql return ungrouped records making up sum	select t.customerid,         t.createdat,         t.transactionamount from transactions t inner join (     select         customerid,      from transactions     where createdat > dateadd( day, -7, getdate() )     group by clientid, cast(createdat as date)     having sum(transactionamount) > 1000 ) a on a.customerid = t.customerid where t.createdat > dateadd( day, -7, getdate() ) 	0.0907478983757668
19957969	40855	combine multiple lines onto one line	select orderno,     max(case when param_id = 'variant' then param_val end) as variant,     max(case when param_id = 'period_from' then param_val end) as period_from,     max(case when param_id = 'period_to' then param_val end) as period_to,     max(case when param_id = 'division' then param_val end) as division,     max(case when param_id = 'show_div' then param_val end) as show_div,     max(case when param_id = 'group_div' then param_val end) as group_div from orderreport group by orderno order by orderno 	0.00103932814023476
19958052	40385	mysql query a query and return a count	select   hosts.*, count(gid) from     hosts left join guests using (hid) group by hid 	0.131685858262706
19958148	23239	mysql - count total entries for two variables	select county, count(county) as counties, ad_type from house group by county, ad_type 	0
19958222	2536	t-sql append data to an existing dataset	select st.* , dbo.ufn_usage_and_consumption(st.item_number, st.lot_number) from some_table st 	0.0270746354530068
19959164	24405	display values from several tables that share one foreign key	select a.name as 'academy name',         a.mou_id as         a.academy_id        a.status        a.created_date as 'academy created',        c.course_name as 'course name',        ac.start_date as 'course start date',        i.instructor_fname as 'instructor first name',        co.contact_fname as 'contact first name' from academies a inner join academy_courses ac on a.id = ac.academy_id inner join courses c on c.id = ac.course_id inner join instructors i on i.instructor_id = ac.instructor_id inner join main_contact co on co.academy_id = a.id 	0
19959503	37814	sql sum of 2 rows when 4 rows are returned	select distinct wo.work_order_no, wos.status_description, wo.order_qty as [orderqty], sum(p.good_tot_diff) as [complete], (sum(p.good_tot_diff)/wo.order_qty) * 100 as [percentcomplete] from wo_master as wo,      process as p,      wo_statuses as wos,      so_children as soc,      so_sales_orders as sos,      cs_customers as csc where wo.work_order_no = p.entry_18_data_txt   and wo.work_order_no = soc.work_order_no   and wo.wo_status_id = wos.wo_status_id   and wo.mfg_building_id = @buildid   and wos.wo_status_id = @statusid group by wo.work_order_no,          wos.status_description,          wo.order_qty; 	0
19960020	422	mysql case when then empty case values	select a.ageband, ifnull(t.agecount, 0) from (   select     case       when age is null then 'unspecified'       when age < 18 then '<18'       when age >= 18 and age <= 24 then '18-24'       when age >= 25 and age <= 30 then '25-30'       when age >= 31 and age <= 40 then '31-40'       when age > 40 then '>40'     end as ageband,     count(*) as agecount   from (select age from table1) t   group by ageband ) t right join (   select 'unspecified' as ageband union   select '<18' union   select '18-24' union   select '25-30' union   select '31-40' union   select '>40' ) a on t.ageband = a.ageband 	0.720369432373766
19960398	8351	conditional query of the tables	select p1.playerid, s1.scorename, j1.value from players as p1 inner join scoreforplayerstype1 as j1 on j1.playerid = p1.playerid inner join scoretype1 as s1 on  s1.scoreid = j1.scoreid union all select p2.playerid, s2.scorename, j2.value from players as p2 inner join scoreforplayerstype2 as j2 on j1.playerid = p1.playerid inner join scoretype2 as s2 on  s1.scoreid = j1.scoreid 	0.144208948396661
19962314	29337	sql statement to combine both fields in one table that match the id element in another table	select   event.nid,   location.location,   event_type.event_type,   event.field_eventstartdate_value from   content_type_event as event left outer join (    select       nid,       name as location     from       term_data join       term_node on term_data.tid=term_node.tid     where term_data.vid = 4) as location on location.nid = event.nid left outer join (    select       nid,       name as event_type     from       term_data join       term_node on term_data.tid = term_node.tid     where term_data.vid = 3) as event_type on event_type.nid = event.nid; 	0
19963520	38685	mysql group by with ordering/priority of another column	select * from test join (select 'west' as direction, 4 as weight       union       select 'north',3       union       select 'south',2       union       select 'east',1) as priority   on priority.direction = test.direction join (       select route, max(weight) as weight       from test       join (select 'west' as direction, 4 as weight             union             select 'north',3             union             select 'south',2             union             select 'east',1) as priority         on priority.direction = test.direction       group by route ) as t1   on t1.route = test.route     and t1.weight = priority.weight 	0.00787413752227973
19964764	33691	echo a list of products that do not have a category assigned magento	select cpe.entity_id, cpe.sku from catalog_product_entity as cpe left join catalog_category_product as ccp on cpe.entity_id = ccp.product_id where category_id is null 	0
19967483	2036	searching a grid of tiles with mysql and php	select * from table where localcoordinatex between $x-lo and $x-hi and localcoordinatey between $y-lo and $y-hi. 	0.176477545384475
19971326	3872	mysql 30 days range selection from column value	select sum(m.kilowatts), day(m.report_date),  d.billing_cycle_day from reports_month m join device d on m.mobile_number = d.mobile_number where m.mobile_number = '123' and day(m.report_date) between d.billing_cycle_day and date_add(d.billing_cycle_day, interval 30 day) group by day(m.report_date) 	0
19971613	147	dynamically generated column headings in sql query	select      userid,          browsername,           cast(day(logintime) as nvarchar(2)) + '-' + cast(month(logintime) as nvarchar(2))  as period   into #tmp from user_log_table order by 1 declare @cols as nvarchar(max), @query  as nvarchar(max) select @cols = stuff((select distinct ','                      + quotename(convert(varchar(10), period, 120))                  from #tmp order by 1         for xml path(''), type         ).value('.', 'nvarchar(max)')      ,1,1,'') set @query = 'select userid, browsername,' + @cols + ' from           (             select userid, browsername, period             from #tmp         ) x         pivot          (             count(period)             for period in (' + @cols + ')         ) p ' exec(@query) drop table #tmp 	0.320155732006337
19973184	6051	not grouping through latest dates	select barcodeitem, temp.categoryid, cm.categoryname, temp.productid, pm.productname, effectfrom from (    select barcodeitem, categoryid, productid, convert(date, effectfrom) as effectfrom,     rank() over (partition by barcodeitem order by effectfrom desc) dest_rank     from barcodegroupmap   ) temp   inner join categorymaster cm on cm.categoryid = temp.categoryid   inner join productmaster pm on pm.productid = temp.productid   where temp.dest_rank = 1 	0.00328480492190621
19974064	36932	select statement not selecting the correct fields in dreamweaver	select cit.city,        prov.base_city from providers prov   join cities cit     on prov.base_city = cit.id   left join provider_city_category pcc on prov.id = pcc.provider_id   left join categories cat on pcc.category_id = cat.id where cat.id =7   and pcc.city_id =1 limit 1; 	0.22073352937641
19974574	39656	how to write query to get the data based on month?	select monthname(attendencedate) as monthname,   count(*) as totalworking_days,   sum(case when attendence = 'present' then 1 else 0 end) as present,   sum(case when attendence = 'absent' then 1 else 0 end as absent       from lstms_attendence where addmissionno = 'lstm-0008/2013-2014' group by monthname(attendencedate); 	0
19974804	14982	migration of mysql dates in integer format	select cast(concat(date(olddb.table.date),' ',time(olddb.table.time*100)) as datetime); 	0.0137673374316641
19975257	40570	postgres query to check a string is a number	select '12.41212' ~ '^[0-9\.]+$' => true select 'service' ~ '^[0-9\.]+$' => false 	0.0070392545139963
19975685	13789	how to convert messy two letter code into one "two letter" column tsql in ms sql?	select substring(columnid, 1, 2) from your_table union select substring(replace(replace(columnid,'\\',''),'/',''), 3, 2) from your_table union select substring(replace(replace(columnid,'\\',''),'/',''), 5, 2) from your_table where length(replace(replace(columnid,'\\',''),'/','')) = 6 	0
19977438	856	is there any sql-query to check the value is exist or not in db table	select case when count(1) > 0 then 'true' else 'false' end from table where email = 'abc@gmail.com' 	0.078732351020996
19977695	22706	merging returned results from two querys for log type feature	select "1" as `log_type`, tasks.title, tasks.payment, tasks.timestamp from tasks where tasks.user_id = 12 union select "2", payouts.processor, payouts.amount , payouts.timestamp from payouts where payouts.user_id = 12 order by 4 	0.00684902484017959
19978537	38979	selecting latest row from max row of 3rd table	select * from (   select p.*, et.eventname, et.eventsequence from people p     join peopleevents pe       on p.personid = pe.personid     join eventtypes et       on et.eventid = pe.eventid   order by eventsequence desc ) t group by personid 	0
19978546	1677	select ids that don't exist in a table	select s.a from generate_series(<start>, <stop>) as s(a) except select id from <mytable> where <yourclause> 	0.000130192191733874
19979709	12253	sql - creating a historical fact table from latest snapshot data	select t2.datestr, t1.id from tableone t1 join tabletwo t2 on t2 startdatetime between t1.datea and t1.dateb order by t2.datestr, t1.id; 	0.000250274930178977
19979835	31192	mysql trims value in where	select * from message where binary(messagekey) = 'opt-193-381-markets'; 	0.312111708372149
19981190	36563	how to select records with maximum values in two columns?	select   max( year    ) keep ( dense_rank last order by year asc, quarter asc, message asc ) as year,          max( quarter ) keep ( dense_rank last order by year asc, quarter asc, message asc ) as quarter,          max( message ) keep ( dense_rank last order by year asc, quarter asc, message asc ) as message,          type from     info group by type; 	0
19981495	8912	sql left join foreign key both tables	select `project_question`.`id` as question_id,               `project_question`.`question`,               q_user.`username` as askedby,               `project_question`.`created` as question_created,               `project_answer`.`id` as answer_id,               `project_answer`.`answer`,               a_user.`username` as answeredby,               `project_answer`.`accepted`,               `project_answer`.`created` as answer_created         from `project_question`    left join `project_answer`           on `project_question`.`id` = `project_answer`.`questionid`   inner join `user` as q_user           on `project_question`.`userid` = q_user.`userid`   inner join `user` as a_user           on `project_answer`.`userid` = a_user.`userid`        where `project_question`.`projectid` = $args[0]          and `project_question`.`projectphase` = 2 	0.0368282376146286
19982795	23851	dynamic column, one value, group by and order by	select sq.* from (     select id, message,        (case when from_user_id = 1 then to_user_id else from_user_id end) as with_user_id     from privates     where from_user_id = 1 or to_user_id = 1     order by id desc ) as sq group by sq.with_user_id 	0.00679382631773895
19983617	4784	sum values across multiple tables	select playerid,         concat (day(date), '-', month(date)) as day_month,         sum(points) as total_points from (   select playerid, date, points   from rs_games     union all     select playerid, date, points   from po_games   ) a group by 1, 2 	0.00294217620020182
19984043	11774	select using wildcard to find ending in two character then numeric	select number where     number like '%st[1-9][0-9][0-9]' or      number like '%st[1-9][0-9]' or      number like '%st[1-9]' 	0.00944663813298462
19984746	15222	formating date and time on a table populated with mysql	select    date_format(date,'%m/%d/%y') as formateddate,    time_format(time,'%h:%i') as formatedtime,    info  from tblinfo  where idinfo = ? 	0.00735721527308726
19984799	8897	how do i return column headers when there are no rows returned with invoke-sqlcmd?	select [column_name] from information_schema.columns where table_name='tablename' 	0.000364374179658666
19985424	10621	how to create a query that shows all different row data when joining with a link table?	select 3 file_id, user_name, if(d.file_id = 3, 1, 0) downloaded  from users u left join downloads d on d.user_id = u.user_id && d.file_id = 3 order by downloaded desc 	0
19986121	3338	trying to list certain dates on sql	select *      from table1     where extract( month from dates ) <> 10 	0.00027177227647975
19986171	8218	find a user that is not a member of a specific group	select userid, count(*) group_count from user_groups group by userid having group_count = 1 	0.000182073577793212
19986657	14450	mysql two table, 3 column dependent query	select date,count(*)  from scans, targets  where scans.idtarget = targets.id  and targets.starname like '%21%'   group by date; 	0.00738482475955915
19988378	2203	applying multiple percentages to a column	select prodid, exp(sum(log(modpercent/100+1)))*avg(baseprice) from product join modifiers using(prodid)  group by prodid 	0.426763425283128
19988413	13451	how do i auto increment my own results column from a max value in a table?	select     seed.id + row_number() over (order by t.id) as number,     t.id from     t cross join     (select max(id) as id from t) as seed 	0
19989124	19244	convert rows to columns in mysql v3	select max(case when locationid = 1 then floatvalue end) flow,        max(case when locationid = 2 then floatvalue end) level,        max(case when locationid = 3 then floatvalue end) pressure,        max(case when locationid = 4 then floatvalue end) mr   from table1  where locationid in(1, 2, 3, 4) union all select max(case when locationid = 5 then floatvalue end),        max(case when locationid = 6 then floatvalue end),        max(case when locationid = 7 then floatvalue end),        max(case when locationid = 8 then floatvalue end)   from table1  where locationid in(5, 6, 7, 8) 	0.00373063734612606
19989952	31105	adding a count from another table to existing query	select posts.titulo as value,   posts.id as id,   posts.img_src as img,   posts.id_familia,   posts.tiempo,   posts.votos,   familias.clave,   familias.id as fm,   textos.clave,   textos.texto as familia,   coalesce(com_count.num_comments,0) as num_comments from posts  inner join familias on posts.id_familia = familias.id inner join textos familias.clave = textos.clave left join      ( select id_post, count(*) as num_comments       from comentarios       group by id_post     ) com_count on com_count.id_post = posts.id    where and textos.lengua = ".detectaridioma()."   and posts.id_usuario = $term order by posts.id desc 	0.000413024019222096
19993272	18192	oracle- logically give each set of rows a group based on a value from ordered list	select sum(case when line_type  = 0 then 1                  else 0 end           ) over (order by sequence_number) as grp,        line_type,        sequence_number,        product from ret_trand order by sequence_number; 	0
19993940	14869	grouping the data according to table field	select *    from (     select m.*, row_number() over (partition by groups, barcodeitem                                     order by effectfrom desc, createddate desc) rnum       from barcodegroupmap m      where groups = 1 ) t  where rnum = 1  order by groups, barcode item 	0.000264697713119473
19993949	30838	excluding values with a subquery	select movie_name from movies as m inner join actors_movies as am on m.movie_id = am.movie_id left outer join actors as a on a.actor_id = am.actor_id     and actor_name = 'actor_name' where a.actor_id is null; 	0.0661539908202275
19994073	3446	multiple outer joins return top result	select object.id, (select name from gloss g where g.object_id = x.object_id and g.order = x.ord) as [glossname],     x.order, title.name  from object left outer join     (select object_id, min(order) ord from gloss group by object_id) x on x.object_id = object.id left outer join title on title.object_id = object.id 	0.445695579095437
19995141	35432	sql using where contains to return rows based on the content of another table	select * from stores s where exists (     select * from countries     where contains(s.address1, town) or contains(s.address2, town) ) 	0
19995643	26655	check if a data set is present in a database	select * from productsinventory where productid in ("ab","bc","cd","ae","fg","bv","etc"); 	0.00290592641684296
19997255	33001	comparing each value with rest in oracle	select     s.sid,     s.name from student s where not exists (     select *     from takes t1     join takes t2 on (t1.cid = t2.cid and t1.sid <> t2.sid and t2.score > t1.score)     where t1.sid = s.sid ); 	7.98819028620177e-05
19998210	2612	how do i get distinct count values of 2 columns?	select a from yourtable union select b from yourtable 	0
19998850	14573	isnull/coalesce counterpart for values that are not null	select isnull(nullif(dbo.getfirstssninfromssnout(rma.imei), 'n/a'), rma.imei) as [imei to credit]      , othercolumns from dbo.tablename 	0.0336044776738316
19999165	27953	how to select the key of a group order by column a where a column b is not ordering	select distinct d1.id from data d1, data d2 where d2.id = d1.id and d2.line_no > d1.line_no and d2.obj_id < d1.obj_id 	0.000298436096668201
19999234	3960	how to get last 10 added records in sqlite table in iphone	select     * from     contentmaster where     contentaddedbyuserid='%@' and     hiveletcode='%@' order by     rowid desc limit 10 	0
20001256	17895	in ms azure database how do you search for a string containing _	select * from table where fieldcolumn like '%!_%' escape '!' 	0.535163598307719
20002764	29529	sort by id desc	select * from news_blog order by `news_id` desc 	0.0252915639070516
20004967	38856	getting sum within join and group by query	select sum (mycount) from (select  account_asset.product_group_id, product_group.product_code,  product_group.name, product_group.conference_year, product_group.delivery_format, product_group.id, count(*) as mycount from account_asset  inner join product_group on product_group.id = account_asset.product_group_id group by account_asset.product_group_id  order by product_group.conference_year,product_group.product_code,mycount) t1 	0.293804713891332
20005979	14434	select field from table a where subselect from table b = table a field	select a.*,        stuff((               select ', ' + cast([somevalue2] as varchar(20))               from tableb b               where a.id = b.id               for xml path ('')), 1, 1, '') from tablea a 	0
20008201	29362	sql divide two integers and get a decimal value error	select    convert( decimal(4,3)          , ( convert(decimal(10,3), abc) / convert(decimal(10,3), xyz) )           ) as def 	0.00242043929111935
20008364	37347	how to add a subquery to return count of related rows	select subscriberid   ,subscribername   ,daysuntilexpired   ,subscriptionstatus subscriptionstatuscode   , c.description  subscriptionstatus   ,(select count(*) as numberusers from dbo.userinfo where subscriberid = s.subscriberid) as numberusers from dbo.subscriber s      join dbo.codevalue c on s.subscriptionstatus = c.value     join dbo.codenamespace n on n.id = c.codenamespaceid and n.name = 'subscriptionstatus'     join dbo.codevalue v on s.notificationstatus = v.value     join dbo.codenamespace x on x.id = v.codenamespaceid and x.name = 'notificationstatus' group by      s.subscriberid   ,subscribername   ,daysuntilexpired   ,s.subscriptionstatus   ,subscriptionstatus 	0.00012808728833266
20009462	18912	mysql: count total "value" for each occurrence	select color,sum(amount) as count from tablename group by color order by count desc; 	0
20009731	24118	generate_series for min and max dates	select * from generate_series (     (select extract (year from min(t1.create_date)) from t1)::int,     (select extract (year from max(t1.create_date)) from t1)::int ) 	0.0158057293545077
20010090	29897	sql divide a string when a comma appears and join it back in reverse order	select  right(name,len(name)-charindex(', ',name)) + ' ' + left(name,charindex(', ',name)-1) from @table1; 	0.0559397213520498
20010952	11372	using count and union to extract data and support a scenario	select customerid, voucherid, minimumspendamount, validfromdate, validtodate from dbo.discountvoucher where validfromdate <= 15/11/2013 and validtodate >= 15/11/2013 and customerid in     (select customerid     from dbo.discountvoucher     where validfromdate <= 15/11/2013     and validtodate >= 15/11/2013     group by customerid     having sum(case when minimumspendamount > 0 then 1 else 0 end) = 1     and sum(case when minimumspendamount = 0 then 1 else 0 end) = 1     ) order by customerid 	0.307945524746679
20012290	12983	refering to another field in a form and return entries based on the filed	select org_year from org_year where org_name_id=organisation_name_id.value; group by org_year.org_year 	0
20012831	3011	sum of counted fields	select      count(table1.id) as field1,       count(table2.id) as field2,     count(table1.id) + count(table2.id) as field3 from table3 left join table1 on (table3.id=table1.idv)  left join table2 on (table3.id=table2.idv)   group by table3.id order by field3 desc 	0.00572904568524296
20014432	40514	getting count to return 0 in oracle sql using a union	select r.vid_id, movie_title, vid_format, count(r.client_num) "num_rental" from video v left join rental r on r.vid_id = v.vid_id left join movie m on m.movie_num = v.movie_num left join client c on r.client_num = c.client_num group by r.vid_id, movie_title, vid_format 	0.129148843809657
20014910	1285	ordering with id for a distinct column	select distinct sender from ((select distinct pm.id,pm.sender from pm where receiver='a') union (select distinct pm.id,pm.receiver from pm where sender='a') order by id desc) as abc 	0.00729547295719203
20015937	10873	incorporating an incrementing value into this sql	select id, percent,         @currank := if(parent = @prevparent, @currank + 1, 1) as rank,        @prevparent := parent from (     select child.id, child.percent, child.parent     from likesd parent     join likesd child        on parent.id = child.parent     where parent.type = 3     order by parent.id, child.percent desc) x cross join (select @currank := 0, @prevparent := null) r 	0.159559817257815
20017695	37841	teradata : transpose columns to rows	select 'job1', job1 from tab  union all  select 'job2', job2 from tab 	0.00390521838179084
20018551	12841	mysql select distinct values from query excluding sorting-purpose column	select category from (   select category, count(*) as number   from data where date between adddate(now(), interval -2 day) and now()   group by category   union all   select category, count(*) as number   from data where date < adddate(now(), interval -2 day)   group by category   order by number desc ) s group by category order by max(number) desc limit 50 	0.000560705685106903
20019297	20895	query for padding a string in sqlite in ios	select substr(size || 'yyyyyyyyyyyyyyyyyyyy', 1, 20) from sizetable 	0.611002387996271
20020119	16279	mysql create select results from two separate queries	select teams.team_name, count(*) as total_points_gained, (select count(*) from fixtures where fixtures.team_name = teams.team_name) as games_played  from scores,players,teams  where scores.player_id=players.player_id  and players.team_name = teams.team_name  group by teams.team_name 	0.00128542097967782
20021105	22353	mysql query to get the row position in a table	select * from ( select t.*,(@rownum := @rownum + 1) as rownum from ( select sum(score) as s,id from mytable group by id order by s desc ) as t  join    (select @rownum := 0) r  ) as w where id = 3 	0.000230540473294008
20025595	28910	how to create a virtual table or how to order by date in same row	select t.*, t2.times from yourtable t, (     select id, time1 times from yourtable union     select id, time2 from yourtable union     select id, time3 from yourtable union     select id, time4 from yourtable union     select id, time5 from yourtable ) t2  where t.id = t2.id  order by t2.times desc 	0
20025854	39138	error joining using same id for two columns - mysql	select song.title as 'song title',      perfartist1.`name` as 'made popular by',      recording.title as 'recording title',      perfartist2.`name` as 'recorded by' from      perfartist_recording inner join     recording on perfartist_recording.recording_id = recording.id inner join      song_recording on song_recording.recording_id = recording.id inner join      song on song_recording.song_id = song.id  inner join      perfartist perfartist1 on madepopularby.perfartist_id = perfartist1.perfartist_id inner join      perfartist perfartist2 on perfartist_recording.perfartist_id = perfartist2.perfartist.id 	0.00143983509457937
20026158	41027	where to start sql query	select payer.company_name, payer.contact_name, payer.phone_num  from payer  join plan on plan.payer_id = payer.payer_id  join policy on policy.plan_id = plan.plan_id left outer join insured on insured.policy_id = policy.policy_id  where  insured.policy_id is null 	0.378205078048448
20027093	18959	how to get year in format yy in sql server in asp.net c#	select right(year(getdate()),2) select year(getdate()) % 100 	0.016861901235516
20028102	31946	merging columns from separate tables	select playername, sum(field1) + sum(field2) as power, sum(field3) as weakness from(select t1.playername, t2.field1, t2.field2, t3.field3      from       plays t1,creep t2,weakcreep t3      where       t1.id = t2.id and t1.id = t3.id      group by t1.playername, t2.field1, t2.field2, t3.field3)      group by playername; 	7.58541295207774e-05
20028856	10106	count the difference between two nbr i in the query?	select    max,   min,   max - min as difference from    aggregates  where    name='tagg' and date between date1 and date2; 	0.00109017160847597
20029489	12743	how to select from 2 different tables and order them by one column?	select post, date from tableone union select sharedpost, date from tabletwo order by date 	0
20030931	39853	new to sql - sql statement query	select van.model, vaf.modeldescription, van.[count of chassis] from (select model, count(chassis) as [count of chassis]       from van.csv       group by model       ) van inner join vaf.csv vaf on van.model = vaf.modelid group by van.model, vaf.modeldescription, van.[count of chassis] 	0.621888772456525
20031413	24702	sql query, total number of people who have taken more than 1 variety in a season	select count(*)  from (select 1 as y       from farmer data       group by farmer name       having count(distinct variety of crop)>1) x 	0
20031821	22219	mysql - select rows which have less than x "child rows"	select one.planet_id, one.planet_name from first_table one join second_table two on (one.planet_id = two.planet_id) group by one.planet_id, one.planet_id having count(two.area_id) < 5 	0
20032946	27897	select lower and upper from lower only table	select r1.family, r1.name, r1.lowbound lower, coalesce(min(r2.lowbound), 9) upper from records r1 left join records r2 on r1.family = r2.family and r1.lowbound < r2.lowbound group by r1.family, r1.name, r1.lowbound 	0.155186726120831
20034782	6238	making a co-occurrence matrix from mysql database in mysql, php or r	select   a.uid a, b.uid b, count(*) cnt from     my_table a join my_table b on b.id = a.id and b.uid > a.uid group by a.uid, b.uid 	0.161007518626377
20035444	29339	sql: how to get rows containing only certain ids?	select `group`  from mytable group by `group` having group_concat(distinct `user` order by `user`) = '1,2'; 	0
20036242	5883	how to make one sql query asking for many rows	select n1.node_id from node_tags n1 inner join node_tags n2 on n1.node_id = n2.node_id inner join node_tags n3 on n1.node_id = n3.node_id where n1.k = 'addr:housenumber' and n1.v = '50' and n2.k = 'addr:street' and n2.v = 'kingsway' and n3.k = 'addr:city' and n3.v = 'london' 	0.0130908449671945
20038526	14718	insert (join of two tables) into a different table	select id, name, email, password into newtable  from  (   select o1.id, concat(o2.fname, ' ', o2.lname), o2.email,  o1.password   from oldtable1 as o1     join oldtable2 as o2     on o1.id = o2.id ) 	6.27152307182054e-05
20039160	41004	how to get a regular rank without olap functions	select a.nickname,   a.avg_responsetime,   count(b.avg_responsetime) + 1 - count(case (a.avg_responsetime - b.avg_responsetime) when 0 then 1 else null end) as rank from table_avg a, table_avg b where b.avg_responsetime<=a.avg_responsetime group by a.nickname, a.avg_responsetime having count(b.avg_responsetime) <=10 order by rank asc, a.nickname asc; 	0.415495831207226
20041335	22597	fetch last id where column is equal to a string	select max(id) from tblfood  where food_name='chicken sandwich'; 	0
20042573	30132	return the query when count of a query is greater than a number?	select *  from tab  where m in (select m from tab where m = 1 group by m having count(id) > 5); 	0.000758490664556686
20043086	12896	sql: reading description for a columns from a different table	select      c1.c2 as c1, c2.c2 as c2 from     t1 inner join     t2 c1 on t1.c1 = c1.c1 inner join     t2 c2 on t1.c2 = c2.c1 	0
20043312	3012	how to delcare the whole year sql	select * from your_table where year(your_date_column) = @year 	0.00730298177410526
20044470	540	conver varchar value as time in oracle	select      to_char(        to_date('001500','hh24miss')      ,'hh24:mi:ss') from dual; 	0.0346223005875839
20045086	7771	extract first entry for each person for each day	select [date], agentname, [exception], [start], [stop]  from table1 t  inner join  (     select [date], agentname, min([start]) as [start]     from table1     group by [date], agentname  ) x  on t.[date] = x.[date] and t.agentname = x.agentname and t.[start] = x.[start] 	0
20045189	11946	mysql select * from one table based on stock from another table	select * from oos_email_notify tbl1 join temp_parts tbl2 on tbl1.part_id = tbl2.part_id where tbl2.stock > 0 and tbl1.email_sent = 0 	0
20045499	30488	sql server 2008 select same field with different values	select     y1.pid     ,y1.description     ,y2.description from     ytest as y1 inner join     ytest as y2 on     y1.pid = y2.pid and y1.description = 'log' and y2.description like 'design%' 	0.00131701991356859
20046146	21062	return a count from a given month as column	select      page as path,     count(*) as total,     sum(case when month(date)=1 then 1 else 0 end) as jan,     sum(case when month(date)=2 then 1 else 0 end) as feb,     ....     sum(case when month(date)=12 then 1 else 0 end) as dec     from hitstable     where year(date)=2013 group by page; 	0
20047082	34081	get random friends from mysql	select * from  (  select * from users join on friend_list.userid = users.id where users.id = ? ) as sub_equity order by rand() limit 2 	0.000270562404657415
20048054	13146	left join tag table	select i.*, group_concat(t.name) taglist from items as i left join tag_rel as tr on (tr.item = j.id) left join tags as t on (t.id = tr.tag) group by i.id  order by i.id desc 	0.517180286963962
20048608	7960	sql select and or	select date from footballclubs.tableofgames a      join footballclubs.tableofgames b on a.date=b.date where a.team='liverpool' and b.team='swindon'; 	0.460565702415856
20048802	23870	have a loop of queries or use mysql (in)?	select * from tbl where  id between 0 and 10 	0.366569129408798
20049557	10760	limiting number of left join group	select i.*, substring_index(group_concat(t.name separator ','), ',', 5) taglist from items as i left join tag_rel as tr on (tr.item = j.id) left join tags as t on (t.id = tr.tag) group by i.id  order by i.id desc 	0.211391157568821
20049997	26550	mysql select max(datetime) not returning max value	select d.id, d.computer, d.app, d.version, d.build, a.installed from data d inner join (   select computer, app, max(date) as installed   from data   group by computer, app   ) a on a.computer = d.computer and a.app = d.app where placement = 'xxx' 	0.138466507502386
20050406	7173	query totaling multiple columns and grouping by another	select location,        sum(isnull(species1, 0)) as species1,        sum(isnull(species2, 0)) as species2,        sum(isnull(species3, 0)) as species3 from record group by location 	0.00296298833140533
20052042	36086	mysql query string date issue	select * from members where curdate() = date_add(renewal_date, interval $month month)   or (     curdate() = date_add(reminder_date, interval 1 month)     and blocker = 0     ); 	0.703582654632714
20053209	20682	how to deal with each rows and combined several rows into one row in oracle/sql	select date_, name,        sum(case when subject = 'math' then t1.mark * t2.weight end) as math,        sum(case when subject = 'history' then t1.mark * t2.weight end) as history,        sum(case when subject = 'cs' then t1.mark * t2.weight end) as cs,        sum(case when subject = 'science' then t1.mark * t2.weight end) as science from t1 join      t2      on t1.subjecct = t2.subject group by date_, name; 	0
20053297	24530	using max() to get the latest rows in a table, joined on another table	select  v.id,          e.environment,          v.date from (  select max(v2.id) as id         from vhistory v2           inner join instance i2             on v2.instance = i2.id           inner join environment e2             on i2.environment = e2.idenv         where v2.component = 100         group by e2.environment       ) as maxid         join vhistory v         join instance i         join environment e           on (  maxid.id = v.id             and v.instance = i.id             and i.environemnt = e.idenv            ) 	0
20055644	7182	mysql - counter within group	select g, x, counter from (     select g, x,         @counter := if (g = @prev_g, @counter + 1, 1) counter,         @prev_g := g     from tb, (select @counter := 0, @prev_g := null) init     order by g, x ) s 	0.378365543803981
20055852	31295	sql not properly filtering on certain criteria	select * from ext  where `approved` = 0 and `account-type`= 2  and (`ext-name` like :search or description like :search) 	0.168330933172732
20056918	20356	how can i return top 4 results by user using postgres sql	select     * from (     select         user_id,         survey_id,         row_number() over (partition by user_id order by survey_id desc) rn     from         all_survey_res     ) x where     x.rn <= 4 	0.00888159216103399
20057525	22383	how to select columns from 1 specific table from a query that joins across several tables	select d.*  from device d, policy p where d.deviceid = p.deviceid and p.name = 'hello' 	0
20063125	32648	mysql is in() as a result	select t1.*, (t2.pid is not null) exists_in_table2   from (   select *     from table1    order by pid    limit 100 ) t1 left join table2 t2     on t1.pid = t2.pid 	0.287982980706704
20063154	14690	mysql how to select value front of decimal	select id, floor(desc) from table1 	0.00376558990997784
20063735	35461	parent child and relationship in oracle	select t1.child_par,t2.child_par from test t1     ,test t2     ,test_rel tr where tr.childkkey=t1.child_par_key and   tr.parent_key=t2.child_par_key 	0.0105993975229363
20064484	40180	query to pivot in sql	select test,  col + ' '+ student stu_col ,  value into #temp from marks  unpivot(value for col in (english, maths)) unpiv declare @cols as nvarchar(max), @query  as nvarchar(max) select @cols = stuff((select distinct ',' + quotename(stu_col)              from #temp order by 1     for xml path(''), type     ).value('.', 'nvarchar(max)')  ,1,1,'') set @query = 'select test, ' + @cols + ' from       (         select test, value, stu_col         from #temp     ) x     pivot      (         sum(value)         for stu_col in (' + @cols + ')     ) p ' exec(@query) drop table #temp 	0.736470856894358
20064942	33211	query to find unique records in a historical table	select device_id from your_table group by device_id having count(*) = 1 	8.83127209972517e-05
20065105	30563	selecting from two tables joined by a reference table?	select *  from teams_members tm, members m, teams t  where tm.members_id = m.member_id  and m.member_id = 1 and tm.teams_id = t.team_id 	0
20065668	27859	querying sql database in php - datediff?	select owner_level.description as 'location', v_rpt_opportunity_salesdash.sales_rep1 as 'member',  (select sum(v_quota.gm) from v_quota where v_quota.forecast_year = ? and  v_quota.forecast_month between ? and ? and v_quota.member_recid = v_rpt_opportunity_salesdash.memberrec) as 'quota', sum(case when v_rpt_opportunity_salesdash.sales_stage = 11 then (isnull(so_forecast_dtl.revenue,0) -  isnull(so_forecast_dtl.cost,0) +  (isnull(so_forecast_dtl.recurring_revenue*(nbr_cycles/12),0)) -  isnull(so_forecast_dtl.recurring_cost,0)) else 0 end) as 'invoiced', datediff(day,recurring_date_end ,recurring_date_start)as datedifference 	0.368167368826868
20066101	24482	how to join value from another table by same condition value	select m.id, p.post_name, m.meta_value from posts p inner join post_meta m on p.id = m.post_id inner join  (    select post_id, min(id) as minid    from post_meta    group by post_id ) m2 on m.post_id = m2.post_id and m.id = m2.minid 	0
20067598	23287	get multiple attributes from one left attribute in sql	select        case when username=lag(username) over (order by username)       then null       else username end username,      useremail,       boardname from       yourtable; 	0.000174660129854651
20068362	10288	order by id based on id inside in	select * from mall  where mall_id in (3331083,33310110,3331080,33310107,33310119,3331410)    and mall_status='1'  order by    field(mail_id, 3331083,33310110,3331080,33310107,33310119,3331410)  limit 50 	0.000336326681162025
20068381	28632	sql query for duplicate records?	select group_concat(`user_id` separator ',') as user_ids,         message,        lattitude,         longitude,         status,         img_name        from table_name     group by img_name, message; 	0.0142822831095274
20069193	26492	oracle count how much values in varchar	select length(verdunning) - length(replace(verdunning, ',', '')) + 1 from (select '-1,-2,-4,-6' as verdunning from dual) t 	0.0667740188341633
20069415	21170	fetch data by percent from sql server	select t.* from categories join ( select tdata.*,          ntile(100) over             (partition by tdata.categoryid order by tdata.id) as grp from tdata ) as t       on (t.categoryid=categories.id)           and          (t.grp<=categories.percentofrecords) order by t.categoryid,t.id 	0.00104809141164016
20071722	20229	order by only one dataset of a union in a tsql union of datasets	select id       , name   from (select 1 as ordercol       , a.id       , a.name    from tablea  union  select 2 as ordercol       , b.id       , b.name    from tableb) i order by ordercol, name 	0.000303966653081182
20072605	34648	looking to remove the subquery	select a1.`active_id`  from active_table a1            left join view a2 on (a1.`active_id` = a2.active_id) where a2.active_id is null   and datediff(now(),a1.active_date)>30 	0.319935427970502
20073988	6634	identical tables in sql, find rows in one that aren't in the other	select distinct a.storeid,a.cashierid,a.registerid,a.timein,a.timeout,a.cashierprofile       from timecard a left outer join timecardssl b          on b.storeid = a.storeid         and b.cashierid = a.cashierid         and b.registerid = a.registerid             and b.timein = a.timein         and b.timeout = a.timeout         and b.cashierprofile = a.cashierprofile      where b.storeid is null; 	0
20074330	35170	mysql - pulling list pending on dates	select distinct posterid from table1 where postingdate between '2012-05-01' and '2012-06-30' and posterid not in (select posterid   from table1   where postingdate > '2012-07-01'); 	0.000766556260227405
20074421	41322	get rows with same id and must have certain values combined	select b.b_id, a.a_id from tablea a inner join tableb b on a.a_attribute = b.b_attribute group by a.a_id, b.b_id having count(*) = 3 	0
20075279	27617	sql, same column different rows to same row different columns	select 'serialno' as serialno      , [1], [2], [3], [4], [5] from ( select row_number() over (partition by serialno order by part + ' - ' + location) as rn         , serialno        , (part + ' - ' + location) as pl     from ttt ) as sourcetable   pivot (      max(pl)      for rn in ([1], [2], [3], [4], [5])     )  as pivottable 	0
20077332	7359	mysql - pulling list depending on date and category	select distinct posterid from table1 x where postingdate between '2012-05-01' and '2012-06-30' and posterid not in (select posterid   from table1 y   where postingdate > '2012-07-01' and x.categoryid = y.categoryid); 	0
20079831	27135	calculate sum() but excluding join	select   s.submit.date,   ,sum(s.point)   ,count(s.sales_id) as totalsales   ,sum(sl.saleslines) as totallines from  sales s inner join  (select   sales_id   ,count(distinct id) as saleslines  from    sales_lines  group by   sales_id) sl on s.sales_id = sl.sales_id3 group by  s.submit_date 	0.0146769501631178
20079908	24077	arrange multiple rows into one row	select 'east/flw' as location,    round(sum(case when t2.locid = '2815' then t2.value else 0 end), 2) as reading,   round(sum(case when t2.locid = '2620' then t2.value else 0  end), 2) as flw,   round(sum(case when t2.locid = '2618' then t2.value else 0  end), 2) as prs,  round( sum(case when t2.locid = '2595' then t2.value else 0  end), 2) as lvl from table2 t2 inner join table1 t1   on t1.id = t2.locid where t2.t_stamp = (select max(t2.t_stamp)                      from table2 t2                      where t1.id = t2.locid) group by 'east/flw' 	0
20081074	39306	mysql selecting across multiple tables + using mathematical operators average/count	select dept_name,sum(emp_nbr_of_dependents),avg(emp_nbr_of_dependents),count(emp_nbr)  from deptartment join employee on dept_nbr=emp_dept group by dept_name having count(emp_nbr)<50 	0.381887460546533
20082183	19670	left joining table to itself with where	select u.fname fname, u.lname lname, r.fname inviter_f, r.lname inviter_l from guests u left join guests r on u.inviter_id = r.guest_id where u.wedding_id = 10 	0.353732203206505
20083666	19782	check for invalid triggers	select id, name      , replace(sql, 'create trigger', 'alter trigger')         + char(13) + char(10) + 'go'  as sql  from (                              select id,name , sql = stuff( (select ' ' + cast(text as varchar(max))                                 from sys.syscomments c                                  where c.id =s.id                                  order by  colid                                 for xml path(''), type                                 ).value('.', 'nvarchar(max)')                             , 1, 1, '') from sys.sysobjects as s where xtype = 'p' ) x 	0.595089180237214
20085934	13048	oracle sql inner join first record in right table	select t1.symbol, t3.high, t3.low, t3.timestamp  from table1 t1 join (       select inn.*        from (select t2.*, (row_number() over(partition by symbol order by timestamp desc)) as rank              from table2 t2) inn        where inn.rank=1      ) t3      on t1.symbol = t3.symbol; 	0.139363171307101
20087065	31960	sql join - one column serving as id for two columns in another table	select w.gameid,        h.teamname as 'home team',        a.teamname as 'away team'  from week12 as w       left join teams as h                 on w.homeid=h.teamid       left join teams as a                 on w.awayid=a.teamid 	0
20087399	35122	remove a subquery and want a single query	select a1.`active_id`   from active_table a1 left join `view` a2 using(active_id) where a2.`active_id` is null   and datediff(now(), active_date) > 9 	0.104184017374729
20087551	1838	an sql query with a where greater than a count, when another field is already in group by	select airport, market, state from (   select airports.name as airport         ,markets.name as market         ,states.abbr as state         ,count(distinct airports.state) over (partition by airports.market)          as states_per_market   from   airports   join   markets   on     airports.market = markets.id   join   states   on     airports.state = states.fips ) where states_per_market > 1; 	0.00305323760979274
20089272	37805	searching the relevent rows and adding rows based on time stamp	select gname,        sum(`count`),        `timestamp` from ( select       case when name like '1f%in' then 'first'           when name like '2f%in' then 'second'           when name like 'gf%in' then 'ground'           else 'unknown'      end as gname,       `count`,      `timestamp` from t   where name like '%in' ) t1  group by gname,`timestamp`  order by `timestamp`,gname 	0
20089826	1809	php/mysql - limit to last 500 then continue	select ... from tweets where ... limit 1 500 select ... from tweets where ... limit 501 500 select ... from tweets where ... limit 1001 500 	0.000728021309733589
20089833	33411	how can i check whether the column data is present in other table in mysql?	select j.*,         case when o.resultid is not null              then 'yes'              else 'no'        end as present from jobs j inner join results r on r.jobid = j.jobid left outer join orders o on o.resultid = r.resultid 	0
20090822	6967	oracle sql: count number of rows with specific value	select   id, count(id) from table where age = 25 group by id having count(id) > 1 	6.14716108904423e-05
20093115	27763	find maximum average in sql	select avg(salary) from employee group by name order by avg(salary) desc limit 1 	0.000250167167991688
20093410	35382	sum and difference of two sql query result	select a.id_of, a.col, a.bnt,         sum(a.size1) - sum(b.size1) as size1,      sum(a.size2) - sum(b.size2) as size2,     sum(a.size3) - sum(b.size3) as size3,     sum(a.size4) - sum(b.size4) as size4,     sum(a.size5) - sum(b.size5) as size5,     sum(a.size6) - sum(b.size6) as size6,     sum(a.size7) - sum(b.size7) as size7,     sum(a.size8) - sum(b.size8) as size8,     sum(a.size9) - sum(b.size9) as size9,     sum(a.size10) - sum(b.size10) as size10,     sum(a.total) - sum(b.total) as total,     a.ref     from tbltailleofall a      join  tbltailleall b       on a.id_of = b.id_of      and a.col = b.col      and a.bnt = b.bnt group by a.id_of, a.col, a.bnt, a.ref 	0.00381612054228964
20093503	7500	possible with mysql replace()?	select concat(replace(substring(email, 1, locate('@', email)-1), '.', '') , substring(email, locate('@', email), length(email))) 	0.722935842686601
20094084	16086	mysql older than 6 months in linked tables	select customer,        max(datefinished) from orders group by customer having sum(datefinished > curdate() - interval 180 day) = 0 	0.000229823399580461
20095150	40759	find the rating that given to a certian game by each member who rated it in sql	select rating, name  from ratings, members  where gameid = 2 and ratings.memberid = members.id; 	0
20096316	31301	how to fill null field from another table in oracle?	select e.op_id ,      nvl(e.op_name, o.emp_name) op_name ,      e.emp_id  from   employee e ,      other_employee_table o where  e.emp_id = o.emp_id and    ... 	8.67904074942539e-05
20096524	29823	get query from mysql database group by day	select date(view_time) as `day`, count(*) as `views`, sum(view_cost) as `cost` from `your_table` group by date(view_time) 	0.000243871604640851
20096683	15975	how to get record of today's inserted data in sql server in c# windows form application	select date_time from raw_s001t01 where  date_time >= convert(datetime, datediff(day, 0, getdate())) order by date_time desc 	0.000201082532951147
20097233	26418	how to perform operations on dates in queries?	select dateadd('day',100, "date") from "history"; 	0.403375673225008
20097859	5102	select from something, select case then compare	select users.status, users.id_user, status1.status1 from users as users ,(select case          when users_actions.timestamp >= "2013-11-20 15:30:36"              then 2         when users_actions.timestamp >= "2013-11-20 15:30:51"              then 1         else 0         end as status1         from users_actions as users_actions         order by users_actions.timestamp desc         limit 1) as status1 where users.id_user in (5,22)  and users.status != users.status1 	0.0172863776818575
20100207	6062	mysql join table only to find missing values from previous join	select if(q26.question is not null, q26.question, q8.question) as question, if(q26.response is not null, q26.response, q8.response) as response from table1 t1 left join table2 as q26 on  (t1.id_user = q26.iduser and q26.idquestion = 26) left join table2 as q8 on (t1.id_user = q8.iduser and q8.idquestion = 8); 	0
20100919	31545	average & count together	select name, avg(callattemps) from hotwire.calldatabase where completedcall is null group by name order by name 	0.0121289221496437
20103379	25062	sql first row only following aggregation rules	select t.* from table as t inner join (     select * from     (         select c1.*, row_number() over(partition by c1.id order by t.importance_order) as rn         from company as c1         inner join address as a         on c1.id = a.company         inner join address_type as t         on t.id = a.address_type_id     ) a      where rn = 1 ) as b on b.id= t.company_id 	0.00276893068539641
20104057	22258	join three tables with counts	select s.s_id,        p.p_id,         count(d.did_something) as count_d_did_something,         sum(case when d.did_something = 1 then 1 else 0 end) as count_d_did_something_is_one from   soknad as s         left join prognose as p on p.p_s_id = s.s_id        left join did as d on d.d_s_id = s.s_id 	0.126017534432966
20104151	11321	sqlite monthly averages	select  strftime('%y', fecha), strftime('%m', fecha), avg(s10_avg), min(s10_avg), max(s10_avg) from @winddata group by strftime('%y', fecha), strftime('%m', fecha) 	0.0101388928114178
20105216	21233	sql query optimisation: comparing adjacent rows	select t1.* from table t1 inner join table t2 on t1.key = t2.key - 1 where t1.foo = 1 and t2.bar = 0 	0.377993680493019
20106405	13606	to use having in sql, join and count	select count(distinct salesid) numberofsalespeople from studios 	0.772946470995374
20107543	18834	how can i sum columns using conditions?	select p.policy_num, sum(i.net_insurance) net_insurance   from policies p join insurances i      on p.id = i.policy_id    and p.date_ini >= i.initial_date    and p.date_expired <= i.final_date  group by i.policy_id, p.policy_num union all select p.policy_num, i.net_insurance   from (   select max(i.id) id     from policies p join insurances i        on p.id = i.policy_id      and (p.date_ini < i.initial_date       or  p.date_expired > i.final_date)    group by i.policy_id ) q join insurances i      on q.id = i.id join policies p     on i.policy_id = p.id 	0.0355961594811488
20107827	28544	insert data into temp table with query	select * into #temp from   (select      received,      total,      answer,      (case when application like '%stuff%' then 'morestuff' end) as application    from      firsttable    where      recieved = 1 and      application = 'morestuff'    group by      case when application like '%stuff%' then 'morestuff' end) data where   application like     isnull(       '%morestuff%',       '%') 	0.0237671162605914
20107873	28545	join where row may not exist in one table	select students.id,students.name,courses.teacher from students left join (select * from courses where courses.period = '1') courses on students.id = courses.student_id 	0.0420490867421557
20109464	25005	sql max of count 2 tables	select * from owners where ownerid in    (    select ownerid     from properties    group by ownerid    having count(*) =        (select count(*)        from properties        group by ownerid        order by count(*) desc        limit 1)   ) 	0.00332261200833668
20110310	11664	how to return count from table as 0 if row does not exist?	select   fruit.name, count(baskets.fruit) from     fruit left join baskets on baskets.fruit = fruit.id where    baskets.basket = 'x' group by fruit.id 	0.00151246448868464
20111202	6484	sql server 2012 - two table query	select a.groupname, a.memberaddress, d.groupname, d.memberaddress from [groupsmembers1] a full outer join [groupsmember2] d     on a.groupname = d.groupname         and a.membername = d.membername where a.groupname like '%somegroupname%' 	0.375766543816183
20111397	27439	duplicate records in a sql join	select s.[biddernumber] as 'bid #',     ltrim(rtrim(b.biddername)) as 'name',     isnull(sum(s.saleprice * quantity),0) as 'spent',      (select isnull(sum(t.amount),0) from transactions t           where t.salescounter = s.salecounter) as 'paid', b.cconfile, t.notes  into #temp1 from sales s inner join bidders b on s.biddernumber = b.biddernumber group by s.biddernumber, b.biddername, b.cconfile order by s.biddernumber, b.biddername, b.cconfile 	0.0121648083004165
20115301	28491	need help on query to select data from union of two tables in orcacle	select  m.user_id,         m.org_role_id,         m.last_update_date,        ro.role_id    from si_user_org_roles m,        si_org_roles ro  where m.org_role_id = ro.org_role_id    and ro.role_id = 100074 union  select  au.user_id_o,   au.org_role_id_o,   au.last_update_date_o,   ru.role_id from si_user_org_roles_au au,si_org_roles ru where au.transaction_type = 'delete' and au.org_role_id_o = ru.org_role_id and not exists(select 'x'                   from si_user_org_roles m,                       si_org_roles ro                 where m.org_role_id = ro.org_role_id                   and ro.org_role_id = ru.org_role_id                    and ro.role_id = 100074) 	0.023714100384882
20115881	10624	how to get stored procedure parameters details?	select      'parameter_name' = name,      'type'   = type_name(user_type_id),      'length'   = max_length,      'prec'   = case when type_name(system_type_id) = 'uniqueidentifier'                then precision                 else odbcprec(system_type_id, max_length, precision) end,      'scale'   = odbcscale(system_type_id, scale),      'param_order'  = parameter_id,      'collation'   = convert(sysname,                     case when system_type_id in (35, 99, 167, 175, 231, 239)                      then serverproperty('collation') end)     from sys.parameters where object_id = object_id('myschema.myprocedure') 	0.177778662849322
20117666	428	sql export for select result	select email from   users where  userid in (select userid                   from   users,                          profiles                   where  users.id = profiles.user_id                          and profiles.country_id = 1) 	0.123821883328332
20117698	20033	sql multiple conditions together not true	select * from table1 where not exists (select * from table1  where  ((field1 = 0 and field2 > 0) or (field3 is null and field4 > 0))) 	0.480983354773589
20119410	26972	remove duplicate results in autocomplete	select distinct name from table_name where name<>'' 	0.133961959300832
20119901	941	counting number of joined rows in left join	select m.messageid, sum((case when mp.messageid is not null then 1 else 0 end)) from message m left join messagepart mp on mp.messageid = m.messageid group by m.messageid; 	0.00109678553946082
20119968	41313	sql - select statement where not exists a condition for each id ?	select activityid  from   dbo.activity as x where  not exists (          select activityid          from   dbo.activity          where  dateend ='9999-12-31'          and    activityid = x.activityid        ) 	0.0311689111198286
20121323	15648	how can i add a character into a specified position into string in sql server?	select substring(code,0,len(code)-1)+'.'+substring(code,len(code)-1,len(code)) from table1; 	0.000948623257774171
20124410	15300	oracle; two dates, difference in minutes	select round (  (  sysdate                  - to_date (to_char (sys_extract_utc (systimestamp),                                      'yyyy-mon-dd hh24:mi:ss'                                     ),                             'yyyy-mon-dd hh24:mi:ss'                            )                 )               * 1440,               0              )   from dual 	0.000405819094807139
20125570	36155	show data from same table in different column but in same row in mssql	select emp.id, emp.firstname, emp.lastname, min(case i when 1 then ski.skill_description end) as skillone     , min(case i when 1 then ski.experience        end) as skilloneexp  , min(case i when 2 then ski.skill_description end) as skilltwo     , min(case i when 2 then ski.experience        end) as skilltwoexp  , min(case i when 3 then ski.skill_description end) as skillthree   , min(case i when 3 then ski.experience        end) as skillthreeexp from employee as emp cross apply (   select top 3   row_number() over(order by experience desc) i,   cast(skill_description as varchar(50) ) as skill_description,   cast(experience        as varchar(50) ) as experience from employeeskill t1 inner join skills t2 on (t1.skill_id = t2.skill_id) and t1.id=emp.id order by experience desc ) as ski group by emp.id, emp.firstname, emp.lastname 	0
20126010	1571	sql select field using a part of other field in another table	select * from tablea join tableb on id=substring(field1,1,instr(field1,'-')-1) 	0
20128963	38110	selecting from single dataset on multiple columns for a result with combined columns but multiple rows	select  certificationid, empid, last_updated, case when x.question = 'q1_status' then 1     when x.question = 'q2_status' then 2     when x.question = 'q3_status' then 3     when x.question = 'q4_status' then 4 end [question], answer from ( select     certificationid, empid, last_updated, question,     answer from     (select *    from certification_table) t unpivot    (answer for question in        (q1_status, q2_status, q3_status, q4_status) )as unpvt ) as x 	0
20129105	14328	two count and a group by	select a.month, a.courses, b.absences from (select date_format(c.date, "%m") as month,              count(*) as courses       from course c       group by month) a left join (select date_format(c.date, "%m") as month,                    count(*) as absences             from absence a             left join course c             on a.course_id = c.id             group by month) b on a.month = b.month; 	0.0241795748344292
20129520	4406	sql filter by count of records	select s.name,s.admin  from states s inner join ( select ss.admin from states ss group by ss.admin having count(*) < 100 ) a on a.admin = s.admin order by s.admin asc; 	0.00544879612865975
20130224	7254	select single row from database table with one field different and all other being same	select min(a) a,b,c,d,e,f,g,h from mytable group by b,c,d,e,f,g,h 	0
20130495	28616	sql derby return middle of table	select t.* from mytab t inner join (select min(col1) as val2             from mytab             where col1 not in (select min(col1) from mytab)) x on t.col1 > x.val2 	0.0302181206854394
20131075	30882	oracle sql count with date requirement	select drno,        name,        contact,        (select count(*)           from patient          where patient.drno = doctor.drno            and months_between(sysdate,patient.datevisit) <= 6) as patientseen   from doctor 	0.500826849322898
20132720	29976	php/mysql: get one row and the next five rows	select *  from uploads  where upload_id >= $upload_id order by upload_id asc limit 6 	0
20133340	35606	mysql date between query not working	select count(*) from app where lastupdate between 1992 and 1981 	0.742557113507275
20133469	33348	oracle table top left not null value	select colfkey, coalesce( col1, col2, col3, col4 ) as value from   table_name where  rownum = 1 and    coalesce( col1, col2, col3, col4 ) is not null; 	0.117162718187128
20133786	2670	ms access sql - fetch data from 3 tables	select tblorders.fldordrid, tblcustomers.fldcustname,      tblproducts.fldprodname, tblorders.fldordrdate from (tblorders inner join tblcustomers on tblorders.fldcustid = tblcustomers.fldcustid) inner join tblproducts on fldprodid = tblorders.fldprodid 	0.00473838737323606
20133981	38948	how can you return multiple counts with varying where definitions?	select  id,  count(*) login_count0,  sum(case when logintime >= time1 then 1 end) login_count1,  sum(case when logintime >= time2 then 1 end) login_count2,  sum(case when logintime >= time3 then 1 end) login_count3 from usertable group by id 	0.0486969462308522
20134741	37920	how to return all data with duplicate columns using table aliases	select alias1.id `alias1.id`,         alias1.city `alias1.city`,         alias1.state `alias1.state`,         alias2.id `alias2.id`,        alias2.city `alias2.city`,         alias2.baseball_team `alias2.baseball_team`   from table1 as alias1  left join table2 as alias2      on alias1.id = alias2.id 	0.000127703164531249
20136863	19102	mysql using subqueries instead of join	select *   from artists a  where exists (   select *     from xrefartistsmembers x    where artistid = a.artistid      and exists   (     select *        from members       where memberid = x.memberid        and gender = 'female'   ) ) 	0.678100056153193
20137821	3923	using select statement with count	select count(distinct cheatcodes.gameid) as cheatcodecount from cheatcodes, games, gameversion,hardware, versionhardware where cheatcodes.gameid = games.id and   gameversion.gameid = games.id and   versionhardware.versionid = gameversion.id and   versionhardware.hardwareid = hardware.id  and   hardware.id = 5; 	0.552909651069137
20137902	29407	splitting of a string using query	select substr('imagelocation/r1.jpg',15,2) as image_location from dual 	0.0552981077612755
20138042	12477	sql server 2008 query to select correct record based on multiple rules	select * from  ( select *, row_number() over (partition by company_refno order by      case when isnull(isactive,'y') = 'y' then 1 when isactive !='n' then 2 end asc,            isnull(enddate,'31-dec-9999') desc, startdate asc)            as rank_no from mytable ) aa where rank_no = 1 	0.0115758717220275
20138202	4925	how to check if a column value contains integers	select * from table where column regexp '^\-?[1-9][0-9]*$' 	0.000279062043905507
20138847	25600	how to find rank using mysql or java(jdbc)	select rank,total from (     select @rank:=if(@prev=comp, @rank, @fullrank) as rank,             adm,             @prev:=comp,             comp as total,             @fullrank:=@fullrank+1     from my_table     cross join (select @rank:=0, @prev:='fred', @fullrank:=1) sub1     order by total desc ) result 	0.147463125982674
20139212	16304	union all query	select p.itemno, p.batchno, p.mrp, p.rate,         avg(s.npr) as npr,sum(s.stock) as total   from pricelist p   join stock s on s.itemno to p.itemno   group by p.itemno, p.batchno, p.mrp, p.rate 	0.12477249881966
20139348	9939	sql server: get newest (most current) date per group	select      categoryx,             max(categorydate) as latestdate from        yourtable group by    categoryx 	0
20139423	3489	positive value to negative and negative to positive in oracle	select a ,      -1 * a "changed value" from   test_tab; 	0.000189048437796191
20139549	25478	join on several conditions	select c.name      , coalesce(a.date, b.date)      , coalesce(a.amount, 0)       , coalesce(b.amount, 0)   from c   join (a full outer join b on b.fruitid = a.fruitid and b.date = a.date)     on coalesce(a.fruitid, b.fruitid) = c.fruitid   order by 1, 2 	0.206233156416355
20141283	25042	mysql query using count on multiple tables	select  r.rid,          fname,          lname from realtor as r inner join contract as c on r.rid=c.buyrid inner join property as p on r.rid=p.sellrid group by r.rid order by count(*) desc limit 1 	0.0896770885868794
20142165	21944	mysql sort by number with dots	select yourcolumn from yourtable order by cast(substring_index(yourcolumn,'.',1) as unsigned), cast(substring_index(substring_index(yourcolumn,'.',2),'.',-1) as unsigned), cast(substring_index(substring_index(yourcolumn,'.',3),'.',-1) as unsigned) ; 	0.040442190361167
20144027	3014	how to exclude records with certain values in sql	select col1,col2 from table where col1 not in (select col1 from table where col2 not in (1,20)) 	0
20146825	9486	select statement across 2 tables	select * from users u left join bids b on u.user_id = b.user_id where u.role='bidder' and  b.bid_id is null 	0.0264231939246626
20147823	15631	grouping by column that has most matches	select * ,count(business_id) as cbusiness_id  from contacts  group by business_id order by cbusiness_id desc 	0.000254212680078299
20149128	22814	get last distinct row?	select p.* from posts p inner join (   select threadid, max(datecreated) maxdate    from posts   group by threadid   having count(*) = 3 ) x on x.threadid = p.threadid and x.maxdate = p.datecreated 	0
20149463	2871	set 24 hours timeinterval in where clause of sql server	select * from your_table  where (datecol=cast (getdate() as date) and timecol<'17:00:00')  or (datecol=cast (getdate()-1 as date) and timecol>'17:00:00') 	0.00781668693559703
20150136	32169	count characters matching in concat mysql regexp	select *, concat( office, ' ', contactperson ) as bigdatafield from webcms_mod_references  having bigdatafield regexp "one|two" order by (bigdatafield regexp "one" + bigdatafield regexp "two") desc 	0.117563016069006
20151584	39129	select statement to exclude results through join table relationship	select * from fruit left join fruit_taste    on fruit_taste.fruit_id = fruit.id   and fruit_taste.taste_id = 1 where fruit_taste.id is null 	0.0333258002247092
20152214	5084	create temp table with conditional criteria	select * into temp1  from [statistikinlamningdataskl].[dbo].[skl_adminkontroll_result] e where         ( e.adminkontroll <> 'skl_admin_kn_annan_aid'     and e.adminkontroll <> 'skl_admin_kn_lararloner'     and e.adminkontroll <> 'skl_admin_kn_specialitet'     and e.adminkontroll <> 'skl_admin_kn_ldatum'     and e.adminkontroll <> 'skl_admin_kn_tillsvidare'     and  e.adminkontroll <> 'skl_admin_kn_timlon'         )     or ( e.värde < 90 and e.adminkontroll = 'skl_admin_kn_ldatum')     or ( e.värde < 50 and e.värde > 95 and e.adminkontroll ='skl_admin_kn_tillsvidare')     or (e.värde < 5 and e.värde > 25 and  e.adminkontroll = 'skl_admin_kn_timlon') 	0.224280818530479
20153232	7070	unable to retrieve results from a large table	select * from (     select myquery.*, rownum rnum     from (         select * from mytable order by id     ) myquery     where rownum <= 15 ) where rnum >= 2; 	0.00181246222276058
20154052	23292	any way to change a value on odd/even records in a sql select statement?	select case when @recordsetid % 2 = 0 then 'even' else 'odd' end 	0.00223203741692954
20154831	829	combine two mysql rows into one	select chart_date,group_concat(chart_field )as chart_field, replace(group_concat(chart_counts),'2},{','2,')as chart_counts  from table where chart_date='20131115' group by chart_date 	5.99904036862069e-05
20155721	6858	mysql get 4th, 5th, 6th, 7th result	select * from members limit 4,4; 	0.0484988130663499
20155781	34743	add column during mysql select	select  id, name,last_name, 1 as some_value from table 	0.00860761669383011
20156927	27924	mysql - using joins to get several informations	select a.article_id, a.title, u.user_id, a.article_text, from article a inner join user u on a.user_id = u.user_id left join tag_article ta on ta.article_id = a.article_id left join tag t on t.tag_id = ta.tag_id  where a.article_text like '%yourstring%'   or a.title like '%yourstring%'   or t.tag like '%yourstring%' group by a.article_id order by a.article_id desc 	0.195467598723357
20160661	31519	get a latest record in group by	select claimid ,interestsubsidyclaimid ,bankid,bankname ,updatedprincipalamountofoutstanding ,[date]  from interestsubsidyreviseclaim  where claimid=(                    select max(claimid)                    from interestsubsidyreviseclaim                     where isactive = 1 and interestsubsidyreviseclaim.interestsubsidyclaimid=1                     group by bankid               ) 	7.81832244422459e-05
20161271	1924	sql query for hourly average through out the month for the same hour	select substring(convert(varchar(100),longdate,114),1,2), avg(value1),avg(value2) from yourtable where month(longdate) = 11 and year(longdate) = 2013 group by substring(convert(varchar(100),longdate,114),1,2) 	0
20162095	10326	how to convert varchar column values into int?	select mystudy.toysid  from concepts       join (select study.toysid from study where isnumeric(study.toysid)= 1) as mystudy            on convert(int, mystudy.toysid) = concepts.toysid 	0.000753003177200848
20162575	18877	sql where clause to match against both conditions simultaneously	select   * from  mytable m1 where not  (m1.user = '1' and m1.status = '1') 	0.325092413305981
20164095	4022	count unique rows mysql (stuck with count that returns non distinct values)	select count(distinct user_id) from connections 	0.000461915047101175
20164431	29930	mysql getting reverse order limited by 6	select * from `table` order by `id` desc limit 6 	0.0476658250443174
20165426	27651	query to get count of rows with and without a value - 1query	select sum(case when value = 1 then 1 else 0 end) ones , sum(case when value = 0 then 1 else 0 end) zeros 	0.000148255463730152
20166204	28095	dynamic filter table error subquery returned more than 1 value	select brandname from item where displayprice =1  and (@test is null or yearman in (select item from split(@test,',')) 	0.313635161206241
20166240	9361	rename table data field in mysql	select  chart_date   ,           replace(chart_field,                  'user_jrfeed_item_count,user_jrforum_item_count,',                 'song_file_stream_count') as chart_field,         chart_counts  from table1 	0.00247194347821604
20168006	10962	mysql - generate rows based on results only when needed	select final.tempval1, final.tempval2, final.tempval3 from (   select temptable1.tempval4 as tempval1, temptable5.word2 as tempval2, temptable6.word3 as tempval3   from (     select temptable2.word1 as tempval4, temptable2.word2 as tempval5, temptable2.word3 as tempval6     from view_name temptable2     left join view_name temptable3 on temptable2.word1 = temptable3.word1     left join view_name temptable4 on temptable3.word2 = temptable4.word2 order by rand() limit 50 offset 3   ) temptable1       left join view_name temptable5 on temptable1.tempval4 = temptable5.word1   left join view_name temptable6 on temptable5.word2 = temptable6.word2   limit 0, 50 ) final order by rand() limit 50 	0.000749817472366255
20169683	25078	mysql return different values based on entry existence	select p.name, ifnull(d.score, 0) as score from persons p left outer join dt d on p.name = d.name 	0
20170440	34457	qmf turning sequence number results into their own columns without pivot	select        a.adr_code,        a.adrs_line as adrline1,       a2.adrs_line as adrline2,       a3.adrs_line as adrline3,       coalesce( a4.adrs_line, "" ) as adrline4,       coalesce( a5.adrs_line, "" ) as adrline5    from        addresstable a          join addresstable a2             on a.adr_code = a2.adr_code             and a2.seq_no = 2          join addresstable a3             on a.adr_code = a3.adr_code             and a3.seq_no = 3          left join addresstable a4             on a.adr_code = a4.adr_code             and a4.seq_no = 4          left join addresstable a5             on a.adr_code = a5.adr_code             and a5.seq_no = 5    where           a.adr_code like 'a%'       and a.seq_no = 1    order by       a.adr_code 	0
20171712	1611	combining two tables in a query	select config.date, config.name, 'configure' as type from tbl_configure config union select install.date, install.name, 'install' as type from tbl_install install 	0.0196888699252198
20172741	26821	filling one table column with if else statement in sql	select p.name,     case when x.productid is null then 'no' else 'yes' end as intopten from production.product p left join (      select top 10 productid from sales.salesorderdetail      group by productid       order by count(*) desc ) x on x.productid = p.productid 	0.0255553835168309
20172783	593	optional access column value selection	select  a,         b,         c,         switch         (   a is not null, a,             b is not null, b,             c is not null, c         ) as final from    t; 	0.277420529675927
20172900	932	my sql distinct and count if	select adid, sum(new = 1) new   from message   where (mesfrom = 1 or mesto = 1)     and (mesfrom = 2 or mesto = 2)   group by adid 	0.291181174097889
20172997	30454	sql count votes in one table include name from another table	select votedfor, count(*) as winners, p.name from vote inner join personnames as p on vote.votedfor = p.id group by votedfor, p.name order by count(*) desc; 	0
20174075	16230	link two tables using third one with two entries of second table that relate to one entry in first table	select a.g3e_fid,          max (case when b.g3e_cid = 1 then c.bottom_height end),          max (case when b.g3e_cid = 2 then c.bottom_height end)     from s_pipe_n a          inner join s_many_pcp_n b             on a.g3e_fid = b.g3e_ownerfid          left outer join s_pconpt_n c             on b.g3e_fid = c.g3e_fid group by a.g3e_fid; 	0
20175042	408	database sql counting query issues	select account_type, branchid, count(*) from accounts group by account_type, branchdid; 	0.729736370899452
20175410	621	count substrings in text	select (length(column)-length(replace(column,'test','')))/4 as count  from table 	0.0975687723386069
20175588	15170	posgresql group by a, but still pull b field	select    rpt_date,   sum(case when shipping_id = 1 then total_usage else 0 end) as a,   sum(case when shipping_id = 2 then total_usage else 0 end) as b,   sum(case when shipping_id = 3 then total_usage else 0 end) as c,   sum(case when shipping_id = 4 then total_usage else 0 end) as d from tablea where date(rpt_date) between '2013-11-01' and '2013-11-03'  group by rpt_date  order by rpt_date 	0.0102491379437355
20177577	37750	sqlite joining tables with no direct relation	select p.*, pt.deadline  from project_table p  inner join project_task pt     on pt.project_id_foreign = p._id inner join project_participants_table pp     on pp.project_id_foreign = p._id and pp.user_id_foreign = ?  union select p.*, pt.deadline  from project_table p  inner join project_task pt     on pt.project_id_foreign = p._id inner join group_project gp    on gp.project_id_foreign = p._id inner join groups g    on gp.group_id = g._id inner join group_participants gps    on gps.group_id_foreign = g._id where gps.user_id_foreign = ? 	0.0461423346134459
20179375	22747	mysql trim dynamically	select substring_index(column, '|', 4) from table; 	0.417178656792014
20180264	34051	mysql join data from tables on similar datetimes	select *      from `account`     inner join `values` on         date_format(`account`.`created_at`, '%y-%m-%d %h:%i') = date_format(`values`.`created_at`, '%y-%m-%d %h:%i'); 	0.00188213382707349
20180671	5212	firebird, group by foreign key field	select p.name, p.surname, a.people_index, count(a.index) as cnt from activity a inner join people p on a.index = p.index group by p.name, p.surname, a.people_index 	0.00248655987625712
20183736	29530	select from a result	select tracks.track_title,track_rank.track_id , count(track_rank.track_id) as number_of_repetitions from tracks,track_rank         where tracks.track_id=track_rank.track_id        where track_rank.track_position = 1         and track_rank.track_date_entered between '1970-01-01' and '1972-12-31' and      tracks.track_id = track_rank.track_id      group by track_rank.track_id      having count(track_rank.track_id) =     (        select      count(track_rank.track_id) as number_of_repetitions      from tracks,track_rank      where tracks.track_id=track_rank.track_id     where track_rank.track_position = 1      and track_rank.track_date_entered between '1970-01-01' and '1972-12-31'      and tracks.track_id = track_rank.track_id      group by track_rank.track_id      order by number_of_repetitions  desc     limit 1     ); 	0.0165484932152665
20183892	6707	calculate percentage for an area of study	select subject_id, area_of_study_id, total_students, percentage   from (   select p.subject_id, p.area_of_study_id, p.total_students,          p.total_students / t.total_students * 100 percentage     from   (     select count(*) total_students, ss.subject_id, s.area_of_study_id       from students s join student_subjects ss         on s.id = ss.student_id      group by ss.subject_id, s.area_of_study_id   ) p join    (     select ss.subject_id, count(*) total_students       from students s join student_subjects ss         on s.id = ss.student_id      group by ss.subject_id   ) t on p.subject_id = t.subject_id    order by percentage desc ) q   group by subject_id; 	0.00308055856724225
20183900	217	sql query to make a list from multiple tables	select i.code,        i.description,        it.description,        sc.description,        um.description from items as i inner join itemtype as it     on i.item_type_id = it.id inner join subcategory as sc     on i.subcateg_id = sc.id inner join uom as um     on i.uom_id = um.id 	0.00912217273200679
20186520	21514	need sql query for accessing different serial numbers present in a table	select min(id) from tablename group by substring(id, 1, 1) 	0.000261971580621246
20188042	25463	(my)sql join - get teams with exactly specified members	select * from team t join team_user tu on (tu.id_team = t.id) group by t.id having (sum(tu.id_user in (1,5)) = 2) and (sum(tu.id_user not in (1,5)) = 0) 	0.0232248565737062
20188363	2867	getting sql query values	select location from tablename where latitude between 8.1 and 8.5 and longitude between 80.4 and 81.5 	0.0915181868421367
20189881	18335	union all 2 tables but diferents columns	select id, name, surname, phone, '' as other from tablea where status = 0  union all  select id, name, surname,'' as phone,othercolumn from tableb where status = 0 	0.000635325268028777
20190089	38038	selecting rows with max value in range	select a.id,a.site_id,b.maxdate,a.views from table1 a inner join (     select  site_id ,max(datetime) as maxdate     from table1     where datetime < dateyouwanttosee + interval 1 day     group by site_id ) b on a.site_id = b.site_id and a.datetime = b.maxdate 	0
20190285	11006	rtrim in oracle	select substr(ename,1,1))||'->'||ename from emp order by ename; 	0.790921946623617
20193775	28050	fails to update user table after inserting values from a get form	select point from questions where dif between 1 and 22; 	0
20194806	25201	how to get a list column names and datatype of a table in postgresql?	select         a.attname as "column",         pg_catalog.format_type(a.atttypid, a.atttypmod) as "datatype"     from         pg_catalog.pg_attribute a     where         a.attnum > 0         and not a.attisdropped         and a.attrelid = (             select c.oid             from pg_catalog.pg_class c                 left join pg_catalog.pg_namespace n on n.oid = c.relnamespace             where c.relname ~ '^(hello world)$'                 and pg_catalog.pg_table_is_visible(c.oid)         ); 	0
20195789	7234	how to select a bit based on value in another tables column in sql	select [user].id,case when  rule.id = 8 then 1 when  rule.id = 5 then 0 else 0 end  as bit from [dbo].[user] user inner join [dbo].[rule] rule on [rule].id = 8 where [user].userid = @userid and [user].shopid = @shopid 	0
20196059	6219	optimizing a union all order by when selected tables are already sorted	select t.cdt as cdt, t.cid as cid, t.c3 as c3, t.ctab as ctab from ( select top 1000000000 * from (  select cdt as cdt, cid as cid, c3 as c3, 'tab1' as ctab from table1  union all  select cdt as cdt, cid as cid, c3 as c3, 'tab2' as ctab from table2  union all  select cdt as cdt, cid as cid, c3 as c3, 'tab3' as ctab from table3 ) x order by cdt,cid  ) where t.cid in (select id from tableids) order by t.cdt 	0.000461941670588768
20196293	14592	most efficient way of selecting closest point	select id as aid,x,y,m % 100 as bid from ( select a.id,a.x,a.y,min(cast(((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)) as bigint)*100+b.id)     as m  from a cross join b group by a.id,a.x,a.y) j; 	0.00237325583256482
20197580	24802	sql how to select data in this specific situation	select i.item_id, il.price, i.quantity from items i, items_list il where i.player_id=$player_id and i.item_id = il.item_id group by i.item_id 	0.534070905858224
20198763	10045	comparing row based on contents to another tables rows in access sql	select tblanswers.userid, iif([tblanswers].[bacon]>0 and [tblmenus].[bacon]<>0,[menuid],null) as baconmenu, iif([tblanswers].[ham]>0 and [tblmenus].[ham]<>0,[menuid],null) as hammenu, iif([tblanswers].[sausage]>0 and [tblmenus].[sausage]<>0,[menuid],null) as sausagemenu from tblanswers, tblmenus where (((iif([tblanswers].[bacon]>0 and [tblmenus].[bacon]<>0,[menuid],null)) is not null)) or (((iif([tblanswers].[ham]>0 and [tblmenus].[ham]<>0,[menuid],null)) is not null)) or (((iif([tblanswers].[sausage]>0 and [tblmenus].[sausage]<>0,[menuid],null)) is not null)); 	0
20199081	7420	aggregating data to getting running total	select    [monthid],    [month],    ( select sum([paid]) from tbl t2 where t2.[monthid] <= t1.[monthid] ) as paid from tbl t1 	0.00379453282775922
20199318	40100	insert into columns from specific rows and merge rows in mysql	select company      , max(case when meta_key = 'email' then meta_value end) email       , max(case when meta_key = 'street' then meta_value end) street      , max(case when meta_key = 'tel' then meta_value end) tel       , max(case when meta_key = 'website' then meta_value end) website   from eav   group      by company; 	0
20199735	15231	mysql sort by zip code and then random in each zip code	select * from listings, listings_categories  where listings.id = listings_categories.listing_id and category_id  in (1,3,5,8,7,4,5,2)  and business_zip in (89101,89102,89103,89104,89105,89106)  and status = '1' group by listings.id order by business_zip, rand() 	0.000691310544536694
20200159	22295	co-occurrence graph from 8 million rows of data	select node1.user_id, node2.user_id, count(item_id) from yourtable as node1 join yourtable as node2 on     (node1.user_id <> node2.user_id) and (node1.item_id = node2.item_id) group by node1.user_id, node2.user_id 	0.00259347342482156
20200651	24696	huge sql query on 4 tables and multiple conditions	select products_categories.* where products_categories.category_id not in  ( select distinct category_id from products_categories_relations ) or products_categories.category_id not in ( select distinct products_categories.category_id  from products_categories inner join products_categories_relations pcr on prc.category_id = products_categories.category_id inner join master_products master on master.product_id = pcr.product_id inner join slave_products slav on slav.master_product_id = master.product_id where master.published = 0 or (master.product_stock = 0 and slav.product_logistics = 0) ) 	0.243033751728963
20200654	8729	sql select two nearly fields	select *  from wp_weather where city = 'махачкала' order by abs(timestamp - 1385435000)  limit 2 	0.0198277644288721
20200793	11842	concatenating various field values for the same id	select id, group_concat(state separator '|') from regions group by id 	0
20200847	30641	need help building one mysql query comparing a variable with two tables	select m.project_id, m.meeting_id, ma.* from meeting m inner join meeting_agenda ma on ma.meeting_id  = m.meeting_id  where m.project_id = $project_id 	0.550912128797384
20200861	36683	rank project numbers in view, mysql	select 1+count(b.total_hours) rank, a.pno, a.total_hours from test a left join test b   on a.total_hours < b.total_hours group by a.pno, a.total_hours order by total_hours desc; 	0.065353166055335
20201727	33634	mysql select only x rows from the same categ	select ip, class  from (     select ip, class,           @num := if(@grp = class, @num + 1, 1) as row_number,           @grp := class     from mytable, (select @num := 0, @grp := '') temp_vars     order by class) x where row_number <= 2 	0
20202206	24465	get orders where order lines meet certain requirements	select o.* from tblorders o where exists (     select 1     from tblorderlines ol     where ol.productcategory = 10     and ol.orderid = o.orderid ) 	0
20202302	25819	use avg & count together	select salesman, avg(case when salesman in ('richard', 'jose', 'mendez') and supcheck is not null and ordered is        not null then price1+price2+price3+price4+price5 else null end) from pixiestick.dbo.salesinfo group by salesman order by salesman asc 	0.577588210641663
20202459	27999	how to match one and/or more than one 0s in sql?	select id from table where regexp_like(zeroes, '^0+$') 	0.00295991765273173
20202785	10196	ordering a group by in sql	select       userid,       max(time) from      useractions group by       userid 	0.392462155488196
20203124	34427	sql: i want to select all columns from table1 where columna in table1 is equal to columnb in table2	select t1.* from table1 as t1 inner join table2 as t2 on t1.material = t2.material 	0
20204350	13726	sql data: html table display of column data containing multiple rows	select t1.uuid, t1.value as name, t2.value as size from sldb_data t1, sldb_data t2 where t1.uuid = t2.uuid and t1.field = "name" and t2.field = "size" 	0
20205159	5862	sql select output to xml	select case_num = case                  when child.rec_type = '1' then mast.case_num                 when child.rec_type = '2' then mast.case_num                else '' end      ,mast_date = case                  when child.rec_type = '1' then mast.date                 when child.rec_type = '2' then mast.date               else '' end   ,child.rec_type   ,part_name = case when child.rec_type = '1' then child.col_a else '' end   ,part_price = case when child.rec_type = '1' then child.col_b else '' end   ,subject_name = case when child.rec_type = '2' then child.col_a else '' end   ,subject_type = case when child.rec_type = '2' then child.col_b else '' end from table_master mast join table_child child on mast.case_num = child.case_num 	0.287251685805065
20205672	12161	sql return 1 row	select sum(rank_1 = "$wp_player['id']") * 5 `1st`,        sum(rank_2 = "$wp_player['id']") * 4 `2nd`,        sum(rank_3 = "$wp_player['id']") * 3 `3rd`,        sum(rank_4 = "$wp_player['id']") * 2 `4th`,        sum(rank_5 = "$wp_player['id']") * 1 `5th`  from fcs_player_rankings 	0.0110602234755364
20206606	11739	mysql printing first n line of result	select customerid, sum(amount) as total from orders  group by customerid order by total desc limit 10; 	0.000280786338395538
20207723	39736	mysql: get results from two tables, count matches in a third	select table1.*, table2.*, t3.count from table1, table2 left join (select our_id, count(*) as count from table3 group by our_id) t3 on table1.our_id = t3.our_id where table1.our_id = table2.our_id 	0
20207860	36340	mysql substring get only characters	select documentnumber from transactionheader where  documentnumber  like 'rcv%' 	0.00753563174908726
20208839	26208	how to add thousands separator for all rows in a column in sql server	select format(amount, 2) from detail; 	0.000781026977565066
20209350	9881	mysql - select row by comparing two columns	select max(datetime) as time limit 1 .... group by (sender_userid and receiver_userid) order by datetime 	0.000214040023192293
20212408	10052	mysql get all id using parentid and id	select    a.id  from    users as a      left join users as b        on a.typeid=b.typeid  where    b.id = 5 	0
20212776	24121	sql query with calculation from subquery	select i.invoiceno as 'invoice number',        i.invoiceamount as 'invoice amount',       (i.invoiceamount - coalesce(p.totalpayed,0)) as remainingtopay from invoice i left join (   select invoiceid,          sum(paymentamount) as totalpayed   from payments   where paymentmethod in (1, 2, 3)   group by invoiceid   ) p   on p.invoiceid = i.invoiceid where i.invoicestatus = 2 	0.695222812223938
20213394	8785	sql grouping 2 set of data into 1 set using the same key	select starting_date, sum(qty) from (   select working_date,          item_no,          qty,          (select max(master_table.starting_date)           from master_table           where master_table.starting_date <= details_table.working_date           and master_table.item_no = details_table.item_no          ) as starting_date from details_table   ) as modfied_table group by starting_date order by starting_date; 	0
20214112	19401	find overall rank of a mysql record and determine if tied	select x.*      , count(*) rank   from ( select  player_id, 'gp' stat, gp score from stats union select  player_id, 'goals', goals from stats union select  player_id, 'assists', assists from stats union select  player_id, 'points', points from stats union select  player_id, 'penalties', penalties from stats union select  player_id, 'shots', shots from stats ) x join ( select  player_id, 'gp' stat, gp score from stats union select  player_id, 'goals', goals from stats union select  player_id, 'assists', assists from stats union select  player_id, 'points', points from stats union select  player_id, 'penalties', penalties from stats union select  player_id, 'shots', shots from stats ) y on y.stat = x.stat and y.score >= x.score group by stat,score,player_id order by stat,rank; 	0.000198556014397311
20214848	16207	cross product of columns	select * from (     select distinct name     from test ) x cross join  (     select distinct age     from test ) y cross join (     select distinct spent     from test ) z cross join (     select distinct gender     from test ) a; 	0.0228835319114631
20215079	13426	composite in clause with null value	select  `col1`, `col2` from  `table1` where  (`col1`, `col2`) in ((1, "row1"), (2, "row2"))  or  (`col1` in (2,4) and col2 is null) 	0.590516555900596
20215396	25073	manage id's inserted an in input box seperated by commas	select find_in_set('b','a,b,c,d')  	0.000639491877830815
20217462	21154	get data between hours in php	select fields from table where timefield between date_sub('$date', interval $tohour hour) and '$date' 	0.000178121766045074
20217708	5190	retrieving multiple max() values from different tables	select t1.t1max, t2.t2max  from      (select max(id) t1max from table1) t1,      (select max(price) t2max from table2) t2 	0
20217770	36984	join multiple detail tables with different design to master table	select  m.id,         m.value,         d.id detailid,         d.value detailvalue,         d.date from table_master m left join ( select *             from table_detail1             union all             select *             from table_detail2) d     on m.id = d.master_id 	0.000897552571360968
20217910	3016	mysql get next zero-filled auto incremented value	select lpad(`auto_increment`,8,'0') from  information_schema.tables where table_schema = 'testingdb' and   table_name   = 'table1'; 	0
20221295	15119	how to use max function on oracle sql based on below data?	select tbl.name, tbl.id, tbl.code, tbl.date from tbl   join (       select name, id, code, max(date) as max_date       from tbl       group by name, id, code) tbl_max     on tbl.name=tbl_max.namne       and tbl.id=tbl_max.id       and tbl.code=tbl_max.code       and tbl.date=tbl_max.max_date 	0.0326809280952976
20222990	3364	group by similar string	select case           when right(nombre, 1) between '0' and '9' then           left(nombre, length(nombre) - 2)           else nombre         end as nombrechecked,         group_concat(id_grupo)  from   grupos  group  by 1 	0.146782400040118
20224558	32948	how to count when there are multiple where statements	select c.customer_name, x.no_of_orders, y.total_price from customer c left join (     select customer_id, count(customer_id) as no_of_orders from orders      group by customer_id) x on c.customer_id = x.customer_id left join (     select o.customer_id, sum(p.price) as total_price from order o      inner join products p on o.productid = p.productid     group by customer_id) y on c.customer_id = y.customer_id 	0.205284704574448
20225089	4212	mysql pull data from same table, sum multiple columns with conditions	select call_logs.number   ,sum(if(allowed_numbers.number is not null,call_logs.price,0)) as allowedprice   ,sum(if(allowed_numbers.number is null,call_logs.price,0)) as notallowedprice from call_logs left join allowed_numbers   on call_logs.destination = allowed_numbers.number group by call_logs.number; 	0
20225627	20755	how to get the values with highest number of records with same value in mysql	select category from deal group by category  order by count(*) desc  limit 2 	0
20226532	38021	fill in missing dates for multiple values with a group by	select   u.user_id,   c.calendar_date,   coalesce(sum(e.entry_hours), 0) from calendar c cross join users u left join entry e    on (c.calendar_date = e.entry_date and u.user_id = e.user_id) group by u.user_id,c.calendar_date 	0.00150307851011714
20227113	41252	overriding data based on sub query	select r.datetime, if(d.startdatetime is null, r.rate, 50) rate from rates r left join downtime d on r.datetime between d.startdatetime and d.enddatetime 	0.0278684280009556
20228025	12563	multiple of same result even with group by	select pc.product_code,        count(*) as count,        sum(o.monthly_base_charge) as "monthly fee" from orders o join      product_catalog pc      on pc.product_catalog_id = o.product_catalog_id group by pc.product_code order by count desc; 	0.00661863172590964
20228152	12339	sql select row count and id value of multiple rows with equal values	select id,     name,     partnumber,     param1,     param2,     param3,      stock,     active      from (         select *,              rank() (parition by id, param1, param2, param3 order by stock desc) as max_stock              from product)x         where max_stock = 1 	0
20229453	30093	joining multiple tables with one producing more results	select i.*, a.text, c.* from info i inner join articles a on info.article_id = articles.article_id left join comments c on c.article_id = a.article_id where a.artice_id = :article_id 	0.0692490192500153
20229502	33132	sql - using group by and count	select a.numrows, b.id, b.name from xe.emp b inner join (   select count(*) as numrows, dept_id   from xe.dept   group by dept_id   ) a on b.id = a.dept_id 	0.338484118878161
20229519	2158	ms access select into with fixed value for one field	select sourcenum, 'solid' as type into newtable  from sourcetable 	0.000611278363133909
20231338	34707	sql using group by or distinct to get back first records	select group, min(id) id from table group by group 	0.000443428423772974
20232641	2022	add a row number to result set of a sql query	select t.a, t.b, t.c, number = row_number() over (order by t.a)   from dbo.tablez as t   order by t.a; 	0.000150202287397948
20233114	15918	java, sql, id increment statement?	select count(*) as numusers from users where username = 'theusername'; 	0.116133071323519
20234432	3207	mysql rows with null values are not retriving in select query	select `c`.*  from `customers` as `c`  where `c`.`typeid`!=9     or `c`.`typeid` is null  order by c.name asc 	0.0241565407999062
20236615	20557	add 'zeros' in front of already existing number in my database	select right('0000000'+cast(wc_code as varchar(10),5) 	0.00036818980576661
20237105	8705	mysql inner join based on non empty columns	select t1.*, t2.* from table1 t1 inner join table2 t2 on              (case when                   t1.id != 0                   then t1.id =t2.id                  else                  case when t1.memberid !=0                        then t1.memberid = t2.memberid                       else                            t1.personid = t2.personid                   end             end) 	0.00478698475009876
20237437	4776	select all date that is lesser than today	select *  from sensplit_commercial_goal where commercialgoalid = 'dbe20d71-e304-4989-8524-5feef61d32a7' and (dailybudgetexceeded < getdate() or dailybudgetexceeded is null) 	0.00016339439184707
20238942	14329	sql - group by distinct	select p_no      , b_name   from uhura.dbo.test  where p_no in (select p_no                   from uhura.dbo.test                  group by                        p_no                 having count(distinct b_name) > 1)  group by        p_no      , b_name 	0.228832571000367
20240195	1103	how can i use multiple where clauses in a single mysql select statement?	select names, subjects,  sum(   case    when name_of_exam = 'first weekly test' then (score/full_marks)*20    when name_of_exam = 'first unit exam' then (score/full_marks)*30    when name_of_exam = 'final unit exam' then (score/full_marks)*50    end) as scored from marksheet group by names, subjects 	0.482837271348752
20240974	33061	filter data with query	select   * from     datatable where    refid in (select  distinct refid                     from    datatable                    where   date2 > '20140101') 	0.295760187637971
20241395	9188	mysql - join the 1 table or the other table depending if there is a match	select a.s_id, coalesce(b.s_name, c.s_name) s_name, a.s_date, ... 	5.0668246466252e-05
20241442	36071	sorting by max value	select t1.* from your_table t1 inner join (   select customer_id, max(sequence) mseq   from your_table   group by customer_id ) t2 on t1.customer_id = t2.customer_id and t1.sequence = t2.mseq 	0.0286621033608414
20243338	25885	how to retrieve rows from table based on column value(0,1)	select col1, max(col2) as col2 from your_table group by col1 having count(distinct col2) = 1 	0
20244649	28965	changing int to time from a datediff	select       fastestsegmenttime = min(cast(tbltrace.trfinish - tbltrace.trstart as time(2)))     , slowestsegmenttime = max(cast(tbltrace.trfinish - tbltrace.trstart as time(2)))     , avgsegmenttime = dateadd(ms, 1000 * avg(datediff(second, tbltrace.trstart , tbltrace.trfinish)),0) from      tbltrace     inner join tblusers on usrid = tr_usrid where      (tbltrace.trfinish is not null)     and (tbltrace.trobjecttype like 'segment%')      and (tbltrace.tr_vnuid = @vnuid)      and (tbltrace.trstart between @startdate and @enddate)     and (tblusers.usremail not like '%@test%') 	0.00986267534382631
20244866	11467	mysql query gives null value when one of the where conditions results in false	select b.projname as project_name,         count(a.empid) as project_strength  from projects b  left join users a on  a.empprojid = b.projid where b.projname like '%windows%' group by b.projname 	0.0313579499265845
20245885	5115	select additional columns for a select min() statement	select * from ( select id,   convert(datetime,right (substring(nameanddate,14,8),4)                              + substring(nameanddate,14,4)) d, substring(nameanddate,1,12) n, count(*) over (partition by substring(nameanddate,1,12)) cnt, row_number() over (partition by substring(nameanddate,1,12)                     order by substring(nameanddate,14,8)) rn from mydata ) v where cnt > 1 and rn = 1; 	0.0361571726689635
20247079	35730	select most recent record based on date	select top 1 * from table order by [date] desc 	0
20247487	13390	mysql count rows in a subquery	select  accountgroup,  count(storename) as totalamountofstores,  sum(     if(joineddate > date_sub(now(), interval 2 month), 1, 0)  ) as '2months' from accounts  where accountgroup <>''  and othercode ='site'  group by accountgroup 	0.0661211425772802
20247748	37774	combine 3 mysql queries to make 1 query	select distinct p.id from photos p join photo_tags pt on pt.cat_id = p.id join tags t on pt.key_id = t.id where (p.title like '%black%' or t.tag like '%black%') and p.status = 'a' 	0.148685962138686
20248650	10136	select in calendar with concat and between	select * from calendar  where str_to_date(concat(year,'-',month,'-',day),'%y-%m-%d')            between '2013-1-30' and '2013-1-31'; 	0.198110273939968
20250805	17962	tsql point of execution	select a.col1, a.col2, b.col1, b.col2, c.col1     from [table a] a     inner join [table c] c         on c.key1= a.key1     inner join [table b] b         on b.key1 = a.key1     inner join [table d] d         on  b.key3 = d.key1     where c.key2 = 'static value'          and b.key2 = 'static value'         and right(b.key4,1) in ('static value 1', 'static value 2')         and substring(b.key4, 1, len(b.key4)-1) = c.key1    group by a.col1, a.col2, b.col1, b.col2, c.col1 	0.691279459298651
20251573	13996	check if the given time is between two times (hour,minute) format	select 1 from table where    maketime(time_right_now_hour,time_right_now_minute,0)     between maketime(time_working_from_hour,time_working_from_minute,0)     and maketime(time_working_to_hour,time_working_to_minute,0); 	0
20251948	7868	mysql list of number between a range	select distinct tablea.id from   tablea inner join ranges   on tablea.id between ranges.id_lower and ranges.id_upper 	0
20253644	21797	sql server select percent from table and all data from another table	select count(*) children  from     (select top('" + int.parse(percentcb2.text) + "') percent       f.family_id ,      f.economic_state       from families      where f.economic_state = 'b') f inner join children c on c.family_id = f.family_id  group by fq.family_id 	0
20254026	10067	sqlite: how to write a query which would fill empty cells in resultset	select      f.fruit,      coalesce(x.lbs, 0),      t.time  from (                 ( select distinct fruit from your_table ) f      cross join ( select distinct time  from your_table ) t  )  left join your_table x      on  f.fruit = x.fruit      and t.time = x.time; 	0.0352578011353849
20255232	11259	combining tables while searching for one of the elements	select   a.id         ,a.title         ,a.content         ,(select        group_concat(b.name)                  from    blog_tags b                 join    blog_posttags c                 on      b.id = c.tag_id                 where   c.post_id = a.id          ) as tags from blog_posts a inner join blog_posttags c on c.post_id = a.id inner join blog_tags b on b.id = c.tag_id where b.name = "work" group by a.id 	0.000110052650636424
20256010	16580	sql query design help: finding duplicates in multiple tables & exclusions	select * from bankitem where exists(   select name, itemid, id1, id2, id3   from item   where bankitem.name = item.name   and bankitem.itemid = item.itemid   and bankitem.id1 = item.id1   and bankitem.id2 = item.id2   and bankitem.id3 = item.id3 ) and name not in('redpotion') and charid <> 0 	0.746224346079475
20257387	20092	link multiple table with math operation in sql	select sum(quantity * unitprice) as result from ([order details] inner join orders on [order details].orderid = orders.orderid) inner join customers on customers.customerid = orders.customerid where country = 'argentina' 	0.591349427779122
20260096	22754	how to count number of character after .(dot) in db2	select len(numfmt) - locate_in_string(numfmt, '.') 	0.00211832812753349
20261333	30215	how to select top 4 records of amount from 2 tables	select table2.docentry, custid, custname, docamount, itemid, itemname,  itemprice, qty, lineamount from (select top 3 * from table1 order by docamount desc) topdocs      join table2 on topdocs.docentry=table2.docentry order by docamount desc 	0
20261932	7842	how can i select two dates today /yesterday?	select * from  customer where cno in (select cno from oder where (orderdate=getdate() or orderdate = getdate()-1)) 	0.000369747348302434
20262689	25966	find the customer who with oders before 1/jan/2002 how can i wite a this query in sql?	select * from customer c inner join order o on c.cno=o.cno   where o.orderdate>'2002-01-01' 	0.0117676351898035
20263863	17362	sql sum of count field with different product name once	select product, sum(count) from table_name group by product 	0
20264554	8854	combine rows of results into one in postgres	select id,         sum(count1) as count1,        sum(count2) as count2 from your_table group by id 	5.18835076523243e-05
20267843	21161	limit by grouped field instead of all rows returned	select o.order, oi.article from (select order       from orders       order by order_date desc       limit 50) o join order_items oi on o.order = oi.order 	0
20268963	27659	mysql: join and sum from different tables	select (select sum(c1.amount) from c1 where c1.a = a.id) as c1_amount,         (select sum(c2.amount) from c2 where c2.a = a.id) as c2_amount  from a where a.id = 1; 	0.00360220861928663
20269291	37917	sql: cumulative summing and insertion into table	select     t.date,     t.visits,     t.purchases,     sum(r.visits) as cumvisits,     sum(r.purchases) as cumpurchases,     sum(r.purchases)*1.0/sum(r.visits) as ratio from t join t as r on r.date between substr(t.date, 1, 4) and t.date group by t.date 	0.00660543319501822
20270512	1208	combine results from different row	select t1.*, t2.calltimetoanswer calltimetoanswer2   from table1 t1 join table1 t2     on t1.callsequence = t2.callsequence    and t1.datetime > t2.datetime; 	0.000177841323346452
20270717	31489	sql - how do i use a selected id in another table?	select h.name from hero h inner join owner o on o.heroid = h.id where o.userid = $id 	0.000939015607023564
20271601	38679	mysql custom sort order order by field() issues	select *   from table1  order by field(id, 4,5,6) > 0 desc, id   limit 6 	0.700535431175501
20272329	13185	how to get total by count(*) and a quantity column	select sum(e.quantity) from storefront.elevation e where e.projectid = p.id 	0
20273872	27963	select smallest date after group by	select *  from levelsloaded ll inner join     (select id, min(mindate) as finalmindate      from levelsloaded      group by id ) ill on ll.id = ill.id and ll.mindate = ill.finalmindate order by date desc 	0.0103264330879057
20275113	21426	three table in one query?	select *  from      tb_kategori k,tb_product p,tb_images i where k.id_kategori = p.id_kategori   and p.id_product = i.id_product 	0.0176786877321992
20275190	26164	aggregation function to get the difference or ratio of two rows in order	select product,        sales_date,        current_price - prev_price as diff from (   select product,          sales_date,           price as current_price,          lag(price) over (partition by product order by sales_date) as prev_price,          row_number() over (partition by product order by sales_date desc) as rn   from the_unknown_table ) t where rn = 1; 	8.60671978249987e-05
20276102	32565	same sql statement giving different results	select top 5 * from mytable 	0.125949676968798
20276312	10834	sql sum only distinct value	select planttype, geographicalarea, sum(maxcapacity) as maxcapacity, sum(numberofplants) as numberofplants, count(unitid) as idcount    from tbl_plant   where plantid in (     select max(plantid)       from tbl_plant      where (agreementstart <= '2013-11-28' and agreementend >= '2013-11-28')        and planttype <> '0'        and planttype = '2'        and geographicalarea = '3'      group by unitid ) group by planttype, geographicalarea 	0.00259832257234655
20277029	7937	how to select certain rows with an sql statement depending on whats in another table	select jd2.* from journey_driver jd1 left join journey_details jd2 on jd1.j_id = jd2.j_id where jd1.driver_id = 23 	0
20277168	20617	how i get the preview product and next product in mysql?	select p1.id,        p1.products_name from p p1 inner join (select max(id)as id from p where id < 7  union all  select min(id)as id from p where id > 7 )t on t.id = p1.id order by p1.id asc 	0.000370533793275498
20277426	38422	adding two times from database	select lunch, break, addtime(lunch, break) from table_name; 	0.000891577831212243
20278789	27967	convert double to mysql date format	select from_unixtime(substring(runtime,1,10)) from students; 	0.108411649296351
20281085	2945	limit display of a different table field	select tblusers.firstname, tblstation.stationname, max(tbluserlogs.lastlog) from (tblusers left join tblstation on tblstation.stationno = tblusers.stationnumber)      left join tbluserlogs on tblusers.usernumber = tbluserlogs.userid where tblusers.membertype != 1 	0
20281812	24520	suitable clause to return value that is null and not null but others error	select a.batch_id,         a.effective_dt,         a.from_acct_no,         e.title_1,         b.iso_code as 'from_currency',         a.from_crncy,         a.to_crncy,         a.to_acct_no,         f.title_1,         c.iso_code as 'to_currency',         a.to_posted_amt,         a.status,         a.rej_reason,         d.short_text,         a.from_description,         a.from_amt,         a.batch_tran_id,         d.error_text  from   gb_batch_tfr_trans a inner join ad_gb_crncy b on a.from_crncy = b.crncy_id inner join ad_gb_crncy c on a.to_crncy = c.crncy_id  left outer join pc_ov_error d on  a.rej_reason = d.error_id left outer join dp_acct e on a.from_acct_no = e.acct_no left outer join ln_acct f on a.to_acct_no = f.acct_no where a.status in ( 'rejected' )         and a.batch_id = 61619 	0.702608955554256
20282081	40241	sql greatest n per group with extra criteria	select  maxt.person,         maxt.duration,         t.value,         min(t.uniq) as uniq from    t         inner join         (   select person, sum(`time`) as duration, max(value) as value             from    t             group by person         ) maxt             on maxt.person = t.person             and maxt.value = t.value group by maxt.person, maxt.duration, maxt.value; 	0.00104739923104371
20282305	12369	last day of month with h2	select dateadd(dd, -day(dateadd(m,1,@today)), dateadd(m,1,@today)) 	0
20284310	8044	get minimum value greater than zero	select id_function = @param,    min(t1.column1) as c1min,     max(t1.column2) as c2max,    min(nullif(t1.column3,0) as c3min from table1 (nolock) as t1 where t1.id = @param 	7.34103561937009e-05
20285286	11862	mysql grouping by two columns	select orderid, group_concat(invoiceid), count(distinct invoiceid) as freq  from orders  where financialtype='17'  group by orderid  having freq > 1 order by freq desc 	0.00585772095679688
20285321	40036	mysql - getting a count from the same table	select t.intproductid, t.strsku, t.strproductname, q.cnt from tproducts t left join (     select intoptionid, count(*)  cnt     from tproducts as tproductoptions      where tproductoptions.boldeleted = 0      group by intoptionid ) q on t.intproductid = q.intoptionid where t.boldeleted = 0    and t.intoptionid = 0 	0.000126774286170781
20286288	34296	a mysql query that will run checks from two tables and if true show in c# datagridview	select c.* from customers c inner join animals a    on c.specie=a.specie and c.country=a.country where c.donationpound > a.price 	0.000326091248765068
20286766	19799	mysql join with one to many relations	select * from claims c  inner join claim_status cs  on c.claim_id = cs.claim_id where cs.status='created'   and not exists (   select 1   from claim_status cs2   where cs2.claim_id = cs.claim_id         and cs2.status='submitted' ) 	0.146190076089341
20288700	23524	mysql subquery to count user results in another table is sloooooooow	select users.email, count(r.result_id) as results from users inner join users_groups on users_groups.user_id=users.id inner join programmes_results r on ((r.client_id=users.client_id) and (r.email=users.email)) where users.client_id='130' and users_groups.group_id in (5) group by users.email order by users.email asc limit 10 	0.0146851424031645
20289068	5479	mysql - unique email, with user that has most currency	select tab.email, tab.uname from(     select email, max(credits) as credits     from tab     group by  email ) x join tab on x.email = tab.email and tab.credits = x.credits 	0.000177412353011146
20292377	9107	counting views (relational database)	select `event_views`.`id`,count(`event_views`.`id`) c from `event_views` left join `member_city_access` city       on city.`member_id` = `event_views`.`member_id` left join `cities`       on cities.id = city.city_id where city.city_id = '92'     and city.`primary` = 'on'     and `event_views`.`view_date` >= '20131103'     and `event_views`.`view_date` < '20131110' group by `event_views`.`id` 	0.0962700136629299
20292886	14063	selecting two conditions simultaneously	select doctors.docnumbers, doctors.idnum from doctors inner join workdays as workdays1 on workdays1.docnum = doctors.docnumbers and workdays1.workday = 1 inner join workdays as workdays3 on workdays3.docnum = doctors.docnumbers and workdays3.workday = 3; 	0.00441133595756461
20293013	25884	subtracting 2 values from a query and sub-query using cross join in sql	select (b - a) ... 	0.0416053549319357
20293676	24468	how to query to show all boss names	select r.nazwa, b1.nazwa as bossname1, b2.nazwa as bossname2,   b3.nazwa as bossname3, b4.nazwa as bossname4, b5.nazwa as bossname5 from ((((raid as r   inner join boss as b1 on r.boss1 = b1.identyfikator)   inner join boss as b2 on r.boss2 = b2.identyfikator)   inner join boss as b3 on r.boss3 = b3.identyfikator)   inner join boss as b4 on r.boss4 = b4.identyfikator)   inner join boss as b5 on r.boss5 = b5.identyfikator 	0.000541988853246615
20295142	22845	how to find user with most rows in table - mysql?	select user_id, count(*)  from tablename group by user_id order by 2 desc limit 1; 	4.90154947648964e-05
20295192	17367	get data by percent for each value in table	select f.family_id, f.family_name, f.last_name from (select family_id, family_name, last_name,  row_number() over (partition by last_name order by last_name) rowno from families) f inner join ( select last_name, count(1) as famcount from families group by last_name) gr on f.last_name = gr.last_name and f.rowno <= gr.famcount / 2 	0
20299099	24639	how can filter the record with two time in mysql?	select * from your_table where time not between '14:00:00' and '21:00:00' 	0.000940378918002991
20299859	4287	why adding sum changes the number of retrieved rows?	select id, prodname, prodid, st_date, montant, tvaval, sum(quantite), status, factureno  from stockdata   where " + ventewhere + "   order by " + order_by + " " + sortdir + "  group by xxxxx 	0.00134754302974741
20299860	34828	how to show column value only one time if it is repeated and blank until different value comes in sql	select     case when row_number() over(partition by category order by budgettype) = 1      then category else null end as 'category caption'     , category     , budgettype from yourtable order by category, budgettype 	0
20300382	15586	sql - group by numbers according to their difference	select col1, col2, sum(group_gen) over (order by col2) as grp from (   select col1, col2,          case when col2 - lag(col2) over (order by col2) > 1 then 1 else 0 end as group_gen   from some_table ) 	0.000154329690382995
20300433	26593	sql - max value for item from different table per group	select id,parameter,value,actionfunc,actionvalue,chainto, chainoperator,groupid, max([order]) over(partition by groupid) as actionlevel from [site-obj-prices] as actions inner join [site-obj-pricesparams] as params  on actions.parameter = params.parameter where groupid not in (             select [groupid]             from [site-obj-prices] as act             inner join @parameterslist as par                 on act.parameter=par.skey and act.value<>par.svalue             union              select [groupid]             from [site-obj-prices] as act             left join @parameterslist as par                 on act.parameter=par.skey where par.skey is null     )     order by actionlevel asc 	0
20306534	29122	mysql in statement with column values from another table	select name from table2 where name in(select name from table1 where...) 	0.000412294245582197
20310662	8825	how can i write a query with 2 states?	select distinct saletype.id, saletype.code, saletype.name  from customer left join saletype_customer   on customerid = customer.id  ,saletype where (saletypeid = saletype.id or saletypeid is null) and customer.id= 4; 	0.43469176047156
20311367	30205	mysql column with duplicate values	select      left          (           'stack-overflow stack-overflow',           length('stack-overflow stack-overflow')/2         ) 	0.00477446063194129
20313396	27817	how can useed multi select from statement	select pricing  from maarj_license_management_serverprice  where status=1  and idserver in (select idserver from maarj_license_management_server                   where numberserver > @numberserver ) order by numberserver 	0.192181645736334
20314511	17499	retrieve name from sql - unexpected error "impossible to convert int to string"	select uname from projects where id in (select max(id) from projects) 	0.0806276284735803
20314711	33898	subtracting time down rows	select to_seconds(t2.started) - to_seconds(t1.started) as difference_in_seconds from `table data` as t1 join `table data` as t2   on t2.record_id = t1.record_id + 1 	0.00291119507438873
20318366	27498	mysql rank - row number where field is equal to x	select a.iterator, a.id, a.name, a.points from (         select @rank:=@rank+1 as iterator, id, name, points, auth     from table, (select @rank:=0) tmp     order by points desc) a where a.auth = 1 	0.000152117757052097
20318779	90	mysql selecting last duplicate record with primary key	select master.id, query.phoneno, master.flag, master.date from (select master.id, master.phonenumber, master.flag, master.date from master where master.id in (select max(id) from master group by phonenumber)) master right join query on master.phonenumber = query.phoneno 	0
20319135	16240	group by month and return 0 if data not found	select month(created_at) as month_num,  date_format(created_at, '%b') as month_name, ifnull(count(*),0) as total_num      from table where user_id=1384249399168     group by month(created_at) order by created_at desc 	0.00259587044995121
20319304	28976	arranging data according to their page number in reports	select code,dense_rank() over (order by [code]) page from tablename 	5.35206395845627e-05
20320681	34531	pull up login times in sql database	select player_name, count(distinct date(login_time)) from login_table group by player_name; 	0.0127718364612225
20321169	2062	how to get total amount of sales out of the 5 top-selling products?	select order_details.sku, sum(order_details.quantity * order_details.price) as total_revenue from order_details where order_details.sku in  (select x.sku from order_details as x   order by sum(x.quantity) desc   group by x.sku limit 5) group by order_details.sku; 	0
20322111	19873	how to retrieve single data in sql statement?	select phonemodel, status from network where phonemodel='cisco catalyst 3750g poe24' and status='available' limit 1 	0.00492556607787366
20326150	11192	how to select a minimal value from a joined table with jpa?	select p.country, h.history from personentity as p join p.historyentity h where h.id in (select min(h2.id) from historyentity h2 where h2.historyentity=p group by historyentity) 	0.000226655758449568
20326216	24119	i want to fetch database information as per table mentioned below	select coalesce(t6.main_part,coalesce(t5.main_part,coalesce(t4.main_part,coalesce(t3.main_part,coalesce(t2.main_part,coalesce(t1.main_part,'no result')))))) as result from table t1     left join table t2 on t1.main_part=t2.sub_part     left join table t3 on t2.main_part=t3.sub_part     left join table t4 on t3.main_part=t4.sub_part     left join table t5 on t4.main_part=t5.sub_part     left join table t6 on t5.main_part=t6.sub_part where t1.sub_part='d123' 	0.000310945897439619
20326580	5920	images not pulling through for correct product	select *,            v.vehicle_id as vehicle_id_alias       from vehicle_tbl as v      join manufacturer_tbl as m on v.manufacturer_id = m.manufacturer_id left join image_tbl as i on v.vehicle_id = i.vehicle_id      where v.vehicle_feature1 = '1'   group by v.vehicle_id   order by rand()      limit 6 	0.312074992310383
20327642	40798	get the hits of those days which have more hits than previous day	select t2.*, t1.hits as previous_day_hits from tab1 t1 inner join tab1 t2 on  t2.date = date_add(t1.date, interval 1 day)   and t2.hits > t1.hits; 	0
20328943	15727	how to select all table names where a 'user_id' column is?	select table_name from information_schema.columns where column_name = 'user_id' 	0.00015181405236131
20329306	20815	mysql count in subquery using group by	select fk_member as family, count(v.fk_member) visit_count from members m  inner join visits v on m.fk_family = v.fk_member  group by v.fk_member 	0.647891789897548
20330256	38028	table without id's in other table	select a.*     from users a     where a.id not in (select id from blacklist ) 	0.000101462705076437
20334835	24585	mysql identifying groups in group by new	select md5(concat(mo.model, p.datemodified)) as group_identifier, * from ... 	0.0200194273956889
20334845	24365	mysql check if multiple rows exist	select count(distinct key) = 2  from table1 where key in (0, 2) 	0.00597274962658569
20335914	1145	sql, getting sub query data into table	select u.*,  colors = stuff((           select ', ' + c.colorname           from usercolors as uc           inner join colors as c on uc.colorid = c.colorid           where u.userid = uc.userid           for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') from users as u 	0.0420208860370754
20336356	39781	ordering search results from mysql	select *    from items   where (name like '%$query%'      or keywords like '%$query%')     and status = '1'   order by (name like '%$query%') desc, name, keywords  limit $start, $per_page 	0.107191213188183
20336436	9014	sql sorting on fullname column	select * from  (     select 0 as userid, '-select user-' as usersname, convert(varchar(100),'') as surname      union all      select userid as userid, userfullname as usersname,      reverse(substring(reverse([userfullname]), 0, charindex(' ', reverse([userfullname])))) as surname      from vwselectuser  ) as a order by surname 	0.0752498941315658
20337105	4899	sql server : changing a temp column value	select b.isbn,  b.title,  b.imagepath,  b.summary,  b.amountavailable, case when ub.isbn is not null then 'false' else 'true' end as isvisible from book b left outer join userbook ub on ub.isbn = b.isbn 	0.0174400437571349
20338796	16337	sql statement to find min date	select min(entered), generalist, item from datatable where item = @itemparm and entered between @enteredstart and @enteredend group by generalist, item 	0.0318241252302533
20339399	5350	select columns that exist in in table1 and not in table2 where table1 and table2 differ in columns	select column1, column2 from table1 where table1.column1 not in (     select column1     from table2 ) 	0
20340072	40657	sql group by subselect	select distinct t1.title_id, t1.shared_task_id from mytable t1 join mytable t2 on t1.shared_task_id = t2.shared_task_id  and t1.title_id <> t2.title_id 	0.756575547436676
20340922	39992	mysql: collecting specific data from multiple tables displaying entire database	select customers.name as customer, park.name as park, trips.date as trip, comments from (customers join trips on (customers.customer = trips.customer) join parks on (parks.parknum = trips.park)) left join comments on (comments.id = trips.comment_id; 	0
20344839	18222	select rows as columns in sql server	select set_ratio,pass_ratio,min_right_count from (   select configname,value   from yourtable ) d pivot (   max(value)   for configname in (set_ratio,pass_ratio,min_right_count) ) piv; 	0.00736071090303188
20346565	29401	specify php code to select dates and records 3 days old	select *, date_format(lbs_date, '%y,%m,%d')  from lbs_trace_etrack  where lbs_date >= curdate() - interval 3 day  order by lbs_date desc 	7.21330808059666e-05
20346655	1974	query for selecting distinct names and count names in sql	select name,count(name) as no_of_attempts,max(marks)  from table_name  group by name 	0.000309533386318619
20349002	6110	combining a view and table	select      vinvoices.yymm as yymm,     vinvoices.location as job_location,     vinvoices.job_no as job_no,     format(sum(vinvoices.amount),0) as amount,     tjobtypes.type_name as job_type from vinvoices  join tjobs on tjobs.job_no = vinvoices.job_no join tjobtypes on tjobtypes.type_no = tjobs.type_no 	0.0563072079673
20349798	15115	check if there is no "true" value per "id"	select domain_link_id,  sum(if(is_active = 'true', 1, 0)) as false_count ,  count(is_active) as history_row_count from domain_link_history group by domain_link_id having false_count = history_row_count 	7.33088532976811e-05
20351306	34347	display the latest date and time	select last_data_update from $system.mdschema_cubes where cube_name = 'aaaaaa' 	0
20351319	20927	how to find max value and its associated field values of each type in sql?	select t1.* from your_table t1 inner join (   select class, max(mark) as maxmark   from your_table   group by class ) t2 on t1.class = t2.class and t1.mark = t2.maxmark 	0
20352407	14469	sql: access query unique meets multiple criterias	select distinct studentid from attendant where studentid not in (select distinct studentid from attendant where startdatum between #1/1/2010# and #12/31/2010#) 	0.163599162302593
20353379	31269	getting data from another table with joins	select c.*        ,cc.*        ,uc.*     from customers_companies cc     join customers c         on cc.customer_id = c.id     join users_companies uc         on cc.company_id = uc.id     where uc.id = cc.company_id 	0.00237964702587812
20354080	30634	get previous row's value on a mysql view	select t.date, t.val, coalesce((select val from table1 sq where sq.date < t.date order by sq.date desc limit 1), 0) + t.val as whatever from table1 t order by t.date 	0
20354983	20107	remove enums from list if they already exists in database	select distinct [typeenum] from [app].[dynamictext] 	8.95729624072928e-05
20356256	27503	sql import in table from temp table	select col1 = ( case         when ltrim(status) = '1' then 1     else 0   end)  from #fixtures 	0.00396942576597432
20356682	14507	sql query that sums and groups in a new column	select c.id, c.name,   sum(case when i.month = 201309 then     coalesce(i.amount, 0)   end) sepinvoices,   max(case when c.start < '2013-10-01 00:00:00' and c.end >= '2013-09-01 00:00:00' then     c.amount   end) sepcosts from costs c left join invoices i on c.id = i.costid group by c.id, c.name 	0.00246446390825566
20356800	4670	sum with multiple tables	select s.scheme,  c.surname,  p.policynumber,  cp.type,  sum(ce.totalreceived   )     from clients c, schemes s, policies p, commnpremiums cp, commnentries ce       where c.clientref = p.clientref and        s.schemeref = p.schemeref and        p.policyref = cp.policyref and        cp.commnpremref = ce.commnpremref and        s.schemeref = '164003232' and c.surname = 'smith' group by s.scheme,  c.surname,  p.policynumber,  cp.type 	0.0691451472278537
20357570	17919	why does "select count(*)" from nothing return 1	select 'test' 	0.667841779004428
20357984	2299	finding duplicates in a column using sql joins	select *  from students inner join           (select stu_dateofbirth            from students            group by stu_dateofbirth  having count(stu_dateofbirth           ) > 1) as dateofbirths on students.stu_dateofbirth = dateofbirths.stu_dateofbirth 	0.0868052590428229
20359088	1815	how do i determine what action triggered a trigger that handles multiple events	select eventdata().value('(/event_instance/eventtype)[1]','nvarchar(max)') 	0.0554731606185079
20360168	40081	distinct users, get last login info	select max(logintime), id, name from your_table group by id, name 	0
20360538	33542	how can i get the row-wise sum in this pivot query?	select *       ,isnull(count_0,0) + isnull(count_1,0) + isnull(count_2,0) + isnull(count_3,0) etc.. as count_include from        (select schoolyeardescription ,           case              when col = 'band_count' then 'count_'             when col = 'band_percent' then 'percent_'             end + cast(stackposition as varchar(1)) colname, value        from @r         unpivot         (          value          for col in ([band_count], [band_percent])         ) unpiv) src         pivot         (max(value)         for colname in (count_0,count_1,count_2,count_3,count_4,count_5,count_6,count_7,count_8,count_9,         percent_0,percent_1,percent_2,percent_3,percent_4,percent_5,percent_6,percent_7,percent_8,percent_9) ) piv 	0.623796353684299
20361100	23195	get all the columns and rows from this table where the a rwo repeats more than once	select *  from (     select *     , cnt = count(*) over (partition by tableid)     from mytable  ) x  where x.cnt > 1; 	0
20361648	5036	mysql 2 counts in query	select question,count(*),sum(rightanswer) from table group by question order by question 	0.0811360515441347
20361818	5248	count over different tables	select booker_id, count(reservation_status) from yourtable where reservation_status = 'canceled' group by booker_id having count(reservation_status) >= 3 	0.0127495106869603
20362867	10453	mysql query that multiplies 2 fields then adds all results	select sum(qty * unitvalue) total   from inventory   where datereceived between '2012-01-01' and '2013-01-01' 	0.0013543492821802
20363213	32358	sql two or more with same properties	select t.* from mytable t inner join (   select value   from mytable   where has_other = 0   group by value   having count(*) > 1   ) a on a.value = t.value where t.has_other = 0; 	0.0589551013735953
20363797	34373	need to calculate date difference of today date vs converted date field	select datediff(day, cast(column_name as datetime), getdate()) from dbo.table 	0
20363866	40490	pulling in data from mysql and breaking it up between pages	select * from menuitem limit $startpositionvariable,$howmanyitemsperpagevariable 	0.0027237231039212
20364763	31217	sql join and result filtering	select p1.productname, p2.productname from products p1 cross join products p2 where (p1.productname, p2.productname) not in ( select distinct p3.productname, p4.productname     from order_details od1     join products p3     on od1.productid = p3.productid     cross join order_details od2     on od1.orderid = od2.orderid     join products p4     on od2.productid = p4.productid ) 	0.510577359384932
20367895	14530	mysql. how to get result of "group by" with distinct rows each in its own column?	select t1.f0, t1.f1, t3.f2 as a, t2.f2 as b, t1.f2 as c from t1 t1  inner join t1 t2 on t1.f1 = t2.f1 and t1.f2 != t2.f2 inner join t1 t3 on t2.f1 = t3.f1 and t2.f2 != t3.f2  and t1.f2 != t3.f2 group by t1.f0, t1.f1; 	0
20368235	11806	sql insert column name as value into table	select year, monthno, value from     (select *    from table1) p unpivot    (value for monthno in        (jan, feb, mar) )as unpvt; 	0.000353606406229164
20368907	20804	insert a row in a table with calculations depending on previous rows	select active.acc_id,   active.acc_name,   'existing',   active.value - new.value into table1 from (select * from table1 where status = 'active') active   join (select * from table1 where status = 'new') new     on active.acc_id = new.acc_id 	0
20369077	40948	how to select records from table for a given date using sql server 2008	select distinct news.*  from news  where convert(varchar(max),news.date,101) = convert(varchar(max),@date,101)        and news.publish_status=1  order by news.news_id desc 	5.97550254121325e-05
20369631	18665	getting the lower value of the rating	select min(rating_stars), customer_name, productname  from rating r     inner join customer c        on c.custid = r.custid     inner join product p        on p.prodid=r.prodid group by customer_name, productname 	0.00224891538201909
20371130	12343	sum time values in related table	select e.name, ap.event_id, sum((time_to_sec(end_time) - time_to_sec(start_time))/60) as dif from events e left join appointment ap on e.id = ap.event_id group by e.name, ap.event_id order by 2; 	0.000638976955569996
20371404	3666	oracle regexp_replace: don't replace the first character, replace others	select regexp_replace(phone,'[\|\]','-')  from phone_tbl  where emplid = employee; 	0.00689569300934861
20371496	4673	selecting a distinct value based on 1 value	select table1.name, min(case when table2.allowed = 0 then 0 else 1 end) from table1 left join table2 on table1.id = table2.table1id group by table1.name 	0
20372463	36228	group and sum records in this mysql query	select reports.rep_dated,        count(*) as vis_count from visits join reports on visits.vis_report = reports.rep_id group by reports.rep_dated order by reports.rep_dated 	0.305006318281331
20372626	17471	mysql: sort result by two columns diffrence	select t.id, e.tripid, sum(e.quantity) as total_quantity, (t.limit - sum(e.quantity)) as balance from table_trip t left join table_entry e on t.id = e.tripid group by t.trip order by 3; 	0.0038320500151975
20373082	592	query to return unique values when one of column value is repeating	select nameguid, name, ancestorguid, productguid, pathlength from (     select      nameguid,      name,      ancestorguid,      productguid,      pathlength,      first_value(nameguid) over (partition by name order by pathlength asc, nameguid asc) minnameguid     from (          ... your original query ...     ) ) where  nameguid = minnameguid 	0
20373717	39296	php mysql retrieve min value from several columns	select *,least(onezw , twozw , threezw , fourzw , fivezw , sixzw) as min_value from tab1 	0
20376707	22624	selecting value corresponding with max value of a group	select seo.oxseourl, seo.oxobjectid, max(seo.oxparams) from oxseo as seo where seo.oxobjectid like 'tbproduct_%' and seo.oxparams regexp '^-?[0-9]+$' group by seo.oxseourl, seo.oxobjectid 	0
20377125	30630	group by last date mysql	select u.id, u.name, e.id, e.date, e.comment from user u left join (select t1.*   from visit t1     left join visit t2       on t1.id_user = t2.id_user and t1.date < t2.date   where t2.id_user is null   ) e on e.id_user=u.id 	0.00164786761432282
20377815	4266	dynamic column name and value into where clause	select top 1      temp_col1,     temp_col2,     temp_col3,     temp_col4,     temp_col5 from temp_table where (@use_a = 1 and @use_b = 1 and colname2 = '''' + @valuea + '''' and colname3 = '''' + @valueb + '''')  or (@use_a = 0 and @use_b = 1 and colname1 = '''' + @valuea + '''' and colname2 = '''' + @valueb + '''') 	0.0305498948660676
20377843	27253	how to change a value between two characters sql	select replace(body, substring(body, charindex(':', body) + 1, charindex('the page you can visite is', body) - (charindex(':', body) + 1)) ,' <br/> <br/> <br/> xxxx <br/><br/><br/><br/> ')  from @temp 	0.000734474197215326
20378139	5613	between months query in mysql	select * from products p left join seasons s on p.s_id = s.id where case  when month(s.startdate) > month(s.enddate)   and (month(curdate()) > month(s.startdate)        or month(curdate()) < month(s.enddate))   then 1 when month(s.startdate) <= month(s.enddate)   and month(curdate()) between month(s.startdate) and month(s.enddate)   then 1 else 0 end 	0.0256101970810067
20378444	34474	delete rows with identical columnname value in a sql table?	select min(id) as id into #tmptable from mydatatable group by columnname delete from mydatatable where id not in (select id from #tmptable) 	0.000356577643390559
20379532	15999	how to select the 3 most recent rows using the date field	select top 3 id, first_name, last_name, url, date from tbl_paystubs order by date desc 	0
20381533	41186	grouping data by weeks oracle	select to_date('07/18/2013', 'mm/dd/yyyy') + rownum cur_date,        trunc((to_date('07/18/2013', 'mm/dd/yyyy') + rownum) - 4, 'iw') + 4 as start_date,        trunc((to_date('07/18/2013', 'mm/dd/yyyy') + rownum) + 3, 'iw') + 3 as end_date   from dual connect by level <= 100; cur_date    start_date  end_date 19-jul-13   19-jul-13   25-jul-13 20-jul-13   19-jul-13   25-jul-13 21-jul-13   19-jul-13   25-jul-13 22-jul-13   19-jul-13   25-jul-13 23-jul-13   19-jul-13   25-jul-13 24-jul-13   19-jul-13   25-jul-13 25-jul-13   19-jul-13   25-jul-13 26-jul-13   26-jul-13   01-aug-13 27-jul-13   26-jul-13   01-aug-13 28-jul-13   26-jul-13   01-aug-13 29-jul-13   26-jul-13   01-aug-13 30-jul-13   26-jul-13   01-aug-13 31-jul-13   26-jul-13   01-aug-13 01-aug-13   26-jul-13   01-aug-13 	0.0254976849839515
20381805	17743	how to alter mysql query to temporarily change column name	select p.id as idphoto, title, l.id,  username  from phototable p  join usertable l on (l.id = p.iduser)  order by p.id desc limit 50 	0.0242475500950162
20382323	40822	parsing sql xml output into multiple columns	select dl.d_l_xml.extract('/row/department/name/text()').getstringval() "department name",  dl.d_l_xml.extract('/row/department/courses/course[1]/title/text()').getstringval() "course title"  from departments_list dl  union  select dl.d_l_xml.extract('/row/department/name/text()').getstringval() "department name",  dl.d_l_xml.extract('/row/department/courses/course[2]/title/text()').getstringval() "course title"  from departments_list dl  union  select dl.d_l_xml.extract('/row/department/name/text()').getstringval() "department name",  dl.d_l_xml.extract('/row/department/courses/course[3]/title/text()').getstringval() "course title"  from departments_list dl; 	0.0166735670332454
20382695	38579	ms-access multiple tables query	select 'enero' as month, cliente, venta from [venta ene 2013] union all select 'febrero' as month, cliente, venta from [venta feb 2013] union all select 'marzo' as month, cliente, venta from [venta marzo 2013] union all     etc.... select 'octubre' as month, cliente, venta from [venta oct 2013] 	0.464752882201887
20383848	26452	aggregation in tsql	select ct.id from links ct inner join tags t on ct.id_tag = t.id_tag where t.tag in ('github', 'octocats') group by ct.id having count(distinct t.tag) = 2; 	0.598283100370891
20384466	7044	mysql, show value of column if match exist else leave as null	select o.name, c.cartype, h.address, h.country from owner as o join car as c on o.id = c.ownerid left join house as h on o.id = h.ownerid and ucase(h.country) = "sweden" 	0.000876235757846357
20385245	22472	sql query where null results get placed first	select (case when columna is null then 0 else 1 end) as sort_order, *  from tablea  order by sort_order, columna, columnb; 	0.0053360963112717
20385854	23630	how can i group children and parents in a single query?	select * from   transactions order  by coalesce(parent_id, id), id 	0.0046803951873881
20386186	34984	select all foreign key constraint defs for relations of a specific parent table	select c.relname as relation, c2.relname as parent, pg_get_constraintdef(cons.oid) as condef from pg_class c left outer join pg_constraint cons on cons.conrelid = c.oid left outer join pg_class c2 on cons.confrelid = c2.oid where c.relkind = 'r' and (cons.contype = 'f') and c2.relname in ('users') group by relation, parent, condef 	0
20386478	2882	mysql order by date before selecting	select      a.*,      b.*,      co.*,     (select count(*) from comments where comment_topic_id = a.topic_id) as tot_comment from topics as a  join categories as b on a.topic_category = b.category_id left join (     select *     from comments c     where not exists(         select 'next'         from comments c2         where c2.comment_topic_id = c.comment_topic_id         and c2.comment_date > c.comment_date     ) ) as co on a.topic_id = co.comment_topic_id where b.category_id = '1' and b.category_permission <= '2' order by a.topic_created asc 	0.00911889171433767
20387319	33112	using 'now' in sqlite date arithmetic	select cast(julianday('now') - julianday(substr(cyclestarted, 1, 4) || '-' || substr(cyclestarted, 5, 2) || '-' || substr(cyclestarted, 7, 2)) as int)       from cycles       where cycleid = 10 	0.428335395410053
20390641	30024	transposing rows to a single column	select t.key_id ,      t.event1 event ,      t.name1  name ,      t.date1  date_event ,      t.price1 price from   table t union all select t.key_id ,      t.event2 event ,      t.name2 ,      t.date2 ,      t.price2 from   table t 	0.000476916359006808
20392279	10984	select statement gives different set of records	select count(*) from stu_empl_pers a  where (a.faculty=1  or a.staff=1)        and a.status='a' and a.site_id = 'dexler'; 	0.00655182709891652
20392829	21643	my query is consuming an inordinate amount of processor time of the server's cpu	select id, title, sub_title, date, image_url, hits, text, comment from news where state = '2' and date >= $timeago order by date desc, hits desc limit 6 	0.131756300436266
20394524	24221	get null entries from database with join	select u.id      as userid,         ispresent,         day(date) as day  from   users u         left join employeeattendance e                on e.userid = u.id  where  [date] between 'jan  1 2013 12:00am' and 'jan 31 2013 11:59pm' 	0.000405649666766053
20396297	17751	how to write a self join query to check to conditions on same entity/field	select * from test where userid="2" or public/private ="0" 	0.374406736430078
20398105	3834	mysql get order number	select * from (   select @rownum: = @rownum + 1 num,         country,         userid,         points   from users, (select @rownum: = 0) r   where country = 840   order by points desc ) a where userid = 23 	0.00570249166506588
20399290	2017	query based on enum value	select * from mytable where pid = $id and `group` = 'a'; 	0.00118542816634204
20400654	23868	converting rows into columns tsql	select  pvt.cid,         [notoattend] = pvt.[10],         [nonottoattend] = pvt.[20],         [nowait] = pvt.[30],         [backup] = pvt.[40] from    t         pivot         (   sum([no])             for rid in ([10], [20, [30], [40])         ) pvt; 	0.00392014198333304
20404316	36488	value range query for non numerical or alphabetic db values	select * from `table`  where `clar` in ('si2','si1','vs2','vs1','vvs2','vvs1','if','fl') 	0.000684500773092439
20404986	9866	column names from mysql to csv file	select  * into outfile '/xampp/tmp/sample.csv' fields terminated by ',' lines terminated by '\r\n' from   ( select 'name' as `e_name`, 'email' as `email` union all select `e_name`, `email` from `email` ) `sub_query` 	0.000406866668754354
20406069	39418	sql - select distinct only on one column	select tbl.* from tbl inner join ( select max(id) as maxid, number from tbl group by number) maxid on maxid.maxid = tbl.id 	0.000422408250369024
20406778	24711	jsp search in more tables in database	select distinct u from user u left join u.skills skill where ... (existing or clauses) or skill.name like :param 	0.179260601227185
20408429	21690	how do you or a whole column of bit data in mysql?	select bit_or(your_bit_field) from yourtable group by your_bit_field 	0.0117379116101712
20409122	36991	oracle query to sum a column by every date range in another table	select t2.st_dt, t2.end_dt,  (     select sum(t1.no_of_pax)     from table1 t1     where t1.dt between t2.st_dt and t2.end_dt ) no_of_pax from table2 t2 order by t2.st_dt asc 	0
20409221	23098	best solution for sql without looping	select    alias1.user_id,            max(alias1.user_name) as user_name,           sum(table2.price)     as userstotalprice,           max(table2.price)     as usershighestprice from      table1                as alias1 left join table2    on alias1.user_id = table2.user_id where     country   = 'united states' group by  user_id 	0.79511597306001
20409238	2409	database design implementing support for different languages	select show_id   from show s left join show_international_date sid               on s.show_id = sid.show_id  where s.episodes_available > 5    and sid.status           = 'emitting'    and sid.language_id      = (select language_id                                   from show_languages                                  where language = 'italian') 	0.788399691495345
20409523	36816	how to multiply 2x select	select s.pole * u.usluga_cena as multipliedout from sciana s    join praca p on s.sciana_id = p.sciana_id   join usluga u on u.usluga_id = p.usluga_id 	0.0415435201808478
20411994	17015	sql - add value with previous row only	select id, number + lag(number,1,0) over (order by id) from table 	6.86477973276701e-05
20413492	12612	populate multiple variables based on row	select     @test1 = max(case when <testcolumn> = 'test1' then col1 else null end),     @test2 = max(case when <testcolumn> = 'test2 ' then col2 else null end),     ...     from     <your table>     where    test column in ('test1','test2') 	0.000723694516112451
20413639	18844	mysql query that checks if two user ids are friends	select a.userid1, a.userid2 from friendship a inner join friendship b on a.userid1 = b.userid2 and b.userid1 = a.userid2 	0
20414202	24608	i want to return data form a table depending on whats in another table?	select u.user_id, u.firstname, u.lastname, p.j_id  from users u  left join passenger_table p on p.user_id=u.user_id  where p.j_id=1; 	0
20417845	32659	what is the major difference between varchar2 and char	select      '"'||cast('abc' as varchar2(10))||'"',      '"'||cast('abc' as char(10))||'"'  from dual; '"'||cast('abc'asvarchar2(10))||'"' '"'||cast('abc'aschar(10))||'"' "abc"                               "abc       "                    1 row selected. 	0.0387913236412704
20418749	7607	mysql select from one table, join from another, then select from the new one	select s.*, max(h.date) last_contact from students s join contact_his h on h.students_id = s.idstudents where s.employee_id = 'pass variable here' group by s.idstudents 	0
20421480	22286	mysql the whole query fails if result of sub query is null	select (select firstname from patient where id > 11445 and firstname != '' limit 1) as tblfirstname,          (select lastname from patient where id > 74964 and lastname != '' limit 1) as tbllastname,          (select birthdate from patient where id > 26360 limit 1) as tblbirthdate,          (select location from patient where id > 68356 and location != '' limit 1) as tbllocation 	0.606764002604346
20421675	17859	divide values in a group by query	select *, a.totalprice / a.totalquantity as averageprice from (select         categoryid        , sum(price) as totalprice        , sum(quantity) as totalquantity       from products        group by categoryid) as a 	0.0420926153660595
20422399	19678	how to count orders of products that have pending status in woocommerce?	select count(distinct wp_posts.id)  from wp_posts, wp_postmeta, wp_term_relationships, wp_woocommerce_order_itemmeta oi, wp_woocommerce_order_items ii  where wp_term_relationships.term_taxonomy_id = (xx - order status id)  and  wp_term_relationships.object_id = wp_posts.id and oi.order_item_id = ii.order_item_id and oi.meta_key = '_product_id' and oi.meta_value = (yy - specific product id, the same id as in wp_posts) and ii.order_id = wp_posts.id and wp_postmeta.post_id = wp_term_relationships.object_id and wp_posts.post_status = 'publish' 	0
20422497	14808	mysql modified preorder tree to create url	select concat_ws('/',x.path,y.page_name) full_path   from      ( select node.id, group_concat(parent.title order by parent.lft separator '/') path          from category node          join category parent            on node.lft between parent.lft and parent.rgt         group             by node.title         order             by node.lft      ) x   join pages y     on y.category_id = x.id; 	0.0922417886482584
20422673	11125	database multi table complex join	select *  from request r  inner join customer c on r.customer_id = c.customer_id inner join requestcondition rc on r.request_id = rc.request_id  where r.employee_id = 123 	0.729859502807393
20423112	33204	adding sums from one table to a second table	select sum(u.amount) from user_details u where exists (select * from temptable t where t.child_id = u.child_id) 	0
20423200	2092	postgresql to_timestamp returning different date when wrapping extract()	select      start_time   , extract(epoch from start_time) * 1000 as epoch_start_time   , to_timestamp(1337358352) at time zone 'utc' as to_timestamp_int   , to_timestamp(extract(epoch from start_time) * 1000) at time zone 'utc' as to_timestamp_expression from matches; 	0.037595288771173
20423327	29652	how to skip the column if dayname equals to saturday or sunday in mysql query	select group_concat(dt) from ( select    (cast('2013-12-01' as date) + interval t.n day) dt from ( select 0 as n union all select 1 as n union all select 2 as n union all select 3 as n union all select 4 as n union all select 5 as n union all select 6 as n union all select 7 as n union all select 8 as n union all select 9 as n union all select 10 as n union all select 11 as n union all select 12 as n union all select 13 as n) t where weekday((cast('2013-12-01' as date) + interval t.n day)) not in (5,6) order by dt limit 7 ) t1 	0.00293273367136554
20423751	28302	mysql search by day	select * from table where dayname(date) = 'tuesday' 	0.0167091020469464
20424367	40710	select rows with each record's creation order per day	select id, name, created_at,     if(@prev = date(created_at), @s:=@s+1, @s:=1) as daily_order,     @prev:=date(created_at) as dummy from table1, (select @s:= 0, @prev:='') s order by created_at 	0
20424508	38123	sql server - xml column query returns result with multiple root elements	select statuses = statushistory.query('     <history>     {         /history/status         [             @updatedat >= @sql:variable("@start") and              @updatedat <= @sql:variable("@end"  )         ]     }     </history> ') 	0.0314631924658578
20424549	27855	selecting column value based on another table	select r1.[line#], r1.castid   ,isnull(q.fldana, r1.ana) [ana]   ,isnull(q.fldconn, r1.conn) [conn] from #srst1 r1 left join fn_qryids q on q.fldana = r1.prod   and q.fldprod = r1.prod where r1.castid <> ''   and r1.prod <> ''   and r1.ana <> '' 	0
20425167	1686	how to count composite primary key in mysql	select count(userid) from table1 where itemid = 1 and itemtype = 1 	0.0288969577071397
20425355	39933	use order by with union all	select *  from  (   select eventname, eventdate, 1 as orderpri,      row_number() over(order by eventdate) as row   from eventtable    where eventdate > getdate()   union all   select eventname, eventdate, 2 as orderpri,      row_number() over(order by eventdate desc) as row   from eventtable    where eventdate <= getdate() ) as m order by m.orderpri, m.row 	0.310434894374226
20425464	17257	postgres: select a composite field with each field name as a value?	select (address).* from mytable where id = 1 	0
20426758	29284	avoiding duplicates in my result table	select * from #tmp t where not exists(select * from #tmp                   where b = t.b                      and a < t.a)   and not exists(select * from #tmp                   where a = t.a                      and b < t.b) 	0.392014384966863
20428240	34701	how to join on my result set and a third table?	select * from tablec c inner join (   select a.memno,     a.name,     a.addr1,     a.addr2,     a.city,     a.state,     a.zip,     a.sex,     a.lname,     a.ssan,     b.addr1 as old_addr1,     b.addr2 as old_addr2,     b.city as old_city,     b.state as old_state,     b.zip as old_zip,     b.timec   from lib1.table1 a   inner join lib1.table2 b on a.memno = b.memno   where b.groupid = 'p2'     and b.type = 'b' and b.datec = 20131206     and (       a.addr1 <> b.addr1 or a.addr2 <> b.addr2       or a.city <> b.city or a.state <> b.state       or a.zip <> b.zip)   ) a on a.ssan = c.ssn where c.print_old is null 	0.0260862987628248
20430810	11721	selecting data from same table that doesn't match	select distinct a.*  from vehicle as a inner join vehicle as b on a.license = b.license where a.vin != b.vin  and a.region != b.region  and (a.region = 1 or b.region = 1) 	0
20431027	32425	query with subquery needs to return all rows from original query (even when subquery comes back empty)	select e.id, concat(e.firstname, ' ', e.middlename, ' ', e.lastname) as fullname,  (   select max(cast(f1.score as decimal))   from filledsoc as f1   where f1.socid = '87bf5fba-5702-4304-869c-8707956d34d0'    and e.id = f1.empid ) as score_1, (   select max(cast(f2.score as decimal))   from filledsoc as f2   where f2.socid = '340363d9-e9a2-478b-b819-d3a56d337561'    and e.id = f2.empid ) as score_2 from employees as e 	0.032650346511167
20431262	17247	how to select a column from 1 table and a column from another table given info in the first table	select p.person_name, i.picked_at    from person as p   inner join itempicked as i    on i.person_id = p.personid 	0
20433766	10291	sql how to combine multiple sql queries into one output	select [status],        [queryno_i] as 'query id',        [assigned_to_group] as 'assigned to group',        [issued_date] as 'issuing date',       case when [status] = 3 then [mutation] else null end as 'closing date',       case when [status] = 3 then 'closed' else 'open' end as [state],       case when [status] = 3 then [mutation_int]-[issued_date_int] else null              end as [tat]  from tablename.[tech_query] with (nolock) 	0.00432248115829921
20434714	19271	changing a query from subqueries to joins	select acc.*  from accounts acc  join addresses addr on acc.id = addr.account_id join alternate_ids ids on acc.id = ids.account_id where lower(acc.firstname) = lower('sam')  and lower(addr.name) = lower('street1')  and ids.alternate_id_glbl = '5'; 	0.495320463851665
20437941	22642	select top row in sql and get 5 rows of end table	select * from (     select top(3) * from mytable order by acode desc ) a order by accode 	0
20438806	5470	select count from four tables	select c.id, c.name, count(ccc.company_id) as num from city_category_company ccc inner join categories c on ccc.category_id = cc.id where ccc.city_id={city_id} group by c.id 	0.00310220064266642
20438973	23890	managin subqueries in sql which have multible rows	select * from tweetstab where username = '".$user."' or username in (select followed from followtab where follower = '".$user."') or tweet like concat ('%@', (select followed from followtab where follower = '".$user."'), '%') or tweet like '%@".$user."%' order by tweettime desc; 	0.057419539804062
20439755	25974	sqlite select rows with not same values in two columns	select url, lastcached, lastupdate from your_table where lastcached <> lastupdate 	0
20440187	12791	retrieve right yr from in sql query	select * from nobel where not subject = 'chemistry' 	0.101411894002546
20440305	32608	sql procedure find 4 matching fields from 5	select  distinct o.*         , (select count(*) from match m1             where   m1.id != o.id                     and (                         (o.col1 = m1.col1 and o.col2 = m1.col2 and o.col3 = m1.col3 and o.col4 = m1.col4)                         or (o.col1 = m1.col1 and o.col2 = m1.col2 and o.col3 = m1.col3 and o.col5 = m1.col5)                         or (o.col2 = m1.col2 and o.col3 = m1.col3 and o.col4 = m1.col4 and o.col5 = m1.col5)                         or (o.col1 = m1.col1 and o.col3 = m1.col3 and o.col4 = m1.col4 and o.col5 = m1.col5)                         or (o.col1 = m1.col1 and o.col2 = m1.col2 and o.col4 = m1.col4 and o.col5 = m1.col5)                     )             ) testmatch from    match o 	0.00025886036491569
20441314	30479	mysql query to order by existence in another table	select products.*, product_info.* from products inner join product_info on product_info.product_id = products.id left join specials on specials.product_d = products.id                   and specials.from_date < now()                   and specials.to_date > now() where product_info.language = 'en'   and product_info.title like ? order by case      when specials.product_id is not null then 2     else 1     end desc,   products.id desc,   products.created_at desc 	0.00731245991425346
20441435	14623	select two values from two different rows for a single name	select     max(case when payments.payment = 'debt' then payments.total end) as takendebt,     min(case when payments.payment = 'debtpaid' then payments.total end) as givendebt,     max(case when payments.payment = 'debt' then receipts.datenew end) as takendate,     max(case when payments.payment = 'debtpaid' then receipts.datenew end) as givendate,     case when payments.payment = 'debt' or payments.payment = 'debtpaid' then customers.name end as customer  from receipts     inner join tickets on receipts.id = tickets.id     inner join payments on receipts.id = payments.receipt     inner join customers on tickets.customer = customers.id where     (payments.payment = 'debt'     or payments.payment = 'debtpaid') group by customer order by customer 	0
20441874	22786	single sql query required	select t2.state, t1.name,t2.powerconsumption from table1 t1 inner join table2 t2 on t1.companyid = t2.companyid where t2.month = 'jan' order by t2.state asc, t2.powerconsumption desc; 	0.370673882199426
20443585	8537	argument matching parameter 'text' cannot convert from 'dbnull' to 'string'	select iif(surname is null, '', surname), iif(forename is null, '', forename),   iif(someintfield is null, 0, someintfield) from records where checkoutdate is null 	0.23250774235729
20443918	37495	sql max( ) function	select top 1 * from matches where goals_for > 2 order by date desc 	0.62565631863539
20444164	27323	sql query - i can i sum up the values for the same country	select c.cust_country,         sum(p.proj_contract_value) as value_sum from customers c inner join projects p on c.id = p.id where p.proj_date >= convert(datetime, '2013-01-01') group by c.cust_country order by c.cust_country 	0.00112495992821952
20444474	17335	t-sql query to get role using role id in user table	select userid,name,role_desc from tblusers    inner join tblroles on tblusers.roleid = tblroles.roleid; 	0.00225904735117911
20445752	10112	how can i find records using only certain rows in a joined table?	select c.* from contracts c, locations l where   c.id = l.contract_id and   c.name like '%bay%' and   l.name like '%admin%' and l.order_position = (   select max(order_position)   from `locations`   where `contract_id` = c.id ); 	0
20445800	27235	mysql query to select duplicates	select a.id, a.placex, a.placey, a.wealth from player a,      ( select  placex, placey        from player        group by placex, placey        having count(*) > 1      ) b where a.placex = b.placex and a.placey = b.placey 	0.216347706425259
20447091	11362	mysql - how can i group numbers into 50 increment	select page_count, truncate(page_count / 50, 0) * 50 as rounded_page_count from a_bkinfo.books 	0.00381280080722798
20447883	15271	select date between current date and one week innodb	select * from exp where expiration  between           current_date          and           current_date + interval 7 day 	0
20449309	29504	sql select distinct with multiple columns	select distinct department, 'january' mm from projects 	0.0180383910856663
20449910	8701	sqlite3 and php: sorting entries by datetime	select * from table where time > datetime('now', '-30 minutes'); 	0.00765414573360447
20449945	21506	how to return a query result even when nothing comes up for the results	select    sub.tdate,   count(orders.dt) from (select to_date(to_char((sysdate-1),'mmddyyyy'),'mmddyyyy') tdate from dual) sub left join orders on sub.tdate = orders.dt and orders.ship_method like '%rts%' group by sub.tdate 	0.281141991593645
20451779	37316	get next auto increment value from an empty table	select auto_increment  from information_schema.tables  where table_name ='messages' and table_schema='database_name' 	0
20452655	31617	postgresql multiple subqueries	select * from student s where s.programme = 'it' and exists (   select *    from enrolled e   join class c on c.ccode = e.ccode   join tutor t on t.tid = c.tid   where e.sid = s.sid   and t.tname like '%hoffman'   ); 	0.684613680463709
20453120	34175	joining fields according to some condition in tsql	select t1.tagno + ',' + t2.tagno as tagno, t1.frombay,t1.frompanel,t1.tobay,t1.topanel,t1.fromdevice,t1.fromterminal, t1.fromref + ',' + t2.fromref from t t1 inner join t t2 on (t1.frombay=t2.frombay and t1.frompanel=t2.frompanel  and t1.tobay=t2.tobay and t1.topanel=t2.topanel  and t1.fromdevice=t2.fromdevice and t1.fromterminal=t2.fromterminal and t1.tagno<t2.tagno) 	0.00871443149686818
20453685	31474	selecting rows according to similarity using mysql query	select   name,   dob,   doj,   sex,   t.salary from   table as t   inner join (select                 salary               from                 table               group by                 salary               having                 count(*) > 1) as s       using (salary) 	0.00135748652346809
20453913	35756	mysql group by with order by using specific words	select  projectid, max( status ) status from projstatus  group by projectid 	0.11168355731272
20458145	24449	sql - check if data exists on either table	select top 1 *  from(   select studentid as userid, password, firstname, lastname   from tbluserstudent    where studentid = 's1201235'   union all   select librarianid,password, null, null   from tbluserlibrarian    where librarianid = 's1201235' ) a 	0.0198074970794273
20459022	1006	sql query into a table to find the row with the minimal value >= x for a particular column	select * from table1 where colsize >= x order by colsize limit 1 	0
20459040	39215	mysql concurrent select from rows	select d, count(*) as user_count from (    select start_date as d from your_table    union all    select end_date as d from your_table ) x group by d order by user_count desc 	0.00227103330385072
20461445	23796	oracle sql query to group consecutive records	select line_no,        amount,        narration,        sum( x ) over ( order by line_no                        rows between unbounded preceding and current row         ) as calc_group from (   select t.*,          case lag( narration ) over (order by line_no )           when narration then 0          else 1 end x   from test t ) order by line_no 	0.0203271176099238
20462934	38057	sorting a column in ascending and descending order depending on the current date	select * from products order by expireddate < now(), abs(timestampdiff(second, expireddate, now())) 	0
20463575	15593	recursive sql query to get children under the parents - sql server 2008	select      l1.child 'l1', l2.child 'l2', l3.child 'l3', l4.child 'l4', l5.child 'l5' from      #temp l1 left join      #temp l2 on l2.parent = l1.child left join      #temp l3 on l3.parent= l2.child left join      #temp l4 on l4.parent= l3.child left join      #temp l5 on l5.parent= l4.child where      l1.parent is null 	0.0344087236652985
20463609	26069	group by on table, list all of one attribute for each of another attribute	select name, wm_concat(number) number   from (   select distinct name, number      from patterns t join numbers n       on t.index = n.index join people p       on t.id = p.id ) q  group by name  order by name 	0
20464189	13626	is this good way to find 3 month older record	select * from "table" where dstart < current_date - interval '3 month' 	0.00176686921472124
20466416	39712	showing records from two sql table alternatively	select * from employeedetails ed left join employeeentries ee on ee.empid = ed.empid 	0.000393182761196496
20466424	27155	sql statement to list and country countries in sql	select country, count(*) from dbo.customers group by country 	0.106853873424805
20466609	34906	how to access the data of a table from parent database in sql server	select     localtable.*, tmp.* from     localtable,     [otherservername].[otherdb].[dbo].[othertable] as 'tmp' 	0.000215008741070292
20466839	7017	finding abbreviations from data in mysql	select * from questionanswer where answers regexp binary '\s*[a-z]{2,}\s*' 	0.00615850597692299
20467408	33996	sql unpivot text contents	select      [pk_id]     ,[job_id]     ,[note]  from      table1  cross apply  (     select [note1] as [note]     union all      select [note2] as [note] ) t where t.note is not null 	0.268894549244693
20467612	23416	sql get temperature value by minute average	select   sensorid,    date_format(sensortimestamp, '%y-%m-%d %h:%i'),  (sum(sensortempvalue)/count(sensortempvalue))/16  from temperaturedata  where now()-temperaturedata.sensortimestamp < interval 1 day  group by sensorid, date_format(sensortimestamp, '%y-%m-%d %h:%i') 	0.000199591593480795
20467982	39515	select rows with having after a given date	select * from (   select userid, count(status) as valid, max(date) as lastdate   from ladder_offers_actions    where status="validated"   group by userid   having valid=5 ) x where x.lastdate > '2013-06-06' 	0.000651752663651365
20468013	35689	how to get the rows from mysql that is-5 or +5 then the current row?	select * from test where totalview> (current-5) and totalview< (current+5); 	0
20468632	38802	duplicate line according to quantity amount	select t.*, numbers.n from t inner join  (  select aa.a + 10 * bb.b + 100 * cc.c + 1000 * dd.d as n from  (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) aa,  (select 0 as b union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) bb,  (select 0 as c union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) cc,  (select 0 as d union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) dd ) numbers on t.quantity >= numbers.n where numbers.n != 0 order by t.id, numbers.n 	6.44757445976468e-05
20469392	38565	merge records in one record with a sql query	select    id,name,    stuff((select ','+phone from tblphone             where id=tblusers.id for xml path('')),1,1,'') from     tblusers 	0.000246402163411935
20470016	10616	counting up a column incorrectly sql	select count (rvsessionkey) from tblreport tt left outer join tblreportview  on rptid = rv_rptid where rpt_orgid in (1002,1047)     and tt.rpt_orgid = tblreport.orgid    and rvemail not like '%support%'    and rpt_qtrid in (1)) as [page view], 	0.153556530078289
20471154	24384	join 2 tables and extract one column based on where clause	select  track_id from    table1 where   artist_id = 34 union select  track_id from    table2 where   artist_id = 34 	0.000107770478915657
20474309	3561	wordpress admin users	select      usr.display_name,     m1.meta_value,     m2.meta_value from wp_usermeta m1 join wp_usermeta m2   on (m1.user_id = m2.user_id and m1.meta_key = 'lastname' and m2.meta_key = 'firstname' join wp_users usr   on m1.user_id = usr.id order by m1.meta_value, m2.meta_value limit 0,30 	0.118699550256539
20475181	31738	sql where condition for getting the first and second maxium values	select * from( select tname,teacher.tid,grade from teacher  inner join _view on(_view.tid=teacher.tid) )as d where grade in(select grade from  _view order by grade desc limit 2) order by grade desc,tid; 	9.45290846810687e-05
20476159	36015	how to do 2 while loop mysqli_query in php?	select * from bicycle_list inner join bicycle on bicycle.bicycle_id = bicycle_list.bikeid; 	0.104342036575537
20476500	13808	sql group count of values derived from a like case statement	select site, count(*) as count from (     select (case                 when  propertyvaluestrings like '%www.website.co.uk%' then 'uk'                 when  propertyvaluestrings like '%www.website.us%' then 'usa'                 when  propertyvaluestrings like '%www.website.com.br%' then 'brazil'                 when  propertyvaluestrings like '%www.website.co.id%' then 'indonesia'                 when  propertyvaluestrings like '%www.website.com%' then 'global'            else 'xxxxxxxxxxxxxxxx            end) as [site]     ,     propertyvaluestrings      from profiles ) x group by site 	0.211814130772154
20478153	4047	mysql query related to group by and having	select  player_id as 'players',  sum(sb_stats_hr) as 'homers' from softball_stats   group by player_id  having sum(sb_stats_hr) > 3; 	0.18072952330104
20478307	15450	count number of saturdays between two dates - mysql	select received_on,closed_on, floor(datediff(date(received_on), date(closed_on))/7) as numofsat from table 	6.03801852468524e-05
20478870	28750	including results in group by when the count is zero for one of the groups	select p.status as `0`, sum(case when c.status = 'new' then 1 else 0 end) as `1`, sum(case when c.status = '1 attempt' then 1 else 0 end) `2`, sum(case when c.status = '2 attempts' then 1 else 0 end) `3`, sum(case when c.status = '3 attempts' then 1 else 0 end) `4`, sum(case when c.status = 'connected' then 1 else 0 end) `5`, sum(case when c.status = 'follow up' then 1 else 0 end) `6`, sum(case when c.status = 'referred' then 1 else 0 end) `7` from (   select 'new' status   union select '1 attempt' status   union select '2 attempts' status   union select '3 attempts' status   union select 'connected' status   union select 'follow up' status   union select 'referred' status ) p left join contact c on p.status = c.status group by p.status having status not in('invalid', 'archived') order by field (p.status, 'new', '1 attempt', '2 attempts', '3 attempts', 'connected',    'follow up', 'referred') 	0.000190799732737463
20479620	20849	how can i return the next row of where clause?	select id1 from table where id in (select t1.id+1 from table t1  left join table t2 on t1.id1=t2.id  where t2.id1 is null); 	0.00120945323355968
20479626	9220	return top n rows for each group (vertica/vsql)	select *  from (select tag_id, geo_country, sum(imps),     rank() over (partition by tag_id order by sum(imps) desc) as rank      from table1     where tag_id in (2013150,1981153)     and ymd > current_date - 3     group by 1,2) as t2 where t2.rank <=5; 	0
20480412	39475	sql query multiple tables in database	select propertyname, clientsinprop_visitdate, clientname   from property    left join clientsinprop on clientsinprop_propertyid = property_propertyid    left join client on client_clientid = clientsinprop_clientid   where proprty_name = 'house 1' and clientsinprop_visitdate > '01.10.2013' 	0.14400921708329
20480625	15675	what is a dataset in the context of databases?	select * from table where age > 20 	0.0551094754727482
20481868	39170	finding the pair of points whose distance from each other is maximal ( plpgsql )	select set1.id, set2.id, abs(set1.the_geom - set2.the_geom)  from foo set1, foo set2 where set1.id != set2.id  order by 3 desc; 	0
20482208	23621	query listing company name and first order date	select c.customerid, companyname, min(o.orderdate) as 'first order date' from     customers c     join orders o on c.customerid = o.customerid group by c.customerid, companyname  order by c.customerid 	0.000941377227427332
20483848	40800	access sql - how to prevent alternating date while selecting from latest date	select m.*, r2.rate from    (select t.empid, t.timesheet,  max(r.promotiondate) as promotiondate from timesheet as t left join  rates r on r.empid=t.empid and t.timesheet>=r.promotiondate    group by t.empid, t.timesheet) m   inner join rates r2 on  m.empid=r2.empid and m.promotiondate=r2.promotiondate 	0
20484016	37554	how to get current transaction id in sql azure	select @transactionid = transaction_id from  sys.dm_tran_session_transactions  where session_id = @@spid 	0.000111097176235814
20484221	33052	checking if data in one table is contained in another	select columna from tablea except select columnb from tableb 	0.000773406053580761
20484574	38534	selecting a max number of rows per group	select user_id, first_name, last_name, email   from (   select user_id, first_name, last_name, email,   (     select 1 + count(*)       from users      where email = u.email        and user_id < u.user_id   ) rnum          from users u ) q  where rnum <= 2   order by email, user_id 	0
20488396	24682	group by with maximum date	select n1.id, n1.message_id, n1.client_id, n1.date from shailjas_note n1 where n1.date = (select max(n2.date)                   from shailjas_note n2                   where n1.message_id = n2.message_id                       and n1.client_id = n2.client_id) 	0.00881894288193801
20489341	24105	how to count results from groupped subquery	select distinct sr.srclngid, sr.supplierid into #mytable99 from supplierlangs sl select srclngid, count(srclngid) as [count] from #mytable99 temp group by srclngid drop table #mytable99 	0.073521610867501
20489410	28476	adding together values from all returned rowsz	select quoteid, sum(value) total from votes group by quoteid 	0.000502558836038456
20489824	17588	get top number of rows anyway	select top 5 col  from(     select 0 srt, col from yourtable     union all     select 1 srt, 'no data' col union all     select 1 srt, 'no data' col union all     select 1 srt, 'no data' col union all     select 1 srt, 'no data' col union all     select 1 srt, 'no data' col )x order by srt 	7.26468165393969e-05
20490153	4912	sql count rows and display in order	select type, count(type) as type_count from animals group by type order by type_count desc limit 0, 10 	0.00159057216424797
20490280	25039	get date from sql table	select * from grn_final where to_date(date, 'yyyy_mm_dd') between to_date('2013_12_9', 'yyyy_mm_dd') and  to_date('2013_12_10', 'yyyy_mm_dd'); 	0.000599361276345737
20491066	16673	can i have one row in select from other table than currently referred ?	select   a.c_col1,   a.s_col2,   b.c_col3 from   (select count(col1) c_col1,           sum(col2)   s_col2    from   table_a) a,   (select count(col3) c_col3    from   table_b) b 	0
20491138	29449	count unique results in one column which have a given value in another column	select u.uid       ,testrig       ,convert (date, [stamp]) as date       ,description from (      select uid            ,count (uid) as attempts      from [dbase].[dbo].[tbl_results]      where testrig in ('rigone', 'rigtwo')        and testname = 'finished'        and stamp > '2013-12-01'      group by uid) as u  join (      select uid            ,pass            ,testname            ,stamp            ,testrig            ,description      from [dbase].[dbo].[tbl_results]      ) as r on (u.uid = r.uid) where u.attempts = 1   and r.pass = 'p'   and testrig in ('rigone', 'rigtwo')   and testname = 'finished'   and stamp > '2013-12-01'   and pass = 'p' 	0
20492368	25956	show best matches in a mysql tag system	select    distinct some_text  from    articles join article_tags on (articles .article_id = articles_tags.article_id )    join tags on (articles_tags.tag_id =  tags.tag_id)  where    tag_name in ("hard", "sweet", "red")  order by count(tag_id) desc; 	0.0209619311592413
20492709	18862	ordering by more than one field?	select       u.id     ,u.email     ,u.verified     ,u.verified_on     ,u.created_on     ,ca.html as age     ,cg.html as gender     ,cs.html as state from users u     left join combo ca on ca.combo_group='age' and ca.value =u.age     left join combo cg on cg.combo_group='gender' and cg.value =u.gender     left join combo cs on cs.combo_group='state' and cs.value =u.state  order by created_on desc, email asc 	0.00941825229788201
20496279	3787	php pull data out of mutiple databases	select t1.id, name, gender, dob, state, t2.stuff, t2.stuff2 from database1.people t1 left outer join database2.offenders t2 on t1.id=t2.id 	0.00287449863684491
20496518	11621	query="select * from table where `varcharcol1`= numeric"	select * from table where `varcharcol1` rlike '^[0-9]+$' 	0.0374611688183109
20497461	28727	parent without child sql	select *  from parenttable p where not exists(               select 1               from childtable1 c1               where c1.parentid = p.id)      and not exists(               select 1               from childtable2 c1               where c1.parentid = p.id) 	0.0139172674872249
20498238	22802	additional inner join modifying results of previous calculations	select b.id, count(distinct s.staff_id) from branch b  inner join staff s on s.branch_id = b.id inner join tool_stock ts on ts.branch_id = b.id group by b.id; 	0.617615758481572
20498543	17324	select unique records from table mysql php	select $cols,type_id from notification group by type_id order by alert_on asc 	0.000131636445358489
20499812	9102	using grouped value instead of table value in mysql query	select `date`, sum(pageviews) as pageviews from (select date_format(`date`, "%y-%m") as `date`, sum(pageviews) as pageviews     from `domains_data`     group by `date`) as ref group by `date` order by `date` desc 	0.000237761140411631
20500117	26529	get data from 1column and split in to two using based using table join and column filter in sql	select           g.gloss as meaning,     wrd.ss_type as word_type,     wrd.word as word,     wrdopp.word as opposite from wn_synset as wrd  join  wn_gloss as g   on wrd.synset_id = g.synset_id  join wn_antony as a   on a.synset_id_2 = wrd.synset_id   and wrd.w_num= a.w_num_2  join wn_synset as wrdopp   on a.synset_id_1 = wrdopp.synset_id   and wrdopp.w_num= a.w_num_1  where wrd.word= 'good'   order by wrd.ss_type 	0
20500570	37031	mysql group by with count	select country,count(*)  from author  group by country; 	0.30940228892525
20500609	37598	sql select distinct deciding which record to keep	select id, firstname, surname, max(lessonstatus) from(     select * from assessment1     union     select * from assessment2 ) group by id, firstname, surname 	0.00452303440988168
20501127	15839	how can i create a mysql query within a query and concatenate?	select  u.uid,  u.name,  m.membership_no, (select group_concat(name) from users_roles ur inner join roles r on r.rid = ur.rid where ur.uid = u.uid) as roles from users as u  left join memberships as m on u.uid = m.uid; 	0.0367643794678526
20501135	15481	index number for records within a pipe-delimited field inside a csv	select row_number() over (partition by crimerecords.casenum order by crimerecords.casenum) as idx, crimerecords.casenum, crimerecords.offense, primarycrime.primarycrime from (select casenum ,x.i.value('.','varchar(20)') as offense              from (select casenum, convert(xml,'<i>'+replace(crimetype, '|', '</i><i>') + '</i>') as d                          from crimeview.dbo.tblcrimedata)x1 cross apply d.nodes('i') as x(i)) as crimerecords 	0.00106454468875968
20503623	31525	getting min value over a period of time for each record	select t1.dept, min(t2.cnt) min_last_3_month, t1.dat from   tbl t1 inner join tbl t2 on t1.dept = t2.dept                  and t2.dat > dateadd(month, -3, t1.dat)                  and t2.dat <= t1.dat group by   t1.dept, t1.dat order by   t1.dept, t1.dat 	0
20504217	24762	order number and strings putting strings last	select * from posts  order by price * 1 desc 	0.000162986040592182
20505670	37289	combining mysql queries of unrelated data when related point is a substring()	select count(*) from `trades` where tid > (select substring(url,50, 50) as oldest from querylog where url like 'https: 	0.00638989513441547
20506356	4882	sql server select where value equals results of another select	select name from tableb where label in ( select label from tablea where value = 'a' ); 	0.000920617873179035
20511218	17877	how can i get 'day of week' for the 'friday' only?	select  date, dateadd(dd,(7- datepart(dw,date)),c.date) as 'end date', datename(dw,(dateadd(dd,(6- datepart(dw,date)),date))) as 'dayname' from table_name; 	0
20512689	1313	how to sum only a specific row in a table	select (mark1+mark2+mark3) as mark_sum  from studentdetail  where mark1=96 	0
20512801	13327	find the database in which a particular record is available	select 'db1' as db, 't1' as table from db1.dbo.t1 where 'some_value' in (c1, c2) union all select 'db1' as db, 't2' as table from db1.dbo.t1 where 'some_value' in (c3, c4, c5) union all select 'db2' as db, 't1' as table from db2.dbo.t1 where 'some_value' in (c1, c2) union all select 'db2' as db, 't2' as table from db2.dbo.t1 where 'some_value' in (c3, c4, c5) union all select 'db3' as db, 't1' as table from db3.dbo.t1 where 'some_value' in (c1, c2) union all select 'db3' as db, 't2' as table from db3.dbo.t1 where 'some_value' in (c3, c4, c5) 	0
20512990	34164	mysql variable precedence	select *    from tablename   where ifnull(colname, 0) <=0; 	0.62147731390242
20513586	24568	how can i join several mysql queries while excluding some results?	select users.uid, users.gender, users.username from users     left join users_fav on users.uid=users_fav.matchuid and users_fav.uid = 1     left join users_rated on users.uid=users_rated.matchuid and users_rated.uid = 1 where users_fav.uid is null and users_rated.uid is null 	0.0877787540683005
20515814	33359	select statement adds values together instead of displaying separately	select spelers.naam,  concat(wedstrijden.gewonnen,' - ',wedstrijden.verloren) as uitslag from spelers inner join wedstrijden     on spelers.spelersnr = wedstrijden.spelersnr where wedstrijden.gewonnen > wedstrijden.verloren; 	0.0527529362773261
20516128	7403	ms sql retrieve related data from same table in one query	select a.id, a.name, b.id, b.name from mc.staff a inner join mc.staff b on a.supervisorid = b.id 	0
20517154	30520	retrive the id as per single element from an array of a coloumn	select * from table_name where misc regexp '(.*\"level_id\":\"20\".*)' 	0
20518715	4672	percentage of total in pivottable	select convert (date, [stamp]) as date   ,sum(case when pass='p' and testrig = 'rig 1' then 1 else 0 end) as r1passes   ,sum(case when pass='p' and testrig = 'rig 2' then 1 else 0 end) as r2passes   ,sum(case when pass in ('p', 'f') and testrig = 'rig 1' then 1 else 0 end) as r1tests   ,sum(case when pass in ('p', 'f') and testrig = 'rig 2' then 1 else 0 end) as r2tests from [dbase].[dbo].[tbl_results] where stamp > '2013-12-01'   and testname = 'finished' group by convert (date, [stamp]) 	0.00123302469757862
20519161	26102	each id with how many “column1”, “column2” and “total ” and order them by “total”	select payroll,        sum(case when "leave class" = 'emergency' then 1 else 0 end) as "emergency leave",        sum(case when "leave class" = 'sick' then 1 else 0 end) as "sick leave",        count(*) as "total" from leave group by payroll order by count(*) desc; 	0
20519190	18856	how to write a query that returns all the information?	select * from stackoverflow_users u left join stackoverflow_skills s on s.user_id = u.source_id left join github_urls l on l.id = u.id where u.user_name like 'a%'; 	0.00662883425494651
20519281	23437	how to add a php variable inside regexp in mysql	select count(product_id) as totalcount from ref_products where misc regexp '(.*\"level_id\":$course_level_id.*)' 	0.41981320868724
20519670	1281	sql query to get the student name with rank between 10 and 20 out of 100 students?	select studentname from studenttable order by totalmarks desc limit 10, 10; 	0
20520222	22138	connect by prior	select   child_id from   collection_items where   level <= 3   start with parent_id      = 16917   connect by prior child_id = parent_id 	0.203171497125435
20522672	6671	sql query to select the name of the branch with max number of employees working	select top 1 branchid, count(*) from employee  group by branchid  order by count(*) desc 	0.000339318869270818
20523256	34730	how can i select items that don't have a particular column value?	select group_id from your_table group by group_id having sum(meta_key = 'has_foo') = 0 	0
20524840	7515	sql: get the average value of stocks in each fund	select fundname, sum(numshares * price) / sum(numshares) as avgshareprice   from table group by fundname; 	0
20525052	29045	select name of column in pivot	select distinct    filename,   vals,counts from     (select          filename,         a1,         a2,         a3    from        foo) p unpivot    (vals for counts in        (a1,a2,a3) ) as bar 	0.0191825301452724
20526226	11063	select a variable as condition and display another one	select winner from table where year in (select min(year) from table) 	0.000164618137359249
20526344	12258	join history table with itself to get the newest event at specific time	select t.id,        t.ts,        t.event,        max( case event when 'e' then ts end )         over        ( partition by id order by ts           rows between unbounded preceding and current row ) occ from history t ; 	0
20527600	32148	sort varchar integers first in mysql	select          *   from          table1   order by          case when alexacr like 'n/a' then 1 else 0 end asc,         lpad(alexacr, 20, '0') asc 	0.00429012744522682
20528293	1230	mysql query for extracting "1" from "1-a","1-b",etc from a particular column	select cast(tableno as unsigned) 	6.18911142057735e-05
20528564	7119	postgresql modeling ranges	select bookings.*, lead("time") over (order by "time") as next_booking_time from bookings 	0.247642305408943
20530617	18296	multiple sums with different where clauses in same query result set	select t1.region, t1.model, t1.uniques, t2.sales from (select cast(left(b.name, 3) as varchar(3))as region, a.model, sum(a.number)as uniques from table1 a inner join database2.....table2 b on a.code = b.code where year(a.eventdate) = @year and month(a.eventdate) = @month and a.make='toyota' group by cast(left(b.name, 3) as varchar(3)), a.model order by cast(left(b.name, 3) as varchar(3)) ) t1  inner join ( select cast(left(c.name, 3) as varchar(3)) as region, a.model, sum(b.number)as sales from table1 a left join table3 b on a.leadid = b.leadid inner join database1..table2 c on a.code = c.code where year(a.eventdate) = @year and month(a.eventdate) = @month and a.make='toyota' group by a.model, cast(left(c.name, 3) as varchar(3)) order by cast(left(c.name, 3) as varchar(3)) ) t2 on t1.region = t2.region  and t1.model = t2.model 	0.0054478118699039
20531003	18460	two queries, two different tables, only one loop	select cola as eithercol from table1 where cola is not null order by datea union select colz as eithercol from table2 where colz is not null order by datez 	0
20531260	29598	selecting database name, table name and column name.	select d1.col1, d2.col1 from db1.table1 d1 inner join db2.table1 d2 on d1.id = d2.id 	9.29451930330503e-05
20531468	23612	mysql index sort order	select min(key_part2),max(key_part2)   from tbl_name where key_part1=10; 	0.402176686247673
20531940	37623	multiple joins with criteria in one of them	select fund.code, value, actvalue, count, actcount     from fund      left join (select code, sum(value)as value, count(code) as count from policy group by code) policy on fund.code=policy.code     left join (select code, sum(value)as actvalue, count(code) as actcount from policy where dod is null group by code )on fund.code=active.code 	0.00413879527231425
20532311	36591	sqlplus, export the query in 1 column, and disordered	select camp1 || '|' || camp2 || '|' || camp3 || '|' || camp4 from table; 	0.0775055514119227
20533361	8310	sql query filtering according to status	select [account grp],         [account names],         sum(balance) [total balance],         sum(case [account status]               when 'current' then balance               else 0.00             end)     current,         sum(case [account status]               when 'past' then balance               else 0.00             end)     past  from   [accounts]  group  by [account grp],            [account names] 	0.0251429950193522
20534434	22686	postgresql query to get pivot result	select shipping_id,        sum(case when status=1 then 1 else 0 end) as total_activate,        sum(case when status=0 then 1 else 0 end) as total_deactivate from (select distinct shipping_id,                        shop_id,                        status         from test) a group by shipping_id order by shipping_id 	0.172246860535553
20536414	12731	how do i check memory used by each database/tables in mysql using command prompt?	select table_schema "table name", sum( data_length + index_length ) / 1024 / 1024 "data base size in mb"  from information_schema.tables group by table_schema ; 	0.0222705677800263
20536484	21059	find records inside same table by query with different where filters	select cid, sid, sdate,price from sales as t1 where sdate > #11/01/2013# and sdate < #11/30/2013# and  exists  (select cid,sid,sdate from sales as t2 where (sdate > #12/01/2013# and sdate < #12/30/2013#) and (t1.sid = t2.sid and t1.cid = t2.cid)); 	0.000458649578664237
20538012	31385	mysql - finding difference between any two integers in same column	select     here.city as here,     there.city as there,     here.price - there.price as profit,     abs(here.lat - there.lat) as distance from buying as here left join buying as there on (here.city <> there.city) where here.city = 'springfield' 	0
20538234	36636	find out missing stored procedures in mssql	select specific_name from db1.information_schema.routines where routine_type = 'procedure'   and left(routine_name, 3) in ('sp_',                                 'xp_',                                 'ms_') except   select specific_name   from db2.information_schema.routines where routine_type = 'procedure'   and left(routine_name, 3) in ('sp_',                                 'xp_',                                 'ms_') 	0.197640854645957
20539680	40556	select query not working when selecting particular column 'condition'	select `condition` from `tbl_condition`; 	0.256402630863903
20539858	17187	mysql price handling with valid time interval, limiting join	select     p.id,     pp.id,     pp.price,     pp.comment from     product_products p join     product_prices pp on     pp.id = (select id from product_prices where _from < now() and product_id = p.id order by _from desc limit 1) where pp.comment is not null group by     p.id 	0.746913536499445
20539970	8551	count and divide two columns of the same table in sql	select count(sk_patientid) as pnum             , count(case when sk_metricid = 11 then 0 end) / count(case when sk_metricid = 12 then 0 end)             , sk_metricdateperiod    from [metricvalues]     where sk_metricid in (11, 12)    group by sk_metricdateperiod    having count(case when sk_metricid = 12 then 0 end) > 0 	0
20541690	12483	mysql join to fetch one result in one table and many in another	select *  from parent_table  right outer join child_table  on (parent_table_id = child_table_id)  where parent_table_id = ? 	0
20542601	13296	mysql one to many in one row	select t1.`id_c`,c.`name`,t1.latest,t1.`note` from `tablea`c  inner join  (  select t2.`id_c`,t2.latest,t3.`note` from `tableb` t3   inner join  (select `id_c`,max(`data_visited`) as latest from `tableb`  group by(`id_c`))t2  on (t3.`id_c`=t2.`id_c`) and (t3.`data_visited`=t2.latest) )t1 on(c.`id_c`=t1.`id_c`) 	0.000501155061788729
20543768	16652	tsql, join to multiple fields of which one could be null	select * from   products p        left join sometable st          on st.someotherid = p.someotherid             and exists (select st.someid intersect select p.someid) 	0.0605035168174999
20543848	25921	sql to search for string matches and compute a percentage	select 100*avg(case when table_b.first_name is null then 0 else 1 end) percent from table_a  left join table_b   on table_a.first_name  = table_b.first_name  and table_a.family_name = table_b.family_name 	0.0261292207927783
20544493	24685	sqlite query _ select only different varchar and add them to one	select group_concat(name,'') from (   select distinct name   from testtable   where id<=10   order by name ); 	0
20544754	40992	how to use order by based on strings in sqlite	select * from t order by (url is null),id 	0.0147602715448042
20546693	5892	mysql - nested select return list?	select *  from table1  inner join table2    on table1.id = table2.id    and table2.type = 'type1'  where table1.name = 'somename' 	0.120787186941683
20546922	15058	convert "_" to " " when selecting column names in sql?	select replace(column_name, '_', ' ') as name from information_schema.columns where (table_name = 'im_notes') 	0.00223949754956263
20547810	35052	postgresql run upsert function for each record in query	select myfunction(arg1,arg2,arg3)   from (     select arg1, arg2, arg3       from data_table       where something='something-other'   ) as _; 	0.016303282851196
20547989	19381	select from 2 selects	select    p.product_name,    isnull(i.quantity,0) - isnull(s.quantity,0) as [currently_in_stock] from    products p    left join (select product_id, sum(quantity) as quantity from inventory group by product_id) i    on p.product_id = i.product_id    left join (select product_id, sum(quantity) as quantity from sales group by product_id) s    on p.product_id = s.product_id group by    product_name 	0.0138469129419179
20549452	12772	select only n number of characters from varchar(max) field	select substring(yourcolumnname,0,2000) from yourtablename 	0
20549535	37014	mysql select most used ip's from user id's	select userid, count(distinct ip) from loginlogs group by 1  order by 2 desc 	0.000114235192365214
20550243	33267	how to order by count of related entity	select f from file f where f.name like '%example%' order by size(f.commentaries) 	0.0182127595460822
20551857	32619	tsql: find required missing records	select * from yourtable a where not exists(select 1 from yourtable                  where inspectionid = a.inspectionid                    and componentid = a.componentid                  and ratingtypeid = 6) 	0.019171647694604
20552007	6057	select distinct fields with criteria	select a.id,        a.interfaceid,        i.deviceid,        i.typeid,        a.anotype from i  inner join a on i.interfaceid = a.interfaceid inner join d on i.deviceid = d.deviceid where i.accountid = '500'   and d.userid = '1000'   and a.anotype <> -3   and a.interfaceid  not in (select interfaceid                              from a                              where anotype = -3) 	0.0199724098616613
20552302	10827	trying to get the max from a group of aggregates	select max(spread) from (     select student, max(score) - min(score) as spread from exams group by student ) x; 	0.00101565857210826
20553237	2661	mysql get count of items using right join	select ads.id, ads.title, count(sign_ups.user_id) as total from sign_ups right join ads on ads.id = sign_ups.ad_id where advertiser_id=1 and sign_ups.user_id is not null union all select ads.id, ads.title, 0 as total from sign_ups right join ads on ads.id = sign_ups.ad_id where advertiser_id=1 and sign_ups.user_id is null 	0.0174108054805244
20553270	24059	sql query to compare rows with each other based on relational data from other tables	select ma.member_id as 'member 1',        ma2.member_id as 'member 2',        count(maa.answer_id) as 'total matches' from members_answers ma   join questions q     on q.question_id = ma.question_id   join questions q2      on q.question_id = q2.question_id   join members_answers ma2     on ma2.question_id = q2.question_id   join members_acceptable_answers maa     on  ma2.answer_id = maa.answer_id      and ma.member_id = maa.member_id group by 1,2 order by 1,2 	0
20553452	36824	in sql need to manually increment on insert	select   alertid,   alertdate,   (select isnull(max(actionid), 0) from corraction as c where c.alertid = t.alertid)    + row_number() over (partition by alertid order by alertdate desc) as actionid from temptable as t; 	0.274390136661707
20553786	17322	mysql sum columns across tables and group by	select bsm, sum(t.att) - sum(t.re_org) from (select bsm, `date`, `hour`, att, re_org from t1 union all       select bsm, `date`, `hour`, att, re_org from t2 union all       select bsm, `date`, `hour`, att, re_org from t3 union all       select bsm, `date`, `hour`, att, re_org from t4      ) t group by bsm; 	0.00344930606256204
20553865	10276	sql how to find out which table the data is located	select pub.serial,     (select count(*) from boo where boo.num = pub.serial) as boo_count,     (select count(*) from per where per.num = pub.serial) as per_count from pub order by pub.serial 	0.00132762344034064
20554652	8192	creating a csv list from a sql table	select stuff((select ';'+ email as [text()] from person for xml path('')),1,1,''); 	0.00292317944592821
20556551	7756	php sql selecting the same column with two different values	select table_01.id, table_01.price, t21.price as 'group1 price',    t22.price as 'group2 price'   from table_01    left join table_02 t21   on table_01.id=t21.id and t21.group= '1'   left join table_02 t22   on table_01.id=t22.id and t22.group= '2' 	0
20556814	8884	mysql get current highest priced items	select id, product_id, value, change_date from prices join (select product_id, max(change_date) as recent_date       from prices       group by product_id) as most_recent   on prices.product_id = most_recent.product_id     and prices.change_date = most_recent.recent_date order by value desc limit 20; 	0
20557799	34331	oracle query group by type	select case when type in ('a', 'b') then type else 'others' end as type,        sum(qty) as qty   from x group by case when type in ('a', 'b') then type else 'others' end order by 1 	0.605762525901826
20559685	30425	how to check whether a table is empty(truncated already) or not in php?	select count(id) from table limit 1. 	0.00495400185120708
20559746	7168	filtering records from database	select d.* from informationdata d where not exists     (select * from filters f inner join luserstofilters l on f.id=l.filterid     where (d.title like '%'+f.keyword+'%' or d.description like '%'+f.keyword+'%')     and l.userid = @userid) 	0.00298360469893256
20560535	809	how can i group days depending on the database field value in php	select group_concat(day) days, concat(from_time, ' to ', to_time) times from yourtable group by from_time, to_time 	0
20561112	39635	transpose row as column in mysql	select   student,   max(if(month = 'jan', `sub-1`, null)) `jan-sub-1`,   max(if(month = 'jan', `sub-2`, null)) `jan-sub-2`,   max(if(month = 'jan', `sub-3`, null)) `jan-sub-3`,   max(if(month = 'feb', `sub-1`, null)) `feb-sub-1`,   max(if(month = 'feb', `sub-2`, null)) `feb-sub-2`,   max(if(month = 'feb', `sub-3`, null)) `feb-sub-3` from   trans group by   student 	0.00793176758791481
20561612	10813	count() pagination with one-to-many relation and where in	select      count( distinct users.id) from     users     left join users_sections on (users.id = users_sections.user_id)      left join sections on (users_sections.section_id = sections.id) where      sections.id in (2,3) 	0.773018455119947
20563331	22127	select from 3 joined tables with condition?	select r.id, rc.id, c.name, r.serial, rc.requestcondition     from request r     inner join customer c on c.id=r.custid     inner join requestcondition rc on rc.requestid=r.id     inner join (        select max(id) as rcid         from requestcondition         group by requestid     ) latest on latest.rcid=rc.id 	0.00341915259680152
20565040	40032	compare elements by linked server rules for values (mssql+ linked mysql)	select t.student,      t.grade,      t.expected,      case          when m.val > m1.val then 'above target'         when m.val < m1.val then 'below target'         else 'on target'         end as achievements      from students t left join (select * from openquery(mysql, 'select * from grade')) m on t.grade = m.grade left join (select * from openquery(mysql, 'select * from grade')) m1 on t.expected = m1.grade 	0.00335267706516367
20565172	22438	display records per day	select dayofmonth(date) as day, group_concat(name separator ', ') as name from table1 group by day 	0
20565426	17639	how can i create a sensible report in sql	select report_id, no_of_crimes, fk1_time_id, areatable.name, fk3_crime_type_id from yourtable join areatable on yourtable.fk2_area_id = areatable.id 	0.525722972622753
20568983	19140	fetching columns of a multiple rows in one row	select * from (    select attr_name, attr_value    from   test ) pivot (  min(attr_value)    for attr_name in ( 'abc','ghi','mno' ) ) 	0
20569639	1562	count id numbers	select o.`name` , count(o.id) `count`  from  computers c left join operatingsystems o on (c.operatingsystemid  =o.id) group by o.id 	0.00347227744093567
20570603	3979	sql join where string is contained within another table field	select table_1.name from table_1 inner join table_2 on table_2.fielda like '%' + table_1.name  + '%' 	0.0145741572865518
20572126	19847	how to run sql code on a subsets of data (grouped by without aggregation)	select  "source system",         "customer id",         "customer name",         case when row_number() over(partition by "customer id"                                      order by case when "source system" = 'sap'                                                  then 0                                                  else 1                                              end)                              = 1 then 'y' else 'n' end as "survivor" from    t 	0.0143656629862347
20573090	32373	query returns null instead of 0	select ifnull(count,0) as count,thedate as date from        (select @month := @month+interval 1 month as thedate        from service_jobs,(select @month:='$lastyear' - interval 1 month)as t1        limit 13)as t2 left join        (select count(work_id_num)as count,date        from service_jobs        where (date between '$lastyear' and '$date')           and job_type like 'street light'         group by year(date), month(date)) t3  on (year(thedate) = year(date) and month(thedate) = month(date)) order by thedate; 	0.233620507175906
20573226	21424	mysql newbie - select all false in one to many	select d.id, d.hostname, n.dns from devices d     left join network_card n on d.id = n.device_id where d.hostname != substring(n.dns, 1, length(d.hostname)) 	0.015425361889364
20573737	21113	find number string in string and count	select number, count(*) from (   select substring(n, 1, 2) as number   from l     union all     select substring(n, 4, 2)   from l     union all     select substring(n, 7, 2)   from l   ) a group by number; 	0.000722787312293168
20575162	22775	creating a view of multiple joins	select   u.id,   u.gradyear,   w.salary,   s.hasgradschool from dbo.students u outer apply (   select     sum(wages) as salary   from dbo.wages   where id = u.id     and year = u.gradyear+1 ) w outer apply (   select top 1     1 as hasgradschool    from dbo.gradschool   where id = u.id     and year = u.gradyear+1 ) s where u.graduated=1 	0.500054422525329
20576326	5198	why do i get a "indexed columns are not unique" error when trying to add a unique index to a sqlite table?	select charcolumn,        intcolumn,        count(*) as count from mytable group by charcolumn,          intcolumn having count > 1 	0.0354396990139765
20576763	24975	select rows from table based on data from another table	select  m.*, s.name from    dbo.mentor m join    dbo.student s on exists  (     select  x.languageid     from         (         select 1 as languageid where s.english = 1 union all          select 2 as languageid where s.french = 1 union all          select 3 as languageid where s.german = 1     ) x     intersect     select  y.languageid     from         (         select 1 as languageid where m.english = 1 union all          select 2 as languageid where m.french = 1 union all          select 3 as languageid where m.german = 1     ) y ) order by m.name 	0
20577042	19978	add results of three subqueries	select item_name, sum(quantity) as quantity from (select item_name_1 as item_name, sum(quantity_1) as quantity from table1 group by item_name_1 union all select item_name_2 as item_name, sum(quantity_2) as quantity from table1 group by item_name_2 union all select item_name_3 as item_name, sum(quantity_3) as quantity from table1 group by item_name_3) as abb1 group by item_name; 	0.0889090638747013
20577181	39402	how do i sum the result of 2 group by queries	select player_id, sum(total) total from (   select winner_id player_id, count(*) total from results group by winner_id   union all   select loser_id, count(*) from results group by loser_id ) s group by player_id order by total desc 	0.00412851268410565
20577401	11143	combining multiple where conditions in mysql select query	select id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) as distance from markers where date_field between 'date1' and 'date2' having distance < 25 order by distance limit 0 , 20; 	0.306074801092535
20578720	6649	can you only use one select command w/sqldatasource	select x.a , y.b from (select column1 as a from tablename) x, (select column2 as b from tablename) y 	0.0863239738965089
20583748	32321	retrieving data from multiple tables base on id	select p.*, group_concat(colors separator ',') colors from products p left outer join colors c on p.pcode=c.pcode group by p.pcode; 	0
20585564	21333	how to use select command by another select result? (mysql, php)	select *  from post where postid in  (select postid      from save_board_post      where boardid= 'testboard'); 	0.0635292941273051
20586081	32707	assign incremental seed to field based on another column value	select    id,   groupid,   topid,   dense_rank() over (order by topid asc)  from tracker  order by topid; 	0
20587105	22573	aggregate two different events tables with a single query	select  p.id,         p.title,         coalesce(v.totalview, 0) totalview,         coalesce(u.totalupvote, 0) totalupvote from    posts p         left join         (             select  post_id,                     sum(v.value) totalview             from    views v             group   by post_id         ) v on p.id = v.post_id         left join         (             select  post_id,                     sum(u.value) totalupvote             from    upvotes u             group   by post_id         ) u on p.id = u.post_id 	0.00121090194127911
20589890	23785	mysql query - select join if latest record in join table contains a specific value	select activity.id as activityid     , activity.type     , activity.date     , clients.id as clientid     , clients.name from activity left join activity as other_activities   on activity.clientid  = other_activities.clientid     and activity.date < other_activities.date left join clients   on activity.clientid = clients.id where activity.type = 500   and other_activities.clientid is null; 	0
20590380	36797	sql query in a php based website	select `desc`,`user` 	0.0439953809313996
20591660	37109	how to use a left outer join with a filter that returns the first row in a child table?	select p.partyid,    a.addressline1,    a.city,    a.state,    a.postalcode from party p left join (select a1.partyid,            a1.addressline1,                 a1.city,             a1.postalcode,             isdeleted,                 a1.state, row_number() over (partition by partyid order by a1.partyid) as rownum from [address] a1 where isdeleted = 0) a on a.partyid = p.partyid and a.isdeleted = 0 and rownum = 1 order by p.partyid 	0.00226825379380369
20593428	20019	mysql query for last rows that have a specific field	select m1.* from yourtable t1     left join yourtable t2 on (t1.id= t2.id and t1.topicid < t2.topicid) where t2.id is null; 	0
20594016	40862	having clause on sum column	select p.id, p.project_name,        sum(case when r.type_code in ('good','very_good') then 1                 when r.type_code in ('bad','very_bad') then -1                 else 0 end) score from   record_project as rp        join project as p on p.id = rp.project_id         join record as r on r.id = rp.record_id  group  by p.id, p.project_name having sum(case when r.type_code in ('good','very_good') then 1                 when r.type_code in ('bad','very_bad') then -1                 else 0 end) <= 1 order  by score desc  	0.227155053097294
20594071	21835	how to add a column in database using code and calculation using database value	select order_id, customer_name, dress_type, dress_price, quantity, date_of_pickup, payment_status, dress_price* quantity as total" 	0.00884439210622546
20595467	25908	execute other sql query if first one was empty for set of elements to eliminate php foreach loop	select * from item_list where itemname = ( select itemname     from   item_list     where  itemid = '17'     and    (itemsub ='1' or itemsub ='0')     order  by itemsub desc     limit  1) or itemname = ( select itemname     from   item_list     where  itemid = '57'     and    (itemsub ='0' or itemsub ='0')     order  by itemsub desc     limit  1 ) 	0.000131741642075334
20602291	25964	fetch mysql data ignore some value	select name,country from person where name!='jonathan' and name!='fedrick' and country!='italy' 	0.00184356136131053
20604051	30408	set default value in query in sql server	select      count(*)     , location_tbl.locname as location    , 'violated request' as status_name from             transaction_tbl  left join    location_tbl on transaction_tbl.locid = location_tbl.locid   left join     status_tbl on transaction_tbl.status = status_tbl.status where           transaction_tbl.status='3' and    transaction_tbl.locid in (5) and     datediff(n, transaction_tbl.paydate, getdate()) > 10 group by     location_tbl.locname, status_tbl.status_name 	0.0951573210643526
20604347	36003	selecting leaderboard using mysql	select player_id, count(correct_id) correctanscnt, sum(correct_id), sum(reward)  from questions_correct  group by player_id order by correctanscnt desc 	0.331066069334215
20605916	26183	result consisted of more than one row	select trigger_name    from information_schema.triggers   where trigger_schema = schema()    and event_object_table = 'proy'; 	0.000809952181899775
20606347	29379	calculate two different sum with two different where in one query in mysql	select sum(case when mi.myitem_order_id = 'somevalue'               then mi.myitem_price * msi.my_item_quantity end) order_sum,        sum(case when mi.myitem_location_id = 'somevalue'               then mi.myitem_price * msi.my_item_quantity end) location_sum    from sometable 	0
20606374	32624	how do i combine multiple select statements in separate columns?	select count (distinct vid) as sum_of_sec ,(select sum (amount*paidperitem) from pdalis where pid = 501 ;) as sum_of_a , (select sum(amount * paidperitem) from pdalis where pid in (500,504);) as sum_of_p  from pdalis where pid in(500,504); 	0.00218854453679172
20607347	2012	sum of columns in a row in sql server 2010	select     mid,   sum(cast(case when mat1='n/a' then null mat1 else  as int)) as mat1,   sum(cast(case when mat2='n/a' then null mat2 else  as int)) as mat2,   sum(cast(case when mat3='n/a' then null mat3 else  as int)) as mat3,   sum(cast(case when mat4='n/a' then null mat4 else  as int)) as mat4,   sum(cast(case when mat4='n/a' then null mat4 else  as int)) as mat4,   sum(cast(case when mat5='n/a' then null mat5 else  as int)) as mat5 from mat group by mid 	0.00742840120502777
20607509	9643	new column with rowtotals	select id,         nr,         cost,         a.subtotal as total  from   table1         inner join (select nr,                            sum(cost) as subtotal                     from   table1                     group  by nr) as a                 on table1.nr = a.nr 	0.0862513659213274
20607831	1880	how to handle conversion from type 'dbnull' to type 'integer' is not valid	select coalesce(sum ([totaltime]), 0) from [line1log] where ([state] = 'test') 	0.407054309323344
20608651	22545	order by using polish letters	select   name from     mytable order by name collate sql_polish_cp1250_cs_as_ki_wi 	0.240742937852752
20608784	17057	query pulling users back which don't meet criteria of where statement	select a.user_id as userid, a.group_id, a.role,  b.id, b.name, b.last_name from b_sonet_user2group a  inner join b_user b on a.user_id = b.id  where a.group_id = $groupid  and (a.role = 'a' or a.role = 'e') 	0.000833599779063368
20610211	34314	grouping the data after fetching the query	select distinct month,product,sum(mod)/tot_cnt as mod_p,sum(sev)/tot_cnt as sev_p  from table x  group by month, product 	0.0135349835388263
20610762	29561	select one specfic row from each user by a different time	select pid, frage, antwort, user, created_at from antwortenverlauf a1 where frage =  'risiko: wie empfinden sie die kommunikation mit dem kunden?'     and (user, created_at) in (select user, max( created_at )                                 from antwortenverlauf a2                                where a1.frage=a2.frage                                 group by user) order by created_at desc 	0
20611098	20894	sql, and, or in one statement	select *  from  `users`  where (    fname like  '%toms%'    or lname like  '%toms%' ) and (    bdate < "1991-12-03"    and regdate > "2000-12-03"    and lastactivity > "2000-12-03" ) limit 0 , 30 	0.372642026257746
20613900	39566	joining columns from different tables, and to get the total of the joined columns	select yesterday, today  from     (select report_account_receivable_yesterday.balance as yesterday     from report_account_receivable_yesterday) yesterday,    (select report_account_receivable_today.balance as today     from report_account_receivable_today) today,     (select id, name, balance, debit, credit, a.type     from        (select min(l.id) as id, to_char(l.date::timestamp with time zone, 'yyyy:iw'::text) as name,           sum(l.debit - l.credit) as balance, sum(l.debit) as debit, sum(l.credit) as credit, a.type        from account_move_line l) as id    ) ssssssssssssssssssssssssss     left join account_account a on l.account_id = a.id where l.state::text <> 'draft'::text group by to_char(l.date::timestamp with time zone, 'yyyy:iw'::text), a.type; 	0
20616387	34759	sql query same exposed names	select       t.trades_id1,       n1.name as trade1name,       t.trades_id2,       n2.name as trade2name    from       trades t          join name n1 on t.trades_id1 = n1.nameid          join name n2 on t.trades_id2 = n2.nameid 	0.0107445477839046
20617083	22955	sql server 2008 - cannot order data using formatted date	select      substring(convert(varchar(8), convert(datetime, [tran_date], 103), 3), 4, 5) as 'date',      sum([tran_amount]) as 'amount'  from [transactions]  group by convert(varchar(6), convert(datetime, [tran_date], 103),112),          substring(convert(varchar(8),           convert(datetime, [tran_date], 103), 3), 4, 5)   order by convert(varchar(6), convert(datetime, [tran_date], 103),112) 	0.394827183189861
20618423	28072	sql - how to pull records from different tables where the table relates to a primary key	select        tableb.partno       ,tableb.orderno       ,tableb.currency       ,tableb.purch_price       ,tableb.mutation   from   tablea, tableb   where tablea.partno = tableb.partno; 	0
20618717	40559	distinct count per day sql	select sum(numipsperday) from (select date(thedaycol) as d, count(distinct t.ip) as numipsperday       from track t       group by date(thedaycol)       ) t; 	0.00021093815317757
20619128	26729	return the "diff" between two sequential results	select   id, unix_timestamp(measuredtime), measured, what,          measured - @prev as diff, @prev := measured from     stats, (select @prev := null) as init where    what = 5      and measuredtime > now() - interval 24 hour order by id desc 	0.000433666300743521
20619459	5991	how do i check if the current time is between two times in sql?	select top 1 'yes' from    dbo.salesorder where datepart(hour, getdate()) between 7 and 16 	0
20619679	27829	use some row values as column sql	select sum(amount) as amount,  sum(`type`='kill') as `kill`, sum(`type`='death') as `death`, sum(`type`='win') as `win`,  gamemode_statistics.name as playername  from gamemode_statistics  inner join type on gamemode_statistics.type_id = type.id  group by gamemode_statistics.type_id, playername 	0.00700734888972404
20620669	21520	count distinct records (all columns) not working	select count(*) from (    select distinct * from your_table ) x 	0.00348875563086505
20621024	2016	mysql fulltext search for words at beginning or end of string	select `idcolumn` from `sometable`  where match(`textcolumn`) against ('foo') having `textcolumn` like ('%foo'); 	0.0132030710921233
20621893	40957	sub query in the from clause in sql	select      partno_aud,      partno_ing,      costset_aud,      itemver_aud,      procno_aud,      procver_aud,      procstage_aud,     allitem_aud,      costerr,      dbo.ssi_davl_func('costerr', costerr, 'e') as description,     qty  from dbo.mbi030 a     inner join (         select              partno_b02par,              partno_b02com,              qtyoff / (100 - psloss) * 100 as qty          from dbo.mbb020) b     on a.partno_aud =b.partno_b02par           and a.partno_ing =b.partno_b02com where (partno_ing <> n'')      and (procno_aud <> n'')      and (costerr <> n'00') 	0.567085315643702
20622318	38765	sql query - select usernames and sum their row	select username, sum(paymentvalue) as sumofpayments from thetable group by username 	0.000880129407677443
20628903	37379	compare 2 mysql tables with common field, identify data that is only in 1 of the tables	select sq.filename  from   (select filename          from   photos          union all          select filename_housekeeping as filename          from   housekeeping) as sq  group  by sq.filename  having count(*) = 1 	0
20630518	32819	mysql query inner join on same table with different conditions	select l.email from transactions as l left join transactions as r on r.email = l.email and r.state = 'paid' and r.date_paid < '2013-12-01 00:00:00' where r.email is null and l.state = 'paid' and l.date_paid <= '2013-12-31 23:59:59' 	0.0372694943936049
20631982	24851	mysql: select non matching rows in a join	select table1.*  from table1 left join table2 on table1.id in (table2.matchid1,table2.matchid2) where table2.matchid1 is null and table2.matchid2 is null 	0.00373478554364611
20633409	8152	is there a way to format mysql celldata via the column type/attributes?	select     concat(ucase(substring(t.name, 1, 1)), lcase(substring(t.name, 2))),     replace(format(t.number, 0), ',', ' ') from table t 	0.108373002187035
20634365	11833	select from mysql datetime field where the year doesn't matter	select * from table1 where dayofmonth(datecolumn) = 17 and month(datecolumn) = 12 	0.000838406684268428
20635761	33091	how to get distinct results in one row from two column of same table?	select group_concat((case when senderid = 1 then recid else senderid end) separator ', '                    ) as trans  from test  where senderid = 1 or recid = 1 ; 	0
20637346	29896	create php arrays with dates and number of orders extracted by month from sql	select date_format(`date`, '%y%m') as `ym`, count(*) as `count` from `orders` group by `ym` 	0
20637623	12943	loop through select statement and assign ids 1-16	select  rowdescription,         (row_number() over (order by rowdescription)-1) % 16 + 1 as assignedid from    yourtablename 	0.0102413044417549
20640094	30314	get the average of one column of dates as day	select assetid, datediff(d, min(datecol), max(datecol)) as days from table group by assetid 	0
20640656	28641	joining parent with one example of child	select a.* from (    select p.*, c.child_id, some_field_of_children    from  parents p     left join children c on p.id = c.parent_id ) a where a.child_id = ( select min(b.child_id) from children b where b.parent_id = a.parent_id) 	0.00127208235526327
20641455	8392	sql query to pivot data	select category,   max(case when name = 'test1' then date end) test1date,   max(case when name = 'foo2' then date end) foo2date from yourtable group by category; 	0.522493484383771
20642368	20928	inner join for a single table - mysql	select c1.coach_code as coach1, c2.coach_code as coach2, c1.year_of_birth from coaches as c1 join coaches as c2 on c1.year_of_birth = c2.year_of_birth and c1.coach_code < c2.coach_code 	0.19831884176334
20643705	9646	match where value is null in sparql	select ?label ?img where { ?uri rdfs:label ?label.  optional { ?uri vtio:hasimage ?img. } } 	0.0577835812298389
20645142	38263	summing a count (with group by)	select t.processed as title,         coalesce(sum(clh.count), 0) + coalesce(sum(ch.count), 0) as ckos from title t left join (select bib#, count(*) as count            from circ_longterm_history            where cko_location = 'dic'            group by bib#) clh        on clh.bib# = t.bib# left join (select i.bib#, count(*) as count            from item i            join circ_history ch              on ch.item# = i.item#            where ch.cko_location = 'dic'            group by i.bib#) ch        on ch.bib# = t.bib# group by t.processed order by ckos desc 	0.124488001731878
20646126	11691	selecting distinct values in mysql	select distinct leverancier.lev , afdnaam from leverancier join inkart on leverancier.lev = inkart.lev join artikel on inkart.art = artikel.art join verkart on artikel.art = verkart.art join afdeling on verkart.afd = afdeling.afd where afdnaam = 'hobby' except select distinct leverancier.lev , afdnaam from leverancier join inkart on leverancier.lev = inkart.lev join artikel on inkart.art = artikel.art join verkart on artikel.art = verkart.art join afdeling on verkart.afd = afdeling.afd where afdnaam <> 'hobby' 	0.00455622266472133
20648062	20060	getting a total amount from a column for month/year for each user	select username, concat(year(date), month(date)), sum(downloadmb) from adslaccount group by username, concat(year(date), month(date)) 	0
20651235	3882	columns to rows queries	select company      , item      , max(case when year = 1 then value end) y1      , max(case when year = 2 then value end) y2      , max(case when year = 3 then value end) y3   from       ( select company, year, 'revenue' item, revenue value from my_table        union        select company, year, 'cost',cost from my_table        union        select company, year, 'profit',profit from my_table      ) x  group     by company      , item  order      by company      , field(item,'revenue','cost','profit'); 	0.00428252953804855
20652987	5305	count total days between current day (sql)	select datediff(day, getdate() , dayconfirm) 	0
20652996	27013	select distinct query / subquery	select user_set, read, last_updated, user_id, pk_id from message_interaction_log  where (user_set, last_updated) in (   select user_set, max(last_updated)   from message_interaction_log   where user_id = 2002   group by user_set ) 	0.505390802967342
20653232	37826	mysql select all from one table and check another table for id and status	select p.*, g.id, g.hol from pictures as p   inner join galleries as g on g.id = p.gallery_id where p.views > $views and g.hold <> 1 order by p.rating(?) desc  limit $index, $pics_per_page; 	0
20653309	10333	convert selected column values to another row using select with the same id part2	select a1.id, a.1status, a1.timestamp, a2.status, a2.timetstamp from timetable a1 left join timetable a2 on a2.id=a1.id and a2.status = 'out' where a1.status = 'in' 	0
20653446	29443	select minimum from maximums of groups	select min(billed_at) from (select max(billed_at), currency from bills group by currency) as tab 	0.000680413162245581
20655494	22723	query and subquery on the same table	select b.*   from yourtable a   left join        yourtable b     on (    a.patient_id = b.patient_id         and a.dateofservice = b.dateofservice)  where a.cptcode = "some value" 	0.0169905902850101
20655636	15173	sql count non existing item	select a.status, count(distinct g.id) statuscnt from (select 'ok' status from dual       union        select 'nok' status from dual       union        select 'pending' status from dual       union        select 'rejected' status from dual      ) as a  left join groups g on a.status = g.status  group by a.status; 	0.00471370307882296
20656196	9921	sql select... in result order	select styid     from `styles`     where zyid in ['abcd9876','bcde0000'] order by field(zyid, 'abcd9876','bcde0000') 	0.245237588042683
20659037	23181	sql count on dates	select      count(pm.dateapprcvd) as [dateapprcvd],      u.fullname as [advisor]  from      tbl_profile_mortgage as pm      inner join tbl_profile as p on pm.fk_profileid = p.id      inner join tbl_user u on p.advisor = u.userid  where      (         dateapprcvd between '01-nov-2013 00:00:00.000' and '30-nov-2013 23:59:00.000'          or         dateapprcvd is null     )     and pm.accelind '1'      and u.fullname in ('colin sneddon ','graeme hastie','jonathon bede pratt','mark reidy','neil jones','nigel crook','sharon parouty','tom mcsherry') group by u.fullname 	0.0242184926430058
20660159	9000	summing amount attribute according to some entry in other attribute	select     amount   ,currency   ,(select sum(amount) from tablename where currency = 'usd' groupby currency) as usd_sum   ,(select count(*) from tablename where currency = 'usd) as usd_count ..... repeat for other currencies from tablename 	0
20661005	6249	postgresql selecting each row from two temporary tables and comparing their values	select * from foo   cross join bar where foo.age > bar.age 	0
20663067	4	count for each row on mysql	select      c.catnome as nome,      c.catid as id,     count(p.catid) as the_count   from aux_categoria c  left join tb_pinturas p on(c.catid = p.catid) group by c.catnome,c.catid     order by c.catnome 	0.000149642935350804
20663908	1644	for xml multiple control by attribute in tree concept	select @data.query('   element main {     for $s in main/sample     return element sample {       $s/@*,       for $n in $s/node       return element node {         for $i in node/*          order by $i/@order         return            if ($i/self::tree)           then element tree { $i/@testid }           else element tree-order { $i/@testid }         }       }     }     }') 	0.0787428700300618
20664361	6210	compare two column dates return if they are within 6 months	select distinct m.number  from jm_people p inner join master m on p.accountid = m.number inner join jm_subpoena s on m.number = s.number inner join jm_people p2 on p.pid = p2.pid inner join master m2 on p2.accountid = m2.number inner join jm_subpoena s2 on m2.number = s2.number and m.number != m2.number where datediff( mm, s2.daterequested, s.daterequested) < 6 or datediff( mm, s2.daterequested, s.daterequested) = 6  and datepart( dd, s2.daterequested) <= datepart( dd, s.daterequested) 	0
20666256	41154	capturing a time frame	select * from table where (interview_date between '2012-01-01 00:00:00' and '2012-05-31 23:59:00') 	0.118328394821724
20666335	12669	sql query - divide two numbers from same column	select convert(varchar(3), ta_due_date-28, 100) as month,  ta_task_id as ppm,  min(case when f_task_ans.ta_ans_question like '%total no. contractors on e-learning inducted report%' then f_task_ans.ta_ans_answer end) +0.0   / min(case when f_task_ans.ta_ans_question like '%total no. contractors on e-learning user list%' then f_task_ans.ta_ans_answer end)    as percentage from f_task_ans inner join f_tasks on f_task_ans.ta_ans_fkey_ta_seq = f_tasks.ta_seq where ta_ans_answer <> '' and f_tasks.ta_fkey_ctr_seq = 126 and (f_task_ans.ta_ans_question like '%total no. contractors on e-learning user list%' or     (f_task_ans.ta_ans_question like '%total no. contractors on e-learning inducted report%') and (ta_hist_status is null or ta_hist_status = 'complete') and ta_task_id like '%6025' and ta_due_date >= getdate()-360 and ta_due_date <= getdate()+7 group by convert(varchar(3), ta_due_date-28, 100),ta_task_id 	6.0305576638887e-05
20667736	29011	find row based on set of foreign rows	select conversation_participant.conversation_id as conversation_id   , sum(if(members.participant_id in ($list),1,0)) as member_count   , count(*) as total from conversation_participant join conversation_participant as members   on members.conversation_id = conversation_participant.conversation_id where conversation_participant.participant_id = $participant group by conversation_id having member_count = total   and member_count = $qty; 	0
20670031	16518	oracle sql to take the first record in a group by clause	select id, max(created_dt) from table group by id 	0.00139801244006533
20670291	6789	order count of customer_id by posts for category no	select customer_id, category_no, count(1) as total_post from category   group by customer_id, category_no  order by count(1) desc; 	0.000278739676794794
20670403	21000	how to get 5 last record in the sqlite db in android?	select * from table order by somecolumn desc limit 5 	0
20671777	8963	find if one column contains another column	select *   from table  where instr(first_name, last_name) >= 1; 	0
20671944	15971	mysql howto select unique values of column 2 ordered by column 1?	select distinct column2 from (     select column2      from mytable      order by -column1 ) as a; 	0
20672016	39883	ssrs query for only data from current quarter?	select * from yourtable where date >= dateadd(qq,datediff(qq,0,getdate()),0)     and date < dateadd(dd,1,dateadd(qq,datediff(qq,-1,getdate()),-1)) 	6.86165752712412e-05
20674325	27810	how to dynamically create multiple select statement and store it in a datatable	select  test_result.stud_id, max(case when test_result.test_info_id =1 then test_result.test_score end) as quiz_1, max(case when test_result.test_info_id =2 then test_result.test_score end) as quiz_2, max(case when test_result.test_info_id =3 then test_result.test_score end) as quiz_3, . . .  from test_result left join test_info    on test_result.test_info_id = test_info.test_info_id  where test_info.test_type_id = 1 and test_info.test_num = 1 group by test_result.stud_id; 	0.163028142766156
20674673	30265	sql joining query how to	select  date,  sum(case when recordtype = '1' then 1 else 0 end) as count_unique1, sum(case when recordtype = '2' then 1 else 0 end) as count_unique2, sum(case when recordtype = '3' then 1 else 0 end) as count_unique3 from interview group by date 	0.255091218153408
20674734	4049	how to get column data in column names in query?	select prod, sum(case when cust='bob' then qty else 0 end) as bob, sum(case when cust='rob' then qty else 0 end) as rob from t group by prod 	0.000106008738629828
20675041	29473	how to fetch data message wise?	select t.thread_id, t.message_id, t.tomsg, t.frommsg, t.msg, t.time, t.readstatus  from (select t.thread_id, t.message_id, t.tomsg, t.frommsg, t.msg, t.time, t.readstatus        from thread t order by t.message_id, t.thread_id desc      ) as t group by t.message_id 	0.0033106349564676
20675435	7439	sql sum function giving different data every time running query	select sum(convert(money, gl_amount)) gl_amount from tablea 	0.0896677541631242
20675450	3884	truncate table with foreign key	select  sysobjects.[name] as "constraint name",         tabls.[name] as "table name",         cols.[name] as "column name" from sysobjects inner join  (select [name],[id] from sysobjects) as tabls on tabls.[id] = sysobjects.[parent_obj]  inner join sysconstraints on sysconstraints.constid = sysobjects.[id]  inner join syscolumns cols on cols.[colid] = sysconstraints.[colid]  and cols.[id] = tabls.[id] where sysconstraints.status in (1, 3) order by [tabls].[name] 	0.00165253215116683
20675525	2044	extract xml value from clob	select extractvalue(xmltype.createxml(transaction_document), '/transaction/transcache/am/txn/eo/perabsenceattendanceseorow/replacementpersonid') from   hr_api_transactions  where  lengthb(to_char(substr(transaction_document,1,4000)))<>0; 	0.000829879293173779
20675778	7208	needing assitance getting orders in last 2 quarters	select c.cust_id, sum(if(quarter(od.orders) = 1, od.order_price * od.quantity, 0)) quarter1,         sum(if(quarter(od.orders) = 2, od.order_price * od.quantity, 0)) quarter2,         sum(if(quarter(od.orders) = 3, od.order_price * od.quantity, 0)) quarter3,         sum(if(quarter(od.orders) = 4, od.order_price * od.quantity, 0)) quarter4 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  where year(od.orders) = year(current_date()) - 1 group by c.cust_id 	0
20677072	32796	get data from a table with my foreign key?	select * from billeder left join album on billeder.fk_album_id = album.album_id 	5.2527352533809e-05
20679263	11914	column as a result of difference of two other columns	select pnr_from, pnr_to, pnr_to - pnr_from as how_many from (     select (         select coalesce(max(pnr)+1,1)         from pord         where pnr < p.pnr         ) as pnr_from,          p.pnr - 1 as pnr_to,         von     from pord p     where p.pnr != 1 and not exists (         select 1         from pord p2         where p2.pnr = p.pnr - 1         )         and pnr > 300 and pnr < 600 ) t order by von 	0
20679280	22962	sql query not bringing back correct records	select bs.[id],bs.[warehouseno],bs.[customer],bs.[site],bs.[vendorno],bs.[description], bs.[actualqty],bs.[baseqty], (bs.[baseqty] - bs.[actualqty]) as placeorderqty from [dbo].[stockcontrolbasestock] as bs left join [dbo].[stockcontrolstockorder] as so on bs.id = so.basestockref where (bs.[actualqty] + iif(so.orderqty is null, 0, so.orderqty)) <> bs.[baseqty] and bs.[actualqty] is not null and bs.[baseqty] is not null 	0.617788092418397
20681668	39891	sql sum values from different columns based on condition	select     select datepart(year, date) as [year],     datepart(month, date) as [month],     sum(coalesce(nullif(actual,0), nullif(estimated, 0), original) from yourtable group by datepart(year, date), datepart(month, date); 	0
20683002	36012	sql statement to return the current step in a list of steps that should be passed through and whether the process has ended or not	select * ,case when t1.approved=0 then 'ended'       when t1.approved=-1 then 'not ended'       end as stat from (select name, position, approved from table1 t2 where  (case when approved=0 then 1       when position =(select max(position) from table1) and approved=1 then 1         when (position= 1 and approved=-1) or (approved=-1 and 1=(select approved from table1 t1 where t1.position=t2.position-1))then 1  else 0 end) =1        order by position)t1 limit 1 	0.000628519408308753
20684071	9985	query for equal decimals in row	select t.* from t order by q1, q2; 	0.0990597614667131
20684656	35569	mysql sum plus count in same query	select product.id, (sum( ifnull(ur.rate,0) + ifnull(ar.rate,0) ) / (count(ur.rate)+count(ar.rate))) from products as product left join users_rate as ur on ur.id_product = product.id left join anonymous_rate as ar on ar.id_product = product.id group by product.id 	0.0225703480988182
20685657	23528	mysql: need to query for missing records from various start dates	select distinct id from table2 t2 where t2.tran_date < now() - interval 7 day and       not exists (select 1                   from table2 t2a                   where t2a.id = t2.id and                         datediff(t2a.tran_date, t2.tran_date) = 7                  ); 	0.000364111773098487
20685861	33518	how to get differents values 'types' from table creating virtual columns - mysql	select  e.id_emp  ,e.name_emp ,(case when sum(r.type_req=1) is null then 0 else sum(r.type_req=1) end ) type_req1 ,(case when sum(r.type_req=2) is null then 0 else sum(r.type_req=2) end ) type_req2 from  tb_employee e left join tb_detail d on (e.id_emp=d.id_emp) left join  tb_requirements r on (d.id_req=r.id_req) group by e.id_emp 	0
20686847	37361	malformed mysql query	select      pl.id, pl.latitude, pl.longitude, pl.userid, pl.time, pl.type, com.id as com_id, com.text, com.time as com_time,     com_usr.name as com_name, com_usr.email as com_email, com_usr.picture as com_picture,     usr.name as com_usr_name,     usr.email as com_usr_email,     usr.picture as com_usr_picture,     usr.type as com_usr_type  from aa_places as pl   left join aa_comments as com on ( pl.id = com.place_id )    left join aa_users as com_usr on  (com.user_id=com_usr.id) left join aa_users as usr on (pl.userid = usr.id) 	0.763246900902945
20687040	25053	mysql join on different column names	select mls_number, city, list_price, bedrooms from bonita_property_res where ... union  select mlsnumber as mls_number, city as city, listprice as list_price, totalbeds as bedrooms from naples_property_res where ... 	0.00205182056562402
20688655	33721	mysql return set if values don't exist	select * from table where id not in (select id from table where key = 'latlng') 	0.00262441043312683
20690965	19822	how do i get values for all months in t-sql	select m.months  as monthsold,d.qtysold as qtysold   from (  select distinct(month(sd.sbindt))as months from dbo.salesdata sd)m   left join      (            select month(sd.sbindt) as monthsold,sum(sd.sbqshp) as qtysold            from dbo.salesdata sd      where  sd.sbtype = 'o'        and sd.sbitem = @part        and year(sd.sbindt) = @year        and sd.defaultlocation = @location    group by month(sd.sbindt)    )d on m.months = d.monthsold 	8.69930077062774e-05
20691588	37642	writing a select query?	select sum(m.fastec_qty)      , sum(m.sourse_qty)      , sum(m.fastec_qty) - sum(m.sourse_qty)      , sum(o.amount)      , sum(m.fastec_qty) - sum(o.amount)    from tbl_main m      , tbl_dorder o   where m.item_id = o.item_id   group by 1, 2, 3, 4, 5 	0.650331009041769
20691808	38284	max statement in sql query	select contract, product, max(enddate) from table1  inner join table2 on table1.contract = table2.contract  group by contract, product 	0.663637212720458
20692591	23267	how to do a conditional branch in ssis	select count(1)as table_count   from information_schema.tables t   where t.table_name = 'mytable'; 	0.747013883952596
20692694	3423	need to set all rows value based on the top row results	select <fields> from table order by <your field> desc limit 1 ; 	0
20694178	34026	finding closest before and after time in mysql	select calibrationid, endcaltime from cpcalibrations where endcaltime < @stabtime order by endcaltime desc limit 1 	0.00286560920391528
20694499	5878	sql query for counts and accessing another tables	select attribute, count(*) from users as u,  (select distinct user_id from y) as y2 where u.user_id = y2.user_id  group by attribute; 	0.00594778102802799
20694660	33111	sql select column value with biggest number of duplicates	select top 1 id_job from job_table group by id_job order by count(*) desc 	8.63309089330489e-05
20696492	40471	date difference between first and last book per each author	select authors.author_id,        max(name.first_name||' '||name.last_name) as full_name,        max(to_char(yearpub,'yyyy')) - min(to_char(yearpub,'yyyy')) as  years from author_name name, books,authors where       authors.author_id = name.author_id and       authors.author_id = books.author_id and       authors.book_id = books.book_id group by authors.author_id 	0
20696837	9259	how to obtain trend from a table for the same column values in multiple row that needs group by	select a.name, a.lastcount, (((a.firstcount-a.lastcount)/a.firstcount)*100) trend from (select a.name, max(if(a.interval = 'last', a.count, 0)) lastcount,               max(if(a.interval = 'first', a.count, 0)) firstcount       from tablea a       group by a.name      ) as a 	0
20697854	33790	mysql query to get only last day of week data from range	select week,        count(*) as total,        sum(case when status = 'fail' then 1 else 0 end) as failcount,        sum(case when status = 'pass' then 1 else 0 end) as passcount from test_report join (select substring_index(work_week, '.', 1) as week,               max(substring_index(work_week, '.', -1)) as last_day       from test_report       group by week) as last_days on work_week = concat(week, '.', last_day) group by week 	0
20698014	27701	filter out one column value depending on other column value	select  t2.* from    (         select  distinct id         from    <yourtable>         ) t1 cross apply         (         select  top 1 *         from    <yourtable> t         where   t.id = t1.id         ) t2 	0
20699636	19763	concatenate multiple rows into one field	select distinct customer,     stuff((             select ',' + cast(policy as varchar(10))             from table1 b             where a.customerid = b.customerid             for xml path('')             ), 1, 1, '') [policies] from table1 a 	0
20701976	23450	sql select and find rows that not exists in other table	select a.* from addressbook a left outer join users u on a.phone = u.phone1 where (u.phone1 is null) 	0.000184018125264901
20702137	11128	how to pass multiple values using stored procedure?	select *  from mytable where charindex(',' + cast(column1 as varchar) + ',', @yourparameter)  > 0 	0.282883032303873
20702966	5940	convert column's type in result of a query	select column1, cast(column2 as varchar(11)) as column2 from yourtable 	0.00726773932288969
20704276	39284	oracle where clause only if a condition exists	select  q.job_queue_id    id_1,      q.job_id          id_2,      j.job_name,      q.queue_date,      q.username,      q.status,      q.processed_date,      q.comments,      q.rowid from rs_new_job_queue q inner join rs_new_job j on q.job_id = j.job_id where (l_role_id>0 and q.username = l_name) or l_role_id <= 0 order by q.processed_date desc; 	0.444557687593333
20705221	22816	is it possible to apply select into a temporary table from another select?	select * into #temptable from (select * from table2) t; 	0.000638374376058714
20705999	30403	convert number int in minutes to time in mysql	select sec_to_time(duration*60) 	0.000792077929438033
20706095	35416	check if table-column contains at least one value != 0	select max(priceeur),max(pricechf),max(priceuk),max(pricerub) from mytable 	0.000174791011735694
20707153	8358	mysql selecting rows with max of a given id	select id, max(score) max_score from yourtable group by id 	0
20707345	26378	sql for displaying query field wise	select u.realname,    sum( if( t.status = 'new', 1, 0 ) ) as new,    sum( if( t.status = 'stalled', 1, 0 ) ) as stalled,    sum( if( t.status = 'open', 1, 0 ) ) as open from tickets t, users u where    u.id = t.owner and    t.status in ( 'new', 'stalled', 'open' ) group by u.realname 	0.0429447120919482
20707665	17261	sql server - how to sum field from multiple table	select * from workheader wh   inner join (select sum(sewingprice) sumsew, workheaderid           from workdetail           group by workheaderid) sew on     wh.workheaderid = sew.workheaderid   inner join (select sum(det.combinationprice) sumcombo, wd.workheaderid           from details det             inner join workdetail wd on wd.workdetailid = det.workdetailid           group by workheaderid) combo on     combo.workheaderid = wh.workheaderid   where wh.workdate = '2013-12-20' 	0.00154545070036401
20707790	10277	echo related table row if not empty - php	select t1.blogid t1blogid, t1.author t1author, t1.date t1date, t1.entry, t2.commentid, t2.author t2author, t2.date t2date, t2.comments from $table_name t1 left join $table_name2 t2 on t1.blogid = t2.blogid where t1.blogid = $postid 	0.00144023523825262
20708220	10194	group rows by time interval	select trip, min(date_time), max(date_time) from (   select  @trip := if(timestampdiff(minute, @date_time, date_time) <= 20, @trip, @trip+1) as trip     , logid     , @date_time := date_time as date_time   from gpslog   join (select @trip := 1, @date_time := null ) as tmp   order by date_time) as triplist group by trip 	0.00612636103693043
20708253	41126	prevent mysql casting string to int in where clause	select delivery_name  from orders  where concat('a',orders_id) = concat('a','985225a') 	0.742092031570227
20709944	19929	search for column names in oracle	select column_name from all_tab_columns    where table_name='mytable' and column_name like '%id%'; 	0.0283840467096272
20711432	14085	day and night averages sqlite	select strftime('%y', fecha) as year,        strftime('%m', fecha) as month,        (select avg(t10_avg)         from ger as g2         where g2.fecha glob strftime('%y-%m*', ger.fecha)           and (g2.hour >= '06' and g2.hour < '20')        ) as avg_day,        (select avg(t10_avg)         from ger as g2         where g2.fecha glob strftime('%y-%m*', ger.fecha)           and (g2.hour < '06' or g2.hour >= '20')        ) as avg_night,        avg(t10_avg) as temp_prom from ger group by year, month 	0.0015725928787808
20716396	22572	retrieve only todays data from sql server database	select * from <table_name>  where  <date_field> >= convert(<date_field>,  datediff(day, 0, getdate()))order by <date_field> desc 	0
20716923	16974	how to filter sql query	select *    from student   where (class regexp '^$param'      or week regexp '^$param'      or name regexp '^$param'      or f_name regexp '^$param'      or avg1 regexp '^$param'      or avgf1 regexp '^$param'      or avg2 regexp '^$param'      or avgf2 regexp '^$param'      or addr1 regexp '^$param'      or ex11 regexp '^$param'      or ex12 regexp '^$param'      or ex13 regexp '^$param'      or ex21 regexp '^$param'      or ex22 regexp '^$param'      or ex23 regexp '^$param'      or addr2 regexp '^$param')    and mail is not null     and mail <> ''  order by class desc 	0.332290701091987
20717681	28254	how to remove blank comments from table?	select table_comment  from information_schema.tables  where table_name ='xxx'    and table_comment is not null   and table_comment <> '' 	0.000481654491715687
20718623	26298	how to find orders from repeat/old customers using sql query?	select customer_id , order_id, order_date from orders where order_date between '20/12/2013 00:00:00' and '20/12/2013 23:59:00' and customer_id in (select customer_id from orders where order_date < '20/12/2013') 	0.000335381091701739
20724433	28669	mysql where condition when intersecting 2 values (comma delimited)	select * from table_name where products regexp "(^|,)[23](,|$)"; 	0.00768640708063475
20725816	31082	select documents that are not tagged	select tags.name  from     tags     left join documents_tags dt on (tags.id = dt.tag_id and dt.document_id = 111) where dt.id is null 	0.0531263958981006
20727184	4285	concat multiple columns with string in oracle	select (ime||  ',' || prez|| ',' || br_tel) "poštari" from postari 	0.0742604195284949
20728509	34389	select distinct with difference	select owner, index_name, text   from (select t.*,                count(*) over(partition by text, index_name) both_match,                count(*) over(partition by text) text_match           from columns_tab t)  where text_match > 1    and both_match = 1; 	0.0364792017670838
20729716	7644	how to sort employee data, based on department count	select eno, ename, salary, e.deptmentid from emp e inner join                  (select deptmentid, count(ename) totalemps                   from emp                  group by deptmentid) sub on e.deptmentid = sub.deptmentid order by totalemps desc 	0
20732476	18586	cartesian product as a result of inner join	select mo.date, mo.title, r.roledescription from movies mo,  inner join role r on r.moviecode=mo.moviecode where r.actorid=2 	0.503589973194706
20733719	21047	join on two databases using postgresql and dblink	select * from a_t1 full outer join dblink('dbname=server_b','select * from b_t1')  as tmp_b_t1 ( a1 serial not null (primary) , a2 character varying(50) ) where a_t1.tmp_b_t1>1 	0.23075205516442
20734827	13687	select products all coming from same supplier region	select x.product_code from  (     select supply.product_code,     dense_rank() over (partition by product_code order by region) rank     from supply     inner join supplier on supply.supplier_code = supplier.supplier_code ) x group by x.product_code having max(rank) = 1 	6.65271583281333e-05
20735846	23986	c# mysql datetime to unix time	select unix_timestamp(str_to_date('dec 23 2013 02:29am', '%m %d %y %h:%i%p')) 	0.0119433735155327
20738462	38376	mysql group by year and count field	select year(register_date) as registeryear,        sum(gender = 'man') as man,        sum(gender = 'woman') as woman        from your_table group by registeryear 	0.00425703147504421
20739132	30293	how to count votes in mysql tables?	select answers.answer_id,sum(if(votes.direction = 0, -1, 1)) as answer_vote  from answers      left join votes on answers.answer_id=votes.answer_id  where      answers.question_id='61'  group by answers.answer_id 	0.0235317730712264
20739358	23250	datetime search in sql	select study_date,start_time,end_time from study where cast(study_date + 't' + start_time  as datetime)  >='2013-12-22t19:12:01'      and cast(study_date + 't' + end_time  as datetime) <='2013-12-23t13:12:14' 	0.29631117073089
20742540	4998	union some two-field tables into one multi-field with first field as key	select [keyfield]      , (max([t1.f1])) as f1      , (max([t2.f2])) as f2      , (max([t3.f3])) as f3      , (max([t4.f4])) as f4      , (max([t5.f5])) as f5 from t1 join t2 on t2.keyfield = t1.keyfield join t3 on t3.keyfield = t1.keyfield join t4 on t4.keyfield = t1.keyfield join t5 on t5.keyfield = t1.keyfield group by t1.keyfield 	0
20743074	25225	find value in different row and get it to particular row	select t1.id, t1.b, t1.c, t2.b as newcolumn from yourtable t1 left outer join yourtable t2     on t1.c = t2.id where t1.c is not null 	0
20743919	38825	search entire table for a keyword	select column_name from information_schema.columns where table_name = 'tablename' 	0.0467584600382008
20746531	4397	get a data from a different table using id	select u.name, r.rank_name  from users as u  left join ranks as r on u.rank = r.rank_id 	0
20746616	33886	add signal - the result of mysql	select nome,data,if(valor<0,concat(valor),concat('+',valor)) as valor from  (  (   select nome, data, valor from `financ_receita`    where data between ('2012-12-01') and ('2013-12-23')  )  union all  (   select nome, data, valor*-1 from `financ_despesa`   where data between ('2012-12-01') and ('2013-12-23')  )   order by data asc ) as mytable where valor != 0 	0.015946136762787
20748841	26248	transforming a 2 column sql table into 3 columns, column 3 lagged on 2	select a.id, a.i, coalesce(min(b.i),'0') from test a left join test b on b.id=a.id and a.i<b.i group by a.id,a.i order by a.id, a.i 	0
20750181	4061	count with distinct	select  shippingid,         count(*) items,         shipdate  from mytable where customerid = 'c1' group by shippingid,          shipdate 	0.140842785084047
20750429	21169	mysql age from date of birth (ignore nulls)	select  case             when user.dateofbirth is null then ""             else year(curdate())-year(user.dateofbirth) - (dayofyear(curdate()) < dayofyear(user.dateofbirth))          end as 'age' from    mytable 	0.00042002907079757
20751218	18813	group mysql results by type - but only in a certain order	select min( timestamp ) from_timestamp,         max( timestamp ) to_timestamp,        max( timestamp) - min( timestamp ) + 1 how_long,        min( id ) from_id,        max( id ) to_id,        status from (     select t.id,            t.timestamp,            if(@last_status = status, @group, @group:=@group+1) group_number,             @last_status := status as status     from table1 t     cross join (        select @last_status := null, @group:=0     ) as init_vars     order by t.timestamp  ) q group by group_number order by from_timestamp 	0.000824563108443192
20751691	6761	join 3 tables of users, friends, chats	select f.frd_id, u.usr_id, u.usr_fname, u.usr_lname, max(c.cht_timestamp) from friends as f left join users as u on u.usr_id in ( select u1.usr_id from users as u1 where u1.usr_id != $user_id) left join chats as c on ( (c.cht_usr_id1=$user_id and c.cht_usr_id2=u.usr_id) or       (c.cht_usr_id1=u.usr_id and c.cht_usr_id2=$user_id) )     where ( (f.frd_usr_id1=$user_id and f.frd_usr_id2=u.usr_id) or     (f.frd_usr_id1=u.usr_id and f.frd_usr_id2=$user_id) )     group by u.usr_id order by  max(c.cht_timestamp) desc 	0.00145839959784337
20752744	27393	how to display 1 name from database	select companyname, count(*) as totalorder from orders o inner join company c on c.companyid = o.companyid group by c.companyname order by count(*) desc 	0.000135541137385374
20753159	13724	how to merge two different field values into one row?	select `date`, uid,        (case when source = 'source1a' then 'source1' else source end) as source,        sum(pageviews) as pageviews from trafficsourcemedium group by `date`, uid,           (case when source = 'source1a' then 'source1' else source end); 	0
20753762	17428	how to do get multiple columns + count in a single query?	select count(*) over (partition by seriesid) as numepisodesinseries,        st.seriesid, st.seriesname, et.episodeid, et.episodename,        ct.createdid, ct.creatorname from series_table st join      episode_table et      on et.ofseries = st.seriesid join      creator_table ct      on ct.creatorid = st.bycreator; 	0.000238017058481787
20754228	41245	<sql> how to edit exists query	select           prcs_sno, year, subsc_canc_yn                                  from tb_pot_ecd_prcs_info inf     where inf.subsc_canc_yn = 'n'     and 'x' in (                 select 'x'                 from tb_pot_ecd_prcs_hist his                 where prcs_ste_cd = 'r01' or second_column= 'r02'                ) 	0.498025493093811
20755994	316	slow insert: select from table	select t1.sku from item_data t1 left join item_table t2 on t1.sku = t2.sku where t2.sku is null select t1.sku from item_data t1 where not exists (select 1 from item_table t2 where t1.sku = t2.sku) 	0.195163733396159
20756574	1443	query to fetch specfic part from a filepath	select  left(      right(str,charindex('\',reverse(str))-1),      charindex('_',right(str,charindex('\',reverse(str))-1))-1   ) from t 	0.00492696617402226
20757248	8734	retrieving data from two tables.	select u.*,w.* from users u inner join warnings w on u.uid == w.id   where u.rank=2 and u.language='en' and w.warn_active='yes' 	0.000178631899843204
20759699	38118	mysql- split cell and insert into another table	select id, scr, smb, rsm,        (cast(scr as decimal(18, 5)) + cast(smb as decimal(18, 5)) + cast(rsm as decimal(18, 5))) total from (select id, replace(substring_index(state_numbers, ';', 1), 'scr:', '') scr,               replace(substring_index(substring_index(state_numbers, ';', -2), ';', 1), 'smb:', '') smb,               replace(substring_index(state_numbers, ';', -1), 'rsm:', '') rsm       from test      ) as a 	0
20763642	14712	max column value for distinct value on different column sql server 2008 r2	select  * from (     select episode_no         , ord_no         , [date time column]         , row_number() over(partition by episode_no order by ord_no) as rownum     from    smsmir.sr_ord     where   svc_desc = 'discharge to'     and     episode_no < '20000000' ) src where src.rownum = 1 	0.000204202107207152
20765529	8581	select and summarize data from three tables	select  orders.id, orders.date,  sum(order_details.qty * order_details.cost) as amount,  sum(order_details.qty) as qty from  orders   left join order_details on  order_details.order_id=orders.id  and orders.customer_id = 1  group by orders.date having amount is not null and qty is not null 	0.00317154309370005
20768527	9789	in sqlite3, how do i use datetime('now') to find datetimes that are more than n days ago?	select * from table where (datetime('now','-100 days') > lastupdated 	0
20769086	36101	select count from one field	select option_name,         round (        (         length(option_value)             - length( replace ( option_value, ".com", "") )          ) / length(".com")             ) as dot_com_count     from wp_9_options where option_name like '%registered_domains_%' limit 0 , 30; 	0.00061908264025687
20770844	30637	check if two articles have a common tag in between	select 1 from your_table a inner join your_table b on a.tag = b.tag where a.article = 1 and b.article = 2 	0
20771330	8625	how to find count of column, based on 3 distinct values of 3 columns in sql server?	select buildingno, floor, zone, count(rooms) as noofrooms from mytable group by buildingno, floor, zone order by buildingno, floor, zone 	0
20771384	23527	date sortorder on group by with average	select date_format(r.date, '%d %b %y') as datum,         avg(nullif(r.temp, 0)) as temp,         avg(nullif(r.cod, 0)) as czv,         avg(ifnull(r.nh4, 0)) as nh4  from reactor1 r  group by date(r.date)  order by date(r.date) desc; 	0.0042361869489817
20773385	2509	sql statement where clause by two dates	select d.id, d.packingdate, d.deliverydate, b.name  from dbo.distributions d  inner join dbo.beneficiaries b  on d.beneficiary = b.id  where d.deliverydate       between cast(@fromdate as datetime) and cast(@todate as datetime) 	0.330497018047342
20774091	11071	return row field on a condition	select name, group_concat(c.color) from product as p left outer join color as c on p.id = c.productid group by p.name 	0.00139289650424575
20775275	17999	how to insert/edit data into database(s) which i created in cli using mysql workbench?	select * from yourtable 	0.20088055519356
20776015	29602	select available and unavalible slots from three mysql tables	select * from class_info left join class_slots on class_slots.class_info_id = class_info.class_info_id and active = 1 left join class on class.class_id = class_slots.class_id 	0.000582749825734126
20776429	28106	how to select referencing rows in order?	select * from my_table where (sender = '$this' and receiver = '$friend') or (sender = '$friend' and receiver = '$this'); 	0.0380435846819136
20776540	13187	how to join fetch data from two table with using (like, limit and order by)	select name from ( select name from live_search  union  select name from php_test  ) tab where name like '%$q%' order by name asc limit 10 	0.00214709404156865
20778905	3090	how to compare/match values in sql server in two different tables	select * from tblstudent as s inner join feetype as f on s.class = f.class 	0.000860553849969365
20779805	523	getting the table structure in ms access with sql query?	select * from msysobjects where type=1 and flags=0 	0.466402816077379
20780119	40673	output different columns from 2 select statements	select max(case when name='counter' then value end) as counter,        max(case when name='baggage' then value end) as baggage from table 	0.000429431085869966
20780442	29771	sqlite mistake on joining tables	select orders.order_number, products.name as prname, products.price,  ord_details.product_count, orders.order_sum, ord_times.start_t, ord_times.end_t from orders  left join ord_details on orders._id=ord_details.order_id  join products on ord_details.product_id=products._id left join ord_times on orders._id=ord_times.order_id 	0.225030306015006
20781489	6212	how can i add a calculated column based on another column in an sql select statement	select noteid, versionid,        row_number() over (partition by noteid order by versionid) versionno   from notes 	0
20781915	10537	granting privileges to user	select * from user2.info 	0.104744387889458
20784309	40545	how to write select query for column with xml as datatype in db2?	select xmlserialize(tab.extension_xml  as blob(1m))  from table tab; 	0.347034739417764
20784790	11858	how to select all category with its specific parent categoryname	select a.category_id, a.category_name, a.parent, a.category_tag,        isnull(b.category_name,'-') as parent_name from category as a left join category as b on (a.parent=b.category_id) 	0
20785324	6897	order by with a particular value on top	select *         from (select l.look_up_code, to_char(l.city) look_up_desc                 from ghcm_in_cities_mapping_dtls l, ghcm_look_up_tbl a                where l.enabled_flag = 'y'                  and l.state = in_state                  and a.look_up_type = 'location_value'               union               select a.look_up_code look_up_code,                      a.look_up_desc look_up_desc                 from ghcm_look_up_tbl a                where a.look_up_type = 'location_value')        order by (case                   when look_up_desc = 'others' then                    'zzz'                   else                    look_up_desc                 end); 	0.00142105004447274
20785518	41306	select non-duplicated records	select ca.`callerid`  from call_archives  group by ca.`callerid`  having min(ca.`call_start`) >='2013-12-22' 	0.0291123027413843
20786552	3397	select into single column from instead 4 different columns?	select report_id,     user_id,     action_type,     action_start,     action_end ,     case          when action_end is null and action_type = 'close' then action_start         when action_end is null and action_type in ('open', 'comment', 'retrieve') then getdate()         else null      end as column_action_end from table1 order by report_id 	0
20787791	31286	how to combine two select statements in sql server	select a.product_name as [product name], a.product_id as [product id], b.duplicate_id from tb_new_product_name_id as a,  (     select count(product_id)+1 as duplicate_id     from tb_new_product_name_id_duplicate     where product_id= (select  product_id                        from tb_new_product_name_id                        where product_name=@product_name_id                      ) ) as b where  a.product_name like '%'+@product_name_id+'%' or product_id like '%'+@product_name_id+'%'; 	0.0421370609610574
20788670	35918	advanced mysql query (ranking results based on 2 other tables)	select a.*, count(c.id) * if(count(b.id),1.25,1) + a.views as ranking from a left join c on a.id = c.a_id left join b on a.id = b.a_id group by a.id order by ranking desc limit 10 	0.00114353865073439
20790123	3276	select most current data in grouped set in oracle	select account,         sum ( amt_due),         sum (case when last_payment_date = last_dat then last_payment else 0 end),         max (last_payment_date) from (   select t.*,        max( last_payment_date ) over( partition by account ) last_dat   from table1 t ) group by account 	5.10251484567045e-05
20791201	36596	mysql - how to flatten records and subrecords	select r.username, street.value, city.value from records r join subrecords street   on street.record = r.id    and street.name = 'street' join subrecords city   on city.record = r.id    and city.name = 'city' order by r.username; 	0.0302163062575835
20792754	851	how do i use a column in a single-row tables as a scalar?	select a.foo * tab1.bar - b.quux from big1 a join big2 b by big1.id = big2.id join tab1; 	0.335346209884784
20794206	1555	need strategy to generate snapshot of table contents after a series of random inserts	select descriptor1, descriptor2, descriptor3 from mytable mt1 where id in (select max(id)                from mytable                group by room               ); 	0.000819723539437193
20794452	30124	grouping in t-sql	select upc, min(price), x.id from table t1 cross apply (select id from table t2 where t2.isgroupspecial =0 and t1.upc=t2.upc) x  group by upc, x.id 	0.34032909763557
20794480	9351	find all missing mapping table entries	select a.lid,         b.mid  from   people a         cross join meetings b  where  not exists (select 1                     from   attendance c                     where  c.mid = b.mid                            and c.lid = a.lid); 	7.14182370209934e-05
20798988	22980	how to group by with max(date)	select    tblcustomer.*,    t.maxdate from tblcustomer left join  ( select tblcustomerservice.custid,           max(tbltransaction.transdate) as maxdate    from tbltransaction    join tblcustomerservice on          tblcustomerservice.custservid=tbltransaction.custservid    group by tblcustomerservice.custid   ) as t       on tblcustomer.custid = t.custid 	0.265421174608696
20799057	2247	sql cross table select sum() for each item in another select	select pc.barcode,         pc.name,         pc.quantity - sum(ifnull(oc.ordered, 0)) as column_name  from   productscatalog pc         left join orderscatalog oc                on pc.barcode = oc.barcode  group  by pc.barcode,            pc.name,            pc.quantity 	0
20800970	390	select data from 2 different tables on basis of maximum orders	select p.id, p.name, count(o.id) ordercnt from sc_products p  inner join sc_orders o on o.product = p.id group by p.id having count(o.id) > 1 order by ordercnt desc 	0
20803604	24730	php cms design - implementing categories by referencing another table	select * from classes left join catclasses on classes.categoryid=catclasses.id; 	0.1389879294719
20803794	13552	getting sum of two distinct procedure	select bio.*,  sum (cr11_1.cnt_report + cr11_2.cnt_report_2) as total from biographical bio left join (     select cr.id, count (*) as cnt_report     from   report cr     group by cr.id   ) cr11_1 on bio.id = cr11_1.id left join (     select cr.id2,     count (*) as cnt_report_2     from   report cr     group by cr.id2   ) cr11_2 on bio.id = cr11_2.id2 group by bio.* 	0.00566657583469939
20804129	25933	sql select max value or null	select val, max(dat) from t1  where val not in (select val from t1 where dat is null group by val, dat) group by val, dat union select val, dat from t1 where dat is null group by val, dat 	0.0688414540751332
20804954	2433	substring extract from database file paths	select distinct left(physical_name, len(physical_name) - charindex('\',reverse(physical_name))) as physical_path from sys.master_files 	0.0160455909551985
20807143	22234	regex to extract first two numbers of a date	select substring_index(column, '/', 1) from yourtable 	0
20807818	28757	php / mysql relation between 2 tables	select *  from artists  where artist_id in (     select related_artist_id      from related_artists      where artist_id = 1 ); 	0.0111769416168467
20808321	4384	mysql how get unique words?	select group_concat(result order by length(result),result) as finalresult from     (select distinct trim(substring_index(substring_index(`values`,',',p.place),',',-1))             as result      from yourtable,(select 1 as place                      union select 2                      union select 3                      union select 4                      union select 5)p      )t1 	0.00219194771846179
20810100	16914	find total number of rows using data from 3 tables, mysql	select count(distinct oc.usersname) from opencall oc  inner join userdb u on oc.site = u.site inner join company c on u.company = c.pk_company_id where c.division_name = 'north'and oc.logdatex between 1385041200 and 1388041200 and        oc.condition not in (8,9,11,12,19) 	0
20817608	32493	select record using values from a previous count() in mysql	select table.* from table  join     (select field from table group by field having count(field) > 1) newtable  on     table.field = newtable.field; 	0
20818625	25664	sql carriage return	select 'hi i'm a select' ||        chr(13) ||         chr(10) ||         'and i want to be your friend' from   dual 	0.128145625603109
20821001	16203	representing "linked" contacts in mysql	select distinct person_id from contact where period_id = <whatever> 	0.389345430015502
20822611	27321	filter by value in last row of left outer join table	select c.client_id, c.client_name   from clients c left join (   select *, row_number() over (partition by client_id order by created_at desc) rnum     from orders ) o      on c.client_id = o.client_id    and o.rnum = 1  where o.fulfill_by_date < current_date     or o.order_id is null 	0.000768968798448386
20822809	544	ms access max and select top n query issue with duplicate values	select studentid, testid, testscore   from mytable t  where testid in (   select top 3 testid      from mytable    where studentid = t.studentid     order by testscore desc, testid )  order by studentid, testscore desc, testid; 	0.0225072437797862
20822889	23498	inserting an increment number that initializes based on another column value	select qno, row_number() over(partition by qno order by ano) as incrementalno from   table 	0
20824712	22953	my sql select where clause date	select * from `transaction` where date(date_transaction) = str_to_date('19-04-1994', '%d-%m-%y'); 	0.794811268087125
20825040	16559	combine string with column name in query with sha1	select * from users  where sha1(concat('12345678', `email`)) = password collate utf8_general_ci 	0.0748143143529234
20825553	14237	get the values from 2nd and 3rd table for the matched values in 1st table	select tb1.*, tb2.cname, tb3.ename from tb1 join tb2 on tb1.cid = tb2.cid join tb3 on tb1.eid = tb3.eid where tb1.pid = 12 	0
20825727	1110	how can i grab the last value of a coloumn	select sem_no     from course  as t1 join          student_info as t2          on t1.c_id = t2.c_id      where t2.s_id = '0001'     order by sem_no desc     limit 1; 	0
20826192	32213	how to make a correct time calculation?	select time_format(timediff(timediff(time_in, time_out), break), '%h:%i') 	0.409507108970499
20827821	25336	using all with mysql	select * from suppliers as s inner join supplierservices as ss on ss.supplierid = s.id where ss.serviceid in(2,3) group by s.id having count (distinct serviceid)=2 	0.101852188636768
20828029	27965	how to get the top 5 username's with highest values using sql server	select   top 5 username from     yourtable group by username order by count(*) desc 	0
20830050	20446	create view in mysql	select h.hotel, s.site, r.review_content, r.review_date from hotels as h left join hotel_sites as hs on (hs.hotel_id = h.id) left join sites as s on (s.id = hs.site_id) left join reviews as r on (r.hotel_site_id = hs.id) 	0.350435683358616
20830114	20963	how to match two sets of data using mysql and php	select sc.userid, sc.id, group_concat(services)   from bk_schedule sc   join bk_service se on (sc.id = se.bk_id)  group by sc.userid, sc.id; 	0.0011533584045712
20830899	8535	return specific id in postgres column	select "id", count(*) as "count"             from "events" where id = 12345 group by "id" 	0.000498911091365468
20831142	3153	sqli multi-query combine two queries on a single one	select * from table where name like '%query%' or  lastname like '%query%' union all  select * from table where address like '%query%' or  state like '%query%' order by name, surname, state 	0.000664303213294635
20831547	2843	multiple arrays display in one table	select        c.user,       c.cur_attack,       e.exp_attack  from curstats c  left join experience e  on c.user = e.user  order by c.cur_attack desc limit 25 	0.00015703501861048
20831615	24389	mysql query with where not exists returning no rows	select c.course_id, c.course from course as c     left join course_tutor_link as ctl          on c.course_id=ctl.course_id and ctl.user_id=9 where ctl.course_id is null 	0.438466530751604
20834441	11971	daily attendance to show all the employees whom attendance is not exist in another table?	select e.*    from employees e left join daily_attendance d     on e.sno = d.emp_sno    and d.duty_year = '2013'     and d.duty_month = '1'     and d.duty_day = '1'     and d.is_current = 1  where d.emp_sno is null 	0
20834735	5464	query returning incorrect number of rows	select   anon_user_id          ,title               ,(case             when score  between 0 and 0.33 then 'low'            when score  between 0.33 and 0.66 then 'medium'            when score  between 0.66 and 1.01 then 'high'            else 'undefiend'            end) as 'achiever' from   quiz_scores where item_id between 100 and 200 	0.0348127712147562
20834967	14026	how to find total of two columns using php	select a.id, a.shop, a.ipop, a.item, a.weight, a.touch, a.issuedwt, a.receiptwt,         if(a.ipop = 'input', @balance:=@balance + a.issuedwt, @balance:=@balance - a.receiptwt) as balance from tablea a, (select @balance:=0) b 	0
20837244	6473	create new table structure from orginal table	select * from crosstab(        'select "id", "trainingname", "expirydate"         from   trainingmatrix         order  by 1,2'       ,$$values ('t1'::text), ('t2'), ('t3'), ('t4')$$) as ct ("section" text, "t1" text, "t2" text, "t3" text, "t4" text); 	0.0019800665457811
20838676	16289	how to get numbers from a string	select regexp_replace('my_4name - 7203', '.*?([[:digit:]]+)[)]?$','\1')  from dual; 	0.000169749293453786
20839155	25081	mysql, sorting by field count	select      count(album_id) as tot,album_id,date   from      purchased_albums  group by album_id order by tot desc"; 	0.0651709583082377
20839276	25367	select rows until to amount	select o.id, o.name, o.price, o.date from (select o.id, o.name, o.price, o.date, (@totalprice:=@totalprice + o.price) totalprice       from offers o, (select @totalprice:=0) a       order by o.date      ) as o where o.totalprice <= 1500 	0.000246674770387243
20840886	33862	two rows above and below specific id based on football team points	select * from (   (select * from teams   where points >= (select points from teams where id=3)   order by points asc limit 0,3)   union   (select * from teams   where points < (select points from teams where id=3)   order by points desc limit 0,2) ) as `teamresults` order by points desc 	0
20841811	17772	bringing latest date from another table	select   case.case_number,   max(report.compiled_date) from   case   inner join report on report.case_number = case.case_number where   case.case_active = 1 group by   case.case_number order by   case.case_number asc 	0
20842830	16344	how to get each json child of an array, postgresql	select   value->'time' from    json_array_elements('{"route_json": [{"somekeys": "somevalues","time": 123},{"somekeys": "somevalues","time": 456}]}'::json->'route_json'); 	0
20847660	8803	sql: how to group data in a table by date, and join it with another table to display account numbers?	select  accountnumber       , sum(case when datediff(day, invoicedate, getdate()) between 271 and 360                  then qtyshipped             end * price) '360 to 271 days ago'       , sum(case when datediff(day, invoicedate, getdate()) between 181 and 270                  then qtyshipped             end * price) '270 to 181 days ago'       , sum(case when datediff(day, invoicedate, getdate()) between 91 and 180                  then qtyshipped             end * price) '180 to 91 days ago'       , sum(case when datediff(day, invoicedate, getdate()) between 0 and 90                  then qtyshipped             end * price) '90 to 0 days ago' from    datahub..invoicehold where   accountnumber in (         select  customer         from    [logistics].[dbo].[logistics_distributorgrowth]         where   [type] = 'customer'                 and show = 'yes' )         and qtyshipped > 0         and invoicedate >= dateadd(d, -360, getdate()) group by accountnumber 	0
20848737	16543	odbc foxpro order by multiple columns and a specific value issue	select       nvl( rcp.item, ari.item ) as recipe_group,       iif( ari.code = 'rw', 1, 2 ) as rwsort,       ari.item,       ari.descrip,       ari.cost,       ari.code as rcode    from       arinvt01 ari          left join arrecp01 rcp             on ari.item = rcp.recipe    where       ari.code = 'rw'    order by       recipe_group,       rwsort,       ari.item 	0.0348049603321127
20849245	40613	how to display the most recent record in a database mysql	select * from dvd where genre = 'action' order by yor desc limit 1; 	0
20849511	28480	mysql and c# updating	select       name   from       names   order by id  limit 1 	0.628732855763278
20849946	21906	join select statements and remove duplicates	select jobuid, jobcode, sum(amount) from (     select jobuid, jobcode, count(*) as amount     from [dbo].historyitemsview r       group by r.jobuid, r.jobcode     union all     select jobuid, jobcode, count(*)     from [dbo].fieldsview r               group by r.jobuid, r.jobcode ) x group by jobcode having sum(amount) > 1 	0.270980008886571
20849973	12281	oracle sql joining two separate user generated tables	select x.bin_type_name,   x.bin_level floor,   x.empty_locations empty,   ( ( b.total total - x.empty_locations ) / y.total total ) * 100  perc_available,   y.total total,   to_char ( sysdate, 'mm-dd-yyyy ' ) as day,   to_char ( sysdate, 'hh:mi:ssam' )  as time    from   (      select bin_type_name,       count ( b.bin_id ) empty_locations,       bin_level        from bins b     left join bin_items bi          on bi.bin_id = b.bin_id       where quantity is null       and usage       = '1024'    group by bin_type_name,       bin_level,       quantity   )   x inner join   (      select bin_type_name,       bin_level,       count ( bin_type_name ) as total        from bins       where usage = '1024'    group by bin_type_name,       bin_level   )   y      on x.bin_type_name = y.bin_type_name   and x.bin_level       = y.bin_level order by 2  ; 	0.00231360525266175
20851048	21986	mysql : select count when id have multiple same value and calculate percentage	select t1.id as t1id,        t2.id as t2id,        t1.id1,        t2.id2,        t1.id1/t2.id2 * 100 as percentage from  (select id,count(*) as id1   from tableone   group by id  )t1,  (select id,count(*) as id2   from tabletwo   group by id  )t2 	0
20851055	33056	get the full name by userid	select firstname + ' '  + lastname from users where userid = @inuserid_int 	0.0142469766170582
20851912	6111	get top 3 random values from sql query	select * from (    select itemcode,itemname from hmis.shopitemcode order by dbms_random.value ) where rownum <= 5; 	0.000111164988528351
20852559	924	select distinct - access	select count(*) as uniquemembers from    (             select distinct transid              from transactiontable              where (transactiontable.trandate) between [enter the start date:] and [enter the end date:]         )  as t; 	0.255439365988937
20857834	22247	get distinct records after concat clause in mysql	select concat ('us-',  medicare_provider_charge_inpatient_drg100_fy2011.`provider state`) as `provider state`,                                 sum(round(medicare_provider_charge_inpatient_drg100_fy2011.`total discharges`, 2)) as `total discharges`                                 from medicare_provider_charge_inpatient_drg100_fy2011                                 where medicare_provider_charge_inpatient_drg100_fy2011.`provider name` like '%elk regional health center' group by concat ('us-',  medicare_provider_charge_inpatient_drg100_fy2011.`provider state`)                                  limit 0,5 	0.0131403462058748
20857900	8843	displaying document totals in category view	select *,ifnull(count(d.categories),0) as total from categories_docs as cd left join docs as d on d.categories=cd.catid where cd.parent = 0 group by cd.catid 	0.00840400124354191
20858500	38526	mysql - count positive consecutive value	select x consecutive_numbers,        count(*) how_many_times from (   select y, max( x ) x   from (     select      if( value < 0, @x:=0, @x:=@x+1 ) x,      if( value < 0, @y:=@y+1, @y ) y,      value     from table1     cross join (        select @x:=0, @y:=0     ) var     order by id   )q   where value >= 0   group by y ) qq group by x ; 	0.000948282875982676
20858917	13920	mysql query for most recent and unique ids	select t1.* from tablename as t1 inner join (    select nodeid, max(timestamp) as latesttimestamp    from tablename    group by nodeid ) as t2 on t1.timestamp = t2.latesttimestamp and t1.nodeid = t2.nodeid 	0
20859002	40267	compare like clause with entire word	select * from mytable where mytext regexp '[[:<:]]car[[:>:]]'; 	0.150150580938079
20860819	29716	merge sql scripts for row condition and table merging	select a.* into dest  from (select top n *        from source        where source.var1='1'        union all        select top n *        from source        where source.var2='1'        union all        select top n *        from source        where source.var3='1'        union all        select top n *        from source        where source.var4='1'        union all        select top n *        from source        where source.var5='1'       ) a 	0.00165483669358598
20862283	20378	mysql group by date count how many	select date(dateadded) date, count(*) count from sample_table group by date order by date 	0.0329077807299371
20862288	27450	get two values from the same column in the same query	select   src.name as srcname,   tgt.name as targetname, from   friends   inner join users as src on friends.source=src.id   inner join users as tgt on friends.target=tgt.id 	0
20863129	39239	getting last x amount of dates in mysql	select date(date) as month, sum(amount_paid) as amount  from      payments  where      date_format(date,'%y-%m') < date_format(now(),'%y-%m')  and      date_format(date,'%y-%m') >= date_format(now() - interval 7 month,'%y-%m')  group by      year(date), month(date) 	0
20867234	11841	mysql select last value from 2 tables, 2 columns (with the same name)	select   (select max(numberrenamed) from 2_1_journal) max1,   (select max(numberrenamed) from 2_1_paidused) max2 	0
20867281	24010	how to verify that the given value is not in table?	select count(*) from   consumer where  'name' not in (first_name, last_name) 	0.000338210954067231
20868554	23482	a dynamic column name with value in sql query	select a.id, a.name, 'not available' as address from dbo.a  where (a.id not in (select b.id from dbo.b)) and (a.id=5) 	0.0517431294313915
20869256	9437	mysql wordpress filtering in separate rows with same id	select p.id         , t.term_id         , max(case when pm.meta_key = 'fc_start' then pm.meta_value end) fc_start         , max(case when pm.meta_key = 'fc_end' then pm.meta_value end) fc_end      from wp_posts p      join wp_postmeta pm        on pm.post_id = p.id      join wp_term_relationships tp        on tp.object_id = p.id      join wp_terms t         on t.term_id = tp.term_taxonomy_id     group         by p.id,t.term_id    having fc_start <= '2013-12-07'         and fc_end   >= '2013-12-01'; 	0.000188878992849573
20876563	15909	sql statement to get largest id from database column	select top 1 id from table order by convert(int, id) desc 	4.6295167130229e-05
20876619	36889	mysql query value where current date	select field from table where date(column) = curdate() select * from tb_data where date(date) = curdate() 	0.00163598026754842
20877154	14810	retrieve the name from table based on matching pattern through sql?	select distinct name from `student` where `name` regexp '[ae]' 	0
20877904	15096	database having the exact same row of record..why so?	select convert(varbinary(max), [column 1]), convert(varbinary(max), [column 2]), convert(varbinary(max), [column 3]) where <use your criteria to get the records> 	0.000800417885078049
20879044	23105	how to sort perfectly a select from a mysql database	select id, cmd where cmd like %httpd% group by ppid having count(ppid) = 1 	0.00334782337454924
20879869	31611	mysql count on multiple colums with group by	select `product_matrix` as matrix,          sum(sold) as qty_sold,         count(id) as products from `products`  where `sold` > 0  group by `product_matrix` 	0.0359569721685924
20880833	8681	pivoting pivoted table	select *   from   (select 1 cntcol, convert(char(3), [data out (no val#vuoto)], 0) month,             ( [gruppi min (gg flusso/decorrenza        from   dbpratiche         where  compagnia = 'generali ina assitalia'             and stato = 'out attivata'             and [data out (no val#vuoto)] > '01-01-2012') tlb     pivot ( count(cntcol)           for tlb.[gruppi min (gg flusso/decorrenza                          ([<=06],                            [<=08],                            [<=10],                            [>10] ) )pvt 	0.107403180769688
20881275	3483	create sql column relative to another	select  case when id in (1,4) then 'ok' else 'not ok' end as myfield from  mytable 	0.00594659894838322
20881454	27164	how to write a query to get values from a table filter(where clause) based on multiple value field?	select * from tablename where find_in_set('52',category) > 0 	0
20882374	36583	count same id column with different condition in same select statement	select sum(job_status = 0) pending, sum(job_status = 1) approved  from tbl_employer_post_details epd  inner join tbl_employer_registration er on epd.employer_id = er.employer_id where job_status in (0, 1); 	0
20882667	9062	how to check a record belongs to user in mysql?	select r.*, t.title, t.active, ticket_author.username as ticket_author, responser.username, responser.isadmin, responser.ismod  from `support_tickets_replies` r  left join `support_tickets` t on (t.id = r.tid)  left join `users` ticket_author on (ticket_author.id = t.uid)  left join `users` responser on (responser.id = r.uid)  where r.tid = [something goes here] and t.uid = [user id goes here] 	0.000424878792042266
20883539	24386	select top 1 from each group sql	select city, itemname, max(quantity) from (             select                      l.city as city,                     mi.name as itemname,                     sum(ft.quantity_sold) as quantity             from                     facttable ft                             join menuitem mi on (ft.menuitemid = mi.id)                             join location l on (ft.locationid = l.id)             group by                     l.city, mi.name) sub group by city, itemname; 	7.16879783449889e-05
20885829	36637	how to count items by day	select    i.dt_closed,   rp.name,   count(i.id) from incidents i join reps rp on (rp.id = i.id_assignee) where i.dt_closed > @startdate group by rp.name, i.dt_closed 	0.000213377126812817
20886406	15263	select distinct query to string list	select distinct st2.subjectid,             substring((select ','+st1.studentname  as [text()]             from dbo.students st1             where st1.subjectid = st2.subjectid             order by st1.subjectid             for xml path ('')),2, 1000) [students]      from dbo.students st2 	0.0195907686209874
20886583	34285	sql multiple tables join one to many relationship	select routes.route_name,        concat(startstop.stop_latitude,",",startstop.stop_longitude) as start_pt,        concat(endstop.stop_latitude,",",endstop.stop_longitude) as end_pt,        routes.total_stop from routes inner join route_stop as routestart on (routestart.route_id=routes.route_id and routestart.stop_position = 1) inner join route_stop as routeend on (routeend.route_id=routes.route_id and routeend.stop_position = routes.total_stop) inner join stops as startstop on (startstop.stop_id=routestart.stop_id) inner join stops as endstop on (endstop.stop_id=routeend.stop_id) 	0.0152894492464495
20886658	3965	tsql - extract string using substring	select substring ('tf_bskt trade', charindex('_', 'tf_bskt trade') + 1, len('tf_bskt trade')) 	0.143385149594658
20887348	40375	the conversion of the varchar overflowed an int column	select convert(nvarchar(10), mydate, 103) from mydates 	0.00557648176509547
20888136	28858	how do i return only rows where all conditions are met based on an array of intergers (ids)?	select * from drink_recipes where drink_recipes.id not in (         select          dr.id      from drink_recipes_ingredients dri         join drink_recipes dr on dr.id = dri.fk_recipes_id         join raw_materials rm on rm.id = dri.fk_raw_materials_id     where rm.id not in (16,34,35) ) 	0
20889146	30784	mysql query using count() and if/case	select user_id, count(arv) as arv         from         (             select distinct user_id, date(answer_time) as arv from result where answer_time is not null          ) a         group by user_id order by arv desc; 	0.626438697209064
20889892	14737	sql select last message for each contact who user has been mailing with	select messages.* from messages join (select contact_id, max(date_and_time) as time_when       from messages       group by contact_id) as mostrecent   on mostrecent.contact_id = messages.contact_id     and mostrecent.time_when = messages.date_and_time order by date_and_time desc 	0
20889974	752	should i combine these queries, and if so, how?	select     foo.*            ,bar.*           ,c.*             ,d.*         from     foo         inner join bar on foo.pk = bar.fooid             left join charlie c on bar.fooid = c.fooid             left join delta d on bar.fooid = c.fooid 	0.654934093801038
20890842	20500	programatically identify all foreign keys that cascade	select * from sys.foreign_keys    where delete_referential_action > 0      or update_referential_action > 0; 	0.000844569790654504
20892202	33768	sql result count changes when joining same table	select base.t2a, count(*) as t2bcnt from ( select t2a, t2b from t2 where t2d = 'bar' group by t2a, t2b ) as base group by base.t2a having count(*)>1 order by base.t2a 	0.00631816195520523
20893634	25187	group by in sql	select iif([cancellation date] is null, 'not cancelled', 'cancelled') as status, sum(loss) as [total loss] from insurance_data group by iif([cancellation date] is null, 'not cancelled', 'cancelled'); 	0.392489385150794
20894123	5931	sql statement to generate a table of totals by month	select account,     sum(iif(month(date)=01, amount, 0)) as jan,     sum(iif(month(date)=02, amount, 0)) as feb,     sum(iif(month(date)=03, amount, 0)) as mar,     sum(iif(month(date)=04, amount, 0)) as apr,     sum(iif(month(date)=05, amount, 0)) as may,     sum(iif(month(date)=06, amount, 0)) as jun,     sum(iif(month(date)=07, amount, 0)) as jul,     sum(iif(month(date)=08, amount, 0)) as aug,     sum(iif(month(date)=09, amount, 0)) as sep,     sum(iif(month(date)=10, amount, 0)) as oct,     sum(iif(month(date)=11, amount, 0)) as nov,     sum(iif(month(date)=12, amount, 0)) as "dec" from items where year(date) = 2013 group by account 	0.000451287362362952
20896310	32316	sql multiplication of multiple rows resulting in one row	select itemid, description, store, (localcurrencyamount * exchangerate) as 'us currency amount' from item; 	8.47194842523293e-05
20898835	34529	call function only single time for multiple places in a query	select     value,     float_quantity,     int_packinglistdetailid =                 case                     when value = 0 then 1                     when value < float_quantity then 2                     when value = float_quantity then 3                 end from dbo.tblsdpackinglistdetail t1 cross apply (     select value = dbo.totalpackagedqty(t1.int_packinglistdetailid) ) tt where int_packingid = '10901032014121313496pm0' 	0.0185307108898714
20899223	9945	how to select count all and rows and only echo where column is not empty	select count(*) from ads where position is not null or position != ''; $numrows = mysql_numrows( $result ); 	0
20899447	20345	how do i get the field to pass to another sql phrase in a join statement	select      a1,b,c,d,e,f,g,h,a2,b2  from     (select          a as a1,b,c,d,e,f,g,h      from          `table1`      inner join          `table2`      where          table1.a=table2.a and b=0)z  inner join     (select          a2,b2     from         `table3`     where         b2=1      group by b2)x on z.a=x.a2 group by a1 	0.00384205262340131
20899458	13434	how to print "y" if it has a certain value in a column	select case         when aa = 1         then 'y'         else null        end from   a 	0
20900473	40079	select multiple row values from mysql based on two column	select * from table where 1p_id = '29' order by count asc 	0
20900557	10140	latest group by mysql + link table	select s.* from system_devices s left join system_devices s1    on (s.carid = s1.carid and s.lastused < s1.lastused)    inner join link_devices_user ld on s.id = ld.deviceid where (s1.id is null) and (ld.shopid = 46) order by carid 	0.00220948734301102
20903170	16223	check rows in first table, compare them with rows from the second table and output a match	select * from timetable t where in_dates = 0 or   (     in_dates = 1 and     exists (      select 1      from dates d      where d.subject = t.subject and        d.date = t.date     )   ) 	0
20903559	11553	sum of first purchase details of all coustemers	select id,monthname,sum(amount) from mytable group by id,monthname 	0
20903861	20194	separating out related records in same table in sql	select login, logout from (     select userloginauditid as logout,      (select userloginauditid from         (select userloginauditid, row_number() over (order by l2.logindate desc) rn          from logtable l2           where loginauditcodeid = 96           and l2.logindate < l.logindate           and l2.employeeid = l.employeeid) y where rn = 1       ) login     from logtable l where loginauditcodeid = 137 ) x where not login is null 	0.000200572954834669
20905920	24582	using select * from table	select * from table; # it would depend of the table internal order ['surname','office','name','irrelevant'] select name,surname,office from table; # you decide which column to show the element ['name','surname','office'] 	0.0158021394623946
20907871	16877	how to get the count of rows in a column between a range in a sql table	select count(*) from yourtable where columnname >=5 and columnname <=9 	0
20908445	20942	mysql joining tables while counting & grouping	select created_at, s.label, amount from  (     select count(r.source) as amount, r.source, r.created_at     from  related_table r     group by r.source, r.created_at) a  inner join source_table s    on a.source = s.source_id where created_at between '2013-12-01' and '2013-12-31' order by amount desc, created_at desc 	0.0215574265184737
20909408	25325	bind variables in the from clause for postgres	select *  from information_schema.sequences  where sequence_name = :name    and sequence_schema = :schema; 	0.562499011842646
20909643	25145	mysql assort categories with title	select        ccl.name        ,group_concat(cpl.title) from cms left join cms_category_lang as ccl   on cms.id_cms_category = ccl.id_cms_category left join cms_page_lang as cpl   on cms.id_cms = cpl.id_cms group by ccl.name 	0.0791953592232622
20910928	1978	how to add sorting to this query (order by desc)	select * from ( select      ip, count(*) as cnt from    withdraw_update wu          join     update_detail u on wu.update_id = u.update_id group by 1 having count(*) > 1   limit 10) sub order by cnt desc ; 	0.715658848661432
20913160	18784	finding a running difference in columns with mysql	select hour, throughput, difference   from (   select hour, throughput,           throughput - @p difference, @p := throughput     from   (     select hour(p_datetime) hour,            count(*) throughput       from product_log l      where p_datetime >= '2013-11-30'        and p_datetime < '2013-11-31'        and p_type = 'stack'      group by hour(p_datetime)   ) a cross join (select @p := 0) i ) b 	0.00427714287131761
20916825	17243	pdo select and count in having distinct to appear in dropdown	select l.locationname, count(distinct lu.email) as total    from location l left join location_user lu     on l.locationname = lu.locationname    and l.custnum = lu.custnum    and lu.userlevel < 3   where l.custnum = ?  group by l.locationname  having count(distinct lu.email) < 6 	0.148653933451021
20919530	39201	mysql select distinct months (abbreviation) from table	select distinct      month(date) as id,      monthname(date) as name,      substring(monthname(date),1,3) as abrv     from table_name order by id asc 	0.00137793084814608
20920023	31741	mysql query for selecting and counting some fields from two tables	select    p.post_id,   p.post_date,   p.post_summary,   p.post_title,   count(c.post_id) as number_of_post_comments  from   post p    left join comment c      on p.post_id = c.post_id  group by p.post_id 	5.68670136073277e-05
20923577	6621	checking if array is contained in another array in postgresql	select array[10,20]  <@ array[30,20,10]; 	0.0198679527418169
20924603	41285	getting rooms that are free between two dates mysql	select ro.*  from room ro   where not exists (select 1 from reservation re                     where ro.id = re.room_id                    and ([yourstartdate] between re.reservation_datefrom and re.reservation_dateto                         or [yourenddate] between re.reservation_datefrom and re.reservation_dateto)                    ) 	0
20926410	1405	how to divide two columns and discriminate the result in sql	select * from table where (totalrate/nrrates)>=4 	0.000787217628753218
20928010	7630	how to get the value of a row with max aggregation function?	select c.comment, m.*  from  comments c  join (     select t.match_id, max(t.timestampe) as maxtimestamp, count(t.match_id) as comments_no     from comments t     group by t.match_id ) m on c.match_id = m.match_id and c.timestampe = m.maxtimestamp 	0.00018895271840297
20928364	8435	mysql, get total weight of products from based on uuid of category	select l.subject, sum(g.weight) weight   from gear_list l join gear_list_items i     on l.gearlistuuid = i.gearlistuuid join gear g     on i.gearuuid = g.gearuuid  group by l.subject 	0
20928800	1241	listing column values using sql queries?	select distinct tvserialnumber from viewingtable; 	0.0500513871474037
20929864	31790	join three tables in mysql	select distinct student_id,t3.date,if(t3.date is null, null,t1.status) as status,t2.date as date2,t2.status as status2 from table2 t2 left join table3 t3 using(date) join table1 t1 on (t1.id = t3.id or t3.id is null) order by date2,student_id 	0.204339688880659
20930185	4887	finding a specific address in sql	select s.staffno, staffname,branchregisteredin from staff s join registration r on s.staffno=r.staffno where staffaddress like  '%london%' 	0.00660963606146389
20930617	5213	sql query to get result in asc order but 0 values should be last after all data	select * from tbl_student order by case when marks = 0 then 9999 else marks end asc 	0.000104936018243165
20932624	3311	mysql: show everything that doesn't join	select * from `post_plus` left join `post` on `post`.`id` = `post_plus`.`news_id` where `post`.`id` is null 	0.124245339800493
20932757	6844	mysql expression to retrieve percentage	select sum( case when active=1 then 1 else 0 end )        /        count(*)         * 100          as percent_of_active_records from table1 t  where t.regdate <= '2013-03-31'    and t.regdate >= '2013-01-01' 	0.0392799782460692
20933105	5407	order by date but add important at first in mysql	select * from ads where livetime > unix_timestamp() order by special desc, timestamp desc 	0.000798943924688248
20933251	36494	concatenating columns and displaying in oracle	select first_name || lower(last_name) from table_name; 	0.0187234522650296
20933764	28734	copy float data to varchar from table to another after excel import	select cast(cast(yourvalue as decimal) as varchar) 	0
20933812	3384	how would i get values from 2 rows into one	select  wp1.meta_value as first_name,  wp2.meta_value as last_name from  wp_usermeta wp1 inner join wp_usermeta wp2 on ( wp1.user_id = wp2.user_id ) where 1 and wp1.meta_key = "first_name" and wp2.meta_key = "last_name"; group by wp1.user_id; 	0
20935265	25550	select query with case condition and sum()	select sum(case when cpayment='cash' then camount else 0 end ) as cashpaymentamount,        sum(case when cpayment='check' then camount else 0 end ) as checkpaymentamount from tableorderpayment where ( cpayment='cash' or cpayment='check' ) and cdate<=sysdatetime() and cstatus='active'; 	0.786167339359992
20935365	15898	mysql team/score	select `id_player`, count(*) as `match_win` from     (select         if(`score_player1`>`score_player2`, `id_player1`, `id_player2`) as `id_player`         from `your_table_name_here`     ) as `tmp` group by `id_player` 	0.610911624309268
20936963	33899	how to select all id's that are within one year prior to a date on a second table?	select *  from a join b on a.id = b.id where str_to_date(a.date, '%m/%d/%y')  between str_to_date(b.date, '%m/%d/%y') - interval 1 year  and str_to_date(b.date, '%m/%d/%y'); 	0
20936980	25944	efficient query for counting multiple relationships of multiple entities	select foo.id,     (select count(*) from foo_thing1 where foo_thing1.foo_id = foo.id),     (select count(*) from foo_thing2 where foo_thing2.foo_id = foo.id),     (select count(*) from foo_thing3 where foo_thing3.foo_id = foo.id),     ... from foo where foo.id in (1, 2, 3, 7, ...); 	0.0575425913624594
20940073	10047	sum from entries of 3 tables	select q.name, sum(q.points_column) total from  (   select name , points_column  from table_one   union all    select name , points_column  from table_two   union all    select name , points_column  from table_three   union all    select name , points_column  from table_four   union all    select name , points_column  from table_five   ) q group by q.name 	0
20940087	14933	best way to sort the results of multiple join statements	select      `pages`.id as pageid,      `pages`.view as pageview,      `pages`.accesslev,      group_concat(`scripts`.scriptpath separator ',') as scriptspath,      group_concat(`components`.componentpath separator ',') as componentspath from `pages` left outer join `scripts` on `scripts`.page_id = `pages`.id left outer join `components` on `components`.page_id = `pages`.id where `pages`.pagename = 'home' group by `pages`.id 	0.0523555447194782
20940257	20131	how to make a union of two tables in sqlite3?	select col1, col2 from test  union  select col1, col2 from test2 	0.0156871492840781
20941763	28179	group by a field not in select	select a.lecturername, b.numofmodules from lecturer a,( select l.lecturerid, count(moduleid) as numofmodules     from lecturer l , teaches t     where l.lecturerid = t.lecturerid     and year = 2011     group by l.lecturerid) b where a.lecturerid = b.lecturerid 	0.110235375029562
20942927	6556	sql join logic to take the availabe matched values and common values for unmatched ones	select e.employeeid, e.name, e.dept, e.rank, e.salary,        coalesce(i.increment, o.increment, oo.increment) increment   from employee e join increment oo     on oo.dept = 'other'    and oo.rank = 'other' left join increment i     on e.dept = i.dept    and e.rank = i.rank    and i.rank <> 'other' left join increment o     on e.dept = o.dept    and o.rank = 'other' 	0.000106228708340007
20943369	37758	grand total of columns using sum (if) in mysql	select date(o.orderdate) as date,        sum(if(o.productnumber = '1', o.qty, 0)) as `product 1`,        sum(if(o.productnumber = '2', o.qty, 0)) as `product 2`,        sum(if(o.productnumber = '3', o.qty, 0)) as `product 3`,         sum(if(o.productnumber in ('1', '2', '3'), o.qty, 0)) as `total` from orders o group by date(o.orderdate) 	0.000136428208496397
20943424	112	dynamically table joining by column value	select *  from   animal a         inner join land_animal l                 on l.animal_id = a.animal_id  where  a. type = 0  union  select *  from   animal a         inner join air_animal ai                 on ai.animal_id = a.animal_id  where  a.type = 1 	0.00181518098338687
20946871	3731	mysql query comma separator	select `users_2`.`table_2_id` , group_concat(`users`.`username`) as `usernames` from `users_2` inner join `users` on  find_in_set(`users`.`id`,`users_2`.`user_id`) 	0.322198957287138
20947499	36708	same query result the value on local but on server it shows null result	select e.* from target t  left join closure_employee e on t.fk_user_id = e.ce_recruiter_id where t.fk_user_id ='31' select e.* from target t  left join closure_employee e on t.fk_user_id = e.ce_recruiter_id and month(t.target_month) = month(e.offer_date) where t.fk_user_id ='31' select e.* from target t  left join closure_employee e on t.fk_user_id = e.ce_recruiter_id and month(t.target_month) = month(e.offer_date) and e.offer_date > date_sub(now(), interval 7 month)  where t.fk_user_id ='31' 	0.00548306574675453
20947690	34885	select data from last month sql	select *  from daily_reports  where username = '$username'  and month(date) = month(date_add(now(), interval -1 month))  order by date desc 	0
20947715	22824	sql string padding	select right(replicate('0',13)+ '12345',13) 	0.363845919180803
20948702	14674	pivoting the count of data	select * from ( select convert(char(4), [data out (no val#vuoto)], 100) as month , [cod# prodotto] as col1,count([cod# prodotto]) as codprodotto from dbpratiche where  [cod# prodotto] is not null and [data out (no val#vuoto)] < convert(datetime,'2012/01/11') and stato='out attivata' or stato='sospesa'  group by ([cod# prodotto]),convert(char(4), [data out (no val#vuoto)], 100) ) t pivot (   sum(codprodotto)   for month    in([nov],[dec],[jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct]) ) p 	0.00658234132407048
20949403	2458	selecting complex data from mysql table	select * from account_records ar inner join  ( select distinct id from  ( select ar.id as id from  account_records ar inner join (   select count(*), max(id) as lastid, acc_name, date_created from account_records ar   group by acc_name, date_created    having count(*) > 2 ) aggr on ar.acc_name = aggr.acc_name  and ar.date_created = aggr.date_created and ar.id < aggr.lastid  union select id from account_records ar inner join    (     select count(*), max(id) as lastid, acc_no from account_records ar     group by acc_no     having count(*) > 2    ) aggrid on aggrid.acc_no = ar.acc_no and ar.id < aggrid.lastid   ) allids   ) distinctids on ar.id = distinctids.id ; 	0.0105808385454994
20949794	18298	mysql adding conditional logic and combining select	select m.player_id_1 as 'original_player_name',m.player_id_2 as 'matched_player' ,p.username as 'input_user_name',  (select username from player_data where player_id=matched_player) as 'matched_player_name'  from marriage_data m inner join player_data p on p.player_id=m.player_id_1 and m.player_id_1=enter_your_playerid_here union select m.player_id_2 as 'original_player_name',m.player_id_1 as 'matched_player' ,p.username as 'input_user_name',  (select username from player_data where player_id=matched_player) as 'matched_player_name'  from marriage_data m inner join player_data p on p.player_id=m.player_id_2 and m.player_id_2=enter_your_playerid_here 	0.791947631958749
20950598	10033	how to get the records from multiple tables?	select * from table1 where column1 not in  ( select column1 from table2 union select column1 from table3) union  select  * from table2 where column1 not in  (select column1 from table3) union select  * from table3 	0
20951636	9658	return count for each distinct	select customersperorder, count(*) from ( select count(*) as customersperorder from customerorder group by customerorder.orderid ) sub group by customersperorder 	0.000344194211581742
20952208	2751	sql query to get specific rows based on one value	select * from fullresults where id = (select id              from fullresults             where type= @variable); 	0
20955004	12648	select users who send a post with a break from 5 minutes in postgresql	select id from posts group by id having count(*) > 1    and max(post_time) - min(post_time) > interval '5 minutes' ; 	0
20956065	35616	select from multiple tables using 1 column	select user.name, user.country, data.best_time from user, data where user.user_name = data.user_name; 	0.00168964798097008
20958146	13459	sql select and group	select p.postid, group_concat(t.tags) from posts p inner join tags t on t.did = p.did inner join users u on u.username = p.username group by t.did 	0.285895722667933
20961804	29503	combining string with variable in sql server	select *,          '01-jan-1900' as from_date_x,          '01-jul-' + cast(from_finyr as varchar(4)) as to_date_x      into bbt_item_6_a      from bbt_item_5_finyrs 	0.451471800654008
20964039	32179	sql statement - based on total sum of a column type	select  model ,quantity ,price ,scheduleb ,orderid from table1 where scheduleb in    (select scheduleb from table1 group by scheduleb having sum(quantity * price) > 2500) 	0
20964171	37671	top 3 rows based on score, but to handle ties	select * from studtable  where score in (select distinct top(3) score from studtable order by score desc) order by score desc 	0
20966412	30990	mysql review rating	select produkt.id_produkt,         produkt.kod,         produkt.tytul,         produkt.opis,         opinie.id_opinie,         opinie.id_produkt_opinie,         opinie.opinia_opinie,         opinie.ocena_opinie,         opinie.aktywny_opinie,         review_avg from produkt left join opinie  on opinie.id_produkt_opinie = produkt.id_produkt  and aktywny_opinie = 'y' inner join (     select produkt.id_produkt , avg(ocena_opinie) as review_avg      from produkt     left join opinie      on opinie.id_produkt_opinie = produkt.id_produkt      and aktywny_opinie = 'y'     group by produkt.id_produkt  ) sub1 on sub1.id_produkt = produkt.id_produkt 	0.285732758014234
20967011	16725	how to count data within date intervals	select   month(solddate),    sum(sold) from    selling where solddate between date_sub(now(), interval 1 year) and now() group by month(solddate); 	0.00111374621334666
20967275	59	counting results in mysql with highest value by category	select    users,   count(*)  from   (select      users,     count(*) count   from     `table`    where points in      (select        max(points)      from       `table`      group by category)    group by points) temp  group by users ; 	5.61584149641235e-05
20967383	13199	sum of columns from tables in join	select count(*) as orders, sum(ord.order_total_value) as total_value, ord.date_interval as date_interval, sum(ship.order_shipping_value) as total_shipping from ( select o.orders_id,        o.last_modified as modified_date,        sum(op.final_price * op.products_quantity) as order_total_value,         date_format(o.last_modified, '%m-%y') as date_interval from  orders as o       inner join orders_products as op on o.orders_id = op.orders_id where o.orders_status = 3   group  by date_interval,o.orders_id ) ord left outer join  (  select orders_id,sum(value) as order_shipping_value  from orders_total  where class='ot_shipping'  group by orders_id ) ship on ord.orders_id = ship.orders_id group by ord.date_interval order by modified_date desc; 	0.000784942897809326
20967881	25266	informix sql compare datetime value on where statement	select * from mytable where extend(entrytimestamp, hour to second) > '09:00:00' 	0.124436947569783
20967998	33033	please proide sql query that return row in which current sysdate exist between startdate and enddate	select * from seasons  where getdate() >= @startdate  and getdate() <= @enddate 	0.000126832063970516
20970028	803	search database id field with string manipulated id	select * from orders where where 'a-123456-14' regexp '[:punct:]' + id + '[:punct:]'; 	0.000923719859045651
20970096	40054	ordering fields in a table upwards mysql	select   tablename.* from   tablename order by   substr(user,   least(     case when locate('0', user)>0 then locate('0', user) else length(user) end,     case when locate('1', user)>0 then locate('1', user) else length(user) end,     case when locate('2', user)>0 then locate('2', user) else length(user) end,     case when locate('3', user)>0 then locate('3', user) else length(user) end,     case when locate('4', user)>0 then locate('4', user) else length(user) end,     case when locate('5', user)>0 then locate('5', user) else length(user) end,     case when locate('6', user)>0 then locate('6', user) else length(user) end,     case when locate('7', user)>0 then locate('7', user) else length(user) end,     case when locate('8', user)>0 then locate('8', user) else length(user) end,     case when locate('9', user)>0 then locate('9', user) else length(user) end     )) + 0 	0.0402703482204634
20970684	37982	best (circle) for a (member) depening on best common	select circle_id, count(*) from member_circles mc inner join (     select relatedmemberid     from member_relations     where member_id = 1  ) x on x.relatedmemberid = c.member_id group by circle_id order by count(*) desc 	0.0033648558330378
20973036	36058	sql aggregating running count of records	select foo.cust_id      , foo.`date`      , min(p.`date`) as firstorder      , count(*) as ordercount from foo join foo as p   on p.cust_id = foo.cust_id     and p.`date` <= foo.`date` group by foo.cust_id, foo.`date` order by foo.`date`; 	0.0155698059634808
20973708	19790	organize similar items in columns from same table	select s.name as firstartist, j.name as secondartist, s.genre as commongenre from artist s  inner join artist j  on s.genre = j.genre and s.id < j.id 	0
20973867	22184	sqlite: multiple aggregate columns	select id,      sum(case when dayofweek = 1 then numevents else 0 end) as day1events,     sum(case when dayofweek = 2 then numevents else 0 end) as day2events,     sum(case when dayofweek = 3 then numevents else 0 end) as day3events  from eventtable group by id; 	0.125028233544229
20974383	14112	sql query to sum-up amounts by month/year	select year(date) as y, month(date) as m, sum(paid) as p from table group by year(date), month(date) 	0.243795928937902
20975539	22930	deleting rows before a date with datetime-field	select id from `wp_users` where user_registered < '2013-12-01' 	0.005169360876722
20976315	27324	create oracle table based in xml file	select * from   table-with-xml-column t ,      xmltable        ( 'path/to/what/you/need'           passing t.xml_column_name          columns column1 number       path 'path1'          columns column2 char(1 byte) path 'path2'          columns column3 varchar2(30) path 'path3'        ) t2 	0.00456621948726177
20976332	34346	how to group mysql query results by hour?	select count(*) as total, hour(from_unixtime(`date`)) as hour ... group by hour(from_unixtime(`date`)) 	0.0339070223270566
20979714	34308	get new clients per day for a month	select     count(*) as clients,     date( from_unixtime(added) ) as date_added from     table where     date_added >= concat( year(curdate()) , '-' , month(curdate()) , '-' , '01' ) group by     date_added asc 	0
20980330	36386	sql > edit select sum(column) group by hour for dataset	select      s.number as ohour,      sum(isnull(o.total,0)) as total  from      master..spt_values s     left join orders o on s.number = datepart(hour, date) where     s.type = 'p'     and s.number between 0 and 23 group by      s.number 	0.0464342385587025
20980508	35145	multiple category join	select * from business b inner join business_con_category bc on b.id=bc.business_id where bc.category_id=4 and b.city=4; 	0.0652387489507022
20980812	35751	multiple filters per item	select * from tblapartments t     where active = 1      and exists (select f.aptid from tblapartmentfilters f                  where f.filterid = 1 and f.filteroptionid = 7 and f.aptid = t.aptid)     and exists (select f.aptid from tblapartmentfilters f                  where f.filterid = 2 and f.filteroptionid = 18 and f.aptid = t.aptid) 	0.000991844189516168
20981034	30905	select status of last activity of each ticket and use the status within where	select c.data_criacao_chamado from atividades a join      (select fk_chamado, max(id_atividade) as latest_atividade from atividades group by fk_chamado) latest_atividades         on a.fk_chamado = latest_atividades.fk_chamado and a.id_atividade = latest_atividades.latest_atividade and a.status_item not in (3,5) join      chamados c on c.id_chamado = a.fk_chamado 	0
20981252	8737	date is null rather than using default value	select coalesce( jobfromdate, l_default_date) result from jobdates; 	0.0152331887297497
20982009	1229	adding extra columns along with a union	select *, 1 as fldbf,            row_number() over (partition by fldpk, fldcia order by fldpk) as scount  into #tmptable  from v_qrycspga  where fldpk in(select distinct thepk from fn_qryalldtpk())  union all    select *, -1 as fldbf, -1 as scount  from fn_qrycsgba()  where fldpk in(select distinct thepk from fn_qryalldtpk()) order by fldpk, fldcia, fldndat; 	0.00737748219938
20982570	35736	check if internal (nested) mysql query returned a value	select * from products where     client=123     and product=234     and not exists (select 1 from block_list where client=123) 	0.13571401298577
20983732	16396	can we do in mysql a select query that order by date and add anything that expire current date on the bottom of the query?	select     distinct title,     (case when representationdate >= now() then 1 else 0 end case) as `current` from show where id = 23 order by `current` desc, representationdate asc 	0
20984047	2476	sql combine two tables with two parameters	select id, date, state_on_date, (   select top 1 year_quantity     from table2    where id = t.id      and date >= t.date    order by date ) as year_quantity   from table1 t 	0.00787790169792021
20984247	30178	get single corresponding row based on lowest distance for each job	select * from (   select *,   round(3956 * 2 * asin(sqrt(power(sin( (@user_lat - abs(loc.latitude))  * pi()/180 / 2),2) + cos(@user_lat * pi()/180 ) * cos( abs(loc.latitude) * pi()/180) * power(sin((@user_lng - loc.longitude) * pi()/180 / 2), 2) )), 2) as distance   from locations   order by distance) loc group by job_id 	0
20984798	39985	php mysql return values in same columns	select group_concat(columnvalue separator ', ') from table group by columnname; 	0.000277994562854959
20984987	10989	counting subquery in sql	select id_count, count(*) as 'num_count' from (select a.process_track_id             ,count(*) as 'id_count'       from transreport.process_name a       group by a.process_track_id       )sub group by id_count 	0.424227783093542
20985817	26036	sqlite: using other tables to exclude results from self-join	select str1._id, str2._id from story as str1, story as str2 where str1._id < str2._id and (select chr_id     from participant     where isparent = 0     and str_id = str1._id     intersect     select chr_id     from participant     where isparent = 0     and str_id = str2._id) is null; 	0.00038269325637474
20990807	12924	c# to sql - date format	select * from tbldata where ( [date] >= @datefrom and [date] <= @dateto ) 	0.0964104174434241
20992673	40546	count the number of columns where a condition is true? sql server 2008 r2	select  case when col1 = 3 then 1 else 0 end + case when col2 = 3 then 1 else 0 end + case when col3 = 3 then 1 else 0 end + case when col4 = 3 then 1 else 0 end from tablename 	0.0117708528494322
20992744	3279	mysql howto access temporary table generated by subquery in another subquery?	select a.productid as gmid,         sum(if(b.assigndate between '$date1' and '$date2', b.amount, 0)) as sum0,         sum(if(b.assigndate between '$date2' and '$date3', b.amount, 0)) as sum1 from somerealtable a left join tmp b on a.productid=b.gmid  group by productid 	0.182078261605641
20993357	11995	mysql query from 2 tables confusion	select users.user_id, 'users' from users  where users.name='mikeboss' union  select users_archive.user_id, 'archive' from users_archive where users_archive.name='mikeboss'; 	0.149728117181282
20996049	17459	price comparision in mysql query	select * from tablea where (case pricetype when 1 then price when 2 then price * (800000 / 1000) end) <= $price 	0.128272024744017
20996368	28901	mysql: alter table drop foreign key based on select result	select concat(     'alter table network_profile drop foreign key \'',     constraint_name,     '\' ) into @sqlst from information_schema.key_column_usage ... ; prepare stmt from @sqlst; execute stmt; deallocate prepare stmt; set @sqlstr = null; 	0
20996407	10503	select rows based on where clause which return multiple rows	select * from mentor m where m.id in ( select ml.id from mentorlanguage ml, studentlanguage sl   where ml.language like sl.language    group by ml.id ) 	0
20999341	9517	how to select * from table where "function_value"? in mysql?	select * from dados  where (select fn_distance ($a, $b, lat , lon)) >100; 	0.014014239801185
21000057	4634	select all categories for each k2 item	select i.id      , i.title name      , c.name cat    from k2_items i   left   join k2_categories c      on find_in_set(c.id,i.catid)>0; id  name    cat 1   item 1  category 1 1   item 1  category 2 2   item 2  category 1 2   item 2  category 2 2   item 2  category 3 3   item 3  category 2 3   item 3  category 3 	0
21000292	27292	sql select using same table for join	select l.*  from loads as l  join route as r1    on r1.zipcode = l.pu_zipcode  join route as r2    on r2.zipcode = l.do_zipcode  where r1.route_order < r2.route_order 	0.0417364826136922
21001631	18414	in-stock product count by day	select w.work_date, count(p.name)  from workdays as w join products as p   on p.received < w.work_date and (p.sold is null or p.sold > w.work_date) group by w.work_date 	0.00374795474681817
21002037	35728	can't find a column that exists	select r.roomid, m.messagecontentid,  m.message, m.msgdate, m.sender, m.receiver, m.ismine    < from room r left join  ( select     m1.messagecontentid,    m1.roomid,    m1.message,    m1.msgdate,    m1.sender,    m1.receiver    <    ,m1.ismine  <    from messagecontent m1 join       ( select        r1.roomid,        max(m2.msgdate) maxmsgdate        from room r1        left join messagecontent m2 on r1.roomid = m2.roomid        group by r1.roomid      ) mf on m1.roomid =  mf.roomid           and m1.msgdate = mf.maxmsgdate  ) m on r.roomid = m.roomid 	0.0337624667919782
21003554	7508	subtract totals from 2 tables	select     accountnumber,    sum(amount) as balance from (    select d.accountnumber as accountnumber, sum(d.amount) as amount from deposit d group by d.accountnumber    union    select d.accountnumber, sum(-d.amount) from withdrawal d group by d.accountnumber ) as t group by accountnumber 	0.00029497208033267
21004056	8722	positioning rows according to column values in sql	select name , dense_rank() over (order by mark) position from table order by position 	0.000326704950038714
21004170	9167	sql timestamp, eliminate duplicate rows	select * from product_price qualify    row_number()     over (partition by product_number          order by update_timestamp desc) = 1; 	0.000999466203115707
21005708	33603	how to connect 2 suqueries which doesn't return single value? mysql	select pl,te from  (select function(player.age, stats.a, stats.b), id from player join stats where tname = 'player') as pl  join  (select function(team.ratio, stats.a, stats.b), id from team join stats where tname = 'team') as te on pl.id = te.id 	0.00159871555166139
21007845	13061	use values from postgres subquery that returns json arrays	select id from prompts where (id in (array(select properties->>'prompt_ids'::integer from "prompts" where (type = 'aggregate')))); 	0.0291017394905072
21008934	9492	how to take the data from two tables?	select group_concat(city.name,city.city_id),region.name as region_name from city  left join region  on (city.region_id = region.region_id) group by region.name; 	0
21010461	31625	searching names with sql	select firstname,         middlename,         lastname  from   people  where  ( upper(firstname) like token1            or upper(middlename) like token1            or upper(lastname) like token1 )  intersect  select firstname,         middlename,         lastname  from   people  where  ( upper(firstname) like token2            or upper(middlename) like token2            or upper(lastname) like token2 ); 	0.0870399787356656
21011698	3200	selecting distinct value from a column in mysql	select sender_id,goods_id from items t1 where not exists (select 1 from items t2                   where t2.sender_id = t1.sender_id                     and t2.receiver_id = t1.receiver_id                     and t2.price > t1.price)  and receiver_id = 1 order by price desc 	9.84938148170579e-05
21012375	7378	retrieve size of field having varchar datatype in sql server using c#	select table_catalog,         table_name,         column_name,         data_type,         character_maximum_length  from   information_schema.columns  where  data_type = 'varchar' 	0.00623109869839529
21012791	11506	convert columns to rows in oracle	select date,qty from (select date,qty1 as qty from tbl union select date+7 as date,qty2 as qty from tbl union select date+14 as date,qty3 as qty from tbl union select date+21 as date,qty4 as qty from tbl) order by date 	0.00453126145956401
21014295	639	create xml in t-sql with one table	select i1.rank as 'rank/@id',        (        select i2.name        from info as i2        where i1.rank = i2.rank        for xml path(''), type        ) as rank from info as i1 group by i1.rank for xml path('data') 	0.0288209568279692
21015067	28861	how to get latest record on the top using desc but the records come from two tables	select     crb_issues.id,     crb_issues.title,     crb_issues.volume,     crb_issues.number,     crb_issues.publish_date,     crb_issues.is_publish,     crb_issues.pdffile,     crb_issues.flyer,     crb_issues.cover,     crb_issues.`status`,     crb_issues.issuetype,     crbissue_data.typevalue,     crbissue_data.typefieldname,     crbissue_data.typedata,     crbissue_data.issueid,     crbissue_data.id from crb_issues inner join (select max(id) id              from crb_issues             where crb_issues.is_publish = '1' and crb_issues.issuetype = '0') latest       on crb_issues.id = latest.id inner join crbissue_data on crb_issues.id = crbissue_data.issueid 	0
21016168	18223	compare datetime field (for birthday) with today	select * from person  where datepart("month", birthdate) = datepart("month", getdate())  and datepart("day", birthdate) = datepart("day", getdate()) 	0.000235159270398404
21016664	13369	display bit values from database in a combobox	select 'bunglows'  from   tblsocietydetail  where  str_societyname = @strsocietyname         and bit_societytypebunglow = 1  union  select 'flats'  from   tblsocietydetail  where  str_societyname = @strsocietyname         and bit_societytypeflat = 1  union  select 'pent houses'  from   tblsocietydetail  where  str_societyname = @strsocietyname         and bit_societytypepent = 1  union  select 'row houses'  from   tblsocietydetail  where  str_societyname = @strsocietyname         and bit_societytyperow = 1; 	0.000225356821376145
21017001	41038	output in sql table : without using join	select * from test1 union select * from test2 	0.480606292993655
21017647	146	select only one entry of multiple occurrences	select *    from table     where id in (select max(id) from table group by fk) 	0
21017697	14724	php / mysql - how to select only the most recent value for each different value	select `id`, `imei`, `latitude`, `longitude`, `date`       from (select *,                     if(@lastid = @lastid:=imei, @idx:=@idx+1, @idx:=0) rownumber              from `my table` l, (select @lastid:=0, @idx:=0) a             order by `imei` desc, `date` desc            ) as a where rownumber = 0 	0
21018044	40277	select subarray and its length in postgresql	select l.country, c.list, c.list_count from   location l left   join (    select location_id as id          ,array_agg(id) as list          ,count(*) as list_count    from   competition    group  by 1    ) c using (id) 	0.0704784082768592
21018187	37698	show in one column by selecting from multiple column by date	select user_name, date(request_date) request_date,         sum(if(sim_id = 1, request_amount, 0)) sim_id1,         sum(if(sim_id = 2, request_amount, 0)) sim_id2,         sum(if(sim_id = 3, request_amount, 0)) sim_id3,         sum(request_amount) total_amount from request  group by user_name, date(request_date) 	0
21019973	2398	sql: combination of one column + count	select st1.action, st2.action, count(*) from sourcetable st1 left inner join sourcetable st2 on (st1.userid=st2.userid) where (st1.rowid <> st1.rowid) and st1.action <= st2.action group by st1.action, st2.action having count(*) > 0 	0.00156549905052547
21019990	24566	selecting only rows containing at least the given elements in sql	select parent from table where child in(10,20) group by parent  having count(distinct child)>=2 	0
21021520	9379	mysql group_concat of first n rows	select    group_concat(user_id) as userids from   (select      user_id   from     user_tasks   where due_date > curdate()   limit 10) as users 	0.000308661177832327
21022344	2350	mysql average latest 5 rows	select avg(result) from (select result       from tests       where line_id = 4       order by test_time desc       limit 5      ) t 	0
21023276	6916	mysql substring_index() for fetching value after "-"	select substring_index(table1.`val1`,'-',-1)as value1, max(table1.`covered charges`) as `max covered charges`for selected hospital` from table1 	0.399818294907854
21024639	36992	how to filter an xml field on multiple conditions	select * from mytable as t where t.xmlfield.exist('/dictionary[item[key/int/text() = 1 and value/string/text() = "web"] and                                        item[key/int/text() = 2 and value/string/text() = "email"]]') = 1 	0.0154455554541533
21027928	34502	mysql query to show value that matches exact values only	select * from table1  where data_id = $value and $value regexp '^[0-9]+$' 	0
21029303	33163	sql result with numbers as column headers, how to call with with php or change sql column headers for pivot	select section,    [0.9] as a,   [1.2] as b from t  pivot  (    avg(stock)    for length in ([0.9], [1.2]) ) piv 	0.029794622288117
21029817	4413	case statement based on sum results in query	select bill.billnumber_id, billdetail.billclass, sum(billdetail.amount) as amount,        (case when sum(billdetail.amount) > 10 then 'bigone'              else 'little'         end) group by bill.billnumber_id, billdetail.billclass 	0.161999415649343
21030990	26337	android "null" from sum	select total(g.field1),         total(g.field2),         ... 	0.0886673080090635
21031374	2589	select users who is not member of group	select distinct username from table   except  select username from table where group_id = 2 	0.00249539285894902
21031837	17646	mysql select distinct records	select * from (   select s.swimmername, r.resulttimetext, r.resultagegroup, r.resulteventid, v.venuename        from tblresults r   join tblevents e on e.eventid = r.resulteventid   join tblswimmers s on r.resultswimmerid = s.swimmerid   join tblvenues v on e.resultvenueid = v.venueid   where s.swimmergender = %s   and r.resultstroke = %s   order by 2) x group by swimmername order by 2 	0.0107933968119376
21031975	34083	sql query month name sort	select    max(datename(month, reqdate)) as month, count(wo_num) as tickets from      dbo.tasks where     (reqdate >= '6/1/13') group by  datepart(month, reqdate)   order by  datepart(month, reqdate) asc 	0.00713025001166288
21033615	40043	refine query results from mysql database	select routes.route_date, time_slots.name, sum(time_slots.openings), sum(time_slots.appointments) from routes inner join time_slots on routes.route_id = time_slots.route_id where route_date between 20140109 and 20140115 and time_slots.openings > time_slots.appointments group by routes.route_date, time_slots.name order by route_date, name 	0.0484273332079423
21033830	6311	sql table data source	select object_name(id) from syscomments where text like '%table_name%' 	0.044931732111169
21033899	40002	vb.net get the last id and display it	select max(id) as lastid from customers 	0
21036834	34947	sql and pattern matching	select * from some_jobs where jobtype like '%$keyword%' and state=1 	0.0745508425946181
21036855	39851	display row value as column after grouping- oracle	select t.customer_id,         count(case when result = 'success' then 1 end) count_success,         count(case when result = 'failure' then 1 end) count_failure from   tbl_dtl_feature t where  t.feature_id = 'f001' and    trunc(t.start_datetime) between to_date('10/01/2014', 'dd/mm/yyyy') and to_date('10/01/2014', 'dd/mm/yyyy')  group by t.customer_id; 	7.65229075384811e-05
21037465	4852	to calculate average of date differences in a column in sql server	select zone , avg(numofdays) from           (select zone, (datediff(dd,startdate,enddate)-datediff((ww,startdate,enddate)*2)) as         numofdays from table where startdate >'1/1/2013')     group by zone 	0
21037826	24771	tsql query for time range	select     [appid] = freeapps from table_name t1     where appid not in (         select appid         from table_name t2             where ((starttime >= '17:00' and starttime <= '18:00')                   or (endtime >= '17:00' and endtime <= '18:00'))               and date = '12/1/2013'               and t1.appid=t2.appid) group by appid 	0.040505555848848
21042057	25414	how to combine these two results as one in mysql?	select b.user_id,b.first_name, b.last_name, b.email_id, sum(sharedfiles)as sharedfiles from( select b.user_id,b.first_name, b.last_name, b.email_id,  count(distinct a.file_id) as sharedfiles   from email_history a, users b   where a.email_receiver_id = b.user_id  and a.email_sender_id= 20   group by b.user_id,b.first_name, b.last_name, b.email_id   union   select b.user_id,b.first_name, b.last_name, b.email_id,  count(distinct a.file_id) as sharedfiles   from email_history a, users b   where a.email_sender_id = b.user_id   and a.email_receiver_id= 20   group by b.user_id,b.first_name, b.last_name, b.email_id)x group by b.user_id,b.first_name, b.last_name, b.email_id; 	0.00171494394406865
21042467	35375	get the list of views given by linked servers in sql server	select * from [linked_server].[database].sys.views 	0.000199507179223297
21043105	17597	finding gaps in concurrent date ranges - mysql	select   users.user, count(*) from     users            cross join weekdays             left join userdates on                         userdates.user  = users.user                    and  userdates.from <= weekdays.date                    and (userdates.to is null or userdates.to >= weekdays.date) where    weekdays.date >= '2013-01-01'      and weekdays.date <  '2014-01-01'      and userdates.user is null group by users.user 	0.000322423777650697
21044656	35096	how to get top 8 the most common values​​?	select tag, count(tag) as frequency from tags gorup by tag order by frequency desc limit 0,8 	0
21045712	19074	unroll table with multiple keys and values in each row with sql	select key1, value1 from table union all  select key2, value2 from table 	0
21046818	18524	orace/sql multiple group by	select    at.pieceno, at.created,count(*)  from      send_piece at   where     message_no in (7104, 7113)  and       at.created > to_timestamp('01-jan-14 00:00:00', 'dd-mon-yy hh24:mi:ss')  group by  at.pieceno, at.created; 	0.412009420803338
21047360	5013	how to find timeslot conflict in sql query	select count(1)  from t1 inner join      t2      on cast(t1.starttime as time) < cast(t2.endtime as time) and         cast(t1.endtime as time) > cast(t2.starttime as time); 	0.718373368632185
21048062	28489	getting values as list in list in c# from 3 joined tables tsql	select      p.*, c.* from        parents            p left join   parentschildren    pc    on    pc.parent_id    = p.parentid left join   children           c     on    c.childid       = pc.childid 	0
21048295	3843	sql - order by with alphanumeric characters	select product_id from tbl               order by len(product_id), product_id 	0.379318560237931
21048439	7889	mysql select sum(price) last month	select stk_id, sum(price) from sales left join stk on stk_id = stk.id left join stk_type on type_id  = stk_type.id where date >= date_sub( curdate(), interval 1 month ) group by stk_id 	0.000220300471866649
21048878	33947	sql (oracle) joins when column results are slightly different	select ... from table1 t1  right join table2 t2 on t1.key_id = to_number(substr(t2.doc_num,2)); 	0.192051467689189
21049204	24560	update list of time values from single column in sql server?	select convert(varchar(8), convert(datetime,'12:00:00',14)-convert(datetime,'9:19:4',14) ,14) 	0
21049276	3332	sql: count two different columns from two different tables	select p.id,   (select count(*) from data_table_1 t1 where t1.id=p.id) count1,   (select count(*) from data_table_2 t2 where t2.id=p.id) count2 from projects p 	0
21049865	27663	suppress bad data within mysql query	select replace(column_name, '<br/>', '') as comments from table1; 	0.781373006910152
21051402	1516	sql to always return false	select case when 1=2 then 1 else 0 end from dual 	0.185068692666728
21051934	19942	how to use the result of a built-in sql function twice in a single query?	select case          when substr1 is null             then '????'         when substr1 in ('000', '010', '018')             then '100l'         when substr1 = '123'             and substring(a, 8, 3) = 'abc'             then 'xxx'         end from (     select substring(a, 4, 3) as substr1 from mytable     ) a 	0.32324945423515
21053185	34436	how can i calculate rankings of unique values in mysql?	select appid, count(*) from mytable group by appid order by count(*) desc 	0.000437837415148997
21055551	26011	sql - get count from one table based on result of query	select e.event_name,   e.event_time,   e.total_spaces_available,   (select count(*) from bookings b where b.event_id=e.event_id) as number_of_bookings from events e 	0
21055682	1963	group by, show min	select title, min(date) from financials group by title order by title 	0.0411591625365187
21056433	33810	import data from mysql to stata	select ... into outfile 	0.014493804776382
21057258	3804	select entries only with dates between two specified dates	select * from mytable where mydate > '2008-6-22' and mydate < '2014-1-10' 	0
21058630	20828	sql : how to translate rows to one field?	select  b, stuff((select ', ' + c + ': ' + cast(d as varchar)         from table xt         where xt.b = t.b         for xml path('')), 1, 2, '') from table t group by b 	0.00375581374633808
21059077	32950	ms access select top n query grouped by multiple fields	select studentid, year, subject,  avg(testscore) as avgscore   from (   select studentid, year, subject, testscore    from mytable t    where testid in   (    select top 3 testid       from mytable     where studentid = t.studentid       and year = t.year       and subject = t.subject     order by testscore desc, testid   ) ) q  group by studentid, year, subject  order by studentid, year, subject; 	0.00226238227557807
21059201	22260	mysql query request from two tables with in clause	select v.id, v.fieldsid, v.value, v.ordering, count(p.productid) as count from `ms_fields_values` v left join `ms_conn_products_to_fields_values` p on p.fields_values_id = v.id and p.productid in (9, 11, 12) where v.fieldsid =1 group by v.id order by `ordering` asc 	0.119871873682545
21059611	39756	how to get data for different conditions in sql server?	select ft.feedtype,         round( mr.rateperkg,3)as rateperkg,         round( mr.rateper50kg,3)as rateper50kg   from   k_fs_feedmrpdetails mr         inner join k_fps_feedtype ft             on ft.sno=mr.feedtype  where date in (select top 1 date from k_fs_feedmrpdetails order by date desc ) 	0.00282133996879756
21060463	14998	how to apply the where clause of the whole query on the sub-queries also?	select u.username, u.id, count(t.tahmin) as tahmins_no,         sum(t.result = 1) as winnings from users u  left join tahminler t on u.id = t.user_id  left join matches_of_comments mc on t.match_id = mc.match_id where month(str_to_date(mc.match_date, '%d.%m.%y')) = 1 and        year(str_to_date(mc.match_date, '%d.%m.%y')) = 2014 and flag=1 group by u.id  having tahmins_no > 0 	0.0276326241420277
21060994	18113	"double group by" in oracle sql?	select d.dname from emp e  inner join dept d on(e.deptno = d.deptno)             inner join salgrade s on(e.sal between s.losal and s.hisal) group by d.dname having count(distinct s.grade) = (select count(*) from salgrade); 	0.786350602908533
21062517	33407	select most viewed for the last 24 hours	select articles.*, count(*) views24h     from articles     left join pageview on pageview.articleid = articles.id                and pageview.viewdate > subdate(now(),1)     group by article.id     order by views24h desc     limit 10; 	0
21064411	35304	perform query calculations on two tables	select avg(paymentdays) from (select sp.sales_id, (datediff(max(sp.payment_date), min(sp.payment_date)) + 1) as paymentdays       from sales_payment sp       group by sp.sales_id      ) sp; 	0.13416798034345
21064443	37637	mysql - get records who doesn't have refferal	select r.id as id  from users as u right join ref as r  on ( u.ref_id = r.id ) where u.ref_id is null 	0.000669749052400365
21066807	17739	select from one table where does not exist in another	select * from people  where personid not in (select personid                         from absences                         where datevalue(absences.absentdate) = '20140111')                                                                   ^ yyyymmdd 	0.00289430063912011
21067931	33313	combining duplicate results	select requests.cust, sum(price.cost) from requests join price on requests.serv = price.serv group by requests.cust order by requests.cust asc 	0.0274414036188502
21068030	23869	changing charset of mysql database comes to select issues?	select * from table where column='%ü%' collate utf8_bin 	0.78931889076329
21068737	2453	rename all columns from a table within select	select '      u1.'+column_name+' as customer_'+column_name+',' from information_schema.columns where table_name = 'users' and schema_name = 'dbo'; 	0
21070898	34238	access a parent field from sub query in mysql	select id, remind, rid, title from reminders where datediff(start_day, now()) <= least(3, remind); 	0.0437945932008238
21070914	25679	most efficient way to find friends of friends, excluding freinds	select f2.uid2 from friends f1 join friends f2 on f1.uid2 = f2.uid1 left join friends f3 on f3.uid2 = f2.uid2 and f3.uid1 = 'yourid' where f1.uid1='yourid'  and f2.uid2!='yourid' and f3.uid2 is null 	0
21071776	8946	how to return difference of successive rows in a column with other data (mysql)	select document_no, bill_date, bill_amount,         (@balance := @balance + bill_amount) as balance from ((select bill_no as document_no, bill_date as trans_date, bill_amount as amount        from bill_table        where consumer_name = 'john'       )       union all       (select receipt_no as document_no, receipt_date as trans_date, -receipt_amount as amount       from receipt_table       where consumer_name = 'john'      )     ) t cross join     (select @balance := 0) const order by trans_date; 	0
21071844	9619	sql join tables of elements that have two types	select o.id, o.name, t1.name as name1, t2.name as name2 from objects o left outer join      types t1      on o.type1 = t1._id left outer join      types t2      on o.type2 = t2._id; 	0.000127932667117444
21071987	5619	is there anyway to count values in a set of mysql cloumn	select id, length(colname) - length(replace(colname, ',', '')) + 1 as set_count from yourtable 	0.0179454734342409
21072705	21890	mysql selecting column as null if join is not made	select    table1.*,   case when table3.f_type is null then null else table2.value end as emailaddress  from   table1    left join table2      on table2.f_contact = table1.f_contact     and table2.f_type = 2    left join table3      on table3.table2_id = table2.id     and table3.f_type = 3  where table1.f_contact = 1113 	0.370140291218738
21075029	29700	sql to retrieve related records with many to many relation	select c.id, i.id, i.name from contracts c    join contract_institutes ci on c.id = ci.contractid   join institutes i on i.id=ci.instituteid where ci.instituteid <> *somevalue*     and ci.contractid in (select ci2.contractid          from contract_institutes ci2         where ci2.instituteid = *somevalue*) 	0.000298702950610877
21076344	31309	how to compare results from the same timestamp in sql(sqlite)?	select dt,        max(case when ab = 'a' then price end) as a_price,        max(case when ab = 'b' then price end) as b_price from prices group by dt; 	0
21077145	13987	sql selecting spatial points	select x(coordinates),y(coordinates) from table 	0.228057906672105
21077653	25289	finding the 100th 200th and so on records in sql server	select * from tbl_point where point%100=0 and point>0 	0.0142843131894283
21077677	12885	comparing two tables and returning answers that do not appear in both in mysql	select seat_q.area_name, (seat_q.num_seats - count(*) as occupied_seats) as free_seats from booking b where row_no in (     select s.row_no      from seat s     where s.area_name = 'front stalls'     group by s.area_name) join (select s.row_no, s.area_name, count(s.*) as num_seats  from seat s  where s.area_name = 'front stalls'  group by s.area_name) as seat_q on seat_q.row_no = b.row_no where b.date_time = '21:00, 7.7.14' 	0.00732770383507095
21077987	14817	mysql select 2 items from multiple tables	select    i.item_name,   i2.item_name  from   items i    join item_pairs ip      on ip.item_id_1 = i.item_id    join items i2      on ip.item_id_2 = i2.item_id  group by ip.item_id_1,   ip.item_id_2 	0.000169715965959235
21080243	15793	selecting data from table b based on the output of select from table a	select * from `order` order     inner join `orderitem` items         on items.orderid = order.orderid where order.orderdate <= date_sub(now(), interval 7 day) 	0
21083870	34752	how to use tables returned from subquery in sql query in oracle	select t1.offer_id,t1.offer_name,t1.total_offers_sold, t3.total_device_changed,t2.total_offer_changed  from table1 t1 left outer join table2 t2 on t1.offer_id = t2.offer_id left outer join table3 t3 on t1.offer_id = t3.offer_id  order by t1.offer_id; 	0.292755797413818
21084354	14639	select query into list on one column	select group_concat(id) as idlist from tablea 	0.000416314708327667
21084969	21188	mysql - getting age and numbers of days between two dates	select a.user_id, b.last_name, b.first_name, c.birth_date,         floor(datediff(current_date(), c.birth_date) / 365) age,         datediff(b.left_date, b.join_date) workdays from users a inner join users_signup b on a.user_id a = b.user_id inner join users_personal c on a.user_id a = c.user_id where b.join_date >= '2013-01-01' and b.join_date < '2014-01-01' group by a.user_id 	0
21086593	346	mysql get latest 3 rows for every id in where in	select a.*, u.name  from (select c.*, if(@updateid = @updateid:=update_id, @idx:=@idx+1, @idx:=0) idx        from comms c, (select @updateid:=0, @idx:=0) a       where update_id in ('1451', '1416', '1186', '1157', '1150', '1122', '1057', '914', '850', '816', '794', '790', '749', '746', '745', '744', '740')       order by update_id, id desc        ) as a  inner join users as u on u.id = a.user_id where a.idx < 3 	0
21086803	1741	sql: count emails per year	select year(rcm_datesent) as yearsent, count(*) as numbersend from mail group by year(rcm_datesent) order by yearsent 	0.000841517733293685
21087174	34087	why no results are displayed when searching a value in hebrew string?	select [id] ,[caption] from  [dictionary] where cast(caption as nvarchar(max))like n'חי%' 	0.0399204894828372
21087429	2395	how to join these rows into one record in the same table	select a.date,         sum(case when a.methos = 'a' then a.count else 0 end) as 'a',         sum(case when a.methos = 'b' then a.count else 0 end) as 'b',         sum(case when a.methos = 'c' then a.count else 0 end) as 'c',         sum(case when a.methos = 'd' then a.count else 0 end) as 'd',         sum(case when a.methos = 'e' then a.count else 0 end) as 'e',         sum(case when a.methos = 'f' then a.count else 0 end) as 'f',         sum(case when a.methos = 'g' then a.count else 0 end) as 'g',         sum(case when a.methos = 'h' then a.count else 0 end) as 'h' from tablea a  group by a.date 	0
21087865	7446	database size different after export/import	select table_name, table_rows, data_length, index_length,  round(((data_length + index_length) / 1024 / 1024),2) "size in mb" from information_schema.tables where table_schema = "test"    union all select 'total', sum(table_rows), sum(data_length), sum(index_length),  sum(round(((data_length + index_length) / 1024 / 1024),2)) "size in mb" from information_schema.tables where table_schema = "test"   group by 1 	0.0182140183789334
21088184	34133	display records from a table using if statement	select a.*, c.category_name from articles a  inner join categories c on a.article_category_id = c.category_id  where c.category_id = '$id' and a.article_type_id in (1, 2, 3) order by a.article_id desc  limit $start, $limit 	0.000157648683654456
21089054	4414	mysql - order by string date	select p.*, s.meta_value from posts p  left join storage_varchars s on p.id = s.post_id  where parent_id = 20 and str_to_date(s.meta_value, '%d-%m-%y') >= current_date()  order by str_to_date(s.meta_value, '%d-%m-%y') asc; 	0.0646493758258014
21089623	26625	using posgresql for storage image routes	select currentpic,        id_image,        route from   (select row_number() over (order by id_image) as currentpic,                id_image,                route         from   location.image) as q where  currentpic = 3 	0.784024611052717
21092082	27981	sql query to get title name	select  b.parent_function_id,  parent_function = (select top 1 a.title from [dbo].functions a  where  a.functionid = b.parent_function_id),  b.child_function_id,    child_function = (select top 1 c.title from [dbo].functions c  where  c.functionid = b.child_function_id) from [dbo].[function_hierarchy] as b 	0.00946344354968997
21092539	13711	mysql add join to query	select distinct    *,   3956 * 2 * asin(     sqrt(       power(         sin(           ($orig_lat - abs(dest.wlatitude)) * pi() / 180 / 2         ),         2       ) + cos($orig_lat * pi() / 180) * cos(abs(dest.wlatitude) * pi() / 180) * power(         sin(($orig_lon - dest.wlongitude) * pi() / 180 / 2),         2       )     )   ) as distance  from   mytable dest    left join other_table o on dest.column=o.column having distance < $dist  order by distance 	0.390270985891185
21094289	1530	sort sql table by sum of values of associated table	select a.id, a.ip, a.network, sum(b.in_bytes + b.out_bytes) as traffic from client a inner join connections b on a.ip = b.ip group by a.id, a.ip, a.network order by traffic 	0
21095086	15753	mysql locate duplicates between two table with similar column	select fort.matrix_unique_id fort.full_address as fortaddress, sun.fulladdress as sunaddress from fort_property_res fort, sunshinemls_property_res sun where fort.matrix_unique_id = sun.matrix_unique_id 	0.00502992120096403
21103180	36325	change mysql output column width	select left(your_column, 50000) from your_table; 	0.0828684988794348
21105521	1303	query results depends on result from seperate query	select pn,     sum(case when date='20141201' then qty end) as day1qty,     sum(case when date='20141202' then qty end) as day2qty from table group by pn 	0.00772995520650187
21106324	4517	joining two related tables in mysql	select *, orders.id as id, orders.name as name from orders  left join cart on orders.authid = cart.authid where orders.id != '0' group by orders.authid 	0.0031173945010022
21108100	20566	show only first row of each group excluding null	select patientid, caseno, gender, name   from  (   select patientid, caseno, gender, name,           row_number() over (partition by caseno order by gender) rnum,          count(*) over (partition by caseno) rcnt     from patients ) q  where caseno is null      or rcnt = 1     or (rcnt > 1 and rnum = 1)  order  by name 	0
21108448	31533	sql server : how to join record not in another table?	select a.sid,a.name,b.periodid,b.perioddescription,c.status from  staffdb a  cross join  [appraisal period] b left join  appraisal_record c on a.sid = c.sid and b.periodid =  c.periodid 	0.00933020025146286
21109186	32222	count of result of a sql query based on its return	select count([file_no]) from [my_file] where [file_no] like '%s%'; 	0
21111078	25941	mysql join two tables issue	select g.venue,g.game_date,g.logo,fb.game_selected as game_id,fb.accept_status,fb.request_id   from fb_request fb   left join game g on (fb.game_selected=g.id)  where fb.user_id=17; 	0.591407435254184
21111301	28552	using the output of an sql statement in another sql statement?	select event.event_id,booking.*  from event join booking on event.event_id=booking.event_id where booking.user_id='$id'; 	0.247630725174418
21112184	2825	sql query has few rows which are duplicate	select sno, users, tab1.ref, extra, max(ad) as ad from      tab1,tab2      where tab1.ref=tab2.ref      and tab1.users = 1     or tab1.extra=1 group by sno, users, ref, extra; 	0.000330635236761439
21112602	2111	mysql: how to get the percentage of non existing ids in a table using only one query	select (max(id)-count(id)) / max(id) * 100 as missingrate     from my_table 	0
21113017	1661	sql request for several tables and operations in mysql	select   cc.unit_id, min(cc.date) as stage_min_date , sum(dd.clicks) as stats_max_clicks from   stage cc left join (   select     bb.stage_id, bb.clicks   from     stats bb left join (       select id, stage_id, max(date) as max_date       from stats       group by stage_id     ) aa   on     aa.max_date = bb.date   where     aa.max_date is not null ) dd on cc.id = dd.stage_id left join unit ee  on ee.id = cc.unit_id where ee.status = 3 group by cc.unit_id 	0.598834207823952
21113989	5500	find those rows with only one value in another column?	select column1 from table1 t1 where (select sum(column2)        from table1 t2        where t2.column1=t1.column1        group by column1) = 0 	0
21114682	28325	meaning of a large mysql command	select      itm.*,     mem.username as username,     cpn.* from aw_rdw_items itm, members mem, aw_rdw_items_coupons, cpn where itm.item_id=cpn.item_id     and item_special_type != 'g'      and itm.item_id=cpn.item_id      and itm.memberid=mem.memberid      and item like('%".addslashes($_request["item_name"])."%')     $prs1 $prs2 $greenget $subsql order by display_order, itm.item_id asc 	0.45412953824572
21114873	31978	combining database tables in 3rd normal form	select s.name, c.color, co.college  from student s inner join favorite_colorid fc on s.studentid = fc.studentid  inner join color c on fc.colorid = c.colorid  inner join favorite_collegeid fco on s.studentid = fco.studentid  inner join college co on fco.collegeid = co.collegeid 	0.0219920909875716
21117957	38969	access columns within exists clause	select * from alluk a join allcompanies b on a.mobile = b.mobile 	0.412230405925754
21118156	8770	sub-query referencing a field in parent query	select      machineident,     entrygauge,      w.displayscalefactor,      round(entrygauge * w.displayfactor) as scaledentrygauge from coil inner join coilpass on coil.coilident=coilpass.coilident  inner join passsection on coilpass.passident=passsection.passident  inner join webreportparametersetup w on w.machineident = coilpass.machineident  where w.itemname = 'entrygauge' 	0.247465655143629
21118325	10100	grouping records in one single row	select id, max(city), max(state), max(country) from mytable group by id 	7.10944417640937e-05
21118690	26326	sql server : how to make multiple references to the same table substituting values	select r1.somecolumn, r2.somecolumn from master_table m           inner join refrenced_table r1   on m.column1 = r1.pk                           inner join refrenced_table r2       on m.column2 = r2.pk                   	0.000575964757851037
21119313	8474	mysql query date between dates	select * from contracts where your_date between date_start and date_finish 	0.00906104728719212
21121726	26042	won't group by?	select min(a.time), a.quiz_id, a.time, b.end, b.images,  b.prize_title from entries a, quiz b where a.quiz_id = b.id and  a.member = '".$_session['id']."' group by a.quiz_id 	0.706920997351037
21122181	8827	return first id matching a sequence of conditions	select      s.scode,      coalesce(l1.id, l2.id, l3.id) as id  from      #pocstbl  s  left join #poclutbl l1 on s.scode = l1.lc1  left join #poclutbl l2 on s.scode = l2.lc2  left join #poclutbl l3 on s.scode = l3.lc3 	0
21122399	40029	select mysql results, ignoring fields that have a count greater than x	select t.tracking, count(t.tracking) as count from tracking t  join (     select s.ip, count(s.ip) from tracking s group by s.ip having count(s.ip)<=2) d  on d.ip = t.ip group by t.tracking 	6.25728520054393e-05
21123529	12067	mysql query for check alerts during a timelapse and condition	select count(*) total   from (   select 1     from   (     select *,             @n := @n + 1 rnum,             @g := if(value between 15 and 20, @g + 1, 1) grnum,             @p := value       from table1 cross join (select @n := 0, @p := null, @g := 0) i      order by datetime   ) q    group by rnum - grnum   having count(*) >= 5      and timestampdiff(hour, min(datetime), max(datetime)) >= 1 ) p 	0.27987480699446
21123665	33563	sql show not duplicates lines left join	select name, part1, part2, item1, item2 from tomatch as t left join against as a on (  t.part1 = a.item1  or t.part2 = a.item1  or t.part1 = a.item2  or t.part2 = a.item2  ) group by name, part1, part2, item1, item2 having count(*) = 1 	0.279093681786301
21123794	16302	find records with a single common field, but different values for other fields	select distinct p.* from promotions p      join promotions q on p.promoid = q.promoid and p.id <> q.id where (p.customerid <> q.customerid)      or (p.dealperiod <> q.dealperiod)      or (p.lob <> q.lob) 	0
21125527	9479	how to get related articles by tag names?	select a1.id, group_concat(distinct a2.id) as related_articles from articles as a1 join article_tags as t1 on a1.id = t1.article_id join article_tags as t2 on t2.tag_name = t1.tag_name and t2.article_id != t1.article_id join articles as a2 on a2.id = t2.article_id group by a1.id 	0
21126094	20686	select statement for more than 1 value of a column for condition	select  o.orderid [order number], s.salemanname [saleman], p.product_type [product type]  from    (             select  x.orderid             from    [order] x                     inner join producttypes pt on x.producttypeid = pt.productid             where   x.month= '01'                     and x.year='2014'             group by x.orderid             having count(pt.productid) > 1         ) o         left outer join [order] od on o.orderid = od.orderid         left outer join saleman s on od.salemanid = s.salemanid         left outer join producttypes p on od.producttypeid = p.productid 	0.00184157551409465
21128506	33843	count number of available in mysql	select u.name, sum(q.available) as count_available from users u left join      qty q      on u.id = q.user_id group by u.name; 	0.000758786909424583
21129766	15747	sql, multiple if statements, then, or else?	select personid,lastname,firstname,age,        case when age between 26 and 27 then 'post graduate'             when age between 28 and 30 then 'working and single'              when age between 31 and 33 then ' middle level manager and married'              else 'nil'        end comments  from persons 	0.740817242876874
21132735	8064	how to create a range for the given data	select count(case when age >= 26 and age <= 27 then 1 else null end) as [total26to27]       ,  count(case when age >= 28 and age <= 30 then 1 else null end) as [total28t30]       ,  count(case when age >= 31 and age <= 33 then 1 else null end) as [total31t33] from persons 	0.00011274472181017
21133520	6643	sql for specific count of table entries	select userid, count(userid) as usertotal from yourtable group by userid 	9.49723778664279e-05
21135758	11179	mysql group by two columns either way	select least(column1, column2), greatest(column1, column2) from table1 group by  least(column1, column2), greatest(column1, column2) 	0.0253243392625829
21136329	5746	mysql rows disappearing (mysteriously)	select count(*) from tablea; select count(*) from tableb; select count(*) from tablec; 	0.117147396753728
21139197	9828	how to join two tables	select b.col1, b.col2, a.col1, a.col2 from a left outer join      b       on a.key = b.key; 	0.0304643536326955
21140062	7120	how to check if there is any zeros in column fields using sql	select count(*) from mytable  where (flag1 = 0 or flag2 = 0) and id = 202 	0.00982109105300456
21142919	37659	adding two columns from two different tables	select bg_id,  store_number,  sum(total_area) from   (     select bg_id,  store_number,  total_area as total_area     from temp_prop_area_block a     where store_number='33665'     union all     select bg_id,   store_number,  total_area_blk as total_area     from temp_prop_area_bg b     where store_number='33665'   ) my_view group by bg_id, store_number; 	0
21143692	8159	how to get number of rows per group by partition in mysql?	select count(a) from table group by a; 	0
21143978	26170	sql server recursive query with associated table	select r.id, r.name, r.parentid, r.lvl, a.folderid, a.id as associationid  from [recurse] r left join [association] a  on r.id = a.folderid where a.folderid is not null order by lvl desc 	0.470094164360348
21144086	25207	sql looping cartesian product	select a.scode glacct, a.sdesc glacctdescp sum(case when month(t.umonth) = 1 then t.smtd else 0 end) as januaryamount, sum(case when month(t.umonth) = 2 then t.smtd else 0 end)as februaryamount, sum(case when month(t.umonth) = 3 then t.smtd else 0 end) as marchamount from acct a inner join total t on a.hmy = t.hacct where year(t.umonth)=2013 and t.ibook = 1 group by a.scode, a.sdesc 	0.40350550928663
21146081	24055	keeping unique rows with group by cube	select campus, (     select avg(wage)     from      (         select ssn, campus, wage, row_number() over(partition by ssn order by wage) as rn         from #thetable as inside         where (inside.campus=outside.campus or outside.campus is null)      ) as middle     where rn=1 ) from #thetable outside group by cube(campus); 	0.0316602618529536
21146326	39684	a better way to get customers who placed maximum and minimum number of orders	select x.*    from       ( select customer_id             , count(*) cnt           from orders          group              by customer_id      ) x    join       ( select min(cnt) min_cnt             , max(cnt) max_cnt           from              ( select customer_id                    , count(*) cnt                  from orders                 group                    by customer_id             ) n      ) y      on y.min_cnt = x.cnt      or y.max_cnt = x.cnt; 	0
21147973	9615	mysql multiple rows, grouping multiple values	select id_mat,     (sum(prev='1')/count(*))*100 as prev1,     (sum(prev='x')/count(*))*100 as prevx,     (sum(prev='2')/count(*))*100 as prev2 from dgpl_se_bets1x2 group by id_mat; 	0.00203058414178173
21148481	2847	sql query add count information	select  b.bg_bug_id as defect, count(distinct t.ts_test_id) as number_of_test_ids from  bug b join link l on b.bg_bug_id = l.ln_bug_id join test t on l.ln_entity_id = t.ts_test_id where  (b.bg_status = 'open') or  (b.bg_status like '%re%') or  (b.bg_status like '%en%') or  (b.bg_status = 'fixed') or  (b.bg_status = 'new') and  (l.ln_entity_type = 'test') group by b.bg_bug_id order by b.bg_bug_id asc 	0.07013050227821
21148720	37557	adding a cast to a parameter	select distinct material.materialid from data where material.materialid = cast(:value as float) 	0.462694324991399
21151335	35719	select date from timestamp sql	select title, date(timestamp) as mydate from team_note tn where id = 1 	0.0023452548080991
21151430	35058	mysql group by year(), month() returns dates sometimes at start of month, sometimes at end	select min(datefield) first_day_of_month from calendar group by year(datefield), month(datefield) 	0
21153632	31548	efficient technique to calculate geographic union of many polygons	select city, geography::unionaggregate(spatiallocation) as spatiallocation from person.address where postalcode like('981%') group by city; 	0.132446916889827
21155055	24346	how to fetch values from more than one table from mysql?	select tree.id, tree.name, sum(leaf.value) as total from tree left join leaf   on leaf.tree_id = tree.id group by tree.id 	0
21156761	10594	sql join same tables on datetime?	select sra2.value-sra.value as diff, sra.* from summary_reading_all sra inner join summary_reading_all sra2 on sra2.readingdatetime = sra.readingdatetime and sra.readingtypeid = sra2.readingtypeid and sra.deviceid = sra2.deviceid where sra.readingtypeid = 15 and sra.deviceid = 173 order by sra.readingdatetime 	0.0132912454542422
21156846	28412	calculating values in a hierarchy of a known depth	select     senior_manager.name as name,     sum(sales.amount) as sales,     sum(sales.amount * manager.commission/100) as managercommission,     sum(sales.amount) * (senior_manager.commission/100) as seniormanagercommission from     users as senior_manager left join users as manager     on manager.parent = senior_manager.id left join users as employees     on employees.parent = manager.id left join sales     on sales.id = employees.id and     sales.created_at between date(?) and date(?) where     senior_manager.id = ? group by     senior_manager.name 	0.000337919799735053
21157505	37372	how to use part of sql query in the same query?	select u.username, u.id,            sum(t.result = 1) as winnings,            sum(t.result = 2) as loses,            f1.comments_no     from users u      left join tahminler t on u.id = t.user_id     inner join (select user_id, count(distinct match_static_id) as comments_no from comments group by user_id) f1     on u.id = f1.user_id     group by u.id 	0.0257627881050555
21159423	21367	retrieve different data from same table in two coloums	select dp.id, dp.date , dp.sales-rep-1, sr1.sales-rep-name, dp.sales-rep-2,        sr2.sales-rep-name   from data-pool as dp, sales-representatives as sr1,        sales-representatives as sr2  where dp.sales-rep-1=sr1.id and dp.sales-rep-2=sr2.id 	0
21160368	36670	stored procedure for tables data	select e.employeeid, e.employeename,       stuff((select  ', ' + g.profession              from employeegroups eg              inner join groups g on g.groupid = eg.groupid              where e.employeeid = eg.employeeid                 for xml path('')             ), 1, 1, '') profession     from employee e; 	0.223976274680479
21160714	20987	show null values on mysql query and left join	select   pupils.id_pupil  , name  , surname  , ifnull(qua.media, 0) media  , ifnull(qua.count, 0) count  , sum( case when type_incident='miss' then 1 else 0 end ) as misses  , sum( case when type_incident='delay' then 1 else 0 end ) as delays  , sum( case when type_incident='attitude' then 1 else 0 end ) as attitude  , sum( case when type_incident='miss_justif' then 1 else 0 end )   as misses_justificadas  from   pupils   left join incidents on incidents.id_pupil=pupils.id_pupil  left join  (select id_pupil, id_trimester,   count(qualification) count,   round(avg(qualifications.qualification),2) media  from qualifications   where type_qualification='class'  group by id_pupil, id_trimester ) as qua  on ( qua.id_pupil = pupils.id_pupil ) where   level=1  and class='a'   and qua.id_trimester=1  group by pupils.id_pupil 	0.164175041176846
21162377	4378	select 3 items with higher sales	select id_service, count(*) as cnt from vendas where id_service is not null group by id_service order by cnt desc limit 3; 	0.000934471099571678
21162568	2052	sql mathematical calculations	select round(sum(cast(column as float)),2) 	0.677331365526466
21162884	31018	sum on left outer join on 2 different child tables	select i.*, li.[sub total], ac.[additionalcosts] from invoice i left outer join (select invoiceid, sum(unitprice*qty) as [sub total]                  from lineitem                  group by invoiceid) li      on li.invoiceid = i.id left outer join (select invoiceid, sum(amount) as [additionalcosts]                  from additionalcost                  group by invoiceid) ac      on ac.invoiceid = i.id 	0.0112768394319286
21163944	27096	select all from table where imgid is max in every projid	select * from projimg  where imgid in (      select max( imgid )      from projimg      group  by projid) 	0.000249845720810412
21164656	5396	mysql query to get a record whose date time is immediately after the current date time	select *  from appointments app  where app.patient_id = 123 and appointment_start_dt > now() order by appointment_start_dt asc limit 1; 	0
21164665	13081	comma separated value search in mysql	select * from table where find_in_set('1',meta_val) and find_in_set('2', meta_val); 	0.00106578329801366
21166399	2103	mysql: how to sum distinct rows in complex joined query	select `inv.nr`, articleid, sum(quantity), sum(amount), sum(vat) from ((`invoice` inner join `invoice line`             on `invoice`.`inv.nr`=`invoice line`.`inv.nr`)       inner join           (select sum(amount) as amount, sum(vat) as vat, `line-id`               from ((`invoice line vat`                    inner join `more stuff`                     on .... )              inner join ....                    on ..... )             where some-where-stuff            group by `line-id`) x          on `invoice line`.id = x.`line-id`) where other-where-stuff group by ..... having ..... 	0.0324541171534503
21167332	19661	how to filter out multiple values of a particular set	select * from person where age != '10' or gender != 'm'; 	0.000213010379915438
21167810	15447	sql query _ not able to find recently hired employee is each department	select dpt.department_name, dpt.department_id, employee_name, hire_date, salary      from dpt inner join emp on emp.department_id = dpt.department_id inner join     (select emp.department_id, max(hire_date) as datemax from emp) x on  emp.department_id=x.department_id and emp.hire_date =x.datemax          order by dpt.department_name; 	0.000104212113853404
21168036	28598	join data on a table based on a relationship table	select cause.name as 'cause', effect.name as 'effect'  from fact_cause c inner join fact cause on c.idcausefact = cause.id inner join fact effect on c.ideffectcause = effect.id 	9.08110509764475e-05
21168200	22844	insert multiple records with values based on each other	select id from from tablea where someconditions select count(*) from tableb where refid = (select id from from tablea where someconditions) select count(*) from tablec where refid = (select id from from tablea where someconditions) 	0
21171389	14453	how to check with statement is empty or not	select lo.id , s.service_name , lo.obj_name ,     ........     into #temp     from dbo.r_objects ro     inner join dbo.services  s on ro.service_id = s.id      inner join dbo.local_objects lo on ro.local_object_id = lo.id     where ro.service_id = @service_id if exists (select 1 from #temp) begin     select id , service_name , cast(obj_name as varbinary(200)) obj_name     from #temp      where ....... some logic     end else begin   set @check = 'data is empty'   ...............some logic here   end 	0.785857194086661
21171581	7338	how can i query system data in mysql?	select * from information_schema.tables  select * from information_schema.columns 	0.482181154734833
21171922	27956	sum the result of certain rows by comparing string values of column	select    case        when division_name like '%-wc'        then substring(division_name from 1 for position('-wc' in division_name) -1)        else division_name    end,    category_name, sum(amount) as amount from tblstaff  where fy=2013 and period_=4 group by     case        when division_name like '%-wc'        then substring(division_name from 1 for position('-wc' in division_name) -1)        else division_name    end,    category_name 	0
21172033	25050	convert sql server query to access	select      u.voorstellingnummer, u.uitvoeringnummer, u.zaalnaam, s.rijnummer, s.stoelnummer from        uitvoering as u inner join  stoel as s     on      u.zaalnaam = s.zaalnaam where       u.voorstellingnummer = 4     and     u.uitvoeringnummer = 1     and     ('rij ' & s.rijnummer & ' stoel '  & s.stoelnummer) not in          (         select      ('rij ' & b.rijnummer & ' stoel ' & b.stoelnummer)         from        bezetting as b         where       b.voorstellingnummer = 4             and     b.uitvoeringnummer = 1         ) 	0.789842271029354
21172544	15501	execute multiple sql statements in stored procedure with single result return	select top 1 categoryname, displaypartno from (   select categoryname, displaypartno, 0 as resultpriority   from categories   where catalogid = @catalogid and source = @manufacturer   union all   select '' as categoryname, displaypartno, 1 as resultpriority   from products   where catalogid = @catalogid and source = @manufacturer ) t order by resultpriority, categoryid desc 	0.580783981727776
21174806	39881	how to select into with a check on each row before insertion	select distinct   case when col2 > col1 then col1 else col2 end,   case when col2 > col1 then col2 else col1 end from newtable 	0
21175529	27087	sql joining, which is the best join	select * from tablea a left join tableb b on a.id = b.new_id join tablec c on c.board_id=b.board_id 	0.145137986978581
21178119	1832	query displays each record several times	select             dbo.hremployee.emplid, dbo.hremployee.emplname, dbo.atdrecord.recdate,      dbo.atdrecord.rectime, dbo.hrdept.deptname from                 dbo.atdrecord  inner join     dbo.hremployee on dbo.hremployee.emplid = dbo.atdrecord.emplid inner join     dbo.hrdept on dbo.hrdept.deptid = dbo.hremployee.deptid 	7.53852465459581e-05
21179414	14745	retrive records between two dates in mysql?	select * from emp  where approved_date  between str_to_date('18-01-2014', '%d-%m-%y')  and str_to_date('26-01-2014', '%d-%m-%y') 	7.55327621674821e-05
21179751	22270	how to select data with condition	select * from statement where date >= a and date <= c and type = 'balance' order by date asc limit 1 union select * from statement where date >= a and date <= c and type != 'balance' order by date asc 	0.08173527070547
21180948	36767	select records with latest timestamps	select s.user, s.system, sw.max_tstamp, sw2.soft from   systems s inner join (select system, max(tstamp2) as max_tstamp                         from software                         group by system) sw   on s.system = sw.system inner join software sw2   on s.system = sw2.system and sw.max_tstamp=sw2.tstamp2 	8.55210411020422e-05
21181664	8921	sql server union but keep order	select *  from (  select name,surname, 1 as filter from  table1 union all select name,surname , 2 as filter from table2 ) order by filter 	0.624819657707782
21181867	38799	rank sql columns	select color, fruit, amount, case when (if(@prev_color != color, @rank:=1, @rank:=@rank + 1)) is null then null      when (@prev_color := color) is null then null else @rank end as rank from your_table , (select @rank:=0, @prev_color := null) v order by color, amount desc 	0.0514231313480681
21182321	11733	mysql filter query?	select count(*) as `count`,`region`, `lang`, date(now()) as `week_ending`  from mydata.table  where `date` > date_add(date(now()), interval -1 week) and `date` < date(now())  group by `region`, `lang`, date(now()); 	0.446491552454074
21183033	23525	difference between 2 datetimes in sql server	select * from tablea where updatetime > dateadd(mi, -5, getdate()) 	0.00284469658803362
21183503	21758	add values of one column	select pay.projectid,         sum(pay.productpayment),        max(pay.paymentdate)  from dbo.pm_productpayment pay inner join dbo.pm_product pro on pay.projectid = pro.productid     inner join dbo.pm_productcost cos on pay.productid =cos.productid     inner join dbo.salesdetail sal on pro.salespersonid = sal.id  group by pay.projectid 	0.000213909087471309
21183629	249	how to get row count with same field value as from row with provided id?	select t2.id, t1.year, count(*)  from temp t1 inner join temp t2 on t1.year=t2.year group by t1.year, t2.id 	0
21186954	907	selecting specific rows based on data from other table	select software.name, software.pc, systems.pc, systems.user from software join systems on software.date = systems.time and software.pc = systems.pc; 	0
21187645	17395	search sqlite database and use values from retrieved rows for calculation	select avg(price) from prices where subcat = 'meat' and item = 'lamb' 	0.00281891243686174
21188661	7209	join two tables with geometry column into one	select * into dbo.parkingbay  from (select * from dbo.parkingbay_old        union all       select * from dbo.parkingbay_new) as parking_bay; 	0.00117521791296158
21188912	31733	what is most efficient sql query?	select * from events e left join subscriptions s on s.r_id = e.r_id where s.user_id = ? 	0.7336943714691
21189014	16547	mysql join multiple column from same table	select u.name as name, s1.skill name as skill1, s2.skill name as skill2, s3.skill name as skill3     from table1 u     join table2 s1 on (s1.id = u.skill1)     join table2 s2 on (s2.id = u.skill2)     join table2 s3 on (s3.id = u.skill3) 	0.000791855013113737
21189139	39681	sql join of 2 date tables with gaps (lookup)	select    a.id      , a.date     , (     select top 1                  b.hours             from _lookup b             where a.date >= b.date                 and a.id = b.id             order by b.date desc         ) as workinghours from [_basetable] a 	0.00442158143038646
21189927	13316	how to select duplicate records without a primary key in sql server	select          a,         b,         c from    [dms].[dbo].[creditdebitadjustment] group by a,b,c having count(*) > 1 	0.00023370482133245
21191682	11159	generate unique id from string	select checksum(name, birthdate) from dbo.eligibility; 	0.000136951733591843
21192601	2931	plsql : if variable in subquery	select count(*)  into foo  from blah where yvar = xvar if foo > 0 then ... 	0.768287212805068
21193287	35023	how to convert date to drop minutes and seconds ssms	select    itr_employeeid,    convert(date, itr_transdate) as transdate,    count(itr_transtype) as tc  from dbo.itr  where (itr_employeeid in (n'sweda', n'bakja', n'gebwa'))  and (itr_transtype like n'po inspect')  and (itr_transdate >= @fromdate and itr_transdate < dateadd(day, 1, @todate)) group by itr_employeeid, convert(date, itr_transdate); 	0.00142393725630307
21195264	8375	select where row has '/' in 4th location	select * from table where  substring(location,4,1) = '/' 	0.0101773448268613
21195481	6503	alternative to group_concat? multiple joins to same table, different columns	select u.name as user_name, l1.name as primary_location , l2.name as secondary_location from users u join locations l1 on(u.pri_location_id=l1.location_id) join locations l2 on(u.sec_location_id = l2.location_id); 	0.00592157765882457
21195631	37438	sql query returning records that have always the same value	select x, min(z) from tab group by x  having min(z) = max(z)  having count(distinct z) = 1 	0.000141115252585719
21198642	21319	group by date_format in sql and return group of unix timestamps	select floor(unix_timestamp(created_at)/60)*60 as date,        count(tweet_id) as count  from `tweets` where tweet_text like '%{$q}%' group by date 	0.00448684479729588
21200278	31835	sorting array using two keys, if two values of a key is same then use another key?	select *  from users u  order by u.count desc, u.liked_count desc 	0
21200417	1357	found integer in text data with mysql	select id  from tablea  where tags like '%1%' 	0.11314072839633
21200699	31549	how do i convert a varchar field into the datetime data type?	select *  from travail  where date(datereception) = str_to_date('01/01/2014', '%d/%m/%y') 	0.000296654844136876
21201884	14286	selecting from two different tables	select b.country, b.anothercode, a.code from country1 a left join country2 b on a.country=b.country 	5.80301701870884e-05
21201909	6729	mysql checking duplicate record with clause group by	select tid, item, count(*) c from yourtable group by tid, item having c > 1 	0.0547081311338689
21203585	35092	mysql condition on joined data	select   customers.name from   customers inner join campaigns c1 on customers.id=c1.id and c1.name = 'a' inner join campaigns c2 on customers.id=c2.id and c2.name = 'b' 	0.0310563710815723
21206331	39340	select statement to select only one value	select * from ( select     item.itemid,     item.name,     item.description,      item.quantity,       item.condition,     category.name as expr1,     auction.enddate,      auction.currencyvaluepost,      image.image,     row_number() over(partition by  item.itemid order by  item.itemid asc) as rn from item      inner join category on item.categoryid = category.categoryid      inner join auction on item.itemid = auction.itemid     left join image on item.itemid = image.itemid  where auction.status = 'valid' ) as t where rn=1 	0.000956936264129487
21207213	11682	select sql inner join and omit certain record	select id, desc from a join ( select id, action, rank() over (partition by id order by datetime desc) ranking from b ) b on (b.ranking = 1 and b.id = a.id and b.action <> 'delete') 	0.00791877263268194
21207636	13234	mysql three table join results empty set	select c.code,c.name, a.ltp as begning, b.ltp as enddate, d.interim_cash,d.interim_rec_date,      d.annual_rec_date,d.annual_cash,  cast(((b.ltp - a.ltp) / a.ltp * 100) as decimal(10, 2)) as chng  from eod_stock as a  left outer join eod_stock as b  on a.company_id = b.company_id  left outer join company as c  on c.id = a.company_id  left outer join dividend_info as d  on c.id = d.company_id and d.interim_rec_date between "2012-09-24" and "2012-09-25" and       d.annual_rec_date between "2012-09-24" and "2012-09-25"  where a.entry_date = "2013-09-24"  and b.entry_date = "2013-09-25"  and a.company_id in (13, 2,4,5); 	0.0686901932398295
21207871	14	conditional joining in postgres using levenshtein	select a.col1, b.col2   from a inner join      b       on levenshtein(replace(a.col1, ' ', ''), replace(b.col2, ' ', '')) < 2; 	0.785706446369935
21210198	35091	mysql joins on the same table	select n.title as title,        hotelk.name as kenyan_hotel,        hotelk.star as kenya_hotel_star,        hotelt.name as tanzanian_hotel,        hotelt.star as tanzanian_hotel_star  from node n inner join       hotel hotelk       on n.kenya_hotel_id = hotelk.id left join       hotel hotelt       on n.tanzania_hotel_id = hotelt.id; 	0.0135018005169391
21211736	32074	select count from one table and join another table based off of one id	select s.*, u.username, count(sv.id) votes from submissions s inner join users u on  s.user_id = u.id left join submissions_votes sv on s.id = sv.submission_id  where s.id = 15 group by sv.submission_id 	0
21213677	7356	average of two columns in sql	select a, avg((b+c)/2) as bc, avg((c+b)/2) as cb from tabletest where a = 's' group by a 	0.000161154316603662
21214388	39705	get last 20 rows of inner join when sorted asc	select * from (         select a.*, b.some_column                 from a                 inner join b on b.id = a.id and (other conditions here)                 order by a.timestamp desc                 limit 20     ) as result     order by result.timestamp asc 	0
21215085	32956	mysql & php : getting the latest x posts, then the next x latest, and so forth	select * from wall_posts order by date desc limit 10, 10 	0
21216534	4096	sql query result from multiple tables without duplicates	select id, lastorderdate, total, segment from segmenta union all select id, lastorderdate, total, segment from segmentb where id not in (select id from segmenta) union all select id, lastorderdate, total, segment from segmentc where id not in (select id from segmenta) and id not in (select id from segmentb) union all select id, lastorderdate, total, segment from segmentd where id not in (select id from segmenta) and id not in (select id from segmentb) and id not in (select id from segmentc) 	0.013760763065511
21217884	26936	how do select all rows from table groups and count of contacts for each groups in sql	select a.group_name, count(b.contact_id) from groups a left join contacts b on a.group_id = b.contact_group_id group by a.group_name 	0
21218611	5937	how to calculate percentage with a oracle sql statement with two tables	select (n/c)*100 pct from ( select count(*) c from przedmioty )  , ( select count(*) n from przedmioty      where id_prz not in (select id_prz from transakcje)); 	0.0070862984291911
21218689	28613	get last record in mysql table	select * from table t1  join (select record_id  ,max(updates)as maxupdate from table group by record_id)x  on t1.record_id = x.record_id  and t1.updates=x.maxupdate 	0
21219219	2704	joining tables for count query	select sum(num) from (   select count(url) as num from pox_topics where url = :url   union all   select count(url) as num from people where url = :url   union all   select count(taxon) as num from gz_life where taxon = :url ) as subquery 	0.0829564346913184
21219368	41039	search for time in mysql	select t.* from table t where time <= '2014-01-19 02:07:00' order by time desc limit 1; 	0.193577249383027
21220038	1432	what percentage of users participated on each day (sql query)	select date(time),        count(distinct userid) / cd.cnt from activity_entries ae join      (select count(distinct userid) as cnt       from activity_entries) cd group by date(time); 	0
21221326	15370	making a null field in a mysql row appear as a value?	select if(soda='mtndew','mountain_dew',' not mountain_dew'); 	0.00109851727154521
21222653	31314	select statements have a different number of columns	select * from (    select *, null as distance from user u    inner join employee e on (u.empid = e.empid)    inner join awards a on (u.empid = a.empid)    where u.empid = 123    union    select *,  ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) )+ sin( radians(37) ) * sin( radians( lat ) ) ) ) as distance    from user u    inner join employee e on (u.empid = e.empid)    inner join awards a on (u.empid = a.empid)    having distance < 25    order by distance ) a order by timestamp desc; 	4.62636123225156e-05
21222877	40543	some columns are hidden in phpmyadmin	select * from `tablename` where 1 	0.0207310302081994
21223758	36901	calculate total minutes between two timestamps across multiple records using postgresql	select id,        (sum(extract(epoch from end - start)) -         (case when max(start) < min(end)               then extract(epoch from max(start) - min(end))               else 0          end)         ) / 60 from timeperiods tp group by id; 	0
21225348	21122	passing static values on a count query (php/mysql)	select 'px' as site, count(url) as num from people where url = :myurl; 	0.0548133891849358
21227000	34416	join on a selected column	select * from  (   select a,      (select name    from table3     limit 1) as b   from table1 ) as r group by b 	0.0303797068101312
21227332	30590	how to get a empty value column count in a given row in my sql	select if(col1 is null ,1,0)+ if(col2 is null ,1,0) +if(col3_id is null ,1,0) +......as cnt  from yourtable where id=100000 	0
21228685	37985	first 5 entries for a single user	select cust_id, date from (   select cust_id,          date,          row_number() over (partition by cust_id                             order by date, id ) rn   from transaction ) as alias where rn <= 5 order by 1,2 	0
21229695	4034	listing owner with multiple distinct entries	select   [student name] from   tablename group by   [student name] having   count(distinct subject)>1 	0.00237062829558595
21230706	5831	mysql query between 2 tables and find not null	select a.articleid,a.articletitle,aa.articleid,aa.attrid,aa.stringvalue from cms_articles a inner join cms_attr_art aa on aa.articleid = a.articleid where a.articleid not in (select articleid from cms_attr_art where attrid = 7); 	0.00969252400073998
21231747	23178	how to exclude rows for the same id based on category and date	select orderid,orderdate from ( select *,row_number() over(partition by id,cat order by orderdate desc) as rn from tbl ) as tmp where rn = 1 	0
21234231	22568	sorting by a to z with limit	select c.name from (select c.name, if(@lastletter=@lastletter:=left(c.name, 1), @cnt:=@cnt+1, @cnt:=0) lettercnt       from customers c, (select @lastletter:='', @cnt:=0) a        order by c.name asc     ) as c where c.lettercnt < 5 	0.44432862266116
21239549	41113	select a composite key, where max(column_value)	select t.* from mytable t join      (select part, max(quantity) as maxq       from t       group by part      ) m      on m.part = t.part and m.maxq = t.quantity; 	0.29868371181201
21240469	13961	how to get today date in yyyymmdd in firebird	select replace(cast(cast('now' as date) as varchar(10)), '-', '') from rdb$database 	0.000764059529074469
21242502	30587	sql query that would return a table, and count other tables relevant to the results of the first	select `forums`.*, count(distinct `topics`.`topic_id`) as `num_of_topics`, count(distinct `posts`.`post_id`) as `num_of_posts` from `forums` left join `topics` on `topics`.`forum_id` = `forums`.`forum_id` left join `posts` on `posts`.`topic_id` = `topics`.`topic_id` group by `forums`.`forum_id` 	0
21242804	3534	find all rows that have a value in a certain column that occurs more than once	select id, text from (select t.*, count(*) over (partition by id) as cnt       from table t      ) t where cnt > 1; 	0
21244471	11393	sql server concatenating values from several rows	select p.playername,     at.times from player p cross apply (   select cast(time as varchar) + ' ' as [text()]   from times t   where p.id = t.playerid   for xml path('') )at(times) 	0.000455688233844576
21244681	33206	retrieve previous row to subtract from current row by date	select nav_date, nav_value, (nav_value / prev_value) - 1 from (select t.*,              (select top 1 nav_value               from yourtablenamegoeshere as t2               where t2.nav_date < t.nav_date               order by t2.nav_date desc              ) as prev_value       from yourtablenamegoeshere as t      ) as t 	0
21248617	12939	efficient way to union based on inner query return count?	select problem_id, name from ((select problem_id, name, 'bad' as which        from (select r.problem_id, p.name, sum(r.value) as knowledge              from responses r join                   problem p                   on p.id = r.problem_id              group by r.problem_id             )         where knowledge = 0       ) union all       (select id, name, 'new'        from problem p        where p.id not in (select problem_id from responses)        group by p.id       )      ) as final order by which limit 30; 	0.0751926663802716
21249778	32292	datediff to output hours and minutes	select  emplid         , emplname         , intime         , [timeout]         , [datevisited]         , case when minpart=0          then cast(hourpart as nvarchar(200))+':00'          else cast((hourpart-1) as nvarchar(200))+':'+ cast(minpart as nvarchar(200))end as 'total time'         from          (         select   emplid, emplname, intime, [timeout], [datevisited],         datediff(hour,intime, [timeout]) as hourpart,          datediff(minute,intime, [timeout])%60 as minpart           from times) source 	0.00299020487562689
21250694	4046	mysql query multi data from same column	select a.id, a.name,         max(case when b.type = 1 then b.point else 0 end) type1,         max(case when b.type = 2 then b.point else 0 end) type2,         max(case when b.type = 3 then b.point else 0 end) type3,         sum(b.point) total from tablea a  left join tableb b on a.id = b.fk  group by a.id 	0.00182425596765044
21251935	20590	get count of unique widgets on a join	select  count(distinct widget_id)  from     widgets w  join categories c using (widget_id)  where c.category in ('print', 'automotive', 'beer')      and w.stock > 0 ; 	0.000741012204785188
21251953	15120	get unique month-year combination from sqlite database	select case m         when '01' then 'january'         when '02' then 'febuary'         when '03' then 'march'         when '04' then 'april'         when '05' then 'may'         when '06' then 'june'         when '07' then 'july'         when '08' then 'august'         when '09' then 'september'         when '10' then 'october'         when '11' then 'november'         when '12' then 'december'         end || ' ' || y as dates    from  (   select distinct           strftime('%m', dateinterval, 'unixepoch') m,          strftime('%y', dateinterval, 'unixepoch') y     from mytable ) q  order by y desc, m desc 	0.00015934254100768
21252221	16446	how to get table structure at a time for many?	select * from information_schema.columns where table_schema='test'; 	0.000346443447110121
21252644	4289	how to extract date from a datenow() in yyyymmdd format in sql server	select convert(varchar(8), getdate(), 112) as [yyyymmdd] 	0.00217975814451199
21252892	28514	how to show field name if it set to true	select cast(faname as varchar)+' - '+cast(  case when isspecial = 1 then 'isspecial,' else '' as varchar)+cast( case when isperishable = 1 then 'isperishable,' else '' as varchar)+cast( case when isdanger = 1 then 'isdanger' else '' as varchar) from your_table 	0.00116912270471043
21253213	38912	how to subtract 18 months from the current date in ms-access	select name  from babies where birthdate >= dateadd(month, -18, getdate()) 	0
21253336	25158	how to retrieve unique records that have different ids but the same name	select min(id), name from table_a group by name; 	0
21253867	40489	how do i find current time is between certain time period in sql-server	select timeperiod, datepart(hh,timeperiod), case      when datepart(hh,timeperiod)  >= 8 and datepart(hh,timeperiod)  < 9 then 1     else 2      end as yourcase     from visit 	0
21254152	25025	concatenating by group	select studentid,        ( select subject + '-' + score + ','            from students t2           where t2.studentid = t1.studentid           order by name             for xml path('') ) as name       from students t1       group by studentid ; 	0.163637709271977
21254704	34460	get rows by id or all rows if id is 0	select store_id, sum(traffic) from traffic  where (store_id = @store_id or @store_id = 0) and year = @year  group by store_id 	0
21255043	28800	sql command between two datetimes for table reservation	select * from `booking` where table='$i' and not(comming >= '$guestdepature' or depature <= '$guestcomming') 	0.0152667652633865
21255429	19261	difference between results mysql	select    meter.meter_serial,   her060.node_address,   her060.report_time,   her060.node_reading,   @previous - node_reading as your_difference,   @previous := node_reading from   meter inner join her060 on meter.node_address = her060.node_address  cross join (select @previous := (select node_reading from her060 order by report_time desc limit 1)) variable_initialization_query_alias where    meter.meter_serial = '31602193'  order by her060.report_time desc  limit 10 	0.0214882101416764
21255534	8697	how can i create a auto updating time field in mysql?	select now() - inserttiontime from table; 	0.00462313887013176
21255873	18500	sql server 2012 sum values by specific datetime	select registrationid from mytable where stateofwork = 'done'  and year(incomingdate)=2013  and month(incomingdate)=12 	0.0374075139117486
21256121	35321	db2 using limit and offset	select emp.empno, emp.salary  from (      select empno, salary,              row_number() over(order by salary desc) as row_number      from employee  ) emp  where emp.row_number > 10  and emp.row_number <= 20 	0.554450735624756
21256590	18634	how to check last 3 rows for the same value?	select if(count(*) = 3, 'true', 'false') from ( select * from your_table order by id desc limit 3 ) sq where value = 20; 	0
21257396	6	select the two latest rows for each user to get the difference of a column (mysql)	select uid, max(myvalue)-min(myvalue) as diff from     (select a.* from tablename as a         left join tablename as a2             on a.uid=a2.uid and a.myvalue<=a2.myvalue         group by uid,myvalue         having count(*)<=2     ) a group by uid 	0
21257818	13144	advanced mysql order by parent sequence and then by child sequence	select        t1.*     from        t t1           left join t t2              on t1.parent_uid = t2.uid    order by       coalesce( t2.sequence, t1.sequence ),       case when t2.uid is null then 1 else 2 end,       t1.sequence 	0.0119520513151383
21257905	32979	using a join and a where ? mysql	select delegate.name,        module.code,         module.name,        delegate.no  from module  inner join take  on module.code = take.code  inner join delegate  on delegate.no = take.no  where grade<40; 	0.594541201617375
21260901	19496	sql multiple rows into one row	select max(col1) as col1, max(col2) as col2, max(col3) as col3 from t; 	0.000101804961553707
21261356	1267	mysql: select first or last rows when grouping by multiple columns	select o.`bid_id`,o.`buyer_id`,o.`item_id`,o.`amount`,o.`time` from `offers` o join (select min(`bid_id`) as `bid_id`,`buyer_id`,`item_id`,`amount`,`time` from `offers` group by `buyer_id`,`item_id`)x on x.bid_id=o.bid_id  and x.buyer_id=o.buyer_id 	0
21263219	6352	select date in form dd/mm/yyyy in sql query	select (cast(day as varchar(2)) + '/'      + cast(month as varchar(2)) + '/'      + cast(year as varchar(4))) as xdate  from table1 	0.0290483625307824
21263524	37199	calculation on multiple rows	select      article,     sum(pieces) as "pieces",     sum(sum) as "sum",     sum(inventory) as "inventory",     sum(inventory * price) / sum(inventory) as "price",     sum(inventory * cond) / sum(inventory) as "cond" from     table_name   where      "article" = 'nl1234'  group by      article 	0.0237806396411729
21264902	27451	mysql, displaying two tables	select 'buy' as [type], b.* from buy as b union all  select 'sell' as [type], s.* from sell as s order by timestamp 	0.0162774681563454
21266054	17329	multiplying column by weight in another table requiring a second select and summing in sql	select sum(t1.value * t2.weight)  from t1 join t2 on t1.vid = t2.vid 	0
21266324	36888	sql maximum number of doctors in a department	select * from department dp order by (select count(*) from doctor d where d.department_id=dp.id) desc limit 1 	0.000274860410889634
21267527	12836	making a null value in a mysql field appear as 0 / n/a	select col1, col2, ifnull(col3, 'n/a'), col4 from table 	0.043330637531993
21272299	30086	mysql - take two tables and return results that don't exist in one	select      schedule_recurring.date_start,      employees.id,      employees.firstname,      employees.lastname from employees left join schedule_recurring on schedule_recurring.employee_id = employees.id   and dayname(date_start) = dayname('2014-01-20') where schedule_recurring.id is null 	0
21273301	29154	using regexp_extract to get domain and subdomains	select regexp_extract(domain, r'([^.:]+):?[0-9]*$'), regexp_extract(domain, r'([^.:]+).[^.:]+:?[0-9]*$'), regexp_extract(domain, r'([^.:]+).[^.:]+.[^.:]+:?[0-9]*$') from [weblist.domain] order by 1 limit 250; 	0.0304453097453633
21276206	1468	select 10 rows where sold='false' from sql	select * from your_table where sold='false' limit 10 	0.00118542396599652
21276274	31103	mysql query to select count of conflicts between two users	select sum(case(field(t1.answer, t2.acceptable_1, t2.acceptable_2, t2.acceptable_3,     t2.acceptable_4)) when 0 then 1 else 0 end) as conflict_1_over_2, sum(case(field(t2.answer, t1.acceptable_1, t1.acceptable_2, t1.acceptable_3, t1.acceptable_4)) when 0 then 1 else 0 end) as conflict_2_over_1      from user_answers t1 join user_answers t2 on t1.uid > t2.uid and t1.quid = t2.quid     where t1.importance <> 1 and t2.importance <> 1 and t1.uid in (1, 2) and t2.uid in (1, 2) 	0.0010421512515838
21276975	13026	get records of current month	select * from table where month(columnname) = month(current_date()) 	0
21276986	38897	mysql dynamic inner join for combining multiple rows into one?	select      shop.name, shop.address, shop.zip, shop.city, shop.municipal, shop.phone, shop.lat, shop.lng,     max(case when h.day = 1 then h.day else 0 end) as day1,     max(case when h.day = 2 then h.day else 0 end) as day2,     max(case when h.day = 3 then h.day else 0 end) as day3,     max(case when h.day = 4 then h.day else 0 end) as day4,     max(case when h.day = 5 then h.day else 0 end) as day5,     max(case when h.day = 6 then h.day else 0 end) as day6,     max(case when h.day = 7 then h.day else 0 end) as day7 from shop     inner join hours h on shop.id = h.shop_id group by     shop.name, shop.address, shop.zip, shop.city, shop.municipal, shop.phone, shop.lat, shop.lng; 	0.0173484796730309
21277216	9364	sql query to combine some rows	select   case when item in ('motor1', 'motor2', '...') then 'motors' else 'others' end item,   count(*) number from   table group by   case when item in ('motor1', 'motor2', '...') then 'motors' else 'others' end 	0.0165241446546034
21277696	10164	mysql count the same value	select firstname,count(*) from tblstudent group by firstname 	0.00138304168387276
21281122	7326	only join tables if certain value does not exist among multiple rows in other table	select * from debtor d join items i on d.debtor = i.debtor  where not exists    (select debtor     from items i2    where item = '20004' and i2.debtor = i.debtor    ) 	0
21282540	9217	mysql select to convert numbers to million,billions format	select format(count(total_profit), 0) as profit  from sales_profits 	0.0184330073389841
21282764	35085	sql - find if date is between two dates	select * from job where job.type='manager' and job.fromdate <= '2014-01-22' and job.todate >= '2014-01-22' 	0.00018575407059363
21283158	7932	mysql price field insert $ and comma	select concat('$',format(listprice, 2)) as formatted, mls from table 	0.00247927058058616
21284471	6532	how to get column difference between 2 rows in db in sql	select p.id,         c.time  - p.time as time_difference from the_table p   join the_table c on c.id = p.child_id where p.child_id is not null; 	0
21285497	13678	inner join returns correct max date but not other fields in same row	select     statistics_meter.mpan_number as mpannumber,     s.contract_end_date as contractenddate,     s.supplier as suppliername from statistics_contract as s     inner join statistics_meter          on statistics_meter.id=s.meter_id where s.contract_end_date = (     select max(contract_end_date)      from statistics_contract as sc      where sc.meter_id=s.meter_id ) 	0.00267207524367487
21286236	32519	how to retrieve data from different columns in different tables and combine them into one report	select pd.* from admission a inner join personaldetails pd on a.studentid = pd.studentid where a.subject = @subject order by pd.lastname, pd.firstname 	0
21286270	12993	how to pass a list of values as parameter in c# databinding	select somefield from sometable where somefield in udfdelimitedtorows(?) 	0.0112351757746419
21287864	14743	split sql rows between 4 flags	select case          when mod(row_number() over(order by number), 4) = 1 then 'joe'         when mod(row_number() over(order by number), 4) = 2 then 'jim'         when mod(row_number() over(order by number), 4) = 3 then 'gill'         when mod(row_number() over(order by number), 4) = 0 then 'jack'     end from t 	0.00344928525659576
21288518	19816	sql server: set two or more records with the same value	select a.*, case when exists (select label_id from table b                    where a.label_id = b.label_id and b.type = 'salad') then 'yes'      else 'no'  end [ind] from table a 	0.000172164983662293
21289983	9711	ms access: finding the top of each group in an sql query	select p.*  from   players p         inner join (select age,                            max(score) as mscore                     from   players                     group  by age) as mp                 on p.age = mp.age                    and p.score = mp.mscore 	0.000532973175936704
21290746	13751	group by first query in mysql	select      min(`date`) as `firstofdate`,      min(`time`) as `firstoftime`,      `homematchingid`,      `awaymatchingid`,      `runningstatus` from `20121202` group by      `homematchingid`,      `awaymatchingid`,      `runningstatus` having      `runningstatus`=1 	0.062884350598034
21291794	37144	how to get the latest record from mysql server database for a particular condition?	select id, type, details, created from mytable where type = 4 order by created desc limit 1 	0
21292913	13031	sql server, joining on generated rank()	select a.*  from  (     select name, (rank() over( order by name)) as rank_num     from animal ) as a join dbo.split(" ", "345345 345436 678768") split on split.num = a.rank_num 	0.172290694854121
21294029	39405	oracle selecting object not in as group/collection	select * from t1 where not exists(select 1 from t2                  where credential = t1.credential                  and activity <> 8) 	0.529555869369401
21295345	19753	how to indirectly join two tables	select *  from table1 t1   join table2 t2 on t2.name like '%'||t1.firstname||'%'                  and t2.name like '%'||t1.lastname||'%' 	0.0254245099413924
21295895	12126	trying to move the decimal place in an output	select round(0.1428571428571428571428571428571428571429 * 10, 1) 	0.0823955043197622
21296787	41317	how to select from a selection?	select   * from (   select   *   from     pagecomments   where    page_id='$pageid'   order by date desc   limit    20 ) t order by likes-dislikes desc limit    2 	0.0147045318016842
21298580	30741	avoiding two queries in two tables	select p.product  from table1 d, table2 p where d.date = 'selecteddate' and d.id = p.id 	0.0206594418982154
21300395	34629	left join between two tables	select x.a, y1.c ac, x.b, y2.c bc   from x      left join y y1 on x.a = y1.c      left join y y2 on x.b = y2.c 	0.0907450482710131
21301314	1036	figuring out a join between two users excluding where column does not exist for one	select * from user_answers t1  where t1.uid=1 and t1.quid in   (select t2.quid from user_answers t2 where t2.uid=2); 	0.000451520820279603
21302315	8545	t-sql remove "duplicate/non-interesting" data rows	select id, status, code, type, moddate from  ( select     id, status, code, type, moddate,     lag(type,1) over (order by id, moddate) prevtype from data )t where type<>isnull(prevtype,'') 	0.0142445452742573
21303110	10864	select rows from a table matching other table records	select t1.item_id, t1.name, t1.timestamp     from items t1       left join items_to_categories t2 on t1.item_id = t2.item_id         where cat_id = 5         order by t1.timestamp desc         limit 2; 	0
21303189	20365	can i left join between column types int and varchar?	select students.person_code, students.password from students left join users  on cast(students.person_code as varchar(10)) = users.username where students.person_code > 0 	0.148859464645828
21303564	18973	joining table with range id matching	select idx, columnx, columny from (     select id, columny, @previd as previd, @previd := id     from table2     cross join (select @previd := null) init     order by id desc) as t2 join table1 as t1 on t1.idx >= t2.id and (t2.previd is null or t1.idx < t2.previd) 	0.000125679247588206
21303745	37341	dynamically add a groupid and find the distinct count sql server 2008	select pid, opid, count(*) from (select tid, pid, opid,     (select ',' + cast(x.pid as nvarchar(10))                         from #temp x                         where x.tid = t.tid                    for xml path ('')) as pidgroup,     (select ',' + cast(x.opid as nvarchar(10))                         from #temp x                         where x.tid = t.tid                    for xml path ('')) as opidgroup     from #temp t) innerselect group by pid, opid, pidgroup, opidgroup 	0.010220140329463
21303837	35791	list out the table names having `clob` or `blob` or `lob` containing columns	select distinct table_name  from   user_tab_cols  where  data_type in ('clob', 'lob', 'blob'); 	0.000377457817045029
21306401	19927	efficient select from table of boolean changes	select      day,     hour,     state from     log where     day*100+hour      between         (select max(day*100+hour) from log where day < 12)      and         (select min(day*100+hour) from log where day > 12) 	0.0126552184564962
21306815	20903	sql best way finding all results presents in two tables with a criteria	select a.usercode , a.entitycode from table1 a  join table2 b on a.usercode = b.usercode and a.entitycode = b.entitycode join entity c on a.entitycode = c.entitycode where c.specialcode = 105 	0.00029385114793556
21309096	19918	replace cell with null if there is more than 2 cells of same value	select      case when rownum > 1 then null else scheme end as scheme,name,surname,event,registered_under as [registered_under]     ,capacity,free_beds as [free beds]  from  (    select u2.[text] as [scheme], k.name as name, k.surname as surname, u1.akce as event,     u1.[text]  as [registered_under], u1.z,    cte.reserved ,(u2.x) as [capacity], (u2.x-cte.reserved) as [free_beds]    ,row_number() over (partition by u1.[text] order by u1.[text]) rownum           from klient k           inner join ubytov u1 on u1.[text] = k.ubytov           inner join cte on u1.z = cte.z           left outer join ubytov u2 on u1.z = u2.id where u1.akce = 'ff1231-00'  )i       order by registered_under 	0
21310124	15610	how to join 3 tables in ms acces	select a.*, b.brandname, c.size, c.color from (item a     inner join [primary] b on a.itemid = b.itemid)     inner join [secondary] c on b.itemid = c.itemid 	0.349673414202904
21311356	40932	select count of value	select    id_blog,    sum(rate='like') as like_count,    sum(rate='dislike') as dislike_count  from    blog_posts  group by    id_blog 	0.00535869056047204
21311529	17131	how can i select the name of the active database?	select db_name() as [current database]; 	0.000251943497967515
21317921	12982	select from default catalog of linked server	select * from [remote_server_alias].[database_name].[schema].[table_name] 	0.0262080796948937
21318152	36844	where clause if match	select m.member_id, m.first_name, m.last_name from cal_form_answers a inner join cal_form_elements e     using(element_id) inner join cal_forms f     using(form_id) left join members m     using(member_id) where f.org_id = ?     and (m.org_id = ? or m.org_id is null)     and e.form_id = ? group by a.member_id order by a.member_id 	0.553403899604986
21319657	12341	oracle - sql - select from table at least subset of data searched for an agent	select distinct     agent_id from    user_agency  where    agent_id <> 3    and agent_id not in     (      select         uatarget.agent_id      from         user_agency uasource         inner join user_agency uatarget on         uasource.agent_id <> uatarget.agent_id      where         uasource.agent_id = 3         and not exists             (select agency_id              from user_agency              where             agent_id = uatarget.agent_id             and agency_id = uasource.agency_id)   ) 	0.00065826629217212
21319687	5146	last records from multiple tables postgres?	select   concat_ws(',', sim, simfile, txtlaser, txtregflow) from   (select     chksimulation as sim,     txtsimfile as simfile   from     devices   order by     id desc   limit 1) resone,   (select     txtlaserpower as txtlaser,     txtregularflow as txtregflow   from     calibrations   order by     id desc   limit 1) restwo 	0
21320155	38315	looping through set of results and change its results in sql	select a.itemid       ,a.itemname       ,case when count(b.iteminventoryid) = 0 then 'false' else 'true' end as itemstatus   from table1         a  left join inventory b on(       b.iteminventoryid =  a.itemid  ) group    by a.itemid      ,a.itemname; 	0.0060846053046567
21324016	27132	getting non repeating values (oracle)	select 'data' ||','||ltrim(to_char(trunc(create_time),'mm/dd/yyyy')) ||','||ltrim(to_char(trunc(max(close_time)),'mm/dd/yyyy')) ||','||count(tickets_closed) from app_account.otrs_ticket where create_time between sysdate -7 and sysdate and close_time between sysdate -7 and sysdate group by trunc(create_time) order by trunc(create_time) 	0.0111195829800513
21324661	24877	"select * from..." vs "select id from..." performance	select * 	0.0421029498416462
21328133	33848	get sum of counts for several tables	select (select count(*) from a) +         (select count(*) from b) +         (select count(*) from c); 	0.000366728275782646
21328742	11009	mysql: select records based on the time intervals	select * from tblname where hour(datetime_column) between 10 and 11 group by day(datetime_column) 	0
21330196	17143	mysql search data from multiple table	select * from user, category  where user.id=[text field]   or category.user_id=[text field]   or category.cat_id=[text field] 	0.00657254312903884
21332437	13758	how to return a query on only one column?	select string_agg(longitude::text||' '||latitude::text, ',') from mytable 	0.000218265346244351
21333744	11154	efficiency - looping greater than the sum of it's parts?	select somefields from servername.databasename.owner.tablename where whatever 	0.0010107354832748
21336015	421	getting a daily summary of figures from shop database	select categories.name as category, products.name as name,  receipts.quantity as quantity, products.price as price, (receipts.quantity * products.price) as total from categories join products on categories.id = products.cid join receipts on receipts.pid = products.id where date(receipts.ts) = curdate() order by categories.name 	0.00029708792528524
21336208	32977	sql query to find if most recent records are all of the same type	select t0.order_id  from transaction t0  join transaction t1 on    ((t1.response=t0.response) and (t1.order_id=t0.order_id) and     t1.id=(select max(id) from transaction where id<t0.id and t0.order_id=order_id))  join transaction t2 on     ((t2.response=t0.response) and (t2.order_id=t0.order_id) and     t2.id=(select max(id) from transaction where id<t1.id and t0.order_id=order_id))  where t0.response='declined' and     t0.id=(select max(id) from transaction where order_id=t0.order_id); 	0
21336256	20912	searching few rows with one variable	select *  from user  where first_name = '$userinfo'      or last_name = '$userinfo'      or concat(first_name, ' ', last_name) = '$userinfo' 	0.0085322635494423
21336257	5322	comparing dates to a subquery	select count(*) from   user join other on other.userid = user.id where  user.lastlogin >= other.timestamp + interval 90 day 	0.0437589298734593
21336994	9992	most efficient way of randomly selecting any mysql value given multiple values to match it to	select * from imagelist where valid='1' and (siteid='6' or siteid='7') order by rand() limit 1 	0
21337194	85	count how many rows from parent table exist in other 2 tables	select count(distinct l.protocol) as parent            ,count(distinct e.protocol) as tbl2            ,count(distinct n.protocol) as tbl3     from parent l     left join tbl2 e on l.protocol=e.protocol     left join tbl3 n on l.protocol=n.protocol     union all  	0
21337233	36391	mysql complex joining	select * from vehicles v1  join  available_colors ac1 on v1.id = ac1.vehicle_id where exists  ( select * from available_colors ac  where ac.vehicle_id = v.id and ac.color like '%metalic red%') 	0.750903267064621
21338706	18811	select data from second table if condition match from first table and limit data as a whole	select ss.vendor, ss.affiliate, ss.salests, ss.orderid from ss union all select sf.vendor, sf.affiliate, sf.salests, sf.orderid from sf  inner join ss on ss.orderid = sf.orderid where ss.vendor = ss.affiliate limit 100, 10 	0
21339911	29113	select data in sql from no links between another table/column	select * from attachment where att_id not in (select att_id from assignment) 	0.000157109958370129
21341186	35047	sql query for data	select username, times from (select username, count(title) as times    from yourtable group by username) qry order by qry.times desc; 	0.327455462893424
21342567	37868	getdate() sql server 2008	select case when cast(getdate() as date) >= '20140124'                   and cast(getdate() as date) <= '20140125'                   then 'show message' end 	0.765281291328616
21342924	14809	mysql - finding no active users	select u.user_name,   from users as u left outer   join entries as e     on e.user_id = u.user_id    and e.date_created >= current_date - interval 7 day  where e.user_id is null 	0.000871379919201224
21343131	4640	query date from date to today with french format	select * from commandes where str_to_date(cmd_date, '%d/%m/%y') between '2013-01-01' and curdate(); 	0.00153782070524189
21343808	10251	tsql :how to reset the value of identity column in a table?	select l.*, row_number() over (partition by id_testa order by id_riga) as seqnum from lines l; 	0
21343830	25469	mysql where match a concatenated string with a string in php	select * from events where find_in_set('internal medicine', replace(audience, ', ', ',')) > 0 and ('$date' < end_date) order by end_dat; 	0.0113006851490874
21343858	23837	getting the value upon match from the ref table	select   a.id        , a.valuea        , b.place        , getdate()   into #temptable from   table1 a inner join table2 b on     a.valuea = b.valueb 	8.04307239949968e-05
21345580	16744	postgresql query between 2 tables	select c.name, b.name, a.value from table_a a, table_b b, table_b c where b.id = a.id1 and c.id = a.id2 	0.0278500004516188
21346223	11145	mysql count table like in database	select count(*)  from information_schema.tables  where table_schema = 'mydatabasename' and        table_name like 'dev1%' 	0.173721827968402
21346857	297	querying sqlite db for data from one column based on another column	select substr(mydate, 7, 4) as year,        substr(mydate, 1, 2) as month,        sum(price) from purchases group by year,          month 	0
21347885	15174	mysql selecting multiple foreign keys	select group_concat(distinct i.user_ip) from ips i  inner join users u on i.id in (u.reg_ip, u.last_ip) 	0.000918551110143053
21349726	3853	how to get multiple inner node values	select      id,      xtbl1.loc.value('locationname[1]','varchar(200)') as locationname,      xtbl2.incharge.value('.','varchar(200)') as locationinchargename  from @test cross apply xmlcontent.nodes('location') as xtbl1(loc) cross apply xtbl1.loc.nodes('locationinchargename') as xtbl2(incharge) 	0.00756352250846118
21350587	994	group users by message last sent	select t1.sender, t1.receiver, max(t1.date) from tbla t1 inner join (select * from tbla ) t2 on t1.sender = t2.sender                                      and t1.receiver = t2.receiver                                      and t1.sender <> t2.receiver  group by t1.sender, t1.receiver 	0.0004752383242352
21351334	10021	sql logic to sort a table, calculate sum and duplicate rows for a specific date range	select [date],  [id],  convert(varchar(8), dateadd(ms, sum(datediff(ms, 0, cast([duration] as time))), 0), 108)   as duration, count(*) as nb from table1 group by [date], [id] 	0
21352593	17490	php numbers sort from mysql asc	select * from yourtable order by numbers + 0 	0.00617355039892536
21352658	23197	sql server datediff	select new_hwwarrantyenddate from table where  new_hwwarrantyenddate is not null and new_hwwarrantyenddate between getdate() and dateadd(day, 90, getdate()) 	0.683863887453825
21352824	12279	mathematical operation on mysql table name	select table_name from information_schema  where table_schema='your_database_name' and table_name.substring(4, len(table_name) - 4) > 'timex'  and table_name.substring(4, len(table_name) - 4) < 'timey'; 	0.174030172482958
21352917	27084	join tables using bridges	select e.firstname, e.lastname         from department_groups as dg  join employees_department as ed on (ed.department_id = dg.department_id)  join employees as e on (e.employee_id = ed.employee_id)  where dg.group_id = 2 	0.550350020862462
21352954	150	sql: selecting specific data concerning two diferent tables	select * from (select name,surname from moderator     inner join show on moderator_id = moderator.id    group by  moderator.id,name,surname    order by sum(length) desc)  where rownum = 1 	0.000160968572720316
21355074	472	get all the other user names where user=1 exists	select distinct b.name from tbla a join      tblb b      on b.id in (a.sender, a.receiver) and         ((b.id <> 1 and (a.sender = 1 or a.receiver = 1)) or          (a.sender = 1 and a.receiver = 1)         ); 	0
21356735	18804	group users by last sent/received message	select least(receiver, sender), greatest(receiver, sender),        max(date),        substring_index(group_concat(msg order by date separator '|'), '|', 1) as msg,        substring_index(group_concat(idmsg order by date), ',', 1) as idmsg,        substring_index(group_concat(name order by date separator '|'), '|', 1) as name from tbla  where '1' in (receiver, sender) group by least(receiver, sender), greatest(receiver, sender); 	0.00198446627975389
21359320	34737	how to create monthly reports from daily based reports using sql server	select sum(cost), [month], [year], customer-id from  (     select cost, month(date) as [month], year(date) as [year] , customer-id    from customerbooking where date >= '2-1-2014' and date <= '2-28-2014' ) as a group by [month], [year], customer-id 	5.50777111757544e-05
21359939	25783	what is the difference between these two postgres query	select 3 - null; 	0.0288721493292071
21360072	33911	fetching number of records from outer join table	select      band.*, count(comments.band) as count_no from     band         left join     comments on band.id = comments.band group by band.id; 	0.000552531174574849
21360631	32489	how to group by only 2 rows of a column?	select (case when column1 in ('type1','type2') then 'typex' else column1 end) as column1,     sum(column2) as column2  from table_name  group by (case when column1 in ('type1','type2') then 'typex' else column1 end) 	0
21361222	25126	sql query select statement	select name, role from manager m inner join login l on l.manager_id = m.manager_id where username="gmjohn" and password="abc"; 	0.734372125955491
21362771	16528	mysql vlookup duplicated values	select      t.person, f.projectteam `from`, t.projectteam `to` from        my_table t   left join my_table f          on f.person = t.person         and f.transfered = 1 where       t.transfered = 0 	0.0923581287159886
21363732	18506	mysql -- getting most popular item based on where condition in another table	select threadid,   count(*) as [count] from forumreplies group by threadid order by [count] desc 	0
21363930	3038	last occurrence in oracle	select value, timestamp from (     select min(a.start) timestamp,            a.id value,            a.id,            1 ord       from mytable a       group by a.id      union all      select max(a.end) timestamp,            '0' value,            a.id,            2 ord       from mytable a       group by a.id ) order by id, ord 	0.000911378219053943
21365014	24085	formatting decimal data type to show currency	select trim(salary * (-1) (format '-z(i)bn')) 	0.0410718067114293
21371585	7409	how can i collapse these fields and rows in this result set	select  caseid,  min(material) min_material, (select  cast(tooth as varchar(10)) + ',' from tt b where a.caseid=b.caseid for xml path('') ) list from tt a group by caseid 	0.0719163319348476
21372002	38367	joinining within a category	select year, min(day) as first_day from t where temperature > 100 group by year order by year 	0.0317144060345675
21372169	15714	create comma delimiter in select query	select * from wo where sales in (select a.department                 from dbo.m_salescode a left join dbo.m_salescode b                  on a.up1_code=b.sales_code left join vwemployeeads v                  on a.user_id=v.login                 where v.login = @saleslogin) 	0.0392163281411947
21373911	14034	optimize mysql query suppliers <-> products <-> categories with distinct	select  s.id  from    suppliers s  where   exists  (                     select  1                     from    products as p inner join                              products_categories as pc on p.id = pc.products_id                      where   (p.supplier_id = s.id)                     and     (p.color in ('red', 'blue'))                      and     pc.categories_id in (2,3,125)                 ) 	0.366461419507306
21375493	1069	sql statement with two sums and inner joins of three tables	select s.stock_id, s.stock_code, ifnull(si.total_in, 0) total_in,         ifnull(so.total_out, 0) total_out, s.balance  from stockinfo s left join (select si.stock_id, sum(si.quantity) total_in             from stock_in si             where si.date_time between '2013-12-01' and '2013-12-31'            group by si.stock_id          ) si on s.stock_id = si.stock_id left join (select so.stock_id, sum(so.quantity) total_out             from stock_out so             where so.date_time between '2013-12-01' and '2013-12-31'            group by so.stock_id          ) so on s.stock_id = so.stock_id group by s.stock_id 	0.245967476088402
21375564	14226	mysql row numbering reset every different record values	select  a.id,          a.plate_number,          (             select  count(*)             from    tablename c             where   c.plate_number = a.plate_number and                     c.id <= a.id) as rownumber from    tablename a 	0
21377252	18237	order multiple tables according to one column	select position from (   select base_layers.position as position   from base_layers   union   select selects.position   from selects   union   select subbases.position   from subbases  ) x order by position asc; 	0.000365746977690786
21377549	13066	mysql : how make recurring fields appear only once?	select   dist.name,   if(grouped.description is null, '', grouped.description) as description from (select    distinct name,    description  from    ninja as n      inner join ninja_type as nt        on n.ninja_type_id = nt.ninja_type_id) as dist left join (select     distinct name,     description   from     ninja as n       inner join ninja_type as nt         on n.ninja_type_id = nt.ninja_type_id   group by     description) as grouped on    dist.name=grouped.name 	0.00187308501363111
21377566	2283	select rows not in another table by comparing two table	select tablea.id     from tablea     where not exists (       select 1       from tableb       where tableb.month_id = tablea.month_id       and tableb.customer_id = tablea.customer_id       and tableb.total_amount = tablea.total_amount    ) 	0
21378385	28239	concat several rows into one using grouping in t-sql	select t.id, t.seq, max(t.amount) amount, d.ds from tbl t cross apply (     select [description] + ' '     from tbl b         where t.id = b.id             and t.seq = b.seq             and [description] is not null     for xml path('') ) d(ds) group by id, seq, ds 	0.00155915186625632
21379121	26832	best way to get single max value + another column value from sql	select b.*, (c.startpoint + c.length) as usedsize from tableb b inner join  (   select *, dense_rank() over(partition by c.majorid, c.minorid order by c.startpoint desc) as rank   from tablec c ) c on c.majorid = b.majorid and c.minorid = b.minorid and c.rank = 1 	0
21379529	30135	select fields using formatted date	select date from user      where date          between str_to_date('13/01/2011','%d/%m/%y %h:%i:%s')          and str_to_date('28/01/2014','%d/%m/%y %h:%i:%s') 	0.0100593845312337
21379905	5203	in sql query records is coming double	select   a.item_name, a.item_uom,   b.estm_id, b.estm_qntydlvrd, b.estm_itemprice, b.estm_lntotl into temp1 from dbo.productsnrwmtrls a left outer join dbo.estimatesdtls   on (a.item_id = b.item_id) select   c.item_name, c.item_uom,   c.estm_id, c.estm_qntydlvrd, c.estm_itemprice, c.estm_lntotl   d.quot_id into temp2 from temp1 c left outer join dbo.estimates d   on (c.estm_id = d.estm_id) 	0.327281358713574
21382399	17851	counting different values of the same table field in grouped result	select count(log_id) login_count        , date(date)        , plugin        , action     from universal_log l    group        by date( `date` )        , plugin        , action; 	0
21385129	31849	sql query where date='2012-10-22' but has more info in database	select * from table where date >= '2012-10-22 00:00:00' and date < '2012-10-23 00:00:00' 	0.0620862153631316
21385578	15131	need to select a row even when the value doesn't exist	select uid, max(case when game_id = 1 then score end) as game1max from scores group by uid; 	0.00985816187094319
21385733	33999	how to combine two sql queries result	select  visitdate = left(datename(month,v.visitdate),3),          count( distinct i.inspectorid) as totalused,         count(distinct case when i.officeid  in (5) then i.inspectorid end) as totalcontractorused from visits v   inner join inspectionscope insp on insp.assignmentid = v.assignmentid   inner join assignments a on a.assignmentid = insp.assignmentid    inner join inspectors i on i.inspectorid = insp.inspectorid  where a.clientid in (22,33) group by datename(month,v.visitdate); 	0.0139771339377875
21390653	32891	sql select only rows where certain condition is met	select     base.pt as "patient number",     max(base.vist_date) as "baseline",     max(proc.visit_date) as "procedure",     case         when followup.visit_interval = '1_month'         then followup.visit_date         else null end as "1 month",     case when followup.visit_interval = '2_month'     then followup.visit_date     else null end as "2 month" from base left join proc     on base.pt=proc.pt left join followup     on base.pt=followup.pt group by base.pt 	0.000186190789990196
21390970	27681	count sum of up and down vote for each item	select a.asset_id, f.filename,        coalesce(sum(v.vote = '1'), 0) as upvote,        coalesce(sum(v.vote = '-1'), 0) as downvote from asset a join asset_files f on a.asset_id = f.asset_id left join vote v on a.asset_id = v.asset_id group by a.asset_id 	0
21392127	27177	mysql query with where statement with varchar field	select * from `projecttabs` where find_in_set('10', projecttab ); 	0.693884506543224
21393212	10379	sql, select max 5 from field	select percentage from x order by percentage desc limit 5 	0.00153804749817838
21393340	30655	(sql) using select statements to display data with odd requirements	select company from   yourtablename group by company having count(*) > 1 	0.269948597128553
21395638	18901	group mysql query by field with same value and count	select city, lon, country_code, lat, count(*) as number_of_items from table t where timestamp between starttimestamp and endtimestamp group by city, lon, country_code, lat; 	0.00254497607841094
21396336	35641	mysql order by best match and order by field	select * from mall where mall_status = '1' and        (mall_name like '%cap%' or mall_name like '%square%' or mall_name = 'cap square' or         tag like 'cap square,%' or tag like '%,cap square' or tag like '%, cap square' or        tag like '%,cap square,%' or tag like '%, cap square,%' or tag = 'cap square'       )  order by mall_name = 'cap square' desc,          field(state_id, 14, 10, 5, 4, 1, 6, 11, 3, 2, 7, 8, 15, 12, 13) asc , mall_name limit 0, 30 ; 	0.0358174344919118
21396601	28671	use value from a subquery	select a, b, total, total / 2 from (   select a, b, (select count(*) from x) as total   from y   where ...) z 	0.0753758505311555
21397695	3060	hide mysql count column	select region from   world group  by region having count(*) > 1 	0.0453512253813399
21397766	3657	convert c# datetime to 0000-00-00 00:00:00 to mysql	select * from information_schema.global_variables   where variable_name = 'sql_mode'; 	0.164379548389899
21398061	16514	use result from query in same query?	select location  from contractors  inner join teams on teams.location = contractors.location and teams.team_id = 3 	0.0553274281432512
21398437	39246	sum of column name using group by in sql server?	select min(ps.sno) as sno,         pd.productname,        sum(ps.quantity) as quantity,        ps.modelno  from k_rt_purchasedet ps   join k_rt_productdetails pd on pd.sno=ps.product   where purchasedby=@purchasedby    and ps.quantity!=0 and attrited='false' group by pd.productname,          ps.modelno,          ps.company 	0.0235529054349394
21398855	25971	daily report in a month from different tables	select, dates.adate, table-1.amount1, table-2.amount2, table-3.amount3, table-4.amount4 from (     select date_add('2013-04-01', interval (units.i + tens.i * 10) day) as adate     from     (select 0 as 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,     (select 0 as 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     having adate <= '2013-04-30' ) dates left outer join table-1 on table-1.date1 = dates.adate left outer join table-2 on table-2.date2 = dates.adate left outer join table-3 on table-3.date3 = dates.adate left outer join table-4 on table-4.date4 = dates.adate 	0
21399337	24027	how to add serial number over a randomly generated resultset in sql server?	select row_number() over (order by newid()) as slno, *  from mytable order by 1 	0.000143747054401845
21399544	24573	mysql, group by and subquery in one row	select id, title, tag from contents  join   (select id_content, group_concat(tag) as tag from contents_tags    join tags on contents_tags.id_tag=tags.id group by id_content) t on contents.id=t.id_content 	0.0255806938732782
21400417	23172	how to display all row data after ordering is done using union with single column	select name,lastname,id,position from ( select name,lastname,id,base_layers.position as position from base_layers where base_layers.section_id =1 union  select name,lastname,id,selects.position from selects where selects.section_id =1 union  select name,lastname,id,subbases.position from subbases where subbases.section_id =1 )x order by position asc 	9.34486487310992e-05
21403052	20610	sql count() in query	select `cola`, count(distinct `colb`) from `data` group by `cola` order by `cola` asc; 	0.411032898746839
21403764	6261	multiple group_concat	select        matchnumber,       group_concat( winners ) winners,       group_concat( losers ) losers    from       (          select           matchnumber,           teamnumber,           case result when 'w'                   then group_concat(individualname separator '&') end winners,           case result when 'l'                   then group_concat(individualname separator '&') end losers,           group_concat(result separator '&') r          from           resultstbl           group by            matchnumber, teamnumber       ) g     group by matchnumber 	0.499061896990471
21404660	39216	get all year and months from date range in sql with or without data	select year(sg_process_date) as yearname ,datename(month, dateadd(month, month(sg_process_date), 0) - 1) as monthname ,sum(sg_worktime) as workhour from innovator.[sg_attendance] where ( sg_process_date between '2013-01-01' and '2014-03-01') group by year(sg_process_date),month(sg_process_date) union  select datename(year, dateadd(month , x.number , '2013-01-01')) as yearname, datename(month, dateadd(month, x.number, '2013-01-01')) as monthname, 0 as workhour  from    master.dbo.spt_values x where   x.type = 'p' and     x.number <= datediff(month, '2013-01-01', '2014-03-01') except select year(sg_process_date) as yearname ,datename(month, dateadd(month, month(sg_process_date), 0) - 1) as monthname ,0 as workhour from innovator.[sg_attendance] where ( sg_process_date between '2013-01-01' and '2014-03-01') group by year(sg_process_date),month(sg_process_date) 	0
21404818	37653	concatenate data from two fields ignoring null values in one of them?	select trim(a.firstname) & ' ' & trim(a.lastname) as employee_name, a.city, a.street & (' ' +a.housenum) as address from employees as a 	0
21404904	19601	populating data in checkboxlist in asp.net	select * from student_info where emp_id is null 	0.697685578390092
21405132	39259	query to get data with minimum query cost	select accountid, sum(case when bid_fk=1 then amount else 0 end) amount1, sum(case when bid_fk=2 then amount else 0 end) amount2 from yourtable group by accountid 	0.00857828406004522
21405379	12094	mysql count paid sales and orders	select sales.id,     max(sales.price) sales_price,     sum(payment.price) payment_price from sales, payment where sales.id = payment.sale_id group by sales.id having max(sales.price) = sum(payment.price) 	0.00142083457700897
21406363	32374	select query with priority based on column values	select term, arr, org, sta, ata, arr_pax, asrc, dep, dep_pax, dsrc, std, atd,        max(dep_pax) keep (dense_rank first order by apriority) from (select t.*,              sum(case when dpriority = 'usr' then 1 else 0 end) over (partition by . . . ) as numusr,              sum(case when dpriority = 'ldm' then 1 else 0 end) over (partition by . . . ) as numldm       from t      ) t where dpriority = 'usr' or numusr = 0; 	0.000308680936195542
21406927	15949	how can i get info from 2 tables into one sql query?	select image1 as image, boat1 as boat from all_images union all select image2 as image, boat2 as boat from all_boats_images 	0
21407645	20468	retrieve records that have been timestamp updated since last accessed / read	select messages.id as unread from   messages left join (select message_id, max(last_read_timestamp) as last_rd                       from reads                       where user_id = 1                       group by message_id) lr   on messages.id = lr.message_id      and messages.timestamp < lr.last_rd where   lr.message_id is null 	0
21408051	9910	php mysql select with group by date range	select * from table where time between '$start' and '$end' group by date(time),datepart(hh,time) 	0.0104449682533092
21409077	18745	get data from 2 tables, of the same id with $pdo	select se.value, st.name, st.url from oc_setting  se inner join oc_store st on st.store_id = se.store_id and st.key = 'config_logo' 	0
21417153	25587	mysql: value of child lines based on proportion of cost?	select t1.line_id,        t1.sku,        t1.name,        t1.weight,        if (t1.parent_line_id is null,t1.value,            round(t1.cost * t2.value_divided_by_total_cost,2))as value,        t1.cost,        t1.is_kit,        t1.parent_line_id from packslip t1 left join    (select parent_line_id,(select value from            packslip p2 where p1.parent_line_id = p2.line_id)            /sum(cost)            as value_divided_by_total_cost     from packslip p1     where parent_line_id is not null     group by parent_line_id     )t2 on t1.parent_line_id = t2.parent_line_id 	0
21417291	31689	find out who modified a stored procedure	select name, create_date, modify_date  from sys.objects where type = 'p' 	0.00544011203041403
21418051	25922	selecting from multiple tables and adding up all occurrences from 1 table	select `account id`, `date`, sum(`hours`) as `hours`, sum(`minutes`) as `minutes` from `table1`  join `table2` on (`table1`.`account id` = `table2`.`account id` and `table1`.`date` = `table2`.`date`) group by `account id`, `date`; 	0
21419928	37730	sql query to joint a data table with different data from another	select   questions.name as questionname   answers.name as answername from records   inner join nodes as questions on records.questionid=questions.id   inner join nodes as answers on records.answerid=answers.id 	6.2531321031503e-05
21420434	10209	mysql - combine single result query & multi result query into one	select     a.userid,     a.profile_username,     a.profile_gender,     a.photo_name,     a.photo_verified,     b.profile_headline,     year(date_sub(now(),      interval to_days(a.profile_birthdate) day)) as age,     d.city,c.english as country,     (select count(*) from photos where photo_description_profanity=1 and photo_visible=1 and photo_verified=1 and userid= a.userid) as result_count from login as a join `profiles` as b on a.userid=b.userid  join geocountry as c on a.profile_country=c.countrycode join geoworld as d on a.profile_geo_location=d.pid where a.userid in ('1000000002','1000000003','1000000004'); 	0.00203096197892716
21420657	19656	sql server : joins, duplicate records and union	select c.idcontract, c.sgcommonname, cl.sgclienttitle, cl.sghomeaddress, cl.sglettercasual,        c.sglotaddress, ffd.sgcaption, ffv.sgtextvalue,        max(case when fkidffdefinition = 1161 then dtdatevalue end) as "11 day",        max(case when fkidffdefinition = 1162 then dtdatevalue end) as "30 day" from tblcontracts c inner join      tblclients cl      on cl.idclient = c.fkidclient inner join      tblflexfieldvalues ffv      on ffv.fkidcontract = c.idcontract inner join      tblflexfielddefinition ffd      on ffd.idflexfielddefiniition = ffv.fkidffdefinition  where ffd.idflexfielddefiniition in (1161, 1162) group by c.idcontract, c.sgcommonname, cl.sgclienttitle, cl.sghomeaddress, cl.sglettercasual,          c.sglotaddress, ffd.sgcaption, ffv.sgtextvalue; 	0.0956946945668013
21424764	8139	select data from mysql in different order	select * from table order by field(column_name,4,3,2,1,5) ; 	0.00247148097455518
21425516	8816	mysql selective group by, using the maximal value	select sz.name,         count(*)  from   (select r.user_id,                 ifnull(max(k.szak_id), -1) as max_szak_id          from   user_reservations r                 left outer join user_kar k                              on k.user_id = r.user_id          group  by r.user_id) t         left outer join szak sz                      on sz.id = t.max_szak_id  group  by sz.name; 	0.0105936283934318
21425541	28945	sql order by using different conditions	select categoryname  from table1 order by case when categoryname like 'b%' then 1               when categoryname like 'd%' then 2               when categoryname like 'c%' then 3          end asc 	0.131486514112729
21427275	25244	how to select two tables compare them and get a single column value in php mysql	select city  from   customers  union  select city  from   suppliers  order  by city; 	0
21427509	26753	tsql : sum of count of distinct rows per day within a specified time period	select c_count.tran_date         ,sum(c_count.tot) as customer_count  from         (select r.tran_date        ,count(distinct (slip_no)) as tot          from rem_upload r         where  (r.location_id like '001') and (r.tran_type <>'z' and r.tran_type <> 'x') and (r.tran_date >= '2014-01-02' and r.tran_date  <= '2014-01-03')          group by r.mech_no                  ,r.tran_date)as c_count   group by tran_date 	0
21427684	11303	how to get the rows of master table only if details table satisfies condition?	select tto.orderid,tto.dateadded,tto.itemscount,tto.totalamount,     ttu.firstname,ttu.lastname,ttu.email ,isnull(ttu.firstname,'') + ' ' + isnull(ttu.lastname,'') fullusername     from tbl_orders tto join tbl_users ttu      on tto.userid = ttu.userid     where tto.orderid = isnull(@orderid,tto.orderid)     and tto.userid = isnull(@userid,tto.userid)     and tto.itemscount= (         select count(orderid) from tbl_uerquotes where orderid=tto.orderid and quotestatusid=4         )     order by tto.dateadded desc 	0
21431808	7143	mysql group by single column but aggregate on multiple columns?	select      user_id,      sum(rank = 1) as rank1,      sum(rank = 2) as rank2,      sum(rank = 2 and is_fresh = 1 ) as rank2_fresh,     sum(if(rank = 1, age, 0))/sum(rank = 1) as rank_1_avg_age     ...  from users group by user_id 	0.00326322828011754
21432095	10628	mysql select from two tables and cutting down queries	select wptr.*, wptt.taxonomy from wp_term_relationships wptr  inner join wp_term_taxonomy wptt on wptr.term_taxonomy_id = wptt.term_taxonomy_id where object_id = '88' 	0.00551793348175992
21432113	13798	mysql get rest of values	select * from ... group by job_primary.id 	0.000257269499592226
21432478	1227	select union all - select always zero for two fields	select *, (select case      when rot_tore > schwarz_tore      then 1 else 0   end ) as w_r, (select case      when schwarz_tore > rot_tore     then 1 else 0   end ) as l_r, (select case      when schwarz_tore > rot_tore      then 1 else 0   end ) as w_s, (select case      when rot_tore > schwarz_tore      then 1 else 0   end ) as l_s, rot_tore tore, schwarz_tore gegentore from `kicker_spiele` where datetime is not null 	0.00121650464773229
21432757	36389	generate random values in oracle view	select value1, value2, step, row_number() over (partition by value1, value2 order by rn) from      (select value1, value2, step, rownum as rn     from table ) 	0.0209613359879228
21434739	35691	traverse sql hierarchy from bottom up till specific level reached	select s.id from treetable s where s.l = (select max(t.l)             from treetable t, treetable leafnode             where t.isactive = true               and t.l < leafnode.l               and t.r > leafnode.r               and leafnode.id = ?) 	0.00186721815702916
21436555	24843	check rows for same entries in neighbouring columns	select a.id, a.col1, a.col2   from tbl as a   join tbl as b on        (     a.id=b.id         and (a.col1 =  b.col2 or  a.col2 = b.col1)         and (a.col1 != b.col1 and a.col2 != b.col2)       ) 	0
21437104	4221	sql select for each age group and count members	select agegroups.groupid, agegroups.grouptitle, count(1) as membercount from agegroups join events on eventid = 1 join members  on datediff(year, members.dob, events.eventstart) >= agegroups.minage and datediff(year, members.dob, events.eventstart) <= agegroups.maxage order by agegroups.groupid 	0.000113094490387138
21438157	18290	select one value if it exists, another if not	select ..  coalesce(`short_description_id`.`value` , `short_description_id_default`.`value`) as `short_description` .. from  ...      left join `catalog_product_entity_text` as `short_description_id`       on p2c.product_id = short_description_id.entity_id           and short_description_id.attribute_id = 62          and (short_description_id.store_id = 3)      left join `catalog_product_entity_text` as `short_description_id_default`       on p2c.product_id = short_description_id.entity_id           and short_description_id.attribute_id = 62          and (short_description_id.store_id = 0) 	0.00179422880818054
21438399	15046	join on all fields without listing them?	select * from a intersect select * from b 	0.00212438745488574
21439342	4050	improving speed of sql query with max, where, and group by on three different columns	select example1.name, max(example1.id) from exampletable example1 inner join ( select name, max(dateadded) dateadded from exampletable where dateadded  <= '2014-01-20 12:00:00'  group by name ) maxdatebyelement on example1.name = maxdatebyelement.name and example1.dateadded = maxdatebyelement.dateadded group by name; 	0.3252864703193
21439748	13502	subquery as another field	select i.order_date,        c.name,        group_concat( concat(x.itemname,' ', x.itemdesc) separator "\n" ) as info from invoices i  inner join customers c on i.customer = c.id left join invoice_items x on i.id = x.order group by i.order_date,c.name 	0.0394333664279999
21440009	18958	row_number for most used returning all rows	select productid, arpvend, rn from (   select productid, arpvend, rn,            row_number() over(partition by productid order by rn desc) rownum   from firstresultset ) a where rownum = 1 	0.00648939406675907
21440274	11061	take top 3 count from two table sqlserver 2008	select top 3 dbo.family.f_id from dbo.family  inner join dbo.family_member on dbo.family.f_id = dbo.family_member.fm_f_id group by dbo.family.f_id order by count(*) desc 	9.91694486567362e-05
21440754	36789	mysql tagging system - top keywords per month	select * from (     select *, @rowno := if(@pv = week, @rowno+1, 1) as rno, @pv := week     from (         select keyword_id, count(*), yearweek(from_unixtime(created)) as week         from keyword_sentence         where              from_unixtime(created) >= current_date - interval 2 month         and             from_unixtime(created) < current_date - interval 1 month         group by week, keyword_id         order by week, count(*) desc     ) temp     join (         select @rowno := 0, @pv := 0     ) tempvalue ) tmp where     tmp.rno < 6 	0.003282491519852
21441988	10717	sort and count sql results with php	select count(1) as frequency, referrer  from url_log where u = '".$dom."' group by referrer order by frequency desc; 	0.145980659259313
21445172	31236	simple query for the relationship	select e.emp_id, e.lname from  employee e join contactinfo c on e.emp_id = c.emp_id  join phones p on c.contid = p.cont_id  join phonetype pt on pt.phonetype_id = p.phonetype_id  join department d on d.dept_id = e.dept_id where d.type = 'tech' and pt.type = 'w' 	0.698946838259233
21445706	8520	find total children for each parent	select e1.manager, count(e1.id) as emp_count from employee as e1 where e1.manager is not null group by e1.manager 	0
21447943	2391	filter query results in group by with condional counts	select p.parent_id,        count(*) as children,        sum(c.qty > 0) as in_stock,        sum(c.qty = 0 and c.wh_soh > 0) as warehouse,        sum(c.qty = 0 and c.wh_soh = 0) as out_of_stock from test_parent p  inner join test_relation r using (parent_id) inner join test_child c using (child_id) group by p.parent_id having children > 3    and in_stock > 0    and warehouse > 0    and out_of_stock > 0 	0.536653886702213
21448421	23702	remove the 00:00:00.000 from a sales query mysql	select date(sales_date) from sales where date(sales_date)  between '2013-11-02' and '2013-12-01' 	0.00425152153703059
21449426	30923	sql order by multiple fields in different order	select * from table order by firstnumber,secondnumber desc; 	0.0202964052317843
21451327	4875	mysql query to peform join between 2 tables	select professor.name from  professor join works a on a.empid=professor.empid and a.classid=9 join works b on b.empid=professor.empid and b.classid=10 	0.118421958098365
21451444	25880	select query with distinct on one field	select   id1,id2,id3  from   (    select          [t1].[id], [t2].[id] , [t3].[id] ,         rn = row_number() over(partition by [t1].[id] order by [t1].[id])    from  [t1]    inner join [t2] on [t1].[id] = [t2].[t1id]    inner join [t3] on [t2].[id] = [t3].[t2id] )a where a.rn = 1 	0.00612485593718171
21451764	37617	inner join with m/n relationship tables and sum of a certain column	select users.*,         codes.code,         sum(users.downloads) as _downloadscount  from   users         left join (codes                    inner join codes_users                            on codes.id = codes_users.code_id)                on users.id = codes_users.user_id  group  by users.id; 	0.00155021285253436
21452106	35815	sqlite android add character field	select 'b ' || value_a || ' b' from a where value_a like '%1 % 2 -%' 	0.106349987438328
21452231	14301	select dbnull in sql with user defined table type	select item  from dbo.customertable where isnull(customerid,'') in (select customer from @customers) 	0.0664802720074722
21453334	36791	cannot understand the date output of query in mysql	select current_date, `current_date` from tab; 	0.395327611329912
21453719	16916	combine two sql statements where both must be true in many to many relationship	select   r.id, r.title,   u.name as 'created_by',   group_concat( concat(cast(c.id as char),',',c.name,',',c.value) separator ';') as 'categories' from   resource r   inner join    (select    distinct r.id as id   from    resource r   inner join    category_resource cr1 on (r.id = cr1.resource_id)   inner join    category_resource cr2 on (r.id = cr2.resource_id)   where    cr1.category_id in (8, 9)   and    cr2.category_id in (10, 11, 12)) mr     on r.id = mr.id   inner join category_resource cr     on r.id = cr.resource_id   inner join category c     on cr.category_id = c.id   inner join user u     on r.created_by = u.id group by r.id; 	0.0810574397302055
21453796	15925	is there a way to return more than 1 row in select without using existing tables	select n from (values (1),(2),(3)) d(c); 	0.00124029596191301
21454684	26637	count the number of spaces in values in sql server	select len(column1)-len(replace(column1, ' ', '')) 	0.00109572626659828
21455226	24024	mysql: show strings in result that were not found	select stringcolumn, count(*) from tablename group by stringcolumn 	0.0033651268268789
21455568	10410	summarize initial column mysql	select malecount+femalecount as sumcount from  (select count(if(gender="male",1,null)) as malecount,    count(if(gender="female",1,null)) as femalecount   from biodata) as  query 	0.06385469773653
21456096	6663	how to extract specific values using a query?	select a.name from test a, test b where a.parentid = b.id and b.name="t1"; 	0.00229263481959257
21456788	24887	selecting rows having more than one connection to another two tables	select customers.* from customers inner join (   select customer_id, count(*) as count from contracts group by customer_id    having count > 1 ) as contracts on customers.id = contracts.customer_id inner join (   select customer_id, count(*) as count from phones group by customer_id    having count > 1 ) as phones on customers.id = phones.customer_id 	0
21458033	15598	how to divide by the result of another query	select job_group, current_people,        current_people / sum(job_group = 'worker1' then current_people end) over () as ratio from (select job_group,              sum(people) as current_people       from my_view       where month = '01-dec-2013'       group by rollup (job_group)      ) t order by ratio desc; 	0.00118987978124856
21458410	29684	select values with duplicate max values sql	select    max(sales),    max(date_) keep (dense_rank first order by sales desc),    sum(sales),    min(date_) from    table_ 	0.00107262925510834
21458633	5002	update with last known location?	select   data.ppid,   data.point_time,   case     when data.the_geom is null     then (       select geom.the_geom       from test_data geom       where data.ppid = geom.ppid       and geom.point_time < data.point_time       and geom.the_geom is not null       and not exists (         select *         from test_data cull         where cull.ppid = geom.ppid         and geom.the_geom is not null         and cull.point_time < data.point_time         and cull.point_time > geom.point_time         and cull.the_geom is not null         )     )   else data.the_geom   end from test_data data 	0.00069455433318989
21461767	18476	selecting last element with sql select last and turing it into php variable	select * from producten order by product_id desc limit 0,1 	0
21462506	21441	selecting records group by	select type, id, id2, address from (select a.*,              rank() over (partition by id2 order by addresscnt desc) as addressrank       from (select a.*,                    (case when max(address) over (partition by id2) =                               min(address) over (partition by id2)                          then 1 else 0                     end) as addresssame,                     count(*) over (partition by id2, address) as addresscnt             from a            ) a      ) a where (addresssame = 1 and type = 'self') or       (addressrank > 1 or type = 'self') or       id2 is null; 	0.00458428183684148
21464369	22992	how to compute the cost of querying an additional table using left join?	select * from a          left join b                    on a.src_ip::inet = b.ip                    and b.resolve_time is not null and b.resolve_time <= now()                    and b.expire_time is not null and now() < b.expire_time 	0.176712478310021
21469126	8748	passing a column result as a parameter of other datasets	select ordersid, field1, field2, field3 from table2 where ordersid in (select ordersid from table1 where filenumber = @filenumber); 	0.0031104887053134
21471120	11355	need hint with mysql query from 2 tables	select d.name, active, ratio, import_id  from data d join names n on d.name = n.name where import_id = (select import_id                    from data                    order by id desc                    limit 1) and d.status = 'online' and n.active = 1 order by ratio desc limit 1 	0.159936423530648
21474075	2277	show distinct tuples regardless of column order	select distinct        least(s1.country, s2.country) c1,        greatest(s1.country, s2.country) c2   from battles b1 join battles b2     on b1.battlename = b2.battlename    and b1.ship <> b2.ship join ships s1     on b1.ship = s1.name join ships s2     on b2.ship = s2.name having c1 <> c2 	0.000263888526154468
21475617	24689	sql where clause count for individual records	select purchases.customer_name, purchases.product_name, count(purchases.product_name) from purchases where customer_name "brian" and product_name like 'al% group by purchases.product_name, purchases.customer_name; 	0.0601009574828127
21477024	2802	use result of two subqueries to calculate ratio	select performance_ratios, ratio1, ratio2, ratio1 - ratio2 as subtract, ratio1 * ratio2 as multiply from ( select 'active borrowers per loan officer' as performance_ratios,     (         select count(distinct l.customer_id) / count(distinct l.mis_acct_officer) as ratio         from ld_loans_and_deposits l         where report_date = (                 select min(report_date)                 from ld_loans_and_deposits                 )         ) as ratio1,     (         select count(distinct l.customer_id) / count(distinct l.mis_acct_officer) as ratio         from ld_loans_and_deposits l         where report_date = (                 select max(report_date)                 from ld_loans_and_deposits                 )         ) as ratio2 ) table 	0.00576259537456605
21479211	16526	write a query to select a column with a additional letter	select concat(id,'d') as id from tb_abc  where title='xyz' 	0.035796168835605
21479576	22199	how to store result of cross-table-query to a table variable	select_result  select_results%rowtype; 	0.00914972758633271
21480459	36804	compare two database tables of differing types and compare their data?	select * from openquery(test,'select * from mysql_table) 	0
21482482	35565	logics extracting right dates from mysql	select if(  now() < (select min(date) from event_dates)  and now() > (select max(date) from event_dates), (select date from event_dates where date > now() order by date asc limit 1),  '-1' ); 	0.0125838021782365
21482853	16252	how to select which id comes second the most often in sql server	select  ib_b, count(id_a) no_of_times from (select *, row_number() over (partition by id_a order by dt) as row_no from t1)temp where row_no = (select top 1 row_no+1 from (select *, row_number() over (partition by id_a order by dt) as row_no from t1)temp where ib_b =6 ) group by ib_b order by count(id_a) desc 	9.72290217108128e-05
21483625	13134	sql get the latest records from a set of data	select * from holdings where holding_date = (select max(holding_date) from holdings) 	0
21483775	16890	selecting last n dated records for each in a group	select x.*    from my_table x    join my_table y      on y.name = x.name     and y.date >= x.date   group      by x.name      , x.date  having count(*) <= 2   order      by name,date desc; 	0
21484966	20398	mysql join with two potential field names	select d.isself, other_id, u.displayname as other_name, a.url as other_avatar, text from (     select 0 as isself, m.sender as other_id, m.timestamp, m.text     from messages as m     where m.recipient = ?     union     select 1 as isself, m.recipient as other_id, m.timestamp, m.text     from messages as m     where m.sender = ? ) as d     left join user as u          on u.id = d.other_id     left join avatars as a         on a.id = u.avatarid where unix_timestamp(timestamp) > ? order by m.timestamp asc limit 100 	0.0102716287810811
21485876	23679	querying all data from multiple tables	select a.locid, a.locname, b.subareaid, b.subareaname, c.username from location a     left join subarea b on a.locid = b.locid     outer apply (select c.username               from details c               where a.locid = c.locid                   and (c.subareaid = b.subareaid or b.subareaid is null)     ) as c 	0.000339218872729478
21486073	12782	fetching required data using joins in mysql	select      professor.name, count(works.courseid) from     works inner join     professor on          professor.empid = works.empid  where     work.classid = 10 group by     professor.name  order by count(works.courseid) desc limit 1 	0.640399220084358
21486795	25450	translate value to name sql	select c1.currencyshortcut [currency1], c2.currencyshortcut [currency2]  from spot as s     join currencies as c1 on s.currencyid = c1.currencyid     join currencies as c2 on s.currencyid = c2.currencyid 	0.113489512412398
21487104	16750	how to select max value for each id in sql select statement?	select a.projectid,a.maxstageid,b.stagename from (select projectid,max(stageid) as maxstageid       from stageproject        group by 1 ) a inner join stagetable b on a.maxstageid = b.stageid; 	0
21487531	27389	select on aggregate result	select     b.name,     ue.event_title,     ue.event_vis,     ue.event_date,      tmp.shares,     (dayofyear(ue.event_date) - dayofyear(curdate())) as days from     brains b join user_events ue on b.user_id = ue.user_id     left join (         select             ls.user_id,             ls.event_id,             count(*) as shares         from             list_shares ls         group by             ls.user_id,             ls.event_id) tmp on b.user_id = tmp.user_id and ue.user_event_id = tmp.event_id where     b.user_id = 63 and     ((ue.event_vis = 'public') or (tmp.shares > 0)) and      mod(dayofyear(ue.event_date) - dayofyear(curdate()) + 365, 365) <= 30  order by     days asc 	0.271572123212827
21488570	13706	sql join - looking to search one table for keyword, two other tables	select     c.company_name from     company c join company_states cs on c.companyid = cs.companyid     join states s on cs.stateid = s.stateid where     c.company_name like '%associates%' and     s.stateid = 7 	0.00347572991277993
21493219	14315	postgres - counting children in level (below) using ltree	select count(distinct subpath(path, 1, 1)) from foo 	0.0330683889774334
21494259	18659	retrieve mysql entry from a sub/child table	select min(portfolio_id) from portfolio where person_person_id = '$id' select min(file_store_id) from file_store where portfolio_portfolio_id = $oldestportfolioid 	7.70762032491139e-05
21495750	36669	unable to get exact results for select query with join	select count(*), x from (     select count(fp.kat),fs.cid,fcc.cid as x     from tbl1 fs     left join tbl2 fp  on fs.cid=fp.cid     left join tbl3 fcc on fcc.cid=fp.kat     group by fcc.cid,fs.cid ) y group by x 	0.161662548148152
21496245	39580	sql server count distinct value of a field	select to,      (select count(*) from content c where c.id= p.id and c.isspecial=1) as special,      (select count(*) from content c where c.id= p.id and c.isperishable=1) as perishable,      (select count(*) from content c where c.id= p.id and c.isperishable=1) as danger from pack p group by to 	0.00161034059573544
21496938	29744	mysql null and empty values sorting	select yourtable.* from yourtable order by   concat(user_country,user_state,user_city,user_area,user_pincode) is not null,   (user_country is null) +   (user_state is null) +   (user_city is null) +   (user_area is null) +   (user_pincode is null) 	0.0722768623934979
21497696	22535	mysql query to find the value	select      concat(         ('po_'),         year(current_timestamp),         '_',         substring(upper(monthname(current_timestamp)),1,3),         '_',         ifnull(max(cast(             replace(po_number,             concat('po_',                 year(current_timestamp),                 '_',                 substring(upper(monthname(current_timestamp)),1,3),                 '_'),'') as unsigned ))         +1,1)) as number     from po_jobs 	0.00539051903423415
21501778	10782	mysql- count the most occurring string in a column	select club, count(club) from sport group by club order by count(club) desc limit 1 	0.000598961088281717
21502823	32542	need to calculate payroll for a few employees in sql (across two tables)	select          ed.firstname,         ed.lastname,         sum(ed.salary) as salaryperemployee     from employeedata ed     inner join jobtitle jt on ed.jobid = jt.jobid                            and jt.exemptnonexemptstatus = 'exempt'     group by ed.firstname,  ed.lastname,     order by salaryperemployee; 	0.000276850018664746
21502970	20145	sql inner join among 2 tables summing the qty field multiple times	select a.orderno, a.styleno, a.qty, b.qtyship from (   select orderno, styleno, sum(qty) qty   from a   group by orderno, styleno   ) a     join (   select orderno, styleno, sum(qtyship) qtyship   from b   group by orderno, styleno   ) b on a.orderno = b.orderno and a.styleno = b.styleno 	0.000335188243949073
21505116	10527	how to select all even post id's from a table in a mysql database (php)	select * from table where (id % 2) = 0; # even select * from table where (id % 2) > 0; # odd 	0
21505722	2686	mysql outer join three tables	select      a.id_team,     a.team_name,      b.id_person,      b.is_leader,      c.name  from      teams as a     left outer join (teams_has_persons as b                       inner join persons as c on b.id_person = c.id_person )                       on (a.id_team = b.id_team and b.is_leader = 1) 	0.759017080291209
21508389	32735	sqlite use year with date functions in where clause and group by	select date(trxdatetime / 1000, 'unixepoch') from trx_log 	0.747986061990488
21509100	29243	storing, retreiving and searching tags in mysql database	select distinct reverse(substring_index(reverse(substring_index(tags, ',', n.n)), ',', 1)) as tags from products cross join      (select 1 as n union all select 2 as n union all select 3 as n union all select 4 as n) n having tags is not null 	0.0364836981808291
21510148	13543	importing data from postgres table into sql server view	select * from openquery(pgexample, 'select * from yourtable'); 	0.00275175949943461
21514037	31215	only show recent data from db	select * from transfer where personid=$user  and (`time` > date_sub(now(), interval 30 day) 	0
21516145	38835	sql count using subquery	select user, count(*) from orders where entry_date between sysdate - 5 and sysdate group by user 	0.696477441831688
21518283	27865	how to group difference of date values by range	select * from  (   select fldfranchisecode, ...   from   (      select fldfranchisecode, case ...     from     (       select fldrecordid, ...       from       (         select fldrecordid, ...         from    tblstatuslog t1         join tblinquiry on t1.fldinquiryrecordid = tblinquiry.fldinquiryrecordid       ) as t       group by range, fldfranchisecode                ^^^^^ note, can't group by an alias here     ) q1   ) as q2  ) as q3    pivot (   max(jobs)   for [day range] in ([0- 9],[10-19],[20-29],[30-39],[40-49],[50-59],                      [60-69],[70-79],[80-89],[90-99],[over 100]) ) as pvt; 	0
21518307	18388	selecting from two tables based on id and timestamps	select t.*    from tasks t   left   join completed c     on c.taskid = t.id    and c.datetime between  1391385600 and  1391472000  where c.id is null; 	0
21518502	15950	mysql sorting by votes in another table	select v.id,   sum( v.count) as totalcount from  (select e1.id as id, 2 as count from votes as v join entries as e1   on v.vote1 = e1.id union all select e2.id as id, 1 as count from votes as v join entries as e2   on v.vote2 = e2.id) as v group by v.id order by totalcount desc 	0.00772930293507501
21518922	22611	sql group by statement, max values for grouped data	select sheet1.productid, sheet1.reportingdate, sheet1.quantity from sheet1 inner join (select sheet1.productid, max(sheet1.reportingdate) as maxofreportingdate from sheet1 where reportingdate < #2012/03/15# group by productid) as a  on sheet1.productid = a.productid and sheet1.reportingdate = a.maxofreportingdate order by sheet1.reportingdate desc 	0.00967996608903961
21519797	13550	how to apply group by in sql	select distinct t1.scantime, stuff(      (select ',' + convert(varchar(10), t2.imageid, 120)       from yourtable t2       where t1.scantime = t2.scantime       for xml path (''))       , 1, 1, '')  as imageids from yourtable t1 	0.399906096781533
21521269	22749	mysql query to return 2 counts on same data field	select count(*) as 'grand total',        sum(lastcontact > date_add(now(), interval -6 minute)) as 'online total' from computers 	9.93010045885354e-05
21522833	27015	how to get distinct values from a table for a particular column?	select distinct totalmarks,student_id from studenttable group by stuident_id; 	0
21523876	4471	index statistics available for not existing index?	select sch.[name] as 'schema'        ,tbl.[name] as 'table'        ,ix.[name] as 'index'       ,ix.index_id       ,ixstats.[avg_fragmentation_in_percent]       ,ixstats.[page_count] from [sys].[dm_db_index_physical_stats] (db_id(), null, null, null, null) as ixstats inner join [sys].[tables] as tbl      on tbl.[object_id] = ixstats.[object_id] inner join [sys].[schemas] sch      on tbl.[schema_id] = sch.[schema_id] inner join [sys].[indexes] as ix      on ix.[object_id] = ixstats.[object_id]     and ixstats.[index_id] = ix.[index_id] where ixstats.database_id = db_id() order by ixstats.[avg_fragmentation_in_percent] desc 	0.216167206248459
21524532	32385	select different values of a column having count more than one	select tbl.`acct_id` as 'acct_id',count(`acct_id`)  as 'counts', group_concat(`sa_type`) as 'types' from `sa_tbl` as tbl  group by tbl.`acct_id`  having counts > 1 	0
21524534	18974	query to find the records which are having with column3 null or with empty value in column4	select count(*)  from customers   where site_id = 0 or siteid is null 	0.0004182115192123
21525642	22696	select from two tables return nulls	select r . * , ra.blg, ra.ben, ra.uid  from rooms r  left join     room_access ra on     r.id = ra.rid  and      ra.uid =1 	0.00146801858015067
21526006	14827	how to select entries without matching dependants in same table	select p.* from person as p left join person as s on p.`primary` = s.per_id where s.per_id is null and p.cls =3 	0
21530567	36462	get rows between last inserted and 10 minutes before that date	select x.*    from tbltable x   join       ( select max(datum) max_datum from tbltable ) y      on x.datum >= y.max_datum - interval 10 minute; 	0
21530609	36969	show approve and pending documents	select distinct           dbo.documentinfo.docid as documentid,              dbo.documentinfo.docname as documentname,            dbo.documentinfo.uploadeddate as uploadeddate,            dbo.doctype.doctype as document,           dbo.department.deptype as department,            dbo.documentinfo.uploadfile as fileuploaded,          dbo.approvetype.approvetype as status   from  dbo.documentinfo   inner join dbo.doctype    on  dbo.documentinfo.doctypeid=dbo.doctype.doctypeid   inner join dbo.department on dbo.documentinfo.depid=dbo.department.depid  left join dbo.approvetype on dbo.documentinfo.approveid=dbo.approvetype.approveid   inner join  dbo.approval on dbo.documentinfo.docid = dbo.approval.docid       where userid=@userid and dbo.approval.desigid = 3 	0.0179647611934802
21532461	34769	limit by percentage of all rows in mysql	select* from    (     select list.*, @counter := @counter +1 as counter     from (select @counter:=0) as initvar, list     order by value desc    ) as x where counter <= (10/100 * @counter); order by value desc 	0.000328020457019453
21532465	15123	how do i determine the time at which the largest number of simultaneously events occurred?	select top 1 max(e1.startdate), count(e2.eventid) from event e1 inner join event e2    on e1.startdate between e2.startdate                        and dateadd(second,e2.duration,e2.startdate) group by e1.eventid order by count(e2.eventid) desc 	0
21532778	37932	how do you join three tables in oracle?	select      o.customer_num,      o.order_num,      s.stock_num,     s.description from      orders o,     items i,     stock s where     i.customer_num >= 104     and i.customer_num <= 198     and o.order_num = i.order_num     and i.stock_num = s.stock_num 	0.227589559053137
21533215	7066	sql - how to merge different rows into one without group_concat	select user_id,         max(case when `key` = 'name' then value end) as name,        max(case when `key` = 'url' then value end) as url,        max(case when `key` = 'email' then value end) as email from your_table group by user_id 	6.46198758909893e-05
21533330	29502	trying to average a substring that is data type varchar	select i.location, avg(convert(int,substring(b.text,8,4))) from item i join bib b on i.bib#=b.bib# where b.tag = '008' and isnumeric(substring(b.text,8,4))=1 group by i.location 	0.00305209654065921
21533554	10465	php for each on the while loop select from table	select distinct * from table_name where condition=value; 	0
21535062	9604	finding the percentage using case statement	select  round((sum(aol_int) /   (sum(aol_int + android_phone_int + androidtablet_int))) *   100,2) as aol_percentage, round((sum(android_phone_int) /   (sum(aol_int + android_phone_int + androidtablet_int))) *    100,2) as android_phone_percentage, round((sum(androidtablet_int) /   (sum(aol_int + android_phone_int + androidtablet_int))) *    100,2) as android_tablet_percentage from mytable 	0.235355028766761
21536218	33306	sql query comparing columns in separate tables and databases	select a.c2,   count(case when a.c2 = b.c1 then 1 else 0 end) as c1count from table1 as a  left join table2 as b on a.key = b.key group by a.c2 	0.00226819875434411
21537979	39107	sql returning three time the same column	select p.name as  professor, a.name as student, s_p.name as second_professor from  users as p join jobs on(p.id = jobs.id_professor) join users as s on(jobs.id_student = a.id) left outer join users as c on(c.id = jobs.id_professor2) where jobs.id = 2 ; 	0.00203242929558388
21541452	7438	comparing corresponding rows from the same column and same table	select customer_id, state, last_name, first_name from customers where (((state) in (select state from customers group by state having (((count(state))>1))))) order by state,last_name, first_name 	0
21544291	32142	compare dates in mysql	select * from tablename  where datediff(now(),date) <=3 	0.00935719252032882
21545321	7641	sql query to show minutes as hours	select   psprojectid,codepattern,ncr,sum(totaltime)/60.0 as totaltime    from ct2 group by psprojectid,codepattern,ncr 	0.000583956328316904
21545781	36197	sql sum, count for only unique id	select count(o.id) no_of_orders,         sum(o.total) total,         sum(o.shipping) shipping    from orders o join  (     select distinct order_id       from designer_orders      where state in('pending', 'dispatched', 'completed') ) d      on o.id = d.order_id 	0.000287488682288623
21545821	13431	need way to compare two tables by date, sum values in table 2 by date, & output values to a 3rd table w/ totals of table 1	select "key-" & cstr(slipdate) as keytemp,          sum(cash),sum(credit),         sum(sc),         sum(off by),         sum(total) into table_temp_1     from slipdate     group by slipdate      select "key-" & cstr(date) as keytemp,          sum(amount),         sum(tax 1),         sum(tax 2),         sum(tax 3),         sum(discount)  into table_temp_2           from salesreport     group by date 	0
21546444	6262	get only one row from products table for each category row with category name included	select category_id, product_name from products group by category_id 	0
21547512	25876	sql statement to eliminate duplicates based on value in another column	select a.* from table1 a inner join ( select id, sdate = min(splitdate) from table1 group by id ) b on a.id = b.id and a.splitdate = b.sdate 	0
21548415	37028	sql union all with unique grouping in each block	select dealerid, dealername from (     select 1 as myconst, dealerlevel, dealerid, dealername as title        from dealers     union all     select 2, dealerlevel, carid, carname        from cars inner join dealers on dealers.dealerid = cars.dealerid     union all     select 3, dealerlevel, truckid, truckname        from trucks inner join dealers on dealers.dealerid = trucks.dealerid     union all     select 4, dealerlevel, vanid, vanname        from vans inner join dealers on dealers.dealerid = vans.dealerid     union all     select 5, dealerlevel, suvid, suvname        from suvs inner join dealers on dealers.dealerid = suvs.dealerid ) t order by myconst, dealerlevel desc, newid() ; 	0.000152013731748129
21549947	14347	expiration bar usage from two dates	select datediff(date(now()),date(column_name)) as diff from table_name 	0.00342541999317107
21550167	37124	get between times only	select * from table  where from_unixtime (`datecolumn`, '%h:%i') between '12:01' and '12:50'; 	0.000261986450973279
21551196	38133	select multiple column values in single query - oracle	select eat.email_address as to ,ea.email_address as from, e.id, e.sent_date from email_address ea, chann_email e,email_address eat where e.id=ea.id and e.id=eat.id and ea.type in ('from') and eat.type in ('to') 	0.00597269955314479
21551685	3515	php mysql select * with this value with between these dates	select count(members.voucher_code)  from members  where     members.voucher_code = 'new' and    date_started between '2014-01-01' and '2014-12-31' 	0.0595584537486606
21551920	13658	change column value when matching condition	select case when (parent is null and flag01 = 'ok' and flag02 = 'ok')         then 'ct_00000'        else parent end as columnsomename,        child, flag01, lag02  from yourtable 	0.00396973142627274
21553567	323	how to multiply nvarchar values to decimal in sql server 2008 r2	select cast(convert(decimal(18,2), qty)+ convert(decimal(18,2), rate) as decimal(18,2)) from product where code='p0001' 	0.139121752502026
21553661	17802	retrieval of data in 2 periods possible with one (mysql) query possible?	select 1 as type, id, data_i, '' as content from table where date between ... and ... union select 2, id, 0, data_t from table where date between ... and ... 	0.00449045425972969
21553721	30330	mysql: combining multiple values after a join into one result column	select p.`id`, p.`title`, group_concat(a.`fullname` separator ', ') from `publications` p  left join `authors` a on a.`publication_id` = p.`id`  group by p.`id`, p.`title`; 	0.000165647362489203
21553888	11814	can i sum a certain cell value using a query in mysql?	select sum(values) from table_name where key='1' group by key 	0.000220988916367923
21556770	29521	multiple case merge sql	select *     from a  inner join   b on a.cusip=b.cusip  or           a.ticket = b.ticket; 	0.38185559415613
21557516	22850	how to adjust year in date if it's empty	select title, if(event_year = '',  if(event_day < day(curdate()) and event_month = month(curdate()) or event_month < month(curdate()), year(curdate())+1, year(curdate())), event_year) as ev_year, event_day, event_month  from `events` 	0.000605041297023901
21557758	34604	counting in a complex query	select       p.name,       a.name as activity,       count(*) as numcomments    from       place p          join comment c             on p.id = c.place_id             join activity_comment ac                on c.id = ac.comment_id                join activity a                   on ac.activity_id = a.id    group by       p.name,       a.name    order by       p.name,       count(*) desc,       a.name 	0.644320737882402
21561245	6958	select all items in a table and display them in order depending on their parent id's	select     i.title,     t.title,     d.title from     items i     left join types t         on i.type_id = t.id     left join departments d         on t.department_id = d.id order by     d.column asc,     d.order asc,     t.createdate asc,     i.createdate asc 	0
21561900	34569	select based on age at time of record creation	select [student name], [date of birth]   from <however your table is named>  where datediff(month, [date of birth], [notice date]) between 3 * 12 and 5 * 12 + 1 	0
21562425	16659	how to get weekly data from table?	select week(date(datecol - 1)), . . . . . . group by week(date(datecol - 1)) 	9.99177707675125e-05
21562994	25197	how to do select with 2 conditions into two columns	select usr.username, err.description as error, 1 as solved from users usr, errors err where err.solved_by_id=usr.id union  select usr.username, err.description as error, 0 as solved from users usr, errors err where err.submited_by_id=usr.id 	0.000182274999985547
21563404	36419	sqlserver ssis xml export possibility	select point ,datetimeformat ,dt as "s/dt" ,v as "s/v" ,q as "s/q" from mytable for xml path(''), type, elements, root('data') 	0.462461253883066
21563816	25371	how to select and sum() most recent item in a history table for each time period?	select item_month, count(*), sum(amount) from (    select opportunity_id,            item_date,           amount,           to_char(item_date, 'yyyy-mm') as item_month,           row_number() over (partition by opportunity_id, to_char(item_date, 'yyyy-mm') order by item_date desc) as rn    from opportunity_history ) t where rn = 1 group by item_month order by 1; 	0
21564137	34621	have trouble when table.field_name is needed in two columns based on different values	select sum(case when person.sex=1 then 1 else 0 end) as female,         sum(case when person.sex=0 then 1 else 0 end) as male,        cast(datediff(current_date,person.birthday)/(365.256366) as signed) as age from person group by age 	0.000387946393383381
21565209	726	most recent cost value as of date by item	select item_id        , tran_end_dt        , cost from (select distinct item_id, tran_end_dt from item cross join datestable) a outer apply (select top 1 item_cost as cost                  from itemcosthist ich                     where ich.eff_dt <= a.tran_end_dt                       and ich.item_id = a.item_id                        order by eff_dt desc) b order by item_id, tran_end_dt, cost 	0
21565466	34022	current date in oracle db	select "date", bus, value from {your_table} where "date" >= trunc(sysdate) and "date" < trunc(sysdate+1) 	0.00418493215456828
21568721	26341	query sql column twice to build html table	select schedule.date, ht.team_name as home_team,         at.team_name as away_team  from schedule     inner join teams ht on schedule.home_team_id = ht.team_id     inner join teams at on schedule.away_team_id = at.team_id; 	0.091583015059339
21569409	25577	is there a mysql function that will compare two fields in a table?	select item_name  from items where quantity < minimum_level; 	0.00318968270050619
21570387	14732	query to fetch salesperson records who has same cities alloted	select a.salesperson from dbo.table a where exists (select 1                from dbo.table b                where not a.salesperson = b.salesperson               and a.city = b.city) 	0
21572556	18990	get id from another table through a table	select     ptc.ptc_name,     aud.aud_year from     ptc_table ptc inner join     ada_table ada on     ada.ada_ptcid=ptc.ptc_id inner join     aud_table aud on     aud.aud_id=ada.ada_aud_id 	0
21572801	38079	sum of each table and sum of individual table	select @table1:=( select count(id) as tot_live from crm_rentals where status = 2 and is_active=1 and is_archive=0), @table2:=(select count(id) as tot_live from crm_sales where status = 2 and is_active=1 and is_archive=0 ),   (@table1 +@table2) as tot_live 	0
21573830	24897	finding cooccuring values in mysql weak relation table	select a.hid, group_concat(b.id) from header a inner join header b on a.did = b.did and b.hid != 1 where a.hid = 1 group by a.hid 	0.00719096970948787
21575194	20602	how to get separate fields data with if() statement in single query	select     sum( if(i.status = 'unpaid', i.total_amount, 0) ) unpaid,      sum( if(i.status = 'partial', i.paid_amount, 0) ) partial  from {ci}invoices i  where     i.customer_id = ? and     date(i.invoice_date) < '2014-01-01' and     i.status in ('unpaid', 'partial') 	0.00094278443444088
21575340	9542	calculating percentage of a value in an oracle database	select 100          * sum(case when totaltime > 100 then 1 else 0 end)          / nullif(count(*),0) from server_metrics; 	0.00194227241393623
21575700	5802	alternating default value for new field in mysql database	select (id+1)%3+1 as given_number, ... from ... 	0.00136077032068789
21576453	19389	sql multiple record : time scheduler	select t.time,  isnull( (select c.studentcode  from tbclassrsv c  where c.transdate='2014-02-05 00:00:00'  and c.class='room 01' and c.status<>'del'  and dateadd(minute, 30, convert(datetime, t.time))>= convert(datetime, c.time)  and convert(datetime, t.time) <= convert(datetime, c.until) ),'-') from [tbtime] t 	0.015863359234523
21576697	279	bind two select statements	select empid,    empname,    days,    sum (case           when particulars in ( 'water charge', 'housing allowance' ) then           amount           else 0         end) amount2,    sum (case           when particulars in ( 'basic pay', 'allowances' ) then            amount           else 0         end) amount1 from   tbl_details group  by empid,       empname,       days 	0.50830904758714
21577180	34361	average of max - sql	select avg(maxscore)  from     (select max(a.score) as maxscore      from posts a      join posts q on q.id = a.parentid      where q.posttypeid = 1 and q.acceptedanswerid is null      group by q.id) as sub; 	0.00413010913202542
21577599	2797	set column value to 0 if date is older than	select *, if(dateexpire >= now(), up, up= 0) as up from tbl_news order by up desc 	0.000150645347246393
21580114	33809	mysql join query results	select topicid, subject, body, posted_by, date_posted from topics where topicid = 2372 union select r.topicid, t.subject, r.body, r.posted_by, r.date_posted from replies r     inner join topics t on r.topicid = t.topicid where t.topicid = 2372 order by r.date_posted desc; 	0.675398537712464
21580820	22063	three table join mysql	select  e.epis_episode_id,          e.epis_title,         wli.wali_status,         wlo.wast_status from `episodes` as e left join `watch list` as wli     on e.epis_episode_id = wli.wali_episode_id     and wli.wali_user_id = 16 left join `watch log` as wlo     on e.epis_episode_id = wlo.wast_episode_id     and wlo.wast_user_id = 16 	0.171223288004767
21581839	23501	uncommon records between two result sets from two different queries	select * from     (     select distinct [entityid],[year],[name],[operationalstatus],[reftypeid]      from [db].[dbo].[entity] a     where [year]='2014' and [reftypeid] in ('abc','xys') and      not exists      (       select distinct [organizationid],[year],[operationalstatusid],[active],[modifiedby],            [modifieddate]        from [db2].[dbo].[organization] d where [fiscalyear]='2014' and       a.entityid = d.organizationid and       a.year=d.year       a.name = d. name     ) ) as t 	0
21582640	39036	postgresql json has key	select (customer_data->>'framemenudata'->>'frameelement' is null) as has_frame, 	0.0517345943171518
21583385	40814	how to get the recent records first?	select * from `likers` order by `id` desc 	0
21589600	18651	select by frequency	select name,  count(user_id) from users u join phones p on u.id = p.user_id group by name having count(user_id) > 3 	0.0433973999394849
21590331	30000	join 2 tables using a pivot	select username, firstname,lastname,address,  max(if(uc.`primary`=1 and uc.row_num=1, uc.number,0)) as phone,  max(if(uc.row_num=2, uc.number,0)) as alt1,  max(if(uc.row_num=3, uc.number,0)) as alt2,  max(if(uc.row_num=4, uc.number,0)) as alt3,  max(if(uc.row_num=5, uc.number,0)) as alt4 from user_info as ui left join  (  select username, number,`primary`,alternate,      if(@type = username,@rownum:=@rownum+1,@rownum:=1) as row_num,     @type := username as `type`  from user_contact , (select @rownum:=0 , @type:='') as r  group by username, number  order by username, `primary` desc ) as uc  on ui.username = uc.username order by username 	0.214587888783156
21593016	31577	summing values over multiple, non-related tables?	select u.user_id, sumvalue, sumscore from users u left outer join      (select user_id, sum(value) as sumvalue       from sales       group by user_id      ) s      on u.user_id = s.user_id left outer join      (select user_id, sum(score) as sumscore       from points       group by user_id      ) p      on u.user_id = p.user_id; 	0.00706080187519244
21595527	34612	check that a given date does lie between two existing dates inside a datatable	select * from tblemployeeleaves where date(getdate()) between leavestartdate and leaveenddate and  isapproved='approved' 	0
21595850	23719	how to substract time in sql server 2008 r2	select dateadd(minute,-15,starttime) from employees where employeeid = 18 	0.657587204858223
21596034	11462	how to add a string value to the results in a row	select to_char(current_date, 'month, dd, yyyy "current century -" cc"st"') as "today's date and century" from dual; 	5.09559005846727e-05
21597341	22440	how would you truncate or limit the results of a date result you are adding time to? (oracle sql)	select to_char(current_date, 'dd/mm/yyyy') as "today's date",   to_char(add_months(current_date, 3), 'yyyy-mm-dd')     as "today, three months hence",   to_char(add_months(current_date, 3), 'month') as "three months hence" from dual; | today's date | today, three months hence | three months hence | | |   06/02/2014 |                2014-05-06 |          may       | 	0.00240694265842849
21597429	19077	ms sql insert if not exist with a result	select top 1 * from (    select 'c' source, key, val from c   union all    select 'd', key, val from d ) x where key = 'something' order by source 	0.594481740667075
21599802	29294	select rows not between particular date?	select * from tbldate where '2014-02-25' not between startdate and enddate 	0.000870989849194802
21600080	28629	3 tables and 2 left joins	select sum(total_revenue_usd)   from table1 c  join (   select distinct ga.assign_id    from table2 ga    join table3 d    on d.campaign_id = ga.assign_id  ) x on c.irt1_search_campaign_id = x.assign_id 	0.292047702834623
21602426	1398	group by date by day and group of hours	select to_char(start_date, 'day') as dow,        (case when extract(hour from start_date) between 8 and 19              then 'work/on hours'              else 'work/off hours'         end) as period,        sum(actv) from sess_actv group by to_char(start_date, 'day'),          (case when extract(hour from start_date) between 8 and 19                then 'work/on hours'                else 'work/off hours'           end) 	0
21603343	7923	sql - joining 3 tables on same column	select blogs.user_id,        blogs.blog_id,        blogs.blog_content,         users.user_id,        users.name,         comments.comment_id,        comments.blog_id,        comments.user_id,        comments.comment_content ,        comment_writers.name as commentusername from blogs  left join users on users.user_id = blogs.user_id  left join comments on comments.blog_id = blogs.blog_id left join users as comment_writers on comment_writers.user_id = comments.user_id where blogs.blog_id = 2 	0.000852171019441813
21604057	17785	join only the last row of an associated table with postgresql	select     id,     p.ano_processo,     p.numero_processo,     h.descricao,     h.status,     h.data_modificacao from     vs_protocolo p     inner join     (         select distinct on (id_protocolo)             id_protocolo as id,             descricao,             status,             data_criacao as data_modificacao         from vs_protocolo_historico         order by id_protocolo, data_criacao desc     ) h using (id) 	0
21604260	18241	how do i "order by" more than on column?	select count(oi.id) imgcnt, o.*,      if(pricet=2,c.currency_value*o.attributes_36*o.price,     c.currency_value*o.price) as pprice, od.title, oi.image,      min(oi.id), ( c.currency_value * o.price ) as fprice,      ag.agent_name, date_format( o.date_added, '%d-%m-%y') as dadded ,     offer_status     from i_offers_12 o      left join i_agents ag on o.agents_id = ag.id      left join i_currencies c on o.currencies_id = c.id      left join i_offers_details od on ( o.id = od.offers_id and od.languages_id = 1 )      left join i_offers_images oi on ( oi.offers_id = o.id and oi.o_id = '12' )      where ( o.offer_status='active' or o.offer_status='sold')      and actions_id = '1'      and c.id = o.currencies_id      and o.counties_id = '2'      and o.cities_id = '3'      and o.offer_status='active'      group by o.id     order by offer_status, dadded     desc 	0.0289101333221738
21604407	14446	add a column into a select for calculation	select revenue,         cost,        case when revenue <> 0              then ((revenue - cost) / revenue) * 100        else 0 end as result from   costdata 	0.00390508397449117
21604639	29215	sql result query in another query	select name.name, name.number from name     join relationship as r on name .id = r.id_name      join street on street.id = r.id_street     where street.street = "yourstreet" and street.zip="1111"; 	0.146684746540535
21605445	38896	how to select max values from different tables	select max(combineddate) from (     select max(date) as combineddate from table1     union all     select max(created) as combineddate from table2 ) 	5.68795800287992e-05
21606774	2747	pulling text out of a string in sql	select substring(p, charindex(',',p,1)+1, case when charindex(',',p,charindex(',',p,1)+1) = 0 then len(p)-charindex(',',p,1) else charindex(',',p,charindex(',',p,1)+1) end) from products 	0.012889136348308
21607003	11926	merging two tables under some conditions	select       t1.d1,       t1.id2,       t1.dr1,       t1.dr2    from        table t1          join table t2             on t1.d1 = t2.d1             and t1.dr1 = t2.dr2             and t1.dr2 = t2.dr1    where          t1.dr1 > 0       or t2.dr2 > 0 	0.00175763322619629
21607401	6282	sql generate sequential id's based on other column(s)	select *, dense_rank() over(order by customer desc) from #orderranking 	0
21607481	17006	mssql db get records that don't have a specific status	select alarmid from alarmstates as inner join alarm a  on (as.alarmid = a.id) inner join listalarmstates la  on ( as.listalarmstatesid = la.id) group by as.alarmid having count(case when la.statename = 'clearednotified' then 1 else null end) = 0    and count(case when la.statename = 'cleared' then 1 else null end) > 0) 	0
21608321	16404	how to use "group by" and max value into inner join queiries?	select       index_data.host_name,              max(data_bin.value) as value         from metrics       inner join index_data on index_data.id = metrics.index_id       inner join data_bin   on data_bin.id_metric = metrics.metric_id  where metrics.metric_name = 'avg' and   from_unixtime(data_bin.ctime) between date('2014-02-05 16:15:24') and date('2014-02-06 16:15:24')  group by index_data.host_name; 	0.168771440911359
21609910	3512	gettin a value from a table and using in the same query	select (h.horario), h.codigo from horarios as h join horario_turma as h_t on(h.codigo != h_t.cd_horario) where h_t.cd_turma = 'htj009'  and h_t.cd_dia = 2 and h.cd_turno = (select cd_turno from turmas where codigo='htj009') 	0.000146062640715049
21609976	22958	compare value of a column with multiple values from other column	select    p.id, p.nparentid,p.stitle,   (select count(*) from pub.category c where c.nparentid = p.id) as nchildrencount,   if (select count(*) from  pub.category c where c.nparentid = p.id) , true, false) as bhaschildren from pub.category p 	0
21611033	28536	sql server - quarterly data report	select *     from mytable     where mydate >= dateadd(qq, datediff(qq, 0, getdate()) - 1, 0)         and mydate < dateadd(qq, datediff(qq, 0, getdate()), 0) 	0.592753038545265
21611811	28633	how to get the latest data with where and max in mysql	select crop,  area,  dateupdated,  price  from crops cr where trim(area) = 'cogon'  and dateupdated = (select max(dateupdated)                 from crops                 where crop = cr.crop and trim(area) = 'cogon' ) ; 	0.000123009737505197
21614792	5522	mysql multi-table select	select * from     ((select 1 precedence, `sp_content`      from `loc-ae_siteparts`       where `sp_name` = 'name_of_some_sitepart' and `sp_lang` = 'de' and `sp_corrected`='1'      limit 1)      union      (select 2 precedence, `sp_content`       from `loc-ae_siteparts`       where `sp_name` = 'name_of_some_sitepart' and `sp_lang` = 'en'       limit 1)      union      ...     ) x order by precedence limit 1 	0.674439664673128
21616644	20937	hive sql: avg for last three dates for each user_id	select b.user_id, avg(b.number) from (    select user_id, number, date,           row_number() over (partition by user_id order by date desc) r    from table_name ) b where r <= 3 group by b.user_id 	0
21619263	1665	mysql query select between dates php not working	select * from log where `date` > '2013-12-12 00:00:00' and `date` < '2014-02-08 00:00:00' limit 10 	0.527422353889647
21619480	33864	mysql: select records where joined table matches all values	select empid, name from (    select em.id as empid, em.name, es.id as skillid     from employee em     inner join emp_skills es on es.emp_id = em.id    where es.skill_id in ('1', '2')  ) x group by empid, name having count(distinct skillid) = 2; 	0
21619970	6353	where clause specific middle left value oracle	select s.st_sample_id, s.st_cn_no as cnnumber, s.st_smptyp as sampletype, s.st_wasgrp as wastecode, s.st_wascod as wastecategory, s.st_received_dt as receiveddate, s.st_wastyp_name as wastetype, s.st_status as samplestatus, s.st_dispose_ind as disposalstatus, s.st_container as samplecontainer, s.st_smppnt as samplepoint, s.st_nature as samplenature, c.scm_name as color,cm_client_name  from sample_txn s,sample_color_mstr c,client_mstr cm   where s.st_color=scm_auto_no (+) and st_client_id=cm_client_id  and st_year='13' and s.st_lab_id='r' and to_char(s.st_received_dt,'mon') = 'jan'; 	0.482896911061855
21620365	27875	select rows with same column	select mt.* from mytable mt join (   select c3, count(*)   from mytable   group by c3   having count(*) > 1 ) x on mt.c3 = x.c3; 	0.00104414873975049
21621293	36561	set the value of variable from combined values of rows in sql	select @xmlstring = coalesce(@xmlstring+',' , '') + cast( responses as varchar(max)) from tablename 	0
21622437	17573	summing record in table based on key in row	select id,x,sum(y)over(partition by x) as yy,z  from  table 	0
21622682	6326	how can convert to only first uppercase letter and other letters lower case in p/l sql?	select initcap( your_column )   from your_table 	0.00027279765160596
21624641	128	creating a view table that override null values	select c.[id],        coalesce(c.[date], p.[date]) [date],        c.parentid   from child c   join parent p     on p.[id] = c.parentid 	0.0493523851776091
21626932	32309	how to get table structure with column name in a single row?	select      c.table_name,      c.column_name,      c.data_type,      case when tc.constraint_name is not null then 1 else 0 end as isprimary from information_schema.columns c      left join (         information_schema.constraint_column_usage ccu          join information_schema.table_constraints tc          on tc.constraint_name = ccu.constraint_name                and tc.constraint_schema = ccu.constraint_schema                and tc.constraint_catalog = ccu.constraint_catalog           and tc.constraint_type = 'primary key'     )     on ccu.column_name = c.column_name        and ccu.table_name = c.table_name        and ccu.table_schema = c.table_schema        and ccu.table_catalog = c.table_catalog where c.table_name = 'employee' 	0
21630621	14220	padding numeric on sql sybase	select right(replicate('0', 16) + cast(cast(field*100 as int) as varchar(255)), 16) 	0.45183888520302
21631741	8107	mysql query a resultset	select . . . from (select *       from `listing`       where status = 200       order by created_at desc       limit 10      ) t where . . . 	0.220493866052619
21632453	17485	difference between current and previous timestamp	select x.timestamp      , x.data-coalesce(max(y.data),0) data    from my_table x    left    join my_table y      on y.timestamp < x.timestamp   group      by x.timestamp; 	0
21632681	1181	trying to multiply 2 column values together for each row & print the total sum of all the rows	select sum(s_count*cost) as value_sum from stock 	0
21633226	2865	wildcard that matches whitespaces only	select city from cities where city regexp 'london\s*gb' 	0.0695968853389261
21634039	5137	oracle date stored as a number	select to_char(to_date(table.timestamp,'yyyymmddhh24miss'), 'mm/dd/yyyy hh24:mi') from xxxx.table where rownum < 10; 	0.0245041460453605
21636347	1642	searching on multiple values in php	select   *  from    user_email  where    email  in    ('$d1','$d2','$d3')  limit    1 	0.022562730193912
21637094	28048	count all items in table mysql plus get record	select * , concat('', (select count(*) from memberfilereports)) as total  from memberfilereports limit 0,5 	0
21637530	22411	how to order data in mysql by join count?	select *, count(comments.id) as total_comments from posts left outer join comments on  posts.id = comments.post_id where posts.show = '1' group by posts.id order by total_comments desc 	0.125688519711949
21638367	31047	oracle: how to get a month without year restriction?	select *  from orders where extract(month from order_date) in (3,4,5); 	0
21640196	29220	mysql query within query	select count(distinct calldate ) as today_total_8 from cdr  where channel like '%from-queue%'      and disposition='no answer'      and date(`calldate`) = date(curdate()) group by calldate 	0.616479163715014
21640431	10231	select max id of each id	select c.commentid, max(cs.commentstatusid) maxcommentstatusid   from   tbcomment c        join tbcommentstatus cs on c.commentid = cs.commentid where  c.islocked = 1 and    cs.statustypeid = 4 group by c.commentid 	0
21640752	17209	mysql query with condition based on field value or left join value	select p.product_id   from product p   join product_category c     on c.product_id = p.product_id    and c.category_id = 1   left   join ( select g.product_id            from product_group g            join product h              on h.product_id = g.child_product_id             and h.price > 0.00           group by g.product_id        ) r     on r.product_id = p.product_id  where p.price > 0      or r.product_id is not null 	0.00568626081264059
21642666	29672	how to perform sql search on results of previous query	select * from palette  join users on (users.id = palette.id) where (users.subscription_plan!=null) 	0.0414661280457783
21642878	37744	get average value of from one table for a specific row in another table php	select hospital.*,(select avg(hrating.rating_h)                     from hrating                     where hid = hospital.hid) as overall_rating  from hospital  where hid=:hid limit 1 	0
21643333	7196	combining multiple columns in two tables	select t1.id, t21.name, t22.name, t23.name from t1      inner join t2 t21 on t21.id = t1.referenceperson1id     inner join t2 t22 on t22.id = t1.referenceperson2id     inner join t2 t23 on t23.id = t1.referenceperson3id where t1.id = 1 	0.000945985696018801
21644931	32633	mysql group by two columns	select distinct opponent as team from table union select distinct competition as team from table 	0.00925027591500729
21645785	27666	sql, add column with summed values of the same type	select t.id,t.type,t.quantity,x.sum from table t left join (select id,type,quantity,sum(quantity) as sum from table group by type)x on t.type=x.type 	0
21647213	18701	connecting and querying two mysql databases simultaneously with php	select *   from database1.table1   join database2.table2 on ... 	0.0285283702091767
21647757	23313	how to select column names for the values those are bold?	select    case       when bjp between aap and cong then bjp        when aap between bjp and cong then aap        else cong    end as againstvote,    case       when bjp between aap and cong then 'bjp'        when aap between bjp and cong then 'aap'        else 'cong'    end as againstpartyname from tab 	0
21647777	29205	converting time using strtotime php	select unix_timestamp(value) ... 	0.788322695674518
21651485	35097	how to get rows older than 30 min	select * from temp where `timestamp` < (now() - interval 30 minute); 	0
21653886	31401	combine 2 mysql count queries from same table	select `week`, sum(`opened`), sum(`closed`) from (     select week(t1.opened) as `week`, count(*) as `opened`, 0 as `closed`     from issues as t1     where t1.opened is not null and ##filter by opened##     group by week(t1.opened) union all     select week(t2.closed) as `week`, 0 as `opened`, count(*) as `closed`     from issues as t2     where t2.closed is not null and ##filter by closed##     group by week(t2.closed) ) as t3 group by `week` 	9.07505333032302e-05
21654027	10786	select only values from table a depends on table b	select t1.id_user, t1.username from user t1 left join block_user t2 on     (t2.user_request = <current user id> and t2.user_banned = t1.id_user)    or    (t2.user_request = t1.id_user and t2.user_banned = <current user id>) where t2.id_block is null; 	0
21654900	9767	mysql sum of product rows where data stamp within cost data range	select a.id as account_id,     count(p.id) as qty,     c2.amount as previous_cost_per_unit,     c1.amount as cost_per_unit,     c1.datestamp as cost_date,     p.datestamp as product_date from product p     inner join account a on a.id = p.account_id     inner join cost c1 on c1.account_id = p.account_id and c1.datestamp = p.datestamp     left join cost c2 on c2.datestamp = (select max(datestamp) from cost where account_id = c1.account_id and datestamp < c1.datestamp) group by account_id, product_date 	0
21656751	22681	how to select data which have same maximum value	select * from table where role = (select role from table where role = (select max(role) from table)) 	0
21660991	24885	mysql union query with table name	select col1,col2,...,coln,'table1' as tablename from table1 union select col1,col2,...,coln,'table2' as tablename from table2 	0.212966117170441
21663332	8943	php & mysql: query to "sum" 2 rows from php	select date, min(time) as time, custom_id, sum(number) as number from table group by date, custom_id, hour(time) 	0.00125146131185882
21664308	25997	join table when selecting a max value of columns	select t.* from (    select      *,      row_number() over (partition by commentid order by createdatetime desc) as rn    from      tbcommentbreadcrumb      where commentstatustypeid = 4             and    createdatetime <= {ts '2014-02-09 09:44:57'} ) t join tbcomment c on t.commentid = c.commentid where    t.rn = 1 and c.commentislocked = 1 order by commentstatusid desc 	9.69710663694099e-05
21665978	13756	i'm over-querying my mysql database. another way to retrieve many data?	select max(case when option_name = 'siteurl' then option_value end) as siteurl,        max(case when option_name = 'sitetitle' then option_value end) as sitetitle,        max(case when option_name = 'sitesubtitle' then option_value end) as sitesubtitle,        max(case when option_name = 'logofile' then option_value end) as logofile,        max(case when option_name = 'cat1' then option_value end) as cat1,        max(case when option_name = 'cat2' then option_value end) as cat2 from main_conf where option_name in ('siteurl', 'sitetitle', 'sitesubtitle', 'logofile', 'cat1', 'cat2'); 	0.0147910491474245
21667790	40148	sql querying of a table	select * from users; (enter) 	0.0232475330140135
21668516	4833	how can i get second max id in mysql?	select max(id) from a where id != (select max(id) from a) 	0.000123603807203556
21669395	6871	how to find duplicates from 2 linked tables?	select r.first_name , r.last_name, s.email_address  from table1 r inner join table2 s on r.id = s.contactid group by r.first_name , r.last_name, s.email_address having count(s.contactid)>1; 	0.000195712846577484
21670573	27870	select max(date) and next highest max(date) from table	select max(dates.businessdatadate) as businessdatadate,         min(dates.businessdatadate) as previousdatadate from (select top 2     'cb_account' as tablename     , businessdatadate from cb_account group by businessdatadate order by businessdatadate desc) dates 	0
21670597	20662	how to select database rows by days ,month,years	select * from tabename where day(mydate) = 20   month(mydate) = 12 year(mydate) = 2008 	0.000166648287040203
21671309	39598	mysql join query help : join two tables with distinct right table rows ordered in descending order	select a.*, b.* from complaint as a left join     (select c.*      from assign as c      where c.id in (         select max(d.id) as max_id         from assign as d         group by complaint_id)) as b         on a.id = b.complaint_id 	0.0607778484257872
21671947	21354	count duplicate values and display each different value from mysql table using php	select distinct(referer), count(referer) as frequency from url_log  group by referer order by frequency desc; 	0
21672140	16751	join 2 select statements on common column	select name, sum(number1),sum(number2) from (      select t.name, sum(t.value) as number1 , 0 as number2         from table1 t          where t.value = '1'          group by t.name     union     select v.name, 0 as number1 ,sum(v.value) as number2         from table2 v          where v.value = '2'          group by v.name ) group by name; 	0.00514767484062748
21672725	39683	command to clone a table (structure/data) in t-sql	select top 0 * into b from a 	0.734547459617299
21672830	1037	mysql query with values of the same table	select * from your_table where position = 2  and rec_id in (select rec_id from your_table where sbj_id = 9) 	0.000713745497416328
21674017	18782	how to fetch id from database if particular column has both value	select products_id,count(options_values_id)  from products_attributes where  options_values_id in(12,31) group by products_id having count(options_values_id)>=2 	0
21675018	11218	get all customer that bought 2 product	select customer      , count(distinct product) ttl    from t  where product in ('p1', 'p2')  group      by customer having count(*) = 2  	0
21676248	12270	conversion mysql to postgresql	select country as grouper, date(min(users.created_at)) as date,         to_char(min(users.created_at), '%y-%m') as date_group,         count(id) as total_count    from "users"  having (users.created_at >= '2011-12-01')     and (users.created_at <= '2014-02-11')   group by grouper, date_group   order by date asc 	0.563713114049849
21676406	35507	join two sql statements in same table	select t1.class, count(t2.class) as count from test t1 left join test t2 on t1.city=t2.city and t1.city in ('xx', 'yy') group by t1.class, t1.city; 	0.0194067719461451
21677135	17126	count the different strings of one column in mysql	select count(distinct column_name) from table_name; 	8.26587901734953e-05
21678048	26609	do transactions prevent other updates for a while, or just hide them?	select * from resources where resource_name=’a’ for update; 	0.0206144706569296
21678839	26837	many to many query mysql return duplicate rows	select l.id as link_id,r.*  from `resources` as r cross join res_res as l where (l.parent_id = 2 and l.parent_id=r.id) or (l.son_id = 2 and l.son_id=r.id) 	0.00202659741481021
21682561	6167	postgresql not equal to string	select substring(get_parameter from '[0-9]*$') from comments 	0.25500009102964
21682788	1594	mysql: select records with lowest sort	select * from table where = (select min(sort) from table) order by id asc group by product 	0.00211221888675987
21684457	21568	joining outer table field to subquery	select      t2.fldnum t2f,t3.fldnum t3f,     t2.fldnum + t3.fldnum/2 as fldnum from      tblnumbers as t2     inner join tblnumbers as t3     on t2.fldindex+1=t3.fldindex         and t2.fldlink1=t3.fldlink1         and t2.fldlink2=t3.fldlink2 	0.351391900370384
21684637	30580	is it possible to use timestamp without having to convert it to string in oracle?	select *  from tabela  where datefield = timestamp '2014-02-10 15:56:00.000'; 	0.57702982454981
21685190	13038	join another table with if statement	select * from `products` left join `packages`    on your_clause_here 	0.106796891070313
21685361	23487	select with a where condition from nested subquery	select  id,  case when name like '%peter%' then name else null end as peters,  case when name like '%mike%' then name else null end as mikes  from  (select id, name from customer) myset 	0.688267542727857
21686045	9335	eliminate null output row	select  * from    (         select  mydates         ,       (p1/(lag(p1) over (order by mydates))-1) as myret         from    top40table         where   mydates between @prevdate and '2012/05/10'                 and primid = 1         ) as subqueryalias where   myret is not null 	0.049157727561703
21688967	22243	mysql echo number of records that has the same session id	select session_id, count(*) from gallery_list group by session_id 	0
21689837	7894	for loop postgres over multiple tables	select ta.type, case when ta.str_agg = tb.str_agg then 'success' else 'failed' end from (select type, array_to_string(array_agg(category order by timestamp desc), ',') as str_agg from (select * from table_a as t where t.id in (select id from table_a where type = t.type order by timestamp desc  limit 5)) as t1 group by type) as ta left join (select type, array_to_string(array_agg(category order by timestamp desc), ',') as str_agg from (select * from table_b as t where t.id in (select id from table_b where type = t.type order by timestamp desc  limit 5)) as t1 group by type) as tb on (ta.type = tb.type) 	0.1438537341601
21690340	34610	query maximum varray value	select t1.id, max(t2.column_value)  from foo t1, table(t1.yvals) t2 group by t1.id 	0.00589832264250447
21690494	32676	how to find which fields in one table match criteria based on another	select * from sections se left join samples sa on sa.job = se.job and sa.id = se.id, and sa.sectionnumber = sel.sectionnumber where sa.id is not null 	0
21690885	19072	transpose 2 rows to one row	select t1.id, t1.name, t1.home_address, t2.office_address (select id,name,address as home_address  from (select id,name,address,row_number() over (partition by id order by id) rnum from table_name) a where a.rnum=1 ) t1  left join (select id,name,address as office_address from (select id,name,address,row_number() over (partition by id order by id) rnum from table_name) b  where b.rnum=2) t2 on t1.id=t2.id 	5.0674514918249e-05
21691149	3031	sql query extracting first few characters	select *  from abc where trim(phones) like '(520)%' 	0.00621412975119678
21692830	33090	list tables and table extended properties	select table_name as ttablename,      table_type as ttabletype,     q.eptablename,     q.epextendedproperty from information_schema.tables as t     left outer join (select object_name(ep.major_id) as [eptablename],         cast(ep.value as nvarchar(500)) as [epextendedproperty]         from sys.extended_properties ep         where ep.name = n'ms_description' and ep.minor_id = 0) as q     on t.table_name = q.eptablename  where table_type = n'base table' order by table_name 	0.0168460381562304
21693378	22388	hexadecimal to int conversion	select convert(int, 0x000000b5) 	0.704680585555942
21694260	7084	php: running mysql_query if data from $_post matches data in table	select * from horses where name = '$horsename' 	0.000233034185800159
21696706	40574	how to calculate hour of time range with sql query (mysql)	select id, sum(hour) from (     select id, least(12, end_time) - greatest(8, start_time) hour from `schedule` where start_time<=12     union     select id, least(16, end_time) - greatest(13, start_time) hour from `schedule` where end_time >=13 ) x group by id 	0.000104825480536463
21696763	34645	how to search a date by month in sql server c#	select *   from leaves where datepart(month, start_date)=2 or datepart(month, end_date)=2 	0.00660434731879147
21697142	26630	max values for different id_groups in one table	select id_group, max(somenumber) from table1 where id_group <> 0 group by id_group union all select 0 id_group, max(somenumber) from table1 	0.00018578733646726
21697483	26513	query records of 7/14/21/28... days ago in mysql	select * from users where datediff(registration_date, now()) % 7 = 0 	8.31197653551133e-05
21697500	32338	jdbc: oracle database change notification & duplicate events	select table_name  from user_change_notification_regs 	0.0347674206770248
21698204	16706	sql show multiple collums	select * from country where continent = 'asia' or continent = 'europe' order by continent desc; 	0.0553402541150685
21698602	14116	sql query with multiple column join	select t2.val valofc1,t3.val valofc2,t4.val valofc3 from table1 t1    inner join table2 t2 on t1.c1 = t2.ids    inner join table2 t3 on t1.c2 = t3.ids    inner join table2 t4 on t1.c3 = t4.ids    where tempid = 'ab' 	0.468731999397443
21699336	22699	how do i select distinct values between two dates	select distinct id, fname, sname from table 	0.000104402974438718
21701094	6269	calculate the difference between two "count(*)" from 2 tables in postgres	select (select "count"(*) as val1 from tab1) - (select "count"(*) as val2 from tab2) 	0
21701553	30163	how to validate the max value of the table?	select isnull(max([date]),getdate()) from [events] 	0.000997910726642238
21701925	21307	sql: flatten hierarchy with missing levels	select id      , [h1], [h2], [h3], [h4], [h5] from (    select distinct          coalesce(c6.id,c5.id,c4.id,c3.id,c2.id,c1.id) as id        , c1.id as lid        , c1.level      from ttt c1     left join ttt c2       on c1.id = c2.pid     left join ttt c3       on c2.id = c3.pid     left join ttt c4       on c3.id = c4.pid     left join ttt c5       on c4.id = c5.pid     left join ttt c6       on c5.id = c6.pid ) as sourcetable   pivot ( max(lid)      for level in ([h1], [h2], [h3], [h4], [h5])     ) as pivottable; 	0.633613768894898
21702168	21825	mysql - count element in month group by day	select adate, count(somedatetable.id) from (     select date_add("2013-02-10", interval (hundreds.i * 100 + tens.i * 10 + units.i) day) as adate     from     (select 0 as 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,     (select 0 as 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,     (select 0 as i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) hundreds     where date_add("2013-02-10", interval (hundreds.i * 100 + tens.i * 10 + units.i) day) <= "2013-03-10" ) sub1 inner join somedatetable on sub1.adate between date(somedatetable.start_date) and date(somedatetable.end_date) group by adate; 	5.98194694624274e-05
21702627	19165	xml vs relational database	select      eventid, eventtime,     announcementvalue = t1.eventxml.value('(/event/announcement/value)[1]', 'decimal(10,2)'),     announcementdate = t1.eventxml.value('(/event/announcement/date)[1]', 'date') from     dbo.t1 where     t1.eventxml.exist('/event/indicator/name[text() = "gdp"]') = 1 	0.731489556010058
21704466	22164	mysql query to ms sql	select date, time, custom_id, number from traffic t where concat(date, ' ', time) between '01/06/2014 00:00' and '01/10/2014 23:00' and number =  (select max(cast(number as smallint)) from traffic where t.date = date and t.custom_id = custom_id) order by date, cast(number as smallint) desc, custom_id 	0.724510012590312
21704783	17927	sql query put a word in a field instead of 0?	select case when f2 = '0' then '(no phone number)' else f2 end as phone ... 	0.00390851410270771
21705463	40227	match first element of a tilde separated values string	select regexp_substr('~a,c~d2f~@hi~~~j(l~e~~~~~~~~', '[^~]+')  from dual; 	0
21705689	28870	mysql group_concat as list of integers, not strings	select themes.theme  from  themes as themes  where  themes.themesid in  (     select      t.mycol      from      activities_themes t     where t.primarycol= 87 ) 	0.106855936542658
21706775	36880	inner join tables	select a.* from from table1 a inner join table1 b on a.policynumber =  replace(b.policynumber,'-' + right(b.policynumber,charindex('-',reverse(b.policynumber))-1), '-' + convert(varchar,convert(decimal,right(b.policynumber,charindex('-',reverse(b.policynumber))-1))) ) 	0.651795883820958
21706951	29604	aggregate function to concatenate strings joining two tables?	select distinct t1.rowid, stuff(            (select ', ' + cast(t2.field2show as varchar(10))             from @secondtable t2             inner join @firsttable t                 on t.linkedfield = t2.linkedfield             where t1.rowid = t.rowid              order by t2.field2show             for xml path(''), type).value('.','varchar(max)') ,1,2, '') as childvalues from @firsttable t1; 	0.0130874277442018
21707503	31994	view all the employees that earn more than a specific person	select * from emp where sal > (select sal from emp where ename = 'jones'); 	0
21708012	21214	table with multiple counts in one row	select id,   count(case when type = 'a' then 1 end) a,   count(case when type = 'b' then 1 end) b,   count(case when type = 'c' then 1 end) c from yourtable group by id; 	0.000624475654259755
21708896	32033	select records with only one value in a column where multiple are possible	select * from customer c join ( select customer_id        from customer        group by customer_id        having count(program_name) = 1      ) t on t.customer_id = c.customer_id where ...  	0
21709655	18994	remove duplicate rows in the following scenario	select min(t.id), t.desc, t.code, t.userid  from mytable t group by t.desc, t.code, t.userid 	0.00518776200020303
21713577	35948	sql missing record issues	select a.answerid as answer, ua.answerid as useranswer from quizanswers as a left join useranswers ua on ua.questionid = a.questiond where a.correctanswer = true and a.questionid = x 	0.423633903417694
21714906	5052	group by column, select most recent value	select studentid, [writingsection], [readingsection], [mathsection], max(datetaken) datetaken from (   select studentid, subject, datetaken, score   from (     select studentid, subject, datetaken, score       , row_number() over (partition by studentid, subject order by datetaken desc) as rownum     from students s     unpivot (       score for subject in ([writingsection],[readingsection],[mathsection])     ) u   ) x   where x.rownum = 1 ) y pivot (   max(score) for subject in ([writingsection],[readingsection],[mathsection]) ) p group by studentid, [writingsection], [readingsection], [mathsection] 	5.52111766000283e-05
21717661	41053	comma separated string into two column	select max(case when id % 2 = 1 then value end) as value1,        max(case when id % 2 = 0 then value end) as value2        from (select id, value, (id-1)/2 as grp       from dbo.fs_1_fn_split(@datap, ',')       ) t group by grp 	0
21717827	9913	how to get all dates in sequence for a group by query?	select     coalesce(sum(data), 0) as "sum",     to_char(date_trunc('week', c.signup_date), 'yyyy-mm-dd') as test_week,     c.record_type as user_type from     facts f     right join     (         (             select distinct record_type             from facts         ) f1         cross join         (             select distinct signup_date             from facts         ) f2     ) c on f.record_type = c.record_type and f.signup_date = c.signup_date group by 2, 3 order by 2, 3 ;  sum | test_week  | user_type     4 | 2013-09-02 | x    5 | 2013-09-02 | y    0 | 2013-09-09 | x   10 | 2013-09-09 | y    2 | 2013-09-16 | x    1 | 2013-09-16 | y 	0.000274720678900113
21717858	27575	phpmyadmin, get a list of user email addess that don't exists in another table	select mail from users where mail not in (select mail from commerce_order) 	0
21719747	21777	how to work with postgresql json where keys are arbitrary?	select * from t1 where exists (     select 1     from json_each(c1)     where value ->> 'status' = '1' ) 	0.468455836424938
21721917	14617	sql server: how to select ids from the table which has values only in 1 or 3	select id from <table> t1 where not exists    (select 1 from <table> t2 where t1.id=t2.id and t2.value not in (1,3)); 	0
21723592	4185	sql query to loop on a given data	select     id,     description from(     select          id+1-row_number() over (order by id) col,         *      from yourtable     where id>=83633 )x where col=83633 	0.0202329565903414
21723748	185	two tables having same composite key	select  t1.no ,       t1.date ,       t1.s_hour - t2.l_hour from    table1 t1 join    table2 t2 on      t1.no = t2.no         and t1.date = t2.date 	0.00238538840661735
21724511	2665	ordering, where column contains same value	select * from table  order by name, id  limit 0,3 	0.00161334775233308
21724754	5517	mysql query select from table and order by date and other field. prioritize other field	select * from (   select * from    agenda   where visible   and startdate >= "2014-02-12"   order by sticky desc, startdate asc   limit 3 ) subquery order by startdate asc 	0
21724992	40231	mysql query to get identifier and aggregate function value of a row	select u.id      , u.name      , (select sub.id from game1 as sub where sub.userid = u.id order by sub.score desc limit 1) as maxscoregameid      , max(game1.score) as maxscore      , (select sub2.id from game1 as sub2 where sub2.userid = u.id order by rank asc limit 1) as bestrankgameid      , min(game1.rank) as bestrank from [user] u join game1 on game1.userid = u.id group by u.id, u.name 	0.0714028105659247
21725977	30707	select and select count (aggregate & non aggregate in same query)	select [month] ,[cluster_name] ,[month_code] ,sum([headcount]) as headcount ,sum([planned_headcount]) as planned_headcount ,sum([joiners]) as joiners ,sum([leavers]) as leavers ,sum([chargeable_hours]) as chargeable_hours ,sum([recoverable_hours]) as recoverable_hours ,sum([total_hours]) as total_hours from cdm_fact_organization inner join cdm_dim_organization on cdm_fact_organization.organization_key = cdm_dim_organization.organization_key inner join cdm_dim_date on cdm_fact_organization.date_key = cdm_dim_date.date_key group by month, cluster_name, month_code where fiscal_year = '20132014' 	0.105717768753211
21726407	7064	mysql join where value or null	select   prod.*,   coalesce(p_user, p_default) as price from   prod inner join (select                      prod_id,                      max(case when user_id=5 then price end) p_user,                      max(case when user_id is null then price end) p_default                    from                      prices                    group                      by prod_id) m_uid   on prod.id = m_uid.prod_id 	0.485237692725833
21728073	3614	postgressql: search all tables of a database for a field called like *active*	select *  from information_schema.columns  where true and table_schema = 'public' and column_name ~* 'active' 	0.000912310886215179
21728797	10728	sql selecting specific field with defined values	select id, value, case when loopupid =1 then 'yes' else 'no' end as result from table1 	0.000956986925942891
21730808	30185	ajax chat system - use query to select twice from a table	select pm.id, pm.message, pm.reciever, pm.sender, pm.senttime, pm.rread, s.username, s.name, s.surname, s.fullname, s.profile, r.username, r.name, r.surname, r.fullname, r.profile  from pm, users s, users r where (r.id = pm.reciever) and (s.id = pm.sender) and ((r.id = 1 and s.id = 2) or (r.id = 2 and s.id = 1)) 	0.0353255338355388
21730815	25308	sql - unique results	select foo.idproject from delivery as foo left join delivery as bar   on foo.idproject = bar.idproject     and bar.idprovider <> 1 where foo.idprovider = 1   and bar.idproject is null; 	0.0623182381870503
21732069	9583	how do i import an excel spreadsheet into sql server 2008r2 database?	select * into xlimport4 from openrowset('microsoft.jet.oledb.4.0', 'excel 8.0;database=c:\test\xltest.xls', [customers$]) 	0.154001136143791
21732281	38469	sqlite: subtotals in own row aka "rollup"	select ticker_symbol,underlying,quantity from ( select '1' ordercol, ticker_symbol,underlying,quantity from stocks  union   select '2' ordercol, ticker_symbol, 'subtotal' as underlying, sum(quantity) as quantity from stocks  group by ticker_symbol  union  select '99' ordercol, '_' as ticker_symbol, 'grandtotal' as underlying, sum(quantity) as quantity from stocks)  as t1  order by case  when ordercol=99 then 1 else 0 end, ticker_symbol, ordercol; 	0.102936710990714
21733680	26914	query for rows that share a set of associations	select id from c where (   select count(*)   from b_c   where c_id = c.id ) <= (   select count(*)   from b_c inner join a_b on b_c.b_id = a_b.b_id    where c_id = c.id and a_id = ? ); 	0.00171972196016024
21734361	10694	sql query: join two tables	select group_members.group_id, group_members.permissions, `group`.group_name from group_members, `group`  where group_members.group_id=`group`.group_id and `group`.group_id = 1 	0.168821863414043
21734580	16161	subtract two columns in sql	select totalcredits - totaldebits as difference from  ( select (select sum(totalamount) from journal where memberid=48 and credit =1) as totalcredits, (select sum(totalamount) from journal where memberid=48 and debit =1) as totaldebits ) temp 	0.00154900209307736
21734802	40959	sql select by relevancy - many to many	select     p.name from product p      join product_type pt on p.id = pt.product_id where pt.typeid in (3, 5, 8) group by p.name order by count(pt.type_id) desc limit 1 	0.163358289167543
21735342	31336	sql - matching resulting columns	select t.column1, t.column2, case when t.column1 == t.column2 then null else column2 end  from (     select sum(case when super.guid is not null then 1 else 0 end) as column1,                 count(...) as column2     from... ) t 	0.00401032165113412
21737137	3121	select 5th entry from database c sharp	select min([flight_date]) as [flight_date_5] from (select top 5 [flight_date]        from flights        where [claimed_by_id] = ?         and [flight_date] <= ?        and [flight_date] >= ?        order by [flight_date] desc) as [top5] 	0.00259828142541667
21737308	184	sql query to join multiple tables with sum function	select history_contract_no,         history_run_date,         history_dataset_code,         contract_status,         confund_blg_method,        confund_blg_status,        sum(premium_trx_amt)   from   history left join premium on     history_field = premium_contract_no join confund  on     history_field = confund_contract_no join contract on     confund_contract_no = contract_contract_no where  history_dataset_code in ('continu1', 'continu2') and    history_run_date between 20140118 and 20140124 group by history_contract_no , history_run_date , history_dataset_code , contract_status , confund_blg_method ,confund_blg_status 	0.71873557678191
21737845	17827	subtracting two column with null	select isnull(totalcredits,0) - isnull(totaldebits,0) as difference  from   (  select  (select sum(totalamount) from journal where memberid=48 and credit =1) as totalcredits,  (select sum(totalamount) from journal where memberid=48 and debit =1) as totaldebits  ) temp 	0.00629317027233917
21738239	27554	how to loop through the value from the same table?	select e1.emp_num, e1.emp_lname as employee_last_name, e2.emp_lname as manager_last_name from emp e1 left join emp e2 on e1.emp_mgr = e2.emp_num 	0
21738899	6938	how to extract matched line of a multiline record in oracle?	select    customer_id,   regexp_substr(exp_comment,'.*'||chr(10)||'(.*export)', 1, 1, 'n', 1) as export from export_comments 	0.000387463429896861
21739745	25536	how do i do a simple "select x where it's value of y is the max in z"?	select *   from ps_dept_tbl  where deptid in        (select deptid           from ps_job          group by deptid         having count(*) = (select max(num_recs)                             from (select deptid, count(*) as num_recs                                     from ps_job                                    group by deptid))) 	0.000772129414802699
21739942	26413	selecting values from one two table	select   u1.*,   case when u2.username is null then 'not following'        else 'following' end is_following from   userinfo u1 left join followers f   on u1.username = f.source_id   left join userinfo u2   on f.destination_id = u2.username      and (u2.username like '%b%' or u2.email like '%b%') where   u1.username='a' 	0
21740183	2760	sql group by with multiple conditions	select yourtable.* from   yourtable inner join (     select   ip_address,              max(case when type='purchase' then id end) max_purchase,              max(case when type='visit' then id end) max_visit     from     yourtable     group by ip_address) m   on yourtable.id = coalesce(max_purchase, max_visit) 	0.40882350731051
21740586	28101	how to put fields from other tables	select   a.id, a.x, a.y, b.name, b.group_id, c.group_name from   a inner join b on a.id = b.id   inner join c on b.group_id=c.group_id 	0.000108939368862563
21742413	21180	mysql replacing column`s data related to actual data from another table	select t.id, i.name from tasks t, industries i where t.industry = i.id 	0
21744076	6956	sql server stored procedure select	select    chips.chip_id as chipid,    chip_number,    test_module.moduletypeid,    test_module.pid,        test_module.component1,    test_module.component2,    test_module.parameter1,    test_module.parameter2,    test_module.parameter3,    test_module.parameter4,    test_module.parameter5,    test_module.parameter6,    coalesce(spectrum.type, 'na') as type,    coalesce(tempcycle.power, 'false') as power,    coalesce(tempcycle.changerate, '0.0') as changerate  from    chips inner join test_module      on chips.chip_number = test_module.module_name    left outer join spectrum      on test_module.modulespec_testid =  spectrum.testid    left outer join tempcycle      on test_module.moduletemp_testid = tempcycle.testid  where    chip_id = @chip 	0.788202979002474
21745214	10042	sql subquery on same table	select p.id, p.age, p.sport, p.gender  from person p cross join      (select * from person where id  = 123      ) p1 where p.id <> p1.id and p.looking_for_gender = p1.looking_for_gender and       p.looking_for_sport = p1.looking_for_sport and p.min_age <= p1.min_age; 	0.0357110517859989
21747467	9047	postgres: select max returns 9 instead of 10	select max(distinct cast(trim(value, 'sample_values_') as integer)) from sample where id = 79 	0.00409421476785489
21747490	36808	how do i self-join the result of an aggregate function in mysql?	select `itemcode`, max( `height` ) from `mountheights` where `type`= 'max' group by `itemcode` 	0.404920072495393
21749042	27	search from two tables	select * from ( select artikel_id as id, artikel_overskrift as overskrift, artikel_keywords as keywords,     artikel_text as texten from artikler union all select begivenheder_id as id, begivenheder_title as overskrift, begivenheder_keyword as keywords, begivenheder_beskrivelse as texten from begivenheder  )tab1 order by id 	0.00520955162035091
21749378	17642	group by and order by in the same select	select modelli.mod_desc, count(modelli.mod_desc) from vega.distrib distrib, vega.modelli modelli where distrib.dis_flag = 'm' and distrib.dis_mod = modelli.mod_cod group by modelli.mod_desc order by modelli.mod_desc 	0.010150891901524
21749705	30868	sql query to convert column to rows	select * from table1     pivot     (     max(view1)     for view1 in([view],[edit])     )as piv; 	0.0133140047936363
21750538	7737	mysql select query that doesnt have to return a result set	select exists (select 1 from tablename where username = '$user' and password = '$pass') whatever_column_alias 	0.0145113443130009
21751368	1255	join with 3 tables	select name_singer from singers inner join songs on songs.id_singers = singers.id_singer inner join songs_join on songs_join.id_singer_join = singers.id_singer; 	0.236532910274541
21752003	7001	i have three tables with name emp, section,type now i need the combination of statements	select *       from emp e         join dept d            on d.deptid = e.deptid             and (case                    when e.fulltime = 0 and e.parttime = 0 and e.contracttime = 1 then 1                    when e.fulltime = 1 and e.parttime = 1 and e.contracttime = 0 then 2                    when e.fulltime = 1 and e.parttime = 1 and e.contracttime = 1 then 3                    when e.fulltime = 1 and e.parttime = 0 and e.contracttime = 1 then 4                    when e.fulltime = 0 and e.parttime = 1 and e.contracttime = 1 then 5                    when e.fulltime = 1 and e.parttime = 0 and e.contracttime = 0 then 6                    when e.fulltime = 0 and e.parttime = 1 and e.contracttime = 0 then 7                    else 0                  end) = d.sectionid; 	0.00331343688962587
21752618	32198	consecutive day query	select contactid from contacttable a inner join contacttable b on a.contctid=b.contactid and datediff(day,a.date,b.date)=1 	0.00269317512305622
21754010	10815	pivot a joined query in mysql query	select timestamp, first_name, last_name, email,   max( case title when 'helpful' then title end ) as 'metric 1 title',   max( case title when 'helpful' then answer end ) as 'metric 1 score',   max( case title when 'polite' then title end ) as 'metric 2 title',   max( case title when 'polite' then answer end ) as 'metric 2 score',   max( case title when 'clever' then title end ) as 'metric 3 title',   max( case title when 'clever' then answer end ) as 'metric 3 score',   category from( select    t0.timestamp, t3.first_name, t3.last_name,   t3.email, t1.title, t2.category,   t0.answer, t0.response_session from responses as t0   left join secondary_metrics as t1     on t0.metric_id = t1.id   left join default_categories as t2     on t0.category = t2.id   left join users as t3     on t0.user = t3.user_id ) tmp_tbl 	0.537969516632277
21754993	10398	select distinct rows from a table with an inner join	select distinct cit.computername from computerinvtracking cit inner join      (select computername, datediff(day, time, getdate()) as time, replace(replace(room, ',ou=rooms,ou=computers,ou=student,dc=campus,dc=ads,dc=uwe,dc=ac,dc=uk',''), 'ou=cl_','') as room       from  computerinvtracking cit2      ) cit2      on cit.computername = cit2.computername order by cit2.time 	0.00770755338892689
21755358	7387	how to generate a query which consider data from one table and correspondingly fill 0 for non matching fields in mysql	select  t1.r1,          t1.n,          t2.r2,          case when t1.r1 = t2.r2 then t2.m else 0 end as m from    t1         cross join t2 order by t1.r1, t2.r2; 	0
21756166	23867	choose join table from column value	select     case when type = 'int'           then int_val.int_val          else float_val.float_val     end from     data     left join int_val on data.value_ref=val_id     left join float_val on data.value_ref=val_id 	0.000618105267197158
21760584	24247	mysql query : i want to 2 queries result merged w.r.t primary key	select ledger.refno, (sum(ledger.rate*ledger.quantity-recieved) - customer.deposit) as total from ledger inner join customer on customer.refno = ledger.refno 	0.00563108941482238
21763047	16715	how do i query to find if values in one table have any corresponding entries in other tables	select val,        exists (select 1                from tablecars                where manid = tm.id) as makescars,        exists (select 1                from tabletrucks                where manid = tm.id) as makestrucks,        exists (select 1                from tablevans                where manid = tm.id) as makesvans from tablemanufactures as tm order by val 	0
21764096	32810	how to select more than one variable from sql in join statement?	select a.*, b.column1, b.column2, b.column3... 	0.0242120635913698
21764213	2773	how to group by a column and return sum of other columns?	select       anchor,        sum(value)   from        infodata   where        infoid in (1,2,3)  group by       anchor  order by        anchor asc 	0
21765093	40211	mysql group_concat only if consecutive dates	select   concat_ws(' - ',     min(checkin_date),     case when max(checkin_date)>min(checkin_date) then max(checkin_date) end   ) as time_interval from (   select     case when checkin_date=@last_ci+interval 1 day then @n else @n:=@n+1 end as g,     @last_ci := checkin_date as checkin_date   from     tablename, (select @n:=0) r   order by     checkin_date ) s group by   g 	0.00316047311816446
21765965	17675	php mysql unknown column in 'on clause'	select * from test_text tt join users u on tt.uid = u.id where u.username in ('$friends') 	0.622161834782402
21766736	9783	mysql - pivot columns into rows	select 'stuff' as thing, sum(stuff) `count` from foo having `count` > 0 union select 'widget', sum(widget) s from foo having s > 0 union select 'toast', sum(toast) t from foo having t > 0 	0.00293688873938158
21767364	24749	how to combine two different query-results by one column	select anchor, max(valueq1) as valueq1, max(valueq2) as valueq2 from (     select         anchor_date as anchor,         sum( getval(24, entry_id) ) as valueq1,         null as valueq2      from users      where blog_id = 173      group by date(anchor)      union      select         anchor as anchor,         null as valueq1,         sum(value) as valueq2      from infodata      where infoid in(330, 1492, 1066)      and entity = 173) as u group by anchor 	5.56515354904768e-05
21768321	29871	t-sql split string based on delimiter	select substring(mycolumn, 1, case charindex('/', mycolumn) when 0 then len(mycolumn) else charindex('/', mycolumn)-1 end) as firstname,        substring(mycolumn, case charindex('/', mycolumn) when 0 then len(mycolumn)+1 else charindex('/', mycolumn)+1 end, 1000) as lastname from   mytable 	0.00070512332479433
21770257	3611	querying sql server 2005	select cast(a.time_col as varchar) + ' - ' + cast(b.time_col as varchar),      cast(a.miles as varchar) + ' - ' +  cast(b.miles as varchar) from (select row_number() over (order by time_col) id, * from table_a) a  inner join (select row_number() over (order by time_col) id, * from table_a) b     on a.id = b.id - 1 	0.649522816475123
21774667	28285	select and calculate a column	select    *, concat(size  * stock_released - req_qty ,' m')  as reject from calculate_genmat 	0.00568173502491576
21776019	11851	average of average with a condition	select avg(avg_results)  from (     select srf.beh_id, avg(srf.result) as avg_results     from `survey_result_full` srf, `raters` r      where srf.`comp_id`= '$corow[id]'      and srf.rater_type = 'riwter'      and srf.survey_id = '$survey'      and srf.rater_id = r.id      and r.participate ='$id'      and r.`type` = '$rt[id]'     group by srf.beh_id) as avgs 	0.000396303739928282
21776385	18120	sql select top counts for grouped rows	select frequency,label,code from (   select     count(*) as frequency     ,max(count(*)) over (partition by label) as rnk     ,label     ,code   from mytable   group by label, code ) x where frequency=rnk order by frequency desc 	0.000522217765750371
21776550	14735	add columns dynamically in the result of a query. oracle	select         subscription_id,        months,        case when months >= 0 then months end month_0,        case when months >= 1 then months end month_1,        case when months >= 2 then months end month_2,        case when months >= 3 then months end month_3,        case when months >= 4 then months end month_4,        case when months >= 5 then months end month_5,        case when months >= 6 then months end month_6,        case when months >= 7 then months end month_7,        case when months >= 8 then months end month_8,        case when months >= 9 then months end month_9,                                                               case when months >= 10 then months end month_10,        case when months >= 11 then months end month_11,        case when months >= 12 then months end month_12  from subscriptions; 	0.00233416705087635
21778207	21938	sql query condition with sum	select class_record.classid,sum(a.vioamount),group_concat(a.vioamount) from class_record inner join (select class_record.classid, class_record.cr_no, if(count(violation.violationid)=1, sum(famount),(famount+samount)) as vioamount from violation  inner join class_violation on violation.violationid = class_violation.violationid inner join class_record on class_violation.cr_no = class_record.cr_no where classid = 'a30-000' group by violation.violationid, class_record.classid) a on a.classid = class_record.classid and a.cr_no = class_record.cr_no group by class_record.classid 	0.554375280679939
21779751	13587	concantenate two and queries in mysql	select distinct crop, price, area, region from crops  tb1 where dateupdated = (select max(dateupdated) from crops tb2 where tb1.crop = tb2.crop and tb1.area = tb2.area and tb1.region = tb2.region) and trim(crop) = '{$product}' and trim(region) = '{$region}'; 	0.153801815235463
21781583	37638	select 5 rows if they are not in top 3	select * from article where foreign_id_menu = '".$id."' and active = '1' and date_created < (select date_created from article order by date_created desc limit 3,1) order by date_created desc limit 0, 5" 	8.76854300992809e-05
21781767	37054	select only one number from array mysql php	select * from subcat where find_in_set(2,catid) order by id desc 	0
21782862	29915	select latest rows	select t1.description,   t1.date,   t1.profile,   t1.user,   replace(t1.locations, ',', '|') locations from test t1 inner join (   select max(date) date, profile, user   from test   group by profile, user ) t2   on t1.user = t2.user   and t1.date = t2.date   and t1.profile = t2.profile where t1.user = 'timmy' order by t1.profile 	0.000742787892004004
21783005	2102	mysql retrieving data starting from joined table	select t11.*,t12.*,t2.* from t2  left join t1 as t11 on t1.id = t2.id1 left join t1 as t12 on t12.id = t2.id2 	0
21788025	681	what's the best way to turn mysql results into simple array?	select post_id,        max(case when meta_key = 'adlink'   then meta_value end) adlink,        max(case when meta_key = 'sublock'  then meta_value end) sublock,        max(case when meta_key = 'size'     then meta_value end) size,        max(case when meta_key = 'location' then meta_value end) location,        max(case when meta_key = 'image1'   then meta_value end) image1,        max(case when meta_key = 'image2'   then meta_value end) image2   from wp_postmeta  group by post_id 	0.136510337990076
21790794	39301	sql to find last sibling in a linked list	select id from foo f1 where id not in (select previous from foo f2) 	0.000180435051967118
21793551	20452	how to split dash-separated values in sql server?	select right(left(ticketid, charindex('-', ticketid, charindex('-', ticketid, 0) + 1) - 1), len(left(ticketid, charindex('-', ticketid, charindex('-', ticketid, 0) + 1) - 1)) - charindex('-', left(ticketid, charindex('-', ticketid, charindex('-', ticketid, 0) + 1) - 1), 0)) from table 	0.0222320137776777
21795567	19541	mysql - how to get data for two foreign key columns of same table	select u1.username as "sender", u2.username as "recipient", m.message, m.from, m.to   from `users_messages` m left join `users` u1 on (u1.id = m.from) left join `users` u2 on (u2.id = m.to) where m.from = xx or m.to = xx 	0
21796247	41314	mysql join tables and display data from a contact list	select u.firstname, u.lastname,u.email,u.avatar from users u inner join friendships f on f.user2 = u.id  where f.user1 = 1 union select u.firstname, u.lastname,u.email,u.avatar from users u inner join friendships f on f.user1 = u.id  where f.user2 = 1 	6.46373336210683e-05
21796279	25518	how can i connect two different views in mysql query	select mvl.leadsid, mvl.leadsid,mvl.fullname,mvl.address,mvl.hours_spent,  mvl.sourcename,mvl.mobilephone,mvl.problem,mvl.leadassignedto,vv.uid,  vv.firstname  from  vbsleads.mview_leads mvl  join vbsleads.view_validaccounts vv on (mvl.companyid=vv.companyid) 	0.0336967529746701
21799485	13412	counting rows with different where and group by to 1 result	select t2.name, sum(case when t3.quality=1 then 1 else 0 end)as bad,        count(*)as total  from t2 left join t3 on t2.id=t3.categoryid where t2.stockid=2 group by t2.name; 	0.000961834119427841
21806352	39568	microsoft access: adding items in a grouped query?	select firstname, lastname, description, sum(checkamt) as 'sum of payment types' from mytable group by firstname, lastname, description 	0.110472835643011
21806534	32990	access: how to find the total of entries in a query	select firstname, lastname, sum([sum of payment types]) as [total pay] from yourtable group by firstname, lastname ; 	0
21808877	21352	mysql show rows that exist in one table but not it another	select organisation.* from organisation left join srp_reseller_buffer on     (organisation.organisation_id = srp_reseller_buffer.organisation.id and property_id = 'x') where srp_reseller_buffer.organisation_id is null 	0
21811162	20968	sql server 2008r2 union all group by	select sum("line sterling") as [line sterling], [business unit] from ((select t0.[totalsumsy] as [line sterling], t0.[whscode] as [business unit], t1.docdate        from [dbo].[inv1] t0 inner join             [dbo].[oinv] t1              on t1.[docentry] = t0.[docentry]       ) union all       (select t0.[totalsumsy] * -1, t0.[whscode], t1.docdate        from [dbo].[rin1] t0 inner join             [dbo].[orin] t1              on t1.[docentry] = t0.[docentry]       )      ) t where [docdate] > convert(datetime, '20121001', 112) group by [business unit]; 	0.208972854295832
21811621	13098	get videos related to video id x	select d.vid, d.vname, group_concat(e.gname) as sharedgenre, count(*) as sharedgenrecount from videos a inner join genre_connections b on a.vid = b.gcvideoid inner join genre_connections c on b.gcgenreid = c.gcgenreid and b.gcvideoid != c.gcvideoid inner join videos d on c.gcvideoid = d.vid inner join genres e on c.gcgenreid = e.gid where a.vname = 'iron man' group by d.vid, d.vname order by sharedgenrecount desc limit 6 	0.000141111768082436
21813425	38329	how to convert date to mysql date format	select * from table1 where searchdate >= '2014-02-01 00:00:00' and searchdate <= '2014-02-10 00:00:00' 	0.0047118506514211
21814866	30730	query for counting how many times a value in one column exists in another column of the same table	select a1.a, count(*)   from anonymous as a1   join anonymous as a2 on a1.a = a2.b  group by a1.a; 	0
21816589	4514	how to order by desc if i have a table with max that has more than one max values?	select * from students order by grade, student_name; 	0
21816941	9249	mysql - count total records sub query?	select * from       (select count(distinct customer_id) from customers as totaluniquecustomers ) tmp,       customers c    left join       belongings using (customer_id)    where       belonging_id between 1 and 5; 	0.00458965502818087
21817725	29888	php mysql classifieds list stuck	select m.id, m.subject   from bx_ads_main m join bx_ads_category_subs s      on m.idclassifiedssubs = s.id join bx_ads_category c     on s.idclassified = c.id  where c.id = 1 	0.777649730879508
21821643	26217	how to substring a nvarchar value from a word to another word in sql server	select left(right(@text, len(@text) - charindex('tag="', @text) - 4), charindex('"', right(@text, len(@text) - charindex('tag="', @text) - 4 - 1))) 	0.000165670300757295
21821653	11666	get records according to first table in join	select userid,         case           when idadmin is null then 'no'           else 'yes'         end as 'grp'  from   (select accessmenu.userid    as userid,                 actionrights.idadmin as idadmin          from   accessmenu                 left join actionrights                        on actionrights.idadmin = accessmenu.userid)z 	0
21823425	5316	how to search for existence of record in one table from another using php and mysql	select * from tablea where `idno` not in (select `sidno` from tableb) 	0
21823811	25001	depending on the value of a column in a table get data from two different tables	select us.user_name,         us.user_owner_id,        coalesce(co.company_name, org.organization_name) as name  from users us left join companies co    on us.user_owner_id = co.company_id   and us.owner_type = 30 left join organizations org     on us.user_owner_id = org.organization_id   and us.owner_type = 20 	0
21824869	12124	searching record within latitude and longitude range	select * from yourtable where lat between a and c and lng between b and  d 	0.00433756227353815
21826555	4312	sql group by doesn't show all variables	select isnull(column,0) from... 	0.0406999417085086
21828589	31246	searching within column with mysql like miltiple times	select *  from `users`  where user = 'king' or alias = 'king' or find_in_set ('king', aliases)>0; 	0.193225820917874
21830333	18920	order by time stored as varchar	select * from table_time  order by to_date(s_time, 'hh12:mi am') asc 	0.178892559372459
21831344	29489	join a row from another table to row in another table php mysql	select diamondslist.*,  dealer.name from diamondslist join dealer on diamondslist.dealerid = dealer.dealerid where ..... 	0
21832373	27775	how can i select duplicate records and keep the data using mysql statements?	select tab1.categories_id, tab1.categories_name from categories as tab1 right join (    select "aaa" as categories_name    union all    select "bbb"     union all    select "bbb"    union all    select "ccc"    union all    select "ccc"    union all    select "ddd"    union all    select "ddd"    union all    select "ddd" ) as tab2  on tab1.categories_name = tab2.categories_name order by tab1.categories_name; 	0.00149649530669712
21832577	40834	how to get the count of occurrence from comma separated string	select  t1.col1 ,       t1.col3 ,       count(t2.col1) from    t1 left join         t2 on      t1.col3 = t2.col3         and ',' || t2.col2 || ',' like '%,' || t1.col1 || ',%' group by         t1.col1 ,       t1.col3 	0
21832609	25631	sql - finding rows with duplicate values in one column	select [nameplate], [model] from dbo.[weighted extract] group by [nameplate], [model] having count(distinct [segment]) > 1; 	0
21833706	4056	how to summarize a database ? sql server	select  ss.name as [schema_name]        ,so.name as table_name        ,c.name  as [column_name]        ,st.name as  [data_type] from sys.all_objects so          inner join sys.columns c on so.object_id = c.object_id inner join sys.schemas ss on so.[schema_id] = ss.[schema_id] inner join sys.systypes st on c.user_type_id = st.xusertype where so.type = 'u' 	0.21680340643325
21833896	14353	selecting table rows from one table where value of table column in another table is x	select *   from faculty  where faculid not in (select faculty.faculid                          from faculty                          join facultycourse                             on faculty.faculid = facultycourse.faculid                          join registration                            on registration.fcid = facultycourse.fcid                         where registration.stuid = 'xyz'); 	0
21834573	8449	select 2 rows distinct and other columns on same query	select id a, fecha b, region c, value d    from test_stack t  where (t.id, t.region) in         (select  distinct d.id a                        , d.region b             from test_stack d); 	0
21834663	30658	count unique number of days between 2 dates where each day will have multiple rows in mysql	select count(*) from (   select distinct  m.date   from mytable as m   where m.temperature < 0   and year(m.date) = 2014 ) as mm 	0
21835015	20183	get total from a certain timestamp	select from_unixtime(added, '%y-%m-%d') as date,   count(*) as added_on_this_date,   (select count(*) from mytable t2 where from_unixtime(t2.added, '%y-%m-%d') <= from_unixtime(t.added, '%y-%m-%d')) as total_since_beginning  from mytable t  group by date 	0
21836730	28146	optimizing mysql operation to get counts	select  g.id good_id,         count(*) cnt_of_goods from    possessions p inner join         goods g on  p.good_id = g.id where   citizen_id=$citizen_id  group by    g.id 	0.354534005783339
21837282	20726	find id that are not part of a list	select ids.id  from (select 2 as id       union       select 3       union       select 4) as ids left outer join products   on ids.id = products.id  where products.id is null 	0
21837407	8873	checking the number of rows returned from mysql data reader	select count(*) as totalnorows, * from reports, software, platforms, versions etc 	0
21838459	24127	jive 5.0 current profile image	select  ja.attachmentid, c.displayname, ja.creationdate, ja.filename , (select propvalue from jivecontentprop jcpi where jcpi.contentid = ct.contentid and propname = 'index' ) from jiveuser u       left join jiveusercontainer c on u.userid = c.userid       left join jivecontent ct on ct.containerid = c.usercontainerid       left join jiveattachment ja on ja.objectid = ct.contentid     where ct.contenttype = 501  and     ja.objecttype = 501 and     u.userid in (4794)  and     filename = 'profile_image_500.png' order by propvalue limit 1 	0.00291559104496758
21839259	10393	complex mysql query from 4 tables	select c.content_id, s.source_name, c.content_title, c.content_date,        max(case setting_name when 'bbc_iplayer_string' then setting_data end) as bbc_iplayer_string,        max(case setting_name when 'reuters_video_id' then setting_data end) as reuters_video_id,        max(case setting_name when 'reuters_category' then setting_data end) as reuters_category from content as c inner join sources as s on s.source_id = c.source_id inner join content_join_settings as cjs on cjs.content_id = c.content_id inner join settings as st on st.setting_id = cjs.setting_id group by c.content_id 	0.253579459704235
21840476	21026	how to refine last but one?	select t.*,    row_number()     over (partition by event_id          order by event_date desc) from tab as t qualify    row_number()     over (partition by event_id          order by event_date desc) = 2 	0.000215540646803306
21841551	20459	how do i get the table to display only data with a specific substring in it	select product_name, name   from a_product p   join a_item i     on p.product_id = i.product_id   join a_sales_order so     on i.order_id = so.order_id   join a_customer c     on so.customer_id = c.customer_id  where regexp_like(product_name, 'transducer') 	0
21841848	24387	mysql limit records depending on size output	select descr from (select descr, @size := @size + length(descr) as size       from table t cross join            (select @size := 0) const      ) t where size <= 100000; 	0.00122182617084308
21844989	28691	how to order the query result by count() of field in postgresql without group by	select t1.*  from   table1 t1         inner join (select count(name) counter,                            name                     from   table1                     group  by name)t2                 on t1.name = t2.name  order  by counter; 	0.00581135953420034
21845043	32900	sql server: how to show value in next table	select a.*, (select ',' + skill from [table2] b where id = a.jobid order by skill for xml path('')) as skills from [table1] a 	0.000243007541821576
21845471	40861	how to find all stored procedure that are using a specific function	select distinct so.name from syscomments sc inner join sysobjects so on sc.id=so.id where sc.text like '%fn_test%' 	0.00156590777480429
21846477	23237	pagination issue while sorting based on last modified property	select * from jobs where name not in('a','b','c','d','e','f','g','h','i','j')  order by last_modified desc limit 10 	0.00192793308111715
21847136	14015	finding a matching value on two columns	select distinct t.b from your_table t inner join your_table s on t.b = s.c and t.id <> s.id 	0
21848537	12164	how to select and average rows in a table in postgresql	select avg(cast(a as float)) avga, avg(cast(b as float)) avgb, avg(cast(c as float)) avgc from (select row_number() over(order by null) - 1 rn, * from tab) t group by (rn/3) order by rn/3 	0.000154556123965819
21851067	15304	joining based on condition per row	select t1.testnr, t1.date, t2.finalid from table1 t1 left join table2 t2 on t1.testnr=t2.testnr and t1.date between t2.from_date and t2.to_date 	0
21851094	14081	getting no result in sqlite query	select * from    contact  left join phone  on cnt_cnt_id = phn_cnt_id                                          left join  email on phn_cnt_id = eml_cnt_id                                              where cnt_cnt_id = 1111 	0.155963997264538
21852684	30675	percentage increase/decrease in sum between 2 dates where first sum is zero	select location,  sum(if(action_dt_tm between '2013-01-01' and '2013-06-30',1,0)) as previous,  sum(if(action_dt_tm between '2013-07-01' and '2013-12-31',1,0)) as current,  sum(if(action_dt_tm between '2013-07-01' and '2013-12-31',1,0))-  sum(if(action_dt_tm between '2013-01-01' and '2013-06-30',1,0)) as diff, (  case    when (sum(if(action_dt_tm between '2013-01-01' and '2013-06-30',1,0))) then     0   else     sum(if(action_dt_tm between '2013-07-01' and '2013-12-31',1,0))-      sum(if(action_dt_tm between '2013-01-01' and '2013-06-30',1,0)))/      sum(if(action_dt_tm between '2013-01-01' and '2013-06-30',1,0))*100 end  as percent  from table group by location order by percent desc 	0
21853546	17921	sql server: how to limit stored procedure to only show one (next) matching record	select      a.meetingid,             convert(varchar(11), a.meetingdate, 106) as meetingdate,             a.createdby,             b.speaker as speaker,             b.topic as topic             from meetingdates a inner join  meetingdetails b on          a.meetingid = b.meetingid             where a.meetingdate in ( select      top 1(a.meetingdate) from        meetingdates a where       meetingdate >= getdate() order by    meetingdate asc) order by    speaker, topic for xml path('meeting'), elements, type, root('ranks') 	0
21853775	30858	sql statement to generate a column whose value is the record index	select    c1,    row_number() over (order by dummy)-1 as record_index from    (select      c1,     42 as dummy    from t1 ) as t1_augmented; 	0.000261396508093771
21855171	7129	count rows in mysql with php with specific value	select zone,        sum(pressure = 'yes') as `yes`,        sum(pressure = 'no') as `no`   from tb1  group by zone 	0.00161126932598492
21856895	19945	find out the list of recently run stored procs with start and end times	select databasename = db_name(st.dbid)     , schemaname = object_schema_name(st.objectid, dbid)     , storedprocedure = object_name(st.objectid, dbid)     , cp.last_execution_time from sys.dm_exec_query_stats cp cross apply sys.dm_exec_sql_text(cp.plan_handle) st where db_name(st.dbid) is not null     and cp.last_execution_time >= '2014-02-19 10:14:45.590' 	0
21857880	12795	combine two tables and add up results	select t1.user, sum(t1.amount), t1.date from (     (select user, amount, date from table1) union all     (select user, amount, date from table2) ) t1 group by t1.user 	0.00222264472550538
21860032	22415	concat two sql's results in one column	select     customer_id from customer union all select     customer_name from customer 	0.0148966071854606
21860615	16527	get top 10 items based on certain register using sql	select user,level from tbluser where level <= (     select level     from tbluser     where user = 'pancho villa' ) and user != 'pancho villa' order by level desc limit 9 	0
21861095	10179	sql: finding maximum of averages with related field	select provider_state, avg(average_total_payments) as average from gnomics where drg_definition like '%$search%' group by provider_state order by average desc limit 1; 	0
21861767	9560	query using counts with multiple conditions	select created_at::date, student_id       ,count(*) as exams       ,sum(case when course = 'history' then essays else 0 end) as essays_hist       ,sum(case when course = 'english' then essays else 0 end) as essays_engl from   public.exams x left   join (    select exam_id as id, count(*) as essays    from   public.exams_essays    group  by exam_id    ) s using (id) group  by created_at::date, student_id; 	0.366259456577044
21862011	12679	using left outer join return one matched row and additional only matching id's	select *,group_concat(website,',') as website from `company` c  left outer join owner o using ( companyid )  left outer join sales s using ( companyid ) group by companyid 	0.000143459381001282
21864195	21789	mysql - how to join multiple tables	select artists.* from artists join genre_artist on genre_artist.artist_id = artists.artist_id              join genre        on genre.id = genre_artist.genre_id and genre.name = 'rock'; 	0.116040318330486
21865012	1986	matching two columns based on the value of some column in a different table in mysql	select f.origin   from flight f   join airport a1     on f.origin = a1.code   join airport a2     on f.destination = a2.code  where a1.country = a2.country 	0
21867072	10860	select variable and count of sql table in same query	select column_a, count(*) from friend_request where prelim_user_id = ? and friend_user_id = ? group by column_a 	0.00425266119461553
21868011	37824	updating a cte table fail cause of derived or constant field	select x.id, isnull(a.matching_id, 0) as match, x.field2, count(*)    from tablex x          left outer join anothertable a on x.id = a.id    group by x.id, isnull(a.matching_id, 0), x.fields2 	0.691430419114141
21870140	34128	intersection in mysql for multiple values	select pid, count(*)   from (select t.oid, l.pid           from lineitem l           join (select o.oid, c1.cid                  from orders o                  join (select c.cid from customer c where c.city = 'x') c1                 where o.cid = c1.cid) t             on l.oid = t.oid) x  group by pid having count(*) = (select count(*)                      from (select distinct oid                              from lineitem l                              join (select o.oid, c1.cid                                     from orders o                                     join (select c.cid                                            from customer c                                           where c.city = 'x') c1                                    where o.cid = c1.cid) t                                on l.oid = t.oid) y) z 	0.0423593336266391
21870372	15577	mysql: find a column name dependant on a value in the column, search for colunm name as value in another table	select * from usertable ut where exists (select 1               from rostertable rt               where rt.usera = 'y' and ut.username = 'usera' or                     rt.userb = 'y' and ut.username = 'userb' or                     rt.userc = 'y' and ut.username = 'userc' or                     rt.userd = 'y' and ut.username = 'userd'              ); 	0
21872946	2614	convert date string to date in mysql query	select str_to_date('fri feb 21 2014 00:00:00 gmt+0800 (malay peninsula standard time)','%a %m %e %y %h:%i:%s'); + | str_to_date('fri feb 21 2014 00:00:00 gmt+0800 (malay peninsula standard time)','%a %m %e %y %h:%i:%s') | + | 2014-02-21 00:00:00                                                                                     | + 1 row in set, 1 warning (0.00 sec) 	0.0159335479163896
21873152	35086	how to retrieve values from database within a date range	select items.parentid,items.name ,stockheader.type, stockheader.date, uom.name,quanty, stockdetails.rate from  items,stockheader,uom,stockdetails where items.id = stockdetails.itemid and stockdetails.detailid = stockheader.id and  stockdetails.uomid = uom.id and stockheader.`date` between 'yourstartdate' and 'yourenddate' 	0
21873686	28201	filtering data in sql for each month from a date field	select  p.pid ,p.productname ,month=datepart(mm, o.date) ,quantitysold = sum(l.number) ,numbercustomer = count(distinct cid) ,revenue = sum(l.totalprice) from orders o  join customer c on c.cid = o.cid join lineitem l on l.oid = o.oid join product p on p.pid = l.pid group by  p.pid ,p.productname ,month=datepart(mm, o.date) 	0
21877284	8506	combining nested child comments with mysql	select parent.id, max(parent.comment) as pcomm,        group_concat(child.id order by child.id) as siblings,        group_concat(child.comment order by child.id) as siblingcomments from   submissions_comments as parent  left  join submissions_comments as child    on  child.parent_id = parent.id where  parent.parent_id is null group  by parent.id order  by parent.id; 	0.0736685306474434
21878331	6003	custom sql query to get most viewed posts with images	select  p.*,  pm1.meta_value + 0 as viewcount , pm2.meta_value as image from wp_posts p inner join  wp_postmeta   pm2  on (pm2.post_id = p.id and pm2.meta_key = '_wp_attachment_metadata') left join wp_postmeta pm1  on pm1.post_id = p.id where  pm1.meta_key = 'pvc_views'  and p.post_status in ('publish')  and p.post_type='post'  and p.post_password =''  order by viewcount  desc limit 0, 10 	0.0012095685671702
21878689	14516	query the data day by day	select userid ,count(id) as clicks,`date`from `table` group by `date`,userid 	7.47039865135686e-05
21881360	3995	multiple conditions in the same sql query	select col0, sum(case when col1 = 'a' then 1 else 0 end) as a, sum(case when col2 = 'b' then 1 else 0 end) as b from t where col0 = 'yes' group by col0 	0.0304554777094122
21881380	29755	how to specify fields returned on table join	select c.name , c.custom_message , d.log_id , c.price , c.quantity ,         group_concat(case when d.form_id=2 then d.value end) as first_name ,         group_concat(case when d.form_id=3 then d.value end) as last_name   from wp_wpsc_cart_contents c   join wp_wpsc_submited_form_data d on d.log_id = c.purchaseid   where c.name like '%%'  group by d.log_id  order by c.name 	0.0155686164895863
21881425	15561	how to insert data in 2 table & check if data already excist in db in php	select count(*) nb_result from tbl_item where itemname = 'your_item' 	8.26558140096321e-05
21881798	61	get count of all users for particular category and rank them	select user,        category,        count(*) as num from tbla where category=1 group by user,          category order by num desc; 	0
21882683	34118	rank users based on count num	select   groups.*,   @rank:=@rank+1 as rank from   (select      user,     category,     count(*) as num   from      tbla   where      category=1    group by      user,      category   order by      num desc,     user) as groups   cross join (select @rank:=0) as init 	0.00121400920554997
21884027	6126	filtering data after group by() or vice versa?	select shopinfo.shopname, ifnull( sum(income.earnings), 0 ) as novearn from income join shopinfo on income.shop=shopname.shopcode where (month(income.date)=11 and year(income.date)=2014) or date is null group by income.shop order by novearn desc 	0.117431375479191
21886570	30814	sql count a record in multiple criterias	select 'hy1''12', min([c1].[date]), max([c1].[date]), count(*) from [table_1] as [c1] where [c1].[date]>='2012-02-19' and [c1].[date]<='2012-07-29' union all select 'hy2''12', min([c1].[date]), max([c1].[date]), count(*) from [table_1] as [c1] where [c1].[date]>='2012-08-05' and [c1].[date]<='2013-01-27' union all select 'hy1''13', min([c1].[date]), max([c1].[date]), count(*) from [table_1] as [c1] where [c1].[date]>='2013-01-06' and [c1].[date]<='2013-06-30' 	0.00899477256335737
21887447	23247	how to find the sum of a temporary column in sql?	select id, name, sum(100) as sumoftempcolumn from mytable where id = 1 group by id, name; 	0.000336327196083061
21889112	27153	single sql statement to select row, but only if there is exactly one matching row	select @widgetid = widgetid     from widgets     where widgetname = 'foo' if @@rowcount = 1 begin end else begin end 	0
21889371	7272	derived table in sql server	select firsttable.*, secondtable.largestorder from (   select emailaddress, orders.orderid, sum(itemprice * quantity) as ordertotal   from customers     join orders on customers.customerid = orders.customerid   join orderitems on orders.orderid = orderitems.orderid   group by emailaddress, orders.orderid) as firsttable join (   select emailaddress, max(itemprice) as largestorder    from customers     join orders on customers.customerid = orders.customerid   join orderitems on orders.orderid = orderitems.orderid   group by emailaddress) as othertable on firsttable.emailaddress = othertable.emailaddress 	0.286970724643685
21890379	39726	labeling rows in mysql	select 'start', date(start_date) from `project`  where name = "project_a" union select 'end', date(end_date) from `project`  where name = "project_a" 	0.0440400847491165
21891840	2493	round of total from average query	select round(sum(t2.inttotal), x) 	0
21892221	36220	mysql: calculating localized min max with subselect	select   ta.my_id, ta.my_id, ta.recent_date, ta.my_value,   max(tb.my_value),   min(tb.my_value) from (   select     t1.my_id,     t1.recent_date,     t1.my_value,     substring_index(group_concat(t2.my_id order by t2.recent_date desc), ',', 5) as last_5   from     basetable t1 inner join basetable t2     on t1.recent_date >= t2.recent_date   group by     t1.my_id ) ta inner join basetable tb on find_in_set(tb.my_id, last_5) group by   ta.my_id order by   recent_date desc 	0.634241373634028
21892498	13116	how do i generate line item numbers in an oracle sql query	select invoice.inv_num, item.name, item.qty ,        row_number() over (partition by inv_num order by qty desc) item_num  from invoice invoice, item   where invoice.inv_num = item.inv_num  order by invoice.inv_num 	0.00370881544335518
21892724	6427	mysql how to get user's activities from users that have had interaction with you?	select sql_calc_found_rows, * from ( select          user.name,         'picture' as type,         user_visit.date_visit as date,         user_picture.date_picture as data1,         user_picture.description as data2     from         user         join user_visit on (user_visit.id_user_to = user.id_user)         join user_picture on (user_picture.id_user_to = user.id_user)     where user_visit.id_user_from = 1 union            select          user.name,           'question' as type,         user_question.date_question as date,         user_question.question as data1,         user_question.answer as data2,     from             user         join user_question on user_question.id_user_to = user.id_user     where user_question.id_user_from = 1 ) order by date; 	0
21894229	3608	mysql merge table b into table a based on values in row of table b	select      id, offline_count from     (select          customers.id,             sum(if(computers.currently_online like '0', 0, 1)) 'offline_count'     from         computers     left join computers_on_customers on computer_id = computers.id     left join customers on computers_on_customers.customer_id = customers.id     group by customers.id) c where     c.offline_count > 0 	0
21894481	2622	any way to retrieve sql field description property with a datarows query?	select schema_name(tbl.schema_id) as [table_schema],        tbl.name as [table_name],        clmns.name as [column_name],        p.name as [name],        cast(p.value as sql_variant) as [value]   from sys.tables as tbl        inner join sys.all_columns as clmns on clmns.object_id=tbl.object_id        inner join sys.extended_properties as p on p.major_id=clmns.object_id                                               and p.minor_id=clmns.column_id                                               and p.class= 1                                               and p.name = 'ms_description'  where tbl.name = 'your table name'                                        order by [table_schema] asc,          [table_name] asc,          [column_id] asc,          [name] asc 	0.00622526309677863
21895034	1476	mysql result for current date and if records don't exist return last 3 records	select * from tickets where updated = curdate() union  (select distinct * from tickets where not exists (    select * from tickets where updated = curdate())  order by    updated desc  limit 3) 	0
21895079	33834	values corresponds to not at all in mysql	select * from airline a where not exists(   select 1   from travel t   join location l   on t.from = l.port   where t.code = a.code     and l.country = 'france'  ) 	0.00389948484984607
21895741	16684	mysql comparing timestamp to current date	select * from visitors where date_format(created_at,'%y%c%d')=date_format(now(),'%y%c%d') 	0.000163472974457758
21896739	29534	how to generate a list where a column is twice as large as the other column in sql	select distinct    a.name,    b.name,    a.grade,    b.grade  from    highschooler a,    highschooler b,    friend f  where    a.id = f.id1 and    b.id = f.id2 and    b.grade - a.grade >= 2 order by    b.name,    b. grade,    a.name,    a.grade asc; 	0.000124315812322055
21897080	38168	display a list of students where both students like each other in sql	select a.name || ' likes ' || b.name from   highschooler a join   likes          on a.id = likes.id1 join   highschooler b on b.id = likes.id2 	0
21897633	21578	msql select sum limit ignore	select (case when count(*) = ".$limit."              then sum(numbers)               else 0         end) from (select numbers       from table       where name ='".$name."'        order by id asc limit 0,".$limit."      ) subt; 	0.192133306099661
21899168	17466	select two name in one column	select * from task where type in("user","admin"); 	0.000540622064525302
21899882	13400	query that fetches all table names & column names in a schema	select * from all_tab_columns where owner = 'scott' 	0
21900351	27468	postgresql. select sum value from arrays	select    name,   sum(value) from   (select unnest(id) as food_id, name from food) food_cte   join (select distinct id, unnest(food_id) as food_id, value from price) price_cte using (food_id) group by   name 	0.00153558969783496
21900648	15829	how to search date in sql server 2012 over two columns	select * from event      where '2014-02-23 00:00:00.000' between startdatetime and enddatetime 	0.0233326617572947
21900869	26240	group results by days in a date range	select * from test where  timepacket between '2014-02-16 00:00:00' and '2014-02-19 00:00:00'  and shift = 1  group by timepacket; 	7.90625481851523e-05
21900874	7934	how to retrieve multiple values from single column using and operator	select * from wp_usermeta t1 where meta_value = 'tagowner' and exists (select 1 from wp_usermeta t2              where t2.meta_value = '999'              and t1.user_id = t2.user_id ) 	0.000154426244777884
21901285	30736	how can i sort rows based on two columns in mysql?	select * from table where date = '2014-02-20' order by username,posts asc 	0
21903350	34076	double select from a same table	select  * from    categories where   parent_id = 0  union all select  c.*  from    categories c inner join         categories p    on  c.parent_id = p.id where   p.parent_id = 0 	0.00192735019797066
21906342	19468	select time in and time out from fingerprint transaction table according shiftperiod table	select  periodid from shifts  where employeecode  = @employeecode  and datefrom <= @indat and dateto  >= @indat order by abs((cast(datepart(hour,timein) as int))-(cast(datepart(hour,@indat) as int))) 	0
21907101	1750	mysql if variable then show results + specific result	select *  from clients where future = 0 or (future = 1      and (now() >= start_date           or start_date is null           or start_date = '0000-00-00 00:00:00')) 	0.00280725891906266
21908416	5961	how to use select query for counting number of attributes in a table?	select service_id,count(*) from your_table group by service_id 	0.000497903778011302
21908565	22976	conditional sum of one column based on another and then all grouped by a third	select  a,     sum(case when c <= 5 then b else 0 end) as band_1,     sum(case when c > 5 and c <= 10 then b else 0 end) as band_2 from mytable group by a 	0
21909427	63	return results of sql query on one row	select t.id, o.name, c.name   from tickets t   join users o on o.id = t.owner   join users c on c.id = t.creator  where t.id = 64; 	0.000674626433567444
21911464	40117	previous years data	select [date], sales(2014) , (select  sales from dbo.table as t_minus_one_year where year([date]) =  year(@startdate) - 1) as sales(2013), (select  sales from dbo.table as t_minus_two_years where year([date]) =  year(@startdate) - 2) as sales(2012), (select  sales from dbo.table as t_minus_three_years where year([date]) =  year(@startdate) - 3) as sales(2011) from dbo.table as t2014 where date between @startdate and @enddate 	0.00162425874668904
21911553	36125	sql server: get data from record with max date / newest date	select * from   (select col1, col2, col3, col4,                 rank() over (partition by col1, col2, col3                              order by updated desc) as rk         from   meetingdetails         where  itemstatus = 'active') t where  rk = 1 	0
21913035	37749	sum only distinct values given certain criteria sql	select m.company_id, m.company_name, sum(m.price) from  (   select distinct company_id, company_name, price   from mytable  ) as m group by m.company_id, m.company_name 	0
21913942	6102	select top sales products	select p.*, sum(po.quantity) qty from products p left outer join product_order po on po.product_id = p.id left outer join orders        o  on o.id          = po.order_id where o.status != 'rejected' group by po.product_id order by qty desc, p.created_at 	0.00161593217522339
21915046	29108	in mysql, how to query multiple table counts on column when joining on common columns	select p.project, p.owner, submission_count, hitup_count from (select   project, owner, count(*) as submission_count       from     projects       group by project, owner) p left out join (select project, owner, count(*) as hitup_count                from hitups                group by project, owner) h  on p.project = h.project and p.owner = h.owner 	0
21915687	35681	2 different fields when using union	select   (     select count(ma_id) as wrong_answers     from exercicio     natural join avaliacao     natural join user_sessao     where se_id=4 and us_id=1 and not exists (        select ma_id        from grelha        natural join exercicio        natural join avaliacao        natural join user_sessao        where us_id=1 and se_id=4     )   ) as wrong_answers,   (     select count(ma_id) as right_answers     from exercicio     natural join avaliacao     natural join user_sessao     natural join grelha     where se_id=4 and us_id=1   ) as right_answers; 	0.0201063188950952
21915849	20370	my sql query to retrieve 4 columns based on unique records from two columns	select com_msg.* from com_msg inner join (select max(msg_id) max_id                          from com_msg                          where 'sw1' in (msg_from, msg_to)                          group by                            case when msg_from!='sw1' then msg_from                                 else msg_to end) m      on com_msg.msg_id = m.max_id 	0
21916644	25526	multiply two values together from a single database column	select m.name, m.processors from (   select name, processors, substr(processors, 1, instr(processors, 'x', 1, 1)-1) as firstvalue,   substr(processors, instr(processors, 'x', 1, 1) + 1, instr(processors, ' ', 1, 1) - instr(processors, 'x', 1, 1)) as secondvalue   from mytable ) m  where m.firstvalue * m.secondvalue > 16 	0
21917124	33985	concatenate results of a sql query	select listagg(columnname, ',') within group (order by columname) 	0.0150894558151495
21917569	22822	logging count of deleted records	select * into #templog    from         (delete from dbo.history         output deleted.id         where keydate < dateadd(y, -7, getdate())) h insert into dbo.misclog(logtype, ontable, message, createby)    select        'info', 'dbo.history',        'there are ' + convert(varchar(20), count(id)) + ' old records being purged.', @by from #templog 	0.00183103205310534
21917834	31423	select statement where fields each contain multiple values	select v.* from   vendors v where   not exists (     select *     from vendor_styles vs1 inner join vendor_styles vs2          on vs1.style_id = vs2.style_id             and vs1.vendor_id = 1      where       vs2.vendor_id = v.id) 	0.00035119038480954
21918780	25593	mysql: selecting records that attended two different courses out of 3	select t1.email, course.course_title from (select email       from attendance       join course         on attendance.course_id = course.id           and course.course_level = 1       group by email       having count(distinct attendance.course_id) = 2) as t1 cross join course left join attendance   on attendance.course_id = course.id     and attendance.email = t1.email where course.course_level =1   and attendance.id is null; 	0
21919371	1464	ms-access query to exclude matching rows under specific conditions	select part from tableb  where part not in (select part from tableb                        inner join tablea on tableb.product=tablea.product                    where tablea.productline='widget') 	0.000868836478333773
21919543	25806	select distinct and join?	select y.text from y inner join    (select x.id from x    group by x.id) x on x.id = y.id 	0.21561152150234
21919620	20614	select between two dates in european format	select * from data   where  convert(datetime, data, 105)  >= convert(datetime, '01-01-2014', 105)       and  convert(datetime, data, 105) <= convert(datetime, '01-31-2014', 105) 	0.000876873280985338
21919947	39842	how can i use the results from 1 column as a part of another column	select     round( i.events / (i.totalmiles / 1000), 1) as events_perlk from (    select        sum(miles)  as totalmiles,       sum(events) as events    from     ... ) i; 	0
21920291	31241	find all other tables that use a current table (oracle database)	select 'table has key referencing this table' as match_type, table_name   from all_constraints  where constraint_type = 'r'    and r_constraint_name in        (select constraint_name           from all_constraints          where constraint_type in ('p', 'u')            and table_name = 'table_xyz'            and owner = 'schema_xyz') union all select distinct 'table is used by this trigger', trigger_name   from all_triggers  where table_name = 'table_xyz'    and owner = 'schema_xyz' 	0
21921400	28121	show max value with a join	select p.playername, s1.totalscore , s1.car, s1.track from player p inner join  score s1 on p.id = s1.player_id where s1.totalscore = ( select max(totalscore) from score s2 where s2.player_id=s1.player_id) order by s1.totalscore desc limit 10 	0.0110844197292434
21922446	16811	multiple many-to-many relations sql query	select ed.name, e.title   from event e   join event_to_category etc     on etc.event_id = e.id   join event_category ec     on etc.event_category_id = ec.id   join event_to_date etd     on e.id = etd.event_id   join event_date ed     on etd.event_date_id = ed.id  where etc.category_id = 53  order by ed.name 	0.578400994642498
21922886	309	getting only the four digits in mysql where condition	select value from table where length(value)=4; 	0.00247583113624658
21923459	22429	how to query to get the max value of a field in relating to another field? group by doesn't work? (mysql)	select t1.* from table t1 join (select entryid, max(version) maxversion       from table       where entryid in (212, 451)       group by entryid) t2 on t1.entryid = t2.entryid and t1.version = t2.maxversion 	8.3721205056087e-05
21924384	12926	do a while in a query, subquery	select u.cod, u.nombre, u.apellido, u.telefono from user u left join (select f.seguido from follow_follower f where f.seguidor = 1)t1 on u.cod = t1.seguido where t1.seguido is null and u.cod <> 1 group by u.cod 	0.656797841695018
21924735	12794	sql- adding a condition	select charter.cus_code,        charter.destination "airport",        charter.char_date,        charter.char_distance,        charter.ac_number   from charter  where destination = 'bna'; 	0.300018389018445
21924862	29859	oracle, how to match leading zero number in varchar?	select str, regexp_replace(str,'([^[:digit:]]*)(0*)(.*)','\1\3') new_str  from  (select 'a00105xyz' str from dual union  select 'cc000036qwe' str from dual union  select 'fd403t' str from dual union  select '000000010' str from dual) ╔═════════════╦═════════╗ ║     str     ║ new_str ║ ╠═════════════╬═════════╣ ║ 000000010   ║ 10      ║ ║ a00105xyz   ║ a105xyz ║ ║ cc000036qwe ║ cc36qwe ║ ║ fd403t      ║ fd403t  ║ ╚═════════════╩═════════╝ 	0.00518845923862935
21927551	37364	mysql - getting latest contents from 3 different table	select * from (select * from books             union             select * from audio             union             select * from parfume )   order by date desc limit 10 	0
21928194	16000	pass is null instead of = null	select * from users  where isnull(clientid, -1) = isnull(@clientid, -1) 	0.32942065823085
21929233	5712	sql - many to many relations	select  d.* from    tbldocument d inner join         tblsubperson p  on  d.docid = p.docid where   p.personid = 1 	0.238479627651812
21929624	18326	join two tables data in third table	select gate_id  ,   bay_name ,   bay_status  ,  bays_info.station_id,    max(case when sensor_name = 'us.sen1' then round(value,2) end) as sensor1,    max(case when sensor_name = 'us.sen2' then round(value,2) end) as sensor2,    max(case when sensor_name = 'us.sen3' then round(value,2) end) as sensor3,    max(case when sensor_name = 'ds.sen1' then round(value,2) end) as sensor4,    max(case when sensor_name = 'ds.sen2' then round(value,2) end) as sensor5,    max(case when sensor_name = 'ds.sen3' then round(value,2) end) as sensor6,    max(case when sensor_name = 'ms.sen1' then round(value,2) end) as sensor7    from bays_info    inner join sensor_info     on sensor_info.station_id = bays_info.station_id    group by gate_id 	0.0025629929401575
21931735	9286	how to filter with extra column in json php	select ... sum(if(queue.operator = 'vodafone', 1, 0)) as vodafoners from ... 	0.0820786523665589
21931923	2716	how to get data from 3 diffrent tables in mysql	select t1.name,         t2.department,         t3.salary  from   table_one t1        inner join table_two t2               on t2.dept_id = t1.dept_id         inner join table_three t3               on t1.emp_id = t3.emp_id  where  t1.name = 'test2' 	0.000139833388450605
21932285	8281	pick recent modified date in the table	select b1.[id], b1.[appname], b2.[depcode], b1.[depname], b1.[group],      b2.modifieddate, b2.yearlyamount, b2.monthlyamount,      b1.[funded], b1.[appcategory], b1.[research] from business b1 inner join     (select [id], depcode, max(modifieddate) as modifieddate, sum(yearlyamount) as yearlyamount,         sum(monthlyamount) as monthlyamount      from business     group by id, depcode) b2 on b1.id = b2.id and b1.modifieddate = b2.modifieddate 	0
21933364	26048	use generate_series to populate list of months for a given year in postgresql	select distinct to_char(dd, 'month') from generate_series(to_date('2013', 'yyyy') , date_trunc('month', now()), '1 month') as dd; 	0
21933771	22692	how to get a particular values on priority basis	select top 2 tv.id, tv.values  from table_values tv inner join table_priorities tp on tv.id = ip.id where tv.values < 5 order by tv.values, tp.priority 	0
21934916	20235	get total of referenced tables' column	select a.name, coalesce(sum(d.dollars),0) as sums from accounts a left join deposits d on (a.id = d.account and d.status='complete') group by  a.name order by sums desc 	0
21935979	10093	any alternative to month() and year() functions which are common to both mysql and postgresql	select extract(month from t.date) as monthofdate,         extract(year from t.date) as yearofdate from ticket t; 	0.000192158874945633
21936612	18761	mysql get items where current dayofweek is in list	select * from playlist_item  where playlist_id='31'  and type_id='56'  and jobcomplete='0'  and startuur<=time(now()) and einduur >=time(now())  and (dagen='*' or find_in_set(dayofweek(now()), dagen)); 	0.000111180891954657
21939527	19979	mysql left join limit to one row	select      table1.country from    table1 join table2 on table1.id = table2.table1_id    join table3 on table2.id = table3.table2_id    join table4 on table3.id = table4.table3_id group by     table1.country 	0.0781695155913867
21941970	4779	join column names in output with symbol	select id, date||'t'||time as date from table 	0.0956943485662356
21943046	31038	getting mysql max() value	select name from item where qty = (select max(qty) from item) 	0.0146954546793783
21943088	11455	find lowest level in hierarchy	select id from mytable except select parentid from mytable 	0.0126450858598948
21943226	5182	selecting by two fields in union all and ordering between rows	select distinct c.* from categories c, categories p where c.status<>0 and (c.parent_id = 0 or (c.parent_id=p.id and p.parent_id=0)) order by c.id,c.position 	0
21943333	36401	column ignored creating unique index	select  a, b, year, t1.fkid, c, d, count_big(*) as cnt from [dbo].[t1] t1 inner join [dbo].t2 t2 on t1.fkid = t2.id inner join [dbo].t3 t3 on t1.fkid = t3.fkid and t1.fkid = t3.fkid group by a, b, year, t1.fkid, c, d having count(*) > 1 	0.442195525785991
21943612	37902	difference in result of two mysql queries	select (select column1 from table1 where condition1)-(select column2 from table1 where condition2) 	0.00422814680202798
21944132	19552	oracle sql query to get the list of customers who placed most recent orders	select customer_name, most_recent_order    from (     select        c.customer_name,        max(o.order_date) as most_recent_order     from customers c     join orders o on o.customer_id = c.customer_id     group by c.customer_name   )   order by most_recent_order desc 	0
21944659	14333	sql best way to join day over day data into same row including new and deleted ids	select      isnull(t.id,t1.id),     isnull(t.date,getdate()) as 'currdate',     isnull(t.quantity,0) as 'currqty',     isnull(t1.date,getdate()-1) as 'prevdate' ,     isnull(t1.quantity,0) as 'prevqty' from      (            select                t.id,               t.quantity,               t.date          from @table t            where t.date = convert(varchar,getdate(),100)        )t     full outer join      (       select              t1.id,             t1.quantity,             max(t1.date) as [date]        from @table t1        where   t1.date <> convert(varchar,getdate(),100)       group by  t1.id,t1.quantity     ) t1 on t.id = t1.id 	0
21946221	34337	oracle sql query to get the list of customers who purchased more than one item	select c.* from customers c, orders o, order_details od  where c.customer_id = o.customer_id      and o.order_id = od.order_id      group by od.order_id having count(od.item_id) > 1; 	0
21946246	6253	listing all varchars that contain exactly same letters or numbers	select hashed_string_field, count(*) from yourtable group by hashed_string_field having count(*) > 1 	0
21946657	2740	return only numeric values from column - postgresql	select substring(name from '[0-9]+') from contacts 	0.000155420683310693
21947235	21463	comapare values in same column same table	select maker from product group by maker having count(distinct type) = 1 and count(*) > 1; 	6.41336032079755e-05
21951439	30764	sum for more fields in mysql	select sum(case when status = 1 then 1 else 0) as open1,        sum(case when status = 2 then 1 else 0) as closed,        sum(case when status = 3 then 1 else 0) as notspecified,         status,        type,        sub_status,        created_date,        (case when status = 1 then 'open'              when status = 2 then 'closed'              when status = 3 then 'notspecified') as bystatus,        (case when type = 1 then 'rent'               when type = 2 then 'sale'               else 'not specified' end) as lst_type from crm_mydeals  where status in (1,2,3) and agent_1_id > 0 and is_active=1  and date(created_date) between '2013-11-22' and '2014-2-22'  group by status, type, sub_status, created_date 	0.0687896665211443
21953251	10290	set rows in order mysql	select * from table1     order by case when id <=4 then id end desc 	0.0321771584853724
21956140	36458	combine a running balance statement as a column	select clientid, externalbank, placementdate,(select sum(effectiveamount) from tbldeposittransactions where id = 15 group by id)as runningbalance from tbldeposittransactions where id = 15 	0.110392645052295
21959845	17445	query in sql to get the top 10 percent in standard sql (without limit, top and the likes, without window functions)	select s1.id, s1.name s1.points, count(s2.points) from score s1, score s2 where s2.points > s1.points group by s1.id, s1.name s1.points having count(s2.points) <= (select count(*)*.1 from score) 	0.00027955094513108
21961365	36341	mysql select based on date, then join	select * from events e  inner join tickets t on e.id = t.events_id where e.`date` = curdate(); 	0.0013447927730573
21962337	35245	postgresql index unused	select "matches".* from   "matches" where  exists (select 1                  from frames                 where frames.match_id = matches.id); 	0.571649615505442
21962831	6305	mysql select 2 randoms row using count	select ... where location='new york' order by rand() limit 2 	0.0088138776099674
21963182	29038	mysql - match columns between two tables / outer join	select b.z from a inner join b on a.x=b.y 	0.00996296193499552
21963269	32713	how to have multiple queries in one request while keeping order?	select * from (   select col1, col2, '1' as ord ...   union    select col1, col2, '2' as ord ...   union   select col1, col2, '3' as ord ...  ) as tmp order by ord asc 	0.014637315378462
21967860	40751	mysql group by week on two years	select  sum(rate) as rate, week(rdate) as rdate , year(rdate) as rdate_year from cpustats  where server_id='$server_id'  group by year(rdate),week(rdate) 	0.000152585378798666
21967954	19011	how to fetch data from three or more tables?	select class.name , count(student.name),avg(marks.marks) as average_mark   from class    inner join student on class.fields_id = student.fields_id   inner join marks  on marks.fields_id = student.fields_id   group by class.name; 	0.000583766922581286
21968316	30525	nested select to fetch date in sql	select i.*, group_concat(l.tname separator ',')  as names from items_table as i join tag_ref_table r on r.iid=i.iid join tag_list_table l on r.tid= l.tid group by i.iid 	0.046076216192774
21968798	23220	sql records with the same date	select max(id) as max, group_concat(bilgi order by bilgi) as bilgi, yayin_tarihi from table t group by yayin_tarihi order by yayin_tarihi desc; 	0.000692343034373696
21971734	23030	sql: select all values from one table in a join while not knowing all column names?	select tget.* from contact as tget ... 	0
21972552	28565	how to use generate_series to output the week startdate and enddate when input is monyyyy in postgresql	select to_char(d,   'dd mon yyyy" to "')     || to_char(d+6, 'dd mon yyyy') as week from  (   select generate_series(d1                         ,d1 + interval '4 weeks'                         ,interval '1 week')::date as d   from  (select date_trunc('week', to_date('jan2014', 'monyyyy')) as d1) sub1   ) sub2 	0.0151683299607497
21972774	36048	efficiently fetching 25 rows with highest sum of two columns (mysql)	select ur1.* from (select u.*       from users u       order by rank1 desc       limit 1000      ) ur1 join      (select u.*       from users u       order by rank2 desc       limit 1000      ) ur2      on ur1.username = ur2.username order by ur1.rank1 + ur1.rank2 desc limit 25; 	0
21972824	762	fetch data in the mentioned scenario using a single mysql query	select s.stuname, c.testname from student_test_status s join course_test_status c on c.testid = s.testid join student_login l on l.stuid = s.stuid 	0.0197172139956773
21974519	17651	how to get a specific combination of columns in mysql	select   e.employee_id, e.salary as emp_salary, e.manager_id, m.salary as mgr_salary from employees as e left outer join employees as m on m.employee_id=e.manager_id where e.salary > m.salary 	0
21979727	38957	combine the queries in sql-server 2008	select m.ward_id, m.bed_strength - isnull(count(a.ward_id),0)  as free_bed from ward_master m  left outer join ip_admission a   on a.ward_id = m.ward_id  and (a.status='v' or a.status='d') group by m.ward_id, m.bed_strength; 	0.169646161784032
21980064	40740	find duplicate column value in sqlite	select dataid, count(*) c from datatab group by dataid having c > 1; 	0.000403797873516796
21985082	19529	sql return unique count from 3 columns - datetime, vehicle, driver	select     m.currentdatetime, v.vehiclename, count(distinct m.driver) from     vehicles as v inner join     maindata as m     on l.vehicleid = m.vehicleid where     v.vehiclename = 'car 1'  group by     m.currentdatetime      , v.vehiclename order by      m.currentdatetime      , v.vehiclename 	0.000391057432180042
21986445	27743	mysql group by month	select s1.m as mnth,ifnull(s2.smv,0) as smv from (select 1 as m 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) s1 left join (select month(startdatum) as mnth,  sum(somevalue) as smv from db_table group by mnth) s2 on s1.m=s2.mnth 	0.0191442365300912
21986774	18294	writing a query to get the value of a certain shortcode as on today,30 days back and 60 days back in a single select	select today.shortcode, today.value todayvalue, lastmonth.value lastmonthvalue, twomonths.value twomonthsvalue     from revenue_shares today     inner join revenue_shares lastmonth on lastmonth.shortcode=today.shortcode          and [date]=dateadd(day, -30, getdate())     inner join revenue_shares twomonths on twomonthsshortcode=today.shortcode          and [date]=dateadd(day, -60, getdate())      where today.[date]=getdate() 	0
21987375	17745	how do i store nested locations?	select * from mytable where path like '2_4%'; 	0.763831434752165
21988283	36360	generate 'source' column value when joining tables to form a view	select fruits.*, 'fruit' as type from fruits union select vegies.*,  'vegie' from vegies 	0.000622031049166555
21991953	19006	how to split string by character into separate columns in sql server	select *,   substring(dat,1,charindex('-',dat)-1) as section,   substring(dat,charindex('-',dat)+1,charindex('-',dat)-1) as township,   reverse(substring(reverse(dat),0,charindex('-',reverse(dat)))) as myrange from mytable 	0.000223826647338992
21992986	19209	sql subtract min and max	select wsn, max(base) as maxbase, min(top) as mintop into memory firstpass from perfs group by wsn ; select (maxbase - mintop) as calc from memory firstpass 	0.0221592779544882
21996852	4543	counting items within a value found inside mysql table	select id, type, details,     case details when null then 0      when '' then 0     else     (length(details) - length(replace(details, ',', '')) +1)      end as details_count     from foodbasket 	0.000566784637042404
21998165	10121	sql store procedure loop	select    company.name   ,[admin].firstname as firstadmin   ,[user].firstname as firstuser from company left join contact [admin] on [admin].companyid=company.id and [admin].type=40 left join contact [user] on [user].companyid=company.id and [user].type=41 	0.719654104107263
22000239	6790	sql count columns and create table with computation	select department.departmentname, count(*) as amountofprojects     from project, department     where project.department = department.departmentname     group by department.departmentname; 	0.0187189089531111
22002889	22531	select an id where the foreign key is null	select        auction.auctionid  from            item                 inner join auction on item.itemid = auction.itemid                 left outer join bid on auction.auctionid = bid.auctionid where        (auction.status = 'valid') and bid.auctionid is null group by auction.auctionid having count(bid.auctionid) = 0 	0.000935485754695874
22006007	37510	sql nvarchar order	select [bproject_id]  from [workload].[dbo].[bending_projects]  order by right([bproject_id], len([bproject_id]) - 2) 	0.514533499544763
22006013	35420	sql query to get average per group in two tables	select grade,         avg(score)  from   students         join results using (student_id)  group  by grade 	0
22008497	15987	how to retrieve number of users from mysql db by using other db as reference?	select count(distinct(user)) as cnt from `table3` a inner join `table2` b on a.service_id = b.service_id inner join `table1` c on b.organization_id = c.organization_id and c.organization_id =123 	0
22008737	21500	pivot table on two sql table, one with 5m+ rows?	select      c.city_name,      count(p.person_id) as `count`  from      cities c      left outer join persons p on c.id = p.city_id  group by      c.city_name 	0.000357528518057814
22009072	20641	fetching data from different table in while loop	select posts.id, thumbsup.user  from posts left outer join thumbsup  on posts.id = thumbsup.topic and thumbsup.user = '".$_session['username']."' 	0.000862344603875032
22009169	22095	how to get those row where a field value exist in all foreign key type from a table	select count(resource_id) as cnt,         resource_name  from   the_table  group  by resource_name  having cnt = (select count(distinct resource_id)                from   the_table); 	0
22010876	30088	compare rows value in two tables and return if any of value from a row is different	select * from tableb except select * from tablea 	0
22011015	30014	what should be the sql query to get the desired result?	select * from thetable where messageid in (   select max(messageid)   from thetable   where recipientid = 110   group by senderid ) order by senderid; 	0.799633575804249
22011526	28385	transpose t-sql query	select  '201401', sum(      case     when  start_date <= '2014-01-01' and  (end_date > '2014-01-01' or end_date is null)then 1 else 0 end ) from table union all select  '201402', sum(      case     when  start_date <= '2014-02-01' and  (end_date > '2014-02-01' or end_date is null)then 1 else 0 end ) from table union all select      (etc) from table 	0.456854875048852
22011758	7434	how to compare date in postgresql timestamp with time zone?	select * from my_table where date_field between to_timestamp(1333065600000) and to_timestamp(1364601600000); 	0.00045783060075964
22011801	6116	sql server get rank of one column amongst columns	select * from mytable cross apply (   select count(*) as [black rank]   from (values (blue),(green),(red),(yellow),(brown),(black) ) t(val)   where val >= black ) b 	6.76359692713742e-05
22013179	22491	importing a datetime field from csv/txt into access	select convert(varchar(10), [field1], 101) as date1 	0.00226189805616232
22013231	32158	combine two inner join queries into one procedure	select top 15       us.mxitid as transactioncreatedby , count(t.createdby) as total , sum(case when childgender = 'female' then 1 else 0 end) as femalecount , sum(case when childgender = 'male' then 1 else 0 end) as malecount from [user] us inner join [transaction] t on t.createdby = us.userid group by us.mxitid order by 2 desc 	0.0242062268090085
22013646	180	classic asp access database query, sum and group	select month(enddate) as mo, year(enddate) as yr,         sum( ((enddate - startdate) * rentfee) + bookingfee - ((enddate - startdate) * rentcost) ) as profit from rent_table where enddate is not null group by year(enddate), month(enddate) order by year(enddate), month(enddate) 	0.727105702186528
22013823	6229	use alias name as a column	select [year],        [financevalue-2014],        [financevalue-2013],        [financevalue-2012],        [financevalue variance],        round([financevalue variance] * 2.50,4) as [newvariance] from ( select [year],        [financevalue-2014],        [financevalue-2013],        [financevalue-2012],        [financevalue-2014]-[financevalue-2013] as [financevalue variance]       from finance)t 	0.345617087487233
22016694	3996	deleting rows with integrity constraint	select table_a.b_id  into #temp_a from table_a where condition delete from table_a where b_id in  (select b_id from #temp_a)  delete from table_b where id in  (select b_id from #temp_a)  drop table #temp_a 	0.0143387591382498
22017483	29397	sort array results based on variable algorithm - mysql & php	select forum.*, timestampdiff(hour, from_unixtime(bd.date_add), now()) as 'timedif' ((forum.votes - alg.vote_reduction)/pow(('timedif' + alg.time_variable),alg.gravity)) as 'al' from forum as forum left join algorithm as 'alg' on (alg.id='1') order by al 	0.00202287116304821
22017895	1490	sql server sum over one column with another column as criteria	select   r.customer,   sum(r.revenue) as revenuesinceregistrationdate from   revenue r   inner join othertable t on t.customer = r.customer where   r.date >= t.registrationdate   group by   r.customer 	0.000398380581010304
22019043	7922	how to return a list of results in mysql, where only return one	select title from sakila.film f  join sakila.film_actor fa on fa.film_id = f.film_id where fa.actor_id = @id 	0
22022847	5760	mysql query based on hour	select hour_date,  sum((hour(start_date)<=hour_date) and (hour(end_date)>=hour_date)) as active  from sessions,  (select distinct hour(start_date) as hour_date from sessions where start_date>'2014-02-25 00:00:00') hours where start_date>'2014-02-25 00:00:00' group by hour_date; 	0.00179959018474523
22023322	962	postgresql matching purchases with most recent device loggedin	select uid, amount, date, ifa from     (select             t1.uid,             t2.amount,             t2.date as date,             row_number() over (partition by t1.uid, t2.date) as rn,             t1.ifa       from             session_logs t1             join purchases t2 on                  t1.uid = t2.uid and                  t1.date <= t2.date) x1 where x1.rn = 1 	0.000648244103605347
22024654	33482	sql query to select certain number of records with where clause	select * from (    select top 500 * from (     select top 1000 * from records where entitytype='business' order by id desc    ) x   order by id  ) y  order by id desc 	0.000544357485002323
22027253	19901	sql query to get total in columns	select table.region, table.country, sum(table.[population]) as [sum population] from table group by table.region, table.country; 	0.000324080672077479
22030253	2856	how to select content in database?	select substring(columnname, 1, charindex(',', columnname, 1) - 1) from testtable; 	0.0324560128503348
22033298	14334	how to get "1" if value last in "over(order by something)" group, and "0" if not?	select     productid,      is_last = case when count(*) over()=row_number() over(order by productid) then 1 else 0 end from [productstatuses] order by productid 	0.000137129450079793
22033488	30095	how limit start value come from other table in mysql	select q.totalmarks from ( select *,@currow := @currow + 1 as row_number from student as std join    (select @currow := 0) r where std.status=1 order by (std.datetime) asc ) q where row_number>(            select us.startnum              from user as us             where us.username='abc'           ) limit 10 	0
22035509	39615	table with two nullable foreign keys join results into single column	select common.personid,        common.petid,        isnull(person.personname, animal.animalname) as name,        isnull(person.personasset, animal.animalasset) as asset from common left join person on common.personid = person.personid left join animal on common.animalid = animal.animalid 	0
22035822	35200	counting forum topics and replies	select     forumtopic.forum_category_id,     count(distinct postleftouterjoin.id) as forumtopics_count,     count(replyleftouterjoin.id) as replies_count from forum_topics as forumtopic left outer join posts as postleftouterjoin on postleftouterjoin.object_id = forumtopic.id     and postleftouterjoin.object_type = 'forum_topic'     and postleftouterjoin.status = 'approved' left outer join posts as replyleftouterjoin on replyleftouterjoin.object_id = postleftouterjoin.id    and replyleftouterjoin.object_type = 'post'    and replyleftouterjoin.status = 'approved' where forumtopic.forum_category_id = 'some_id' group by     forumtopic.forum_category_id ; 	0.0459574084974387
22038180	38587	read only logic on the basis of user logged in to openbravo	select ad_role_id, name from ad_role;  ad_role_id                        | name  ....  1000001                           | admin  sdjfalsdfjklasjdfklasdfasldfjaklsj| velmurugan   sdflaksdjflkasjdlfalsdfaldskfjlas | employee  dsklfjakldsjfklasjfkladsjflkajsdfk| f&b us, inc. - admin  .... (38 rows) 	0.000766836106405703
22038395	20712	php sql group by user	select top 10 userid, max(poang) from floppy group by userid order by max(poang) desc 	0.195703017408303
22040388	2472	sql find closest timestmaps when duplicates exists	select t1.*, max(t2.unixtimestamp as rj_time), t2.response_detail as rj_error  from t1   left join table2 as t2 on t1.id=t2.personid and t1.clientcode=t2.client where t1.clientcode='quouk'    and (t1.language = 'en_gb')  group by t1.id order by t1.id 	0.0538065963860272
22040720	13665	count the number of 1st and 0's with a specific date	select          departmentname, count(*) as total      from          tablename      where          time between             convert(date,@time)          and             convert(date, @time2)     group by departmentname     order by count(*) desc 	5.8618665630827e-05
22040775	8627	sql query exclude rows if having two different values	select id from t group by id having count(*) = 1 	9.08086655876258e-05
22040948	6474	select rows where column a is not unique and column b is unique?	select min(id),        column_a,        column_b from mytable where column_a in (select column_a                    from mytable                    group by column_a                    having count(distinct column_b) >= 2) group by column_a,          column_b 	7.07716108576327e-05
22043193	9090	sql average group by	select nbagamelog.opp, avg(nbagamelog.points) from players inner join      nbagamelog      on players.player_id = nbagamelog.player_id where (nbagamelog.date_played between date()-15 and date() and       players.position = "c" group by nbagamelog.opp; 	0.0339956614369059
22043583	29163	column 'media_id' in field list is ambiguous	select title,blurb,m.media_id from media_career_crossref mcc inner join media m  on m.media_id = mcc.media_id 	0.0804616118499104
22044280	20948	sql group by before averaging	select t.opp, avg(points) from (select gl.team, gl.opp, avg(gl.points) as points       from players p inner join            nbagamelog gl            on p.player_id = gl.player_id       where (gl.date_played between date()-15 and date() and             p.position = "c"      group by gl.team, gl.opp;     ) t group by t.opp; 	0.125860451106089
22044467	28831	need the highest id using left join	select * from table1 inner join ( select max(table1.id) as id from table1 inner join table2 on table2.client = table1.client and table2.campaign=table1.campaign and table2.enabled != 'disabled' group by table1.client, table1.campaign ) as m on m.id = table1.id 	0.026380593155555
22044634	12201	creating columns per where clause	select sum(if(value > 10 and value < 20), 1, 0) as '10-20',          sum(if(value > 20 and value <  30), 1, 0) as '20-30',          sum(if(value > 30 and value <  40), 1, 0) as '30-40',          sum(if(value > 40 and value <  50), 1, 0) as '40-50', week(created) as 'week', year(created) as 'year' from table  where  group by year(created), week(created) 	0.0664156549924083
22046642	22905	get id and count mysql record in same table for seperate list	select tag_id as id, count( tag_id ) as count  from tag where tag_id in ( 1, 2, 3, 28 ) group by tag_id ; 	0
22046965	35398	sql select query to group into 'other' section	select (case when total > 10 then country else 'other' end) as country,        sum(total) as total from (select country, count(country) as total       from employees       group by country      ) eg group by (case when total > 10 then country else 'other' end) order by total asc; 	0.0708856462261587
22048102	33282	sql convert data into one row from multiple columns	select customernumber,      case when [1] > 0 then 'y' else 'n' end [sony],     case when [2] > 0 then 'y' else 'n' end [lg],     case when [3] > 0 then 'y' else 'n' end [samsung] from (select product1, customernumber     from table) as sourcetable pivot (     count(product1)     for product1 in ([1], [2], [3]) ) as pivottable; 	0
22049295	30953	how to extract tags from strings	select id  from tags  where tag='%expensive%'      or tag='%high%'      or tag='%quality%'      or tag='%computer%'     or tag='%hardware%'; 	0.000634625233851947
22049670	21871	find most frequent record in whole table	select val, count(*) ttl from ( select date, 'a' type, a val from my_table union all select date, 'b', b val from my_table union all select date, 'c', c val from my_table union all select date, 'd', d val from my_table union all select date, 'e', e val from my_table union all select date, 'f', f val from my_table ) x group by val order by ttl desc limit 1; 	0
22050307	27619	mysql, using columns in another table for a case statement	select i.item, i.count, ifnull(ic.itemcountstatus,'unknown') status from items i left join itemsconfig ic on (i.count between ic.itemcountlow  and ic.itemcounthigh) 	0.0366718343546873
22050912	984	how to find records from table a, which are not present in table b?	select a.* from      table_a a left join table_b b on a.request_id = b.request_id                    and a.order_id   = b.order_id where b.request_id is null 	0
22050974	10690	select parent rows where child a is 1 and child b is 2 (mysql)	select a.* from a inner join b on b.id = a.b_id and b.whatever = condition1 inner join c on c.id = a.c_id and c.whatever = condition2 	0
22051165	38842	sql query to find total count in certain price range	select count(order_id),        value_range from       (select order_id,             total_value,             case when total_value between 0 and 50 then '0-50'                 when total_value between 51 and 100 then '51-100'                 when total_value > 100 then '100'             end as value_range        from table)a group by value_range 	0
22051609	29041	getting an error saying the conversion of a varchar data type to datetime resulted in an out of range value	select  ord_type       , case when entered_dt  between '20130201' and '20130228'               then 1 else null end   from oehdrhst_sql 	0.000659869762717393
22053684	29535	trying to write a query in toad to calculate sales commission	select saname,        sum(amt) * case          when saname = 'mike' then           .15          when sanme = 'dave' then           .12          when saname = 'tony' then           .1          else           0        end as commission,        count(actno)   from rcvmgr.rcv_act_daily  where saname in ('mike', 'dave', 'tony')    and ref1 = 'pmt'    and sadt between add_months(last_day(sysdate - 1), -1) + 1 and        trunc(sysdate - 1)  group by saname 	0.0343236358829759
22055789	11658	jsp- grouping rows of database with unique field name?	select iif((value = grp_value and quantity = grp_quantity),cust_id,'') as cust_id        value,        quantity   from (select x.*, grp.value as grp_value, grp.quantity as grp_quantity           from invoice x           join invoice grp             on x.cust_id = grp.cust_id          where grp.value = (select min(y.value)                               from invoice y                              where y.cust_id = x.cust_id)            and grp.quantity = (select min(y.quantity)                                  from invoice y                                 where y.cust_id = x.cust_id                                   and y.value = grp.value)          order by x.cust_id, x.value, x.quantity) x 	0.000143805082642802
22058216	29661	full text search using contains shows different results with same database content	select name from recipes where  contains(name, 'formsof (inflectional, apple) and formsof (inflectional,pies)', language 1033) 	0.00692258253961739
22060782	127	search a word by capital or small letter	select * from table_name where binary title like '%th%' 	0.0821735580067648
22060928	6941	select "max" records amongs groups of records that share same columns values	select c1,        c2,        c3,        c4  from(   select      xxx.*,      row_number() over (partition by c1 order by c3 desc) rnum   from xxx )x where rnum=1 	0
22061155	18421	sql server inner join only getting results from 1 table	select top 1000 * from profile; 	0.0137110702157067
22061350	230	how to substract time from column in mysql	select timediff(max(time),min(time)) as duration from tcm_packet where latitude ='-6.916202' and longitude = '107.599276'; 	0.00308507729125943
22062031	34504	i cannot extract exact number of count	select id, name, (select count(*) from user where user.position = rank.id) as cnt from rank; 	0.00224491086318463
22062265	13596	find duplicate rows in a table	select *,         count(partner_name)   from partner  where partner_name in (               select partner_name                  from partner                 where partner_main=1        ) group by         partner_name having count(partner_name) > 1 union all select *,         count(partner_name)   from partner  where partner_name in (                select partner_name                   from partner                  where partner_main=0        ) group by         partner_name having count(partner_name) = 1 	0.000146886293516538
22062672	24531	after joing a table i dont get a proper result which i want	select t0.id, t0.propertyname, group_concat(t1.catid)  from t0  inner join t1 on t0.id = t1.propid group by id 	0.0016339531249706
22062683	17473	how to select the group by result from an iif statement?	select   (case when item in ('pork', 'fish') then 'meat' else 'vegetable' end) type, sum(number) from table group by (case when item in ('pork', 'fish') then 'meat' else 'vegetable' end) 	0.0609928894583754
22063633	3973	sql: how to count occurrences based on file extension	select extension,         count(*) as extensioncount  from   (select right(name, charindex('.', reverse(name)) - 1) as extension          from   files) t  group  by extension 	9.30737516617418e-05
22063678	10567	change only single column values when we use * in sql	select col1||'_asd_', t.* from mytable t; 	0.0101417063087036
22063688	1729	mysql select to columns as one but display only one where value %like%	select  case     when fname like '%james%'    then fname    else lname end  as name from `table` where id='1' and concat(`fname`,`lname`) like '%james%'  order by date asc limit 0,1 	0
22065726	21691	statistics customer list with a total purchase value is greater than 50m in 3 months from the time of 31/1 and earlier	select   buyeremail from     orders where    paymenttime between '2014-01-31' - interval 3 month and '2014-01-31' group by buyeremail having   sum(finalprice) > 50000000 	0
22066717	29835	how to pivot multiple records	select p.floor,p.[1] as room1,p.[2] as room2,p.[3] as room3 from ( select floor,apt,row_number() over(partition by floor order by apt) as rn from #t) as t pivot (  min(t.apt) for t.rn in([1],[2],[3])  )as p; 	0.028533759399681
22067218	11136	how to join 2 table and select a particular column using a common column in both tables	select table1.customer_loan,table2.customer_nam from   table1 inner join table2 on (table1.customer_id =table2.customer_id) 	0
22067616	36108	fractional day difference in oracle	select sysdate - (sysdate -dbms_random.value(1,10)) from dual; 	0.00971934541386827
22074443	30729	creating sql table with range of months as columns and populating fields with table data	select  project, [jan 2014], [feb 2014], [mar 2014], [april 2014] from    t         pivot         (   sum(monthvalues)             for months in ([jan 2014], [feb 2014], [mar 2014], [april 2014])         ) pvt; 	0
22074833	9673	using ms access code in sql by identifing column names	select  q.query_name        ,q.attempts        ,q.successes        ,q.failures        ,cast(q.[successes] as nvarchar(10)) + '/' + cast(q.[attempts] as nvarchar(10)) as proportion from ( select generate_query as query_name,         sum(case when recnum is not null then 1 else 0 end) as attempts,         sum(case when query_test = 'yes' then 1 else 0 end) as successes,        sum(case when query_test = 'no' then 1 else 0 end) as failures        from tbl_tpf         group by generate_query       )q order by q.query_name 	0.759473765913292
22075146	28446	php algorithm and mysql	select      sum(`volume`*`proof`)/sum(`volume`)  from      `tbl_spirits`  where      1 	0.262462129005175
22076940	13456	mysql select record within last 4 hours	select count(*) as u_count from xxyyzz_users  where id=$user_id and now() - interval 4 hour <= last_post_time 	0
22078308	14001	sql - finding largest period of activity by customer	select t.*,        (select sum(t2.amount)         from table t2         where t2.customer = t.customer and               t2.date >= dateadd(day, -90, t.date) and t2.date <= t.date        ) as amount90 from table t; 	6.97790143156728e-05
22078538	30918	aggregate values by range	select y.max_deals as deals      , avg(profit_perc_year) as avg_profit      , count(*) as users from  (    select (generate_series (0,2) * x.max_t)/3 as min_deals          ,(generate_series (1,3) * x.max_t)/3 as max_deals    from   (select max(transactions_year) as max_t from portfolios_static) x    ) y join   portfolios_static p on p.transactions_year >  min_deals                           and p.transactions_year <= max_deals group  by 1 order  by 1; 	0.0200559113637711
22079129	22412	finding array length in postgres	select array_upper ( value, 1 ) from table_name_here; 	0.0172890660552587
22080269	21377	select dates from multiple columns in same table	select * from (    select ovulation as `date`, 'ovulation' as treatment, mare    from `dates`    where ovulation > date()    order by ovulation asc    limit 5    union    select pregnancy as `date`, 'pregnancy' as treatment, mare    from `date`    where pregnancy > date()    order by pregnancy asc    limit 5    ... ) as x order by x.`date` asc limit 5; 	0
22085518	24223	mysql, specific order by	select      *     ,case         when (`confirmchoice` is null) then '1'         when (`confirmchoice` is not null and `datestart` is not null ) then '2'         else '3'      end as sort_order from     `supertable` where     1 order by      sort_order     ,`dateend` 	0.0889758782328278
22085672	13963	select multiple columns from 4 different tables	select  product_description.name as name,         product_description.author as author,         product.model as model,         `order`.`order_id` as `order_id` from product_description inner join product on product_description.product_id=product.product_id inner join order_product on order_product.product_id=product.product_id inner join `order` on `order`.order_id=order_product.order_id where `order`.order_status_id=1 	6.4868951468708e-05
22088093	37275	getting data from one table to another table using join	select a.id, a.name, b.id, b.suid from b join a on b.suid = a.id where b.id = 3; 	0
22089797	40108	sqlite: query to get common attributes	select product.code,        attribute.name,        attribute.value from product join attribute on product.id = attribute.product_id group by product.code,          attribute.name,          attribute.value having count(*) = (select count(*)                    from product as p2                    where p2.code = product.code) 	0.00333656218681368
22089988	11525	mysql - additional analysis on sum(field) grouped by name	select      name,      sum(price_paid) as total_price_paid,     case when sum(price_paid) between 0 and 100 then 1          when sum(price_paid) between 101 and 350 then 2          when sum(price_paid) > 350 then 3 end as purchase_level from      orders  group by      name 	0.0654209793654103
22091727	29519	give every "empty" age band 0	select   count(members.whatever_column_best_would_be_primary_key) as `members`,   ages.age_range from `members` right join (     select '10-20' as age_range     union all     select '21-30'     union all     select '31-40'     union all     select '41-50'     union all     select '51-60'     union all     select '61-70'     union all     select '71+' )ages on ages.age_range = case     when members.age >= 10 and age <= 20 then '10-20'     when members.age >=21 and age <=30 then '21-30'     when members.age >=31 and age <=40 then '31-40'     when members.age >=41 and age <= 50 then '41-50'     when members.age >=51 and age <=60 then '51-60'     when members.age >=61 and age <=70 then '61-70'     when members.age >= 71 then '71+'   end group by ages.age_range 	0.00812327781599016
22093290	3514	load average jumps up during a sort in mysql query	select table2.* 	0.0214172760785685
22097209	10925	mysql select count rows for each unique item in column	select     father,     count(child) as total_child,      sum(if(sex = 'm', 1, 0)) as total_m,     sum(if(sex = 'f', 1, 0)) as total_f from     table_name group by     father 	0
22097285	16626	sql server join results as comma separated list	select co.companyid, allindustries =         (select (cast(industry as varchar(200))+',') as [text()]        from company c,         company_industry_map m         where c.company_id = m.company_id and c.company_id = co.company_id         order by industry_id for xml path('')) from companies co 	0.00560962141415042
22097740	3552	select top nth row (or last row if there's fewer than n rows)	select score from (     select score     from table     order by score desc     limit 1000 ) s order by score limit 1 	0
22097845	37694	sql: joining results of 2 select queries into 1 row	select max(location_a) as location_a,        max(refno_a) as refno_a,        max(location_b) as location_b,        max(refno_b) as refno_b from ( select location as location_a,        refno as refno_a,        null as location_b,        null as refno_b from tablea where refno = '1234' union all select null as location_a,        null as refno_a,        location as location_b,        location as refno_b from tableb where note = 'ln1234567') s 	0.000153368659026072
22098167	33909	ms access sql: in a query check if a field contains spaces and if it's equal to another field without them	select * from your_table  where a1 like '% %'  and replace(a1,' ','') in (select b1 from table 2) 	0
22099301	18426	db2: select all rows of data when multiple categories types of a column for each primary id is found	select t1.* from mytable t1 where exists(     select 'hasford'     from mytable t2     where t2.id = t1.id    and t2.car = 'ford' ) and exists(     select 'hashonda'     from mytable t3     where t3.id = t1.id    and t3.car = 'honda' ) 	0
22101157	19324	mysql query get range between date not from table	select *,timestampdiff(month, date_sub(start_pay,interval 1 month), curdate()) as  month_count,payment * month_count as total_to_pay from table 	6.62559877514991e-05
22103606	937	self-referencing calculated field	select layer, layerperocclimit,   sum(layerperocclimit) over(order by layer       rows between unbounded preceding and current row)            as runningtotal   from yourtable 	0.0675344673546483
22104195	37632	sql select with 2 foreign key referencing on the same table	select  a.name as asker  , d.name as doer  , e.eventname from event as e left outer join user as a on e.askerid = a.id left outer join user as d on e.doerid = d.id 	0
22104688	12783	adding values in oracle sql database based on certain conditions	select worker.name, max(ledger.item), sum(ledger.amount) from ledger, worker where worker.name = ledger.person   and ledger.action = 'bought' group by worker.name order by worker.name asc; 	6.51057453601176e-05
22105494	865	mysql query: need to totalize monthly given order number	select ft.idcliente, ft.mes, ft.anio, sum(st.precio*st.cantidad) as total from firstable ft inner join secondtable st on (st.idalbaram = ft.idalbaran) group by ft.idcliente, ft.mes,ft.anio 	0.00460230476913815
22105662	19962	getting a column which shows above and below for each person based on the average value	select employee_name,department_id     (case         when (salary>=(select avg(b.salary)from hr.employees as b where a.department_id = b.department_id))         then 'above'         else 'below'     end) "salary status" from hr.employees as a; 	0
22107342	16417	sql developer get time when query is run	select to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') from dual; 	0.510814993475028
22107862	4632	join two tables using multiple rows in the join	select a.color_group_id, a.document_id from (     select color_group_id, document_id, count(*) ct     from color_document d     join color_group g on d.color_id = g.color_id     group by color_group_id, document_id) a join (     select color_group_id, count(*) ct     from color_group     group by color_group_id) b on a.color_group_id = b.color_group_id and a.ct = b.ct join (     select document_id, count(*) ct     from color_document     group by document_id) c on a.document_id = c.document_id and a.ct = c.ct 	0.00597312289690434
22109499	9533	how can i change column headers title from sql query datagrid in vb.net	select roomnumber as room_number, etc 	0.0249008351403603
22110053	26377	mysql query to show salary depending on department	select dept_no,        if(dept_no='c1',salary,0) as dept_noc1,        if(dept_no='c2',salary,0) as dept_noc2,        if(dept_no='c3',salary,0) as dept_noc3 from emp group by dept_no; 	0.000159745256988397
22111612	32050	how can i combine two mysql query to get one single result?	select cv_requirement,cv_target,cv_target_date_for, achi   from (select cv_requirement,cv_target,cv_target_date_for     from `cv_target`     where cv_target_date_for between '2014-02-20' and '2014-02-27' and cv_recruiter='44') a    left outer  join     (     select count(candidate_id)as achi,cv_target_date from candidate   where fk_posted_user_id='44'   and cv_target_date between '2014-02-20' and '2014-02-27'   group by fk_job_id,cv_target_date) b   on a.cv_requirement=b.fk_job_id and a.cv_target_date_for=b.cv_target_date 	7.00340133613937e-05
22111939	20879	how to use a not in a join?	select distinct releases.*  from releases inner join artist_love on  releases.all_artists like concat('%',artist_love.artist,'%') and artist_love.user =  'quickinho' inner join label_love on label_love.label = releases.label_no_country and label_love.user =  'quickinho' left join charts_extended on charts_extended.release_id=label_love=releases.id and charts_extended.artist =  'quickinho' where charts_extended.release_id is null order by releases.date desc  limit 0 , 102 	0.710656374021227
22111990	31160	selecting all not present in the intermediate table with ought nested select	select * from t1 left join t2_has_t1 on t1.id_t1 = t2_has_t1.fk_t2 where t2_has_t1.fk_t2 is null 	0.0058791143826641
22112011	2792	how should i find the sum of a column from a series of time periods under postgresql?	select     (extract(epoch from time) / 120)::integer,     sum(size) as size from test where     ip=inet '192.168.1.69'     and     time > current_timestamp - interval '24 hours' group by 1 order by 1 ;    int4   | size   11613921 |  100  11614273 |  400  11614276 |  200  11614278 |  400 	0
22112242	26878	stock control determinant	select testx.dispatchdate,        testx.stockin,        testx.stockout,        (select sum(stockin)         from   testx a         where  a.dispatchdate <= testx.dispatchdate) as sumin,        (select sum(stockout)         from   testx a         where  a.dispatchdate <= testx.dispatchdate) as sumout,        [sumin] - [sumout]                            as balance from   testx order  by testx.dispatchdate; 	0.6059885958352
22113469	9087	change the date format in sqlserver	select     convert(varchar, max(mydate), 101) as datetouser from      blatable 	0.0208443459417005
22113648	39108	between two date condition in sql server	select id  from master m  where ((m.fromdate between '10/03/2014' and '17/03/2014')       or (m.todate between '10/03/2014' and '17/03/2014')) 	0.0144010981776029
22113862	16064	pl/sql : how to extract data for any 5 days in a month	select customerid from actions a where actiondatetime >= '2014-01-01' and actiondatetime < '2014-02-01' group by customerid having count(distinct trunc(actiondatetime)) >= 5; 	0
22115823	16261	last 5 comments for x articles query with mysql	select     c.comment_id, c.comment_title, c.article_id,             a.article_id, a.article_title, a.category_id, cats.category_name from       articles      a inner join categories cats on (a.category_id = cats.category_id) inner join (select   article_id, max(comment_id) comment_id, comment_title             from     comments co             where    co.article_id in (1, 2, 3, 4, 5)             group by co.article_id) c             on (a.article_id = c.article_id) order by    c.comment_id desc 	0
22116136	40250	sql distinct count with group by	select team, count(date_played) as count from     (         select distinct team, date_played         from nbagamelog     ) as whatever group by team 	0.206086360268036
22120675	4298	sql query count and distinct year	select count(musicianid) as allmusicians  from musician  where year(dateofbirth) = 1990 	0.0205004509720823
22122854	14048	distinct date mysql php year	select distinct year(date_issue) from invoices_sales 	0.00396807059063529
22122925	1550	optional tables in sql query	select a.a1,        (select c.c1 from tablec c where b.b_id = c.fb_id) as c1,        (select c.c2 from tablec c where b.b_id = c.fb_id) as c2,        (select d.d1 from tabled d where b.b_id = d.fb_id) as d1,        (select e.e1 from tablee e where b.b_id = e.fb_id) as e1,        (select e.e2 from tablee e where b.b_id = e.fb_id) as e2,        (select e.e3 from tablee e where b.b_id = e.fb_id) as e3 from tablea a join      tableb b       on a.a_id = b.af_id; 	0.751289429138138
22123985	996	mysql select matching ids, output to json	select distinct t1.thought_id as source, t2.thought_id as target from thoughts_tagged t1 inner join thoughts_tagged t2 on t1.tag_id = t2.tag_id and t1.thought_id <> t2.thought_id 	0.00205425234966691
22125719	28517	how to avoid identical expressions in sql select and where?	select * from (    select match(test) against("str" in boolean mode) as testrelevance,           ....    from ...    where ...  ) as t where testrelevance > 0 	0.705859889177539
22125949	18311	mysql query to check whether a table is in the database or not	select count(*) from information_schema.tables where table_schema = 'db_name' and table_name = 'table_name' 	0.0146736248011461
22126761	22217	mysql join tables with condition	select * from post  left join comment on post.id = comment.post_id and comment.user_id=1 	0.45100994151743
22129373	16560	changing select_query to mysql_query?	select sum(tblaffiliatespending.amount)  from tblaffiliatespending  join tblaffiliatesaccounts on tblaffiliatesaccounts.id=tblaffiliatespending.affaccid  inner join tblhosting on tblhosting.id=tblaffiliatesaccounts.relid  inner join tblproducts on tblproducts.id=tblhosting.packageid  inner join tblclients on tblclients.id=tblhosting.userid where affiliateid=$id  order by clearingdate desc 	0.286071215108789
22130454	12594	how can i get true\false output in sqlserver	select id,         case when id is null then 'true' else 'false' end as id_description from dbo.table1 	0.0372980899984136
22130886	20491	select rows that fall within standard deviation	select avg(price) from prices join (select avg(price) myavg, stddev_pop(price) mydev from prices) stats where price between stats.myavg - stats.mydev and stats.myavg + stats.mydev 	0.00365558843078913
22135081	13768	how to select the row which matches a complex where clause and has the minimum value in a given column?	select top 1 <columns> from <table> where <complex where clause> order by <columnx> asc 	0
22135526	40843	sql max value in one column	select   r.id, r.title,   u.name as 'created_by', m.name as 'modified_by', r.version, r.version_displayname, r.informationtype, r.filetype, r.base_id, r.resource_id, r.created, r.modified,   group_concat( concat(cast(c.id as char),',',c.name,',',c.value) separator ';') as 'categories', startdate, enddate from   resource r   inner join    (select    distinct r.id as id   from    resource r   inner join    category_resource cr1 on (r.id = cr1.resource_id)   where    cr1.category_id in (9) ) mr     on r.id = mr.id   inner join category_resource cr     on r.id = cr.resource_id   inner join category c     on cr.category_id = c.id   inner join user u     on r.created_by = u.id   inner join user m     on r.modified_by = m.id where r.enddate is null group by r.id; 	0.00136878956186521
22135679	12394	get highest value of 2 columns and the full row information of the row that has the highest number	select * from data order by greatest(num1,num2) desc limit 0,1; 	0
22135685	14225	combining two tables, ordering by date, with limit	select results.*, u.username from (     select p.post_id, p.user_id, p.message, p.datetime from posts p     union         select r.post_id, r.user_id, r.message, r.datetime from replies r  ) as results   left join users u on results.user_id = u.user_id order by results.datetime desc limit 25 	0.00904106851461037
22136172	26095	use from in the select clause	select n.id as 'seller_id', n.name as 'seller_name', n.email as 'seller_email', r.relation, t.id as 'buyer_id', t.name as 'buyer_name', t.email as 'buyer_email' from `name` as n       inner join relationship r on n.id = r.id       inner join name t on r.target_id = t.id  where n.id = 'abc123' 	0.226927459205279
22136279	22459	count total numbers of same item exist in database	select post_id, count(*) from table group by post_id 	0
22138513	7955	how do i use more "select query" with mysql to get result from different table	select    users.*,    user_property.*,    offers.property_id as offers_property_id  from users    join user_property on users.id = user_property.user_id     and (           user_property.postcode = users.pc1        or  user_property.postcode = users.pc2       or  user_property.postcode = users.pc3       or  user_property.postcode = users.pc4     )   left join offers on      offers.property_id = user_property.property_id     and offers.agent_id = users.id  where users.company_name != ""   and datediff(curdate(), user_property.creation_date) <= 7 having offers_property_id is null; 	0.000722685775223735
22139202	33812	select subquery in postgresql get list	select stations.station as st,count(username) as co  from member left join stations on member.station=stations.station  group by stations.station  order by stations.station; 	0.0353476008298433
22140028	40949	how to sum of total price from multiple tables?	select  isnull(t1.price, 0) + isnull(t2.price, 0) + isnull(t3.price, 0) as total from tbl_startupbanner t1 left join tbl_signinbanner t2 on t1.matchcol = t2.matchcol left join tbl_signoutbanner t3 on t1.matchcol = t2.matchcol 	0
22140805	31428	how to use just one column when multiple columns are returned from subquery?	select avg(cnt)  from (     select deptno, count(*) as cnt     from employee group by deptno) src 	0.00015052431305294
22140905	30	display all table a records which are not in table b using mysql joins concept	select  t1.* from tablea as t1 left join tableb t2 on t1.email=t2.email where t2.id is null 	0
22140950	9258	selecting values after integer using substring	select id,substring(street,charindex(' ',street)+1,6) from #t 	0.00895335994667952
22141377	7285	mysql query: get new customers in the month	select customer_id , min(date) as min_date from thetable group by customer_id  having min_date>=<the desired date> 	8.6114946353146e-05
22141462	35179	how to remove null value from distinct column of a table in sql?	select distinct city from billingsystem  where city is not null 	0
22143853	4821	mysql query for getting field value as count	select message_pairs.*,             count(all_messages.id) as unread_msg_count        from all_messages             right join message_pairs                  on message_pairs.id = all_messages.pair_id       where is_read = 0      group by             message_pairs.*; 	0.00875791626655683
22144017	6770	insert two select queries in a single row	select  a.id ,a.[year],vala,valb from( select id ,[year],sum(total_volume)/ (count(distinct(month))*7) vala from tablea   group by id,[year]) a inner join (select id,[year],sum(total_volume)/(count(distinct(month))*5) valb from tablea   where weekday not in ('friday','saturday')  group by station_id,[year]) b on a.id=b.id and a.[year]=b.[year] 	0.000744711530855435
22145241	18285	join query: how to return results from join table2 as an array in the table1	select articles.article_id, `title`, `text`, group_concat(tags.tag_name )as tg_name from `articles`  left join `tags`  on articles.article_id = tags.article_id  where articles.author_id = 150342 group by tags.article_id 	0.00306731218267135
22145680	2134	mysql query for prices with three or more decimal places	select field_name from table_name where length(substr(column_name,instr(column_name,"."))) >3 	0.0594492358677536
22146898	36280	mysql date range manipulation	select sum(datediff(least(to_date, date('2014-03-01')), greatest(from_date, '2014-02-01'))) as days from table t where to_date >= date('2014-02-01') and from_date < date('2014-03-01'); 	0.0212244790717125
22147117	39379	mysql group by row	select case          when pay_code = 'ot' then 'ot'          when pay_code in ('vacp','pers') then 'paid shrink'          when pay_code = 'reg' then 'reg'          when pay_code in ('vto','loa','ber') then 'unpaid shrink'          else 'unknown'        end as paycode_2        ,year(date), week(date,4), sum(hours), site, pay_code from table group by paycode_2, pay_code, site, year(date), week(date,4) 	0.0517772629859189
22149270	8928	mysql query counting and assigning constants based on ranges	select id_inviter, count (*) as cnt,  case when count (*) <20 then 'imagea.gif'  when count (*) <30then 'imageb.gif' else 'imagec.gif' end as image,  case  when count (*) <20 then 'x'  when count (*) <30 then 'y' else 'z' end as reward from members where dt_activate>=$dt_start and dt_activate<=$dt_end group by id_inviter having cnt>=10 	0.00524668296496376
22150763	23307	select dates inside current month sql	select * from table1 where   startdate >= dateadd(month, datediff(month, 0, getdate()), 0)  and startdate < dateadd(month, 1+datediff(month, 0, getdate()), 0) 	0.000230948648082116
22152809	12382	creating a new table using a synonym in sql server	select into 	0.132101921928487
22155667	38194	query to create view with concatenated column from multiple tables	select a.id, a.name, stuff(     (       select cast(',' as varchar(max)) + b.course       from b       where b.pid = a.id       order by b.course       for xml path('')     ), 1, 1, '') as course, stuff(     (       select cast(',' as varchar(max)) + c.nick       from c       where c.pid = a.id       order by c.nick       for xml path('')     ), 1, 1, '') as nick from a 	0.00153975150841465
22156281	35617	combine two different unrelated sql queries( returning single column results) into one query result with two columns	select    (       select sum(marksobtained)         from tbanswers where qid in (           select qid from tbquestions where examid = 2       )    ) as marksobtained,    (        select sum(marks)           from tbquestions where examid = 2    ) as maxmarks 	0
22156612	8126	how can i select specific columns from 3 different tables, by their primary key	select      c.fname, c.lname, p.productname, o.quantity from orders o join customers c on o.customerid = c.customerid join products p on p.productid = o.productionid where o.orderid = @orderid 	0
22157749	3284	how to find unique url calls per date?	select convert(date, t.date, 101) date,     count(t.url) [total calls],     count(distinct t.url) [unique calls] from table t group by convert(date, t.date, 101) 	0.000295051891215264
22158197	18889	how can i tell which order tables will lock in h2 database?	select * from table_a where ... for update; select * from table_b where ... for update; 	0.744240700373089
22159046	38470	query returning values with set column to value or null	select p1.*, p2.price as null_price, p3.price as user_price from `products` p1  join `prices` p2 on p1.id = p2.product_id and `p2.user_id` is null left join `prices` p3 on p1.id = p3.product_id and `p3.user_id` = 3 	0.0163296491771605
22159444	17765	data in column instead of row	select p.program_title,  listagg(m.module_title,',') within group (order by m.module_id) as module_title from program_module pm inner join program p on pm.program_id = p.program_id inner join module m on pm.module_id = m.module_id group by p.program_title 	0.000838929840788514
22161766	13815	left joining 2 of the same table with count	select a.month, a.totalcountsub, b.totalcountcust from (   select datepart(mm,starttime) as month, count(*) totalcountsub   from data    where usertype='subscriber'   group by datepart(mm,starttime)   having count(*) > 1  ) a  inner join (    select datepart(mm,starttime) as month, count(*) totalcountcust    from data    where usertype='customer'    group by datepart(mm,starttime)    having count(*) > 1  ) b  on a.month = b.month order by a.month asc 	0.000676121863882677
22162770	40693	mysql select the rows having same column value	select     a.* from     employee a     join employee b         on a.empsalary = b.empsalary         and a.empid != b.empid 	6.64909209949069e-05
22162798	6180	sql server group by show only first match	select [name],[phone]  from (       select *,row_number() over (partition by phone order by (select null)) as rn       from table1       ) as t where rn = 1 offset n rows 	0.000551868138962065
22165054	37107	how to check column value null or having value	select productname,unitprice*(unitsinstock+ifnull(unitsonorder,0)) from products 	0.0017449486776014
22165989	4527	combine select statements with aggregates in each statement	select a.localcustomerid, b.sales2013, b.salesyeartodate, a.[sum of orderseuro] from ( select customerlocal.localcustomerid,         sum(orders.orderseuro) as 'sum of orderseuro' from mydatabase.dbo.customerlocal customerlocal, copelanddatabase.dbo.orders orders where orders.localcustomerid = customerlocal.localcustomerid and orders.plant =    customerlocal.plant and ((customerlocal.intextcust in ('e'))) group by customerlocal.localcustomerid ) a join ( select sales.localcustomerid,  sum (case when sales.dateofinvoice between{ts '2012-10-01 00:00:00'} and {ts '2013-09-30 00:00:00'}  then sales.saleseuro else 0 end) as sales2013 , sum (case when sales.dateofinvoice >= {ts '2013-10-01 00:00:00'}   then sales.saleseuro else 0 end) as salesyeartodate from "dbo"."sales" where sales.dateofinvoice >= {ts '2012-10-01 00:00:00'} group by sales.localcustomerid ) b on a.localcustomerid=b.localcustomerid order by a.localcustomerid 	0.0457411613346524
22168746	25556	i want to get attended event of particular lead	select     e.* from     eventtbl as e     join event_attendance as ea on (e.event_id = ea.event_id)     join user_lead as ul on (ul.user_id = ea.user_id) where     ul.user_id = 123; 	0.00100074773692358
22169682	10636	oracle 11g: how to fetch column type from view?	select * from all_tab_columns@abc.world where table_name='viewname' 	0.00330974399111836
22169755	15132	mysql tables have two foreign keys from another same table	select inv.invoice_id, us1.user_name as invoice_to_user_name, us1.user_email as invoice_to_user_email, us1.user_address as invoice_to_user_address, us2.user_name as invoice_by_user_name, us2.user_email as invoice_by_user_email, us2.user_address as invoice_by_user_address from [invoice] inv inner join [user] us1 on inv.invoice_to_user_id = us1.user_id inner join [user] us2 on inv.invoice_by_user_id = us2.user_id 	0
22170284	27615	sqlite select except where single column has duplicate	select r.breakout_id, r.case_id, r.stage_id, r.chart_id,  s.stage1_choice,s.user_id,max(w.stage1),w.user_id from results as r, submissions as s, switch as w where r.breakout_id = '1' and s.breakout_id = '1' and w.breakout_id = '1' and s.user_id = w.user_id  and w.case_id = r.case_id and s.case_id = r.case_id and  s.stage1_choice is not null  group by r.breakout_id, r.case_id, r.stage_id, r.chart_id,  s.stage1_choice,s.user_id,w.user_id order by w.user_id; 	0.000834695750623312
22170747	29524	connecting table with organizations with person, but connect only first person associated with organization	select org.org_id,       org.orgname as 'nazwa klienta',       isnull(org.sic,'') as 'nazwa skrócona',       isnull( (org.address1+', '+ org.zip+ ', ' + org.city),'') as 'adres',       person.lastname as 'nazwisko',       person.firstname as 'imię',       isnull(org.industry,'') as 'branża',       isnull(org.comments,'') as 'dostarczane wyroby i usługi'  from org  inner join (select org_id, lastname, firstname from person             where exists (                 select min(person.org_id)                  from   person                 where  person.org_id = org.org_id) ) p   on org.org_id = p.org_id where org.orgname is not null 	9.48703828319208e-05
22171118	36841	calculate most populare newspaper for every person	select p.name,n.title from (   select o.person_id, o.newspaper_id,          rank() over(partition by person_id order by cnt desc) as rnk   from (     select o.person_id, o.newspaper_id,count(*) as cnt     from orders o     group by 1,2) o) r   join persons p on (r.person_id = p.id)   join newspapers n on (r.newspaper_id = n.id) where r.rnk=1 	0.000260564562795277
22171536	39317	postgresql division by zero when ordering column	select wavelength,         (lead(wavelength) over (order by wavelength) - wavelength)/        (case when (lead(reflectance) over (order by wavelength) - reflectance) = o then 1         else (lead(reflectance) over (order by wavelength) - reflectance) end)        as reflectance from  grassland1 	0.345439634949331
22172282	34537	count file status time in mysql	select a.fileid,  sum(time_to_sec(timediff(coalesce(b.t,utc_timestamp),a.t))/60) as filetimeinmin     from filelog a     left join filelog b     on a.fileid = b.fileid     and b.status in ('onhold', 'complete')     and b.t > a.t     left join filelog c on a.fileid = c.fileid      and c.t > a.t and c.t < b.t where a.status = 'inprogress' and c.t is null     group by a.fileid; 	0.0131969257895319
22173290	7156	possible self join to get id of all matching columns	select *  from mytable  where id in (select id              from mytable              where (name = 'product' and value = 'foobar')                 or (name = 'colour'  and value = 'blue'  )              group by id              having count(*) = 2) 	0
22173906	17467	mysql count time spent on site by user	select userid,sum(res) result from (select t1.userid, case when t1.userid = t2.userid then t2.timestamp - t1.timestamp else 0 end res  from  table1 t1 left outer join table1 t2 on t1.id = t2.id - 1)tab1 group by userid; 	0.021281722169607
22176611	123	how can i make an sql query that handles missing records?	select customerid, max(age), max(height) from   (   select customerid, age, 0 as height from ages   union   select customerid, 0 as age, height from heights  ) s group by customerid; 	0.118291617846256
22176664	3203	turning certain rows into columns in sql server	select      yourtable.* , service, handling, freight from yourtable     inner join  (     select customerid, paymentid, claimnum,              [1085] as service, [486] as freight, [559] as handling     from              (select customerid, paymentid, claimnum, deductionid, amount from yourtable) t                 pivot          (sum (amount) for deductionid in ([1085],[486],[559]))p         ) pt      on yourtable.customerid = pt.customerid     and yourtable.paymentid = pt.paymentid     and yourtable.claimnum = pt.claimnum where itemid is not null 	0
22178259	36668	how to get result array in php	select name , sum(substring_index(amount, '$', -1)) amount ,count(*) counts    from fruits    group by name    where date_of_tr= '$date'   order by amount desc 	0.00719166996578469
22179606	38319	sql server backup report	select      [server_name] = a.server_name,      [database_name] = a.database_name,      [last_backup]      = max(a.backup_finish_date),       [last_full_backup] = max(case when a.type='d'                                      then a.backup_finish_date else null end),     [last_diff_backup] = max(case when a.type='i'                                      then a.backup_finish_date else null end),     [last_log_backup]  = max(case when a.type='l'                                      then a.backup_finish_date else null end),     [backup_set] = b.name,     [days_since_last_backup] = datediff(d,(max(a.backup_finish_date)),getdate()) from msdb.dbo.backupset as a inner join msdb.dbo.backupset as b on a.backup_set_id = b.backup_set_id group by a.database_name, a.server_name order by database_name 	0.790835143717815
22180603	19600	in clause usage for date fields in oracle sql	select * from table_name where date(req_date) in (date '2014-01-12', date '2014-02-14', date '2014-03-17'); 	0.584568431279274
22182542	41119	selecting the count of rows on second table based on foreign key in mysql	select a.album_id, a.album_name, a.album_preview, a.album_owner, a.album_time, a.album_access, count(i.*) as images  from imgzer_albums a  left join imgzer_images i      on a.album_id = i.album_id  where album_owner = some_value group by a.album_id 	0
22182921	15379	sql concat columns from different tables	select c.id, concat(c.fname, p.lname) as full_name from parent p inner join child c on p.id = c.parent_id 	0.000738471576286042
22183533	23566	getting a row based on a certain condition in sql self-join	select t1.id, t1.pid, t1.type from   tablename t1 left join tablename t2   on t1.pid = t2.pid and t2.type=3 where   t1.type=1 and   t2.type is null 	0
22184127	40358	create a view with one column containing the result of another select	select job, rel, phase, avg(tcount) as avgcount, (select count(*) from dbo.wfr) as numframes, (select count(*) from dbo.wfr)/avg(tcount) as remain_days from (select   vwframe_totals.job   ,vwframe_totals.rel   ,vwframe_totals.phase   ,vwframe_totals.[day]   ,count(vwframe_totals.fr_id) as tcount from   vwframe_totals   group by job,rel,phase,day) as counts group by job, rel, phase 	5.26486136660156e-05
22184393	3240	php: prevent item from being displayed more than once	select * from table_name group by model, color 	8.8415402045015e-05
22186415	9678	sql inner join most recent row of xref table	select t.id, t.name, s.name     from ticket t join (     select ticketid, statusid, row_number() over             (partition by ticketid order by createddate desc) rn     from ticketstatusxref ) x on x.ticketid=t.ticketid and rn=1 join status s on x.statusid=s.statusid 	0.000475864947239679
22187707	607	show new field from count result in other table	select p.id, p.name, p.cnt  from tbl_people p inner join    (select personid, count(1) as cnt    from tbl_vehicle    where vehicle_name = 'car'    group by personid) v on v.personid = p.id order by p.name 	0
22188631	35017	merging multiple columns in oracle based on row value	select column_name "name",        replace(replace(nullable, 'n', 'not null'), 'y') "null?",        (data_type || '(' || case          when data_type = 'number' then           data_precision          else           data_length        end || ')') "type"   from user_tab_cols  where column_name = 'courseid'     or column_name = 'course_name'     or column_name = 'student_count'; 	0
22190985	19355	mysql query to retrieve data from two tables even no data found and unique column in both tables	select menu.menu_id, menu.menu_desc, role.role_id, role.rights from menu left outer join role on menu.menu_id=role.menu_id order by menu.menu_id 	0
22192464	19399	sql query to pick all rows from one table and selective rows from table 2	select col1 as col1, col2 as col2.... from table1 union all select col1 as col1, col2 as col2.... from table2 where  datediff(week, startdate,getdate()) <= 2 	0
22193037	27559	sql calculating a percentage for a group	select  [result] , count( * ) as total,       (1.0 * count( * ) / (             select count( * )             from[my_table]             )        ) * 100 as  '%'  from [my_table] where  ([result]!='success')  group by  [result] 	0.0368699645508348
22193838	22948	is there a way to create a view selecting the greatest line in table?	select x.*   from play y   join play_summary s     on s.play_id = y.id    join profile f     on f.id = s.profile_id   left   join play_summary x     on x.play_id = s.play_id    and x.tot < y.tot  where x.play_id is null; 	0.00172683822079553
22194331	38268	how to do exact pattern match in query string	select * from mytable where concat(firstname, '', lastname) like '%".$fname.$lname."%'  or (firstname like '%".$fname ."%' or lastname like '%". $lname ."%') 	0.0345155362683112
22196454	31321	find total time spent by user on the website.	select ..., row.one_value - row.second_value as row.somecolumn, ... from foo ... 	0
22197341	36975	mysql query: get totals from two non-related tables	select sum(atual),     (select sum(budget) from table2 where user=1) from table1 where user=1 	0.00029074765270636
22198478	37974	mysql: get the totals from two columns organised by category	select t3.id, t3.name, sum(actual) as actual, sum(budget) as budget from ((select category_id, sum(actual) as actual, null as budget        from table1        where user = 1        group by category_id       ) union all       (select category_id, null as actual, sum(budget) as budget        from table2        where user = 1        group by category_id       )      ) ab join      table3 t3      on ab.category_id = t3.id group by t3.id, t3.name; 	0
22201059	40658	select sum of top 10 rows grouped by location column	select sum(units), mytable.* from mytable group by location order by sum(units) desc limit 10 	0
22201067	8070	get values from different tables in one query	select table1.*, table1_record.* from table1 inner join table1_records on table1.id = table1_records.table_id 	0
22202429	26229	select non-null columns from a row as a list	select  x.field from yourtable t cross apply  (     values         (t.field1),         (t.field2),         (t.field3),         (t.field4) ) x (field); where t.id = 1 and field is not null 	0
22204164	16122	selecting records from foreign key table where multiple items match the condition	select g.contentid from ( select pt.contentid, pt.tagid from papertags as pt where pt.tagid in (15, 18) group by pt.contentid, pt.tagid ) as g group by g.contentid having count(*) = 2 	0
22204216	26719	mysql union losing table names	select    a.lastname ,    b.busname  from clients as a  inner join     busclients as b    on b.agent_id = a.agent_id  where a.agent_id = $agent_id        and (a.lastname like '$q%' or b.busname like '$q%') 	0.039821497840414
22205438	21805	mysql select: replace parent_id column with name	select a.id, b.name parentname, a.name from projects a left join projects b     on a.parent_id = b.id 	0.0414370037400158
22206609	30206	how to limit mysql query output of specific column to 100 characters while fully displaying remaining columns?	select id, title, left(body, 100) as body from $tablename order by id desc limit $limit 	0.000156278070666609
22207397	26473	ms sql server 2008 - finding max value from a subset of results	select * from od where orderno in(select max(orderno), part from od where type = 'p' group by part) 	0.00048056677475316
22207709	32094	oracle sql pivot with multiple sum columns	select * from (   select country, month, metric1 metric, 'metric1' metric_name   from my_table_for_pivot   union all   select country, month, metric2 metric, 'metric2' metric_name   from my_table_for_pivot ) pivot (   sum(metric) as month for month in ('01-jan-2013' as jan_13,  '01-feb-2013' as feb_13,  '01-mar-2013' as mar_13)) where country = 'usa' ; 	0.167846115483975
22209899	33485	return true if tuple has a value?	select case when name1 = 'jeo' or name2 = 'jeo' then 'true' else 'false' end from tablename; 	0.00154276396727968
22211105	39508	sql script transaction log to table report	select customerid       ,count(case when transactiontype     = 'esl'                 and transactionlocation = 'wbee' then 1 else null end) as wbeeesl       ,count(case when transactiontype     = 'lote'                 and transactionlocation = 'wbee' then 1 else null end) as wbelote       ,count(case when transactiontype     = 'esl'                 and transactionlocation = 'vale' then 1 else null end) as valeesl       ,count(case when transactiontype     = 'lote'                 and transactionlocation = 'vale' then 1 else null end) as valelote from table_name group by customerid 	0.387730714652272
22211205	5435	how to add two columns from two separate ms sql queries with different number of rows	select productid, (inv.inventory + s.sales) as balanceinventory from (      select  productid, inventory     from [table]     where xxx ) inv left outer join (    select  productid, sales      from [table]     where xxx ) s on (s.productid = inv.productid) 	0
22214474	4602	how to generate uniquerowdate number for a datecolumn i?	select concat(replace(cast(product as date), '-', ''),               row_number() over(partition by product order by product)) as prod_id   from tbl 	0.00957108044122657
22215869	34814	select distinct using a join	select cid,cname,tid from colors c left join tags t on t.tname = c.cname; group by c.cid 	0.247833981560658
22216419	34243	return rows where column matches all values in a set	select group_concat(`type`) as types,user_id  from users  where `type` in('b','c')  group by user_id  having find_in_set('b',types)>0 && find_in_set('c',types)>0 	0
22219244	13845	mysql parent record have multiple records in child table show in one column	select user_name,group_concat(service_name) from user  join servies on user.user_id=servies.user_id group by user_name 	0
22220335	33127	mysql if statment on same row across a group by statment	select      table1.cartarticleid,     max(if(table2.testvalue = 1, 1, null)) as lol,     max(if(table2.testvalue = 3, 1, null)) as lol3 from     table1         inner join     table2 on table1.cartarticleid = table2.cartarticle_id group by cartarticleid 	0.00484962313726541
22221159	12139	count duplicate records in mysql	select t.customer_id,s.duplicate_count from     (     select customer_id,count(customer_id) as duplicate_count     from yourtable group by customer_id     having (duplicate_count > 0)     ) as s join yourtable on s.customer_id = t.customer_id 	0.00299366486919349
22221229	15090	mysql query from two tables with multiple joining	select items.*, c1.cat_name, c2.cat_name, c3.cat_name, c4.cat_name from items left join category as c1 on c1.cat_id = items.field1 left join category as c2 on c2.cat_id = items.field1 left join category as c3 on c3.cat_id = items.field1 left join category as c4 on c4.cat_id = items.field1; 	0.00451896549232747
22221925	16097	get id of max value in group	select `id`  from `mytable`  where (`group_id`, `time`) in (   select `group_id`, max(`time`) as `time`    from `mytable`   group by `group_id` ) 	7.87051476632918e-05
22222014	16758	fetch records from mysql by splicting the value of the column "122-362-25-36"	select * from table where id in (select replace('122-362-25-36','-','') as id); 	0
22222225	26895	sql outer join 2 tables	select     p.id_product,     pm.price from comp_product p left outer join comp_product_marchand pm     on p.id_product = pm.id_product     and id_marchand = 4 	0.604847777332776
22222583	5894	adding two subqueries to produce third column	select t.*,t.district1 + t.district2  `new_col` from ( select d.id, concat(d.disease, '( ' ,d.disease_nepali, ' ) ') as disease,  ifnull((select patients.d_o_m+patients.d_o_f from patients where clinic = 22 and     patients.disease = p.disease),0) as `district1` ,  ifnull((select patients.d_o_m+patients.d_o_f from patients where clinic = 21 and disease = p.disease),0) as `district2`  from diseases d left join patients p on  (d.id = p.disease and p.district = 9 and p.status = 1 and p.report_date like '2014-03%')  group by disease ) t 	0.0450852595372189
22222840	36010	how to query mysql if data in one field look like 32;13;3;33 and the condition is where 3	select * from table where concat(';',ids,';') like '%;3;%' 	0.0271696689153997
22226543	38044	move one row value to another sql	select t1.dbname, t1.api50, t2.countervalue from mytable t1 inner join mytable t2 on t1.primarykey -1 = t2.primarykey where t1.dbname is not null 	5.41167961423979e-05
22226991	38068	sql - choose wich field to select	select case            when customname is not null and customname <> '' then               customname            else               defaultname          end as customername     from mytable 	0.0246250313000841
22228655	11686	mysql select max value from derived values grouped by field	select playerid, sum( score1 + score2 ) from `test` group by playerid order by 2 desc limit 1 	0
22228799	27445	make unioned queries show on the same row	select     t.accountnum,     t.department,     t.division,     sum(isnull(t.jan, 0)) as jan,     sum(isnull(t.feb, 0)) as feb from (     select distinct          ledgertable.accountnum,         department,          division,          [gl description],          [1] as jan,         [2] as feb     from          #tempfeb     join ledgertable          on ledgertable.accountname = #tempfeb.[gl description]     union     select distinct          ledgertable.accountnum,         department,          division,          [gl description],          [1] as jan,         [2] as feb     from          #tempjan      join ledgertable          on ledgertable.accountname = #tempjan.[gl description] ) t group by     t.accountnum,     t.department,     t.division 	0.000565898885314219
22228838	16001	calculating 'minutes' between two two date/time columns	select index_id        ,start_time        ,end_time       ,datediff(minute, start_time,end_time) as  time_to_complete from table_name with (nolock) order by start_time desc 	0
22229811	25202	mysql use stored procedure results multiple times within a query	select * from (     select customers.*,             totalorders (customers.id) as total       from customers ) as t   where total >0  order by         total  limit 10 	0.443499400835372
22230369	33910	using concat in match against	select  produse.*, variante.*, categorii.categorie  from produse left join variante on variante.id_produs=produse.id_produs left join categorii on categorii.id_categorie=produse.id_categorie left join produse_valori on produse_valori.id_produs=produse.id_produs where produse.activ=1  and (     match(produse.produs) against('.$keyword.' in boolean mode)      or match(variante.varianta_cod, variante.nume_varianta) against('.$keyword.' in boolean mode)      or match(categorii.categorie) against('.$keyword.' in boolean mode)  ) group by produse.id_produs 	0.282053028803271
22230510	15456	sql subquery count with conditions	select users.id,     game.id,     badge.id,     users_badges.created as badge_created,    count(gamesbefore.id)_games  from badges     inner join users_badges                on badges.id = users_badges.badge_id     inner join users                on users_badges.user_id = users.id     inner join games as gamesbefore               on users.id = game.user_id                and gamesbefore.created <= users_badges.created where users.id = 1 group by user.id, badge.id 	0.712062081820599
22234090	12565	how to get the first id with sql	select id from times where date='2014-03-07' order by id asc limit 1 	0.000116957974939912
22234112	21118	combining two sql queries to get all from one table with where clause and only count of occurrences from another table	select    u.pid,   u.experience,   u.lastlogin,   u.won,   u.lost,   u.tied,   u.product1_count,   u.product2_count,   u.product3_count,   u.ad_free,   u.codename,   u.fb_uid,   u.wsbalance,   u.best_game_score,   u.best_word_score,   u.best_move_score,   u.mw_played ,   count(g.sid) as c   from   `user` u   left join games1 g   on (     (g.p1_uid = u.pid     or g.p2_uid = u.pid     or g.p3_uid = u.pid     or g.p4_uid = u.pid) and  g.active = 1    )  where (pid > 9      and (( '. $servertime .' - u.lastlogin < 1209600)        or (u.ad_free + u.product1_count + u.product2_count + u.product3_count + u.product4_count) > 0)   )    group by u.pid 	0
22234431	14463	mysql group by count by min length	select   categoryid,   substring_index(group_concat(name order by length(name)), ',', 1) as s_name,   count(name) as c, from   posts  where   categoryid=1101 and language=1  group by categoryid  order by c asc; 	0.092433887495133
22236508	33869	how does one detect a non-contiguous number column in a mysql query?	select t1.checkno,t1.id,        if(@lastcheckno is null or @lastcheckno = t1.checkno - 1,'','*') as outoforder,        @lastcheckno := t1.checkno from (select * from `table` order by checkno) t1,(select @lastcheckno := null)variable 	0.00855458304183244
22236530	13466	postgres output id of dup rows between 2 tables	select m.id from master m, master_staging ms where m.email= ms.email and m.firstname = ms.firstname and m.lastname = ms.lastname 	0
22237731	33777	getting the number of rows sharing the same id in separate mysql tables	select forums.forum_id, forums.name, forums.description, (select count(forum_threads.thread_id) from forum_threads where forum_threads.forum_id = forums.forum_id)  as num_threads, (select count(forum_posts.post_id) from forum_posts where forum_posts.forum_id = forums.forum_id)  as num_posts from forums where hidden = 0 order by ordering 	0
22238528	39309	sql - select only one value from multiple fields	select ltrim(rtrim(col1 + col2 + col3 + col4)) 	0
22239313	13655	in php-mysql, how can i union the results of the sql query in a cell of the result table?	select code_en.code, code_co.disease_co, code_en.disease_en , hx.family,    hx.personal, note.note, inclusion.inclusion, exclusion.exclusion, ds.ds_content,    subject.icd_category, subject.group_code, group_concat(im.im_content) as im_content   from code_en   left join subject on code_en.code = subject.code   left join note on code_en.code = note.code   left join im on code_en.code = im.code   where code_en.code = '".$code."'" 	7.69714590281112e-05
22241512	37177	sql statement to rank records depending on specific values	select <fields that matter>, (case  when tab1.program_type_id = applications.program_type_id then 490 when  tab1.postal=    applications.postal then 1000 end )from tab1, applications where  tab1.a = applications.a or tab1.b = applications.b 	8.3628366356728e-05
22242699	33569	sql server - ordering by running total for week	select t.descr,        t.monday,        t.tuesday,        t.wednesday,        t.thursday,        t.friday from (      ) as t order by t.monday + t.tuesday + t.wednesday + t.thursday + t.friday desc 	0.0038558125174001
22243344	17073	update multiple tables at a time in mysql	select concat('update ', table_name, ' set col = "whatever" where condition = true;') into outfile '/tmp/my_update.sql' from information_schema.tables t where t.table_schema = 'your_database_name'; source '/tmp/my_update.sql'; 	0.00689242894674991
22243914	18373	use the results of sum in the same query	select  business_period, sum(transaction.transaction_value) as total_transaction_value, sum(transaction.loss_value) as total_loss_value, (sum(transaction.transaction_value) - sum(transaction.loss_value)) as net_value from transaction group by business_period 	0.00489055475419797
22245128	22672	retrieve datas from database as verital	select   city_id,    max(case cat_id when 1 then value else 0 end) as category_1,   max(case cat_id when 2 then value else 0 end) as category_2 from   my_table group by   city_id 	0.00100546856257887
22245573	5359	how to select uncommitted rows only in sql server?	select * from t with (snapshot) except select * from t with (readcommitted, readpast) 	0.0106831814230471
22246651	26110	oracle: table with all constraints	select a.table_name, a.column_name, a.constraint_name, c.owner,         c.r_owner, c_pk.table_name r_table_name, c_pk.constraint_name r_pk   from all_cons_columns a   join all_constraints c on a.owner = c.owner                         and a.constraint_name = c.constraint_name   join all_constraints c_pk on c.r_owner = c_pk.owner                            and c.r_constraint_name = c_pk.constraint_name  where c.constraint_type = 'r'    and a.table_name = :tablename 	0.00851266696487173
22247023	2073	set flag if reference exist in other table	select *, (select exists(             select 1 from register r where m.id = r.module_id limit 1         ) ) as active     from module m; 	0.00250452229845577
22250526	30972	mysql - exclude conflicting date ranges	select `id`, `start`, `end` from (   select     r1.id   , r1.start   , r1.end   , count(distinct r2.id) as "conflicts"   , md5(group_concat(distinct r2.id order by r2.id)) as "group_chksum"   from range_table as r1   left join range_table as r2     on (r1.end > r2.start and r1.start < r2.end)   group by r1.id ) as tmp group by group_chksum ; 	0.00102686204526241
22251322	34106	how to select distinct rows in 2 columns and sort both individually	select distinct car_year from cars order by car_year select distinct  car_make  from cars order by car_make 	5.29911044344757e-05
22251823	28609	codeigniter - get related entries	select     table1.*,     group_concat(table2.image_name separator ', ') as image_name from table1 left join table2 on table1.id = table2.user_id group by table1.id; 	0.000260896107640297
22251883	8063	how can i create a mysql query to include all of this information?	select s.name, p.first_name, p.last_name, c.title, pnk.next_of_kin_relation,                 pnk.next_of_kin_first_name, pnk.next_of_kin_last_name, pnk.next_of_kin_telephone,                 pnk.next_of_kin_alt_telephone, pnk.other_kin_relation, pnk.other_kin_first_name,                  pnk.other_kin_last_name, pnk.other_kin_telephone, pnk.other_kin_alt_telephone             from personnel p                 left join personnel_next_of_kin pnk on pnk.personnel_id = p.personnel_id                 left join ship s on s.ship_id = p.currently_serving_ship_id                 left join personnel_key_info pk on pk.personnel_id = p.personnel_id                 left join crew_position_title c on c.crew_pos_id = p.personnel_id             where p.currently_serving_ship_id is not null 	0.022370968721018
22253965	38169	how to convert column values to column names in teradata?	select    name,    max(case when subjects = 'math' then 'y' else 'n' end) as math,    max(case when subjects = 'science' then 'y' else 'n' end) as science,    max(case when subjects = 'english' then 'y' else 'n' end) as english from tab group by name 	0.000265046933674817
22254995	20541	mysql using variables in select subquery	select sql_no_cache @num := @num + 1 as `#`, l.* from (         select s.* from (         select         @num := 0 as 'label 1',         '' as 'label 2',         '' as 'label 3'         union         select concat(users.first_name, ' ',users.last_name),u.type, u.date, u.description from     (             select o2.* from              (select @period:=31) as o1              join (                select c.user_id as uguid, 'type1' as type, c.date_start as date, c.description from table1 c                 where deleted = 0                  and date_start > subdate(current_date,@period)               union                 ...              ) as o2        ) as u    ) as l 	0.740173437912037
22257492	18518	how to add an extra row at end of query with value of (previousrowcola + 1) in mysql?	select (@rank:=@rank+1) as 'value' from mytable a     inner join (select @rank :=0) b union all select (@rank+1); 	0
22257881	41071	sql query to get the sum of all column values in the last row in access table	select  models, parts from    your_table union select  'total' as models, sum(parts) as parts from your_table 	0
22258086	9096	duplicate data when joining sql pivot table with columns from other tables	select  r.resourceid as resourceid,  r.resourcename as resourcename, p.projectid as projectid, p.projectnumber as projectnumber, p.projectname as projectname, p.projectsystem as projectsystem, p.projectmanager as projectmanager, a.[may 2014], a.[june 2014] from    projects p, resources r  join (   select * from allocation a     pivot (sum(allocationvalue) for allocationmonth in ([may 2014], [june 2014])) pvt ) a on (r.resourceid = a.resourceid) order by resourceid where p.projectid = a.projectid 	0
22258997	11507	how can i exclude guids from a select distinct without listing all other columns in a table?	select * into #temp from table alter table #temp drop column id alter table #temp drop column msrepl_tran_version select distinct * from #temp 	0
22260097	32955	how do i set a variable as the return value of an oracle sql statement?	select case    when count(*) > 0 then 1    else 0 end  from times where ordernumber = '123456789' and times.stopsequence = '1' ; 	0.0131561396598872
22260108	873	no future date sql query	select cs.cust_id, oh.order_date,         case         when datediff(dd,oh.order_date, getdate()) < 0 then 'future date'         when datediff(dd,oh.order_date, getdate()) < 14 then 'less than 14 days'         when datediff(dd,oh.order_date, getdate()) < 30 then 'less than 30 days'         end      as 'orderage'     from customers as cs     inner join order_headers as oh on oh.cust_id = cs.cust_id     order by cust_id, order_date; 	0.0499306987934868
22261802	18690	how to concat two columns	select * from crosstab('select  concat(u.firstname,'' '',u.lastname) as name') 	0.0065744288735089
22261844	11283	mysql multiple order by trouble self joining from the same table	select c.manufactuer,        c.model,        c.year,        s.year as most_recent_year from cars c inner join (   select m.manufactuer, max(m.year) year   from cars as m    group by m.manufactuer   order by year desc limit 3 ) s on c.manufactuer=s.manufactuer  order by s.year desc, c.year desc 	0.0141586623988033
22261850	11352	sql union query - multiple tables	select id, name, 'projects' as table_name  from projects where name like '%querystriong%' union select id, name, 'documents' as table_name from documents where name like '%querystriong%' 	0.331417940302051
22263075	32654	mysql where clause - age greater/less than	select count(userid) from login  where 17 < year(date_sub(now(), interval to_days(profile_birthdate) day))      and 46 > year(date_sub(now(), interval to_days(profile_birthdate) day)); 	0.631003750480573
22263762	6370	mysql adding columns together	select column1,sum(column2) from table group by column1 	0.0433232381450845
22264996	19556	storing game player progress id's in database - comma-delimited data in mysql vs normalized mysql records (regarding server performance)	select 1 from achievements where playerid = @playerid and achievementid = @achievementid 	0.0367541199409399
22267083	434	select statement to get 2 value from column in a table	select unsold.total, paid.total  from (   select count(auction.auctionid) as total   from auction    inner join item on auction.itemid = item.itemid    where (auction.status = 'unsold') and (item.sellerid = 201)   group by auction.status ) as unsold, (   select count(bid.bidid) as total   from bid   where (bid.status = 'paid')   group by bid.status ) as paid 	0
22269862	6085	mysql many to many select only fixed row at joined row	select     id_conversation, conversation_name from       conversation_user_involved inner join conversation on (id_conversation = conversation.id) where      id_user in (1, 2) group by   id_conversation having     count(id_conversation) = 2 	0
22270091	24279	cumulative value in sql	select columntitle as months,        sum(select cellcontent            from workflow_customformcolumnsdata as cd            where (customformcolumnid = workflow_customformcolumns.id)               and (rownumber = 1)) +        sum(select cellcontent            from workflow_customformcolumnsdata as cd            where (customformcolumnid = workflow_customformcolumns.id)              and (rownumber = 2)) from workflow_customformcolumns where (customformid = @customform) and (columnnumber <> 1) group by columntitle 	0.0159688929972119
22273948	3386	i want to select a specific data, but query result gives all column in sqlite	select country_code  from countries, country_small_info  where countries.id = country_small_info.id and countries.country_name = 'belgium' 	0.0017149029268023
22274000	40997	mysql, single table multiple columns	select e.id, e.firstname, e.lastname,ee.firstname, ee.lastname from employees e join employees ee on e.reportsto=ee.id 	0.00189906442656188
22274095	22426	sql select if they have more than once	select a.name, b.color, count(*) 'color count'  from names a join colors b on a.id = b.id group by a.id, b.color having count(*)>1 	0.000895957399289723
22274122	14043	mysql return names of columns that are not 0 in a certain row	select  case when ps0101>0 then 'ps0101' else '' end as column1,  case when ps0102>0 then 'ps0102' else '' end as column2, case when ps0103>0 then 'ps0103' else '' end as column3 from table_name where id = 1; 	0
22274229	11920	sql query to retrieve below average score	select student.studentid, student.firstname, student.lastname, grade.grade, subjects.subjectname from student inner join grade on grade.studentid=student.studentid  inner join subjects on grade.subjectid=subjects.subjectid where grade.grade<50; select student.studentid, student.firstname, student.lastname, avg(grade.grade) as average  from student inner join grade on grade.studentid=student.studentid  group by grade.studentid; select subjects.subjectid, subjects.subjectname, avg(grade.grade) as average  from subjects inner join grade on grade.subjectid=subjects.subjectid  group by grade.subjectid; 	0.00116358975787543
22275215	38536	sql server select data excluding junction table	select *    from volunteertable v  where not exists(select 1                      from junctiontable j                     where j.volunteername = v.volunteername                       and j.trialid = @trialid) 	0.010979825279021
22275703	29669	how to get last year's date range?	select * from orders where dispatch_date >= makedate(year(now()) - 1, 1)   and dispatch_date < makedate(year(now()), 1)   	0
22276790	40670	mysql cumulative sum grouped by date	select    date(e.date) as e_date,    count(e.id) as num_daily_interactions,    (       select           count(id)       from example        where date(date) <= e_date    ) as total_interactions_per_day from example as e group by e_date; 	0.0016619494650101
22277142	6321	comparing 2 tables with same structure in postgresql	select       l.* into       #sometemptable from      lov l where not exists  (select <<someuniqueorcompositekey>> from lov_tmp) 	0.00355182704512115
22279478	5272	3 mysql query using 1 query and limit	select id member_id, col1, col2, col3,   (select balance     from billing b1     where b1.suite=m.suite     order by bill_id desc limit 1) balance,    sum(net) as checker from members m left join billing b   on m.suite = b.suite group by col1,col2,col3,id order by id desc 	0.473848977717578
22279892	4758	how to get number of students in mysql	select st_category as cat, st_gender, count(studentpk) from es_preadmission where st_category in ('gen','sc','st',....,'sgc') group by st_category, st_gender union all select st_handi as cat, st_gender, count(studentpk) from es_preadmission where st_handi = 'ph' group by st_handi, st_gender 	0.000126378571701891
22282944	2851	access vba sql: find max date and retrieve row id	select test.id, test.inv, test.tdate, test.status from test inner join     (select test.inv, max(test.tdate) as maxoftdate     from test     group by test.inv)  as q  on (test.tdate = q.maxoftdate) and (test.inv = q.inv) group by test.id, test.inv, test.tdate, test.status; 	9.64793590235496e-05
22284062	36122	count operation on multiple condition using musql	select pre_scat_id as cat   , count(case when pre_gender = 'male'   and pre_class = 1 then 1 end) as m1   , count(case when pre_gender = 'female' and pre_class = 1 then 1 end) as f1   , count(case when pre_gender = 'male'   and pre_class = 2 then 1 end) as m2   , count(case when pre_gender = 'female' and pre_class = 2 then 1 end) as f2 from es_preadmission where pre_scat_id in ('gen','sc','st','obc') group by pre_scat_id 	0.664124348549104
22284427	26228	search keywords in one mysql column by using php	select title from mytable where title like '%ho%windo%' 	0.041660945630074
22284979	25621	sql with few join	select genre.title title1, country.title title2 from  movie   inner join countryrelation on movie.id = countryrelation.id_movie   inner join genrerelation on movie.id = genrerelation.id_movie   inner join genre on genre.id = genrerelation.id_genre   left join country on country.id = countryrelation.id_country   where movie.id = 1  group by country.title 	0.632260499376321
22287155	18316	prepared statement varying number of where clauses	select * from t where ? in (attr1, '') and ? in (attr2, '') and ? in (attr3,'') 	0.324387000015583
22287876	8128	joining two tables to find non matching info	select * from warehouselogin            where warehouselogin.instructor_password            not in           (select warehousedatains.instructor_password from warehousedatains) 	0
22287994	5804	group by breaks order by	select "mid", array_agg("tr") as agg_r, array_agg("tg") as agg_tg, array_agg("tp") as agg_tp, array_agg("sid") as agg_sid ,array_agg("date") as agg_date  from (    select "tid", "mid","sid","tr", "tg","tp", "date"     from table     where "tid" =1     order by "date" desc, "mid","sid" )as qres  group by qres."mid" order by max("date") desc; 	0.68982112408494
22291098	40685	mysql queries, using multiple table fields with the same name in a where clause	select      * from household_address join catchment_area on catchment_area.household_id = household_address.household_id join bhw on catchment_area.bhw_id = bhw.user_username join master_list on master_list.person_id = catchment_area.person_id join house_visits on house_visits.household_id = household_address.household_id where catchment_area.household_id in (   select household_address.household_id   from demo.household_address ha   join catchment_area ca on ca.household_id = ha.household_id   join previous_cases pc on ca.person_id = pc.person_id   join active_cases ac on ca.person_id = ac.person_id   join ls_report ls_r on ls_r.ls_household = ha.household_name   where date(ha.created_on) between '2014-03-01' and '2014-03-31'    and date(ca.created_on) between '2014-03-01' and '2014-03-31'    and date(pc.created_on) between '2014-03-01' and '2014-03-31'  ) 	0.00821800454002695
22292781	40017	get multiple counts multiple joins from schedule table	select mem_id, prod_code, prod_type, period,         round(max(amount), 2) amount,         case when period = 'weekly' then  52 else 27 end correct,              count(*) actual   from (   select s.*, m.period     from test_schedule s join test_member m       on s.mem_id = m.id       and s.prod_code = m.prod_code      and s.prod_type = 1    where s.status = 1    union all    select s.*, a.period     from test_schedule s join test_member_addon a        on s.mem_id = a.mem_id       and s.prod_code = a.prod_code      and s.prod_type = 2    where s.status = 1  ) q  group by mem_id, prod_code, prod_type, period 	0.00148844221622185
22293292	25017	comparing different columns and rows on the same table	select t1.* from table1 t1  inner join table1 t2 on t1.a = t2.b and t1.b = t2.a; 	0
22294815	25794	to display all records of table?	select * from table1 where (a is null or a != 2) and (b is null or b != 5) 	0
22295382	37679	subtract grouped figures in oracle select statement	select sol_id, (sum(case when int_id = 'c' then amount_in_lcy else 0 end)- sum(case when int_id = 'd' then amount_in_lcy else 0 end)) as difference  from interest_details   group by sol_id; 	0.0348663253196145
22296973	35346	how to distinct sum() when using joins	select      date_format(date, '%y-%m'),      sum(ok.qty),      sum(reject.qty),      ((sum(reject.qty) / sum(reject.qty + ok.qty))*100)as reject_percent from ok inner join (select ok_id,sum(qty) as qty from reject group by ok_id) as reject on ok.id = reject.ok_id group by date_format(date, '%y-%m') 	0.435602288210277
22297299	2953	how can i increase number of rows in sql table	select * from table t1 cross join table t2 	0.000452059513115247
22297352	19784	mysql - (reverse) left join from multiple tables and multiple relationship	select   max(i.idsa)  as idsa,  max(i.idsb)  as idsb,  max(i.idsc)  as idsc,  max(i.idsd)  as idsd from (select se.idse as idsa, null as idsb, null as idsc, null as idsd from serva s left join serverog se on se.servtype = s.type and s.idsa = se.typeid  union select null , se.idse, null, null from servb s left join serverog se on se.servtype = s.type and s.idsa = se.typeid  union select null , null, se.idse, null from servc s left join serverog se on se.servtype = s.type and s.idsa = se.typeid  union select null ,  null, null, se.idse from servd s join serverog se on se.servtype = s.type and s.idsa = se.typeid) i 	0.0797784423484846
22297387	25532	mysql different order by conditions	select *, `level` * unix_timestamp(`pexpdate`) as `bonusdate` from `localhost-tests` where 1 order by `bonusdate` desc, `adddate` desc 	0.0691106579897112
22298238	40453	max - min for each day in sql	select [signal name], cast(sampletime as date) as sampledate, max(value)-min(value) as diff_value from table1 group by cast(sampletime as date),[signal name] 	4.57036527280383e-05
22299266	30315	how to pivot two values in mysql?	select agent,product,  max(case when type='c' then value_2013 else 0 end) as value_2013_c,     max(case when type='c' then value_2013 else 0 end) as value_2013_a,      max(case when type='a' then impap else 0 end) as value_2014_a,          max(case when type='a' then impac else 0 end ) as value_2014_c           from  mytable   group by agent,product; 	0.0187381089555722
22299448	38828	sql join 2 table with 2 count	select   * from (   select mod_desc, mod_cod, count(mod_desc) as num   from modelli, pv_proposti, gestione_commesse    where  something )   as mpg full outer join (   select mod_desc, mod_cod, count(mod_desc) as num    from distrib, modelli    where something )   as dm     on  dm.mod_desc = mpg.mod_desc     and dm.mod_cod  = mpg.mod_cod 	0.0191172996327032
22300377	12054	sql query to transpose data in below case	select   heading,    a package_a,   b package_b,   c package_c,   d package_d from (       select * from yourtable ) up  pivot (sum(limit) for package in (a, b, c, d)) as pvt 	0.692839497172856
22300738	5592	mysql count multiple values in same column	select vid, substring_index(keyword, ' ', -1)  as item1  from video  group by item1   order by item1 	0.000681730864426695
22302161	27038	oracle sql - unwanted spaces when concatenating fields and text strings	select replace(('ep.'||to_char(pwrotpr_transx_nbr,'0000000')||'.'||to_char(pwrotpr_submit_counter,'00')), ' ', '') as ats_nbr 	0.694113517348317
22302649	33998	difference between where and and clause in join sql query	select a.id, a.name,a.country from table a left join table b on a.id = b.id where a.name is not null 	0.613229463419577
22302723	1200	row count and values in one select	select     t.`id`,      t.`name`,      student_count.`count`,     s.`name` from `teachers` t left join `students` s on t.`id` = s.`teacher_id` left join (     select          ti.`teacher_id`,          count(*) as count      from `students` ti     group by ti.`teacher_id`) student_count on t.`id` = student_count.`teacher_id` 	0.000285199687738828
22303703	37018	datediff - how many days until sunday	select 8-datepart(w, closed_time) as days_until_purged from db1 ... 	0.00047107205796607
22304526	28864	how to count the expected number of rows	select * from ints; + | i | + | 0 | | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | + select sql_calc_found_rows * from ints limit 3; + | i | + | 0 | | 1 | | 2 | + select found_rows(); + | found_rows() | + |           10 | + 	0.00286746404844251
22304577	3322	mysql query enhancement to get correct results	select * from users where company like '%a1a%' or company like '%a1' 	0.314839930508512
22305052	5578	how may i get these values using a query	select meal, ingredients, occurence from table join (select meal as m, max(occurence) as max_occurence from table group by meal) t on table.m = t.meal where table.occurence = t.max_occurence 	0.040638867846061
22305909	29885	how to get the correct 'customernumber'?	select temp.customernumber, max( temp.tsum ) as tmax  from (     select p.customernumber, sum( p.amount ) as tsum      from payments p      group by p.customernumber ) as temp group by temp.customernumber 	0.0763192268981262
22305952	21362	how to mapping data with text multi level?	select table_product.product, table_mapping.productname     from         table_product         inner join         table_mapping             on table_product.product = table_mapping.productgroup     where instr(table_mapping.productgroup, "*") = 0 union all     select table_product.product, table_mapping.productname     from         table_product         inner join         table_mapping             on table_product.product like table_mapping.productgroup     where instr(table_mapping.productgroup, "*") > 0         and table_product.product not in (select productgroup from table_mapping) order by 1 	0.398060337164832
22308030	27863	find out unique of variable with two dimension	select company from production group by company  having count(distinct model)>1 and count(distinct product)=1 	0.000845349106344964
22308272	22281	how do i efficiently compare users?	select user_id, count(category_id) as count, group_concat(category_id separator "|") from likes where category_id in (     select category_id     from likes     where user_id=1 ) and user_id != 1 group by user_id; 	0.0068139219501227
22308610	14082	sql stored procedure return single record per id with max date for that id	select p.prid, cost,margin from prodtrans as p join ( select max(transdate) as maxdate, prid from prodtrans group by prid ) as m   on m.prid = p.prid   and m.maxdate = p.transdate order by p.prid 	0
22308821	33350	mysql query for library database	select b.something      , c.something_else   from a   join b     on b.x = a.x   join c     on c.y = a.y  group      by b.m      , c.n having count(*) >= 5; 	0.395957911063812
22309113	4676	how to count tuples containing the same value?	select name, count(*) from my_table group by name 	0.000159447287431382
22309687	17822	first value in group by	select id, count(*) as multiplicity,        if (count(*) > 1, 0, if(max(good) = 't', 1, 0)) as goodn from ... 	0.00381858657537006
22310719	2285	sql query to combine two user tables, remove duplcates and find the latest update entry for each user	select  a.eusername,         a.eemailaddress,         b.maxsubmitdate from tablea as a inner join (select txtcontactemail, max(submitdate) maxsubmitdate             from tableb             group by txtcontactemail) as b     on a.eemailaddress = b.txtcontactemail 	0
22312137	21419	select rows from mysql where col1 is value and another row where col1 is not value based on col2 related values	select count(distinct `callid`) from `voipnow`.`ast_queue_log` where `event`='ringnoanswer' and `callid` not in (select `callid` from `voipnow`.`ast_queue_log` where `event`='connect' or `event`='abandon') 	0
22313321	34367	how do i aggregate one column for 2 tests into two columns on one row	select      codename             , codedesc             , sum(case when passfail = 1 then 1 else 0 end) as pass_values             , sum(case when passfail = 0 then 1 else 0 end) as fail_values from        passfailmaster group by    codename             , codedesc 	0
22314016	7581	grouping display data from mysql	select case count(*)         when 1 then boxes         else concat(min(boxes), '-', max(boxes))        end as boxes,        concat(sum(weight), 'kgs of ', items) as items from yourtable group by items 	0.000846118247308568
22317332	31827	sql - select all rows and replace column value(s) with max column value with identifier	select type1,type2,code,max(amt) over(partition by code) as maxamt from table1 	0.000199713022544172
22317355	20282	how to optimize sql query on date field	select count(*) as count,        date_format(date,'%d-%b-%y') as datename  from mytable, (select utc_timestamp() - interval 30 day as start_date, utc_timestamp() as end_date) dd   where date between dd.start_date and dd.end_date and id=123  group by day(date)  order by date asc; 	0.167988341148791
22317721	4178	how to get 2 results from 3 tables with 1 mysql syntax	select a.soft_id,   a.soft_name,   b.p_cnt as quantity,   c.o_cnt as owner_count from soft a inner join   (select soft_id, sum(pu_quantity) as p_cnt from product group by soft_id   ) b on a.soft_id = b.soft_id inner join   (select soft_id, count(*) as o_cnt from owner group by soft_id   ) c on b.soft_id = c.soft_id group by a.soft_id,   a.soft_name 	0.00153391453475345
22318266	36922	i want to check already applied leave dates	select count(empid) from employee where ($a>=leavefrom and $a<=leaveto) or ($b=leavefrom and $b<=leaveto) and empid=1; 	0.00197832308786459
22318776	19059	sql join 2 tables with conditons on other tables	select n.name     from tbl_name n              inner join tbl_ref r on n.id = r.id where fid =  '111-11'; 	0.00389776141032036
22319408	14351	postgres: get min, max, aggregate values in one select	select array_agg(distinct type) as types,min(value) as min, max(value) as max  from your_table 	0.000556473956540184
22319688	17804	query to count the number record contain text	select notice_type, count(*) from [table]  where person_id=5 group by notice_type 	0.000819375533655836
22320596	13084	i want to join 3 tables from this data	select  c.custid,         c.custname,         count(distinct b.carid) countcar,         sum(b.billtotal) sumbill from    customers c inner join         bill b  on  c.custid = b.custid group by    c.custid,             c.custname 	0.085470893362198
22323190	1399	want to select data from each group	select * from your_table where eid in (     select eid      from your_table     group by eid     having sum(case when involvement not in ('amanda','dina') then 1 else 0 end) = 0 ) and involvement in ('amanda','dina') 	0.000116025228290278
22324549	7037	adding date difference of two dates in sql for all columns	select sum(datediff(minute, r.arrivaldate, r.departuredate)) / 60 as totalhours      , sum(datediff(minute, r.arrivaldate, r.departuredate)) % 60 as totalminutes  from tablewithdates r 	0
22325405	2710	sql remove duplicate record while using join	select p.productid,p.productname,x.details  from products p cross apply (select top 1 inv.details from inventory inv where p.productid = inv.productid) x 	0.0138931911661227
22327100	21297	how to get list of all users to follow	select usid, name from user u  where u.usid <> @id and u.usid not in (     select distinct fusid from relation_user where usid = @id ) 	0
22327992	26590	sql-statement to use predefined values list as an sql-table	select to_number(regexp_substr(str, '[^,]+', 1, level)) ids   from (select '0,12,2,3,4,54,6,7,8,97' as str from dual) connect by level <= length(regexp_replace(str, '[^,]+')) + 1 minus select level from dual connect by level <= 10; 	0.0793939402619192
22328037	17137	sql/php - get table name in php from union	select 1 as field0, field1, field2 from table_a union  select 2 as field0, field1, field2 from table_b 	0.000606564981334034
22328158	28523	how to table minus table = answer php mysql	select id, team, dpv, dpt, dpv-dpt as difference from e2teams 	0.0518894256042684
22329490	4795	sql all students who are older than the youngest teacher?	select s_id, s_firstname from s_schueler  where s_gebdatum > (select max(l_gebdatum) from l_lehrer); 	0
22330450	37654	how to select all the offers a user earned?	select offer.name  from offer inner join user_offer  on user_offer.offer_id=offer.id  where user_offer.user_id='1' 	0.000958312018919259
22333189	7146	mysql query to select a column with only alphabetical characters	select * from listing where zip regexp  '^[a-z]+$' 	0.00682410767014776
22334958	13571	how to find the average of differences of the last n readings of a column php mysql	select avg(difference) from (     select @next_reading - reading as difference, @next_reading := reading     from (select reading           from level_records           order by date desc           limit 20) as recent20     cross join (select @next_reading := null) as var     ) as recent_diffs 	0
22336176	24065	mysql if not exists return 0	select c.steps, ifnull(c.steps, 0) value, r.calendar_date   from log_activities c  right join calendar r     on r.calendar_date = c.date_logged  where email = 'a@mail.com'    and substr(r.calendar_date, 4, 2) = '01'    and r.calendar_date between        (select min(date_logged) from log_activities) and        (select max(date_logged) from log_activities)  order by c.date_logged desc 	0.301308447933779
22336466	35090	select distinct word count?	select word,count(*) as count from (select substring_index(substring_index(concat(searches,' '),' ',value.v),' ',-1) as word from yourtable,(select 1 as v union                  select 2 union                  select 3 union                 select 4 union                 select 5)value  )t where word != '' group by word 	0.0318095126891578
22338688	3839	sqlite check if number is integer	select     "(" + databaseopenhelper.key_row_id + " - 1)/4 + 1" as field from     table where     field not like '%.%' 	0.0147578761705087
22339873	11964	mysql group by marks with gender	select (case when marks between 1 and 5 then '01 - 05'              when marks between 6 and 10 then '06 - 10'              when marks between 11 and 15 then '11 - 15'              when marks between 16 and 20 then '16 - 19'              when marks between 21 and 25 then '21 - 25'         end) as marksrange,        sum(gender = 'b') as boys,        sum(gender = 'f') as girls from report group by marksrange order by marksrange; 	0.635772388488187
22340121	3893	select from tablea.code if in tableb.code	select *  from table1  where exists (select *                from table2 where table2.code = table1.code) 	0.0587083934459727
22340655	15591	sql - count multiple columns and join in a single query	select id, concat(db_users.fname, ' ', db_users.lname) as username,     (if (aaa = 'n/a', 0, 1) +       if (bbb = 'n/a', 0, 1) +       if (ccc = 'n/a', 0, 1) +       if (ddd = 'n/a', 0, 1) ) as count     from db_log     join db_users on db_log.userid = db_users.userid 	0.0152141929404187
22342787	17977	how to get specific cell from table mysql to vb.net	select col_name    from table_name   where col_name='values'         and id = '1' limit 1 	0
22344505	20653	mysql multiple joins with same table	select      dt.date,      t1.cond as tk1cond,      t1.hard as tk1hard,     t2.cond as tk2cond,      t2.hard as tk2hard   from (select date from systemvalue group by date) dt left join systemvalue t1 on t1.date = dt.date and t1.tankno = '1' and t1.system = 'ht' left join systemvalue t2 on t2.date = dt.date and t2.tankno = '2' and t2.system = 'ht' 	0.0623163120051015
22346180	19618	how to group from coalesce? sql	select b.vehicleowner, city from (select a.vehicleowner,       coalesce(a.city, (select b.city from a inner place b),                (select b.city from a inner   place b)) as city       from vehiclemileage a) as b where b.vehicleowner in (select vehicleowner                       from vehiclemileage                       group by vehicleowner                      having count(*)>1); 	0.199587225115567
22347587	24769	concise syntax on a single table to collapse columns using union all	select    time,   if (temp.row_n=1,t.type_x,t.type_y) as type,   if (temp.row_n=1,t.type_x,t.type_y) as val from t,      (select 1 as row_n       union       select 2 as row_n) temp 	0.00543389931781535
22348492	20535	write the content of sql row into varchar variable	select    'id: ' + convert(varchar(10), id) + '; name: ' + name +    '; age: ' + convert(varchar(10), age) + '; city: ' + city  from test 	0.00209655022720857
22349163	9009	postgresql count based on condition	select count(designer_orders.id) as pr, sum(case when designer_orders.package_status = 'packed' then 0 else 1 end) as pu from "designer_orders" 	0.00830846354796192
22351052	14600	sybase asa database and listing columns with types	select t.creator, t.table_name, t.table_id, c.column_type, c.nulls, c.width, c.default   from sys.systab t, sys.systabcol c where t.table_id = c.table_id 	0.0396034489794852
22354498	701	getting second to last record per group in sql	select *  from ( select job as qjob       , id as qid       ,row_number() over (partition by job order by id desc) as rn from sqbclog )sub where rn <= 2 	0
22354766	36780	select all from one table and if exist take the more details on another table	select *  from oficinas_inscritos left outer join oficina_pesquisa  on oficina_pesquisa.cpf = oficinas_inscritos.cpf 	0
22354893	40801	mysql - get row if other rows match	select distinct t1.entry_id from yourtable t1 join yourtable t2 on t1.entry_id = t2.entry_id where t1.cat_id = 1 and t2.cat_id in (2, 3) 	0
22356760	37992	getting the difference between two times stored as varchar	select ((floor(finish_time/100)*60)+mod(finish_time,floor(finish_time/100)*100))-((floor(start_time/100)*60)+mod(start_time,floor(start_time/100)*100)) from table; 	0.000168257041091906
22356972	40165	finding duplicates based on multiple fields	select    somecommongfield  from    biggertemptable    where not in      (select somecommonfield from smallertemptable) 	0.000173217642040908
22357657	24062	count + distinct sql query	select count(*) from (select researcher, count(*)  from mytable group by researcher) as temptable; 	0.242733369077583
22357858	22950	show an empty result on succeeding rows	select id, product_id, status,        if(id <> @previd and @prevstatus <> status and status = 'complete', transaction, null) as transaction,        action,        @previd := id, @prevstatus := status from table t cross join      (select @previd := -1, @prevstatus := '') const order by id, product_id, status; 	0.00296721512044756
22357990	24521	mysql last entry on revolving table	select element from table x order by time desc limit 1 	9.87546768748104e-05
22359353	34023	return records that are not in a query	select d1.* from table.diet as d1 left join table.diet as d2 on d1.date = d2.date and d1.fruitseatentoday <> d2.fruitseatentoday and d2.fruitseatentoday = 'banana' where d2.fruitseatentoday is null 	0.00454517542690071
22362362	39387	select row where string dose not exist	select staffname  from worktable  where staffname not in      (select distinct staffname from worktable where intweek = '$week')  order by staffname asc 	0.088752492994447
22363352	40461	how would i go along with fetching same name values from mysql	select username, count(*) as total from votes group by username order by total desc 	0.000148951247208604
22364089	25780	google bar chart from mysql and php	select   school,   sum(if(gender='m',1,0)) as m,   sum(if(gender='f',1,0)) as f from   participant group by   school 	0.432505818612904
22365011	38848	sql search query for matching at least half of the keywords of array	select *  from tablename where description is not null and if ( length(concat( if (description like '%busy%', '1', ''),  if (description like '%good%', '1', ''),  if (description like '%nature%', '1', ''),  if (description like '%blck%', '1', ''), if (description like '%sweet%', '1', '') )) > 2, 1, 0)=1 	0.000195196577561389
22366501	2236	compare values from two tables	select totals.nrlist,        if (totals.nrproducts = t.nrproductsactual, 'yes', 'no') as matchnrproducts,        if (totals.total = t.totalactual, 'yes', 'no') as matchtotal   from totals inner join        (select nrlist,               count(*) as nrproductsactual,               sum(quantity*price) as totalactual           from listproducts          group by nrlist) as t on totals.nrlist = t.nrlist 	8.11720249051706e-05
22370173	8745	match data from multiple tables	select l.userid,l.name,l.pass,l.email from login l inner join    phyinfo p on l.userid=p.userid inner join    loc on l.userid=loc.userid inner join    skills s on s.userid=l.userid where p.height='5''21"' and p.gender='male' and loc.country='india' and s.skillslists like '%design%' 	0.00175198316217237
22371038	27130	count value in output with normal rows	select t.id,t.name,s.step_no,s.step_data,counts.count from test t       join steps s on t.id = s.testid      join (select testid, count(*) as count             from steps             group by testid) counts on t.id = counts.testid 	0.0108446462871891
22371058	20307	how to combine two conditions in a query?	select cust_code,cust_name,cust_city  from mgen_custcode  where mgen_branch='$bangalore'        and (cust_name like '%$q%' or cust_code like '%$q%')  order by cust_name 	0.0142822206220048
22371857	20251	php/mysql sort numbers with speed units	select * from results order by      case          when speed like '%kb/s' then cast(speed as decimal(10,2))         when speed like '%mb/s' then cast(speed as decimal(10,2)) * 1024     end desc limit 20 	0.487185747444519
22373847	12876	mysql filter first date for last user for each item	select t.* from (   select t2.`file_id`, t2.`user_id`, min(t2.`action_datetime`) ts_first_date from (     select t1.*     from table_1 t1     join (       select `file_id`, max(`action_datetime`) as ts_last_user       from table_1       group by `file_id`     ) tmp2     on tmp2.`file_id` = t1.`file_id` and tmp2.ts_last_user = t1.action_datetime   ) t3   join table_1 t2   on t3.`file_id` = t2.`file_id` and t3.`user_id` = t2.`user_id`   group by t2.`file_id`, t2.`user_id` ) outertable join table_1 t on t.user_id = outertable.user_id and t.file_id = outertable.file_id and t.action_datetime = outertable.ts_first_date order by t.file_id 	0
22374419	17584	mysql: count and total for two different groupings	select i.site_id,          i.referrer_domain as referrer_domain,          count(*) as items,          t.site_total  from qvisitor_tracking_1 as i inner join  (     select site_id,              count(1) as site_total      from qvisitor_tracking_1      where referrer_domain != ''      group by site_id ) as t  on i.site_id = t.site_id where referrer_domain != ''  group by i.site_id, referrer_domain, t.site_total 	0.000279926804404784
22374592	22859	why we can't select data from temporary table into another temporary table	select col1, sum(col2) as sumofcol2 into #temp2 from #temp1 group by col1 	0.00587904948270415
22375504	12496	sql - condition for each record in bundle	select  * from    bundles b where   not exists         (         select  *         from    courses c         where   c.id = b.course                 and course_date < getdate()                  and ...         ) 	0.000853826790778471
22376577	30575	how to count fields on where clause	select t1.instanci from table1 t1 inner join table2 t2 on t1.table1id=t2.table2id group by t2.table2id having count(t2.table2id)<2 	0.162301482822495
22378683	35022	how to count this	select count(id), state from table_name where id in (select id from table_name group by id having count(id) = 1) and state = 'alabama' group by state 	0.540112163513923
22378727	23573	making query from variable from multiple tables	select u.name as username, c.name as carname, col.name as carcolor from users as u join cars as c on (c.user = u.id) join colors as col on (col.car = c.id) where u.id = 1; 	0.0132972209204222
22379865	32895	sql - return rows matching all values from a joined table	select p.productid, max(p.name) from product p inner join productcategory c on c.productid = p.productid inner join matchtable m on m.categoryid = c.categoryid group by p.productid having count(*) = (select count(*) from matchtable) 	0
22382716	20242	assign row numbers to a set of results retrieved via a pl-sql stored procedure	select row_number() over (order by column1) as row_num, t.*  from (    select column1, columns2 ... from table1 where mycondition    union    select column1, column2 ... from table2 where mycondition    union    select column1, column 2....  ) t; 	0.000160439888247068
22383169	20549	mysql - find and count duplicates (quantities)	select user_id, product_id, count(product_id) as num_of_prod  from cart group by user_id, product_id 	0.0138967813804753
22384124	36565	how to get the sum of certain rows based on an id and populate column with the value without using a loop	select id, customerid, paymentid, itemid, deductionbucketid, qty, amount, deductions , sum(amount) over (partition by customerid, paymentid) as sumofamount from ... 	0
22384430	32572	how to get max birth date while grouping on course?	select s1.name, s1.lastname, s1-fdate from student s1 where not exists (     select 'youngest'     from student s2     where s2.course = s1.course     and s2.fdate > s1.fdate ) 	0.000123294204333146
22386005	18327	sql query calculating 2 separate columns of data based on date range group by size and type	select sum(case when a.dtacquired < '2014-01-25'                 then i.qty                 else 0            end) as begqty,        sum(case when a.dtacquired between '2014-01-25' and '2014-03-15'                 then i.qty                 else 0            end) as acqqty,        i.size, i.type      from invdetails i join      acquisition a      on i.serialno = a.serialno group by i.size, i.type; 	0
22387012	22770	select users who's first appearance has a referrer value of adwords and appear more then once	select t1.tableentries, t1.billing_email from (     select billing_email, min(order_id) as usersfirstorderid     , count(*) as tableentries     from tblorder      group by billing_email     having tableentries>1 ) as t1 join tblorder as t2 on t1.usersfirstorderid=t2.order_id and t2.referrer='adwords' 	0
22387058	32328	return maximum value from group for year required	select fs_perm_sec_id, [date by year], label from ( select      fs_perm_sec_id, year(date) as [date by year], label, dense_rank ( ) over (order by sales desc) as rankno from      ff_v2.ff_segreg_af where      fs_perm_sec_id = 'sn9w4d-s-us' and year(date) = '2013' ) r where rankno = 1 	0
22387791	28898	sql to select the the results of an update on a left join	select id     , lat     , lon     , isnull(area,0) from regionll left join regiona     on idll = ida 	0.0587037795242376
22387837	28515	sql query to sum the column data based on the same id's in access table	select eid, sum(value) from table group by eid 	0
22389491	8441	determining where column collations don't match	select * from (  select *         from sys.columns         where object_name(object_id) = 'tablea') a inner join (select *             from sys.columns             where object_name(object_id) = 'tableb') b     on a.name = b.name where a.collation_name <> b.collation_name 	0.0978189584218063
22389623	21716	sum different values from same column	select hour,sum(temperature) from mytable group by hour 	0
22390841	8319	how can i display the result twice for the same column for different conditions	select campaign,      count(case when statusid=1 then statusid else null end) as notstarted,      count(case when statusid=2 then statusid else null end) as inprogress      from [tldcrm2].[dbo].[vpipeline] group by campaign select campaign,      sum(case when statusid=1 then 1 else 0 end) as notstarted,      sum(case when statusid=2 then 1 else 0 end) as inprogress      from [tldcrm2].[dbo].[vpipeline]     group by campaign 	0
22391191	8201	mysql query dates from timestamp	select distinct from_unixtime(your_timestamp_column/1000,'%m %d, %y') from your_table; 	0.00346783623785616
22391452	29537	count of other rows in table with the same value	select t1.*,   (select count(1)   from mytable t2   where t2.`room number` = t1.`room number`   ) from mytable t1 	0
22391478	8774	ssrs report data source for query with multiple databases	select * from vw_interactions 	0.241704159511675
22391651	26086	how to get total number of registered users *at* each month?	select date, count(id) from users group by month(date_registered). 	0
22393740	39447	how to run a script on entry form before saving data	select last_insert_id(); 	0.00823942980082835
22394054	28924	how to combine two records in the same table	select option_date, option_symbol, option_price, option_expire_month, option_strike, sum(option_call_volume), sum(option_put_volume)  from table  group by option_date, option_symbol, option_price, option_expire_month, option_strike 	0
22395708	16341	sorting data in oracle table using 2 conditions	select job_id from job where job_id in (   select job_id    from job   where job_process = 'is_assist' and job_process_state = '0'   group by job_id ) order by case when job_process = is_pullahead and job_process_state = 1                then 0               else 1           end 	0.0376441613301491
22397622	20245	a great select query including count	select sid,name,surname,        (select count(*) from student_scores where sid = s.sid ) as scorecount ,        (select count(*) from student_documents where sid = s.sid ) as doccount ,        (select count(*) from student_messages where to= s.sid ) as messagecount  ,        (select count(*) from student_payments where sid = s.sid ) as paymentcount ,         .         .         . from studentstables s where sid=891 	0.101891836844565
22398974	13841	concatenate all the notes in a single row based on lead's id?	select l.first_name, l.last_name, l.id, group_concat(n.name), n.description from      leads as l inner join notes as n on l.id = n.parent_id where l.deleted = 0 and n.deleted = 0 and l.id='104c4b25-adab-32f3-16ee-50d098a5dd5d' group by l.id 	0
22399242	25211	select minute avg in one minute increments	select avg(price), date(timecolumn), hour(timecolumn), minute(timecolumn) from `table`  where time(timecolumn) >= '09:00:00' and time(timecolumn) <= '17:01:00' group by date(timecolumn), hour(timecolumn), minute(timecolumn) 	0.00453657514999678
22399508	5683	mysql query to fetch limited rows of each type	select * from (     select     c.*,     @rn := if(company_type != @ct, 1, @rn + 1) as rownumber,     @ct := company_type     from     companies c     , (select @rn := 0, @ct := null) var_init     order by     company_type ) comp where rownumber <= 20; 	0
22399644	2915	sql based on if case (read details)	select t.* from your_table t join  (   select user_id, max(anonymous) as m_anon   from your_table   group by user_id ) x on x.user_id = t.user_id and x.m_anon = t.anonymous 	0.17053090862862
22401878	24006	how to join two tables with redundant column value?	select serviceiod.keyword,   serviceiod.shortcode   from serviceiod where shortcode = 36788  union select servicesubs.keyword,   servicesubs.shortcode  from servicesubs where shortcode = 36788 	0.00503940996179479
22404876	17537	sql select query	select u.first_name from users u  left join usermodule um on um.user_id = u.user_id where um.module_id = '$module_id'; 	0.448716452127667
22406767	8222	join 3 mysql tables with condition	select p.product_id, pd.name,p.image  from product p  left join product_description pd  on (p.product_id = pd.product_id) join product_store ps on (p.product_id = ps.product_id and ps.store_id in (0,1)) order by p.product_id desc  limit 3 	0.296097455421365
22407233	23842	is there a way in mysql to do a “round robin” order by on a particular field in variable universe?	select `group`, name from (   select    t.*,   @rn := if(`group` != @ng, 1, @rn + 1) as ng,   @ng := `group`   from t   , (select @rn:=0, @ng:=null) v   order by `group`, name ) sq order by ng, `group`, name 	0.0121551898726989
22407631	21669	comparing column to column in sql	select     student.roll from     student     inner join teacher on student.class = teacher.class 	0.0123796468186358
22408885	16942	sql alter table excluding a column	select    regno,            name,            dept,            gpa           @currank := @currank + 1 as rank from      leaderboard, (select @currank := 0) r order by  gpa; 	0.0055452904556366
22409068	27538	mysql: get start & end timestamp for each day	select   date(statustime) statusdate,   min(case when reading<50 then statustime else null end) start_time,   max(case when reading<50 then statustime else null end) end_time from mytable group by statusdate 	0
22409446	12142	list all tables in a db using sqlite	select * from sqlite_master where type='table' 	0.00314657287933293
22409523	15267	mysql: get latest record then group alphabetically	select * from(      select form_id as form_id,         mag_logo_url,          cover_date,          fs.ukip_title_id as title_id,          fs.form_title as form_title      from form_advertisers fa      inner join form_settings fs      using ( form_id )      where fa.advertiser_id =135      order by fs.form_id desc  )as temp  group by title_id  order by form_title asc , form_id desc 	0
22409688	17837	combining two mysql results	select productid, sum(amout) from  (select * from vw_view1 union all select * from vw_view2 union all select * from vw_view3) group by productid 	0.037673138100562
22410296	21885	flatten table rows by combining certain values into columns	select foo.orgname, max(foo.admin1), max(foo.admin2) from   (select dbo.organization.organizationname as orgname,                case when (dbo.organizationuser.adminorder = 1) then dbo.organizationuser.userid else '' end as admin1,                case when (dbo.organizationuser.adminorder = 2) then dbo.organizationuser.userid else '' end as admin2         from   dbo.organization           inner join dbo.organizationuser on dbo.organizationuser.organizationid = dbo.organization.organizationid         where  dbo.organizationuser.usertype = 'admin') foo group  by foo.orgname 	0
22412223	25855	sql query to get databases larger than a value	select table_schema as databasename,     sum(data_length + index_length)/1024/1024/1024 as sizeingb from information_schema.tables  group by table_schema having sizeingb >= 1.5; 	0.00297284678642702
22412373	26435	mysql query to find records that are common in multiple columns across multiple tables.	select distinct c1.a from  `t1` c1  join  `t1` c2 on ( c1.a = c2.b )   join  `t1` c3 on ( c2.b = c3.c )   join  `t1` c4 on ( c3.c = c4.d )   join  `t2` c5 on ( c4.d = c5.a )   join  `t2` c6 on ( c5.b = c6.c )   join  `t2` c7 on ( c6.c = c7.d )   limit 0 , 10 	0
22415220	26017	tag database schema	select      qt.question_id,      group_concat(t.tag_name separator ',')  from question_tag qt left join tag t on t.tag_id = qt.tag_id group by qt.question_id; 	0.214844381653211
22415366	26778	sql return all rows if admin, otherwise return user records	select name, address, databaseid, isadmin from yourtablename where databaseid = @databaseid       or 1 = (select isadmin                from yourtablename               where databaseid = @databaseid); 	0
22415631	36768	create sequence oracle sql random primary keys	select rn from ( select    row_number() over (order by dbms_random.random) as mx, rn   from (   select rownum  as rn      from dual   connect by rownum <= 10   minus  ( select sin from people )     )      ) where mx = 1 ; 	0.0265118516784366
22415947	17598	how to write a sql join to retrieve results from second table?	select * from table2 where id in (select id from table1 where color = 'green'); 	0.000158943796116042
22416257	27442	sql get available records between two hours	select name from employees  where (entrytime < exittime and @time between entrytime and exittime) or       (exittime < entrytime and @time not between exittime and entrytime); 	0
22420683	25482	mysql find duplicate ipaddress in table	select `ip`, count(*) cnt from `webinformation` group by `ip` having cnt > 1; 	0.00245368231461064
22422676	17705	fetch email id of those employee who has resigned	select emailid from emp_master as m left join emp_resignation as r on m.empid = r.empid where r.empid is null 	0
22423207	36467	display all departments and all employees	select department.id, department.name, employee.id, employee.name from department left join employee on department.id=employee.dept_id order by department.id 	0
22426373	31347	sql - use like to search two columns at once (first and last name)	select * from users where first_name like '%$query%' and last_name like '%$query%' 	0
22427141	26667	issue combining two mysql queries	select s.date as date, s.title as title,   count(f.id) as impressions,   count(d.event) as completed from stats s   left join stats as f on s.id = f.id and f.event ='play' and f.videopos = '0'   left join stats as d on s.id = d.id and d.event = 'completed' where s.user_id = '2' and (s.date_time between '2014-03-08 00:00:00' and '2014-03-18 23:59:59') and s.title is not null group by s.title 	0.56556329781762
22428132	489	adding a new column sql query	select * from  (select sum(*) as "tot1" from table1 t, table2 t2 where t1.id=t2.id and t1.column=1) a, (select sum(*) as "tot2" from table1 t, table2 t2 where t1.id=t2.id and t1.column=2) b, (select sum(*) as "tot3" from table1 t, table2 t2 where t1.id=t2.id and t1.column=3) c 	0.0652127057437053
22430693	19680	query sql database for home and away team based on team id	select hometeam.teamname as teamh, awayteam.teamname as teama, m.scorehome, m.scoreaway from match as m join team as hometeam on m.teamidhome = hometeam.teamid join team as awayteam on m.teamidaway = awayteam.teamid 	0.000684621482481495
22432662	28382	oracle convert date to number	select (to_date(s1, 'mm/dd/yyyy hh24:mi:ss') -         to_date('1970-01-01', 'yyyy-mm-dd')        ) *24*60*60 from (select '12/03/2013 12:23:00' as s1 from dual      ) t 	0.00969690617438142
22433011	23300	mysql > count number of records added at the same time	select calldate, count(*) as total from calls  where disposition = 'answered' group by calldate having total > 1 order by calldate asc; 	0
22433422	24302	how do i select a column of dates and use that to drive a second select statement?	select    order_date as o_date,    quantity,   (select order_date from orders where order_date > o_date limit 1) as next_date,   (select quantity from orders where order_date > o_date limit 1) as next_quantity from orders where quantity > 35 	0.000151377590160054
22434792	4182	mysql, how to display data that was entered in the last 3 hours?	select * from tablename where date >= date_sub(now(),interval 3 hour); 	0
22436396	20207	mysql - join 2 tables with 2 id's in common as query	select   u.id,   t1.name as team1_name,   t2.name as team2_name,   u.uitslag from uitslagen u   join teams t1     on u.teamid1 = t1.id   join teams t2     on u.teamid2 = t2.id 	0.000222424996890314
22437577	12328	sql query remove till last occurrence and return the values	select * from tablea where sequence>(select max(squence) as lastoccur from tablea where width=0) 	0
22439612	36718	how to get sum of one column based on other table in sql server	select c.id, c.customername, sum(isnull(p.price, 0)) as sumprice   from tblcustomers c   left join tblpurchases p     on c.id = p.customerid  group by c.id, c.customername 	0
22447443	39144	mysql query tag search with relevance	select business.biz_name    from business,business_tags,tags    where business.biz_id = business_tags.biz_id    and business_tags.tag_id = tags.tag_id    and (business.biz_name like '%bank%' or tags.tag_name = 'bank') 	0.780549717718638
22447874	9264	make rows into extension column on queried rows only sql	select      cid,     sum(if(camountdescription='payment',camount,0)) as payment,     sum(if(camountdescription='loan',camount,0)) as loan from the_table group by cid 	0
22448085	1873	how to get a timestamp value from sqlite	select strftime('%y-%m-%d-%h:%m', ztimestamp, 'unixepoch') as time from sqltable 	6.48823584216734e-05
22450081	31049	finding duplicates by size and name using sql query	select t1.filepath  form myduplicatetable t1 inner join (   select filesize, filename    from myduplicatetable    group by filename, filesize    having count(*) > 1 ) t2 on t1.filesize = t2.filesize and t1.filename = t2.filename 	0.0351096689448117
22451222	16936	categorize by columns	select decode(rn,1,a,null) as a,   decode(rn,1,b,null)      as b,   c,   d,   e from   (select a,     b,     row_number() over (partition by a,b order by a,b) as rn,     c,     d,     e   from     (select * from test_table order by a,b     )   ); 	0.0212206264688254
22451734	7956	mysql shortening select query	select     `p`.id ,   f1.title as filter_01 ,   f2.title as filter_02 ,   f3.title as filter_03 ,   f4.title as filter_04 from     `products` p left join     `products_types` t     on p.type_id = t.id     and t.ttv_end is null left join products_types_attributes f1 on f1.filtername = 'filter_01' and a.ttv_end is null and a.id = p.filter_01 left join products_types_attributes f2 on f1.filtername = 'filter_02' and a.ttv_end is null and a.id = p.filter_02 left join products_types_attributes f3 on f1.filtername = 'filter_03' and a.ttv_end is null and a.id = p.filter_03 left join products_types_attributes f4 on f1.filtername = 'filter_04' and a.ttv_end is null and a.id = p.filter_04 where     `p`.`id` = 9754 and    `p`.`ttv_end` is null 	0.698581010477168
22451839	5223	dynamically select top rows in sql server	select top (@number) id from tblemployee 	0.012233239927175
22454057	2737	select rows with same value as given id	select * from mytable  where name in (    select name from mytable    where id = '.$docid.' ) 	0
22455546	8962	select with timestamp dynamic returning results from the same table	select i.id, i.timestamp, i.code, i2.code, i2.timestamp  from table i left join (      table i2      on i.id != '0' and          i2.timestamp between i1.timestamp - interval '7 days' and i1.timestamp - interval '1 day' where i.timestamp between '2013-01-08' and '2013-01-08'; 	0.000441759767074006
22455776	38750	oracle - sql query select max from each base	select t.accounts.bidd.baseid, max(t.accounts.balance) from order o, table(c.accounts) t where t.accounts.acctype = 'verified' group by t.accounts.bidd.baseid; 	0.000280921935471319
22456554	24310	get percentage of appearance of a certain value in mysql	select version, count(*) / const.cnt from mytable cross join      (select count(*) as cnt from mytable) const group by version order by version; 	0
22457279	19511	how to perform inner join on same table in mysql	select switch,group_concat(port_no) from sla group by switch; 	0.13582481246843
22457311	4798	sql query - select max where a count greater than value	select max(something) maxvalue from sometables join (select id, count(*) records from atable group by id) temp on atable.id = temp.id where records >= 30 	0.00539048159600345
22458026	22300	how can i stop the php from showing the book twice if it has more than one author	select distinct bk.title as title, bk.year as year, bk.publisher as publisher, group_concat(aut.authorname) as author           from book bk           join book_category bk_cat           on bk_cat.book_id = bk.bookid          join categories cat           on cat.id = bk_cat.category_id          join books_authors bk_aut           on bk_aut.book_id = bk.bookid          join authors aut          on aut.id = bk_aut.author_id group by bk.title, bk.year, bk.pulisher 	4.81229357992527e-05
22458517	40015	sql server query that returns the number of likes and number of dislikes	select itemid,        description,        sum(case when type = 1 then 1 else 0 end) as like,        sum(case when type = 0 then 1 else 0 end) as dislike from table group by itemid,          description 	0.000151732143269506
22459467	31354	sql sum help - only returning 1 field	select users.id, users.name, sum(biproductprice) as utotalspent  from users  left join orders on uid = orduserid  left join basket on orduserid = buserid  left join basketitems on bid = bibasketid  where ordstatus between 4 and 50 group by users.uid, users.name 	0.114919786467023
22459576	40256	select all rows except if this condition is true	select count(*) as count  from $table_name  where shared_id = '{$shared_id}' and (processed != '0' or user_id != '1') 	0.0162740449786466
22459662	453	sorting private messages the newest at the bottom	select * from (     select * from table order by id desc limit 50 ) sub order by id asc 	0.000383723939780613
22460798	4600	join rows from 3 tables where tablea.column1 = tableb.column1 = tablec.column1	select * from tablea inner join tableb on tablea.id = tableb.id inner join tablec on tablea.id = tablec.id 	0.0356927034849545
22461121	40516	sql join with duplicate values	select   i1.cur_id,   i2.value,   p.price from   tbl_price p inner join tbl_id i1 on i1.id = p.id inner join tbl_id i2 on i1.cur_id = i2.id 	0.0568882053605649
22463250	24193	how to divide one column with another in mysql?	select ocena / st_ocen     from  filmi     where film = 'deadspeed 2013'    and st_ocen != 0 	0.000568171999308231
22464008	32775	relational division - mysql - get value name	select fld_name from (tbl_product_colors join tbl_product  on tbl_product_colors.fk_prod_id = tbl_product.fld_id) join  tbl_colors on tbl_product_colors.fk_color_id = tbl_colors.fld_id 	0.00820146727037811
22465653	18918	select all upcoming events where a user participate in	select e.*    from events e    join responses r     on r.event_id = e.id   join      ( select user             , event_id             , max(timestamp) max_timestamp          from responses          group            by user             , event_id      ) x     on x.user = r.user    and x.event_id = r.event_id    and x.max_timestamp = r.timestamp  where e.timestamp > now()     and r.user = 50     and r.canceled = 0     and e.deleted = 0; 	0.000760398945530875
22469544	26874	count rows returned by subquery	select title, count(distinct code) as [no. of codes] from tblsample  where category = 'com' group by title order by title 	0.039036467811236
22471615	24564	mysql grouping in a select statement	select reptiles, rodents from      (      select distinct count(an_id) as reptiles      from animals      where an_type in ('chelonian', 'crocodilian', 'lizard', 'snake')     ) rep,     (      select distinct count(an_id) as rodents      from animals      where an_type in ('hamster', 'porcupine', 'dormouse', 'capybara')     )rod 	0.330786150748632
22472744	8283	select a row or rows only when a status change in status column in oracle	select carid, carmodel, statusdate, statuscode, duration from (   select carstatus.*, lag(duration) over (order by carid, statusdate) as previous_duration   from carstatus ) where duration <> nvl(previous_duration,-1) order by carid, statusdate; 	0
22473409	27175	easiest way to select from 2 tables, with where condition in second	select your fields from entries as e inner join categories as c using (id) where c.category = 'default' 	0.00339482808997744
22473829	36862	how to remove 0 and/or null from row sql	select cl.cl_id, cl_name_last from vt_clients as cl inner join vt_animals as an on an.cl_id = cl.cl_id inner join vt_exam_headers as eh on eh.an_id = an.an_id inner join vt_exam_details as ed on ed.ex_id = eh.ex_id group by cl.cl_id, cl_name_last having sum(ed.ex_fee) >=300 and sum(ed.ex_fee) < 900 	0.00460839824890113
22474749	12930	how to return first place and ties?	select top 1 with ties an.an_id, an.an_name, count(eh.ex_date) as cnt from vt_animals as an inner join vt_exam_headers as eh on eh.an_id = an.an_id where an.an_type in ('snake', 'chelonian', 'crocodilian', 'lizard') group by an.an_id, an.an_name order by count(eh.ex_date) desc 	0.00276188199935961
22475963	7140	sql join 1 instance	select distinct     p.projectid,     p.title,     (select top 1 i.name from dbo.institution i       inner join dbo.projectinstitution pi on i.institutionid = pi.institutionid      where pi.projectid = p.projectid) as name,     p.startdate,     p.enddate,     ped.projectethicsdocumentid,     st.description as statustext from     dbo.project p     inner join dbo.workflowhistory w on p.projectid = w.projectid     left join dbo.projectethicsdocument ped on p.projectid = ped.projectid     left join dbo.status st on p.statusid = st.statusid 	0.314323751900636
22480922	3370	sql subqueries and group by	select ename    from emp  where sal > any (select avg(sal)                      from emp                    group by                           deptno) and deptno in (select deptno                from emp                group by                 deptno having count(deptno) > 4); 	0.765131675305536
22481983	5057	mysql query not exists	select books.isbn,books.bkname,books.cid     from books     left join issued on books.isbn = issued.isbn and issued.snr = :snr where books.cid = :course and issued.isbn is null order by books.isbn asc 	0.778728733627863
22486302	24880	sql: get array of numbers "id" column	select idr,count(*) as count_idr from table group by idr; 	0
22486543	14824	mysql: get result from 2 tables	select history.*, phonebook.photo from history inner join phonebook on phonebook.name = history.name  and history.id = $id 	0.000379749395261781
22488214	23314	difference between timestamp variable and time variable	select timestamp1 - interval '1 hour' * variable1 from table1 	0.00291416321423327
22488690	24952	tsql add two numbers	select     cast([firstshift] as decimal) + cast([secondshift] as decimal) as [total counted] from 	0.0067240670759901
22488838	15524	compute multiple queries in mysql	select t1.amount - t2.sum + t3.totalcost from (select amount from table1 where id = "1") as t1,       (select sum(hours * 10) as hours from table2 where empid = "1") as t2      (select totalcost from table3 where id = "1") as t3 	0.384807090486183
22489463	36495	sort by / order by time stored in database "00:00 - 23:00"	select *  from mytable  order by appointment_time asc 	0.197200030527261
22490028	35497	automatically open a report for a perimeter viavba?	select carrier.cid, carrier.cname, carrier.crepname, carrier.crepcontact, carrier.cbalance, carrier.creorderbalance from carrier where (([cid]=[forms]![carrier]![cid])); 	0.575164946863656
22490161	25268	multiple group by	select task, day, count(*) from table group by task, day 	0.212327767743199
22490589	27188	if statment with multiple column select	select oi.id as order_item_id, o.status, o.processed,     oba.item_id as buy_item_id,      oba.price as buy_price,      oba.condition as buy_condition from orders_items oi  left join books b on oi.isbn = b.isbn  left join orders o on o.id = oi.order_id  left join orders_bought_a oba on oba.id = oi.buy_order_id  where oi.location = 'a' union all select oi.id as order_item_id, o.status, o.processed,     obb.item_id as buy_item_id,      obb.price as buy_price,      obb.condition as buy_condition, from orders_items oi  left join books b on oi.isbn = b.isbn  left join orders o on o.id = oi.order_id  left join orders_bought_b obb on obb.id = oi.buy_order_id  where oi.location = 'b' order by date_ordered desc 	0.133771292715148
22491847	5821	mysql phpmyadmin, grabbing from multiple tables	select `product`,`name_id_2`,`name_id_1`, sum( `amount` ) as amount from table2 inner join table1 on `table2`.`name_id_1` = `table1`.`id_1` group by `name_id_2` 	0.0169220999714337
22491954	34472	find a column with one value for 2 different dates	select user_id, channel, count(distinct date)    from iptv_clean  group by user_id, channel having count(distinct date) > 1; 	0
22492117	19773	how to use t-sql linked server to get ms access data dictionary info for columns	select top 1 *  into #temp from [hcdb_current]..[dbo_vwhqi_ftnt] select name from tempdb.sys.columns  where object_id = object_id('tempdb..#temp'); drop table #temp; 	0.0077331571027229
22496761	29615	replace multiple characters in sql	select      table_value,      replace(replace(replace(replace(table_value, 'm', 'mxxting'), 'e', 'xmail'), 'p', 'phonx'), 'x', 'e') required_value  from foobar 	0.360020842429125
22497419	38614	query for select items where time after 12 o'clock	select visitno from   <table_name> where  extract(hour from cast(arrivaldate as timestamp)) >= 12; 	0.0138312333707186
22497642	8301	mysql group by with having	select t1.* from table1 t1 join  (select max(part) part ,ids from table1 group by ids ) t2 on(t1.ids=t2.ids and t1.part =t2.part) 	0.570570329828406
22499074	28927	how to get current financial year quarter in sql server?	select    'quarter '+cast(datepart(q,dateadd(mm,-3,getdate())) as varchar) as quarter 	0
22499753	19786	sorting date difference in sql	select datediff(hh,getutcdate(),end_date) as "duration" from mastertable order by case when duration >= 0 then 0 else 1 end,duration 	0.0342887056513176
22499949	32578	fetch the latest records from many-to-many relationship table	select t1.userid from tbluserservicelevel t1 inner join (     select userid, max (id) as maxid     from tbluserservicelevel     group by userid ) t2 on t1.userid = t2.userid and t1.id = t2.maxid inner join tblservicelevel sl on t1.servicelevelid = sl.id and sl.code <> 4 where t1.status = 'active' 	0
22500524	15691	sql find difference between two table	select  coalesce(b.displayname, a.displayname) displayname,         coalesce(b.lastname, a.lastname) lastname,         coalesce(b.diremail, a.diremail) diremail,         result = case when a.diremail is null then 'new'            when b.diremail is null then 'delete'                          else 'maintain'                 end from    vhris_staffdb b             full join hris_dl_lists a             on a.diremail = b.diremail where ( a.diremail is null or      a.displayname != b.displayname ) 	0.000237622679801898
22501622	4789	mysql combining 3 tables with 2 from same table	select matsh.*, mang.*, voistkonnad1.* , voistkonnad.*   from mang   inner join matsh on matsh.mang_id = mang.mang_id    inner join voistkonnad on matsh.voistkond_1_id = voistkonnad.voistkond_id   inner join voistkonnad as voistkonnad1 on matsh.voistkond_2_id = voistkonnad1.voistkond_id 	6.84392766850527e-05
22501809	17299	mysql- join multiple table depending on column	select user_id,first_name,last_name from m_user_info where user_id in  (select m_groups.group_creator_id as group_admin  from m_groups where m_groups.group_id='6'   union select m_group_admin.group_admin from m_group_admin  where m_group_admin .group_id='6';) 	0.00169912173361641
22502439	18631	sql server insert missing record	select  sitename     ,sum(case when datepart(mm,orderdate) = datepart(mm,getdate())                         and datepart(yyyy,orderdate) = datepart(yyyy,getdate())                         and 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') group by sitename order by sitename 	0.0799992049746647
22502597	10315	mysql query picking highest id using "where in" and limit, not returning enough results	select total from table1 join (     select max(id) as id     from table1     where campaign in ('car', 'van', 'bike', 'bus')     group by campaign ) t on t.id = table1.id 	0.02664885541807
22504055	31739	get date from database in php	select date(column_datetime) as date from yourtable 	0.000920353779239105
22506390	11498	select earliest of two nullable datetimes	select if(date1 is null or date2 is null,            coalesce(date1, date2),            least(date1, date2)        ) as earlydate  from mytable 	0.000340375672682557
22507569	20687	search in table where search phrase is stored in two separate rows	select s1.id as id1, s2.id as id2 from sentences s1 join      sentences s2      on s1.creator_id = s2.creator_id and         s1.order = s2.order - 1 where s1.text like '%first part%' and       s2.text like '%second part%'; 	0.0059440726664033
22508492	32434	sql: query contains at least one "true" value	select idt, nome, bool1 from path where idt in (   select idt from path where bool1 = 'true'); select path.idt, nome, bool1 from path inner join   (select distinct idt from path where bool1 = 'true') q on path.idt = q.idt; 	0.000587804878794322
22509413	20075	mysql find all the possible combinations of one column	select a.contact_id a, b.contact_id b from   usercontacts a   join usercontacts b on b.contact_id > a.contact_id 	0
22510624	23946	split city, state, zip from one column into 3 separate, also add dash to 9 digit zips	select      [city],     [state],     case len([zip])         when 5 then [zip]         when 9 then stuff([zip],6,0,'-')     end [zip] from (     select          left([city state zip],charindex(',',[city state zip])-1) [city],         substring([city state zip],charindex(',',[city state zip])+2,2) [state],         right([city state zip],charindex(' ',reverse([city state zip]))-1) [zip]     from dbo.foo ) a 	0
22510736	14211	mysql - select only numeric values from varchar column	select * from mixedvalues where value regexp '^[0-9]+$'; 	0.000142576182271267
22511224	10660	stuck with a sum in a sum	select k.id,     k.price1,     k.price2,     sum(h.price3) as "idontwork",     k.price4,     k.price5,     k.price6,      k.price1+k.price2+sum(h.price3) as firsttotal,     (k.price4+k.price5+k.price6) as secondtotal,     (k.price1+k.price2)+sum(h.price3)-(k.price4+k.price5+k.price6) as finaltotal, from table1 k, table2 h where k.id=h.id group by k.id,k.price1,k.price2,k.price4,k.price5,k.price6; 	0.38792653508878
22515816	23594	query wins and losses with score	select team, sum(win) as won, sum(loss) as lost, sum(score) as score from ( select team_one as team,       case when one_score > two_score then 1 else 0 end as win,       case when one_score < two_score then 1 else 0 end as loss, one_score as score   from matches   union all   select team_two as team      case when two_score > one_score then 1 else 0 end as win,       case when two_score < one_score then 1 else 0 end as loss, two_score as score   from matches ) t group by team order by won, lost desc, score 	0.337707103908215
22517145	37183	subtracting data from a week ago using a subquery in mysql	select i.date_key, i.converts, i.converts / j.`starts` from (     select t2.`date_key`,     count(id) as `starts`     from `table2` as t2     where date_key between '2014-02-25' and '2014-03-03'     group by t2.`date_key` ) as j join (     select t1.`date_key`,     count(id) as converts     from `table` as t1     where date_key between '2014-03-04' and '2014-04-11'     group by t1.`date_key` ) as i on i.`date_key`=date_add(j.`date_key`, interval 7 day); 	7.68464032947733e-05
22517859	30832	sql counting values and selecting column name as result	select 'a', sum(a) from table union select 'b', sum(b) from table 	0.000225820441747695
22522485	8486	how do i pass a muti-column datatable with n number of rows as a csv?	select column + ',' from table for xml path('') where condition 	0.000103097896056034
22522840	5872	select from table where timestamp is within x seconds	select *   from notifs  where foo = 'bar'    and timestamp between unix_timestamp(now() - interval 15 second)                       and unix_timestamp(now()) 	0.00014264199062292
22524273	7553	how to get records which matches most to lesser criteria for user search?	select    *,   case when productname='prod#1' then 1 else 0 end +   ...   case when city='city#1'        then 1 else 0 end +   ...   case when country='country'    then 1 else 0 end rank from search order by rank desc limit 12 	0
22526564	31751	grouping a column, and then subtracting rows?	select      sum(traderquantity - invoicedquantity) as balance,      partid,      sum(invoicedquantity) as totalinvoicedquantity,     sum(traderquantity) as totaltraderquantity from      orderitems   where      status = 'active'     and ordertype = 'po' group by      partid order by      partid 	0.000272133175469463
22528318	684	search for values apart from the letter case - oracle	select company_name  from   companies  where  upper(companies) in ('abc', 'def', 'bde', 'mno'); 	0.0068538247733012
22530079	10709	how to get order by last name if single field "name" contains both first name and last name	select * from `table` order by   substring_index(`name`, ' ', -1); 	0
22530103	21420	to get the multiple maximum-count of repeated values in mysql	select     distinct g.customer_id,     g.cnt from     (     select         distinct customer_id,         count(customer_id) cnt     from         table     group by          customer_id     ) g inner join     (     select         max(s.cnt) max_cnt     from         (         select             distinct customer_id,             count(customer_id) cnt         from             table         group by             customer_id         ) s     ) m on     m.max_cnt = g.cnt 	0.000347800703784163
22530108	29307	how to give alias to results returned after inner join in mysql	select      distinct p.name,     count(d.mid) cnt from      hindi2_person p inner join      hindi2_m_director d on      p.pid = d.pid group by     p.name having count(d.mid) > 9 ; 	0.783081621212087
22530480	16103	timestamp having milliseconds convert to seconds in oracle	select extract(second from to_timestamp(p_request_time)-to_timestamp(p_response_time)) diff_seconds from <table_name>; 	0.00821926100126831
22530483	33044	how to limit mysql search result from multiple tables?	select     r.'route-id',     s.'station id',     s.'stop-time' from     routes r inner join     trips t on     r.'route-id' = t.'route-id' inner join     stop-times s on     t.'trip id' = s.'trip id' where     r.'route-name' = 'your_route_name' and     s.'station id' = your_station_id 	0.00852703825247198
22532027	5924	row to column in mysql database.	select two.stname, sum(smark*(1-abs(sign(sname)))) as en, sum(smark*(1-abs(sign(sname)))) as mat, sum(smark*(1-abs(sign(sname)))) as phy from a1 as one left join a2 as two on one.sid=two.stid group by sname; 	0.0061120097837441
22532246	1991	counting the distinct columns(2 columns) value	select     column1,     column2,     count(*) as column3 from     yourtable group by column1, column2 	0.000414168185021592
22532724	15582	possible to have two between in one query?	select ph, chlorine, temperature, date, time  from googlechart  where date between '2014-03-19' and '2014-03-21' and time between '15:00' and '20:00'  order by date, time; 	0.0021011723428841
22532972	38308	how to compare information schema column with table column in sql server2008 using inner join?	select * from a1 a inner join information_schema.columns c on c.column_name = a.a1 where c.table_name = 'b' 	0.0133665572451615
22533670	27844	how to access table when the name is a keyword	select * from `as` 	0.138712050077268
22534519	9481	date format sqlite 3	select id_column from table where strftime('%y-%m-%d', date_camp)='2014-01-01' 	0.0416954030414033
22534576	35916	multiple counts on same table in mysql	select m.year, @tot:= (select count(*) from hindi2_movie as yaar where yaar.year = m.year),count(m.title)/(@tot)*100 as perc from hindi2_movie as m where not exists (select * from hindi2_m_cast as c,hindi2_person as p where c.pid=p.pid and c.mid=m.mid and p.gender='m') and exists(select * from hindi2_m_cast as c,hindi2_person as p where c.pid=p.pid and c.mid=m.mid and gender='f') group by m.year; 	0.0016717229244386
22534780	3969	sql query to pick up values on some rules	select cg.code, tmin.type, tmax.des, tmin.sr     from (           select code, min(sr) as minsr, max(sr) as maxsr           from table           group by code          ) cg     inner join table tmin on cg.code = tmin.code                              and cg.minsr = tmin.sr     inner join table tmax on cg.code = tmax.code                              and cg.maxsr = tmax.sr 	0.0130233567366211
22535807	14471	sql server statement	select count(leads), county, state from table where state = 'texas' group by county, state 	0.792506887640035
22535849	23892	sql adding the same char into multiple fields	select substring('06037-11' from 1 for (position('-' in '06037-11') -1))     || '0-'     || substring('06037-11' from (position('-' in '06037-11') + 1)) 	0.000537744526454352
22536475	29894	mysql: union two columns with count	select   city,   count(1) as c,   concat(100*count(1)/sums.total, '%') as p from   (select  from_city as city from t   union all   select to_city from t) as cities   cross join   (select       count(from_city)     +count(to_city) as total   from t) as sums group by   city order by    c desc 	0.013659819192379
22536570	11622	mysql where condition groupings from remote table	select distinct shop_products.* from shop_products join shop_products_filters on  (shop_products.id = shop_products_filters.product_id) where category_id = '2' and price >= '1.00' and price <= '10.00'  and exists( select 1 from shop_products_filters where filter_category_id = '161' and filter_option_id in (1046,1051)) and exists( select 1 from shop_products_filters where filter_category_id = '162' and filter_option_id in (1057,1058)) order by price asc 	0.189665036834768
22538867	3189	sumif access - multiple tables	select broker.brkr_code,        sum(opt.com_brkr1)+ sum(opt.com_brkr2) as opt_tot,        sum(trs.com_brkr1)+ sum(trs.com_brkr2) as trs_tot from (broker       inner join  opt      on (broker.brkr_code = opt.brkr2) or (broker.brkr_code = opt.brkr1))       inner join  trs      on (broker.brkr_code = trs.brkr2) or (broker.brkr_code = trs.brkr1) where broker.status = "active" group by broker.brkr_code 	0.260695784011665
22539639	34089	custom postgres function for term dates and times	select * from     t     left join     holiday on date_trunc('day', t.ts) = holiday.day where     extract(dow from ts) in (0, 6)      or     (extract(hour from ts) >= 18 and extract(hour from ts) <= 8)     or     holiday.day is not null  	0.234607654200601
22540584	38286	excluding some results from sql query	select us.username, ur.username  from requests r  join users us on us.userid = r.sender  join users ur on ur.userid = r.reciever where (us.username = ? or ur.username = ?)   and r.response = 1   and not exists (     select 1 from circles c     join circlemembers cm on c.circleid = cm.circleid     where c.name = ?     and cm.userid in (us.userid, ur.userid)   ) 	0.0214050836135885
22540884	18899	oracle - char(39)	select chr(39) from dual 	0.761542701354177
22542602	35053	find nearest record (before or after) to a given date/timestamp	select distinct on (t1.date, t1.customer)     t1.date, t1.customer, t1.price,     t1.price - t2.price as price_diff,     abs(extract(epoch from (t1.date - t2.date))) as seconds_diff  from     tmp t1     inner join     tmp t2 on t1.customer != t2.customer order by t1.date desc, t1.customer, seconds_diff 	0.000118651106061298
22542917	30880	how to sort an array using specific index value?	select distinct u.user_fb_id, sum(u.points) as total_points, r.user_firstname, r.user_lastname  from user_points u, user r  where u.match_id >= 2300 and r.user_id = u.user_fb_id  order by total_points desc; 	0.0054931933929745
22543321	18196	decompose source data into new, many-to-many schema	select distinct rxcui, [name] into drugwordsconsojunction from words 	0.017280478207735
22545419	8788	mysql error 1452 (23000): cannot add or update a child row: a foreign key constraint fails another issue	select * from states; 	0.0124262897596441
22545722	18718	query for multiple tables	select distinct p.productname from orders o inner join customerdata c on o.customeroid = c.customeroid inner join products p on o.productoid = p.productoid where c.state = 'ca'; 	0.15373451284974
22546082	24578	how to get only those rows where the next row (by datestamp) has a different property in some field?	select     * from dbo.dms_audt d1 cross apply (      select top 1         *     from dbo.tbl_audt x     where   d1.o_objguid = x.o_objguid         and d1.o_acttime < x.o_acttime     order by x.o_acttime ) d2 where   d1.o_action = 1012     and d2.o_action != 1012 	0
22546237	14454	sql looking up values on three joined tables	select c.car_id,p1.coord as origin_coord, p2.coord as dest_coord from cars as c join buildings as b1 on b1.build_id=c.origin join buildings as b2 on b2.build_id=c.destination join plots as p1 on p1.plot_id=b1.plot join plots as p2 on p2.plot_id=b2.plot 	0.00997075111047531
22546847	33737	codeigniter: multiple count and sum from one table	select sum(if(status=1 and user_id=x, 1, 0)) as v1, sum(if(status=1 and user_id=x, ads, 0)) as v2, sum(if(status=0 and user_id=x, 1, 0)) as v3, sum(if(status=0 and user_id=x, ads, 0)) as v4 from table) 	0.000475304429838251
22550512	17241	select table from accessexclusivelock locked table	select reltuples from pg_class where oid='test_table'::regclass; 	0.00274191631895112
22551902	24096	check mysql version of domain provider	select version(); 	0.0843340200351619
22552745	12035	how to find radius of geometry in postgis?	select st_contains ((select the_geom from gis.city_border),(select the_geom from geofence)) 	0.0493080303994019
22554237	19699	how to select a field corresponding to the tuple in which max(anotehrfield) exists	select article, dealer, price  from   shop where  price=(select max(price) from shop); 	0.000315795225368641
22554595	5685	sql match exact set of values between two tables	select top 1 pcr1.groupid from table1 pcr1 where not exists (select campaignid from table1 as pcr2 where campaignid = @campaignid and pcr2.groupid= pcr1.groupid except select t2.package from table2 as t2 where t2.orderid = @ordid) group by pcr1.groupid  order by count(pcr1.groupid) desc 	4.70271784620737e-05
22558371	12190	get ranking of query when getting a single entry	select * from (select @currank := @currank + 1 as rank, $wpdb->posts.*,              (select count(*) from likes l where l.postid = $wpdb->posts.id) as totallikes       from $wpdb->posts cross join (select @currank := 0) r       where $wpdb->posts.post_type = 'post' and $wpdb->posts.post_status = 'publish'       order by totallikes desc      ) t where <whatever condition you want>; 	0.0003641386858722
22558580	18560	how to convert my data from row to column ?	select  [0 - 10],      [11 - 20],      [21 - 30],      [31 - 40],      [41 - 50],      [51 - 60],      [61 - 70],      [71 - 80],      [81 - 90],      [91 - 100],      [101 - 9999]  from (         select row_number() over(partition by [level] order by [count]) as [rownumber],                  [level],                  [count]              from tablename       )  as t             pivot (min([count])                 for [level] in ([0 - 10], [11 - 20], [21 - 30], [31 - 40], [41 - 50], [51 - 60], [61 - 70], [71 - 80], [81 - 90], [91 - 100], [101 - 9999])                 ) as p 	0.00340866418040984
22559095	4209	retrieve a record that has 2 specific features in sql	select picture.name from picture  join features  on picture.id=features.pictureid where features.name in('portrait','big') group by features.pictureid having count(distinct features.id)>=2 	0
22561330	24652	counting rows for some predefined data	select label, count(*) from (select t.*,              (select t2.label               from test t2               where t2.date < t.date               order by t2.date desc               limit 1              ) as prevlabel       from test t      ) t where prevlabel = 'b' group by label; 	0.00197377104848311
22562871	11361	select only if related entities collumn contains specific value	select c.pkid, c.name from company c inner join license l on c.pkid=l.companyid where l.name like '%test%' except select c.pkid, c.name from company c inner join license l on c.pkid=l.companyid where l.name not like '%test%' 	0.000115824777729202
22564799	22562	condition in oracle sql query	select * from emp where emp.id in(1,2,3) and (design.type<>'labor' or emp.sal>10000) 	0.742862538525733
22565039	40950	error using a value in a range condition	select count(*) as july     from sinisters   where date between concat(@year, "-07-01") and concat(@year, "-07-31") 	0.0737668116033676
22566088	8583	selecting rows and filler (null data)	select ins.reportid, teams.teamid, ins.inning, score.runs from games as ins join games as teams     on ins.reportid = teams.reportid left join games as score     on ins.reportid = score.reportid     and teams.teamid = score.teamid     and ins.inning = score.inning group by ins.reportid, teams.teamid, ins.inning; 	0.00302196365986588
22568662	13177	mysql fetch rows and count how many of them have a certain amount of characters	select count(*) as totalusers,        sum(length(userid) = 15) as num15s,        sum(length(userid) = 30) as num30s,        sum(length(userid) not in (15, 30)) as oopsiwaswrongsomearenotlength15or30 from users; 	0
22569524	21159	string comparison in ms sql	select subj_code, crse_code         from section_info         where (cast(left(crse_code,3) as int) as num between 800 and 899) and subj_code = 'acc'         order by crse_code 	0.692432990997761
22569672	9282	get max value based on specific field	select city, max(age) from people group by city 	0
22571910	18102	mysqli seaching for two values even if one is not present	select cover,id,price from songs where (genre=?) or (artist=?) 	0.00287190862922187
22572353	19267	how to change the last line of this query to inner join	select format(((sum(sureness)/count(*))+1)/2, 4) from tweet  inner join entity_topic_epoch_dataitem_relation r on r.dataitemid = tweet.id inner join epoch on epoch.id = r.epochid  inner join omit.entity as o on r.entityid = o.entityid where epoch.startdatetime >= '2013/12/05'  and epoch.enddatetime <='2013/12/10' and dataitemtype=3  and o.partyid=1; 	0.01814053975432
22572591	27401	using a case statement to change the value of a cell	select o.order_number, o.order_date, ol.line_number, ol.line_type, ol.sku,    case when ol.line_type = 'shipping' then 'shipping charges'         when ol.line_type = 'tax' then 'tax charges'         else p.title         end as price, round(ol.price,2) as price, ol.quantity, sum(ol.price * ol.quantity) as total_price from hr.bc_orders o inner join hr.bc_orderlines ol on o.order_number = ol.order_number left join hr.bc_products p on ol.sku = p.sku where o.order_number = 'o21010469' group by o.order_number, o.order_date, ol.line_number, ol.line_type, ol.sku,    case when ol.line_type = 'shipping' then 'shipping charges'         when ol.line_type = 'tax' then 'tax charges'         else p.title         end, round(ol.price,2), ol.quantity  order by ol.line_number; 	0.0064021410298188
22573836	27194	record filtration issue	select * from agents a where railenabled = 1      and not exists (select 1                   from userpermissions b                 where a.companyid = b.companyid                 and b.modulecode = 'ral'                 and b.enabled = 1                 ); 	0.72334186500906
22574649	40792	replace data in a column for a character in sql	select      description,      isnull(        reverse(stuff(reverse(name), charindex(',', reverse(name), 0),1,'dna ')),      name) name from yourtable 	0.0528313493643362
22575493	38030	how i can order mysql with rate to every column	select * , (likes * 2 + views * 1) as count from tablename order by count asc 	0.00769227659484588
22575548	36592	top 2 distinct in sql	select t1.*  from table t1 join (select status, max(date) as maxdate       from table       group by status) m on m.status = t1.status and m.maxdate = t1.date 	0.013393532284277
22576392	36879	select top 1 row for distinct id sqlite	select b.*  from  ( select id, max(time) as time from yourtable group by id) a inner join yourtable b on a.time = b.time and a.id = b.id 	0.000171878368717609
22577230	29270	select top 1 for distinct value according to time	select tblmyfriends.friendid,        tblmyfriends.groupid,        tblmessages.mymessage,        max(tblmessages.mytime) from tblmyfriends left join tblmessages        on coalesce(tblmyfriends.friendid, tblmyfriends.groupid) =           coalesce(tblmessages.friendid,  tblmessages.groupid) group by tblmyfriends.friendid,          tblmyfriends.groupid 	5.73584301145405e-05
22578327	24286	sql searching part of a sentence in two fields simultaniously	select post_name, org_name from table  where post_name + org_name  like 'searchterm%'; 	0.00907786914775449
22581908	23240	sum of differences between rows in table	select sum(time_to_sec(differences)) from (select sec_to_time(timestampdiff(second,min(timestamp),max(timestamp)))as differences  from table group by callid)x 	4.86330866668854e-05
22582254	6300	select between 2 tables and find the user	select     cr.reply_user_id from     comments_reply cr join comments c on cr.comments_id = c.comments_id and cr.reply_user_id = c.user where     cr.reply_flag = 1 group by     cr.reply_user_id 	9.67787781788321e-05
22585915	5049	select 2 tables from 1 database in php mysql	select * from (    select username as user, password as pwd     from admininfo     where username='$username' and password='$password' and type='admin')    union     (select username as user, password as pwd     from customerinfo     where username='$username' and password='$password' and type='customer')  )"; 	0.00106878313356833
22586931	30771	mysql how to obtain the min and max of the top 100 values in a table	select max(best_game_score) as max_bgs , min(best_game_score) as min_bgs from (select best_game_score       from user       order by best_game_score desc       limit 100      ) u; 	0
22587108	25947	report weekly in php mysql from form field	select ... ... where (year(timestamp) = 2013) and (month(timestamp) = 10) group by year(timestamp), month(timestamp) 	0.00436933524385263
22587409	11614	select all rows which column has not already returned existing result	select * from tablename  where street in (     select distinct street from tablename ) limit 1; 	0
22589219	13463	performance based count for total number of users registered	select count(id) from user_table 	0
22589980	35975	mysql concat two columns if	select concat('http: 	0.0121522050832732
22590554	25767	mysql select after where	select count(*)  from table_a as a, table_b as b  where a.something=0 and b.active=1 and  (    select avg(c.rating)    from table_rating as c    where c.id=a.id  ) >= $rating 	0.279919350619804
22590602	35292	check if values exist in two mysql tables	select name, if(age =''  or age is null, 'empty',age) age   from   table1   join   table2    on table1.id = table2.user_id 	0.000967428024457566
22590754	37012	sqlite select default rows if not exists	select * from tphones where dept = ?   and (hid = ? or (hid = 1 and                    not exists (select 1                                from tphones                                where dept = ?                                  and hid = ?))) order by location 	0.0490929414888353
22592591	14280	limit only on one of tables in join	select * from  `gallery` g inner join  (select * from  `product` limit 5) p  on( p.product_id = g.product_id ) 	0.00107631726288625
22593554	13783	mysql prevent duplicates in a specific table field	select      m.id,              m.movie_title,              m.movie_description,              m.movie_url,              m.movie_actors,              m.movie_thumbnail,              m.time_uploaded,              m.movie_categories  from        movie_comments mc left join   movies m     on      mc.movies_id = movies.id  where       movie_status=1  group by    m.id,              m.movie_title,              m.movie_description,              m.movie_url,              m.movie_actors,              m.movie_thumbnail,              m.time_uploaded,              m.movie_categories order by    max(mc.time_posted) desc  limit 10; 	0.00202756172363216
22594820	31403	is it possible to combine 'distinct' and 'count' queries, so that i can see how many times each distinct value appears?	select field, count(*) from table group by field 	0
22596000	22083	get percentage of appearance of a certain value in mysql 2	select version,         count(*) / const.cnt ,        mytable.post_id from   mytable  inner join (select post_id, count(*) as cnt             from   mytable            group by post_id) const  on mytable.post_id = const.post_id group  by version, post_id order  by version; 	0
22596073	7021	mysql to select row with unique column value comparing with other columns	select *  from new_table where concat( col1,  ' ', col2,  ' ', col3 ) like  "%red%" and col1 <> col2 and col2 <> col3 and col1 <> col3; 	0
22597243	40487	user votes table	select count(*) from votes where reportname = $id and userid = $_session['sess_uid']; 	0.0215662033063255
22598708	13344	how to group rows in a single sql query?	select    ip  , count(ip) as count  , group_concat(compaignid) as campaigns from table_name group by ip 	0.009567306928696
22600653	28917	query a query's column name in sql server	select t1.res.value('local-name(.)', 'varchar(50)') from (select cast( (     select count(*) as amount from test     for xml raw) as xml )) q(res) cross apply q.res.nodes('/row/@*') as t1(res) 	0.218135630637406
22601688	36347	date time format in sql server	select cast(datepart(d, dt) as nvarchar(2)) +    case datepart(d, dt)  when 1  then 'st' when 2 then 'nd'                         when 3  then 'rd' when 21 then 'st'                         when 22 then 'nd' when 23 then 'rd'                          when 31 then 'st' else 'th' end +   cast(substring(convert(nvarchar(256), dt, 106), 3, 256) as nvarchar(256)) as [mydate] from test; 	0.0550094901707064
22601841	37562	sort a mysql table column value by part of its value	select * from sample order by right(id, 3); 	0
22601880	28110	individual studio count in a table	select      studio_name,     count(*) region from sheet7  where merchant='buy vip' and      retouch_level=9 group by studio_name 	0.0967454058329572
22601922	2706	ordering row having same values in two columns on top	select * from tbltest  order by case when userid = playerid then 0 else 1 end 	0
22602262	39479	how to use case plus join plus group by into a single mysql statement	select b.*,sc.cate_name,(     case when special_offer_type ='fixed value'     then b.price - special_offer     when special_offer_type =  'discount %'     then b.price * ( 1 - special_offer / 100.0 )      else b.price     end     ) as final_price,     ifnull(xx.avg_rate,'0'),     ifnull(yy.count_comment,'0')     from book b join setting_category sc on b.cate_id = sc.cate_id      left join (select a.isbn,sum(a.rate)/count(a.rate) as avg_rate      from book_rating a      group by a.isbn) as xx on b.isbn = xx.isbn      left join (select c.isbn,count(*) as count_comment from book_comment c      group by c.isbn) as yy on b.isbn = yy.isbn 	0.554738386063783
22602941	37710	logic of applying group by in sql queries	select messagegroup,count(messagegroup)from tblmessage  where senderid=2  group by messagegroup 	0.727281570740231
22603140	14679	return only last row left join	select msg.userid, msg.messages, users.fullname,    (select max(path) from profile where profile.userid = msg.userid) as maxpath from messages as msg left join users on msg.userid = md5( users.userid ) order by msg.date asc; 	0.000367125273929082
22604048	4575	get median value of a time period in sql server 2005, 2008 server	select min(license_count) min_lic     , max(license_count) max_lic     , avg(license_count) avg_lic     , sum(case when ra between rd - 1 and rd + 1 then license_count else 0 end) * 1.0     / sum(case when ra between rd - 1 and rd + 1 then 1 else 0 end) as median_lic     , datepart(month, created_at) monat from (     select created_at         , license_count         , row_number() over (partition by datepart(month, created_at) order by license_count, created_at) as ra         , row_number() over (partition by datepart(month, created_at) order by license_count desc, created_at desc) as rd     from session_counts     where created_at between '01.01.2014' and '31.12.2014' ) t group by datepart(month, created_at) order by monat desc 	0.000902994286233833
22606118	38229	mysql: join with special character in column name	select * from shipment right join truck on `shipment`.`truck_#`=`truck`.`truck_#` 	0.315219867647523
22606161	16556	difference between timestamps in milliseconds in oracle	select   extract(second from systimestamp - doj) * 1000 from   test1; 	0.00121600063645159
22607597	37519	how to get the name of the currently executing trigger and the name of the table it is attached to, in sql server?	select name tablename, object_name(@@procid) triggername from sys.objects where object_id = (select parent_object_id                    from sys.objects                    where name = object_name(@@procid)) 	0
22611525	5601	sql statement returns only rows that exist also in the joined table	select * from products where not exists (   select *   from orders   where product_id = products.product_id    and order_date < somedate  ); 	0
22611717	18830	skipping ranking in rows which do not meet required value from mysql sorted ranking with ties?	select regd, sum(if(subject = 'english'    , mark_score, 0)) english,             sum(if(subject = 'mil'       , mark_score, 0)) mil,             sum(if(subject = 'mathematics', mark_score, 0)) mathematics,              sum(if(subject = 'ss'         , mark_score, 0)) ss,             sum(if(subject = 'science'    , mark_score, 0)) science,             mark_score, perc             from (         select regd, subject,(sum(mark_score) / sum(full_mark) * 100) perc , (sum(mark_score)) mark_score         from exam e1         group by regd, subject         having perc > 35         ) as t           order by mark_score; 	7.60829313530778e-05
22611892	11965	how to count one column, having a condition where an element is null and another where the element is not null? everything grouped by another element	select cy.name,         sum(case when noa.gz_aparat_id is null then 0                   when  noa.gz_aparat_idis not null then 1                   end) as countnonnull,         sum(case when noa.gz_aparat_id is null then 1                   when  noa.gz_aparat_id is not null then 0                   end) as countnull   from gz_nominalizare_aparat noa    inner join gz_nominalizare no on (no.gz_nominalizare_id = noa.gz_nominalizare_id)   inner join gz_acordacces aa on (aa.gz_acordacces_id = no.gz_acordacces_id)   inner join gz_abonament ab on (ab.gz_abonament_id = aa.gz_abonament_id)   inner join gz_punctconsum pc on (pc.gz_abonament_id = ab.gz_abonament_id)   inner join gz_iu iu on (iu.gz_punctconsum_id = pc.gz_punctconsum_id)   left outer join c_bpartner_location bplo on (ab.c_bpartner_location_id = bplo.c_bpartner_location_id)   left outer join c_location lo on (bplo.c_location_id = lo.c_location_id)   left outer join c_city cy on (lo.c_city_id = cy.c_city_id) group by cy.name 	0
22613205	18372	mysql - fastest way to find rows having common field	select t.* from table t join table t2 on t2.col2 = t.col2 where t2.col1 = 'some value' 	0.000170453498283393
22613446	5449	finding combinations of rows that combined do not exceed a value in mysql	select x.size+y.size+z.size size      , x.score+y.score+z.score score      , x.value+y.value+z.value value    from items x    join items y      on y.id < x.id    join items z      on z.id < y.id  having size = 14     and score = 11     and value = 13; 	0
22613525	20435	how to properly link 2 sql tables with a referential table	select d.dname        ,c.cname     from car_dealer cd     join car c         on cd.cid = c.cid     join dealer d         on cd.did = d.did     where cd.did = 200; select d.dname        ,c.cname     from car_dealer cd     join car c         on cd.cid = c.cid     join dealer d         on cd.did = d.did     where cd.cid = 4; 	0.281156305470481
22614460	11232	sql case expression returning multiple rows	select tbl.id   from table1 tbl  where ( [some condition] and tbl.id = [a single id number]) or ( not [some condition] and tbl.id in ( select tbl2.id                                            from table2 tbl2                                           where [some other condition]) 	0.778368265247552
22615761	2099	get related posts by tags	select *, sum(`postsa_tags`.`tag` = `postsb_tags`.`tag`) as rel from `postsb_tags` left outer join `postsa_tags` `postsa_tags` on(`postsa_tags`.`tag` = `postsb_tags`.`tag`) group by `postsb_tags`.`postid` order by rel desc 	0.000120249377145282
22616742	16165	amalgamating rows in a table and ommitting null values	select id, max(preoporg) as preoporg, max(preoptreatment) as preoptreatment,        max(postoporg) as postoporg, max(postoptreatment) as postoptreatment from table t group by id; 	0.00159482225812761
22619000	3506	how to summarize two tables in teradata	select t2.datex, t2.caseid, sum(t1.points) from table1 as t1 join table2 a t2  on position(trim(t1.caseid) in t2.caseid) > 0 group by 1,2 	0.0319808330007129
22624171	35185	select previous record in sql server 2008	select t1.id, t1.[group], t1.value      , coalesce(max(t2.value),0) as prev_value      , t1.value - coalesce(max(t2.value),0) as result from mytable t1 left join mytable t2 on t2.[group] = t1.[group] and t2.value < t1.value group by t1.id, t1.[group], t1.value 	0.0168235138489163
22624194	6546	mysql calculation several column	select service_id,(labor hours * labor cost per hour + part cost) from  service s inner jion   rate r on r.rate=s.rate  where  (labor hours * labor cost per hour + part cost) > 500 	0.0950749228750032
22624725	31873	how to create horizontal columns from rows in mysql?	select       g.studnumber,       g.subjcode,       max( case when g.period = 1 then g.grade else 0 end ) as 1st_period,       max( case when g.period = 2 then g.grade else 0 end ) as 2nd_period,       max( case when g.period = 3 then g.grade else 0 end ) as 3rd_period,       max( case when g.period = 4 then g.grade else 0 end ) as 4th_period,       avg( g.grade ) as ave    from       grades g    group by        g.studnumber,       g.subjcode 	9.40412566387709e-05
22624851	5985	mysql joining 3 tables with one being a link table	select faq_title from faq f join faq_link_category flc on f.faq_id = flc.faq_id join category c on flc.category_id = c.category_id where flc.category_id = 6 	0.00181743291872604
22624860	39572	my sql join more than 5 tables	select  quote.quote_id, quote.notes, quote.is_quote_active, quote.created_timestamp, category.category_name, subcategory.subcategory_name, rural.rural_name, region.region_name, country.country_name, s.name as sname, r.name as rname    from quote          left join category on quote.category_id = category.category_id    left join subcategory on quote.subcategory_id = subcategory.subcategory_id    left join country on quote.country_id = country.country_id    left join region on quote.region_id = region.region_id    left join rural on quote.rural_id = rural.rural_id    left join user s on quote.sender_uid = s.uid     left join user r on quote.receiver_uid = r.uid 	0.242293973457386
22625792	37487	correct mysql query to query one table and have that provide information for another table query	select members.id, members.username, posts.* from members inner join posts on members.id = posts.member_id where members.active='y' and members.gender='m' and members.city='yuma' and members.state='arizona' order by posts.list_weight desc 	0.000912286826219998
22626692	6040	mysql: grouping a data by multiple fields	select criteria1 'criteria',sum(amt) from yourtable where (criteria1 = 'a') group by criteria1 union select criteria2 'criteria',sum(amt) from yourtable where (criteria2 = 'b') group by criteria2 	0.0158687403217728
22627667	40356	how to check for user defined tables in postgres?	select count(*) as cnt from pg_tables t where tableowner=current_user  and tablename='tablename'  and schemaname='schemaneme' if cnt = 0 then (create table tablename) 	0.0076248107600483
22629307	9594	mysql select where max date and max time	select * from (   select b.id, b.checkdate, b.checktime, b.accountid, b.costcenter, b.percentage, c.id, c.name        from buckets b join customeraccounts ca on (b.accountid= ca.linkedaccountid)                  join customer c on (ca.customerid = c.id) ) as s join  (   select max(checkdate) as maxdate,max(checktime) as maxtime from buckets ) as t on t.maxdate = s.checkdate and s.checktime = t.maxtime 	0.00835073388900723
22629690	30967	i got stuck on multiple select	select star      , is      , evil      , case when evil = 1 then star else null end as we_can_refer_to_this_now from   (         select star              , is              , case when column = 'a' then 1 else 0 end as evil         from   ...        ) as a_subquery where  evil in (1, 0) 	0.705692288751198
22630577	29769	limit results in join	select  q.proj_name,         q.proj_phase,         q.proj_actions_next_action,         q.proj_actions_next_action_date from ( select     a.proj_name,     a.proj_phase,     c.proj_actions_next_action,     c.proj_actions_next_action_date,     row_number() over (partition by a.proj_name             order by c.proj_actions_next_action_date desc) as rn     ,b.clientname from     projects a   left outer join     projects_actions c         on a.proj_id = c.proj_actions_projects_link left outer join     clients b         on a.proj_clientlink = b.client_id     )q where q.rn = 1 order by q.clientname 	0.504667442118369
22634528	40856	join 3 different tables based on type of post	select a.id, a.type, a.postid, a.timestamp, b.message, c.photo, c.caption from posts a left outer join posts_messages b on a.postid = b.id and a.type = 1 left outer join posts_photosposts_photos c on a.postid = c.id and a.type = 2 	0
22638628	31281	get users which i have friends in common	select * from users where user_id in (   select user1_id   from   (      select userfriends_user_id as user1_id, userfriends_friend_id as user2_id      from userfriends where userfriends_user_id != 1 and userfriends_friend_id != 1     union      select userfriends_friend_id as user1_id, userfriends_user_id as user2_id      from userfriends where userfriends_user_id != 1 and userfriends_friend_id != 1   ) others   where user2_id in   (      select userfriends_user_id from userfriends where userfriends_friend_id = 1     union     select userfriends_friend_id from userfriends where userfriends_user_id = 1   ) ); 	0
22640246	25817	trouble forming a single mysql query to sum values in a table	select sum(value) from foo inner join (     select id, max(`time`) as maxtime     from foo     where time(`time`) between '18:00:00' and '19:00:00'     and parameter = 'a'     group by id ) sub1 on foo.id = sub1.id and foo.`time` = sub1.maxtime 	0.0381022582783376
22640270	35780	mysql calculation results are the same	select v.vehicle_id,         v.year,         v.make,         v.model,         v.mileage,         count(distinct vo.order_id) as unique_orders,         sum(order_summation.order_cost) as sum_of_all_orders from tbl_vehicle_order vo inner join tbl_vehicle v    on vo.vehicle_id = v.vehicle_id join (     select os.order_id as order_id       , sum(s.part_cost + s.labor_hour*r.labor_cost_per_hour) as order_cost     from order_service as os     join service as s      on os.service_id = s.service_id     join tbl_rate as r      on r.rate_id = s.rate_id     group by os.order_id) as order_summation   on order_summation.order_id = vo.order_id group by v.vehicle_id,           v.year,           v.make,           v.model,           v.mileage; 	0.00778772387410755
22642734	31183	group by month displaying duplicate months in sql	select      distinct  tranl.division,      datename(month,tranl.trandate) as 'month',      count(tranl.qty) as transactions,      sum(tranl.qty) as units     from translog (nolock) tranl      where tranl.location = 'stage'     and end_tran_date >= '2013-04-01 00:00:00.000'     group by datename(month,tranl.trandate), tranl.division    order by  tranl.division 	0.000191205502618421
22643125	27918	mysql sorting messages sent and received	select senderid, receiverid, message, dateandtime, case when senderid=1 then receiverid else senderid end as optional from messages where senderid = 1 or receiverid=1 order by optional, dateandtime desc; 	0.0358676058972985
22643884	37938	return all child records related to parent	select t1.acct#, t1.name, t2.cfseq, t2.cfaal1, t2.cfacc# from data.table1 t1 join  data.table2 t2 on t1.acct# = t2.cfacc#  where     t1.acct# in (select cfacc# from t2 where cfaal1 like '%pod%') 	0
22644066	33079	how to loop through a list of strings with sql sever stored procedure and update a table	select channelname,substring(email,0,charindex('-',email)) from accounts as a  inner join channel as c on channelname like substring(email,0,charindex('-',email)) 	0.0274974733592078
22644235	19811	sql server concatenate date and time	select  [created on], [created at], cast(convert(date, [created on]) as datetime) + cast(convert(time, [created at]) as datetime), left([created on],11) + right([created at],8) from [verical$purch_ inv_ header]  where [posting date] > '2014-02-01 	0.00659797452702208
22645398	12427	how can i get all table names, row counts and their data sizes in a sql server 2012 database?	select      s.name +'.'+ t.name as tablename,      convert(varchar,cast(sum(p.rows) as money),1) as [rowcount],     convert(varchar,cast(sum(a.total_pages) * 8 as money),1) as totalspacekb,      convert(varchar,cast(sum(a.used_pages) * 8 as money),1) as usedspacekb,      (sum(a.total_pages) - sum(a.used_pages)) * 8 as unusedspacekb from sys.tables t inner join sys.partitions p on p.object_id = t.object_id inner join sys.schemas s on t.schema_id = s.schema_id inner join sys.allocation_units a on p.partition_id = a.container_id where t.is_ms_shipped = 0 and p.index_id in (1,0) group by s.name, t.name order by sum(p.rows) desc 	0
22645694	35498	what is the difference between -> and ->> in postgresql json functions?	select     '[1,2,3]'::json->2 as "->",     pg_typeof('[1,2,3]'::json->2) as "-> type",     '[1,2,3]'::json->>2 as "     pg_typeof('[1,2,3]'::json->>2) as " ;  -> | -> type |   3  | json    | 3   | text 	0.386603711000345
22647294	4945	select only the persons that have both values	select x.clientid from (    select distinct clientid, phonetype from [table a] ) as x group by x.clientid having count(x.phonetype) = 2 	8.10908415828148e-05
22647422	2386	get primary key column of a table	select   schema_name(t.schema_id) as schemaname  ,t.name as tablename  ,i.name as indexname  ,co.name as columnname  ,ic.key_ordinal as columnorder     from sys.tables as t  inner join  sys.indexes as i     on i.object_id = t.object_id  inner join sys.index_columns as ic     on i.object_id = ic.object_id    and i.index_id = ic.index_id  inner join sys.columns as co     on co.column_id = ic.index_column_id    and co.object_id = t.object_id  where i.is_primary_key = 1    and t.name = 'mytable'    and schema_name(t.schema_id) = 'dbo'    order by ic.key_ordinal   	6.1274798242328e-05
22647810	14194	mysql - select last two rows in query	select * from (     select * from comments where post='$id' and status='1' order by time desc limit 3 ) sub order by time asc 	0.000139162157077409
22649255	12398	unique string table in sql and replacing index values with string values during query	select mn.string as 'machinename', an.string as 'alarmname'  from alarm a    join uniquestring mn on a.machinename = mn.id   join uniquestring an on a.alarmname = an.id 	0.000417331201866493
22649310	2917	mysql grouping distinct query	select city,   sum(if(subject='english',1,0)) as english,   sum(if(subject='math',1,0)) as math from foo group by city; 	0.245346490113858
22649645	38071	creating a summary report by group and quarter sql	select      id             , type             , tag             , sum(case when qtr = 1 then amt else 0 end) as qtr1             , sum(case when qtr = 2 then amt else 0 end) as qtr2 from        tbl group by    id             , type             , tag 	0.248967677756439
22651296	17546	group_concat with columns of a particular type in the first	select distinct group_concat(p.name order by p.sex asc)  from person p join parent_child pc on p.ssn=pc.parent_ssn            join school s  on s.child_ssn = pc.child_ssn where s.school_name='x'  group by pc.child_ssn; 	0.000185430930822275
22652612	25931	sql: subtracting sums from 2 different tables	select p1.memberid, p1.p1sum -l1.l1sum as res_sum as pia from (select p1.memberid, sum(p1.point) as p1sum from point p1 group by p1.memberid) p1 join (select l1.memberid, sum(l1.lessonpoint) as l1sum from lesson l1 group by l1.memberid) l1   on p1.memberid= l1.memberid  order by p1.memberid desc 	6.52946232732383e-05
22652654	6692	rows as columns without join	select *   from (select rownum as cnt, teacherid              , teachertype, teachername           from teachers          where teachertype = 1) qry1        full outer join (select rownum as cnt, teacherid                              , teachertype, teachername                           from teachers                          where teachertype = 2) qry2           on qry1.cnt = qry2.cnt 	0.0101445302484358
22653287	16731	mysql join with group by and order by	select * from ( select `p`.`id` as product_id, `p`.`title` , `i`.`image` , `u`.`user_username` , `m`.`id` as message_id, `m`.`date` , `m`.`from` , `m`.`to` , `m`.`message` , `m`.`read` from (`messages` as m) join `products` as p on `m`.`product_id` = `p`.`id` join `users` as u on `m`.`from` = `u`.`user_id` join `product_images` as i on `p`.`id` = `i`.`product_id` where `i`.`type` = 'front' and (m.to = '1171' or m.from = '1171) order by `m`.`id` desc ) tmp group by `m`.`therad_user` , `m`.`product_id` 	0.681551226461659
22655460	9347	sql fetching data in minutes not getting proper result	select  t.tbarcode ,         t.plateno from    transaction_tbl t where   [status] = 4        or ([status] = 5 and datediff(n, cast(deldate as datetime), getdate()) <= 3) 	0.0720313660487654
22657314	27268	sql server - get the final sum of a product of two columns	select products.customname as 'name', ordered_products.scanned as 'sent quantity', charged_products.price as 'product price', ordered_products.scanned * charged_products.price as 'charged' from products     join charged_products         on products.productsid = charged_products.productsid     join ordered_products         on ordered_products.productsid = products.productsid where ordered_products.ordersid = 500 and ordered_products.scanned > 0 union all select 'total', '', '', sum(ordered_products.scanned * charged_products.price) from products     join charged_products         on products.productsid = charged_products.productsid     join ordered_products         on ordered_products.productsid = products.productsid where ordered_products.ordersid = 500 and ordered_products.scanned > 0 	0
22658956	6721	mysql between in between	select title from my_tables where start_date <= '2014-02-28' and       end_date >= '2014-02-02'; 	0.0364900688123106
22659204	29043	ms-sql - extracting numerical portion of a string	select substring(importcount,13,patindex('% schedule items%',importcount)-13) from table name 	0.0020693945228371
22659629	29759	selecting two columns in same table multiple times	select * from (     select country, population     from         (             select country, population             from country             order by population             offset 1 limit 1         ) s     union     select country, population     from         (             select country, population             from country             order by population desc             offset 1 limit 1         ) q ) s 	0
22659771	21263	extracting value from xmltype column	select extract(value(b),' from   xml_tab x,         table(xmlsequence(extract(xmlval,' 	0.000329135281622133
22660189	16355	sql to show matching records if exists else show all records	select * from table where not exists (select id from table where id = 2) or id = 2 	0
22660366	16681	mysql break down the rows to columns	select product_id,       sum(case(priority) when 1 then priority else 0 end) as priority1,       sum(case(priority) when 2 then priority else 0 end) as priority2,       sum(case(priority) when 3 then priority else 0 end) as priority3,       sum(case(priority) when 1 then price else 0 end) as price1,       sum(case(priority) when 2 then price else 0 end) as price2,       sum(case(priority) when 3 then price else 0 end) as price3 from product_discount pd group by product_id 	0.00171273345286911
22661253	39359	sql and temporary row in select query	select -1 as id, '' as name 	0.0591398921459789
22661662	34700	sum/group rows into totals for each day	select userid,        count(*) from yourtable where completeddate > dateadd(day,datediff(day,0,getdate()),0) group by userid 	0
22666124	37950	sql query: get values included from a certain threshold	select path.idpath, path.token, path.istv,relation.rel from path left outer join relation on (path.idtokenn=relation.idtokenn) where path.idpath in(select distinct path.idpath from path where path.istv='true') and path.idpath in(select distinct path.idpath from path group by path.idpath having count(*) >= 2 and count(*) <= 3) 	4.91331710952772e-05
22668619	32893	sql server - replace money numbers with text	select freight,  cast(cast(floor(freight) as decimal(2,0)) as varchar) + ' dollars and ' + cast(cast(100*(freight - floor(freight)) as decimal (2,0))as varchar) + ' cents' from dbo.orders 	0.308263159210692
22670659	32345	join solution on postgres with many tables	select central, id, map, camel, nrrg from     v1     full outer join     v2 using (central, id)     full outer join     v3 using (central, id) order by central, id ;  central | id | map  | camel | nrrg    a       |  1 | map1 | cap1  | nrrg2  a       |  2 | map1 |       |   a       |  3 |      |       |   b       |  1 | map3 | cap1  |   b       |  2 |      | cap2  |   b       |  3 |      | cap3  |   c       |  1 |      |       |   d       |  1 |      |       |   d       |  5 |      |       | nrrg1 	0.712865461531723
22670804	5690	how to hide tables from view if value = 0	select msg_type_id, count(*) from db1 with (nolock) where msg_type_id in ('0', '1', '2', '3', '5') group by msg_type_id; 	0.000989615937806758
22671173	32312	sql - length of firstname and lastname	select 'your name is ' + cast(len(firstname + ' ' + lastname) as varchar(64)) + ' chars ' 	0.712225828166023
22672661	11478	how to check the coulmn null in sql	select (case when params is null then '' else params end) as params from table1 	0.0284802488047086
22672892	11699	sql - get top record for each date	select t2.currentdate ,month(t2.currentdate) month ,datename(month, t2.currentdate) as 'monthname' ,datepart(wk,t2.currentdate) week ,left(cast(datepart(year,t2.currentdate) as char),4) +  right('0' + cast(datepart (week,t2.currentdate) as varchar(2)),2) as yearweek ,rtmcode ,rtm ,cpcode ,cp ,cdcode ,cd ,branded ,rv ,holiday from  (select currentdate  from dbo.edb e  group by currentdate)t cross apply ( select top 1 * from dbo.edb i1             where i1.currentdate = t.currentdate             order by i1.currentdate desc)t2 	0
22672959	34550	trying to get month to date sales value for each date	select soh1.shipdate, sum(soh2.totaldue) from     (select distinct shipdate from sales.salesorderheader         where shipdate < '2005-09-01' and shipdate >= '2005-08-01') as soh1    join sales.salesorderheader soh2          on soh2.shipdate <= soh1.shipdate and soh2.shipdate >= '2005-08-01'     group by soh1.shipdate order by soh1.shipdate 	0
22673064	20213	how to select avg(value) per column_name in sql	select country,avg(earnings) from studios group by country; 	0.0136318410601386
22673294	9816	multiple sql join	select s.name, g.grade from grades g natural join student s  natural join module m where m.modulename='databases' and g.date='1001-11-21' 	0.501826682838192
22673729	20323	complex query to get total balance for each day	select dnt,     @running_bal := @running_bal + `balance` as `balance` from    (select dnt, sum(credit) - sum(debit) as `balance` from transactions group by dnt) tmp,   (select @running_bal := 0) tempname order by dnt asc 	0
22674402	5480	how to count number of fields by specific column in mysql?	select f.family_code,f.family_name, count(p.prod_id) as number_of_products from family as f left join products as p  on f.family_code = p.family_code group by f.family_code, family_name; 	0
22674777	3003	correlated subquery (on same table)	select status_change.*  , previous.timestamp as earlier_timestampe  , timediff(status_change.timestamp, previous.timestamp) as time_between from status_change  left join status_change as previous   on status_change.room = previous.room     and status_change.timestamp > previous.timestamp left join status_change as inbetweener   on status_change.room = inbetweener.room     and inbetweener.timestamp between previous.timestamp and status_change.timestamp where inbetweener.room is null order by status_change.timestamp desc; 	0.239328907966745
22675390	9625	how to get a grand total of distinct cells based on t-sql count output?	select company,  count(destination) as company_destination,  destination, count(destination) over() as totalcities  from dbo.burger_orders  where (date >= 20140301 and date <= 20140331)  group by company, destination 	0
22681766	17754	efficient way to check if row exists for multiple records in postgres	select     a.id as id, count(b.foreing_id) as cnt from a left outer join b on     a.id = b.foreing_id group by a.id 	0.00159697886678937
22682875	24577	get customers that has more than 2 orders but logged in less than 3 times though sql	select user_id,count(user_log_id) from user_log where user_id in             (                 select user_id from orderes                             group by user_id                             having count(order_id) =2                     ) group by user_id having count(user_log_id) < 3 	0
22685086	16162	extract number from part of a string	select convert(int, reverse(substring(reverse([field]),1,charindex(' ',reverse(@field))-1))) 	5.43622163266995e-05
22685229	35863	mysql get records what have max value	select x.*   from period x    join       ( select year             , month           from period          order             by year desc             , month desc          limit 1      ) y      on y.year = x.year     and y.month = x.month; 	0.000356050962264019
22685448	13015	relational algebra, finding how many a number is called	select cn.callingnumber, count(t.callednumber) as cnt from (select distinct callingnumber from table t) cn left outer join      table t      on cn.callingnumber = t.callednumber group by cn.callingnumber; 	0.0767641247030859
22687362	39984	sql query to convert existing column entries into row headers	select name,   max(case when measure = 'm1' then value end) m1,   max(case when measure = 'm2' then value end) m2,   max(case when measure = 'm3' then value end) m3 from tablename group by name 	0
22687403	21178	sql server: convert a varchar to a datetime	select convert(datetime,'05 jun 2007')  	0.0758028431202204
22688255	33616	mysql - where multiple column data	select *  from products  where concat(lpad(prod_id, 8, '0'), lpad(barcoder_int, 4, '0')) in (xxxx,yyyy,zzzz); 	0.0529038157942686
22688708	35540	make a query to split a line into x line depending on a field	select id, trim(regexp_substr( names, '[^;]+', 1, level)) from table_name connect by level <= length(regexp_replace(names, '[^;]+')) + 1 and prior id = id and prior dbms_random.value is not null 	0
22688953	9987	count and group by on multiple coulmns	select st.version as version, count(st.version) as total sys_ids,count(a),count(b),count(c) from (     select sys_id,version,state,     max(decode(state,'a',state)) as a,     max(decode(state,'b',state)) as b,     max(decode(state,'c',state)) as c     from system st     group by sys_id,version,state ) group by version; 	0.223235431305947
22689190	19696	relationship between product and category, build query	select *  from product_category pc where  (pc.id_category=1 or pc.id_category=2) and exists (select *  from product_category pc2 where  pc2.id_product = pc.id_product and  (pc2.id_category=3 or pc2.id_category=4) ) 	0.0210044924815747
22689571	26891	duplicates from an sql query	select accountid, min(dateentered) as dateentered  from ....  group by accountid  order by accountid 	0.123328161707218
22690108	17809	presence / absence of an outgoing edge from a vertex in orientdb	select from person where oute('friend').size() > 0 and oute('owns').size() = 0 	0.0121824484569553
22690208	2152	sql - how to select the same column two times with different values?	select pa.prod_name, pb.prod_name, pv1.prod_vers_name, pv2.prod_vers_name,cl.compa_lvl_name     from tbl_prod as pa, tbl_prod as pb,tbl_prod_vers as pv1, tbl_prod_vers as pv2, tbl_prod_vers_alloc as pva, tbl_prod_vers_alloc as pvb,  tbl_compa_lvl as cl, tbl_compa as c     where      pa.prod_id=pva.prod_id and      pv1.prod_vers_id=pva.prod_vers_id and      pva.prod_vers_alloc_id=c.prod_vers_alloc_id_a and      pb.prod_id=pvb.prod_id and      pv2.prod_vers_id=pvb.prod_vers_id and      pvb.prod_vers_alloc_id=c.prod_vers_alloc_id_b and      cl.compa_lvl_id=c.compa_lvl_id and          p.prod_id=66; 	0
22690417	8800	mysql: how do i count instances of an object and then display that which has the most instances of said object?	select submittedby, count(1) as count from recipe group by submittedby order by count desc limit 1 	0
22690894	39693	using xml path to concatenate multiple fields	select distinct a.id,     (         select  b.type + ','         from test as b         where a.id = b.id         for xml path ('')     ) from test as a 	0.00993517979822299
22691239	38007	which is the best approach to translates the results of a sql query directly to the x and y axis of a chart	select concat(city , ', ', country) as x_axis, count(*) as y_axis from beer group by city, country having count(*) > 100 order by country, city; 	0.000349628485802554
22692261	17144	find most frequently used query	select address, sql_text, parse_calls, executions from v$sqlarea order by executions desc; 	0.0264342435641664
22692457	23512	mysql: how do i relate multiple tables together	select p.guitarrig      , sum(r.price) as totprice   from part p      , product r      , purchaseinformation i  where p.product = r.name    and p.name    = r.part    and r.name    = i.product group by p.guitarrig order by totprice desc  limit 1 	0.0402209593598424
22694718	33564	sql patern match to find a space or character	select * from <table>  where field like '%asc%' and field not like '%non[ ,-]asc%' create table #lookfor (thefld varchar(200)) insert into #lookfor     values ('asc'),('non-asc'),('non asc'),('non,asc') select * from #lookfor    select * from #lookfor where thefld like '%asc%'          and thefld not like '%non[ ,-]asc%' drop table #lookfor 	0.0661395675502553
22694816	28091	is it possible to convert string column to datetime in sql server?	select       id      ,name      ,convert(datetime,                 ('20' + substring(registration_dt,5,2)                     + '-' +                  substring(registration_dt,1,2)                     + '-' +                  substring(registration_dt,3,2)))       as registration_dt from yourtable 	0.149371142768393
22695260	18688	sql query to get filters with expected values for a web view	select     name,     count(job_id) from   (     select j.id as job_id, loc.city, j.company, jt.tag_name     from job_tag_new jt     left join job j on jt.job_id = j.id     left join location loc on loc.id = j.location ) base cross apply ( values     ([city]),     ([company]),     ([tag_name]) )  v(name) group by name 	0.776639463875296
22696941	38553	how to select distinct on 1 key column when querying multiple columns	select t.field1,t.field2,t.field3 from ( select *, row_number() over (partition by field1 order by field1) as rownumber from mytable ) t where t.rownumber = 1 	0.000103773076911499
22697072	38048	select single row from table with multiple row values from different table	select      tablea.id, tablea.name, tablea.date,              firstplayercode, firstplayeramount,              secondplayercode, secondplayeramount  from        tablea left join   (select payercode as firstplayercode, amountpaid as firstplayeramount               from   tableb              where  playercount = 1) p1 on p1.recordid = tablea.recordid  left join   (select payercode as secondplayercode, amountpaid as secondplayeramount               from   tableb              where  playercount = 2) p2 on p2.recordid = tablea.recordid 	0
22697359	3342	joining two tables together with two foreign keys	select   object.objid as id,   od.description as description,   ld.description as location from object   inner join description as od     on object.objdescid=od.descid   inner join description as ld       on object.objlocid=ld.descid; 	8.74514225140458e-05
22697488	16922	create calculation that looks for same organization and previous year (where to start?)	select thisyear.companyname   , thisyear.asset - lastyear.asset   , nz(lastyear.asset,'no prior year') as [message] from companytable as thisyear left join on companytable as lastyear on thisyear.companyname = lastyear.companyname and thisyear.reportyear -1 = lastyear.reportyear 	0.000110826072942907
22698847	36994	delphi 7 + zeos: how to prevent sqlite 3 converting date and integer/float to string?	select date(*) as test from (select date(d) from a union all select date(d) from b) s order by 1; 	0.038172149755192
22699008	32517	t-sql group by date instead of datetime	select cast([datetime (utc)] as date) as [date],   sum([messages sent external]) as 'messages sent external', sum([messages sent internal]) as 'messages sent internal', sum([messages received external]) as 'messages received external', sum([messages received internal]) as 'messages received internal', max([message latency internal high]) as 'message latency internal high',  max([message latency internal avg]) as 'message latency internal avg'  from dbo.monthly_mailflowstats_2014_03  group by cast([datetime (utc)] as date)  order by [date] asc 	0.0153513282547828
22700282	5181	sqlite - count how many records there are for each foreign key	select l.name as listname from list l left join      person as p       on l.identifier = p.fk_list_identifier where p.fk_list_identifier is null group by l.name; 	0
22701580	17956	mysql: counting number of instances of numerous objects with use of intersection	select cep.guitarrig as guitarrig from  (select guitarrig from part where name='choruseffectpedal') cep join  (select guitarrig from part where name='delayeffectpedal') dep on cep.guitarrig=dep.guitarrig; 	0.000286992691789199
22701731	20218	sql query to match preferences	select b.*   from propertyforrent b   join client a     on a.preftype = b.type  where a.fname = 'john'    and a.maxrent <= b.rent 	0.263089039045729
22702188	16208	select rows between start and end column (unix timestamps)	select * from deposit_dates where start <= 1396396810 and end >= 1396396810; 	0
22702705	14925	count of open orders per week	select yw.y, yw.w, count(t.open_dt) as "open" from (select distinct year(open_dt) as y, week(open_dt) as w,              year(open_dt) * 100 + week(open_dt) as yw       from table t      ) yw left outer join      table t      on yw.yw >= year(open_dt)*100 + week(open_dt) and         (yw.yw <= year(close_dt)*100 + week(close_dt) or close_dt is null) group by yw.y, yw.w order by yw.y, yw.w; 	0
22704824	4548	oracle : how to find occurrence of specified value in particular column of a table in oracle	select nvl(max(col),'na') from (select id, col from table       where id = 1        union all        select 1 id, null from dual) group by id 	0
22707794	21864	how to show previous 3 inputs in mysql	select * from data where  `cat`='$data[cat]' and `id` < $data[id]  order by id desc limit 0,3 	0.00153016381543073
22709182	5767	from_unixtime() returns epoch, not the date	select from_unixtime(join_date) 	0.743308507144872
22709210	7158	joining two given set of queries in mysql	select temp1.cy_id, tsn, tx, ty, fsn, fx, fy from ( select c.cy_id,        c.to_id as tsn,        se.x as tx,        se.y as ty from c join se on c.to_id = se.ar union select c.cy_id,        c.to_id as tsn,        swt.x as tx,        swt.y as ty from c join swt on c.to_id = swt.ar) temp1, ( select c.cy_id,        c.fr_id as fsn,        se.x as fx,        se.y as fy from c join se on c.fr_id = se.ar) temp2 where temp1.cy_id = temp2.cy_id 	0.000917111458977195
22710290	11571	find entry which has same has many	select group_concat(subject_id order by subject_id) as teacher_concat ,teacher_id        from teacher_subjects         group by teacher_id         having teacher_concat in                     (select group_concat(subject_id order by subject_id)                      from student_subjects group by student_id) 	0
22712668	6893	every derived table must have its own alias	select *  from `evenement` left join `evenementontvanger`  on `evenementontvanger`.`idevent` = `evenement`.`id`  left join (select `werknemer`,                   group_concat(`initialen`) as `initials`            from `werknemer` ) a  on sometablename.somecolumnname = a.somecolumnname where evenementontvanger.idevent =evenement.id and `evenementontvanger`.`idwerknemer`=20 	0.00269542106997422
22712927	12762	fetching from an associative table	select *  from article_has_tag a  where a.id_tag = 1 or a.id_tag = 4 group by id_article having count(*)=2 	0.0145571228332782
22713827	9263	how to use a sum result in the same query?	select * from `table` where field = ( select sum(otherfield) as energy           from `table2` ) 	0.0129632441114777
22715340	35250	sum column values and also check null condition	select '$ '+ convert(varchar,convert(decimal(10,0),convert(money, isnull(sum(amt_value),0.00))),1) as  [amount]  from products 	0.000455927765675109
22715770	4880	sql server last like functionality	select a.* from mytable a left join mytable b  on b.name = a.name  and b.date > a.date where b.value is null 	0.352117038306033
22718474	25765	mysql export chat table history	select from_user_name, to_user_name, message, timestamp from chat c join user f on c.from_user_id = f.user_id join user t on c.to_user_id = t.user_id order by timestamp asc 	0.0386628741410009
22718691	30042	how to calculate % of total in mysql	select count(*) as headct , case     when year(dob) <= 1945 then 'traditionalist'     when year(dob) >= 1946 and year(dob) < 1965 then 'baby boomer'     when year(dob) >= 1965 and year(dob) < 1981 then 'gen x'     when year(dob) >= 1981 then 'gen y'   end as generation , concat(round(count(*)/     (select count(*) from ret_active)*100,0),'%') as '% of total' from ret_active group by generation with rollup 	0.000263292100429573
22718914	4625	need to do tthis in 1 sql	select t1.ordernumber      from tra99 t1     where t1.ordernumber in (                  select ordernumber                  from tra99                  where tcode in ('qee','qne')                  )      and t1.tcode='@23' group by t1.ordernumber 	0.751238606104551
22720160	28066	create an alphabet in php with only some letters depending of names in database	select distinct substring(lastname,1,1) 'initial' from people order by initial asc 	0
22720673	33434	mysql select using combined columns	select * from `users` where concat(fname," ",lname) = "james stafford" 	0.0321045840077305
22721597	8102	how to get this condition in where clause of sql	select * from tabl where  datepart(month, completed_date) = datepart(month, dateadd(mm,-1,getdate())) and datepart(year, completed_date) = datepart(year, dateadd(mm,-1,getdate())) 	0.525620660060206
22722786	16625	is it possible in sql to count the number of distinct values as well?	select c.lastname as 'distinct last names', count(*)  from customer as c group by c.lastname 	0.00282461676995733
22722791	36329	can mysql generate random numbers that can be either negative or positive?	select -1+2*rand(); 	0.00492601419995921
22727572	6393	intersection of queries using junction table	select std.studentid, std.studentname from students std inner join junction jnc where jnc.classroomid in(1,2) 	0.0391882702648926
22728849	33256	current month each day stats per user row	select u.user,        max( if(day(p.date_added) = 1, p.participated, 0 ) ) day1,        max( if(day(p.date_added) = 2, p.participated, 0 ) ) day2,        ..............        ..............        ..............        max( if(day(p.date_added) = 28, p.participated, 0 ) ) day28,        max( if(day(p.date_added) = 29, p.participated, 0 ) ) day29,        max( if(day(p.date_added) = 30, p.participated, 0 ) ) day30,        max( if(day(p.date_added) = 31, p.participated, 0 ) ) day31 from user u join participate p on u.id = p.user_id where p.date_added >= '2014-03-01'   and p.date_added < '2014-04-01' group by u.id 	0
22728895	23183	mysql query (join)	select u.id,u.name,p.date_password from tbl_user u  left join tbl_lastchangepassword p on u.id= p.loginid 	0.724110026477687
22730023	7093	mysql query to find last logged in date of each user	select u.id,u.name,max(l.date_lastlogin) date_lastlogin from tbl_user u left join tbl_lastlogin l on(u.id=l.loginid ) group by u.id 	0
22730590	3119	sql query for object and child collection	select mainobjectid,name, max(case when columnname='columnname1' then columncontent else 0 end)as columnname1, max(case when columnname='columnname2' then columncontent else 0 end)as columnname2, max(case when columnname='columnname3' then columncontent else 0 end)as columnname3 from t1 join t2 on t1.mainobjectid=t2.mainobjectid group by t1.mainobjectid 	0.182581293778272
22731087	25279	conditional data retrieve from two mysql tables	select      form_id,      form_name,      if(db.table2.owner_name is null, db.table1.owner_id, db.table2.owner_name)         as owner_name from db.table1 left outer join db.table2 on db.table2.owner_id = db.table1.owner_id; 	0.000504019079712999
22736086	29749	mysql query balance	select inventory.inv_id, inventory.item, inventory.qty,  coalesce(sum( `order`.qty ) , 0 ) as sum_qty,  coalesce((inventory.qty - sum( `order`.qty)) , 0) as balance from inventory left join `order` on inventory.inv_id = `order`.inv_id group by `inventory`.inv_id order by inventory.inv_id asc 	0.513699021288162
22736970	1763	sql query for joining multiple tables containing multiple rows - the right way?	select user.user_id, post.post_id, group_concat(concat_ws('~',replies.reply_id, reply_photos.photo_id)) as replyphotoid from user where user.user_id = 1 left join post on user.user_id = post.user_id left join replies on post.post_id = replies.post_id left join reply_photos on replies.reply_id = reply_photos.reply_id group by user.user_id, post.post_id 	0.0238622123792754
22738178	4958	mysql many to many selecting data - possible?	select email, group_concat(distinct group_name order by g.group_id) as groups   from users as u   join users_groups as ug on u.user_id = ug.user_id   join groups as g on ug.group_id = g.group_id  group by email  order by email 	0.0190126105600866
22738499	1041	calculating previous date in postgresql	select id, match_date, team,        lag(id) over (partition by team order by match_date) as prev_matchid from ((select id, match_date, home_team as team, 'home' as which        from matches       ) union all       (select id, match_date, away_team as team, 'away' as which        from matches       )      ) m; 	0.00745442939122165
22740242	29394	to get records in between two date in mysql	select * from      stackoverflow.`table`  where str_to_date(`date`, '%d-%m-%y') between      str_to_date('12-5-2005', '%d-%m-%y') and str_to_date('20-6-2005', '%d-%m-%y') 	0
22741090	12262	optimize mysql query to find rank of a user for differnet tests in single query	select *, (select count(*)+1             from user_date_table b             where a.my_test_id = b.my_test_id              and a.test_score < b.test_score) userrank from user_date_table a where user_id = '1'; 	0.0167752381132247
22742300	5833	mysql union display	select trackid as id, title as title, 'track' as result_type from tracks where title like '%$s%' limit 5 union select artistid as id, name as title , 'artist' as result_type from artists where name like '%$s%' limit 5;    foreach($result as $row){      if($row['result_type'] =='track'){      }      if($row['result_type'] =='artist'){      }    } 	0.0376504872337357
22742683	29670	what is the effective query to retrieve related information from related mysql tables, when there can be search in both tables	select taf.*,        tbf.*   from table_a taf  inner join table_b tbf          on tbf.tbf4 = taf.taf4  where taf...... 	0.000234844813027263
22742940	5338	tsql: sum before and after today per customer	select customer_id,     sum(case when enter_into_force_date <= getdate() then salary else 0 end) before_today,     sum(case when enter_into_force_date <= getdate() then 0 else salary end) after_today from orders group by customer_id 	0
22744222	22014	if time is more than 60 minutes then show in hours in sql server	select     case        when avg( datediff(mi,t.dtime, t.deldate )) <= 60            then cast(avg( datediff(mi,t.dtime, t.deldate )), varchar)       else            cast(avg( datediff(mi,t.dtime, t.deldate )) / 60, varchar) + ":" + cast(avg( datediff(mi,t.dtime, t.deldate )) % 60, varchar)    end 	0
22745615	25900	sql query with where definitions are from another table	select * from callrecords  where dnis in (select dnis from dnis_table) order by date desc 	0.00286826947182079
22748117	22853	how to get total order price using mysql?	select order_id,         sum(order_price) as total_sum from order_details group by order_id order by total_sum asc 	0.000225184134606863
22748348	29157	merging 2 sql queries into a single one	select *    from (  select distinct e.* ,        (6371 * acos( cos( radians(9.977364864079215) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(76.58620953448485) ) + sin( radians(9.977364864079215) ) * sin( radians( latitude ) ) )         ) as distance   from schools e   left join geodata g on e.id=g.id  where (e.type = 'preprimary')    and ( e.title like '%government%' )  ) as s   where s.distance  < 20   order by s.distance 	0.000125047766295353
22749217	6797	reference data n levels up	select b.foo from bar b where (select bz.foo        from baz bz        where (select bl.foo from blah bl where bl.foo = b.foo)      ); 	0.0209492028681302
22750809	41047	how to reverse sort mysql data	select * from (     select * from `articles`      where date >= unix_timestamp(date(now() - interval 30 day))     order by `views` desc      limit 20  ) as reverse_article  order by views asc 	0.047065235175252
22751290	36543	how to query three different tables to find out specific information	select s.* from   users         u join   session_user su on u.id = su.user_id join   tutor_session s on s.id = su.tutor_session_id where  u.email = 'foo@bar' 	0
22752276	2178	mysql: select from table a, based on seen date of user in table b	select regionname.*, regionplayer.*, players.* from regionname join regionplayer     on regionplayer.regionkey= regionname.key join players     on players.key = regionplayer.playerkey where regionname.perent = 'none' group by regionname.name having      sum( seen > (now() - interval 8 day ) ) =0     order by `regionname`.`name` asc,     players.seen desc 	0
22752784	20868	how to design similar structure tables in mysql	select u.name,        e.title as event_title,        a.title as activity_title from `user` u left join `event` e on u.id = e.owner left join `activity` a on u.id = a.owner 	0.123783984917045
22753051	17757	mysql php query to count field lengths	select yearborn, length(name) as len, count(*) as cnt from table t group by yearborn, length(name) order by yearborn, length(name); 	0.0549192048238683
22753522	6666	sql query can't find the way to get the result	select user.name, count(distinct question.id) + count(distinct answer.id) from user  left join answer on user.id = answer.user_id left join question on user.id =question.user_id group by user.name 	0.0160954681283262
22755936	22532	how to use the highest values for a certain criteria to sort the list?	select pid, name, max(balance) as highest_balance from my_table group by pid, name order by max(balance) desc; 	0
22757689	23374	is it possible to use 1column extract to 4 column	select id, sum(case when status = 'present' then 1 else 0 end) as present, sum(case when status = 'absent'  then 1 else 0 end) as absent, sum(case when status = 'leave'   then 1 else 0 end) as leave from tbchecked group by id 	0.145277717841922
22759284	12952	mssql return 0 for null blank	select coalesce([itemslotx],0) as [itemslotx],coalesce([itemsloty], 0 ) as [itemsloty] from (select null dummy ) d left outer join [powerup_items] on   [itemindex]=16 and [itemgroup]=255 	0.167881774820935
22759430	9545	checking the adjacent column value in mysql	select     * from     films  where     (         director_sirname = 'wilson'         and director_firstname = 'john'     ) or     (         producer_sirname = 'wilson'         and producer_firstname = 'john'     ) ; 	0.00507989064687947
22759468	23135	how to add new column into temp table	select t.component_id, t.pub_id, m.date_value from #temp2 t join custom_meta m on t.pub_id = m.item_id and m.key_name = 'articledate' 	0.00036786516683787
22759791	15743	temp table for xml auto, elements - sql server 2005	select * from #bla as bla for xml auto, elements 	0.00538865805217434
22760537	22590	extract only alphabetic characters from varchar column	select regexp_replace('12-mar-2014,,1234,data,value,12/03/14,,124,end','[[0-9]{2}-(jan|feb|mar|apr|jun|jul|aug|sep|oct|nov|dec)-[0-9]{4}]*|[^a-za-z]+|$','%') from dual 	0.000103800207063354
22766664	6004	return two rows as a single row	select top 1        stuff((select ' ' + name as [text()]                 from dbo.test                 order by id                  for xml path('')), 1, 1, '' ) concatenated  from test 	0
22766694	2698	using multiple sum case lines in query	select datepart(year,  smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date) as totalyear,         datepart(month,  smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date) as totalmonth,         count(*) as total from [table] group by datepart(year,  smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date),         datepart(month,  smsdss.c_cfv_pas_fct_pt_acct_vst_all.vst_end_date) 	0.35603931059982
22768292	10020	join two tables, only display unique values and maxium date	select p.*, p1.* from table01 p inner join table02 p1 on p.id = p1.id inner join     (  select s.id, max(dt_date) maxdate        from table02 s         group by s.id     ) d   on p1.id = d.id and p1.maxdate = d.maxdate order by d.maxdate desc; 	0
22768480	29863	join two tables with two columns sql server 2008 r2	select a.doc_name as attending_name,         b.somefield,         a2.doc_name as admitting_name from doctors a,       someothertable b,       doctors a2 where a.doc_id = b.attending_doc_id   and a2.doc_id = b.admitting_doc_id   and b.record_id = <whatever> 	0.0489239919549066
22769271	29617	subselect to grab most recent record	select blah1 from  dbo.ac_source as ac  inner join (     select blah2 from      (         select blah2, row_number() over (partition by employeeid order by meeting_end_date desc) as rownum         from         (             select blah2             from   dbo.ac_cddata_1             union all             select blah2             from  dbo.tms_data_latest_career_meeting_rating             where (plan_year = '2013')          ) as innerselect     ) as cd     where rownum = 1 ) on ac.tms_id = cd.employee_id 	8.40550255332127e-05
22770202	16386	distinct - download the content again	select fms_bruger.fornavn, fms_bruger.efternavn, fms_opslagpm.id, fms_opslagpm.title  from fms_bruger  inner join fms_opslagpm on fms_bruger.id=fms_opslagpm.fra_id  where fms_opslagpm.til_id = ?  group by fms_opslagpm.title  order by fms_opslagpm.datotid desc 	0.090306136710887
22770997	26824	mysql select column in table where two other columns are equal in the referenced tables	select   value2 from   tablea a   inner join tablec c on a.value1= c.value1   inner join tableb b on c.value3= b.value3 where   b.city = a.city 	0
22771290	10080	how to format a date to "mm/dd"	select convert(varchar(5), getdate(), 101) 	0.0104464107062892
22772541	19546	how could i condense 3 mysql queries; using avg and count	select p.provider_id, p.description, r.date, r.f_name, r.s_name,        r.website, r.rating, r.message, r.email_address,        tsum.avg_rating, tsum.cnt from providers p inner join      reviews r      on r.provider = p.provider_id cross join      (select provider, round(avg(rating),1) as avg_rating, count(*) as cnt       from reviews       where provider like concat('%',:provider,'%')      ) tsum where p.provider_id like concat('%',:provider,'%') limit $set_limit 	0.639340041146799
22772933	1887	mysql count total number of multiple line items	select      qa.id,      qa.created_at,      qa.updated_at,      count(qa.id) as askers from questions_asked as qa where qa.created_at between your_first_date and your_second_date group by qa.item_in_question_id 	0
22774324	10469	mysql counting duplicates - grouping by two columns	select item, count(userid) as multi_clickers from   (select item, userid, count(userid) as total_clicks_for_user    from clicks     group by item, userid    having total_clicks_for_user > 1) a group by item 	0.00100987295894246
22774372	10769	how to compare column values of different rows with sql	select   teacherid,   class,   sum(case when passfail = 'fail' then count else 0 end) * 100.0 /sum(count) as failpersent from tbl group by teacherid, class 	0
22775434	39619	cumulative sum based on consecutive values	select d.id, d.distance, d.time_s,        (case when d.distance = 0              then sum(case when d.distance = 0 then d.time_s end) over (partition by grp order by id)         end) as stoptime from (select d.*,              sum(case when distance = 0 then 0 else 1 end) over (order by id) as grp       from data d      ) d; 	0
22776061	4510	how to select data from the table which have default key word as a table name	select `group` from `groups` where id !='b0000000-1111-1111-1111-11111111111b' and             id !='e0000000-1111-1111-1111-11111111111e'; 	0
22777581	11723	how to merge rows in select query result set	select t1.date1, t1.acc1, t1.cr, t2.date2, t2.acc2, t2.dr from (the table or query) t1      join (the table or query) t2 on t1.acc1=t2.acc2 where t1.acc1 is not null 	0.00198903455370829
22778940	14216	group by count(*) mysql multiple tables	select a.customer, sum(client1), sum(client2), sum(client3) from (     select customer, count(*) as client1, 0 as client2, 0 as client3 from table where `date` = current_date() group by customer     union all     select customer, 0, count(*), 0 from table2 where `date` = current_date() group by customer     union all     select customer, 0, 0, count(*) from table3 where `date` = current_date() group by customer ) as a group by a.customer 	0.0573504143178624
22780649	880	joining same table multiple times	select person.id, person.name, dept1.name, dept2.name, dept3.name left join dept dept1 on dept1.id = person.dept1 left join dept dept2 on dept2.id = person.dept2 left join dept dept3 on dept3.id = person.dept3 	0.000629701465200365
22780883	12539	sql query for extracting values from one column where other value columns are same	select     pa1.author_id,     array_agg(pa2.author_id order by pa2.author_id) as co_author from     paper_author pa1     left join     paper_author pa2 on         pa1.paper_id = pa2.paper_id         and pa1.author_id != pa2.author_id group by pa1.author_id order by pa1.author_id 	0
22781624	18425	sql show 0 when no records where found	select s.statusses_namenl, count(*) from statusses left join recipes r on r.fk_recipe_status = s.id left join projectrecipes pr on pr.fk_projectrecipes_recipeid = r.id and pr.fk_projectrecipes_projectid = 213 group by s.statusses_namenl; 	0.00836305421546379
22781807	17708	data not displayed present in current table but not present in another table	select tb.code from templates_boxes tb where tb.id not in (select templates_boxes_id from templates_boxes_to_pages where templates_id = 3) and tb.modules_group = 'boxes' 	0
22782375	29970	joining rows into column	select  b.id,b.name ,(select a.value from attr_value a inner join attr_type at on at.id=a.attr_type_id where b.id=a.block_id and at.id=1) as 'type_a' ,(select a.value from attr_value a inner join attr_type at on at.id=a.attr_type_id where b.id=a.block_id and at.id=2) as 'type_b' ,(select a.value from attr_value a inner join attr_type at on at.id=a.attr_type_id where b.id=a.block_id and at.id=3) as 'type_c' ,(select a.value from attr_value a inner join attr_type at on at.id=a.attr_type_id where b.id=a.block_id and at.id=4) as 'type_d' from block b 	0.00116380905353516
22783691	37816	mysql search query inner join limit id_image field results to 1 per id_product	select ps_product_lang.id_product , ps_product_lang.name as product_name , ps_product_lang.description_short , ps_product_lang.link_rewrite as product_link_rewrite , ps_product_lang.meta_title , ps_product.reference , ps_product.id_category_default , ps_product.on_sale , ps_product.price , ps_category_lang.name as category_name , ps_category_lang.link_rewrite as category_link_rewrite , ps_image.id_image from ps_product_lang inner join ps_product inner join ps_category_lang on ps_product.id_category_default=ps_category_lang.id_category inner join ps_image on ps_product_lang.id_product=ps_image.id_product where ps_product_lang.name like '%simon%' or ps_product.reference like '%simon%' group by ps_product_lang.id_product order by ps_product_lang.id_product asc 	0.46889494225349
22785072	30231	select article and select article liked time only if article liked (if there is row with userid in article likes)	select    article.id,    article.title,                                           article.content,    coalesce(article_likes.time,'not liked') as time from articles    left join article_likes on article.id = article_likes.articleid  where  article.id = (articleid) limit 1 	8.13252745055934e-05
22785348	30333	sql - obtain latest record in subquery subset or in join using group by	select d.data_id, d.name, d.date_created, s.sync_id, s.result, s.details from `data` as d left join (   select sync_id, data_id, result, details, date_created from (     select sync_id, data_id, result, details, date_created     from sync     order by date_created desc   ) a group by a.data_id ) s on d.data_id = s.data_id  order by d.date_created desc; 	0.00625885525165677
22785583	33339	how to fetch the icno and count(icno) in mysql for the following table based on given condition?	select icno, count(icno) from tbl_studentapplication where icno not in (     select distinct icno     from tbl_studentapplication     where idprogram in (1,2) ) group by icno 	0
22786586	29594	sql query: favorite product in a certain timeframe	select top 1 r.productnumber,sum(r.amount) from order as o left join orderrule as r on o.number = r.number where o.dbdatetime between @sdate and @edate group by r.productnumber order by sum(r.amount) desc 	0.0128512045630383
22791766	31644	php: count the items and echo them	select  t.name,  `replies`, `comments` from topics t left join  (      select topic_id,count(reply_id) as `replies`     from replies     group by topic_id )r on r.topic_id = t.topic_id left join (     select topic_id,count(comment_id) as `comments`     from comments     group by topic_id )c on c.topic_id = t.topic_id group by t.name 	0.00037234699222754
22792593	34380	return 0 if no row/empty result in mysql	select coalesce(t1.amt, d.amount) as amt  from   (select 0 as amount         from   dual) as d        left join          (select t1.amount as amt          from   table1 as t1                 inner join table2 as t2                         on t1.project_id = t2.id          where  t2.proj_name = "project_kalinga"                 and t1.date_sent = (select max(date_sent)                                     from   table1                                     where  project_id = "0123")) as t1         on 1 = 1 	0.0595855924518868
22793818	18437	mysql show uncounted	select t.*, (select count(*) from ratings r where r.trackid = t.trackid) as ratingscount from tracks t order by ratingscount desc; 	0.108576584209627
22794387	17221	how to search many tables efficiently	select match from  (select name as match from costumers where name like'%foo%' union  select category as match from products where category like'%foo%' ...) 	0.0621493191805457
22796011	28117	querying data from sql table basing on other rows values	select      *  from (     select p.id as p_id from photo p     join tag t on t.photo_id = p.id     join tag_name tn on tn.id = t.name_id     where tn.name = 'date' ) as ti join tag t1 on t1.photo_id = p_id join tag_name tn1 on tn1.id = t1.name_id where tn1.name = 'time' 	0
22796310	13551	mysql sum values of difference between two columns	select sum(time_in-time_out) as diff  from table_timelogs  where year(log_date) = year(now()); 	0
22799854	27576	separating data sql	select level, count(studentid) as numofstudents from student group by level 	0.213456243799042
22799860	19598	how to get count after using aggregate functions	select count (distinct customerid)  from (select customerid , shipperid from orders group by customerid having count(distinct shipperid)=1 and shipperid = 3) as data ; 	0.220833519506752
22800061	19685	benefits of explicit type conversion?	select top (0)   cast('' as nvarchar(50)) as address1,   cast(0 as smallint) as languageid union all select   t.address1,   case t.language_cd     when 'e' then 31     when 'n' then 32     when 'd' then 38   else 39 end as languageid from mytable t 	0.68774388139041
22801102	31371	get rank user with php/mysql without inserting current user's score into the table	select id, username, score, time from scores union all select 0 as id, 'yourscore' as username, 99999 as score, 45 as time order by score desc, time desc 	0
22801445	20823	compare two select statements in oracle sql	select (whatever operations you gonna do) from dual where (select sum(quantity) from table 1 where order_number = xxxx) = (select sum(quantity) from table 2 where order_number = xxxx); 	0.0476684152728838
22801600	6815	formula execution on multiple intervals	select   r/i as tera,   (r-i)/(r+i) as tera2 from     (select wavelength, reflectance as r, row_number() over(order by wavelength) as rn      from test where wavelength between 340 and 345) t1     join      (select wavelength, reflectance as i, row_number() over(order by wavelength) as rn      from test where wavelength between 350 and 355) t2 using (rn) 	0.34737245164259
22803084	34630	multiple values on selection	select   2.5*((r-i)/(r+(6*i)-(7.5*n)+1)) as tera,   (r-(2*i)-n)/(r+(2*i)-n) as tera2 from     (select wavelength, reflectance as r, row_number() over(order by wavelength) as rn      from test where wavelength between 340 and 345) t1     join      (select wavelength, reflectance as i, row_number() over(order by wavelength) as rn      from test where wavelength between 350 and 355) t2 using (rn)     join     (select wavelength, reflectance as n, row_number() over(order by wavelength) as rn      from test where wavelength between 360 and 365) t3 using (rn) 	0.0264295100193539
22803233	2826	uniquely identify same column name of two different table after join - mysql	select a.*,b.col1,b.col4,b.col5 from a,b 	0
22803991	19474	postgres query count characters and order by longest length	select title from stories order by length(title) desc 	0.0489782956234329
22804543	22495	php mysql group by similar values in a column	select concat('group ', sub1.group_order), group_concat(subject), count(*) from messages inner join (     select distinct substring_index(references, ',', 1) as iref, @order:=@order+1 as group_order     from messages, (select @order:=0)     order by iref ) sub1 on substring_index(messages.references, ',', 1) = sub1.iref group by concat('group ', sub1.group_order) 	0.011130465791533
22804607	22015	mysql query union all	select count(distinct tel_number) as `cases present`,        count(distinct case when action > '' then tel_number end) as `cases analyzed` from `tbl_tel_number` where consuming is not null group by zone, consuming limit 3; 	0.142672852385986
22805005	20592	joining a quotation, orders and customer table?	select tbl_quotations.quote_id, customers.customer_id, name, sum(amount)  from tbl_quotations inner join customers on tbl_quotations.customer_id = tbl_customers.customer_id join orders on tbl_quotations.quote_id = tbl_orders.quote_id group by tbl_quotations.quote_id 	0.000525606888867138
22806683	5391	to fill combobox with multiple fields	select (' '+fisrtname + lastname)   from student_groups   for xml path('')   where username=' ' 	0.020019526728304
22806891	6592	how to join two sql squery results	select p.house_id, h.location  from prices as p join houses as h on h.id = p.house_id group by p.house_id, h.location 	0.161617957210279
22807413	29991	sql query to select where other rows do not equal values	select arg2 as r from voipwallboard_ast_queue_log v1     where queuename = '0536*401'     and time > '2014-04-02 10:30:00'     and event = 'connect'     and not exists (select 1 from voipwallboard_ast_queue_log v2                     where v1.callid = v2.callid                     and v2.event in ('connect','abandon ','ringnoanswer')                     ) 	0.00273847127801057
22807465	2291	mysql distinct with multiple fields	select distinct a,b,c,d from your_table 	0.0628929323623587
22808054	30777	how to get data from two different tables with different field names	select user_id, user_grp_id, null as cust_id, null as cust_grp_id from table1 union all select null as user_id, null as user_grp_id, cust_id, cust_grp_id from table2 	0
22808412	38078	calculate percentage in t sql	select      tests2.name,      (count(name)* 100) / (select count(*) from tests where tests.name=tests2.name) from tests as tests2 where status='running' group by name 	0.0212142027983974
22808610	30621	mysql get most recent entries from a big table	select  user , timestamp  from  (select user,timestamp from transactions order by id desc) a  group by user; 	0
22808799	28007	select one value if result of both criterias is equal	select distinct t1.code from tablename t1 inner join tablename t2  on t1.code = t2.code where t1.days = 30 and t1.rate = 2 and t2.days = 60 and t2.rate = 0 	0.000265361119614391
22808908	21349	how to assign the value to the access column in the where clause	select case cells(1, 1).text ' cell a1 contains y or n     case "y": swhereclause = " where med_d = 'y'"     case "n": swhereclause = " where med_d in ('y','n')"     case else: msgbox "error": exit sub end select debug.print sql & swhereclause ' send this to access 	0.00156633212840409
22809046	1086	select another user from same table	select * from table as t1 join table as t2 on t1.user_id = t2.user_owner_id where t2.user_id = 63 	0
22809357	17294	difference between join and where for two identical queries	select * from questionsetquestionanswer where questionid =  (   select questionid    from questionsetquestion    where setid = '45e20157-0030-c58b-55c4-08d11c725bd7' ) and exists  (   select *   from questionanswer    where id = questionsetquestionanswer.selectedanswerid and iscorrect = 'true'  ); 	0.00652551293059701
22809756	7181	sql server: show default value for null in select	select      coalesce(a.ranking,0) as ranking             (                 select      coalesce(b.groupname,'') as groupname,                             (                                 select      c.policy,                                             c.groupcount                                 from        @temp c                                 where       c.ranking = a.ranking                                 and         c.groupname = b.groupname                                 order by    c.groupcount desc, c.policy                                 for xml path(''), elements, type                             ) as groupname                 from        @temp b                 where       b.ranking = a.ranking                 group by    b.groupname                 order by    b.groupname                 for xml path(''), elements, type             ) from        @temp a group by    a.ranking order by    a.ranking for xml path('policyranking'), elements, type, root('ranks') 	0.0100379700585525
22811157	8239	mysql database: query table and join with "valid from" date column of other table	select user.name, userstatus.status, blog.date, blog.text from blog join user    on user.id = blog.user_id join userstatus    on user.id = userstatus.user_id   and valid_from_date = (select max(valid_from_date)       from userstatus       where user_id = user.id       and userstatus.valid_from_date <= blog.date) 	0.000134968444687545
22811609	37791	mysql. how to select data from database higher than exact number	select username,min(time) time  from game where time > 10  group by username  order by time asc limit 15; 	0
22811994	5694	sql server: select with count by item and total count	select name, count(name) as count from table group by name     union all select 'sum', count(name) from table 	0.000476947490958206
22813436	33815	select into table from table2 where column in (subquery)	select  .... columnnames ... into [found_duplicates]      from [find_duplicates]     as fd     where fd.[contract no]         in (  select [contract no] from (select          [contract no],         [vehicle identity number (vin)],         count(*) as anzahl      from find_duplicates     group by          [contract no],         [vehicle identity number (vin)]     having count(*) >1)x) 	0.00117375549667916
22813667	25713	select rows without nested associated records	select id  from employees e  where not exists (                 select *                  from assignments a                       join contracts c on a.id = c.assignment_id                      join tasks t on c.id = t.contract_id                 where a.employee_id = e.id) 	0.00174235097242086
22815686	16040	how do i find record older than 90 days from a datetime field in mysql?	select * from table where lastlogin < date_sub(now(), interval 90 day); 	0
22815847	32456	sql selecting from multiple tables	select s.name from student s inner join enrolment e on s.studentid = e.studentid inner join building b on e.building_id = b.buildingid inner join campus c on c.campusid = b.campusid where c.campusname = 'city centre' 	0.00249295699707073
22816291	22517	postgresql merge two queries with count and group by in each	select date1 date, sum(a) count_a, sum(b) count_b  from (   select date_trunc('day', date1) date1, 1 a, 0 b from table_a    union all    select date_trunc('day', date1) date1, 0 a, 1 b from table_b ) z  group by date; 	0.00025055380939817
22817776	22616	checking product stock against a date	select p.* from products p left join (select product_id, count(*) in_use            from hire            where :specified_date between h.start_date and h.end_date            group by product_id) h on h.product_id = p.id  where stock_quantity - ifnull(in_use, 0) > 0 	0.0179871432677553
22818169	8011	comparing two variables from different database tables using php	select     t.image from     templates as t,     products as p where     t.category = p.title and     t.category = 'wine' limit 1; 	0.000250070520019544
22818291	34819	how can sum group values?	select      sum(case when p.state = 0 then 1 else 0 end) as state_0,     sum(case when p.state = 1 then 1 else 0 end) as state_1,     sum(case when p.state = 2 then 1 else 0 end) as state_2,     p.policy_business_unit_id as units,      p.cia_ensure_id as cias  from policies p where  p.policy_business_unit_id in ( 1 )      and p.cia_ensure_id =1 group by case when p.state in (0,1,2) then 1 else 0 end 	0.0307386679695602
22819270	24908	sql query: select max sum quantity	select top 1 productid, sold from (   select productid, sum(quantity) as sold   from orderrule   group by productid ) totals order by sold desc 	0.0573342963589903
22819536	27973	how to select values that already exists in column	select key from table group by key having count(*) > 1; 	0.000467117013975978
22820637	14898	count how many records there are for each foreign key, with like clause	select count(distinct l.identifier) as regcount from list as l left outer join person as p on l.identifier = p.list_identifier where l.name like '%a%' 	0
22820883	36189	sql query group by year different columns where condition apply	select year(custdecdate), sum(valuexx), sum(valueyy) from bids where forbid = "for contract" group by year(custdecdate) 	0.00599935194633736
22821114	26454	getting number of rows of joined table by condition on another	select  p.product_id, p.name, p.price from products p inner join products_to_categories  pc on pc.product_id = p.product_id where  pc.category_id = 1 and p.price > 100 	0
22821297	11800	generating sqlite results	select e.*        ,v.*     from events as e     join hostedat as h         on e.eventid = h.eventid     join venues as v         on h.venueid = v.venueid 	0.557829703405434
22822708	3680	retrieving multiple rows in sql server in a sub query and concatenating them to a string	select sbrv_table.master_key      , stuff((select ', ' + parent_key [text()]               from dbo.dlnk                where dlnk.parent_key = sbrv_table.masterkey               for xml path(''),type)              .value('.','nvarchar(max)'),1,2,'') as parent_key_list                       from dbo.sbrv_table  group by sbrv_table.master_key 	0.000661861203989856
22823264	3743	how to do 2 where statements in sql	select *  from table where (col1 = 'a' or col2 = 'b') and col3 = 'c' 	0.251096776178459
22825037	16367	sql - average across multiple vehicles and speeds	select sum(count*speed)/sum(count) as overall_average from t1; 	0.0139509801001172
22826194	37674	finding duplicates via sql with enumeration of results	select   (select count(1) from data b where b.hash = a.hash and b.filename <= a.filename) as instance,   a.hash,   a.filename from data a order by   a.hash,   a.filename 	0.028055478109271
22827606	41079	how do i query for the sum of averages?	select sum(average_price) as total_averages from (select avg(price) as average_price)       from table       where <conditions>       group by stock_name) as averages 	0.00506285381058359
22828424	7898	finding intersecting areas in mysql spatial db	select id from contractor c where intersects(c.geom, st_buffer(point, radius)); 	0.242429521178489
22828640	29533	mysql create virtual column out of result	select id, username, level, name course_expertise, substring_index(subjects,',','1') subject1, substring_index(substring_index(subjects,',','2'),',','-1') subject2, substring_index(substring_index(subjects,',','3'),',','-1') subject3  from ( select     u.id,     u.username,     u.level,     c.name course_expertise,     group_concat(s.name ) subjects from     user_profiles lp inner join users u on lp.user_id = u.id inner join courses c on lp.course_expertise_id = c.id inner join user_subjects us on u.id = us.user_id inner join subjects s on us.subject_id = s.id group by u.id ) a 	0.00475342711769437
22829620	20661	how to select row values for max(2 columns)	select top 1 level,stage from tablename order by level desc,stage desc 	0.000310651739336978
22831268	11022	converting smalldatetime datatype to varchar datatype	select 'some text'+convert(char(16), @date, 121) 	0.770125506860729
22832439	9618	change value based on previous rows in mysql	select t.*, if(@previd = po_id and @prevprod = product, 0, quantity) as new_quantity, @previd := po_id, @prevprod := product from t , (select @previd:=null, @prevprod:=null) var_init order by po_id, product 	0
22832769	34922	reference a table in nested subqueies	select     c.id_comp,    count(t.id_comp) trip_count from company c   left join trip t     on c.id_comp = t.id_comp group by c.id_comp 	0.550594564319739
22833255	33588	select if (query in query)	select agent  from `sales`  where price='3000.00'  and comdte > '2014-02-02'  and comdte < '2014-03-02'  and agent in (select id from `agents` where rank = 1) 	0.454918505811434
22834916	944	performing interpolation on a table, grouping by a 3rd field	select delta, ( datediff(d, @previousdate, @forwarddate) * nextrate                     + datediff(d, @forwarddate, @nextdate) * previousrate                    ) / datediff(d, @previousdate, @nextdate) as rate from   (select main.delta as delta, pr.rate as previousrate, nr.rate as nextrate   from @ratestable main   inner join @ratestable pr on pr.delta = main.delta and pr.forwarddate = @previousdate   inner join @ratestable nr on nr.delta = main.delta and nr.forwarddate = @nextdate) as prevnextratetable group by delta,         ( datediff (d, @previousdate, @forwarddate) * nextrate                     + datediff(d, @forwarddate, @nextdate) * previousrate                    ) / datediff(d, @previousdate, @nextdate) ; 	0.00629522934798904
22835844	29115	mysql select with join, count, order by	select a.schedule_id,         count(a.schedule_id) as schedule_count,         min(a.startdate) as earliest_startdate ,         t.title from tours_schedules a join tours t on a.tour_id = t.tour_id group by t.tour_id 	0.443772745789331
22836550	33795	sorting mysql fields in different order on different sites	select `fruit`      from (`fruit`)      order by field(`fruit`, 'tangerine','banana','apple', 'orange', 'peach', 'kiwi') asc 	0.00261490037603702
22838595	8761	mysql: counting number of records in a table using a value in another table	select tbl_users.usr_num as userid, tbl_users.name as username, count(*) as qn_forms_enetered from tbl_users inner join tbl_intrvw          on tbl_users.usr_num = tbl_intrvw.survyr_num group by tbl_users.usr_num,tbl_users.name 	0
22839684	32347	how to combine two sql queries and selectively display a result	select *  from      content  where      folder_id in (select                      folder_id                    from                      [content_folder_tbl]                  where                      parent_id in (158, 149)) and      published = 1 and      upper(content_title) not like '%description' and      upper(content_title) not like '%image' and     folder_id = 106 and      content_type = 1 and      published = 1  order by      content_title 	0.000280888148450146
22840276	4496	how to use wildcard character(%) search on java.lang.long value	select * from tcotet a where cast(a.icont as char(12)) like '%7187%' 	0.572450025674519
22840731	29390	sql select statement with a quotename removing the last character on the last row	select quotename(field1,'''')+    case when row_number() over(order by (select 1))=     count(*) over () then '' else ',' end as [1] from <table> 	0
22841046	2855	forming extended groups of group elements	select distinct `key` from your_table where `group` in (     select distinct `group`     from your_table     where `key` in      (       select `key`       from your_table       group by `key`       having count(*) > 1     ) ) 	0.00967060572226025
22841250	36863	how do i filter out the latests runs in and crosstab the rowns into columns?	select product, max(ad) ad, max(ss) ss, max(td) td from (   select product,       max(case tests when 'ad' then results else 0 end) as ad,       max(case tests when 'ss' then results else 0 end) as ss,       max(case tests when 'td' then results else 0 end) as td   from product   group by product, tests ) test_reports group by product order by product; 	0.0190562058483585
22841843	38556	accessing a column name in the parent	select (select(count(*) from t where id = id_company) ... 	0.000830647151912997
22841955	18898	how to compare the first date and the last date?	select name      , sec_to_time( max(time_to_sec(login_date))                   - min(time_to_sec(login_date))                   ) x    from my_table   group      by name; 	0
22842729	26623	php select loop	select *, (case when co_subj1 is not null then co_subj1 else co_subj2 end) as subject  from course_conf join course_type on ct_id=co_fk_ct_id order by co_name where co_subj1 is not null or co_subj2 is not null 	0.331634351871677
22843116	27266	return a constant text string for every row in a column (dynamic) sql server 2008	select wh_id, item_number, 'link' as constant from   table_1 	0.00153008437388792
22843402	7516	grouping date of births in 2 month periods	select case  when t.dob between date_sub(now(), interval 25 month) and date_sub(now(), interval 23 month) then 'between -25 and -23 month' when t.dob between date_sub(now(), interval 22 month) and date_sub(now(), interval 20 month) then 'between -22 and -20 month' when t.dob between date_sub(now(), interval 19 month) and date_sub(now(), interval 17 month) then 'between -19 and -17 month' when t.dob between date_sub(now(), interval 16 month) and date_sub(now(), interval 14 month) then 'between -16 and -14 month' end as my_ranges, count(*) from t group by my_ranges 	0
22843760	6586	select next word after string (sql)	select 'this is a test of concept with other words' as [column1]     ,'this is a test of ' as [column2]     into #tmp select *  ,case when right(rtrim(column2),3)=' of'  then column2+substring(column1, patindex('% of %',column1)+4,                         charindex(' '                          ,column1                           ,(patindex('% of %',column1)+4) - patindex('% of %',column1)+4)) else column2 end from #tmp drop table #tmp 	0.00581639075107214
22849314	40524	how to add child elements attached to parents, through an association table?	select level_id, contact_id, visible from contact union all select level_id_child, contact_id, visible from levels l inner join contact c on l.level_id_parent = c.level_id order by level_id 	0
22851231	25633	json/hstore in postgresql arrays	select name from (select name, members, generate_subscripts (members, 1) as s from rock_band) as foo   where members[s]->>'name' = 'chester'; 	0.343800620825922
22851611	6150	how do i use select on columns that don't have column names in sql server 2008 r2?	select distinct [column 3] from [testtable].[dbo].data 	0.00092356418334848
22851961	31953	sql - referencing 3 tables	select c.brgy_zone_num,count(a.chrchfamly_isbaptized) as [num of people baptized] from tbl_church a left join  tbl_intrvw b on a.qn_number=b.qn_number left join  tbl_area c on b.zone_num=crgy_zone_num where a.chrchfamly_isbaptized='yes' group by  c.brgy_zone_num 	0.234027857625313
22853300	15135	fails to pass column into sql user function	select top 1 ut.userid,  ut.deleted, case when fun.userid is not null  then 1 else 0 end as foo from [dbo].[user] ut left join [dbo].[uf_testfunction_table]([ut].[userid]) as fun on fun.userid =ut.userid 	0.267133548336699
22856718	26724	mysql with 2 tables	select person.name, person.age, count(distinct log.time_stamp),         sec_to_time(max(time_to_sec(time_stamp))- min(time_to_sec(time_stamp)))        from person        left join log on person.name = log.name        group by person.name; 	0.0564483823895227
22858248	37413	select the row with the max value in a specific column, sql server	select top 1 tblclients.client_id,count(tblloans.client_id) as max_nol  from tblclients, tblloans  where tblclients.client_id=tblloans.client_id  group by tblclients.client_id order by count(tblloans.client_id) desc 	0
22858671	22935	function regexp with a list of numbers	select id from my_list where find_in_set('8', id_list) and find_in_set('44', id_list) 	0.0503458261879347
22862017	36259	mysql: get the values from different tables in one query?	select * from tablea a, tableb b1, tableb b2, tableb b3 where a.item1 = b1.id and a.item2 = b2.id and a.item3 = b3.id 	0
22863885	8495	how to get rows with duplicate values with a better performance	select `match`.*  from `match` join (select `matchview`.`hometeam`                     from `matchview`                     group by `matchview`.`hometeam`                      having (count(0) > 1)) watches on `match`.`hometeam`=watches.`hometeam` order by `match`.`hometeam` 	0.00751655454439227
22863904	2869	how to omit some results but not all from a query	select      * from     mtable where     foo not in ('ad' , 'ca', 'qw')         and (foo not like '9%' or foo='96321'); 	0.00317475540528201
22864849	30568	mysql select one record from cerain categories, for rest categories this rule not affected	select id, categoryid, data from (     select id, categoryid, data, @seq:=if(@prev_cat = categoryid, @seq + 1, 1) as catseq, @prev_cat = categoryid     from sometable     cross join (select @seq:=0, @prev_cat:=0) sub1     order by category_id, id ) where (categoryid in (2,3) and catseq = 1) or categoryid not in (2,3) 	0.000336447294133976
22865097	29581	sql - select a list of items that belong to user "x"	select *  from   tasks  where  user_id = 123 	0
22865929	16500	sql query select the last entry of each product	select u1.*  from  $usertable u1 join (  select component, ref, max(date) date from $usertable  group by component, ref ) u2 using(component, ref,date) 	0
22866200	9873	displaying records that contain a certain letter in sql	select customer_country  from customer  where customer_country like '%u%' 	0
22866867	41089	sql query multiple dates to one date	select `hostess code`, date_format(`datum bezoek 1`, '%e %m'), count(pa), count(pb), count(pg), goedkeuringdoornew, blanco,... where ... group by date_format(`datum bezoek 1`, '%e %m') order by date_format(`datum bezoek 1`, '%e %m') 	0.00246248532112162
22867578	36940	how to query 2 identical sql server databases on different server machines	select abc.pays from sr1.db1.sc1.tbl1 abc union all select def.pays from sr2.db1.sc1.tbl1 def 	0.00508628516572365
22867998	14293	retrieve name and address of employees working in department	select d.dname,e.fname+' '+e.minit+' '+e.lname as name from employee e inner join department d on e.departmentnum=d.departmentnum 	0.000555774203523114
22868008	8117	troubles with selecting the lastes record from mysql	select      * from     lat         join     lng using (id) order by lat.id desc 	0.00171190110857927
22868743	30311	mysql get row positions	select r1.*,   (select count(*) +1    from reservation r2    where r2.status = 1      and r2.id < r1.id) as positiontotal,   (select count(*) +1    from reservation r3    where r3.status = 1      and r3.people = r1.people      and r3.id < r1.id) as positionsamepeople from reservation r1 	0.00960998989476926
22868854	23712	select all until first occurence of a character with multiple columns	select   tbldoc.[docid],    tbldoc.[docext],   substring(tbldoc.[errormsg], 1, charindex('.',tbldoc.[errormsg])) from      tbldoc where      charindex('.',tbldoc.[errormsg]) > 0   and tbldoc.[errormsg] like '%trackrevisions%' 	0
22869591	19794	tsql function to find a county based on city and zip	select @county = county from tzprod.plandata_rpt.dbo.zipcode where zip = @zip and      city = @city and     createdate < '1/1/2012' 	0.00133204592575063
22871973	2501	autocount records when displaying	select *, (select count(*)+1             from [sometbl] counter             where t.groups = counter.groups             and t.description > counter.description) as counter from [sometbl] t 	0.0530219054415712
22873142	16441	joining records from same table	select id1,id2,id3, date1,  isnull(lead(date1) over(partition by id1,id2,id3 order by date1)-1, '99991231') as date2 from test 	6.88462045143847e-05
22873337	36532	sql query select last entry for each product and the one previous the last	select u1.* from $usertable u1 where (         select  count(*)          from $usertable u2         where u2.component= u1.component          and u2.ref= u1.ref          and  u2.date>= u1.date         ) <= 2 order by component asc, ref asc 	0
22875531	7016	inner join with 2 primary keys	select content1        ,content2        ,content3   from           table1 t1       inner join table4 t4 on t1.table1id = t4.table1id       inner join table3 t3 on t4.table3id = t3.table3id       inner join table2 t2 on t3.table2id = t2.table2id 	0.188596134726063
22875978	4019	how to get total number of rows in a mysql database?	select sum(table_rows)  from information_schema.tables  where table_schema = '{db_name}' 	0
22876041	16366	multiple subqueries to find answer	select  product_name from    a_product p where   exists ( select 'x'                  from   a_item i                  where  i.product_id = p.product_id )         and exists ( select item_id                      from   a_item i                      where  exists ( select 'x'                                      from   a_sales_order s                                      where  s.order_id = i.order_id ) )         and exists ( select order_id                      from   a_sales_order s                      where  exists ( select 'x'                                      from   a_customer c                                      where  s.customer_id = c.customer_id                                             and name = 'thermo power' ) ) 	0.111432250784109
22876407	15866	counting occurrence while changing null to 0	select itemid,        ones,        twos,        ones + twos as total,        100 * (round(ones / (ones + twos), 4)) as ones_perc,        100 * (round(twos / (ones + twos), 4)) as twos_perc from      (select itemid,        sum(case when eventtype = 1 then 1 else 0 end) as ones,        sum(case when eventtype = 2 then 1 else 0 end) as twos      from a      group by itemid)b 	0.00568119194652066
22877095	11290	how to create a query that returns forums by user	select f.id as f_id, f.message, c.id as c_id, c.user_id as c_user_id, c.comment     from forum_submission f    left join submission_comment c    on c.forum_id=f.id     where f.user_id= ?     order by f.id 	0.0559110632133738
22877865	34856	mysql join over three tables	select p.name,        count(r.name) as count_requests,        sum(r.failed) as count_failed,       count(r.name) - sum(r.failed) as count_bookings   from products p   left join requests r on (p.name = r.name)  group by p.name; 	0.251846278994282
22880076	7547	get the value of a cell in another table based on the cell in the query table	select table2.id, table2.name, table1.name from table1, table2 where table1.id = table2.city 	0
22880187	41335	how to retrieve date field regardless year in mysql	select * from table1 where date_format(date ,'%m-%d') ='04-04' 	0
22880472	30200	mysql return the nearest higher value	select min(temp)  from foo  where temp > &userinput;` 	0.00181469893498022
22881240	8679	select last date and all dates in the future	select * from table1  where from_p >= (     select from_p from table1      where from_p <= now() and prod=3000    order by from_p desc limit 1     )     and prod=3000  order by from_p; 	0
22881553	8080	using aggregate function but don't want to group by the specific column	select firstpartno       ,count(firstpartno)       ,sum(case when sex = 'm' then 1 else 0 end) nmalecount   from dbo.vw_split4   group by firstpartno 	0.0462093677628796
22882445	37739	sqlite - store matrices in a table	select c1.value as col1, c2.value as col2, c3.value as col3 from data c1 on col = 1 inner join data c2 on col = 2 and c2.compilation = c1.compilation and c2.row = c1.row inner join data c3 on col= 3 and c3.compilation = c1.compilation and c3.row = c1.row where c1.compilation = 1 order by c1.row 	0.23418186009328
22883554	15158	count loans for each copy of a dvd and then count how many loans per dvd, sql server	select d.dvd_id,        d.title,         count(*) from   tbldvds d        inner join tblcopies c on d.dvd_id = c.dvd_id        inner join tblloans l on c.copy_id = l.copy_id group by d.dvd_id,        d.title 	0
22883569	39636	how to convert one row into multiple rows in sql like this	select name, cpp, 0 as java, 0 as python, age from {table} where cpp = 1 union all  select name, 0 as cpp, java, 0 as python, age from {table} where java = 1 union all select name, 0 as cpp, 0 as java, python, age from {table} where python = 1 	0.00182415792585099
22883781	9181	combining two sql queries pdo	select r.roomid as roomid,        roomname,        numofrooms,        maxpeopleexistingbeds,        maxextrabeds,        maxextrapeople,        costperextraperson,        maximumfreechildren,        includebreakfast,        minrate from rooms r join roomdetails rd     on r.roomid = rd.roomid join (     select b.roomid,            accommodationid,            count(b.roomid) as bookings     from booking b     where arrivedate >= :adate       and departdate <= :ddate     group by roomid ) t     on t.accommodationid = r.accommodationid where r.accommodationid = :aid     and t.bookings < numofrooms group by roomname 	0.191019797288787
22884341	18094	take the center of an image	select min(p.id),r.project_id from photo p  inner join room r on r.id = p.room_id  inner join project pro on pro.id = r.project_id group by r.project_id order by r.project_id desc limit 4 	0.0200036766927577
22884407	27593	how to obtain and count '@gmail.com' from a column of email accounts in sql	select sum(instr(some_column, '@gmail.com') > 0) as gmail_count from your_table 	7.91819803516658e-05
22885909	18010	how to group corresponding values in 2 columns in sql?	select account2, substring(list, 1, len(list)-1) from (select distinct account2 from #t) t cross apply (     select account1 + ', ' as [text()]     from #t     where account2 = t.account2     for xml path('')) x(list) 	0.000172688031922294
22891776	19211	mysql select statement with datetime	select id_event , event_title, event_details, event_date_time, id_show, id_category,  distance from( select event.id_event id_event, event_title, event_details, max(event_date_time) event_date_time, max(event_showtime.id_show) id_show, event_category.id_category id_category, ( 6371 * acos( cos( radians(  '49.20513921227407' ) ) * cos( radians( event_showtime.latitude ) ) * cos( radians( event_showtime.longitude ) - radians(  '18.762441839599678' ) ) + sin( radians(  '49.20513921227407' ) ) * sin( radians( event_showtime.latitude ) ) ) ) as distance from event join event_showtime on event.id_event = event_showtime.id_event join event_category on event.id_category = event_category.id_category group by event.id_event having distance <  '5' order by distance limit 0 , 20   )t 	0.430923299588668
22891922	23910	merging the rows of two tables	select b.pubid, a.year, a.studid, b.dramt, b.cramt, b.items as description      from table2 b     join table1 a on a.pubid=b.pubid     union     select a.pubid, a.year, a.studid, a.dramt, a.cramt, a.description     from table1 a     order by 1,2,3 	0
22893075	19459	in sqlite i am try to count people by current age when i have a column of birth dates	select age,count(age) from (select strftime('%y',date('now')) - strftime('%y',birth) age from table1)t group by age; 	0
22893289	5847	"select count (*)" vs count of results from "select 1" : which is more efficient way to get the rows count in db2?	select count 	0
22893431	16447	display salary, avg(salary), name for those who earns more than company avg(salary)	select last_name, salary, avg_salary from employees join (select avg(salary) avg_salary from employees) x   on salary > avg_salary 	0
22893535	36684	mysql select lowest timedate for each id	select id_event, min(event_date_time) as lowest_date from event_showtime where event_date_time > now() group by id_event 	0
22896218	34430	mysql result using query	select   avg(case when sex = 'm' then age end) as avg_male ,  avg(case when sex = 'f' then age end) as avg_female ,  name,  book_date  from reviews r  inner join books b  on b.id = r.book_id  where age<30        <  group by book_id    < 	0.519836420458854
22896494	30829	mysql query for two way relationship	select f1.user_id, f2.user_id as 'friend'     from friends f1 left join friends f2    on f1.user_id = f2.friend_id 	0.133649200380933
22897404	6750	listing number one records in a simple sql database.	select band_name, count(cds.cd_id) from (select cds.cd_id, cds.position from cds where cds.position = 1 group by cds.cd_id) join releases on cds.cd_id = releases.cd_id join bands on releases.band_id = bands.band_id group by band_name having count(cds.cd_id) > 0 	0.00259429211864337
22897468	29654	selecting values from a table where values from one column is divided into multiple columns	select * from  ( select id, max(case when val='a' then 'a' end) as val_1,             max(case when val='b' then 'b' end) as val_2 from table1 group by id )a where val_1 is null or val_2 is null; 	0
22897572	33989	sql query to select people interviewed more than once in a year	select p.id       ,name       ,number       ,location       ,interviewno   from person p         inner join         (select id               ,count(1) as interviewno           from interview           where year(interviewdate) = 2013          group by id         having count(1)> 1) i on p.id=i.id 	0.000315738694182288
22904210	36673	sum of row depending on data in sql server	select  customerid,  sum(case when vouchartype = 'c' then -amount else amount end) as amount from yourtable group by customerid 	0.00018723075798349
22904444	10840	mysql use aggregate function sum between two values	select sum(number) from yourtable where id between 0 and 2 	0.142213595183967
22905333	8751	get value from multiple table sql	select * from table1 a where a.id not in (select b.tbl1id from table2 b) 	0.000214984243858167
22905623	9923	view sql data table	select  dun     ,sum(case when jantina = 'melayu' then jumlah else 0 end) as melayu     ,sum(case when jantina = 'cina' then jumlah else 0 end) as cina  from maklumat  group by dun 	0.0889076506072698
22905860	668	to get the input of the subquery in the output of the main result	select r.doc_id,a.id from request r inner join action a on r.id=a.request_id where a.id in (1253960076) 	0.000352376406612829
22906158	15229	mysql \ join 2 tables and show results from 2 rows in one column	select p.id, group_concat( im.i_name separator '; ' ) as images from products p  left join images im on (im.product_id = p.id) where p.id in (1, 3) group by p.id 	0
22907317	6437	delete symbol (number, space, dot, comma) in string sql oracle	select regexp_replace(regexp_replace(address, '[0-9\. ,]+$',''),'^[0-9\. ,]+','') from customers 	0.0106653600247305
22907692	39051	select the customer who does not attend an event using oracle sql	select cus_name   from customer  where cus_name not in (                         select distinct c.cus_name                         from customer c                         full outer join booking b on c.cus_id = b.cus_id                         full outer join event e on e.event_id = b.event_id                         full outer join venue v on v.venue_id = e.venue_id                         where v.venue_name = 'glasgow';                       ) 	0.0245706639944332
22908650	22296	find next certain weekday with mysql stored procedure	select     case case_number     when 1 then case dayofweek(now())                  when 0 then date_add(curdate(), interval x day)                  when 1 then date_add(curdate(), interval x day)                  when 2 then date_add(curdate(), interval x day)     .....                 end     when 2 then ''     when 3 then ''     when 4 then ''     else 'unknown'     end from customer 	0.000425332338300121
22909789	40305	matching any x out of n criteria in the where statememt	select * from my_table  where  (column1 = 5) +  (column2 = 10) +  (column3 > 20) +  (column4 = 30) +  (column5 = 'interesting')  >= 3 	7.07330013869791e-05
22910016	17477	how to set filter for gridview in editvalue changed ? winforms devexpress	select invoiceid, invoicenumber, invoicedate,   (select customerid from customer where customer.customerid=newinvoice_1.customername) as customerid,   (select customername from customer where customer.customerid = newinvoice_1.customername) as customername,   duedate, tax, grandtotal, companyid  from newinvoice_1  where invoicedate < '06-04-2014'; 	0.0342265049708802
22910994	26620	increment variable in sql query	select [id], [number],        isnull(1+(select sum([number]) from table1 t2 where t2.id<t1.id),1) from table1 t1 	0.296017620736135
22912036	35317	incrementing counter on each duplicate in column	select    t.*,    @i:=if(id=@id, @i+1, 1) as num,    @id:=id  from    t    cross join (select @i:=0, @id:=0) as init  order by id 	5.52405745991195e-05
22914209	28524	how to find duplicates in two columns access sql	select t1.*  from table_name t1 inner join (select bno,bno-csccode             from table_name            group bno,bno-csccode            having count(1)>1) as t2 on t1.bno=t2.bno and t1.bno-csccode=t2.bno-csccode 	0.00130671558753397
22914787	32224	multiple query with many tables in mysql	select c.name, (select count(*) from visit as v where v.card_id = c.id) as visits, (select count(*) from `like` as l where l.card_id = c.id) as likes, (select count(*) from favorite as f where f.card_id = c.id) as favorite from card as c 	0.206467818391257
22915109	9821	sql left join based on existing value	select ig.section_id, ig.select_textname,   isl.sec_id, isl.sec_textname,   issl.item_sub_sec_id, issl.individualitemname from item_groups ig   join on items_section_list isl (ig.section_id = isl.section_id) left join on items_sub_section_list issl (isl.sec_id = issl.sec_id)             where issl.item_sub_sec_id>0             order by ig.select_textname, isl.sec_textname, issl.individualitemname,                issl.item_sub_sec_id asc 	0.0134176001707199
22917126	4230	using sqlite3 in objective c how to retrieve the number of rows in a result set	select count(*) from table_name 	0
22917286	12378	find records with more than 1 column value in sql	select count(*) from ( select e_mail, count(distinct e_mail) as emailcount from ocrd group by e_mail having count(distinct u_noemail) > 1 ) result 	0.000109276852074651
22917542	5370	mysql result offers duplicates, how to stop	select distinct(id) from... 	0.155597702063932
22918110	31265	query to find 'most watched' [count()] from one table while returning the results from another	select *   from filmdb    left join (        select filmid, count(*) as cnt          from watch_list          group by filmid) as a     on filmdb.film_id = a.filmid  order by isnull(cnt, 0) desc; 	0
22918866	13320	how can i count two diffrent things in a query	select *, count(*) as total_count,  (   select p.username    from crimes as sc   inner join players as p on p.id = sc.crimeissuedto   where sc.crimedescription = sm.crimedescription   group by sc.crimeissuedto   order by count(*) desc   limit 1 ) as personwithmostoffenses from crimes as sm group by sm.crimedescription order by count(*) desc  limit 15 	0.0308421155076664
22918902	30300	compare two columns of same row sql	select * from table where location like '% legacy'     or (         substring(name,-2)='da' and substring(location,-2)='da'         or         substring(name,-2)='rt' and substring(location,-2)='rt'     ) 	0
22918957	2684	mysql - ignore other records if a condition is met	select league_id,user_id,        case when outcome=0 then 'pass' else 'fail' end as outcome_id from ( select league_id,user_id,sum(case when outcome_id=4 then 1 else 0 end) as outcome from tablename group by league_id,user_id ) as z 	0.00162646652561052
22918977	40114	select value inside a comma separated string mysql	select *  from `orders`  where find_in_set(1, `include`) > 0 	0.000658243995988029
22919133	21946	mysql - ordering results based on order of subquery	select d.table_name, d.description, d.table_rows  from db_stats d join db_stats x on d.table_name = x.table_name                 and x.description = "before" order by x.data_length + x.index_length desc,          d.table_name,          d.description desc limit 6 	0.0161782880412078
22919293	10880	postgresql - joining 3 tables returning too many results	select  requirements.description from requirements  inner join advancement_requirements on requirements.requirement_id = advancement_requirements.requirement_id  inner join advancements on advancement_requirements.advancement_id = advancements.id where advancements.id = 1; 	0.359215888041731
22919997	25249	mysql query, can't figure out how to fetch the correct data	select * from images i  inner join containers c on c.iid = i.id  inner join posts p on c.pid = p.id  where i.category in('value1','value2','value3')  order by p.time desc; 	0.594103336657856
22920886	37157	mysql - latest row by set of users	select p.* from posts p  join( select user_id , max(post_date) post_date from posts  group by user_id   ) pp using(user_id,post_date) where pp.user_id in ($matches) order by p.post_date desc 	0
22921984	27462	group by, having and count	select count (rowtotal) as total    from (       select sum(1) as rowtotal       from `products_groups` `productgroup`        left outer join `products` `products`        on (`products`.`product_group_id`=`productgroup`.`id`)        group by productgroup.name having (count(products.id) > 0)   )as grouprows 	0.260366890070849
22922186	11383	mysql fill in missing dates for each specific value in column	select       year(c.datefield) as year,     month(c.datefield) as month,     s.subchannel,     count(l.created) from db.calendar c     cross join (select distinct subchannel from l_events) s     left join db.l_events l         on (date(l.created) = c.datefield)         and l.subchannel = s.subchannel where c.datefield between '2013-10-01' and '2014-03-31'  group by     s.subchannel,     year(c.created),      month(.created) order by     s.subchannel,     year(c.created),      month(.created)     ; 	0
22922548	28653	ms access: selecting the first item according to a rank	select   r.employee, d.description from   table1 as d   inner join (select min(rank) as rank, employee               from                  table1               group by employee) r on d.rank = r.rank                                       and d.employee = r.employee 	0
22923032	12051	sql exclude field from group by in results but use in where	select submitter_ch_id, submitter_last_name, count(id) as [total submissions] from (     select id, submitter_ch_id, submitter_last_name     from  dbo.recognitions     where date >= @start_date and date <= @end_date ) t group by submitter_ch_id, submitter_last_name 	0.0145381634620856
22924049	16830	how to use distinct in where clause to avoid repeated row returns	select  basefeeds.siteurl, feedfinishes.timetaken, feedfinishes.timesubmitted from feedfinishes  join basefeeds  on feedfinishes.guid = basefeeds.guid  where basefeeds.siteurl like '%www.example.com%'  group by basefeeds.siteurl, feedfinishes.timetaken, feedfinishes.timesubmitted 	0.543315520741715
22925040	29810	sql extract list where instances fall outside multiple, varying date windows	select member, [service date], [order number] from [transaction table] as tt where not exists(     select *      from [eligibility table] as et      where tt.member=et.member and tt.[service date] between et.[elig begin] and et.[elig end]) 	0.000486395058690167
22925837	25650	find all rows with matching columns with two conditions	select o.id, customer, date_placed, li.qty from orders o inner join line_items li   on o.id=li.order_id and li.sku='ball' where exists(   select order_id    from line_items tli    where o.id=tli.order_id    group by order_id    having count(*)=2) 	0
22926275	20284	duplicate and out of sequence numbers	select s1.patientid, s1. randomid, 'outofsequence' from @valuecheck s1 left join @valuecheck s2 on s1.randomid = s2.randomid – 1 where s2.randomid is null union all select patientid, randomid, 'duplicate' from @valuecheck where randomid in  (select randomid from @valuecheck group by randomid having count(randomid) > 1) 	0.001186459208483
22926668	26788	join 3 tables with different column names	select s.id, s.shirt_id, case   when s.is_team = 0 then i.member_id   else  t.team_name  end as entity from shirts s left join individuals i on i.id = s.entity_id and s.is_team = 0 left join teams t on t.id = s.entity_id and s.is_team = 1 	0.000956252691240451
22929433	35462	can't get today orders?	select id, date(date) as date,  count(id) as total_sales from away_order_master where shop_id='1' and status='shipped' and date(date) = curdate() group by branch_id order by date desc 	0.00279823397607273
22930157	33142	regex for getting the date	select regexp_substr('outstanding trade ticket report_08 apr 14.xlsx', '\_(.*)\.',  1, 1, null, 1) from dual 	0.0599969609200202
22932288	12618	getting the latest 'role-switch' timestamp from a messages table	select * from (  select * from (   select m.*   from messages m   join (     select conv_id, type, max(created_at) last_created     from messages     group by 1,2) x     on x.conv_id = m.conv_id     and x.type != m.type     and x.last_created < m.created_at) y  order by created_at) z group by conv_id 	0
22932529	19904	mdx+tsql column name doesn't exist	select "[measures].[statename]" as state,     "[measures].[somemeasure]" as [sum]     from openquery(my_olap_server,     'with member [measures].[statename]     as [state].[country].currentmember.member_caption     select {[measures].[statename],[measures].[somemeasure]} on 0,     filter([state].[country].[country],not isempty([measures].[somemeasure])) on 1     from (select {[state].[country].[country].&[index_here]} on columns from [my cube])') 	0.138313734937942
22932629	7763	sql get the count of rows in each group when it 's not null	select action_id,count(action_id) from table1 where  id > (select min(id) from table1 where action_id is null) and id < (select max(id) from table1 where action_id is null) and action_id is not null group by action_id; 	0.000143466447838773
22932752	13379	how to assign string values to numeric values in a sql view	select *,             case when percentage < 80 then 'b'                 when  percentage < 70 then 'c'                 else 'add the grade which should be default when above 2                        case conditions are not met'            end as lettergrade     from (           select *,         100 * count(case turnedin when 1 then 1 else null end)                                   / count(turnedin) as percentage      from table1     when ..) t 	0.000472898727590095
22932793	10060	select date where there is data in-between	select date_sub(logdatetime, interval counter minute) as starttime, logdatetime as endtime from (   select if(todayrainsofar = 0, @i:=0, @i:=@i+1) as `counter`,      logdatetime, todayrainsofar   from     sibeniku_monthly, (select @i:= 0) i   order by logdatetime ) t order by `counter` desc limit 0,1 	0.26734888963592
22933627	24839	query on a relation table	select distinct a_id from relation_table where a_id not in (select a_id from relation_table where status != 1); 	0.0774530085852685
22934427	29089	mysql select specific date from datetime	select      date_format(colname, '%y-%m-%d') as colname from      `my_table`  where      date_format(colname, '%y-%m-%d') >= '2014-01-01' and date_format(colname, '%y-%m-%d') <= '2014-01-15' 	0.000819567548609434
22935146	23186	return boolean on mysql select statment after comparing values of particular column	select    course_id, count( distinct weightage ) = 1 as matched from my_table group by course_id 	0.000180609551453193
22935901	31664	mysql join query on post with categories, only return one result per post	select p.id as pid, min(p.time) as first_post_time, max(pc.category) as category from posts p left outer join postcategories pc on pc.pid = p.id where pc.category in('value1','value2') or pc.category is null group by p.id order by p.time desc 	0
22935972	39794	sorting by total value of two fields in another table where id = id	select  g.gangid, g.gangname, concat('$ ',`tot_wealth`) as `total wealth` from gang g inner join  (     select gang,format(sum(cash+bank),0) as `tot_wealth`     from players      group by gang )p on p.gang = g.gangid group by g.gangid 	0
22938856	36757	mysql query to fetch the quarter month from table	select distinct processym    from activity   where right(processym,2)%3=0   order by processym desc 	0
22939202	3325	mysql - select table a rows that are not in table b except the rows are in table c	select * from a  where (not exists (select * from b where b.dvdid=a.dvdid))    or (exists (select * from c,b where c.rentid=b.rentid and b.dvdid=a.dvdid)) 	0
22939205	38761	how to find a timestamp in string	select from_unixtime(message) as timestamp,        message    from note  where from_unixtime(message) >= '2011-01-01' 	0.00177315331472469
22939580	24896	copy table from one sql server 2005 to another sql server 2005 table	select * from tblusers where value = '76' 	0.000499783722049575
22939885	8040	select data from daily lowest value	select * from table1 t inner join (select date(datetime) as dt, min(value1) v from table1 group by dt) st on date(t.datetime) = st.dt and t.value1 = st.v 	0
22941200	3997	transposing rows to columns in postgres	select * from  (    select right(key, -10) as name_id    where "value" ~~ 'value%'    ) n full join (    select right(key, -10) as name_id, id as desc_id    where "value" ~~ 'desc%'    ) d using name_id; 	0.00104613533286384
22942007	7570	how to get this additional data with existing query	select     source, target from ( select distinct     a.as_no source, b.as_no target, c.`time` trange from     as_path a,     as_path b,     update_detail c where     a.update_id = b.update_id         and a.path_index = b.path_index - 1          and a.update_id in (             select  update_id              from (                 select *                  from bgpstorage.announce_update t1                 join (                     select ip as i, max(update_id) as maxupdate                      from bgpstorage.announce_update                     group by ip                 ) x                  on t1.ip = x.i                  and t1.update_id = x.maxupdate             ) sub         )     ) where `trange` between '2013-02-01 00:00:00' and '2013-02-02 23:59:59'; 	0.184844189993447
22942643	10030	how to join 2 tables when one might be empty	select col_1,         col_2,         col_b    from table_a         left join          table_b on col_1 = col_a   where col_1 <> isnull(col_b,-col_1)  	0.0378569938047053
22943141	4393	sql sum for date range while showing all stock	select     stock.number, sum(items.quanto) as usage, stock.desc1, stock.units, stock.low from     stock       left join     items on          items.item = stock.number and          items.it_sdate between '3/31/14' and '4/5/14' group by stock.number, stock.desc1, stock.units, stock.low 	0.000359616125045068
22944143	2322	how do i combine two tables with inner join and count some of the columns	select g.gangid,         count(p.username) as total_members,         sum(cash+bank) as total_wealth from gang g left join players p on p.gang = g.gangid group by g.gangid 	0.000422760229509378
22944798	25604	stuck on a select query	select  visitors.name, visitors.birthdate, date_format(now(), '%y') - date_format(birthdate, '%y') - (date_format(now(), '00-%m-%d') < date_format(birthdate, '00-%m-%d'))    as age, (select price from prices where age_group < age order by age_group desc limit 1) as price from  visitors 	0.601348922804566
22945873	38192	how can i write a self join that combines rows based on the value of a column?	select     account_id,     max(case when profile_name = 'one' then distributor_id end) as distributor_one_id,     max(case when profile_name = 'two' then distributor_id end) as distributor_two_id,     max(case when profile_name = 'three' then distributor_id end) as distributor_three_id from tbl group by account_id 	6.21899475116936e-05
22947669	31393	duplicate elements in a mutidimensional array php	select artist,         song,         count(id) as uploadcount   from mytable  group by artist,            song 	0.00225990332519897
22948010	289	i am trying to add a new column in access called reduced price that reduces the productunitprice column by 10%	select productid, productdescription, productunitsonhand,        productunitprice, (productunitprice * .9) as [reduced price] from tblproduct 	0.0006783983238203
22951748	40441	repeated values with group_concat without using distinct on mysql query with multiple joins	select i.id, i.title, i.items_title, f.filters_title from ( select   projects.id,   projects.title,   group_concat(project_items.title) as items_title   from projects   left join project_items on project_items.projects_id=projects.id   group by projects.id,   projects.title) as i inner join ( select   projects.id,   projects.title,   group_concat(filters.title) as filters_title   from projects   left join project_filters on projects.id=project_filters.projects_id   left join filters on filters.id=project_filters.filters_id   group by projects.id,   projects.title) as f on i.id = f.id where i.id="1" 	0.526268754918153
22952249	8122	select unique combination of two fields in the db	select *    from (select distinct xsec from tbl) a        cross join         (select distinct condconfg from tbl) b 	7.34614325192712e-05
22953329	18649	select rows if one column equals sum of other two	select gtt_id,column1,total from ( select gtt_id ,       column1,       sum(nvl(column2, 0) + nvl(column3, 0))  total from my_table  group by gtt_id, column1 ) where column1 = total; 	0
22953843	9204	get correct time difference between two times	select     es.empid,     es.shiftid,     es.start_time,     es.end_time,     case when (es.end_time > es.start_time) then         timediff(es.end_time, es.start_time)     else         addtime(timediff('24:00:00', es.start_time), es.end_time)     end from `empschedule` as es inner join `employee` as e on  es.`empid`=e.`empid` 	8.37508106784866e-05
22955011	25723	sum of value with distinct date sql server	select actd0v,sum(price0v) from table_4 group by actd0v 	0.00365612525205322
22957404	14065	join two tables with condition on the first table	select *  from activegroupmodel as a inner join model as m on a.modelid = m.modelid where a.groupid = ?  order by a.groupmodelid desc  limit 1 	0.000433466178857109
22957503	40638	prompt user for table in oracle	select column_name "column name", data_type "data type", data_length "data length",                    data_precision "data precision", nullable "nulls allowed?" from user_tab_columns where table_name = upper('&tabname') / 	0.0550878515087184
22959317	17897	sql union with where clause a result of the first select	select  clients.clientid ,clients.notificationid ,clients.email ,clients.mobile ,clients.homephone  ,jobs.jobid ,jobs.title ,jobs.trade ,jobs.address               as jobaddress ,jobs.urgency ,jobs.dateposted ,jobs.description ,jobs.photo ,jobs.photo2 ,jobs.showaddress ,jobs.showexact ,jobs.jobstatus     ,jobs.tradesmanid     ,jobs.longitude     ,jobs.latitude  from     clients  inner join      jobs         on clients.clientid = jobs.clientid 	0.0354426594633399
22959456	22229	order by descending then ascending same column	select tablename.* from tablename order by   `n/s` = 'n' desc,   case when `n/s` = 'n' then distfromc end desc,   case when `n/s` != 'n' then distfromc end asc 	0.000261022136223088
22960851	12456	joining(?) or unioning(?) values from two columns in two tables, filling in the blank	select id,col_a,col_b,col_union, 'len_' + col_union,length(col_union) as ln from  ( select id,col_a,col_b,col_c as col_union from myuniona  union all select a_id,a.col_a,a.col_b,col_d as col_union from  myunionb  as b inner join myuniona as a on  a.id = b.a_id )a order by id,col_union 	0
22962175	33922	get xml node attribute value	select l.n.value('(pkl/text())[1]', 'int') as pkl,        p.n.value('text()[1]', 'int') as pkd,        p.n.value('@o', 'int') as o from @xmldoc2.nodes('/mt5/l') as l(n)   cross apply l.n.nodes('d/pkd') as p(n) 	0.00044198057801012
22964224	14571	get detail of all ids in comma separated string of same table, mysql	select * from users where id = 2 or  find_in_set(id,(select privilege from users where id = 2)); 	0
22964272	38258	postgresql get a random datetime/timestamp between two datetime/timestamp	select timestamp '2014-01-10 20:00:00' +        random() * (timestamp '2014-01-20 10:00:00' -                    timestamp '2014-01-10 10:00:00') 	0.00132351604144633
22965893	7130	aggregate, show only count >1 for each entry	select article_name, tag, count( * ) as count from articletagview group by article_name, tag having count(*) > 1 order by count desc 	0
22967368	19520	how to count number of digits in a number in oracle pl/sql?	select length(to_char(11111)) from dual 	0.000124081968017338
22967397	33914	convert or cast field in sql query	select date_format(somedate, '%y%m%d') from sometable 	0.596415910842316
22969169	10646	adding a column to a pivoting stored procedure in ssrs/sqlserver 2005	select  a.id  , a.measure , a.value , a.chaptername , a.formtitle , dc.ch_col_region  from #tmp a     join demo_chapter dc      on a.id = dc.id  order by a.chaptername, a.id 	0.363868778949604
22970212	8898	access query to reterive all three fields not equal	select a, b, c from   my_table where  a<>b and a<>c and b<>c 	0.0632252451873861
22971413	23942	retrieve last days data from timestamp(6) column	select * from table_name where trunc(date_initiated) = trunc(sysdate-1) 	0
22971691	39787	mysql query extracting two pieces of information from table	select   userid, game_level, sum(score), x.avg from     my_table join (            select   avg(case when (@rank := (case                       when t.userid     = @userid                        and t.game_level = @gamelevel                       then @rank + 1                       else 0                     end) < 20 then score end)   as avg,                     @userid     := userid     as userid,                     @game_level := game_level as game_level            from     my_table,                     (select @rank := @userid := @game_level := null) init            order by userid, game_level, date_of_attempt desc          ) x using (userid, game_level) group by userid, game_level 	7.52945957778445e-05
22971720	19985	how to produce the same group id for like records in sql server	select address,date,dense_rank() over(order by address, date)  from table1 	0.001412916369984
22972713	28810	sql join within same table	select guid, keyinfo, message from mytable where guid  in(select guid from mytable where keyinfo = 'test-1') 	0.0333254283999277
22972760	8190	group duplicate mysql results under a same result	select tusers.username, messages.sentby,         group_concat( messages.message ) as messages    from messages   join offlineconversations   on messages.messageid = offlineconversations.messageid   join tusers   on tusers.id = messages.sentby    where offlineconversations.userid = 100 group by tusers.username, messages.sentby; 	0.00169083699527936
22974425	19615	avoid null values for a specific record	select * from  (select * from table where column_b = 431 and column_a is not null  union all  select * from table where column_b <> 431) a 	0.00352060415093116
22975025	30628	c#.net: execute two sql statements at a time	select sum(quantity) as sumqty, count(*) as ct from tblstock where prodname = @prodname 	0.0575605337427252
22975502	8297	two tables in left join both have id fields. trying to pull id field from first database, but getting the second instead	select `spins`.id as spinsid from `spins` left join `players` on `players`.id=`spins`.player order by `time` desc limit 30" $content.='<td>'.$row['spinsid '].'</td>'; 	0
22975822	1223	how to return query result as time hh:mm?	select extract(hour from numtodsinterval(sum(hours_worked), 'hour'))||':'    ||extract(minute from numtodsinterval(sum(hours_worked), 'hour')) as total_hours from (... 	0.00872209772762521
22976285	34516	how to compare current time to retrieve record stored in sql	select count(*) as total from tablename where date >= dateadd(hour, 9, convert(datetime, convert(date, getdate()))) 	0
22977419	6439	select query from three tables sql	select i.* from images as i join news as n on n.id_gallery = i.id_gallery where n.id_news = <selected news> 	0.022881921005335
22978632	38475	latest date with sql query	select sum(amount) as total from table1 as t where lastupdate = (select max(lastupdate)                      from table1                      where name = t.name) and amount = (select max(amount)                from table1               where name = t.name               and lastupdate = t.lastupdate) 	0.0140344819360462
22980393	26758	sql have one column in two tables	select table1.*, employees.name, patients.name    from table1   left join employees on employees.id = table1.employeeid   left join patients on patients.id = table1.patientsid 	0.000395144970935277
22981031	31982	how to order sql results starting with a certain string	select animal_name  from animal  where animal_name like '%cat%'  order by  case when animal_name like 'cat%' then 0 else 1 end,   animal_name  	0.000529608614096952
22981654	11313	most efficient way for creating unique index on oracle if dates between two columns intersect	select count(*) as bad_rows   from stack_overflow_question a   join stack_overflow_question b using(ssn, irn)  where a.rowid < b.rowid     and (   a.begin_date between b.begin_date and nvl(b.end_date, a.begin_date)         or b.begin_date between a.begin_date and nvl(a.end_date, b.begin_date)        ); 	0.000320399870546909
22983540	19322	display custid for customers who ordered the exact book > 1	select distinct cust_id     ,(select cust_name_last       from bkorders.customers as cs       where cs.cust_id = oh.cust_id) as cust_name_last from bkorders.order_headers as oh where exists     (select 1 from bkorders.order_details od     where od.order_id = oh.order_id     group by order_id, book_id having count(*)>1) 	0
22984310	17940	return string from mysql without hyphen	select <field(s)> from ringupp where replace(telnr,'-', '') ='$p_mod' 	0.0432917020453018
22986549	14040	php/mysql database daily report	select field_name1, field_name2, field_name3      where date_time_field= '2014-04-10 16:14:54'      order by date_time_field desc 	0.0297712930454164
22987175	26198	how to do union all with different order by conditions	select * from your_table order by case when enquirystatus=1 then lastattendendeddate end desc 	0.00846898178496569
22988146	3218	select and group by year, month and condition	select   year(open_time) as theyear,   month(open_time) as themonth,   sum(case when datepart(yyyy, open_time)= year(open_time) and datepart(mm, open_time)= month(open_time) then 1 else 0 end) theopened,   sum(case when status = 'closed'  then 1 else 0 end) theclosed from   table where   casegroup= 'support' group by   month(open_date),   year(open_date) order by   theyear desc,   themonth asc 	0.00071046520453314
22988328	27552	insert record for each foreign key to result set	select employee_group_id, name from (     select employee_group_id, name, 2 as ordervalue from table1     union all     select distinct employee_group_id, 'somevalue' as name, 1 as ordervalue from table1 ) x order by employee_group_id, ordervalue 	0
22988753	15362	find difference between hours	select [users].memberid,   [users].firstname,   [users].lastname,   thislog.dateofchange,   statuslist1.title as oldstatus,   statuslist2.title as newstatus,   (select top 1 datediff(hour,lastlog.dateofchange,thislog.dateofchange)   from [dbo].[statuslog] lastlog where lastlog.dateofchange<thislog.dateofchange   order by dateofchange desc ) as hourssincelastchange   from [dbo].[statuslog] thislog   inner join [users] on [users].iduser=thislog.iduser   inner join statuslist statuslist1 on statuslist1.idstatus=thislog.oldstatus   inner join statuslist statuslist2 on statuslist2.idstatus=thislog.newstatus   order by dateofchange desc 	0.000121543405993762
22989220	28947	hibernate partially fill objects	select new somedata(c.name, c.code, c.address) from somedata c 	0.230143364496625
22989946	29069	mysql: combine 2 tables and calulate for sum value	select book.isbn, book.title, book.price, sum(total_price)  from sales_item, book  where book.isbn = sales_item.isbn group by isbn; 	0.000946445597493049
22990883	30143	sql select to intersect records by at least one common attribute value?	select t1.id, t2.id, collect_set( feature ) features from   ( select id, feature from mytable ) t1 join   ( select id, feature from mytable ) t2 on   ( t1.feature = t2.feature ) where     t1.id < t2. id group by t1.id, t2.id; 	0
22991225	23753	multi line with no sum	select  case when dim_2  like @query then 'dim_2' end as dim_2, case when dim_3 like @query then 'dim_3' end as dim_3, case when ext_ref like @query then 'ext_ref' end as ext_ref, * from  table1  where client = 'cl'  and period >= @period_from   and @period_to <= @period_to   and voucher_no='170075928'  and agrtid='9662846' 	0.0920870516722716
22991842	31151	how do i select values based on a specific value in a table?	select employeename from salespeople where commrate > (select commrate from salespeople where employeename = 'anne greens') 	0
22991866	38328	get list of active employees at a store	select * from   (select * from     (select * from mytable        where `month` = 3        order by `month` desc,       units_sold desc) a    group by employee_id) j  where location_id = 1 	0
22992224	29648	selecting (almost) duplicate rows	select * from table group by replace(text, 'sth', '') 	0.000662674125892809
22992920	18387	how do i compare 2 columns and return a third based off the result?	select e.employeename, s.employeename as supervisor  from employees e left join employees s on s.employeeid = e.supervisorid 	0
22993090	16978	select query on a table based on condition from other table ? no foreign key	select  a.somecolumn, a.anothercolumn from    a where   exists (select 1 from b where b.x = something); 	0
22994030	15156	sorting with multiple union query	select * from (<your current query here>) as x order by student_name, faculty_name, firm_contact_name 	0.644832265350053
22996396	11227	option menu from distinct price to an option with price range	select case when price between 0 and 500 then '0-500'             when price between 501 and 1000 then '501-1000'             when price between 1001 and 2000 then '1001-2000'             when price > 2000 then '>2000'        end as price_range from products  where category like %s and manufacturer = %s and color = %s group by price_range 	0.000491373132483363
22996959	38435	getting date with timezone offset in postgres	select '1-1-2014 02:00:00'::timestamp at time zone 'utc' at time zone 'america/los_angeles';       timezone         2013-12-31 18:00:00 	0.104348561039323
22998631	18683	how to show one image instead of four images	select * from notes where product_id = ? group by product_id 	0.000138462247281575
22998717	7315	sql server 2012 express how do i pull information from one column and compare it to another with an expression restriction	select c.customerid, c.[company name], isnull(ordersum.ordercount,0) as ordercount     from customers c     left join (select customerid, count(1) ordercount                from orders                group by customerid) ordersum     on c.customerid = ordersum.customerid     where isnull(ordersum.cnt, 0) < 6     order by 2 	0.00130382661426526
22998851	32390	how can i add total row after some results?	select   case when id_user is not null then concat(`year`, '/', `month`)                                 else 'total' end as `year_month`,   id_user,   sum(if(`mod` = 1, 1, 0)) as mod_1,   sum(if(`mod` = 2, 1, 0)) as mod_2,   sum(if(`mod` = 3, 1, 0)) as mod_3 from   dw_rm_log where   `year` = 2014 group by   `year`, `month`, id_user with rollup having `year` is not null and `month` is not null 	0.000155175311934005
22998963	9475	select a column two times to seperate data that i'm viewing (dates)	select id, type,         case when type='lic' then docdate else null end as licdate,        case when type='med' then docdate else null end as meddate from mytable 	4.9516976772915e-05
22999060	29332	mysql chat system to display last message of sender/receiver and name of other person	select sql_calc_found_rows     u.id_user as id,     i.id_user_from,     i.id_user_to,     u.name as name,     unix_timestamp(i.date_msg) as date_msg,     i.message as msg     from inbox as i     inner join user as u on u.id_user = if(i.id_user_from = 1 , i.id_user_to, i.id_user_from)     where id_msg in     (select max(id_msg) as id from     (         select id_msg, id_user_from as id_with         from inbox         where id_user_to = 1         union all         select id_msg, id_user_to as id_with         from inbox         where id_user_from = 1) as t         group by id_with     )     order by i.id_msg desc 	0
22999160	14787	select all which share an id (of a list of ids) with another entry without using subquery	select   distinct   others.userid from   userproject   as target inner join   userproject   as others      on others.projectid = target.projectid where   target.userid = 1 	0
22999953	28781	check if subquery is null	select sid from (   select coalesce(mytable.sid, t.placeholder) as sid   from (select 0 as placeholder) as t    left outer join mytable on keyword='tank' ) as innertmp limit 1 	0.504631718167441
23003859	26518	how to perform a list of drop index concurrently in postgresql?	select 'drop index concurrently "'||schemaname||'"."'||indexname||'";' from pg_indexes where schemaname='public';  drop index concurrently "public"."idx_tbl_id";  drop index concurrently "public"."tbl1_pkey";  drop index concurrently "public"."tbl_join_1_pkey";  drop index concurrently "public"."tbl_join_2_pkey";  drop index concurrently "public"."tbl_join_3_pkey";  drop index concurrently "public"."tbl_join_4_pkey";  drop index concurrently "public"."tbl_join_5_pkey";  drop index concurrently "public"."tbl_join_6_pkey";  drop index concurrently "public"."tbl_join_7_pkey";  drop index concurrently "public"."tbl_join_8_pkey";  drop index concurrently "public"."tbl_join_9_pkey";  drop index concurrently "public"."pgbench_branches_pkey";  drop index concurrently "public"."pgbench_tellers_pkey";  drop index concurrently "public"."pgbench_accounts_pkey";  drop index concurrently "public"."tbl_userinfo_pkey";  drop index concurrently "public"."i_test_pkey"; 	0.14635191368428
23004533	27115	mysql sum field values of a row while grouping by a different row	select `order`, name, product, sum(quantity) as total from tablename group by product,name 	0
23005840	29391	get data from another table using multiple join	select case            when gen.category_name = 'male' then 'mr'            when gen.category_name = 'female' then 'ms'         end as emp_salutation        ,l.login_id as lginfo_nt_login_id        ,org.category_name as emp_organisation        ,gen.category_name as emp_gender_id         ,emp.emp_category        ,emp.emp_id       ,acc.eac_card_number from prj_employee_detail emp       left join prj_category gen on emp.emp_gender_id = gen.category_id        left join prj_category org on emp.emp_organisation = org.category_id       left join prj_login_info l on emp.emp_id=l.lginfo_resource_id        left outer join (select row_number() over(partition by eac_empid order by eac_startdate desc) rn, eac_empid,eac_card_number  from acc_emp_accesscard ) acc on acc.eac_empid = emp.emp_id and acc.rn=1  where l.lginfo_client_id = 0  and emp.emp_number not in ('0','') 	0.000160280233644843
23006042	11291	mysql select multiple/all max values in the same column	select  * from    mytable where   count =          (             select  max(count)              from    mytable         ) 	0.000308096986280483
23006240	162	selecting just one row that has max datetime	select  top (1) v.doorno,v.newdoorno, v.garagename, c.versiondate, v.operatorname as operator, v.operatorid, c.deviceid, c.vehicleid, c.programversionno,                    c.parameterfileversionno, c.tarifffileversionno, c.blaclistfileversionno, c.linenofileversionno, c.screenprogramversion,                    c.soapprogramversiyon from         dbo.vvalidator as v right join                   dbo.cdeviceversion as c  with(nolock) on (v.doorno = c.doorno                                 or v.newdoorno=c.doorno)                                                           where v.newdoorno='o1211'  order by c.versiondate 	0
23006537	29496	how could i find a row with maximun value of a column in sql?	select * from ( select *,rn=row_number()over(partition by city order by totalpoints desc) from table )x where rn=1 	0.000184822729680036
23007555	38735	t-sql select query row numbers as they were without where clause	select * from (select row_number() over (order by color) as row, color from color_table) a where color != 'blue' 	0.00448058492279244
23007779	40350	how to print values from nested query in the main select query?	select tr.l#, tr.reg#, d.e#, count(1) trips from trip tr join driver d on (d.l# = tr.l#) join employee e on (e.e# = d.e#) group by tr.l#, tr.reg#, d.e# 	0.0140883475960511
23008613	25730	show all rows of group with group by	select name,email from users  where email in (     select email from users group by email having count(email) > 1; ) 	0.000291629178594423
23008891	26360	error when selecting from join	select count(*)  from individual as i left join establishment as e using (establishment_id) where i.bla = e.bla; 	0.453137378400041
23009143	8555	how to select faulty records?	select * from your_table where section > 1 and districtname in (   select districtname   from your_table   group by districtname   having count(distinct disid) > 1 ) 	0.0201044195573218
23009482	35871	t-sql query to get the last value in a list of months	select date,value from table1 where date in (     select max(date) from table1 group by month(date) ) 	0
23010031	26022	sql find next available string key	select   concat('dsh', lpad(seq, 10, '0')) as k from   (select     @seq:=@seq+1 as seq,     num   from     (select        cast(substr(table_id, 4) as unsigned) as num      from        t      union all      select         max(cast(substr(table_id, 4) as unsigned))+2 as num      from         t      order by        num) as ids    cross join        (select @seq:=0) as init    ) as pairs where   seq!=num limit 1 	0.000114619600827215
23010772	23161	check columns for two seperate rows and return true if identical	select exists (  select 1 from tablename t1, tablename t2  where   t1.`attribute_1` = t2.`attribute_1` and  t1.`attribute_2` = t2.`attribute_2` and  t1.`attribute_3` = t2.`attribute_3` and  t1.`product` = $id1 and  t2.`product` = $id2 ) 	0
23012148	3496	select same row multiple times	select t1.* from ( select a.a, b.b, c.c from a inner join b .. inner join c .. where a.a =.. and b.b = .. and c.c = .. ) as t1 inner join number_table on 1=1 where number<=3 	0.000277183645979338
23014869	9668	postgresql sql query: getting a count of everyday within a period	select count(id), extract(hour from visitors.last_seen) as hour,  extract(day from "visitors"."last_seen") as date,  extract(month from "visitors"."last_seen") as month  from (select id,generate_series(first_seen,last_seen,'1 hour'::interval) from tbl) t where ... group by month,date,hour  order by month asc, date asc , hour asc 	0.0133988473876862
23015312	9372	t-sql query: select only the most recent row (for each computer name)	select * from ( select *, row_number() over (partition by computername order by timestamp desc) rno  from computerstatus ) where rno = 1 	0
23017735	15466	sql query to compare one column with another	select s.*, sum(pledge_payment_amt) as pledged from test_table2 as recipients left join test_table2 as pledgers     on recipients.gift_no = pledgers.pledge_gift_no group by s.gift_no having s.pledge_amount > pledged 	0.000735761058525895
23018772	4622	row permissions based on child rows	select * from events where id not in(   select event_id from events_accounts where account_id not in(     select account_id from users_accounts where user_id = @user_id )) 	0
23019730	20038	list of sql exceptions caused by a trigger	select * from sysmessages where description like '%trigger%' 	0.192358817866538
23021310	8618	sql server : casting a decimal value to nvarchar	select cast(yourcolumn as varchar(3)) + '%'  from yourtable 	0.0853200631596633
23021777	29819	sqlite union columns	select mid, 0 as aid, name from table1 union select 0 as mid, aid, name from table2; 	0.0945420604815771
23021919	1727	querying a specific result set	select       yt2.*    from       ( select yt.wonum            from yourtable yt            where parent is null              and status = 'comp' ) pq       join yourtable yt2          on pq.wonum = yt2.wonum          or pq.wonum = yt2.parent    order by       coalesce( yt2.parent, yt2.wonum ),       case when yt2.parent is null            then 1 else 2 end 	0.0149892365926734
23022138	33933	calculate weeks between more than one date entry in mysql with php	select c.clutch_breeding_pair,   ifnull(avg(datediff(c.next_clutch_laid_date,c.clutch_laid_date)/7),0) average_weeks from (     select c1.clutch_breeding_pair,       c1.clutch_laid_date,       min(c2.clutch_laid_date) next_clutch_laid_date     from clutches c1       left join clutches c2         on c2.clutch_laid_date > c1.clutch_laid_date         and c2.clutch_breeding_pair = c1.clutch_breeding_pair     where c1.clutch_breeding_pair = 2     group by       c1.clutch_breeding_pair,       c1.clutch_laid_date     ) c group by   c.clutch_breeding_pair 	0
23023789	39111	how would i write a sql query to retrieve closest match to my parameters?	select * from rulestable where isnull([type], @param1) = @param1 and isnull(subtype1, @param2) = @param2 and isnull(subtype2, @param3) = @param3 order by [type] desc, subtype1 desc, subtype2 desc 	0.27782261280284
23024013	39796	sql query to delete charge and matching credit	select     t.mbrid,     t.transactiondate,     t.charge,     t.authorizationid from yourtable t     left join yourtable r         on r.reversalid = t.authorizationid where t.reversalid is null     and r.reversalid is null 	0.238480686208854
23024710	19826	join tables from multiple sources	select c.id, c.name, c.cost, 'job assign' as assign_source   from course c   join job_assignment ja     on ja.course_id = c.id   join employee emp     on emp.job_id = ja.id  where emp.name = 'bob' union all select c.id, c.name, c.cost, 'pers assign' as assign_source   from course c   join personal_assignment pa     on pa.course_id = c.id   join employee emp     on emp.job_id = pa.id  where emp.name = 'bob' 	0.0309023094594184
23026065	21010	mysql: sum of multiple subqueries	select *, plays1 + plays2 + plays3 as total_play from  (select  ...         (select one_result ... limit 1) as plays1,         (select one_result ... limit 1) as plays2,         (select one_result ... limit 1) as plays3 from plays) order by total_plays 	0.190404002462523
23026178	25877	sql incorrect join and condition compare value	select      c.courseid,      c.gradevalue mingradevalue,     isnull(min(m.gradevalue)-1,100) maxgradevalue,     l.lettergrade ,     l.[description]  from coursegrade c     left join lettergrades l         on c.lettergradedid=l.lettergradeid      left join coursegrade m         on m.courseid=c.courseid         and m.gradevalue > c.gradevalue group by     c.courseid,      c.gradevalue, l.lettergrade ,     l.[description]; 	0.272128627088617
23026214	35441	mysql group by function	select *, count(*) as total  from `tybo_orders`  where timestamp in (select max(timestamp) from `tybo_orders` group by email)  and  store_id='5416'  group by  case when customer=0 then customer else email end 	0.748487103682477
23033345	2213	mysql opposite of left join	select u.id from   a as u left join b as c   on u.id = c.a_id  where   u.active='1'   and c.a_id is null 	0.704771013534172
23033492	391	sql query to display only unsold tender	select    tendername from [tender master] tm where not exists       (           select 1 from [bid master] bm           where tm.tenderid = bm.tenderid           and bm.status = 'sold'       ) 	0.0189243738226606
23033674	25731	sql adding result of 2 count querys	select count(*) from (     select 1     from team     where team.teamname in (select data from csvtest_match where header in ('home team', 'away team'))     union all     select 1     from teamalias     where teamalias.teamname  in (select data from csvtest_match where header in ('home team', 'away team')) ) t 	0.0238640070316167
23034235	2696	sum of row and column in sql pivot table	select t.c_melli, s.[1], c.[1], s.[2], c.[2], s[3], c.[3], s.[1]+s.[2]+s.[3] as sumrow from (select distinct c_melli from temp) t inner join(   select * from   (select * from temp) as s    pivot   (     sum(price)     for [cost_teacher] in ([1],[2],[3])   ) as p1 ) s on s.mellicode = t.mellicode inner join(   select * from   (select * from temp) as s    pivot   (     count(price)     for [cost_teacher] in ([1],[2],[3])   ) as p1 ) c on c.mellicode = t.mellicode 	0.00183726926957432
23035532	26021	sql group by month and join	select dateadd(month, datediff(month, 0, activation_date), 0) as mymonth,  count(case when stb_group = 'laptop' then stb_group end) as laptop, count(case when stb_group = 'pc' then stb_group end) as pc,  count(stb_group) as units from inventary  where (activation_date > '10-01-2013')   group by dateadd(month, datediff(month, 0, activation_date), 0) 	0.0551853361690809
23037747	39112	sql count on group by	select users_id, count(distinct problem_id) from `submission` where status = 'ac'  group by users_id 	0.159862451283737
23038288	15935	include rows that contain null values in a particular column with inner join	select distinct e.employee_id as employee_id,                  e.full_name as employee_name,                  m.manager_id as reports_to,                  m.full_name as manager_name from emps e left join emps m on e.manager_id = m.employee_id; 	0.000955492822015456
23038561	36630	mysql query to return a list of months	select date_format(date, '%y-%m-01') as months from table group by months; 	0.000883352980490482
23038621	37348	select 1 random item in mysql from many post_ids	select     mt.id,      mt.post_id,      mt.title from (   select   distinct mt1.post_id as my_post_id,      (        select          tttt.id as m_id        from mytable tttt        where tttt.post_id = my_post_id        order by rand()        limit 1      ) as t   from mytable mt1   group by mt1.post_id ) as tt join mytable mt on mt.id = t group by mt.post_id 	0.000393890817172291
23040872	11900	how to find table name using select query	select product, 'table_name_1' as table from table_name_1 where id = '% textbox1.text %' union select product, 'table_name_2' as table from table_name_2 where id = '% textbox1.text %'  union select product, 'table_name_3' as table from table_name_3 where id = '% textbox1.text %' 	0.00548798241477535
23041233	39011	datagridview - condition within condition	select * from yourtable where nalog in    (select nalog from yourtable    where nalog like '%u-%'    and datpro between #1/1/2014# and #12/31/2014#    and konto like '%2702%') 	0.343576120115578
23042861	40766	users with their child count	select t1.userid, t1.name, count(t2.userid)  from table t1  inner join table t2 on t2.parentid = t1.userid  group by t1.userid, t1.name 	0.000549101190862227
23044264	13545	how to query all locations that are near a user's position(latitude, longitude) in mysql	select loc.id from `user` u, locations loc where u.id = @user_id   and (6371 * acos(cos(radians(u.latitude)) * cos(radians(loc.latitude )) * cos(radians(loc.longitude ) - radians(u.longitude)) + sin(radians(u.latitude)) * sin(radians(loc.latitude )))) <= @circle_diameter / 2; 	0.0126970532855778
23046740	40308	query to show "standard" theme first, then rest of the results	select     *  from      installed_designs  where      u_id='$user[id]'  order by      standard desc,     tmp_id desc 	0
23047201	39285	get next month in y-m-d format from any given y-m-d	select * from sometable where somedate like '%-08-%'; 	0
23047372	35971	fix subquery returning more than 1 row	select s.stationid,        s.capacity,        count(c.currentstationid) as num_cars_at_station   from station s   join cars c     on s.stationid = c.currentstationid  group by s.stationid, s.capacity having count(c.currentstationid) >= s.capacity 	0.435253589116162
23048240	17042	ms access – return a daily count of booked resources within a date range	select c.check_date, count(b.resource_id) as resources_used   from calendar c, bookings b  where c.check_date between b.start_date and b.end_date group by c.check_date 	9.09146089672306e-05
23049725	31284	mysql find an id based on 2 ids	select     roundid from     entries where     playerid in (9, 14) group by     roundid having     count(*)>1 	0
23050578	31663	access sql statement to query the current day	select count (custid) as [number of transactions]     from [transaction]     where format (date, "short date") = format(now(), "short date") 	0.00249847330762507
23050670	29315	outer joining to more than 1 table	select ta.columnb,tb.columnb from  tablec tc  left join tableb tb on (tc.columna = tb.columna) left join tablea ta on (tb.columna = ta.columna) 	0.132856719587704
23051591	4557	selecting count without group by	select  orderid,         containertype,         count(containerid) over (partition by orderid, containertype) as containercount,         containerid from    @ordercoarntainers 	0.0275624179625512
23052881	32856	unable to retrive rows when using where instead of on	select * from a, b where  a.column1 = b.column1 	0.0147317035389444
23053460	3447	multi-tenant how to overwrite default values?	select * from  (   select * from user_styling limit 1   union all   select * from default_styling limit 1  ) tmp limit 1 	0.0103824715216794
23053631	4079	mysql query for getting records with reference to records of related table with condition	select pr.id, pr.jobno  from project pr  join (select jobno        from user_table u        join assign_user a on u.id=a.f_userid        join project p on p.id=a.f_projectid where u.id=2) a  on pr.jobno=a.jobno  where pr.islive='y'; 	7.80909311763538e-05
23054693	39308	how to use several group by in one query?	select t1.zone_id,t1.temperature    from tempdat t1 where    t1.tdate = curdate() and t1.temperature =     (select max(t2.temperature) from  tempdat t2          where t1.tdate = t2.tdate          and t1.zone_id = t2.zone_id); 	0.078983716790683
23054990	20988	compare php datetime value with mysql query	select * from event_master where create_on = str_to_date('$date_time', '%y-%m-%d %h:%i:%s'); 	0.0149468994859818
23058720	11502	name of parent category with parent_id	select a.category_id, a.name as category,  b.name as parent from "category" a join "category" b on a.parent_cat=b.category_id where a.parent_cat is not null order by a.name 	0.000709000909005274
23059242	6584	mysql table with key/value pairs, get keys as column names	select     max(case when name = 'start' then value end) as `start`,     max(case when name = 'stop' then value end) as `stop`,     max(case when name = 'fwd' then value end) as `fwd` from info where id = 110506; 	0
23061892	5666	searching multiple values in sql table, with a range	select * from recipes where   case when ingredients like '%ketchup%' then 1 else 0 end   +   case when ingredients like '%salt%' then 1 else 0 end   +   case when ingredients like '%honey%' then 1 else 0 end   > = 2; 	0.00154267441983423
23062724	37988	sql combining two queries	select      accountname,      emailaddress,      dateofbirth from  (     select          a.accountname,          a.emailaddress,          u.dateofbirth,          a.loginid,         count(*) over (partition by a.emailaddress, u.dateofbirth) as cnt     from account as a      join [user] as u on a.accountid = u.accountid               ) ua            join audit as a    on a.loginid = au.loginid      where cnt > 1 and emailaddress is not null and dateofbirth is not null      and a.startdate = (select max(startdate) as startdate                    from    audit as b                    where b.loginid = a.loginid) order by emailaddress, dateofbirth 	0.081417787109067
23063069	779	postgresql returning duplicate ids when using in in a join	select p.description, p.featureimage, a.accessory_id from accessories a     join products p on p.id = a.accessory_id 	0.0253726290948394
23063724	11412	sql - select boolean results from table	select id_user, mail_id      , groupid current      , @roll := case when coalesce(@groupid, '') = groupid                       then @roll + 1                       else 1                  end as roll      , @groupid := groupid old from   (select mh.id_user, mh.mail_id              , concat(mh.id_user, mh.mail_id) groupid         from mailing_history mh              inner join (select   id_user                                 , max(case isread                                             when 1 then mailsend_id                                             else 0                                        end) lastread                          from     mailing_history                          group by id_user) lr      on mh.id_user = lr.id_user and mh.mailsend_id > lr.lastread order by id_user, mailsend_id) a 	0.0240743456352813
23064220	21179	sql checking if value exists through multiple different tables	select vals from tablea a  unpivot( vals for n in (columna, columnb, columnc)          ) up where vals  = '534bde4c322755995941083' union all  select columnd  from tableb  where columnd =  '534bde4c322755995941083' union all  select vals from tablec  c  unpivot( vals for n in (columne, columnf)          ) up where vals  =  '534bde4c322755995941083' 	0.00187323300539409
23064240	36608	figure out which orderids are 0$ payment totals	select distinct a.orderid,                 a.orderpaid,                 c.orderamount                 d.payment from vwselectorders as a inner join ( select sum((lineprice + lineshippingcost + linetaxcost + lineoptioncost) * linequantity) as orderamount,orderid              from vwselectorderlineitems group by orderid) as c on c.orderid = a.orderid inner join (select sum(payamount) as payment,orderid from vwselectorderpayments where isnull(sum(payamount),0) > 0 group by orderid) as d on d.orderid = a.orderid left outer join vwselectorderpayments b on b.orderid = a.orderid where b.payvalid = 1 and a.orderpaid = 0 and 	0.179301644586793
23065013	15525	parsing string in mysql and get the date	select replace(substring_index(substring_index(name,'_',4),'_',-3),'_','-') as date from test 	0.00322005666294777
23065038	36541	where not exists with one to many relationship	select  * from    itemsale i where   not exists          (   select  1             from    itemsale i2             where   i.itemid = i2.itemid             and     i2.categoryid = 1         ); 	0.156402916278427
23066226	19653	concatenate and format text in sql	select   isnull(city, '') +   case when isnull(city, '') != '' then ', ' else '' end +   isnull(state, '') +    case when isnull(state, '') != '' then ', ' else '' end +   isnull(country, '') as outputtext  from    places 	0.0326531680754013
23069326	40488	add average time to last row of query using sqlite	select t.id, ... from ... where ... union all select 999999999, null,        avg(strftime('%s', c.created_at) - strftime('%s', t.created_at)),        null, null from ... where ... order by 1 	0
23069920	24917	select randomly 3 records in a second table	select s.* , round( coalesce( avg( n.note ) , 0 ) , 1 ) as average, g.genres from serie s left join      note n      on s.id_serie = n.id_serie left join      (select substring_index(group_concat(distinct g.genre order by random()), ',', 3) as genres       from genre g       group by g.id_serie     ) g     on g.id_serie = s.id_serie group by s.id_serie order by average desc 	0
23071554	270	joining query result with another table	select ta.column1 , coalesce(te.column2,ta.column2) as  mydata, tx.column2 from tablea ta inner join tableb tb on (ta.column2 =tb.column1) left join tablec tc on (tb.column2  = tc.column1) left join tabled td on (tc.column1 = td.column1) left join tablee te on(td.column2 = te.column1) left join tablex tx on (coalesce(te.column2,ta.column2)) = tx.column1 	0.0135336526854225
23071861	34925	how can i export mysql qry results to a csv or excel file?	select * from table_name into outfile '/dir/file.csv' fields terminated by ',' enclosed by '"' lines terminated by '\n' 	0.336374332066174
23071960	5912	mysql query to not show duplicate records	select * from (    select * from highscores    order by score desc) x group by name order by score desc limit 100 	0.00373456089053448
23075871	25672	output content of a table as one line in mysql sql	select group_concat(product,',' ,quantity) from orders; 	0.00147230420575786
23077415	18947	query filtering by date and time in one column and milliseconds in another	select *  from table where ( '2014-04-11 13:33:24' < time_stamp or ('2014-04-11 13:33:24' = time_stamp and 879 <= time_stamp_ms)) and ( '2014-04-11 13:33:25' > time_stamp or ('2014-04-11 13:33:25' = time_stamp and time_stamp_ms < 79)) 	5.36601375245856e-05
23077845	10704	how to split a string using two characters using regular expressions in oracle?	select regexp_substr(            'test1,test2@mail.ru, test3.vasya@test4.com'          , '([^@ ]+@[^,]+)'          , 1, 1) m1      , regexp_substr(            'test1,test2@mail.ru, test3.vasya@test4.com'          , '([^@ ]+@[^,]+)'          , 1, 2) m2    from dual; 	0.162363258796215
23079147	2245	mysql order by, showing uppercase results first	select     id as id,    cast(aes_decrypt(fname,'$_enckey') as char character set latin1 ) as fname1,    aes_decrypt(lname,'$_enckey') as lname     from patient     order by fname1 collate latin1_general_cs 	0.0184212890635977
23079345	7194	oracle sql query for subtracting time from timestamp	select date_create,id from table where date_create >= current_timestamp - numtodsinterval(15, 'minute') 	0.00368418494563729
23080796	31605	display certain values mysql	select users1.id,users1.nume, count(pontaj.prezente)     from users1     inner join  pontaj     on users1.id = pontaj.id   group by users1.id,users1.nume 	9.84038858412985e-05
23083397	36252	check if time difference between date in database greater than today	select startdate from db_dates where abs(datediff(str_to_date(startdate, '%m-%d-%y'), curdate())) > noofdays 	0
23085834	20504	oracle: limiting a join with a 'many' table to just one instance?	select      b.meet_name as course,      a.race_time as time,      (f.jf_name||' '||f.jl_name) as jockey,          e.horse_name as horse,      c.odds,      d.place,      d.race_comment as note,      (g.bf_name||' '||g.bl_name) as breeder,      h.trainer,      a.race_type as type,      a.distance as     furlongs,      a.prize_money as "prize money",      a.ground as ground from proj_race_details a join proj_meet b on a.meet_id = b.meet_id join proj_entry c on c.race_id = a.race_id join proj_results d on d.race_id = c.race_id and d.horse_id = c.horse_id join proj_horses e on e.horse_id = d.horse_id join proj_jockey f on f.jockey_id = d.jockey_id join proj_breeder g on g.breeder_id = e.breeder_id join  (select ph.horse_id as horse_id, min(pj.tf_name||' '||pj.tl_name) as trainer from proj_trainer pj inner join proj_horses ph on pj.trainer_id = ph.trainer_id group by ph.horse_id ) h on h.horse_id = e.horse_id; 	0.0159086991176683
23086803	7652	mysql group by to produce one row	select max(if( sort_order =1, title, null )) as q1,        max(if( sort_order =2, title, null )) as q2,        max(if( sort_order =3, title, null )) as q3 from  `choice`  where  `question_id` = 1101; 	0.00952242104274923
23088121	23602	sqlite: merging two tables with using id and hash-value, where resulting ids are from a chosen table	select * from x where hash not in (select hash from y) union all select * from y 	0
23091018	36454	sql query to sum the column data	select sum(price) from thistable where fmt in ('mt1','mt2','mt3','mt4','mt5'); 	0.0190730807742066
23091849	11441	select a specific column in sql server from a concatenation from a different table	select case tableb.[column] when '01' then tablea.column01                             when '02' then tablea.column02                             when '03' then tablea.column03                             when '04' then tablea.column04                             when '05' then tablea.column05        end as value from tablea  inner join tableb on tablea.item_id = tableb.itemb where tablea.item_id = 1 	0
23093314	35737	restricting values in a table used in a full outer join	select ts.seg_id, ts.departure_location, ts.destination, p.partner_name from trip_segment ts full outer join transportation t    on ts.seg_id = t.seg_id full outer join (select *                   from partner                   where partner.partner_id < 6) p    on t.partner_id = p.partner_id; 	0.547782587886066
23094414	22267	sql select max values	select max(     case myvalue         when 'x' then 1         when 'y' then 2         when 'z' then 0     end) myvalue from mytable 	0.0283576250716936
23094909	11522	get sql table info	select * from  mylinkedserver.mydatabase.information_schema.columns where table_name = 'address' 	0.00257231366372314
23095418	12693	which mysql query to select product based on location	select   m.name,   d.miles,   d.mfr_id from distances d   join mfr on mfr.id = d.mfr_id     and mfr.radius > d.miles   join models m on m.mfr_id = mfr.id   join (select m1.name,min(d1.miles) miles         from models m1           join distances d1 on d1.mfr_id = m1.mfr_id         group by m1.name         ) md on md.name = m.name              and md.miles = d.miles where d.zip_code = 72761 order by d.miles asc 	0.000664755393567568
23096280	2950	sql join - calculate weighted students grades based on grade type	select s.stu_fname, s.stu_lname, gt.grade_type_name,  (sum(sg.grade_earned)/sum(g.grade_possible) * gt.grade_weight) as calculated grade  from student s     inner join studentgrade sg on sg.stu_id = s.stu_id     inner join grade g on sg.grade_id = g.grade_id     inner join gradetype gt on g.grade_type = gt.grade_type group by s.stu_fname, s.stu_lname, gt.grade_type_name; 	0.000387911007569166
23096547	15163	why dateadd is not getting data from past month?	select * from intranet.dbo.csereduxresponses where status=1 and execoffice_status=0  and month([approveddate])= month(dateadd(month,-1,getdate())) and year([approveddate])= year(dateadd(month,-1,getdate())) 	0.00858687977398597
23097356	4013	matching fighters from a single table	select min(a.id),b.id,a.fullname name1,b.fullname name2,a.weight     from tfc_sparring_requests_athletes a ,tfc_sparring_requests_athletes b  where a.weight = b.weight     and a.fightsport = b.fightsport      and a.level =b.level      and a.sex = b.sex      and a.fullname != b.fullname     and b.id > a.id group by b.id; 	0.000515031647991481
23098629	9991	duplicate rows of data except 2 columns	select checksheet_no,        max(case when rn=1 then fault end) as fault1,        max(case when rn=2 then fault end) as fault2,        max(case when rn=3 then fault end) as fault3 from    (    select checksheet_no,fault,        row_number() over(partition by checksheet_no order by fault) as rn    from checksheet_fault     ) z group by z.checksheet_no 	0
23100736	3045	did "and" and "or" will work in same query?	select *  from products_event   where products_event.active > 0        and is_event_activated > 0        and is_user_activated > 0        and quantity > 0         and         (products_event.name like '%" . $search_keyword . "%'        or products_event.short_desc like '%" . $search_keyword . "%') 	0.734157708379051
23100761	38753	use having to find avg	select w.wrkname,sum(ti.hrsworked) "total hours" from timelog ti  inner join allocation a  on ti.wrkid = a.wrkid and ti.taskid = a.taskid  inner join worker w  on ti.wrkid = w.wrkid  group by w.wrkname having sum(ti.hrsworked) >      (select avg(hrsworked)       from          (select wrkid, sum(hrsworked) as hrsworked           from timelog          group by wrkid)     ) order by 1; 	0.29376303803343
23100972	22512	oracle sql - union attribute from where parenthesis in starting select statement	select      co.owner_id     , educational_structures.name "committee name"     , c.min_members "minimum members"     , c.max_members "max members"     , c.type "type" from      committeeowner co     ,committee c     ,(  select committeeowner_owner_id, name         from unit natural join committeeowner          union all         select committeeowner_owner_id, name         from school natural join committeeowner         union all         select committeeowner_owner_id, name         from campus natural join committeeowner) educational_structures    where      owner_id = committee.committeeowner_owner_id      and owner_id = educational_structures.committeeowner_owner_id order by owner_id; 	0.232947215483521
23101298	28866	ms access query for items not in table	select tableb.* from tableb left join tablea on tableв.orderid = tablea.orderid where tablea.orderid is null; 	0.278724639877227
23103427	24854	summarize mysql table entries by day	select dayname(date) as day,  group_concat(completedtasks separator ',') as completedtasks,  group_concat(duration separator ',') as duration,  group_concat(educationdepartment separator ',') as educationdepartment  from programm_completedtask group by dayname(date); 	8.19688370044322e-05
23104301	23826	using inner join & distinct in one query	select mc.* from merge_codes mc join (select distinct country from factors) f   on mc.country = f.country 	0.503783729030961
23105368	386	build dynamic string efficiently tsql	select replicate(@in,@len) 	0.764781097395928
23105442	27938	how to know my timezone in mysql	select timediff(now(), utc_timestamp); 	0.617518761232203
23108563	13997	mysql query combine table from one table	select        t1.word1, t1.word2, t1.count,        coalesce(t2.word1, 'b') as word1_, t1.word2 as word2_, coalesce(t2.count, 0) as count_ from table1 t1 left join table1 t2 on t1.word2 = t2.word2 and t2.word1 = 'b' where t1.word1 = 'a'  union select        coalesce(t2.word1, 'a'), t1.word2 , coalesce(t2.count, 0),       t1.word1 as word1_, t1.word2 as word2_, t1.count from table1 t1 left join table1 t2 on t1.word2 = t2.word2 and t2.word1='a' where t1.word1 = 'b' 	0.000407126553542466
23108778	28516	get certain amount of rows after the first 3 php mysql	select * from #__table where published=1 order by id desc limit 0,3 then limit 3,3 next limit 6,3 	0
23110769	7026	foxpro database and date, how?	select * from table where between(mydate, gomonth(mydate, -12), mydate) 	0.0490992942677007
23111378	32159	reversing order of results in start with lpad sql query	select lpad('*', 2*level-1)||sys_connect_by_path(unit_data, '/') "battle_unit_id"    from battle_units    start with parent_id is null    connect by prior battle_unit_id = parent_id; 	0.292646997386524
23111867	20600	oracle sql count of a field grouped by another field	select  count(*) as count, sum(area) as area location_id, zone, from table where site_id = 'abc' and location_id not like ('%land%') group by location_id, zone 	9.21376875606145e-05
23114433	39832	query to select row with specific id for each of two unique fields & count position of third field	select t1.type, t1.pspeed, 1+sum(t2.pid is not null) as rank from scores t1 left join scores t2    on t1.type = t2.type and t1.pspeed = t2.pspeed and t1.distance < t2.distance where t1.pid = 1 group by t1.type, t1.pspeed 	0
23114727	3860	order by before group by for leaderboard	select t.user_id, m.min_result, min(t.id) id from results t inner join (select user_id, min(result) min_result             from results             group by user_id) m         on t.user_id = m.user_id        and t.result = m.min_result group by t.user_id, m.min_result 	0.558459514106029
23115211	2315	how do i query a parent table for two distinct child rows?	select distinct o.order_id from order o join lineitem item1   on item1.order_id = o.order_id join lineitem item2   on item2.order_id = o.order_id  and item2.lineitem_id != item1.lineitem_id where item1.price = 10   and item2.productcode = 12345 	0
23115281	36662	doing two count on a single column without using views in one sql statement or in pl/sql block	select student_idstudent,     count(case when  status = 'present'  then 1 end)/count(*)*100 as percentage     from attendence      where student_subject_subjectid = 102     group by student_idstudent; 	0.0100213028170098
23115338	17341	3 table join - with two unique identifiers pulling different data from the third	select    cakes.*,   sponges.*,    cake_description.description as cake_description,   sponge_description.description as sponge_description from sponges join cakes on cake_id = sponge_id join descriptions cake_description on cake_description.cake_desc_id = description_id join descriptions sponge_description on sponge_description.cake_desc_id = description_id 	0
23117418	16378	android sqlite virtual table id value not auto incrementing, returning null	select rowid, * from yourtable 	0.000498762721443236
23118360	12815	sql pivot table	select pvt.* from (   select clientpartner, clientmanager, wipamount from tbltranwip ) as tranwip pivot (  sum(wipamount) for clientpartner in ([46], [58], [177], [207]) ) as pvt 	0.343610850717632
23118487	12955	sqlite rows to column	select teamname,        group_concat(playername) from teams join players using (teamid) group by teamid 	0.0101959992054731
23119255	12992	sql select where (sum of 2 columns) is greater than x	select * from rentals where town = town and fullbath + halfbath >= bathrooms 	0.00010197177444484
23120240	23222	mysql how to get count of rows for each keyword	select     'test' as `search_term`,     count(*) as `term_count` from table where text like '%test%' union select     'test2' as `search_term`,     count(*) as `term_count` from table where text like '%test2%' union select     'test3' as `search_term`,     count(*) as `term_count` from table where text like '%test3%' 	0
23120287	32020	how to evaluate an expression for last 12 weeks in ssrs	select top 12 [date], [abandon_rate] from [db].[dbo].[table] order by convert(date,[date]) desc 	0.00275471553486948
23124257	28425	mysql complex order by specific attribute	select u.* from users u inner join attributes a      on (a.username = u.username and a.datakey = 'your_datakey_value') order by a.datakey; 	0.102738932195366
23125062	8605	merge two row results into one row mysql	select pid,        max(case when email_type=1 then email end ) as email_p ,        max(case when email_type=2 then email end ) as email_w  from tablename where email_type in (1,2) group by pid 	0
23126166	12600	how can i list the columns in information_schema.columns?	select column_name, data_type  from information_schema.columns  where table_name = 'columns'   and table_schema = 'information_schema'; 	0.00454760334836361
23126518	8068	how do i structure a sql query to find an object that is the parent of two specific other objects?	select p.* from parent p join join_table j on p.id=j.parent_id where j.child_id=1 or j.child_id=2 group by j.parent_id having count(j.child_id)=2; 	0
23126781	41065	how to get the time in milliseconds of a store procedure	select datediff(millisecond, datefrom, dateto) 	0.000346657000664353
23127438	37947	sql sum values from different tables using item_details group by order_id and order_date	select o.orderid, sq.total+o.freightcharge from order_table o left join (   select o.orderid, sum((od.unitprice*od.quantity)*(1-od.discount*0.01)) as total    from order_table o, order_detail_table od   where o.orderid=od.orderid group by o.orderid ) sq on sq.orderid=o.order_id; 	0.000470794824615813
23128264	26256	compare rows sql counting discrepancies in value	select id, @prevgreater and secondval < firstval as discrepancy,         @prevgreater := secondval > firstval as secondgreater from (select * from yourtable order by id) as x cross join (select @prevgreater := false) as init 	0.000459161003589861
23128317	9802	insert random number mysql	select @cnt := count(*) from my_table; update my_table set random = floor(@cnt * rand()) + 1; 	0.0108764130859428
23128612	35738	how to add same column value but having different ids	select i.item_id,case when i.item_id='chocolate/icecream' then (select sum(item_cost) from dbo.tbl_item_cost where item_id in ('chocolate','icecream')) else item_cost end as item_cost from dbo.tbl_item_cost c right join dbo.tbl_item i on i.item_id=c.item_id 	0
23128735	27211	min and max value in sql sever	select convert(varchar(10), max(checktime), 120),         convert(varchar(8), max(checktime), 108) time,         userid,         max(checktime)   checktimeevent,         checktype  from   checkinout,         workdateview  where  convert(varchar(10), checktime, 120) = workdateview.workdate         and userid = 2         and checktype = 'o'  group  by userid,            checktype  union  select convert(varchar(10), min(checktime) , 120),         convert(varchar(8), min(checktime) , 108) time,         userid,         min(checktime)                      checktimeevent,         checktype  from   checkinout,         workdateview  where  convert(varchar(10), checktime, 120) = workdateview.workdate         and userid = 2         and checktype = 'i'  group  by userid,            checktype 	0.0318575207435659
23129315	39360	select events that take place in given month	select *      , case when date_from >= '2014-03-01' and date_to < '2014-04-01' then 'fits'              when date_from < '2014-03-01' and date_to between '2014-03-01' and '2014-04-01' then 'past'              when date_from between '2014-03-01' and '2014-04-01' and date_to >= '2014-04-01' then 'extends'              when date_from <= '2014-03-01' and date_to >= '2014-04-01' then 'full'          end `range`    from eventstesting  having `range` is not null; 	0
23130199	19141	select from 2 tables when t1.id=t2.id and t1.name<>t2.name	select   * from   table1 inner join   table2     on  table1.id    = table2.id     and table1.name <> table2.name 	0.00985141189056177
23130302	5837	combining resultset to get one row	select nodeid ,nodename ,max(convert(int,canadd)) ,max(convert(int,candelete)) ,max(convert(int,canedit)) ,max(convert(int,canview)) from yourtable group by nodeid, nodename 	0.000112130067326419
23132049	8972	random id fetching from database	select columnlist from tablename order by rand() limit 1 	0.000609177291106592
23132240	6746	using left outer join to retrieve data	select table1.items,  table1.category,  table1.buyer,  table2.price,  table2.stocks  from table1  left outer join table2  on table2.item = table1.items  where table1.items  = 'fr732001'; 	0.651003352394121
23133860	1387	how to convert datetime value to yyyymmddhhmmss in sql server	select replace(replace(replace(convert(varchar(19), convert(datetime, getdate(), 112), 126), '-', ''), 't', ''), ':', '') 	0.0176243630800016
23134292	16639	getting id related to another id in table then using the id to get information from another table	select albumaccess.*, albumdetails.* from albumaccess, albumdetails where albumaccess.albumid=albumdetails.albumid and  albumaccess.userid=your_required_user_id 	0
23134571	20810	conditional results based on two interconnected columns	select process   from workstep  where workstep_name = 'manager'    and not ( performer = 'test' and end_time is null ) 	0.000923066845549637
23135130	38297	(mysql) get woocommerce order by meta_key and product_id	select t2.meta_value from wp_woocommerce_order_items as t1 join wp_woocommerce_order_itemmeta as t2 on t1.order_item_id = t2.order_item_id where t2.order_item_id in(select distinct oi.order_item_id from wp_posts, wp_postmeta, wp_term_relationships tr,wp_term_taxonomy tt,      wp_terms te, wp_woocommerce_order_itemmeta oi, wp_woocommerce_order_items ii  where tt.taxonomy like "shop_order_status" and te.term_id = tt.term_id and te.slug  not in ('failed','cancelled','refunded') and tr.term_taxonomy_id = tt.term_taxonomy_id and oi.order_item_id = ii.order_item_id and oi.meta_key = '_product_id' and oi.meta_value = 99 and ii.order_id = wp_posts.id and wp_postmeta.post_id = tr.object_id and wp_posts.post_status = 'publish') and t2.meta_key like "member_id" 	0.0650581170066111
23135456	36392	mysql select distinct does not show all records	select distinct `customers_id`, max(date_altered) from bp_booking group by `customers_id` 	0.00251976622022139
23136625	16321	show record value as a column	select y as date, sum(case when z='a' then x else 0 end) as a, sum(case when z='b' then x else 0 end) as b, sum(case when z='c' then x else 0 end) as c, sum(case when z='d' then x else 0 end) as d from table group by y 	0.000143692776303257
23136795	32785	sql query for all systemusers who's organisationunits has a datevalue < ... with pivot table in between	select         systemusers.displayname, systemusers.email,     organisationalunits.description, organisationalunits.coveredtill,     organisationalunits.id, organisationalunits.parentid, organisationalunits.typeid from             userorganisationunits inner join systemusers on systemusers.id = userorganisationunits.id                        and (systemusers.active = 1)  inner join organisationalunits on organisationalunits.id = systemusers.id                                and organisationalunits.active = 1                                and organisationalunits.coveredtill < '2017-03-31 00:00:00.000' where userorganisationunits.active = 1 	0.0119673147199841
23137208	5914	sub query for column name	select t1.col1,t1.col2,t2.id,t2.title from table1 t1     cross apply  (select top 1 id, title                    from table2                    where ref=t1.id                    order by date desc) as t2 	0.208318969242068
23137752	34893	return first character sql derby	select substr(table.column,1,1)  from table order by table.column 	0.0342358683491266
23138159	18721	join two tables, display values from two table besides joint row	select table1.a, table2.d from table1 join table2 on table1.b = table2.c 	0
23139050	24218	query 2 date ranges against the same column in one select statement without using a sub select?	select case when finvdate between '6/15/2013' and '1/15/2014' then finvdate else null end as firstdate, case when finvdate between '1/15/2014' and '04/15/2014' then finvdate else null end as seconddate, from salesdollars 	0
23139234	27629	sql inventory count wont return item name	select inventory.equipmentid, equipment.model, count(*) as count from inventory left join equipment on inventory.equipmentid=equipment.equipmentid where equipment.typeid = 14 and inventory.status not in (4,5,6,8) group by inventory.equipmentid, equipment.model; 	0.00782317291149545
23139303	7579	sql sub query to return a value for each row in query	select   case       when t1.range_start = t1.range_end          then t1.range_start        else t1.range_end      end as value,   column1,   column2,   column3 from dbo.t1 	0.000208928322109402
23140067	37217	count number of occurence for unique data in mysql	select city, state, count(*) as count from location group by city, state order by count desc 	9.94742978956283e-05
23140186	10027	build a varchar using the first four characters of a uniqueidentifier	select     left(x.id, 1) + '\' +     left(right(x.id, 3), 1) + '\' +     left(right(x.id, 2), 1) + '\' +     right(x.id, 1) from     (         select left(cast(idfield as varchar(38)), 4)  as id         from mytable     ) x 	0.00687464674341955
23141901	30405	get daily sales from a database	select   date(o.date_purchased)  as date_purchased,          round(sum(ot.value), 2) as sales_per_day,          count(*) as orders_today from     orders as o join     orders_total as ot on ot.orders_id = o.orders_id where    ot.class = 'ot_total' and      o.date_purchased >= last_day(now() - interval 1 month) + interval 1 day and      o.date_purchased <= last_day(now()) group by date(o.date_purchased) 	0
23143484	1473	query that returns quantity of repeated values	select count(*) - count(distinct info) from log; 	0.00446324155217175
23143903	10805	multiple nested select distinctstatments using inner join on the same table	select e.*     from [rigid industries$item ledger entry] e     where [posting date] = (select max(x.[posting date]) from                              from [rigid industries$item ledger entry] x                               where x.[item no_] = e.[item no_] and                  x.[posting date] <= convert(datetime, '2014-01-17 02:33:16.939')) and e.[quantity] > 0  order by e.[location code] desc, e.[item no_] asc, e.[posting date] desc; 	0.194450873129168
23145404	32118	calculate exact date difference in years using sql	select convert(date, getdate() - 912) as calcdate       ,datediff(day, getdate() - 912, getdate()) diffdays       ,datediff(day, getdate() - 912, getdate()) / 365.0 diffdayscalc       ,datediff(month, getdate() - 912, getdate()) diffmonths       ,datediff(month, getdate() - 912, getdate()) / 12.0 diffmonthscalc       ,datediff(year, getdate() - 912, getdate()) diffyears 	0.000274363742524912
23145421	9540	hiveql query for multiple joins	select a.column1, b.column2, c.column3, d.column4 from a join b on (a. playerid = b. playerid) join c on (c. playerid = b. playerid) join d on (d. playerid = c. playerid) 	0.785585995818931
23145610	25489	check 3 tables to see if an email exists in any of them	select id from pims where email = '{$email}' union all   select id from dms where email = '{$email}' union all   select id from users where email = '{$email}'; 	0.000372032486977559
23147612	8845	where or having for mysql month() queries	select count(images.image_url)             as num_images,         ( day(date(timestamp)) )            as tday,         month(date(transactions.timestamp)) as month,         transactions.sr_no  from   bni_pixcapp_client_details as transactions         inner join bni_pixcapp_image_urls as images                 on images.sr_no = transactions.sr_no  where  month(date(transactions.timestamp)) = 4         and year(date(transactions.timestamp)) = 2014         and (              transactions.payment_status = 'manually created'             or               payment_status = 'completed'             ) group  by day(date(timestamp)) 	0.155613978263469
23148560	30051	how do i extract only the shipping address and not the billing address using sql and join?	select firstname, lastname, line1, city, state, zipcode from customers join addresses on (customers.shippingaddressid = addresses.addressid); 	0.00489866687198098
23148582	2916	how to calculate student grade with sql	select r.student, (asst1+asst2+exam) as totalmark,      case when (asst1+asst2+exam) > 84.5     then 'a'     when (asst1+asst2+exam) < 84.5 and (asst1+asst2+exam) > 64.5     then 'b'     when (asst1+asst2+exam) < 64.5 and (asst1+asst2+exam) > 49.5     then 'c'     when (asst1+asst2+exam) < 49.5 and (asst1+asst2+exam) > 29.5     then 'd'     else 'e'     end as grade     from results r; 	0.0240722860247149
23151403	25063	need query for counting for 2 columns at a time	select city, sum(case when statusid = 'delivered' then 1 else 0 end) as [no. of delivered orders], sum(case when statusid = 'not_delivered' then 1 else 0 end) as [no. of pending] from orders 	0.00116292863708738
23151573	34425	mysql statement for group by with count over 1	select name,  count( * ) as anzahl  from product  group by name  having anzahl > 1 	0.492247668517007
23152030	36842	in sqlite many-to-many example, how to get bookmarks common to 2 tags?	select * from bookmarks where bm_id in (select bookmark_id from bookmarktag where tag_id = 2                 intersect                 select bookmark_id from bookmarktag where tag_id = 3) 	0.000579658439537061
23152271	4857	how to add missing values in a table based on other table	select distinct table_2.client, table_1.category into table_3 from table_1, table_2; 	0
23154246	4712	mysql - wrapping multiple rows into one	select distinct(tbl.id), name, pre_count.count, post_count.count, other_data from `tbl` left join (select id, count(*) as count                       from `tbl` where pre_post = 'pre' group by id) as pre_count                       on tbl.id = pre_count.id            left join (select id, count(*) as count                       from `tbl` where pre_post = 'post' group by id) as post_count                       on tbl.id = post_count.id 	0.00106736488865658
23154516	31019	groupby and get percentage for each	select     country,     count(id) * 100 / (select count(id) from `mytable`) as `something` from     `mytable` group by     `country`; 	0.000252791650181128
23155043	23368	sql request into 2 tables to get percentage of each rows	select r.roo_number boo_roomnumber, ((ifnull(cnt_book,0)*100)/(select count(*) from bookings)) percentage, ifnull(cnt_book,0) `count` from rooms r left join (select boo_roomnumber, count(*) cnt_book            from bookings            group by boo_roomnumber) cnt on r.roo_id=cnt.boo_roomnumber 	0
23155082	22967	how to select all records that do not have all 20 locations	select item_no, count(distinct loc) from some_table group by item_no having count(distinct loc)<20 	0
23155135	31125	using multiple conditions in one query in oracle	select id, performer, max(end_time) from workstep where workstep_name = 'review' and status ='w_completed' group by id,performer 	0.183013078572983
23155513	5293	join multiple tables and fetch the status based on first table id	select a.agent_id, a.agent_name, a.company_name, ifnull(cnt_all,0) total_drivers,ifnull(cnt_active,0) active_drivers, ifnull(cnt_idle,0) idle_drivers from agent a left join (select agent_id, count(*) cnt_all                    from driver                    group by agent_id) cnt on a.agent_id=cnt.agent_id left join (select agent_id, count(*) cnt_idle                    from driver                    where last_viewed=0                    group by agent_id) idle on a.agent_id=idle.agent_id left join (select agent_id, count(*) cnt_active                    from driver                    where last_viewed=1                    group by agent_id) active on a.agent_id=active.agent_id 	0
23156346	9596	fetch records based on timestamp and not day oracle	select * from table where  to_number(to_char( timestamp, 'hh24' )) < 5 	0
23156663	28017	query to return all records (including all associated data) where at least one associated data matches requirements	select     u.*     , r."name" as "roles.name"     , r."id" as "roles.id"     , ru."createdat" as "createdat"     , ru."updatedat" as "updatedat"     , ru."userid" as "userid"     , ru."roleid" as "roleid" from "users" u  join "rolesusers" ru on u."id" = ru."userid"  join "roles" r on r."id" = ru."roleid"  where exists (         select *         from "rolesusers" ru2         join  "roles" r2  on r2."id" = ru2."roleid"         where ru2."userid" = u."id"         and r2."name" in ( 'member' , 'admin' )         )         ; 	0
23158578	2125	cast string of day-month-year to date in mysql	select str_to_date('11-apr-14','%d-%m-%y') 	0.0441384223082427
23158745	9036	sql - best way to determine operation type in trigger?	select @action = case              when exists(select 1 from inserted)               and exists(select 1 from deleted) then 'u'             when exists(select 1 from inserted) then 'i'             else 'd' end; 	0.696244389885734
23160192	16996	join a mysql table with itself	select t1.id as id,     t1.text as english,     t2.text as translated from translation t1     left join translation t2 on t1.id = t2.id         and t2.locale = :locale where t1.locale = 'en_us' order by translated 	0.220862270101135
23160336	37101	mysql join - how to get all rows besides related? howto sum within a joined table?	select n.* from names n where not exists (select 1                   from link l join                        photos p                        on l.photo_id = p.id                   where l.name_id = n.id and                         p.filename = 'aa.jpg'                  ); 	0
23161151	4539	query to return single distinct row	select            max(s.netbios_name0),     max(l.timestamp),     max(l.description0),     max(l.deviceid0),     max(l.drivetype0),    max(l.name0),     max(l.systemname0),     max(l.volumename0),     l.volumeserialnumber0,     max(p.size0),     max(l.filesystem0) from                dbo.v_r_system s    inner join dbo.v_gs_logical_disk l    on s.resourceid = l.resourceid     inner join dbo.v_gs_partition p    on l.resourceid = p.resourceid group by    l.volumeserialnumber0 	0.0021667813714416
23161182	35279	how to insert into one table from multiple table while using union	select * into <whatever> from (<your query here>      ) t; 	8.42538021942248e-05
23162290	1336	display numbers of rows you want	select * from tbl1 order by len(id), id 	7.40808245716514e-05
23162461	10756	receive day id to use in where clause (sql server)	select * from table where datename(dw,datecolumn) = 'monday' select * from table where datepart(dw,datecolumn) = 1 	0.0429522526773107
23162469	22938	sqlite3: selecting n minimum values for all ids	select r.* from my_table r where r.date in (select date from my_table where id = r.id order by date limit 5); 	0
23162628	37446	optimise and merge sql queries into one - newbie alert	select m.username,     (         select sum(liter) as sumofliters         from diesel         where diesel.dato >= '$dx'         and diesel.idfield = d.idfield     ) as totalfuel from members m     join diesel d on d.userid = m.id where d.dato >= '$dx' 	0.665114130206695
23162842	20834	inner join on cte (common table expression) without pk	select     customerid,            firstname,             lastname,             dateofbirth,              email,              c1.status,         case          when c1.stage = 6 then 'first'         when c1.stage = 7 then 'second'         when c1.stage = 8 then 'third'         when c1.stage = 11 then 'fourth'         when c1.stage = 9 then 'fifth'         when c1.stage = 10 then 'sixth'         when c1.stage = 12 then 'unknown'         else ''    end as stage,            count(*) as totalcount from customer c inner join customer_1 c1 on c1.customerid = c.customerid group by   customerid, firstname, lastname, dateofbirth, email, c1.status, c1.stage having count(*) > 1 	0.54413994730643
23164636	14159	pick values from grouped rows in postgres	select z.code, z.prevcode from (      select id, code, year         , lag( code, 1 ) over ( partition by id order by year ) as prevcode      from tbl      where year in(2016,2015)      ) as z where z.year = 2016 	0
23165057	14401	how can i omit the number/0 in the result in sqlite?	select num1 / num2 from data where num2 <> 0 order by 1 	0.0576599317045801
23165277	35597	how only select max row in sqlite?	select * from table where (b,a) in     (select max(b),a      from table      group by a      )     and d=1; 	0.00140645866139052
23165331	41229	mysql name profit with date range	select name, sum(profit) from yourtable where  date >= '2014-04-19 00:00:00'  and  date <  '2014-04-19 23:59:59' group by name 	0.00482343953617543
23166754	17931	inner join limit left table results limit to 1	select     st.id,     st.roll_num,     st.first_name,     st.middle_name,     st.last_name,     st.course,     st.photo_url,     rs1.parano,     rs2.grade  from students st, results rs1, results rs2  where rs1.std_id=st.id and rs2.std_id=st.id  group by st.id having          count(rs1.parano) =          (select count(rs.parano)          from results rs          where rs.std_id=st.id          order by count(rs.parano)          limit 1) and     count(rs2.grade) = (         select count(rs.grade)          from results rs          where rs.std_id=st.id          order by count(rs.grade)          limit 1) 	0.77047129735848
23166989	30622	combine multiple rows to single row having same values	select problemid,        group_concat(eventtype separator ',') as eventtype from table group by problemid; 	0
23167069	32143	find last row start_date & previous row end_date from database table?	select end_date from your_table  where end_date > (select start_date from your_table order by id desc limit 1); 	0
23167230	38497	convert bigint to number of days	select from_unixtime(date_of_registration, '%y-%m-%d %h:%i:%s') as user_registeredon,          round((renewal_date - date_of_registration)/(60*60*24)) as expiry_date,         a.agent_id  from ta_agent a,       ta_subscription s  where s.agent_id = a.agent_id 	0.000230403427285882
23168263	5983	mysql combine two select statements using and	select e.eventstartdate,        e.eventenddate,        e.eventprice,        e.eventdescriptio,        e.eventtitle,        c.catdesc from te_events as e left join te_category as c on e.catid=c.catid order by e.eventtitle 	0.0538488750483437
23168460	3945	mysql counting same strings	select columnname1,count(columnname1)    from tablename     group by conlumnname1; 	0.00927159883674119
23174106	11245	query records with consecutive characters	select * from cities where substr(name,1,1) = substr(name,2,1) and substr(name,2,1) = substr(name,3,1); 	0.0103235872765867
23174416	3607	comparing two objects at different dates by database or algorithm	select t1.topper_position        , t0.app_store_id        , coalesce(t2.topper_position, 6) - coalesce(t1.topper_position, 6) as delta2        , coalesce(t1.fetch_date, t2.fetch_date) as cur_date     from (select distinct app_store_id             from crawler_2_application_details            where topper_position <= 5              and fetch_date in ('2014-04-19 19:56:24', '2014-04-18 19:56:24')          ) as t0     left join crawler_2_application_details as t1       on t1.fetch_date = '2014-04-19 19:56:24'       and t0.app_store_id = t1.app_store_id      left join crawler_2_application_details as t2       on t2.fetch_date = '2014-04-18 19:56:24'       and t0.app_store_id = t2.app_store_id     order by t1.topper_position is null           , t1.topper_position   ; 	0.000108776504592081
23177775	20121	sql subtract two independent counts	select t1.name,(count1 - 10* coalesce( count2,0) ) as netcount    from     (             select userid,users.name, count(*) as count1             from chat             inner join users             on chat.userid=users.id             where channel=$channel             group by userid,users.name             order by count desc             limit 100;      ) as t1   left join   (             select userid, count(*) as count2             from chat             where channel=$channel and text = '[some message]'             group by userid   ) as t2   on t1.userid=t2.userid 	0.00914799865038701
23178366	40927	sort mysql query by a single match, then normally	select * from posts order by field(author_id, '5') desc, timestamp 	0.00499041311839051
23178620	24656	show sum per time period and sum per entire time span	select  email,sum(amount),'2' as ord from (       select email,sum(amount) as amount ,month(d1) from t1 group by       month(d1),email) as t group by email       union all        select email,sum(amount) as amount,      '1' as ord from t1 group by month(d1),email      order by ord 	0
23181706	18359	mysql select username only if username doesn't exist in other table	select username  from players  where not exists   (      select username     from punishement_banned     where players.username = punishement_banned.username  ) 	0.00217600290672843
23183319	7411	select from two tables	select id, name from fruit union select id, name from color 	0.00220297715881018
23184026	4551	sort only numbers from alphanumeric string in mysql	select * from table1 order by right(numbers,3) 	0.000216014316094924
23184259	37428	sort middle and then last three numbers in alphanumeric string	select * from table1 order by substring(pattern,4,2) desc, right(pattern,3) 	0
23188385	9924	displaying most popular/viewed articles - divided by time	select   * from     articles where    publishtime > current_time - interval 7 day order by viewcount / (unix_timestamp() - unix_timestamp(publishtime)) desc limit    4 	0.000556114334559055
23188659	13028	mysql find max value	select id from table where pricea = least(pricea, priceb, pricec); 	0.00430044854004314
23191011	12599	mysql return true if idx exists in another table	select u.user_idx, u.name, g.user_idx is not null as has_joined_group from user as u left join group as g on g.user_idx = u.user_idx and g.group_idx = 3 	0.00405576724565686
23191147	4350	mysql query to get data from 3 different tables for one userid	select * from users    join file on file.user_id = users.id    join friends on friends.user_id = file.user_id where users.id = $other; 	0
23192086	12522	how to subtract between any 2 dates in a table?	select customer_id,        min(date) as mindate,        max(date) as maxdate from bill group by customer_id  having datediff(max(date),min(date))>=30 	4.9797202225587e-05
23192153	8076	mysql group by max score	select s.*  from scores s join ( select max(score) score, id_game  from scores group by id_game ) ss using(score ,id_game ) limit 0 , 30 	0.0600038992368788
23194244	6460	mysql count with join from two tables for one user-id	select id,        name,        (select count(*) from folow where following = users.id) followers,        (select count(*) from folow where follower  = users.id) following from   users where  id = ? 	0.00107031082590252
23194808	20129	mysql: joins, the used select statements have a different number of columns	select questions.*,  tags.tagdata, users.username from questions left join tags on  tags.questid = questions.id  left join users on users.id = questions.ownerid 	0.000246142698227342
23194899	11360	how to use count on two tables with where clause	select count(*) total       from   tblticket_engineer       inner join  tblticketdetail on tblticketdetail.ticketid = tblticket_engineer.ticketid and tblticketdetail.status = 1       where tblticket_engineer.engineerid = 1 	0.174843158184538
23196108	25969	save logged on user(name only) in oracle when os based authentication is used	select  sys_context('userenv','os_user')  from dual 	0.112718238250713
23196656	25548	mysql show records of current user + users that he is a parent of	select * from orders where user_id = $_session['loggeduser'] or  user_id in (select user_id              from users             where parent_user_id= $_session['loggeduser']) 	0
23198083	19667	connecting two queries in one table in sql	select date_format(payments.paymentdate, '%m') as month, sum(payments.amount) as amount_total, sum(if(customers.country='usa', payments.amount, 0)) as amount_usa from payments  inner join customers on customers.customernumber = payments.customernumber group by date_format(payments.paymentdate, '%m') 	0.00553738651431481
23198361	22825	merging two mysql tables with sorted datetime	select "buy" as action, qtybuy as item, datebuy as actiondate  from tbuy union all select "sell" as action, qtysell as item, datesell as actiondate from tsell order by actiondate 	0.000283403797361957
23198401	28346	db2 select statement using count and group by	select customerid, customergroup, productid, productname, alertname, alertcount,        alertlevel, more data.... from (select t.*,              count(*) over (partition by alertname) as alertcount,              row_number() over (partition by alertname order by customerid) as seqnum       from table t       where customerid = xxx and customergroup = yyy      ) t where seqnum = 1 order by alertlevel, alertname, productname; 	0.493536866432894
23200285	29593	oracle sql query to get exact last 30/31/28 days from sysdate	select add_months(trunc(sysdate), -1) from dual; 	0
23200503	6698	using decode to input 'not a valid month' value as it is	select   number_column,          case   when number_column between 10000 and 129999                       and mod(number_column,10000) between 1900 and 2100                  then 'good format'                  else 'bad format'          end result from     (select 52002 number_column from dual union all      select 41995 number_column from dual union all      select 122016 number_column from dual union all      select 0 number_column from dual union all      select 10000 number_column from dual union all      select 131994 number_column from dual union all      select 421996 number_column from dual union all      select 731989 number_column from dual )  ╔════════╦═════════════╗  ║  52002 ║ good format ║  ║  41995 ║ good format ║  ║ 122016 ║ good format ║  ║      0 ║ bad format  ║  ║  10000 ║ bad format  ║  ║ 131994 ║ bad format  ║  ║ 421996 ║ bad format  ║  ║ 731989 ║ bad format  ║  ╚════════╩═════════════╝ 	0.293528166912082
23201512	21241	row_number and multiple join	select *    from (<you existing query without the where>)  where linenumb <= 5 	0.736357288375037
23202482	29440	how can i optimally filter a view from a stored procedure that accepts lots of nullable parameters?	select   <columns> from   myview where   (@param1 is null or cola = @param1)   and (@param2 is null or colb = @param2) ... 	0.251430920412612
23202614	24722	sql - query multiple rooms with different adults/children per hotel	select      count(pl.day) as days,     p.property_id as hotel_id,      p.name as hotel_name,      r.room_name as room_name,      r.room_type_id as room_id,     r.max_adults as max_adults,     r.max_children as max_children from property p inner join room_type r on p.property_id=r.property_id inner join plan pl  on pl.room_type_id=r.room_type_id and (pl.day >= '2014-07-07' and pl.day <= '2014-07-11') where exists     (select 1     from room_type r1     where p.property_id=r1.property_id     and r1.max_adults = 2 and r1.max_children = 0) and exists     (select 1     from room_type r2      where p2.property_id=r2.property_id     and r2.max_adults = 4 and r2.max_children = 2) and exists     (select 1     from room_type r3      where p.property_id=r3.property_id     and r3.max_adults = 2 and r3.max_children = 1) group by      p.property_id,      p.name,      r.room_name,      r.room_type_id,     r.max_adults,     r.max_children having      count(pl.day) = 4; 	0.00140018355941083
23203157	34533	mysql join to show all records with or without matching records	select empid, empname,    coalesce(round(avg(ratingvalue ), 2),0) as avgrating,    coalesce(count(empid),0) as ratingcount  from emp  left join ratings    on emp.empid = ratings.empid  group by empid, empname order by `avgrating`desc 	0
23204284	19230	how do i "collapse" the following column data with tsql in access 2010?	select [year]       ,placeid       ,count(case offersmembership when 'y' then 1 else 0 end) as offersmembership       ,count(case hasseating when 'y' then 1 else 0 end) as hasseating       ,count(case quietarea when 'y' then 1 else 0 end) as quietarea   from mytable t  group by t.[year]          ,placeid 	0.653491522401299
23205281	242	mysql: count of records with consecutive months	select person, count(*) as nummonths from (select person, ym, @ym, @person,              if(@person = person and @ym = ym - 1, @grp, @grp := @grp + 1) as grp,              @person := person,              @ym := ym       from (select distinct person, year(purdate)*12+month(purdate) as ym             from records r            ) r cross join            (select @person := '', @ym := 0, @grp := 0) const       order by 1, 2      ) pym group by person, grp; 	0.000107089411085776
23205387	28871	obtain records with multiple instances of field values	select     patientid,    min(proceduredate)  from     clinicaldata cd1 where    [procedure] in ('stitches', 'cast', 'hemoglobin-a1c-check')          and diagnosis in ('laceration', 'lung-cancer','diabetes') group by    patientid, diagnosis, [procedure] having count(*) > 1 	0
23205908	17551	postgresql using count to form statistical results	select  m.id,  m.title,  count(distinct c.id) as cds,  count(distinct v.id) as vinyl,  gig.id as gid, gig.date as gdate, sum(case cd.type            when 'silver' then 1            else 0            end) silver, sum(case cd.type            when 'cdr' then 1            else 0            end) cdr, sum(case cd.type            when 'pro-cdr' then 1            else 0            end) pro_cdr from media m left join cd c on m.id = c.media left join vinyl v on m.id = v.media  left join media_gigs g on m.id = g.media  left join gig gig on g.gig = gig.id group by m.id, gig.id; 	0.285464536848193
23205993	39677	how can i use getdate() to get month and year from the past month?	select datepart(month, dateadd(month, -1, getdate()), datepart(year, dateadd(month, -1, getdate()) 	0
23206853	39271	running total based on data column	select r.*,        (select sum(r2.dailyamount)         from @result r2         where r2.datevalue <= r.datevalue        ) as cumsum from @result r; 	6.25927819973431e-05
23208340	31058	querying a table where the field contains any order of given text strings	select * from mytable where match (category) against ('+term1 +term2 +term3' in boolean mode); 	0.000102693217234921
23209258	16294	how do i get the averages of duplicate values in a postgresql column?	select division,avg(rate) from your_table group by  division; 	0
23209514	1745	sql selecting records where one date range doesn't intersect another	select v.campsiteid, v.checkindate, v.checkoutdate from visitors v where v.checkindate <= #checkoutdate# and       v.checkoutdate >= #checkindate# ; 	0
23210770	9929	need to fetch records from one table which is not present in another one table	select table1.*  from table1  left outer join table2      on table1.c1 = table2.c1      and table1.c2 = table2.c2  where table2.c1 is null     and table2.c2 is null 	0
23211405	17085	is there a way to select a certain number of row for a certain column?	select * from   table1 t where          (             select  count(*)              from    table1  t1             where t1.user_id = t.user_id and                    t1.score >= t.score         ) <= 2 order by t.user_id asc,t.score desc 	0
23212216	15227	how could i filter duplicates?	select  `username`,`userid` from `giveaway` group by `username` having count(`username`) > 1 union select `username`,`userid` from `giveaway` group by `userid` having count(`userid`) > 1 	0.381760682184362
23213091	13579	limit and offset on joined table	select  c.* ,f.amount, f.item from item_table f    left join (    select * from category c     order by c.id desc    limit '.$offset.', 3    )  as c on f.cat_id = c.id  order by c.id desc 	0.0234330276340538
23214432	2997	merging row_number column with other column	select  '[' + cast(row_number() over (order by name) as varchar(100))  + ']' + name from people 	0.00422854014114352
23214515	32546	order by date time with am pm	select * from table order by date_format(str_to_date(`date_time`,'%y-%m-%d %h:%i %p'),'%y-%m-%d %h:%i:%s'); 	0.774128368124448
23214610	29063	mysql: print counted values	select      izvajalecid from      servis  group by     izvajalecid union select      count(distinct izvajalecid) from      servis 	0.00621652719586576
23215231	12863	counting votes in a mysql table only once or twice	select vote, count(vote) from  ( select max(user), vote from table1  group by user ) d group by vote 	0.000298490387588583
23216709	12135	calculating average from 2 database table colums	select avg( greatest( coalesce(first_score,last_score) , coalesce(last_score,first_score) ) ) from mytable; 	0
23217528	36796	trying to query an array	select   utilizadores.nome,   funcoes.funcao from   utilizadores   join funcoes on (utilizadores.id_funcao = funcoes.id_funcao) where   utilizadores.nome like "%<query>%" 	0.35962437809849
23219547	39433	how to sort by three-characters weekday in mysql	select * from `table` order by field(`day`, 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'); 	0.0421472990798267
23222212	25358	sql: how can i select the first and last date for each customer?	select   custid,   min(transaction_date)  as firstt,   max(transaction_date)  as lastt from   yourtable where       transaction_date >= '2014-04-01'   and transaction_date <  '2014-04-02' group by   custid 	0
23223117	11356	how to sum columns group by different date in sql server	select   datepart(wk,transaction_date) week,  datepart(yy,transaction_date) year,   min(transaction_date),  sum(numb1) as [ registration],   sum(numb2) as [renewal],   sum(penalty) as penalty,   sum(mtr),   sum(numb3) as ph,  sum(insurance) as insurance,   sum(nub4) as [data received],   sum(numb1)+ sum(numb2)+ sum(penalty)+ sum(mtr),   sum(numb3) + sum(insurance)+ sum(nub4)  as [total sum] from dbo.vehicle_transactions group by datepart(wk,transaction_date), datepart(yy,transaction_date) 	0.000908777224564637
23223990	32264	postgres: how to get number of docs fetched per hour?	select date_trunc('hour', to_timestamp(starttime)) as hour, count(*) as total from repohistory where     (activitytype like '%ingest%' or activitytype like '%fetch%')     and  resultcode = 'ok' group by 1 order by 1 	0
23224993	5159	reverse comma separated column values in sql server	select split.t.value('.', 'varchar(50)') as column1    from  (select  cast ('<m>' +   replace(column1, ',', '</m><m>') + '</m>' as xml) as string    from  @tbl) as t cross apply string.nodes ('/m') as split(t); 	0.000676558549425335
23226799	10500	tsql least number of appearences	select [balie].[balienummer],  count([incheckenbijmaatschappij].[maatschappijcode]) from [balie] join [incheckenbijmaatschappij] on [balie].[balienummer] = [incheckenbijmaatschappij].[balienummer] group by [balie].[balienummer] order by count([incheckenbijmaatschappij].[maatschappijcode]) 	0.00741971199889034
23227475	40152	a function calculating average age in years in sql [postgresql]	select avg(age(dateofbirth))     from person 	0.00132771899894561
23230041	16247	how to protect sql statement from divide by zero error	select  case when count(broken_cones) = 0 then 0 else cast(nullif((.01 * 2500)/count(broken_cones), 0) as decimal(7,4)) end from [ice].[ice_cream_inventory] where broken_cones = 'yes' 	0.724796654812985
23230407	23279	mysql retrieving range between 2 max values	select * from posts order by front_weight desc limit 40 	0
23231916	35042	maximum average rating per week	select imagesrc,avg (rating / total_votes) as maximumrate  from imagerate where time >= curdate() - interval dayofweek(curdate())+6 day and time < curdate() - interval dayofweek(curdate())-1 day group by imagesn order by avg( rating/total_votes ) desc  limit 1; 	0
23232714	37780	mysql: union all and sort by relevance?	select id, title, keywords, post, img,         null as device_id, null as mfgr, null as model, null as img,        match(title, desc_meta, keywords_meta, post) against('boost') as relevance from blog_posts where match(title, desc_meta, keywords_meta, post) against('boost') > 0 union all select null, null, null, null, id as device_id, mfgr, model, img, summary,        match(mfgr, model, summary) against('boost') as relevance from device_specs where match(mfgr, model, summary) against('boost') > 0 order by relevance; 	0.0596115017446629
23233410	11405	sql azure time consuming query	select * from sys.event_log  where database_name ='<dbname>' and event_type <> 'connection_successful' order by start_time desc 	0.565603682375041
23234072	39634	trying to find the most expensive book written by a certain author in oracle sql	select b.title, b.retail from books b join bookauthor ba using (bookid, authorid) join author a using (authorid) join (select max(retail) highestprice from books bb join bookauthor ba using (bookid, authorid) join author aa using (authorid) where aa.lname = 'white' and aa.fname = 'lisa' group by bb.bookid) temp on retail = highestprice where a.lname = 'white' and a.fname = 'lisa' 	6.76204113721505e-05
23235448	16532	select different fields as one field (no concat)	select val1 as res  from vals union select val2 as res   from vals where val2 is notnull; 	0.000302708920665879
23236035	4161	mapping surrogate keys in ssis	select advid as advbk,campid campbk,campname from staging.camp 	0.651978134361166
23236303	3753	several query mysqli	select    count(*) as count,   browser from   log group by   browser order by   count desc limit 3 	0.460926456037137
23237738	28956	wordpress db query to count number of users registered per day	select  count(*) as total_users , date(user_registered) as reg_date  from wp_users  group by reg_date  having total_users > 0 	0
23239598	29030	parent select sql query generating child select	select fld1,fld2,fld3 from ( select cast(date as varchar(10)) as fld1  ,cast(personid as varchar(10)) as fld2, cast(billno as varchar(10)) as fld3,1 as fld4, billno as fld5 from table_bill_summary where  personid =@x union select cast(im.itemname as varchar(10)) as fld1  ,cast(bi.quantity as varchar(10)) as fld2,cast(im.itemrate as varchar(10)) as fld3 ,2 as fld4, bs.billno as fld5 from table_bill_summary bs inner join table_bill_items as bi  on bs.billno=bi.billno inner join item_mastertable as im  on bi.itemid=im.itemid where  bs.personid =@x ) as x order by fld5,fld4 	0.0366306437097006
23240548	12064	obtaining the percentage in sqllite	select   mood, sum (counter) total     from   (  select   0 mood, 0 counter from dual             union all               select   1 mood, 0 counter from dual             union all               select   2 mood, 0 counter from dual             union all               select   mood,   count ( * )                              * 100.0                              / (select   count ( * )                                   from   entry                                  where   data > date ('now') - 30)                 from   (select   *                           from   entry                          where   data > date ('now') - 30)             group by   mood, data) group by   mood order by   mood asc; 	0.0245096744878083
23241502	2319	combine two separate sql queries into one	select distinct account, lastlogin, licences_bills  from licences  where lastlogin > convert(varchar,dateadd(d,-(day(dateadd(m,-1,getdate()-2))),dateadd(m,-1,getdate()-1)),106) and lastlogin < convert(varchar,dateadd(d,-(day(getdate())),getdate()),106) and access = 1  and licences_bills in (   select bc.id   from customers as c   right join bills as bc on c.id = bc.bills_customer   right join months as m on bc.month_bills = m.id   where c.argument = 'kp'   and year(bm.datum) = year(current_timestamp) and month(bm.datum) = month(current_timestamp) ) order by licences_bills asc 	0.000231552778934352
23241989	21667	can i choose different table for inner join operation?	select id,profile,type ,        case profile           when 'soft' then 'sid'           when 'hard' then 'hid'         end as [profile]         from productdetail p1 inner join tablea a   on profile='soft'     and <any other condition> union  select id,profile,type ,        case profile           when 'soft' then 'sid'           when 'hard' then 'hid'         end as [profile]         from productdetail p1 inner join tableb b   on profile='hard'     and <any other condition> 	0.287249388278336
23242913	29977	sum table column from previous select results	select l.locnumber, i.code,sum(units)      from locations l      inner join itemdetails i        on l.locnumber = i.locnumber      inner join plant p       on p.code=i.code     where l.locnumber= '4577'     group by  l.locnumber, i.code 	0.000124063506571742
23245025	22130	how to sort a mysql table with null column values	select id from sometable order by points desc, img_link desc; 	0.00151313105126851
23248191	21975	select rows with same value on other field	select    n.* from    participant n join (   select        t.conversation_id   from       participant t   where            t.user_id = 'user1'        and            t.conversation_id = (select conversation_id from participant where user_id = 'user2' and conversation_id = t.conversation_id) ) m on m.conversation_id = n.conversation_id 	0
23248752	24225	sql statement for value from multiple field	select ..... from .... where (status = @status or @status is null) and (created=@created or @created is null) and (release = @release or @release is null) and (date = @date or @date is null) 	0.00568313373601215
23250008	29963	convert datetime to string/varchar in sql server	select convert(varchar(8), dateadd(yy,-2,getdate()), 112)  if convert(varchar(8), dateadd(yy,-2,getdate()), 112)  = '20120423'  begin     print 'values are the same' end else begin    print 'values are not the same' end 	0.363307773509926
23250837	33464	how to join two string collumns into one in mysql	select concat(name,' ',surname) as fullname from author 	0.00195522606666305
23253269	38555	how to combine two different sql queries into one with primary key in the where clause	select     '9' as fieldindex,     infields.name as infieldname,     outfields.name as outfieldname from     fields as infields,     fields as outfields where     infields.field_id = 1000000005 and outfields.field_id = 1000000004 union select     '10' as fieldindex,     infields.name as infieldname,     outfields.name as outfieldname from     fields as infields,     fields as outfields where     infields.field_id = 1000000007 and outfields.field_id = 1000000006 	0
23253307	32902	how to add quantites from different fields	select sum(case when raw1 = 'a' then qty1 else 0 end +      case when raw2 = 'a' then qty2 else 0 end +     case when raw3 = 'a' then qty3 else 0 end +     case when raw4 = 'a' then qty4 else 0 end) as sumqty from jtjobfil 	0.000505573876280358
23253351	21993	group by only for one column	select       max(ges_gestor_id),      max(spo_sponsor_id),      max(crt_numinterno_id),      max(crt_version_id),       max(car_fecemision),      max(car_fecvncmto),      max(car_pribruta_t),      max(car_signo),      max(car_numcuota_id),      case sum(car_pribruta_t * car_signo)            when 0 then 'cobrado'            else 'pendiente'       end as car_deuda   from cartera  where crt_numinterno_id = 287623  group by crt_numinterno_id 	0.00196027039393023
23255403	10259	sql query -- student weighted grade calculation	select results.stu_fname, results.stu_lname, sum(results.calculatedgrade) from(        select s.stu_fname, s.stu_lname, gt.grade_type_name,              (round((sum(sg.grade_earned)/sum(g.grade_possible)), 2) * round((gt.grade_weight/100.0)     , 2) ) as calculatedgrade      from student s     inner join studentgrade sg on sg.stu_id = s.stu_id     inner join grade g on sg.grade_id = g.grade_id      inner join gradetype gt where g.grade_type = gt.grade_type     group by s.stu_fname, s.stu_lname, gt.grade_type_name )results group by results.stu_fname, results.stu_lname; 	0.449092897971567
23256884	7719	mysql - join table if x is not null	select *  from stories s left join menu m     on s.mainmenu = m.id      and m.menu_active = 1 left join sub me... 	0.207108096101655
23257471	12840	mysql return results where there exist at least one from the other table	select  s.id, c.code  from    course c         inner join student s             on c.student = s.id where   exists         (             select  1             from    course c1             where   c.student = c1.student                     and c1.course = 'c'         ) 	0
23261942	1099	sql server select statement for 3 tables using join	select top 3 package_title, durationindays,package_image_1, adult_price ,      stuff((select themes.theme + ',' from package_theme          inner join themes on themeid = package_theme.theme         where package_theme.package = packages.package_id for xml path('')),1,1,'')     as theme from packages  inner join  rates on rates.package = packages.package_id 	0.638243943911853
23264019	8338	conditional ordering by two fields	select * from pendientescobro order by   case when npendiente>0 then 1 else npendiente end asc,   dfecha 	0.143433100913771
23265245	8852	sql count all of the column that has a value greater than 10 and sum it up	select t.d      , sum(t.valcount) cnt   from (          select [date] as d               ,   case when t1.value1 >= 10 then 1 else 0 end                 + case when t1.value2 >= 10 then 1 else 0 end                 + case when t1.value3 >= 10 then 1 else 0 end                        as valcount            from table t1        ) t group by t.d      ; 	0
23267127	4038	how can i use the sum of sums in a having clause in sql	select * from (     select  left(rstab1.eventstartdate,6) monthtab1        ,left(rstab2.eventstartdate,6) monthtab2        ,rstab1.tigomainnumber        ,(sum(rstab2.revenuerwf)+sum(rstab1.revenue)) as total_revenuesum        ,count(*) as countrevenue     from dwhaux1.[subscriberbase].[dbo].[cdrsubscriber_revenue]as rstab1 with(nolock)      inner join dwhaux1.cdrnormal.dbo.nrmmsc rstab2 with(nolock)      on  rstab1.tigomainnumber= rstab2.calledpartynumber     where left(rstab1.eventstartdate,6) between 201310 and 201403      or left(rstab2.eventstartdate,6) between 201310 and 201403      group by left(rstab1.eventstartdate,6)             ,left(rstab2.eventstartdate,6)             ,rstab1.tigomainnumber ) as z where total_revenuesum >680 order by countrevenue desc 	0.242155051628367
23267396	4976	mysql select row with not like	select    case      when max( case when table2.status = 'expired' then 1 else 0 end ) = 1 then 'expired'     when max( case when table2.status = 'cancelled' then 1 else 0 end ) = 1 then 'cancelled'     when max( case when table2.status = 'new' then 1 else 0 end ) = 1 then 'new'     else 'not active'   end as status   table1.title  from table1  inner join table2 on table1.id = table2.id  group by table1.title having max( case when table2.status = 'active' then 1 else 0 end ) = 0; 	0.416051096992128
23270140	1576	correct sql query for accessing groups available to user	select cg.* from chat_group as cg join chat_group_has_oi_relationship as cgr on cg.id = cgr.chat_group_id join user_has_oi_relationship as ur on ur.oi_relationship_id = cgr.oi_relationship_id join user as u on ur.user_id = u.id where u.name = 'john smith' 	0.0109658287493805
23270581	1100	sql limit & order by across joins	select tu.screen_name as handle     ,min(tw.created_at) as earliest from twitter_users tu left join tweets tw     on tu.user_id = tw.user_id left join twitter_social ts     on ts.user_id = tu.user_id left join social_categories cs     on ts.social_id = cs.social_id where cs.category_id=3 group by tu.screen_name order by earliest asc 	0.634774845607679
23272260	19052	select and count with null values	select   coalesce(opened.ano, closed.ano) as ano,   coalesce(opened.mes, closed.mes) as mes,   coalesce(opened.cnt, 0) as opened_cases,   coalesce(closed.cnt, 0) as closed_cases from (   select      year(open_time) as ano,      month(open_time) as mes,     count(*) as cnt   from table1   where groupdesc = 'support'   group by year(open_time), month(open_time) ) opened full outer join (   select      year(close_time) as ano,      month(close_time) as mes,     count(*) as cnt   from table1   where groupdesc = 'support'   group by year(close_time), month(close_time) ) closed   on opened.ano = closed.ano and opened.mes = closed.mes where closed.mes is not null order by coalesce(opened.ano, closed.ano) desc, coalesce(opened.mes, closed.mes)    desc; 	0.0383543150456946
23272282	9228	mysql: query with condition on one-to-many table	select * from clients_actions  where from_unixtime(date_done) < date_sub(now(),interval 7 day)  and client_id not in (   select client_id from    clients_actions   where from_unixtime(date_done) > now() ) ; 	0.295303232361842
23272577	3688	hive date manipulation in a query	select col1, col2, mydate, date_add(mydate,daysdiff) as adjusteddate  from datesource join   (     select datediff(from_unixtime(unix_timestamp(),"yyyy-mm-dd"),maxdate) as daysdiff        from         (          select max(mydate) as maxdate from datesource        ) maxdate   ) diffdate; 	0.526724525774823
23272724	13388	filtering duplicate rows from mysql table	select store_id,col_a,col_b,col_c,stores.store_name,store_number,street_address,apt_suite,city,state_id,zip_code,latitude,longitude,phone_number,phone_extension,fax_number,email_addr,location_direction,open_24_hr,website_url, sub1.distance as distance  from stores  inner join (     select store_name, min(3959*acos(cos(radians(12.1234567)) * cos(radians(latitude)) * cos(radians(longitude)-radians(-45.678910.)) + sin(radians(12.1234567)) * sin(radians(latitude)))) as distance      from stores      where primary_provider_code = '01' or secondary_provider_code = '01' or tertiary_provider_code = '01'      group by store_name  ) sub1 on stores.store_name = sub1.store_name and (3959*acos(cos(radians(12.1234567)) * cos(radians(latitude)) * cos(radians(longitude)-radians(-45.678910.)) + sin(radians(12.1234567)) * sin(radians(latitude)))) = sub1.distance where primary_provider_code = '01' or secondary_provider_code = '01' or tertiary_provider_code = '01'  order by distance limit 0 , 10 	0.000272207638039093
23276119	1944	how to inner join table?	select name, check_in,        ii.illness_name as illness_name_in,        io.illness_name as illness_name_out,        check_out_id from check_in as ci inner join patient_detail as p on ci.check_in_id = p.check_in_id  inner join illness as ii on ii.illnessid = ci.illness_id inner join check_out as co on co.check_out_id = p.check_out_id inner join illness as io on io.illnessid = co.illness_id 	0.414189883168069
23277827	17826	mysql grouping from a database	select occurance, date(time), hour(time), count(*)  from table  where time between '01-01-2014 01:00:00' and '01-01-2014 03:00:00'  group by occurance, date(time), hour(time) 	0.0199511950832731
23279537	39727	payment amount tracking sql	select a.customername, b.payment,        (a.amount - sum(b.payment) over (partition by a.id order by date)) as remainingbalance from tablea a left outer join      tableb b      on a.id = b.id; 	0.11076850774842
23279881	31093	pl sql retrieve maximum version number	select msg_id, max("version number") from yourtable group  by msg_id 	0.000396013292476926
23280031	33291	how can i get a newly inserted auto increment value?	select last_insert_id(); 	0
23281411	19625	how to count each month without repeating the lines?	select case when monthset @year := 2014; select sum(case when month(created_at) = 1 then 1 else 0 end) as jan,  sum(case when month(created_at) = 2 then 1 else 0 end) as feb,  sum(case when month(created_at) = 3 then 1 else 0 end) as mar,  sum(case when month(created_at) = 4 then 1 else 0 end) as apr,  sum(case when month(created_at) = 5 then 1 else 0 end) as may,  sum(case when month(created_at) = 6 then 1 else 0 end) as jun,  sum(case when month(created_at) = 7 then 1 else 0 end) as jul,  sum(case when month(created_at) = 8 then 1 else 0 end) as aug,  sum(case when month(created_at) = 9 then 1 else 0 end) as sep,  sum(case when month(created_at) = 10 then 1 else 0 end) as oct,  sum(case when month(created_at) = 11 then 1 else 0 end) as nov,  sum(case when month(created_at) = 12 then 1 else 0 end) as `dec` from `quotes`  where year(created_at) = @year 	0
23281450	8899	fetch data from two different tables in one query	select id, name, first name, place from tbl_friend   where place= 1 union all select id, name, first name, place from tbl_colleague   where place= 1 	0
23283009	15995	how to avoid count with empty records in sql	select count(nullif(dt_userttrainingdate2,'')) as a  from ref_courseregistration_users 	0.0618332556014831
23283132	29928	select min and max values before a particular row per customerid sql	select visitor, min(date) as mindate, max(date) as maxdate from (select t.*, row_number() over (partition by visitor order by rank) as v_rank       from table t       where event = 'visit'      ) t group by visitor, (rank - v_rank); 	0
23283459	36817	mysql join returning only 1 row out of several rows	select questions.id,        questions.question,        questions.author,        questions.date,        answers.answer,        answers.user,        answers.datetime from questions left join answers on questions.id = answers.question where tag in (:arrayids) 	0.000108393808075109
23284700	40933	how can i bind separate query to separate column in gridview asp.net c#	select en1.text as 'country', en2.text as 'city',en3.text as 'region'  from enumvalue en1, enumvalue en2, enumvalue en3 where en1.id = en2.[fkenumeration] and en3.[fkenumeration] = en2.id  and  en1.id='yourid' ; 	0.226613759972047
23284845	37734	mysql: counting how many times each unique element appeared in `select` query	select iwebs, count(iwebs) from wordstable where iwebs in ('a1','a2','a3','a4') group by iwebs 	0
23285106	22570	querying multiple values from multiple columns in mysql	select * from table where src = 'a' and dst = 'b'    or src = 'e' and dst = 'f' 	0.000325916276595503
23285893	5126	how do i get the count for a sql query containing a group by statement?	select count(*) from    (select p.*    from parent p join join_table j on p.id=j.parent_id    where j.child_id=1 or j.child_id=2    group by j.parent_id    having count(j.child_id)=2) as res; 	0.0252929345226714
23288210	19131	extracting a string value from a pipe-separated string in a table column	select substr(surname,1                  ,instr(surname,'"',1,1)-1) from (select substr(column                  ,instr(column,'list',-1)+5                  ) as surname      from table) 	0
23288386	25338	getting formated and sorted data from sql	select `date`,        sum(`ios`) as `ios`,        sum(`android`) as `android` from   (select date(`date`) as `date`,           case               when `platform`='ios' then 1               else 0           end as `ios`,           case               when `platform`='android' then 1               else 0           end as `android`    from demo) t group by `date` 	0.00156122603314148
23289129	16675	select * from table, table depending on another query - sql	select coalesce(p.name, f.name) as name from contacts c left join people p on p.contacts_id = c.id and c.type = 'person' left join firms f on f.contacts_id = c.id and c.type = 'firm' where c.id = 42; 	0
23290299	3924	select using group by and display the total with two tables	select d.d#,    count(p.p#) from department d left join project p on project.d#=department.d group by d.d#; 	0
23290440	11912	how to join query on three tables with multiple colums im my sql?	select ch.mandieng, cw.price from commoditywise cw inner join mandihindi ch on ch.mandihini = cw.mandi where  cw.commodity = 'paddy' 	0.44572391999752
23291047	14271	how to combine rows based on field value	select  v.visitid, case     when sum(case when vd.doctype = 1 then 1 else 0 end)>0 then 'y' else 'n' end as 'finalreportattached' ,case     when sum(case when vd.doctype = 13 then 1 else 0 end)>0 then 'y' else 'n' end as 'inspectorreportattached' ,case     when sum(case when vd.doctype = 2 then 1 else 0 end)>0 then 'y' else 'n' end as 'co-ordreportattached' from visits v inner join visitdocs vd on vd.visitid = v.visitid   where v.visitid  = 79118 group by v.visitid 	0
23291341	37029	column name doesn't belong to table when getting results in datarow using c#	select count(nullif(dt_userttrainingdate1,'')) as theorycoursedate1,   count(nullif(dt_userttrainingdate2,'')) as theorycoursedate2  from ref_courseregistration_users 	0.0218363052597237
23291602	24540	database structure changing lookup values	select *  from lookup where lookup.period_start <sysdate and lookup.period_end >sysdate 	0.0294204290320281
23293095	33412	mysql query to get records in result set	select * from t1 where id in (1,2); 	0.00241009165352132
23293310	1678	how to find if two rows are similar to each other?	select state, count(state) from ( select varcol1, varcol2, case when varcol1 like concat('%',varcol2,'%') then 'similar' else 'not similar' end as state from test.test) a group by state; 	0
23293570	30312	select values from 2 tables based on 1 variable.	select *  from cars inner join enquiries  on cars.carid=enquiries.carid where cars.dealerid     = '".$_session['dealerid']."'"; 	0
23294146	6499	how to replace different occurances in sql?	select person_name, mobile_nr, smss = 'yes' from person a inner join user_mobile b on a.id_person=b.id_user inner join mobile_number c on b.id_mobile=c.id inner join message_id d on c.id=d.id_mobile where a.person_name not in  (select person_name from person a inner join user_mobile b on a.id_person=b.id_user inner join mobile_number c on b.id_mobile=c.id inner join call_id d on c.id=d.id_mobile) 	0.0395766939253166
23295630	31826	sql two multi-row counts in one query	select coalesce(q2.name, q1.name) as name, q1.kursnrcount, q2.trainercount from  (        select m.name, count(distinct a.kursnr) as kursnrcount     from trainer t     left outer join abhaltung a      on t.svnr = a.trainer      left outer join mitarbeiter m      on t.svnr = m.svnr      left outer join einzeltraining e on svnr = e.trainer     group by m.name, t.svnr ) q1 full join  (        select count(e.trainer) as trainercount, m.name     from trainer t      left outer join einzeltraining e      on e.trainer = t.svnr      left outer join mitarbeiter m      on t.svnr = m.svnr     group by e.trainer, m.name ) q2 on q2.name = q1.name 	0.0107322257823464
23295966	17202	sql, group by one colum	select id, version, sequence from datatable dt where version =     (select max(version)      from datatable       where sequence = dt.sequence) 	0.0172656226809825
23296276	19229	how do i select specific names of a column with content?	select e.especes,count(*) as [nombre de sujets], stuff((select  ',' + ' ' + a1.nom            from  animal a1,espece e1           where e1.idespece = a1.idespece and a1.idespece=a.idespece           for xml path (''))           , 1, 1, '')  as noms into statespece  from espece e,animal a  where e.idespece = a.idespece  group by a.idespece, e.especes; 	0.000119902850846656
23297984	20796	alpha numeric id's formatting	select *, upper(left(lastname, 3)) + right('000' + cast(id as varchar(3)), 3) from (     select          lastname,          firstname,          row_number() over (partition by left(lastname, 3) order by lastname) as id     from @table ) t 	0.148305399869089
23299646	3626	get name of weekday in netezza	select to_char(date, 'day') from table 	0.00448702324211966
23299875	11565	aggregate sum of a field when another row with the same id is selected in sql	select a1.v, sum(a2.v) from users u inner join attributes a1 on a1.user_id = u.id inner join attributes a2 on a2.user_id = a1.user_id and a2.k = 'k2' where a1.k = 'k1' group by a1.v 	0
23300732	21357	sql server query to divide rows in a column into four groups or columns	select      [1] as col_1,[2] as col_2,[3] as col_3,[4] as col_4  from (     select           tableid,         rownumber=row_number() over (partition by quarttile order by quarttile),         quarttile     from     (         select             tableid,             quarttile=ntile(4) over(order by newid())         from             table     )as z )x pivot (avg(tableid) for quarttile in([1],[2],[3],[4]) )as pvt 	6.33314837838658e-05
23301928	39731	t-sql, compare record property, then suusequent date compare	select top 1 foo, bar, datetime from table  where foo='foo1' and bar='bar1' order by datetime desc 	8.34365384520217e-05
23302548	28955	how do i search a mysql database for entries that exceed a certain number of characters?	select * from yourtable where length(yourcolumn) > 70 	0
23302675	10058	sql join with aggregated data	select     users.id, users.username,     count(products.pr_name) as num_products_bought  from     users  left join     products on products.userid = users.id  group by     users.id having     sum(case when products.pr_name = "apple" then 1 else 0 end) > 0 	0.349613189581741
23305613	14895	left join to produce one row for each day	select hed.hcc_emp_id, eam.emp_attendance_action, eam.emp_attendance_date from  hcc_emp_detail hed left join emp_attendance_main eam     on hed.hcc_emp_id = eam.emp_attendance_emp_id        and eam.emp_attendance_date=cast(getdate() as date) 	0
23306948	15719	select and get the most repeated occurrence on mysql	select     kills,     count(id) as kill_count from table group by kills order by kill_count desc limit 1 	0
23307787	11140	get last one month record in mysql	select pt_product_name, purhis_measurement, purhis_quantity, purhis_return_qty, purhis_actual_qty, purhis_per_qty_price, purhis_ledgerid, purhis_invoice_no, purhis_purchase_dt, purhis_invoice_dt, purhis_type_of_purchase, purhis_mode_of_purchase from purchasehis_tb as pur,product_tb as pt where pt.pt_bt_branchid='bra102451717858' and pt.pt_productid=pur.purhis_pt_productid and pur.purhis_updated_dt between subdate(curdate(), interval 1 month) and now() 	0
23308073	35054	joing the tables to get the required data, i got three tables which are connected and i want to get the data from the 3rd table	select a.username from t3 a,t2 b,t1 c      where a.userid=b.userid and b.usertrainerid= c.usertrainerid ; 	0
23311274	5201	mysql selecting date on timestamp	select *, date(last_update) from labor; 	0.00143457719026434
23311755	19498	using switch() to split data from a column into distinct columns, with associated data in reach row	select id, switch( val='a', 'a') as val_1, switch( val='a', date) as val_1_date, switch( val='b', 'b') as val_2, switch( val='b', date) as val_2_date from table1 group by id 	0
23312102	25560	using datetime functions to check for subscriptions that fall on booking date	select     s.startdate,     d.* from     subscription s join subscribeddays d on s.id = d.subscriptionid right join (     select         '2014-04-28' as c_dt,         dayofweek('2014-04-28') as c_dt_wk,         1 as c_space     from         dual ) c on c.c_space = s.spaceid and s.startdate <= c.c_dt and (     (c.c_dt_wk = 1 and d.sun = 1)     or (c.c_dt_wk = 2 and d.mon = 1)     or (c.c_dt_wk = 3 and d.tue = 1)     or (c.c_dt_wk = 4 and d.wed = 1)     or (c.c_dt_wk = 5 and d.thur = 1)     or (c.c_dt_wk = 6 and d.fri = 1)     or (c.c_dt_wk = 7 and d.sat = 1) ) 	0.0190464638139732
23314569	36460	in sql how to check if a string contains a substring in(case insensitive)?	select * from products where lower(name) like '%a%' 	0.229882057423459
23314679	5481	join big data table with keys tables fast	select `dati`.* from `dati` right join `i2` on `i2`.`valore` = `dati`.`i2` right join `i3` on `i3`.`valore` = `dati`.`i3` right join `i4` on `i4`.`valore` = `dati`.`i4` where ( `i1` = 'target|internauti' or `i1` = 'target|internauti social' ) and ( `i2` = 'banche|adv awareness spontanea online' or `i2` = 'banche|brand awareness tom' ) and ( `i3` = 'brand bancari|(net) gruppo ucxredit' or `i3` = 'brand bancari|banca mecdioum' ) and ( `i4` = 'anno|2013' or `i4` = 'anno|2014' ) and ( true ) and `i2`.`mostrare` =1 and `i3`.`mostrare` =1 and `i4`.`mostrare` =1 order by `i2`.`ordine` asc, `i3`.`ordine` asc, `i4`.`ordine` asc 	0.0511201003085866
23315126	37015	how to sort in a other way (mysqli)	select ip from chat where datum > '".$timestamp."' group by ip  order by id asc 	0.0221308731127632
23315564	2559	how to use the id in one table to display relating information from another table?	select  p.id, p.name, p.description, p.image, p.price, c.name as category_name from  products p inner join categories c on c.id = p.category_id 	0
23315639	8115	sql query for all values in single row	select t.id, t.patient, t.study,        sum(t.ava) as ava, sum(t.lvot) as lvot, sum(t.lv) as lv, sum(t.avpg) as avpg from table t group by t.id, t.patient, t.study; 	0.000430718234293696
23316385	1320	getting latest data out from a table and then doing a sum	select l1.`date`, sum(l1.`pages`) `pages` from `log` l1 join (   select `website_id`, max(`created_at`) as `created_at`   from `log`   group by `website_id`, `date` ) l2 on l1.`website_id` = l2.`website_id`   and l1.`created_at` = l2.`created_at` group by `date` 	0
23316922	38335	select rows where day is less than today	select * from orders   where created_date < to_date('2014-04-28', 'yyyy-mm-dd'); 	8.63655686575762e-05
23318016	24424	sql server query: sum columns from 2 tables	select   a.cust_id         , sum(isnull(p.price,0) + isnull(s.price,0)) final_price from appointment a  inner join product p   on a.prod_num = p.prod_num inner join service s   on s.service_id = a.service_id group by a.cust_id 	0.00139714845508718
23319493	22246	single mysql query to get list of user who did like the posts which is liked by me	select liked_by_uid from likes where post_id in     (select post_id from likes where liked_by_uid='51') 	4.87017514454215e-05
23319847	36586	convert two date columns from two diferent tables into one in sql server	select table1.id , table1.onedate , table1.hourswork , isnull(table2.hoursrest, 0) from table1 left join table2 on table1.id = table2.id 	0
23320185	36135	sql outer join count above rows	select _id     ,sub_id     ,(         select count(*)         from table2 t2         where t2.sub_id >= t1.sub_id         ) count from table1 t1 	0.422176024302846
23320376	20017	counting how many times each element appeared in the "search"	select indexval,count(indexval) from key_word where hashed_word in ('001','01v','0ji','0k9','0vc','0@v','0%d','13#' ,'148' ,'1e1','1sx','1v$','1@c','1?b','1?k','226','2kl','2ue','2*l','2?4','36h','3au','3us','4d~')    group by indexval 	0
23320887	33781	mysql - customers with at least one purchase in every one of the three months	select distinct cust_id, concat(cust_name_last,', ',cust_name_first) as 'customer name' from a_bkorders.customers where exists     (select *      from a_bkorders.order_headers     where order_headers.cust_id = customers.cust_id     and date_format(order_date, '%y-%m') in (prevmonth( current_date(), 3))) and exists     (select *     from a_bkorders.order_headers     where order_headers.cust_id = customers.cust_id     and date_format(order_date, '%y-%m') in (prevmonth( current_date(), 4))) and exists     (select *     from a_bkorders.order_headers     where order_headers.cust_id = customers.cust_id     and date_format(order_date, '%y-%m') in (prevmonth( current_date(), 2))); 	0
23320945	36098	postgresql select if string contains	select id from tag_table where 'aaaaaaaa' like '%' || tag_name || '%'; 	0.060669242697988
23321694	23260	get default value or value from table in sql	select b.idb, coalesce(a.text, a2.text) text from b left join a on b.idb = a.fkb and a.langid = 1 left join (   select fkb, text   from (     select fkb, text,         row_number() over (partition by kfb order by langid) seq_no     from a   ) t   where seq_no = 1 ) a2 on b.idb = a2.fkb 	6.65840850260525e-05
23321867	870	join count from one table to select from another - mysql	select users.username, name, anniversarydate, regioncode,          coalesce(count(b.username),0) as cnt      from users          left outer join (select username, max(timeused)             from log_table where role='cou'             group by username order by max(timeused) desc limit 10         ) a using (username)         left outer join fedbacks b on (a.username = b.username)         group by users.username; 	0
23322874	12433	sql counting using multiple columns in the same table	select p1.productid, p1.productname, p1.manufacturer, count(p2.productid) games from productstbl p1 left join productstbl p2    on p2.producttype = 'game' and p2.platform = p1.productname where p1.producttype = 'console' group by p1.productid, p1.productname, p1.manufacturer; 	0.000188145413214248
23323156	6597	order by the greater column	select * from your_table order by case when time_1 >= time_2 then time_1                else time_2          end desc 	0.0131699261571607
23323287	21454	sql query to select data from two tables with single column known	select     * from     alumnidetails ad inner join alumwork aw     on ad.username = aw.username where     ad.firstname = ‘pete’; 	0
23323432	27837	sql server: check if selected date is older or newer than current date	select      dateid,             convert(varchar(11), datedt, 106) as datedt,             case when convert(varchar(11), datedt, 106) > getdate() then 'future'              else 'past' end as futureorpast,             convert(varchar(10), datedt, 126) as datedtshort,             countries,             regions from        daysfixed where       countries like '%'+@selcountry+'%' or          regions like '%'+@selcountry+'%' order by    dateid for xml path('datesdt'), elements, type, root('root') 	0
23324849	10284	sql count occurences multiple columns	select count(distinct user) as numnames from ( select person1 as user from mytable union all select person1 from mytable union all select person3 from mytable union all select person4 from mytable union all select person5 from mytable ) all_users 	0.00359082026474998
23325959	18904	sql query, linking one table back to itself	select v1.[title] as current_video       ,v2.[title] as suggested_video from      video_suggestions vs  left join suggested_videos sv  on vs.suggestion_id = sv.suggestion_id left join videos v1    on   vs.video_id = v1.video_id left join videos v2    on   sv.video_id = v2.video_id 	0.00533886309603386
23327837	17890	mysql query order by the query itself	select name from products where id=0 or id= 4 or id=2 order by field(id,0,4,2); 	0.405326405349696
23328293	25726	get data from column in oracle 10g	select user from dual; select owner from all_tables where table_name = 'hp'; 	0.00306495672391891
23328297	21513	i am calculating total amount spent per customer in mysql, using join with 3 tables	select sum(products.listprice) from order_has_products inner join products on order_has_products.isbn = products.isbn group by order_has_products.customer_id 	0
23329624	9245	find duplicate records in mysql without named column	select distinct lead_id from tablename as t1 where exists (   select 1   from tablename as t2   where t1.field_number = t2.field_number   and   t1.value = t2.value    and   t1.lead_id <> t2.lead_id    ) 	0.000107879222043403
23329903	2918	computed column in select case t-sql	select   providercode,    case     when coverageitem in ('lab', 'ben') then 'lab'     else coverageitem   end as coverageitem,   sum(hb.billedamt) as billedamount from hospitalbill hb group by    providercode,    case     when coverageitem in ('lab', 'ben') then 'lab'     else coverageitem   end 	0.203334127162069
23330909	5155	case mysql - select as value	select     u.id as id     case u.role         when 0 then \'handlowiec\'         when 1 then \'kierownik\'         when 2 then \'administrator\'     end as role,     u.name as name,     u.email as email,     coalesce (m.name, '-') as manager from user u left outer join user m on u.manager = m.id ' . $where . ' order by name 	0.259913755172512
23331765	10226	getting the sum of values in same column in sql query	select sell_date, sell_hour, sum(price), count(*)  from dbo.sold_items  group by sell_date, sell_hour; 	0.000137718676102628
23331871	24268	how to select best score for golf tournament mysql?	select player, min(hole1), min(hole2) ... from scores group by player 	0.136878426529896
23331963	34704	exclude records from query based on table join results	select id, artist, title from video where artist not in (   select v.artist   from video v, runlog r   where v.id = r.videoid     and r.datetime > dateadd(hour, -1, getdate())   union   select v.artist   from video v, runlog r   where v.id = r.videoid     and r.datetime > dateadd(hour, -24, getdate())   group by v.artist   having count(*) > 2 ); 	0
23332701	16803	view duplicate data in sql statement	select * from participants where nokp in (   select nokp   from participants   group by nokp   having count(*) > 1  ) 	0.145283550134308
23332723	14547	how to remove duplicate records from same table while displaying	select count(cust_id),to_char(date_enq,'dd-mon-yyyy') from demo group by to_char(date_enq,'dd-mon-yyyy'); 	0
23333321	24970	sccm sql query join of multiple tables	select   s.name0,   s.operating_system_name_and0,   s.is_virtual_machine0,   us.full_user_name0,   us.user_name0,   v_gs_system_enclosure.chassistypes0,   v_gs_system_enclosure.manufacturer0,   v_gs_system_enclosure.model0,   v_gs_x86_pc_memory.totalphysicalmemory0,   v_ra_system_ipaddresses.ip_addresses0 from v_r_system s left join v_gs_system_enclosure on s.resourceid = v_gs_system_enclosure.resourceid left join v_ra_system_ipaddresses on s.resourceid = v_ra_system_ipaddresses.resourceid left join v_gs_x86_pc_memory on s.resourceid = v_gs_x86_pc_memory.resourceid left join  (select   u.user_name0,   upm.userresourceid,   upm.machineid,   u.full_user_name0 from v_usersprimarymachines upm join v_r_user u on upm.userresourceid = u.resourceid) us on s.resourceid = us.machineid where (v_ra_system_ipaddresses.ip_addresses0 not like '%:%') 	0.318354794020308
23333576	28959	selecting specific row number in sql?	select right(intvalue, (len(intvalue) - (patindex('%$*%' , intvalue) + 1)))as data from dbo.split('1$*hi,2$*hellow,3$*acronym', ',')  where left(intvalue,patindex('%$*%' , intvalue) -1)  = 1 	0.000139695413646395
23335440	2845	return null for missing values in an in list	select v.id, t.val from   (select 1 as id    union all select 2    union all select 3    union all select 4    union all select 5) v   left join tab t   on v.id = t.id 	0.0080077244932559
23335849	35486	conversion of string to datetime fails with exception how to find which row causes it	select     nr,     datum from mytemptable where datum is not null and      try_parse(case when len(datum) = 9         then left(datum,6) + cast((cast(right(datum, 3) as int) + 1900) as varchar(4)) + ' 00:00:00.000'         else datum  + ' 00:00:00.000'     end as datetime2 using 'de-de') < '01.01.1753 00:00:00.000'; 	0.0754536880746868
23336162	23811	sum in mysql than group by	select code, sum(package_id_price) from(     select code, package_id, max(price) as package_id_price     from lottery      where round = '$current_round'      group by code, package_id ) sub1 group by code 	0.13021368901441
23336315	19710	find different records in 2 tables mysql	select *  from music_class  where name not in (select name from sport_class); 	5.13809086723205e-05
23336346	4669	mysql select datetime	select timestamp('2010-01-01 12:34:56'); 	0.12336768447885
23336663	26261	how to get the distinct records based on maximum date?	select id, name, date from (     select *, row_number() over (partition by id order by date desc) as rownum      from [mytable] ) x where rownum = 1 	0
23337947	16932	month sorting in sql	select *  from table_name order by right([month], 4) desc , substring([month], 5, 2) desc 	0.027643528936155
23339013	29263	mysql count total logged in time for application	select e1.userid, sum(unix_timestamp(coalesce(e2.time, now())) -                        unix_timestamp(e1.time))/3600 total  from eventlog e1  left join eventlog e2   on e1.userid = e2.userid and e2.eventtype='logout' and e1.time < e2.time left join eventlog e3   on e1.userid = e3.userid and e1.time < e3.time and e3.time < e2.time where e1.eventtype='login' and e3.time is null group by e1.userid 	0.00436723872196757
23339715	39840	t-sql force null value based on condition	select e.text as statustext,         a.created as [date],         case a.status             when 2 then null             when 3 then null             else a.username         end,           b.name  as customername,         c.name  as servicename,         d.message as deviationmessage    from dbo.statusupdate as a         left outer join dbo.customer as b on a.customerid = b.customerid         left outer join dbo.service as c on a.serviceid = c.serviceid         left outer join dbo.deviation as d on a.deviationid = d.deviationid         left outer join dbo.statustext as e on a.status = e.id 	0.00858048428077527
23340025	23533	how to find number of times record is accessed for oracle	select yourtable.* from yourtable where yourfunct('yourtable', yourtable.key) = 'done' 	0
23341888	36553	how to append measurement units in select statement in sql query within the output	select to_char(speed_limit) || ' mph' from city 	0.326393254558815
23342479	8172	how can i avoiding cartesian product on sql on multiple tables	select      p.pid, p.lname,p.fname, thingone, thingtwo from     person p      left outer join      (         select isnull(t1.pid, t2.pid) as pid, t1.value as thingone, t2.value as thingtwo         from              (select *, row_number() over (partition by pid order by value) rn                       from table1) t1              full outer join                      (select *, row_number() over (partition by pid order by value) rn                       from table2) t2                      on t1.pid=t2.pid and t1.rn=t2.rn     ) v         on p.pid = v.pid 	0.152726427311349
23345107	15070	how to do a sql conditionnal joining on multiples tables?	select [...], request.id from [action] inner join [other tables on ...] inner join     person on action.personid = person.id left join  request as r on r.personid = person.id left join subject as s on s.subjectid = r.subjectid left join typerequest tr on tr.idsujet = s.subjectid **and typerequest = 'move'** where  ([already existing conditions]) 	0.0101529534035633
23345178	37802	how to filter sql by time (greater and less than)?	select * from data  where datetime(   substr(time,1,4)||'-'||   substr(time,6,2)||'-'||   substr(time,9,2)||' '||   substr(time,12,8) )  between datetime('2014-04-25 18:00:00') and datetime('2014-04-25 19:00:00'); 	0.00699457369377999
23345346	18938	filtering sqlite database by item "popularity"- android	select * from yourtable order by counter limit 10; 	0.0566842120445948
23345651	10824	sql command - advanced selecting	select * from table2 a inner join  (select * from table1 where manager = 'managerx') b on a.user = b.username 	0.600597671072142
23345723	1930	select available rooms in given date range	select * from rooms where id not in(select room_id from reservations where '2014-03-07 19:00:00' < e_to and '2014-03-08 19:00:00' > e_from) 	0
23348972	6024	how can a create an sql statement that offers multiple sum() totals?	select category, sum(qty * price) from your_table group by category union all select 'total' as category, sum(qty * price) from your_table 	0.0397508380719945
23349151	32254	how to calculate amount based on the number of working days from the month	select top 1000 [date]           ,[amount], [amount]/(select 20 + count(*) from           (select dateadd(month, datediff(month, 0, [date]), 28) as thedate           union           select dateadd(month, datediff(month, 0, [date]), 29)           union           select dateadd(month, datediff(month, 0, [date]), 30) ) as d      where datepart(day, [date]) > 28 and datediff(day, 0, [date]) % 7 < 5)     from [database].[dbo].[table] 	0
23350092	26673	mysql if statement to different where clause	select * from (   select article.type,article.name,member.name as user from articles inner join members                         on members.id_member = articles.author_id where article_type=0  union all  select article.type,article.name,company.name as user from articles inner join members       on members.id_member = articles.author_id inner join company on company.id_company = articles.author_id  where article_type=1 	0.55063401052596
23351300	16875	get id column from xml attributes	select d.value('( from (select id, cast(xmlstring as xml) data from xmldata) d cross apply data.nodes(' 	6.09132945718249e-05
23353118	26986	sql query, avg and count on multiple tables	select l.isbn, v.rating, r.rec from book l,      (select isbn, avg(rating) as rating from ratings group by isbn) v,     (select isbn, count(isbn) as rec from recommend group by isbn) r where l.isbn=v.isbn and l.isbn=r.isbn 	0.104462563439496
23354848	8756	ms access sql get latest records from each category	select *  from my_table as t1 where t1.report_date = (select max(report_date)                          from my_table as t2                           where t1.category = t2.category) 	0
23355354	24319	sql server : how to combine two select queries from the same table and take the result on column	select d,         sum(case when lw = 'green'     then cnt else 0 end) [green],         sum(case when lw = 'non-green' then cnt else 0 end) [non-green] from (   select [date] as d,    [type] as lw,    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,   dense_rank() over (order by [date] desc) dr   from tbbooth    where type in ('green','non-green') ) x  where dr < 8 group by d order by d asc 	0
23355858	7787	how to get each total from database?	select t1.company_accountno as account_no, sum(t2.amount) as total_amount, count(t1.company_accountno) as no_of_cheque   from table1 t1 inner join table2 t2 on t1.id = t2.company_accnopky  group by t1.company_accountno 	0
23356098	967	conversion failed when converting the nvarchar value "xxx" to data type int	select 'a' + right('000' + cast((max(convert(int,substring(userid,2,len(userid)))) + 1) as     nvarchar(50)), 3) from users 	0.500467395588634
23357254	27909	sql query to find the students in one course	select s.id, s.name from students s inner join registration r on s.id = r.stu_id group by s.id, s.name having count(*) = 1 	0.000581045504292053
23357359	14738	mysql : fetching the data except negative values	select * from xxx where yyy>=0 	0.00104932222738949
23357831	27624	how to join tables and get the result from the two tables when they appears in the first table and not in the second or vice versa	select isnull(a.customer_id, b.customer), isnull(a.date_of_revenue, b.revenue_date),     sum(isnull(a.revenue,0)+isnull(b.revenue_amount,0)) as total_revenue from tbl_a a full join tbl_b b on a.customer_id = b.customer and a.date_of_revenue = b.revenue_date group by isnull(a.customer_id, b.customer), isnull(a.date_of_revenue, b.revenue_date) order by isnull(a.customer_id, b.customer), isnull(a.date_of_revenue, b.revenue_date) 	0
23358333	5939	how can i generate a series of repeating numbers in postgresql?	select a.n from generate_series(1, 100) as a(n), generate_series(1, 3) 	0.00111738141474725
23359416	36508	sql join query - two fk, one field	select i.spolicynumber,         i.ddatepaid,         i.drenewal,         i.mlastpremium,         c.screditorname,         b.screditorname    from insurance i         left join creditor  c on c.lcreditorid = i.lcreditorid         left join creditor  b on b.lcreditorid = i.lbrokerid   where insurance.lownerscorporationid = '1' 	0.0165330713932017
23365124	18968	how to query for request records that do not have response	select t1.uniquenumber from mytable t1 left join mytable t2 on t2.uniquenumber = t1.uniquenumber   and t2.type = 'response' where t1.type = 'request' and t2.type is null 	0.0902334066384642
23365388	12710	return a selected status table and then join a count of those statuses from another table. sql	select     aqa.statusid,     aqa.[description],     count(isnull(aq.activestatus, '0')) as [count] from     ap_quoteactivestatus as aqa with(nolock) left outer join ap_quote as aq with(nolock)     on aq.activestatus = aqa.statusid group by aqa.statusid, aqa.[description] order by aqa.[description] 	0
23366121	7921	format [timestamp] field value in where clause?	select         memno.1 edtcde(l), name.2, 'sys1' name(sys), "&&startdate" name(startdate), current date name(curdate) from           library1/table1, library1/table2 join               ssan.1=ssan.2 where          date(timestamp)>startdate and rscode='stp' union  select         memno.1 edtcde(l), name.2, 'sys2' name(sys), "&&startdate" name(startdate), current date name(curdate) from           library2/table1, library2/table1 join               ssan.1=ssan.2 where          date(timestamp)>startdate and rscode='stp' order by   sys asc, memno asc 	0.016160295926208
23366138	25153	select newest entry from two tables in addition to left join and union mysql query	select  comment_id,comment, user_id,poster_id,timestamp, contact_person,company,pic_small  from  (select  alerts.comment_id,alerts.user_id,alerts.poster_id,alerts.timestamp,users.contact_person,users.company,users.pic_small,act.comment  from alerts  join activity act  on act.comment_id=alerts.comment_id  left join users on users.user_id = alerts.user_id  where alerts.user_id = %s  order by act.timestamp desc) a  group by comment_id; 	0.00137193330258878
23366495	32130	datediff of 2 dates in the same column sql	select t1.orderno,datediff(day,t1.loadedstartdate,t2.loadedstartdate) from unnamedtablefromquestion t1        inner join      unnamedtablefromquestion t2        on          t1.orderno = t2.orderno where t1.opno = 1 and       t2.opno = 4 	9.78596585233968e-05
23368865	17508	data in condition is not equal	select * from t2  where t2.t1_id not in(select id from t1) 	0.308784225968656
23368886	35251	how can i order data and add a record to the first position of the data set?	select 0 sortfield, '' name, etc union  select 1 sortfield, name, etc from etc order by sortfield, name. 	0
23370153	25296	mysql - duplicate rows by different collumn	select o.* from table1 s  inner join table1 o  on s.job = o.job where s.type = 'searching' and o.type = 'offering' and s.user_id = (the user who is searching) 	0.00124913963795365
23370401	24162	mysql: grouping ordered results	select   yearweek(u.min_created_at) as yearweek_first_user,   count(*) from   (     select school_id, min(created_at) as min_created_at     from users     group by school_id   ) u group by   yearweek(u.min_created_at) 	0.0469672453288637
23371085	31694	distribution of values in a postgresql table	select quantity, count(*) from (     select user_name, count(*) as quantity     from t     where product_name = 'candle'     group by user_name ) s group by quantity order by quantity 	0.00276852512211481
23371203	5616	combining multiple queries in access so that the data is displayed in different fields within a single table	select   sq1.district , sq1.countofdistrict , sq2.[countofsite id] from (   ... your first query here ... ) as sq1 inner join (   ... your second query here ... ) as sq2 on sq1.district = sq2.district 	5.53066018563476e-05
23371268	30417	how to get individual counts from same table,based on different keywords	select sum(if(type = 'iphone', 1, 0)) as n_iphone, sum(if(type = 'android', 1, 0)) as n_android, sum(if(type = 'windows', 1, 0)) as n_windows from mobile_types; 	0
23372585	20016	select based on where-clause on multiple rows	select groupid  from your_table  where userid in (1,2,3) group by groupid having count(*) = 3 	0.000449848535770105
23374570	2839	sql picking one record over another	select attempt,      min(value) as value,     (select time from t as t1       where t1.value = min(t.value)           and t.attempt = t1.attempt) as time from t as t group by attempt 	0.000247745790092482
23376001	36515	sql server : query joining two tables	select      u1.userdisplayname as [challenger],     u2.userdisplayname as [challengee] from challengematch cm left outer join users u1     on cm.challengeruserid = u1.userid left outer join users u2     on cm.challengeeuserid = u2.userid where cm.challengematchid = 2 	0.0716548876465666
23376019	376	sql using not between by defining a range in an another unrelated table	select a.* from table-a a left outer join      table-b b      on a.id between b.rangefrom and b.rangeto where b.rangefrom is null; 	0.00032788208341594
23376023	22186	mysql join get info from 2 rows	select t.cat, p1.name name1, p2.name name2, p1.points + p2.points points from teams as t join players as p1 on p1.dni = t.dni1 join players as p2 on p2.dni = t.dni2 where cat = 1 order by points desc 	5.64052639059671e-05
23376778	7467	following mysql table search result	select u.id      , u.username      , f.id_1      , f.id_2    from users u   left join following f   on u.id in (f.id_1,f.id_2)   and f.id_1 = '$userid'  where u.username like '%$search%'  order by u.id  limit 1; 	0.226434099654463
23376840	34336	where to get a web graph with corresponding web pages dataset	select * from links where link_type='a' 	0.0452660478587485
23377375	12727	find minimum of one variable and matching values of other variables in sql	select v1, v2, v3 from test a where (select min(v2) from test b where a.v1 = b.v1) = v2; 	0
23379143	17605	how to match time with my table?	select top(1) * from  mytable where time <= current_time     order by time 	0.0408164409929254
23379655	32709	how do i order rows in a specific sequence using mysql?	select booksize(page_count) as size, count(*) as nmbrboooks from books where page_count is not null and page_count > 0 group by size order by page_count; 	0.00629199805778064
23382479	9196	error : associating xsd with xml data type column - "cannot create a row of size"	select p.index_id, p.partition_number,     pc.leaf_null_bit,     coalesce(cx.name, c.name) as column_name,     pc.partition_column_id,     pc.max_inrow_length,     pc.max_length,     pc.key_ordinal,     pc.leaf_offset,     pc.is_nullable,     pc.is_dropped,     pc.is_uniqueifier,     pc.is_sparse,     pc.is_anti_matter from sys.system_internals_partitions p join sys.system_internals_partition_columns pc     on p.partition_id = pc.partition_id left join sys.index_columns ic     on p.object_id = ic.object_id     and ic.index_id = p.index_id     and ic.index_column_id = pc.partition_column_id left join sys.columns c     on p.object_id = c.object_id     and ic.column_id = c.column_id left join sys.columns cx     on p.object_id = cx.object_id     and p.index_id in (0,1)     and pc.partition_column_id = cx.column_id where p.object_id = object_id('pphgrader_preferencedata') order by index_id, partition_number; 	0.0383855183857989
23384775	31842	append character if word count more then 20	select  case when length(sentence) > 50 then      sentence || '...'      when length(sentence) > 20 then      sentence || '.'      else      sentence end as sentence from yourtable 	0.00221779963418965
23386684	25576	how to select on the basis of date from different table	select si.product_id, sum( si.quantity ) soldqty  from  sale_items si inner join sales s on s.id = si.sale_id where s.date = 'your date' group by si.product_id 	0
23386746	493	returning a 'calculated' column in an sql server query	select     matchid,    scorehome,     scoreaway,    (case when (scorehome > scoreaway) then 'home win'          when (scorehome < scoreaway) then 'away win'                      else 'the draw' end    ) as result from     match 	0.332514722771925
23388968	1869	how can i join three tables in sql server?	select     l.ledger_id,    l.std_reg_id,    l.fee_of_month,    l.ledger_date,    l.fees,    f.other_fees_id,    f.title from dbo.ledger l left join dbo.other_fees f on l.other_fees_id = f.other_fees_id left join dbo.std_profile p on l.std_reg_id = p.std_reg_id 	0.356960897647737
23389357	12467	select clause with count and condition more than 2	select dl.dname from deptloc dl group by dl.dname having count(*) > 1; 	0.14408417409883
23391525	30379	get most recent event using join	select t1.id, t1.name, t1.address1, t2.item, t2.visit_date from table1 t1 cross apply (select top 1 * from table2 where id = table1.id  order by     visit_date desc) t2 	0.00036942289229538
23391832	36339	sql query to select data between dates does not show last date	select * from order where status = "completed" and date(orderdate) >= date(?) and date(orderdate) <= date(?) order by orderid desc 	7.08438499872394e-05
23392932	15858	group by month with mutliple tables and date fields	select     t.[month]     ,sum(t.costtotal)     ,sum(t.repairtotal)     ,sum(t.servicetotal) from  (     select         datepart(mm, purchasedate) as [month],         costtotal,         0 as repairtotal,         0 as servicetotal     from tablea     union     select         datepart(mm, repairdate) as [month],         0 as costtotal,         repairtotal,         0 as servicetotal     from tableb     union     select         datepart(mm, servicedate) as [month],         0 as costtotal,         0 as repairtotal,         servicetotal     from tableb ) as t group by t.[month] order by t.[month] 	0.000427570321696299
23393303	9566	conditional time period for totals	select * from a left join b case when a.dateid >= b.periodstart and a.dateid <= b.periodend then 1 else 0 end = 1 	0.0639510407965364
23393369	13670	[solved]get record with a field egal to a specific value else with null	select top 1 col1, col2, col3 from table1 where (col2 = my_specific_value or col2 is null) and       col3 = '42' and col1 = 3 order by (case when col2 = my_specific_value then 1 else 2 end); 	0.00169219031844712
23393829	29860	sql query wont order by time and date	select measurements.title as tittel, routines.value as verdi, convert(varchar(10),routines.date,103) as dato, convert(varchar(10), routines.time, 108) as tid, pools.name as basseng, emps.user_name as ansatt from routines, measure_routine, measurements, pools, emps where routines.id = measure_routine.routine_id and measure_routine.measure_id = measurements.id and (measurements.title  like 't_%') and measure_routine.pool_id=pools.id and routines.emp_id=emps.id  and date between '2014-04-29' and '2014-04-30' order by routines.date desc, routines.time desc 	0.365264889453281
23394546	8741	get last auto increment php	select   id, question,   @seq:=@seq+1 as seq from   questions,   (select @seq:=0) as init ; 	0
23395918	23859	how to ignore null in a mysql query	select source, count(*) as count from cs where source is not null 	0.273645451204748
23398272	38653	table has one record per employee per year. how do i select the record for each employee for the latest year for that employee?	select employee_ref, firstname, lastname from table where employment_year = (     select max(employment_year)     from table b     where b.employee_ref = table.employee_ref) 	0
23398893	31554	sql for xml multilevel from one pivoted table - grouping data	select country as 'loc/@name',        id as 'loc/@id',        (          select [city] as 'dub/@name',            (                select 1950 as 'data/@year',                   [1950] as 'data/@value',                   null,                   1955 as 'data/@year',                   [1955] as 'data/@value'                from yourtable as d                where country = c.country                and city = t.city                for xml path(''), type              ) as 'dub/datavalues'          from          (            select distinct city            from yourtable            where country = c.country          ) as t          for xml path(''), type        ) as 'loc/dubs' from (   select distinct country, id   from yourtable ) as c for xml path(''), root('locations'), type 	0.00326545884303948
23399070	6989	how to query in the same table, comparing the field count?	select * from mytable where buyer in (   select buyer    from mytable   group by buyer   having      sum(case when car = 'bmw' then 1 end) =     sum(case when car = 'audi' then 1 end) ); 	7.97169703052422e-05
23401213	8147	retrieve user profile data from all of a user's friends using php and mysql	select u.* from users as u inner join friends as f on f.friend_user_id = u.id where f.initiator_user_id = 1001 	0
23401787	5058	select clause using 3 different tables	select d.dname,p.title from department d   inner join dp on d.dname=dp.dname   inner join project p on p.p#=dp.p# order by d.dname desc, p.title asc 	0.0518966943058624
23404529	8689	how do you find open transactions on windows azure sql database?	select * from sys.dm_tran_active_transactions select * from sys.dm_tran_database_transactions select * from sys.dm_tran_session_transactions 	0.0661496317509332
23406792	36949	search for ids half string and half number	select id from orders where order_id>'obe30000' 	0.000220862599446407
23410181	6911	total of entries where record/row count equals 2	select user_id , count(name) as c from table_name group by user_id having count(*) = 2 	0
23411691	15668	look up items in same table from relationship table sql	select * from objects o1 inner join relationships r on o1.id = r.relatedfromid inner join objects o2 on r.relatedtoid = o2.id where o1.value like '%the value you are searching for%' 	6.14673319909251e-05
23414848	27853	sqlite query gives different results	select name, slot, id, species_id  from type_names t, pokemon_types pt, pokemon p  where t.type_id = pt.type_id  and p.id = pt.pokemon_id  and t.local_language_id = 9  and p.identifier like '%char%' order by p.species_id, id, slot asc; 	0.344142215034603
23415509	5376	ms access - substitute for except using same table	select  * from (select * from table1 where subposition is not null) as hassubposition left join (select * from table1 where subposition is null) as nosubposition on  hassubposition.eventid = nosubposition.eventid and hassubposition.position = nosubposition.position and hassubposition.pool = nosubposition.pool and hassubposition.status = nosubposition.status and hassubposition.area = nosubposition.area where nosubposition.eventid is null 	0.111881566451224
23417040	16131	mysql tell difference between table and view	select *  from information_schema.tables  where 'table_type' = 'base table' and table_name = 'your table name' 	0.0246081751202027
23417936	7794	quarterly totals using loop in sql server	select county,      year(ddate) as year,      count(*) as total,      sum(case when datepart(q, ddate)=1 then 1 else 0 end) as q1,     sum(case when datepart(q, ddate)=2 then 1 else 0 end) as q2,     sum(case when datepart(q, ddate)=3 then 1 else 0 end) as q3,     sum(case when datepart(q, ddate)=4 then 1 else 0 end) as q4 from #tcounty group by county,      year(ddate) 	0.773976388023338
23418126	37909	display 1st precision value after decimal (in oracle)	select    case     when column_a like '%.%' then       to_char(cast(column_a as decimal(10,3))*100, '999.0') || '%'     else column_a    end as column_f from   table_a; 	0.000351090912502677
23419881	9478	sql: select criteria for two tables, compare 1 field, return using condition	select  te.employeename       , emp.id_skills       , case when min(emp.trainingrequired) = 0 then 'no'              else 'yes'         end as trainingrequired from    dbo.tblemployee as te join    (select tecs.id_employee               , tecs.id_skills               , 0 as trainingrequired          from   dbo.tblemployeecurrentskills as tecs          union          select tsr.id_employee               , tsr.id_skills               , 1 as trainingrequired          from   dbo.tblskillsrequired as tsr         ) emp         on te.id_employee = emp.id_employee group by te.id_employee       , te.employeename       , emp.id_skills order by te.id_employee       , emp.id_skills 	8.31568543070421e-05
23422553	37023	mysql subquery on multiple tables	select g.guest_no, g.g_name, g.g_address from guest g inner join booking b on b.guest_no = g.guest_no inner join hotel h on h.hotel_no = b.hotel_no where h.city = 'london' 	0.186389999024035
23423729	30493	t-sql case statement where value is derived from joining tables	select t.[taskid], t.[sectionid], t.[dateadded],    case        when sectionid is null then 1       when o.[type] = 6 then 2       else 3    end as [type] from [task] as t     left outer join organisation o on t.taskid = o.taskid where (t.[deleted] = 0) order by t.[dateadded] 	0.237416944964282
23423757	11837	using distinct with specific case	select name, ae, bytes_alloc, maxbytes  from  (select name,   max (ae) over (partition by name order by name) ae,   sum(bytes_alloc) over (partition by name order by name) bytes_alloc,  sum(maxbytes) over (partition by name order by name) maxbytes,  row_number() over (partition by name order by name) rn  from tbl) s  where s.rn = 1 	0.397724801175353
23424595	12597	inner join to get all attributes	select * from albums  a inner join people p on a.idauthor = p.id inner join people p1 on a.idcompositor = p1.id inner join people p2 on a.idfeat = p2.id where a.idalbum=:id 	0.015874820949423
23425204	13478	pl/sql sort a varchar2 variable	select listagg(substr(v_text,level,1)) within group    (order by substr(v_text,level,1)) into v_text    from dual connect by level<=length(v_text); 	0.157047488880623
23426059	23853	use sql to calculate a market penetration ratio?	select count(distinct customer_id) * 100  / (select count(distinct customer_id) from transactions) from transactions where customer_id = 12 	0.0707187546615435
23426460	29152	how to select next record value in sql result	select t.*,        if(u_id = @u_id, timediff(`timestamp`, @timestamp), null) as diff,        @timestamp := `timestamp`, @u_id := u_id from table t cross join      (select @timestamp := 0, @u_id := 0) var order by u_id, timestamp; 	0.000119804584599103
23427646	26815	i have one issue in my query not get group record	select * from ( select *,rn=row_number()over(partition by grp order by id) from table )x where x.rn=1 	0.0825375001551627
23430472	38617	postgresql: trying to get average of counts for the last 10 ten days	select avg(last_10_count) as last_10_avg from  (select count(*) as last_10_count from dim_user where effective_date::date  > current_date -10 group by effective_date :: date) z 	0
23430479	37030	mysql statement (select) based on date now	select * from timekeeping where date(createddate) = date(now()); 	0.0025954846291519
23431006	4746	how to get last 4 inserted id's in mysql	select whatever_fields from table order by idfield desc limit 4 	0
23431726	7471	select between a range	select * from table where id between 20 and 30; select * from table where id >= 20 and id <= 30; 	0.00412781846037853
23432111	25738	how to select only those users that have multiple records attached to them?	select   user_id, count(distinct subscription_plan_id), min(created_at), max(created_at) from   subscriptions where    created_at between '2014-01-01' and '2014-01-31' group by   user_id having   count(distinct subscription_plan_id) > 1 ; 	0
23432441	7498	mysql adapt join according to the scenario	select * from exp_hotel join exp_result on  (res_posa = 'xxx' and  hot_id = res_idhotel) or (res_posa = 'yyy' and hot_webid = res_idhotel); 	0.198004529061965
23432582	5732	how to separate only the numbers out to two columns	select rtrim(left(column1, charindex('@', column1) - 1)) number1,        ltrim(right(column1, len(column1) - charindex('@', column1))) number2   from table1 	0
23434411	20495	how to create a derived column base on other column name	select      prodfileinfo.*  from prodfileinfo  inner join prodinfo  on prodinfo.prodnum = (case                             when len(prodfileinfo.prodfile) < 5 then cast(substring(prodfileinfo.prodfile, 1, least(5) as decimal)                            else cast(substring(prodfileinfo.prodfile, 1, 5) as decimal)                        end); 	5.32933350035151e-05
23434456	29801	case statement to combine two columns except when first characters not similar	select      case         when left(lastname1,4) <> left(lastname2,4)            then lastname1 + ', ' + lastname2         else lastname1 end as lastname 	0.0052383823812133
23434600	7256	tsql multiple selects for stats	select      sum(case when empid is not null and orderstatus = 'complete' then 1 else 0 end as totalorders,     sum(case when empid is not null and paymentstatus = 'complete' then 1 else 0 end as totalpayments from      chandlerbrandlaunch 	0.629733279681031
23435295	23972	using the sum function with a case function based on criteria	select c.keydma as 'keydma',        c.dmaname as 'dmaname',        a.dateendedstandard as 'dateendedstandard',        sum(             case when a.averagehouseholdincome > 75000                  then a.householdsbest                  else null             end           ) as 'bestabove75k',        sum(             case when a.averagehouseholdincome <= 75000                  then a.householdsbest                  else null             end           ) as 'bestless75k'   from lookup..demographiccbg a   join internaluseonly..blockgroupdmamap  b on a.blockgroupfips = b.blockgroupfips   join lookup..dma c on b.keydma = c.keydma   where a.updoperation < 2     and b.updoperation < 2     and c.updoperation < 2     and a.dateendedstandard = '12-31-2013'   group by             c.keydma,            c.dmaname,            a.dateendedstandard 	0.211178581457033
23437489	16253	sql: split a row into multiple rows based on fiscal year	select f.name, t.name from t inner join f on f.start between t.start and coalesce(t.end,current_date) or f.end between t.start and coalesce(t.end,current_date) 	0
23438839	35637	mysql tallying attributes of a refrenced foreign key	select artist, title, ifnull(count(s.mid), 0) salescount from music as m left join sale as s on m.id = s.mid and sdate <= curdate() group by artist, title 	0.00271750782421556
23440685	26947	show all weeks/month include empty count	select *,    yearweek(`the_day`) as yw,   count(`userid`) as numaction  from      (select        makedate('2014', id) as the_day     from integerseries     limit 365) as all_days  left join `login`      on date(login.`date`) = all_days.the_day  where `action` = 'login' and `userid` != 'admin'      or `action` is null group by week(`the_day`) order by `the_day` desc; 	0.00262153319796301
23440842	30309	resolve mysql query to select unique from id and order by date acceding	select  d2.*, d1.* from details d1 left outer join (select d.id, count(*) as total_ids from `details` d        group by d.id       ) d2 on d1.id=d2.id  order by d1.`difftime` asc, d2.total_ids  desc limit 5 	0.00211653455567556
23444594	21427	sql select decimal not 0	select *  from table1  where decimalvalue <> '0'; 	0.379740788821184
23444877	15826	calculate average fuel last 30 days	select 10 * sum(liter) / (max(km) - min(km)) as avgfuel from diesel where diesel.dato >= '$dx' and userid = ".$_cookie['userid']."; 	0
23448380	25798	sql server selecting 1 single datapoint every hour or every day from a table	select * from activitylog where id in     (select max(id) maxid      from activitylog      where activitydatetime between @startdatetime and @enddatetime      group by datepart(hour, activitydatetime)) 	0
23448569	28505	sql join and get another column	select user_games.*, games_steam.name   from user_games   join games_steam    on user_games.appid = games_steam.appid   where user_games.uid = '76561197996836099'   group by user_games.appid   order by games_steam.name asc   limit 0, 30 	0.00396542558432519
23448862	3522	mysql db inherited without normalization in one table, but i need to query off of it	select t1.hero_id, sum(t2.cost) from table1 t1 left join      table2 t2      on t2.item_id in (t1.item1, t1.item2, t1.item3, t1.item4, t1.item5, t1.item6) group by t1.hero_id; 	0.0807151146371697
23450599	23875	2 request by 1 mysql	select link, title, description, imguri, vkcount, fbcount, twcount, edition, name   from articles   join editions on id = articles.edition order by (vkcount + fbcount + twcount) desc limit 0, $count 	0.0817154501455246
23451533	32331	mysql not using an index on where in with two columns	select * from my_table  where (col1, col2) in ( (1000,1), (2000,2) ) and col1 in (1000,2000) 	0.17418529698188
23452851	36164	sql - null value should match with not null value with another table	select column1 from ( select table1.column1 as column1,table1.column2 as column2 from table1 join table2 on   table1.column2=table2.column2 and table1.column3=table2.column3 union select table1.column1 as column1,table1.column2 as column2 from table1 join table2 on   table1.column2 is null and table1.column3=table2.column3 ) as unioned order by column2 nulls last limit 1; 	0.00720852334673922
23453414	29386	how to find single row data from joined table in mysql?	select p.id, p.name, p.description,(select case when (select jt.image from joined_table jt where   jt.product_id=p.id and jt.is_profile=1 limit 1) is not null then (select jt.image from joined_table jt where   jt.product_id=p.id and jt.is_profile=1 limit 1) else (select jt.image from joined_table jt where   jt.product_id=p.id and jt.is_profile=0 limit 1) end) as img from product p where p.id=2 limit 1 	0
23456226	24034	display all action dvd in a particular year	select * from dvd where category = 'action' and year(str_to_date(years, "%y-%m-%d")) between 2013 and 2014; 	0
23456430	39707	grouping different columns in 1 sql query	select * from messages where messageid in (    select distinct    case when m2.messageid is null then m1.messageid    when m1.messageid > m2.messageid then m1.messageid else m2.messageid end    from messages m1    left join messages m2 on    (m1.fromuserid = m2.touserid    and m2.fromuserid = m1.touserid    and m1.messageid != m2.messageid) ) 	0.00605631340268662
23458586	10885	how to do a sum in mysql	select   p.level as levelid,   ifnull(count(distinct p.playerid),0) as nbplayerperlevel,   ifnull(count(distinct pp.playerid),0) as totalplayer from   player as p   left join player as pp on p.level<=pp.level group by p.level  order by p.level desc 	0.0787108156920548
23459920	7684	optimizing sql query with multiple keys	select firstguid, secondguid, name, datecreated from (select t.*,               rank() over (partition by secondguid order by datecreated desc) r       from testtable t) ilv where r=1 	0.783658915572449
23461069	8208	php mysql left join more fields	select restaurants.id, group_concat(resfoodhelper.id)  from restaurants left join resfoodhelper on restaurants.id = resfoodhelper.resid group by restaurants.id 	0.685020192058316
23461357	4657	filter sql server records	select refid from table1 as t group by refid having exists(   select refid    from table1 as t2    where [date]<>'2014-04-15'      or ([date]='2014-04-15' and isactive=0)    group by refid    having t.refid=t2.refid      and count(t.refid)=count(t2.refid)     ) 	0.0667846479900079
23462881	21184	mysql query - list events not being blocked within a given distance	select e.*,   ( 3959 * acos( cos( radians(-122.243475) ) *              cos( radians( latitude ) ) * cos( radians( longitude )              - radians(33.457573) ) + sin(-122.243475) ) *              sin( radians( latitude ) ) )          as distance   from `events` e   where      not exists (        select 1 from `blocked` b                where b.uid = '001'            and (e.bid = b.bid or e.category = b.category                 or e.type = b.type or e.subtype = b.subtype)     )      and active = '1'      and end >= 1398786400     and end <= 1398786400   having distance < 10000000000000; 	0.0134453721475148
23464377	6156	how to select and group date per 5 seconds interval?	select concat(date_format(dt,'%y-%m-%d h:%i:'),lpad(floor(second(dt)/5)*5,2,'0')), count(*)     from dates  group by concat(date_format(dt,'%y-%m-%d %h:%i:'),lpad(floor(second(dt)/5)*5,2,'0')); 	0
23464974	23967	error while joining two tables	select toolname,errordescription,starttime,endtime  from transactiondetails,tools where toolsoutageid=" + x +" and toolid="+y 	0.243450902702014
23468569	10404	select *, sum(net) as total from table1 where clause	select dv_id, sum(net) as sum_net from tbl_dv group by dv_id 	0.00713619925013069
23469245	40296	sql server - concat null numeric column	select cast(lower as varchar(50)) + '-' + isnull(cast(upper as varchar(50)), '') from name.tblrange 	0.388179767261046
23469328	40440	isa relationship query in sql	select e.empid, e.name, h.hourlysalary, m.monthlysalary from employee e left outer join hourlyemployee h on h.empid = e.empid left outer join monthlyemployee m on m.empid = e.empid; 	0.742076164566404
23471242	13360	sql - subtract value from same column	select    fab_info.fab_id,   earliest_fab.x - latest_fab.x,   earliest_fab.y - latest_fab.y,   earliest_fab.z - latest_fab.z,   earliest_fab.m - latest_fab.m from  (   select      fab_id,      min(correction_date) as min_correction_date,     max(correction_date) as max_correction_date   from fab   group by fab_id ) as fab_info inner join fab as earliest_fab on    earliest_fab.fab_id = fab_info.fab_id and    earliest_fab.min_correction_date = fab_info.min_correction_date inner join fab as latest_fab on    latest_fab.fab_id = fab_info.fab_id and    latest_fab.min_correction_date = fab_info.max_correction_date; 	0
23472663	21205	transform mysql table into edge list	select t1.user user1, t2.user user2 from table1 t1 inner join table1 t2 on t1.user<t2.user and t1.project=t2.project 	0.00476314811703671
23473021	4896	postgresql: get elapsed amount between integers	select max(stop_time) - min(start_time) from table1 	0.000553587634477166
23473566	25159	join two tables without extra rowes	select a.cola,    a.colb,    a.colc,    a.cold,    b.cold as cole from table_a as a join table_b as b   on b.cola = a.cola  and b.colb = a.colb group by a.cola,    a.colb,    a.colc,    a.cold,    b.cold 	0.0948198501265052
23475002	17576	test if dates overlap in a single query	select ep.performer_name, ep.performer_id, ep.performer_fee, e.event_id, e.event_fee, e.start_time, e.stop_time, group_concat(e2.event_id separator ',') from events as e join event_performers ep on e.event_id = ep.event_id join events e2 on e2.event_id != e.event_id and       greatest(e2.start_time, e.start_time) < least(e2.stop_time,e.stop_time) join  event_performers ep2 on ep2.event_id=e2.event_id and ep2.performer_id=ep.performer_id group by ep.performer_name, ep.performer_id, ep.performer_fee, e.event_id, e.event_fee, e.start_time, e.stop_time 	0.0117087679835172
23477280	17441	query for a skill database	select name from   person where  personnelnumber in (select   personnelnumber                            from     skillmapping                            where    (skillid = 2 and skilllevel = 3) or                                     (skillid = 4 and skilllevel = 5) or                                     (skillid = 8 and skilllevel = 2)                             group by personnelnumber                            having   count(*) = 3) 	0.342884611354101
23477973	30754	selecting last 5 positions of all users from a join	select      player_id,     player_lat,     player_lon,     `timestamp` from      (select          pp.player_id,          pp.player_lat,         pp.player_lon,         pp.`timestamp`,         @rn := if(@prev = pp.player_id, @rn + 1,1) as rn,         @prev:=pp.player_id     from         player_positions as pp         join (select @prev:= null, @rn := 0) as v     order by          pp.player_id,         pp.timestamp desc) as t where     rn <= 5; 	0
23478749	16797	sql - query which extracts all records but only the most recent record of a duplicate	select distinct t1.*  from ['duplicate data$'] t1 join (   select name, max(date) as [maxdate]   from ['duplicate data$']   group by name   having count(*)>1 ) as d on d.name = t1.name  and d.maxdate = t1.date order by t1.name 	0
23480816	24201	sql statement that returns sums of records and returns both make names in sql server	select       tdealerships.capshortname,     sum(tobjective.commitobj) as commitobj,      sum(tobjective.actualmtd) as mtd,      sum(tobjective.deltoday) as delt,     sum(tobjective.actualmtd)/sum(tobjective.commitobj) as commitunit,     sum(tobjective.commitgrossobj) as commitgrossobj,      sum(tobjective.grossactual) as grossactual,     sum(tobjective.grossactual)/sum(tobjective.commitgrossobj) as commitgross,     sum(tobjective.actualmtd)/sum(tobjective.grossactual) as mtdpru      'gmc/buick' as make  from tobjective, tmake, tdealerships  where tobjective.dealershipid = 10     and newused = 'new'     and tobjective.makeid = tmake.makeid     and tobjective.dealershipid = tdealerships.dealershipid     and (tmake.make like '%buick%'          or tmake.make like '%gmc%')  group by tdealerships.capshortname 	0.00573647959654171
23481937	4167	sql: how to select only one record from a group of related records	select * from productstable pt1 join (select left(pt1.productid, 13) as prodid, max(pt2.primarykey) as primarykey from productstable pt2 group by left(pt1.productid, 13)) as a on a.primarykey=pt1.primarykey 	0
23482790	28173	full join between three tables sharing the same primary key	select has_1165, has_1174, has_1173, count(*) as cnt, min(userpid), max(userpid) from (select userpid,              max(case when classid = 1165 then 1 else 0 end) as has_1165,              max(case when classid = 1174 then 1 else 0 end) as has_1174,              max(case when classid = 1173 then 1 else 0 end) as has_1173       from store.attendance       where classid in (1165, 1173, 1174) and             datehour between '2014-04-28 00:00:00' and '2014-04-30 00:00:00'       group by userpid      ) a group by has_1165, has_1174, has_1173; 	0.000231977864270164
23483547	38815	sql query to include/exclude an item line based on the status of other lines in the order	select orderno, itemcode, status from table1 t1 where ((itemcode = 'shipping'     and exists (select * from table1          where orderno = t1.orderno          and status != 'completed')) or status != 'completed') and orderno = 111; 	0
23483942	20882	date functions in sql	select cert_date "date of last cert test",        add_months(cert_date, 6) "date due" from testing.certs where months_between(current_date, cert_date) <= 3 	0.444842675626575
23485470	10481	sql query using distinct convert to date format	select distinct datename(month, datee) as dtall from dbalarmnotice.alamnotice order by datee asc; 	0.0735105076882289
23486428	17842	to manage seasonal prices for hotel rooms	select season from price_table where str_to_date(startdate,'%d-%m-%y')>='15-03-2014' and str_to_date(enddate,'%d-%m-%y')<='17-03-2014' and room_id=1 	0.0211896831610166
23487091	25118	group concat in mysql	select     id, product, sum(quantity) quantity, group_concat(distinct id order by id) ids from     <table> group by product order by id ; 	0.497501857110882
23489801	19312	mysql union - output two single value queries into different columns	select (select count(distinct(`uniqueid`))  from `table1` ) as `t1id`, (select count(distinct(`uniqueid`))  from `table2` where `condition`='true') as `t2id` 	0
23490538	2259	getting rows of a table based on query on another table	select company.name, products.name, products.partno, products.idsgroup from company left join products on company.id = products.companyid where company.name like "$usersearch%" 	0
23491678	1666	sort of following data.	select * from mytable  order by left(myfield,5), substring_index(substring_index(myfield,'-',-1),'/',1); 	0.0374961396330873
23492604	32549	sql calculating sum based on another column	select     [account number],     sum(amount) amount from     yourtable group by [account number] 	8.15252654091236e-05
23495740	18368	how avoid negative numbers during datediff	select id  from mytbl where type = 2        and datediff(mi,my_time,left(cast(getdate() as time),5)) <= 15        and datediff(mi,my_time,left(cast(getdate() as time),5)) >=0 	0.0322838376935497
23495751	5681	fetching upto a limited condition in oracle query	select * from (select * from users order by joined desc) u where rownum<=5 	0.6576968254926
23496665	3899	getting rid of redundant rows in sql db2	select id,        max(case when test_no = 1 then result end) as test1,        max(case when test_no = 2 then result end) as test2,        max(case when test_no = 3 then result end) as test3 from my_table group by id 	0.0953733935267142
23497837	29459	use of isnull with date	select t.requireddate, isnull(t.requireddate, convert(datetime, '01/01/2013', 101))  from mytable t  where t.somekey = somevalue 	0.514897837980992
23498025	33203	sqlite 3 sum with inner join returns twice the value it should	select distinct species.species,s.count from species  inner join (     select sum(killcount) as count,trip_data.species     from trip_data     where tripid="+tripid+" and not trip_data.species =0      group by trip_data.species )s on species.speciesidno=s.species 	0.66140840648988
23499144	15809	fetching mysql via their foreign keys	select o.serial as serial, d.productid as productid, d.price as price, d.quantity as quantity, o.total as total, o.date as date from order_detail d left join orders o on o.serial = d.orderid left join billing b on b.serial = o.customerid where b.userid = '$username'; 	0.000399265714597455
23499151	32545	sum and order by on multiple tables	select userid,sum(filesize) as totalsize from files group by userid order by sum(filesize) desc 	0.0240800169704297
23500057	37796	counting likes and comments between two different table of a specific topic	select posts.id, count(comments.id) + count(likes.id) as score  from posts left join comments on posts.id = comments.post_id  left join likes on posts.id = likes.post_id  group by posts.id  order by score desc; 	0
23500104	33041	using count(*) and exists	select v1.vendor_id, v2.vendor_id v2id from vendor v1, vendor v2 where v1.vendor_id <> v2.vendor_id; + | vendor_id | v2id      | + |         2 |         1 | |         3 |         1 | |         1 |         2 | |         3 |         2 | |         1 |         3 | |         2 |         3 | + 	0.278701641769637
23500310	7347	using union, join and order by to merge 2 identical tables	select p.id_usu,p.id_cat,p.titulo,p.html,p.slug,p.fecha  ,hits.id,hits.hits,usuarios.id,usuarios.usuario from ( (select  id_usu,id_cat,titulo,html,slug,fecha ,id from posts where id_cat='".$catid."' order by id desc limit 20) union all (select  id_usu,id_cat,titulo,html,slug,fecha ,id from posts2 where id_cat='".$catid."' order by id desc limit 20) ) p join hits on p.id = hits.id join usuarios on p.id_usu = usuarios.id  order by p.id desc limit 20 	0.00982979541223245
23500494	34038	find all aggregate table entries that have ids contained in a given set	select w.*  from worker w, (     select worker_id, count(*) cnt     from worker_project     where project_id in (1,4,5)     group by worker_id ) w_count,  (     select worker_id, count(*) cnt_all     from worker_project     group by worker_id ) w_count_all where w.worker_id=w_count.worker_id and        w.worker_id=w_count_all.worker_id and       w_count.cnt=w_count_all.cnt_all 	0
23501020	10204	grouping data that has specific values	select group_concat(first_name), group_concat(last_name), concat(house_number, " ", street_name, " ", street_suffix, " ", unit_number, " ") as address, group_concat(distinct party) as parties from walksheet_1  group by address having parties in ('dem','rep'); 	0.000340005101473531
23501312	12958	load three posts by user	select u.*, p.* from user u left join (    select      p1.*    from        post p1    where         (        select           count(*)         from        post p2        where         p1.user_id = p2.user_id        and p1.id <= p2.id     ) <= 3    order by p1.id desc ) p on  u.id = p.user_id order by u.id 	0.0164467259755892
23502195	34939	select the previous business day by using sql	select .. . . and date(a.scantime) = (case weekday(current_date)                               when 0 then subdate(current_date,3)                              when 6 then subdate(current_date,2)                               when 5 then subdate(current_date,1)                              else subdate(current_date,1)                          end) .. .. 	0.000749840097189608
23502882	18509	swap values from database after performing count	select customer from tblorders group by customer order by count(*) desc limit 1 into @maxcust; update tblorders set customer = case  when 1 then @maxcust when @maxcust then 1  end  where tblorders in (1, @maxcust ); 	0.00330875688465043
23504764	14205	mysql searching for id in array from db	select * from `table` where find_in_set('2',`column_name`) >0 	0.00250663955700335
23505497	15495	sql: how do you sum he fields in one column, when a separate 2 columns fields are equal	select     m.fname,     m.lname,     m.total_paid,     x.sum(colc) as total_paid from     mytable m     inner join      (         select             fname,             lname,             sum(colc) as total_paid                     count(colc) num         from             mytable         group by             fname,             lname              having                      count(colc) > 1      ) as x on x.fname = m.fname and x.lname = m.lname 	0
23507813	14506	how to get info from a child table using pdo in php with sql?	select ul.*, ui.* from user_list ul left join user_info ui   on ui.userlist_id=ul.id where ul.id = :id 	9.27457397408274e-05
23507928	4445	showing each year income	select to_char(s.selldate, 'yyyy') year, sum(p.price) income   from sells s, products p  where p.pid = s.sellpid  group by to_char(s.selldate, 'yyyy')  order by 1 	0.000161372482614504
23509045	1852	queries mysql tables	select e.eid, e.fname, e.lname from editor e inner join edited_by b on e.eid=b.eid where b.isbn='3489374345' 	0.191763849962578
23509404	17029	mysql select rows that match multiple rows in related table	select e.exercise_name,  p.exercise_plane  from exercise_rolladex e inner join exercise_has_planes h on h.exercise_id=e.exercise_id inner join exercise_planes p on p.exercise_plane_id=h.exercise_plane_id where p.exercise_plane_id in(2,1) group by e.exercise_id having count(distinct h.exercise_plane_id ) >= 2 	0
23510721	8315	order by in mysql without asc and desc	select    *  from   book_history  order by field(`status`, 1, 0, 2) 	0.478733104421505
23510801	40149	how to search for a specific word in a column of a table in sql server that contains xml data	select * from xmlinformation where cast(xmldetail.query(' 	0
23511686	32194	getting all values based on value in another table	select * from sales  left join brick_regions on brick_regions.id = sales.brick_region  where sales.date between '2014-01-01' and '2014-03-30'  and brick_regions.region = (select region from brick_regions where id = 2); 	0
23512546	39709	getting data from a table, if it exists on another table get it from there	select   price.item,   coalesce(sp.value, price.value) from price left join sp on sp.item = price.item; 	0
23512558	15465	select clause for 3 data fields and display as 1 field	select city || ',' || road# || ',' || street# as "location" from location; 	0.000460480784102209
23513446	38018	mysql - count distinct row based on criteria in one column	select   hcp_id,  case when coalesce(sum(`status` ='false')) =0 then 1 else 0 end `all_true` from   t  group by hcp_id 	0
23513798	6029	loop through a column of a table using the row count in sqlserver	select childid from child inner join consumer on child.consumerid = consumer.consumerid 	0.000272662251870191
23520546	27675	mysql join is ignoring count in results	select      r.emailaddress,     count(*)     from property_res e     left join activeagent_matrix r      on e.listagentmlsid=r.membernumber     group by r.emailaddress     having count(*) > 1; select      e.listagentmlsid,     count(*)     from property_res e     left join activeagent_matrix r      on e.listagentmlsid=r.membernumber     group by e.listagentmlsid     having count(*) > 1; 	0.440855635683115
23521001	26323	mysql - count rows where some have more than 1 quantity	select name, sum(quantity) as total  from 'database'.oc_order_product  group by name  order by total desc; 	0.000776853330131238
23521984	35065	compare columns in a table and only show differences	select    host_name,    replace(host_environment,',','/') host_env,    host_subnet_env from     host_table where (subnet_environment = 'prod' and environment <> 'production') or (subnet_environment = 'non-prod' and environment = 'production') 	0
23521999	32091	how to sum up the time in sql access	select v.name, sum(datediff(second, v.starttime, v.endtime)) as timediffinsecs from volunteers as v inner join vol_tasks as vt     on v.name = vt.name inner join tasks as t     on v.taskcode = t.taskcode group by v.name 	0.0711403146316704
23522773	40595	select a value from table with diferent criteria sql	select idmatch, (select name from t1 where t2.idplayer1=t1.idplayer) as name1,  (select name from t1 where t2.idpalyer2=t1.idplayer) as name2,  date from calendario 	0.00026470849407434
23523530	15649	null to zero with isnull	select   name,   sum(ifnull(growth, 0))                         as sum_buy_price,   sum(ifnull(recovery, 0))                       as sum_msrp,   sum(ifnull(growth, 0))+sum(ifnull(recovery,0)) as total from   orders where   id = '$id' group by   name 	0.693805261781366
23524023	26852	set value for a new column based on group by clause	select p.productid, count(p.productid), pa.comment, min(p.isapproved) from     products p  inner join productapproval pa on p.productid = pa.productid where     p.productid = '123456' group by     p.productid, pa.comment 	0.000262003767563956
23525650	4770	is there a way to possibly put the case in the from clause?	select ab.* from ((select a.*        from stocka a        where @location = 'location a'       ) union all       (select b.*        from stockb b        where @location = 'location b'       )      ) ab 	0.366447243487319
23526133	451	generate sum for foreign key on one table and append to another in mysql	select lr.requestid, sum(la.amount) as amountpaid from loansrequest lr inner join loansaccounts la on lr.requestid = la.requestid' group by lr.requestid 	0
23526220	32249	search for substring, return another substring	select  case when instr(value, 'ia_beh_inc_num') > 0      then substr(substr(value, instr(value, 'ia_beh_inc_num'), 25),15,10)      else 'not found' end as result from example 	0.0410966476104377
23527342	38121	table inner joined to itself with sum function in the having clause	select count(distinct sfrstcr_pidm)  from    (     select sfrstcr_pidm     from   saturn.sfrstcr     where  sfrstcr_term_code = '200808'            and sfrstcr_pidm in                 (select sfrstcr_pidm                 from   saturn.sfrstcr                 where  sfrstcr_term_code = '200809')     group by sfrstcr_pidm     having sum(sfrstcr_credit_hr) >= 12   ) 	0.605472410719745
23527957	1315	mysql - select count from two tables	select count(usrtype_id) as quantity, type from user_type inner join type on user_type.type_id = type.type_id group by type 	0.00142119656944597
23528585	40690	select in many to many relations in mysql with multiple conditions	select      r.*  from recipe r join recipe_ingredients ri on ri.id_recipe = r.id_recipe join ingredients i on i.id_ingredient = ri.id_ingredient join recipes_tags rt on rt.id_recipe = r.id_recipe join tags t on t.id_tag = rt.id_tag where i.name = 'ziemniaki'     or i.name = 'cebula'   and t.tag = "tani"     or t.tag = "łatwy" group by r.id_recipe having count(r.id_recipe) > 3  ; 	0.133873664486308
23531238	32083	best way to combine these results using oracle sql?	select coalesce(a.main_id, b.main_id) as main_id,        coalesce(a.sub_id, b.sub_id) as sub_id,        a.attrib_a, a.attrib_b, b.attrib_c, b.attrib_c from tablea a full outer join      tableb b      on a.main_id = b.main_id and a.sub_id = b.sub_id; 	0.355332226054436
23533524	11885	multiple count(*) in single query	select total_rows, total_error_rows, total_rows-total_error_rows as total_success_rows  from (      select count(*) as total_rows           , count(error_code)  as total_error_rows      from table  ) as t 	0.0584019701829602
23533974	29095	sorting based on specific order sqlite	select  * from table  order by  (case when status = 'running' then 1  when status = 'pause' then 2 when status = 'new' then 3  when status = 'completed' then 4 when status = 'deleted' then 5 end), date  asc 	0.00299074460744135
23537072	891	sql query how to get data	select name, date, max(time) from mytable group by name, date order by name,date 	0.0244008807415947
23537568	13819	how to find how many are not unique from a column in mysql	select customer_id, count(*) c from net_advert group by customer_id having c > 1 	4.62799339496342e-05
23538469	36393	sql query to fetch data form another table	select `devices`.`key`  from users  join preferences on users.id = preferences.user_id join user_devices on users.id = user_devices.user_id join devices on user_devices.device_id = devices.id where preferences.monday = true 	0.000637933859770627
23538694	37272	select from 2 database remove same column	select ci_name from appwarehouse.ci_table where ci_name not in   (select affected_ci from sitequota.incidents   ) 	5.06752911486355e-05
23542661	10425	select clause with exist condition	select r.title, r.salary from ranktitle r where r.salary < (select max(s.salary) from rank s) 	0.687590346008272
23543333	5053	how can i do two groupings in single query in sql server 2008	select operated_by,        sum(case when status = 'aprove' then 1 else 0 end) as aprove,        sum(case when status = 'rejected' then 1 else 0 end) as rejected from mytable group by operated_by 	0.274402647606859
23544008	20341	querying into xml with repeating data using sql	select @xml.value('(/document/controls/control[@id = "vendor_name"]/value/text())[1]', 'nvarchar(100)') as vendor_name,        @xml.value('(/document/controls/control[@id = "vendor_number"]/value/text())[1]', 'int') as vendor_number,        r1.x.value('(control[@id = "invoice_number"]/value/text())[1]', 'int') as invoice_number,        r2.x.value('(control[@id = "description"]/value/text())[1]', 'nvarchar(max)') as description,        r2.x.value('(control[@id = "amount"]/value/text())[1]', 'nvarchar(max)') as amount,        c2.x.value('(footer/control[@id = "inv_subtotal"]/value/text())[1]', 'nvarchar(max)') as inv_subtotal,        c1.x.value('(footer/control[@id = "subtotal"]/value/text())[1]', 'nvarchar(max)') as subtotal from @xml.nodes('/document/container') as c1(x)   cross apply c1.x.nodes('row') as r1(x)   cross apply r1.x.nodes('container') as c2(x)   cross apply c2.x.nodes('row') as r2(x) 	0.0308972509160901
23544602	33938	need to modify java timestamp to get thae latest records from database	select top 1 *  from orders inner join (     select id, updated_at as modified from orders     union     select id, created_at from orders  ) as whatever on whatever.id = orders.id order by whatever.modified desc 	0
23544952	21994	mysql regroup data for chart	select x.*      , min_value      , max_value    from my_table x    join       ( select date             , min(value) min_value             , max(value) max_value           from my_table          group             by date      ) y     on y.date = x.date  order       by x.user      , x.date; 	0.251882287618126
23545181	38687	select distinct returns duplicates - no table join	select distinct ascii(substring(mytextcolumn, 99, 1)) 	0.0386100629829896
23545421	4511	tsql random value from table select in every row	select      prodcode,      prodname,      (         select top 1 itemcode          from items          where items.assortment in (102) and itemcode <> products.prodcode         order by newid(), products.prodcode     ) from products where productgroup in (102) 	0
23546579	29119	mysql grouping with search criteria	select f.name from files as f inner join (select file_id             from files_tags_associations             where tag_id in (3,5)             group by file_id             having count(*) = 2) as ft     on f.file_id = ft.file_id 	0.222901249605862
23547935	6264	adding leading zeros to a number	select lpad(last4, 4, '0') as last4 from numbers; 	0.00618974363000452
23548053	39962	add an iterator number to a column after the first 8 results	select      case          when row_number() > 7      then          row_number()-7      else          ''  end as wosequence , colum2, column3  from dbo.abc [..] 	4.60162863229607e-05
23550929	8638	northwind query with join on orders and order details	select count( distinct o.orderid) as orders from orders o join [order details] od on o.orderid = od.orderid 	0.180079231219662
23552095	21963	between clause - do i have to reorder the parameters?	select id  from mytable  where valuecol between least(:x,:y) and greatest(:x,:y); 	0.239624291703438
23552655	23155	how do i find out which columns and rows contain extended ascii codes?	select * from mytable where mycolumn<>convert(mycolumn, 'us7ascii'); 	0.000521130167033403
23553582	25565	inner join with 2 seperate queries	select dl.locid,  paramid,  alertnumexceed, upperalarm,  loweralarm,  alerton,  entryuserid,  paramorder   from     (select  locid,  paramid,  alertnumexceed, upperalarm,  loweralarm,  alerton,  entryuserid,  paramorder       from data_locparams )  dl       inner join      (select locid      from map_sites ms     inner join map_watersystems mw on mw.siteid = ms.siteid     inner join map_locations ml on mw.sysid = ml.sysid     where ms.siteid = 344 )  mq     on dl.locid = mq.locid 	0.427805868518534
23554441	13786	how do you get an amount for different locations?	select sum(s.amount) as totalamount from sometable s inner join select sum(l.amount) as locationamount from sometable l where l.loc1 = @location 	0.000650650566804907
23554733	24607	take data from next row for which keyword has been entered	select   txt from (   select 1 as level, country as txt from masterdata where continent like '$criterion'   union   select 2 as level, state as txt from masterdata where country like '$criterion'   union   select 3 as level, area as txt from masterdata where state like '$criterion'   union   select 4 as level, subarea as txt from masterdata where area like '$criterion'   union   select 5 as level, city as txt from masterdata where subarea like '$criterion' ) as abuseview order by level limit 1 	0
23554762	1138	how to get a different number each month in sql?	select @location       ,sum(x.amount) as tot_amount       ,sum(case when date_part('month', x.date) = 1 and date_part('year', x.date) = 2014 then amount end) as january_tot       sum(case when date_part('month', x.date) = 2 and date_part('year', x.date) = 2014 then amount end) as february_tot left join this_table2 y       on x.no = y.no where y.desc = 'income' and x.date between '1/1/14' and current_date 	0
23558290	2568	mysql single table summation	select    user,   sum(case when correspondant = 'a' or user = 'a' then amount else 0 end),  sum(amount) from  (select      _to as correspondant,     amount,      _from as user   from table1   union all   select     _from as correspondant,     amount,      _to as user   from table1) s group by user 	0.0522385992680089
23559055	30128	mysql join with latest update in 4 tables	select keywords_s.skeywor      , keywords_s.kid      , sites.sname      , rank.rank      , rank.url      , rank.dateon from matchon join sites on sites.sid = matchon.sid              join keywords_s on keywords_s.kid = matchon.kid              join rank on rank.mid = matchon.mid and                           rank.dateon = (select max(dateon) from rank where mid =  matchon.mid) where matchon.uid = :uid and sites.sname = :sname and sites.deactive != '1' group by keywords_s.skeyword order by rank.rank 	0.013279870616272
23560177	16398	sql server, need to get total item qty for each item for each customer within date range	select customer_name, item, unit, sum(qty) as totals from orders o inner join order_items oi    on o.id = oi.order_id where o.delivery_date between @datefrom and @dateto group by  customer_name, item, unit order by  o.delivery_date 	0
23561676	21284	mysql query return unexpected number of rows	select abc.* from abc where exists (select 1 from xyz where abc.column1 = xyz.column1) and       exists (select 1 from xyz where abc.column2 = xyz.column2); 	0.00285658470440568
23562483	16472	extracting multiple choice answers stored in single database field as integer	select customer, answer,  answer & power(2,0) pos1, answer & power(2,1) pos2, answer & power(2,2) pos3, answer & power(2,3) pos4, answer & power(2,4) pos5, answer & power(2,5) pos6, answer & power(2,6) pos7 from ( select 1 customer, 6 answer union all select 1 customer, 2 answer union all select 1 customer, 62 answer ) f 	0.00364957721890797
23563376	15812	start date and end date of current month in mysql?	select * from `table_name` where datetime_column as date between '01/01/2009' and curdate() 	0
23563931	182	how to find columns in mysql that starts with certain strings	select count(listing_id) from mytable where listing_id like 'cg_%'; 	0
23565848	12624	sql query linking tables, returning the earliest history from one table with the associated result	select a.*        a_histories.created_date from   a   inner join a_histories on a.id = a_histories.a_id   inner join (select a_id, max(create_date) as max_create_date               from a_histories               group by a_id) max_hist on a_histories.a_id = max_hist.a_id                                       and a_histories.ceate_date = max_create_date 	0
23565990	38273	query using multiple criteria on one field where all criteria has to be met	select lname, fname, trade, title, count(*) as courses from( select tblemployees.lname, tblemployees.fname, tblemployees.trade,        tblemployees.title, tbltraininghistory.date, tblcourses.coursename,        iif(isnull(courselength),"",dateadd("m",[courselength],[date])) as expirydate from tblemployees left join (tblcourses right join tbltraininghistory on       tblcourses.courseid = tbltraininghistory.courseid)         on tblemployees.empid = tbltraininghistory.empid where      (((tblcourses.coursename)        in ("confined space","manwatch","ventis mx4","first aid","cpr"))     and ((iif(isnull([courselength]),now(),dateadd("m",[courselength],[date])))>now())    and ((tblemployees.active)=true)) group by tblemployees.lname, tblemployees.fname, tblemployees.trade,        tblemployees.title, tbltraininghistory.date, tblcourses.coursename,       tblemployees.empid, tblcourses.courselength ) results group by lname, fname, trade, title having count(*) = 5  ; 	8.04956841103238e-05
23567143	38016	mysql custom select order	select * from (select * from plants order by date desc,time desc) as t group by plant 	0.529801288340034
23568264	28183	ssrs top 20 for multiple locations	select  [location] ,[item no_] ,totalquantity from ( select      [location]     ,[item no_]     ,sum(-[quantity])                       as  totalquantity     ,row_number()         over (partition by [location code]          order by sum(-[quantity]) desc)     as rn from      [ledger entry]     left join [item] i      on  [ledger entry].[item number] = i.no_ where    [date] between @startdate and @enddate group by     [location code]   ,[item no_]  ) as subquery where rn <= 20 	0.0184266688095433
23568921	7846	how to return null value if no record found on joined table	select rep.rpt_id ,tech.tech_id ,proc.proc_id from report rep left join technician tech on tech.rpt_id = rep.rpt_id left join procedure proc on proc.rpt_id = rep.rpt_id and proc.proc_id = tech.proc_id where rep.lab_id in ('test_lab'); 	0
23569209	4999	sql pivot - adding another column	select t.workdate ,sum(case when t.par='cr' then t.qty else 0 end) as cr ,sum(case when t.par='cr' then t.laborhrs else 0 end) as crhours ,sum(case when t.par='er' then t.qty else 0 end) as er ,sum(case when t.par='er' then t.laborhrs else 0 end) as erhours ,sum(case when t.par='et' then t.qty else 0 end) as et ,sum(case when t.par='et' then t.laborhrs else 0 end) as ethours ,sum(case when t.par='yd' then t.qty else 0 end) as yd ,sum(case when t.par='yd' then t.laborhrs else 0 end) as ydhours group by t.workdate from [tablename] t 	0.0413771275802253
23569634	29817	how to find lowest count of rows for a value in sql server 2005	select top 1 username, count(*)  from mytable  group by username  order by count(*) asc 	0
23569752	12248	get extra rows for each group where date doesn't exist	select    s.emp_name as name   ,s.number as m    ,st.salestotal as amount from (   select distinct emp_name, number   from salestotals, numbers    where number between 1 and 12) s left join salestotals st on      s.emp_name = st.emp_name and s.number = month(st.yearmonth) 	5.51886747886316e-05
23570197	33647	how can i grab the record set from a join with the most recent datestamp?	select       robinson_rigs.rigid     , robinson_rigs.rigname     , robinson_clients.companyname     , robinson_wells.wellname     , robinson_wells.county     , robinson_wells.startdate     , robinson_wells.directions from robinson_wells     join robinson_rigs on robinson_wells.rigid = robinson_rigs.rigid     join     (         select rigid             , max(startdate) as mostrecentdate         from robinson_rigs         group by rigid     ) latestrigdate on robinson_rigs.rigid = latestrigdate.rigid         and robinson_rigs.startdate = latestrigdate.mostrecentdate     join robinson_clients on robinson_wells.clientid = robinson_clients.clientid order by robinson_rigs.rigid 	0
23570621	2210	window query for counting subsections	select     region.id,     count(*) as total_jobs,     count(job = 'janitor' or null) as "janitor"     count(job = 'repair' or null) as "repair" from     region_center     inner join     region on st_dwithin(region_center.geom, region.geom, 2640) group by region.id; 	0.737321658328844
23572314	11365	using joins to retrieve data twice	select      c1.countries_id as delivering_id,     c2.countries_id as billing_id from orders o left join countries c1      on c1.countries_name = o.delivery_country left join countries c2      on c2.countries_name = o.billing_country where o.orders_id = 1208; 	0.039312615045853
23572792	37513	ranking mysql and query for one people	select * from ( select    id,punkty,           @currank := @currank + 1 as rank from      users p, (select @currank := 0) r order by  punkty desc   ) t where id='6'; 	0.0241544497987537
23574077	27816	sql - dividing by sum by group	select * from (select sum(case when cd.date_value >= s.entrydate and cd.date_value <= current_timestamp                       then cd.insession                      else 0                  end), s. student_number       from calendar_day cd cross join            students s       where cd.schoolid = 405       group by s.student_number      ) sc join      (select s.student_number, s.lastfirst,              sum(case when a.attendance_codeid = 2 then 1 else 0 end),              sum(case when a.attendance_codeid = 4 then 1 else 0 end),              sum(case when a.attendance_codeid = 3 then 1 else 0 end),              sum(case when a.attendance_codeid = 51 then 1 else 0 end)       from attendance a inner join            students s            on a.studentid = s.id       where a.att_date between '%param1%'  and  '%param2%'       group by s.student_number, s.lastfirst      ) sa      on sc.student_number = sa.student_number; 	0.162221033201883
23574375	36066	limit sql results to one result per pkey searched using "in"	select h.* from `history` as h inner join (select `pkey`, max(`time`) as maxtime             from `history`             where `pkey` in (13309, 13311, 13951, 14244, 1500,                               15558, 15691, 15938, 9769)             group by `pkey`) as t     on h.`pkey` = t.`pkey`     and h.`time` = t.`maxtime` 	0.0119931767345354
23576183	35397	sql join several tables based on latest entry in transaction table per join record	select   eventtable.evtname as evtd,   transtable.tranact as lasttrans,   usertable.username as usrnm, from   transtable   inner join (     select evid, max(uid) uid from transtable group by evid    ) last on last.evid = transtable.evid and last.uid = transtable.uid   inner join eventtable on eventtable.evid = transtable.evid   inner join usertable on usertable.usid = transtable.usid 	0
23577480	9621	rows to column conversion sql query sql server	select formattype, [true], [false], [blank], [true] + [false] + [blank] as total from (     select formattype, result     from table1 ) as sourcetable pivot (     count(result)     for result in ([true], [false], [blank]) ) as pivottable 	0.134871274202057
23577859	21497	sql query records containing all items in list	select m.title  from movie m      inner join direct md      on md.movie_id = m.movie_id      inner join directors d      on md.director_id = d.director_id where       d.name in('clint eastwood', 'al pachino') group by m.title having count(distinct d.director_id) = 2; 	0.000111797445
23579477	16709	improve this query to fetch data from different tables	select a.*,     coalesce(b.name, c.name),     coalesce(b.field1, c.field1),    coalesce(b.field2, c.field2) from events a ... 	0.0303405702286311
23580379	26732	unknown column 'posts.id' in 'field list'	select      `posts`.`id` as `post_id`,      `categories`.`id` as `category_id`,     `title`,      `contents`,      `date_posted`,      `categories`.`name` from      `posts`         inner join `categories`              on `categories`.`id` = `posts`.`cat_id` order by      `posts`.`id` desc 	0.0298512392081217
23582860	9224	sqlite select query summarizing values	select name || ' ' || surname as playername,        age,        (select sum(games_won) from team where player1id = playerid or player2id = playerid) as total from player ; 	0.126152535589303
23583881	29410	mysql orders by category by month	select '2014-01' month , sum(case when order_category = 'hardware'                          then 1 else 0 end )as hardware,                              sum(case when order_category = 'bedding'                          then 1 else 0 end )as bedding   from table1   where month(order_date) = 01 and  year(order_date) = 2014   union all    select '2013-12' month , sum(case when order_category = 'hardware'                          then 1 else 0 end )as hardware,                             sum(case when order_category = 'bedding'                          then 1 else 0 end )as bedding   from table1   where month(order_date) = 12 and  year(order_date) = 2013 	0.000124856924186292
23586991	7000	is there a way to do a multi table query and get result just from specific tables?	select a.id, a.column1, b.column2  from table1 a  left join table2 b on a.id = b.otherid; 	0.000128593820307837
23587511	27147	date repeating twice in php for each loop	select      id,      max(end_date) as max_end_date  from      thetable  group by      id  where      id in (<outer query goes here>) 	0.000492293479669772
23588788	14751	mysql select with an extra column containing a string	select id, col1, col2, '12:48' as tempcol 	0.043647971275274
23588991	36778	mysql select all days by grouping a year in each month	select year(`date`) as `year`,        max(case when month(date) = 1 then day(`date`) end) as jan,        max(case when month(date) = 2 then day(`date`) end) as feb,        max(case when month(date) = 3 then day(`date`) end) as mar,        max(case when month(date) = 4 then day(`date`) end) as apr,        max(case when month(date) = 5 then day(`date`) end) as may,        max(case when month(date) = 6 then day(`date`) end) as jun,        max(case when month(date) = 7 then day(`date`) end) as jul,        max(case when month(date) = 8 then day(`date`) end) as aug,        max(case when month(date) = 9 then day(`date`) end) as sep,        max(case when month(date) = 10 then day(`date`) end) as oct,        max(case when month(date) = 11 then day(`date`) end) as nov,        max(case when month(date) = 12 then day(`date`) end) as dec from table t group by year(date) order by year(date) 	0
23589886	29743	grouping data in ms access 2010 based on multiplication	select     sum(principal_paid),     days_range   from     (       select         principal_paid,         case days           when between 0 and 30           then '0-30'           when between 31 and 60           then '31-60'           when between 61 and 90           then '61-90'           when between 91 and 120           then '91-120'           when between 121 and 150           then '121-150'           else 'over 150'         end as days_range       from         yourtable     )     as t   group by     days_range 	0.144790961674572
23591457	21467	sqlite : how to merge column into one row select	select id_boss,         min(id_child) as id_child1,        max(id_child) as id_child2 from your_table group by id_boss 	0
23591931	7755	sqlite : select statement from multiple table and merging column	select (select value from table1 where table1.id_table1 = r1.id_boss) as id_boss,        coalesce( (select value from table1 where table1.id_table1 = r1.id_child),                  (select value from table2 where table2.id_table2 = r1.id_child)                ) as child_t,        coalesce( (select value from table1 where table1.id_table1 = r2.id_child),                  (select value from table2 where table2.id_table2 = r2.id_child)                ) as child_f   from r_table as r1 join r_table as r2     on r1.id_boss = r2.id_boss and r1.id_child <> r2.id_child and r1.answ = 't' ; 	0.00113289377705413
23592112	24435	mysql query - how to sum data by total, current year and last 12 months in the same query (1 sum by collum)?	select wp_postmeta.meta_value as tipo de aeronave       , count(wp_posts.id) as total       , count( case when year(wp_posts.post_date) = year(current_date)                      then 1                 end ) as tot_curr_yr       , count( case when wp_posts.post_date >= (current_date - interval 12 month)                     then 1                end ) as tot_last_12_months  from wp_postmeta  left join wp_posts     on wp_postmeta.post_id = wp_posts.id  where wp_posts.post_type = 'ocorrencia'    and wp_posts.post_status = 'publish'     and wp_postmeta.meta_key = 'tipo_de_aeronaves_envolvidas'   group by wp_postmeta.meta_value 	0
23595543	4975	mysql datetime to second function	select  * from table_name order by   unix_timestamp(message_datetime) / like_number 	0.0545961279013232
23596027	38990	multiples of a number oracle sql	select * from num_w where mod(n_id,2) = 0; 	0.00677491099208777
23596707	30071	select from table based on select distinct from another table	select hid, name, location from table2 inner join table1 on table1.hid = table2.hid group by table2.hid; 	0
23597495	15392	get first row in oracle sql	select * from ( select distinct name, age  from donates, persons  where name = donor   and name in (select receiver from donates)  order by age desc ) where rownum <= 1; 	0.000878547702049421
23599182	40224	relation mysql table , create an array column in my table java eclipse	select * from player where id_team = 5 	0.26573240418505
23599460	40929	sqlite : select statement and show `null` value too	select (select value from table1 where table1.id_table1 = r1.id_boss) as id_boss,     coalesce( (select value from table1 where table1.id_table1 = r1.id_child),               (select value from table2 where table2.id_table2 = r1.id_child)             ) as child_t,     coalesce( (select value from table1 where table1.id_table1 = r2.id_child),               (select value from table2 where table2.id_table2 = r2.id_child)             ) as child_f from r_table as r1 , r_table as r2  where r1.id_boss = r2.id_boss and r1.answ = 't'  and r2.answ = 'f'; 	0.193738370514038
23599780	14855	get only the max create date from the same table	select      i.createdate     ,i.fullname     ,i.email from (     select          t.createdate         ,t.fullname         ,t.email         ,row_number() over (                             partition by t.email                              order by t.fullname                            ) seq     from userdata t         inner join (                     select                          email                         ,max(createdate) as maxdate                     from userdata                     group by email                     ) tm             on t.email = tm.email                 and t.createdate = tm.maxdate     ) i where i.seq = 1 	0
23600188	25697	count from several columns oracle sql	select f.fruit, sum(f.cnt) as cnt   from ( select d.fruit1 as fruit, count(1) as cnt from fruits d group by d.fruit1            union all          select e.fruit2 as fruit, count(1) as cnt from fruits e group by e.fruit2        ) f  group by f.fruit  order by f.fruit 	0.00424578377499049
23600619	34441	concat varchar2 fields in oracle db	select trim(user.pname || ' ' || user.fname) as "name" 	0.185987440181088
23600757	11823	exeception query id	select * from users where id not in (1, 2) 	0.117517549510145
23601701	17365	using multiple values in strtomember	select strtoset  ('{[geography].[geography].[country].[germany],[geography].[geography].[country].[canada]}')  on 0     from [adventure works] 	0.0930409873134671
23602487	8749	select duplicate combination of columns in oracle	select tran_date, foracid, tran_particular, part_tran_type, tran_amt, count(*) as counts  from tbaadm.htd, tbaadm.gam  where gam.acid=htd.acid and tran_particular like '%fee%'    and tran_date between '03-mar-2014' and '11-mar-2014'   and htd.acid in (select gam.acid from tbaadm.gam where gam.acct_ownership <> 'o') group by  tran_date, foracid, tran_particular, part_tran_type, tran_amt having count(*) > 1 order by 2 desc; 	0.000994183958479323
23602505	31672	sql two "group by" in the same query	select     product_tracking.user_id,     sum(case when product_tracking.product='a' then 1 else 0 end) as a,     sum(case when product_tracking.product='b' then 1 else 0 end) as b,     sum(case when product_tracking.product='c' then 1 else 0 end) as c from     product_tracking group by     product_tracking.user_id 	0.00850924730722742
23602771	34510	mysql select count from multiple tables	select job.id, job.name, count( * ) as 'employee count' from job left join employee  on job.id = employee.job_id group by job.id 	0.0050677680025608
23603031	23609	how do i display non duplicate values in a table in oracle?	select id, listagg(phone, '; ') within group (order by id) phone_list from ( select distinct id, phone from customers unpivot include nulls (phone for phonetype in  (phone1, phone2, phone3, phone4, phone5, phone6, phone7, phone8)) ) group by id 	5.84522044342439e-05
23604379	26082	if statement in sql	select user_id,score,min(time) as mintime from (select user_id,max(score) as score,time from table  group by user_id, time ) t group by user_id,score order by score desc limit $startlimit,$numperpage 	0.613786416164413
23604530	39749	mysql: accumulate occurrences of each specific value in a field	select e.*,        (select count(*) from `events` as e2         where e2.country = e.country        ) as times,        (select count(*) from `events` as e3         where e3.country = e.country and e3.id <= e.id        ) as accumulated from `events` as e 	0
23604788	13355	check whether record exists, if not return id (mysql)	select idlist.id from (   select 1 as id   union all select 2    union all select 3    union all select 4    union all select 5    union all select 6  ) as idlist left join the_table   on idlist.id = the_table.id where the_table.id is null; 	0.000131980785073103
23608118	4197	select only and only specific record in oracle	select truck from   table where  location in (1, 2) group by     truck having count(distinct location) = 2 	0.000114070866634189
23608689	28684	find the size of database ldf file	select      [servername] = @@servername,     [databasename] =  instance_name,     datasizeinkb = sum(case when counter_name = 'data file(s) size (kb)' then cntr_value end),     logsizeinkb = sum(case when counter_name = 'log file(s) size (kb)' then cntr_value end) from      sys.dm_os_performance_counters where      counter_name in ('data file(s) size (kb)', 'log file(s) size (kb)')     and instance_name <> '_total' group by      instance_name; 	0.00228263738655695
23609203	1196	mysql only showing posts if user is subscribed to group	select postid, postmessage  from posts  inner join mygroups  on posts.groupid = mygroups.groupid  where mygroups.userid = *theusersuserid* 	0.00165395458360413
23609359	24462	how to select multiple columns within subquery in mysql	select     sum(column) from     table1 where     id in (select col1 from table2 union select col2 from table 2) 	0.0297550675917241
23610642	24300	how to combine multiple table headers columns into 1 list	select name into output.header_list from syscolumns where id in (object_id('input.table1'), object_id('input.table2'), ....); 	0
23611168	28324	match any of the combinations of the word	select count(*) from mytable where lower(mytable.login) = lower('vlajko'); 	0.000105064365049722
23611838	25451	grouping multiple selects within a sql query	select supplier      , sum(case when date >= cast('2014-05-12' as date) then totalstock end) as stockthisweek      , sum(case when date >= cast('2014-05-01' as date) then totalstock end) as stockthismonth      , sum(case when date >= cast('2014-01-01' as date) then totalstock end) as stockthisyear from  stockbreakdown group by supplier 	0.339753977265889
23612664	31140	how do you list all tables and their foreign + primary keys in a sql query?	select     tablename = t.name,     indexname = i.name,     fkname = fk.name,     referencedtable = reft.name from      sys.tables t left outer join      sys.indexes i on i.object_id = t.object_id and i.is_primary_key = 1 left outer join      sys.foreign_keys fk on fk.parent_object_id = t.object_id left outer join      sys.tables reft on fk.referenced_object_id = reft.object_id order by     t.name, i.name 	0
23612830	3021	selecting rows that have certain number of specific type of character in a column	select * from   my_table where  len(col1) - len(replace(col1, ',', '')) = 5 	0
23614910	36694	different user, friendships and selection	select u.email, count(u.email)  from user u  inner join friendship f on f.user1_email = u.email or f.user2_email = u.email  group by u.email  having count(u.email) < 3 union select u.email, 0 from user u where u.email not in (select user1_email from friendship)  and u.email not in (select user2_email from friendship); 	0.0193909268208875
23616176	5486	how to get sum from two child tables	select    distinct f.forecast_id, (select sum(e.amount) from expense e where e.forecast_id = f.forecast_id ) as expense,  (select sum(i.amount) from income i where i.forecast_id = f.forecast_id ) as income from    forecast f where     f.forecast_id = 721 	0
23618566	11713	sql order by complex sort	select   p1.*, groups.gmaxdescr from parts p1 inner join    (select      p2.part as gpart,      p2.locker as glocker,      p2.serial as gserial,      max(p2.descr) as gmaxdescr    from parts p2    group by part, locker, serial   ) as groups          on p1.part = groups.gpart       and p1.locker=groups.glocker       and p1.serial=groups.gserial order by groups.gmaxdescr desc,          part desc,          locker desc,          serial desc 	0.77056526470175
23618690	9011	merge sql results in one column	select tb2.customer_no, tb2.last_name || ' ' || tb2.first_name name from ccare.customer tb2 where tb2.customer_no = '1000647' 	0.00347175028859776
23618835	4703	how do i find records in a database that associate on on key and don't include a certain value on any of them?	select lit.line_origin_key from bills_table bt inner join line_items_table lit     on bt.bill_key = lit.bill_key where bt.bill_status = 1  and bt.bill_code = 2  and not exists( select 1 from lines_origin_table                  where line_origin_key = lit.line_origin_key                 and [type] = 'c') 	0
23618959	35935	choose row based on max date (multiple tables)	select maxfromdate.service_id, correct_account.accountservice_id, maxfromdate.maxfromdate from (select      service.service_id,      max (accountservice.fromdate) as maxfromdate      from service      join accountservice on service.service_id = accountservice.service_id)      group by service.service_id) maxfromdate join (select      service.service_id,      accountservice.accountservice_id,      accountservice.fromdate      from service      join accountservice on service.service_id = accountservice.service_id )correct_account on      (maxfromdate.service_id = correct_account.service_id        and maxfromdate.maxfromdate = correct_account.fromdate) 	0
23619128	36989	counting the number of different values in a mysql column	select [column_name], count([column_name]) from [table_name] group by [column_name]; 	0
23622780	4593	ordering and grouping records together	select a.* from mytable a join mytable b   on a.recordid=b.recordid  and b.parent=1 order by b.total,b.recordid,a.parent desc 	0.0304148726318633
23623033	16419	linking three tables sql	select t.id,case when tt.stablerecords is null then 0 else tt.stablerecords end as stablerecords,case when tt.expiredrecords is null then 0 else tt.expiredrecords end as expiredrecords from towns t left join (select ph.id, count(case when pr.status='stable' then 1 end) as stablerecords, count(case when pr.status='expire' then 1 end) as expiredrecords from patientsrecords pr inner join  patientshome ph on ph.serial_number=pr.serial_number group by ph.id ) as tt  on t.id=tt.id 	0.0263978999351318
23625671	23332	how to write a query	select count(*) from tbl a where dependentid = 0 and (     a.[active flag] = 'y'         or exists (         select 1          from tbl b          where b.basequestionid = a.id         and b.[active flag] = 'y'      ) ) 	0.506587966113912
23627958	40060	how to write a query for getting free seats in a hostel	select b.roomid,   b.numberseats,   count(a.student) from rooms b left join contracts a on a.room=b.roomid group by b.roomid,   b.numberseats having b.numberseats>count(a.student); 	0.248970965758574
23629735	7059	add new column to an existing table with addition	select productid, sum(qty) as totqty from tmpprch group by productid; 	0.005518175781187
23631649	13718	how to get three records based on agentid and rank in mysql	select t2.* from yourtable t1 join yourtable t2 on abs(t1.rank - t2.rank) <= 1.5  where t1.agentiid = 2 	0
23632428	29246	calculate the average of several marks excluding null values	select      (         select coalesce( nb1, 0 ) + coalesce( nb2, 0 ) + coalesce( nb3, 0 ) as addition     )     /     (         select          coalesce(nb1 /nb1, 0)         +          coalesce(nb2 /nb2, 0)         +          coalesce(nb3 /nb3, 0)         as divideby     ) as avg from yourtable 	0
23633372	36338	how could one duplicate the same environment configuration as a database server?	select current_setting(name), *   from pg_catalog.pg_settings 	0.000674931070714834
23633790	16597	sql "splitted" group by	select     animal,     sum(case when flg = 'a' then v1 else 0 end) as a_v1,     sum(case when flg = 'a' then v2 else 0 end) as a_v2,     sum(case when flg = 'b' then v1 else 0 end) as b_v1,     sum(case when flg = 'b' then v2 else 0 end) as b_v2 from     mytab group by     animal 	0.61340064311582
23634984	18695	multiple column selcet in sqlite in one query android	select uname from alldata where id= (select id from searchtable where latinnames ="ahmad") 	0.0908781290646619
23635970	38606	apply computation and return as another row without union	select id, table1.intvalue * val.n, date from table1 cross join (values (5), (10), (15)) val(n) 	0.00779154233724549
23636681	7488	(oracle) returning 00 in data conversion	select to_char(to_date('14-05-13','rrrr-mm-dd'),'rrrr') from dual; 	0.60126380518347
23637585	15324	how can i pull latest posts, with unique authors, so that if an author wrote two posts in a row, it only gets the first?	select author, maxts, etc  from sometables join  (select authorid, max(timestamp_field) maxts  from etc  where whatever  group by authorid) temp on temp.authorid = author.authorid  and sometable.timestamp_field = maxts  where whatever 	0
23638202	15861	mysql query multiple tables	select t2.num_id from tbl1 t1, tbl2 t2 where t1.bar_id = number     and t1.foo_id = t2.foo_id     and t2.bool = 1 	0.177305444517246
23640775	24529	mysql fetch record with find_in_set	select  subject, group_concat(distinct teacher_name) as teacher_name, group_concat(distinct student_name) as student_name from (   select   s.name as subject,   t.name as teacher_name,   st.name as student_name   from    subject s   left join teacher t on find_in_set(s.id,t.subject)   left join student st on find_in_set(s.id,st.subject) )x group by subject; 	0.0204517559538883
23640828	5011	update single column found in multiple tables	select 'update ' + table_name + ' set customer= ''newcustomervalue'' where customer=''xxxx''' from information_schema.columns  where column_name = 'customer' 	0.00333932932040739
23641474	12967	how do i total and display a total for the game colums in mysql	select   mom_rebels_cms.log.age,   mom_rebels_cms.log.team,   mom_rebels_cms.log.last_name,   mom_rebels_cms.log.number,   mom_rebels_cms.log.game_1,   mom_rebels_cms.log.game_2,   mom_rebels_cms.log.game_3,   mom_rebels_cms.log.game_4,   mom_rebels_cms.log.game_1 +   mom_rebels_cms.log.game_2 +   mom_rebels_cms.log.game_3 +   mom_rebels_cms.log.game_4   as tourneysum  from   mom_rebels_cms.log 	0
23641740	753	sql server query for distinct rows	select mindate, count(*) as numnew from (select custid, min(date) as mindate       from table t       group by custid      ) c group by mindate 	0.0893775369921105
23641823	31681	check if a role in postgresql has a password set	select * from pg_shadow; 	0.135675617750853
23642167	4848	sql xpath query	select xtab.my_attr, xtab.my_attr_values from my_table jx, xmltable('for $i in /root/a/b return element r { $i/../@attr, $i/. }'  passing jx.field_xml columns my_attr path '@attr',  my_attr_values path 'b')xtab; 	0.772644908490949
23642414	33498	merging two select queries' results in one row result	select emp.*,prd.*  from employee emp  inner join products prd on emp.employee_id = prd.id limit 1 < 	7.98843533540211e-05
23643007	33808	php variables to get a single answer	select players.fullname, seasonteam.teamid, seasonstats.sea, seasonstats.gp,        sum(seasonstats.goals) as totalgoals, sum(seasonstats.assists) as totalassists,        sum(seasonstats.points) as totalpoints, seasonstats.pim,  seasonstats.plusminus,        seasonstats.pp, seasonstats.sh, seasonstats.gw, seasonstats.gt,   seasonstats.s,        players.playerid from seasonteam left join (players left join seasonstats on players.playerid = seasonstats.playerid) on seasonteam.teamid = seasonstats.teamid where seasonteam.teamid=$iteamid group by players.playerid; 	0.00598124397618502
23643205	14813	get count of multiple column occurrences in sql	select      count(*), agent, un from        tbl group by    agent, un order by    1 desc 	0.000124859013804061
23643352	18431	how do i exclude data based on column values in sql?	select name from tbl   group by name  having count(questioncd) = 5 	0
23643506	13916	sql query: not able to add a column from another table	select       t.testid,      t.days,       t.userid_fk         , [date] = convert(date,dateadd(dd, 0, datediff(dd, 0, t.checkin)))     , checkin = convert(char(5), t.checkin, 108)     , checkout = convert(char(5), t.checkout, 108)     , [hours] = cast(datediff(minute, t.checkin, t.checkout) / 60. as decimal(10,2))     from     (select *     from test     join users     on test.userid_fk=users.userid) t     outer apply (         select top 1 *         from usertime t2         where              t2.checkintime > t.checkintime             and dateadd(dd, 0, datediff(dd, 0, t.checkintime)) = dateadd(dd, 0, datediff(dd, 0, t2.checkintime))             and t2.loginstatus = 'o'         order by t2.checkintime             ) r         where t.loginstatus = 'i'      ) t     where t.rownum = 1 	0.000965464675383773
23643976	35783	union 2 column and another column from another table	select f.from_id as friend_id, u.user_profile_picture as profile_picture, f.created_date as time    from friends f    inner join users u on u.user_id = f.from_id    where f.to_id = :user_id1 and f.accepted = 1    union    select t.to_id  as friend_id, u2.user_profile_picture as profile_picture, t.created_date  as time    from friends t    inner join users u2 on t.to_id = u2.user_id   where t.from_id = :user_id2 and t.accepted = 1 	0
23644609	9173	how to select records of a certain format in ms sql server	select ein.edl_employeeid, ein.edl_logdate, ein.edl_logtime as [out], eout.edl_logtime [out] from t_employeedtrlogs ein inner join t_employeedtrlogs eout on ein.edl_employeeid = eout.edl_employeeid and ein.edl_logdate = eout.edl_logdate where ein.edl_logtype = 'in' and eout.edl_logtype = 'out' 	0.000209508256464013
23644654	14949	sqlserver:select and group by month	select month (pc.createtime) as month,        sum(case when pl.partsmodelid = 21028 then partsmodelsum end) as totalsum from partscontract pc left join      partscontractlinkmodel  pl      on pl.partscontractid = pc.partscontractid and         pc.companyid = 8 and         pc.createtime between '2013/11/01 00:00:00' and '2014/04/30 23:59:59' group by     month(pc.createtime) order by totalsum desc; 	0.0207039065804014
23650067	7380	split column value at delimiter	select    regexp_substr(column, '[^.]+', 1, 1) as account , regexp_substr(column, '[^.]+', 1, 2) as grpid , regexp_substr(column, '[^.]+', 1, 3) as org , regexp_substr(column, '[^.]+', 1, 4) as rel from your_table 	0.000376328377722246
23650246	6491	get specific entry in case of duplicate entry	select userid, first name, last name, isrequired, isdeleted from table where userid in (select userid from users group by userid having count(distinct(isrequired)) > 1) and isrequired = 'true' union select userid, first name, last name, isrequired, isdeleted from table where userid in (select userid from users group by userid having count(isrequired) = 1) 	0
23652407	1414	how to convert numeric date to textual display in oracle?	select to_char (column_name,'hhsp:mispth am ddspth/mmspth/yyyyspth')  from table 	0.00149752631075474
23654013	27138	how to get array of latest auto incremented id's?	select * from exp_channel_titles order by id desc limit x 	0
23654714	9835	sql selecting with 2 entries in 1 table	select name   from t  where course in('bio', 'maths')  group by name  having count( distinct course ) = 2 	8.42759275539637e-05
23655633	22045	php search form display incorrectly?	select * from properties as prop left join images as img on img.propertyid = prop.propertyid where **** your condition **** order by ** (desc or asc) 	0.0686110868502481
23655862	39863	querying mysql database for unique counts of column values	select question_id,        answer,        count(*) as answercount    from poll_answers    group by question_id, answer     order by question_id, answercount desc 	0.000142260236102121
23656686	37234	sql query unique equipment list	select e.equipmentid,         e.stationeventid,         e.eqpartno,         e.eqlocation,         e.eqcalexpires,         max(e.eqrecupdated) from equipment e inner join station_events se on se.stationeventid=e.stationeventid where se.stationid='1' group by eqpartno,eqlocation 	0.0515608179125243
23656753	36748	filter sql results by highest number in column	select *    from table  where reportnumber in (select max(reportnumber)                            from table) 	0.000218397398055353
23657180	31936	self-referencing mysql table	select c1.id, c1.name, c1.columntype, group_concat(c2.columntype order by c2.columntype) as refer_type from columns as c1 left join columns as c2 on c1.id = c2.refer_type group by c1.id order by c1.id 	0.147689166164614
23657556	33234	how to select 2 distinct columns and count one of them	select t.question,        t.answer,        count(*) as 'count' from yourtable as t group by t.question,          t.answer 	0
23659168	25466	mysql: get data from two tables relationed by an id	select 'normal' as name, price from products   where id = 5 union select name, price from presentations   where id_product = 5 	0
23659899	17648	oracle sql date time inquiry	select * from sysadm.ps_is_stats_urls where userid = 'zx08067' and descr254 = 'tools and calculators' and datetime_stamp = (to_timestamp('22/06/2012 16:26.03.589868', 'dd/mm/yyyy hh24:mi.ss.ff')) 	0.250548911002774
23660093	23701	sql multiple select rows	select * from tablename where name in (select name                from tablename                where value=1) 	0.02267918998877
23660762	4970	query multiple values from one column	select count (*) as newcol   from table1   where col1 = 'val1'     and col2 = 'val1'     and (col3 = 'val1' or col3 = 'val2')       ; 	0.000419216668520193
23660844	27674	decimal data type in oracle	select to_char(1234.4, 'fm9999999.00') from dual;  select to_char(1234.45, 'fm9999999.00') from dual;  select to_char(1234,'fm9999999.00') from dual; select to_char(1234.4567, 'fm9999999.00') from dual; 	0.123575100346545
23661202	2143	sql query combine rows on id	select quote_number,         datediff(hh,                 max(case when status = 'submitted' then dateentered end),                 max(case when status = 'accepted' then dateentered end)                ) as hour_difference from status_history where status in ('submitted','accepted') group by quote_number; 	0.00174730689523796
23662366	3251	when to add calculated custom columns to a query - right away or by using a join	select systemname, caption, label, capacity, freespace,        100*freespace/capacity [% of free space],        capacity-freespace [used space] from ccs_win32_volume order by systemname, caption 	0.552447638834746
23662457	32240	mysql left join and no satisfied match in the joining table	select *  from vehicle  left join vehicle_insurance as ins on vehicle.id=ins.vehicle_id and ins.effective<='{$date}' and  ins.expires>='{$date}' where vehicle.id='{$vid}' 	0.0799834000590176
23662689	17161	split mysql regex into multiple lines	select * from table.ips where ipip not regexp concat(     '^4\\.|',     '^8\\.|',     '^12\\.|',     '^18\\.' ) 	0.00637401758091577
23662701	36047	mysql select two different queries	select rn, max(basetype) as basetype, max(itemid) as itemid from ((select @rn := @rn + 1 as rn, basetype, null as itemid        from table1 cross join             (select @rn := 0) var        where name = 'test'       ) union all       (select @rn2 := @rn2 + 1, null, itemid        from table2 cross join             (select @rn2 := 0) var        where itemid = '5'       )      ) t group by rn; 	0.00908631897611642
23663423	12500	using having with count to restrict results	select teacher from students  group by teacher having count(student) > 3 	0.423186158065348
23663922	1949	how to return the "table.column" name on mysql?	select test1.id as `test1.id`, test2.id as `test2.id` ... 	0.0137119580675757
23665276	4919	mysql: select id if not repeated exactly 4 times	select id_product, count(*) from <table> group by id_product having count(*) < 4 	0.00236737796188489
23665851	40919	removing duplicates from sql query	select *   from tbl t  where t.label = (select x.label                     from tbl x                    where x.primary = 'y'                      and x.id = t.id)     or (not exists         (select 1            from tbl x           where x.primary = 'y'             and x.id = t.id) and         t.label = (select min(x.label) from tbl x where x.id = t.id)) 	0.0942416755512054
23667222	33187	select from a select statement from a defined value	select   * from     table where    date < (select date from table where id = 1) order by date desc limit    3 	0.000752238835474108
23668736	4325	mysql - single criteria for multiple columns within single table - mysql	select * from t1 where concat(id, f_name, l_name, .....) like '%criteria%' 	0.000127624728605156
23668987	38701	how to check if a value exists in multiple tables	select count(*) from (select emp_id from table_1  union  select emp_id from table_2) t where t.emp_id = <id_value> 	0.0012599621400561
23669868	31425	replacing string in sql query	select     (case     when myplan = 'true , true , true'     then 'breakfast, lunch, dinner'     when myplan = 'true , true , false'     then 'breakfast, lunch'     when myplan = 'true , false , false'     then 'breakfast'     when myplan = 'true , false , true'     then 'breakfast, dinner'     when myplan = 'false , false , true'     then 'dinner'     when myplan = 'false , true , true'     then 'lunch, dinner'     when myplan = 'false , true , false'     then 'lunch'     else ''     end) myplan from mytable 	0.410124591464303
23670638	4935	sql sorting date how to	select min(id), date from table_name group by date; 	0.07912363290456
23672731	7487	sql select from three tabled and foreign key	select * from (application_table inner join appxserv on application_table.id = appxserv.app_id)  inner join service_table on appxserv.serv_id = service_table.id  where appname = "app1" 	0.000772625831027795
23672990	13871	get data from table using group by	select a.*     from emptbl a         inner join     emptbl b         on  substring(a.emptype, 2, 4) = substring(b.emptype, 2, 4) and         substring(a.emptype, 1, 1) <> substring(b.emptype , 1, 1) 	0.00108361536335216
23673988	16248	selecting record where string value begins with number	select * from productmanufacturers where name like '[0-9]%' 	0
23674488	32591	sql sum all values in col x for values smaller than value of x in this row	select c1,        max(c2) as c2 from (      select c1,             sum(c2) over(order by c1 rows unbounded preceding) as c2      from yourtable      ) t group by c1; 	0
23675569	31104	mysql query not returning true values as concatenated string	select concat_ws( ',',                      if(a = 0, null, concat('a:', a)),                      if(b = 0, null, concat('b:', b)),                      if(c = 0, null, concat('c:', c)),                      if(d = 0, null, concat('d:', d)),                      if(e = 0, null, concat('e:', e)) ) where id=5 	0.0521303064381547
23675898	27287	sql select multiple keys/values	select person_id from person_properties group by person_id having sum(case when key = 'fname' and value = 'robert' then 1 else 0 end) > 0 and sum(case when key = 'lname' and value = 'redford' then 1 else 0 end) > 0 	0.366052535170371
23677552	7495	mysql @grouping results by id and sorting them by score" issue	select t.* from t join (select name, min(`time`) `time`  from t group by name) t1 on(t.name = t1.name and t.`time`=t1.`time`) order by t.`time` 	0.0196770822926803
23680329	11908	using a page item as its value in like statement	select title as "word found in"  from articles  where instr(text, article)>0; 	0.00599010847527503
23681426	36726	query to list users based on condition and order by count of other condition	select sum(last_state in (4,5,6,7)) as numprojects, u.* from (select u.*,              (select ps.state_id               from project_states ps               where ps.project_id = p.id               order by ps.created_at desc               limit 1              ) as last_state       from users u join            users_data ud            on ud.user_id = u.id left join            projects p            on p.agent_id = u.id       where ud.area_id = 1      ) u group by u.id order by numprojects desc; 	0
23681802	1595	many to many relation select where="specific"	select     u.username,     t.title,     t.thread,     t.catagory     from      post p     join user u on u.username_id = p.user_id     join threads t on t.who_id = p.threads_id     where t.catagory = 'some specific category' 	0.184641581628867
23682055	37685	trying to combine these two queries	select     ts.zname,     totala ,     totalb from (     select     count (*) as totala,     z.zname     from ctable c, stable s, sltable sl, ztable z     where c.sid=s.sid     and s.sid=sl.sid     and sl.zid=z.zid     group by z.zname ) tc inner join  (     select      count (*) as totalb,     z.zname     from stable s, sltable sl, ztable z     where s.sid=sl.sid     and sl.zid=z.zid     group by z.zname ) ts on ts.zname = tc.zname order by ts.zonename 	0.0391659357231598
23682473	30904	netezza string comparison	select     case when             (select                    strpos(                           trim(lower('abc.com')),                           trim(lower('xyz'))                           )              ) > 0      then             1     else             2     end; 	0.679489301486531
23683594	9772	mysql, getting rows from table with latest date from 2 different columns	select id, userid, fieldid, (select max(date1) from mytable where fieldid=mt.fieldid) as dateone, (select max(date2) from mytable where fieldid=mt.fieldid) as datetwo,   from mytable mt  where userid=1 	0
23684064	27333	sum of grouped rows of two different tables	select   name,   sum(time) as total_time   from (     select name, time from table_a     union all     select name, time from table_b   ) as u   group by name   order by total_time desc   limit 2 ; 	0
23685336	20128	how to select from a given month without using between or >=?	select *from your_table where monthname(foodate)='january' ; 	0.000200698603270605
23685401	16243	average of a field with running total in mysql	select t.id, @rn , @avg_rate , @num_rows , round( @avg_rate / @num_rows , 2 ) from ( select @rn :=0, @avg_rate :=0, @num_rows :=0 )d join ( select id, amount, rate from table order by id desc )t where ( @num_rows := @num_rows +1 ) and ( @avg_rate := @avg_rate + t.rate ) and ( @rn := @rn + t.amount ) > 150 limit 1 	0.000120137318368609
23685742	4742	mysql: unexpected select result after insert into table with autoincrement column	select * from t1 where id = last_insert_id(); 	0.017546260738285
23685815	16457	mysql - how do i compare values in common between two tables	select     f.* from     friends f join     users u     on     r.friend_id = u.user_id where     f.friend_id = ... 	0
23686272	729	query 3 tables in 1 query - miss the last one	select cty_en,        count(kdx_id) * 100 /   (select count(kdx_id)    from ___kardex) as kdx_countrypercentage,        count(kdx_id) as kdx_countrycount from ___kardex inner join ___countrylist on ___kardex.kdx_postaladdress_country=___countrylist.cty_code where kdx_hotelid=:hotel_id group by kdx_postaladdress_country order by kdx_countrypercentage desc 	0.000283912574002833
23687565	32733	sql server 2008 find the min date	select min([date])  from [day]  where instruction = '-1'    and grade = '14'  group by calendarid        , structureid 	0.0230262939353166
23688598	35193	combine multiple result rows into one in sql	select [course section], [instructor name], [respondent code],         max([1]) as [1],         max([2]) as [2],         max([3]) as [3],         max([4]) as [4],         max([5]) as [5] from [sirssoctonlineforms].[dbo].[denormalized_v] where term = 'ss14' and subject = 'iss' and course like '%330%' group by [course section], [instructor name], [respondent code] order by subject, course, [course section], [respondent code] 	0.000184763084783474
23688792	18072	how can i get connected values of two times the same foreign key?	select sim.id ,base.id ,base.name ,base.latex ,similar.id ,similar.name ,similar.latex from similarity as sim join symbol as base on base.id=sim.base_symbol_id  join symbol as similar on similar.id=sim.similar_symbol_id 	0
23689066	17049	use 'as' multiple times	select   p.id,   count(v.post) as votescount,   sum(v.vote) as votesup,   count(v.post) - sum(v.vote) as votesdown from   posts p   left join votes v on v.post = p.id where   p.id = 1 group by   p.id 	0.13797776831164
23697243	7677	sql query selecting from two separate tables using a order clause	select t.* from tickets as t join ticket_updates as tu on t.ticketnumber = tu.ticketnumber where status = 'completed' order by tu.datetime desc limit 50 	0.00227086273651615
23698190	37127	filtering select with join on the same table	select e.* from entity e where e.foreignkey = 0 and       e.flag in (0, 15) and       not exists (select 1 from entity e2 where e2.parentid = e.id); 	0.00616882040149928
23700893	6492	combine results of two unrelated queries into single view	select t2.total_session,        t1.watch_count from   (select 1 as common_key,           count(*) as watch_count    from video    where monthname(views) = 'may') as t1 join   (select 1 as common_key,                sum(sessions) as total_session    from user    where user_id = 6) as t2 on t1.common_key = t2.common_key; 	6.891315927303e-05
23701009	4284	mysql: joining four tables based on user	select u.*      , and      , some      , other      , columns   from users u   join table1 a     on a.users_idusers = u.idusers   join table3 l     on l.custom_id3 = a.a_id   left   join table2 c     on c.a_id = a.a_id   [and c.users_idusers = a.users_idusers]?? 	0.000298261176179295
23702064	15097	grouping records between start and end time	select cast(startdate as date) as fordate,        datepart(hour, startdate) as onhour,        count(*) as totalstarts,        sum(case when cast(startdate as date) <> cast(enddate as date) or                      datepart(hour, startdate) <> datepart(hour, enddate)                 then 1                 else 0            end) as startedbutnotendedinhour from #events group by cast(startdate as date),        datepart(hour,startdate) 	0.000210578811164062
23702233	5419	select rows that are "different" than the previous row	select * from table_name  where id in (select min(id) from table_name group by id_user) 	0
23702733	21075	trying to relate tags to products by product category	select p.*,     (select group_concat(tag) from tags where pid = p.id) as tags     from products p     having p.loc_cat = 'pre-rinse units'     and tags like '%body:deck mount%' and tags like '%body:single%'; 	0.000233977156205766
23702974	24205	mysql joining most recent record from another query is slow	select * from mods as m left join (     select ml1.*      from modlogs as ml1      join (         select `mod`, max(time) as time         from modlogs          group by `mod`        ) as ml2 using (`mod`, time) ) as ml on m.id = ml.`mod`; 	0.00019148895168775
23703020	9237	selecting data from one table or another in multiple queries pl/sql	select 1st query where boss_condition union all select 2nd query where not boss_condition 	0
23705167	7864	mysql relation between tables	select type, car_numbers, avg(price) as average_price from (select type_id, type, sum(car_numbers) as car_numbers       from table1       group by type_id) as t1 join table2 as t2 on t1.type_id = t2.type_id group by type 	0.0462365897705497
23708668	40185	ms access sum of 2 table in one qury	select* into #temp from table1 union select* from table2 select id,sum(ppic) as ppic, sum(pcrt) as pcrt from #temp group by id 	0.00447467146094972
23709068	15991	mysql sum of counts of two queries	select p.player_first_name, p.player_last_name, (count1+count2) as total_count from (select player_id, count(*) count1 from(select * from 1st_assists union select * from 2nd_assists) as tem join players on tem.fk_player_id=players.player_id group by fk_player_id order by count(*) desc) q1 left join (select player_id, count(*) count2 from goals_for join shots_for on goals_for.fk_shot_for_id=shots_for.shot_for_id join players on shots_for.fk_player_id=players.player_id group by player_id) q2 on q1.player_id=q2.player_id left join player p on q1.player_id=p.player_id order by (count1+count2) desc; 	0.00179839560831606
23724629	7235	php /mysql select data from 3 different tables and display result it in one table	select s.tag_id, s.name, lt.lecture_name, lt.lecturer_name, sa.abs_hours from students_absence sa join students s on (s.tag_id = sa.tag_id) join lecture_table lt on (s.lecturer_name = lt.id) where s.tag_id = 00000023; 	0
23724805	14629	splitting a result into three columns	select   floor((id - 1)/3) + 1 id,   max(case when mod(id - 1,3) = 0 then word end) col1,   max(case when mod(id - 1,3) = 1 then word end) col2,   max(case when mod(id - 1,3) = 2 then word end) col3 from tbl group by floor((id - 1)/3) 	0.0010449561465949
23726003	26628	mysql: help in query from two tables	select u1.name as from_name,        u2.name as to_name from friends as f join users as u1 on u1.users_id = f.fromid join users as u2 on u2.users_id = f.toid 	0.119422865554582
23726256	32017	mysql replace string between two known strings	select    id,    post_title,    substr(post_content,    instr(post_content,'<div style="position:absolute'),     locate('</div>',post_content,instr(post_content,'<div style="position:absolute')+30)-instr(post_content,'<div style="position:absolute')    +6) as temp  from wp_posts  where post_content like '%<div style="position:absolute%'  limit 10 	0.00298670619499211
23726534	14385	with a table of visitor data, how do i get hourly totals of total and unique visitors?	select max(h.total) as total, count(firstvisit.session) as firsts, h.hr from (select hour(time) as hr, count(*) as total       from visits v       where date = '05-18-2014'       group by hour(time)      ) h left outer join      (select session, min(hour(time))as hr       from visits v       where date = '05-18-2014'       group by session      ) firstvisit      on h.hr = firstvisit.hr group by h.hr; 	0
23728687	6468	how to get another table field information	select a.id as tid a.name as tname b.name as username from team a left join user_team c on a.name = c.teamid and c.isdeleted = 0 left join user b on b.id = c.userid 	0
23730833	31302	sql check that all rows have only certain values	select count(*)  from   invoices  where  invoicedraftnumber = '12345'  and    status <> 'rejection' 	0
23730922	16024	how do you count the frequency of a word in a column?	select count(*),substr(col,1,(instr(col,'.')-1) from tab group by  substr(col,1,(instr(col,'.')-1) order by 2; 	0.000181213294836813
23730982	35435	return the values of max count of rows with the same values	select  instructornumber, time, date, cpnumber from table_schedule group by instructornumber, time, date, cpnumber order by count(*) desc limit 1 	0
23731628	19429	(solved)mysql select and sum from multiple table without duplicate it	select t.code,t.name,t.quantity,t.out,t.in,(t.out+t.in) as total from (        select table1.code, table1.name, table1.quantity,                 ( select sum(table2.qty_out)                    from table2                    where table1.code=table2.code ) as out,                 ( select sum(table3.qty_in)                    from table3                   where table3.code=table1.code ) as in         from table1      ) as t 	0.00193304034716578
23731986	34633	sql group by: how to get % of records over a certain score	select   stepid,   cast(sum(case when rating > 9 then 100.0 else 0 end)  /count(*) as decimal(5,2)) pct from yourtable group by stepid 	0
23732122	6564	how to retrieve all unanswered q(uestion)?	select q.* from question q left join answer a on a.question_id = q.id where a.question_id is null 	0.0161675946035404
23733288	25196	get stored procedures parameters	select ua.argument_name param_name, ua.sequence param_order     from user_arguments ua    where     nvl (ua.package_name, '1') = nvl (in_package_name, '1')          and ua.object_name = in_procedure_name          and ua.in_out = 'in' order by ua.sequence; 	0.262957609249048
23735698	39238	sql server query check empty fields for a number of columns	select * from table  where name is null or name = '' or city is null or city = '' or [address] is null or [address] = '' 	0.000340278370742469
23736061	7988	how to present a mixed result of two tables using subqueries in mysql?	select   table01.id,   table01.individuum,   table01.species,   table01.genus,   table02.id as id2,   t01.individuum as individuum2   t01.species as species2,    t01.genus as genus2,   table02.index from   table01 inner join   table02 on table01.id = table02.id1 left join   table01 as t01 on t01.id = table02.id2 where     table01.individuum in (alfa , epsilon) order by   index desc; 	0.00611981414735921
23736729	19122	how to calculate count of records between several dates	select t1.date, t1.ticker_name, dateadd(days, -100, date) as lookback_date,     (select count(ticker_name) as cnt      from table1      where date > t1.date            and date < dateadd(days, -100, date)) from table1 t1 	0
23738242	7865	sql query combine two rows into one row of data	select   table2id,   max(b) b,   max(c) c,   max(d) d from tbl where a != 'type_3' group by table2id 	0
23738357	10543	how do i consolidate unique row values into a single column across multiple columns?	select   table_a_id,   array_to_string(array_agg(distinct column_1), ',') as the_ones,   array_to_string(array_agg(distinct column_2), ',') as the_twos,   array_to_string(array_agg(distinct column_3), ',') as the_threes from table_a  group by table_a_id ; 	0
23739206	9875	find date based on week + dayofweek mysql	select str_to_date('2014-20-2','%y-%u-%w')-interval 1 day n; + | n          | + | 2014-05-19 | + 	0
23741406	10549	sql : how to get the latest value of an unordered column	select uuid from run where <some_condition> order by id desc limit 1; 	0
23741872	36773	how do i get the latest row by date t-sql for each file id	select t1.* from table t1 where dateuploaded = (select max(dateuplaoded from table t2 where t1.docid = t2.docid) 	0
23742523	39358	find row with data between a range sql	select * from your_table where @input between _begin and _end 	8.99656070219813e-05
23745329	30688	sqlite compare timestamp with datetime in c#	select datetime(1092941466, 'unixepoch'); 	0.0152447548033901
23745524	41297	mysql php combine select queries	select `cpet`.`product_id`, `cpet`.`product price`, `cpet`.`product attribute`  from `catalog_product_entity_text` as `cpet` join `catalog_product_entity` as `cpe` on `cpet`.`product_id` = `cpe`.`entity_id` where `cept`.`attribute_id` = '139' 	0.115102095224711
23745771	16478	get the highest value of the last 7 days with sql	select max(value) as value_of_week from events where event_date > date_add(now(), interval -7 day); 	0
23746578	18212	getting data from two different databases with single connection, is this a valid way	select db1.table1.column1, db2.table2.column2 from db1.table1 join db2.table2 on db1.table1.column1 = db2.table2.column2; 	0.00527909686251528
23748872	3825	sql 1tom join query where criteria in child isn't met are shown	select id, name, pid, typeid, phone from parent  left outer join  child on parent.id = child.pid and child.typeid = 2 	0.0961611719211066
23750355	33304	where variable between 2 column dates	select * from resources where　@cdate　between begindate and endingdate 	0.0026080082086123
23752328	26317	sql get most hits on specified datetime period	select max(loggedincount) from table      cross apply (           select count(1) as loggedincount           from table as innertable           where innertable.loggedindate <= table.loggedindate                 and innertable.loggedoutdate >= table.loggedindate      ) as ca1 where table.loggedindate in yourperiod 	6.24718389362179e-05
23754554	8891	how to write this query to join output of two queries	select * from  (    select sourceid     from audittraillogentry     where event ='67' and innodename like '%_collector'  ) as t1 join  (    select  destinationid     from audittraillogentry     where event ='68'       and (outnodename like '%_distributer' or outnodename like '%_arch')  ) as t2  on t2.destinationid like t1.sourceid || '%' 	0.750800675072092
23755122	20297	how to append/updated records in sql server virtual table?	select a.identifyingnumber as identifyingnumberl, a.included as includedl,        b.identifyingnumber as identifyingnumberr, b.included as includedr from (     select  row_number() over(order by identifyingnumber) as row,             identifyingnumber, included     from @entitylist  where included=0 )  a full outer join  (     select row_number() over(order by identifyingnumber) as row,            identifyingnumber,included from @entitylist  where included=1 )b  on a.row=b.row 	0.00585380138846837
23756702	16874	compare dates in mssql	select * from table where thedate < convert(date, getdate()) 	0.0140517210481219
23757412	40746	order by count (somerecord)	select   full_name, server_name, count(directory) from     some_table group by full_name, server_name order by 3 desc 	0.397346492048123
23760269	33715	best way to select multiple records gridview asp.net	select * from table where positionid in (1234, 5678) 	0.037860682258438
23760367	1670	sql - using count in a sum query	select d.docname, d.cost*count(a.appid) as totalcost from doctor d left join appointment a on a.docid=d.docid group by d.docname having d.cost > average(d.cost); order by d.docname 	0.279811203755694
23760573	35579	select query to return a row from a table with all values set to null	select t2.* from     mytable as t2     right join     (         select top 1 (id * -1) as badid          from mytable as t1     ) as rowstubs         on t2.id = rowstubs.badid 	0
23760698	29729	mysql true way for using group by	select g2.days, group_concat(price) prices,  group_concat(seconds) times, minp, maxp from goldprice g1 inner join ( select gid, days,  max(price) as maxp, min(price) as minp, max(seconds) as maxt, min(seconds) as  mint from `goldprice` where gid = 1 and days = 16200 group by days ) g2 on (g1.days = g2.days and g1.gid = g2.gid and (seconds = mint or seconds = maxt))  where gid = 1  and days = 16200 group by days order by days desc, seconds asc 	0.484922330315457
23763394	33572	shape a for xml query against an xml column to include attribute in root	select 42 as [@tag],          (select content as [*]  from #test t for xml path(''), type) as [*]  for xml path('root') 	0.0193129208139231
23763933	38673	sql to find the output file with respect to input file from a table	select e68.destinationid  from audittraillogentry e68,    audittraillogentry e80,    audittraillogentry e67  where e67.event='67'   and e67.innodename like '%_sftp_%'   and e67.destinationid=e80.sourceid   and e80.event='80'   and e80.innodename like '%_sftp_%'   and e80.destinationid=e68.sourceid   and e68.event='68'; 	0.000364249691212267
23767298	11976	sort within category and limit 5 for this hive table	select user,collect_set(item) from (     select user, item,row_number () over (partition by user order by score desc) rn      from a ) t1 where rn <= 5 group by user; 	0.0407667055538868
23767414	1079	what is select for sum, grouped and distincted by another columns in sql?	select date, categories, sum(price) from tablename group by date, categories 	0.00201743802255001
23768364	40331	unioning multiple tables together and filtering out selection based on aggregated fields.	select * from ((select '001' as reportnumber, 'rpt001' as reportname, isnull(sum(1),0) as activereportcount        from [dbname].[dbo].[v_rpt001]       ) union all        (select '002' as reportnumber, 'rpt_002' as reportname, isnull(sum(1),0) as activereportcount        from [dbname].[dbo].[v_rpt001]       )      ) r where activereportcount > 0; 	0.000178310486035129
23773631	14678	join with two result sets from same table?	select a.channel_oid as _id, a.oid as now_oid, a.title as now_title,        a.start_time as now_start_time, a.end_time as now_end_time,        b.oid as next_oid, b.title as next_title, b.start_time as next_start_time,        b.end_time as next_end_time from (     select channel_oid,         oid,         title,         start_time,         end_time     from epg_event     where  start_time <= datetime('now') and end_time > datetime('now')     order by channel_oid) as a   join (     select channel_oid,         oid,         title,         min(start_time) as start_time,         end_time     from epg_event     where start_time > datetime('now')       group by channel_oid)  as b  on a.channel_oid = b.channel_oid 	0.000394545395388077
23773845	34102	combine two queries as a single one	select reip,  (700+(reip-r45))/((r72-r45)*40) as reipw from (    select (max(tert)+min(tert))/2+min(tert) as reip,    case when iner=44.5 then tert end as r45,  case when iner=72.1 then tert end as r72   from  table_name   where iner between 43 and 79   group by iner,tert ) as se_23693370 	0.000583024095923365
23774131	4509	sql query to select matching rows for all or nothing criteria	select id, cartype from cars c where ( select count(1) from cities where id in (...))     = ( select count(distinct cityid)         from locations          where c.companyid = locations.id and cityid in (...) ) 	0.0036605929439123
23775428	2162	how to add duplicate value to existing column in sql?	select  id, tpoi, "date", case when id in      (select distinct             id          from              test1.dbo.duplicate          where              dbavailability = -1) then '-1' else dbavailability end as dbavailaility from test1.dbo.duplicate  where  date between '2014-05-01' and '2014-05-04' 	0.000207504696273833
23776821	11238	join a table to the max records from another table	select t.*, m.*  from topic t  left join    (select id_topic, max(created) as created     from message     group by id_topic    ) t2 on t.id = t2.id_topic  left join message m on m.id_topic = t2.id_topic and m.created = t2.created 	0
23777160	4572	sort comments by id and related answers in php-mysql	select id, comment, reply from comments_table order by if(reply is not null, reply, id), id 	0.000462884173270948
23778155	5059	select block order by timestamp and randomized by id	select * from (    select * from table order by timestamp limit 1000 ) as a order by rand() 	0.00365048816081174
23778535	15539	merge adjacent repeated rows into one	select * from table t1 where not exists(select * from table t2 where t2.order = t1.order - 1 and t1.data = t2.data) 	0.000110333776537657
23779161	2560	how to pick record from a query that has distinct and use of case in sql	select    employees.pinno,    employees.surname + ' ' + employees.othernames,   tblemployeeperioddetails.basic_pay,   tblemployeeperioddetails.house_allowance,   transport_allowance=     isnull((       select sum(tblemployeetransactions.amount)        from tblemployeetransactions inner join tblpayrollcode on tblemployeetransactions.payrollcode_id = tblpayrollcode.payrollcode_id        where payrollcode_code = 'p137'          and tblemployeeperioddetails.employee_id = tblemployeetransactions.employee_id          and tblemployeeperioddetails.period_month = tblemployeetransactions.period_month          and tblemployeeperioddetails.period_year = tblemployeetransactions.period_year      ),0.0) from    employees  inner join    tblemployeeperioddetails on employees.employeeid = tblemployeeperioddetails.employee_id  where    tblemployeeperioddetails.period_month = 7 and    tblemployeeperioddetails.period_year =2010 	0.000279653264365682
23780301	31070	mssql select with count	select t1.onomateponimo,t1.dieuthunsh,t1.tilefono, count(t2.person_code)  from persons as t1 inner join operations as t2     on t1.person_code = t2.person_code group by t1.onomateponimo, t1.dieuthunsh, t1.tilefono order by t1.onomateponimo asc; 	0.288196786366785
23780405	40196	how to export data when the fieldnames are stored in one table and the data in another	select a.data as 'name',b.data as 'age'  from (select userid,data from tablename where fieldname=1) a  join (select userid,data from tablename where fieldname=2) b  on a.userid=b.userid; 	0
23782553	24593	how to get unique result from below entry?	select * from  tablename a   where a.ress_id = (select max(b.ress_id) from tablename b where b.table_no = a.table_no)  group by a.plan_id,a.table_no 	0
23785621	1344	convert cakephp queries into normal queries	select * from itemswhere id=$id; 	0.276015301904451
23788109	10831	mysql - count total of rows from multiple tables with same column name	select count(user_id) from (select user_id from a_survey where user_id = 3 union all select user_id from b_survey where user_id = 3  union all select user_id from c_survey where user_id = 3) tables 	0
23789449	23445	sql server break columns into row with join	select distinct package_id, package_title, durationindays,videourl,package_image_1 + ',' + package_image_2 + ',' + package_image_3 + ',' + package_image_4 + ',' + package_image_5 as pacakage,  rating, adultprice from packages inner join rates_and_dates on rates_and_dates.package = packages.package_id where package_id=1 and adultprice='4500' 	0.0102299316284369
23790939	580	sql query that will return duplicate lottery numbers	select newwln, count(*) as cnt from (select lotterynumber, group_concat(numpart order by numpart separator '-') as newwln       from (select wln.lotterynumber,                    substring_index(substring_index(wln.lotterynumber, '-', n.n), '-', -1) as numpart             from winninglotterynumbers wln cross join                  (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5                  ) n            ) wln       group by lotterynumber      ) nwln group by newwln having count(*) > 1 order by count(*) desc; 	0.0067008134594416
23791361	24972	create dynamic sql statement based on the output of a select in sql server	select  inputdates.date as inputdate, dbo.getfuturedate(inputdates.date,yearinyearlist) as pastdate     into #datemap     from inputdates, yearlist 	0.0182588522742584
23792432	29543	returning null values as something else from a query	select test_code, test_mdl,     convert(varchar(20),isnull(test_mdl,'null'))     from test; 	0.181241683410916
23792440	29849	sql join two cells without criteria	select      (select avg(column1) from table1 where company like '%3m%'and column2!=0) as a,     (select avg(column3) from table1 where company like '%3m%'and column4!=0) as b 	0.0230289614338894
23794286	26200	mysql: find users that registered on site & then bought same day	select date(c.date_created) as `date`        ,count(distinct c.customer_id) as registered_customers_who_bought from customer as c join purchase as p   on c.customer_id = p.customer_id     and date(c.date_created) = date(p.date_modified) where (c.`date_created` >= '2011/09/01' and c.`date_created` < '2014/05/14') group by date(c.date_created) 	0
23797818	6712	multiple select statements with different where condition in one query	select    trainnumber,   sum( iif(bookcategory = 'general' and reservationstatus = 'confirmed', 1, 0) ) as totalseatgen,   sum( iif(bookcategory = 'ac' and reservationstatus = 'confirmed', 1, 0) ) as totalseatac,   sum( iif(bookcategory = 'general', 1, 0) ) as totalbookgen,   sum( iif(bookcategory = 'ac', 1, 0) ) as totalbookac from passenger group by trainnumber  order by trainnumber; 	0.0456125299839411
23798974	41	extract values from a database within a period of time.	select user.firstname, user.lastname, user.userid, stats.userid, stats.roleid,        sum( statsreads ) as numreads, sum( statswrites ) as numwrites,        sum( statsreads ) + sum( statswrites ) as totalactivity        from  `mdl_stats_user_daily` stats, `mdl_user` user        where userid in (select userid                         from mdl_role_assignments                         where roleid in (1,2,3,4))        and user.id = stats.userid        and stats.timeend < adddate(curdate(), -7)       group by userid order by totalactivity desc limit 20" 	0
23799331	5735	using interval in postgresql to add hours date/time	select timestamp '2010-11-19 01:11:22' + interval '4 hours'; 	0.00171938239815871
23800445	5096	get records added last week, but exclude records added today	select * from table where  date(date_added) > date_sub(curdate(), interval 7 day)  and  date(date_added) < curdate() 	0
23802634	33595	sql query help needed - tale with max date value for each row group	select room, max(day), people, theme  from table_name group by room, people, theme; 	0.00930197668835847
23802785	9489	averaging timestamps in sql query	select avg(time_to_sec(your_column)) as average_seconds, sec_to_time(avg(time_to_sec(your_column))) as average_time from your_table; 	0.0434937820819525
23804184	20553	sql multiple characteristics in one line	select client,group_concat(product) as product-history from your_table  group by client 	0.0315162587561162
23804374	27094	splittng a comma separated string mysql	select distinct ename as emp_name, substring_index(substring_index(table1.work_place, ',', 1 + units.i + tens.i * 10), ',', -1) as wp   from table1 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.00260538563995468
23806264	490	how do show a result table from two 'select'? sql	select tableb.name, tablea.value, count(tableb.name) as newcolum from tableb join tablea on tableb.name = tablea.kname group by tableb.name,tablea.value 	0.000128157044198825
23806655	17188	how to get total number of rows from a query with also all column	select row_number() over(tbltaxingschemedetails.taxschemedetailsid)as seqno, tbltaxingschemedetails.taxschemedetailsid, tbltaxingscheme.taxschemeid,  tbltaxingscheme.taxschemename,  tbltaxingschemedetails.taxtype, taxname, tbltaxingschemedetails.taxrate from tbltaxingscheme inner join tbltaxingschemedetails   on tbltaxingscheme.taxschemeid = tbltaxingschemedetails.taxschemeid inner join tbltaxtype  on tbltaxingschemedetails.taxtype = tbltaxtype.taxtypeid where tbltaxingscheme.taxschemeid =5@taxschemeid 	0
23807176	32804	joining two tables to turn two stored procedures into one sql	select t2.discountamount  from table2 t2 inner join table1 t1 on t2.discountid = t2.discountid where t1.productid = @productid 	6.9849178014564e-05
23807915	12776	random over users considering their posting (mysql)	select name, count( post ) as "number of posts" from user_and_posts group by name having count( post ) >= 100   order by rand( ) limit 0, 199 	0.00258339615954231
23808982	34821	unknown column error when joining from 2 different databases	select      j.id,     j.title,     v.name as venuename,     ja.completed from     jobs j inner join venues v on v.id = j.venueid left join dbsiv.job_applications ja on ja.jobid = j.id and ja.pin = $currentusersid where      and j.closingdate > unix_timestamp()     and j.active = 1 order by      j.closingdate desc 	0.0259951884136385
23809605	15795	how to treat acct = 'labor ot' and acct = 'labor' as the same when grouping the column acct	select fiscalno, case when acct='labor ot' then 'labor'else acct end as 'acct', data1, employee, project, pjt_entity, sum(units) as units, sum(amount) as amount, tr_id03, tr_id05, vendor_num from dbo.pjtran  group by fiscalno, case when acct='labor ot' then 'labor'else acct end, data1, employee, project, pjt_entity, tr_id03, tr_id05, vendor_num order by fiscalno, acct, employee 	0.00259539970812611
23811107	39438	order by column names with codeigniter and mysql	select * from events order by field(event_id,42,43,41) 	0.0265871383864141
23811826	37221	sql statement to randomly select one row having a certain criteria	select tmp.id, tmp.name, tmp.last_name, tmp.location from profiles left join (select * from profiles order by rand()) tmp on (profiles.location = tmp.location) group by tmp.location order by profiles.location; 	0
23812211	35500	how can i select the distinct values from one col with their latest value from another	select name, mark from table t1 where date=(   select max(date)   from table t2   where t2.name=t1.name ) 	0
23812563	25424	what's the most efficient way to match values between 2 tables based on most recent prior date?	select  d.val,         p.val,         newval = d.val + isnull(p.val, 0) from    dailyt as d         outer apply         (   select  top 1 val             from    periodt p             where   p.date <= d.date             order by p.date desc         ) as p; 	0
23813356	13495	is there a way to select columns with html tags in them in mysql?	select `rot<sub>1</sub>` from chem.thermtable; 	0.00169799789386706
23816130	14400	forcing sql server to pre-cache entire database into memory	select * 	0.0441608050107636
23816727	35298	how to get maximum value from column while using joining sql	select  st.roll, cr.code, cr.title, cr.credits, max(sch.obtainedgpa) from [miu_ucam.1.0.1].[dbo].[studentcoursehistory]  as sch join [miu_ucam.1.0.1].[dbo].[student] as st on sch.studentid = st.studentid join [miu_ucam.1.0.1].[dbo].[course] as cr on sch.courseid = cr.courseid and sch.versionid = cr.versionid where st.roll ='0914bpm00387' group by st.roll, cr.code, cr.title, cr.credits 	0
23817308	1524	get a timestamp's monday's date	select date_trunc('week', current_timestamp) 	0.000421828148961761
23818119	12029	sql left join with conditions from two tables	select a.id, b.[02], b.[01] from a inner join b on b.[01] = a.[01] left join c on a.id = c.[01] where c.[02] is null 	0.112622546993554
23818805	16900	how to get table format output with sql query for a given table	select *  from ( select s,t,c as cd from  data ) as src pivot( sum(cd) for t in ([a],[b],[c],[d]) ) as pvt 	0.000462094322910755
23819174	25660	sql i have to find the entire row of people that did something the same day. count function?	select distinct d1.*   from donates d1        inner join donates d2         on  d1.donors = d2.donors         and trunc(d1.giftdate) = trunc(d2.giftdate)         and d1.rowid < d2.rowid  ; 	0
23819386	37945	adding "default" to multiple columns in one single query	select 'alter table table1 add default ('''') for '+ column_name  from information_schema.columns    where table_name='table1' 	0.000583337024700002
23819446	10258	select some specific data after inner join	select distinct s.size,m.modelname from . . . where   m.modelname like '%xx3%' order by m.modelname 	0.0934358313572236
23819727	2428	mysql calculating time difference when one data point is null	select wardtransactions.id id,         genders.description gender,         wards.code ward,         time_to_sec(timediff(        (case when dischargedatetime is null then now() else dischargedatetime end), admissiondatetime)) duration from wardtransactions join wards on wardtransactions.wardid=wards.id join demographics on wardtransactions.demographicid=demographics.id join genders on demographics.genderid=genders.id join visits on wardtransactions.visitid=visits.id 	0.00430661085911819
23820607	30611	counting the number of times a word appears in a column in oracle	select regexp_substr(title, '\w+') first_word, count(*)    from film  group by regexp_substr(title, '\w+'); 	0
23821074	24259	obtain below date format in sql server	select format(getdate(), 'g'); 	0.0667727563999716
23821457	23203	getting previous data (one less running column)	select cmpi_prcinx as current_price, (select max(cmpi_prcinx) from cmd_mtrl_price_inf  where cmpi_prcinx<(select max(cmpi_prcinx) from cmd_mtrl_price_inf)) as privious_price from cmd_mtrl_price_inf where cmpi_prcinx = (select max(cmpi_prcinx)  from cmd_mtrl_price_inf group by cmi_code) 	0.000454983615314743
23822343	28234	how to select only 2 rows of same fruit type in mysql?	select @a := @a + 1 as id, fruitname, fruittype from  (select @a := 0)  r join ( select fb1.fruitname,fb1.fruittype     from testdb.fruit fb1      group by fb1.fruitname,fb1.fruittype    having count(fb1.fruitname) >=2   union all     select fb1.fruitname,fb1.fruittype       from testdb.fruit fb1      group by fb1.fruitname,fb1.fruittype     having count(fb1.fruitname) >=2) b      order by fruitname,fruittype; 	0
23827753	27499	dql select association	select a from a a left join a.bees b where a.name like ?1 or b.city like ?1 	0.456802034906994
23827944	29072	differentiate between groups of duplicated values	select groupnum, column1, column2, seqnum from (select t.*, count(*) over (partition by column1, column2) as cnt,              dense_rank() over (order by column1, column2) as groupnum,              row_number() over (partition by column1, column2 order by column1) as seqnum       from table t      ) t where cnt > 1 order by groupnum; 	0.000308253290351836
23828794	21212	get distinct rows combined from multiple fields (including a joined one)	select a.id artifactid, status, revision, productname, organization from products p join artifacts a on a.productid = p.id group by productid, status, revision 	0
23828813	8365	sql calculating difference between columns	select avg(difference), meter_id from table group by meter_id 	0.00176370277557099
23830086	1264	sqlite join 2 tables with same columns	select date, amount as amount1, null as amount2 from tablea union all select date, null as amount1, amount as amount2 from tableb 	0.00184109305561838
23831888	30546	sql - how to get first and last occurence based on conditions	select article,         min(case when status = 3 and queue = inloa then regdate end) as firstloa,        min(case when status = 2 and queue = lo2st then regdate end) as last from a group by a; 	0
23832045	30356	tsql xml parsing using select statement	select      paramvalues.x2.value('type[1]', 'varchar(100)'),     paramvalues.x2.value('action[1]', 'varchar(100)') ,     paramvalues.x2.value('../account[1]', 'varchar(100)')  from @xmldata.nodes('/thedata/data') as paramvalues(x2)` 	0.777575090266605
23832403	38232	trying to sum based off an id	select      a.[unique_claim_identifying_number],     sum([charge amount]) as total_charge_amount from   (    ...... place your query here..... ) a group by  a.[unique_claim_identifying_number] 	0.000552936839601951
23833731	19854	copy a table into a new table and add a new column on sql server 2008	select          table1.col1, col2, col3,                  case when table2.col1 is null then 0 else 1 end as col4 into            table1_new from            table1 left outer join table2 on table1.col1 = table2.col1 	0
23836579	10613	reordering output to predefined sequence	select * from your_table order by case when some_column = 'l' then 1               when some_column = 'c' then 2               when some_column = 'e' then 3               when some_column = 'o' then 4               when some_column = 'a' then 5          end desc 	0.216748210121658
23837088	37009	mysql - finding mismatches between sets of "batched" data	select *  from order_addresses o1   inner join order_addresses o2    on o1.parent_id = o2.parent_id    and o1.entity_id <> o2.entity_id where o1.last_name <> o2.last_name   or o1.zip_code <> o2.zip_code 	0.00473738619822027
23837830	29116	sql query joining multiple tables using and critrea	select parent.parent_name from parent inner join child on parent.parent_id = child.parent_id where child.hair = blond or child.hair = red group by parent.parent_name  having count(distinct child.hair) = 2 	0.364949534329159
23838038	22028	mysql. selecting only a few data from one row	select t1.name as name, t1.car as car, t1.price as max_price     from table1 t1     order by max_price desc     limit 1; 	0
23838510	2625	using sql, how do i convert a comma separated list to be used with the in command?	select p.* from perm p join dbo.splitstring('50,40,30') s on p.user_type = s.name 	0.0118972637886606
23839774	36957	how to use different where clauses for each column	select week, sum(case when fruit_type = 'apples' then fruit_num end) as 'apples', sum(case when fruit_type = 'oranges' then fruit_num end) as 'oranges' from fruit group by week order by week 	0.000729592078341583
23841431	640	select statement joining 2 tables, searching by date, and status	select r.* from (   select rp.regionid, p.key, p.name, p.vacation, p.seen   from regionplayer rp   join players      p  on p.key = rp.playerid    where rp.status = 1   group by rp.regionid   order by p.seen desc ) r where ((r.vacation != 1) and (r.seen <= (now()-interval  8 day)))    or ((r.vacation != 0) and (r.seen <= (now()-interval 58 day))); 	0.00156357677183267
23843615	20042	count specific rows to match the query	select id, students, sub1, sub2, sub3, sub4, sub5, sub6,        ((sub1 < 40) + (sub2 < 40) + (sub3 < 40) + (sub4 < 40) + (sub5 < 40) + (sub6 < 40)        ) as failedin  from table t; 	0.000819727270699568
23847914	24945	calculate discount price of net amount in sql server?	select item_model,        item_name,        item_description,        quantity,        rate=case when discount is null or discount=0              then rate             else rate*(discount/100) end,        amount,        date,        discount         from item_details         order by item_model 	0.00104631275881725
23849073	25992	creating oracle view with using a composite key table	select category_id, category.name, count(category.film), avg(rental_rate)   from film_category    full outer join category using (film_category.category_id)   full outer join film using (film_category.film_id)   group by category_id, category.name; 	0.484516028982418
23849378	29356	mysql : mix data from 3 tables and join with another table	select c.id, c.user, c.comment, c.from, t.title, t.url from comments c, posts t where c.t_id=t.id and c.from='post' union select c.id, c.user, c.comment, c.from, t.title, t.url from comments c, imgs t where c.t_id=t.id and c.from='img' union select c.id, c.user, c.comment, c.from, t.title, t.url from comments c, zaps t where c.t_id=t.id and c.from='zap' 	0.00159779668110681
23853681	16798	using mysql query in selecting room availability	select     room.room_num from     room where   roomtype = 'deluxe' and   room.room_num not in    (     select       room_booked.room_num     from       room_booked     where       (room_booked.dor<='2014-06-1' and room_booked.dco>='2014-06-1')       or       (room_booked.dor<'2014-06-06' and room_booked.dco>='2014-06-06')       or       (room_booked.dor>='2014-06-01' and room_booked.dco<'2014-06-06')    ) 	0.284996803133746
23856847	2680	filtering oracle 11g hierachical tables	select ...    from ( select ... from ... where year_of_birth not between 1965 and 1980 )   start with mgr is null connect by nocycle prior emp = mgr; 	0.613751964876646
23856943	12759	query to get values of one table which are not there in string column of another table, also less than a particular datetime value	select qb.id,qb.enddate   from quizquestionbank qb   left join quizuserdetails qd   on find_in_set(qb.id, questioniddetails) > 0    and msisdn = '235346'   where qd.id is null  and qb.enddate < '2014-05-10 00:00:00'     	0
23857059	925	mysql. products not sold in a period	select * from table1   where id not in ( select id from table1 where              `date_sold` between '2014-05-10' and '2014-05-20') 	0.00634854924925113
23857994	38945	i want to count records from a database where the columns have the same value	select bookid, count(*) as views from books where `time` >= '2014-04-01' and `time` < '2014-05-01' group by bookid order by views desc limit 5 	0
23859738	12837	don't count duplicate entries in mysql database	select count(distinct message) from your_table 	0.000143799532412033
23860695	5566	mysql group by twice and count	select * from ( your_sql_select_with_everything ) group by id 	0.15244819104768
23861197	12176	mysql and php calculating totals	select ps.player, count(*) as player_points_total from predicted_scores ps join actual_scores acs on ps.game_id = acs.game_id  where ps.score = acs.score group by ps.player 	0.0904072658668429
23861959	11790	combine two complex sql queries into one	select s.id, s.name, users.username, users.successes, users.attempts  from ((select schools.id, schools.name from schools inner join users on schools.id = users.school     where users.attempts !=0     order by rand()     limit 1) s) inner join users on s.id = users.school order by users.successes / users.attempts desc limit 1 	0.0124462943885683
23863622	8735	converting a table column into table rows using mysql	select id,name,day,no from ( select id , name , 'morning' as day,morning as no from test union all select id , name , 'afternoon' as day,afternoon as no from test union all select id , name , 'evening' as day,evening as no from test )x order by name 	0.000535804930337767
23864172	39307	get the latest date from the three columns	select case when date1 is not null               and date1>=coalesce(date2,cast('0001-01-01 00:00' as datetime2))               and date1>=coalesce(date3,cast('0001-01-01 00:00' as datetime2)) then date1              when date2 is not null               and date2>=coalesce(date1,cast('0001-01-01 00:00' as datetime2))              and date2>=coalesce(date3,cast('0001-01-01 00:00' as datetime2)) then date2              when date3 is not null               and date3>=coalesce(date1,cast('0001-01-01 00:00' as datetime2))              and date3>=coalesce(date2,cast('0001-01-01 00:00' as datetime2)) then date3         end as latest from t1 	0
23864265	25297	getting one column count based on joining 3 tables in sql server	select table2.questionsetid,        count(questionid) from table2  inner join table3 on table2.quesionid = table3.quesionid where difficultylevel='low' group by table2.questionsetid 	0
23864822	16841	search mysql database, order results by count	select *,  count(*) as users_sales_guild_id_count  from sales_list  where sales_entry_date between '2013-10-01 00:00:00' and '2014-11-30 23:59:59'  group by users_sales_guild_id order by users_sales_guild_id_count desc 	0.18279495963691
23867308	11737	t-sql overlapping time range parameter in stored procedure	select * from times where authorizationtime >= @from and authorizationtime <= @to and (         (@fromtime > @totime and ((cast(authorizationtime as time) between '00:00:00' and @totime) or                                    (cast(authorizationtime as time) between @fromtime and '23:59:59.999')                                  )         ) or        (@fromtime <= @totime and cast(authorizationtime as time) between @fromtime and @totime)     ) 	0.0498689789994075
23867955	27901	sql - 2 equal queries differently written are not working the same	select c.name as 'country', s.name as 'state', city.name as 'city'  from      countryregion as city inner join      countryregion as s on s.id = city.countryregionparentid inner join     countryregion as c on c.id = s.countryregionparentid where  city.id=11 	0.126202510954602
23868471	5015	group by returnign 0 rows	select  trunc (sysdate - 1) d,         col1,         col2,         total from (    select  nvl(avg (column1),0) col1,            nvl(avg (column2),0) col2,            count (* ) total    from   table1    where column3 = 0  and trunc (utc_timestamp + tz_offset / 24) = trunc (sysdate - 1)) group by trunc (sysdate - 1),             col1,             col2,             total 	0.0605045589436038
23869002	34179	selecting and grouping with subqueries in mysql - returning latest record	select pe_id, pa_name, ex_name, pe_d1, pe_d2 from patient_exams pe join patient p on pe.pe_pa_id = p.pa_id join exams e on pe.pe_ex_id = e.ex_id join (   select pe_pa_id, pe_ex_id, max(pe_d2) as max_pe_d2   from patient_exams   group by pe_pa_id, pe_ex_id ) as t on pe.pe_pa_id = t.pe_pa_id  and pe.pe_ex_id = t.pe_ex_id  and pe.pe_d2 = t.max_pe_d2 order by pa_name, ex_name 	0.00147051641580371
23869440	19673	how to sum (time(n)) in sql server?	select sum(         datediff(second, '00:00:00', [timecol])     ) from     ... 	0.386003126485285
23870583	40785	mysql: order by similar column values	select t.* from t join  ( select count(*) count , productid from t  group by productid   ) t2 on(t.productid = t2.productid) order by t2.count desc, t.productid,t.ordernumber 	0.0172352971555535
23872827	26399	nearest place within the latitude and longitude	select parties from mytable where distance(latitude,longitude,x,y) < 10 	0.106726424459907
23872830	34917	how do sql query: select *from tablea where number_1 in (select number_1 from tablea) > (select number_2 from tablea)	select *                           from tablea emp where exists (     select *      from tablea boss     where boss.id = emp.chief_id       and boss.salary  < emp.salary      ); 	0.740005103882469
23873325	28456	checking one row against the next in sql	select t.* from (select t.*,              (select t2.end_date               from table t2               where t2.start_date < t.start_date               order by t2.start_date desc               limit 1              ) as prev_end_date       from table t      ) t where prev_end_date >= start_date; 	0.000232519269912642
23873500	14390	sqlite join tables and select where column contains	select p.*, group_concat(posttagrel.tag_id) as tags  from posts p  left join posttagrelatives posttagrel on posttagrel.post_id = p.id  where 2 = ( select count(*)             from posttagrelatives ptr             inner join tags t on (t.tag_id = ptr.tag_id and ptr.post_id = p.post_id )             where t.tag_name in ('published','favorites') ) group by p.id 	0.0519196525128268
23873874	28550	select a distinct column with it's relative id	select * from table1  where id in (select min(id) from table1 group by `value`) 	0.000485865763505824
23875835	17311	sql join, select and where	select f.title, f.rental_fee from film f inner join filmtype t on f.type_id = t.type_id where f.certificate=12 and t.type_name='drama' 	0.62522631198194
23876431	13592	mysql left join first and second results and return as one row	select   members.member_id,   members.member_name,   c1.contact_name as contact_1,   c2.contact_name as contact_2 from   members   left join contacts as c1 on (members.member_id=c1.member_id)   left join contacts as c2 on (members.member_id=c2.member_id and c1.contact_id <> c2.contact_id) group by members.member_id 	8.3480297073932e-05
23877384	35998	mysql count and group by	select `reporter`, count(*) from `details` where `details`.lastchecked > date_sub(now(), interval 1 hour) group by `reporter` 	0.200590238144674
23878791	3903	greater than in case when in sql	select case when (timestampdiff(second,last_active,now())) > 100 then 'true' else 'false' end  from sessions where uuid=11 and token='test'; 	0.597768027192644
23879012	35335	search two tables in one query	select id, startdate, enddate , '-' as point_id  from sarcshiftcentertable  where startdate >='2014-05-27' and enddate <='2014-06-27' union select id, startdate, enddate, point_id  from sarcshiftpointtable  where startdate >='2014-05-27' and enddate <='2014-06-27' 	0.00988196730346884
23881014	17268	mysql query select count where in group by	select user_id, sum(bid_credits), sum(bid_credits_free) from bids_history  where auction_id = 9438 and user_id in (62323,76201) group by user_id; 	0.395782291129896
23881018	14702	how can i count an sql field for the number of results within a range?	select case when overdueby >= 50 then '50+'  when overdueby >= 40 and overdueby < 50 then '40-49' when overdueby >= 30 and overdueby < 40 then '30-39' ..... else 'less than that' end as overduerange, count(*) as overduecount, sum(amount) as [total amount] from yourtable group by case when overdueby >= 50 then '50+'  when overdueby >= 40 and overdueby < 50 then '40-49' when overdueby >= 30 and overdueby < 40 then '30-39' ..... else 'less than that' end 	0
23881322	14183	sql query - mathematical query across 2 tables	select sum((day1+day2+day3+day4+day5+day6+day7+day8+day9+day10+day11+day12+day13+day14) * rate * ot) as totall from from timesheet inner join rates on timesheets.rate-id = rates.id 	0.152000953104016
23882372	21674	sql subquery to return min of a column and corresponding values from another column	select id, course_count, days_to_first, c2.course first_course from (     select s.id, count(c.course) course_count,          datediff(min(datepassed),s.dateenrolled) as days_to_first,         min(datepassed) min_datepassed     from student s         left join course c on c.studentid = s.id      where s.dateenrolled between '2013-01-01' and '2013-12-31'         and s.id not in (select id from expelled)     group by s.id ) t1 left join course c2      on c2.studentid = t1.id     and c2.datepassed = t1.min_datepassed order by id 	0
23882764	31229	how to return one part of the string in mysql?	select substring_index('saturday sunday',' ',1) select substring_index(your_column,' ',1) from table 	0.000318319378800193
23883215	1933	sql server user roles that have roles inside them	select dbrole = g.name,     membername = u.name,     membersid = u.sid from sys.database_principals u,     sys.database_principals g,     sys.database_role_members m where g.name =     and g.principal_id = m.role_principal_id     and u.principal_id = m.member_principal_id     and u.name in (         select name         from sys.database_principals         where type = 'r'         ) order by 1, 2 	0.00318939826657415
23884612	20606	sql query that gives smallest date per match	select a.appointment_id, ms.do_by, a.sale_id (       select a2.sale_id as sale_id, min(a2.do_by) as do_by       from [askus7].[crm7].[appointment] a2 join [askus7].[crm7].[sale] s2       on a2.sale_id=s2.sale_id       group by a2.sale_id )ms join [askus7].[crm7].[appointment] a on a.sale_id = ms.sale_id and a.do_by = ms.do_by; 	0.00233824319492242
23885446	12748	select data from three different tables with null data	select * from [user] inner join [parentchild] on ([parentchild].userid = [user].id)  left join [location] on ([location].userid = [user].id) where parentid=7 	0.000267692508681074
23885780	32555	retrieve last 2 rows from a table in mysql database	select id, type, details from supportcontacts order by id desc limit 2 	0
23886084	14883	how can i disable the where clause at the query when the parameter is not passed to the the report?	select * from table_name where column_name = $p{parameter_name} or $p{parameter_name} is null 	0.681164590608637
23888516	10763	query for row data as columns in mssql?	select  date = t.entrydate,         debitledgername = dl.ledgername,         creditledgername = cl.ledgername,         d.amount from    [transaction] as t         inner join debitcredit as d             on d.transactionid = t.transactionid             and d.isdebit = 1         inner join ledger as dl             on dl.ledgerid = d.ledgerid         inner join debitcredit as c             on c.transactionid = t.transactionid             and c.isdebit = 0         inner join ledger as cl             on cl.ledgerid = c.ledgerid; 	0.00660378050938677
23889562	5274	how can get max salary in each department? sql (join, max)	select table_department.id, table_department.nome, max(table_people.salary) from table_department inner join table_people on table_people.dep_id = table_department.id group by table_department.id, table_department.nome 	0
23889589	23391	sql query - return rows from table a matching any row in table b	select  b.location,  (other fields of interest) from  tableb b join  (select a.location, min(a.workdate) as min_workdate    from tablea a       group by a.location) c on b.location = c.location where c.min_workdate > '201201' 	0
23890433	23429	sql query to fetch data between starting and ending null	select * from company where id between     ( select min(id)         from   company       where  company_name is not null ) and     ( select min(id) - 1       from   company       where  company_name is null       and    id > ( select min(id) min_id                      from   company                     where  company_name is not null ) ) 	0.000995781630427048
23891916	40497	adding values returned by sql query to get the total?	select sum(weight * quantity) as totalweight from orderitems where orderid = @orderid; 	7.42505156990491e-05
23892992	35162	mysql - product attributes select	select distinct products.* from products where exists (select 1 from product_has_specification join specifications on product_has_specification.spec_id = specifications.id_specification where specifications.name = 'color' and product_has_specification.value='black' and products.products.id = product_has_specification.product_id)  and exists (select 1 from product_has_specification join specifications on product_has_specification.spec_id = specifications.id_specification where specifications.name='size' and product_has_specification.value='s' and products.products.id = product_has_specification.product_id) 	0.0613929805847451
23893876	39605	mysql left join - returning rows using null and a condition	select   shift.*  from shift  left join (select distinct shift_id from event where type = 4) event on event.shift_id=shift.id  where event.shift_id is null; 	0.58496803953466
23894620	25448	join another table without a join for limit at one	select t1.a, t1.b (select top 1 t2.a from t2 where something = true) as c, (select top 1 t2.b from t2 where something = true) as d from t1 	0.00195101434270732
23895863	26304	average spend per customer in database	select m.uid, avg(m.amount) from mytable m  group by m.uid 	5.63033638511765e-05
23896133	11116	update column with values from another column using a cursor	select rowid,   dense_rank () over (order by column1, column2) groupnum  column1, column2, row_number () over   (partition by column1, column2 order by rowid) seqnum  from table1  where (column1, column2) in   (select column1, column2   from table1   group by column1, column2   having count(*) > 1) 	0.000406812823676104
23899566	2933	sql making last year's data into another column	select revenue, country, date   , (     select revenue     from revenue r2     where r1.country=r2.country       and r1.date = dateadd(yy,1,r2.date)   ) as lastyearrevenue from revenue r1 	0
23899632	34009	difficult mysql query to determine rank for a parent based on aggregated child data	select count(*) as rank from (   select sum(c.score) as parentscore     from child   group by parent_id      having parentscore <= (select sum(c.score) from child where parent_id = _parent_id) ) as scores 	0.00025752257476342
23901601	27993	subtract column with the next column in a different row	select a.matrix_no, a.descriptions, a.debit - b.credit as total from (select * from matrix where debit > 0) a inner join (select * from matrix where credit > 0) b on a.matrix_no = b.matrix_no and a.descriptions = b.descriptions 	0
23903745	22022	select a data using a keyword that exists in all columns (sql)	select      mytable.* , from mytable join (      select        id,        ifnull(col1,'')+ifnull(col2,'')+...+ifnull(coln,'') concatenated       from mytable ) t on t.id = mytable.id where   t.concatenated like '%x%' 	0.00147846391477907
23904654	27874	converting a date format in sybase	select convert(char(12),cast("may 8 2014" as datetime) ,103) 	0.149652523165939
23904742	32123	first value (oracle) equivalent in hive	select col_a, min(   named_struct(     'col_c', -coalesce(col_c, 0),     'len' , length(col_b),     'col_b', col_b   ) ).col_b from tablea group by col_a 	0.372526822951025
23905773	24020	how to get 5th maximum value from a table in sql?	select *  from products order by price desc limit 5, 1 	0
23905808	38345	adding a month to a date. setting day to last day of given month	select date_trunc('mon','2014-04-30'::date+interval'2mon')-interval'1day',        date_trunc('mon','2014-05-31'::date+interval'2mon')-interval'1day'; 	0
23907213	31148	how to separate query result by comma	select  stuff((select ','+ cn.name  from wmccmcategories cn                 inner join categorysets uc on uc.categoryid = cn.categoryid                 inner join keyprocesses u on u.categorysetid = uc.setid                inner join companies c on c.companyid = u.companyid                where c.companyname = 'some name'                order by sortorder     for xml path('')), 1, 1, '') as liststr  from wmccmcategories cnn group by cnn.name 	0.0112519185547937
23908684	18908	sql: display all the records related to common id	select id,group_concat(title separator '\n') from mytable group by id 	0
23910094	11244	show records that counts data of a certain column and summing up total amounts	select `bettype`,        count(`bettype`) as count,        sum(`betamount`) as betamounttotal,        sum(`payout`) as payouttotal from `betdb` left join `matchdb` on `betdb`.`matchid` = `matchdb`.`matchid` where `betdb`.`matchid`=135 group by `bettype` 	0
23910917	29437	how to get rows with count of occurence (frequency) in the table	select top 2 albumid, count(*) frequency from tbl where genreid=5 group by albumid  order by 2 desc 	0
23912278	10174	how can i prevent getting duplicates with this union select (or a different method)	select dealdate, datereceived, bounced, stocknumber,     locationname, customername, comment  from tvehicledeal vd    join tdealerships d        on d.dealershipid = vd.dealershipid         and d.dealershipname like '%'+@dealership+'%'    join tinternallocations il        on il.internallocationid = vd.internallocationid         and il.locationname <> 'down deal'     join tcustomer cu        on cu.customerid = vd.customerid    left join tvehiclecomments c        on c.dealid = vd.dealid where vd.titled is null    and vd.archived = 0 	0.673529726756336
23912455	23862	get value for each day in month	select date, max(onlineusers), sum(messagessent) from stat where date between '2014-05-01' and '2014-05-31' group by date 	0
23915595	1830	list of count for each date	select  a.insdatetime,         b.n from (  select distinct convert(date,insdatetime) insdatetime         from dbo.queues) a outer apply (select count(*) n              from dbo.queues              where insdatetime < a.insdatetime) b where a.insdatetime >= '20140501' 	0
23916540	30299	find all tables that have x column name	select t.name  from sys.tables t inner join sys.columns c on t.[object_id] = c.[object_id] where c.name like '%columnname%' 	0
23918108	26072	charindex is returning 0 even when the substring is present	select charindex('a$bc', '$') as wrong, charindex('$', 'a$bc') as ok 	0.678948213118258
23918232	12535	query between 2 tables, merge the results. postgresql	select tab1.id  , coalesce(tab2.value, tab1.value ) as the_value from tab1  left join tab2 on tab1.id = tab2.id     ; 	0.00176118334785401
23919224	39228	classifying months in periods	select     year, mn,     row_number() over (order by year, mn) as period from t 	0.00861202268888769
23919372	39162	sql server sql "down filling" data that doesn't exist in source table	select t2.company, t2.type, t1.dt, t2.value from tbldata t1,       tblfact t2 where t2.dt <= t1.dt and   not exists (select top 1 1                   from tblfact t22                   where t22.dt <= t1.dt                   and   t22.dt > t2.dt) 	0.0332956250226956
23924296	20383	how to create a query to exclude specific obejct in table	select *  from disk_table  where not (machine = 'b' and instance = 'c:') 	0.00174878725560586
23925408	31457	mysql query to get result between the two given dates	select      mdn,     recharge_status_code,     recharge_status_code_desc,     date_time,     retry_status  from impressions_log  where recharge_status_code in ('515')      and date(date_time) between '2014-05-18' and '2014-05-24'; 	0
23926669	34551	how can i use the query to get the output with comma seperator in oracle?	select to_char(rate, '999.99'), to_char(amount, '999,999,999,999,999') from tt_table 	0.0482677841226349
23927747	16949	ms access group by number of distinct items in column	select agentcode     ,sum(iff(status='registered',1,0)) as registered     ,sum(iff(status='rejected',1,0)) as rejected     ,count(status) as total from table group by agentcode 	0.000733468589185799
23927754	22906	get last rows based on datetime and using name	select t1.location, t2.t2_dt as dt, t1.temperature  from table_name t1  join (   select   location,   temperature,   max(dt) as t2_dt   from table_name   group by location )t2 on t2.location = t1.location and t1.dt = t2.t2_dt group by t1.location 	0
23929405	7818	sum() different columns according to row values	select month,     year,     sum(3r00) one,     sum(3r01) two,     sum(3r02) three,     sum(3r03) four from table group by month,     year 	0
23929652	2756	sql algorithm with three identifiers from one table	select planid, production_nr from information inf1 where not exists (select 1 from information inf2                   where inf1.planid = inf2.planid                   and   status < 3) 	0.00469418073330526
23933528	51	comparing two sql tables i want to always output a table 1 value if they have an id in common output table 1 value and table 2 value	select table1.value, table2.additionalinfo from table1 left outer join table2 on table1.id=table2.id 	0
23933817	9247	sql 2005 update column on insert	select  login_id,         login_id_name,         date_begin,         (   select  min(date_begin)             from    [#loginid_name] as l2             where   l2.login_id = l.login_id             and     l2.date_begin > l.date_begin         ) as date_finish from    [#loginid_name] as l; 	0.135747539850072
23934424	12559	run a query consisting of subqueries only	select  (select count(id) from customers  where customers.isdemo =0  and customers.islead=0  and regtime < '2012-01-01') as totalnumofcustomers, (select count(id)  from customers  where customers.isdemo =0  and customers.islead=0  and regtime >='2012-01-01'  and regtime < '2012-02-01') as totalnumofcustomerspermonth, (select count(positions.id) from positions   left join customers on positions.customerid = customers.id  where date >= '2012-01-01'  and date < '2012-02-01'  and customers.isdemo=0  and customers.islead=0  and status != 'canceled') as totalpositions, (select round(sum(amount),2) - round(sum(payout),2) from positions   left join customers on positions.customerid = customers.id  where date >= '2012-01-01'  and date < '2012-02-01'  and customers.isdemo=0  and customers.islead=0  and status != 'canceled') as grossincome; 	0.431801362770231
23936578	26600	sql query - filtering results from multiple matches	select msm.galaxyid, min(prog.galaxyid) as proggalaxyid, msm.maxstellarmass, msm.snapnum from (select des.galaxyid, prog.snapnum, des.lastprogenitorid, max(prog.stellarmass) as maxstellarmass from dbase prog, dbase des where des.galaxyid in (0,3000042000000,1000019007037)      and prog.galaxyid between des.galaxyid and des.lastprogenitorid      and prog.snapnum in (63, 48, 27)  group by des.galaxyid, prog.snapnum, des.lastprogenitorid) as msm join dbase prog on prog.galaxyid between msm.galaxyid and msm.lastprogenitorid and  prog.snapnum=msm.snapnum and prog.stellarmass=msm.maxstellarmass group by msm.galaxyid, msm.maxstellarmass, msm.snapnum 	0.0284692892494248
23936771	5092	combine two oracle queries	select aq.batchnum,          aq.status,          (dateended - datestarted) * 24 * 60 minutes,          count (*) page_count     from archivedqueue aq,          itemdata id,          itemdatapage idp,          (select *             from scanninglog            where usernum = '3724' and actionnum in ('200', '202')) sl    where     aq.batchnum = id.batchnum          and idp.itemnum = id.itemnum          and aq.batchnum = sl.batchnum          and aq.batchnum = '648353'          and aq.datestarted between to_date ('27-may-2014 00:00:00', 'dd-mon-yyyy hh24:mi:ss')                                 and to_date ('29-may-2014 23:59:59', 'dd-mon-yyyy hh24:mi:ss') group by aq.batchnum, aq.status, (dateended - datestarted) * 24 * 60 order by aq.batchnum desc; 	0.0536571964158225
23937997	2004	get non repeating data from pivot table	select * from video  where video_id in  (select video_id from video_category  where category_id not in (list of meaninless ids)) 	0.000346504615413469
23938562	19819	count for one value in multiple columns sql	select t1.d, (   select count(*)    from table2 s2a    where s2a.d1 = t1.d ) as count_d1, (   select count(*)    from table2 s2b   where s2b.d2 = t1.d ) as count_d2, (   select count(*)    from table2 s2c   where s2c.d3 = t1.d ) as count_d3, (   select count(*)    from table2 s2d    where s2d.d4 = t1.d ) as count_d4 from table1 as t1 	0.000393959150455826
23940223	18871	how to group all conversations in a database by date, conversation thread	select a.id, a.sender, a."to", a.msg, a.timestamp from table1 a join table1 b   on case when a.sender=9 then a."to" else a.sender end =      case when b.sender=9 then b."to" else b.sender end  group by a.id, a.sender, a."to", a.msg, a.timestamp order by min(b.timestamp), a.timestamp 	0.000480442706708106
23940461	4372	mysql query for selecting friends	select  actors.first_name,         actors.last_name from    actors where   actors.login in (     select  friendslist.loginf     from    friendslist     where   friendslist.logina = 'xstad' ) 	0.0152002905194275
23940764	9876	get the latest n results for each person	select * from (     select a.* from points as a     left join points as a2     on a.person= a2.person and a.time <= a2.time     group by person, time     having count(*) <= 2) a order by person asc, time desc; 	0
23941305	21021	set order by clause dynamically for procedure based data block	select ... from ...  order by decode(:val, 1, col1, 2, col2) 	0.0483432550892281
23942235	31678	sql select max and 2nd max	select accountnumber,    max(mydate),    (select max(sd2.mydate) from #sampledata sd2 where sd2.accountnumber=#sampledata.accountnumber and sd2.mydate<max(#sampledata.mydate)) from #sampledata group by accountnumber 	0.00903841197205436
23942744	13403	performing an operation within each group of rows	select day, workflow_id   , max(unix_timestamp(finished_time)) - max(unix_timestamp(finished_time)) from modeling_dashboard_workflow_stats group by day, workflow_id 	0.000996182501459826
23943203	25410	convertion nvarchar to decimal	select nom ,sum(cast(replace(solde,',','.') as float)) as _solde from tab  where num_client='550322'  group by nom 	0.340499754703612
23943523	9823	sql query for selecting all items except given name and all rows with id of that given name	select cm.car_model_id, ci.car_location_name, cm.car_name from car_model cm join car_inventory ci   on cm.car_model_id=ci.car_model_id where cm.car_model_id not in (   select car_model_id from car_inventory where car_location_name='germany' ) 	0
23944461	38100	get multiple rows as comma separated string column and map values to temp table from junction table	select distinct us.siteid, stuff((select ', ' + u.email         from users u          join userssites us2 on us2.userid = u.userid         where us2.siteid = us.siteid             for xml path('')), 1, 2, '') from userssites us 	0
23945099	34587	sum two different columns in two different tables grouped by column in third table	select ci.cluster_name, hi.total_units, vi.allocated_units from cluster_info ci left join       (select hi.cluster_id, sum(hi.unit_count) as total_units       from host_info hi       group by hi.cluster_id      ) hi      on ci.cluster_id = hi.cluster_id left join      (select vi.cluster_id, sum(vi.unit_count) as allocated_units       from vm_info vi       group by vi.cluster_id      ) vi      on ci.cluster_id = vi.cluster_id ; 	0
23945896	16865	crystal reports or t-sql: comparing multiple records values based on values in another table	select x.vendor, x.productid, i2.inventorycount - i.inventorycount inventorycountdiff, i2.inventoryvalue - i.inventoryvalue inventoryvaluediff from (     select i.vendor, i.productid, max(e.entrydate) maxentrydate, (select max(e2.entryid) from entry e2 join inventory i2 on i2.entryid = e2.entryid and i2.vendor = i.vendor and i2.productid = i.productid where e2.entrytype = 10) maxentryid     from inventory i      join entry e on e.entryid = i.entryid     group by i.vendor, i.productid ) x join inventory i on x.vendor = i.vendor and x.productid = i.productid join entry e on i.entryid = e.entryid join inventory i2 on x.vendor = i2.vendor and x.productid = i2.productid join entry e2 on i2.entryid = e2.entryid where e.entrydate = x.maxentrydate and e2.entryid = x.maxentryid 	0
23947610	10134	to display top 4 rows using mysql rank is displaying wrong	select t.agentid,t.amount, @rownum := @rownum - 1 as rank  from  (select agentid,sum(amountrecevied) as amount  from collection   group by agentid  order by amount  limit 4) t,(select @rownum := 11) r 	0.00403303467190248
23947882	11643	difference between a column of two constitutive rows in sql	select name  from (  select t.*,        @prev as previousage,        @prev:=age    from t,(select @prev:=null) as t1    order by id ) as t3 where age-previousage>10 	0
23948021	9194	order a list by the second and third text in a field	select * from table order by substr(prono,5,2), substr(prono,8,2) 	9.18576857868442e-05
23950543	5657	mysql distance calculating	select user_id,      sqrt(         pow(69.1 * (lat_col - 60.454509), 2) +         pow(69.1 * (9.667969 - lng_col) * cos(lat_col / 57.3), 2)     ) * 1.609344 as distance     from users order by distance asc 	0.130511415604584
23955094	32640	left join don't list multiple rows	select product.id as pid, product.name as pname, sum(amount.amount) as amnt from product left join amount on product.id=amount.pid where product.name like '%o%' group by product.id 	0.0206912431634051
23958477	11491	grouping records in order (sql)	select count(*) "count", min(id) starting_id, number from (   select a.id, a.number, a.number || '-' || count(b.id) seq   from mytable a   left join mytable b     on a.id > b.id and a.number <> b.number   group by a.id, a.number ) group by seq order by id; 	0.0412381333052772
23958705	32379	order by single column using multiple where clauses	select     l2.id,     l2.lang_id,     l2.key,     l2.text from     language l1 join     language l2     on l2.key = l1.key where     l1.lang_id = 1     and     l2.lang_id = 2 order by     l1.id  	0.0748006248508007
23961317	34979	data from several temp tables to be consolidated in one temp table	select a.cstid, sum(case when processed = 'yes' then 1 else 0 end) as num_yes, count(cst_id) as num_total from #temp a   inner join cst b on a.caseseveranceid = b.caseseveranceid group by a.cstid 	0.00038304527196238
23961808	38317	sqlite misuse of aggregate: sum()	select email_to, count(*) as total_emails from emails where email_box='sent' group by email_to order by total_emails 	0.450209999048632
23962278	40782	get a list of all columns that do not have only null values in sql server	select 'select '''+syscolumns.name+''' from '+sysobjects.name+' having count('+syscolumns.name+') > 0' from syscolumns with (nolock)  join sysobjects with (nolock) on syscolumns.id = sysobjects.id where syscolumns.id = (select id from sysobjects where name like 'email') 	0
23964041	11454	selecting if all row ids exists in other table with column check	select count(*) from sites  where site_id not in (select distinct site_id from callback_votes where ip='1.0.0.127') 	0
23964972	5226	sqlite fails to find existing column in select via jdbc and jooq	select location.name,         world.world,         player.player  from   location         join world           on location."world-id" = world."world-id"         left outer join location2player           on location."location-id" = location2player."location-id"         left outer join player           on location2player."player-id" = player."player-id" 	0.0422177668040226
23967185	15205	mysql natural sorting of alphanumeric values	select * from ab order by     substring(col,1, case when locate(' ',col) = 0 then 100 else locate(' ',col) end ),    substring(col,case when locate(' ',col) = 0 then 100 else locate(' ',col) end ) + 0; + | col             | + | in-direct labor | | level 1         | | level 2         | | level 3         | | level 4         | | level 5         | | level 6         | | level 7         | | level 8         | | level 9         | | level 10        | | level 11        | | level 12        | | level 13        | | level 14        | | level 15        | | level 16        | | level 17        | | risers  risers  | | roof/penthouse  | | site            | + 21 rows in set (0.01 sec) 	0.071015583242053
23968817	7619	mysql - using table data twice	select      k.rnaam as kind,     v.rnaam as vader,     v.gesl         from dier v         join dier k             on v.dnr = k.vader         join soort s             on s.snr = v.snr     where         s.nsnaam = 'chimpansee' 	0.0552059841554808
23968932	14073	select substring of retrieved value	select myval,case when myval like '%[_]%' then substring(myval,1,patindex('%[_]%',myval)-1) else myval end from t 	0.00612417993203175
23970586	34958	select distinct with inner join	select distinct table_b.tb_name     from table_a          inner join table_b             on table_b.tb_id = table_a.ta_user     where ta_date like '%$vardate%'     order by ta_user asc; 	0.70634306344552
23970969	1995	multi count from multi table in sql	select (select count(*) from users) as user_count,        (select count(*) from cities) as city_count 	0.0214569152593911
23973477	33579	finding working days in sql	select work_date from (    with dates  as     ( select to_date('01/01/2014','mm/dd/yyyy') dt_start,      to_date('01/10/2014','mm/dd/yyyy') dt_end      from dual    )   select dt_start + (level-1) work_date   from dates   connect by level <= (dt_end - dt_start + 1 )   ) wdates where work_date not in ( select holiday_dt                          from country_holiday                         where country_id = 1) and to_char(work_date,'dy') not in ('sat','sun') order by work_date 	0.0270646419115058
23974682	8229	sql combined and select older by one day	select title, description from event_planner  where  date(concat('year','-',lpad('month',2,'00'),'-',lpad('day',2,'00'))) >= curdate() 	8.74683622235586e-05
23974887	38583	postgresql select random rows having given sum	select difficulty from {your_table} 	0.000952804059661907
23975297	15568	weekofyear 3 weeks ago	select weekofyear(date_sub(curdate(), interval 3 week)) 	0.00603851790205253
23976147	10653	sql query - excluding rows where one value of a column with multiple values matches	select ws.id     array(select distinct dn.name from domainname dn where ws.id = dn.website_id),      array(select p.code from promotionredemption pr, promotion p where p.id = pr.promotion_id        and pr.site_id = ws.id)   from   website ws  where  not exists (         select      1         from        promotion p         left join   promotionredemption pr             on  p.id = pr.promotion_id               where       pr.site_id = ws.id             and p.code = 'test'     )  order by     ws.id asc 	0
23977864	21915	unrandom back answers using view	select questiontext, [1], [2], [3] from (     select          row_number() over (partition by questionid order by answerid) answerinquestionid,         answertxt,          questiontext     from questions q         join answers a             on q.questionid=a.answer_question_id ) a pivot (     max(answertxt)     for answerinquestionid in ([1], [2], [3] ) ) as piv 	0.774054256307308
23978435	37763	sqlite query to add index for results	select (select count(*)         from inf_table as inf2         where inf2.group_id = inf_table.group_id           and inf2.name    <= inf_table.name    ) as "index",        group_id,        name from inf_table order by group_id,          name 	0.364832445499015
23979464	12478	select data from one table which is connected to another 2 tables	select count(id)  from   employees  where  exists (         select      1         from        job         where       id = employees.job_id             and     dept_id = 2     ) 	0
23979489	10486	how to sort a table using order by clause in desc order using difference in value of two other columns	select *, like-unlike as customorder from table order by customorder desc; 	0
23980662	13080	sql count statement with multiple date ranges	select id,         (             select  count(*)             from    table2             where   id = table1.id                 and table2.start_date >= dateadd(mm,-6,table1.start_date)         ) as table2records  from   table1 	0.0233924572419844
23981188	33676	mysql row number generation on statement already used join tables	select @currow:=@currow+1 as row_number, t1.commonname from ( select b.commonname as commonname from bodymass m left join bird b on m.eolid=b.eolid  where m.mass>2 and m.mass<=3.3 group by b.commonname ) t1, (select @currow:=0) t2; 	0.0110203057174294
23981404	36210	calculate difference in values between 2 tables	select orderid, (grandtotal-credits) from orders left join (select sum(credit) as credits from journal group by orderid) as credits on credits.orderid=jornal.orderid where orders.paid=false and customerid=@customerid 	0
23982931	2038	select distinct from multiple columns and its matching values sum	select x.prod      , sum(x.total) from (        select prod1 as prod, sum(prod_1_qty) as total from table group by prod1           union all        select prod2 as prod, sum(prod_2_qty) as total from table group by prod2             union all        select prod3 as prod, sum(prod_3_qty) as total from table group by prod3      ) x  group by x.prod 	0
23983477	6247	sql replace multiple ids with strings from another table	select el.date,    w.worker,    e.event,    r.registration    from    events_list as el     join     workers as w on el.worker=w.id    join     events as e on el.event=e.id    join    registration as r on el.registration_method=r.id 	9.88501094299541e-05
23986897	17611	postgresql output column from another table	select     e.id, e.group_id, e.name, e.stage, s.label from    entry e left join    storage_log sl on     sl.id = e.storage_log_id left join     storage s on     sl.storage_id = s.id 	0.00094907828863091
23987346	38390	sql - group & sum based on date	select d1,sum(case                 when d1=d2 then cnt                end            )  as count_d1_d2,          sum(case                when d1=d2 then sm               end              ) as  sum_d1_plus_d2,          sum(case                 when d2=d1+1 then cnt                end            )  as count_d1_d2_1,          sum(case                when d2=d1+1 then sm               end              ) as  sum_d1_d2_1 from test group by d1 	0.00180915745633078
23987741	3047	mysql how to query where round(avg(`row`)) equals	select `items`.`itemid`,        `items`.`name`,        `items`.`address`,        `items`.`suburb`,        `items`.`latitude`,        `items`.`longitude`,        `reviews`.`comment`,        round(avg(`reviews`.`rating`), 0) as avg from   `items`        right join `reviews` using (`itemid`) group  by `reviews`.`itemid` having round(avg(`reviews`.`rating`), 0) = 3 	0.484320473758588
23988292	6607	how to merge 2 tables with different structures into 1 table using mysql?	select t.appt_id,t.field1,t2.field2 from table1 t left join table2 t2 on t.appt_id = t2.appt_id union select t2.appt_id,t.field1,t2.field2 from table2 t2 left join table1 t on t.appt_id = t2.appt_id 	0
23989655	6966	how to get the ordered query in sqlite?	select * from test order by code, content; 	0.0038074623009675
23991959	39018	select distinct values - multiple rows of same id - multiple conditions	select distinct t.id, name, test1_score, test2_score from t inner join (select id, value test1_score from t where field_key = 'test1_score' and value >= 7) t1 on (t1.id = t.id) inner join (select id, value test2_score from t where field_key = 'test2_score' and value is not null) t2 on (t2.id = t.id) inner join (select id, value name from t where field_key = 'name') t3 on (t3.id = t.id) order by test1_score; 	0
23992730	19243	how can i get the sum of a column ?	select r.id as req_id,         r.project_id,        r.name as req_name,         r.cost,r.estimated,         p.name as project_name,         v.name as `status` ,         sec_to_time(sum(time_to_sec(a.duration)))  from requirements r       inner join projects p on p.projectid = r.project_id     inner join `values` v on v.id = r.r_status_id     left join tasks t on t.id_requirement = r.id     left join activities a on a.taskid=t.taskid where 1 = 1  group by r.id, r.project_id, r.name,r.cost,r.estimated,p.name, v.name order by req_id  desc 	0.00205046698106949
23994067	20864	sql: select the same column multiple times from a table	select   t_ticket.id,    t_ticket.description,    t_ticket.created_by,    e1.name as created_by_name,    t_ticket.updated_by,    e2.name as updated_by_name from   t_ticket  left join   t_employee as e1 on e1.id = t_ticket.created_by left join   t_employee as e2 on e2.id = t_ticket.updated_by 	0
23994802	6611	get friends of friends in php and mysql with this table structure	select distinct id from (     (select t1.inviter_id as id from tablename t1 left join tablename t2 on t1.friend_id = t2.inviter_id where t1.status = 1 and t2.status=1 and t2.friend_id = userid)     union     (select t1.inviter_id as id from tablename t1 left join tablename t2 on t1.friend_id = t2.friend_id where t1.status = 1 and t2.status=1 and t2.inviter_id = userid)     union     (select t1.friend_id as id from tablename t1 left join tablename t2 on t1.inviter_id = t2.inviter_id where t1.status = 1 and t2.status=1 and t2.friend_id = userid)     union     (select t1.friend_id as id from tablename t1 left join tablename t2 on t1.inviter_id = t2.friend_id where t1.status = 1 and t2.status=1 and t2.inviter_id = userid) ) as temp where id != userid and not exists (select * from tablename where (friend_id = id and inviter_id=userid) or (inviter_id = id and friend_id=userid)) 	0.00100078111574102
23995532	6783	converting the comma seperated string in oracle to the format for the in clause	select '''' || replace( '2611,2616,3306', ',', ''',''' ) || '''' from dual; 	0.00596173810791623
23996379	9266	sql count the distinct values that accomplish two condition for a single row	select count(distinct userid) from (     select userid      from mytable      where platform in ('ios', 'android')     group by userid     having count(distinct platform) = 2 ) 	0
23996740	18562	sql : fusion of lines from one table	select * from mytable t1  inner join  mytable t2 on t1.ida = t2.idb and t1.idb = t2.ida and t1.ida<t1.idb 	0.000192766191065892
23997836	1330	get variables from query with join	select c.name as clientname, d.name as devicename  from clients c join devices d on clients.id=devices.client_id 	0.0697344588778479
23997866	34148	selecting unique random values from different rows	select first_col,   max(second_col) keep (dense_rank first order by num) as rand_second_col    from  (select first_col, second_col,dbms_random.value() as num   from table)  tmp   group by first_col 	0
23998690	35323	calculate percentage with t-sql statement while using group by	select  datediff(dd,duedate,enddate) as 'days late', count(workorderid) as 'late orders', (count(workorderid)*1.0 / (select count(1) as totallateorders from production.workorder where duedate < enddate)) as '% of late orders' from production.workorder where duedate < enddate group by datediff(dd,duedate,enddate) order by datediff(dd,duedate,enddate); 	0.206921524928206
23999662	22688	join and have child table go into new columns on the parent table	select a.p2p_id, a.address,a.city, a.state,a.zip, a.date, group_concat(concat(first_name,' ', last_name)) as name from site s  join attend a on s.p2p_id=a.p2p_id  group by a.p2p_id, a.address,a.city, a.state,a.zip, a.date, 	0
24000720	10507	sql query from a tutorial table using having	select yr from nobel where subject = 'physics' group by yr having count(winner) = 3 	0.31738981255453
24000767	40679	update query: sum divided by count between 2 different columns in 2 different tables	select count(mastertable.acct1) 	0
24000883	12393	ado recordset type for date	select convert(datetime, annoyingfield) from crazyfuturistictable 	0.138547225158697
24001549	31213	query to combine 2 column into 1 from same table	select mdc + '-' + mdctext as mdc_new from mdccategories 	0
24001880	27263	combining rows without a unique identifier	select a.*, b.reference as 'modify', b.details as 'expires' from my_table a join my_table b on a.pri_key = b.pri_key - 1 where a.type = 'a' 	0.0330262419249001
24003609	37812	sql: new column with calculation data	select staff_id      , first_name      , surname      , hourly_rate as "old hourly rate"      , (hourly_rate*1.10) as "new_hourly_rate" from copy_am_staff where staff_type = 'instructor' 	0.0624000814707772
24004681	3305	sql query with conditional order by for a specific condition	select [companyname]      , [companycode]      , sortorder = case when companyname is null then 3                         when companyname = 'mycompany' then 1                         else 2                     end   from [dbo].cond_orderby_test  order by 3 asc, companyname asc 	0.630643719787778
24005327	37818	exclude certain value in order by and duplicate	select country from (select 1 as priority, country       from countries       where country = "holland"       union       select 2 as priority, country       from countries) as subquery order by priority, country 	0
24005687	6846	trying to find the average of each date of the years using php?	select day(date) as day, avg(amount) as avg_amount from apple where month(date) = 6 group by day 	0
24006000	7321	complex two table join	select distinct s.sensorid,s.msg,s.name from sensorrule s,sensordata d where s.sensorid=d.sensorid and  time(d.messagedate)>s.fromtime and  time(d.messagedate)<s.totime; 	0.366499371055958
24006733	9362	mysql check no records within 3 months with group limit by 1 show the last transaction	select name, max(dttransaction) from <tablename> where date <= curdate() - interval 3 month group by name 	0
24008607	8214	sql: get parent join child where child type = 1 and child type = 2	select * from city join   (      select city_id from airports where type in (1,2)      group by city_id      having count(distinct type) =2    ) as a   on city.id=a.city_id 	0
24008897	15657	how to join two columns to the same table	select u1.username as userfrom,u2.username as userto, m.message from messages m join      aspnet_users u1 on u1.userid=m.userfrom join      aspnet_users u2 on u2.userid=m.userto 	7.20288492716249e-05
24009613	34194	select products by condition in another table	select distinct jshopping_products.* from   jshopping_products    join extra_field_values field_1 on jshopping_products.extra_field_1 = field_1.id    join extra_field_values field_2 on jshopping_products.extra_field_2 = field_2.id where     field_1.name between 100 and 120 and     field_2.name between 200 and 205 	0.00130691160767411
24010933	1615	how to show spaces in columns which do not have data in oracle	select   pa_cpnt.cpnt_id,   pa_cpnt.cpnt_desc,   min(case when subj.rn = 1 then subj.subj_id end) as subj_id1,   min(case when subj.rn = 2 then subj.subj_id end) as subj_id2,   min(case when subj.rn = 3 then subj.subj_id end) as subj_id3 from pa_cpnt left outer join  (   select      cpnt_id,      subj_id,      row_number() over (partition by cpnt_id order by subj_id) as rn   from pa_cpnt_subj  ) subj on subj.cpnt_id = pa_cpnt.cpnt_id group by pa_cpnt.cpnt_id, pa_cpnt.cpnt_desc; 	0.000942658435938554
24012806	2692	summary of service rating in sql	select rates, [5] as 'excellent' ,[4] as 'very good',               [3] as 'good',[2] as 'average' ,[1] as 'poor' from( select * from     (select rateto, q1,q2,q3,q4,q5    from servicerating) p unpivot    (rate for rates in        (q1,q2,q3,q4,q5) ) as unpvt ) x  pivot (  count(rate) for rate in  ([5],[4],[3],[2],[1]) ) as pvt 	0.0811843291371197
24015524	24136	how to acquire number of times a value is found in several columns	select files, count(*) from (     select slot1 as files from your_table where slot1 is not null     union all     select slot2 from your_table where slot2 is not null     union all     select slot3 from your_table where slot3 is not null     union all     select slot4 from your_table where slot4 is not null     union all     select slot5 from your_table where slot5 is not null ) sq group by files 	0
24015614	7588	exclude rows with specific columns values from select	select stock, quant from yourtable where not(stock_status = 10 and quantity <= 0); 	0
24017590	6673	how to have mysql only show results that have been modified in the last 11 seconds	select msg.sender, msg.gamename, msg.modtime from msg where msg.sender ='".$sender."' and msg.modtime >= date_sub( now() , interval 10 second ) order by msg.sender asc 	0
24017693	32403	select distinct values with count in postgresql	select country, count(country) as city_count from table group by country 	0.0242310537254201
24017967	6598	selecting nested data from multiple mysql tables	select * from betting_sport left join betting_group on betting_sport.id = betting_group.betting_sport_id left join betting_league on betting_group.id = betting_league.betting_groupid left join betting_match on betting_league.id = betting_match.betting_league_id where betting_match.status = 1 	0.00472653610706212
24018123	29740	wordpress sql with category addition	select u.id, u.user_nicename, u.display_name, u.user_email, p.post_date, p.id, ktt.taxonomy, kct.name from kc_users u  inner join (select post_author, max(post_date) post_date, id         from kc_posts          where post_type = 'post' and post_title != 'auto draft' and post_title != '' and post_status = 'publish'          group by post_author) p  inner join kc_term_relationships ktr on ktr.object_id = p.id inner join kc_term_taxonomy ktt on ktt.term_id = ktr.term_taxonomy_id inner join kc_terms kct on kct.term_id = ktt.term_id where u.id = p.post_author  and ktt.taxonomy = 'category' order by u.display_name 	0.207158815503933
24018242	39199	sql: use table from table valued function	select     @runs = count(*),     @won = sum(case when posnum = 1 then 1 else 0 end) from tvf_horse_going('allow me', 'heavy') set @perc = (@won * 100) / @runs 	0.63196721537758
24018377	39090	sql server adding numbers between rows without cursor	select t.*, sum(val) over (partition by firstname, lastname order by date) as cumsum from table t; 	0.0130414348409715
24019288	32108	inner joins on 3 tables how to get the id of the max values of a date?	select con_id, max(com_datetime) from (     select con_id, com_datetime      from con_conversation     inner join cou_conversationuser as cu using (con_id)     inner join com_conversationmessage as cm using (con_id)     where cu.usr_id = 4328 and cm.usr_id = 4328     order by con_id desc ) as sub group by con_id order by max(com_datetime) desc 	0
24019708	16794	moving average in sql	select consumption_month,    avg(b.power_consumption) from  (     select distinct date_format(`date`, '%y%m') as consumption_month from consumption_table a ) a inner join consumption_table b on consumption_month >= date_format(b.`date`, '%y%m') where b.`date` >= '2014/04/01' group by consumption_month 	0.0135217879437549
24022064	15814	add time stamp to date in sqlserver	select cast (dateadd(hh,6,dateadd(wk, datediff(wk, 6, getdate()), 0)) as datetime) 	0.00198196938920825
24022202	37668	how to output from select statement only if all rows have the same value	select *     from rule r1     where r1.ruleid = 27460     and r1.data = (select r2.data from rule r2 where      r2.data='true' and r1.data = r2.data)     limit 1; 	0
24022306	23689	mysql - get row if another rows value is set for a group of records	select a.submit_time, b.value from dbplugin_submits a  join dbplugin_submits b on (a.submit_time = b.submit_time and b.field_name='your-email') where  a.field_name = 'checkbox-signup' and a.value = 'signup for our email newsletter' 	0
24023824	32506	mysql rank by column value grouped by column value	select t.*,    @current_rank:= case when @current_rank = competition               then  @video_rank:=@video_rank +1               else @video_rank:=1 end  video_rank,    @current_rank:=competition from t , (select @video_rank:=0,@current_rank:=0) r      order by competition desc, votes desc 	7.16942740715045e-05
24024964	3951	advanced sql select to get same column value with different heade name	select a.file_name , a.sn as 'udav' , b.sn as 'hemat' , c.sn as 'cci' from  ( select agnt_serial_num sn from t1 where agnt_name ='uv inhibitor' ) a ,( select agnt_serial_num sn from t1 where agnt_name ='hematoxylin' )b ,( select concat(agnt_serial_num,'_',agnt_lot_num) sn from t1 where agnt_name ='carbon morpher' ) c where a.file_name = b.file_name and b.file_name = c.file_name 	5.91706122878915e-05
24028999	6381	mysql rooms availability for range	select a.title, ifnull(sum(datediff(least(b.end, '2014-06-30'), a.start) + 1),0) days_taken from rooms a left join rooms_booking b on a.id = b.rooms_id where b.start >= '2014-06-15' and b.start <= '2014-06-30' group by a.title having days_taken <= datediff('2014-06-30', '2014-06-15'); 	0.0191425136034109
24030674	30077	postgres aggregating conditional sum	select o.work_order_number dn       , sum(opd.qty) units       , sum ( opd.qty * case pc.type                             when 'tees' then 0.75                             when 'jerseys' then 1.5                         end ) as weight from ... group by o.work_order_number 	0.479907586602381
24031077	36740	selecting rows with max attribute value	select * from table1 t          join (select clientid,max(version) as mver                 from table1 group by clientid) s          on t.clientid = s.clientid and t.version  = s.mver 	5.54299807461624e-05
24032027	32092	sql select distinct or a new table?	select distinct 	0.0267438937444148
24034678	630	get count by unique values in a column	select parent, sum(frequency) as freq from (select distinct parent, item, frequency from sampletable) as t  group by parent order by freq desc 	8.50154828895314e-05
24034924	33448	sql bank db: return only people with a given property	select c.customerid, c.name, a.uan, a.balance, a.overdraft   from customer c join current_acc a   on c.customerid = a.customerid and a ='current account' 	0.00024366328219309
24036720	21934	sql query to group by and merge rows	select t1.col1,t1.col2,t2.col3 from (select col1,col2,row_number()over(order by col1) as rn  from tablename  where col2 is not null) t1 full outer join (select col1,col3,row_number()over(order by col1) as rn  from tablename  where col3 is not null) t2 on t1.col1=t2.col1 and t1.rn=t2.rn 	0.0167523490982447
24037046	4620	how to insert current year and next year using sql query in vb.net	select year(getdate()) as fl_date union select year(getdate()) + 1 	0
24038381	11741	tsql un-pivot 2 columns	select letter, val from @t unpivot(val for letter in (a,b,c,d)) as unpvt 	0.0495586069014469
24038600	3385	joining two tables but with select requiring all secondary columns to be the same	select distinct r.ruleid,                 r.name,                 r.age,                 h.col2  from hash h join rule r on r.ruleid = h.ruleid where not exists (  select 1  from rule rr  where rr.ruleid = h.ruleid   and rr.state <>  h.state ) 	0
24039550	22827	how to return zero instead of null from a subquery in mysql	select t1.id, t1.amount, t1.parent,         @total := ifnull( ( select sum(t2.amount) as amount from transactions t2 where t1.`id` = t2.parent group by t2.parent ), 0) as amountrepaid, 	0.00376025189761289
24039712	40939	how to convert gwt date format to datetime in sql?	select cast(left('2014-06-04t17:23:45+5:30', 19) as datetime) 	0.0316991258424466
24040123	35390	how do i select only one column result based on its value from a transnational table?	select distinct no, 'closed' from table1 t1 where exists (select * from table1 where status = 'closed' and no = t1.no) union select distinct no, 'open' from table1 t2 where not exists (select * from table1 where status = 'closed' and no = t2.no) 	0
24040597	38022	query using external key in sql	select e.emp_no, e.first_name, e.last_name from employees e join title t on t.emp_no = e.emp_no group by e.emp_no, e.first_name, e.last_name having count(*)=1; 	0.514077819714722
24042046	36993	mysql concatenate multiple columns and sort within a row	select  combo, count(combo) total from (     select  id, group_concat(item order by item) combo     from     (         select  id, item1 item         from    cart_table         union all         select  id, item2         from    cart_table         union all         select  id, item3         from    cart_table     ) ) group by combo 	5.47223273900646e-05
24042281	9482	sum up the column using access sql query	select eid, sum(pcnum) from table1 group by eid; 	0.294497272360125
24042320	2451	most frequent attribute for a subject not returning correct number of distinct subjects	select distinct f1.episodio, x.tipo_assepsia from dws_dm f1 outer apply     (       select top 1 r.tipo_assepsia , (count(*)) as freq             from  dws_dm r             where r.episodio = f1.episodio             group by tipo_assepsia              order by count(tipo_assepsia) desc     ) x 	9.74814219697974e-05
24043701	25312	mysql query to select from database where term occurs more than x amount of time	select substring_index( substring_index(  url_column,  ': from your_table group by substring_index( substring_index(  url_column,  ': having  count(*)> 1000 	0
24044505	1421	sql sum of totals from different tables in single query	select  c.customer_id,         t1.total total_t1,         t2.total total_t2,         t3.total total_t3,         t4.total total_t4,         t5.total total_t5 from customer c left join ( select customer_id, sum(total) total)             from table1             group by customer_id) t1     on c.customer_id = t1.customer_id left join ( select customer_id, sum(total) total)             from table2             group by customer_id) t2     on c.customer_id = t2.customer_id left join ( select customer_id, sum(total) total)             from table3             group by customer_id) t3     on c.customer_id = t3.customer_id left join ( select customer_id, sum(total) total)             from table4             group by customer_id) t4     on c.customer_id = t4.customer_id left join ( select customer_id, sum(total) total)             from table5             group by customer_id) t5     on c.customer_id = t5.customer_id 	0.00011163856546862
24045732	20404	rank an sql table with mysql, ranked by score, where game = x	select ranking,user,score from (select  @rank:=case when score =@s then @rank else @rank+1 end as ranking, @s:=score, user, score,game from tablename , (select @rank:=0,@s:=0) as i order by score desc ) new_alias where game='a' 	0.0138974645268825
24045797	21316	how do you join tables sharing the same column?	select d.department_name, count(*) as 'not_approved_manager' from cserepux c inner join csedept d on c.departmentid = d.departmentid where approveddate is null group by d.department_name 	0.000806696859979834
24046689	18186	select only rows with either the max date or null	select m.member, mx.state, mx.country from member m  left outer join ( select ma.state, ma.country, ma.member from memberaddress ma              inner join (select member, max(modified) as maxdate     from memberaddress     group by member) as m2 on (ma.member = m2.member and ma.modified = m2.maxdate) ) mx on m.member = mx.member 	0.00112963313778792
24046993	38130	database with hierarchy and joins	select breed.breed, gender.sex, dog.name from dog  join gender on dog.genderid = gender.id  join breed on gender.breedid = breed.id where dog.id = 'yourdogidhere' 	0.632150772639597
24047157	2312	mysql query to rank based on number of similar tags	select count(res.tag_id), res.video_id from tag_link_table res   inner join tag_link_table target     on target.video_id = 4321 and res.tag_id = target.tag_id group by res.video_id order by count(res.tag_id) desc 	0
24048090	7862	getting entries from one mysql table, optionally counting respective id's in other	select   c.commentid , sum(case when cvuser.vote is null then ifnull(cv.vote,0) else 0 end) commentscore , sum(case when cvuser.vote is null then abs(ifnull(cv.vote,0)) else 0 end) totalcommentscore , sum(ifnull(cvuser.vote,0))!=0 userhasvoted  from   comments c   left outer join comments_votes cv using (commentid)   left outer join comments_votes cvuser on c.commentid=cvuser.commentid and cv.userid=<insert user id here> group by c.commentid 	0
24049038	27297	an sql query from a 3 tables, can't get the results required	select      items.title, items.artist, orders.order_date, orders.ship_date from      items  join      orderline on orderline.item_id = items.item_id  join      orders on orders.order_id = orderline.order_id 	0.0141533466097578
24049711	20272	select only the rows where column values appear more than once	select * from a   inner join b on a.id_x = b.id_x   inner join c on b.id_y = c.id_y   inner join d on c.id_z = d.id_z where   a.date > '2014-01-01'   and a.id_y = 154   and d.id_t = 2   and  a.id_x in   (   select a.id_x from a   group by a.id_x   having count(a.id_x)>1); 	0
24050274	27227	get unique id at the same time get the sum of value for each id	select id, sum(val) from     (     select id_col_1 as id, value_1 as val from tbl     union     select id_col_2 as id, value_2 as val from tbl     ...     union     select id_col_640 as id, value_640 as val from tbl     ) group by id 	0
24050458	28621	hourly sales report	select (cast(datepart(hour, [time]) as varchar(255)) + ':00 -' +         cast(datepart(hour, [time]) as varchar(255)) + ':59'        ) as [time],        sum (total) as hourly_sales  from tblsales where mall = 'mall1' and ordate  = '6/2/2014' and void = 'n'  group by cast(datepart(hour, [time]) as varchar(255)); 	0.0220617935997742
24051132	4023	left outer joining tables with multiple property keys	select   c.case_id, char.value   from     case c, case_char char   where              c.case_id = char.case_id (+)            and          char.property_key(+) = 'issue';                            ^                            | 	0.472563923704475
24051437	2281	oracle pl/sql split string into columns, convert to numbers, and insert into new table	select to_number(regexp_substr(ptsstring.column1, '[^( ,]+', 1, 1)) col_one,        to_number(regexp_substr(ptsstring.column1, '[^ )]+', 1, 2)) col_two from puntosstring; 	0
24051829	6020	create invoice number in sql server stored procedure	select * from test   select      idorder, transactiondate,       replace(cast(transactiondate as date),'-','') +              cast(row_number() over(partition by cast(transactiondate as date)                                     order by idorder) as varchar(8)) as invoicenumber   from test 	0.176637435868834
24052704	33223	select records 4 to 6	select top 3 * from  ( select top 6 * from beitrag order by erstellungsdatum desc ) 	0.00176382316434064
24053574	23558	how to interogate a query to get all the images in wordpress from wp-posts?	select p.post_parent, p.guid, p.post_title, wp.post_content, p.post_date  from wp_posts p  left join wp_posts wp on p.post_parent = wp.id where (p.post_mime_type = "image/jpeg" or p.post_mime_type = "image/png"  or p.post_mime_type = "image/gif") 	0.000221759373569856
24054355	17372	sql server money cell * percentage cell	select      sum(             table1.money * (1+(table2.percentage/100.0))        ) answer  from table1 inner join table2       on table1.id= table2.id where id2= 3; 	0.00249379536283979
24056910	34694	how to put condition in order by sql query	select  * from xyztable order by order_number = 0, order_number asc; 	0.202013165131631
24056999	21834	sql - how hide duplicates id	select s.s_id, sc.c_id from student s left join stu_cour sc on sc.s_id = s.s_id and sc.c_id = 1 	0.0149980345749379
24061187	23479	replace function in a column where comma is replaced by apostrophe and comma?	select *, replace(employees, ',',''',''') from employees 	0.607216498209251
24061524	21507	sql row to column	select operator,         count(*) as total,        sum(case when operation_type = 'delete' then 1 else 0 end) as deletes,        sum(case when operation_type = 'update' then 1 else 0 end) as updates,        sum(case when operation_type = 'read' then 1 else 0 end) as reads,        sum(case when operation_type = 'create' then 1 else 0 end) as creates from operations group by operator 	0.0128894458806811
24061663	10804	group by with concatenate values with sum	select refernceno,       (select description + ' ' from [table] t2       where t2.referenceno = t1.referenceno for xml path('')      ),      sum(amount)  from [table] as t1  group by refernceno 	0.00759650338260807
24062332	17443	mssql create view that joins table to itself	select      a.itemid,             a.details,             a.color1,             a.color2 from        (                        select      itemid,                         details,                         color as color1,                         (select color from #table1 as b where b.itemid = a.itemid and b.color <> a.color)   as color2                         , row_number()   over (partition by itemid order by details desc)  rn             from        #table1     as a             ) as a where       a.rn = 1 	0.195219610303624
24062994	12083	group by only primary key, but select other values	select myprimarykey, max(otherthing) from mytable group by myprimarykey 	5.36966371131182e-05
24065856	35083	mysql request on multiple tables	select table2.store, table1.* from table1 inner join table2       on table2.id_product=table1.id_product where table1.id_product='p1' into outfile 'file_name' 	0.0884088245075792
24065872	24087	oracle: pivoting data into date ranges	select date as startdate,        lead(date) over (order by date) - 1 as enddate,        quantity   from table; 	0.00093839549109186
24066521	7210	sql query that finds a negative change between two rows with the same name field	select (score_end - score_start) delta, name_start from ( select date date_start, score score_start, name name_start   from t t   where not exists   ( select 1     from t x     where x.date < t.date      and x.name = t.name    )  ) as start_date_t join ( select date date_end, score score_end, name name_end   from t t   where not exists   ( select 1     from t x     where x.date > t.date       and x.name = t.name    )  ) end_date_t on start_date_t.name_start = end_date_t.name_end  where score_end-score_start  < 0 	0
24067123	2785	select values of a column which appear n times in sql	select e.emp_no, e.first_name, e.last_name from   employees e, dept_emp de where  e.emp_no=de.emp_no group by e.emp_no, e.first_name, e.last_name having count(*) = (select count(*) from departments); 	0
24067289	22954	call a postgres function that returns a record, passing in the result of a query	select * from foo((select foreignkey from sometable where primarykey = 5)); 	0.0341905984177617
24068323	19657	list tables in redshift using sqlworkbench	select distinct tablename from pg_table_def where schemaname = 'public' order by tablename; 	0.422335065507301
24069828	21748	how to join a column from another table to a new table you wish to display	select   source , numberofuses , numberofrows from (     select source,count(calculationid) as numberofuses     from tmpcalcsources     where source not like '%_result%'     group by source     ) tableuses     join numrowstable on numrowstable.tablename=tableuses.source order by numberofuses desc; 	0
24070191	24217	use listagg to select multiple rows on joined table	select u.id, u.name, listagg(price, ', ') within group (order by price) as prices from user u left outer join      values v      on u.id = v.id and v.tag in ('start', 'end') group by u.id, u.name; 	0.00467507046101081
24070792	6053	select a sequence of numbers and then link to another query	select * from nums  left join (select email, count(email) as nemail from people group by email) as x on  nemail=n order by n 	0.000132356729903346
24071640	10010	selecting row based on id and then again based on cardinality of text box	select filmid, text from (   select filmid, text, count(*), @r:=@r+1 as rank   from filmreview     join (select @r:=0) r   group by filmid, text   order by filmid, count(*) desc, text   ) t where rank <= 2 	0
24071641	6438	mysql query: add x day to current date	select date_format(date_add(now(), interval allowed_days day), '%d.%m.%y' ) from `my_table` where `user_id` = '[user_id]'; 	0
24073735	9869	combine my two queries into one query	select s.student_id, sub.unitid, sub.unitname, s.name, count(a.student_id) as count from students s left join absences a on a.student_id = s.student_id  left join subjects sub on a.unitid = sub.unitid group by s.student_id, sub.unitid, sub.unitname, s.name order by count desc 	0.00598850994915374
24074243	1578	sql query to fetch output based on multiple row values	select userid      , case when min(rights) = max(rights)              then min(rights)              else 2         end  from t  group by userid 	0
24075718	732	combine multiple rows value in mysql table	select  a.id, (@inc := concat(@inc, a.name)) as name from  mytable a, (select @inc:= '') c order by a.id asc 	0.000307184258238144
24076069	40561	mysql query to get array of averages of each month's data	select date_format(rate_date,'%m, %y') as rate_month,currency_pair,avg(rate) as avg_rate  from historical_currencies_rate where currency_pair='eur-usd' group by date_format(rate_date,'%m, %y'),currency_pair order by rate_month 	0
24076125	19731	mysql query, select episode on random from top view movie, but based only if status = 0	select views from (  select s.`views` from `serial` s inner join `serialreal` sr on s.id = sr.`sourceid`  inner join `serialrealepisode` sre on sre.`srid` = sr.`id`  where sre.`status` = '0' group by s.`views` order by s.`views` desc limit 3  ) as tbl order by rand() limit 1 	0
24076653	21304	php mysql newest records from multiple tables	select *   from      ( select * from x        union all        select * from y      ) n  order      by date desc   limit 10; 	0.00013656279886023
24076913	10122	mysql how to `sum` a value on a many-to-one relationship, in the case that there are multiple values take only 1 the maximum?	select sum(employees) from  (select max(employees_affected) as `employees`      from `project` as `p`      left join `business` as `b`      on b.id = p.enterpriseid where (awarded = 1)          and (b.region = 3)         and (cancelled = 0)          and (year(project_date) = 2014)          and (month(project_date) = 6)     group by enterpriseid ) x 	0
24077527	5555	get the latest data comparing datetime fields from two tables	select u.id, u.name, if(u.lastupdatetime >= k.lastupdatetime, u.password, k.password) as password, greatest(u.lastupdatetime, k.lastupdatetime) as lastupdatetime from user u inner join user_k k on u.id = k.id 	0
24078234	22927	joining 4 tables in mysql	select r.* from room r left join `reservationroom` rr on r.`hotelid` = rr.`hotelid` and r.`roomid` = rr.`roomid`  where ( rr.`reservationroomid` = '' or rr.`reservationroomid` is  null ); 	0.0540981249884682
24078388	6242	sql query to get data based on current date	select * into #temp from  dbo.fndashboard_dummyweekly1( dateadd(day, datediff(day, 0, '5/28/2014'), 0), convert(date,getdate()) ) 	0
24078625	20257	mysql - get data from 2 tables similtanusly	select post_id_fk, post_thread_views, post_subject, post_username from `gforum_postview`  join `gforum_post` on post_id =post_id_fk order by `gforum_postview`.`post_thread_views` desc 	0.000294210752386457
24079551	25284	sql query on effective date	select * from drinkhistory; 	0.0959069877864643
24082120	18603	codeigniter search engine not working correct - get only published posts	select `post_id`, `title` etc etc ... from (`posts`) where `posts`.`date_published` <= '2014-06-06' and `posts`.`visible` =  1 and   (`title`  like '%lorem,%' or  `keywords`  like '%lorem,%' or  `title`  like '%ipsum%' or  `keywords`  like '%ipsum%’) order by `date_published` desc, `posts`.`category_id` asc, `post_id` desc 	0.202920054783071
24082325	17205	mysql : get latest score for each users where quiz_id = something	select t1.*  from your_table t1 join (   select user_id, max(date_replied) as mdate   from your_table   where quiz_id = 1   group by user_id ) t2 on t1.user_id = t2.user_id and t1.date_replied = t2.mdate 	0
24082882	27505	how do i get the last record from sql server?	select top 1 commentaire from billet order by billetid desc 	0
24086144	12945	order by statement with start value in a round robin select	select top 1 [date],[domain] from (   select [date] ,[domain],           row_number() over (partition by [domain] order by [date]) as recid   from  delivery ) as r order by recid,     (case when domain >@lastuseddomain then domain          else domain + (select top 1 domain from delivery order by domain desc)      end) 	0.0282085216951703
24087286	3328	mysql coalesce() function - determining which field was non-null	select coalesce(override,role,0), (override is not null) as override_enabled 	0.196335971100432
24087482	28784	sql server : combining like rows	select min([wl].[id]) as id   ,[wl].[userid]   ,[u].[id]   ,[u].[username]   ,sum([slength]) as slength from [wsite].[dbo].[wlog] as wl  inner join [wsite].[dbo].[users] as u          on [u].[id] = [wl].[userid]       where [wl].[wdate] >= convert(datetime, '2012-01-01 00:00:00', 120)          and [wl].[wdate] <= convert(datetime, getdate(), 120)   group by [wl].[userid]   ,[u].[id]   ,[u].[username] 	0.229518751134439
24087804	36897	sql join count(*) of one table to another table as aliases	select u.username, count(sc.message) as comment_count  from song_comments sc join        users u on u.id=sc.user_id  where u.user_id = 7  group by u.username 	0.000924411521662591
24087892	9940	is it possible to pass a table valued parameter to a stored procedure and return a table result?	select top 100 keyvalue, datevalue from @indata 	0.715786934511563
24091023	37993	need php code for a selection from database that's greater than 5 but not 15 (meaning all numbers higher than 5 not including 15)?	select * from `groups` where   `id` > 5   and `id` <> 15 order by `name` asc 	0
24096197	4265	unique id at particular column	select  top(2) table1307.fld297,table1307.fld256,table1307.fld295,table1307.fld9,isnull(fld287,0),isnull(fld288,0),isnull(table1310.fld9,0) from table1307 (nolock) left join table1310 on table1310.fld9=table1307.fld232 where table1307.fld309=1 and table1307.fld200=1 and getutcdate() between table1307.fld291 and table1307.fld292   and table1310.fld9 in (select fld9 from table1310 (nolock) where fld102=1) 	6.92633225708976e-05
24097706	11436	reuse computated data from a subquery	select x.emp_no   from dept_emp x   join       ( select dept_no           from dept_emp de          join titles t               on t.emp_no = de.emp_no         where t.title = 'engineer'         group             by de.dept_no        having count(*) < 1000      ) y     on y.dept_no = x.dept_no  order      by emp_no  limit 10; 	0.044157128041055
24098538	5779	rails: faster way to retrieve n random records	select  rnd_id, rnd_value from    (         select  @cnt := count(*) + 1,                 @lim := 10         from    t_random_innodb         ) vars straight_join         (         select  r.*,                 @lim := @lim - 1         from    t_random_innodb r         where   (@cnt := @cnt - 1)                 and rand() < @lim / @cnt         ) i 	0.00404071482186567
24098858	12888	how to create view from 3 linked tables starting from data to another table	select tb_c.id_c as id_c, desc_c, tb_p.id_p as id_p, desc_p,         tb_r.id_r as id_r, desc_r  from tb_main  inner join tb_c  on tb_main.id_c  = tb_c.id_c   inner join tb_p on tb_c.id_p = tb_p.id_p  inner join tb_r on tb_r.id_r = tb_p.id_r 	0
24100551	17952	sql group dates as week date	select dayofweek('2007-02-03'); 	0.000870774804669427
24101094	13725	sql join statement and deliberately repeat first line in every group	select invh, line from invhed join invdet on (invh = invd) where voidline = ''  union all  select invh, min(line) from invhed join invdet on (invh = invd) where voidline = '' group by invh 	0.00553966079026468
24103433	38798	exclude days from another table using two dates inside function	select @workdays =  (datediff(dd, @startdate, @enddate) + 1)                     -(datediff(wk, @startdate, @enddate) * 1)                     -(case when datename(dw, @startdate) = 'friday' then 1 else 0 end)                     -(case when datename(dw, @enddate) = 'friday' then 1 else 0 end)                     -(select count(*) from [vsrc].[tbholydays] where holydaydate between @startdate and @enddate) 	0
24104960	22720	how to concat strings with space delimiter where each string is nullable?	select   rtrim(concat(         nullif(f1, '') + ' '     , nullif(f2, '') + ' '     , nullif(f3, '') + ' '   )) from   @test 	0.00218731166546217
24108381	2314	is it possible to list attribute values for one column based on a common attribute value in another column	select t1, t2, group_concat(concat(t3,'(',cateogoryid,')'),', ') x from something group by 1,2 	0
24111836	14149	complex query over two tables	select t1.id, sum(ifnull(t2.cond, 0) = 1) as c1, (select sum(cond = 1) from table2 where id2 = 2) as c2 from table1 t1 left join table2 t2 on t1.id = t2.id2 group by t1.id order by abs(sum(ifnull(t2.cond, 0) = 1) - c2) * rand(); 	0.425812430557325
24113741	38434	how to show my unique indexes in my database	select table_name as `table`,        index_name as `index`,        group_concat(column_name order by seq_in_index) as `columns` from information_schema.statistics where table_schema = 'yourdatabasename' and index_name='primary' group by 1,2 	0.15151581872768
24114582	14169	query to get the data in related table	select     adu.id sd as updateid,     adu.name as updatename,     adc.id as createid,     adc.name as createname from     news ns         left outer join admin adu             on ns.updateby=adu.id         left outer join admin adc             on ns.createby=adc.id where     news.id=1 	0.000517841459790016
24115257	35031	getting percentages from sql query and grouping	select max(questions_only.question),        max(answers_only.answer),        (count(*)/max(t.all_count))*100 as answer_percent from questions    join (             select question_id,                    count(*) as all_count            from questions            group by question_id           ) as t on questions.question_id=t.question_id    join questions_only on questions.question_id=questions_only.question_id    join answers_only on questions.answer_id=answers_only.answer_id group by questions.question_id,questions.answer_id having (count(*)/max(t.all_count))*100>=90 	0.360514172041562
24115683	21620	how to select multiple rows with mysql while numbering the records?	select sub2.sort, sub2.number, sub2.user, sub2.id  from (     select @sort1:=@sort1+1 as sort, number, user, id      from table,      (select @sort1 := 0) s      order by number desc ) sub1 inner join (     select @sort2:=@sort2+1 as sort, number, user, id      from table,      (select @sort2 := 0) s      order by number desc ) sub2 on sub1.id = 6 and sub2.sort between (sub1.sort - 2) and (sub1.sort + 2) 	0.000202597922163926
24116055	11024	city names as column title	select memphis,nashville,chattanooga  from (   select f.id,c.cityname,f.foodname    from food f    inner join city c     on f.cityid=c.id )result  pivot (   max(foodname)    for cityname in(memphis,nashville,chattanooga) ) as pvt 	0.000610390312960133
24116387	35030	list all scalar function with datatype	select     so.name,     sp.parameter_id,     sp.name,     sp.user_type_id from sys.objects so inner join sys.parameters sp     on sp.object_id = so.object_id where so.type = 'fn' and sp.parameter_id = 0 and sp.user_type_id = 231 	0.364972023889923
24117663	15446	mysql - trying to get post id with max number of comments from comment table	select post_id, count(id) as total  from comments  group by post_id order by total desc limit 1 	0
24118642	3548	oracle query to get month wise data and give 0 for month not available	select   listagg(count(name),',') within      group (order by m.rn)  from       (select * from  ps_bqueues_host        where time_stamp          between to_date('01-mar-14', 'dd-mon-yy')          and     to_date('01-jun-14', 'dd-mon-yy')       )    right join       (select level rn from dual connect by level <= 12) m      on m.rn=extract(month from time_stamp) where m.rn between extract(month from to_date('01-mar-14', 'dd-mon-yy'))            and  extract(month from to_date('01-jun-14', 'dd-mon-yy')) group by m.rn 	0
24118882	38900	how to display data corresponding to 2 coulms into a third and fourth column in sql within a sigle table?	select distinct a.name, coalesce(a1.build_id,'not found'), coalesce(a2.buildid,'not found') from artifact a left outer join artifact a1 on a1.name = a.name left outer join artifact a2 on a2.name = a.name where a1.environment = 'uat 2' and a2.environment = 'sit 2' 	0
24120635	31786	using the return value from sql as an argument in another query	select a.id, var4, b.var1 from table2 a inner join table1 b    on a.id = b.id where var3 = x and id = y 	0.00478745059543514
24121313	214	how to display null value instead of numeric	select id, name, amount from table2  union all   select id, name, null from table1  order by id 	0.000267827991790235
24124485	32045	get posts from deleted users sql function	select a.*, b.username, b.id as user_id from ".tbl_posts." a left join ".tbl_users." b             on a.author_id = b.id             where a.thread_id = ".$thread_id 	0.000309501428151413
24124846	40688	passing the results of a mysql query to a subquery on the same table	select *  from test  where `group` = (select min(`group`)                   from `test`                   where taken = 0) 	0.00118638375539639
24124888	30947	display monthly attendance report of an employee	select eid 'id',empname 'name', month(logindatetime) 'month', count(*) 'attendance' from empattendancetable  where month(logindatetime)=@month group by eid,empname, month(logindatetime) 	0.000548380590918779
24125377	25084	how to find all users with execute rights on a stored procedure in sql server	select s.name as schemaname, o.name as objectname, dp.name as principalname, dperm.type as permissiontype, dperm.permission_name as permissionname, dperm.state as permissionstate, dperm.state_desc as permissionstatedescription from sys.objects o inner join sys.schemas s on o.schema_id = s.schema_id inner join sys.database_permissions dperm on o.object_id = dperm.major_id inner join sys.database_principals dp  on dperm.grantee_principal_id = dp.principal_id where dperm.class = 1  and dperm.type = 'ex' and  dp.name = 'specific_username' and o.name = 'specific_object_name' 	0.00530651053835754
24126097	452	join and rename on multiple column in less queries	select wed_id, wed_date,     user1.username as username1, user1.avatar as avatar1,      user2.username as username2, user2.avatar as avatar2,      user3.username as username3, user3.avatar as avatar3,      user4.username as username4, user4.avatar as avatar4 from wedding      inner join user as user1 on user1.user_id = wedding.mid1     inner join user as user2 on user2.user_id = wedding.mid2     inner join user as user3 on user3.user_id = wedding.tid1     inner join user as user4 on user4.user_id = wedding.tid2 	0.0158471058563631
24127450	33364	sql compare 2 table datasets, return only exceptions / differences (reconciling)	select     t1.name,    t1.state,    t1.city,    abs(t1.balance - t2.balance from     table1  t1    inner join table2 t2    on t1.name = t2.name      and t1.state = t2.state      and t1.city = t2.city      and t1.company = t2.company where    t1.balance <> t2.balanace 	4.60628393054467e-05
24129682	3387	how to count data depending on the date?	select employeedept, execoffice_status, employee, count(*) as 'totalstars', year_cse =year(execoffice_date) from csereduxresponses where execoffice_status = 1 group by employeedept, execoffice_status, year(execoffice_date), employee 	0.00011219462431435
24130697	22993	reading ms excel file from sql server 2005	select * from    openrowset('microsoft.ace.oledb.12.0',             'excel 12.0 xml;hdr=yes;database=c:\file.xls',             'select * from [sheet1$]') 	0.318680151361443
24132751	4410	is it possible to put a if condition in a select query	select     t1,     t2,     if(         t3 is null,                                           concat('empty(', category_id, ')'),                   group_concat(concat(t3,'(',category_id,')'))      ) as consildated_data from categories group by 1, 2; 	0.226506815160105
24133136	20939	mysql query to find minimum and maximum of 2 columns where minimum of 1 column must not be equal to zero	select max(`p`)  , min(`p`)  from (select min(`discounted_price`) as `p` from `table` where discounted_price!=0)    union    (select max(`mrp_price`) as `p` from `table` ) 	0
24136507	5923	how to select column value depends on its existence?	select case when isnull(c1,'')<>'' then c1             else c2        end as column_name from table t 	7.52573173131218e-05
24136829	14948	mysql filtering result from a foreign key that doesn't have contents	select distinct test_category._id, test_category.score_type from test_category  join questions on 'questions.test_cat' = 'test_category._id' 	0
24137246	18034	searching for the non-friend users in php	select * from `registration` where username like '%$search%' and id != $user_id and id not in (     select sender_id     from sed_request      where reciever_id = $user_id ) and id not in (     select reciever_id     from sed_request      where sender_id = $user_id ) 	0.0402043360271095
24137765	25064	sql % character	select * from t_package    where t_package.packageflags like '*vccfg=use_case_view;' 	0.399729350511734
24138064	23315	query return null instead of a result with some record	select u.name, r.title, count(c.comment) from users u left join resumes r on r.users_id_fk =u.id left join comments c on c.resumes_id_fk = r.id where u.id = 2 group by u.name, r.title 	0.00263821696562808
24138655	32482	convert utc seconds to string in sql	select dateadd (second, <your number of seconds>, '1970-01-01') 	0.0787287809124254
24139003	23800	how do i get last id from set of 3 returned rows?	select min(noticeiid) from ( select top (3) n.noticeid,      [subject],     n.issuedate,     d.departname as 'department',     n.body,      n.noticeimage,      n.icon  from dbo.notice n inner join dbo.department d on  d.departmentid = n.departmentid where n.noticeid not in (select top 3 n.noticeid from dbo.notice n inner join  dbo.department d on d.departmentid = n.departmentid order by issuedate desc) order by n.issuedate desc ) as t1 	0
24139322	5574	how to get duplicate column values in comma separated	select pid,group_concat(qid) from client_parent_question group by pid 	0
24141220	26169	how to query find common values from database table	select  (   select county   from mytable   where id in (1,2)   order by county desc   limit 1 ) as county, (   select state   from mytable   where id in (1,2)   order by state desc   limit 1 ) as state, (   select zip   from mytable   where id in (1,2)   order by zip desc   limit 1 ) as zip 	0
24146352	5007	mysql query with two different join and count	select p.*,m1.*,m2.*,ifnull(m2.rimborsi, 0) as rimborsiok   from professionisti p   left join   (     select ca.email, count(*) as totali     from contatti_acquistati_addebito ca                 where ca.data between ('2014-06-01') and  ('2014-06-31')     group by ca.email   ) as m1 on p.email = m1.email   left join   (     select cr.email, count(*) as rimborsi     from contatti_rimborsi cr     where cr.data between ('2014-06-01') and  ('2014-06-31')     group by cr.email   ) as m2 on p.email = m2.email where p.categoria like '%0540%' and p.province like '%mi%'  and p.standby='0' and p.addebito='1' having  m1.totali-rimborsiok<p.limite or p.limite=0 	0.0418526367083212
24146376	1946	how to join the five more tables in ms sql 2008	select ri.fk_rec_no          ,ri.fk_item_no         ,a.item_type       ,sr.rep_name       ,a.inv_date as item_date       ,a.inv_amt  as item_amt from ( select inv_no   , 'invoice' as item_type, fk_rep_id, inv_date, inv_amt from dbo.invoice union all select return_id, 'return' as item_type, fk_rep_id, ret_date, ret_amt from dbo.[return] union all  select note_id  , 'credit_ note' as item_type, fk_rep_id, note_date, note_amnt from dbo.credit_ note  ) a left join receipt_items ri  on ri.fk_item_no  = a.inv_no left join sales_rep sr      on sr.rep_id = a.fk_rep_id 	0.167992466242075
24148882	1566	3 last record of each customer	select  r.`key`, r.date, r.customer from customers c left join  (   select    r1.*   from requests r1   where    (     select count(*)     from requests r2     where r1.customer = r2.customer     and r1.`key` <= r2.`key`   ) <=3   order by r1.date desc )r on r.customer = c.`key` order by c.`key` 	0
24149185	36076	sql server: avg sum	select (case when sum(numvisits) = 0 then 0 else sum(totalspend)/sum(numvisits) end) as totalspend        , hhtype   from dbo.anthem_ids_jr    group by hhtype, totalspend 	0.49147339275027
24149895	25569	group by two columns is possible?	select `price` from items group by `price`, `time` order by `time`; 	0.0244241903431975
24150646	15724	how to select row b only if row a doesn't exist on group by	select p.id, p.name,      group_concat( '{',coalesce(a.id, b.id),',',coalesce(a.attachment_url, b.attachment_url), '}' ) as attachments_list  from products p  left join attachments a      on (a.product_id=p.id and a.language='pt')  left join attachments b     on (a.product_id=p.id and a.language='bb') 	0
24151028	9633	need a count, but multiple other fields	select person, count(trip_id) as trips, min(date) as firstdate, home from [table] group by person, home order by firstdate 	0.00870700972926766
24153463	40476	mysql: rollup on top, sum(financial amount), then order financial amount column by datetime desc	select concat(    case when t.pkfinancialid is null          then 'total due:     '         else '               '    end,  cast(financialtotalamount as char(20))    )   , case when t.pkfinancialid is null         then null         else fdatetime    end from (     select pkfinancialid      , max(financialdatetime) as fdatetime      , sum(case when fkfinancialentryid = 1                  then 1                  else -1         end * financialamount) as financialtotalamount     from tblfinancials      where tblfinancials.fkuserid = 1        and tblfinancials.fkprofileid = 1      group by pkfinancialid with rollup ) as t   order by case when t.pkfinancialid is null then 0 else 1 end        , fdatetime; total due: 0.00     (null)          100.00     june, 07 2014 07:00:00+0000         -100.00     june, 08 2014 08:00:00+0000 	6.47881484489162e-05
24154789	23677	perform string replace with select query creating new field mysql	select *, replace(duration,':', '') as duration_modified from songs_test where id in ($ids) order by duration desc; 	0.463240889168944
24154998	13715	how to use dynamic value of table column in the value of another column on insert	select start_time, start_time_type, end_time,        if(list_in = 'store', '', 'duration'),        if(list_in = 'store', end_time - start_time / 86400, duration) from (select if(start_time_type = 'now'            or start_time < " . current_time . ", " . current_time . ",        start_time) as start_time,        start_time_type,        if(list_in = 'store', 0, ( if(end_time_type = 'duration',                                   " . current_time . " + duration * 86400,                                   end_time                                   ) )) as end_time,        duration,        list_in from   bulk_listings where ...) as subquery 	0
24156209	36131	single sql query to return maximum values of unique values of different column	select descid,progid,progstellarmass from (     select rank() over (partition by des.galaxyid  order by prog.stellarmass desc) as rankid, des.galaxyid as descid,        prog.galaxyid as progid,        prog.stellarmass as progstellarmass     from guo2010a..mmr prog, guo2010a..mmr des     where des.galaxyid in (0,2,5)         and prog.galaxyid between des.galaxyid and des.lastprogenitorid        and prog.snapnum = 48 ) as wrap where rankid = 1 	0
24158752	39622	sql server -multiple rows in sub query	select t1.num1-t2.num2 from table1 t1,table1 t2 where t1.t_type=2 and t2.t_type=3 	0.309500925516371
24159531	27668	join two tables and pick one row from the second table if a field is set in second table otherwise select any row	select distinct adverts._id as _id, adverts.subcategory_id as subcategory_id, adverts.title as title, adverts.price as price, images.name as name, adverts.created_date as date from images,adverts where images.adverts_id=adverts._id and images.adverts_id not in(select images.adverts_id from images where images.default_img='1') group by adverts._id union select adverts._id as _id, adverts.subcategory_id as subcategory_id, adverts.title as title, adverts.price as price, images.name as name, adverts.created_date as date from images,adverts where images.adverts_id=adverts._id and default_img='1' order by date 	0
24160978	40578	get available stocks to sell	select p.id    , a.nome    , p.preco    , date_format(p.`data`,'%m/%d/%y') as `data`    , coalesce(p.quantidade-sum(f.quantidade), p.quantidade) as quantidade    , p.preco*coalesce(p.quantidade-sum(f.quantidade), p.quantidade) as total     from acao_trans p     left join acao_trans f     on p.id=f.parent     inner join acao a     on p.id_acao=a.id     where p.parent is null     and p.id_acao=1     and p.id_empresa=9     group by p.id 	0.0016105393333684
24161873	37212	fetching last 30 days data from mysql table and grouping them by date	select (sum(success_hit)/sum(total_hit)*100) as `percentage`,        date(date_time) as `date` from my_table where date(date_time) >= date_sub(curdate(), interval 1 month) group by date(date_time); 	0
24165680	35842	sql count with multiple criteria and conditions	select count(*) from table t where t.value in ('value', 'value2', 'value3')     and (       (t.value = 'value2' and       t.date between @date1 and @date2)       or (t.value <> 'value2')     ) 	0.0998952514604084
24166199	40004	selecting all rows where one field contains the same value	select *    from mytable  where someid in (                    select someid                      from mytable                     where salesman in ('ashley','barney')                  group by someid                    having count(distinct salesman) = 2                  ) 	0
24166648	20668	filtering db result based on column value	select user_id, username from users where users.url like '%domain.com%' 	0.000181134277608873
24166820	38733	sql - selecting groups of rows that share a common value	select acc, ip from yourtable where ip in (select ip              from yourtable              group by ip              having count(*) > 1) order by ip, acc 	0
24168223	17771	liquibase tried to apply all changeset, even if database is present	select * from databasechangelog where id='05192014.1525' 	0.0627041528467233
24168471	12484	ssrs multiple value parameter filter based on dataset	select id, value, userid, rn = row_number() over(partition by userid order by userid) from *my huge query* 	0.000834398095892677
24168752	28630	group repeated values by group_by with counter?	select id, group_concat(final_tags)  from(   select *   from(     select        tag,        combined,        if(tag <> combined, concat(tag, combined), tag) as final_tags,       counted,        id      from (       select          id,         tag,         if(@a = tag, @b := @counter, @b := 1) as counted,         if(@a = tag, @d := concat('(x', @counter, ')'), @d := tag) as combined,         @a := tag,         if(@b = 1, @counter := 1, @counter),         @counter := @counter + 1       from mytable       join (select @a := '', @d := '', @counter := 1, @b := 0) as t       ) as temp     order by counted desc     ) as whatever   group by tag ) as this_is_it group by id 	0.209751094698019
24169718	22153	sql query make 'groups' with mysql	select s.* from (    select epi_nr, min(upload_date) as upload_date     from spalte     group by epi_nr  ) g inner join spalte s on s.epi_nr = g.epi_nr and s.upload_date = g.upload_date 	0.542175240810702
24170306	16818	how to group by columns, and pick arbitrary non null other columns to display	select sq.city   ,sq.state   ,sq.country   ,a.latitude   ,a.longitude from (   select city     ,state     ,country   from staging2.address_daily s   where not exists (       select *       from mart.city m       where m.city_name = s.city         and m.state_code = s.state         and m.country_code = s.country       )   group by city     ,state     ,country   ) sq  left join staging2.address_daily a   on a.id = (       select id       from staging2.address_daily i       where i.city = sq.city         and i.state = sq.state         and i.country = sq.country          and not latitude is null limit 1       ) 	0
24170758	26032	joins are erroring with multiple tables	select ... from mydb.match as t1 	0.34898016117872
24170885	13749	access query compare datetime to year only date?	select count(*) as mcount from [projects] where year([dateprojectsubmitted]) > " & youryear 	0.000267915463717184
24171623	41230	select rows that do not have a distinct value	select * from custdetails where custno in (select custno from custdetails                   group by custno                   having count(custno) > 1) 	0.00036386310286164
24172976	29574	sql - filter based on the wildcard character	select my_column from   my_table where  my_column like '%/%' 	0.0225328812791339
24175244	15994	sql join multiple keys multiple columns	select      tf.faultid,     tf.faultedassetid,     ta1.assetname as faultedassetname,     tf.faultedprimaryassetid,     ta2.assetname as faultedprimaryassetname from faults tf left join assets ta1 on ta1.assetid = tf.faultedassetid left join assets ta2 on ta2.assetid = tf.faultedprimaryassetid 	0.0201059472614247
24176682	32296	select from multiple table and left join to one table	select calendar.cdate, sum(transaction.amount) from calendar left join (     select transaction.amount, transaction.created_at from transaction, agent, town     where     transaction.agent_id = agent.id     and agent.town_id = town.id     and town.state_id = 14 ) transaction on calendar.cdate = date_format(transaction.created_at, "%y-%m-%d")  where calendar.cdate >= '2014-06-01' and calendar.cdate <= '2014-06-11' group by calendar.cdate; 	0.00207108377774855
24177799	36226	cast current day to english	select to_char(sysdate,'day','nls_date_language=english') eng,        to_char(sysdate,'day','nls_date_language=german') ger,        to_char(sysdate,'day','nls_date_language=french') fre,        to_char(sysdate,'day','nls_date_language=italian') itl from dual; |       eng |        ger |      fre |       itl | | | thursday  | donnerstag | jeudi    | giovedì   | 	0.000797104919187428
24179695	14512	mysql how to select by longblob	select id from table where octet_length(content) = 0; 	0.200117522268919
24179761	15550	select distinct value in sql with 35 columns	select distinct field1, field2, field3 etc...  from table1 	0.0269075805310134
24181416	40866	how can i get grouped data in sub-query	select t1.date , (select stuff((select ','+ cast(t2.id as nvarchar(5))               from demotable t2 where t2.date = t1.date               for xml path('')), 1, 1, '')) as ids from demotable t1 group by t1.date 	0.0100163124963019
24184199	107	need help to finding pattern	select substring(col,                  patindex('%[a-z][a-z][a-z][a-z][0-9][0-9][0-9][0-9][0-9][0-9]%', col),                  10) 	0.7207095375212
24185587	27447	sql sum group by where id changed over time	select isnull(n.newid,myd.id) id, sum(myd.monthly_value) from my_database myd left join newoldids n on n.oldid = myd.id group by isnull(n.newid,myd.id) 	0.00942496253307849
24187286	40496	select with condition -sql server	select contract,         (select date_prolog from test where contract = 'yes') as date_prolog,         hours from test where contract = 'no' 	0.566634531817507
24188271	24629	combining two identically-structured tables where one has priority, and also excluding by field value	select    coalesce(o.fieldkey   ,n.fieldkey   ) as fieldkey   ,   coalesce(o.fieldlabel ,n.fieldlabel ) as fieldlabel ,   coalesce(o.fieldstatus,n.fieldstatus) as fieldstatus from t_normal n full join t_override o on (o.fieldkey = n.fieldkey) where (o.fieldkey is null or o.fieldstatus = 'active') 	0
24188485	15426	how to select from nested table	select col1, col2,   col1/(     select sum(col2)     from sometable   ) from sometable 	0.0300450770769861
24188677	12663	search in phpmyadmin all wordpress post that contains "fileadmin" and ".pdf"	select * from `mydatabase`.`dv_posts` where (convert(`post_content` using utf8) like '%fileadmin%' and convert(`post_content` using utf8) like '%.pdf%') 	0.0143140516926186
24190809	20934	how to get the latest record in each group and check if it's the only record?	select m1.*, m2.total from messages m1, (select max(id) id, count(*) total, name  from messages  group by name) m2 where m1.name = m2.name and m1.id = m2.id 	0
24192106	28498	getting ids that have value all the same	select id, max(code) code, count(1) cnt from table  group by id having max(code) = min(code) and max(code) = 1 	0
24192775	39979	renaming xml elements and attributes in sql	select t1.otherdata as '@otherdata',        (        select i.x.value('@attr1', 'int') as '@newattr1name',               i.x.value('@attr2', 'int') as '@newattr2name',               (               select s.x.value('@attr1', 'int') as '@newattrname1'               from i.x.nodes('subitem') as s(x)               for xml path('subitem'), type               )        from t2.x.nodes('/items/item') as i(x)        for xml path('newitemnodename'), root('newitemsnodename'), type        ) from ta_test as t1   cross apply (select cast(t1.xmlstring as xml).query('.')) as t2(x) for xml path('test'), type 	0.0114716457052945
24194092	27962	how to combine several sql queries into one	select g.surname, g,games, p.penalties from (select  count(1) as games,ejl_refery.surname from  ejl_protocols  left join ejl_refery on ejl_protocols.refery = ejl_refery.id where  ejl_protocols.season = 2013 group by refery) g inner join  (select  count(1) as penalties,ejl_refery.surname from  ejl_protocols  left join ejl_play_events on ejl_protocols.id = ejl_play_events.protocol_id left join ejl_refery on ejl_protocols.refery = ejl_refery.id where  ejl_protocols.season = 2013 and ejl_play_events.event_id  in (3,4)  group by refery) p on g.surname = p.surname 	0.00132748319828152
24195808	5427	search for same data in two different columns	select user_id,  user_firstname,  user_lastname,  user_profile_picture, 'users' as 'type' from users  where user_firstname like :user_firstname or user_lastname like :user_lastname  union all select page_id,   page_firstname,   page_lastname,   page_profile_picture ,'pages' as 'type' from pages  where page_firstname like :page_firstname  or page_lastname like :page_lastname 	5.13742858752956e-05
24196366	10718	mysql join multiple rows based on an interval	select min(start_time) start_time, max(end_time) end_time,    time_format(sec_to_time(sum(duration)),'%i:%s') duration from (   select start_time, end_time, duration,      if (@dur>=120, @grp:=@grp+1, @grp) g,     if (@dur>=120, @dur:=duration, @dur:=@dur+duration) dur   from mytable a   join (select @dur:=0, @grp:=0) b) a group by a.g; 	0.000860247275767563
24196958	25677	how to get not distinct values and display data	select m.`lastname` as lname      , m.`firstname` as fname      , m.`middlename` as mname from table m join ( select `lastname`                     from `table`                      group by `lastname`                     having count(*) > 1 ) x on x.`lastname` = m.`lastname` 	6.86096032334945e-05
24198948	20946	building a select clause with dynamic number of columns	select tbl1.col1 as firstname, tbl1.col2 as lastname, null as street, tbl1.col3 as job as street from ... where @variable = 1 union all select tbl2.col4 as firstname, tbl2.col5 as lastname, tbl2.col8 as street, null as job from ... where @variable = 2; 	0.059638794765728
24200834	21807	not common filtering in mysql	select     * from     (         select         table1.s1,         table1.date,         table1.t,         (         select            min(tbl.s1) as s1         from            table1 as tbl         where              tbl.s1 > table1.s1         ) as nextid     from         table1 ) as tblinner join table1 as next     on tblinner.nextid=next.s1 where timestampdiff(second,next.date,tblinner.date)<tblinner.t 	0.117982482770885
24201038	38691	selecting the last entry of each day in a timestamp and corresponding values	select    rec.id,    rec.time_stamp,    rec.curr_property,    rec.day_property,    rec.mytime,    rec.mydate from  (   select      admin_tmp.*,     date(time_stamp) as mydate,     time(time_stamp) as mytime   from admin_tmp   where time(time_stamp) >= '07:00:00' and time(time_stamp) <= '07:59:59' ) as rec join (   select      date(time_stamp) as mydate,     max(time(time_stamp)) as mytime   from admin_tmp   where time(time_stamp) >= '07:00:00' and time(time_stamp) <= '07:59:59'   group by date(time_stamp) ) as max_times on max_times.mydate = rec.mydate and max_times.mytime = rec.mytime order by rec.mytime limit 15; 	0
24201621	13382	search an sql table that already contains wildcards?	select * from my_table where '511132228' like replace(phone_number, 'x', '_') 	0.0707256538604708
24202559	5584	select column if results/row not exists?	select distinct(post_id ) from tablename where post_id not in(select post_id from tablename where user_id=1); 	0.286784701445057
24203006	29345	set different limit on each tables in sql	select * from (select number       from menu       where user_id = 1       order by id       limit 3) as number, join (select *       from users       where id = 1       limit 1) as users 	0.000101616041460928
24203103	1913	insert `count(*)` based on separate table	select  et.id,  et.eventname,  count(distinct ebt.booth_id) as booth_count,  count(distinct ept.participant_id) as participant_count from  event_booths_tbl ebt  left join events_tbl et on et.id=ebt.event_id  left join event_participants_tbl ept on ept.event_id=ebt.event_id group by et.event_id; 	0.000208506574585095
24203847	12131	mysql - how can i/workaround ordering by the result of a group function	select target, goals / shot as ratio from (         select `team` as 'target',             (             select count(`id`)                 from `database`                 where `team` = `target`             ) as 'shots',             count(`id`) as 'goals'         from `database`         where (             `result` =    'g'         )         group by `team`         limit 0, 10) foo     order by goals desc, ratio desc 	0.252068285308135
24205456	26273	display null instead of zero	select case when your_column = '0.0000' then null             else your_column        end as your_column from your_table 	0.00236582481059149
24207200	15894	how to verify if the content of a specific table field is univocal?	select title, count(1) as titlecount from maliciouscodealertdocument group by title having count(1) > 1 	8.79847690153617e-05
24207959	20938	only show order when all the order detail are received	select orderheader.orderid, orderheader.name from orderheader       inner join orderdetail      on orderheader.orderid = orderdetail.orderid group by orderheader.orderid, orderheader.name having        count(orderdetail.orderid )   = sum(iif (orderdetail.statusfk = 2 ,1,0) ) 	0
24208209	2233	merge results from 2 datasets from 2 different databases in ssrs	select d.cola, d.colb, d.colc from dbo.mytable d union all select b.cola, b.colb,b.colc drom db1.dbo.myothertable b 	0
24210379	25322	group by in sql to get monthly breakdown of data	select   itemdescription ,substr(orderreceiveddate,2,7) as orderreceiveddateupdated  ,count(*) as itemcount  into 'c:\users\whatever.csv'  from 'c:\user\inputfilehere.csv'  group by itemdescription, orderreceiveddateupdated  having orderreceiveddate like '%2011%' 	0.000490599188340377
24210512	24944	how to do conditional column joins in sql?	select * from this_table tt  left join main_table mt  on tt.countrry = mt.country                           and tt.phase = 'zzz' left join main_table mt2 on tt.countrry = mt2.country                          and tt.city = mt2.city                          and tt.phase = 'aaa' 	0.702610994021316
24211743	14358	how to check who has access to symmetric keys in sql server	select u.name, p.permission_name, p.class_desc,      object_name(p.major_id) objectname, state_desc  from sys.database_permissions  p join sys.database_principals u on p.grantee_principal_id = u.principal_id where class_desc = 'symmetric_keys' 	0.0111847533024425
24213660	25362	multiple where clauses as separate columns	select so.salesordercode ,i.itemcode ,sum(case when i.warehousecode = 'main' then  i.unitsinstock else 0 end) as main ,sum(case when i.warehousecode = 'pfc' then  i.unitsinstock else 0 end) from salesorder so inner join inventory i   on so.itemcode = i.itemcode group by so.salesordercode, i.itemcode 	0.0173840088617422
24215304	35667	sql query based on multiple criteria	select * from orders ord1, orders ord2, conditions con  where ord1.trans = ord2.trans  and ord1.item = con.product1 and ord2.item = con.product2 	0.00559183164266376
24217183	14155	mysql qurery returns 0	select message from message join user_message on id = message_id where status = false 	0.757166479488766
24217679	8288	select all unique names based on most recent value in different field	select distinct x.staffname  from sicknesslog x where start/return = 1   and not exists (      select 1       from sicknesslog y      where x.staffname = y.staffname        and y.datestamp > x.datestamp        and y.start/return = 0   ) 	0
24217883	39983	sum sql values based on distinct values from another column and put the result in array	select month, sum(lessons)  from lessons_by_month  group by month  order by month(str_to_date(month,'%m')) asc 	0
24219266	16065	multiple date differences	select [staffname], datediff("d", min([date]), getdate()) as [days sick] from sicknesslog where [start/return] != 0 group by [staffname] 	0.00677829425987513
24220844	36981	mysql select top 10 results prepared statement	select id, username, score, name from ratings order by score desc limit 10 	0.0758833092084121
24221326	14125	sql union needs to return value in single column for calculations	select (cast(fech1 as timestamp) - cast(fech2 as timestamp) )total from (    select min(case when message='log a starts here' then t_stamp end) fech1,           max(case when message='log a ends here'   then t_stamp end) fech2    from alllog     where application = 'net'       and component='abc'      and transid='291-123'      and trunc(time_stamp) >= to_date('01-jan-2012','dd-mon-yyyy')       and trunc(time_stamp) <= to_date('30-jan-2012','dd-mon-yyyy')    group by transid ) 	0.00619152485095092
24223729	20642	compare software version in postgres	select regexp_split_to_array(v1, '\.')::int[] v1,         regexp_split_to_array(v2, '\.')::int[] v2,        regexp_split_to_array(v1, '\.')::int[] > regexp_split_to_array(v2, '\.')::int[] cmp from versions; 	0.149017056282127
24225611	23725	basic sql retrieve list of items without counting it twice	select distinct cityvisited from cv where day = 1 	0.000508105340596594
24225634	15401	sql query needed to combine many-to-one values into single result	select i.item_id,        group_concat(p.property_id, ':', p.property_value separator ';') as properties from item i inner join      property p      on i.item_id = p.item_id group by i.item_id; 	0.0180992491998771
24228567	8228	select first row of every mrn	select mrn, visit_number, event_time from (select oh.mrn, oh.visit_number, oh.event_time,              row_number() over (partition by oh.mrn order by oh.event_time) as seqnum       from oncology_histroy_mv oh       where oh.proc = 'bc - heamatology-oncology appt'      ) oh where seqnum = 1 order by event_time asc; 	6.53957361356553e-05
24228705	20575	mysql get between two dates	select * from `klj_agenda` where date between '2014-05-01' and '2014-30-05' 	0.000341001998985962
24230757	27234	combine sqlite query for multiple conditions	select * from table where (apple >= 3 and orange >= 1) or (apple = 0 and orange >= 1) or (apple = 4 and juice = 0) 	0.176220448815964
24231358	23973	select 2 specific lines from a table in database	select * from ps_product where id_product=44 or id_product=29 	0
24234465	16780	select max date even if it's null?	select a.custno, a.item, a.price, unix_timestamp(a.priceexp) priceexp from customers_view_items a join (   select custno, item, max(week_of) week_of   from customers_view_items   group by custno, item) b on a.custno = b.custno and a.item = b.item and a.week_of = b.week_of; 	0.00531199967362291
24234524	1135	codeigniter, join of two tables with a where clause	select *  from access_table a inner join codenames c on      a.chain_code = c.chain_code where a.chain_code = '123' and       c.accselect_lista != 0 	0.222660498094267
24235850	17737	mysql group_concat within group_concat different group by values	select  c.cus_name,         group_concat(cncat.size order by cncat.prod_name separator ', ') as size from    customer c         inner join         (             select  pc.cus_code,                      p.prod_name,                     concat(p.prod_name, '(', group_concat(pc.size), ')') size             from    product_customer pc                     inner join product p                         on pc.prod_code = p.prod_code             group   by pc.cus_code,                          p.prod_name         ) as cncat             on  c.cus_code = cncat.cus_code group   by c.cus_name 	0.108263148021046
24236689	37903	sql. how to select multiple rows by using the min and group by	select min(a.id) tbl1id, b.rewardid from mytable a join mytable b   on a.name = b.name group by b.userid, b.rewardid order by tbl1id, rewardid; 	0.00371239745585729
24237391	36475	binding drop down lists with unique data value fields from multiple sql tables?	select      data_type + '_' + convert(varchar(10), row_number() over(order by data_type))as data_type,      column_name  from information_schema.columns  where      (table_name = 'mytable1' and column_name in ('column1','column2','column3','column4','column5'))     or     (table_name = 'mytable2' and column_name in ('column1')) 	0.00050928092527726
24239167	11822	not getting the join i want	select sum(score_hours) from a join (select distinct uid       from b) as b on a.uid = b.uid 	0.406278887102672
24239889	12575	oracle sql - select distinct columns based on few columns	select distinct a, b, c, d, e, f, g, h, min(upper(i)) i, min(upper(j)) j from sample_table group by a, b, c, d, e, f, g, h; 	5.36059972714425e-05
24240300	6240	select all from left, only from right only where	select              r.*, u.username from                [dbo].[roles] r left join           [dbo].[usersinroles ] ur on                  r.id = ur.roleid left join           [dbo].[users] u on                  u.id = ur.userid                 and u.username = 'admin' 	0.000520878780193209
24240559	3147	query to fetch the number of rows fetched by another query	select count(*) from  (  select * from yourtable ) as a 	0
24240964	17381	conversion failed when converting the varchar value 'd1' to data type int	select isnull(max(cast(substring(aid,4,1) as int)+1),1) from tbl_name 	0.118709371136026
24241589	31437	find out which table a column in a view is from (t-sql)	select table1id, table1values...etc, 'table1' as originatingtable from table1 union select table2id, table2values...etc, 'table2' as originatingtable from table2 	0.000299005296804449
24241879	17003	group by one field and order another field by rand in mysql	select t1.parent, count(*),         ( select child            from test t2           where t2.parent = t1.parent            order by rand()            limit 1 ) child from test t1 group by t1.parent; 	0.000634177896988778
24243962	1310	how to use union all in a pivot query	select 'risk','adab','bahrain','kuwait','masirah','qatar' union all select convert(varchar,risk) ,convert(varchar,[adab]) as adab ,convert(varchar,[bahrain]) as bahrain ,convert(varchar,[kuwait]) as kuwait ,convert(varchar,[masirah]) as masirah ,convert(varchar,[qatar]) as qatar from (select risk, piv_site = risk, site         from qcvqciffull         where (1=1) and risk is not null) as ps pivot (count(piv_site)         for site in ([adab], [bahrain], [kuwait], [masirah], [qatar])) as pvt 	0.330293888259923
24244465	22554	selecting rows using multiple like conditions from a table field	select ir.*  from importedrows ir join customids c on ir.customid like replace(c.searchpattern, '*', '%') where c.fkcustomerid  = 1; 	0.000155658361004364
24244729	25028	combining one column between two tables in mysql	select a.vote_candidate, count(*) ranked_choice_votes, d.original_votes from vote_orders a inner join (   select vote_id, min(vote_order) as min_vote_order   from vote_orders   where vote_candidate not in (1,6)   group by vote_id ) b on a.vote_id = b.vote_id and a.vote_order = b.min_vote_order inner join (   select vote_id   from vote_orders   where vote_candidate = 1   and vote_order = 1 ) c on a.vote_id = c.vote_id left outer join (     select vote_candidate, count(*) as original_votes     from vote_orders      where vote_order = 1     group by vote_candidate ) d on a.vote_candidate = d.vote_candidate group by vote_candidate; 	0.000169021494231947
24245797	40009	sql on pull rows where id is < #	select sum(km) from travel where dayid < 3 	0.00887894110247777
24245934	35896	mysql conditions with grouping many-to-many tables	select employeetable.employee_id from   (select sl.skill_id, count(*) as subskill_count   from skill_links sl   group by sl.skill_id) skilltable   join   (select esl.employee_id, sl2.skill_id, count(*) as employee_subskills    from emp_skill_links esl      join skill_links sl2 on esl.subskill_id = sl2.subskill_id    group by esl.employee_id, sl2.skill_id) employeetable   on skilltable.skill_id = employeetable.skill_id  where employeetable.employee_subskills = skilltable.subskill_count 	0.242318999609112
24247521	1472	counting and finding greater then value in sql	select department, count(employeeid) as numberofemployee from deparment d inner join employees e on d.deparmentid = e.deparmentid group by deparment having count(employeeid) >= 4; 	0.000355211758396067
24248334	39586	t-sql list dump devices	select * from sys.backup_devices 	0.569481057023832
24248778	34271	mysql - return first column once and all corresponding column data	select name, group_concat(`data`) from table group by name; 	0
24250064	31500	getting a unique value from an aggregated result set	select * from [crm_mscrm].[dbo].[asyncoperationbase] where regardingobjectid in (    select regardingobjectid    from [crm_mscrm].[dbo].[asyncoperationbase] a    where workflowactivationid in     (      '55d9a3cf-4bb7-e311-b56b-0050569512fe',      '1bf5b3b9-0cae-e211-aeb5-0050569512fe',      'eb231b79-84a4-e211-97e9-0050569512fe',      'f0ddf5ae-83a3-e211-97e9-0050569512fe',      '9c34f416-f99a-464e-8309-d3b56686fe58'    )    and statuscode = 10    group by regardingobjectid    having count(*) > 1 ) 	9.945223883938e-05
24250213	40735	handling null values with join across multiple tables	select  tblcounty.id,      isnull(tbladdress.code, 'none') from tblcounty left join tblcode on tblcounty.name = tblcode.name     left join tbladdres on isnull(tblcode.code, 'none') = isnull(tbladdress.code, 'none') 	0.285873161497275
24250267	13421	mysql search results for similar sounds	select * from t where soundex(firstname)=soundex('suman') 	0.559325615329912
24250513	28573	converting data types in sql	select top 1 @variableid = left(variableid,20) from @temptable 	0.25368172544155
24252246	41101	sql select to return 2 rows one for each column in table	select name, pri as addr from table1 where pri is not null union all select name, sec as addr from table1 where sec is not null order by 1,2 	0
24252958	1802	postgresql group by sequence time stamps	select row_number() over (order by grp) as groupid,        string_agg(id, ',') as ids from (select t.*,              (time - row_number() over (order by time) * interval '1 hour') as grp       from table t      ) t group by grp; 	0.155615979675089
24253701	27112	sql select from multiple tables + in list	select a.id, a.title, b.u1, b.u2 from articles a join (   select if(a.id=b.id,a.id,concat(a.id,',',b.id)) author, a.name u1, if(a.id=b.id,'no user',b.name) u2   from users a   join users b) b on a.author = b.author; 	0.0024518505607248
24253814	7917	can't select an existing column in postgresql	select "foto_municipis" from avatar_avatarx 	0.359770524111873
24253991	37094	using not in() mysql with table lacking unique rows or primary keys	select a.hid      , a.yr      , a.mo    from ap a  where not exists (        select v.hid          from `ap supervisory visits` v         where v.hid = a.hid           and v.yr  = a.yr           and v.mo  = a.mo  ) 	0.00344677763648714
24256533	19679	sql server pivot query add a total	select semester, studentdesc, [a],[b],[c],[d], isnull([a],0)+isnull([b],0)+isnull([c],0)+isnull([d],0) as totalsessions from 	0.0471631552390738
24256885	41018	change value based on dynamical object	select dateadd(hour, 9, cast(cast(@a as date) as datetime)) 	0.00133905166830696
24257411	31899	hiding repeated row values in sql	select      case when rnum=1 then username else '' end username,     case when rnum=1 then fee else '' end fee,     referencename,     billed  from(     select          *,          row_number() over (partition by username order by username) rnum      from tbl )x 	0.0058165719960552
24258137	4938	string split to table on whole column	select q.personid, r.racedescription from dbo.questionaireresponse q join dbo.race r  on ',' + q.raceids + ','  like  '%,' + convert(varchar(10),r.raceid) + ',%'; 	0.000737213378783245
24258608	7882	order rows by columns names	select * from table_name order by ticker_flag desc, twitter_flag desc 	0.000442337212963936
24259472	36279	how to select only the rows with the latest date for each stock	select stock_data.*  from stock_data inner join (     select ticker, max(date) maxdate     from stock_data     group by ticker) maxdates  on maxdates.maxdate=date  and maxdates.ticker=stock_data.ticker 	0
24260088	9020	matching query from two tables	select table2.motor, table1.name1 as name2, table1.id, table2.name2 as name1, table1.siteclassification from table1 inner join table2 on table1.id = table2.id; 	0.00114863044232033
24260755	36001	how do i select the top three rows in my database for posts	select * from posts order by likes desc limit 3 	0.000202181519945131
24260790	15842	finding most 'popular' items in multiple tables in mysql	select some_name, @rank_1:=@rank_1 + 1 as ranking from table_1 cross join (select @rank_1:=0) sub_1 union all select some_name, @rank_2:=@rank_2 + 1 as ranking from table_2 cross join (select @rank_2:=0) sub_2 union all select some_name, @rank_2:=@rank_2 + 1 as ranking from table_2 cross join (select @rank_2:=0) sub_3 	0
24261098	21440	maximum number of rows in sqlite database in pycharm	select count(*) from <name_of_table> 	5.74695146171618e-05
24262471	3933	count of nulls in if condition	select sum(b.correct = 1) correct_answers,        sum(b.correct != 1) incorrect_answers,        sum(a.answer is null) as no_answers,        a.id from a  left join b on a.answer = b.id  where a.created_at between '2014-06-10' and '2014-06-17'  group by a.id  order by sum(b.correct = 1) desc; 	0.0976237669888187
24265449	28464	finding empty space in time	select * from ( select end as start,        coalesce((select min(start) from t where start>t1.end),               date_add(date((select max(end) from t)), interval 1 day)          ) as end from t as t1  where not exists (select * from t                             where t1.end                                   between start and end                                  and userid<>t1.userid ) union all  select date(min(start)) as start,        min(start) as end from t  ) as t2 order by start 	0.0209950353921619
24266415	22949	mysql: get next 'n' results	select * from table where pk < $stored_pk order by date desc limit 3; 	0.000313860167269933
24267299	24600	sql sum down rows and sum of sum across columns	select  sum(finperiodnr) as  finperiodnr  , sum(baljan) + sum(balfeb) + sum(balmar) + sum(balapr) as totalsumofbal from tble 	0.000106880031073312
24268252	33009	mutilple select in one query	select           projects.project_id,                  projects.project_name,                  count(*) as numberofemployees from             projects inner join       project_manager manager on projects.project_id = manager.project_id  inner join       project_employee emp on projects.project_id = emp.project_id   where            manager.manager_id = @mid             group by         projects.project_id,projects.project_name 	0.102032225748623
24268380	40137	casting string to date	select to_date(to_char(max(entdate), 'dd/mm/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss') as last_transaction_date from table; 	0.0604031900700769
24269041	117	merging duplicate rows instead of removing arbitrarily	select max(prefix), firstname, max(middlename), lastname, max(suffix)    from table   group by lastname, firstname  order by lastname, firstname 	0.000285334484881066
24270135	40808	applying sql where conditionally	select distinct a.user, b.name from tablea a inner join tableb b on a.record_idn = b.r_idn                      or a.access = 'all'                      or b.folder_access = 'all' where a.user = 2 order by a.user, b.name 	0.612811534990849
24270767	8028	how to create multiple rows from single row with time interval in mysql	select d.date as active_date, t.start_date, t.end_date, t.frequency from {your_table} as t inner joib {date_lookup_table} as d on d.date between t.start_date and t.end_date 	0
24270939	13554	comparing two unrelated counts in sql	select     sum(iif([grant awarded],1,0))/ nz(sum(iif([grant submitted],1,0)),1) as [award rate] from       grants 	0.00293209728873856
24270940	39886	split column into two columns based on type code in third column	select min(id), sin,         max(case when type = 'phone' then contact end) as phone,        max(case when type = 'email' then contact end) as email from people t group by sin; 	0
24272757	2790	using a repeater to display time punch data by day	select   [1] sun, [2] mon, [3] tue, [4] wed, [5] thr, [6] fri, [7] sat from (    select      punchtime,      punchday,      row_number() over(partition by punchday order by punchtime) rownumber    from @t    unpivot(punchtime for punchtype in (punchin,punchout) ) t1 ) t2 pivot(max(punchtime) for punchday in ([1],[2],[3],[4],[5],[6],[7]) ) t3 	0
24273366	17550	how to query a table to find rows where there are no numbers in a column	select top 10 * from @workorderhistory wo   where wo.workorder like '%[^0-9]%' 	0
24275317	20228	in mysql, can i select with union but limit the rows from the second query based on the first query?	select id,name,awesomeness from cats where color = 'blue' union select cat_id,null,badness from badcats     where cat_id in     ( select id from cats where color = 'blue')     and color = 'blue 	0
24275895	26708	grouping by time ignoring the date portion	select sec_to_time(floor(time_to_sec(time(date_time))/300)*300) as time5, count(id) from data where score >= 500 group by sec_to_time(floor(time_to_sec(time(date_time))/300)*300) order by time5; 	0.00165761565788418
24276730	29195	match substring with list members in big query	select word from [publicdata:samples.shakespeare] a cross join  (select split(fragments) fragment from (select "duck,cat,bear" fragments)) b where word contains fragment group by 1 word bear      scathful      bearing   dedication    mollification     ... 	0.0710700960826955
24276925	738	how to find all most common values in sql?	select name, count(*) as popularity  from cattwo  group by name  having count(*) =          (             select count(*) as max_popularity              from cattwo              group by name             order by max_popularity desc             limit 1         ); 	0
24278613	20020	search alphanumeric string in sql server	select * from [tbkname] where len([columnname]) = 9 and columnname like '%[^a-za-z0-9]%' 	0.378854910879738
24278871	25699	incremental count based on criteria	select    student,    term,    subject,    row_number() over (partition by student, subject order by term)-1 as count from     tablename 	0.000566156496970332
24279748	17170	removing duplicate rows from a sql query	select distinct question.id_question, candidat_test_answer.id_test,candidat_test_answer.id_candidat, date from question join candidat_test_answer on question.id_question = candidat_test_answer.id_question where ctr.id_test=17 and id_cand=1 and date='2014-06-01' 	0.00160972738920718
24280256	35954	using max in a having sql query	select  hgmclent.clnt_name  ,cmpadd.add_1 ,cmpadd.add_2 ,cmpadd.add_3 ,hgmprty1.post_code ,hgmprty1.prty_id ,hraptvpd.seq_no ,vd_prd ,void_cd ,void_desr ,st_date ,seq_no ,end_date ,est_avldt ,lst_revn, rank() over (partition by clnt_name,cmpadd.add_1 order by hraptvpd.seq_no desc) as rnk  from hgmprty1 join hratency on prty_ref=prty_id join hrartamt on hrartamt.rent_acc_no=hratency.rent_acc_no join hracracr on hracracr.rent_acc_no=hrartamt.rent_acc_no join hgmclent on hgmclent.client_no=hracracr.clnt_no join cmpadd on cmpadd.add_id=hgmprty1.add_cd join hraptvpd with (nolock) on  hraptvpd.prty_ref=hgmprty1.prty_id join hraptvps on hraptvps.prty_ref=hraptvpd.prty_ref and seq_no=vd_prd where tency_end_dt is null and prim_clnt_yn=1 	0.502907631729524
24280641	9899	php mysql - select the id with the highest number	select *  from `stats`  where user_id = '$userid' order by id desc limit 1 	0
24280664	24382	sql, number of user of each group	select g.name, count(u.usergroupid) as members from groupuser g left join user u  on  u.usergroupid = g.id group by g.name 	0
24282261	9414	t-sql select rows with 3 consecutive int columns over threshold	select * from t where (jan > 100 and feb > 100 and mar > 100) or       (feb > 100 and mar > 100 and apr > 100) or       (mar > 100 and apr > 100 and may > 100) or       (apr > 100 and may > 100 and jun > 100) or       (may > 100 and jun > 100 and jul > 100) or       (jun > 100 and jul > 100 and aug > 100) or       (jul > 100 and aug > 100 and sep > 100) or       (aug > 100 and sep > 100 and oct > 100) or       (sep > 100 and oct > 100 and nov > 100) or       (oct > 100 and nov > 100 and decm > 100) 	0.000235910046952298
24284247	12092	mysql need to select all values having the biggest number of multiple entries	select icd10 from (     select max(disease_count) as max_disease_count     from     (         select tbl_disease.icd10, count(tbl_disease.icd10) as disease_count         from `tbl_disease`         join tbl_symptom_disease         on tbl_disease.icd10=tbl_symptom_disease.diseasecode         where tbl_symptom_disease.symptomcode='p18'          or tbl_symptom_disease.symptomcode='p19'         group by icd10     ) sub0 ) sub1 inner join (     select tbl_disease.icd10, count(tbl_disease.icd10) as disease_count     from `tbl_disease`     join tbl_symptom_disease     on tbl_disease.icd10=tbl_symptom_disease.diseasecode     where tbl_symptom_disease.symptomcode='p18'      or tbl_symptom_disease.symptomcode='p19'     group by icd10 ) sub2 on sub1.max_disease_count = disease_count 	0
24284338	20156	apart from union , union all and pivot in ms- sql server can i combine two columns into one column	select t.x from table      cross apply (          values (col1), (col2)      ) as t(x) 	0
24284382	39591	list brand only once from table	select distinct brand from products 	0
24285118	7717	show available rooms between to dates? sql	select roomnumber, roomtypeid from rooms  where roomnumber not in  (   select roomnumber    from booking    where departure >= to_date(? , 'yyyy-mm-dd')   and arrival <= to_date(? , 'yyyy-mm-dd') ) and roomtypeid = ? order by roomnumber; 	7.90632250466558e-05
24286141	15180	matching algorithm in sql	select x.name, max(x.rank)  from matches x join (     select name from matches where prop = 1 and rank > 5     intersect     select name from matches where prop = 3 and rank >= 8 ) y     on x.name = y.name  group by x.name order by max(rank); 	0.0713155595038993
24287190	25344	how to connect to a db on another server using sql?	select top 10 * from [linked server name].[remote database name].[schema].[table] 	0.0333662250806148
24290356	282	search "int" in a database	select object_name(c.object_id) tablename, c.name columnname from sys.columns as c join sys.types as t on c.user_type_id=t.user_type_id where t.name = 'int'  order by c.object_id; go 	0.18929589885124
24290612	39954	adding a count column to a grouped query	select users_pics.wardrobe,   profile.fname,  users_pics.pic,  users_pics.u_pic_id,  users_pics.email,  users_pics.make,  users_pics.designer,  photo_comment.comment,  max_photo_comment.count_pic_id from dbo.users_pics  inner join profile on users_pics.email = profile.email   left join (select pic_id, max(comment_id) max_comment_id, count(pic_id) count_pic_id            from photo_comment            group by pic_id) max_photo_comment      on users_pics.u_pic_id = max_photo_comment.pic_id          left join photo_comment on max_photo_comment.pic_id = photo_comment.pic_id      and max_photo_comment.max_comment_id = photo_comment.comment_id where users_pics.wardrobe = mmcolparam and users_pics.email = mmcolparam2 order by u_pic_id asc 	0.00570440109679735
24290781	16296	how to display two separate graph in one chart	select top 2 [date]       ,[lastweekemrorders]       ,[lastweekacclaborders]       ,[lastweeklabresults]   from [db].[dbo].[tbl1]   order by [date] desc 	0.000165765422610082
24291500	906	select recently incerted record from table in oracle 11g	select max(employee_in_time), employee_no, trunc(employee_in_time) as calday from employee_time group by employee_no, trunc(employee_in_time) 	0.000861602912299476
24291527	7397	order sql query by the sum of specefic columns	select case when [phone] = 'y' then 1 else 0 end  +  case when [employee] = 'y' then 1 else 0 end  +  case when [address] = 'y' then 1 else 0 end as total from table 	0.0117144902915479
24293943	10988	sql select items with only certain attributes	select     c.name from     config c join     config_capability as cc on     c.id = cc.config_id join     capability ca on     cc.capability_id = ca.id  where     config.node_count <= 4 group by c.name  having sum(ca.name not in('cap1','cap2')) = 0 	7.86139406448718e-05
24294393	39923	sql oledbcommand selecting excel columns	select f8 from [sheet1$] where f11 = '1' 	0.0488070794290769
24295913	29479	oracle how to get the count of occurrences within a comma separated string	select cd_vals, cd_val, count(1) from   (select cd_vals,column_value cd_val         from   temp1 t1, table(split(rtrim(t1.cd_vals)))) join   temp2 using  (cd_val) group  by cd_vals, cd_val cd_vals     cd_val count(1) yb,yl       yb            1 yb,yl,yl,yl yl            3 yl          yl            1 yb,yl       yl            1 yb,yl,yl,yl yb            1 5 rows returned. 	0
24300547	31467	mysql query is returning additional results	select c.lastname, b.bidamount, b.bidtime, p.productname  from bids b join product p on b.product_id = p.product_id join customer c on b.customer_id = c.customer_id where bidtime between '06/19/2014 12:00:01 am' and '06/19/2014 11:59:59 pm' 	0.769651990478202
24300616	35164	php show links a user haven't clicked	select links.id, links.link from links where links.id not in (select id from clickedlinks); 	0.00257303868807736
24303507	34669	multiple select queries using primary and foreign key	select     count(c.[s_id]) total,     s.[usd_value],     s.[eur_value] from sales s left join country c on c.[s_id] = s.[s_id] group by s.[s_id] having total > 1 and (usd_value > 0 or eur_value > 0) 	0.00243407576918458
24304485	40707	repeated rows status based on given rule	select a.refno, a.amount, a.id, a.billed,  case    when b.bill_total = 0 then 'singleunbilled'    when b.bill_count > b.bill_total then 'multiplebilled'    when b.bill_count = b.bill_total then 'singlebilled'   else '' end as [status] from test a inner join (   select refno,    count(billed) as bill_count,    sum(cast(billed as int)) as bill_total    from test   group by refno ) b on a.refno = b.refno 	0
24305913	28876	cant search sql db from front end	selectcommand = "select * from fish where [common name] like @0 or [latin name] like @0"; searchterm = "%" + request.querystring["searchfield"] + "%"; 	0.231073499659065
24306601	27093	mysql transpose columns to rows	select project, 'q1' quarter, q1_hc hc, q1_cost cost from tablename union select project, 'q2', q2_hc, q2_cost from tablename order by project, quarter 	0.00200874454913805
24306627	35343	sql : select some column which i don't know the entire name	select * from information_schema.columns  where table_name='table1' and column_name like 'exemple_%' 	0.000182290030096577
24306883	38402	counting duplicate rows in mysql	select count(id) as ocurences, id from master_huts group by id 	0.00188219789087903
24306988	9148	get data from database according two dates	select type, sum(case when date = date1 then a else 0 end) 'a', sum(case when date between date1 and date2 then b else 0 end) 'b' from table  group by type 	0
24307073	22831	last_day in postgresql	select (     date_trunc('month', now())     + interval '1 month -1 day'     + now()::time )::timestamp(0); 	0.685292123538253
24309203	27416	oracle hourly report subtract two fields by hour for given date range	select t1.time_hourly,     sum(nvl(off1.num_cust_off, 0)-nvl(on1.num_cust_on,0))            over (order by t1.time_hourly) as user_still_affected from (     select trunc(off_time,'hh') as time_hourly from tablea     union      select trunc(on_time,'hh') as time_hourly from tablea ) t1 left join (     select trunc(off_time,'hh') as off_hour,          sum(user_affected) as num_cust_off     from tablea     where off_time > '06-02-2014 00:00:00'          and on_time < '06-02-2014 16:00:00'      group by trunc(off_time,'hh')  ) off1 on t1.time_hourly = off1.off_hour left join (     select trunc(on_time,'hh') as on_hour,          sum(user_affected) as num_cust_on     from tablea     where off_time > '06-02-2014 00:00:00'          and on_time < '06-02-2014 16:00:00'      group by trunc(on_time,'hh')  ) on1 on t1.time_hourly = on1.on_hour order by t1.time_hourly 	0
24310005	24934	mysql multiple selects?	select a.id,  a.title,  at1.artid,  at.value visible, at1.value date, at2.value featured from articles a inner join attributes at on a.id = at.artid inner join attributes at1 on a.id = at1.artid inner join attributes at2 on a.id = at2.artid where      at.attrib='visible' and at1.attrib='date' and at2.attrib='featured' and at.value ='true' 	0.339716771903235
24310104	40661	how can i use a 'group by' (or similar) statement to aggregate a few specified rows?	select    case when id in ('03','05') then '03 and 05' else id end,    sum(value) from tab group by 1 	0.34188485925589
24310492	5375	multi-column duplicates query	select a.col1, a.col2, a.col3, a.num1, a.num2, a.num3, a.num4, a.num5, t.cnt as numberofduplicates from tablea a join (select num1, num2, num3, num4, num5, count(*) as cnt       from tablea       group by num1, num2, num3, num4, num5       having count(*) > 1      ) t   on a.num1 = t.num1 and a.num2 = t.num2 and a.num3 = t.num3 and a.num4 = t.num4 and a.num5 = t.num5 	0.416411721331531
24310811	13372	how to inner join on non-empty values but at the same time left join on empty values?	select c.customercode, a.addressvalue from customers c left join addresses a     on a.addresscode = c.customer_addresscode where c.customer_addresscode = ''    or a.addressvalue is not null 	0.000775612289709457
24311196	38294	filtering data in left join	select  r.id, r.name from    record r join    record_type_field rf on      rf.data_type = 'color' left join         record_type_data rd on      rd.record_id = r.id         and rd.type_id = rf.id order by         rd.data 	0.699394728515797
24311648	36442	mysql - selecting the latest 3 records of each stock group	select t.* from ( select s.*, @rank:= case when @group = s.ticker then @rank +1 else 1 end rank , @group:= s.ticker g  from `stock` s join (select @group:='',@rank:='') t order by ticker  ,`date` desc ) t where t.rank <=3 	0
24312444	7655	oracle sql: join a table of dates with different ids	select dt.dates, d.acct_id, d.amt from table_dates dt     left outer join table_amt d partition by (acct_id)         on d.dates = dt.dates order by d.acct_id, to_date(dt.dates); 	0.00014544879666845
24312524	20778	mysql select grouping with a specific criteria	select  * from    table order by         find_in_set(stage, '8,0,5'),         date desc 	0.014172333060303
24313646	22762	sql replacing a null value with 0 within a pivot	select [employee id], name, @year as [year], isnull(january, 0)  as january,  isnull(february, 0)  as february,  isnull(march, 0)      as march, isnull(april, 0)    as april,    isnull(may, 0)       as may,       isnull(june, 0)       as june, isnull(july, 0)     as july,     isnull(august, 0)    as august,    isnull(september, 0)  as september, isnull(october, 0)  as october,  isnull(november, 0)  as november,  isnull(december, 0)   as december from 	0.153597269258023
24315525	38012	ssrs/t-sql sum if another condition is met	select transactionid     , value     , sum(value) over(partition by transactionid) as total from sometable 	0.0170103423974684
24315902	32614	sql server - summing values in one column based on common value in another column	select item, sum(count) 'count' from temp group by item 	0
24316888	9001	move values from rows to columns in sql server 2008	select 'mon' as day, mon as number from t1 union all select 'tue', tue from t1 union all select 'wed', wed from t1 union all select 'thu', thu from t1 union all select 'fri', fri from t1 union all select 'sat', sat from t1 union all select 'sun', sun from t1 	0.000299772200718316
24318445	20537	trim specific column names in select statement	select ltrim(rtrim(firstname)) as firstname,        ltrim(rtrim(lastname)) as lastname,        ltrim(rtrim(email)) as email from [user] 	0.00666855755344006
24319490	2780	dateadd sql 2008 next time and next date	select id, date, time, value,      cast(floor(cast(dateadd(hour, 1, date + time) as float)) as datetime) as nextdate,      convert(time, dateadd(hour, 1, date + time), 108) as nexttime      from tablename 	0.00160085169320498
24319926	6257	convert month fullname to month number	select month(str_to_date('april','%m')) as month; 	0
24320242	13683	historical inventory by day	select date, count(*) from inventory  where status != 'shipped' group by date order by date; 	0.00336689138477426
24320799	17847	mysql group records with latest entry from child table	select `c`.`id`,  `c`.`name`,  `c`.`office_id` , `o`.`name` office_name,  `m`.`date`, `m`.`description` from `computer` as c left join `office` as `o`  on (`o`.`id` = `c`.`office_id`) left join `maintain` as m on (`c`.`id` = `m`.`computer_id`) inner join  (select computer_id,max(`date`) maxdate   from maintain   group by computer_id ) t on(m.`date`=t.maxdate and m.computer_id= t.computer_id)  where `c`.`name` ='cp1' ... more conditions 	0
24320998	21631	select query by array values	select  point, privacy from `tablename` where status=1 and id in(?,?,?...) 	0.0378555355149717
24321404	39522	adding two count queries in sql server 2008	select sum(f) from (    select count(*) as f from table1    union all     select count(*) as f from table2 ) t 	0.24767735867387
24322001	14669	sql non aggregate pivot	select i.ilanid,iduz.deger,ozellikadi from ilan i join kategori k on i.kategoriid=k.kategoriid join kategoriduzyazilar kduz on kduz.kategoriid=k.kategoriid join ilanduzyazilar iduz on iduz.ilanid=i.ilanid  and kduz.id=iduz.kategoriduzyazilarid where i.kategoriid=6864 	0.77822404760531
24322551	10583	sql server: combine two small selects in one	select a.email as requesteremail,b.email as approveremail     from  logtable b join logtable a     on b.ntid = r.approver and a.ntid = r.requester     for xml path(''), elements, type 	0.0229171413967229
24324405	31957	fetch firstname using userid from another table	select journeyid, pax.firstname as passengername, dri.firstname as drivername      from paymenthistory pay      join userinformation pax on pay.passengerid = pax.userid      join userinformation dri on pay.passengerid = dri.userid 	0.00119257602043835
24325924	17767	mysql returned an empty result set (i.e. zero rows) where expecting more then zero rows	select username   from `info`   where id in ('919953990950_1403180247868.707',                 '919953990950_1403239797121.525',                '919953990950_1403241821083.838',                '919953990950_1403248486971.661',                '919953990950_1403248511255.484',                '919953990950_1403248860947.79',                '919953990950_1403255594277.013'               ) and        username <> '1403176452487620892'   limit 50; 	0.000339598003088936
24326278	29821	select columns with and without group by	select p.* from  table1 as p inner join  (select productname, min(price) as minprice    from table1      group by productname) t  on p.productname  = t.productname and p.price = t.minprice 	0.0351230873073125
24326759	34693	sql joining table with two different alias	select u.userid,u.fname,u.lname,a.managerid from user u a left join agents a on u.userid=a.agentid where u.fname like '%anyname%' union select u.userid,u.fname,u.lname,a.managerid from user u a left join agents a on u.userid=a.managerid where u.fname like '%anyname%' 	0.0171121929360181
24328971	4339	how to query an xml column in tsql (hl7 message)	select      spm.query('     obx.query('     obx.query(' from (     select          @xmldata.query('         @xmldata.query('     from          (select number from master..spt_values             where type='p' and number between 1 and @xmldata.value('count(/hl7message/spm)','int')         ) v ) items 	0.427052753019535
24329353	23675	select user if the user has data on another table	select users.name from users join data on users.name = data.name 	0
24329853	16453	find related topics in mysql?	select t_id, t.title, count(*) as cnt from post_topic pt join topic t on t.id = pt.t_id where exists (select null               from post_topic pt1               join topic t1 on pt1.t_id = t1.id               where t1.title = 'database'  and p_id = pt.p_id) and t.title <> 'database' group by  t_id, t.title order by cnt desc; 	0.00653071734613987
24330465	15762	find duplicate records in mysql for each customer id	select customers_id, count(points_comment) duplicate_rows from customers_points group by customers_id, points_comment 	0
24330610	25425	populate data in sql server	select id, datelog, min(timelog) as timein, max(timelog) as timeout      from tablename      group by id, datelog 	0.27662137358239
24331186	37702	query foreign key and constraint's name of table in sqlserver	select         object_name(f.parent_object_id) tablename,        col_name(fc.parent_object_id,fc.parent_column_id) colname     from         sys.foreign_keys as f     inner join         sys.foreign_key_columns as fc            on f.object_id = fc.constraint_object_id     inner join         sys.tables t            on t.object_id = fc.referenced_object_id     where         object_name (f.referenced_object_id) = 'yourtablename' 	0.000121291318093231
24332571	34997	find number value in string and increment it using replace	select    v,    concat(     left(v,locate('[',v)),     mid(v, locate('[',v)+1, locate(']',v)-locate('[',v)-1)+1,     right(v,length(v)-locate(']',v)+1)) v2 from table1; 	0.000433667149653945
24332799	3906	converting datediff(s, x, x) results to hh:mm	select userid, first_nm, last_nm, mgrname, convert(varchar(5),  dateadd(minute, sum(onprod)/60, 0), 114) as onprod, convert(varchar(5),  dateadd(minute, sum(offprod)/60, 0), 114) as offprod,  convert(varchar(5),  dateadd(minute, sum(onprod+offprod)/60, 0), 114) as sumprod from #prodtmp group by userid, first_nm, last_nm,  mgrname 	0.00581526702785455
24332892	13030	trying to combine three individual select statements into one main select statement	select    aid   , eid   , storeid   , [language]   , 'brandlabel' = case when brandlabel like '%"'                           then left(brandlabel, len(brandlabel) -1)                         else brandlabel                    end   , 'terms' = case when terms like '%"'                           then left(terms, len(terms) -1)                         else terms                    end   , 'trackorderlbl' = case when trackorderlbl like '%"'                           then left(trackorderlbl, len(trackorderlbl) -1)                         else trackorderlbl                    end from parallel_purchase_email_content_oms with (nolock) 	0.00289629782875902
24334624	24303	mysql: find rows from table a not indicated in tables b or c	select distinct a.recipe_id  from recipe_log a  where a.type='category changes' and not exists (select * from recipe_batches b where a.recipe_id = b.recipe_id) 	0.000190801312742095
24337282	27136	convert varchar to bigint including null values	select swmitems.upc from swmitems       left join obj_tab          on case when isnumeric(obj_tab.f01 + '.e0') = 1                   then case when convert(float, obj_tab.f01) between -9223372036854775808                                                                  and 9223372036854775807                            then convert(bigint, obj_tab.f01)                       end             end = swmitems.upc where obj_tab.f01 is null 	0.029709831985845
24337501	1415	mysql - group 2 rows based on different columns	select max(ta.a_id) as a_id, max(ta.a_name) as a_name,        max(tb.b_id) as a_id, max(tb.b_name) as b_name,        max(tc.c_id) as a_id, max(tc.c_name) as c_name,        max(td.d_id) as a_id, max(td.d_name) as d_name        from (select a_name as name from table t union select b_name union select c_name union select d_name      ) names left outer join      table ta      on is_same(ta.a_name, names.name) left outer join      table tb      on is_same(tb.b_name, names.name) left outer join      table tc      on is_same(tc.c_name, names.name) left outer join      table td      on is_same(td.d_name, names.name) group by names.name; 	0
24337876	10649	how to get hash value of a text saved in a database	select md5(some_column) from some_table; 	0.0015591742993261
24339287	38324	how to find duplicate id in table and display list of that	select rpsid, count(*) as n      from rpserv      group by rpsid      having count(*)>1      order by rpsid desc 	0
24340757	23433	more efficient sql to eliminate multiple sub-queries?	select id, name, nr_r, is_d, ...      , (is_d + is_p)/(is_d + is_p + is_b + is_i) yay      , (is_p + is_b)/(is_d + is_p + is_b + is_i) boo from (      select f.id, f.name          , count(r.id) as nr_r          , sum(r.is_d) as is_d          , ...      from features f      left join responses r           on r.id_feature = f.id         and r.is_deleted is null       left join participants p           on r.id_participant = p.id         and p.is_ignored is null         and p.category like :p_category        where f.is_deleted is null         and f.id_survey=:id_project      group by f.id, f.name ) as t order by ... 	0.707720028765431
24343527	17629	sqlite count as type cast	select cast(count(columna) as real) as count from ... 	0.427436711789978
24347571	30860	get an processing instruction value	select x.xml.value('data(processing-instruction("ent")[1])','varchar(30)') from @x.nodes('/root/entity') x(xml); 	0.0885652712970972
24347798	39150	how to get a group of the highest foo's in a sql table	select     * from     foos where     foo = (select max(foo) as highestfoo from foos) 	0
24349938	8840	php & mysql can't get name of table with union	select `condition`, 'table1' as source from `table1` where `id` = '1' union all select `condition`, 'table2' from `table2` where `id` = '1' union all select `condition`, 'table3' from `table3` where `id` = '1' 	0.0287544924174709
24350411	35211	mysql find parent records where given values are found in all child records	select *, count(option_name) as total from parent p  left join relations r on r.parent_id = p.parent_id  where (option_name = colors   and option_value = aaa)  or (option_name = country  and option_value = ddd)  having total > 1 	0
24352557	1031	how to count from two tables by using join	select user.*, count(*) as best_answer_count  from answer  left join user on  answer.userid = user.id   left join question on question.bestanswerid = answer.id   group by user.id 	0.00352995159326019
24352698	18074	using sql or pl/sql to parse an xml document to extract field values	select  j.col1, j.col2, j.col3, j.col5, j.col6, j.col7, j.col8, x.*  from junk j, xmltable ('$d' passing xmltype(col4) as "d"     columns     type     varchar2(100)   path '    authors  varchar2(100)   path 'fn:string-join(    documentdate varchar2(100) path '    publishedcountries varchar2(100) path 'fn:string-join( 	0.0206935180044085
24354109	12638	mysql order by max matches field value	select distinct(l.name) as link  from links l inner join tags t on l.id = t.link_id  and l.id <> 1 group by t.link_id order by count(t.link_id) desc 	0.00255440462333022
24354891	7441	count total flow inventory in and out php mysql	select t.*, @stock := @stock + case when status = 'in'                                      then total                                     else -total                                  end as stock from your_table t cross join (select @stock := 0) s order by t.id 	0.00641062358604603
24355198	12043	how to join a table to a ranked select query in mysql?	select  @currank := @currank + 1 as rank, points, userid from  (select rr.points, rr.userid  from rank rr inner join settings sr on sr.userid=rr.userid and sr.active=1 order by rr.points desc) as m, (select @currank := 0) r; 	0.043906127746811
24356069	22673	php query to sort result from database	select t1.*  from  (     select t2.* from (       select c.* , my_order 1 from comments c       where content = '$id'           and approved = '1'            and parent_id = '0'       order by rating desc limit 3     ) t2     union     select c.* , my_order 2 from comments c     where content = '$id'          and approved = '1'          and parent_id = '0'          and id not in (             select id from comments             where content = '$id'               and approved = '1'                and parent_id = '0'             order by rating desc limit 3         ) ) t1 order by      my_order,      (case when my_order = 1 then rating else timestamp end) 	0.0161380271145067
24356256	1104	counting the number of rows based on like values	select      left(customers.name,1) as 'name',     count(*) as numberofcustomers from customers where     customers.name like '[a-z]%' group by left(customers.name,1) 	0
24356957	17707	how do i check if values in a column are all equal to a given constant?	select student.name, student.major  from student  natural join grade_report group by student.name, student.major  having sum(grade_report.grade <> 'a') = 0 	0
24357588	27429	how to query the order result in this table structure in mysql/ sql?	select src.max_date,        src.order_id,        src.member_id,        case            when s1.description = 100 then 'order_receive'            when s1.description = 200 then 'order_deliver'        end as status_description from   (select max(s.create_date) max_date, s.order_id , o.member_id    from status s    join `order` o on o.order_id = s.order_id    group by s.order_id, o.member_id) src join status s1 on s1.create_date = src.max_date; 	0.445133255323787
24358571	28819	sql query to count all rows with duplicate values broken down by primary key	select d.autoid, v.status, count(v.status) from edsp_drivers d left join edsp_violations v      on d.autoid = v.driverid      and (v.status = 'yellow' or v.status='red') where d.employerid = '000000028'  group by d.autoid, v.status order by v.status asc, count(v.status) desc 	0
24362262	19100	mysql - postgres: wrapping multiple rows into one	select id ,sdate,subject,sum(exam1)exam1,sum(assgn1)assgn1,overallmark,result,   credits   from exam_results   group by studno,subject 	0.000881765036878683
24362609	30825	how to group by week?	select  datepart(wk, datecreated) ,       sum(userhits) from    userdata group by         datepart(wk, datecreated) 	0.00748243892638212
24362859	15004	check if a string contains a value from one table	select id, lib_type from (   select id, lib_type, 1 prio from mytable   where upper('foch highschool') like upper('%'||lib_type||'%')   union all    select id, lib_type, 2 prio from mytable   where id=3   order by prio ) z where rownum=1; 	0
24363214	11055	how to get matching and non matching rows from a sql join	select coalesce(d.eid,n.eid),         coalesce(d.pid,n.pid),         coalesce(d.day,n.day),         d.shift as dshift,         n.shift as nshift     from #day d         full join #night n on d.eid = n.eid and d.pid = n.pid and d.day = n.day 	0
24364318	5005	how to get maximum and average of a field from mysql table with some conditions	select score.id, score.student_id, score.course_id, score.score, round(avg(mscore.score),2) as avg_score, max(mscore.score) as max_score  from `scores` as `score`  left join `scores` as `mscore` on mscore.course_id = score.course_id  where score.student_id = 1 group by score.id 	0
24364811	16687	how to use select query with max date?	select ro.roomtitle,         ro.isreserved,         res.checkintime,         res.checkouttime from reservation res join rooms ro on ro.roomid = res.roomid join (     select roomid, max(entrydate) as maxdatetime     from reservation     group by roomid ) groupedtt on ro.roomid = groupedtt.roomid             and res.entrydate = groupedtt.maxdatetime 	0.138758810276382
24365010	3205	mysql expression to select everything from a database orde by date desc	select * from `user_job`  order by `year` desc,            case when `month` = 'january' then 1                 when `month` = 'february' then 2                when `month` = 'march' then 3                when `month` = 'april' then 4                when `month` = 'may' then 5                when `month` = 'june' then 6                when `month` = 'july' then 7                when `month` = 'august' then 8                when `month` = 'september' then 9                when `month` = 'october' then 10                when `month` = 'november' then 11                when `month` = 'december' then 12           end desc,          `day` desc 	0.0315228244008556
24366271	15757	mssql calculate total by hour	select  [hour], isnull([critical],0) as critical, isnull([major],0) as major, isnull([minor],0) as minor, isnull([warning],0) as warning,   isnull([information],0) as information,  isnull([critical],0) + isnull([warning],0) + isnull([major],0) + isnull([minor],0) + isnull([information],0) as [total] from (select      datepart(hh, created) as 'hour',     datepart(hh, dateadd(hh,-datepart(hh, created),getdate())) as sorthour,     [severity],       count([id]) as incidents   from [alarm_transaction_summary]   where created >= getdate()-1    group by datepart(hh, created), severity   union all    select numbervalue,datepart(hh, dateadd(hh,-numbervalue,getdate())), null, null    from numbertable   ) ps pivot ( sum (incidents) for severity in ( [critical], [information], major, minor, warning) ) as pvt order by sorthour 	0.000252780940784282
24366755	9359	splitting columns with iseries sql	select ref                                                           , substr(ref                                                            ,1                                                               ,locate(' ',ref,1)              ) as ref1                                 , substr(ref                                                             ,locate(' ',ref,1) + 1                                          ,locate(' ',ref, locate(' ',ref,1) + 1)                         - locate(' ',ref,1)                                           ) as ref2                                                       , substr(ref                                                            , locate(' ',ref, locate(' ',ref,1) + 1) + 1                   ) as ref3                                                  from mytable 	0.186350022279172
24368191	35814	sql, select where not equal	select std_id, std_name from student  where std_id not in (select b_std_id from studentbatch ) 	0.499416345583348
24371975	24139	converting an irregular varchar to datetime in sql server	select cast(stuff('13mar99 2032', len('13mar99 2032') - 1, 0, ':') as datetime) 	0.696206992949754
24373516	12439	ms access combining rows	select    nz(tun.user_full_name, ad.user_full_name) as user_full_name_agg,           sum(ad.processed_mss) from      all_data ad left join tps_user_names tun           on ad.user_full_name = tun.duplicate_user_full_name group by  nz(tun.user_full_name, ad.user_full_name); 	0.140658774039642
24373525	41044	double query a table from two fields (inner join?)	select alumnos.alumnosid, invest.investigadoresid, asignaciones.alumnosid as alumnosid1, asignaciones.investigadoresid as investigadoresid1, instituciones.institucion instituciones1.institucion from alumnos inner join asignaciones on alumnos.alumnosid = asignaciones.alumnosid inner join invest on asignaciones.investigadoresid = invest.investigadoresid inner join instituciones instituciones on alumnos.institucionesid = instituciones.institucionesid  inner join instituciones instituciones1 on  invest.institucionesid = instituciones1.institucionesid 	0.042853221024874
24374196	31861	replace statement	select ccc.*, replace(     replace(         replace(             replace(                 replace(bbb.text,                 '[change]', convert(varchar, cast(coalesce(ccc.change, 0) as decimal(10, 2)))),             '[currentamount]', '$' + convert(varchar, cast(coalesce(ccc.currentamount, 0) as money), 1)),         '[increase]', convert(varchar, cast(coalesce(ccc.increase, 0) as decimal(10, 2))) + '%'),     '[amountincrease]', convert(varchar, cast(coalesce(ccc.amountincrease, 0) as decimal(10, 2))) + '%'), '[amountdecrease]', convert(varchar, cast(coalesce(ccc.amountdecrease, 0) as decimal(10, 2))) + '%') as condition from ccccheck ccc with (nolock) 	0.729928233228357
24374925	8879	where clause with multiple condition on same table	select counts.name,         group_concat(matchcount.name) simliarname  from   (select name,                 count(technology) techcount          from   table1          group  by name) counts         left join (select t1.name              t1_name,                           t2.name,                           count(t2.technology) matchingtech                    from   table1 t1                           join table1 t2                             on t1.technology = t2.technology                                and t1.name != t2.name                    group  by t1.name,                              t2.name) matchcount                on counts.name = matchcount.t1_name                   and counts.techcount <= matchcount.matchingtech  group  by counts.name 	0.0663216848637265
24375572	22795	select multiple values from a single column in wordpress database	select id, post_title, post_content, max( if ( wp_postmeta.meta_key = "thumnail", wp_postmeta.meta_value, '' ) ) as thumbnail, max( if ( wp_postmeta.meta_key = "video", wp_postmeta.meta_value, '' ) ) as video from wp_posts inner join wp_postmeta on wp_posts.id=wp_postmeta.post_id where wp_postmeta.meta_key in ( "thumnail", "video" ) group by id select id, post_title, post_content, max( case when wp_postmeta.meta_key = "thumnail" then wp_postmeta.meta_value else '' end ) as thumbnail, max( case when wp_postmeta.meta_key = "video" then wp_postmeta.meta_value else '' end ) as video from wp_posts inner join wp_postmeta on wp_posts.id=wp_postmeta.post_id where wp_postmeta.meta_key in( "thumnail", "video" ) group by id 	0.000113613318076677
24377939	29960	counting most common word in sql table with exclusions	select aword, count(*) as wordoccurancecount from (select substring_index(substring_index(concat(text, ' '), ' ', acnt), ' ', -1) as aword from table cross join ( select a.i+b.i*10+c.i*100 + 1 as acnt from integers a, integers b, integers c) sub1 where (length(body) + 1 - length(replace(text, ' ', ''))) >= acnt) sub2 where sub2.aword != '' and       length(sub2.aword) >= 5 group by aword order by wordoccurancecount desc limit 10 	0.00117143935409485
24379835	4171	sql server group by week, get first day of week	select o.customer_name,  dateadd(week, datediff(week, 0, o.delivery_date), 0) as first_day_of_week, item_code,  (select i.[desc] from items i where i.item = oi.item_code) as description, unit, (sum(oi.price) / sum(oi.qty) ) as unit_price,  sum(oi.qty) as total_qty,  sum(oi.price) as total_charged  from order_items oi inner join orders o on localid = local_order_id where o.[status] = 'submitted' and qty > 0 group by dateadd(week, datediff(week, 0, o.delivery_date), 0), customer_name, item_code, unit order by customer_name, first_day_of_week, item_code 	0
24379867	25991	how to join where there is a possibility of no record	select mv.clientid,        mv.fundid,        max(case when date = '1 may 2010' then value else 0 end) as startvalue,        max(case when date = '1 may 2011' then value else 0 end) as endtvalue from mv group by clientid,fundid 	0.024337040079131
24379955	21796	select 'exist' or 'notexist' as a column	select sku,     case when p.sku is null then 'notexists' else 'exists' end [exists?] from (values    ('sku1'),    ('sku2'),    ('sku3'),    ('sku4'),    ......    ......    ......    ('skun') ) sku(sku) left outer join products p on p.sku = sku.sku 	0.136291601914204
24380462	103	mysql - many to many relationship - tables	select * from answeritems t1 inner join (     select answerid     from answeritems     where itemid in (1, 2)     group by answerid     having count(distinct itemid) = 2 ) t2 on t1.answerid = t2.answerid group by t1.answerid having count(*) = 2; 	0.0423054983565862
24380544	21679	select a non id column in a foreign key table (table b) based on the foreign key in the primary table (table	select      s.name,      s.surname,      s.address,      r1.rulename as rule1name,      r2.rulename as rule2name,      r3.rulename as rule3name,      r4.rulename as rule4name,      r5.rulename as rule5name from student s      inner join rules r1 on s.rule1 = r1.id     inner join rules r2 on s.rule2 = r2.id     inner join rules r3 on s.rule3 = r3.id     inner join rules r4 on s.rule4 = r4.id     inner join rules r5 on s.rule5 = r5.id 	0
24382308	24720	addition from mysql query	select sum(columnname) as totalscore from tablename where id = 34; 	0.211828652279333
24382537	39084	count(*) againt top 1 in sql server	select top(1)        from yourtable with (nolock)     where ..... (your conditions here) 	0.0987960790599338
24383043	25676	sql subquery, invalid column name	select alarms.* from dbo.vehicles join          dbo.movements on dbo.vehicles.id=dbo.movements.vehicleid join         dbo.alarms on dbo.movements.id=dbo.alarms.movementid where vehicleid =1 	0.733483323567035
24383199	20719	excluding null results and counting number of rows based on several elements	select sum(themecount) from (select template.templateid, count(distinct case when object.theme is not null then object.theme end) themecount from  object object where count(distinct object.isactive)>1 group by object.template_id) 	0
24384207	25597	mysql count,group_concat and group by together	select  count(*) as `count`, host, group_concat(distinct botname) as botname, label as type from name group by host, type 	0.608319457797582
24384486	22716	union two selects removing duplicates base on some columns (not the full row)	select * from table1 union select * from table2 where not exists(select 1 from table1                   where table2.parent = table1.parent                   and table2.type = table1.type) 	0.000447587910205776
24384918	6745	changing single column data with multiple rows to multiple column data with single row	select [1], [2], [3], [4], [5] from (select top 5 trans_data_np, row_number() over (order by day_in_id) as rownumber       from day_in_status_mcg     order by day_in_id     ) as sourcetable pivot ( min(trans_data_np) for rownumber in ([1], [2], [3], [4], [5]) ) as pivottable; 	0
24385506	22970	count associate rows in multiple tables with left join	select `waller_posts`.*,        count(distinct waller_comments.id) as num_comments,        count(distinct waller_likes.id) as num_likes from `waller_posts` left join `waller_comments` on `waller_comments`.`post_id` = `waller_posts`.`id` left join `waller_likes` on `waller_likes`.`post_id` = `waller_posts`.`id` where `wall_id` = 1   and `wall_type` = "user" group by `waller_posts`.`id` 	0.171665142361287
24386160	35084	how to get rid of null values in pivoted table?	select date,        max(rs1),        max(rs2),        max(rs3) from table1 group by date 	0.00161205046228595
24386250	9938	how to find the sequence used for auto_increment?	select table_name,column_name, column_default_val from iicolumns  where column_always_ident    = 'y'    or column_bydefault_ident = 'y' order by 1,2 	0.0317312970350976
24386700	14162	get all columns after finding sum of sal from a table	select employee_id,e_name,sal, sum(sal) over()   from your_table 	0
24386895	3683	sql joining tables (a,b) - but only rows from a	select o.customer_email,       a.prefix  from sales_flat_order o   left join (select  distinct a.prefix, a.parentid              from sales_flat_order_address) a  on o.entity_id = a.parent_id 	0.00024741845098493
24386999	1407	database: importing data from other tables to another tables	select groupofficecom.cal_events.id,     source.c221codeclient,     '' as col_5,     '0' as col_6,     source.c218nom,     source.c219prnom,     source.typeactions,     source.id_element from source inner join groupofficecom.cal_events     on groupofficecom.cal_events.calendar_id = 5     and groupofficecom.cal_events.user_id = 3     and groupofficecom.cal_events.start_time = unix_timestamp(source.datedebut)     and groupofficecom.cal_events.end_time = unix_timestamp(source.datefin)     ... left join cf_cal_events     on groupofficecom.cf_cal_events.model_id = groupofficecom.cal_events.id where groupofficecom.cf_cal_events.model_id is null 	0
24387620	27592	mysql join unrelated tables	select  w.id, w.name,         (         select  group_concat(name order by name separator ',')         from    letters         where   lang = 'en'         ) from    words 	0.0731349904219373
24389465	8700	sql query which puts columns from rows into one row	select c.cust_name,        max(case when seqnum = 1 then ref_date end) as ref_date1,        max(case when seqnum = 1 then ref_amount end) as ref_amount1,        max(case when seqnum = 2 then ref_date end) as ref_date2,        max(case when seqnum = 2 then ref_amount end) as ref_amount2 from customer c join      (select r.*,              row_number() over (partition by cust_id order by ref_date desc) as seqnum        from refund r      ) r      on c.cust_id = r.cust_id where seqnum <= 2 group by c.cust_name; 	0
24391414	20550	count the number of rows that have a specific piece of data?	select     min(id),     user,     count(user) as count from     `table` group by     user 	0
24391850	8103	mysql multiple row compare	select      d_id  from table where d_id in(     select          d_id      from table      where tech_id=3 ) and tech_id=1 or tech_id=2 	0.00457406814474116
24393536	5267	get average of fields	select (     isnull(tbl1.bromod,0) + isnull(tbl1.bromoform,0) +  isnull(tbl1.chlor,0)  + isnull(tbl1.dibromoc,0) ) / isnull(     nullif(         convert(int,convert(bit,isnull(tbl1.bromod,0))) + convert(int,convert(bit,isnull(tbl1.bromoform,0))) +  convert(int,convert(bit,isnull(tbl1.chlor,0)))  + convert(int,convert(bit,isnull(tbl1.dibromoc,0)))         ,0     )         ,1     ) from tbltruck tbl1 	0.000199576907468914
24393544	13562	creating one table from select query in sql	select       books.idbooks,   books.title,   books.author,   count(books.idbooks) as numberoforderedbooks into new_table from books right join orders   on (books.idbooks = orders.idbooks) group by     books.idseminar,     books.naziv 	0.0112919511695546
24394701	16180	set output parameter to equal result of select statement	select @recordsaffected = t1.testid from tblwosampletest t1      join tbltest t2 on t1.testid=t2.testid;  where @woid = t1.woid and @sampleid = t1.sampleid and @analyte = t2.analyte 	0.11778912203437
24394849	34250	sql case statement data organization into one query	select t.range as [date range],count(*) as [accidents],      [lost time]=sum(oshaflag) from (     select         oshaflag=case when accidents.oshaclassificationid in(2,4) then 1 else 0 end,        case         when (month(accidentdatetime) >= 6 and year(accidentdatetime) = 2013) and (month(accidentdatetime) <= 12 and year(accidentdatetime) = 2013) then 'other'         when month(accidentdatetime) = 1 and year(accidentdatetime) = 2014 then 'january'         when month(accidentdatetime) = 2 and year(accidentdatetime) = 2014 then 'feburary'         when month(accidentdatetime) = 3 and year(accidentdatetime) = 2014 then 'march'         when month(accidentdatetime) = 4 and year(accidentdatetime) = 2014 then 'april'         when month(accidentdatetime) = 5 and year(accidentdatetime) = 2014 then 'may'         end as range     from accidents     where accidentdatetime between '06/30/2013' and '05/31/2014'     ) t group by t.range 	0.275378885447611
24395121	40302	select grouped table from 3 tables	select e.id, e.url, c.categoryname, a.keywords, count=sum(a.count) from excel e, categories c, analys_results a where e.id = a.websiteid and a.categoryid = c.id group by e.id, e.url, c.categoryname, a.keywords order by e.id, e.url, c.categoryname, a.keywords 	0.000284230931994728
24395143	11300	split columns in mysql	select a.article_id, a.v_article_code mku, b.v_article_code mpn,    ifnull(a.brand_domain_id, b.brand_domain_id) brand_domain_id,   ifnull(c.channel_sku, d.channel_sku) channel_sku from vendor_article a join vendor_article b on a.article_id = b.article_id    and a.brand_domain_id is not null and b.prefered_v_article_id is not null left join vendor_article_channel c on a.v_article_id = c.vendor_article_id left join vendor_article_channel d on b.v_article_id = d.vendor_article_id; 	0.00946330286053214
24395260	24710	generate average growth data for the missing dates	select     dateadd(day,[n],[date]) [date],     [weight] + isnull([n]*([next_weight]-[weight])/[count],0) [weight]   from [dbo].[weight] t1   outer apply (     select top 1       datediff(day,t1.[date],[date]) [count],       [weight] [next_weight]     from [dbo].[weight]     where [date] > t1.[date]     order by [date]   ) t2   cross apply (     select top(isnull([count],1))        row_number() over(order by (select 1))-1 [n]     from master.dbo.spt_values   ) t3 	0.000100749018880136
24395989	21543	identify duplicate values when using join in microsoft access	select o.name, p.reference from t_cust o     inner join t_custprop p on o.customerid = p.customerid where p.reference in (     select p2.reference     from t_custprop p2     group by p2.reference     having count(p2.customerid) > 1     ) order by o.name asc 	0.465745922600194
24396466	7486	information_schema.tables like 'value'	select table_name from information_schema.tables where table_name like '%__quote' 	0.396790226208153
24396694	18731	sql left join 2 tables where condition	select lookupcode from allclients where lookupcode not in      (select lookupcode      from allpolicies     where effectivedate < '2014-06-24' and expirationdate > '2014-06-24') 	0.592383686440036
24397139	34560	getting a results rank in tsql	select a.[id],     a.[petname],     a.[petcaption],     b.[pettype],     c.[firstname] as ownerfirstname,     c.[lastname] as ownerlastname,     d.[imagename],     rank() over (order by sum(f.totalraised) desc) as rank from petcontestsubmissions as a join petcontesttypes as b on a.[pettype] = b.[id] join emptable as c on a.[empid] = c.empid join petcontestimages as d on a.[image] = d.[submissionid] join petcontesttransactions as e on e.[submissionid] = a.[id] outer apply (     select sum(transactionamount) as totalraised,     from petcontesttransactions pt     where pt.submissionid = a.[id] and pt.paymenttype = 'donation' ) f where e.[transactionstatus] = 'completed' and e.[paymenttype] = 'submission'  for    xml path ('submission'), type, elements, root ('root'); 	0.131122436460216
24397569	15779	extract values from records with max/min values	select tmin.name, tmin.valuea, tmax.valuea,      tmin.valueb1, tmin.valueb2, tmax.valueb1, tmax.valueb2 from (   select name, max(valuea) as valueamax, min(valuea) as valueamin   from `foo`   group by name ) as t join `foo` as tmin on t.name = tmin.name and t.valueamin = tmin.valuea join `foo` as tmax on t.name = tmax.name and t.valueamax = tmax.valuea; 	0.000112990036509019
24398372	18922	select top 2 with distinct name sql server	select top 2 clientes.nome, clientes.ncartao, sum(vendas.valorciva) valorciva  from clientes as cli, vendas inner join clientes on clientes.idcliente = vendas.idcliente  group by clientes.nome, clientes.ncartao order by sum(vendas.valorciva) desc 	0.00853310232059716
24399116	13218	get best offers from the database query	select p.id, p.descricao, p_s.preco as antigo, pr.preco as novo from produtos_supermercados p_s join      produtos p      on(p_s.id_produto = p.id) join      promocoes pr      on(pr.id_produto = p.id) order by pr.preco / p_s.preco desc; 	0.00155748313827741
24399456	24188	counting the number of transactions by left joining a category table	select   category.id,   count(trxn.cat_id) from   category left join   trxn   on category.id = (rtrim(trxn.cat_id)+ltrim(trxn.stv))   and trxn.status='ok' where category.status='a' group by category.id 	0.000103967528529252
24400289	13371	retrieve parent child records in one query	select * from (     select parent_id      from album     where album_id = 35 ) as t1 inner join album t2   on t1.parent_id = t2.parent_id or t1.albumn_id = t1.parent_id; 	0
24403772	5780	sql create a table	select cst_id,    sum(case when type='sh' then 1 else 0 end) as sh,         sum(case when type='ka' then 1 else 0 end) as ka,    sum(case when type='ef' then 1 else 0 end) as ef,    sum(case when type='sc' then 1 else 0 end) as sc,    sum(case when type='ka' then 1 else 0 end) as ka,    sum(case when type='no' then 1 else 0 end) as no,    sum(case when type='we' then 1 else 0 end) as we,    sum(case when type='th' then 1 else 0 end) as th,    sum(case when type='bv' then 1 else 0 end) as bv from (   select cst_id,trc_type as type from t    union all   select cst_id,coll_type as type from t ) t1 group by cst_id 	0.0818864951644817
24406812	16256	how to get posts from posts table with both known and unknown authors	select `posts`.id, `posts`.title, `posts`.label, posts.id as author,    users.name as name, users.surname as surname     from `posts`        left join users           on users.id = posts.author              order by `date` desc; 	0
24408905	27158	substring_index using in mysql	select  `source`,         substring_index(`source`, ',', 1) as firstfield,           substring(`source`, locate(',', `source`) + 1) as restoffield  from `data_table` 	0.791581509448728
24408976	29658	sql - get list of different values from column	select distinct type from food 	0
24409589	6949	how to retrieve the latest data on duplicates in this database?	select customer.customer_id, customer.account_id, contact.account_id, contact.time_stamp from customer inner join contact on customer.account_id = contact.account_id where contact.time_stamp = (select max(c.time_stamp) from contact c where c.account_id = contact.account_id); 	0.000104405790988646
24409850	3981	how can i use a subquery on my query results and then order by a calculated result for each row?	select `country`,      `county`,     sum(`donation`) as `totaldonations`,     format(avg(`donation`), 0) as `avgdonations`,     count(1) attending     from `guestlist`      where `party` = `2014charityball`            and attending = `yes`     group by `country`, `county`     order by 4 desc 	0.00130671334901549
24410434	16169	adding custom row number	select @row_num:=@row_num+1 as row_num, t.* from table_1 as t, (select @row_num:=0) as init 	0.0104511890730114
24411116	9903	how to union two tables with different col number ? mysql	select firstname , secondname , lastname   from    (select firstname,secondname,lastname from table1     union     select firstname, null as secondname, null as lastname from table2    ) resutls 	0.000382956894862483
24411248	37399	better to query once, then organize objects based on returned column value, or query twice with different conditions?	select * from my_table order by type 	0
24411322	10391	averaging count for unique dates separately	select count(*)/count(distinct person)  from table1 group by date order by date asc; 	0.00415147046347682
24411771	28022	mysql timediff(date, datetime)	select timediff(cast(<yourdatecolumn> as datetime), <yourdatetimecolumn>) 	0.31689638686081
24413216	33382	mysql listing in a one table, the order in the another table	select users.id as user_id,        users.name as user_name,        users.lastname as user_lastname,        count(*) as tot   from users   left join pages     on pages.user_id = users.id  group by user_id, user_name, user_lastname  order by tot desc, user_lastname, user_name 	4.87429860641995e-05
24413357	12068	how to use select * with union ? mysql	select col1 , col2 , talias.* from (select table2.col1 as col1 , table2.col2 as col2 , table1.* from table1 inner join table2 ... union select table3.col1 as col1 , table2.col2 as col2 , table1.* from table1 inner join table2 ... ) as talias order by talias.col1 	0.600961121891388
24413903	2731	select different results from same table	select  id_user,         sum(iscorrect),         sum(not iscorrect) from    mytable group by         id_user 	9.82279700976815e-05
24415911	12192	how do i set a variable to the value of only one block in sql server	select @state = state from projectlist where project = @project if @state = 'active'  update ...... else delete ..... 	9.16685814288823e-05
24417663	11390	add count/instance no. column to table (sql developer)	select c.*,        row_number() over (partition by car_id order by leave_time) as stop_sequence from cars c; 	0.0191962237734519
24420809	16513	postgres start table id from 1000	select setval('people_id_seq', 999); 	0.000264603879612328
24422114	2942	how to return unknown value using known value from same column in sql	select name.sentvalue as name  from tbl_submission email left join tbl_submission name    on email.formsubsid = name.formsubsid and name.formfield = 'name' where email.formfield = 'email' and email.sentvalue = 'mi@hom.us' 	0
24422924	34147	removing title from select query in php	select realpow, timestamp from powerdata;     while($res = $results->fetcharray(sqlite3_assoc)){         $equal[] = array($res['realpow'], $res['timestamp']);     }     echo json_encode($mearray,json_numeric_check); 	0.0204888800732742
24423328	26596	sql order by but also by min of different col (aka threading)?	select     table.type,     table.value from (     select          type,         min(value) as minvalue     from table     group by type ) as sub inner join table     on table.type = sub.type order by sub.minvalue asc, table.type asc, table.value asc 	0.0011544690071956
24423528	33489	changing a row into a column in mysql	select 'amount1' as amount_type, `amount1` as amount_value from your_query_results union all select 'amount2', `amount2` from your_query_results union all select 'amount3', `amount3` from your_query_results 	0.000696801113655764
24424163	26925	get most recent date from two tables	select  t1.id, t1.serials,         case when t1.date > t2.date then t1.date else t2.date end recentdate,         t1.include, t2.id, t2.serials, t2.rma from    table1 t1 join    table2 t2 on      t2.serials = t1.serials 	0
24424971	4549	sql query to retrieve next available id from table	select concat('stk',                lpad(max(substring(ticket_id, 4)) + 1,                     10,                     '0')              )  from sma_support_tickets; 	0
24427170	17659	list all rows despite join	select t1.*, t2.id_stuff from table1 t1 left join table2 t2 on t2.id_tb1 = t1.id_tb1 and t2.id_stuff = 1 	0.00719208613059321
24428033	41266	subtract columns from two tables	select   `t1`.`code`,   (ifnull(sum(`t1`.`qty`),0) - ifnull(sum(`t2`.`qty`),0)) as totalqty from   `t1`   left join `t2` on `t1`.`code` =     `t2`.`code` group by   `t1`.`code` 	5.15581807511044e-05
24429109	19314	from which table the data has been retrieved	select 'table1' as which, username, password from table1 where username = :username union all select 'table2' as which, username, password from table2 where username = :username; 	5.72288777715609e-05
24429390	32261	mysql select all rows from table with distinct id using newest timestamp	select t1.* from table t1 left join table t2 on t2.id=t1.id and t2.timestamp > t1.timestamp where t2.id is null. 	0
24429515	15945	extracting information from table in sqlserver 2008	select skill_name, skill_level,   count(*) counts from yourtable group by skill_name, skill_level order by skill_name 	0.00232441114644706
24430447	29360	assign multiple variables at once as result from select statement	select @a =col1,@b=col2  from table1 where id=1234 	0.000357328162888367
24433547	27054	average date diff on mysql	select user_id, game_id,        (case when count(*) > 1              then timestampdiff(second, min(timestamp), max(timestamp)) / (count(*) - 1)         end) as avgdiffseconds from game_logs gl where game_event_type_id = 3 group by user_id, game_id; 	0.000810474025226989
24435880	258	python mysql syntax for limit as available no. of rows	select * from ques 	0.0382462364390673
24435902	5648	mysql unique values	select  substring_index(substring_index(t.keywords, ',', n.n), ',', -1) value , count(*) as counts     from table1 t cross join     (    select a.n + b.n * 10 + 1 n    from      (select 0 as n union all select 1 union all select 2 union all select 3 union all  select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) a    ,(select 0 as n union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union  all select 9) b    order by n  ) n  where n.n <= 1 + (length(t.keywords) - length(replace(t.keywords, ',', '')))  group by value 	0.0103615511870876
24436293	1366	how to add commans to a select of an decimal (18,2)?	select '$' + convert(varchar(max), cast(321321321.321231 as money), 1) 	0.00742199953232016
24437007	34313	i need to count those that are not selected	select employee.[site name],        sum(iif(employee.[status] = "completed", 1, 0)) as [number of completed] from employee group by employee.[site name]; 	0.00380778272433227
24437082	16752	sql: how do i limit only one date per row returned?	select      d.device_id,     d.display_name,      d.device_name,      d.ip_address,      date(reports.date_entered) as just_date_entered from iphone_details as d inner join reports as r     on r.report_id= d.report_id     and r.date_entered >= date('2014-01-01')      and r.date_entered < date('2015-01-01') group by     d.device_id,     d.ip_address,     just_date_entered 	0
24438110	25655	how can i get the max value of a column from a record or 0 if no record is matched in my select?	select @maxrelease = isnull(max(release), 0) from   dbo.test 	0
24439655	19557	mysql select based of results of another select	select p.product      , c2.product as category   from products p   join (         select c1.category as c1              , c1.parentcategory as c2              , c2.parentcategory as c3              , c3.parentcategory as c4           from categories c1      left join categories c2 on c1.parentcategory = c2.category      left join categories c3 on c2.parentcategory = c3.category         ) c on p.category = c.c1    join categories c2 on c2.category in (c.c1, c.c2, c.c3, c.c4)   order by p.product asc, c2.category desc; 	0
24441269	4352	mysql query between two ranges	select * from table where low <= $high and high >= $low 	0.00429887375679764
24442594	2033	how to avoid multiple results from sub query	select s.shopname  from shopstable s  join orderstable o on s.shopnum=o.shopnum  group by s.shopname  order by count(*) desc  limit 1 	0.286651683481146
24443515	26864	how to make sql query using group by data	select substring (name,1,5), count(*) from table_a group by substring (name,1,5) 	0.475818367901633
24443721	5018	using mysql associative table and join	select  c.id, c.name, a.street, a.city, a.zip, a.state from contacts_addresses ca join contacts c on c.id = ca.idcontact join addresses a on a.id = ca.idaddress where c.id = 3 	0.382154149300998
24444307	16812	add an interval to a date until is today sql server query	select *      from a     where datediff(dd,date,getdate())% 7 = 0 	0.00162316027133713
24444504	22753	count number of cases	select count(*), leavetype  from (   select leavetype   from leaves   group by employee_id, leavetype ) group by leavetype; 	0.0109049173934366
24444987	28926	sql join from multiple tables from a reference lookup into one view	select accountname, t.tfndesc, v.vdndesc, s.skilldesc  from tblaccount as acc  left outer join tbldbassign as dba1      on dba1.refobid = acc.id left outer join tbldbobject as dbo1      on dbo1.description= 'tfn'     and dba1.tgtobtype =  dbo1.typeid left outer join tfn as t     on t.tfnid = dba1.tgtobid left outer join tbldbassign as dba2      on dba2.refobid = acc.id left outer join tbldbobject as dbo2      on dbo2.description= 'vdn'     and dba2.tgtobtype =  dbo2.typeid left outer join vdn as v     on v.vdnid = dba2.tgtobid left outer join tbldbassign as dba3      on dba3.refobid = acc.id left outer join tbldbobject as dbo2      on dbo3.description= 'skill'     and dba3.tgtobtype =  dbo3.typeid left outer join skill as s     on s.skillid = dba3.tgtobid 	0.000153168874277061
24445058	24688	date extracted from datetime in sql server 2008	select * from [dbo].[production_schedule] where convert(date,date)= convert(date,@date) 	0.0392949860803388
24445547	31111	find last 5 columns of a table	select column_name from information_schema.columns where table_name='your_table' order by ordinal_position 	0
24446511	37426	how to nested sql queries?	select      a.id,              (select top 1                         content              from        b             where       b.id = a.id             ) as content  from        a 	0.727220067993344
24446850	5753	re use existing selected column in sql server?	select  column1 ,column2 ,column3 ,column4 ,(column5 + reusethiscolumn) as reusethiscolumn2 from (   select      column1    ,column2    ,column3    ,column4    ,column5    ,case[computation here] as reusethiscolumn   from table ) as subq 	0.257053575032274
24447636	5644	sql order string primary key	select max(cast(substring(code,9) as int)) from mytable where code like concat('mc-', year(now()), '%'); 	0.0408315663711021
24448698	31118	mysql call recent timestamp in php	select `newest`, `user_2`      from `your_table` order by `timestamp` desc    limit 1 	0.0195890742201076
24449269	4876	mysql constant number between and	select sa.*, st.starttime, st.endtime, st.locationid, st.id as timingid       from ccf_session_attendee sa  left join ccf_session_timing st        on st.id=sa.timingid      where '2014-11-02 07:00:00' between date_add(starttime, interval 1 minute)                                     and date_sub(endtime, interval 1 minute) 	0.00747457903509365
24449461	3559	how to skip multiple rows for one id	select distinct session_user_id from phpbb_sessions where 	6.36209304431098e-05
24449918	37160	split row into multiple rows in stored procedure in sql server 2008	select 1 as hrs, 4 as end , name, 1 as class from thetable where class=3 union select 4  as hrs, 8 as end, name, 2 as class from thetable where class=3 	0.00338890314758042
24450505	8787	inner join within common table expression in postgresql	select  cola, colb, 0 from    (         select  cola, colb, count(*) over (partition by colb) cnt         from    (                 select  distinct cola, colb                 from    mytable                 ) q         ) q where   cnt > 1 	0.538929184961282
24451739	35505	column 'loginattempts' in field list is ambiguous - what's the difference i'm missing here?	select u.user_id, u.loginattempts, u.lastattempttime  from (     select 'john@blah.com' user  ) u  left join table2 a  on u.user = a.username left join  (     select attemptedusername, loginattempts, lastattempttime     from lockouttable      where accounttype = 'public'  ) l on u.user = l.attemptedusername 	0.562995877862177
24452157	18664	aggregating/grouping a set of rows/records in mysql	select min(datetime) as datetime,        min(val) as minval, max(val) as maxval, avg(val) as avgval,        substring_index(group_concat(val order by datetime desc), ',', 1) as lastval from table t group by floor(to_seconds(datetime) / (60*60)); 	0.0733889421116282
24452863	17455	get number of weeks that have passed from a certain date to today sql	select datediff(wk, '2012-08-20', '2014-06-27'); 	0
24454616	6636	multiple distinct counts with where	select count(distinct clientid) as numclients,        count(distinct case when result = 'approved' then clientid end) as numapproved,        count(distinct case when result = 'escalated' then clientid end) as numescalated,        count(distinct case when result = 'approved' and timestamp between @time1 and @time2                             then clientid end) as numapproved,        count(distinct case when result = 'escalated' and timestamp between @time1 and @time2                            then clientid end) as numescalated, from table t; 	0.118458382009479
24455195	8890	sql selecting from one table with multiple where clauses	select * from table t1 join table t2 on t1.title = t2.title where t1.codes = '020' and t2.codes = '021' 	0.00123948459796306
24455641	18595	how to add up column data values when using group by	select a.customernumber,        a.date,        a.salesdocnumber,        a.amount        b.ccf from tablea a inner join (select salesdocnumber, sum(ccf) as ccf from tableb group by salesdocnumber) b on a.salesdocnumber = b.salesdocnumber 	0.00477838556150553
24455714	22103	display the object with the most equal entries	select land, count(*) as anzahl      from yourtable      group by land      order by anzahl      desc limit 1;` 	0
24455749	20981	display all tables that have a foreign key equal to a value	select f.name as foreignkey,      object_name(f.parent_object_id) as tablename,      col_name(fc.parent_object_id, fc.parent_column_id) as columnname,      object_name (f.referenced_object_id) as referencetablename,      col_name(fc.referenced_object_id, fc.referenced_column_id) as referencecolumnname      from sys.foreign_keys as f inner join sys.foreign_key_columns as fc      on f.object_id = fc.constraint_object_id      where object_name(f.parent_object_id)= '**<table_name>**' 	0
24455902	10931	sql compare two unique rows from the same table	select t.* from teacher t where exists (select 1 from teacher t2 where t2.id = t.id2); 	0
24455967	12193	get a subset of rows grouping by one of them	select options, product_id, max(id) as id from (       <the query that returns the rows on this question>      ) prodvalues group by product_id, options; 	0
24458627	31724	sql selection based on two variables, exclusive of others	select * from your_table where group_id in (   select group_id   from your_table   group by group_id   having count(distinct service) = 1 ) 	0.000341249807705249
24460082	9322	get values and like values in sql	select accountnumber from (select a.*, count(*) over (partition by shortestan) as numan       from (select a.*,                    (select top 1 a2.accountnumber                     from accounts a2                     where a.accountnumber like a2.accountnumber + '%'                     order by length(a2.accountnumber) asc                    ) as shortestan             from accounts a            ) a      ) a where numan > 1 order by shortestan, accountnumber; 	0.00689676276776247
24460666	23855	how to outer join two tables?	select a.id, coalesce(a.price,0) as price, coalesce(b.minpay,0) as minipay from tbla a full outer join tblb b  on a.id=b.id 	0.274094905807578
24462139	19643	retrieve the last record when grouping mysql table	select a.id, a.conversation, b.sender_user_id, b.receiver_user_id, b.message from (   select max(id_message) id,          if(sender_user_id>receiver_user_id,             concat(receiver_user_id,',',sender_user_id),             concat(sender_user_id,',',receiver_user_id)) conversation   from t_message   group by conversation) a join t_message b on a.id = b.id_message; 	0
24465815	1416	getting current time in seconds/milliseconds with sparql?	select (now() - ?epoch as ?time ) where {   values ?epoch { "1970-01-01t00:00:00"^^xsd:datetime } } 	0.00315970246151193
24466459	28951	query order results according to search results	select * from people where title like '{param}%' or title like '%{param}%'   order by case when title like '{param}%' then 0                 when title like '%{param}%' then 1 end asc 	0.0852434177225697
24467515	6827	how to run these two rows on one query	select user_id,paidout,count(*),sum(amount) from trans group by user_id,paidout 	0.00167735350231924
24470123	28447	get last record per category filter by date	select a.id, a.buy, b.buy last_before_buy, a.item_id from (select * from prices where (created_at <= now() - interval 5 day) order by id desc) a join (select * from prices order by id desc) b on a.item_id = b.item_id and a.id > b.id group by a.item_id; 	0
24470224	29172	select averages in each group by group?	select type,        count(*) as num,        sum(case when sex = 'male' then 1 else 0 end) as males,        sum(case when sex = 'female' then 1 else 0 end) as females,        avg(cast(age as decimal(5, 2))) as avgage from (select employeeid,              max(case when col1 = 'type' then value end) as type,              max(case when col1 = 'sex' then value end) as sex,              max(case when col1 = 'age' then value end) as age       form employees e       group by employeeid      ) t group by type; 	0.000424136320599704
24470696	25643	join two mysql results by a common column	select country , sum(if(`time`<10,1,0)) as `x<10` , sum(if(`time`<9,1,0)) as `x<9` , sum(if(`time`<8,1,0)) as `x<8`  from `allsub10`  group by `country` 	0.00261117237215172
24471271	35771	fetch only one of each entry based on date	select id, name, number, lastdate from yourtable t1 inner join     (select number, max(lastdate) as maxdate from yourtable group by number) t2 on t1.number = t2.number and t1.lastdate = t2.maxdate 	0
24473306	12240	how to count number of files that the latest time was worked on was yesterday	select count(*) from (   select t1.cfid as cfid, max(t2.task_date) d   from task_list t2    inner join case_files t1 on t2.cfid=t1.cfid    inner join case_file_allocations t3 on t2.cfid=t3.cfid    where t2.worked<>'yes' and t2.acm=t3.acm and t2.acm='310' and t2.deleted<>1      and t1.closed<>'yes' and t1.deleted<>1 and t1.pool_id in(0,1)      and t3.reallocated<>'yes'   group by t1.cfid) a where d < now(); 	0
24474246	21891	mysql: get average of fields in case where value is not a certain value	select avg(case when a = 3 then 0 else a end +              case when b = 3 then 0 else b end +              case when c = 3 then 0 else c end +              case when d = 3 then 0 else d end +              case when e = 3 then 0 else e end)/          (case when a = 3  then 0 else 1 end +           case when b = 3  then 0 else 1 end +           case when c = 3  then 0 else 1 end +           case when d = 3  then 0 else 1 end +           case when e = 3  then 0 else 1 end) as av from table1   group by a,b,c,d,e 	0
24474307	26843	finding the largest group of consecutive numbers within a partition	select player_id, runs, count(*) as numruns from (select p.*,              (row_number() over (partition by player_id order by match_date) -               row_number() over (partition by player_id, runs order by match_date)              ) as grp       from players p      ) pg group by grp, player_id, runs order by numruns desc limit 1; 	4.62954437211363e-05
24474591	8781	count items for each category sql php	select category_id, count(*) as num_items, group_concat(item_id) as items from yourtable group by category_id 	0
24474680	27497	mysql sum data in column "a" when data in column "b" matches	select `year`, `week`, sum(`points`) as total_points from mytable group by `year`, `week` order by sum(`points`) desc limit 3 	0.000241831126748783
24476239	4630	sql group by multiple fields	select * from (yourquery) group by producer 	0.113237360485453
24477956	38436	sql - count occurrences across multiple columns	select * from  (select patient_id,hospital,diagnosis from (     select patient_id, hospital, left(diag_01,1) as diagnosis from table_name where diag_01 is not null union all        select patient_id, hospital, left(diag_02,1) as diagnosis from table_name where diag_02 is not null union all     select patient_id, hospital, left(diag_03,1) as diagnosis from table_name where diag_03 is not null union all     select patient_id, hospital, left(diag_04,1) as diagnosis from table_name where diag_04 is not null       ) as t1 group by patient_id,hospital,diagnosis ) as t2 where diagnosis in ('c','d') 	0.0006924607239007
24478716	8938	query to find districts with at least one value in assets table	select count(*) from district where exists (     select 1     from assets     where district_id = district.id ) 	4.82314486083638e-05
24481109	3550	specific merge 2 columns in sql excluding one of them	select if(user1 = 1, user2, user1) as user from table where user1 = 1 or user2 = 1 	0
24481124	5988	sql command to check domain emails	select substr(e.email, instr(email, '@') + 1) as domain, count(*) from emails e group by substr(e.email, instr(email, '@') + 1); 	0.0967798014916512
24481312	11909	mysql select count join is failing to return records that don't match	select      applications.*,      count(pricingplans.pricingplanid) as pricingplancount from      applications left join pricingplans on     pricingplans.applicationid = applications.applicationid group by     applications.applicationid 	0.00620983067853361
24482206	32984	compare values from 2 while loops (php mysql)	select     count(case when t1.points > t2.points then 1 end) dustin_win_count,     count(case when t2.points > t1.points then 1 end) lee_win_count,     count(case when t2.points = t1.points then 1 end) tie_count from     (select week, sum(points) points     from schedule where     owner = 'dustin'     and opponent = 'lee'     group by week) t1     join (select week, sum(points) points     from schedule where     owner = 'lee'     and opponent = 'dustin'     group by week) t2 on t1.week = t2.week 	0.000956719733726336
24482726	8853	sql combine 2 rows into 2 columns	select entity,        max(case when type=auto then value else null end) as valueauto,        max(case when type=manual then value else null end) as valuemaual from tablename group by entity 	0
24483162	3009	how to determine (qty) monthly new customer?	select newclientid, min(monthsales) as 'monthsales' from #tmp2 group by newclientid order by monthsales 	0.000130627219120454
24483189	32695	mysql get spacific table fields counts	select a.idea_id, a.property_id, a.the_idea, a.user_id, a.added_date, a.status,         sum(b.thumbs = 1) as up, sum(b.thumbs = 0) as down from idea_box a  left join idea_box_voting b on a.idea_id = b.idea_id  group by a.idea_id; 	0.00249409271561321
24484089	11251	mysql join 2 tables with different columns	select contacts.id as 'contacts_id',        concat(users.first_name,' ' ,users.last_name) as assigned_to0 from contacts inner join users on contacts.assigned_user_id=users.id where contacts.date_entered < date_add(now(), interval + 15 day)   and contacts.deleted = 0   and users.id='seed_sally_id'; 	0.00207443135819187
24485584	1176	get multiple value in single row using join	select a.id,a.name,a.status,b.address1,b.state,c.phone, group_concat(d.category_id, d.coverage_id)  from members a left join address b on a.id = b.ref_id  left join contacts c on a.id = c.ref_id and left join mem_cc d on a.id = d.ref_id group by a.id 	0.000349398922062629
24486941	9682	mysql- one table two query in one statement	select card_id from (     select card_id, month(days) as card_month, sum(ytl) as card_sum     from expenses     where days between "2014-05-01" and "2015-06-30"     group by card_id, card_month     having card_sum >= 40 ) sub0 group by card_id  having count(*) = 2 	0.00274147150887404
24487016	21765	getting system tables and views thru sqlconnection	select        object_schema_name(object_id) as schemaname     , name as objectname     , type_desc as objecttype from sys.system_objects where     type_desc in('user_table', 'system_table', 'view') union all select        object_schema_name(object_id) as schemaname     , name as objectname     , type_desc as objecttype from sys.objects where     type_desc in('user_table', 'system_table', 'view'); 	0.177342411991698
24488981	6227	mysql inner join but with multiple columns	select *  from people p inner join job j on p.job_id = j.id and p.job_desc = j.description  order by j.id asc 	0.342611329847325
24490262	39092	mysql - query to select all conversations with al least 2 not banned users	select c.*  from conversations c  inner join (select p.conversation_id              from participants p              inner join users u on p.user_id = u.user_id and u.banned = 0             group by p.conversation_id              having count(distinct p.user_id) >= 2            ) as a on c.conversation_id = a.conversation_id 	0.00272029972323372
24490279	35422	while return rows with a specific value first getting syntax error	select idname  from type_ofid_tbl  where deleted=0 order by case when idname ='emirates id' then 1 else 2 end 	0.00443154791067443
24490446	31054	in a select query, getting the count of something from another table	select m.id, m.username, count(p.id) from members m  left join posts p on m.id = p.memberid group by m.id; 	7.07908400254773e-05
24490986	11539	sql query for selecting records in between date range	select * from events where event_category=@categoryid and (event_startdate between @startdate and @enddate) and (event_enddate between @startdate and @enddate) 	7.22161763289747e-05
24492943	8300	detect gaps in integer sequence	select  case when ((max(x)-min(x)+1 = count(distinct x)) or             (count(distinct x) = 0)  )            then 'true'            else 'false' end    from foo 	0.0681562619996866
24492979	28513	sql: joining on max value	select a.id,a.value,a.year,max(b.value) from tablea a join tableb b on a.year = b.year and b.value < a.value group by a.id,a.value,a.year 	0.0113165938413747
24493401	31744	select users who do not answer a survey yet	select * from user where id not in (select user_id from questionnaire_self) 	0.025016686421268
24493515	14016	mysql cuts off string from subquery which uses udf	select * from (     select          cast(collect('cases:10,drop:10', shipment_bucket_code, weight) as char(255))     from d_shipments ) as sub; 	0.670574356961355
24494028	26132	how to search in sqlite if exist all letter of alphabet	select letter from (select 'a' as letter       union all       select 'b'       union all       ...       union all       select 'z') where letter not in (select letter                      from mytable) 	0.00057704736530948
24494182	16171	how to read the last record in sqlite table?	select * from mytable where rowid in ( select max( rowid ) from mytable ); 	0.000117423097432564
24495754	26128	mysql count for every month	select coalesce(sum(`level` = 1),0) level1count  coalesce(sum(`level` = 2),0) level2count ,y,m from (select 1 as m,2014 as y union . . . union select 12 as m ,2014 as y ) months left join t on(months.m = month(t.time) and months.y = year(t.time)) group by months.m, year(t.time) 	0.000972498428200365
24495864	10026	mysql: group surrounding records by same field value	select      type  from(     select          type,         if(@a = type, @b, @b := @b + 1) as grouping_col,         @a := type     from testing     join (select @a := 1, @b := 0) as temp ) as t group by grouping_col; 	0.000115773496692264
24499765	18574	mysql: condition on result of group_concat?	select distinct a.name from articles a join      article_tag_assocs ata      on a.id = ata.article_id join      tags t      on t.id = ata.tag_id where t.tag = 'some-tag'; 	0.174955088369271
24500339	9989	sql | aggregation	select w.ward_no,        year(pn.start_date) as year,        sum(pn.quantity * d.price) as cost   from ward w   inner join patient pt     on pt.ward_no = w.ward_no   inner join prescription pn     on pn.patient_id = pt.patient_id   inner join drug d     on d.drug_code = pn.drug_code   group by w.ward_no,             year(pn.start_date)   having sum(pn.quantity * d.price) > 25   order by w.ward_no, year 	0.565723242638305
24501558	33903	how to get the running total pay and running balance in mysql?	select id, token tk, actual_pay pay,   if(@rtp is null, @rtp:=token, @rtp:=@bal+actual_pay) rtp,   if(@bal is null, @bal:=actual_pay-token, @bal:=@rtp-token) bal from records a join (select @rtp:=null, @bal:=null) b ; 	0.0019111882017758
24502806	2343	mysql and php to display following data	select birth_state, count(*) as total_count from user_data group by birth_state; output: birth_state | total_count xyz         | 2 abc         | 3 	0.0120619664781327
24502920	29395	mssql finding the maximum value of an avg value list	select distinct cityname,name, avgprice from   v_avrage_price where avgprice=(select max(avgprice) from v_avrage_price) 	0
24503334	30881	query items based on size	select m.*,box_id,box_name from  ( select max(b.height) box_height ,max(b.width)  box_width,m.height ,m.width   from item m join box b on m.height>=b.height and m.width>=b.width  group by m.height,m.width ) t join item m on  m.height = t.height and m.width  = t.width join box b on   b.height = t.box_height and b.width  = t.box_width 	0.000880873325916735
24503589	25902	how to sort based on keyword first?	select * from mytable order by case when country = @country then 0 else 1 end, first_name 	0.000361589264831885
24504802	369	select value from a second level foreign key table	select p.name, a.addressname, c.countryname from person p  inner join adress a on p.adress = a.id  left outer join country c on a.linktocountry = c.id 	0
24504919	22456	mysql query with date comparison	select a.invoiceno,        a.invoicerefno,        a.invoicedate,        c.companyname,        a.grandtotal,        a.twempname,        itemdescription,        quantity from twsql_twalldata.t_invoicedet a inner join twsql_twalldata.t_salesinv_items b on a.invoiceno=b.invoiceno inner join twsql_twalldata.t_customerdet c on a.customercode=c.customercode where a.twempname not like '%auto%' and        (itemdescription like '%amc%' or itemdescription like '%annual maintenance contract%') and         invoicecancelled=0 and date(a.invoicedate) > date('2012-04-01'); 	0.518635072319816
24505238	24953	join two tables and retrieve relevant data and calculate the result	select     table_2.id_pro,             product_name,             sum(1) as quantity,             priceprod,             sum(1) * priceprod as 'quantity * priceprod' from       table_2 inner join table_1 t1 on table_2.id_pro = t1.id_pro group by   table_2.id_pro, product_name, priceprod 	0
24506375	36077	optimizing a query, duplicate rows that have oldest date	select       pushid     , id     , created from (       select                @row_num :=if(@prev_value = d.pushid,@row_num+1,1)as rn              , d.pushid              , d.id              , d.created              , @prev_value := d.pushid       from tbldevices d       cross join(select @row_num :=1, @prev_value :='') vars       order by                d.pushid              , d.created desc       ) sq where rn > 2 ; 	0.000571567819283626
24507350	40539	mysql query lowest value within range not in table	select ifnull(min(t1.n) + 1, 10)   from (select n           from t          where n > 10   # lower bound, exclusive            and n < 199  # upper bound, inclusive      union all         select 10) t1   left join t t2     on t2.n = t1.n + 1  where t2.n is null; 	0.000924499112327937
24508372	25031	sql query for searching the dates	select  smemployee.badgenumber,smemployee.employeefullname,smdepartment.departmentname, subdate.adate from smemployee cross join (select '2014-07-01' as adate union select '2014-06-30') subdate left outer join smdepartment  on smdepartment.departmentid=smemployee.departmentid     left outer join empcheckinout on smemployee.employeeid = empcheckinout.userid  and convert(date,checktime) = subdate.adate where empcheckinout.userid is null 	0.0652225282560713
24509323	33949	sql query group by highest revision number	select a.id, a.columnid, a.revision from bug a  inner join (select columnid  max(revision) as maxrevision  from bug group by columnid ) b on a.columnid = b.columnid and a.revision = b.maxrevision 	0.00185719935483521
24510649	12309	like operator with a variable number of search conditions, in tsql	select mt.*   from mytable mt   join @terms t     on mt.mycolumn like '%' + t.term + '%'  group by mt.mycolumn having count(*) = (select count(*) from @terms) 	0.708481578517347
24511065	40964	sql compare averages against specific rows in a table	select      cust_id,     gender,     weight from customer c where weight >  (select avg(weight)                    from customer                   where gender = c.gender) order by c.gender 	0
24511328	17565	sql plus oracle ascii() how to know ascii code of single quote	select ascii('''') from dual; 	0.653801331892775
24513180	18729	sql ce select convert	select convert(nvarchar(10), c.dob, 120) as formateddate from table 	0.587893319533806
24513822	15895	sql query syntax to retrieve data from 2 tables	select *  from  (     select distinct authors.id, authors.firstname, authors.lastname, authors.age     from authors      join articles      on authors.id = articles.authorid     order by authors.age      desc      limit 3 ) author_sub join articles  on author_sub.id = articles.authorid 	0.0041238798661684
24515139	6653	sql server 2008 time datatype is in decimal need in time	select cast(stuff(replace(str(730.000000,4,0), ' ', '0'), 3,0,':') as time) 	0.504225832933963
24516178	3528	mysql query and join tables	select * from conversation_message, conversation  where conversation.c_id = $id_of_conversation  and (user_one = $id_logged_user or user_two = $id_logged_user)  and conversation_message.c_id =  conversation.c_id 	0.449134740171918
24516451	18706	multiple records in a table matched with a column	select workerid  from tags where name in ('foo', 'bar') group by workerid having count(distinct name) = 2 	0.00032030903133805
24516599	26647	regexp in mysql	select  word from    wordlist where   word regexp 'e'         and word regexp 'a'         and word refexp 't' 	0.515551177170261
24516638	28144	how can i get certain rows and the "previous" rows from a table that includes a datetime column?	select a.id, a.bravo_id, a.created, b.id, b.created from alpha a left join alpha b on a.bravo_id = b.bravo_id                  and b.created < a.created                  and b.special is null where a.special is not null   and (b.created is null or        b.created = (select max(s.created)                     from alpha s                     where s.special is null                       and s.bravo_id = a.bravo_id                       and s.created < a.created)) 	0
24517546	19107	merging two sql tables	select e.*, s.[branch no], s.[barcodes], s.[unit cost]  from storesales s inner join esales e on  e.[inv date] = s.[date] and  e.[our ship qty] = s.[total qty sold] and  e.[unit price (rrp inc vat)] = s.[rrp] and  e.[line total] = s.[total value sold] 	0.00636961930139487
24519509	10161	mysql query with most recent results	select * from tblmatinvlist inner join        (select max(date) as date,               vendorptnum          from tblpurchasereq          group by tblpurchasereq.vendorptnum) prices on prices.vendorptnum = tblmatinvlist.vendorptnum; 	0.00675968161297947
24519670	14331	order database tables by creation time	select * from information_schema.columns order by create_time, column, table; 	0.0308101293998403
24521560	16375	sql server order by	select id, value from table1 order by case when value = @value then 0 else id end asc 	0.56066470596999
24522168	29422	mysql multiple char_length()	select match, profile  from matches  where char_length(match) + char_length(profile) > 300; 	0.568193550340203
24526124	6606	select id from subquery with limit 1000 rows in mysql	select *    from table1 x   join       ( select id from table2 order by id limit 50 ) y     on y.id = x.id; 	0.00179623395736987
24526386	38953	mysql date difference between two rows	select user_id,        datediff(max(case when action="close_app" then timestamp end),                 min(case when action="start_app" then timestamp end)                ) as duration  from mobile_log as t  group by user_id 	0.000107102436290838
24526622	27704	sql select incremental batch number every x rows	select row_number() over (order by (select 0)) as rownumber, (case when convert(int, (row_number() over (order by (select 0)) % 5))=0 then 0 else 1 end) + convert(int, (row_number() over (order by (select 0)) / 5)) as batchnumber, * from workqueue 	0
24526820	19900	search for the closest entry from two tables	select  a.id as aid, b.id as bid from a  inner join (     select  a.id , min(abs (a.volume - b.volume)+ abs(a.fcdate-b.fcdate)+ abs(a.issuedate-b.issuedate))  as mindiff     from a      cross join b     group by a.id ) sub0 on a.id = sub0.id inner join b on abs (a.volume - b.volume)+ abs(a.fcdate-b.fcdate)+ abs(a.issuedate-b.issuedate) = sub0.mindiff 	0
24527193	18553	sql: count column and show the total result	select count(*) as titel, kuenstlername  from bild  group by kuenstlername union all select count(*) as titel, 'total' as kuenstlername  from bild 	0.000103311733341988
24527346	25592	get only latest date from database (but get all rows with that latest date)	select * from normal where day_of_week = '2'     and since = (         select max(since)         from normal         where day_of_week = '2'     ) 	0
24527394	27565	how to put condition check each group by value in mysql	select mt.emp_id from my_table mt left join my_table mtx on (mtx.emp_id = mt.emp_id and (mtx.isapproved = 0 or mtx.isvalid = 0)) where mt.isapproved = 1 and mt.isvalid = 1 and mtx.id is null group by mt.emp_id 	0
24529289	36549	how to calculate aggregate property of has_many relation in sql?	select   person.name,   case when 't' = any (select items.stolen                         from items                         where items.person_id = person.id) then true else false end as owns_stolen_items from   persons 	0.0566799228067093
24529487	6905	sql query for a specific result set	select  sum(case when emp.empno <> emp_error.empno then 1 else 0 end) as diff_empno, sum(case when emp.age <> emp_error.age then 1 else 0 end) as diff_age from emp join emp_error on emp.id = emp_error.id 	0.0575358640893577
24529712	5860	sql server query: convert to dd/mm/yyyy from datetime	select convert(varchar, getdate(), 105) 	0.022700401554609
24532118	17729	mysql query returning data with detailed / duplicated information	select own_name, own_color, name from pet join own on (pet.own_id = own.id) ; 	0.0954026616423052
24535136	30864	query for active records between date range or most recent before date range	select *  from individual i inner join app_indiv ai     on ai.indiv_id = i.indiv_id outer apply (     select top 1 * from app_note an     where an.app_indiv_id = ai.app_indiv_id         and an.when_mod < @date_to     order by an.when_mod desc ) d where d.status = 'active' 	0
24535416	9321	show name based on id	select     loc_name  from location  where loc_id = yourlocid 	0
24536293	15885	sqlserver to oracle datetime	select to_char(sysdate,'mm') from dual 	0.255793595720718
24536305	28340	mysql joins where unique row required	select p.`product_id`, `price`, `discount`, `product_name`,`images`   from products p    inner join product_images pi on p.`product_id` = pi.`product_id`   where stock_status = 'stock' and status = 'enabled'   group by p.`product_id` 	0.121137265415872
24536896	10208	sum some columns of sql selects with union of two tables	select      month(data.date) as monthly,      year(data.date) as annual,     count(data.idcad) as numcad,      sum(convert(float, data.valorpag)) as valor  from      (select date, idcad, valorpag from pi_as     where (status = 'paid' or status = 'available') and platform = 'sales'     union all     select date, idcad, valorpag  from pi_pp     where (status = 'completed') and platform = 'sales'     ) data group by year(data.date), month(data.date) order by year(data.date), month(data.date) 	0.000479631512641212
24537047	25496	how do i write a script to find tables dependencies across schemas?	select uo1.object_name       from (select object_id, referenced_object_id               from public_dependency              where referenced_object_id <> object_id) pd,            all_objects uo1      where uo1.object_id = pd.object_id connect by prior pd.object_id = pd.referenced_object_id start with pd.referenced_object_id in (select object_id                                          from all_objects                                         where     object_name = <your table>                                               and owner = <your schema name> ) 	0.0404502984872416
24537167	13120	single sql query to display aggregate data while grouping by 3 fields	select tt.nameid, tt.teamid, tt.countryid,        avg(tt.goals) - avg(case when tt.sys_time <  date_trunc('day', now() - interval '1 month') then tt.goals end) as change from testing.testtable tt group by tt.nameid, tt.teamid, tt.countryid order by change desc 	0.00170401846774072
24538768	9229	web articles/comments counts	select  top 10 a.title as articles,         count(c.commented_article_id) * 100 / count(b.visitor_id) as percentage from    articles a  join    website_pageviews b on a.id = b.article_id join    comments c on a.id = c.commented_article_id  group by a.id, a.title order by count(c.commented_article_id) * 100 / count(b.visitor_id) desc 	0.686572618042125
24539520	38480	data from different tables have the same name, how to retrieve data?	select table1.insert_id, table1.type, table1.date as date1 " . "table2.user, table2.date as date2 " . "from insert as table1 " . "inner join contact as table2 on table2.contact_id = table1.contact_id"; 	0
24540480	25040	sql query to check if user assigned with a specific value and does not a different value assigned to the same user?	select  user from    a outer where   valueid = 3 and not exists (     select  1     from    a inner     where     (                 valueid = 1         or      valueid = 2     )     and     inner.user = outer.user ) 	0
24540842	40146	sql count hour for each date of a datetime column	select convert(varchar(10), log_date, 120), convert(varchar(2), log_date, 108)+':00:00', count(*) from table1 group by convert(varchar(10), log_date, 120), convert(varchar(2), log_date, 108)+':00:00' order by convert(varchar(10), log_date, 120), convert(varchar(2), log_date, 108)+':00:00' 	0
24541450	34631	how to query for records that have a certain count within a timespan	select     t1.page,      t1.userid,      t1.date,      min(t2.date) as date2,      datediff(minute, t1.date, min(t2.date)) as daysdiff,     count(*) requestcount from     [sto24541450] t1 left join [sto24541450] t2     on t1.userid = t2.userid and t2.date > t1.date group by     t1.page, t1.userid, t1.date having      datediff(minute, t1.date, min(t2.date)) >= 5 and count(*) >= 5; 	0
24546810	13093	sort table data on weekday	select * from table order by case weekday when 'monday' then 1     when 'tuesday' then 2     when 'wednesday' then 3     when 'thursday' then 4     when 'friday' then 5     when 'saturday' then 6     when 'sunday' then 7     else 8 end ; 	0.00327604763280793
24548583	4394	extract data between two tables	select reqid, reqname, isnull(r.isactive, 'false') as isactive from [request type table] t left join [request rights table] r on r.retypeid = t.reqid and empid  = 21 where t.isactive = 'true' 	0.00049947429207292
24548605	15551	summerize sql count on post statuses	select users.username , sum(if(posts.status=4,1,0)) as `status 4` , sum(if(posts.status=2,1,0)) as `status 2` , sum(if(posts.status=1,1,0)) as `status 1`  from users, posts  where users.id=posts.user_id  group by users.id 	0.0166405513683073
24551201	10644	selecting more than one column to query in sql	select t.spropertycode, sdatadate, sfirstseen, a1.stasktype, a2.stasktype, a3.stasktype from tasks as t inner join temp as a1 on t.spropertycode = a1.spropertycode and a1.stasktype = 'rf' inner join temp as a2 on t.spropertycode = a2.spropertycode and a2.stasktype = 'if' inner join temp as a3 on t.spropertycode = a3.spropertycode and a3.stasktype = 'cm'  where iremoved = 1 and ibusinessstreamid = 9 order by spropertycode, sfirstseen; 	0.00235368468855305
24551345	3815	mysql get average values per hour from the last 24 hours	select id, serverid, avg(performance) as performance, avg(online) as online,  hour(timestamp) from stats_server where serverid= :serverid and date_sub(`timestamp`,interval 1 hour) and  timestamp > date_sub(now(), interval 1 day) group by hour(timestamp) order by id asc 	0
24551489	2806	mysql - search for a word in json text and only give back a result if it occurs in more rows	select * from  `sometable`  where  (`field_a` like  '%wordtofind%'         or  `field_b` like  '%wordtofind%') and (select count(*)      from  `sometable`       where  (`field_a` like  '%wordtofind%'              or `field_b` like  '%wordtofind%')) >= 5 	0.000325029536831223
24554603	5320	access sql - how to get the latest record and the last before timestamp?	select bl.* from ip_block_list bl where bl.[action date] in (select top 2 bl2.[action date]                            from ip_block_list bl                            where bl2.[dst ip] = bl.[dst ip] and                                  bl2.[dst port] = bl.[dst port]                            order by [action date] desc                           ); 	0
24555505	964	how do i return rows with specific value if else?	select * from position order by  case  when position_value = 1 then created_at end asc, case when position_value = 2 then created_at end desc 	0.00139585940821555
24555870	24876	retrieve records which have age less than n months	select * from products where creation_date > date_sub(now(), interval 5 month) 	0
24559484	33023	select - order by word in mysql?	select *   from `table`  where `batch` = 'something'         and outcome in ('business','professional', 'consumer') order by     case when outcome  = 'business'     then 1         when outcome  = 'professional' then 2         when outcome  = 'consumer'     then 3         else 4    end 	0.14647409398315
24560007	27824	how to select specific date from oracle linked server	select * from openquery (mylinkedserver, 'select name, location, date_hired from mytable    where  date_hired between to_date(''2012-01-01'',''yyyy-mm-dd'')                          and to_date( ''2012-01-31 23:59:59'',''yyyy-mm-dd hh24:mi:ss'') ') 	0.00277307839003439
24560326	39267	sql server query count data	select count(1) as abc ,'p' as xyz from #temp where a > b and b != 0 union select count(1) as abc, 'u' as xyz from #temp where b = 0 union select count(1) as abc, 'pl' as xyz from #temp where b<= a and b != 0 	0.329308426795523
24560379	38531	returning a value of a column as null or empty when a value of other column in the same table is 1	select a.id, a.date, c.companyname as 'active company',  h.employee_fullname as 'client', j.displayname as 'seller employee',  case when a.transactiontype =1 then null else d.companyname end as 'counterpartycompany', g.broker_fullname as 'buyer trader', a.transactiontype from confirmations a with (nolock) left join company c with (nolock) on c.company_id = a.activecompany left join company d with (nolock) on d.company_id = a.countercompany left join bprod e with (nolock) on e.id = a.productid left join btype f with (nolock) on  f.id = a.quantitytypeid left join companybroker g with (nolock) on g.companybroker_id = a.counter left join companybroker h with (nolock) on h.companybroker_id = a.active left join users i with (nolock) on i.id = a.buyemp left join users j with (nolock) on j.id = a.sellemp where joindate > '2011-06-04 00:00:00'  and a.disabled = 0  order by dealid 	0
24560472	26142	union select not displaying all columns	select col1 as t1c1, col2 as t1c2, null as t2c1, null as t2c2 from view1 union all select null as t1c1, null as t1c2, col1 as t2c1, col2 as t2c2 from view2 	0.00765285936912009
24560931	12538	oracle sql -- find the most recent data where a column changed in a history table	select      id_of_thing,      version_with_latest_change=max(version_number)  from (     select          id_of_thing, version_number, data,          previous_data=lag(data) over (             partition by id_of_thing              order by version_number         )      from test ) x where data <> previous_data group by id_of_thing 	0
24561431	32959	populated dropdownlist using sqldatasource,how to rename list items? asp.net	select sold, case when sold=1 then 'in stock' else 'sold out' end as soldlbl       from sometable .... 	0.0104248821435848
24563443	36192	simple sql query: retrieve a value depending on a date?	select steuersatz%  from ust where steuersatz = 1 and datum = (select max(datum)              from ust              where steuersatz = 1                and datum <= your_date) 	0.000400674425550514
24565203	12156	average of multiple six month periods	select avg(q1.entry1) as avgperweek from (select count(testid) as entry1, year(testdate),       case when datepart(month, testdate) between 1 and 6         then 'first half' else 'second half' end as term       from table1       group by year(testdate),                 case when datepart(month, testdate) between 1 and 6                      then 'first half' else 'second half'                 end      ) q1 	0
24567463	39494	intersecting n number of queries in mysql	select file_name  from file_info  where  file_id in  (   select file_id    from index_group    where word_id in    (     select word_id      from word_index      where word in ('abc','def','ghi')   )   group by file_id   having count(distinct word_id) = 3  ); 	0.00112943304955839
24568149	41076	switching product query	select customer from transaction where extract(year from tdate) = 2013 and extract(month from tdate) <= 6 group by customer having sum(case when product = 'prod1' then 1 end) / count(*) > 0.75 intersect select customer from transaction where extract(year from tdate) = 2013 and extract(month from tdate) > 6 group by customer having sum(case when product = 'prod2' then 1 end) / count(*) > 0.75 	0.572505429959557
24569363	12163	how to fetch data from two tables using mysql query with some conditions applied to the second table?	select tbl1.nid,        min(tbl2.cid) as cid from table1 tbl1 inner join table2 tbl2 on tbl1.nid=tbl2.nid group by tbl2.nid; 	0
24570685	25352	return zero for no rows returned (in a complex query)	select coalesce(sum(transaction_detail.amount),0) into state_total_amount from     lookup_state , lookup_city , lookup_bank ,transaction_detail where    transaction_detail.bank_id = lookup_bank.bank_id and    lookup_bank.city_id = lookup_city.city_id and    lookup_city.state_id = lookup_state.state_id and     lookup_state.state_id = 3; 	0.025596813385877
24573178	40202	get null values in a mysql query	select     gt.gene_alias as transcript_alias,     gn.gene_name as gene_alias  from gene_transcripts gt left join gene_names gn on gt.gene_alias=gn.gene_alias where gt.gene_alias="at4g38300_og.1" 	0.0134135901400308
24573212	21	mysql query select records based on given date input with out time range	select name,age,title,fee from students where date(`date`) = '2014-07-01' 	0
24574669	35695	double join on a table on the same field	select    fly.codeairport1,    a1.value as valueairport1,   fly.codeaiport2,   a2.value as valueairport2 from   fly left join    airports a1 on a1.code = fly.codeairport1 left join    airports a2 on a2.code = fly.codeairport2 	0.00138902277607614
24576954	15953	mysql select the last message from each conversation	select y.*   from (select max(id) as max_id, user_name           from user_harry          where data_type in (1, 2)          group by user_name) x   join user_harry y     on x.max_id = y.id    and x.user_name = y.user_name 	0
24577342	40761	retrieve all videos rented in the last 30 days and sort in chronological rental date order	select m.title, r.rental_date   from movie m   join inventory i     on m.movie_id = i.movie_id   join rental r     on i.serial# = r.serial#  where r.rental_date >= to_char(trunc(sysdate) - 30, 'yyyy-mm-dd')  order by r.rental_date 	0
24577885	1184	sql query to get the list of names that starts with a given query followed by a white space	select * from user where user.name like @querystring + ' %' 	0
24578685	39958	joining two mysql tables where clause may not exist	select *  from listings l  left join uservote u    on l.id = u.listingid   and u.userid = 'foo' 	0.501477037863101
24579217	19402	how can i get the last completed service of each technician in this query?	select uno.* from     (select fechatermino as fechatermino, idtecnico, latitud, longitud, nombre, apellido, flag, idservicio    from servicio, tecnico, servicio_tecnico    where servicio.idservicio = servicio_tecnico.servicio_idservicio    and tecnico.idtecnico = servicio_tecnico.tecnico_idtecnico    and completado = 1) as uno left outer join     (select fechatermino as fechatermino, idtecnico, latitud, longitud, nombre, apellido, flag, idservicio    from servicio, tecnico, servicio_tecnico    where servicio.idservicio = servicio_tecnico.servicio_idservicio    and tecnico.idtecnico = servicio_tecnico.tecnico_idtecnico    and completado = 1) as dos on (uno.idtecnico = dos.idtecnico and uno.fechatermino < dos.fechatermino) where dos.idtecnico is null; 	8.88060803638089e-05
24579493	20721	percent of records with a single mysql query	select sum(rate >= 3) * 100 / count(*) from users 	0.000818556493365735
24580544	37185	join 2 different tables to a third table	select e.id,per.id,t.status  from employee e  join person per on e.personid=per.id  left join training t on e.id=t.employeeid     and t.courseid = ? 	0.00054028448215687
24580866	5003	mysql multiple join with relationship tables	select      task.*  from      task join client_task      on task.id = client_task.taskid join project_task     on task.id = project_task.taskid where      client_task.clientid = 2 and     project_task.projectid = <given projectid> 	0.203341448416723
24581375	38816	how to use mysql full text search when title and text are in two separate tables?	select question, response,         (match(response) against ('quickbooks')) as response_matches from helpresponses as r join helpquestions as q on r.questionid = q.id where match(response) against ('quickbooks') or match(question) against ('quickbooks') order by response_matches desc 	0.00851357688661161
24584421	2744	sum query with groupby	select   users.username,          e.summary from users as a left join   (    select userid,       sum(cast(datediff(minute, enter, leave) as float)) / 60 as summary    from entries    where (@startdate is null or entries.date >= @startdate)       and (@enddate is null   or entries.date <= @enddate)                           group by userid  ) as e   on e.userid = users.id 	0.640797789008957
24585053	34735	how to choose everything except some number of items?	select st.* from agents a1 join agents   a2 on a1.owner = 1 and a1.id = a2.agentid join agentgtp ag on ag.agentid = a2.id  join gtp         on gtp.id = ag.gtpid right  join stations st on st.id = gtp.stationid where gtp.id is null 	0
24585969	5868	join with multiple table	select sid, sname, count(distinct pid) as `c` from pro_stu  inner join student using (sid) group by sid, sname having `c` = (select count(*) from professor) 	0.226626027483743
24586231	36628	how to get post thumbnail url manually in wordpress plugin development?	select         p1.*,         wm2.meta_value     from          wp_posts p1     left join          wp_postmeta wm1         on (             wm1.post_id = p1.id              and wm1.meta_value is not null             and wm1.meta_key = "_thumbnail_id"                       )     left join          wp_postmeta wm2         on (             wm1.meta_value = wm2.post_id             and wm2.meta_key = "_wp_attached_file"             and wm2.meta_value is not null           )     where         p1.post_status="publish"          and p1.post_type="post"     order by          p1.post_date desc 	0.160680493599168
24587709	25332	update column for random value from different table	select * from (     select b.*, b_rownum=rownum from tableb b where rownum <= <your_random_rownum> ) where b_rownum = <your_random_rownum> 	0
24589099	22368	how to create a sequence field that is equal for duplicates and unique only for unique rows?	select t.*, sequence_id=dense_rank() over (                 order by <fields_you_want_to_test_for_uniqueness>             ) from <your_table> t 	0
24590838	21635	find unmatch record 2 table with where condition apply and record show from 1 table	select       e.* from employee e       left join class c             on e.emp_id = c.emp_id where (c.timing <> '3-4'       or c.timing is null) ; select       * from employee where not exists (             select 1             from class             where timing = '3-4'                   and class.emp_id = employee.emp_id       ) ; 	0
24591618	25416	sql summing to 0 if no row found, while using a join	select flower_id.flower_table, coalesce(sum(transaction_table.sold), 0) as sold from flowers_table left join transaction_table on flowers_table.flower_id = transaction_table.flower_id  group by flowers_table.flower_id 	0.0194810335052723
24591803	17248	trying to figure out top 5 land areas of the 50 states in the u.s	select m.state, m.landarea from map m left join map m2 on m2.landarea > m.landarea group by m.state, m.landarea having count(*) < 5 order by m.landarea desc 	0.0289814276845607
24593546	40101	sql join back to self by many to many relation	select distinct t.id, t.name from     (         select distinct entity_id         from entity_tag         where tag_id in (1, 2, 3)     ) e     inner join     entity_tag et using (entity_id)     inner join     tag t on t.id = et.tag_id 	0.764938136963276
24595120	30173	get the date from a column as dd.mm.yyyy	select date_format(release, '%d.%m.%y') from movies 	0
24597626	6927	how to select a single record per group based on multiple max conditions?	select distinct on (user_id, name)     user_id, name, w.id as workout_id,     difficulty_level, rounds_count from     workouts w     inner join     trainings t on t.workout_id = w.id order by user_id, name, difficulty_level desc, rounds_count desc 	0
24598616	25144	postgresql table overlap count	select a.id1, count(b.id1) num_occurences from mytable a left join mytable b on a.id2 = b.id2 and b.id1 = [id] where a.id1 <> [id] group by a.id1 	0.0532780281982963
24598830	40446	sql sum hits per day and calculate percentage change	select date(v.date), count(v.id_update) a, q2.b, count(v.id_update) - q2.b/count(v.id_update)*100 as percentage from vas_updates v left join (select date_add(date, interval 1 day) d2, count(id_update) as b             from vas_updates group by d2) as q2 on v.date = q2.d2 group by date(v.date) 	0
24599453	3707	sql order by, parent, child, and sort order	select * from (   select p.categoryid        , p.category_name        , p.isparent        , p.parentid        , p.active        , p.sort_order as primary_sort_order        , null as secondary_sort_order   from tbl_category p   where p.isparent = 1   union   select c.categoryid        , ' - ' + c.category_name as category_name        , c.isparent        , c.parentid        , c.active        , a.sort_order as primary_sort_order        , c.sort_order as secondary_sort_order   from tbl_category c   join tbl_category a on c.parentid = a.categoryid   where c.isparent = 0   and a.isparent = 1 ) x order by primary_sort_order asc        , (case when secondary_sort_order is null then 0 else 1 end) asc        , secondary_sort_order asc 	0.00831858168522233
24600859	24367	sql search on three fields from one parameter	select    personid,    firstname,    secondname,    lastname from person where firstname + ' ' + secondname + ' ' + lastname = @fullname 	0.00441317471045478
24602757	37850	php sum total hours with conditions continued	select u.employeename,         u.id,         a.isot,         a.daterecorded,        case when a.totalhours > 0800 then 0800 else totalhours end as normalhours        case when a.totalhours > 0800 then totalhours - 0800 else 0 end as othours from user u right join       attendance a on u.id = a.userid where u.departmentid = 2 group by u.id  having daterecorded >= '01-06-2014' <= '31-06-2014' 	0.0012287782051353
24603001	34968	mysql grouping and fetching row corresponding to a maximum field value within that group	select s.id,         s.player,         s.score   from scores s   join (select id,                 player,                 max(score) as total          from scores      group by player        ) r     on r.total = s.score and         r.player = s.player; 	0
24604356	31986	counting groupwise category in sql	select groupcode       ,groupname       ,checklistcode       ,checklistname,                  ,sum(case when status = 'open' then 1  else 0 end) as opentotal       ,sum(case when status = 'closed' then 1  else 0 end) as closedtotal  from punchlistdetails  group by groupcode,groupname,checklistcode,checklistname 	0.0265075323822177
24606485	6488	right join table status with number of member count with where / having condition	select      ms.name,              count(m.id) as totalnum            from        member_status ms left join   (select * from member where created_at between '2014-06-01 00:00:00' and '2014-07-31 23:59:59') m on m.[status]  = ms.id group by    ms.name 	0.0134037128604529
24606675	26197	sql compare and filter multiple columns into rows	select val,max(date) date from (select value1 as val,date from mytable union all select value2 as val,date from mytable union all select value3 as val,date from mytable union all select value4 as val,date from mytable union all select value5 as val,date from mytable)tab group by val order by date desc,val; 	7.92409607533225e-05
24607513	6563	find all possible event_id that were attend by tag_id 5 and 21	select * from  table where tag_id in (21,5) group by event_id having count(distinct tag_id) = 2 	0.000123658331568017
24609620	22841	grouping records by header sql	select  *  from ( select             dbo.manu_stock.stock_code as [stock code],             dbo.manu_stock.description,              datepart(week,[date]) wk,             qty_in_stock + quantity as stock   from  [fs25-w2k8\sqlexpress].sagel50_46772.dbo.salesforecastlines as salesforecastlines1          inner join  dbo.manu_stock              on salesforecastlines1.productcode = dbo.manu_stock.stock_code ) as source pivot ( sum(stock)  for wk in ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10] ,[11],[12],[13],[14],[15],[16],[17],[18],[19],[20] ,[21],[22],[23],[24],[25],[26],[27],[28],[29],[30] ,[31],[32],[33],[34],[35],[36],[37],[38],[39],[40] ,[41],[42],[43],[44],[45],[46],[47],[48],[49],[50] ,[51],[52]) ) as pvt ; 	0.0231823563032846
24610441	9755	select duplicate entries from a database table	select a.columna from mytable a inner join mytable b on a.columna = b.columna  where a.columnb = 'abc' and b.columnb = 'pqr'; 	0
24612954	5113	connect multiple database in select query in ms access	select tbla.*, tblb.* from [;database='c:\documents and settings\user\desktop\2014\fa.mdb'].master as tbla inner join [;database='c:\documents and settings\user\desktop\2014\general.mdb'.[general] as tblb on tbla.somefield=tblb.somefield 	0.737002503287559
24613287	24862	combine two results in one row	select table1.empid, table1.name, table1.date, table1.earn, table2.total_earn from     (select empid, name, date, earn     from yourtablename         where date = "2014-07-02"     group by empid) table1 left join      (select empid, sum(earn)     from yourtablename     where date <= "2014-07-02"     group by empid) table2 on table1.empid = table2.empid 	0.00022602921364244
24614720	39003	mysql query to find unique records	select distinct id from table t where status = 'active' and not exists (select null                   from table                   where t.id = id and t.media = media                   and status = 'pending') 	0.00108739173646352
24615712	9728	mysql time between different rows as an aggregate	select current.time - previous.time as timediff from   usertable current join        usertable previous on current.user = pervious.user and current.order - 1 = previous.order where current.user = 'john' 	0.00304267255575622
24616072	3412	how to split the table based on date into two tables from existing table	select distinct * into   destination_table  from   source_table where  year(date) = '2011' 	0
24616736	274	get value with the clause if and in	select distinct case when month(t.date) >=7 then year(t.date) else year(t.date)-1 end as fiscalyear from the_table t order by fiscalyear desc 	0.0140901259748945
24617029	30060	mysql get the average and sum of a columns for each x minutes of a group	select min20 * 1200 as timestamp, avg( performance ) as performance, sum( players ) as playersonline         from (             select serverid, floor( unix_timestamp( timestamp ) / 1200 ) as min20, avg( performance ) as performance, avg( playersonline ) as players             from stats_server             group by min20, serverid         ) tmp         group by min20         order by timestamp 	0
24617085	39686	transact sql returning data based on foreign key	select a.ind, a.app, a.ten, coalesce(ap.lname,t.lname)  from a  left join app ap on ap.ind = a.app  left join ten t on a.ten = t.ind 	0.000746275750053086
24617372	7597	how to search from values from one table in another one?	select e.`name`   , (select group_concat(`value`) from shiftinfo where `key` = 'date' and reference in (select reference from shiftinfo where `value` = e.`name`)) as dates   , (select count(reference) from shiftinfo where `key` = 'shift' and `value` = '1st' and reference in (select reference from shiftinfo where `value` = e.`name`)) as `1st shift`   , (select count(reference) from shiftinfo where `key` = 'shift' and `value` = '2nd' and reference in (select reference from shiftinfo where `value` = e.`name`)) as `2nd shift`   , (select count(reference) from shiftinfo where `key` = 'station a' and `value` = e.`name`) as `station a`   , (select count(reference) from shiftinfo where `key` = 'station b' and `value` = e.`name`) as `station b` from employee e; 	0
24618142	6139	how to join three tables with multiple primary key	select n.activity_date,n.advertiser_id,c.type as type from  a      join b as n on a.id=n.id and a.name=n.name     join c on n.c_id=c.id where n.country='ca' limit 10; 	0.0107632288827103
24619059	17694	union different tables with differents columns and data	select     (select count (tab.somecolumnname)            from tablename tab            where tab.experience = 1 and tab.bl = 1) as 'regular',            (select count (tab.somecolumnname)            from tablename tab                           where tab.experience = 1 and tab.bl = 0) as 'rptmm',            (select count (tab.somecolumnname)            from tablename tab            where tab.experience = 0 and tab.bl = 0) as 'new',            (select count (tab.somecolumnname)            from tablename tab            where tab.experience = 0 and tab.bl = 1) as 'rptss' 	0.000855764888469819
24619386	40052	need to add up all the hours for selected column	select sum(authreltime) as traininghours from tempcourseassoc inner join tempcoursedetail on tempcoursedetail.ecassocid = tempcourseassoc.ecassocid where accountnumber in ('760413','760416','767601') 	0
24622916	8057	retrieving data from multiple rows on same field in sqlite	select post_title, post_content, postmeta_key, postmeta_value  from post inner join postmeta land on post._id=land.postmeta_id  where postmeta_id = " + postid + " and postmeta_key in (      'landsize', 'buildingsize', 'propertyprice', 'propertybedroom',      'propertybathroom', 'pool', 'propertytype', 'propertyownership',      'propertylocation', 'propertypooltype', 'propertycarport',      'propertyspecialoffer', 'propertycurrencytype'  ) 	0
24624257	27854	postgis distance calculation	select st_distance_sphere(st_makepoint(103.776047, 1.292149),st_makepoint(103.77607, 1.292212)); 	0.466415801947666
24624833	13705	sql query to combine two different table structures	select * from revenuenew union all select returnsid, submissionid, revenuetype,     1 as businesstype, businesstypea as value from revenueold where isnull(businesstypea, 0) <> 0 union all select returnsid, submissionid, revenuetype,     2 as businesstype, businesstypeb as value from revenueold where isnull(businesstypeb, 0) <> 0 union all select returnsid, submissionid, revenuetype,     3 as businesstype, businesstypec as value from revenueold where isnull(businesstypec, 0) <> 0 	0.000752333981364514
24626666	4466	mysql sum of query result	select sum(`grading`) from   (select *    from `trails`    where `name` = "free flow"    order by `id` desc limit 5) as temp; 	0.088138698614814
24628173	15288	sql - how to select records with value a but not b? (a and b belongs to different rows)	select record_id from table_a where tag_id = 2 except select record_id from table_a where tag_id = 3; 	0
24628895	26922	how can i get values from few rows to one in sql oracle	select  max(id),  max(c_01),  max(c_02),  max(c_03) from   tbl 	0
24630061	5044	xml nodes into one row in sql	select      i.value('(image[1]/type)[1]','int') as image1type,      i.value('(image[1]/code)[1]','int') as image1code,     i.value('(image[2]/type)[1]','int') as image2type,      i.value('(image[2]/code)[1]','int') as image2code,     i.value('(image[3]/type)[1]','int') as image3type,      i.value('(image[3]/code)[1]','int') as image3code from      @xml.nodes('/images') x(i) 	0.00072007271258161
24631925	40652	use sql to convert datetime to w32time	select convert(bigint, datediff(day, '1600-12-31', '2014-10-31'))*24*60*60*10000000 	0.545560966495923
24632203	34771	collapse data using order by and group by	select t1.cola, t1.colb, t1.colc from     (select *, row_number() over(order by cola, colb) as rownumber         from test) t1 join (select cola, colb, min(rownumber) as rownumber     from         (select *, row_number() over(order by cola, colb) as rownumber         from test) as subquery_01         group by cola, colb) t2 on t1.cola = t2.cola and t1.colb = t2.colb and t1.rownumber = t2.rownumber 	0.255391504992996
24634295	22488	exposing more fields on group by sql	select a.*, b.* from bmp_visits_sites a outer apply (     select top 1 *     from bmp_visits_comments b     where b.stationid = a.stationid     order by lastdateobserved desc ) b 	0.160277275753615
24635503	29902	oracle sql - returning row of first occurrence by value	select id,        (case when max(event) = 1 then min(case when event = 1 then yrmth end)              else max(yrmth)         end) as yrmth,        max(event) as event           from table t group by id; 	0
24636123	40790	perform select on both tables before join	select tba_filter.* from (select tba.* from tba where tba.id_tbb<=id_max) as tba_filter  inner join (select * from tbb where tbb.id_tbb<=id_max and tbb.date<'2014-01-01 00:00:00') as tbb_filter on tba_filter.id_tbb = tbb_filter.id_tbb where tba_filter.id_tbb<=id_max 	0.139257636860301
24636443	27568	where subquery = 0	select * from eu_questions where 1 = any (   select correct   from eu_answers   where question_id = eu_questions.id ); 	0.759501464250591
24636503	37061	mysql many-to-many query	select     * from     account_character ac     inner join account a on ac.account_id = a.id     inner join character c on ac.character_id = c.id where     account.username = ? and     account.password = ? ; 	0.60466657222863
24638602	15260	sql: trying to put a series of "count"s results into a table	select  count (studyid) as numberofrxs,         count (distinct studyid) as numofpatients,         count (case when exposed = 1 then studyid else null end) as numrxswithstatin,         count (distinct case when exposed = 1 then studyid else null end) as numpatientswithdrug,         count (case when exposed = 0 then studyid else null end) as numrxsnodrug,         count (distinct case when exposed = 0 then studyid else null end) as numpatientssnodrug from &data where zz=&zz; 	0.000212965945454031
24638920	21078	sql - third table joined to two tables but where condition of column in third table is different	select * from project   left outer join salesorder on project.prjg_recordid = salesorder.som_prjg_dfltrecordid   left outer join poi on project.prjg_recordid = poi.poi_prjg_dfltrecordid where (poi.poi_prjg_dfltrecordid is not null and project.projectid is null)    or (salesorder.som_prjg_dfltrecordid is not null and project.projectid is not null) 	0
24640070	33072	how to get the body of a database function through jdbc?	select prosrc from pg_proc where proname = 'my_function'; 	0.0977632441009757
24640265	24966	calculate percentage in sql	select stu.name, exam.standard, avg(stu.marks) as 'percentage' from student stu  inner join examresult exam     on stu.id=exam.studentid; group by stu.name, exam.standard 	0.0211267770176929
24641647	9631	sql get values from xml with same node name	select tag.name.value('.','nvarchar(20)') from @tab tab     outer apply tab.xmldata.nodes('/values/required/name') tag(name) where tab.usernames = tag.name.value('.','nvarchar(20)') 	5.5629097073791e-05
24644697	40779	finding strings with embedded spaces in a column	select * from test t where column like '%  %'; 	0.101099414830708
24647553	34189	join the three tables	select   u1.id_user_type,  p.page,  p.roll   from user_type as u1   left join user_type_page_access as u2  on u1.id_user_type=u2.id_user_type  left join page_access as p  on p.id_page_access=u2.id_page_access  where u1.id_user_type=@id_user_type 	0.0792948106474137
24647927	29832	select statement on case	select    m.id,   m.name,   case     when o.status = '1'      then 'in progress'      when o.status = '2'      then 'complete'    end as status  from   maintable m    join othertable o      on (o.id = m.id) 	0.787237956088619
24649556	16320	generate interesting view of data	select assetname,project,min(t.min)start_day,max(t.max) end_day,        datediff(dd,min(t.min) ,max(t.max)) duration from ( select  assetname,project,dateadd(dd,min(week),weekbeginning) 'min',dateadd(dd,max(week),weekbeginning) 'max' from #temp  t cross apply(select 0 'week' where t.monday=1 union all select 1 where t.tuesday=1 union all             select 2 where t.wednesday=1 union all select 3 where t.thursday=1 union all             select 4 where t.friday=1 union all select 5 where t.saturday=1 union all             select 6 where t.sunday=1              ) d group by assetname,project,weekbeginning )t 	0.146687761125247
24650533	32613	sum values of column with type character	select sum(valorout::decimal) from trans group by(duplicated); 	0.00368806450898197
24651722	11115	how to return count using mysql query?	select `date`, count(`number`) as num_count from play_history  where user_id = 49 group by `date` 	0.122509790806972
24652598	19298	using regex to find same digit phone numbers	select * from tblphone where  substring(replace(phoneno,'+',''),1,len(replace(phoneno,'+',''))-1)  = substring(replace(phoneno,'+',''),2,len(replace(phoneno,'+',''))) 	0.00118969508243961
24653314	15480	find where report email job is	select jobname = rs.scheduleid   , reportname = c.name from reportschedule rs   inner join [catalog] c on rs.reportid = c.itemid 	0.3037455070794
24654884	30229	in access 2010 i would like to find the % by mco where data > 40. not the % of total count by mco, but rather % by count for each mco	select      tblmcos.mcos,      sum(iif(tblmcos.data > 40, 1, 0)) / sum(1) from      tblmcos group by      tblmcos.mcos order by      tblmcos.mcos; 	0.000313262514419949
24656038	8562	sql sequential if conditions	select  project         ,count(status) as "status count"         ,sum(case when status = 'closed' then 1 else 0 end) as closed         ,sum(case when status = 'open' then 1 else 0 end) as "open"         ,sum(case when priority = 'major' then 1 else 0 end) as major         ,sum(case when priority = 'moderate' then 1 else 0 end) as moderate         ,sum(case when priority = 'minor' then 1 else 0 end) as minor         ,sum(case when priority = 'unknown' then 1 else 0 end) as unknown from ( select t.*   ,      case          when charindex ( 'major', defectsummary collate latin1_general_ci_as) > 0          then 'major'          when charindex ( 'moderate', defectsummary collate latin1_general_ci_as) > 0          then 'moderate'          when charindex ( 'minor', defectsummary collate latin1_general_ci_as) > 0          then 'minor'          else 'unknown'          end          priority   from   tasks t ) tasks group by    project 	0.301276846272657
24656236	15997	mysql - join that delete duplicity in column	select v.id,s.name,v.date from software s join software_version v on (s.id=v.software_id) join (select software_id ,max(date) date        from software_version group by software_id) v1 on(v.software_id =v1.software_id and v.date=v1.date) order by v.date desc 	0.0974001789986596
24656335	34420	get timestamp of user's last visit from database	select userid, max(timestamp) from <yourtable> group by userid 	0
24656780	33020	selective join for two tables (sql server)	select t1.docnum, t1.doctype, t1.code, t2.invnum from  (     select *, row_number() over (partition by docnum order by docnum, poline) as ordinal     from table1 ) t1 left join  (     select *, row_number() over (parition by docnum order by docnum, invseq) as ordinal ) t2 on t2.docnum = t1.docnum and t2.ordinal = t1.ordinal 	0.0856715836642904
24656984	40827	oracle selecting one row from multiple rows based on a column value	select     station,     (case when sum(status) > 1 then 1 else 0 end) as status,     date_time from machinestatus group by station, date_time order by date_time 	0
24657099	32738	mysql - select row only if previous row field was 0?	select *    from status s  where s.imei='123456789012345'    and s.acc=1    and (   select acc     from status    where imei=s.imei      and datetime<s.datetime order by datetime desc    limit 1        ) = 0 	0
24657257	1762	selecting rows where there is repetition in columns	select name from your_table group by name having sum(case when score = 0 then 1 else 0 end) = 0 	0.00621512433410358
24658157	6545	sql sum column value once per one-to-many relationship id	select sum(numpayments), sum(amount), sum(totalpayments) from (select p.paymentid, count(*) as numpayments, sum(orderamount) as amount,              max(totalpaymentamount) as totalpayments       from payment p       group by p.paymentid      ) p; 	0
24658355	21001	invalid column name when selecting	select * from job where name = 'testjob'; 	0.103654559935537
24662854	4768	how to get count of a column value returned using subquery?	select source_sys_cd,         count(case                 when is_delete = 0 then 1               end) [del is 0],         sum(case               when trans_amt = 0 then 1               else 0             end)   [stg $0 txn cnt],         sum(case when t.acct_key is null then 1 else 0  end ) countnotin from   staging_transactions (nolock) s        left join (select distinct acct_key                                          from   staging_cust_acct) t          s.hrc_acct_num  = t.acct_key  group  by source_sys_cd  order  by source_sys_cd 	0.000246565028841814
24663139	32239	connecting two tables using a third table (sql)	select       first.name1,              second.name2 from         firsttable first left join    secondtable second on first.code1 = second.code1 inner join   thirdtable third on second.code2 = third.code2 	0.00441621236490895
24663744	16493	sql: number of comments left by single commenter	select    email, count(*) from   mytable group by email order by count(*) desc 	0.00541165568218116
24665321	18030	tsql having statement from sub query	select   top 5 count(a.[nomineeempid]) as totalsubmissions,                  a.[nomineeempid],                  b.[firstname] + ' ' + b.[lastname] as supname,                  b.[ntid] as supntid         from     empowermentsubmissions as a         join emptable as b         on a.[nomineeempid] = b.[empid]         group by nomineeempid, b.[firstname], b.[lastname], b.[ntid], supempid         having (select count(supempid) as totalteammates from emptable where supempid = a.[nomineeempid]) > 0         order by totalsubmissions desc         for      xml path ('data'), type, elements, root ('root') 	0.797186217788426
24665769	129	select [car] based on [feature]s -- all or nothing	select car from car_feature group by car having sum(case when feature in ('cd player', 'sunroof', 'leather')                  then 1                  else -1             end) = 3 	0.00286686853007089
24668371	24350	get data from table with group and the member	select car_category,        group_concat(car_name separator '\n') from `car` group by car_category 	0.000112331964425852
24670222	39237	sql compare values in double select	select b.busname from buses b inner join (select busid, stationname from stations where stationname = @startingpoint) bs on b.busid = bs.busid inner join (select busid, stationname from stations where (stationname = @destination) bd on b.busid = bd.busid  where bs.stationname > bd.stationname 	0.025365568724392
24670237	34217	sql find the number of orders in each line count	select count(*) as orders, lines from (     select order_id, count(*) as lines from data group by order_id )query group by lines 	0
24672773	36651	how to make day in mysql or java	select timestampdiff(day, '2012-06-04 13:13:55', '2012-06-05 15:20:18')+1; 	0.0874737124483458
24673572	13375	mysql sum of two columns wrong result	select cast((a.`value`+b.`value`) as decimal(10,6)) as totalvalue from `table 1` a cross join table 2 where a.`id` = 1   and b.`id` = 1 	0.0126208965639862
24677089	1622	in tsql, how do i replace a value if the value is not null?	select case when len(eweb) > 0 then 'website' else '' end as value from web_facstaffdir  where eweb is not null 	0.0257403805512603
24679124	3508	how to filter group by results by set	select a, ..., sum(if(b in ("foo", "bar"), 1, 0)) as foobarcount from tb where ... group by a having foobarcount < 1; 	0.0683726567884868
24679706	10378	cannot compare start time and start date object with getdate() in query	select mytable.name, mytable.date, mytable.starttime from mytable     where convert(datetime, convert(varchar(13), mytable.dateofbooking, 103) + ' ' +   convert(varchar(8), mytable.starttime, 108),103) >= convert(datetime, getdate()); 	0.0088572297036865
24680601	36179	select statement with null and non-null values	select  [key]         ,[parent_key]         ,[parent_code]         ,[code]         ,[desc]          ,[point]         ,[by]          ,[on] from    [db].[stats] t  where   t.[parent_key] = @tmpparameter  or (t.[parent_key] is null and  @tmpparameter is null) 	0.0638040500921761
24682398	33935	select pk from duplicated values	select     id from     movimentacaoconta mc inner join (     select         v1,         v2,         count(*) as row_count     from         movimentacaoconta     group by         v1,         v2 ) mc0 on     mc.v1 = mc0.v1 and     mc.v2 = mc0.v2 where     mc0.row_count > 1 	0.00188749482454027
24682589	7866	getting counts of the records in two joined queries	select gc.id, count(*) as numberofassociated  from gc inner join rud on rud.commonid = gc.commonid  group by gc.id 	0
24682986	8503	sql server max date in sum of values	select max(date), sum(value) from mytable where date between '2014-01-01' and '2014-08-15'; 	0.00270455396906063
24683894	34812	mysql left join and sum and show 0 instead of null	select o.order_id, ifnull(sum(d.qty),0) as total from orders o     left join details d on o.order_id = d.order_id  group by order_id 	0.089535568260813
24684415	38411	sql: find all rows in a table for which all rows in another table that refer to the original row have a certain property	select distinct challenge_id from contestents c where not exists (select * from contestents                    where challenge_id = c.challenge                      and user_id not in ([list of userids])) 	0
24686357	1384	sql select - include rows that don't exist?	select post_id,        sum(case when ul_key = 'u_like' then ul_value else 0 end) as likes,        sum(case when ul_key = 'u_dislike' then ul_value else 0 end) as dislikes from wp_like_dislike_counters group by post_id; 	0.00237207846118502
24687277	2597	mysql query to convert normalized data into single row	select      cn.name as name,     max(case when pt.type_id = '1' then ph.phone_number else null end) as mobile,     max(case when pt.type_id = '2' then ph.phone_number else null end) as office,     max(case when pt.type_id = '3' then ph.phone_number else null end) as home       from     contacts cn     left join link_contact_phonenumbers lp on lp.contact_id = cn.contact_id     left join phone_numbers ph on ph.phone_number_id = lp.phone_number_id     left join ref_phone_types pt on pt.type_id = ph.type_id group by cn.contact_id 	0.000365578181698721
24687675	25883	mysql - how to select consecutive rows depends of data	select      log_id, id_usu_detalle, log_horafecha, log_estado from     (select          log_id,         id_usu_detalle,         log_horafecha,         log_estado,         if(@a = log_estado, 5, 0) as counter,         @a:=log_estado     from log     cross join (select @a:=10000) as t) as temp where counter = 0; 	7.06959095365863e-05
24687889	28769	oracle sql count with join	select    lifnr,   count(distinct (case when e1.bsart = 'nb' then e1.ebeln else null end)) schedule_orders,   count(case when e1.bsart = 'nb' then e1.ebeln else null end) schedule_order_lines,   count(distinct (case when e1.bsart = 'znbs' then e1.ebeln else null end)) store_orders,   count(case when e1.bsart = 'znbs' then e1.ebeln else null end) store_order_lines,   count(distinct (case when e1.bsart = 'zcso' then e1.ebeln else null end)) third_party,   count(case when e1.bsart = 'zcso' then e1.ebeln else null end) third_party_lines,   count(distinct (case when e1.bsart not in ('zcso', 'nb', 'znbs' ) then e1.ebeln else null end)) other_orders,   count(case when e1.bsart not in ('zcso', 'nb', 'znbs') then e1.ebeln else null end) other_order_lines,   count(distinct(e1.ebeln)) total_orders,   count(e1.ebeln) total_order_lines from saprpe.ekko e1 left join saprpe.ekpo p1 on e1.ebeln = p1.ebeln where e1.aedat between '20130701' and '20140701' group by lifnr 	0.738133180988228
24691202	9627	count multiple results in mysql query	select     sum     (         case             when cat1 = 1 then 1             else 0         end     ) cat1_1,     sum     (         case             when cat1 = 2 then 1             else 0         end     ) cat1_2,     sum     (         case             when cat1 = 3 then 1             else 0         end     ) cat1_3,     sum     (         case             when cat1 = 4 then 1             else 0         end     ) cat1_4,     sum     (         case             when cat1 = 5 then 1             else 0         end     ) cat1_5,     sum     (         case             when cat2 = 1 then 1             else 0         end     ) cat2_1, ... ... ...  from mytable where bizid=$id; 	0.208883346604358
24692058	20023	how to sum a column using after order by and group by	select agentid,groupname, sum(quantity)  from table_name  group by agentid,groupname   order by agentid,groupname 	0.0215694426525708
24694440	38863	sql: increment for every group by	select         exerciseid       , count(distinct date) as exercise_count from user_exercises group by         exerciseid ; | exerciseid | exercise_count | | |         54 |              1 | |         85 |              3 | |        420 |              2 | 	0.0137462082544752
24694911	37223	how to select and print from each variable in another select sql query	select distinct  c1.companyname,  stuff((select ', '+ cn.name           from wmccmcategories cn           inner join categorysets uc          on uc.categoryid = cn.categoryid          inner join keyprocesses u          on u.categorysetid = uc.setid           inner join companies c          on c.companyid = u.companyid                 where c.companyname = c1.companyname          order by cn.name for xml path('')), 1, 1, '') as liststr  from companies c1 group by c1.companyname 	0
24696002	9436	sql, select entries older than 30 days, filter entries older than 30 days that have entries within the last 30 days	select farm_list.customer_id, max(data_stored.`timestamp`) as maxts from hathor_hb.data_stored data_stored inner join      farm_db.farm_list farm_list      on (data_stored.farm_code = farm_list.farm_code) group by farm_list.customer_id having maxts <= curdate() - 30; 	0
24696522	6655	how do i get the desired result?	select t1.p_id, t1.p_name, count(t2.sid) as s_id      from table1 t1 join table t2 on t1.p_id = t2.p_id           group by t2.p_id 	0.0348829874060488
24697421	38782	selecting rows in sql in sequence fashion of column	select t.id, t.col, t.filter from (select t.*,              @rn := if(@f = filter, @rn + 1, if(@f := filter, 1, 1)) as rn       from table t cross join            (select @f := '', @rn := 0) vars       order by filter, id      ) t order by rn, field(filter, 'type1', 'type2', 'type3'); 	0.000553637707359019
24697544	29436	sql : select 20 entries from a specific id	select * from users where id >= 34 order by id asc limit 20 	0
24698074	17297	how to join two tables with repeating entry in sqlite3	select * from table1 inner join table2 on table1.id = table2.id 	0.00251069059977611
24698516	37942	find ratio of duplicate values in a field b/w every 2 users. (mysql)	select distinct u3.user_id,     t.u2userid,     count(u3.ip_address) totalcount,     ipcount from (select     u1.user_id u1userid,     u2.user_id u2userid,     count(u1.ip_address) ipcount from user_hits u1 left outer join user_hits u2     on u1.user_id <> u2.user_id     and u1.ip_address = u2.ip_address group by    u1.user_id,         u2.user_id) t inner join user_hits u3     on t.u1userid = u3.user_id group by    u3.user_id,         ipcount,         t.u2userid 	0
24699636	39118	selecting specific information using two tables	select p.player_id,count(*) from players p inner join login l on p.player_id = l.player_id where l.login_date = '2014-06-01' and l.email_address like '%.net' group by p.player_id 	0.000295185169520066
24700634	20910	oracle sql query records where timeinterval with previous record is less then eg 1 minute	select * from (select a.*,              lag(sdt) over (partition by id order by sdt) as prevsdt,              lead(sdt) over (partition by id order by sdt) as nextsdt       from table_a a      ) a where sdt - prevsdt <= 1/(24*60) or       nextsdt - sdt <= 1/(24*60); 	0.00146303627619103
24700672	299	query to get average and distinct in mysql	select     study,     avg     (         case              when class = 1 then average             else null         end     ) class_1_average,     avg     (         case              when class = 2 then average             else null         end     ) class_2_average,     avg(average) avg_class from mytable group by study; 	0.00160724674100149
24700736	40651	how can i get more columns if i have using aggregate function with keyword group by?	select      avg(salesprice) ,firstname  from tblproducts  join tblsales  on tblproducts.tid = tblsales.productid  join tblcustomers on tblcustomers.customerid = tblsales.customerid  group by firstname having count(cust_id) > 1 	0.182584178521992
24701699	39432	sql grouping by part of string & return comma-separated	select  jobnumber,  substring(answer, patindex('%item%', answer), 7),  notes =     stuff((select ', ' + rtrim(answer)           from docketquestionsandanswers b            where b.jobnumber = a.jobnumber             and substring(a.answer, patindex('%item%', a.answer), 7) =                 substring(b.answer, patindex('%item%', b.answer) , 7)             and screen like '%cut%'             and answer like '%item%'           for xml path('')), 1, 2, '') from  docketquestionsandanswers a where  jobnumber in (select jobnumber               from ) group by  jobnumber,  substring(answer, patindex('%item%', answer), 7)    having  substring(answer, patindex('%item%', answer), 7) like '%item-%' 	0.0124693729865658
24702161	8918	how can i find records that don't have a specific value in a field?	select devices.name from devices except select devices.name from software_installations          inner join devices on devices.id = software_installations.computer_id           inner join software on software.id = software_installations.software_id where devices.dn like "%ou=police_ou%" and software.name = "microsoft .net framework 4 client profile"; 	0
24702460	15210	sql nested queries - part 2	select product_name,         group_concat(distinct large_image) as largeimages,        group_concat(distinct medium_image) as medium_images  from products  left join images on images.image_product_id = products.productid  group by productid 	0.416004124922222
24702539	30184	mysql disorder result set using query	select @d:=@d+1 as count, currentisp  from      ( select @c:=0, @a:=0, @b:=0, @d:=0 )  temp,     (         select *          from (             select 'yahoo.com' as currentisp             union all select 'yahoo.com'             union all select 'gmail.com'             union all select 'gmail.com'             union all select 'hotmail.com'             union all select 'hotmail.com'         ) t         order by             case                  when currentisp='yahoo.com' then @a := @a + 1                  when currentisp='gmail.com' then @b := @b + 1                   when currentisp='hotmail.com' then @c := @c + 1               end desc     ) as t 	0.703556742024206
24702779	39575	best way to find deviation from average number of days with oracle sql	select * from (   select id as ord_id,          customer_id,          total,          (date_shipped - date_ordered) as delay,          avg(date_shipped - date_ordered) over () as avg_delay,          (date_shipped - date_ordered) - avg(date_shipped - date_ordered) over () as deviation   from s_ord ) t where delay > avg_delay order by total desc 	0
24703509	30831	sql select help - who paid this year but is inactive	select distinct f1.costumer_id  from finance f1 where (datepaid >= '2014-01-01'      and datepaid < '2014-07-01')  and datediff(d, (     select top 1 f2.datepaid     from finance  f2     where datepaid <> f1.datepaid     and f1.costumer_id=f2.costumer_id     order by f2.datepaid desc)     ,f1.datepaid)>365 	0.586870848736298
24704167	1917	sql get record with highest amount in given hour	select d.* from data d   join (select max(amount) maxamount, hour(date) datehour, date(date) date         from data         group by hour(date), date(date)         ) d2 on d.amount = d2.maxamount            and hour(d.date) = d2.datehour           and date(d.date) = d2.date 	0
24706022	14816	select from two tables where only 1 unique result from table_1	select t2.firstname, t2.lastname, t2.zip from table_2 as t2 join ( select t1.firstname, t1.lastname, t1.zip from table_1 as t1 group by t1.firstname, t1.lastname, t1.zip having count(*) = 1) as t1   on t1.firstname = t2.firstname  and t1.lastname = t2.lastname  and t1.zip = t2.zip 	0
24707943	13660	get top ranked values across multiple fields	select distinct     first_value(age) over (order by count1 desc) as top1,     first_value(sex) over (order by count2 desc) as top2     from (         select age,                sex,                count(age) over (partition by age) as count1,                count(sex) over (partition by sex) as count2                from some_table     ) some_table 	7.71938521983691e-05
24708400	23637	mysql - rows to columns on date	select      id,      login,      logout,     timestampdiff(minute, login, logout) / 60 as 'hours worked' from(     select id,          max(if(inorout = 1, datetime, null)) as login,         max(if(inorout = 0, datetime, null)) as logout     from table_name     group by date(datetime) ) as temp; 	0.000443049112238775
24709581	28466	how to concatenate three strings first two characters automatically in sql server	select top 1 upper(left(name, 2) + left(village, 2) + left(state, 1) + convert(varchar, year(getdate()) % 100)) code   from k_fs_distributordetails  order by customercode desc 	0.000141453283059922
24709976	11640	select unique values of one column with single non unique value of another table	select min(id) as 'id',column_name  from test  group by column_name order by id; 	0
24710363	21461	query find ranking with criteria in mysql	select case when average > 80 then 1             when average > 65 then 2        end as rangking,        class, name, average from (select class, name, avg(avg_scores) as average       from yourtable       group by class, name       having average > 65) as subquery order by class, rangking 	0.0961899694388248
24710419	16558	how to trim a field with persian text in sql server	select  ltrim(reverse(substring(reverse([name]),1, charindex('٬', reverse('٬' + [name])) - 1))) from dbo.city 	0.348180111936453
24710448	8165	how to get the last record using group by	select p.*,b.brand_name     from portfolio p       inner join branding_category b on p.brand_category = b.id       inner join (         select max(id) maxmsgidforthread         from portfolio         where is_active = '1'         group by brand_category       ) g on p.id = g.maxmsgidforthread     order by p.id desc     limit 10 	0
24711309	15988	sql: return specified column of max() row inside select	select e.id as id, e.name,     max(ue.time) as time,     (         select date         from `users exercises`         where time = max(ue.time) and ue.`userid` = $userid         limit 1     ) as time_date,     max(ue.weight) as weight,     (         select date         from `users exercises`         where weight = max(ue.weight) and ue.`userid` = $userid         limit 1     ) as weight_date,     max(ue.distance) as distance,     (         select date         from `users exercises`         where distance = max(ue.distance) and ue.`userid` = $userid         limit 1     ) as distance_date from `users exercises` as ue left join `exercises` as e on exerciseid = e.id where ue.`userid` = $userid group by e.id limit 30 	0.00129537942366957
24714429	39739	how to count result from two columns in mysql	select      concat(homescore, '-', awayscore) as result,     count(*) as predictions from table where matched = 1 group by concat(homescore, '-', awayscore); 	0.00021907195795592
24714588	28670	query to count the number of values in a columns	select count(case when app_status= 'accepted' then 1 else null end) as accepted,  count(case when app_status='rejected' then 1 else null end) as rejected,  count(case when app_status='pending'then 1 else null end) as pending from application 	0
24714917	6559	select max value of a row from two tables	select * from ( select         a.user_id,        a.name,        b.class,        year from        table1 a inner join            table2 b     on            a.user_id=b.user_id order by year desc ) h group by user_id 	0
24715303	3696	multiple full outer join on store number	select [company$trans_ sales entry].[store no_] as store, [company$store].[name],         sum([company$trans_ sales entry].[net amount] * -1) as sales   from [company$trans_ sales entry]   join [company$store]      on [company$store].no_ = [company$trans_ sales entry].[store no_]  where [company$trans_ sales entry].date = convert(date,getdate())     and [company$trans_ sales entry].[store no_] not like '5%'  group by [company$trans_ sales entry].[store no_], [company$store].[name] 	0.508112609779049
24719068	5726	storing time in database for users in different time zones	select convert_tz('2004-01-01 12:00:00','gmt','met');         -> '2004-01-01 13:00:00' 	0.000485282329015709
24719729	14024	sql - select only players and dates when a date does not contain a player	select player, date  from nba.player_stats where date not in (select date    from nba.player_stats    where player = 'ryan anderson') 	0.00248518306174567
24720333	20133	get the selected minimum price row's columns in sql?	select * from products p outer apply  (     select top 1 coalesce(cp.newprice, cp.price, 2147483647) minimumchildprice,                  promotion minimumchildpricepromotion     from    products cp     where   cp.parentid = p.id     order by coalesce(cp.newprice, cp.price, 2147483647) ) as c 	0
24721649	14612	php mysql 2 select to 1 select	select * from   product p where (   select  count(*)    from    product  p1   where p1.cid = p.cid and    p.id <= p1.id ) <= 3 order by p.id desc 	0.0163284279894883
24727235	5526	mysql multiple count() from multiple tables with left join	select u.user_id,             u.user_name,            count(distinct p.post_id) as `postcount`,            count(distinct ph.photo_id) as `photocount`,            count(distinct v.video_id) as `videocount`       from user u  left join post p         on p.user_id = u.user_id  left join photo ph         on ph.user_id = u.user_id  left join video v         on v.user_id = u.user_id   group by u.user_id   order by postcount; 	0.0999841803930791
24730777	14992	how to find duplicate rows with similar part of string	select substring_index(name,' ',-1),count(*) from birds_name group by substring_index(name,' ',-1) having count(*)>0; 	0
24731417	22828	how can i return datetime constant with datetime type in sql server?	select convert(datetime,'20010528 08:47:00.000')as datefield or  select cast('20010528 08:47:00.000'  as datetime)as datefield 	0.0629989613999232
24732474	32939	creating different user roles in oracle apex	select role from people where e_mail = v('app_user') 	0.0584467741623182
24733602	19573	compare words in string to cell	select dbstring,        if(locate('alfa',dbstring), 1, 0) as c_alfa,        if(locate('bravo',dbstring), 1, 0) as c_bravo,        if(locate('charlie',dbstring), 1, 0) as c_charlie from original; 	0.00122515099126289
24734608	31335	joins and absentee values	select        o.value1,...        cl.value199,        isnull(p.pricefactor1,1) from   orders o        join clients cl on o.clientno = cl.clientno        join calc c on cl.calccode = c.calccode        left join prices p on cl.pricekey = p.pricekey            and o.pricefactor1 = p.pricefactor1            and o.pricefactor2 = p.pricefactor2            and o.pricefactor3 = p.pricefactor3 	0.463382006684209
24735552	36627	count results from a select in a join	select .... count(distinct purchase_details.companyid) company_count from ... group by purchase_details.companyid,purchaseid ; 	0.0182699597780671
24736626	15620	fill in all dates in certain date ranges from another using calendar table	select convert(varchar,d.date, 105) from dbo.days d join dbo.holidays h on d.date between h.datefrom and h.dateto 	0
24736783	19860	oracle sql: how do i concatenate results into one column (with delimiters) and also rename the column?	select column_1||', '||column_2 as "concatenated_result"      , column_3 from   table 	0
24737541	31224	datediff to only include working days?	select  a.siteid, datediff(d,a.mino,a.maxo)-2*datediff(wk,a.mino,a.maxo) from (select  sn.siteid, max(sn.creationdate) maxo, min(sn.creationdate) mino from sitenotifications sn group by sn.siteid) a 	0.0147192937744796
24737889	36176	select with custom result	select id,        name,        case when type = 'a' then 'first'             when type = 'e' then 'second'             when type = 'w' then 'third'        end as alias_name from city 	0.458775618662084
24737905	16581	what is not selected	select * from users left outer join pmt_company on pmt_company.userid = users.usr_uid 	0.751532622015018
24738778	4162	how to get previous value from a log	select  * , prev_value = (     select top 1 newcustomervalue      from #customerexamplelog l      where c.customerrecordid = l.customerrecordid      and l.newcustomervalue <> c.currentcustomervalue      order by logcreatedate desc    ) from    #customerexample c 	0
24739236	1203	joins with 4 tables returns a row for every entry in the fourth table	select  serial       , model          , manufacturer       , customer       , customername       , customercontact from   (     select  serial           , model              , manufacturer           , customer           , c.customername           , cd.customercontact           , row_number() over (partition by serial order by serial) rn     from        unitcoredetails      u      inner join  customerstable       c      on c.customerid=u.customer      inner join  customersitetable    cs     on c.customerid = cs.customerid       inner join  customerdetailstable cd     on cs.customersiteid=cd.customersiteid      where u.serial = 'test'    )q where rn = 1 	8.45933640381436e-05
24739929	20362	oracle sql: export to csv avoiding newlines	select    c.column1,   c.column2,   replace(c.column3,chr(10),null) as column3,    c.column4, from table1 c where condition1 = true; 	0.516394533733587
24742997	40399	test whether time(7) datatype value is 00:00:00.0000000 in sql server 2008 r2	select *  from messages  where timesent = '00:00:00.0000000' 	0.754368803341014
24743268	22655	how to ensure that sets of pairs are selected with sql which don't exclude each other	select * from [dv]  where  ([dv].[data] = "a" and [dv].[map] = 15)  or  ([dv].[data] = "3" and [dv].[map] = 12) 	0
24743615	28224	xpath, parsing xml and deleting xml attributes in oracle	select extract (           xmltype (              '<session xmlns="http:              xmlns:soap="http:              xmlns:xsi="http:           ' 	0.374360479968337
24744312	28677	how to get count of all columns of a table, which are not null using pl/sql?	select t.table_name,        t.num_rows,        c.column_name,        c.num_nulls,        t.num_rows - c.num_nulls num_not_nulls,        c.data_type,        c.last_analyzed from all_tab_cols c join sys.all_all_tables t on c.table_name = t.table_name where c.table_name like 'ext%'   and c.nullable = 'y' group by t.table_name,          t.num_rows,          c.column_name,          c.num_nulls,          c.data_type,          c.last_analyzed order by t.table_name,          c.column_name 	0
24745425	231	getting the nth highest value row in sqlite	select distinct someattribute from mytable order by 1 desc limit 1 offset 4 	0
24747749	20089	mysqli return data in multiple rows with same id	select m.id,        max(case when key = 'name' then value end) as name,        max(case when key = 'age' then value end) as age,        max(case when key = 'zip' then value end) as zip from members m group by id; 	0.000104757904001022
24750260	24017	query to pull second smallest id	select     id,     case_id from (     select          *,         row_number() over(partition by case_id order by id) rn     from customer )x where rn=2 	0.00015289377473153
24756413	7556	change the time and date format in mysql	select date_format(login_timestamp,'%d %m %y %h:%i') from table_name; 	0.00597677768065039
24756968	7368	mysql select query display in php	select * from paper where question = '$row['question']' and exam_id = '3' if($select) {     ************************* show result ********************* } 	0.0284899026715307
24758556	39311	how to sort based on date-like substring?	select * from emp order by left(parsename(replace(date,'/','.'),2),2) 	0.00352585770512733
24759157	6078	transact-sql ambiguous column name	select a.artist,c.album_title,t.track_title,t.track_number,c.release_year,t.ean_code from artists as a inner join cd_albumtitles as c on a.artist_id = c.artist_id inner join track_lists as t on c.title_id = t.title_id where t.track_title = 'bohemian rhapsody' 	0.437713387165398
24759257	363	comparing dates in sql server	select count(*)  from db  where exp_date < dateadd(month, -1, getdate()) 	0.0556800248138401
24759544	38372	selecting items from multiple tables with different where statement	select o.site                       as "site",         count(oi.line_code)          as "no. order lines",         count(distinct oi.line_code) as "no. order lines (unique)",        (select count(o2.order_no)          from   orders o2           where  o2.site = o.site and o2.date_created between '01-jul-13' and '1-jul-14'           group  by o2.site)  as "no. orders"  from   order_items oi,     orders o  where  oi.order_no = o.order_no     and oi.order_type = o.order_type     and oi.site = o.site     and o.despatched_on_date between '01-jul-13' and '01-jul-14'  group  by o.site; 	0.000168411003176318
24760228	7511	use "between" with select for "dates"	select * from produit where date_format(date_commande, '%y-%m-%d) between $filtre_date1 and $filtre_date2; 	0.054342895236096
24761779	22242	foreach non-unique rows to obtain a related key	select * from qtz_users u inner join memberships m on u.uuid = m.uuid inner join groups g on m.group_id = g.group_id inner join (      select m.uuid, max(g.priority) as max_priority     from memberships m     inner join groups g     on m.group_id = g.group_id     group by m.uuid ) sub0 on m.uuid = sub0.uuid and g.priority = sub0.max_priority 	0.000849356231935332
24762519	7768	how to show records which were created within 10mins apart	select name,        title,        created from   table where createdby  = 'billy'   and created between dateadd(minute,-10,getdate()) and getdate(); 	7.48223938564196e-05
24762716	2519	how do i get the latest set id in a mysql db table without sacrificing integrity?	select last_insert_id() 	0
24762920	8387	t-sql in php with pdo	select   courses.coursename, classes.classid,    classes.classstartdate, classes.classenddate,   (convert(nvarchar(max),classes.classstarttime, 0)      + ' - '      + convert(nvarchar(max),classes.classendtime,0)) as timerange,    classes.location, classes.classtype, courses.courseinfolink   ... 	0.760343386614345
24763249	5109	summing up the rows in access vba	select a,b,c,sum(profit)  from tablename  group by a,b,c order by a 	0.171649656792931
24763428	31397	using distinct and coalesce together using variable	select @data = coalesce(@data + ',', '') + column2 from (   select distinct column2   from table   where column1= 'diu02' ) t 	0.764928442485366
24763991	36504	create xml file in sql server 2012	select c.numberofcourse,        c.numberofsemestercredit from courses as c for xml path('students') 	0.76090283816284
24764068	29035	use selected value as a parameter	select a.[post link],     a.score,     a.upvotes,     a.downvotes,     (15 + (([upvotes] * 10) - ([downvotes] * 2)))as [answerer's reputation] from(select top 25 p.id as [post link],                   p.score as score,                   (    select count(*)      from votes     where postid = p.id       and votetypeid = 2)as [upvotes],                   (    select count(*)      from votes     where postid = p.id       and votetypeid = 3)as [downvotes]      from posts q           inner join posts p on q.acceptedanswerid = p.id     where p.posttypeid = 2)a  order by a.score asc; 	0.105650138588358
24764264	12053	modifying or sorting the with rollup row	select id, max(datediff(now(), date)) as date, sum(qty) as qty from item group by id with rollup; 	0.638976724120666
24765483	15277	how find values not duplicate in mysql	select u.*  from users as u join ( select email from users group by email having count(1) = 1) as dt on u.email = dt.email 	0.00299345166889696
24766407	38512	sql to select questions user didn't answer	select question_id from question q where not exists(select * from answer a where a.question_id = q.question_id); 	0.141745542739055
24766413	262	find a record with a key closest to a give value	select * from mytest order by abs( .0750 - probability ) limit 1 	0
24767679	4805	select top 10 salary from employees table	select * from ( select first_name, salary  from employees order by salary desc ) where rownum <= 10 	0
24767814	14352	get max value from one column and min from another column	select tbl1.stage_level_id, tbl1.max_value, min(s.moves) as moves from  (   select stage_level_id, max(value) as max_value   from scores   group by stage_level_id ) tbl1 left join scores s on tbl1.stage_level_id = s.stage_level_id and tbl1.max_value = s.value group by stage_level_id 	0
24767971	31204	sql server extract ints from varchar	select top 10000 convert(int, customertoken) as customertoken from customer where (customertoken not like '%[^-+ 0-9]%'  and replicate('0', 20- len(customertoken)) + customertoken < '0000000000214783647') 	0.0153702932590698
24768417	27803	query database base on tag	select * from your_table where find_in_set('tag3', tag_name) > 0 	0.0468785262103312
24769339	565	counting from multiple tables and return all count values in one query slow	select p.*, c.cnt as commentcount, l.cnt as likecount, v.cnt as viewcount, from post p left join      (select c.postid, count(*) as cnt       from comment c       group by c.postid      ) c      on p.id = c.postid left join      (select l.postid, count(*) as cnt       from like l       group by l.postid      ) l      on p.id = l.postid left join      (select v.postid, count(*) as cnt       from view v       group by v.postid      ) v      on p.id = v.postid group by p.id order by postcount desc; 	7.16761470634164e-05
24769974	14378	find rows where value in column not found in another row	select t1.key1, t1.key2, t1.type from table1 t1 left join table1 t2            on t1.key1 = t2.key2            and t2.type = 'typeb' where t1.type = 'typea'        and t1.key2 is null        and t2.key1 is null 	0
24770904	8824	c# mysql stored procedure insert return value	select row_count() 	0.120512603984712
24771387	20149	how can i calculate columns when using grouping sets	select    store,    product,    fiscalmonth,    fiscalyear,    sum(amount),    (-100 * ((isnull((select sum(amount) from sales where fiscalyear = convert(varchar(20),(convert(int, s.fiscalyear) - 1)) and fiscalmonth is null group by fiscalyear),0) -    case when fiscalmonth is null then sum(amount) else null end  ))) as diff from sales group by store, product,      grouping sets(                   (fiscalyear, fiscalmonth, product),                   (fiscalyear, product)                  ) 	0.00656660048881599
24772010	29424	sql server order by part of string	select yearlevel from student group by yearlevel  order by      (case          when yearlevel like 'year%'         then 'year' + convert(varchar,len(yearlevel)) + yearlevel         else yearlevel     end) 	0.0957019051518744
24772099	9791	if a where clause applies to multiple rows, are all rows tested?	select p.* from projects p where not exists (select 1  from assignments a  where p.id = a.project_id and a.status <> 'paid' ) and p.archived='n'; 	0.00110357437497331
24773092	3001	mysql: return all rows of table a and true|false if record exists in table b	select sales_cat.id_cat, sales_cat.name,case when user_cat.id is null then 0 else 1 end as "selected" from  sales_cat left join user_cat on  user_cat.id_cat = sales_cat.id_cat and  user_cat.id_user = 4 	0
24774076	24194	custom date time formats in sql query	select convert(varchar(8), getdate(), 1)+ ' '+  + right(convert(varchar(20), getdate(), 100),7) as [mm/dd/yy hh:miam (or pm)] 	0.196348531993313
24774567	27070	how to query a (almost) tree structure	select id, parent_id, level from ( select aid id, case when adate = to_date('9999','yyyy') then null else rid end parent_id from (select    c.aid,    c.rid,    c.adate,    nvl(b.d,to_date('9999','yyyy')) bdate from (select a.id aid, a.rid rid, nvl(d,to_date('9999','yyyy')) adate from a, b where a.id = b.id) c, b where c.rid = b.id ) where adate < bdate or adate = to_date('9999','yyyy') )   start with id =1   connect by prior id = parent_id order by id 	0.16956747739214
24776794	7800	display different rows of a record in a single row having all the column values	select ordernumber, max(salesnumber), max(successfail) from yourtable group by ordernumber 	0
24776815	14585	sql union: merge select results with direct values	select p.* from   part p where  p.id in( 'abc', 'def' ) union select p.* from   component c join   part2components pc   on   pc.component_id = c.id join   part p   on   p.id = pc.part_id where  c.id in( 'abc', 'def' ); 	0.0160242788183679
24779783	35992	retrieve count for each id based on a filter in mysql	select id,         sum(val_1 > 0 or val_ > 0) as count from your_table group by id 	0
24780304	37930	get only rows that nearest lower in y column to x column	select x, max(case when y <= x then y end) as y from table t group by x; 	0
24782455	10539	link event with date to event with date in sql	select event_id, datetime, 111 as event_id,        (select top 1 datetime         from table t2         where t2.event_id = 111 and               t2.datetime > t.datetime         order by t2.datetime        ) as datetime from table t where event_id = 110; 	0.00461324846058255
24782781	22972	output of csum() in teradata	select row_number() over (order by column(s)_with_a_low_number_of_rows_per_value)    + coalesce((select max(seqnum) from table),0)    ,.... from table 	0.499801781032792
24784035	9010	multiple row in a single row mysql	select  name, material,         sum(case when trnid = 1 then quantity else 0 end) as purchaseqty,         sum(case when trnid = 2 then quantity else 0 end) as issueqty from transactions t join      item_master im      on t.material = im.id group by name, material limit 0 , 30; 	0.000485337176792973
24784970	1826	sql case with 2 conditions	select * from emptable order by case when @sortcolumn 'first_name' and @sortorder = 'ascending' then fname end asc, case when @sortcolumn 'first_name' and @sortorder = 'descending' then fname end desc 	0.652823742092774
24785418	24410	sql users searching query	select * from  `users` where (        (firstname like '%mat%' or lastname like '%mat%' or         phone like '%mat%' or email like '%mat%' or username like '%mat%')        and        (firstname like '%h%' or lastname like '%h%' or         phone like '%h%' or email like '%h%' or username like '%h%')        and        (firstname like '%50%' or lastname like '%50%' or         phone like '%50%' or email like '%50%' or username like '%50%')        and        (firstname like '%@l%' or lastname like '%@l%' or         phone like '%@l%' or email like '%@l%' or username like '%@l%')        and        (firstname like '%d%' or lastname like '%d%' or         phone like '%d%' or email like '%d%' or username like '%d%')       ) 	0.185924279154774
24785575	12466	cant select data from two tables using mysql	select date, total, null as nettotal from sales union select date, null, nettotal from receipt 	0.0116575739440193
24787478	35682	sql: grouping results by the date	select date(eventtime) as eventtime,        sum(case when inteam = 'true' then points end) as in_team_points,        sum(case when inteam = 'false' then points end) as not_in_team_points from your_table group by date(eventtime) 	0.028937861707055
24789173	28162	sql: grouping by 2 columns	select date(event_time) as event_date,        name,        sum(points) as total_points from points group by date(event_time), name 	0.00970997687917775
24789678	6483	get the sum() of a count(*)	select numactions, count(*), min(username), max(username) from (select username, count(*) as numactions       from actions       group by username      ) a group by numactions order by numactions; 	0.000882586273113681
24789890	12416	mysql - how to join/union these two selects to make a single query?	select * from heartbeat where `imei`=123456789012345 and `datetime`<="2014-07-16 12:00" join (select * from heartbeat where `imei`=123456789012345 and `datetime` between "2014-07-16 12:00" and "2014-07-17 15:00") union select * from heartbeat where `imei`=123456789012345 and `datetime`<="2014-07-16 12:00" union (select * from heartbeat where `imei`=123456789012345 and `datetime` between "2014-07-16 12:00" and "2014-07-17 15:00") 	0.0695973332929899
24791246	1062	sql server : query help on how to find oldest value?	select min(created_time)  from dbo.files 	0.0518014357391176
24791464	5743	digits after first dash on oracle sql	select substr(col, 1, instr(col, '-') - 1) ||        substr(col, instr(col, '-'), 7) as result   from tbl 	0.00628384617938707
24792821	7494	using subqueries to select a count mysql	select   matchid, team, sum(win) as wins from     poolofteams group by matchid, team order by team asc 	0.422587446299809
24793659	19025	sql server find highest balance from transactions	select distinctdays.customerid,distinctdays.transdate,totalamount=sum(totalamount.transamount) from (     select customerid, cast(chargedate as date) as transdate from charge     union      select customerid, cast(adjustdate as date) from adjustment          union      select customerid, cast(paymentdate as date) from payment )as distinctdays inner join (     select customerid, amount as transamount, chargedate as transdate from charge              union all     select customerid,  amount, adjustdate from adjustment          union all     select customerid,amount, paymentdate from payment )  as totalamount on totalamount.customerid=distinctdays.customerid and totalamount.transdate<=distinctdays.transdate  group by distinctdays.customerid,distinctdays.transdate order by distinctdays.customerid,distinctdays.transdate 	0.00100509627506192
24794859	5563	mysql subquery and joining 3 tables	select u.*, es.email_reply_on_comment from users u inner join   (select submissions_comments.parent_id from submissions_comments where id = 96) x on u.id = x.parent_id left join email_settings es on es.id = u.id; 	0.152243938876047
24795043	11484	how select data from two table with mysql	select date, total, nettotal from (select date, total, null as nettotal, 2 as sort_col from sale union all select date null as total, nettotal, 1 as sort_col from receipt) as a order by date desc, sort_col desc 	0.000810314272482833
24795310	5079	how to make sum of each person individually	select   remoteemployees.remoteemployeeid,      remoteemployees.bank,      remoteemployees.beneficiaryname,      remoteemployees.accountnumber,      sum(transactions.amountpayable) as totalpayment,      transactions.remoteemployeeid      from remoteemployees, transactions where       remoteemployees.remoteemployeeid = transactions.remoteemployeeid      group by remoteemployees.remoteemployeeid 	0.000287446584908231
24795592	44	how to make a custom sort order in mysql and check the beginning of the strings?	select * from `videos` order by case  when `videoid` like 'geo%' then 3 when `videoid` like 'g%' then 1 when `videoid` like 'f%' then 2 when `videoid` like 'tri%' then 4 when `videoid` like 'pr%' then 5 when `videoid` like 'vek%' then 6 else 0 end 	0.000776627466822524
24796120	25434	using a calculated value in two places in a postgresql query	select distance, distance/1000 as distance_in_km from  (     select           st_distance(             st_geogfromtext(             'srid=4326;point(' || longitude || ' ' || latitude || ')'         ),         st_geogfromtext('srid=4326;point(1 1)')     ) as distance, id from locations limit 10 ) t; 	0.00287612415729898
24798178	303	sql add a column using left join in a view	select    a.*,            case when a.name is not null and b.id is null                 then 'yes'                 else 'no'            end as is_true from      employee a left join (select distinct id from manager) b on a.id = b.id 	0.449866350870857
24799521	15492	sql sub query splitting results into two rows	select    `week no` ,      date  ,   `v name`, `vy id`,  `gbp t2`, max(`gcp 2.1`), max(`gcp 2.2`)  from (  group by  `week no` ,      date  ,   `v name`, `vy id`,  `gbp t2`; 	0.00492926770678494
24801303	13299	mysql query select sum() only if condition met group by	select sum(moguci_dobitak)  from matches  where rezultat='win'  and month(date) = month(now()) and year(date) = year(now()) group by user 	0.0144208763745719
24801678	31155	inner join same table for values	select d.value_text from dynamic d  inner join dynamic dv on d.object_id = d.object_id and d.field_id = "13" and dv.field_id = "11"  and (dv._obejct_id = "infra" or dv._obejct_id = "hr") 	0.0223372708397208
24802310	31823	using parent field in subquery	select    o.invoice_date,   o.invoice_number,   (        select round(sum(od.product_price * od.tax_rate / 100), 2)       from order_detail od       where od.id_order = o.id_order   ) as `tax` from `order` o where o.invoice_number != 0 	0.12141917767436
24805910	5874	mysql php - select where id = array()	select     product_id from      your table where     category_id in (1, 2, 4) group by     product_id having     count(distinct id) = 3; 	0.026215620256407
24806752	1322	how could i remove rows in a sql query with same value if a certain variable searched was not found?	select part      , max(case when var = 'make' then value end) make      , max(case when var = 'model' then value end) model      , max(case when var = 'year' then value end) year   from attr  group     by part; 	0.000236102806129773
24807714	14321	sql server - counting records with same value across all columns	select id, count(*) from info_table where coalesce(question1, question2, question3, question4, question5) = coalesce(question2, question3, question4, question5, question1) and       coalesce(question1, question2, question3, question4, question5) = coalesce(question3, question4, question5, question1, question2) and       coalesce(question1, question2, question3, question4, question5) = coalesce(question4, question5, question1, question2, question3) and       coalesce(question1, question2, question3, question4, question5) = coalesce(question5, question1, question2, question3, question4) group by id; 	0
24808682	16191	how to transform (select) rows of different types in new columns?	select      type1.type,     type1.value,     type2.type,     type2.value,     type1.loc_x,     type1.loc_y from      (select * ,              coalesce((select 0                       from sample as sample_t                       where                           sample_t.id < sample_a.id                             and                          sample_a.loc_x = sample_t.loc_x                            and                           sample_a.loc_y = sample_t.loc_y                            and                           type = 1                       limit 1), 1) as is_first       from sample as sample_a      where type = 1) as type1     left join     (select *      from sample      where type = 2) as type2     on          type1.loc_x = type2.loc_x         and type1.loc_y = type2.loc_y         and type1.is_first = 1 	0
24810546	691	is there a way to join two tables based on a column that is modified within the query?	select _id, linked_to from tablea join tableb on tablea._id = (tableb.linked_to - 1000000000) 	5.47805492115715e-05
24811109	33771	group by max(time) mysql	select func_id,checksum from content cnt  inner join (   select func_id, max(timestamp) as maxdate   from content group by func_id ) as max on (cnt.func_id=max.func_id and max.maxdate=cnt.timestamp); 	0.568437651174396
24811624	24264	comparing date ranges in sql for specific entries	select * from vt as t1 where exists  ( select * from vt as t2    where t1.id = t2.id      and t1.pk <> t2.pk       and t1.end_date >= t2.start_date     and t1.start_date <= t2.end_date   ) 	0
24812263	30180	convert time from seconds to hours, with rounding	select cast(c.periodlength / (60.00*60) as decimal(6, 2)); 	0.000224515452325009
24813842	17740	get most recent 8pm via sql	select (case when datepart(hour, getdate()) >= 20              then cast(cast(getdate() as date) as datetime) + 20.0/24              else cast(cast(getdate() - 1 as date) as datetime) + 20.0/24         end) 	0.000404749461230323
24815503	8726	trying to count the duplicate entries in a table using pl/sql	select sum(totalcount) from (select print_number, count(print_number) as totalcount       from ls_print_queue       where event_id = 11862       group by print_number       having count(print_number) > 1       ) t 	0.000134705120386945
24817694	2805	single inner join with max condition	select a.id1, b.id2, max(b.data2) from a inner join b on a.id1 = b.id2 group by a.id1, b.id2 	0.496037190486219
24819250	8937	field list in ambiguous in join with 4 tables	select sub.user_id,... 	0.095015629009712
24822657	30606	how to perform two count(*) fetches in one query?	select sum(if(`string` like '%three%', 1, 0))/count(*)   from `table` 	0.0173305723454098
24823707	24601	get all referees referred from usernames with same ip. members can have more than one account	select distinct(u.username) from yourtable u inner join yourtable r on (r.username = u.referee and r.ip = 'theip'); 	0
24825660	33854	mysql - return login attempts by intervals	select    sum(if(secs_ago<=300, 1, 0)) as attempts_in_last_5,   sum(if(secs_ago<=600, 1, 0)) as attempts_in_last_10,   sum(if(secs_ago<=900, 1, 0)) as attempts_in_last_15 from (   select     unix_timestamp(now()) - unix_timestamp(attempt_date) as secs_ago   from er_login_attempts   where target_email='mail@mail.com'   and inet_aton('1.11.11.111')=ip_from   and attempt_date>now() - interval 15 minutes ) ilv; 	0.0194647952813297
24827622	24431	locate rows that have the same resource key (with different .endings) and same values	select w.resource, watermark value  from  (   select      parsename(resourcekey, 1) as resource,      value as watermark   from      mytable   where     value like '%.watermark'  ) w   join  (   select      parsename(resourcekey, 1) as resource,      value as txt   from      mytable   where     value like '%.text'  ) t  on t.resource = w.resource   where     watermark = txt 	0
24828305	7722	sql full join priority	select coalesce(a.id,b.id,c.id) from      tablea a full join tableb b on a.id = b.id full join tablec c on a.id = c.id select coalesce(a.id,b.id,c.id) from      tablea a full join tableb b on a.id = b.id full join tablec c on b.id = c.id select coalesce(x.id,c.id)  from ( select    coalesce(a.id ,b.id) id   from      tablea a   full join tableb b on a.id = b.id) x full join   tablec c on x.id = c.id 	0.669930201766407
24828536	28151	sql select query trouble with unique values	select [master record].[family id], max([master record].[last name]) as [maxoflast name],  max([master record].[address 1]) as [maxofaddress 1], max([master record].[address 2]) as  [maxofaddress 2], max([master record].city) as maxofcity, max([master record].state) as  maxofstate, max([master record].zipcode) as maxofzipcode, max([family members].email) as  maxofemail from [master record] left join [family members] on [master record].[family id] = [family  members].[family id] group by [master record].[family id] having (((count([family members].email))=0)); 	0.178660547962629
24828635	10129	how get max value from result of group_concat mysql	select   user_id,   max(id) as id,   substring_index(group_concat(comment order by id desc separator '|'), '|', 1) from   userapp_accactivitylog group by user_id; 	0.000213378203857127
24829447	29914	select top one record for each unique value of column	select x.*    from my_table x   join       ( select request_id,min(price) min_price from my_table group by request_id )y     on y.request_id = x.request_id    and y.min_price = x.price; 	0
24830006	37497	sql - creating a filter for only a subgroup without using where for that subgroup	select t2.* from nba.player_stats t1 inner join nba.player_stats t2 on  t1.date = t2.date and t1.tm = t2.tm where t1.player = 'courtney lee' 	0.0985713051503173
24830162	33533	combining like minded entries in sql	select item, sum(quantity) as totalquantity from {tablename} group by item; 	0.0510007636039434
24830555	22336	mysql - conditional group by	select col1,col2,etc... from table where acct_num not in ( select multisite.es_acct_num from ( select acct_num as es_acct_num,        count(distinct p.id) as `cnt` from blah, blah, blah group by es.acct_num having `cnt` > 1) as multisite) union select col1,col2,etc... from table where acct_num in ( select multisite.es_acct_num from ( select acct_num as es_acct_num,        count(distinct p.id) as `cnt` from blah, blah, blah group by es.acct_num having `cnt` > 1) as multisite) group by es.acct_num  	0.734866687305413
24833254	6847	how can i query table within table?	select   case when c.clientid <> @clientid then c.name else '' end as clientname,   case when c.clientid <> @clientid then @clientid := c.clientid else '' end as clientid,   p.contactid,   p.name as contactname from   clients c   inner join contacts p on p.clientid = c.clientid   , (select @clientid := -1) x order by   c.clientid, p.contactid 	0.0453863292076901
24834800	646	need different return format from postgres function	select * from store_reward_transaction(4,'blah') f(count bigint, last_update timestamp with time zone); 	0.0241407755910328
24834975	9025	count of weekdays in a given month	select     datename(dw, date) as weekday     ,date     ,row_number() over (order by date) as day from datetable where datepart(dw, date) not in (1, 7) order by date 	0.000111538331388818
24837969	11110	how to add arbitrary values, not present in the database, to selected rows in mysql select?	select id,name,nationality,( case nationality  when 'british' then 'hamburger'  when 'german' then 'sauerkraut'  when 'korean' then 'soup'  else null end) as 'favorite_food' from user 	0
24839080	32665	how do i connect two tables using the concept of foreign key and primary key?	select * from `post` inner join `comments` on `post`.`id` = `comments`.`post_id` 	0
24839951	7688	how to select rows based on two columns	select id from table where page = 1 or (page = 2 and weight <= 1) 	0
24840084	6839	t-sql 2008 insert dummy row when condition is met	select n.name, v.version, coalesce(de.payment, 0) as payment from (select name, max(payment) as maxpay from dataextract group by name) n cross join      (select distinct version from dataextract) v left outer join      dataextract de      on de.name = n.name and de.version = v.version where de.name is not null or n.maxpay > 0; 	0.22268526481012
24841299	19906	how to left join another nested table?	select * from  (     select *     from category as a     where a.type = 'content' ) a left join                               (     select*     from content as c     left join article_has_content as x     on x.content_id = c.content_id     where x.article_id = '4' ) b                                     on b.category_id = a.category_id 	0.324461001201515
24842604	25551	using group by in a sql query for remuving duplicates	select  o.name, o.family, o.phone, o.objectid, o.owner_id, l.licence_contex, l.licence_title, l.id  from  [dbo].[owner_licence] as l join [dbo].[owner] as o on o.[owner_id] = l.[owner_id] join (select      max(ol.id) max_lid,     ol.owner_id from     owner_licence ol where ol.id not in (select l.id from [dbo].[owner_licence] as l,[dbo].[owner] as o          where o.[owner_id] =l.[owner_id]          and (l.registration_date1  > dateadd(year, -1, getdate())          or l.[registration_date2]> dateadd(year, -1, getdate())          or l.[registration_date3]> dateadd(year, -1, getdate())          or l.[registration_date4] > dateadd(year, -1, getdate())          or l.[registration_date5]> dateadd(year, -1, getdate()))) group by     ol.owner_id) t1 on t1.owner_id = o.owner_id and t1.max_lid = l.id 	0.77386514576649
24844496	468	get distinct rows along with sum of field - mysql	select t.*,  (   select sum(count)     from table1    where hash = t.hash ) total   from table1 t 	0
24845094	1544	sql : select record by passing a date within the range	select * from mytable where '2014-01-16' between `from` and `to` 	0.000240368438696561
24845109	37911	how to get a daily sum of numbers with mysql?	select   sum(`points`) as points, `date` from     users group by `date` 	5.9802188357207e-05
24845442	34391	average of sums in mysql	select sum(onhand) / count(distinct branchnum) as avg_per_branchnum from atablelikethis; 	0.00307252177056935
24845662	11766	sql count the number of foods supplied by each supplier even if they did not supply anything	select      a.supplier_id ,     b.supplier_name ,     count(a.supplier_id) as "number of foods"  from       l_suppliers b ,      left join  l_foods a on  a.supplier_id = b.supplier_id       group by  b.supplier_id ,b.supplier_name      order by  b.supplier_id 	0.000111588400068888
24848412	27706	joining a table of properties as columns and values?	select * from persons left outer join person_properties p1 on persons.person_id = p1.person_id and p1.key = 'age' left outer join person_properties p2 on persons.person_id = p2.person_id and p2.key = 'weight' 	0.000296746523740571
24849829	5426	mysql query with select all and select sum	select *, (select sum(score) from student) as score_sum from student 	0.0265681465313432
24850723	7968	mysql - output of sum as one of the rows in one field in a single table	select id,subject,max(score) as 'score',max(mm) as 'fm' from tbl1 group by subject union all (select distinct id, 'test' as subject, (select sum(score) as 'score' from (select distinct score from tbl1 where enna='test')t1) , (select sum(mm) as 'fm' from (select distinct mm from tbl1 where enna='test')t2) from tbl1 where enna = 'test') ; 	0
24851214	70	mysql query select depending on 2 tabels	select i.* from ex_instagram_p i join      exchanges e      on i.id = e.exid where i.type = '".follow."' and i.active=1 and       i.username <> '".$username."' and e.user = '".$username."' order by i.cpc desc limit 1; 	0.00712082994971816
24852347	30639	grouping multiple rows of addresses to show latest row only	select checkin_id,        checkin_client_id,        checkin_inventory_id,        checkin_property_id,        checkin_date,        client_username,        property_address_line_1,        property_town,        property_county,        property_postcode,        property_type,        property_rooms,        client_first_name,        client_last_name,        client_organisation_name,        client_unique_id,        checkin_passcode   from check_in ci  inner join properties pr     on ci.checkin_property_id = pr.property_id  inner join clients cl     on ci.checkin_client_id = cl.client_id  where checkin_date =        (select max(ci2.checkin_date)           from check_in ci2          where ci2.checkin_property_id = ci.checkin_property_id)    and (client_unique_id like ? or client_first_name like ? or        client_username like ? or client_organisation_name like ? or        property_address_line_1 like ?) 	0
24852392	34742	how do i select 5 random rows from the 20 most recent rows?	select foo.* from (select * from table order by date desc limit 20 ) as foo           order by rand() limit 5 	0
24853343	9981	oracle sql find project with most hours logged multiple entries for hours	select p.pname, sum(wh.hours) as sum_hours from projects p  join workers_hours wh on p.pnum = wh.pnum group by p.pname   order by sum(wh.hours) desc 	0
24853594	26876	how to return the row with the data all are null if an empty result set?	select t2.* from (select 1) t1 left join article t2 on t2.id = 2 	0
24853620	7398	ms access - how to add incremental values to groups in table	select x.id, x.group_id, x.itemname, count(y.id) as sort, x.type   from tbl x   left outer join tbl y     on x.group_id = y.group_id    and y.id < x.id  group by x.id, x.group_id, x.itemname, x.type 	0.0011031202834439
24853733	21549	mysql single query possible?	select name,         (avg (avg (q1) + avg(q2) + avg(q3) / 3) as average,        (avg (avg (case when q35 = 1 then q1 else 0 end) +              (avg (case when q35 = 1 then q2 else 0 end) +              (avg (case when q35 = 1 then q3 else 0 end) / 3) as q35_average from tresults  group by name  order by name 	0.278597660960253
24854343	4344	find difference in 2 tables / recordsets mysql	select a.user_id,        case when a.name1 <> b.name1 then concat(b.name1,' changed to ',a.name1) else null end as name1_chg,        case when a.name2 <> b.name2 then concat(b.name2,' changed to ',a.name2) else null end as name2_chg,        case when a.lastname <> b.lastname then concat(b.lastname,' changed to ',a.lastname) else null end as lastname_chg   from tablea a   join tableb b     on a.user_id = b.user_id  where b.lastupdate = (select max(x.lastupdate)                          from tableb x                         where x.lastupdate < a.lastupdate and x.user_id = a.user_id) 	0.00206646598639177
24854451	5765	sql - join on table with duplicate keys	select a.customerkey, b.info1, b.info2, b.info3   from accounts a   join customer b     on a.customerkey = b.customerkey  where acckey in (1, 2, 3)    and b.dayofupdate =        (select max(x.dayofupdate)           from customer x          where x.customerkey = b.customerkey) 	0.0166107116651638
24854477	37880	joining multiple sql queries together into one row	select p.id, p.name, p.img, p.template_id, t.tpl_name from platforms as p, templates as t where p.template_id = t.id; 	0.000822015138584628
24854822	1089	how fetch the first record after every record that has specific attribute set in postgresql?	select id, factor, created_at   from (select id,                factor,                created_at,                lag(factor, 1) over(order by created_at) as prev_factor           from tbl          order by created_at) x  where factor is null    and prev_factor is not null 	0
24855647	9353	split an mysql column value into 2 columns based on regex	select  substring_index(value,' ',length(value) - length(replace(value, ' ', ''))) as value,  substring_index(value,' ', -1) as num from tbl; 	0
24857868	16369	track number of rows in a #table which the population is in progress	select count(*)  from ##yourtablename with(nolock) 	0.000102425870752396
24858208	20608	cummulative to differential data in mysql table	select driver, reportdate, distance_since_last from (     select t1.driver,      t2.reportdate,     if(@prevtaxi = t2.taxi,         t2.distance_in_km - @prevdistance,         t2.distance_in_km) distance_since_last,     @prevtaxi := t2.taxi,     @prevdistance := t2.distance_in_km     from table1 t1     join table2 t2 on t1.taxino = t2.taxi     cross join (select @prevdistance := 0, @prevtaxi := 0) t3     order by taxi, reportdate ) t1 	0.0911042529191227
24859294	25347	yii - select first five records for each type field ordered by date	select t.id,         t.name,         t.content,         i.item,         c.context from (select tbl.id,             tbl.name,             tbl.content,             tbl.owner_id,             tbl type_id,             case                  when tbl.type_id = @category then @rownum := @rownum + 1                 else @rownum := 1             end as num,             @category := tbl.type_id         from advertisements tbl         join (select @rownum := 0, @category := null) r         order by tbl.type_id, tbl.create_date desc) t left join items i on t.type_id = i.id left outer join comments c on c.topic_id = t.id where t.num <= 5 	0
24859561	35517	count number of foreign key columns, ignore system tables, display against each tablename	select kc.column_name, t.table_name, tc.constraint_name from information_schema.table_constraints tc left join information_schema.tables t on tc.table_name = t.table_name left join information_schema.key_column_usage kc on kc.constraint_name = tc.constraint_name where constraint_type = 'foreign key' and table_type = 'base table' 	0
24859947	6940	sql select distinct confusion	select  id, title, photo from mytable group by title; 	0.742036785711153
24860708	4321	retrieve combination of composite key	select distinct `start`,`end` from table_name; 	0.00188878342303269
24860843	2784	select by age and gender	select  agegroup, gender, count(*) as count, round(sum( 100 ) / total) as percentage     from    (     select  case             when  age between 0 and 17 then '00 - 17'             when  age between 18 and 24 then '18 − 24'             when  age between 25 and 34 then '25 − 34'             when  age between 35 and 44 then '35 − 44'             when  age between 45 and 54 then '45 − 54'             when  age between 55 and 64 then '55 − 64'             when  age between 65 and 125 then '65+'             else 'unknown'             end as agegroup, gender     from    (             select  round(datediff(cast(now() as date),                         cast(dateofbirth as date)) / 365, 0) as age,                          gender             from    people             ) as subqueryalias     ) as subqueryalias2     cross join (select count( * ) as total from people)x     group by     agegroup, gender 	0.0489802787691082
24861363	31249	mysql, get the three clients who have the max purchases:	select client.name from client join purchase on purchase.client_id = client.client_id join product on purchase.product_id = product.product_id and product.product_id = 1 group by client.client_id order by count(purchase.purchase_id) desc limit 3 	0
24862626	18473	return one row for each customer mysql	select email_address, sum(quantity * item_price), sum(discount_amount * quantity) from customers join order_items on customers.id= order_items.id group by (email_address) order by sum(quantity * item_price) 	0
24863846	11497	sql query select record with max	select * from tbl a where a.quantity=     (select max(b.quantity) from tbl b where a.customerid=b.customerid) 	0.0489357118913329
24864127	16930	how to select all the duplicates except one?	select d.c_emailaddress, d.c_datasourceid, d.c_datecreated from duplicates as d where d.c_datecreated !=      (select max(d2.c_datecreated)       from duplicates d2       where d2.c_datasourceid = d.c_datasourceid and           d.c_emailaddress = d.c_emailaddress) 	0.000197511274991087
24865156	26652	sql: grouping by number of entries and entry date	select event_date,   sum(case when cnt between 0 and 2 then 1 else 0 end) as "0-2",   sum(case when cnt = 3 then 1 else 0 end) as "3",   sum(case when cnt between 4 and 99 then 1 else 0 end) as "4-99" from      (select cast(event_time as date) as event_date,        name,       count(1) as cnt     from log     group by cast(event_time as date), name) basecnt group by event_date order by event_date 	0
24865619	17909	table data count max val	select machine,sync,       sum(if(laststatus='completed', 1, 0)) as generation,       sum(if(laststatus != 'completed', 1, 0)) as pending from machine_status right join (select machine,                     max(packets) as sync              from machine_packets              group by machine) mp on mp.machine=machine_status.machine group by machine 	0.0155526060692093
24865725	4560	how to perform not equal to function using joins in 2 tables	select * from usr left outer join mat on usr.uid = mat.did where did is null 	0.736936940710202
24866195	25121	oracle date/time manipulation query	select to_number(extract(hour from result_date)) as hour , type , count(id) as number from results where to_date(trunc(result_date)) = to_date(trunc(current_timestamp))         and to_number(extract(hour from result_date)) between 6 and 14                  group by  to_number(extract(hour from )result_date) as hour  , type 	0.637616724844049
24869250	31244	trouble accessing mysql database and printing out matching results	select link from `radar3` where `name` = '$fname' 	0.0730919095095707
24869966	21762	sql group data ?combine?	select petid1, petid2, (a.total + b.total) as combinedtotal from     (select petid1, count( * ) as total from cdc_padchat where petid1 !=0 group by petid1) a inner join     (select petid2, count( * ) as total from cdc_padchat where petid2 !=0 group by petid2) b on a.petid1 = b.petid2 order by combinedtotal desc 	0.0735677089996228
24871166	7076	oracle case statement if null select a different table	select sp1.pref_first_name, case when sp1.pref_first_name is null                                   then s1.first_name                                  else  sp1.pref_first_name                              end as "pref_name" from table1 sp1,table2 s1 	0.230110341347062
24871176	2374	select combined fields from a table	select group_concat(`part_number` separator ', ')  from `quote_items` where `quote_id` = '$quote_id'; 	0.0013774403385655
24871334	5127	calculate or setup overlap calculation in ms access	select t1.code as code1, t2.code as code2, count(*) as numoverlaps from table1 as t1 inner join      table1 as t2      on t1.name = t2.name and t1.state = t2.state and t1.code < t2.code group by t1.code, t2.code; 	0.787792252216609
24871500	3399	mysql query for three table with inner join	select images.id, users.name, likes.user from images join users    on users.id = images.user left join likes   on likes.pic_name = images.pic_name  and likes.user = 22 where image.pic_name = 'pic1'; 	0.764866622060683
24871628	30102	sql - finding number of duplicate records for a given day	select nameid from tablename group by nameid, convert(nvarchar(25), datetime, 111) having count(*) > 1 	0
24872074	33884	sql: id & dte are keys in a table, i want to get a table that has only one id and the latest date	select x.id,   max(x.dte) from x group by x.id 	0
24873445	5725	mysql select with grouping by year and month with special order	select events.* from   events inner join (select min(schedule) min_schedule                      from events                      group by year(schedule), month(schedule)) m   on events.schedule = m.min_schedule order by   events.schedule 	0.00368464568210629
24873532	3956	sql query get course number for certain student grades	select s.course_no,        c.descr,        count(distinct g.grade_type_code) as num_grade_types   from grade g   join enrollment e     on g.student_id = e.student_id    and g.section_id = e.section_id   join section s     on e.section_id = s.section_id   join course c     on s.course_no = c.course_no  group by s.course_no, c.descr having count(distinct g.grade_type_code) = (select count(grade_type_code)                                               from grade_type) 	5.51135749863744e-05
24873776	704	mysql: timeline script, add users posts and my own	select relations.friend as uid, users.name, users.email, posts.id as pid, posts.text, posts.date from `relations` inner join `posts` on relations.friend = posts.id inner join `users` on relations.friend = users.id where relations.user = 2 union select users.id as uid, users.name, users.email, posts.id as pid, posts.text, posts.date from `users` inner join `posts` on posts.user = users.id where users.id = 2 	0.0143704073506364
24876467	26057	mysql select data from archive table if not in current table	select l.*,        ifnull(a.first_name,a2.first_name) as first_name,        ifnull(a.last_name,a2.last_name) as last_name,        case when a.id is null then 'archived' else 'active' end as agent_status   from listings l   left join agents a     on l.agent_id = a.id   left join agents_archived a2     on l.agenct_id = a2.id  where l.agent_id = 'xyz' 	0.000141399406585351
24877230	24544	sql to retrieve one of several rows grouped by 1 field while retaining multiple columns	select x.clientid,        x.lastname,        x.firstname,        x.sex,        min(y.dispositionid) as dispositionid,        x.supervisorid   from (select clientid,                lastname,                firstname,                sex,                max(supervisorid) as supervisorid           from tbl          group by clientid, lastname, firstname, sex) x  inner join tbl y     on x.clientid = y.clientid    and x.supervisorid = y.supervisorid  group by x.clientid, x.lastname, x.firstname, x.sex, x.supervisorid union all select x.clientid,        x.lastname,        x.firstname,        x.sex,        min(x.dispositionid),        x.supervisorid   from tbl x  where not exists (select 1           from tbl y          where y.supervisorid is not null            and y.clientid = x.clientid)  group by x.clientid, x.lastname, x.firstname, x.sex, x.supervisorid 	0
24877689	19749	sql match employee intime (punch time) with employee shift	select ads.attendancesumid,        ads.employeeid,        ads.date,        ads.day,        ads.intime,        ads.outtime,        ss.intime,        ss.outtime   from employee_attendance_daily_summary ads   join employee emp     on emp.employeeid = ads.employeeid   join setup_shift ss     on ss.shiftcode = emp.shiftcode    and datepart(dw, ads.date) = ss.day  where ads.employeeid = 4    and ((abs(datediff(hh,                       cast(ads.intime as datetime),                       cast(ss.intime as datetime))) between 0 and 2) or        (ads.intime = '00:00:00' and        ss.intime =        (select min(x.intime)             from setup_shift x            where x.shiftcode = ss.shiftcode              and x.intime > (select min(y.intime)                                from setup_shift y                               where y.shiftcode = x.shiftcode)))) 	0.00303025871670842
24879224	33774	selecting a diff report from one table mysql	select *   from table1 t  where approved = 'no'    and exists (   select *     from table1    where approved = 'yes'      and apples   = t.apples      and bananas  = t.bananas      and oranges  = t.oranges )    and not exists (   select *     from table1    where approved = 'yes'      and apples   = t.apples      and bananas  = t.bananas      and oranges  = t.oranges      and diffval1 = t.diffval1       and diffval2 = t.diffval2       and diffval3 = t.diffval3 ); 	8.13963691404353e-05
24879264	25293	creating custom customer id	select concat ( left(last,3), left(first,1),'_',date); 	0.0182453252033696
24879494	14251	pulling specific data on top and restricting its limit in mysql php	select *    from listing   where makaan_id = 627   order by listing_id desc  limit 4 union all select *    from listing   where makaan_id <> 627      or makaan_id is null  order by listing_id desc  limit {$start} - 4, {$limit} - 4 	0.000186041418321103
24879834	29917	select data from table and sum qty of the same id	select  t1.gest,t2.codintern, sum(t3.rest) as suma   from mydb.t3 inner join mydb.t2 on                mydb.t3.codobiect = mydb.t2.codobiect  inner join mydb.1 on                mydb.t3.codnir=mydb.t1.codnir  where t1.gest=738 and t3.rest>0  group by t2.codintern, t1.gest; 	0
24880031	25483	search by date in mysql using dateformat	select * from employees where '7-2-2014'= date_format(`date_col`,"%e-%c-%y"); 	0.598463277756283
24880669	25341	row act like column database query	select *  from person where exists(select * from personskill where personid = person.id and typeid = 1 and weight>65) and exists(select * from personskill where personid = person.id and typeid = 2 and weight>65) 	0.190234795356447
24880929	29241	select consequence row with changing data	select name, startdate, event from  (     select name, startdate, event,        case           when event =               lag(event) over (partition by name order by startdate)            then 0            else 1         end as flag     from t42  ) where flag = 1 order by name, startdate, event; 	0.0136295599667705
24881215	15699	find % using like	select  *  from    <table> where   <column> like '%[%]%' 	0.302776000554102
24882242	34687	update field that have duplicates on another table	select t1.id, t2.id as newid from team t1       join (select min(id) as id,                   teamname             from team            group by teamname) t2 on t1.teamname=t2.teamname 	9.52898248885914e-05
24882554	26299	sql server : ignore strings in sum function	select sum(case when type_new = 202 and isnumeric(summe + '.0e0') = 1             then summe             else 0          end) as total_euro from tablename 	0.6928449929921
24882899	3516	how to get selected value group set in single query for mysql?	select user_id,group_concat(id separator ",") as sets  from my_table  group by user_id; 	0.000301505285956757
24884237	29748	for the same value it should be incremented by 1 and different it should be reset and gives result	select bpin, name, @value:=if(@bpin=bpin, @value + 1, 1) as value, @bpin:=bpin from  (     select bpin, name     from some_table     order by bpin, name ) sub0 cross join (select @value:=0, @bpin:=0) sub1 	0.0743201522633987
24884390	22606	pattern matching in mysql database query	select *  from table1 join table2 on substring(table1.id, 6) = substring(table2.id, 6) 	0.0809929245503582
24885086	6140	counting 2 fields while grouping by 1	select tmptbl.agent,         count(tmptbl.calls) as countofcalls,         sum(iif([tmptbl].[success]="no",1,0)) as failed from tmptbl group by tmptbl.agent; 	0.00315353873629253
24887488	4173	select if the parent_id is not null	select m1.id, coalesce(m2.content,m1.content) as content from models as m1 left join models as m2 on (m2.id = m1.parent_id) where m1.id = 90; 	0.195774643492488
24887888	24781	how to select unique value with some condition for mysql?	select    user_id,     max(add_date)  from my_table group by user_id having     min(add_date) between '2014-07-21' and '2014-07-22' and     max(add_date) between '2014-07-21' and '2014-07-22' 	0.00315465631255861
24890186	35236	sql query to stop displaying rows x hours after datetime field	select *  from integra_status  where type <> 'maintenance' and category = '".$result["sequence"]."' and ( status = 'open' or (status = 'resolved' and status_closed > date_sub(now(), interval 24 hour))) 	6.26024225233069e-05
24892174	23970	filtering valid date -mysql	select * from table where unix_timestamp(date_input) >0 	0.259462202900464
24892192	32097	sorting with order by in mysql	select logins.* from logins inner join (     select userid, max(`date`) as max_date     from `logins`     where `status` = 'valid'      group by `userid`  ) sub0 on logins.userid = sub0.userid and logins.`date` = sub0.max_date where `status` = 'valid' 	0.510216201754659
24892472	22580	how to retrieves all rows from a subquery	select serielnumber, idmark from marque m join essay e on m.mark=e.mark 	0.000693289258340561
24894783	22565	get all the columns in a database at once in sql/apex	select column_name from all_tab_columns 	0
24895101	12372	how to write a select statement that can match 1 of 3 parameters across multiple tables	select      uid from     users where     uid in (select ur.uid from users_roles ur) or     uid in (select node.uid from node where node.type = <article>) or     uid in (select s.uid from simplenews s) 	0.00271580332738505
24895510	22902	mysql now() query	select * from ps_specific_price where `to` > now() order by `to` desc 	0.340694048819915
24895539	14830	finding and flagging overlapping dates between grouped records using only sql	select *,   case     when exists (       select 1       from table1 t2       where t1.startdate < t2.enddate         and t2.startdate < t1.enddate         and t1.column2id = t2.column2id            and t1.column1id <> t2.column1id       ) then 1     else 0   end as hasdateoverlap from table1 t1 	0
24895944	30774	sql select in list a but not in list b	select distinct `file_id`  from `file_tags`  where `tag_id` in(1,2,3)    and `file_id` not in(       select `file_id`        from `file_tags`        where `tag_id` in(4,5,6)   ) 	0.00589773825219053
24896483	37531	is there a way for viewing the recent expensive queries in sql server 2005?	select top 10 substring(qt.text, (qs.statement_start_offset/2)+1, ((case qs.statement_end_offset when -1 then datalength(qt.text) else qs.statement_end_offset end - qs.statement_start_offset)/2)+1), qs.execution_count, qs.total_logical_reads, qs.last_logical_reads, qs.total_logical_writes, qs.last_logical_writes, qs.total_worker_time, qs.last_worker_time, qs.total_elapsed_time/1000000 total_elapsed_time_in_s, qs.last_elapsed_time/1000000 last_elapsed_time_in_s, qs.last_execution_time, qp.query_plan from sys.dm_exec_query_stats qs cross apply sys.dm_exec_sql_text(qs.sql_handle) qt cross apply sys.dm_exec_query_plan(qs.plan_handle) qp order by qs.total_worker_time desc  	0.453335194048092
24897127	20314	sql . timestamp issue with max value	select value, timestamp, fooditem, cashcurren   from farm1 f  where timestamp between 1405987200 and (1405987200 + 86400)    and fooditem = '2'    and cashcurren = '10'  where value =        (select max(x.value)           from farm1 x          where x.timestamp between 1405987200 and (1405987200 + 86400)            and x.fooditem = f.fooditem            and x.cashcurren = f.cashcurren) 	0.176356297818618
24897189	22003	how to get average of each player in recent 5 games	select t.`player name` , avg(time_to_sec(t.`total on court`))  from ( select s.*, @rank:= case when @group = s.`player name` then @rank +1 else 1 end rank , @group:= s.`player name` g  from `player stat total` s join (select @group:='',@rank:='') t  where s.`player name` in('aaron brooks', 'chris bosh', 'andre miller') order by `player name`  ,`date` desc ) t where t.rank <=5 group by t.`player name` 	0
24897458	25068	mysql date fieldtype to return value as years	select timestampdiff(year, birth, curdate()) as age 	0.000511284781271802
24898122	14361	compare values between two tables	select       isnull(a.item_id,b.item_id) as item_id, isnull(b.qty, 0) - isnull(a.qty, 0) as qty     from       table_a a       full outer join table_b b on a.item_id = b.item_id 	0.000163737542782264
24898369	9345	sql server : find list of records in one select query that are not in another select query	select row,column from table1 where stage = 130.0     except      select row,column from table1 where stage = 120.0 	0
24899497	24820	avoid alphabet select in mysql select query	select calldate, clid, duration from cdr  where clid regexp "^\"[:alnum:]+\"[:blank:]<[:alnum:]+>$" 	0.559339602999479
24900761	8523	mysql multiple sum table	select   sum(a.sale_event) as sale_eventtotal,  sum(d.order_fullpaytotal) as order_fullpaytotal from     san_activites a left join     (select sum(order_fullpay) as order_fullpaytotal, san_activity_id from sale_event_detail group by san_activity_id) d on     a.san_activity_id = d.san_activity_id where      a.entry_date between '2014-7-1' and '2014-7-30' group by a.province_id 	0.0413604461313206
24902097	36269	sql query where column has characters other than numbers or commas or spaces	select * from sample  where val not like '%[a-za-z.]%' 	0.00281459811124797
24902791	35816	sql access 2010 how to delete rows with duplicate values for all fields but one, based on the value of the distinct field	select a.chartnumber, a.createdat, a.field_name from [full patient database] a inner join (     select distinct chartnumber, createdat, field_name     from [full patient database]     group by chartnumber, createdat, field_name     having count (*) > 1 and count(field_value) < 2 ) b on a.chartnumber = b.chartnumber    and a.createdat = b.createdat    and a.field_name = b.field_name where a.field_value = 1 	0
24906847	14879	order of casting in nested select	select cast(cast([field1] as varchar(max)) as smallint) as myfield from [ipad-cc].[dbo].[zzz_imp_temp] where [field0] is null     and field1 is not null 	0.47970884828687
24907450	154	sql - isnull or if not latest date	select employ_ref, max(date) from (   select e.employ_ref, e.prob_docs_sent as date   from employee_table e   join employee_usercust ec on ec.employ_ref = e.employ_ref   union   select e.employ_ref, ec.usr_finalprob as date   from employee_table e   join employee_usercust ec on ec.employ_ref = e.employ_ref ) tbl group by employ_ref 	0.142633331123949
24908017	13764	mysql split a column into to two values(numbers) and search between those	select id, substring_index( years , '-', 1) as initval,  replace(years,concat(substring_index( years , '-', 1),'-'),'') as endval  from cip_finder; 	0
24911024	15573	limit this join query so one result for each left-side table is returned?	select p.id, pp.name personname, p.name positionname ,p.startdate  from position p inner join (select personid, max(startdate) sdate from position group by personid) as a on p.personid = a.personid and p.startdate = a.sdate left join person pp on pp.id = p.personid 	0.023151787120139
24911574	25330	sql joining tables	select t2.id, t1_1.name, t1_2.name from table2 t2 join table1 t1_1 on t1_1.id = table2.table1_id join table1 t1_2 on t1_2.id = table2.table2_id 	0.108255547574035
24912637	34763	grouping types of bugs by date and priority	select d.dates as date,      sum(case priority when 'major' then 1 else 0 end) as major,      sum(case priority when 'normal' then 1 else 0 end) as normal,      sum(case priority when 'minor' then 1 else 0 end) as minor,     b.category     from bugs b inner join datestable d on d.dates >= b.created  where (status = 'closed' and d.dates <= updated or status = 'open')     and d.dates <= getdate() and d.dates >= '2012-01-01' group by d.dates, b.category order by d.dates 	0.00257808686608727
24913559	22433	select all rows per query except for one	select nr.nid, nr.vid, nr.title, nr.hash   from node_revision nr  where exists(   select 1     from node_revision nri    where nri.vid < nr.vid      and nri.hash = nr.hash            ) 	0
24914385	12187	linq returning records with most recent dates with a join	select ap_tasks.*, history.assigndate from ap_tasks cross apply (    select top 1 ap_taskhistory.assigndate    from ap_taskhistory    where ap_tasks.taskid = ap_taskhistory.taskid    order by ap_taskhistory.assigndate desc ) history 	0.000764750029330906
24917407	36118	query to print triangle star(asterisk) for given n value in sql or pl/sql	select     rpad ('* ', level*2, '* ') from       dual connect by level <= 5  union all select   rpad ('* ', (5-level)*2, '* ') from dual connect by level <= 5; 	0.00223166871241278
24917479	1410	how to join either one of two tables that both share a column, and then continue joining?	select users.name, users.email, tags.name from users join (   select *   from self_posts a   where a.date < x   union all   select *   from ext_posts a   where a.date < x) a a.user_id = users.id inner join tags on a.tag_id = tag.id 	0
24917615	14757	select max and select other column	select sectionitem,        (select max(sectionitemid)+1 from core.sectionitem_lkup) as sectionitemid from core.sectionitem_lkup 	0.00202341559058251
24918398	4601	how can i select one distinct column from more than 2 columns	select id,name,intime,outtime,date  from reports group by id 	0
24921417	7113	mysql how to print the result of this query?	select m.id_rel,  (select sum(visita) as total from icar_mas_vistas where id_rel = m.id_rel) as total, icar_categorias.nombre  from icar_mas_vistas as m, icar_categorias  where m.id_rel = icar_categorias.id_categoria 	0.085309619026807
24922674	1143	best approach to compare database table with datatable in c#	select postal_code from postaldata where postal_code not in (     excelvalue1, excelvalue2, excelvalue3, ...   ) 	0.0241951481212829
24923059	10751	oracle sql select where column equals more than one value	select x.*, pos_time, pos_date   from (select cust_num, cust_fname, cust_lname           from pos           join customer             on cust_num = pos_cust_num          where pos_itemid = 1         intersect         select cust_num, cust_fname, cust_lname           from pos           join customer             on cust_num = pos_cust_num          where pos_itemid = 2) x   join pos     on x.cust_num = pos.pos_cust_num  where pos_itemid in (1, 2) 	0.00148322423407564
24924012	25402	mysql : reset id start from 1 if day change	select concat(date_format(current_date,'%y%m%d'),'q',       lpad(max(right(case when left(idreport,8)=date_format(current_date,'%y%m%d') then idreport else '000' end,3))+1,3,'0')) from record.report; 	0
24927773	18498	mysql: counting occurences in a table, return as a single row	select group_concat(concat_ws('##', country, organizations )) from (     select country, count(*) as organizations      from organization      group by country ) sub0 	0
24927799	24325	fetching combination of records using sql query	select * from yourtable where column1 in  (   select column1  from yourtable  group by column1  having count(distinct column2) = 2   and max(column2) = 'd'   and min(column2) = 'a'  	0.0115279271501045
24928376	9067	get duplicated fields and these fields may have spaces in mysql database	select * from users where phone regexp "\r\n"; 	0.00106295304308755
24928573	15441	use sql to get highest item with same id	select id, p_id, offer from offers  where p_id = 1 order by offer desc limit 1 	0
24929653	756	getting data in a specific time	select * from attendance; #morning time select * from attendance where  hour(`time`) < 12; #after noon time select * from attendance where  hour(`time`) >= 12; 	0.00308348340428729
24930027	15689	how to take a longer time frame in the time range in t-sql	select count(records) from [yourtable] where [timestamp] between '2014-07-01' and '2014-07-02'   and convert(time, [timestamp]) between '21:00:00' and '21:30:00' 	0.00020497881488054
24930824	6531	optimize rows to columns conversion	select     tablename.id,     tablename.name,     max(case when tablename.question=1 then tablename.answer else null end) as q1,     max(case when tablename.question=1 then tablename.reason else null end) as q1_reason,     max(case when tablename.question=2 then tablename.answer else null end) as q2,     max(case when tablename.question=2 then tablename.reason else null end) as q2_reason,     max(case when tablename.question=3 then tablename.answer else null end) as q3,     max(case when tablename.question=3 then tablename.reason else null end) as q3_reason from     tablename group by     tablename.id,     tablename.name 	0.0779819800768525
24931038	36026	mysql query from three tables	select    first.comanda as comanda,   first.total as total,   first.instoc as instoc   second.picked as picked from (   ) as first   left join (   ) as second   on first.comanda=second.comanda order by 	0.0280158343760939
24931344	29862	calculate distribution of date differences in sql	select date_part('day', cancelled_at - created_at) as activedays, count(*) from databasetable group by date_part('day', cancelled_at - created_at) order by activedays; 	0.000333480198078779
24931844	19045	summarizing fields from three table	select     students.code,     students.name,     (         select             sum(cast (pay.price as int))         from             pay         where             students.code=pay.code      ) as paytotal,     (         select             sum(cast(pay2.price as int))         from             pay2         where             students.code=pay2.code      ) as pay2total from     students 	0.00371927494597761
24934471	4829	merge two sql queries	select *  from   table1  where  ( chapter = 88           and sentence >= 23 )          or ( chapter = 89               and sentence >= 1               and sentence <= 23 ) 	0.0294416776413424
24935000	18914	multiple table query in mysql	select category.catname,questions.quid,answers.catid,answers.ansid,answers.answer from  questions  inner join answers  on (questions.quid = answers.quid ) inner join category cat on (category.catid = answers.catid) left join concerns con on (concerns.userid = answers.userid and concerns.catid = answers.catid  and concerns.ansid = answers.ansid ) where  questions.qtype = 'data'  and answers.userid = 1 	0.142699413167455
24935291	19409	sql server : select based on another column specific search	select globalid     ,security_typ     ,case  security_typ         when 'common stock' then 1         when 'reit' then 2         when 'closed-end fund' then 3         else 999      end [priority] into #tmp from temptest select *  from (   select t.*   ,row_number() over (partition by globalid order by priority) as rn    from #tmp t  ) as t1 where rn=1 	0.000100314098234853
24936059	2897	mysql count joined fields	select      a.company,      a.firstname,      a.lastname,      a.title,      a.email,      a.zipcode,      a.created,      a.newsletter,      count(distinct c.id) comments,      count(distinct f.id) follows,      a.linkedinid  from accounts a  left join comments c on a.id = c.user_id  left join followers f on a.id = f.user_id group by a.company,      a.firstname,      a.lastname,      a.title,      a.email,      a.zipcode,      a.created,      a.newsletter,      a.linkedinid 	0.0233650727505744
24940428	26125	how do i use a like statement with multiple values while excluding the values that i don't want?	select *  from result  where rules in ('|494|', '|788|', '|494|788|', '|788|494|') and tradedate >= '2014-01-01' 	0.00417287979686301
24941759	34857	sql find the max value of the sum of two columns	select job, concat('$',format(max(total_pay),2)) from (select job, (coalesce(salary,0) + coalesce(commission,0)) total_pay     from employee) t1 group by job order by job 	0
24942700	25823	performing a sum of count after group by and having count > 1	select    sum(t.count) from (     select  count(id) as count,              id,              location_id,              time,              weekofyear(time)      from table where weekofyear(time) = '28'      group by location_id, id     having count > 1 ) as t 	0.0128452281297448
24943435	6984	nested cursors, multiple result sets	select      (pick your fields here) from objects left join observations on objects.pk_objectid  = observations.fk_objectid left join pts on pts.fk_observationid  = observations.pk_observation_id 	0.765067676739947
24944075	2823	postgres check if ip (inet) is in a list of ip ranges	select inet '192.168.1.5' << any (array['192.168.1/24', '10/8']::inet[]);  ?column?   t 	0.000330031400502833
24944878	26355	mysql - get distinct primary col table row order by foreign key table	select c.contactid, c.name, m.text, m.messagetime from contacts c inner join      messages m      on c.contactid = m.contactid where not exists (select 1                   from messages m2                   where m2.contactid = m.contactid and                         m2.messagetime > m.messagetime                  ) order by m.messagetime desc; 	0
24945867	27470	sqlite, selecting a row by row index, not id	select * from table limit 1 offset 10; 	0.000377228990793703
24946141	14744	sql - group by and exclude minimum and maximum from results	select id, avg(amount) from (select d.*,              min(amount) over (partition by id) as mina,              max(amount) over (partition by id) as maxa       from data d      ) d where amount > mina and amount < maxa group by id; 	7.49524365265987e-05
24946281	15853	find related "ordered pairs" in sql	select x.*, t.p   from (select frame, outputcase, max(station) as max_station           from tbl          group by frame, outputcase) x   inner join tbl t     on x.frame = t.frame    and x.outputcase = t.outputcase    and x.max_station = t.station order by x.frame, x.outputcase; 	0.000350865720433028
24946993	13661	sql - oracle - how to select securities from table with top change %	select m.* from (select security, price1, price2, ((price2 - price1)/price1)*100 as percentage,              dense_rank() over (order by ((price2 - price1)/price1)*100 desc) as ranking       from market      ) m where ranking = 1; 	0.0252887860372698
24949360	5580	sort sql results by column titles?	select t.column_name    from all_tab_columns t   where t.table_name = ? and t.owner= ? order by 1 	0.0351235325420563
24949880	31954	sql: get data in range	select *  from table1  where (( chapter = 1 and sentence >= 3 ) or chapter > 1)   and (( chapter = 3 and sentence <= 4 ) or chapter < 3) 	0.00206287889984264
24951053	33960	how do i get distinct grouped data?	select name, min(id) from table1 group by name 	0.000978216433618794
24951176	5800	get rows which do have references to list of values and at the same time don't have any references to list of other values	select distinct ref_id1 from table1      where ref_id2 in(133,22,44)     and     ref_id1 not in                (select ref_id1 from table1 where ref_id2 in (12, 144, 111)) 	0
24953047	38014	concat with null value	select distinct col1, (     select coalesce(cast(col2 as varchar),'null')+','     from @temp t2     where t2.col1 = t1.col1     for xml path('') ) col2 from @temp t1 	0.167081986108828
24953278	29176	select values which contains specific characters in mysql	select * from mytable where mycolumn like '%[en]%[en:]%'     and mycolumn like '%[hi]%[hi:]%' 	0.000926709632907166
24954369	38234	convert query to if exists	select  ic.[min] from    [dbo].[icov] as ic where   exists (select 1                 from   [dbo].[cov] as c                  where  ic.[geog]  = c.[geog] and                        c.geolevel = ic.study_geolevel and                         c.min < ic.min) 	0.3044488505305
24954605	23812	select table using complicated query	select h.holidayid, holidaydate,description,case when clientid is null then 0 when clientid != @clientid then 0   else 1 end as isholiday                         from holiday h left outer join clientholidays ch on ch.holidayid = h.holidayid                         where clientid = @clientid or clientid is null or clientid is not null 	0.76112339972904
24956840	19682	check if any field has empty value in a table	select * from t where (       select t.*       for xml path(''), type       ).exist('*/text()[. = ""]') = 1 	0.000161252863785495
24957728	29523	subtracting an interval from max(date) in mysql	select max(date_hour) - interval 2 day  from your_table 	0.00688084267233523
24958099	31130	postgresql, add (years, months or days) to date based on another column	select     product, warranty, type_warranty, created_at,      (created_at + (warranty *         case type_warranty             when 'y' then '1 year'::interval             when 'm' then '1 month'::interval             when 'd' then '1 day'::interval         end     ))::date as warranty_ends,     (created_at + (warranty * itvalue))::date - current_date as days     from table; 	0
24958494	25471	select statement in where clause returning more than 1 value	select top 100  team.id,                 team.name,                 sum(results.points) as pointstotal from            results inner join team on results.teamid = team.id left join (       select    team.id, min(date) as mindate       from  results       inner join competition on competition.id = results.competitionid       inner join team on team.id = results.teamid       where competitionid = 3       and   teamid = team.id       and   date > (dateadd(yy, -1, getdate()))       group by  team.id       having    count(competition.id) > 1   ) minimumdatequery on   results.teamid = minimumdatequery.id and   results.date = minimumdatequery.mindate where           results.date > dateadd(yy, -1, getdate()) and             minimumdatequery.id is null group by        team.id, team.name order by        pointstotal desc 	0.361303490847249
24959047	32473	query with like statement for any of the words, not whole	select    * from    products p inner join dbo.fnsplitstring            (              select top 1 gift.name from gift where id = 65            ) sub on p.name like '%' + sub.splitdata + '%' 	0.694012759870317
24960851	32998	get a count of distinct rows that does not include a value in any row	select count(distinct studid) as 'id'  from all_classes where studid not in      (select distinct studid      from all_classes      where absences<>0); 	0
24961113	5085	select a table and join 2 diffrent table	select * from book b left join male m on m.m_id=b.b_author left join female f on f.f_id=b.b_author*-1 	0.00417098392120476
24962820	29240	how to select servers that does not have a date record in a separate table between a date range?	select t1.*, t3.* from table1 as t1 join table3 as t3   on t3.fk_table1 = t1.id where not exists ( select * from table2 as t2 where t2.fk_table1= t1.id                        and t2.patchsuccess between '2014-07-01' and '2014-09-1' )   and t1.decomissioned = 0 	0
24963583	36646	get records for past 24 hours	select dateadd(second, time_stamp /1000 + 8*60*60, '19700101')  as date_and_time from [dbo].[v_agent_system_log]  where event_source = 'sylink'and event_desc like '%downloaded%' and time_stamp >= getdate() - 1 	0
24965039	8109	sql - get records from one table that aren't "like" in another table	select pr.*   from products pr   left join posts po     on post_title like concat('%', pr.model, '%')  where post_title is null 	0
24965359	40456	sql command to copy data from 1 column in table and 1 column in another table into a new table?	select posttagid as be_posttag_posttagid, postrowid as be_posts_postrowid into be_posttagbe_posts from be_posttag inner join be_posts on be_posttag.postid=be_posts.postid 	0
24965365	16734	table shift field values to columns	select    eventid,   max(case name when 'machine' then strvalue end) as machine,   max(case name when 'person' then strvalue end) as person from details where eventid = 1   and name in ('person','machine') group by eventid 	0.000233326784201249
24966047	13704	postgresql grouping error in a query after moving from mysql	select min("events"."schedule") as schedule   from "events"  where "events"."state" in (1)    and "events"."schedule" >= '2014-07-01'  group by extract(year from "events"."schedule"),           extract(month from "events"."schedule")  order by 1 desc 	0.377648897849279
24966090	5913	search for data that matches every single tag (using the like operator)	select m.id, group_concat(t.tag separator ', ') as tags   from movies   join tags t     on m.id = t.mid  group by m.id having group_concat(t.tag) like '%dawn%'    and group_concat(t.tag) like '%of%' 	0.0122979218886822
24966417	24272	aggregating a unique pair of column values from the same table based on a common column value	select common_id, min(uniq_val) as uniq_val_1, max(uniq_val) as uniq_val_2 from my_table group by common_id; 	0
24966630	27815	logic on join two tables and using sum formula	select   c.customerid,          c.customer_name,          sum(case when product = 'dog food' then revenue else 0 end) as dog_food_rev,          sum(case when product = 'cat food' then revenue else 0 end) as cat_food_rev from     table1 c     join table2 p       on c.customerid = p.customerid group by c.customerid, c.customer_name 	0.280399751164853
24968388	29536	sql server : select nvarchar column with null doesn't return any result	select *  from dbo.villa v where v.section = n'مرکزی' 	0.294816870665393
24969147	356	sql query to find employeename, manager name from a table	select one.employeename as "employee", two.employeename as "manager" from employee as one inner join employee_manager as temp on one.employeeid = temp.employeeid inner join employee as two on temp.managerid = two.employeeid 	0.00110421813886968
24974651	26476	subtract timestamp in oracle	select extract(day from timediff) * 24 + extract(hour from timediff) as hours_diff   from (select systimestamp - to_timestamp('2014-07-22', 'yyyy-mm-dd') as timediff           from dual) 	0.0197251566739992
24974931	29477	sql join's from 3 table based on two columns	select f.id as friendshipid,        f.userid,        f.friendid,        u.name,        u.email,        l.location   from (select id, userid, friendid           from friendship         union all         select id, friendid, userid           from friendship) f   left join location l     on f.friendid = l.userid   left join users u     on f.friendid = u.id  where f.userid = 2 	0
24975326	26181	select distinct rows and apply a filter	select distinct col1 from test where      col1 not in (select col1 from test where col2 = 0) 	0.011542782334124
24975686	29237	mysql: select only getting records based on "where x like '%?%'" in many-to-many relationship	select b.id, b.name, b.type from board_game b join board_game_piece_missing bp on b.id = bp.board_game_id join piece p on bp.piece_id = p.id where b.genre = 'strategy' group by b.id having sum(p.color <> 'red') = 0 and sum(p.color = 'red') > 0 	0
24975902	11331	difference in two sql query, but same result	select  ename, deptno, sal, comm from    emp where   (sal, comm) in (select sal, comm from emp where deptno = 30) 	0.00236008613829364
24979151	19348	sql query with 2 joins and count	select user.steamid, user.name, coalesce(winners.nrwon,0) as nrwon, coalesce(nrgiveaways.nrgiven,0) as nrgiven from user left join (select winnerid, count(*) as nrwon from giveaway where winnerid is not null group by winnerid) as winners on winners.winnerid = user.steamid left join (select userid, count(*) as nrgiven from giveaway group by userid) as nrgiveaways on nrgiveaways.userid = user.steamid where roleid in (1,2,3,4) 	0.536009408996002
24979628	17709	how to select most recent values?	select *   from log l  where minute =        (select max(x.minute) from log x where x.probeid = l.probeid) 	0.000109505939192222
24980171	37989	retrieve count of related records	select count(*) as cnt from member m where m.trainerid = @thetrainerid; 	5.75616120363869e-05
24981681	28893	join rows google bigquery	select name, group_concat(columnnamecontainingtheattribute) from yourtable group by name 	0.688258623076749
24982829	30833	select data from multiple table where there may not necessarily be a match between some tables	select convert(varchar(10), orders.orderdate, 101) as orderdate,        orderdetails.orderid,        orders.customerid,        customers.emailaddress,        orderdetails.productcode as orig_product_code,        orderdetails.productname,        orderdetails.productprice,        orderdetails.quantity,        products_joined.vendor_partno,        products_joined.productcode,        products_joined.productprice as current_reg_price,        products_joined.saleprice as current_sale_price   from orders   join customers     on customers.customerid = orders.customerid   join orderdetails     on orders.orderid = orderdetails.orderid   left join products_joined     on orderdetails.productcode = products_joined.productcode  where customers.emailaddress = 'tsmith@abc.com'    and customers.customerid = '1'  order by orders.orderid desc 	0.003894736226618
24983126	12312	howto get freq of count's data in month 1 - 12 in specific year	select x.mo,        count(*) as freq from ( select '01' as mo from rdb$database union all select '02' from rdb$database union all select '03' from rdb$database union all        select '04' from rdb$database union all select '05' from rdb$database union all select '06' from rdb$database union all        select '07' from rdb$database union all select '08' from rdb$database union all select '09' from rdb$database union all        select '10' from rdb$database union all select '11' from rdb$database union all select '12'from rdb$database ) x  left join table_1 t    on x.mo = substring(t.doc_date,3,2) where t.doc_date like '%2014' group by x.mo order by 1 	0
24985011	28940	sqldf: convert and select	select *   from base  where col between '1000' and '1200'    and col not like '% %' 	0.422174765496
24985683	8707	mysql primary key type becomes "index" after inner join	select distinct item_term_results.item_id   from item_terms  inner join item_term_results     on item_terms.id = item_term_results.item_term_id  where item_terms.term in ('jason','bourne') 	0.676237964597368
24988829	37287	mysql same row different column ref.(ifnull check)	select      a.contact_seq,     'test' as memo,      now() as reg_date,     a.user_id,     a.name,     a.contact_num as phone_num,     (select count(*) from tb_contact as a,  tb_contact_group as b         where             b.user_id = 'spark@naver.com'         and             b.group_contact_seq = 120         and             a.group_contact_seq = b.group_contact_seq     ) as totcount,     case when exists(select 1 from tb_auto_ban where user_id =  'spark@naver.com' and phone_num = a.contact_num) then 'y' else 'n' end as define from         tb_contact as a, tb_contact_group as b             where                 b.user_id = 'spark@naver.com'             and                 b.group_contact_seq = 120             and                 a.group_contact_seq = b.group_contact_seq 	8.33667724946582e-05
24989592	33635	mysql join two tables on multiple records	select a.name as "name", b.name as "table2_id1_name", c.name as "table2_id2_name", d.name as "table2_id3_name"  from table1 a left join table2 b on (a.table2_id1 = b.id) left join table2 c on (a.table2_id2 = c.id) left join table2 d on (a.table2_id3= d.id) 	0.0019388855777704
24990536	886	how to add a subtotal rows in oracle?	select    decode(grouping(a),1,decode(grouping(subtot_id), 1, 'total', 'subtotal'),a) as a,     sum(b) as b, sum(c) as c from (     select trunc((rownum-1)/3) as subtot_id, a, b, c     from your_table     order by a   ) group by rollup(subtot_id, a) 	0.00720799283673789
24995081	17421	microsoft access query - convert text to numeric depending on field contents - low, medium, high to 1,2 ,3	select field1,         switch([field1]="low",1,[field1]="medium",2,[field1]="high",3) as switchvalue from atable 	0.00188915868360411
24995649	6588	mysql specific select statement	select t2.id, tfrom.name as kid_a, tto.name as kid_b, t2.gift_description from secondtable t2 join      firsttable tfrom      on t2.`from` = t1.id join      firsttable tto      on t2.`to` = t2.id; 	0.155734533779273
24997788	37192	row that should have a 0 count not showing	select s.section_id,         s.location,         count(e.section_id) as enrolled  from   course c         left join section s                on c.course_no = s.course_no         left join enrollment e                on s.section_id = e.section_id  where  c.description = 'project management'  group  by c.course_no,            s.location,            s.section_id  order  by s.section_id; 	0.0262928989275648
24998959	3943	how to set '5 day' (datetime interval) in jdbc for postgresql?	select * from foo where time +'10 day'::interval >current_timestamp; 	0.000604123284129273
24998963	21028	order by and if some are the same then order by something else in sql	select * from league order by points desc, goaldiff desc, goalsscored desc, playername 	0.0105174631090852
24998980	9660	how to find packages where table name is used more than twice	select t.table_name, p.object_name, count(*) from user_tables t cross join user_objects p join user_source s on s.name = p.object_name          and s.type = 'package body'          and upper(s.text) like '%' || upper(t.table_name) || '%' where p.object_type = 'package body' group by t.table_name, p.object_name having count(*) > 5; 	0.00709571288029797
24999429	15752	not getting (select) all the results using where in mysql database	select       `contact`.`firstname`,      `contact`.`lastname`,      `ssn`.`ssn`,      `contact`.`country`,      `allergies`.`allergy`,      `allergies`.`allergytype`,      `allergies_contact`.`allergynotes`,      `currentprescriptions`.`prescriptionname`,      `currentprescriptions`.`prescribeddate`,      `bloodtype`.`bloodtype`   from      `mher`.`contact`      inner join `mher`.`ssn`         on `ssn`.`contactkey` = `contact`.`contactkey`      inner join `mher`.`bloodtype`         on `bloodtype`.`contactkey` = `contact`.`contactkey`      left join `mher`.`allergies_contact`         on `contact`.`contactkey` = `allergies_contact`.`contactkey`      left join `mher`.`allergies`         on `allergies`.`allergieskey` = `allergies_contact`.`allergieskey`      left join `mher`.`currentprescriptions`         on `currentprescriptions`.`contactkey` = `contact`.`contactkey`   ; 	0.021144133671671
24999843	5661	a query of certain students in a certain room	select count(*) numberofinstructors from (select instructor_id       from section s           join enrollment e                 on e.section_id = s.section_id        where s.location = 'l211'       group by instructor_id       having count(student_id) >= 3) z 	0
24999915	20266	joining three myql table including condition in where clause	select * from (select country as country_name, count(name) as total_member  from members m group by country) members left join  (select sum(ammount) as total_order , country from orders where aproved = 1 group by country) ammounts on country_name = ammounts.country left join (select sum(withraw) as total_paid , country from withraw group by country) withraw on country_name = withraw.country 	0.303383491784701
25000017	12796	return a value if no rows match	select  authorityid = isnull(( select   [authorityid]                                from     [docauthority] with ( nolock )                                where    [grpid] = 0                                         and [sid] = 42                              ), 15) 	0.000170855491403098
25000197	2998	how to overwrite empty column values in a group by with sql server?	select col1, max(col2) sum(col3) from table group by col1 	0.00775404763136697
25000226	35654	sql - selecting all except	select     t.player,     count(t.player) as game_count,     t.tm,     round(avg(t.minutes), 2) as min from     nba.player_stats t where     t.tm not in (                  select tm from nba.player_stats p                  where  p.player in ('courtney lee','ryan anderson')                         and p.date = t.date) group by player; 	0.00428670747096878
25002430	24415	sum accounting session on mysql avoiding duplicates	select  ifnull(sum(sessiontime),0) as total_time from  (select * from acct where name='xxxxx' group by `acctuniqueid`) as temp ; 	0.178586955339687
25003009	4799	in an sql statement, how do you select all elements that are not a certain condition?	select b from book b where not exists (     select bt.id from booktaken bt where bt.bookid = b.id) 	5.86528544159957e-05
25003012	7638	getting a count from a nested query with a case statement	select vehicle "type", count(*) "count" from(   select     case       when auto_type like 'chevy' then 'domestic'       when auto_type like 'ford'  then 'domestic'       else 'foreign'      end as vehicle    from table_name  ) group by vehicle 	0.726141667817866
25003945	33152	fetching data from multiple table using join	select test.eancode, tab_fr.product, tab_it.product, tab_at.product  from   test  left join tab_fr on test.eancode = tab_fr.eancode  left join tab_it on test.eancode = tab_it.eancode  left join tab_at on test.eancode = tab_at.eancode; 	0.00877279574394636
25009111	14108	count number of times value appears in column in mysql	select count(*) as numcustomersfromsydney from table where suburb = "sydney"; 	0
25010373	39778	how to give alias to result table of sql which use multiple subqueries?	select * from  (       select op.order_id,op.product_id,op.quantity as ordered_quantity, sum(odp.quantity) as delivered_quantity       from oops_order_product op        left join oops_order_delivery_product odp on odp.product_id = op.product_id and odp.id is null        where op.status = 0        group by op.product_id       union all                                                                                                 select op.order_id,odp.product_id,sum(op.quantity) as ordered_quantity,     sum(odp.quantity) as delivered_quantity       from `oops_order_delivery_product` odp       join oops_order_delivery od on od.id = odp.order_delivery_id       left join oops_order_product op on op.product_id = odp.product_id and op.id is null       where odp.status = 0 group by odp.product_id ) as finaltable 	0.235266277944637
25015664	4760	mysql limiting only first table from joined table	select         e.*        u.group_id,        u.name,        u.decade,        u.intention,        u.datume  from (select e.id, e.rosary, e.group_name, e.description, from `rosary_group_name` as e $limit) as e  inner join `rosary_groups` as u          on e.id = u.group_id  order by e.id desc; 	0
25016295	16998	mysql select rows where sum of 2 columns > 0	select * from users where (direct_points+sub_points)>0 	0.00017681222509117
25016580	16642	consecutive dates sequence by criteria	select  user_id, project_id, min(done_at) as start_done_at, max(done_at) as end_done_at, sec_to_time(sum(time_to_sec(duration))) as duration  from (     select     t.*,     @gn := if(timestampdiff(day, @prev_date, done_at) between 0 and 1 and @prev_type = type and @prev_project = project_id, @gn, @gn + 1) as group_number,     @prev_date := done_at,     @prev_type := type,     @prev_project := project_id     from     t     , (select @prev_project := null, @prev_date := null, @prev_type := null, @gn := 0) var_init     order by project_id, done_at, duration ) sq group by group_number 	0.00164166818271836
25017412	27600	same query but different tables	select t1.col1, t1.col2, ..., t1.col10 from table1 t1 where pvar = 1 and ... union select t2.col1, t2.col2, ..., t2.col10 from table1 t2 where pvar <> 1 and ... 	0.00295896631575056
25018577	27754	does a column contain certain part of the other column string? (postgres)	select e.complete_email  from emailslist e, emailpartial ep  where e.complete_email like '%' || ep.username || '%'; 	0
25019091	18076	mysql join with multiple mapping tables	select p.product_id from products as p join products_and_categories as pc on p.product_id = pc.pc_product_id join categories as c on pc.pc_category_id = c.category_id join products_and_subcategories as psc on p.product_id = psc.psc_product_id join sub_categories as sc on psc.psc_sub_category_id = sc.sub_category_id where c.category_name = :querycategory and sc.sub_category_name = :querysubcategory 	0.459529142791931
25019621	40194	join on different tables depending on column data in sql	select      st.id,     u.name,     st.comment as comment from salestable st    inner join stuff1 s1 on s1.fk_salestableid = st.id    inner join unit u on s1.fk_unitid = u.unitid    left outer join paymentbank pba on s1.ck_paymenttablename = 'paymentbank'     left outer join paymentcard pcc on s1.ck_paymenttablename = 'paymentcard'     left outer join paymentcash pca on s1.ck_paymenttablename = 'paymentcash'  where    st.derp = 'derp' group by    st.id,    st.comment,    u.name 	0.00011100205260929
25020380	36292	where can i find the main query?	select      deqs.last_execution_time as [time],             dest.text as [query] from        sys.dm_exec_query_stats as deqs cross apply sys.dm_exec_sql_text(deqs.sql_handle) as dest order by    deqs.last_execution_time desc 	0.187174054686615
25022923	22114	mysql logic to count	select type,    value,    count(*)  from answer  group by type, value 	0.493716833054461
25023337	24569	how to categories different strings as a group using sql?	select invoiceid, max(status) from invoice group by invoiceid 	0.00828433724299731
25023479	32193	sql queries that compare values of multiple rows and columns	select top 1     date_id from (     select          date_id,         ( case when col1 between 1 and 5 then 1 else 0 end         + case when col2 between 1 and 5 then 1 else 0 end         + case when col3 between 1 and 5 then 1 else 0 end         + case when col4 between 1 and 5 then 1 else 0 end         + case when col5 between 1 and 5 then 1 else 0 end         ) as value     from results ) d order by value desc 	0
25023508	18716	how to select values that are paired with each in a list of values	select employee_id from atable where role_id in (20, 30, 40) group by employee_id having count(distinct role_id) = 3; 	0
25023600	8021	how to group multiple records from two different sql statements	select * from tbl where uid = '1' union all select * from tbl where uid <> '1' and       exists (select 1 from tbl tbl2 where tbl2.uid = '1' and tbl2.cid = tbl.cid); 	0.000132486457591518
25024030	12295	select count of max value over 2 columns	select     max_level,     count(*) from (     select         max(level) as max_level     from table1     group by record ) max_levels group by max_level order by max_level; 	7.4933468182964e-05
25024077	22264	update multiple table without knowing the table name (due to a chain of foreign key relationship)	select    object_name(fk.[constraint_object_id])    as [foreign_key_name]  ,object_schema_name(fk.[parent_object_id]) as [parent_schema_name]  ,object_name(fk.[parent_object_id])        as [parent_table_name]  ,pc.[name]                                 as [parent_column_name]  ,object_schema_name(fk.[parent_object_id]) as [referenced_schema_name]  ,object_name(fk.[referenced_object_id])    as [referenced_table_name]  ,rc.[name]                                 as [referenced_column_name] from [sys].[foreign_key_columns] fk inner join [sys].[columns] pc on    pc.[object_id] = fk.[parent_object_id] and   pc.[column_id] = fk.[parent_column_id] inner join [sys].[columns] rc on   rc.[object_id] = fk.[referenced_object_id] and   rc.[column_id] = fk.[referenced_column_id] 	0
25024831	26365	creating an mysql view that sums specific column from another table based on a flag?	select c.*      , sum(o.complete=1)      , sum(case when o.complete=1 then total + custom_total else 0 end) ttl   from clients c   join orders o     on o.client_id = c.id  group     by c.id; 	0
25025673	28952	select into query	select history_number = identity(int,1,1),     ... etc... into newtable from existingtable where ... 	0.0963458561395184
25026394	11334	fetch mysql row unless it's a duplicate, in which case ignore it	select distinct owner   from comments   where postid = ? 	0.00135438812712263
25029214	17628	sql division column only returns one row	select t0.itmsgrpcod,        sum(t1.price) as "sell",        isnull(sum(t1.stockprice), 0) as "cost",        case when sum(t1.stockprice) = 0 then 100              else (sum(t1.price) - sum(t1.stockprice)) / sum(t1.price) * 100        end as "gp" from inv1 t1 left outer join oitm t0 on t1.itemcode = t0.itemcode group by t0.itmsgrpcod order by t0.itmsgrpcod 	0.000969828780773409
25030875	2129	mysql select multiple rows from same column and table	select * from locations where location_id in (1,2,3) 	0
25031772	17926	how to count the number of columns with specific data in ms sql	select     employeeid,     pid,     (         case when [1] = 'd' or [1] = 'n' then 1 else if [1] = 'd/n' then 2 else 0 end       + case when [2] = ...       + ...       + case when [31] = 'd' or [31] = 'n' .....     ) as shift_totals,     (         case when [1] is not null then 1 else 0 end       + case when [2] is ...       + ...     ) as day_totals 	0
25033086	19155	list all authors who have published books in all genres	select a.* from author a inner join (     select         authorid,         count(distinct genre) num_genres     from manuscript     group by authorid ) authors_genres on a.authorid = authors_genres.authorid inner join (     select         count(distinct genre) num_genres     from manuscript ) all_genres on authors_genres.num_genres = all_genres.num_genres; 	0
25033572	33598	mysql count hour each day	select      id,     datestart,     dateend,     datediff(dateend, datestart) + 1 as daterange,      (datediff (dateend, datestart) + 1) * `hours` as total_hours from      project_staff_assignment 	0
25033812	12392	how to create bigger time period from multiple smaller ones using t-sql	select min(startdate) startdate, canceldate from ( select a.startdate,  coalesce(b.canceldate, a.canceldate) canceldate from dt a left join dt b on (b.startdate=dateadd(d,1,a.canceldate) or a.canceldate=b.startdate) ) x group by canceldate 	0.0011262714288301
25033816	40216	convert time to hour range in sql	select      coldate,      right ('00' + convert(varchar, datepart(hh, coltime)), 2) + '-' + right('00' + convert(varchar, datepart(hh, coltime) + 1), 2) as timerange from     tbltest 	0.000854495588011231
25034306	39364	how do you select nth row for each id?	select id,  fname,   data from  (      select test_data.*,       row_number() over (partition by id order by order_by_condition) as rank      from test_data ) t  where t.rank=2 	0
25034600	20317	filtering data with from statement	select      fk_id from mytable where number = 0 group by fk_id having count(*) >= 2; 	0.112138242787398
25035389	34837	filter datetime in sql server	select * from sales where month(datetime)=7 and year(datetime)=2014 	0.289274398767378
25037141	5239	sql query to get a row which has comma separated values	select id from table where find_in_set('test', promocode) > 0 	0
25038839	39581	multiple table query with sum and count	select     if (soac.item_id is null, soc.item_id, soac.item_id) as item_id,     if (soac.name is null, soc.name, soac.name) as name,     sum(soc.quantity * coalesce(soac.quantity, 1)) as total_sold from     sale_ord_contents soc         left outer join sale_ord_assembly_contents soac            on soac.order_item_id = soc.id group by     if (soac.quantity is null, soc.item_id, soac.item_id),     if (soac.name is null, soc.name, soac.name) order by total_sold desc limit 20 	0.0558246275519681
25038881	20015	mysql select everything to left of last space in string with variable spaces	select      left(full-name, length(full-name) - locate(' ', reverse(full-name))+1)  from table; 	0.00483535898856838
25039821	23965	condition on another field into a sum	select hour(t.stats_iso) hour_num,            round(minute(t.stats_iso)/60) interval_num,            min(t.stats_iso) interval_begin,            max(t.stats_iso) interval_end,            count(t.id) countid,            sum(t.montantttc) sum_subtotal,            sum(t.montantttc)/count(t.id) moy,            sum(coalesce(a.article_count,0)) article_count      from ticket t left join (        select uid_ticket, count(*) article_count          from article       group by uid_ticket            ) a        on t.uid = a.uid_ticket     where t.annule = 0       and t.stats_iso between '2012-01-01' and '2012-01-02'  group by hour_num, interval_num  order by hour_num, interval_num 	0.000392038256408401
25040082	31563	sql distinct while selecting all columns	select distinct columns.you               , actually.want            from listings l            join selections s              on l.id = s.lid            where activity = 'running'              and s.parent in(1,2) 	0.000417328433960714
25040133	10732	sql server: find most popular category of products bought per user for use in subquery	select user_id, category_name, category_count from (   select        user_id, count(1) as category_count, category_name,        row_number() over (           partition by user_id            order by count(1) desc, category_name asc)            as ordinal_position   from       purchases p            join products p2 on p.product_id = p2.id           join categories c on p2.category_id = c.id           group by user_id, category_name  ) a where ordinal_position = 1 order by category_count desc 	0
25043327	9311	select data from a table and change how it is shown based on the data	select case issue when 'winter' then '1/1/' || issue_year              when 'spring' then '4/1/' || issue_year             when 'summer'....        end issuedate from ihe_issues; 	0
25043368	40204	sql: how do i select fields based on varying existing conditions?	select * from (    select t.*,       row_number() over (        partition by id         order by category asc, dt desc) rn      from t ) tt where rn = 1; 	0.0011338275411518
25043514	8861	mysql select items where count (from another table) is greater than x	select      ay_users . *,     ay_users_outfits . *, from     ay_users_outfits,     ay_users,     ay_votes where     ay_users_outfits.outfituserid = ay_users.userid and      ay_votes.voteoutfitid = ay_users_outfits.outfitid group by ay_users.userid having ay_users_outfits.outfitrequiredvotes <= count(ay_votes.voteid) order by ay_users_outfits.outfitcreationdate asc 	0
25043571	5971	left join specific columns from two different tables using alias	select t.item_desc as description,         tp.customer_name as customer,         tp.purchase_date as datepurchased  from toys t  left join toy_purchases tp on t.item_id = tp.item_id 	0.00098458390086274
25045880	3468	sql query showing just few distinct records	select * from (     select col_1         ,col_2         ,col_3         ,row_number() over (             partition by col_1             ,col_2 order by col_1             ) as foo     from tablename     )  bar where foo < 3 	0.0148049505052884
25046231	11607	remove all characters at the beginning of string up to certain character in oracle	select substr(address, instr(address, '_') + 1, length(address)) as "citystate" from address 	0
25046232	33850	mysql order by sum of another table	select comments.id,         count(comment_rating.id) as rating_count,        coalesce(sum(positive),0) as rating from comments  left join comment_rating on comments.id = comment_rating.comment_id  group by comments.id  order by rating desc 	0.00207810699983687
25048500	27581	compare column values starting with oldest columns until their sum equals a number	select a.* from (   select a.*, @total := @total + a.id total   from balance_down a   join (select @total := 0) b   where user_id = '$other_user_id'   order by a.charge_date asc) a where a.total <= 50; 	0
25049004	24433	returning everything - that is distinct	select distinct name from table 	0.108817434466329
25050038	29236	distinct listagg in oracle sql	select a.col_1,         listagg(a.col_2, ',')            within group(order by a.col_2) as col_2,         sum(a.ss) as col_3   from (select col_1, col_2, sum(col_3) ss           from test          group by col_1, col_2 ) a  group by col_1 	0.605010349469359
25052085	39062	mysql: calculating percentage of count with group by	select      m.m_id as "mailing type",     count(mr.u_id) as "mailings received",     count(mr.u_id) / (select count(*) from mailing_received) as "perc rec" from mailing m  left join mailing_received mr        on mr.m_id = m.m_id group by m.m_id 	0.0143959440220315
25052090	28451	sql - displaying 3 different counts on one query	select people.name, count(*) as allmessages, sum(case when type='text' then 1 else 0 end) as textmessages, sum(case when type='picture' then 1 else 0 end) as picturemessages from ballers.messages join ballers.people on people.id=messages.senderid group by people.name 	0.00130379356157501
25052236	10242	select query that depends on two other tables	select ch.name from tbchilds ch    join tbgroups gr on ch.group=gr.name    join tbcategories cat on cat.id=gr.category  where cat.name='category1'; 	0.000273097538653652
25053650	6397	mysql if statement in group by	select * from    (      select msgtype ,user, min(job_id), project_id       from mail      where msgtype = 1      group by msgtype,user,project_id      union all      select msgtype ,user, job_id, project_id       from mail      where msgtype <> 1    )t order by t.msgtype desc 	0.565332788660403
25055254	1185	match some words between two columns	select table1.title title1, table2.title title2 from table1, table2 where table1.title like concat('%',table2.title,'%')  or table2.title like concat('%',table1.title,'%'); 	0.000245560213928713
25057183	19957	use a particular set of where clauses depending on the comparision of 2 cells	select      sum(case when active_date < submit_date and submit_date < '2014-07-28' then 1              when active_date >= submit_date and active_date < '2014-07-28' then 1         end) as outsla from     woi_workorder where     asgrp in ('woique') and     status = 'assigned' or status = 'pending' or status = 'in progress' 	0
25060695	10821	query that subtracts sum of one column from another	select x.*      , x.a - sum(y.b)    from my_table x    join my_table y      on y.date_created <= x.date_created   group      by x.id; 	0
25061171	5979	mysql get count and sum on different group by in one select	select    c.month,   coalesce(a.mycount,0),   coalesce(b.totalphones,0),   coalesce(b.newphones,0) from   (select monthstart as month from testgb    union    select monthend as month from testgb) c  left outer join    (select    monthstart as month,    count(distinct obild) as mycount,    from testgb    group by monthstart) a on a.month = c.month left outer join    (select    monthstart as month,    sum(newphones) as newphones,    sum(totalphones) as totalphones    from testgb    group by monthend) b on b.month = c.month 	7.3757934905216e-05
25061376	35033	combine concat and rtrim in where sql	select * from `subscribers`  where `subscribers`.`deleted_at` is null    and concat (trim(firstname)," ",trim(lastname)) like 'firstname lastname'; 	0.710690861455906
25062462	23692	how to search a column name within all tables of a database	select table_name, column_name from user_tab_columns where column_name like '%author%'; 	5.2918388688398e-05
25063195	36867	calculating the sum of annual amounts when frequencies of payments differ	select sum (case when frequency='month' then (cast(amount as decimal(10,2))*12      when frequency='quarter' then... end) as [total annual amount] 	0.00279775016317764
25063587	20216	adding a key to a multidimensional array from another multidimensional array	select m.full_name,           m.id,           m.member_ref,           m.type,            (p.id is not null) paid,           count(l.member_ref) log      from members m left join paid p        on m.id = p.id left join log l        on m.member_ref = l.member_ref       and l.timestamp >= '$from'        and l.timestamp < '$to'  group by m.full_name, m.id, m.member_ref, m.type, p.id  order by m.full_name asc 	0.00149319192192925
25063781	8842	how do i grab the "next" event when the offset is variable?	select item,        min(transaction) keep (dense_rank first order by timestamp) as starttx,         min(transaction) keep (dense_rank last order by timestamp) as endtx,        max(timestamp) - min(timestamp) from transactions t group by item; 	0.00131121661793746
25063936	36377	sql server 2012 date change	select convert(varchar(10), creat_dttm, 101) from yourtable 	0.504794387463441
25064162	4801	sql return a distinct column and the first date of the distinct column	select url, min(created_at) from databasetable where blabala group by url 	0
25064613	9733	mysql : how do i select the next rows from id	select *  from your_table  where id > 5  order by id asc limit 5 	0
25065189	27661	grouping distinct values	select distinct coalesce(val, 999) from ((select val1 as val from tablewithvalues) union all       (select val2 from tablewithvalues)      ) twv; 	0.0212651319068194
25066391	9476	building xml in oracle without unnecessary tags	select xmlelement          (             "order_wave"           , xmlagg             (               xmlelement               (                   "order_header"                 , xmlelement("order_number", nvl(t1.l_name,' '))                 , xmlagg                   (                     xmlelement                     (                        "order_line"                      , xmlelement("label_type", nvl(t2.l_name,' '))                      , xmlelement("lpn", nvl(t2.l_num,0))                      , xmlelement("sku", nvl(t2.l_num,0))                     )                   )               )             )          ) xml_data     from test_table t1, test_table t2    where t1.record_type = 'h'      and t2.record_type = 'd'  and t1.msg_ind = t2.msg_ind    group       by t1.l_name; 	0.647369284839274
25067984	32279	mysql query to get the max, min with group by and multiple table joins in separate rows	select max(salary) salary,  dept_name, first_name, dept_id , 'max' type     from ( select a.salary, c.dept_name, b.first_name, b.dept_id, a.salary_id     from employee_salary a     left join employee b on a.emp_id = b.emp_id     left join department c on c.dept_id = b.dept_id order by a.salary desc) t     group by dept_id     union all     select min(salary) salary,  dept_name, first_name, dept_id , 'min' type     from ( select a.salary, c.dept_name, b.first_name, b.dept_id, a.salary_id     from employee_salary a     left join employee b on a.emp_id = b.emp_id     left join department c on c.dept_id = b.dept_id  order by a.salary asc) t     group by dept_id     order by dept_id 	0.000218846112327924
25068528	13027	sql server sum rows with string value	select      case when isnumeric(col1) = 1 then cast(col1 as int) else 0 end    + case when isnumeric(col2) = 1 then cast(col2 as int) else 0 end    + case when isnumeric(col3) = 1 then cast(col3 as int) else 0 end    + case when isnumeric(col4) = 1 then cast(col4 as int) else 0 end    + case when isnumeric(col5) = 1 then cast(col5 as int) else 0 end as sumvalue from mytable 	0.00647815606531479
25068549	38244	possible to play back table of inserts/deletes to get the current state?	select data, sum(case when hst = 'i' then 1 when hst = 'd' then -1 else 0 end) as num from parthistory ph where changedate <= date '2014-07-03' group by data having sum(case when hst = 'i' then 1 when hst = 'd' then -1 else 0 end) > 0; 	0.000238492688692981
25068992	2097	getting a count while accounting for an attribute	select c.id from customer c join      account a      on c.id = a.ind_id where c.status = 'a' group by c.id having max(last_purchase) >= date_add(month, -2, getdate()); 	0.0101271459483185
25069282	28585	joining tables on multiple conditions	select m.id, sname.value as mapname, sdesc.value as description from maps m inner join      strings sname      on sname.id = m.name inner join      strings desc      on sdesc.id = m.description; 	0.0271879979965842
25071367	40725	how to get avg time taken by grouping a particular column using sql?	select ...    sum(case when datacenter = 'phx' then call_count end) phx,    sum(case when datacenter = 'phx' then call_count * avg end)/   sum(case when datacenter = 'phx' then call_count end) phx_avg, 	0.000241951888949658
25073032	28118	sql joining two tables with common row	select b.id account_id,a.code account_code,a.id assoc_id  from  associate a,         account b  where  a.code = b.code    and  a.id in (select a.id                      from   associate a,                             account b                      where  a.code = b.code                      group  by a.id                      having count(*) = (select count(*)                                         from   account)); 	0.000320041287074878
25079431	10153	oracle: like where any part of one string matches amy part of another string	select *  from test_addresses where (addr4 is not null and country like '%'||addr4||'%') or (addr5 is not null  and country like '%'||addr5||'%') 	0.000309271349019985
25080359	11413	stored procedure for counting file types	select filetype,        count(*) as typecount from tbl_uploads group by filetype 	0.194728190501607
25080729	38603	fill blank in table with data from previous row sql	select t1.id,  (case when value is null then @prevvalue else @prevvalue := value end) value from myvalues t1 cross join (select @prevvalue := null) t2 order by t1.id 	0
25082037	29636	how can one implement openablecolumns for a pre-existing table?	select _id,        internalfilename,        filetype,        title,        title || '.' || filetype as displayname from mylittletable 	0.104131276272094
25082164	26791	join table using columns which contains other table's id's separated by commas	select * from faculty f      join course c           on charindex((','+cast(c.id as varchar(10))+','), (','+f.courseid+',')) > 0      join subject s           on charindex((','+cast(s.id as varchar(10))+','), (','+f.subjectid+',')) > 0 	0
25082202	14452	cannot print out the latest results of table	select   names.fname,   names.stime,   names.etime,   names.ver,   names.rslt from names inner join (   select fname, ver, max(etime) as maxetime   from names   group by fname, ver ) t on names.fname = t.fname and names.ver = t.ver and names.etime = t.maxetime 	0.000196250133958817
25082793	6896	extract time from datetime - informix	select to_char(extend (my_datetime_column, hour to second),'%h:%m:%s') as my_time from my_table 	0.0128801292131997
25086350	26242	how to join two tables using sub queries?	select s.*,p.* from salary s  cross join (select * from pension where sal=21) p 	0.189011974670954
25088684	10949	last message in correspondence	select a.* from messages a join (   select if(sid=1, rid, sid) id, max(mdate) d   from messages   where sid = 1 or rid = 1   group by id) b on ((a.sid=1 and a.rid=b.id) or (a.sid=b.id and a.rid=1)) and a.mdate = b.d; 	0.00725441021202706
25088851	23750	running count with no origin	select sum(case status when login then 1 when logout then -1 end) as numusers from table where timestamp <= @timestampcutoff; 	0.294131030136919
25088948	33979	generate start and end dates in a date range oracle	select x.* , end_dt-st_dt from  (select 12-(level-1) as quater , (case when ( trunc(sysdate) - 90*level = to_date('17-aug-11','dd-mon-yy'))  then trunc(sysdate) - 90*level else trunc(sysdate)+1 - 90*level end) as st_dt,trunc(sysdate) - 90*(level-1) as end_dt from dual connect by level <= 12 order by 1 ) x; 	4.70007300048133e-05
25089022	29698	trouble with joining tables and obtaining data in oracle sql	select t1.sku,        t1.main_location,        ml.quantity        as main_qty,        t1.backup_location,        bl.quantity        as bkup_qty   from table_1 t1   left join table_2 ml     on t1.sku = ml.sku    and t1.main_location = ml.location   left join table_2 bl     on t1.sku = ml.sku    and t1.backup_location = bl.location  order by t1.sku 	0.322994949679085
25089811	30478	sql query conditional row	select * from table where system != 'a' or exception = 1 	0.426685840222469
25093024	20722	how use greater than 0 (>0) within case in sql server?	select fields from table  where     (@userregisteredby = 0 and createdby = 0)     or      (@userregisteredby = 1 and createdby > 0)     or      (@userregisteredby is null) 	0.714920577756395
25095444	11855	rewriting sql query to get record id and customer number	select a.record_id,   (case      when a.countopen=1 then a.custnoopen      else                    a.custnoclosed   end) as cust_no from (   select b.record_id,     max(case when b.isaccntclosed='n' then b.cust_no else null end) as custnoopen  ,     sum(case when b.isaccntclosed='n' then 1         else 0    end) as countopen   ,     max(case when b.isaccntclosed='y' then b.cust_no else null end) as custnoclosed,     sum(case when b.isaccntclosed='y' then 1         else 0    end) as countclosed   from table1 b   group by b.record_id ) a where a.countopen=1 or (a.countopen=0 and a.countclosed=1) 	0
25096431	6992	fetching records between two date ranges	select t1.qty,        t2.lastname,        t2.firstname,        t2.date,        t3.name,        t2.reservation_id,        t2.payable   from prodinventory as t1  inner join reservation as t2     on t1.confirmation = t2.confirmation  inner join products as t3     on t1.room = t3.id  where str_to_date(t2.date, '%d/%m/%y') between        str_to_date('$start', '%d/%m/%y') and        str_to_date('$end', '%d/%m/%y') 	0
25097253	26615	store and query time in mysql	select * from table1 where event = 'event1' and hours*3600+minutes*60+seconds+milliseconds/1000 < 0*3600+4*60+30+0/1000 ; 	0.208736621541833
25098188	13529	sql conditional and	select      *  from        job j inner join  exchange_rate er      on      j.currency_id = er.currency_id      and     er.date = coalesce( offer_date, accepted_date, start_date, reported_date ) 	0.750305137605049
25098707	134	mysql query - joining	select a.title, a.desc, group_concat(t.tag)  from articles a inner join tags t on a.id = t.articleid group by  a.title, a.desc 	0.356943657333812
25098767	26422	sort users by similarity in mysql	select all_users.userid, all_users.itemid, count(user.userid) as total_matches from votes as user join votes as all_users     on all_users.vote = user.vote     and all_users.itemid = user.itemid     and all_users.userid != user.userid     and user.userid = 1 group by all_users.userid order by total_matches desc 	0.0221532928477201
25099103	37147	convert columns into rows with inner join in mysql	select distinct a.letter, 'letter' as field   from general a  cross join options b  where b.options = 'letter' union all select distinct a.`double-letters`, 'double-letters' as field   from general a  cross join options b  where b.options = 'double-letters' 	0.0146220747194756
25100747	9338	excluding results of nested sql query	select previous.loser from table1 previous where previous.winner=currentloser and (    select count(*)    from table1 ancient    where (ancient.winner=currentwinner and ancient.loser=previous.loser) or          (ancient.loser=currentwinner and ancient.winner=previous.loser)    ) = 0 	0.294755032058119
25102531	10648	how to count the employees in each department	select b.employee_id,b.salary, a.department_id, a.department_name,   max(b.salary) over (partition by a.department_id) as max_sal from        department a, employee b where       a.department_id(+) = b.department_id and         a.department_id in (     select department_id from employee     group by department_id     having count(employee_id) > 2 ) 	0
25103485	33780	sql comparing values in two rows	select      a.category,      case when a.salesvolumes < b.salesvolumes then 'true' else 'false' end as salesincreasing from mytable a inner join mytable b on a.category = b.category where a.year = 2002 and b.year = 2003 	0.000629932500064185
25103689	3080	convert date format in the select statement	select col1, col3, col3, convert(varchar(10),[date registered], 105), col5, col6, col7 from dbo.car  where dbo.car.[date registered] > dateadd(year, -3, getdate()) and  dbo.car.rentalcost < 350  order by [date registered] desc, brand asc; 	0.0381664702715107
25103901	3983	how can i make a stored procedure return a bit value?	select cast(1 as bit) as authenticated 	0.110477833519974
25105778	13685	query with join on multiple tables	select * from components t1 left join table_321 t2 on t1.code=t2.code left join table3 t3 on t3.code = t1.code where t1.cost=null or t1.cost='' order by t1.code 	0.285933574388451
25106539	6576	how to verify the correctness of the integration of 30 tables into one table on sql server 2008 r2 on win7?	select id from small_table except select id from big_table 	0
25109580	8866	return the count of all records per day of week by clientid	select clientid, [0], [1], [2], [3], [4], [5], [6], [7] from (select clientid, datediff(day,processtime,getdate()) days     from callrecords     where datediff(day,processtime,getdate()) <= 7) t pivot (count(days) for days in ([0], [1], [2], [3], [4], [5], [6], [7])) pt 	0
25112279	12908	group by id after order by time	select fid, timediff  from (           select facebook_id as fid,            timestampdiff(second, `time`, '$mytime') as timediff           from `table`           where `facebook_id` != $fbid           having `timediff` <= '180'           order by `time` desc          ) entries  group by entries.fid 	0.0110217537804854
25112290	11775	sum mysql table column value	select    sum(hours) - sum(newhr)   from subscriber    where    uid='$_session[uniqid]' 	0.00258220136253965
25112681	8904	mysql limit with in statement	select t.* from (select    `user_bookmarks`.`id` as `user_bookmark_id`,   `bookmark_id`,   `user_bookmarks`.`user_id`,   `bookmark_url`,   `bookmark_website`,   `bookmark_title`,   `bookmark_preview_image`,   `bookmark_popularity`,   `category_id`,   `category_name`,   `pdf_txt_flag`,   `youtube_video`,   `content_preview`,   `snapshot_preview_image`,   `mode` ,    @r:= case when category_id = @g then @r+1  else @r:=1 end `rank` ,    @g:=category_id from   `user_bookmarks`    left join `bookmarks`      on `user_bookmarks`.`bookmark_id` = `bookmarks`.`id`    left join `categories`      on `user_bookmarks`.`category_id` = `categories`.`id`    join (select @r:=0,@g:=0) t1 where `category_id` in (164, 170, 172)  order by category_id ) t where t.rank <=6 	0.754981210537574
25118561	9052	postgres count customers with 2 or more orders	select extract(month from datecolumn ) as month,email from shop_orders where status_code = 'confirmed' group by extract(month from datecolumn ),email having count(1) >2 	0.00196245128677312
25119729	22339	calculate win/loss streak query	select      sum(iif(result = 'w', 1, 0)) as totalwins,      sum(iif(result = 'l', 1, 0)) as totallooses from table1; 	0.374876309649623
25119746	34809	show query output / number of total records	select count(*) || '/' || (select count(*)                            from rdf_nav_link as link2                            where link2.functional_class = link.functional_class),        functional_class from rdf_nav_link as link where link_id not in (select dest_link_id        from rdf_sign_destination)   and link_id not in (select originating_link_id from rdf_sign_origin) group by functional_class 	0
25120765	12406	how to join 2 tables and show records in tableview	select * from questionwithanswer as q join records as r on q.date=r.datewithtime; 	0.000247606448191501
25122451	18014	sql server - detect a cell match	select serialno,  sum(quantiy) as quantityremaining from yourtable group by serialno order by serialno 	0.0348042494224428
25122590	12849	how to execute "in" subquery only once	select style  from storage s where not exists(select * from validstyles vs where vs.validstyle=s.style) 	0.033126352876756
25122760	36466	mysqli: select from table where field equals field from other table	select words.word, synonyms.synonym from words left join synonyms on words.word_id=synonyms.word_id where words.word_id = ? 	0
25124175	15439	a query to return a row only when that row lacks a particular value	select distinct cui   from foo where cui not in (select distinct cui from foo                       where  sab = 'snomedct_us') 	0
25124419	18528	sql select one row from table 1 joining on multiple rows in table 2	select i.name  from interests i where i.interest in ('books','dancing') and not exists (   select 1 from interests i1   where interest not in ('books','dancing')   and i.name = i1.name ) group by i.name having count(*) = 2 	0
25124927	22995	split sql row if value of a column is greater than 0	select name,  labor, 0 as parts,0 as misc from table  where labor > 0 union all select name,   0 as labor, parts,0 as misc from table  where parts > 0 union all select name,  0 as labor, 0 as parts,misc from table  where misc > 0 	0
25125026	38849	rewriting a sql without repeating a parameter	select (case when p_param1 = 'rev' then sum(net_invoice_revenue) else sum(quantity)         end) as val  from (select @param1 as p_param1, @agreement_csv as p_agreement_csv,              @part_number as p_part_number, @flag1 as p_flag1, @flag2 as p_flag2,              @a_start_date as p_a_start_date, @a_end_date as p_a_end_date      ) params cross join      pa_trans tr join      pa_sold_to cust       on  tr.sold_to_customer = cust.sold_to_customer  where agreement_nbr = p_agreement_csv and        part_number = p_part_number and        cust.ww_corp = case when (p_flag1 = 'n' and p_flag2 ='n') then @ww_corp else cust.ww_corp end and        cust.ww_affliate = case when (p_flag1 = 'n' and p_flag2 ='y') then @ww_affliate else       cust.ww_affliate end and         ( day >= p_a_start_date and  day < p_a_end_date); 	0.611037561026285
25125211	20851	join table showing no results	select email, tags, lname, fname, company from nameinfo join contacts using (email) 	0.0944707854022109
25126711	14803	postgres: get aggregation query based on multiple values in a column	select owner_id, count(partner_id),        sum(case when level = 'gold' then 1 else 0 end) as gold,        sum(case when level = 'silver' then 1 else 0 end) as silver,        sum(case when level = 'bronze' then 1 else 0 end) as bronze from owner_partner group by owner_id; 	5.57926618692063e-05
25127222	23674	sql server query to select records for a specific foreign key/month combination, or the master record if one does not exist for that day	select      coalesce(meal.description, master_menu.description) as mealdescription,   from meal   left join master_menu  on meal.mealdate = master_menu.mealdate  where providerid = @providerid    and datepart(month, mealdate) = @month    and datepart(year, mealdate) = @year  order by mealdate asc; 	0
25127455	14071	designing a database of sets	select * from element where set_id = <whatever> 	0.0464442170460646
25127754	19039	joining tables through relational table	select   c.*,   p.* from    companies c left join   relations r on (r.parentmodule = 'companies' and r.parentrecordid = c.id) left join   people p on (r.childmodule = 'people' and r.childrecordid = p.id) 	0.0328925893528291
25131449	37128	how to split a string and compare with a column that string is present or not in mysql	select *, skillset from tresume_mas where skillset regexp '.net framework|java j2ee'; 	0.000326120890841572
25131747	15278	trying to display a combination of string mm + int dd + int yyyy in sql management studio	select datename(mm, check_in_date) + ' ' + cast(day(check_in_date) as nvarchar(2)) + ' ' + cast(year(check_in_date)  as nvarchar(4))      from book_details 	0.0693680979598261
25135739	20793	do not show the data if there is no role admin	select firstname, lastname, rolename  from user  inner join userrole  on userrole.userid = user.userid  inner join role  on role.roleid = userrole.roleid  where user.userid not in      (select userid      from userrole as ur      where ur.roleid = (select roleid from role as rn where rn.rolename = 'admin')     ) 	0.0447868494575019
25136651	13765	how can i add rows to a query depending on data in specific fields	select studnr,        mark || '' mark,        module from table1 union select studnr,        result mark,        'result' module from table1 where module = 'mod01' 	0
25137607	22703	sql query to count sessions without repeating lines	select count(distinct sess.user_id) as total from sessions as sess inner join users as user on user.id = sess.user_id where user.equipment_id = 1 and sess.datestart = curdate() 	0.0329219412352884
25138586	5282	count considering sum of 3 columns	select       (prod1 !=0 ) + (prod2 != 0) + (prod3 != 0) as allc  from `testprd`  where id = 3 	0.000832587494292555
25138848	10296	how do i split two or more inner joins into multiple select statements	select emas.cempnoee, emas.cempname, emas.cempemail, esrvc.csrvposition, esrvc.csrvbranch, esrvc.csrvcostcentr from emas inner join esrvc on emas.cempnoee = esrvc.csrvnoee into cursor esc select *, cbranch.cbrndesc from esc inner join cbranch on esc.csrvbranch = cbranch.cbrncode into cursor esbc select *, eaddrs.caddnophoneh from esbc inner join eaddrs on esbc.cempnoee = eaddrs.caddnoee 	0.118238415852249
25140253	15366	retrieving historical queries	select  a.plan_handle ,         a.sql_handle ,         e.text     from    sys.dm_exec_query_stats a         cross apply sys.dm_exec_sql_text(a.plan_handle) as e where text like '%somevalue%'   	0.0387449553067023
25141164	10269	sql arithmetics with unique cells of tables	select tom08/tom, tom920/tom, tom2135/tom, tom3650/tom, tom51/tom   from table1 t1, table2 t2  where t1.ppoint = t2.ppoint; 	0.00478118151761785
25141600	28084	querying a table that contains an xml column	select top 1000 [id]     ,[name]     ,[value] from [mytable] where cast(value as varchar(max)) like '%something%' 	0.00279379269168685
25141681	17880	select sum of column b based on distinct prefix of column a	select left(account,3) accountprefix, sum(qty) sumofqty  from mytable group by left(account,3) 	0
25143121	9600	detect differences between two versions of the same table	select min(table_name) as table_name, col1, col2 from (    select    'table_1' as table_name, col1, col2    from table_1 a    union all    select    'table_2' as table_name, col1, col2    from table_2 b ) tmp group by col1, col2 having count(*) = 1 + | table_name | col1 |    col2    | + | table_2    |    2 | two        | | table_1    |    2 | two        | | table_1    |    3 | three      | | table_2    |    4 | four       | + 	0
25144038	16800	i want to arrange the topics by date and display its category	select t1.topic_id, t1.topic_subject, t1.topic_date, t1.topic_cat, c1.cat_name, c1.cat_description      from topics t1 left join categories c1 on t1.topic_id = c1.cat_id order by t1.topic_date desc 	0
25144894	40914	nested sql queries on one table	select bld_stat,  sum(case when bld_type = 'singl_flr' then 1 else 0 end) as single_flr, sum(case when bld_type = 'multi_flr' then 1 else 0 end) as multi_flr, sum(case when bld_type = 'trailer' then 1 else 0 end) as trailer, sum(case when bld_type = 'whs' then 1 else 0 end) as whs from bld_inventory  group by bld_stat 	0.0957159273177645
25149414	21659	duplicate select rows even distnict	select a.comment       ,a.replymsg       ,a.rep_datetime       ,a.adminreply from (         select    tbl_comment.comment                 , tbl_reply.replymsg                 , tbl_reply.rep_datetime                 , tbl_adminreply.adminreply                 , row_number() over (partition by tbl_comment.comid order by tbl_reply.rep_datetime desc) rn         from tbl_adminreply          inner join tbl_comment    on tbl_adminreply.comid = tbl_comment.comid          inner join tbl_reply      on tbl_comment.comid    = tbl_reply.comid           where      tbl_comment.comid = 3        ) a where a.rn = 1 order by a.rep_datetime desc 	0.00433983942782683
25149936	28835	sql repeate or duplicate results	select  emp.name, emp.lastname, emp.birthdate, emp.gender from employee emp inner join (select 1 as a union all select 2) a on 1 = 1 where employeeid = 1 	0.268396076571645
25152005	14196	sqlite finding all documents containing a word	select docid from wordsindoc where wordid in (17, 23, 37, 42, 69, 105, 666) group by docid having count(*) = 7 	0.00124832394709941
25156798	32623	repeated column values as column header in sql server	select filename,  case when filestage='start' then filestage else null end as start, case when filestage='middle' then filestage else null end as middle, case when filestage='end' then filestage else null end as end, case when filestage='archive' then filestage else null end as archive from table1 	0.00646002645804813
25158505	24591	get data by "priority"	select * from local.strings s where lang = 'fr' union all select * from local.strings s where lang = 'en' and       not exists (select 1 from local.strings s2 where s2.key = s.key and s2.lang = 'fr'); 	0.00626620901064547
25160395	24076	sql 2000 data format using a group by query	select t1.org, (t1.value - t2.value) / t1.value from mytable t1 inner join mytable t2 on t1.org = t2.org and t1.type = 1 and t2.type = 2 	0.475541903022893
25160707	9299	how to get the elapsed minutes between to dates in sql	select datediff(minute,starttime,endtime) from downtimeevent where eventid = 1; 	0
25160875	8321	filter rows based on column values in mysql query	select     * from ( select      a.model_name,     a.model_created_on,      if( b.officially_released_year = '".$currentyear."',1,0 ) as release_year,      if( b.officially_released_month = '".$first_month."' or b.officially_released_month = '".$second_month."' or b.officially_released_month = '".$third_month."' or b.officially_released_month = '".$currentmonth."' ,1,0) as release_month  from ".tbl_car_add_models." a, ".tbl_car_spec_general." b  where a.model_id = b.model_id and a.model_status = '1'  ) as tbl where tbl.release_year=1 and release_month=1 order by tbl.model_created_on desc 	6.70289244395904e-05
25161760	27047	get more columns from inner select using postgresql	select     "slno",     "rlno",     0 as got,     nm,     addr from  (     select "rlno", "slno", nm, addr, count(*) over (partition by "rlno") cnt     from (         select distinct on ("slno", "rlno")             "s1no", "r1no", "name" as nm, "address" as addr         from alldata     ) b ) a where cnt > 1 	0.00462717490812688
25162419	40479	sql left join in history table	select     ca.carkey,     description,     cow.other_info as wanted_color,     cco.other_info as current_color,     cch.datetime as current_color_datetime from     cars ca     left join     colors cow on ca.wanted_color = cow.colorkey     left join (         select distinct on (carkey) *         from car_color_history         order by carkey, datetime desc     ) cch using(carkey)     left join     colors cco on cch.colorkey = cco.colorkey 	0.713395597388767
25164668	14445	grouping/summing arbitrary field	select sum(case when color in ('blue','cyan','indigo','navy') then count end) as blues_count,        sum(case when color in ('purple','violet') then count end) as purples_count,        sum(case when color in ('forest','green') then count end) as greens_count from your_table 	0.0542804310855126
25165166	30613	single query for multiple sql queries	select ifnull(sum(hit='hit'),0) as hits, ifnull(sum(comment !=''),0) as comments    from fk_views where onid='$postid' and email='$email' 	0.191151378921724
25166998	25097	selecting the highest values from database, unique to customer name?	select  customerid ,       customername ,       convert(varchar(7), daterecorded, 120) as [month] ,       max(sqft) as maxsqftthismonth from    squarefootage group by         customerid ,       customername ,       convert(varchar(7), daterecorded, 120) 	0
25170470	18539	mysql left join count() and sum() with case from same table	select         count(distinct statistics_meter.id) as meter_count,         count(statistics_meter.id) as check_meter_count         from company_company         left join company_portfolio on company_portfolio.company_id=company_company.id         left join building_site on building_site.portfolio_id=company_portfolio.id         left join statistics_meter on statistics_meter.building_id=building_site.id         left join (select * from statistics_meter where parent_meter_id is not null) sm2 on sm2.parent_meter_id = statistics_meter.id 	0.0771854292965418
25170775	22072	query last element in array from json structure in postgres	select t.col->'items'->(json_array_length(t.col->'items')-1) from   tbl t 	0.00020270009172717
25171928	34624	search for groups of first words	select min(fazerbem_dates) from table t group by substr(fazerbem_dates, 1, 10); 	0.00113158124799686
25173897	4400	mysql fetch data with count and between date	select zip     , count(1) as count from table1 where created between '2014-08-04 00:00:00' and '2014-08-08 23:59:59' group by zip order by count desc 	0.00109391967457099
25174488	17491	sql query with different averages for different columns for the same data	select name, avg(case when rank <= 10 then score end) avgpast10,   avg(case when rank <= 50 then score end) avgpast50   from (      select name,       @rank := if(@name = name, @rank+1, 1) as rank,      @name := name, score      from tbl      order by name, id desc      ) a group by name 	0
25175419	16133	fetch latest record inserted by system	select * from (    select * from yourtable where id = 111 and type = 'i' and user = 'system' order by    date_ desc ) qry where rownum = 1; 	6.91535037980677e-05
25175676	40193	mysql sort multiple timestamp	select * from ( select * from `admin action` union all select * from `user action`) as a order by timestamp 	0.0223055164846901
25176641	17702	mysql database query with join and count	select a.clientid, a.profileid,        b.zone_id, c.zone_name from tblad_clicks a inner join tblprofiles b on a.profileid = b.profileid inner join tblzones c on b.zone_id = c.zoneid where a.profileid > 0; 	0.557636754689918
25177054	20206	converge duplicate rows in sql server	select     suppid, areaid,     count(*) as dupecount,      case when count(*) > 1 then null else max(suppno) end from     (     values (1, 3, 526), (1, 3, 985), (3, 4, 100)     ) as mytable (suppid, areaid, suppno) group by     suppid, areaid; 	0.0212349980780074
25177737	4018	sumproduct in sql	select sim, ((a.typea * b.typea) + (a.typeb * b.typeb) + (a.typec * b.typec)) 'ba der', ((a.typea * c.typea) + (a.typeb * c.typeb) + (a.typec * c.typec)) 'bsl enh' from tbl1 a, tbl2 b, tbl2 c where b.assetid = 'ba der' and c.assetid = 'bsl enh' 	0.681542312146626
25177881	35868	query a column containing comma separated string	select c.*  from `directoryprogramme` c  where find_in_set('1234',`c`.`presenters`) > 0 or `c`.`staff` = 1234 order by `name` asc 	0.000615026214486494
25178683	24227	grouping and adding results by month	select      company,      sum(case when timestampdiff(                       month,                        last_day(invoicedate) + interval 1 day,                        last_day(now()) + interval 1 day) > 1               then amtdue else 0 end) 60days,     sum(case when timestampdiff(                       month,                        last_day(invoicedate) + interval 1 day,                        last_day(now()) + interval 1 day) = 1               then amtdue else 0 end) 30days,     sum(case when timestampdiff(                       month,                        last_day(invoicedate) + interval 1 day,                        last_day(now()) + interval 1 day) = 0               then amtdue else 0 end) current,     sum(amtdue) total from      quotes group by      company; 	0.00646656496596719
25180181	28422	how to join table and retrieve records containing either parent or child info, but not both?	select     min(guests.name) as name,     reservations.booking_code as code from     reservations join     guests on         reservations.booking_code = guests.booking_code or         reservations.booking_code = guests.parent_booking_code group by code order by name; 	0
25180293	39342	select records based on a non unique column	select * from smp_audit_detail where auditidentity in    (select distinct auditidentity  from smp_audit_detail limit 100) 	0
25182753	40237	sql - select all values id's and count how many time they appear within the last month	select     i.name, x.total  from       item i left join  (select   item_id, count(item_id) as total              from     tracking              where    date > date_sub(now(), interval 1 month)              group by item_id) x on i.id = x.item_id 	0
25185455	20980	how to do sum of product of two columns in postgres and group by two columns?	select date,          store_id,          sum(on_hand*cost) inv_costs,          sum(on_hand) total_on_hand     from inventory    where store_id in (100,101) group by date,           store_id 	0
25185722	2212	mysql cannot join columns from different database having different data type	select hex(id), id2, count   from `database 1`.`table 1` a  inner join `database 2`.`table 1` b on binary hex(`a`.id) = binary upper(`b`.id) 	0.000384958955467763
25186873	13141	mysql opposite query of a join	select * from hdb.addressesconsultants a (nolock) left outer join orderconsultants o (nolock) on a.consultant = o.consultant and a.orderno = o.orderno where o.consultant is null and o.orderno is null 	0.379684719815603
25191523	3877	counting occurrences of duplicates in multiples fields in sql	select t.agentid, count(*) as badcalls from callrecords as t inner join callrecords as h on   t.routercallkey = h.routercallkey   and t.peripheralcallkey = h.peripheralcallkey   and h.sequencenumber > t.sequencenumber where   t.calldisposition = 'transfer'   and h.calldisposition = 'handled'   and t.sequencenumber = 1   and t.agentid <> h.agentid group by   t.agentid 	0.000231795514756564
25195258	39719	weekly total change name	select 'week ' + convert(varchar(255), datepart(ww, d_date) - 26) as reportingweek,        proj_name, sum(expr1) as total from  dbo.view_test_two group by datepart(ww, d_date), proj_name order by min(d_date); 	0.00101713687879245
25196596	10986	removing duplicate records from a joined table and leaving the last occurrence records?	select  * from    (select a.id, a.name,b.modifieddate,                 row_number() over (partition by a.id order by b.modifieddate) as rownumber          from tablea a, tableb b where a.id  = b.tabid ) as temp where   temp.rownumber = 1 	0
25198201	38210	sql sum with subquery	select sum(czas1)  from  (          select      (         select max(czasy)           from          (             values (czas),(czas_trw)         ) as all_val(czasy)     ) as czas1      from projekty_etapy2 pe2      where pe2.id_projektu=34 ) as t; 	0.685092340453809
25198377	9184	sql counting multiple rows as one query	select count(*) from   tblcolors t1        left join tblcolors t2            on t1.id = t2.id - 1        left join tblcolors t3            on t2.id = t3.id - 1 where  t1.color_name + '-' +        t2.color_name + '-' +        t3.color_name = 'red-blue-white' 	0.00300030135200655
25198795	24285	update [can check if the date is future ]	select distinct name from mytable 	0.0392449524056197
25199270	11679	how to find all rows that have all values which has another row	select `name` from students join (select distinct s_id     from marks as marks1     where marks1.`s_id` not in(         select distinct marks2.s_id         from (select score             from marks             join students on marks.`s_id` = students.`id`                            and students.`name` = 'c') as c_scores         cross join marks as marks2                             on marks2.`s_id` not in (                             select s_id                             from marks                             join students on marks.`s_id` = students.`id`                                            and students.`name` = 'c')         left join marks as marks3 on marks3.`s_id` = marks2.s_id                                    and marks3.`score` = c_scores.score         where marks3.`s_id` is null     )) as good_ids on students.`id` = good_ids.s_id where `name` != 'c' 	0
25199294	11870	mysql copy function/procedure between databases using only sql	select * from `mysql`.`proc` 	0.027750998594082
25199418	36512	sql : avoiding duplicates by comparing the consecutive rows	select td.ps_driver from tabdrivers td where td.ps_completion_ts in (select max(td2.ps_completion_ts)                                from tabdrivers td2                                where td2.ps_driver = td.ps_driver  ) 	0.00219802739226655
25203316	4426	sql syntax = display relations inside "one table" + one relation table	select d1.dep_name, d2.dep_name, d3.dep_name, d4.dep_name from tbl_department d1 join tbl_relation r1 on r1.rel_parent_id = d1.dep_id join tbl_department d2 on d2.dep_id = r1.rel_child_id left join tbl_relation r2 on r2.rel_parent_id = d2.dep_id left join tbl_department d3 on d3.dep_id = r2.rel_child_id left join tbl_relation r3 on r3.rel_parent_id = d3.dep_id left join tbl_department d4 on d4.dep_id = r3.rel_child_id where d1.dep_name = 'none' 	0.00304421928452582
25205601	22782	joining three table together using an sql statement to grab data from each table	select jokes.*,category.*,comments.* from jokes  inner join category on jokes.category_id=category.category_id  inner join comments on jokes.joke_id=comments.joke_id  where jokes.joke_id = '$joke_id'; 	0
25207771	15604	sql server, how to merge two columns into one column?	select table_schema + '.' + table_name as columnz  from information_schema.tables 	0
25208311	41056	how to avoid a duplicate row situation in mysql query below?	select r.id, r.phone, st.title, rhs.comment, rhs.date from (     select r.id, max(rhs.date) as date     from requests_has_statuses as rhs     inner join requests r on r.id = rhs.requestid     group by r.id) as temp inner join requests as r on temp.id = r.id inner join requests_has_statuses as rhs on rhs.requestid = temp.id and rhs.date = temp.date inner join statuses as st on rhs.statusid = st.id 	0.203328330605703
25208600	26680	unable compare the values of two columns of two tables and returning the best row if it is in the first table	select t1.product,        (case when t1.price >= coalesce(t2.price,0) then t1.price              else null         end) as price,        (case when t1.tax >= coalesce(t2.tax,0) then t1.tax              else null         end) as tax from (select product, max(price) as price, max(tax) as tax from table1 group by product) t1 left join      (select product, max(price) as price, max(tax) as tax from table2 group by product) t2      on t1.product = t2.product; 	0
25209021	4187	mysql how to query total returned rows in group by situation	select      t.todays_date, t.quantity, t.item_id, t.description, t1.num_plu from (   select           curdate() as todays_date,          qty as quantity,          plu as item_id,          item as description      from transact      where qdate  between ('2013-07-01' and '2014-07-10')       and location ='8'      group by counter ) t join (   select         plu, count(distinct plu) as num_rows     from transact     where qdate  between ('2013-07-01' and '2014-07-10')       and location ='8'  ) t1 on t1.plu = t.item_id 	0.00603442510401443
25209197	18160	mysql join to include non-matching records in where statement	select table1.empnum, table1.firstname, table2.id, table2.secretkey, table2.nickname  from table1 left outer join table2  on table1.empnum = table2.id where table1.emptype = '88' 	0.145657180625201
25210245	8341	how to do an in statement with a sub query returning 2 columns and one of the columns is a count	select * from guitars.fender where fender.guitartype in (     select guitartype     from guitars.guitar_type     where guitarcolor = 'red'     group by guitartype     having count(*) = 1) 	0.000216587188483308
25212453	8642	join with date dimension but don't want null for the dates with values	select * from (   select distinct     d.fiscalmonth,     d.fiscalmonthofyear,     p.name   from dimdate   d   join factsales f on f.saledate=d.pkdate   join dimperson p on p.personid=f.personid   where d.fiscalyear='2014/7/1' ) union (   select     d.fiscalmonth,     d.fiscalmonthofyear,     null as name   from      dimdate   d   left join factsales f on f.saledate=d.pkdate   where d.fiscalyear='2014/7/1'   group by d.fiscalmonth, d.fiscalmonthofyear, p.name   having count(f.saledate)=0 ) order by fiscalmonthofyear asc, personid asc 	0.0020674119946215
25212912	26120	mysql join 2 tables on non-unique column and with timestamp conditions	select part_name,         category,        (select name           from categories_revisions          where categories_revisions.match_id = parts_revisions.category             and categories_revisions.timestamp = (select max(categories_revisions.timestamp)                                     from categories_revisions                            where categories_revisions.match_id = parts_revisions.category                             and categories_revisions.timestamp < parts_revisions.timestamp)) as name    from parts_revisions; 	0.00251925187817566
25213718	35301	excluding pairs of values occurring non-exclusively	select distinct least(t1.p1, t2.p2), greatest(t1.p1, t2.p2) from (  select p1, max(p2) as p2  from (select min(playernum) as p1, max(playernum) as p2 from games group by gamenum union select max(playernum) as p1, min(playernum) as p2 from games group by gamenum) as q1  group by q1.p1  having count(distinct p2)=1 ) as t1 , (  select min(p1) as p1, p2  from (select min(playernum) as p1, max(playernum) as p2 from games group by gamenum union select max(playernum) as p1, min(playernum) as p2 from games group by gamenum) as q2  group by q2.p2  having count(distinct p1)=1 ) as t2 where t1.p1=t2.p1 and t1.p2=t2.p2 	0.000410140201470505
25214617	13183	returning lowest value of a field from rows formed from joined tables	select      *  from (   select          cp.promotionid,          name,          startdate,          enddate,          issuer,          company_name,          p.productid,          p.promotionprice      from company_promotions cp     join productpromotions p on p.promotionid = cp.promotionid     join promotion_general pg on pg.promotionid = cp.promotionid     order by cp.promotionid desc ) t  group by company_name, productid 	0
25215100	9027	how to add column to cachedrowset in java 7?	select a,b,'additional' from ... 	0.0106512094424993
25216341	37987	search in json values from mysql tables	select id,name,ccode,json, cast(substring(substring_index(json, ',', 1)  from 8)  as unsigned) as val  from events  where ccode=231  having val>15 and val<24; 	0.00648009257195714
25216739	8453	correct sql query to return null when optional fk row doesn't exists for pk row (1 to none/many)	select     i.item_id, i.item_name, i.idem_desc,     p.quantity, p.price from items i left join item_properties p on i.item_id = p.fk_item_id where i.item_id = 191 	0.597511691298274
25218372	15438	mysql - counting different values ​​of the same field	select     name,     sum( win = 'y' ) as wins,     sum( win = 'n' ) as losses from games group by name; 	0
25219369	28333	pull out data from different tables in mysql	select c.* from   categories c join   newspaper_categories nc on c.category_id = nc.categroy_id join   newspaper_users nu on nu.newspaper_id = nc.newspaper_id where  nu.user_id = <some id> 	0.000145566862848818
25219840	30188	how to check if records within selected date using multiple tables?	select b.id, b.name,        sum(timestampdiff(minute, rv.date_start, rv.date_end))/60 as meetinghours,        max(hours_end - hours_start)*count(distinct r.id) as buildinghours from buildings b join      information bi      on b.id = bi.building_id      rooms r      on b.id = r.building_id left join      reservations rv      on rv.room_id = r.id and         '2014-08-09' between date(rv.date_start) and date(rv.date_end) group by b.id having meetinghours is null or meetinghours < buildinghours; 	8.17066066543911e-05
25225465	25429	mysqli querying 2 tables, but retrieve only results not in the other table	select group_name from right_table rt where not exists (     select 1     from left_table lt     where lt.member_id = 100     and lt.group_id = rt.id ) 	0
25225709	24110	syntax of select into	select * into newtable from currenttable; 	0.198849808610861
25227468	17884	multilingual database - get all languages of post	select t.*,   (select group_concat(l1.name separator ',')     from translation t1     join languages l1 on l1.id = t1.language_id     where t1.product_id = t.product_id     group by t1.product_id   ) as lang_names from translation t   where t.id = ? 	0.000174061467746383
25228442	674	mysql group by descending order	select id from mytable t1 where dir = 3 and not exists (     select 1     from mytable t2     where t1.version < t2.version     and t1.dir = t2.dir     and t1.fid = t2.fid ) order by version 	0.18134995338034
25229126	12332	copy email address from table and paste them in a text field , seperated by commas	select group_concat(email) as emails from table ; 	0
25229874	22310	what type of join for linking table to get results matching both values?	select studentid    from sc  where courseid in (1,2)  group by studentid  having count(*) = 2 select sc1.studentid    from sc as sc1   join sc as sc2     on sc1 courseid = 1    and sc2 courseid = 2     select studentid        from sc      where courseid = 1   intersect     select studentid        from sc      where courseid = 2 	6.62851425804562e-05
25232288	6231	mysql select query if the curdate between two dates of every month	select m.member_name        from member m, `club_name` c    where m.cabinet = 1 and c.wmmr_report=0 and m.club_name=c.id and day(now()) >24 	0
25234813	868	mysql user defined variable and order by on a dynamic column	select (@position:=@position + 1), value_new from (select (statistics.value - statistics_logs.value) as value_new       from rankings r left join            rankings_logs rl            on rl.name = r.name and sl.user_id = s.user_id       order by value_new desc      ) cross join      (select @position := 0) vars; 	0.0784933753950969
25237329	4205	sql query to get data in a table that starts with some specific row for ios app	select * from tbl where listid = 5 order by wordid <> 58 	8.33731441956624e-05
25237439	9580	sql server for xml path add attributes and values	select ( select 'white' as color1, 'blue' as color2, 'black' as color3, 'light' as 'color4/@special', 'green' as color4, 'red' as color5  for  xml path('colors'),  type  ),  ( select 'apple' as fruits1,  'pineapple' as fruits2,  'grapes' as fruits3,  'melon' as fruits4  for  xml path('fruits'),  type  )  for xml path(''),  root('samplexml') 	0.0281898599731772
25239162	35551	calculate in-out time for each employe	select emp_id, date, min(time), max(time) from your_table group by emp_id, date; 	0.000251943420289066
25240090	19218	how to concatenate a string, an integer and a sequence in sql server 2014	select 'dtr' + cast((next value for dtr_seq)  as varchar(20))         + cast(@lc_org_unit_id  as varchar(20)) 	0.00954957215292964
25240483	34539	mysql get 10 recent comments with all sub comments	select c.`id`, c.`parent_id`, c.`user_id`, c.`text`  from `comments` c, (    select `id` from `comments`     where `post_id` = '$postid'     order by `time` desc     limit 10 ) temp where c.id = temp.id or c.parent_id=temp.id 	0
25241496	24746	pivot table in sql server	select slno,joiningdate,[1],    [2],    [3],    [4],    [5],    [6],    [7],    [8],    [9],    [10],   [11],   [12],   [13],   [14],   [15],   [16],   [17],   [18],   [19],   [20] from  ( select slno,joiningdate,jtime=left(joiningtime,2) from table1) as a pivot (count(jtime) for jtime in ([1],  [2],    [3],    [4],    [5],    [6],    [7],    [8],    [9],    [10],   [11],   [12],   [13],   [14],   [15],   [16],   [17],   [18],   [19],   [20])) pvt 	0.479620720106561
25242647	2828	select field on multiple values	select * from terrainlayer where tags like '%ground%rocks%'; 	0.00313106760172721
25242697	29008	how to call the stored procedure from select statment	select p.*,        stuff((select ',' + variant_name               from variant v               where v.productid = p.productid               for xml path ('')              ), 1, 1, ''             ) as variants from product p; 	0.307146037765166
25243378	36223	set a condition on an email being sent from an sql database	select first_name, last_name from sc_application where candidate_id = $user_id and submitted = 0 	0.00729105211920302
25245008	972	sql select only rows with max value on a column filtered by column	select yt1.* from yourtable yt1 left outer join      yourtable yt2      on yt1.id = yt2.id and yt1.val < yt2.val and yt2.ignore <> 1 where yt2.id is null and yt1.ignore <> 1; 	0
25245016	11170	how to concat data using coalesce in mysql	select group_concat(manualrefund_strreasoncode separator '|') from tblmanualrefunds where manualrefund_lngid in (20,21,22) 	0.567765082093913
25245466	35666	pivot the columns in sql server	select    left(measure, charindex('_', measure)-1) as measure,   left(measure, charindex('_', measure)-1) + '_a1' as measure_a1,    sum(case when right(measure,2) = 'a1' then ytd else 0 end) as ytd_a1,   sum(case when right(measure,2) = 'a1' then q1 else 0 end) as q1_a1,   sum(case when right(measure,2) = 'a1' then q2 else 0 end) as q2_a1,   left(measure, charindex('_', measure)-1) + '_a2' as measure_a2,    sum(case when right(measure,2) = 'a2' then ytd else 0 end) as ytd_a2,   sum(case when right(measure,2) = 'a2' then q1 else 0 end) as q1_a2,   sum(case when right(measure,2) = 'a2' then q2 else 0 end) as q2_a2 from structure group by left(measure, charindex('_', measure)-1) 	0.119742043272572
25247334	2854	count( ) on multiple columns each having a condition	select  name, sum(present = 1) presentcount, sum(absent = 1) absentcount, sum(leaves= 1) leavescount from attendance group by name 	0.000101973054038556
25247403	17915	mysql - where a list of keys is not in subselect	select distinct(obt.oid) as oid, o.borrower_email from `order_borrower_tracker` obt  left join `orders` o      on obt.oid=o.oid left join `order_status_history` h     on h.oid=obt.oid and h.new_status in (18,27,29,41,53) where obt.date_acknowledged_edelivery = 0  and h.oid is null 	0.201982350997816
25248299	30096	three tables inner join	select distinct count(i.itemid) from `item` i      inner join `bidding` b on i.itemid = b.itemid     inner join `user` u on b.userid = u.userid where i.received=1 and u.userid=2 group by u.userid 	0.523901095774074
25249007	7291	sql server group by each day?	select  count(*) as [count],         datename(dw, erstelltam) as [day] from         abfragen where     (datepart(week, erstelltam) = 21) and (datepart(year, erstelltam) = 2014) group by datename(dw, erstelltam) 	0.000305099927047157
25249833	17817	get top and bottom 25th percentile average	select id, unit_sold, n * 100 / @total as percentile from (   select id, unit_sold, @total := @total + unit_sold as n   from mydata, (select @total := 0) as total   order by unit_sold asc ) as t 	0
25250159	32027	adding a row into an alphabetically ordered sql table	select * from table order by instancename 	0.000395525567096825
25250325	29077	how do you join tables to a view using a vertica db?	select key,count(1) from table group by key having count(1)>1 	0.42400223138175
25250637	12462	sql - select column and add records based on enum	select id, tag from tagtable union all select id, case    when type=0 then 'awesome'   when type=1 then 'super'   {etc} end as tag  from objecttable 	0
25250706	21550	mysql: subquery with returned many row	select p.* from post p join follow f      on f.follow_id = p.user_id     and f.id = '$some_id' where p.type = 'accepted' order by p.id desc limit $page , 20 	0.11341157856842
25251412	19973	mysql get next day & time combination	select date_add(@input_date, interval (8 - dayofweek(@input_date)) day) as next_sunday 	0
25251647	30355	i want to select two different columns from two tables based on another column by sql	select a.fname      , a.lname      , a.sex      , p.eventid      , p.performance_in_minutes   from ( select i.eventid, g.sex, min(i.performance_in_minutes) as fastest_pim            from athlete g            join participation_ind i              on i.athleteid = g.athleteid           where i.eventid in (13)                       group by i.eventid, g.sex        ) f   join participation_ind p     on p.eventid = f.eventid    and p.performance_in_minutes = f.fastest_pim   join athlete a     on a.athleteid = p.athleteid    and a.sex = f.sex 	0
25252293	462	php - count entries from second table that match id from first table	select  s.seriesid, count(*) as numberofseries from    seriestable s join         othertable o on s.seriesid = o.seriescolumn group by s.seriesid order by seriesid desc 	0
25253209	35946	php/mysql: prevent inserting according to several columns	select ip from connex where ip = $ip and datetime > date_sub(now(), interval 30 minute) 	0.000865565679114695
25253317	4234	how do i set date format to `yyyy-mm-ddthh24:mi:ss` in postgresql	select to_char(now(), 'yyyy-mm-dd"t"hh24:mi:ss ') 	0.0474137310843226
25253340	38119	split string into table with rows (multiple delimeters)	select r.* from t cross apply      (select data       from split(t.col, ';')      ) di cross apply      (select max(case when did.id = 1 then did.data end) as isactive,              max(case when did.id = 2 then did.data end) as year,              max(case when did.id = 3 then did.data end) as anniversary,              max(case when did.id = 4 then did.data end) as startperiod,              max(case when did.id = 5 then did.data end) as endperiod       from split(di.data) did      ) r; 	0.000291447503076189
25253867	21029	mysql - sum only distinct row selected	select max(a.id_transaction), a.id_book,         count(distinct case when a.finalized = 'y' then a.id_transaction end) as books_read,         count(distinct case when a.finalized = 'n' then a.id_transaction end) as books_unread,         count( distinct a.id_transaction ) as books_read_unread  from ebook_la_rentalbooks_meter_reading as a where a.id_customer = 33  group by a.id_book  order by books_read desc, books_unread desc; 	0.000478725793281236
25254113	12285	php/mysql: select, count and display (by group?)	select      date(date_time_col),      count(*) as cnt from     your_table group by     date(date_time_col) 	0.00497623240277713
25255716	15637	mysql counting without using having	select cid, cname  from (     select cid, cname, count(*) as counter      from customer c      inner join buys b on (c.cid=b.cid)      group by cid, cname ) as result  where counter > 100 	0.241474947503374
25256972	27125	find missing dates in php	select * from x (      select date       from dateseries      where date between '2014-08-11' and '2014-09-10' ) as x where not in (      select date      from stats     where feeddate between '2014-08-11' and '2014-09-10' ); 	0.00940962334332902
25257381	31368	how to count days between two dates with where conditions	select      userid,      name,      sum(datediff(day, datefrom, dateto)+1) total_leave_days from leave  group by userid, name 	0
25258189	27735	retrieving data from 4 tables with if else condition	select  *  from td_product  where      product_title like '%denim%' )       and (if(has_item=0,product_price,(select max(item_price) from td_item where td_item.product_id = td_product.product_id)) < 2000)      and product_id > 0       and active = 1 	0.00392328257263307
25260043	25285	mysql join multiple query	select   b.title,   if(f.bookmark_id is null, 'no', 'yes') as 'favorite',   if(d.bookmark_id is null, 'no', 'yes') as 'deleted' from user_bookmarks b left join user_deleted_bookmarks d on d.bookmark_id = b.bookmark_id left join user_favourite_bookmark f on f.bookmark_id = b.bookmark_id where b.user_id = 26 group by b.bookmark_id order by b.created_at desc 	0.617244173711783
25260499	15102	mysql search string in table ignoring links	select * from `wp_posts` where post_content like '%about%' and post_content not regexp '>[^>]*about[^<]*<'; 	0.0179622214907818
25261318	31865	sorting different rows based on multiple conditions	select * from (select *       from contacts       order by priority desc       limit 20) union all select * from (select *       from contacts       where id not in (select id                        from contacts                        order by priority desc                        limit 20)       order by name) 	8.23590989809582e-05
25261837	2912	how to select the last data? oracle	select id_emp, name, max(emp.id_invoice) as id_invoice,    max(date_invoice) as date_invoice  from employees emp, invoice inv  where emp.id_invoice = inv.id_invoice group by id_emp, name; 	0.000498102740326767
25263013	29478	how to update resultset in sqlite in java	select id,        name,        [...],        case status          when 'a' then 'active'          when 'd' then 'inactive'          else          'whatever'        end as status from mytable 	0.251207127733823
25263531	32339	sql: aggregate & transpose rows to columns	select     car,     max(case when state = 'new' then tstamp end) as new,     max(case when state = 'old' then tstamp end) as old,     max(case when state = 'scrap' then tstamp end) as scrap from     table group by     car; 	0.0102063675930526
25265305	19057	how do i rewrite my sql query to remove redundant values from a group by column?	select case when row_number() over (partition by [task] order by [task]) = 1 then [task] else '' end as [task],  [activity], sum([consumption]) as totalmin  from [timetable] where [name]=@name     and [month]=@month     and [year]=@year  group by [task], [activity] order by [task] asc 	0.396598372642921
25265857	5065	how to get conditional columns by joining two tables?	select productid, sum(case when shippingoption='ground' then 1 else 0 end) isgrouped, sum(case when shippingoption='ground' then  cost else 0 end) groupcost, sum(case when shippingoption='secondday' then 1 else 0 end) issecondday, sum(case when shippingoption='secondday' then  cost else 0 end) seconddaycost, sum(case when shippingoption='overnight' then 1 else 0 end)isovernight, sum(case when shippingoption='overnight' then  cost else 0 end) overnightcost from shipping group by productid 	0.000371315383773808
25268546	31654	mysql query doesnt display results	select * from pelates where find_in_set(onoma, @giorti) 	0.101887674426457
25268895	15195	sql access, sum one column's values only when all values in another column in are in specified range	select person, sum(giftamount) from tblgifts  where person not in (     select person from tblgifts         where giftdate >  [forms]![inputform]![enddate]              or  giftdate <  [forms]![inputform]![startdate] )  group by person 	0
25269380	30492	return all records where column 2 is equal to 1 (in column 3) without searching in column 2	select * from name where variation_nr in (select variation_nr from name where name = $name); 	0
25269410	21199	google big query sql - get most recent column value	select user_email, user_first_name, user_last_name, time, is_deleted  from (  select user_email, user_first_name, user_last_name, time, is_deleted       , rank() over(partition by user_email order by time desc) rank  from table ) where rank=1 	0.000133028692943997
25270599	39839	fetch data from same table using two group by in mysql	select      count(i.id) as individual_count,     count(g.id) as group_count,     date_format(u.joined_date, '%m') as `month` from usertable as u left join usertable as i on u.id= i.id and i.user_type = 'i' left join usertable as g on u.id= g.id and g.user_type = 'g' group by date_format(u.joined_date, '%m') 	0
25270687	11543	mysql order by with limit to ms sql order by	select top 1 @thesttax = stax from transfers  where masterkey = @skey and effdate <= current_date()  order by effdate desc; 	0.757887635466599
25271600	27739	like wildcard from column value?	select * from table where @var like wildcard 	0.0519181436350957
25272196	31037	how to get substring from a sql table?	select   split_part(account_url, '/', 3) from exp_logs; 	0.0012063026539308
25272906	39806	db2 show the latest row record from users, using the date and time	select userid, max(timeabc) from mytable group by userid 	0
25273531	32987	drop all tables from sql server with the same prefix - vb.net	select table_name from information_schema.tables where table_name like 'a%' 	0.00179763110943454
25274478	13599	how to get search result by a keyword from different table in mysql for php?	select p.title, p.model_no,     b.brand_name,     c.category_title,     s.specification_title from tbl_product as p     left join tbl_brand as b on b.id = p.brand_id     left join tbl_category as c on c.id = p.category_id     left join tbl_product_specification as s on s.product_id = p.id where p.title like 'keyword'     or p.model_no like 'keyword'     or b.brand_name like 'keyword'     or c.category_title like 'keyword'     or s.specification_title like 'keyword' 	0.000243857701365938
25274570	33807	oracle sql cumulative sum with identifying column values	select  'actuals' as data_view,         sum(jan_2014) as jan_14,         sum(feb_2014) as feb_14,         sum(mar_2014) as mar_14 from tablea union all select  'live' as data_view,         sum(jan_2014) as jan_14,         sum(feb_2014) as feb_14,         sum(mar_2014) as mar_14 from tableb 	0.00463160616515759
25274660	16896	stored procedure with more than 1 select statements	select a.* from tablea a inner join tableb b  on a.entityid=b.orderrequestid 	0.614188840880731
25274683	28366	sql : join 2 queries	select id as  'main id', null as  'subpageid', page_asp as  'asp file', page_title_en as  'title', null as  'subtitle', null as  'short title', page_text_en as  'content' from sub_menu where page_title_en like  '%test%' or page_text_en like  '%test%' and active =1 and deleted =0 union  select main.id, sub.id, main.page_asp, main.page_title_en, sub.page_title_en, sub.short_title_en, sub.page_text_en from sub_items as sub inner join sub_menu as main on sub.subid = main.id where sub.page_title_en like  '%test%' or sub.page_text_en like  '%test%' or sub.short_title_en like  '%test%' and sub.active =1 and sub.deleted =0 	0.336513805111123
25274825	5787	sql unify count and sum in one query	select      count(x),     sum(case when z = 1 then x else 0 end)  from tbl where x>y 	0.0615186473990014
25275047	15715	trying to use specific range in select statement but include all in outer join	select    da.account_name,    if (sum(fs.total_sales)> 0, sum(fs.total_sales), 0) as total_annual_sales from dim_account as da left join fact_sales as fs   on da.account_key=fs.account_key  and (fs.date_key >=20100101 and fs.date_key<=20101231) group by da.account_key order by da.account_name 	0.0781856970492328
25277403	138	mysql limit 0,15 where 15 is the number of parent_ids, not children	select    comment.id,   comment.deleted,   comment.comment,   comment.user_id,   comment.created,   comment.parent_id,   s.id as sid,   s.user_id submissionuserid,   u.username,   u.photo as userphoto from (select c.*        from submissions_comments as c       where c.parent_id is null       order by c.created desc       limit 0, 15) as base left join submissions_comments as comment on (   comment.parent_id = base.id    or comment.id = base.id ) left join users u on comment.user_id = u.id left join submissions s on comment.submission_id = s.id where base.deleted = 0 order by base.created desc 	0.00261845579874684
25279007	188	how to sort by 2 columns when joining 2 tables?	select id_image, occurences   from (       select id_image, count(id) as occurences, 2 as priority        from images_bookmarks       group by id_image     union       select id_image, count(id) as occurences, 1 as priority       from images_likes il        group by id_image   ) as favorites   order by occurences desc, priority desc 	0.000157153314271575
25279248	29442	t-sql - concatenation of names on two tables/orphans	select sq.ipartgroupid, cast((     select pn.spartnametext + ',' as [data()] from @partnames pn         inner join @partgroup p on pn.ichildid = p.ichildid     where p.ipartgroupid = sq.ipartgroupid     order by pn.ichildid     for xml path('')     ) as varchar(max)) as [grouplist] from (select distinct pg.ipartgroupid from @partgroup pg) sq     left join @product pr on sq.ipartgroupid = pr.ipartgroupid where pr.iproductid is null; 	0.00432585103419138
25279323	35952	how do i join multiple records into a single record in sql?	select id,        max(case when position = 1 then email else '' end) as primary_email,        max(case when position = 2 then email else '' end) as secondary_email from yourtable group by id; 	0.00016061368948383
25280942	18472	nested select query with count condition	select deals.id, deals.field_b, deals_country.field_c deals_country.field_d,   from deals  inner join deals_country  on deals.id = deals_country.id  where  exists  (     select x.id     from deals_country x     where  x.id = deals.id     group by x.id     having count(x.id) > 1  )   order by deal_id 	0.77846842581618
25282796	14449	mysql-how to parse date which is attached with another string	select * from log where bcreq like '%24-07-2014%' 	0.00549381023734893
25284524	39262	add other column (time) to distinct rows	select  logcontent,max(logtime) logtime from    [webapplog] with (nolock)  where   logname = 'frontenderrorlog' group   by logcontent 	0
25284603	10147	sql how to count number of specific values in a row	select ((case when value1 = 'yes' then 1 else 0 end) +         (case when value2 = 'yes' then 1 else 0 end) +         . . .         (case when value50 = 'yes' then 1 else 0 end)        ) as numyesses 	0
25285204	26330	how to retrieve list from sql alphabetically except one item?	select * from (     select *,      case when <yourvalue> = 'others' then 1 else 0 end as primaryorder      from <yourtable> ) as subquery01 order by primaryorder, yourorderbycriteria 	0
25285942	40287	finding names in string that are not in the database	select names.name from ( select 1 as nameid, 'carl' as name from dual union select 2, 'tom' from dual union select 3, 'dan' from dual union select 4, 'thomas' from dual union select 5, 'beneth' from dual) names , (select 'tom thomas ben john peter' as list from dual) string where length(replace(list, name, '')) =  length(string.list) 	0.000249971401704569
25286039	30703	how to sum listed values in column	select sum(case when col1 in ('a','b') then col2 end) as ab_sum,        sum(case when col1 in ('c','d') then col2 end) as cd_sum from your_table 	0.00173763195903771
25286697	30352	pull numbers out of a decimal	select     cast(case         when substring(cast([tbldate] as varchar),1,8) = 0 then null         else substring(cast([tbldate] as varchar),1,8)     end as date) 	0.000842463704966822
25287280	23765	sql connect two columns	select * from table1 where concat(column1, column2) = '0123456789'; 	0.0227526071963438
25287532	25307	best way to join multiple tables	select column_name(s) from table1 left join table2 on table1.column_name=table2.column_name; 	0.173414178456823
25288031	1988	pass results of one query into another in sql	select p.id, p.name, g.name, g.id from person p inner join position pos on p.id = pos.person_fk inner join role_details rd on rd.id = pos.role_details_fk inner join group_role gr on gr.id = rd.group_role_fk inner join "group" g on g.id = gr.group_fk where g.id = (select g.id from "group" g inner join group_role gr on g.id = gr.group_fk inner join role_details rd on rd.group_role_fk = gr.id inner join mandate m on m.role_details_fk = rd.id where m.id = x) 	0.00163519993795231
25288037	18997	mysql get the sum of all rows without retrieving all of them	select * from `table` where `date` > '14-01-01' and `date` < curdate() union select 9999, curdate(), sum(`amount`) from `table` where `date` < curdate() 	0
25289853	34134	how to join users from subscribers to actual signup	select column_name(s) from users left join subscribers on users.column_name=subscribers.column_name; 	0.00124335160585901
25290134	21908	how to insert into table from select without specifying columns?	select   t.*  into #beep from thisorthattable as t 	0.000114601018823926
25290883	2032	how to display duplicate value in a specific field	select * from test where test2 in (     select test2 from (         select test2, count(*) c from test         where (test4 between @startdate and @enddate) and (isnumeric(test2) = 1)         group by test2          having count(*) > 1 ) f     ) 	0
25292158	8459	return min value from query with inner join	select poi.name from poi inner join rtgitems on poi.vote=rtgitems.item where totalrate= (select min(totalrate) from rtgitems) group by poi.name 	0.0665938901234758
25292681	35754	adding a string literal to sql results	select 'this is my string' as note,      count(*) thesematch,       (select count(*) from [mytable]) thisismytotal from [mytable]   where mycondition = 'mycondition' 	0.219215886856938
25293563	25632	mysql query - select based on condition	select id from table where variable=1 or <condition> 	0.0148936043819537
25293606	28939	select distinct count for first name, last name, dob in sql	select  count(1) as totalcount from    ( select    [first name] ,                     [last name] ,                     [dob]           from      mytable           group by  [first name] ,                     [last name] ,                     [dob]         ) a 	0
25296037	25033	select distinct values, pass into where clause	select ('report - '+ username) as reportname,         count(*) match, (select count(*) from [mytable]) total,        cast(count(*) as float) /          cast((select count(*) from [mytable]) as float)*100 percentage from [mytable]    where othercondition = x group by username; 	0.0878071395403056
25296512	14373	how to get data from other tables with id's	select     u.username,     u.rank     n.nationality,     c.city from     your_table u inner join     nations n on     u.nationality = n.id inner join     cities c on     u.city = c.id 	0
25296757	18370	fetch all data from database row?	select * from players order by name asc <select id="select1" name="select">   <?php     while ($row = $results->fetch()) {       echo '<option>'. $row["name"] .'</option>';     }   ?> </select> 	0
25298526	15408	how do i select specific mysql row in java using scanner user_input integer variable in resultset?	select * from suntimes, days, shows where (days.idday = suntimes.idday and suntimes.idshow = shows.idshow) order by actualtime; 	0.0109582993340802
25299726	465	finding parents by matching on children fks	select  * from playlists where id in( select playlistid from playlistitems where title like '%geographer - kites%' intersect select playlistid from playlistitems where title like '%sam kang%') 	7.82338824715718e-05
25301516	27489	is there a better way to find the most popular title in a 'self-linked' table of user posts?	select p.id p.title, p.content, count(c.id) as nbofcomments from tbl_post p left join tbl_post c on p.id = c.post_id where p.post_id is null group by p.id, p.title, p.content 	0
25301777	22809	complex sql query to get data from four tables	select  p.pr_name,         dc.default_oa,         pa.address  from    pdb_profile p join    mdb_permitted_address pa on p.pr_id = pa.service_id join    mdb_service_conn_pr sc on p.pr_id = sc.exc_service_id join    mdb_driver_conn_pr dc on sc.driver_conn_id = dc.pr_id 	0.00905757747164636
25301861	6945	convert int to date in sql server	select dateadd(day,duration_stay,movedate) as todate from table_name; 	0.117753717778215
25302082	39640	select max of each record group by name	select  * from             (           select *,                   row_number() over (partition by name                                      order by name asc, price desc) as rn           from  table         ) as t where   rn = 1 	0
25302793	10960	how to select a row from a table and many rows from another (related) table	select a.id, a.name, b.picurl, b.picdescription from artist a, pics b where a.id = b.id_artist; 	0
25304011	30195	mysql select query from two tables	select u.name, count(*) num     from users u     join works w       on w.user_id = u.id      and w.work_status = 1 group by u.name 	0.00528391093546687
25304609	27801	how to converts all the first letter to upper case in postgresql	select initcap(thename) from tblname 	0.004351252895273
25306146	9751	how to get the duplicate row count in postgres sql	select string_agg(st_no,',') as st_no, string_agg(st_name,',') as st_name, string_agg(directions,',') as directions, string_agg(others,',') as others from table1 group by st_no 	8.34981944675993e-05
25306386	2360	select by related records?	select    posts.id   posts.text from    posts where    posts.id in (select postid from userposts where userid in (1,2)) 	0.00376164637952096
25309267	8295	select the sum of two different tables	select ordered_value-ifnull(paid_value,0) as acct_balance from (   select customer_id, sum(order_total + delivery_cost) as ordered_value   from orders    where customer_id = '1'   group by customer_id ) as orders left join  (   select customer_id, sum(amount) as paid_value   from transactions    where customer_id = '1'    and transaction_status = 'paid'   froup by customer_id ) as payments on orders.customer_id = payments.customer_id 	0.000106994997138373
25310381	12526	using sql to retrieve a value 3 tables away	select role.roletitle from role as role   left join staffrole as staffrole on role.roleid = staffrole.roleid where staffrole.staffid = '12345' and role.primary = 'true' 	0.00055279728816065
25311519	36115	how do i get the percentage from a group by?	select t.classes, count(*),        1.0*count(*) / sum(count(*)) over () as proportion from (select (case when height between 0 and 3 then 0                     when height between 3 and 5 then 1                     when height between  5 and 7 then 2                    when height between 7 and 9 then 3                    when height between 9 and 11 then 4                    when height > 11 then 5               end) as classes       from lkp0201val      ) t group by classes order by classes; 	0.000355568406799189
25311673	13042	union in mysql and merge columns	select      sum(amount) country_id, currency_name from  (   select          sum(if(debit is null, 0, debit)) - sum(if(credit is null, 0, credit)) as amount,         th.country_id,          cl.currency_name     from account_treasury_hq th     left join system_country_list cl on cl.country_id=th.country_id     where th.company_id='$company_id'     group by th.country_id     union     select          sum(case                 when ce_type = 'in' or ce_type is null then payment_amount                when ce_type = 'out' then - payment_amount                end         ) as amount,         source_country_id as country_id,          cl.currency_name     from customer_payment_options cpo     left join system_country_list cl on cl.country_id=cpo.source_country_id     where cpo.company_id='$company_id'     group by cpo.source_country_id ) t group by country_id 	0.0159766054546139
25312052	24498	plsql append rows together from select statements (similar to rbind)	select last_name,         score from (    select last_name,            score,           dense_rank() over (order by score desc) as ranked_first,           dense_rank() over (order by score asc) as ranked_last    from test_scores )  where ranked_first = 1     or ranked_last = 1; 	0.00600928676475586
25313169	26525	sql grouping by offset date range	select name,year(dateadd(d, -1, date)), month(dateadd(d, -1, date)), sum(gain) gain_total from gaintable group by name, year(dateadd(d, -1, date)), month(dateadd(d, -1, date)) 	0.0106983821051954
25313975	37085	sql statement to test foreign key field with variable?	select *  from products as p inner join productapplied as pa on pa.productid = p.id where p.producttype = $type 	0.0255603065192032
25314116	29451	disambiguating identical columns in a join	select m.messageid, p1.name as sender_name, p2.name as recipient_name  from messages m,  join people p1      on m.senderid = p1.personid  join people p2      on m.recipientid = p2.personid 	0.0297918988769523
25315121	36183	how do i subtract from the same table sql	select mprev.hips - m.hips as hips,        mprev.wrist - m.wrist  as wrist,        mprev.abs - m.abs as abs,        mprev.weight - m.weight as weight from measurements m join      measurements mprev      on me.week = mprev.week + 1; 	0.000103804853464103
25315478	21786	populating a dataset from 2 tables (effective date logic) _simplified_	select a.the_date, sum(b.value) as value_sum from a     inner join b on         b.effective_dt_st <= a.the_date and         b.effective_dt_end >= a.the_date group by a.the_date 	0.00496431029395448
25317023	735	mssql - join tables, in different databases, on the same server	select *  from myseconddatabase.dbo.timecard 	0.00197212064642967
25317831	38311	mysql order by occurrence count with values from two columns	select name, food, count(*) count from yourtable group by name, food order by count(*) desc 	0
25319076	10663	how do i convert from a date to string in mysql?	select      * from     yourtable where     date_format(dob, '%y-%m-%d') like '1492%'; 	0.00257733309759117
25321835	7699	google bigquery the count of each string into one table	select    bucket, max(actiona) actiona, max(actionb) actionb from (   select      bucket,     case when regexp_match(action, 'aaaaaa') then count end actiona,      case when regexp_match(action, 'bbbbbb') then count end actionb   from [tmp.a] ) group by bucket 	0
25323667	1279	mysql: how to list all items with sorting?	select hdt1.custom_field_value0 reporter,          hdt1.title issue      from hd_ticket hdt1     join (       select hdti.custom_field_value0 reporter,              count(*) count         from hd_ticket hdti     group by hdti.custom_field_value0     order by count        limit 10          ) hdt2       on hdt2.reporter = hdt1.custom_field_value0 order by hdt2.count desc 	0.000730651251788645
25328667	38997	use sql to output table differently	select a.submission,     b.data as name,     c.data as address,     d.data as phone,     e.data as email,     f.data as website     from tabledata as a     left join tabledata as b     on a.submission = b.submission     and b.field = "name"      left join tabledata as c     on a.submission = c.submission     and c.field = "address"     left join tabledata as d     on a.submission = d.submission     and d.field = "phone"    left join tabledata as e     on a.submission = e.submission     and e.field = "email"    left join tabledata as f     on a.submission = f.submission     and f.field = "website" 	0.523570247454275
25328921	4597	sql : how to select different rows where values are equal to an set of values?	select *  from `services`  where servide in ('wifi','pulizia','parking','ombrellone','driver','colazione') and active = 1 	0
25329417	15166	how to separate string output?	select     substring(member_name, charindex('/', member_name) + 1, 1) as first_initial,    left(member_name, charindex('/', member_name) - 1) + ' ' as last_name from    member 	0.0316303622087554
25331036	13325	how do you pull data from a database to another one using a linked server?	select * from openquery(linked_server_name,'select * from table') 	0
25331729	36497	multiple column of same table in another table	select      t.trainname     , rd.routorder     , s1.name as fromstationname     , s2.name as tostationname from train t   left join routedetail rd     on t.trainid = rd.trainid   left join station s1     on rd.fromstationid = s1.id   left join station s2     on rd.tostationid = s2.id 	0
25332488	4458	complex sql query return result if and not matched	select u.id, u.name, p.info, s.ammount from user u left join profile p on p.user_id = u.id and p.type = 'language' left join score s on s.user_id = u.id and s.type = 'amount' where email = 'example@email.com' 	0.665790879214753
25332516	15522	changing all computed columns to persisted	select schemas.name      , all_objects.name      , 'alter table ' + quotename( schemas.name ) + '.' + quotename( all_objects.name ) + ' alter column ' + quotename( computed_columns.name ) + ' add persisted;'  from sys.schemas  inner join sys.all_objects     on schemas.schema_id = all_objects.schema_id  inner join sys.computed_columns     on all_objects.object_id = computed_columns.object_id    and computed_columns.is_persisted = 0; 	0.00063300612770303
25335420	32366	sql find which products appear every week	select product from productweek group by product having count(*) = (select count(*) from (select distinct weekending from productweek ) as t); 	0
25335672	31090	sql - summarize multiple transactions that share a common value but also have unique row identifiers	select   grp,          sum(case when type = 's' then amount else null end) as type_s_amt,          min(case when type = 's' then location else null end) as type_s_loc,          min(case when type = 's' then date else null end) as type_s_dt,          sum(case when type = 'o' then amount else null end) as type_o_amt,          min(case when type = 'o' then location else null end) as type_o_loc,          min(case when type = 'o' then date else null end) as type_o_dt,          sum(case when type = 'f' then amount else null end) as type_f_amt,          min(case when type = 'f' then location else null end) as type_f_loc,          min(case when type = 'f' then date else null end) as type_f_dt from     tbl group by grp 	0
25335932	32449	php & mysql: how to select rows in 10 minute increments	select * from pairs where sometimestamp > date_sub(curtime(), interval 10 minute) 	0.000217708998561361
25337751	37462	select data from 3 tables : php	select a.album_name  from albums a  inner join album_singer_mapping m on m.album_id = a.album_id inner join singer s on s.singer_id = m.singer_id where s.singer_name like '%ankit tiwari%' 	0.0026474483005339
25340545	35174	make sure records from one table always overwrite others when joining	select m.model_name, s.series_name, s.price, s.ram, s.brand,        (case when sum(a.attr_name = 'material') > 0              then group_concat(distinct if(a.attr_name = 'material', a.attr_value, null))              else group_concat(distinct if(saa.attr_name = 'material', saa.attr_value, null))         end) as material,        (case when sum(a.attr_name = 'color') > 0              then group_concat(distinct if(a.attr_name = 'color', a.attr_value, null))              else group_concat(distinct if(saa.attr_name = 'color', saa.attr_value, null))         end) as color from model m inner join      series s      on m.series_id = s.series_id left join      series_attr sa      on sa.series_id = s.series_id left join      attr saa      on saa.attr_id = sa.attr_id left join      model_attr ma      on ma.model_id = m.model_id left join      attr a      on a.attr_id = ma.attr_id group by m.model_name; 	0.000383825768228516
25340825	34137	how to replace characters before a number in sql	select if(flightid like 'da%',              flightid,              concat('da', lpad(reverse(cast(reverse(flightid) as decimal)), 3, '0'))) as flightid from flighttable 	0.0140798747300573
25340979	23726	mysql union - every derived table must have its own alias	select   sum(`quant`), month(`date`) as month, `id`  from     ((select `date`, `id`, count(`hit`) as `quant`             from   `stat_2014_07`             where  `k_id` = '123') t1           union all            (select `date`, `id`, count(`hit`) as `quant`             from   `stat_2014_08`             where  `k_id ` = '123') t2          ) t_union group by id, month 	0.00560483335549679
25342251	32259	join on datetime field in sql server	select     dateadd(dd, 0, datediff(dd, 0, table1.datetimefield)) as tempfield  from     table1  inner join     table2 on table2.datetimefield = dateadd(dd, 0, datediff(dd, 0, table1.datetimefield)) 	0.138100220609402
25345517	37961	sql how to get indent string of relation of parent and child in table	select   case when viewname is null then objectid else '......'+objectid end as objectid,          description,          priority from     security_templates_exceptions_item order by menuid, priority 	0
25345979	25278	getting an id from 3 tables which has duplicate(multiple) keys and unique(single) key according to condition	select  p.uid from    perinfo p         inner join likes l             on p.uid = l.uid         inner join places pl             on p.uid = pl.uid where   p.hfor = 2 group   by p.uid having  sum(pl.place = 'walhaba') >= 1            and sum(l.likeid = 34) >= 1       	0
25348021	32901	find min value from database my sql	select least(min(price_net), min(promo_price)) from price_net; 	0.0026055853551269
25348496	19935	get places near geographical coordinates	select *, 3956 * 2 * asin(sqrt(power(sin((@orig_lat - abs(tablename.lat)) * pi()/180 / 2),2) + cos(@orig_lat * pi()/180 ) * cos(  abs (tablename.lat) *  pi()/180) * power(sin((@orig_lon – tablename.lon) *  pi()/180 / 2), 2) )) as distance from tablename having distance < @radius order by distance  limit 10; 	0.275895578379519
25351295	22471	add values to sql server where duplicates occur	select id, sum(values) from tbl group by id having count(*) > 1 	0.0185018024746509
25353471	13650	two if statements and join mysql	select d.dayplanner_time,d.day_time,       if(d.dayplanner_time = a.reservations_starttime,'true','false') as reserved,       if(a.reservations_start is null, false, true) as inbetween       from dayplanner d        left join reservations a        on (d.day_time >= a.reservations_start and d.dayplanner_time <= a.reservations_finish)       where d.dayplanner_time between '12:00:00' and '18:00:00'; 	0.282237593814141
25358078	41215	ms access 2002/vba - join a number of lookup tables to main query?	select contact_id, name, member_type, electorate from contact  left join member_types on contact.member_type_id=member_types.member_type_id left join electorates on contact.electorate_id=electorates.electorate_id 	0.200002835053039
25358779	14525	sql: how to display the same item by group and the same group of the dates	select count(site)  from coming  group by site , date(created) 	0
25359197	21490	map columns to its id using tsql	select id from table1 inner join (     select column1, column2     from table1     group by  column1, column2     having count(column1 +  column2) > 1 ) thistable on table1.column1= thistable.column1and  table1.column2= thistable.column2 	0.00211386215848707
25359627	35748	joining 3 tables and count different fields	select a.title, a.lat, a.lon, a.alert_content_id, a.date_added, count(r.alert_id) as countrep ,count(i.alert_id) as countint  from `alerts` a        left join `reply` r on           r.alert_id = a.alerts        left join `interactions` i on           i.alert_id = a.alerts  group by a.title, a.lat, a.lon, a.alert_content_id, a.date_added 	0.000797147675705045
25361471	18873	sql server 2008 - sum of sums	select  bldgcode, floorcode, occupancy, capacity , occupancy+capacity as allsum from( select  fma0.bldgcode,  fma0.floorcode,  sum(fma0.occ) as occupancy,  sum(case when fma0.spacetype like 'a-off-%' or      fma0.spacetype like 'a-wks-%' then fma0.capacity      else 0 end) as capacity from fma0  where fma0.bldgcode = 'tst01'  group by fma0.bldgcode, fma0.floorcode  )tmp order by bldgcode, floorcode 	0.155387180327627
25362899	30757	where in - must meet all params	select * from `xh_user`  where (select count(distinct title)         from `xh_roles` inner join             `xh_role_user`             on `xh_roles`.`id` = `xh_role_user`.`role_id`         where `xh_role_user`.`user_id` = `xh_user`.`id` and              `title` in (?, ?)       ) = 2 and       `id` = ? limit 1; 	0.0515540086377784
25363073	30958	select all rows based on alternative publisher	select id, publisher, price from (   select id, publisher, price,          row_number() over (partition by publisher order by price) as rn   from publisher ) t order by rn, publisher, price 	0.000265988089966303
25364204	39209	row value from another table	select * from customer  where custno in (   select custno   from rental   group by custno   having count(*) > 1 ) 	0
25364805	32178	select where user bought every year	select count(distinct ss.year_ordered) as sales_count, ss.userid  from subscriber_sub ss where ss.date_deleted is null   and ss.year_ordered > 2007 group by ss.userid having  count(distinct ss.year_ordered) >= ( select 2014 - 2008 ) 	0.0003165967912195
25367262	16857	mysql selecting from multiple rows	select     p.*,     j.company_id as companyid,             f.id is not null as jid,     p.id as pid,     f.id as fave_id,     f.id is not null as fave from people p   left join job j         on j.id = p.job_id left join favourites f         on f.people_id=p.id       and f.user_id = 12 where p.company_id = 3 order by p.id asc 	0.000529951815856621
25367655	13748	converting detailed date column into grouped by month column format	select cast(month(creat_dttm) as varchar(2)) + '/1/' + cast(year(creat_dttm) as varchar(4)) as month  from tempso_inv_data 	0
25367693	19118	sql count records if only type x exists on date or other types if other than type x exists on date	select ... where event_type='encounter' group by ... having count(event_type)=1 union select count(event_type),... where event_type <> 'encounter' group by ... having count(event_type)>1 	0
25371789	39785	filter records in sql server	select *  from (               select  [character].name               ,row_number() over (order by [character].name) as rownum       from memb_info left join [character]         on [character].accountid = memb_info.memb___id        and ctlcode <> 8 and ctlcode <> 32       ) as a where a.rownum  between 10 and 20 	0.0655261424025777
25372098	21120	append previous transaction date sql	select id, pid, b_date, p_date    ,max(last_dt)      over (partition by id order by p_date, last_dt desc           rows unbounded preceding) from  (    select id, pid, b_date, p_date,       nullif(min(p_date)               over (partition by id order by p_date                    rows between 1 preceding and 1 preceding)             , p_date) as last_dt    from vt  ) as dt 	0.00748437984682866
25373789	18323	order table by column, but ignore if 0 - sqlite	select * from tbl order by case when my_order = 0 then 1 else 0 end, my_order 	0.0270775314823631
25373992	378	how to create a union of two tables with null values?	select ucharacter, episode, line, null from ucharacters union all select ucharacter, episode, line, place from uplaces; 	0.000925218385027073
25374085	25023	sql server query that asks to return to most recent date customer log in to the system	select u.name, u.phone_num, max(date) as mostrecentlogon from user u join userhistory uh on u.user_id = uh.user_id where uh.action = "logged_on" and uh.date >= dateadd(d, -30, getdate()) group by u.name, u.phone_num 	0
25374094	23365	finding multiple (different) values under same id sql	select distinct misid, networkname from dbo.compiledstudentdata as t1 inner join (     select misid from dbo.compiledstudentdata     group by misid     having count(distinct networkname) >= 2 ) as t2 on (t1.misid = t2.misid) order by 1, 2 	0
25374170	10241	is value in a string stored in table	select * from t1 where find_in_set(?, mystr) 	0.0190733513096427
25375287	32515	mysql get all records for the next week	select * from snip where yearweek(init_visit_start) = yearweek(now()) + 1; 	0
25376868	25681	sql statement ((join?) to fetch result from multiple tables	select a.date, a.gross, a.net, a.bonus, b.paid as payment from tab_purchase a left outer join tab_payments b on a.comp_id = b.comp_id and a.date = b.date where a.comp_id = "c1" union select b.date, a.gross, a.net, a.bonus, b.paid as payment from tab_payments b left outer join tab_purchase a on a.comp_id = b.comp_id and a.date = b.date where b.comp_id = "c1" 	0.00940641588005988
25377315	26441	calculate discount amount based on quantity	select pdi_disc_qty *    (cast(round(((select quantity from shoppingcartitem)/pdi_disc_qty),0) as int)) from prd_disc_inf ; 	0
25378738	17635	calculating total working hours based on shifts	select employee_id, sum(stop - start)  from (     select start, lead(start) over (order by start) as stop, employee_id     from t ) as x  group by employee_id; 	4.63889551292765e-05
25379250	35133	how to find the total time the machine is idle on the primary key, knowing the start date and end date?	select  id, to_timestamp (second_date, 'yyyy-mm-dd hh24:mi:ss.ff') - to_timestamp (first_date, 'yyyy-mm-dd hh24:mi:ss.ff') tdiff from t; 	0
25380386	16068	ordering query by divide two numbers in sql server	select       *               ,cast(column1 as float) as column1convert              ,cast(column2 as float) as column2convert              ,cast(column1 as float)/cast(column2 as float) as [result]  from         mytable  order by     points desc, result asc 	0.0382104706916122
25381422	13858	oracle left outer join, only want the null values	select values...     from bcharge charge     left outer join chghist history     on charge.key1 = history.key1 and charge.key2 = history.key2 and charge.key3 = history.key3 and charge.chargetype = history.chargetype     where charge.chargetype = '2'       and ((charge.value <> history.value or history.value is null) or (charge.date <> history.date or history.date is null))     order by key1, key2, key 	0.565726961888306
25383198	6589	mysql - how to combine the column data into one row	select empid,         if(right(timeinout,2)='am' and in_out='out',           date_add(date, interval -1 day),           date) as realdate,        max(if(in_out='in',timeinout,null)) as time_in,         max(if(in_out='out',timeinout,null)) as time_out  from shifts  group by empid, realdate 	0
25385479	25864	give a list of booked rooms for months of may, jun and july 2009, having price greater than 8000 per day	select b.* from booking b left outer join room  r    on    r.roomno   = b.roomno where b.datefrom >= '2009-05-01' and   b.dateto   <=   '2009-07-31' and   r.price    > 8000 	0
25385624	9622	order by rand() with same id	select t.id, t1.iddomanda, t.question, t1.answer  from (   select id, domanda as question     from questions      order by rand() ) t left join  (   select iddomanda, risposta as answer     from answers ) t1 on t1.iddomanda = t.id; 	0.012463070900997
25388895	19968	mysql query to get monthly consumption data from table	select     m.month,     sum(         (             datediff(                 if(c.month_to > m.last_day, m.last_day, c.month_to),                 if(c.month_from < m.first_day, m.first_day, c.month_from)             ) + 1         ) / (datediff(c.month_to, c.month_from) + 1) * c.consumption     ) consumption from     consumption c     join (         select distinct              date_format(month_from, '%y %m') month,             date_format(month_from, '%y-%m-01') first_day,             last_day(month_from) last_day         from consumption         group by month_from      ) m on          c.month_from <= m.last_day and c.month_to >= m.first_day group by m.first_day order by m.first_day 	0.000145003691284355
25389709	21932	how to select max amount dates from table	select t.*  from  netact_15min.cscflcc_pcscf t join ( select day(`datetime`) `day`,max(earlysesssetupsuccctr) max_amount from netact_15min.cscflcc_pcscf  where `datetime` >= (now() - interval 5 day) group by  `day` ) t1 on(t1.`day` = day(t.`datetime`) and t.earlysesssetupsuccctr = t1.max_amount) 	0
25396425	37265	two tables with no direct relationship	select income.*, expenses.* from  (select to_date(to_char(pay_date,'mon-yyyy'), 'mon-yyyy') as month, 'fee receipt', nvl(sum(sfp.amount_paid),0) amt_recieved        from stu_fee_payment sfp, stu_class sc, class c        where sc.class_id = c.class_id        and sfp.student_no = sc.student_no        and pay_date between '01-jan-2014' and '31-dec-2014'         and sfp.amount_paid >0        group by  to_char(pay_date,'mon-yyyy') income outer join (select to_date(to_char(exp_date,'mon-yyyy'), 'mon-yyyy') as month, et.description,  sum(exp_amount)             from exp_detail ed, exp_type et, exp_type_detail etd             where et.exp_id = etd.exp_id             and ed.exp_id = et.exp_id             and ed.exp_detail_id = etd.exp_detail_id             and exp_date between '01-jan-2014' and '31-dec-2014'              group by to_char(exp_date,'mon-yyyy'), et.description) expenses on income.month = expenses.month 	0.00655935824178156
25396504	30724	mysql select subquery	select c.`week`, p.user_id, c.`date`, c.`time`, count(*) as count, p.score      from `calendar` c     left join      (       select `date`, sum(`point`) score, user_id       from `result`        group by `date`     ) p on c.`date` = p.`date`     where c.`week` = 1     group by c.`date`     order by c.`date` desc 	0.562544214252809
25396558	25104	how to join tables so even rows with no matches are included?	select p.name,s.style from person p left join shirt s    on s.owner = p.id and s.color = 'blue'; 	0.00590954692151524
25398893	36182	find the last position of an element in sql	select instr(columnname, '-', -1) from tablename 	0
25401641	23243	group rows without using group by	select     id,     [1] as ian,     [2] as feb,     [3] as mar,     [4] as apr,    [5] as mai,    [6] as iun,    [7] as iul,    [8] as aug,    [9] as sept,    [10] as oct,    [11] as noe,    [12] as dec from b pivot (    sum(value)     for ida in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]) )  as resulttable 	0.0626974140407521
25403376	36272	cte to replace join	select t1.d_id, t1.employee_name, te.emp_id,        t1.employee_name as manager_name, tm.emp_id as manager_id from tbl1 t1 join      tbl2 te      on t1.employee_name = te.employee_name join      tbl2 tm      on t1.manager_name = tm.employee_name where te.emp_id > tm.emp_id; 	0.785244078369395
25403738	29495	select data from 3 tables in sql	select table1.name, table1.image_name, table2.qty1, table3.qty2 from table1 left join table2 on table2.name = table1.name left join table3 on table3.name = table1.name where table2.name is not null  or table3.name is not null 	0.00370635657082038
25404584	22148	sql select - fetching two different values from another table based on two different ids	select t1.employeeid, t1.employeecarmodelid, t2emp.carmodelname as employeecarmodelname,        t1.spousecarmodelid, t2sp.carmodelname as spousecarmodelname from table1 t1 left join      table2 t2emp      on t1.employeecarmodelid = t2emp.carmodelid left join      table2 t2sp      on t1.spousecarmodelid = t2sp.carmodelid; 	0
25404775	21947	get a value of column for which there may be or not be an entry present in previously joined tables	select top 10 u.userid, u.fullname, u.username, t.tid, t.msg, t.tpic, t.ttime, count(r.tid) from user_details as u inner join tweet as t on u.userid = t.tuid left outer join retweet as r on t.tuid = r.tid where (t.tuid in (select f.fuid from follow as f where f.userid = @usrid) or t.tuid = @usrid) group by u.userid, u.fullname, u.username, t.tid, t.msg, t.tpic, t.ttime order by t.ttime desc; 	0.000104534124284509
25404888	41131	mysql conditioning query	select *      from table_name     where department = 'it'       and 1000 between `start amount` and `end amount`      and country in ('india','*')      and `sub department` in ('sd2','*') order by country = 'india' desc,          `sub department` = 'sd2' desc    limit 1 	0.668903822189389
25404982	18231	postgresql: remove all characters before a specific character	select split_part('123#23','#',1) as "col1",split_part('123#23','#',2) as "col2" 	0.00118872961038461
25405697	24445	query that recursively compare a record with the previous one	select a.transactionid  from   (select *, row_number() over(order by executiondate) as rownumber          from   transactions) a         join (select transactiontypeid, row_number()  over( order by executiondate) as rownumber               from   transactions) b           on a.rownumber = b.rownumber + 1  where  a.transactiontypeid = 1         and b.transactiontypeid = 3 	0
25406634	25961	filtering out duplicates from select statement - sqlite	select name, min(id) as id, min(job) as job, min(employer) as employer from table group by name 	0.0678729312089174
25406715	20622	summing values based on columns & combining	select    agtid,   sum(case when appsstatustype in ('is', 'cp') then colprem else 0 end) as is_cp,   sum(case when appsstatustype = 'pd' then colprem else 0 end) as pd from yourtable group by agtid 	4.77252318665867e-05
25407111	24810	rolling up remaining rows into one called "other"	select *,    row_number() over (order by complaints desc) as sno into #temp from ( select    a.storename   ,count(b.storeid) as [complaints] from stores a left join  (   select      storename     ,complaint   ,storeid   from complaints   where complaint = 'yes') b on b.storeid = a.storeid group by a.storename ) as t order by [complaints] desc select storename,complaints from #temp where sno<4 union all select 'other',sum(complaints) as complaints from #temp where sno>=4 	0
25408153	6913	find values in certain dates in sql server	select consumerid from sometable where year(somedate) in (2009, 2010, 2011, 2012) group by consumerid having count(distinct year(somedate)) = 4 	9.37796352852406e-05
25408294	28560	how to break out of while sqldatareader.read loop to return value and then return to current place in loop	select distinct photos.picture, subcategory.category, subcategory.type, case when subcategory.type is null then subcategory.category else subcategory.type end as linktext from subcategory left outer join photos on subcategory.type = photos.type where (subcategory.type like '%' + @search + '%') 	0
25409521	39194	need to select records based upon return from a select in multiple columns using 'like'	select *      from secondtable     where id in (select id         from secondtable         join (select location from l_locations     where l_locations.locationid in     (         select locationid from [b_locationstomany         where [b_locationstomany].normalizedlocationid in         (             select [b_locationstomany].normalizedlocationid              from [b_locationstomany] join l_locations on [b_locationstomany].locationid =     l_locations.locationid             where l_locations.location like '%wimpole%'     )     ) as searchresults         on secondtable.location like '% ' + searchresults.location + ' %'     ) 	0
25409556	22965	reverse of date_add / interval in mysql	select timestampdiff(month, '2015-09-20', '2014-08-20'); 	0.137506261461734
25410632	32498	how to randomize the order of distinct on results?	select * from (     select distinct on (episodes.podcast_id) episodes.*     from "episodes"     where ...     order by episodes.podcast_id, "episodes"."publication_date" desc ) s order by random() 	0.00327041793721333
25412530	17011	sql - date range from current date to 2 years ago	select  count(invoiceuniqueness) as [nbr] ,         convert(varchar(12), processdate, 101) as [date] ,         case currentstatus           when 1 then 'production'           when 2 then 'exception'           when 3 then 'archive'         end as [currentstatus] from    preprocesstranslog where    convert(datetime, processdate, 102)  >= dateadd(yy, -2, getdate())         and processdate <= getdate()         and initialstatus = 2 group by convert(varchar(12), processdate, 101) ,         currentstatus order by cast (convert(varchar(12), processdate, 101) as smalldatetime) desc 	0
25413758	20898	create database if not exists just once	select schema_name from information_schema.schemata where schema_name = 'library3' 	0.0282081901624031
25414045	14826	php select data from multiple tables	select comment_id as element_id,         comment_time as element_time,         'comments' as origin from comments where comments.comment_time >= 1408557172 union all select ticket_id as element_id,         ticket_date as element_time,         'tickets' as origin from support where support.ticket_date >= 1408557172 union all select image_id as element_id,         image_time as element_time,         'images' as origin from images where images.image_time >= 1408557172 	0.00317514587758606
25414416	17452	how do i calculate an average date in sql?	select from_unixtime(avg(unix_timestamp(created))) from table 	0.00112715662232162
25414458	36777	sql group by year, select max(field1), display full date and field1	select     fixedyr,     max_distance,     min(fixeddate) as min_fixeddate from     mytable m inner join     (       select          datepart("yyyy",[fixeddate]) as fixedyr,          max(distance) as max_distance     from          mytable     group by          datepart("yyyy",[fixeddate]) ) mx on     datepart("yyyy",m.fixeddate) = mx.fixedyr and     m.distance = mx.max_distance group by     fixedyr,     max_distance 	0.00427308750954636
25414516	25265	postgis - line intersection with modified width	select pt.*, st_distance(pt.geom, ln.geom) from lines ln, points pt where ln.id = 'given line' and st_dwithin(ln.geom, pt.geom, width) order by st_distance(pt.geom, ln.geom) 	0.0864980349076065
25415494	14495	count(*) of a windowed sql range	select     a.category_id,     (dense_rank() over w) - 1,     count(*) over (partition by category_id)  from (     _inner select_ ) a window w as (partition by category_id order by score) 	0.0143250467995889
25416879	9878	run a query where it displays records that have duplicate values across two columns but where it has distinct records on another column	select column1,        column2,        count(distinct column3) as num_duplicates   from table  group by column1, column2 having count(distinct column3) > 1  order by 3 desc 	0
25417478	35520	mysql - is there any way to check if a view is referenced by other views?	select * from information_schema.views  where table_schema = 'your schema'  and view_definition like '%referenced_view%'; 	0.0261176433319712
25419193	9198	exclude weekends days from the holidays	select (datediff(week,startdate,enddate)-1) * 2 +         case datepart(dw,startdate)             when 4 then 2             when 5 then 1             else 0         end 	0
25419306	482	order by column 2, group by column 1	select         p.idpartij,        p.partijnaam,        p.gewicht,        per.perceel,        p.moederpartij,        case when p.moederpartij =0 then        concat(p.idpartij ,"-", "0","-", p.idpartij )        else        concat(p.moederpartij ,"-", "9","-", p.idpartij )        end sorder from partij as p left outer join perceel as per on p.idperceel = per.idperceel where p.actief = 1 order by         sorder asc 	0.00399210256607604
25419872	576	union statement same selected values - strange behavior	select 1 as id, 100 as amt from dual union all select 1 as id, 100 as amt from dual union all select 1 as id, 100 as amt from dual union all select 1 as id, 100 as amt from dual; 	0.773839294924976
25420115	38954	sql query to get last 4 friday dates	select top 5 datefield from table where lower(datename(dw, datefield))='friday' group by datefield order by datefield desc 	9.70927729819288e-05
25420322	18286	join table to entry if within 30 seconds of table	select * from tablea inner join tableb on (a.value = b.value or a.value = dateadd(second,30,b.value)) 	0
25420672	29493	sql to get the first occurence of a value in each column within grouped elements	select     line,     code,     max(col1) col1,     max(col2) col2,     max(col3) col3,     max(col4) col4 from mytable group by line, code 	0
25421410	39746	(columns) group into one, count into two	select     group_id,     sum(user_id > 0) as count_users,     sum(user_id = 0) as count_guests from     your_table group by     group_id 	0
25424377	22656	how can i join five tables in one table?	select ...   from devices_active   join (select ... from dj_07_2014 union all         select ... from dj_06_2014 union all         select ... from dj_05_2014        ) using(device_id); 	0.00419888483374704
25425041	31333	combine two mysql sum queries into one which use different where clauses	select q1..name, q1.`year`,     q1.allocation, q1.carried_forward,    q1.lieu_days, q1.totalallocation,   q2.approvedtotal  from (    ~~insert query1 here ~~ ) as q1 inner join (    ~~insert query2 here ~~ ) as q2 on q1.username=q2.username; 	0.000217822338221737
25425318	1714	merge rows to one id with values	select   sfr.[registration],   sfr.[id] as ids,   sfr.[datetime] as datetimes,   tfr.[id] as idt,   tfr.[datetime] as datetimet from      (select * from [unitinfo] where [idtype] = 'sfr') as sfr left join (select * from [unitinfo] where [idtype] = 'tfr') as tfr   on sfr.[registration] = tfr.[registration]; 	0
25425473	25888	sql select in select where get from result max	select g.group_name, sum(money) as time from works w inner join group g on g.group_id = w.group_id group by w.group_id order by sum(money) desc limit 1; 	0.00204768060981995
25425515	24318	mysql maximum 10 rows for single geographical area	select dt.* from dotable dt where (select count(*)        from dotable dt2        where dt2.ordertco = dt. ordertco and              dt2.id <= dt.id       ) <= 10 	0
25425924	7837	mysql - finding if a user has taken a course, and if so, which one, too many rows being generated	select     u.uid,     max(if(c.name regexp 'course i?$ | course i[[:space:]] | course 1', 1, 0)) as 'course 1',     max(if(c.name regexp 'course ii$ | course ii[[:space:]] | course 2', 1, 0)) as 'course 2' from     users u     inner join usercourses uc on uc.uid = u.uid     left join courses c on c.cid = uc.cid group by     u.uid order by      u.uid; 	0
25426299	36702	postgres: how to use value of field in subquery	select * from    services where   service in (1, 3) and     pay_date > '2014-07-01' and     pay_date < '2014-07-30' and     not exists          (   select  1              from    services as s2              where   s2.name = s.name              and     s2.status = 1              and     s2.service in (1, 3)             and     s2.pay_date > '2014-07-01'             and     s2.pay_date < '2014-07-30'         ); 	0.0206323595844282
25426312	14704	select top score only from mysql database	select @i:=@i+1 rank, a.*   from       ( select x.*          from entries x          join (select drivername, min(totaltime) min_totaltime from entries where progress = 19 and totaltime > 1000 group by drivername) y            on y.drivername = x.drivername           and y.min_totaltime = x.totaltime      ) a      , (select @i:=0) i  order      by totalscore desc, totaltime asc; 	0.00020505297838813
25427990	23874	oracle 11g: default to static value when query returns nothing	select nvl(desired_datum, 'default') as desired_datum from dual left join  data_table on the_key = &input_value 	0.77482355518057
25428697	33017	merge sql table rows based on zeros	select time,         max(value1) as value1,        max(value2) as value2,        max(value3) as value3,        max(value4) as value4 from mytable  group by time 	0
25429005	39080	how can i use comma separated string from a column as value for mysql in statement	select t1.*, t2.id as control from test_1 t1 left join test_2 t2 on t1.id= find_in_set(t1.id, t2.ids); 	0.000113333898871429
25430341	28356	sql trying to rename an item	select firstname as firstname2 from datatable2 	0.00952341300832414
25430410	15663	counting the records of two columns from different tables	select     coalesce(t1.[date], t2.[date]) as [date],     isnull(t1.nbr, 0), + isnull(t2.nbr, 0) as total from     (         select count(invoiceuniqueness) as [nbr], convert(varchar(12), processdate, 101) as [date]         from preprocesstranslog         where (convert(datetime, processdate, 102))>=dateadd(m, -24, getdate()) and convert(datetime, processdate, 120)<=getdate() and initialstatus=2         group by convert(varchar(12), processdate, 101)     ) t1,     full join (         select count(manualbillheaderid ) as [nbr], convert(varchar(12), processdate, 101) as [date]         from <whatever table>         where (convert(datetime, processdate, 102))>=dateadd(m, -24, getdate()) and convert(datetime, processdate, 120)<=getdate() and initialstatus=2         group by convert(varchar(12), processdate, 101)     ) t2 on t1.[date] = t2.[date] order by     coalesce(t1.[date], t2.[date]) 	0
25431048	10180	how do i check for repeating data within a time period?	select      a.valuecolumn,      a.datecolumn,      b.datecolumn  from mytablename as a  join mytablename as b       on b.valuecolumn = a.valuecolumn   where      b.datecolumn between a.datecolumn and dateadd(hour, 1, a.datecolumn)      and      b.primarykeycolumn != a.primarykeycolumn  	0.000598734550042853
25431553	5208	how to add more conditions with mysql query?	select loanac.id, loanac.name, loanac.lacc, loanac.phone,         sum(loantrans.in) as totalin, sum(loantrans.out) as totalout  from loanac,       loantrans  where loanac.lacc=loantrans.account  group by loanac.lacc having sum(loantrans.out) > sum(loantrans.in) 	0.207420631703091
25434344	40762	mysql - find values that occur at least two times without using any aggregate function	select distinct c1.city_name    from `city` c1    join city c2          on c1.city_name=c2.city_name         and c1.state_name!=c2.state_name 	0.000138696120479073
25435488	35345	query for grouping columns with the same text in different tables	select * from   `users` where `users`.email in (     select u.email     from       `users` u        left join `accounts` a on u.email = a.email     where       a.email is null) 	0.000188776755699766
25435735	15613	mysql search string begins with string first, but also return any results that contain string	select *  from table  where name like '%john%' order by      case when name like "john%" then 1           when name like "%john%" then 2          when name like "%john" then 3           else 4     end 	0
25436208	25805	query to add a new column based on the result of the other field in mysql	select id,         amount_spend,         case           when amount_spend > 30 then 'high'           when amount_spend > 20 and amount_spend <= 30 then 'medium'           else 'low'        as category from the_table; 	0
25439456	33134	mysql how to count from group by	select abb2.*, abb1.mysql_num_row from `table` as abb2   join        (select companyid, count(userid) as mysql_num_row       from `table`       group by companyid) as abb1 on abb1.companyid = abb2.companyid where abb2.companyid = 1; 	0.0185914637529108
25440150	8857	select sum not limiting as requested	select sum(newpermjobs) as newpermjobstotal,    sum(candidatessubmitted) as candidatessubmittedtotal,    sum(firstinterviewsrecorded) as firstinterviewsrecordedtotal,    sum(oldjobsreactivated) as oldjobsreactivatedtotal,    sum(candidaterecordsupdated) as candidaterecordsupdatedtotal,    sum(companiesaddeddream) as companiesaddeddreamtotal,    sum(socialcontentshared) as socialcontentsharedtotal,    sum(applicantstatuschanged) as applicantstatuschangedtotal,    sum(jobsclosed) as jobsclosedtotal,    sum(revenue) as revenuetotal  from (    select newpermjobs, candidatessubmitted, firstinterviewsrecorded,            oldjobsreactivated, candidaterecordsupdated, companiesaddeddream,            socialcontentshared, applicantstatuschanged, jobsclosed, revenue    from dailyactivity     where (`consultant` like '%".$query."%')     order by date desc     limit 0,7 ) t 	0.375009979075411
25441363	32225	select query for multiple tables with one common column	select *   from dm_audit da   inner join dm_applicants dap on dap.fk_applicationid=da.fk_applicationid etc........ 	0.000584127841362691
25442114	34459	how do i do "group by" and yet also get the sum?	select sum(a) a from (   select distinct a,b   from mytable )z; 	0.00192491359734267
25442528	19137	select records that are only associated with a record in another table	select c.customername, p.policyid, pt.poltypename, providers.providername from customers c left join policies p on c.customerid = p.customerid left join policytypes pt on p.policytypeid = pt.policytypeid left join providers pr on pr.providerid = pt.providerid where pr.providerid = 100001 and c.customername not in (     select c.customername     from customers c left join policies p on c.customerid = p.customerid     left join policytypes pt on p.policytypeid = pt.policytypeid     left join providers pr on pr.providerid = pt.providerid     where pr.providerid <> 100001 ) 	0
25443519	39524	sql statement with the actual week	select * from your_table where yearweek(`date`, 1) = yearweek(current_date, 1) 	0.00986696088594661
25444735	25442	sql - how do i select a "next max" record	select max(field) from table where field < (select max(field) from table) 	0.000692727589665507
25445669	16554	need help displaying only one result per user from database (php)	select distinct name n, (     select time     from round     where map = 'bhop_eazy_csgo'     and name = n     order by time     limit 1 ) as time from round where map = 'bhop_eazy_csgo' order by time limit 0 , 10 	0.000249485214827499
25447912	26055	sql join query to get most viewed atricles by country	select av.id, count(*) as views from article_views av inner join user u on av.user_id = u.id where u.country_id = 'cc' group by u.country_id order by views desc; 	0.00398009444999548
25448033	4101	sql: get undirected links in directed graph	select from_there, to_there from edges x where not exists (     select 1 from edges y      where x.from_there = y.to_there       and x.to_there = y.from_there       and x.to_there < y.to_there ); 	0.0464942657615428
25448141	40173	finding count and a field from two different tables	select id, a.service, count(1), status  from a, b  where a.service = b.service  group by id, a.service, status 	0
25449147	15078	select data based on from year and month	select id,fromyear, frommonth,toyear,tomonth, details from <tablename> where  (     (fromyear = @year and frommonth <= @month)       or      fromyear < @year                             ) and  (     (toyear= @year and tomonth >= @month)      or     toyear > @year                              or     (toyear= 0 and tomonth = 0)            ) 	0
25451722	32387	select one (highest) score per userid or nickname column	select   nickname, userid, max(score) from     my_table group by nickname, userid 	0
25453166	13111	compute the `sum(count(id))`	select g.[id], g.[name], count(s.id) as solders,        sum(count(s.id)) over () as sumcount from groups g join      solders s      on g.id = s.gid  group by g.[id], g.[name]; 	0.359835609070406
25457074	39818	select max sum of records in two columns	select team, sum(score) as totalscore from (     select team1_id as team, sum(score1) as score     from xeg8u_bl_match     group by team1_id     union all     select team2_id as team, sum(score2) as score     from xeg8u_bl_match     group by team2_id ) as scores group by team order by 2 desc limit 1 	0
25458865	3410	mysql - get rows with same value	select sp2.user from session_participants as sp1 join session_participants as sp2 on sp2.session = sp1.session and sp2.id != sp1.id where sp1.user = 1 	0.000104477425144528
25460288	12581	mysql, how to get data with id above 4	select * from testtabel where id > 4 and ((data1 = 'iya' and data2 = 'hallo') or (data1 = 'hallo' and data2 = 'iya')) 	0.000608454086239198
25461089	14213	select 10 greater than and 10 lesser than an integer value in db2.	select t.* from (select t.*,              row_number() over (partition by (case when col < target_val then 'lower' else 'higher' end),                                 order by abs(target_val - col)                                ) as seqnum       from table t      ) t where seqnum <= 10; 	0
25461316	29558	sql, select field if field doesn't exist in another table	select * from products p where not exists (select * from images i where i.productid=p.productid) 	0.00103559416903862
25461427	1525	postgresql return true if table relationship	select g.name, bool_or(c.garage_id is not null) from     garage g     left join     car c on g.garage_id = c.garage_id group by g.name 	0.0194962585211796
25461913	38377	date difference between sysdate and date stored in mm-dd format	select fldid,  date_format(now(), '%y-%m-%d') as todays_date,  concat(year(now()),'-',flddatevarchar) as calcdate,  datediff(now(), concat(year(now()),'-',flddatevarchar)) as difference from test_table 	0.000395393849090328
25463235	22851	how can an unrelated table specified in from-clause affect the outcome of sum()?	select sum(od.quantityordered)  from orderdetails od join offices o   on od.somecol=o.someothercol 	0.00100950545224096
25464223	28732	how to limit a left join	select c.* from (select child.*,              (@rn := if(@id = parent.id, @rn + 1,                         if(@id := parent.id, 1, 1)                        )              ) as rn       from (select * from mytable where category='general' limit 10            ) parent left join            mytable child            on child.parentid=parent.id cross join            (select @id := -1, @rn := 0) vars       order by parent.id asc      ) c where rn <= 5; 	0.69492780746777
25466239	39313	sql query with 3 tables	select project.projectid, project.name, managers.username, project.duedate, task.workerid from project  inner join task on project.projectid = task.projectid inner join user as managers on project.projectmanagerid = managers.userid inner join user as workers on task.workerid = workers.userid 	0.268100814343786
25466844	37322	how to fetch a data from a different table in the databse depending on the outcome of another fetch	select * from products inner join suppliers on suppliers.suppliersid = products.suppliersid 	0
25472175	24804	mysql join query - how to approach 3 tables?	select d.drink, t.temp from drink d inner join drink_temp dt on dt.drink_id = d.drink_id  inner join temperature t on t.temp_id = dt.variety_id where d.drink_id in (:firstdrinkid, :seconddrinkid); 	0.256650093444678
25473530	17022	limit amount of rows fetched by join	select      child.*,      if(@a = child.parentid, @b :=@b+1, @b := 1) as counting_col,      @a := child.parentid from mytable as parent left join mytable as child on child.parentid=parent.id cross join(select @a :=0, @b:=1) t where parent.pageid in ( 1, 2)    and parent.submittype='1' having counting_col <=5 order by child.id asc 	0.000881864764002979
25475537	5917	mysql query to select rows where one column matches and one column does not	select  rc.activity, rc.class from results_class rc join users c on c.activity = rc.activity where not exists (   select 1     from user b      where b.class = rc.class ) 	0.000460164424340472
25476095	20637	how do i get the first half of results in sql server?	select      top 50 percent *  from      table1; 	0.000257167462003601
25476361	39331	select nonexisting attributes	select attribute from attributes a left join (select * from product_attributes pa where pa.product_id = 1 ) pa on a.id = pa.id  where pa.id is null 	0.0489845842850345
25476693	7186	sql: left join multitables with the on the same key	select       t1.id,       t1.name,       t1.observation,       t2.contact,       t3.salary    from       table1 t1          left join table2 t2             on t1.id = t2.person_id          left join table3 t3             on t1.id = t3.person_id 	0.0459044388224758
25476839	31482	connect 2 queries in one	select *, (select count(id) from pvp_stats where elo >= s.elo ) `count`  from pvp_stats s where s.uuid = '4c5be598-11e7-480a-a255-483473b2a452'  limit 1; 	0.0328626289864826
25477560	23795	sql select only duplicates from one column	select t.bn, t.system, sum(t.amount)   from tbl1 t   join (select bn from tbl1 group by bn having count(distinct system) > 1) x     on t.bn = x.bn  group by t.bn, t.system 	0.000150313866509496
25478480	18823	mysql - how do i order based on columns from another table	select d.* from data d join customers c on c.cust = d.customer and c.mkt = d.market join sort s on s.submarket = c.submkt order by      d.customer,      d.category,      d.brand,       d.market,      case s.sortby         when 'a' then d.a         when 'b' then d.b         else 9999999     end 	0
25478977	36238	it is possible to record a data that have a straight row in mysql based on date or sequence?	select username, date, action, num_times as 'straight 3+' from (   select *,         sum(case action when 'sell' then 1 else 0 end) as num_times,         if(@a = action, @b, @b:= @b + 1) as counting_col,         @a := action     from your_table     cross join (select @a := '', @b := 1) t     group by username, counting_col     having num_times > 0 ) t1 	0
25479229	23585	counting rows of selected data in mysql	select count(temp.id) as num from (select * from tablename where number > 1000) temp 	0.000412675892917665
25480611	2633	sql join with no records found	select distinct b.floornumber, b.size as apt1a, c.size as apt1b  from apartementtable a inner join bathroomtable b on a.apartmentnumber  = b.apartmentnumber and b.bathroomnumber = 1 left join bathroomtable c on a.apartmentnumber = c.apartmentnumber and c.bathroomnumber = 2 where a.apartmentnumber = 'apt1' 	0.0596827642739621
25480898	11676	mysql query, catch ip addresses	select      f.id,     f.ref1,     f.ref2 from friends f left join accounts a1 on a1.id = f.ref1 left join accounts a2 on a2.id = f.ref2 where a1.web_ip = a2.web_ip; 	0.789408109974757
25481111	7171	how to count same field twice based on a boolean?	select    count(case when confirmed then 1 end) as n_confirmed,   count(case when not confirmed then 1 end) as n_unconfirmed,   ... from posts    ... 	5.04644620632478e-05
25481256	12006	how to use rownum for a maximum and another minimum ordering in oracle?	select *  from  (my select statement order by a desc, b)  where rownum = 1; 	0.000933487000600557
25482945	8363	get first value as null in select query result	select col1 from tbl1 where col2= 'abc' union select null as col1 from dual; 	0.000434744897299757
25484038	23078	sql multiple values in one column	select p.id, p.product_name from products p  join filters f on p.id = f.product_id where f.filter_id in (2,3) group by p.id, p.product_name having count(distinct f.filter_id) = 2 	0.00213907116414807
25484495	25481	mysql: sorting newest comments to be the first and newest replies on each comment to be the last	select c.* from comments c left join      comments cparent      on c.reply_to = cparent.id order by coalesce(cparent.date, c.date) desc,          coalesce(cparent.id, c.id),          (cparent.id is null) desc,          c.date asc; 	0
25485188	9613	store parts as of a cte as temp-tables	select * into #subfolders  from (   select  x.d           , x.e      from     (  select bla as d             , boo as e         from foobar     ) x     group by x.d, x.e )a ;with folders as  (     select a, b, c from foo ), fulltable as (     select * from folders     cross join #subfolders ) select * from fulltable left join #subfolders on ...; select s.d from #subfolders s;  	0.0962410196923914
25486413	24030	duplicate column (from right table) with values before nullified during left join	select  s.user ,       'your answer = ' + s.submitted_answer ,       'right answer = ' + q.expected_answer  ,       case          when s.submitted_answer = q.expected_answer then 'correct'         else 'incorrect'         end from    submission s join    question q on      s.question_id = q.id 	0.00351247184512309
25486671	25946	how to combine results from 3 tables into one?	select name,        value   from a   where value = 7  union all select name,        value   from b   where value = 7  union all select name,        value   from c   where value = 7 	0
25487056	1757	search form to match all words and specific words using php	select * from members_teachers where (school_name like concat('%',?,'%')        or school_board like concat('%',?,'%')        or country like concat('%',?,'%')        or state like concat('%',?,'%')        or city like concat('%',?,'%') ) and approved = '2' 	0.000556376913100312
25487068	18095	sql query to add a value x in a column if a column has y value	select [machine id], hostname, [ip address],  case when [ip address] like '10.216%' then 'chennai'      when [ip address] like '10.218%' then 'mumbai'      when [ip address] like '172.21%' then 'noida'      when [ip address] like '192.25%' then 'delhi'      else 'unknown' end from mytable 	0
25488362	37672	round sql 2 digits	select        p.productnaam,                f.aantal, p.prijs, f.basisbedrag, f.korting,                format(round(f.basisbedrag * (f.korting / 100.00), 2), "standard") as expr1005,                format(round(f.basisbedrag - f.basisbedrag * (f.korting / 100), 2), "standard") as expr1006,                p.btw,                format(round((f.basisbedrag - f.basisbedrag * (f.korting / 100.0)) * (p.btw / 100.0), 2), "standard") as expr1008,                f.totaalbedrag, p.productid from            (tblfactuur f inner join                      tblproducten p on f.productid = p.productid) where        (f.factuurid = '2014001') 	0.024257666681349
25488808	21585	copy mysql row value from row below?	select *, if( sku is null, @lastid , sku ) as id, @lastid := sku from temp cross join(select @lastid := null)t order by image; 	5.39040662680267e-05
25489024	12304	how can show ages according specific years?	select year(curdate())- year(date_birth) as ages from clients where date_birth <= (curdate() - interval @start year)  and date_birth >= (curdate() - interval @end year) 	0.000413252755950317
25489179	37445	oracle counting the number of sids which belong to a username and retrieving the sum of cpu value used by each session of the sid	select ss.username,          count (distinct se.sid) as "count of sid",          sum(value) / 100 as "total_cpu"     from gv$session ss, gv$sesstat se, gv$statname sn    where     se.statistic# = sn.statistic#          and name like '%cpu used by this session%'          and se.sid = ss.sid          and ss.status = 'active'          and ss.username is not null group by username; 	0
25491268	14303	getting the sum of a column based on another column	select your_original_columns,  sum(sumofprofit) over(partition by customer) as 'total' ... 	0
25491337	13416	mysql select value	select     upd.user_id,     upd.meta_value as lastupdated from wp_usermeta mkey inner join wp_usermeta upd     on upd.user_id = mkey.user_id and        upd.meta_key = 'lastupdated' and        mkey.meta_key = '12345' and        mkey.meta_value = 'abcde'; 	0.0404524944048584
25492886	18966	mysql sum a previous grouped query	select model as model, sum(gearcount) as total from (   select model, ratio, if(count(model)>=3,3,count(model)) as gearcount      from zfgearinv      where allocated = 0 and sold = 0      group by model, ratio ) t group by model order by model 	0.00602096332279589
25493119	819	need to sum transaction totals from one table using customer information in another	select c.name,        sum(if(transaction_date >= date__sub(now(), interval 1 month), total_amount, 0) as total_amount_month,        sum(total_amount) as total_amount_year from transactions as t join customer as c on c.internal_id = t.customer_id where transaction_date >= date__sub(now(), interval 1 year group by t.customer_id 	0
25493132	11483	sql select records common to a column	select  job from    emp e1 where   e1.deptno = 10 and     exists ( select 1          from   emp e2          where  e2.deptno = 20          and    e1.job    = e2.job     ) group by job; 	0.000372899604337286
25494494	22619	mysql: select part of text and cut it of based on dot location	select     id,     case         when len <= 500 then content         else case             when idx > 0 then substring(content, 1, idx)             else ''         end     end as content from (   select      id,     content,     locate('.', content, 500) as idx,     length(content) as len   from data ) as data 	0.00029288490829381
25495735	19408	how to make a simple query that matches column values to a look-up then matches further columns if no match is found	select t1.id,      coalesce(t21.class_group, t22.class_group, t23.class_group) class_group from table1 t1 left join table2 t21 on t21.cat_code = t1.col1 left join table2 t22 on t22.cat_code = t1.col2 left join table2 t23 on t23.cat_code = t1.col3 	7.15669021707561e-05
25497084	34568	select all except one field in sql	select * from 'table name' where characterid != 5 	0.000611789807042881
25498425	36788	can not list all information in my attribute	select job_code from emp_1 where job_code = '501'; 	0.00366079694918145
25502804	18841	sql: join two different rows from the same table to a relation	select rel.id, rel.type, p1.id, p1.name, p2.id, p2.name   from relation rel      , person p1      , person p2  where rel.person1 = p1.id    and rel.person2 = p2.id 	0
25502926	27374	producing a sum query	select sum(sp), manager & " is " & locaton from table group by manager & " is " & locaton 	0.740742993951076
25503235	33043	how to access a column value in a select list within a tabular form for each row in oracle apex	select   "empno",   "empno" empno_display,   "ename",   "hiredate",   "sal",   "deptno",   "empno" "my_lov"   from "#owner#"."emp" 	0
25505745	5589	frequency based sort in sql	select t.id, t.value from t order by count(*) over (partition by value) desc 	0.0019045304980532
25506909	8950	fetch the max date record for each year or an item	select it.* from inv_tab it inner join (select i.item_id                   ,max(i.end_date) as [end_date]            from inv_tab i            group by i.item_id, datepart(year,i.end_date)) t on t.item_id = it.item_id                                                     and t.end_date = it.end_date 	0
25507553	7419	a join or other method to retrieve when one query is null and other have result	select      sum(case when s.score < 0 then s.score else 0 end) n_sum,count(case when s.score < 0 then s.score end) n_count,      sum(case when s.score >= 0 then s.score else 0 end) p_sum,count(case when s.score >= 0 then s.score end)  p_count,      sum(s.score) `sum`      from scores_ofexpert s          where s.user_id = '30' and title='135'     group by title 	0.00103085122870631
25507590	11474	how to join two tables in sql server with multiple select	select * from  ( select u.nm_unit, p.kode_upt, count(p.nomor_aju) as jml, p.status as kode   from m_upt as u   inner join      t_ppk as p on u.kd_unit = p.kode_upt   group by u.nm_unit, p.kode_upt, p.status ) as a  inner join     ( select kode, uraian, keterangan       from m_tabel        where keterangan='status' ) as b on b.kode = a.kode 	0.0485884650633293
25508926	20304	join and sum on secondary table?	select a.questionid, sum(case when(b.lookup = a.response) then 1 else 0 end) as [count] from questions a inner join questionlookup b on a.questionid = b.questionid group by a.questionid 	0.0268734729400964
25509095	14002	mysql duplicate and incorrect results	select musician.musicianforename, musician.musiciansurname,musician_address.musicianaddress1, musician_address.musiciantelno from  musician_address join  musician on  musicianaddress1.musicianaddress1 = musician.musicianaddress1  ; 	0.354931227465643
25509140	27894	how would i get a list of column name & data type for each column in a table in .net?	select c.* from information_schema.columns c where c.table_schema = 'dbo'     and c.table_name = 'yourtable' order by c.ordinal_position 	0
25509909	25494	mysql query over 2 tables	select items.headline  from ms95f_createalist_items items join ms95f_createalist_categories categories on items.heading = categories.id 	0.090880594036181
25510155	17560	mysql merge table, with zero vaules	select      coalesce(s.id, "") as s_id,     coalesce(s.date, "") as s_date,     coalesce(s.values, "") as 'values',     coalesce(s.commonid, "") as s_commonid,     coalesce(d.id, "") as d_id,     coalesce(d.date, "") as d_date,     coalesce(d.valued, "") as 'valued',     coalesce(d.commonid, "") as d_commonid from source s left join destination d on d.date = s.date       and d.commonid = s.commonid where d.commonid = 11 union select      coalesce(s1.id, "") as s_id,     coalesce(s1.date, "") as s_date,     coalesce(s1.values, "") as 'values',     coalesce(s1.commonid, "") as s_commonid,     coalesce(d1.id, "") as d_id,     coalesce(d1.date, "") as d_date,     coalesce(d1.valued, "") as 'valued',     coalesce(d1.commonid, "") as d_commonid from source s1 right join destination d1 on d1.date = s1.date        and d1.commonid = s1.commonid where d1.commonid = 11 order by s_date desc, d_date desc 	0.0336365986306904
25510536	8808	php - mysql query - counting results where timestamp is within specific date ("y-m-d")	select * from table1 where from_unixtime(tm,'%y-%m-%d') =  '2010-07-21' 	0.00414096915828923
25513131	3691	adding up two time fields in mysql returns null	select addtime(cast('08:30:00' as time), cast('06:30:00' as time)); 	0.0188790158958619
25514037	6778	avoid the error -- subquery returns more than one row	select 'choose one' as state, 1 where (select count (distinct state) from test  where country in '&country') > 1 union select state as state, 2 from test where country in '&country' order by 2, 1 	0.412936420703104
25514321	1217	ms sql server 2008 - extract 1st 3 octets of ip address	select left(ip_address, len(ip_address) - charindex('.',reverse (ip_address))) from ip 	0.0444621399604723
25515168	218	mysql - querying for a result across tables that are not directly linked	select distinct mus.musicianforename, mus.musiciansurname, album.albumname enter code here`from album_song  inner join album on album_song.albumid=album.albumid inner join song_instrument s_i on album_song.songid = s_i.songid inner join musician mus on s_i.musicianninumber = mus.musicianninumber where album.albumname = 'what a massacre'; 	0.0137676136965223
25516623	26961	mysql joining two table id's to produce results from one table to another	select customername from projects join customers on customers.id = projects.customerid where projects.id = "1" 	0
25517546	6420	multiple select query mysql without while loop	select * from `coupons` where `storename` in (     select `storename` from `stores` where `brandname` = 21); 	0.41009928530624
25517688	36833	sql query two queries and union	select       sum(columna1)     , sum(columna2)     , (             select                   sum(columnb1)             from tableb             where columnb3 = x                   and columnb4 = y                   and columnb5 = z       ) as sum_columnb1 from tablea where columna3 = x       and columna4 = y       and columna5 = z ; 	0.328553032025076
25519228	14551	how to get image processed count with group by clause?	select  jobid,         count(imageid) as totalcount,          sum(case when statusid=7 then 1 else 0 end)  as 'processedcount' from    jobinfo with ( nolock ) group by jobid order by jobid 	0.0636618761551731
25519412	38597	in sql where if date then compare datecolumn1 else compare with datecolumn2	select * from table where case when @datestart > '1/01/2014' then datecol1 else datecol2 end between @datestart and @dateend 	0.0352234433207913
25520859	12987	how to use join table and count with select query	select ib.*,     (         select count(*)         from idea_box_voting ibv         where ibv.idea_id = ib.idea_id and ibv.thumbs = 1     ) as one_count,     (         select count(*)         from idea_box_voting ibv         where ibv.idea_id = ib.idea_id and ibv.thumbs = 0     ) as zero_count from idea_box ib 	0.345226716736168
25521173	28921	sql select records with non zero parameter	select relname,  case    when (n_tup_ins + n_tup_upd + n_tup_del) > 0 then     cast(n_tup_ins as numeric) / (n_tup_ins + n_tup_upd + n_tup_del)    else      null  end as ins_pct  from pg_stat_user_tables where ins_pct is not null order by relname; 	0.0326601382271876
25522188	12627	how to check duplicate column values?	select      id,     name,     email from (     select         rn = row_number() over(partition by name order by id asc),         id,         name,         email =  stuff((select ', ' + convert(varchar, t2.email)                         from @table_var t2                          where t1.name = t2.name                         for xml path(''))                     ,1,2,'')     from @table_var t1     group by t1.id, t1.name )t where rn = 1 order by id 	0.000442639246268406
25522932	37635	non-updateable query	select (select tbl_comments.comments         from tbl_current_orders on (tbl_mfr0004.mfr0004_id = tbl_current_orders.mfr0004_id)             inner join tbl_comments on (tbl_current_orders.current_orders_id = tbl_comments.current_orders_id),        tbl_mfr0004.delivery from tbl_mfr0004  where (tbl_mfr0004.delivery = get_gvstepdelivery()); 	0.774548191734413
25523524	6001	multiplying common values between 2 tables	select sum (w.weight * f.frequency) from weighttable w join freqtable f  on f.word = w.word 	0
25525014	32116	find the latest location of each users in a mysql table	select yt.* from your_table yt inner join (     select     email, max(timestamp) max_ts     from     your_table      group by email ) sq on yt.email = sq.email and yt.timestamp = sq.max_ts 	0
25526019	37568	sql include results where id does not exists in related table	select *  from user u left outer join results r on r.user_id = u.user_id where r.result_id is null     or(r.result_id is not null and r.module_id <> 1) 	0.0629376888823697
25528313	31916	get highest value from mysql database	select max(substring(code, 3) + 1) from your_table 	0
25529320	12470	sql - finding the maximum date group by id table	select remun_id, date_maj from (   select r.*,           max(date_maj) over (partition by remun_id) as max_date   from histo_statut_remun r )  where date_maj = max_date   and statut = 2; 	0
25530485	14215	return result from query even if where clause not met	select isnull(sum(case         when taskid is null then 0         else 1       end), 0) as taskexists,      isnull(sum(case         when isdowntask = 0 and taskstatus = 63 then 1         when isdowntask = 1 then 1         else 0     end), 0) as pressready,     isnull(sum(case          when isdowntask = 1 and machineid <> 2710 then 1         else 0     end), 0) as downtaskassignedtodifferentmachine 	0.171577289338413
25530598	1260	count and group row in mysql	select count(distinct premium_name), premium_name  from     `table_premium` 	0.0276419193169367
25531435	17699	how do i retrieve all products in inventory, but also any product available with sql?	select p.product_id,   coalesce(i.amount_in_stock,0) as "in_stock" from s_product p left outer join s_inventory i   on p.id = i.product_id  and i.warehouse_id = 301; 	0
25532166	23634	sql - extract column from subquery	select b.id from bid b where b.amount = (select max(amount)                   from bid b2                    where b2.idauction = b.idauction                  ); 	0.0178317825821388
25532473	32306	mysql group and sum with joined tables	select sum(budget) as budget, count(*) as count from     (select * from campaigns where [conditions]) as found_campaigns     left join budgets on budgets.campaign_id = found_campaigns.id     group by channel_type 	0.0388826895001722
25532837	22167	mysql - get number of minutes in each hour when beginning and ending time are in different hours	select hour, userid,    case        when login < hour and logout >= addtime(hour,'1:00:00.0') then '1:00:00.0'        when login >= hour and logout < addtime(hour, '1:00:00.0')then timediff(logout, login)        when login >= hour and logout > addtime(hour, '1:00:00.0') then timediff(addtime(hour, '1:00:00.0'), login)        when login < hour and logout < addtime(hour, '1:00:00.0') then timediff(logout, hour)        else '00:00:00.0'    end case from hourlist join loginlogout on (login >= hour and login < addtime(hour,'1:00:00.0')) or (logout >= hour    and logout < addtime(hour,addtime(hour,'1:00:00.0')) order by hour 	0
25534173	3065	change text received from sql query in asp.net	select distinct case when formtitle = '' then '(blank)' else formtitle end as formtitle, formid from core.form_lkup order by formtitle 	0.178122516933837
25534657	41239	sql server 2012 counting semicolon separated values	select id, replace(fullname, ',', ';') as fullname,         len(fullname) - len(replace(fullname, ',', '')) + 1 as [count] from mytable; 	0.0132889262266715
25534876	18278	duplicates by few rows	select model1,model2 from t except select model2,model1 from t where model2 > model1; 	0.0143417000493234
25535063	26207	check multiple rows for a value	select case   when exists(select * from application where id=@id and issubmitted=1) then 0   else 1   end 	0.000790814245769454
25535235	11951	select only 1 'control number' without using distinct	select ... from (     select [ctrlno]     ,[refno]     ,[dealnocat]     ,[tcustomer].[customername]     ,[tbank].bankname     ,[tfimanagers].[finame]     ,[daysout]     ,[funddate]     ,[comment]     , row_number() over (partition by ctrlno order by daysout) as rn     from [tcontractsintransit]     inner join tfimanagers         on tfimanagers.fimanagerid = tcontractsintransit.fimanagerid     inner join tbank         on tbank.bankid = tcontractsintransit.bankid     inner join tcustomer         on tcustomer.customerid = tcontractsintransit.customerid     where pfx = 'x'       and paid = 'false' ) as t where rn = 1; order by ctrlno desc 	0.00196931848045639
25537043	21325	mysql ignore repeat values and get unique count	select    count(distinct item_id) as count,    user_id from    event_assigned group by    user_id order by    count desc 	0.000135508909222832
25537901	27255	accessing nested parent properties	select child.id as childid, parent.id as parentid, grandparent.id as grandparentid from child join parent join grandparent where child.parentid = parent.id and parent.parentid = grandparent.id 	0.267852337841449
25539317	19779	php code how to list the total value of each user	select user, sum(value1) as v1sum from b group by user 	0
25540241	24391	create a query to return the average transaction of a clients orders	select o.userid, avg(oi.ordertotal) averageordervalue from   orders o        inner join        (select orderid, sum(qty*price) ordertotal         from orderitems         group by orderid) oi on o.orderid=oi.orderid where  o.orderdate between @startdate and @enddate 	0
25541588	20844	java.sql.sqlexception: subquery returns more than 1 row	select log((select count(*) from doc)/(select count(docid) from indiceinv where term = new.term)) from doc, indiceinv 	0.241305143311347
25543926	10301	splitting a string in a stored procedure	select @len=len(@str) while(@i <=@len)     begin         if (substring(@str1,@i,1)=@str2)             begin                 select @laststr = substring(@str1,@i+1,@len)                  break             end         select @i = @i + 1     end 	0.18633850924497
25546139	8531	selection one entry only as non zero in sql select	select case when temp.rownumber > 1 then  0  else  temp.price end as price,  * from (           select *,row_number() over (partition  by id,status order by id,date) as 'rownumber'           from #temp ) temp order by id,date 	0.00016759070906335
25547349	24232	using a group by to group a select statement	select       k.ivalue     , k.jobdescription     , count(k.ivalue) as total from (             select                   a.id as ivalue                 , b.jobdescription                 , rq.currentstatus             from tblg2o_requests a                   inner join tblg2o_jobs b                               on a.jobpostid = b.id                   inner join (                               select                                     r.requestid                                   , ir.currentstatus                               from tblg2o_resultspool r                                     inner join tblg2o_requests ir                                                 on r.requestid = ir.id                               where r.shortlisted = '1'                         ) rqenter                               on rq.requestid = a.id             where active = '1'                   and datecompleted is null       ) k group by       k.ivalue     , k.jobdescription 	0.358890543548524
25547436	24178	sql select latest row by date	select  a.id, a.extractdate, a.total, a.used, a.free from( select   id,  max(extractdate) as [extractdate], total, used, free, row_number()over(partition by id order by max(extractdate) desc) as rnk from maintable inner join datatable on maintable.unkey = datatable.dataunkey group by id, total, used, free )a where a.rnk = 1 	0.000270409833797219
25551417	7414	how to reference a subquery in the select clause of a sql statement	select l.account, l.id,l.opendate,      l.originalbalance, l.balance,      l.duedate, l.creditscore,     pbd.birthdate pbdbirthdate,     jbd.birthdate jbdbirthdate from sym.dbo.loan as l    join sym.dbo.account as a       on a.account = l.account    join sym.dbo.name pbd       on pbd.account = l.account           and pbd.ordinal = 0     join sym.dbo.loanname jbd       on jbd.account = l.account           and jbd.parentid = l.id          and jbd.type in (01, 16, 20, 21)        where l.type in (0, 1, 2, 3, 14, 15, 23)      and l.balance > 0     and l.chargeoffdate is null 	0.376678898699179
25551664	5850	get the number of same field from a table in sql	select userid, count(userid) from usersessions group by userid 	0
25558961	36375	vb6 ms access sql query distinct count two tables	select      employees.employee_id as id      , employees.full_name as name      , presence.yr as year      , presence.mnth as month      , sum(iif(presence.dy, 1, 0)) work_days      , sum(iif(presence.hr, presence.hr, 0)) as work_hours      , sum(iif(presence.holidays, presence.holidays, 0)) as holidays_hours      , sum(iif(presence.hr, presence.hr, 0)) - sum(iif(presence.holidays, presence.holidays, 0) as total_work_hours      , sum(presence.hr) / employees.hoursperday + employees.totalannualholidays - employees.doneholidays as availableholidays from employees inner join presence on presence.employee_id = employees.employee_id where employees.company = 'acompany'      and employees.employee_id = 'anemmployee' group by  employees.employee_id, employees.full_name, employees.hoursperday, employees.totalannualholidays, employees.doneholidays, presence.yr, presence.mnth 	0.134320934745289
25559219	38426	two pdo selects in one if there is a result in both tables	select    *  from    websites w where w.owner    in (select u.username from users u where u.coins >= ?)   order by    rand()  limit    1 	0.00785752529615264
25561431	11541	filtering out good company result based on quarter date in mysql	select *    from (   select companyname,           max(case when quarter(quarterenddate) = 2 then profit end) q1,          max(case when quarter(quarterenddate) = 3 then profit end) q2,          max(case when quarter(quarterenddate) = 4 then profit end) q3,          max(case when quarter(quarterenddate) = 1 then profit end) q4     from quarterlyreport    where quarterenddate >= '2013-06-30' and quarterenddate < '2014-06-30'    group by companyname ) q  where q1 < q2 and q2 < q3 and q3 < q4 	0.000489210867986136
25561988	27463	how to compare date in sql server 2008	select * from datetest where coldate in (select coldate from  datetest group by coldate having count(*) > 1) 	0.0442131342112895
25562312	26005	how to count row1 from table1/count row1 from table2 returned result is group by day	select a.date_application alldates, ( (a.cnt / b.cnt) * 100) || '%' ratio   from    (  select t1.date_application, count (*) cnt                from table1 t1            group by t1.date_application) a        join           (  select t2.date_decision, count (*) cnt                from table2 t2            group by t2.date_decision) b        on a.date_application= b.date_decision 	0
25562322	9843	select multiple data from tables with sum and count	select pr.id      ,sum(p.cost) as [sum(cost)]      ,sum(case              when p.id_product is not null then 1              else 0            end) as [count] from product pr left outer join purchase p on p.id_product = pr.id                             and p.user_id = ... group by pr.id order by pr.id 	0.00123011471918155
25564502	25205	error in sql-syntax..showing just 3 instead of 4 rows	select g.gruppe from gruppen g where g.gruppe like '%vormittag%'    and g.gruppe_id not in (select d.gruppe_id                       from daten d                       where d.gruppe_id is not null                       group by d.gruppe_id                       having count(d.gruppe_id) >= 15) order by g.gruppe asc 	0.0386055053731751
25569626	8402	conditional join to two different tables based on 2 columns in 1 table	select col1,col2 from  dbo.box b join dbo.source s on s.id = b.sourceid where b.overridequeueid  is null union select col1,col2 from  dbo.box b join  dbo.queue q on q.id = b.sourceid where b.overridequeueid  is not null 	0
25570130	39214	sql count() column values	select t.code, count(*) as `count` from mytable t group by t.code order by count(*) desc 	0.0146865967914262
25571112	27522	ms access join tables in separate databases	select dr.* into audit_table from daily_report as dr left join [;database=c:\qa_daily_ytd_report_export.accdb].[ytd-daily_report] as ytd    on dr.recordname = ytd.recordname where ytd.recordname is null 	0.266877064862269
25571489	15244	get the latest date of records from a table, sql	select t.id, t.website, max(logintime) from table t group by t.id, t.website 	0
25572030	28569	adding another column based on different criteria (sql-server)	select c.agent,         sum(s.price) as totalsales,        sum(case                 when s.outboundcalldate is not null then s.price                else 0            end) as outboundsales from contact c, sales s where c.id = s.id group by c.agent 	0
25572147	40554	sum field with condition	select id, sum(hour) as hourtotal  from yourtable t1 where [order] > 1 or        not exists (select 1 from yourtable t2 where t1.id = t2.id and [order] > 1)  group by id 	0.085071797992254
25572883	20817	how to use distinct for just one field when order by another field is used?	select portaluri, max(lastlogindate) lastlogindate from loginhistory group by portaluri order by lastlogindate desc 	0.00113244913723018
25573354	17325	sql how to extract from two tables and join them like the example	select id, sum1, 0 as sum2 from tablea union all select id, 0 as sum1, sum2 from tableb 	0.00121147514683031
25574130	13953	extract from the same column different queries , resuls are diplayed in separate columns	select on.date, off.date from (   select date   from robot_state    where active=1 and section ='area1' and robotid=11 ) as on inner join (   select date   from robot_state    where active=0 and section ='area1' and robotid=11 ) as off  on off.date = (select min(date)                 from robot_state                where active=0 and section ='area1' and robotid=11                and date > on.date) 	0
25574794	2711	sql server pivot multiple columns	select * from (select c1,  b1, 'sales_' + cast(y1 as varchar(4)) as dimension,  sk,  sales as value   from dbo.s1   union all   select c1,  b1, 'cogs_' + cast(y1 as varchar(4)) as dimension,  sk,  cogs as value   from dbo.s1    ) as p   pivot   (   sum(value)   for dimension in   ( sales_2012, sales_2011  , cogs_2012   , cogs_2011)   ) as pvt 	0.181925903966005
25577615	33141	mysql count unique cell combinations, with null	select base.item1, base.item2, base.cnt + coalesce(sum(extra.cnt), 0) from (select item1, item2, count(*) as cnt       from data       where item1 is not null and item2 is not null       group by item1, item2      ) base join      (select item1, item2, count(*) as cnt       from data       where item1 is null or item2 is null       group by item1, item2      ) extra      on base.item1 = extra.item1 or         base.item2 = extra.item2 or         (extra.item1 is null and extra.item2 is null) group by base.item1, base.item2, base.cnt; 	0.000847141596510999
25579903	33272	how to get sql server username, through c# code?	select suser_sname() 	0.209789610056297
25579967	24898	how can i select from different tables in one mysql query?	select t1.firstname, t2.profession from table1 t1 join table3 t3 on t1.id=t3.firstname join table2 t2 on t3.profession = t2.profession 	0.000466503136308471
25582393	4845	i have missing numbers in the data in sql	select top 1 a.number + 1 from a where not exists (select 1 from a a2 where a2.number = a.number + 1) order by a.number; 	0.00581996268394068
25583676	26009	mysql order by date, with null first	select t.* from table t order by (start_time is null) desc,          start_time desc limit 1; 	0.0159810693023715
25585709	38260	do i need to use prepared statements when selecting values from db which was inserted by an user	select foo1, foo2 from tbl 	0.0108590413375943
25587083	5228	finding substring duplication in oracle 11g	select a.* from (select a.*, count(*) over (partition by substr(a.col1, 1, 5)) as cnt       from tablea a      ) a where cnt > 1 order by a.col1; 	0.334618669075997
25587561	19672	query to select intervals in day	select * from intervals  where interval in (     select distinct interval from intervals where day = 8) 	0.00140871718360124
25589631	3767	mysql service start time	select date_sub(now(), interval variable_value second) started_at from information_schema.global_status  where variable_name='uptime'; 	0.10230451789884
25590211	22273	adding 'count' in mysql query with multiple tables in 'from' clause	select * , (select count(*) from u) as totalcount from u , s , c , ut , m ; 	0.115299115591852
25591773	35002	repeating running numbers along side mysql results	select mod(i,3)+1      , result    from       ( select @i:=@i+1 i             , result           from results             , ( select @i:=2 ) vals          order             by result      ) x; 	0.00682016382410949
25594547	30471	sql - grouping results of select but keep some values unique	select year,         sum(wins),         sum(cuts),         sum(case when tour = 'eur' then money end) as moneyeur,        sum(case when tour = 'usa' then money end) as moneyusa from players  group by year 	0.000570385781625026
25596659	8278	get one random value after php query fetch rows from the table	select reg_number from users order by rand() limit 1 	0
25598073	12652	how to write a sql command to sort multiple rows	select col1, min(col2), col3, col4 from mytable group by col1, col3, col4 order by col1, col3, col4 	0.0410770347829042
25598373	40888	sql to get count of members in each group	select     groupname, [group].groupid, count(*) as 'membercount' from [group] inner join group_student on [group].groupid = group_student.groupid group by groupname, [group].groupid 	0
25599037	1115	how to generate auto increment values column when select statement run in my sql?	select @mycount:=@mycount+1 as newcol, id, title, lscno from tutorials_tbl, (select @mycount:= 0) t where lscno in (     select lscno     from tutorials_tbl     group by lscno     having count(lscno) > 1 ) order by lscno 	0.00423398800485788
25599407	24890	select data from table with compare two table	select s.* from list as s,sync as sc where s.device_id = 4 or (sc.device_id=4 and sc.list_id=s.id) 	0
25600186	16049	how to get duplicate rows of a single column including other columns in sql server	select cityid, cityname, countryid from tab where cityid in (select cityid from tab                  group by cityid                  having count(cityid) > 1); 	0
25600555	30820	how to get union of 3 tables in sqlite?	select * from (select * from a                intersect                select * from b                intersect                select * from c) union  select * from (select * from a                intersect                select * from b) 	0.00235292440224532
25601198	32043	how to get the value of max length in sql server	select top 1 t.value from table as t order by len(t.value) desc 	0.000222452448311436
25601999	11918	filter items from linking table	select *  from items i  where id in (select itemid from linking where tagid = 1) or (   id in (select itemid from linking where tagid = 2)   and id in (select itemid from linking where tagid = 3) ) 	0.000225739326210592
25603620	590	how to select firrst column date and second column time as datetime	select cast(cast(@reminderdate as date) as datetime) + cast(dateadd(hour,-3,@remindertime) as time) 	0
25603657	6859	sql select by dayofweek as column header	select    targetname,    sum(case when datepart(weekday,logdate) = 2 then hits end) as monday,    sum(case when datepart(weekday,logdate) = 3 then hits end) as tuesday,    sum(case when datepart(weekday,logdate) = 4 then hits end) as wednesday,    sum(case when datepart(weekday,logdate) = 5 then hits end) as thursday,    sum(case when datepart(weekday,logdate) = 6 then hits end) as friday,    sum(case when datepart(weekday,logdate) = 7 then hits end) as saturday,    sum(case when datepart(weekday,logdate) = 1 then hits end) as sunday from targets group by targetname order by targetname; 	0.0949012519248811
25604457	20012	how find all rows where one of jsonarray elements has give property equal to something?	select id, a from (     select id, json_array_elements((j ->> 'media')::json) as a     from (values(1, '         {"media": [            {},            {},            {},            { "key": "thumbnail", "metadata": { "width": 123, "height": 321 } }         ]}'::json     )) s(id, j) ) s where     a ->> 'key' = 'thumbnail'     and     (a #>> '{metadata, width}')::integer = 123     and     (a #>> '{metadata, height}')::integer = 321 ;  id |                                  a                                     1 | { "key": "thumbnail", "metadata": { "width": 123, "height": 321 } } 	0
25605464	1958	count records which occurs more than once in a column	select count(*) from (select values   from table   group by values   having count(*) > 1) t 	0
25605871	4862	sql: customer that has bought a work from every artist || 2 tables	select t.customerid  from    ( select t.customerid, count(distinct artistid) as artists     from trans t inner join work w on w.workid = t.workid) t    inner join    ( select count(distinct artistid) artists from work) a on  t.artists = a.artists 	0
25606747	30239	how to separate rows group by in sql query	select    sd.invoiceno as sale_details_invoiceno,    sd.product_code,   sd.qty,    sd.totalkg,    sd.rate,    sd.subtotal,        sh.invoiceno as sale_head_invoiceno,    sh.suppliername,    sh.invoicedate from sale_head sh inner join sale_details sd on sh.invoiceno = sd.invoiceno where sh.suppliername = 'ramkrishna creation' union all select    sd.invoiceno,   'total',   null,    null,    null,    sum(sd.subtotal),        null,    null,    null from sale_head sh inner join sale_details sd on sh.invoiceno = sd.invoiceno where sh.suppliername = 'ramkrishna creation' group by sd.invoiceno  order by sale_details_invoiceno, iif(product_code = 'total', 1, 0); 	0.0123967281628976
25607326	1849	condition based on count(*) in query with group by clause	select t.location_id      ,count(t.location_id) as [nbrecords] from yourtable t group by t.location_id having count(t.location_id) > 75000 	0.0981779656629748
25607509	2974	how to get non-nullable data in columns	select empid ,        max(employeedailyfee) as employeedailyfee,        max(employeemonthlyfee) as employeemonthlyfee,         max(companydailyfee) as companydailyfee,         max(companymonthlyfee) as companymonthlyfee from employees group by empid 	0.00115746394845281
25607947	32122	mysql join three tables order by third	select jss_products.* from jss_products_tree inner join jss_products    on jss_products.productid = jss_products_tree.productid  inner join jss_extrafields_values   on jss_extrafields_values.productid = jss_products.productid where stock!=0 and    and sectionid=1  order by jss_extrafields_values.field 	0.101011659452313
25610504	32472	assig multiple columns in a case statement?	select    [filename],   case      when [filename] like 'ate_%' then cast(substring([filename],5,5) as nvarchar(100))     when [filename] like '%adhoc%' then cast([filename] + ' ' + [sheetname] as nvarchar(100))     when [filename] like 'advantagedata%' then [sheetname]    end as abtalookup,   case      when [filename] like 'ate_%' then 'abta'      when [filename] like '%adhoc%' then 'filesheet'     when [filename] like 'advantagedata%' then 'sheet'    end as abtasource 	0.6303031624728
25610741	31529	sql server: how to combine different counts in one query	select      count(*) over() as countb,             null as  countc,             null as counte from        moc_log2 b where       b.modby = @modby and         b.lastupdate = 'added' for xml path(''), elements, type union select      null,             coalesce(sum(d.vote), '0'),             null from        moc_log3 c left join   moc_log3_votes d on          d.itemid = c.itemid where       c.modby = @modby and         c.lastupdate = 'added' for xml path(''), elements, type union select      null,             null,             coalesce(sum(f.vote), '0') from        moc_log4 e left join   moc_log4_votes f on          f.itemid = e.itemid where       e.modby = @modby and         e.lastupdate = 'added' for xml path(''), elements, type 	0.00209951124481615
25611678	2149	mysql select count(*) from two tables based on multiple conditions	select count(c.id) as [count] from t_contacts c inner join t_contacts_meta m on m.cid = c.id                                and m.interest in ('interest_1', 'interest_2', 'interest_n') where c.state = 'state_value'     and c.profession = 'profession_value'     and c.sex = 'sex_value' 	0
25614264	19345	mysql , how to join 2 result , ideas are welcome	select t1.id, t1.`1d`, t2.`2d` from (query1) as t1 join (query2) as t2 on t1.id = t2.id 	0.332226869396805
25616750	40189	mysql how to get month and year with separation like date format	select("date_format(now(), '%y-%m') as dated_now", false); 	5.70462693574686e-05
25617095	16124	how to put a counter in the group by using sql	select name + '-' + cast(row_number() over (             partition by name order by id) as varchar(24)) from your_table 	0.0533017894619274
25617510	12756	how to capture chronological changes to an array in sql?	select * from variations where date(date) <= 'xxxx-xx-xx'   and not exists (select 1                   from variations as v2                   where v2.location = variations.location                     and v2.key = variations.key                     and v2.date <= 'xxxx-xx-xx'                     and v2.date > variations.date) 	0.0456329396757156
25620800	23131	how do i pivot multiple choice values into 1 row per object?	select       objectnumber     , [yes]     , [foo bar baz]     , [lorem ipsum] from     t pivot (     count(field)     for value  in ([yes],[foo bar baz],[lorem ipsum]) ) u 	0.000181401539289471
25621754	5147	query having multiple counts	select    seq_nbr,    terr_cd,    count(*) over (partition by terr_cd, seq_nbr) terr_cnt,   dstr_cd,   count(*) over (partition by dstr_cd, seq_nbr) dstr_cnt,   rgn_cd,    count(*) over (partition by rgn_cd, seq_nbr) rgn_cnt,   area_cd,    count(*) over (partition by area_cd, seq_nbr) area_cnt,   cntr_cd,   count(*) over (partition by cntr_cd, seq_nbr) cntr_cnt from @temp 	0.259293116455984
25622556	5485	inner join on three tables linked by foreignkeys	select * from forceinstance fi  inner join force f on  fi.forceid = f.forceid inner join forcetype ft on f.forcetypeid = ft.forcetypeid 	0.520199782737352
25624070	38045	getting a list of all fields name in a table	select c.name from syscolumns c inner join sysobjects o on c.id = o.id where o.name = 'my_table' 	0
25624076	28626	how to subtract one row from another row in the same table?	select requisitioncode , ( isnull((select top 1 approvedcount from requisitionhistory rh where rh.requisitioncode =r.requisitioncode order by rh.requisitiondate desc),0) - isnull( (select top 1 approvedcount from requisitionhistory rh1 where rh1.requisitionhistorycode not in    (select top 1 requisitionhistorycode from requisitionhistory rh2      where rh2.requisitioncode =r.requisitioncode order by rh2.requisitiondate desc)    and rh1.requisitioncode = r.requisitioncode order by rh1.requisitiondate desc),0)) as structurechange  from requisition r 	0
25624391	1796	ordering in sql	select empno, empname,sal from emp order by 2,3 	0.4772873698995
25626582	22734	mysql order incorrect with capitalized letters	select * from `my_table` order by `name` collate 'latin1_general_ci' 	0.776549016623648
25630429	23059	postgres query to fetch results between two dates	select * from test where (start_date >= '2014-08-15' and (end_date <= current_date or end_date is null)) or        (start_date <= '2014-08-15' and (end_date > '2014-08-15' or end_date is null)); 	0.000310654875770122
25630832	22728	sql count query with no data	select shippers.shippername,count(orders.orderid) as numberoforders  from   shippers   left join orders     on orders.shipperid=shippers.shipperid group by shippername limit 8 order by numberoforders desc; 	0.178406711278467
25630961	25821	sql select categories where items have different values	select * from yourtable a where exists(select 1 from yourtable              where categoryid = a.categoryid               and [status] <> a.[status]) 	9.22521203611904e-05
25631390	20442	get tablename where the variable in a column matches	select * from (     select          'tblc1' as tbl, tblc1.*      from   tblc1        union select 'tblc2', tblc2.* from tblc2         union select 'tblc3', tblc3.* from tblc3  ) t where t.nname = "new5" 	0.00169592818327891
25631515	15907	how to create a summary view of master/detail tables using sql	select   transactionid,   count(*) as [number of details],   sum(case when quantityremaining = 0 then 1 else 0 end) as [completed],   sum(case when quantityshipped > 0 and quantityshipped < quantityordered then 1 else 0 end) as [partially shipped] from orderdetails group by transactionid 	0.0230064565449025
25634028	10736	mysql get time duration up to a selected action	select   session_id,          min(time) as first_action_time,          min(case when action_name = 'email' then time end) as first_email_time,          timestampdiff(second,min(time),min(case when action_name = 'email' then time end)) as diff_in_secs from     actions group by session_id 	0.00088380795756734
25634943	2355	complex query where record is max in set	select    candidatecategoryid from      candidatecategory where     candidatecategoryid in (     select    max(candidatecategoryid)     from      candidatecategory     group by  candidateid ) and       categoryid = 23 	0.416786298847262
25635100	4060	how to use arrays and sets using postgresql?	select distinct property1, property2 from properties where not propertyid=any(propertiesid); 	0.233785444992352
25635254	33733	order an ordered sql query	select shippername, numberoforders from (select s.shippername, s.shipperid, count(o.orderid) as numberoforders        from shippers s left join            orders o            on o.shipperid = s.shipperid       group by shippername, s.shipperid       order by numberoforders desc       limit 8      ) s order by shipperid; 	0.268477427638558
25636023	903	recent rows for each id	select * from sgwebdb.pump_station_data t1 inner join (   select station_id,  max(lastupdate) as lastupdate   from sgwebdb.pump_station_data   group by station_id ) t2   on t1.station_id = t2.station_id   and t1.lastupdate = t2.lastupdate 	0
25639385	23022	make select sum() not return null	select  sum(time) as sumtopay,  w.name,  w.lname  from `service` s  join worker w on s.worker_id = w.id  group by s.worker_id  having sum(time) > 0 	0.272651813257504
25639795	12468	mysql - how can i select column where row is in array?	select * from table_name where event_invitees like '%tnylee%' 	0.0124677783579126
25639940	13516	find duplicate in two columns in sql server	select  propertyid, districtid from dbo.tablename group by propertyid, districtid having count(*) > 1 	0.000399721081283758
25641555	17493	change date format in sql query	select min( str_to_date( date_enter,  '%m/%d/%y' ) ) as minval from  patient  where patient_name='$patient_name'   and patient_dep='$dep'   and patient_doctor='$patient_doctor'   and patient_type='opd' group by patient_id 	0.120491769906202
25641992	38661	mysql - join 2 queries with limit	select u.member     ,t.category from users u inner join tickets t on t.name = u.member inner join (select t2.name                ,max(t2.time) as [maxtime]            from tickets t2            group by t2.name) as m on m.name = t.name                                and m.maxtime = t.time where u.online = 1 	0.428692237794204
25642775	9907	to update a column in xml format selecting data sql table using t-sql	select e.empname,        1      as 'salarydetails/salary',        e.amt1 as 'salarydetails/amount',        2      as 'salarydetails/salary',         e.amt2 as 'salarydetails/amount' from employee as e for xml path('employee') 	0.00204463604219751
25643944	3503	firebird 1.5 : group by maximum value	select gep.kod      , gep.irsz      , gep.varos      , gep.utca      , gep.ugyint      , gep.emelet      , cikk.nev      , max(gepelem.szamlalo)  from gep  left join cikk     on gep.cikk    = cikk.kod and  gep.ceg = 27013 left join gepelem  on gepelem.kod = gep.kod    group by gep.kod      , gep.irsz      , gep.varos      , gep.utca      , gep.ugyint      , gep.emelet      , cikk.nev 	0.00128102201916528
25644216	24199	extract year and month from timestamp(6)	select to_char(timestamp, 'yyyy-mm') from your_table 	0
25644232	24128	get all rows from two tables with sqlite	select * from tablea union select * from tableb 	0
25645183	5076	sql statement to return student's best grade	select studentname        ,min(grade)  best_grade from table_name group by studentname 	0.0587886320832849
25645704	4662	search for same values in two sql tables	select    *  from    table1 t1    left join table2 t2 on t1.number=t2.number  where    t2.number is null 	0.000853560990740468
25646743	37829	convert query to count rows	select count(*) from rz_price left join currencies on currencies.`name` = 'usd' left join  goods on goods.id = rz_price.`rz_art` left join rz_archive on rz_archive.rz_art  = rz_price.rz_art where  rz_archive.rz_art is null  and (round(if(rz_price_grn != 0, rz_price_grn, round(rz_price2 * currencies.`rate`)), 2) != round(if(price is null, 0, price), 2)) 	0.0247085567181768
25651849	11817	counting multiple column sums	select (case when detail_1 like '%sample%' then isnull(qty_1, 0) else 0 end        + case when detail_2 like '%sample%' then isnull(qty_2, 0)  else 0 end        + case when detail_3 like '%sample%' then isnull(qty_3, 0)  else 0 end        + case when detail_4 like '%sample%' then isnull(qty_4, 0)  else 0 end        + case when detail_5 like '%sample%' then isnull(qty_5, 0)  else 0 end        + case when detail_6 like '%sample%' then isnull(qty_6, 0)  else 0 end        + case when detail_7 like '%sample%' then isnull(qty_7, 0)  else 0 end        + case when detail_8 like '%sample%' then isnull(qty_8, 0)  else 0 end        + case when detail_9 like '%sample%' then isnull(qty_9, 0)  else 0 end        + case when detail_10 like '%sample%' then isnull(qty_10, 0) else 0 end) 	0.00875116730673059
25652307	31134	get user position in a fantasy league sql	select [leagueid],        [entryid],        [userid],        [totalpoints],        [totalbonuspoints],        [totalpointslastrace],        [totalbonuspointslastrace],        dense_rank over( partition by [leagueid] order by [totalpoints] desc, [totalbonuspoints] desc) as [position],        dense_rank over( partition by [leagueid] order by [totalpointslastrace] desc, [totalbonuspointslastrace] desc) as [positionlastrace] 	0.016199419603213
25652503	24358	getting duplicates in mysql join query	select distinct <rest of your query goes here> 	0.427825515727461
25653458	28863	mysql. how to number group's members in join statement	select col1, col2, col3, col4 from (   select *      , @num:=@num+1 as col3      , if(@a = col2, @counter := @counter +1, @counter := 1) as col4      , @a := col2     from      (   select *           from         (select (1) as col1 union select (2) union select (3) union select (4) union select (5)  order by rand()         )t     ) a     join     (   select *          from (select (1) as col2 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)         )c     ) b     on b.col2 >= a.col1     cross join(select @num := 0, @counter := 0, @a := 0)temp     order by col2 ) f; 	0.0124971310534374
25654298	12561	how to sum an as column in sql	select sum(wf.frequency * ww.weight) as product from wf  inner join ww on ww.word = wf.word 	0.0534627742472025
25655321	33851	daily sum by type to show date and '0' even when null (no activity for that type on that date)	select v.date_dy, v.type, sum(coalesce(cost, 0))   from data  right join (select date_dy, type from date_table cross join type_table) v     on v.date_dy = data.date_dy    and v.type = data.type  group by v.date_dy, v.type  order by v.date_dy, v.type 	0
25657757	25178	how to filter the total sales record every month using sql query?	select year(date_purchased), month(date_purchased), count(product_id)  from sales_table  group by concat(year(date_purchased), month(date_purchased)) 	0
25659048	8819	where in with column content	select xyz  from abc  where id in  (   select distinct to_number(regexp_substr(content,'[^,]+', 1, level))   from c_configuration   where identifier = 'id'   connect by regexp_substr(content, '[^,]+', 1, level) is not null ) 	0.121609639765491
25661726	23401	set variable inside select statement	select  ft.nbranchid       , ft.tmdate       ,'wrong sign in column ' +         case when ft.fdeposits < 0 then 'fdeposits'              when ft.fwithdrawals > 0 then 'fwithdrawals'              when ft.fperformancefee > 0 then 'fperformancefee'              when ft.ffixedfee > 0 then 'ffixedfee'              when ft.fdividend > 0 then 'fdividend'              when ft.freinvestment < 0 then 'freinvestment'              when ft.fthresholdrate < 0 then 'fthresholdrate'              when ft.fperffeecumulated > 0 then 'fperffeecumulated'         end       as columnname from dbo.fundtransactions as ft 	0.761030530453338
25661864	9655	format specific values for xml path	select    name,   case when name='n2' then round(value,7) else value end as value ... 	0.00986962142285721
25662474	16935	show the column not null of two tables in sql	select n.id_name     ,ifnull(n.name, n.nickname) as [username]     ,case       when n.name is not null then 'name'       else 'nickname'     end as [username_source] from names n inner join companies_to_names c on c.id_name = n.id_name                                  and c.id = 1 	0.000559457265602441
25663106	30913	count unique rows of 3 join tables	select    substring(t3.serialnumber, 1, 3) as batch,    count(distinct t3.code) as total,    sum(case when t2.callnr is null then 1 else 0 end) as nocall,    count(distinct t2.code) as call_per_code from test3 t3     left outer join test2 t2 on t3.code = t2.code group by substring(t3.serialnumber, 1, 3) 	0.000373639514591254
25665204	13668	listing all tables a user has query rights on in oracle	select owner || '.' || table_name   from sys.all_tables  where secondary = 'n' and owner = 'user1' union all select owner || '.' || table_name   from dba_tab_privs  where grantee = 'user1' and privilege = 'select' 	0.000763134848618815
25665302	40206	mysql multiple tables join , same column title	select tour.id_tour as tour_id, tour.title as tour_title, group_concat(country.title order by country.title separator ',') as country_title, tour.* from tour      inner join tour_to_country on tour.id_tour = tour_to_country.id_tour      inner join country on country.id_country = tour_to_country.id_country     group by tour.id_tour 	0.00199805964524001
25666870	15811	retrieving all the column names with a specific value	select column_1, column_2, column_3, column_4, column_5, column_6 from dbo.tablename where column_1 in ('good', 'very good') or    column_2 in ('good', 'very good') or    column_3 in ('good', 'very good') or    column_4 in ('good', 'very good') or    column_5 in ('good', 'very good') or    column_6 in ('good', 'very good') 	0
25667782	22952	mysql query for distinct count based on a specific column	select ut.tagid, t.tag, ut.userid,        (select count(*) from usertags ut2 where ut2.userid = ut.userid) as totalcount from tags t inner join      usertags ut      on ut.tagid = t.tagid order by userid; 	0.000160596485649157
25668027	20581	mysql more readable way to find column value belonging to a very large set.	select t.*  from table as t join somevals as v  on t.col = v.val; 	0.0173703721382325
25668336	38255	sql server: multiple selects in a single query	select      m.maccno,     t.trancode,     v.taxcode,     vt.taxcode from      master m inner join     (select          accno,trancode      from          ntrans      union all      select          accno,trancode      from          ntransarc) t on      m.maccno = t.taccno   inner join      (select         taxcode,         vtrancode     from         vat      union all     select          taxcode,         vtrancode             from          vattrans      union all      select          taxcode,         vtrancode      from          vattransarc) v on      v.vtrancode = t.trancode order by      m.maccno 	0.259732381468603
25668665	18187	joining tables with references to each other	select a.aid, b.bid from a left outer join b on a.aid=b.aid  left outer join c on c.aid=a.aid and (c.bid is null or c.bid=b.bid) where c.cid is null 	4.58330636956049e-05
25669661	17578	concatenate string variables into a new variable in new table	select [id],isnull(cast(x01 as nvarchar(4000)),'') + isnull(cast(x02 as nvarchar(4000)),'') + isnull(cast(x03 as nvarchar(4000)),'') + isnull(cast(x04 as nvarchar(4000)),'') + isnull(cast(x05 as nvarchar(4000)),'') as new_string into newtable from oldtable 	0.000163923910055348
25669985	15583	convert comma separated varchar to numeric without replace	select parse('12,3' as numeric(12,2) using 'sv-se') 	0.00255202559645621
25671953	21482	how to get rows from table	select recipe_id, count(distinct ingredient_id) from recipes2ingredients where ingredient_id in (1,2) group by recipe_id having count(distinct ingredient_id) = 2 	7.76426363713891e-05
25672526	18434	counting records <1500 and >= 1500	select sum(case when amount > 1500 then 1 else 0 end) as gt1500     , sum(case when amount < 1500 then 1 else 0 end) as lt1500     , datepart(year, amount.date) deposit_year     , datepart(quarter, amount.date) deposit_qtr  from account  full outer join amount on account.acctno = amount.acctno group by datepart(year, amount.date)     , datepart(quarter, amount.date) 	0.0162382525918476
25672932	1245	double join resulting in duplicate records and incorrect row count	select pit.table_name, max(i.rows) numberrows from @peopleidtables pit join sys.tables t on pit.table_name = t.name join sys.sysindexes i on t.object_id = i.id group by pit.table_name 	0.00776155906548978
25673133	9787	mysql database query with if condition	select v.*     ,case         when (from_unixtime(v.upload_date) < now() - interval 2 day) then 'yes'         else 'no')      end as new from `video` as v 	0.465706459820504
25673150	37844	php mysql sum values of donations of all the users	select name, id, sum(amount) as totaldonation from t1 group by id order by totaldonation desc limit 0,3 	0
25673284	21664	select last message from each member	select ad.id_membre_message, ad.id_message #and anything else you'd like to select from cbadminmessages ad inner join cbmembres mem on ad.id_membre_message=mem.id where mem.id!='$admin_id' and ad.id_message = (     select max(ad_sub.id_message)     from cbadminmessages ad_sub     where ad_sub.id_membre_message = mem.id) order by ad.id_message"); 	0
25674991	20839	inner join returning column name	select u.id     ,u.primeironome     ,u.ultimonome     ,u.email     ,p.cpf from [user] as u inner join pacientes as p on p.user_id = u.id 	0.443416170605048
25677449	1163	select parent and child in sql server with hierarchyid	select itemno, itemno.tostring() as itemid, lvl, matid from bomtbl p where exists (select * from bomtbl c  where c.matid like 'ma%'  and (c.itemno.getancestor(1) = p.itemno        or c.itemno.getancestor(0) = p.itemno ) ) 	0.0164180241352545
25678251	34840	combining aggregate counts into an existing sql query	select c.categoryid, c.categoryname, utc.sortorder, count(stc.serviceid) from categories c inner join userstocategories utc on utc.categoryid = c.categoryid inner join servicestocategories stc on stc.categoryid = c.categoryid where utc.userid = 1234 group by c.categoryid, c.categoryname, utc.sortorder, utc.userid 	0.146645221633772
25680101	36310	passing more than one row (query result) into a function	select min(f.a)   from bar     cross join foo(bar.a) f   where bar.b = 1 	0.00661368856007825
25680959	20505	sql- how to put your row result as a column	select * from (          select [level]          from [user]      ) as sourcetable pivot(          max([level])          for [level] in ([administrator], [standard user], [limited user])      ) as pivottable; 	0.00958644741170538
25680960	20909	sql 2 where clauses	select * from impoundreports where (userid = @0 and released is null)     select * from impoundreports where (userid = @0 and released is true)     select * from impoundreports where (userid = @0 and released is false) 	0.295092940226554
25681018	383	how to get number of students per course in sql?	select max(t_course.name) as course_name, count(t_enrolment.student_fk) as count_students     from t_course     left join t_enrolment on t_enrolment.course_fk = t_course.course_id     group by t_course.course_id; 	0
25684180	424	comparing dates in sql returns wrong records	select data from montaggio where str_to_date(data, '%d/%m/%y') >= str_to_date('29/08/2014', '%d/%m/%y') 	0.0571895139903172
25685384	21833	getting year and month from sql	select cast(year(getdate()) as varchar(4)) + right('0' + cast(month(getdate()) as varchar(2)), 2); 	0.000105722428653062
25686938	18879	ibm i count needed for db table	select * from yourtable where transcode = '001'   and order# not in (select order# from yourtable                          where transcode <> '001'                     ) 	0.766682334930911
25687070	19403	sql query to check multiple values of multiple columns	select * from mytable as a join mytable as b on a.id=b.id where a.substitute!=b.location_id 	0.000583346653620072
25687179	21449	how to get a simple field with grouped by field?	select * from table t where not exists   (select * from table where t.id_number = id_number and date > t.date) 	0.00210522796163483
25689146	14622	iterate the number of rows returned from a select statement	select   @`rownum` := @`rownum` + 1 `count`,   `t`.`id`,   sum(`t`.`qty`) `sums` from   (select @`rownum` := 0) der, `table` `t` group by   `t`.`id`; 	0
25689159	27512	converting datetime to varchar with just the date portion	select convert(varchar(50), cast('2014-09-05 11:06:38.927' as datetime), 101) 	0.00454860402760189
25689197	20381	get the latest date in sql from text format	select max(cast(table.date as datetime)) from table 	0
25698265	15057	mysql query select from 2 tables, count the most used	select tablea.office  from tablea join tableb   on tablea.ido = tableb.ido group by tablea.office order by count(*) desc limit 1 	0.000345479064088757
25700105	32040	calculating sum of jobs processed every month using two tables	select t.month,          t.year,           sum(s.sum_of_jobs_processed)     from bspm_dim_time t     join bspm_sum_jobs_day s       on t.time_id = s.time_id group by t.month,          t.year order by t.year,          t.month 	0
25701589	27952	is it possible to get corresponding values for related keys	select vat  from tablename  where  item_id in (1, 2, 3); 	0.000258029650192281
25701693	9788	how to pivot a column that is not unique in mysql or ssis?	select     pid,     max(case mid when 1 then val else null end) as mid1,     max(case mid when 2 then val else null end) as mid2,     max(case mid when 3 then val else null end) as mid3,     max(case mid when 4 then val else null end) as mid4,     max(case mid when 5 then val else null end) as mid5,     max(case mid when 6 then val else null end) as mid6 from inputtable group by pid; 	0.159278512256897
25706316	19702	postgres cumulative count over time	select m, count(subscriptions.*)  from subscriptions  join generate_series('2010-01-01'::date, now(), interval '1 mon') as m on m >= subscriptions.creationdate and         (subscriptions.deletiondate is null or m <= subscriptions.deletiondate) group by m order by m; 	0.0158190836072246
25707782	22999	convert from time in format h.mm to minutes	select hh + (mi/100) as final_result from (   select trunc(step3.tot_mins/60) as hh          , step3.tot_mins - (trunc(step3.tot_mins/60)*60) as mi   from (       select sum((step2.hh*60)+step2.mi) as tot_mins       from (         with step1 as (select to_char(ctime, '00000000000.99') ctime                     from your_table)         select to_number(regexp_substr(ctime, '([0-9]+)', 1,1)) as hh                , to_number(regexp_substr(ctime, '([0-9]+)', 1, 2)) as mi         from step1            ) step2     ) step3   ) step4 / 	0.00104565135658539
25707860	9382	select previous date record to be calculated sql	select   row_number() over (order by t1.mydate) as id,   t1.mydate,   t2.value - t1.value as resultvalue from your_table t1 join your_table t2   on t2.mydate = dateadd(d, 1, t1.mydate) where t1.mytime = '0:00:00' and t2.mytime = '0:00:00' 	0.00149181800374658
25709965	1765	php - how to get order from query and get "place number"	select amount, rank  from  (   select *, @rank := @rank + 1 as rank   from referral_competition    cross join (select @rank := 0) r   order by amount desc    limit 40 ) tmp where userid = $someuser 	5.69944788538477e-05
25712505	18416	sql get latest record for each id	select u.id, u.name, s.saldo, p.last_paid_date, p2.amount   from users u   join saldo s     on u.id = s.user_id   join (select user_id, max(paid_date) as last_paid_date           from payments          group by user_id) p     on u.id = p.user_id   join payments p2     on p.last_paid_date = p2.paid_date    and p.user_id = p2.user_id 	0
25714213	13530	group by two tables	select surname, sum(cnt) from (    select surname, count(*) as cnt    from people.northkorea    group by surname    union all    select surname, count(*) as cnt    from peopleglobal.northkorea    group by surname ) group by surname order by cnt desc 	0.025693683081695
25714804	29968	select statement for cocktail db	select cocktail_name as all_ingredients_in_stock  from cocktail_ingredients ci inner join ingredients_in_stock iis      on ci.ingredient_name = iis.ingredient_name group by cocktail_name having count(*) =      (select count(*)      from cocktail_ingredients      where cocktail_name = ci.cocktail_name ) 	0.723623265443925
25715066	36936	mysql find user rank for each category	select user_id, category_id, points,        (@rn := if(@cat = category_id, @rn + 1,                   if(@cat := category_id, 1, 1)                  )        ) as rank from (select u.user_id, u.category_id, sum(u.points) as points       from users u       group by u.user_id, u.category_id      ) g cross join      (select @user := -1, @cat := -1, @rn := 0) vars order by category_id, points desc; 	0
25715117	3876	find records from a table that, among associated records in another table, don't have a record with a specific field value	select a.* from a left join b on a.id = b.table_a_id and b.name = 'cat' where b.id is null 	0
25716490	37656	mysql show select output replacing caracters	select ...,replace(group_concat(...), '@','_'),... 	0.106310248961832
25716757	15961	select vertical table to horizontal table sql	select      min(case when grp = 'a' then mydate end) as mydate1,             min(case when grp = 'a' then value end) as value1,             min(case when grp = 'b' then mydate end) as mydate2,             min(case when grp = 'b' then value end) as value2 from        tbl group by    mydate 	0.00500038055385919
25718190	21157	get missing data from should be identical mysql tables	select *  from t1 as a  left join t2 as b on a.one = b.one and a.two = b.two and a.three = b.three  where b.four is null 	0.00698173427427303
25719690	32141	get minimum unused value in mysql column	select min(unused) as unused from (     select min(t1.id)+1 as unused     from yourtable as t1     where not exists (select * from yourtable as t2 where t2.id = t1.id+1)     union     select 1     from dual     where not exists (select * from yourtable where id = 1) ) as subquery 	0.00020531662106629
25719777	37072	query invoices that have more than one transaction associated with them	select invoiceid from tblaccounts group by invoiceid having count(*)>1 	0.000514995048008897
25719945	40916	redshift: how to cast integer with year into a date?	select year_of_birth, to_date(cast(year_of_birth as text), 'yyyy') from visit_occurrence ; 	0.00421863913142306
25723611	28997	duplicate records in query result	select  t_actionticketlog.actionticketid     ,t_actionticketlog.barcode     ,t_actionticketlog.userid     ,t_ticketstatus.name     ,t_orderticket.orderid     ,max(t_ticketprint.ticketbarcode) from t_actionticketlog  inner join t_ticketstatus     on t_actionticketlog.statusid = t_ticketstatus.id left outer join t_orderticket      on t_actionticketlog.ticketorderid = t_orderticket.id left outer join t_ticketprint      on t_orderticket.actionticketid = t_ticketprint.actionticketid where   t_actionticketlog.actionticketid = 21780101 group by t_actionticketlog.actionticketid     ,t_actionticketlog.barcode     ,t_actionticketlog.userid     ,t_ticketstatus.name     ,t_orderticket.orderid 	0.00650745658131622
25723682	16234	department parameter ssrs	select isnull(name,'not applicable') as [department] from tablea where name in (@departmentname)  or nullif(@departmentname, 'no department link') is null 	0.36586832409367
25724678	6464	i am unable to find the sum of counts in mysql	select sum(c) `sum` from (   select count(distinct col1) c    from table1   group by date ) t 	0.0293882459514969
25724859	25893	data manipulation with mysql - join and counting	select b1.author as author_1, b2.author as author_2, sum(case when s.book_similarity = 'high' then 1 else 0 end) as num_high, sum(case when s.book_similarity = 'low' then 1 else 0 end) as num_low from similarity s inner join book b1 on b1.book_id = s.book_id_1 inner join book b2 on b2.book_id = s.book_id_2 group by b1.author, b2.author 	0.309158890268569
25726013	18772	sql multiple rows into one	select user, access_date,        max(case when formfactor = 'mobile' then 1 else 0 end) as key_mobile,        max(case when formfactor = 'desktop' then 1 else 0 end) as key_desktop,        (case when max(case when formfactor = 'mobile' then 1 else 0 end)  > 0 and                   max(case when formfactor = 'desktop' then 1 else 0 end) > 0              then 1 else 0         end) as key_mobile_desktop from table t group by user, access_date; 	0.000954028769997204
25726161	16589	sql server : query to show only a value on last occurrence	select    jobno, task,     case when row_number() over (partition by jobno order by starttime desc) = 1         then material         else null end as material,    starttime,    endtime,    operator from    mytable order by jobno, starttime 	0
25726377	6511	ms sql - select only one row for an id	select c.change_id, c.object_id, c.operation  from  (   select max(change_id) as cid   from changelog    group by object_id ) s inner join changelog c on c.change_id = s.cid 	0.000205676544790895
25726380	38484	getting top 10 records from mysql database	select * from mytable order by pkt desc limit 10 	0
25726571	152	how to join a table with two tables by choosing another field value	select  a.id_company, a.id_act, a.type, b.body, p.text, p.answer from activity a  left join blog b on(a.id_act = b.id and a.`type` = 'blog') left join poll p on(a.id_act = p.id and a.`type` = 'poll') where a.id_company in (1, 2) 	0
25726618	35840	get correct audit detail for a particular date	select * from #sales s cross apply (     select top 1 cs.stockid         , cs.stock         , isnull(a.validto, getdate()) as validto         , isnull(a.price, cs.price) as price     from #currentstock cs     left join #audittable a on a.stockid = cs.stockid     where s.datesold <= isnull(a.validto, getdate())         and s.stockid = cs.stockid     order by isnull(a.validto, getdate())  ) x 	0.000611141490637197
25727127	10905	mysql querying multiple tables	select a.*  from products as a left join ( select product_id from order_products as b  inner join orders as c on b.order_id = c.order_id where c.date_ordered >= date_sub(c.date_ordered, interval 7 day) group by product_id  ) as d on a.product_id = d.product_id  where d.product_id is null 	0.0735958733271716
25727326	29685	data size of result with join, how to optimize?	select count(*) from tbl1 	0.287980538796219
25727529	34496	sql server -adding values between tables	select  projectfinances.pftotal + isnull(otherapplications.ototal, 0) as apptotal from projectfinances left outer join otherapplications on projectfinances.financeid = otherapplications.financeid 	0.0154135211983918
25728326	8325	grouping rows after "super row"	select    s.supplier_id,    s.supplier_aggregate_id,    s.supplier_description  from suppliers s order by    coalesce(s.supplier_aggregate_id, s.supplier_id) asc,    s.supplier_aggregate_id; 	0.00384228672515022
25728735	24734	how to use 'group by' when joining two tables	select       sm.admissionbase,       pctranks.grp,       count(*) as totalpergroup    from         studentmaster sm           join studentqualificationdetails sqd              on sm.registrationnumber = sqd.registrationnumber              join ( select 'less than 50%' as grp, 0 as atleast, 50 as lessthan                     union select '50% - 60%   ', 50, 61                     union select '61% - 70%   ', 61, 70                     union select '71% - 80%   ', 71, 80                     union select '81% - 90%   ', 81, 90                     union select '91% - 100%   ', 91, 101 ) pctranks                 on sqd.markspercent >= pctranks.atleast                 and sqd.markspercent < pctranks.lessthan    where        sm.admissionbase = '10+2'    group by       sm.admissionbase,       pctranks.grp 	0.0480975203048353
25729064	6314	sql view flatten data into rows	select a, null as b, null as c, null as d, '1/1/2014' from table union select null as a, b, null as c, null as d, '2/1/2014' from table union select null as a, null as b, c, null as d, '3/1/2014' from table union select null as a, null as b, null as c, d, '4/1/2014' from table 	0.00872173584332878
25729645	31036	how can i parse a varchar string into three columns, year, month and day	select datepart(day, '31dec2013') select datepart(month, '31dec2013') select datepart(year, '31dec2013') 	0
25730267	21569	sql query compare and sum	select t."invoice no", t."line no_", t."invoice total",          calctotals.linenum as calcsum, case when t."invoice total" = calctotals.linenum then 'matched' else 'not matched' end from [table] t inner join (     select "invoice no" as invoicenumber,         sum("line _no") as linenum     from [table]     group by "invoice no" ) calctotals on t."invoice no" = calctotals.invoicenumber 	0.0795665756907166
25730443	29001	how to get last five items from database using id's	select * from mytable order by article_id desc limit 5 	0
25730709	30803	select rows from sql table where all of a set of parameters exist in joined table	select b.tablea_id from #statuses s left join #tableb b     on b.status_id = s.id group by b.tablea_id having count(distinct s.id) = count(distinct b.status_id) 	0
25731006	21484	how to change "like '1%'" so that it is efficient for integers?	select top 60 lcode from lessonchart lcode between  power(10,floor(log10(lcode ))) and power(10,floor(log10(lcode )))*2-1 	0.590767279857405
25731777	18927	return \' within a mysql statement	select *, (select count(q1) from results where q1 = 'people\\\'s') as total from results 	0.222965493418434
25732892	29506	table function for each record in a query	select code, name, func.out1, func.out2 from myinnerjoinedtablesresult cross apply dbo.func1(code) as func 	0.000786072346240597
25734194	15100	converting currency in mysql using a join	select o.*, sales_total * (c2.value_usd / c1.value_usd) as converted_total,        c2.currency as converted_currency from `order` o join `currency` c1 on o.currency = c1.currency join `currency` c2 on c2.currency = 'eur' 	0.749417464321985
25737480	37827	joining tables to find absent values in a column	select p.idx  from properties as p  where not exists (     select 1      from comments as c      where p.idx = c.lotindex and c."name" = 'auto'); 	0.000129908116489941
25737504	3318	sq lite get sub string of column based on index	select cast(substr(a, instr(a, '_') + 1) as integer) from a; 	0.00117896988597772
25737520	36072	ranking results based on relevancy in mysql	select   id, name  from     tbl  where    name like 'h%' or name like '% h%' order by (name like 'h%') desc 	0.0131218083642221
25739192	17943	how to query from mysql datetime column based on day name	select * from tablename where `date` > current_date - interval 7 day 	0
25740149	18544	get name of mysql table in which the record exist	select * from (   select 'expense', * from expense   union   select 'administrative expense', * from administrative_expense   union ) all where expenseid = ?  	0
25740603	31963	use one table to order another	select test.* from (     select source.name, source.id, newsitem.uploadedat      from northern_light.source      inner join northern_light.source_newsitem      on source.id = source_newsitem.sourceid      inner join northern_light.newsitem     on source_newsitem.newsitemid = newsitem.newsitemid     where source.name like '%%'     order by newsitem.uploadedat desc     limit 0, 100 ) as test group by source.id; 	0.00474369120826985
25742565	6429	sql select query based on a column value	select applicableto,        idapplicable,        case           when applicableto = 'dept' then (select name from tbldept where tbldept.id = idapplicable)           when applicableto = 'grade' then (select name from tblgrade where tblgrade.id = idapplicable)          when applicableto = 'section' then (select name from tblsection where tblsection.id = idapplicable)          when applicableto = 'designation' then (select name from tbldesignation where tbldesignation.id = idapplicable)        end as 'name' from table1 	0.000414106798268822
25744080	31190	sql join tablese multiple times on different columns	select    e.id   ,p1.name drivername   ,p2.name translatorname    from `events` e   join `personal` p1     on p1.id=e.driver   join `personal` p2     on p2.id=e.translator 	0.00158452773769218
25744117	22634	sql sum with condition field='x'	select id_person,sum(b.grade) from      (         select id_person,max(id_test) testid  from test         group by id_person     )a inner join grade as b on a.testid = b.id_test group by id_person 	0.797029289407266
25746457	9055	sql sum a column and also return the last time stamp	select name,        sum(distance) as distance,        max(create_date) as create_date from   table where  create_date >= '20140801' and create_date < '20140925' group by name 	0
25747747	35474	mysql using `in` while having multiple values	select sum(couponscount) as count,restaurant from `coupons` where `restaurant` in     (select `storename`      from `stores`      where `status`='active'                   and       ((acos(sin(-27.561264299999998 * pi()/180) * sin(latitude * pi()/180) + cos(-27.561264299999998 * pi()/180) * cos(latitude * pi()/180) * cos((153.07304890000003 – longitude) * pi()/180)) *180 / pi()) *60 * 1.1515) <=20) group by restaurant 	0.121249634525607
25748608	37295	how to create a new column from existing column?	select a.*,        (case when cnt_trips_1yr > 3 then 1 else 0 end) as iscntgt3,        (case when cnt_trips_1yr > 2 then 1 else 0 end) as iscntgt2 from (select a.lyl_id_no,              sum(a.trn_tot_prc) as purch,              sum(case when a.trn_dt > current_date - 365 then 1 else 0 end) as cnt_trips_1yr       from abc a       group by a.lyl_id_no      ) a; 	0.000192996290195814
25749237	35492	select max from several columns	select  [detail info, no need to max or group by] from pat_spell as ips left join patient pat       with (nolock) on pat.dim_patient_id = ips.dim_patient_id left join specialty spec    with (nolock) on spec.dim_specialty_id = ips.dim_dis_spect_id left join service_unit dssu with (nolock) on ips.dim_dis_ward_id = dssu.dim_ssu_id inner join (     select patientid, max(ips.disch_dttm) as dischargedt     from [allmytables]     where (ips.disch_dttm <= pat.death_dttm + 30)     and ips.dim_dis_spect_id = '7195'     and ips.disch_dttm between '01/01/2014' and '30/06/2014' ) t1 on pat.patientid = t1.patientid and ips.disch_dttm = t1.dischargedt order by pat.pas_id 	0.000757656105857379
25749553	4072	order by not working on joined and grouped mysql tables	select u.user_name, c.conversation_id, m.sender_user_id, m.message  from conversations c  join messages m on c.conversation_id=m.conversation_id  join users u on u.user_id=m.sender_user_id join (select max(message_id) message_id ,conversation_id      from messages        group by conversation_id      ) m1 on(m.message_id= m1.message_id and m.conversation_id = m1.conversation_id)  where .....  order by m.message_id desc 	0.146573047006039
25751342	23093	joining two or more views in mysql	select view1.company_id, view1.company_name, view1.counta,view2.countb from view1 inner join view2 on view1.company_id = view2.company_id 	0.0839398431075174
25751877	25275	android sqlite when data are not exist	select users.*, comments.* from users left outer join comments where comments.users_id = user._id 	0.417113311648985
25752028	18199	query to see how many times employees has worked same shifts	select a.userid, b.userid, count(a.shiftid) as common_shifts from working as a inner join working as b on ((a.shiftid = b.shiftid) and (a.userid <> b.userid)) having common_shifts > 0 	4.66011338911234e-05
25752725	21962	only show multiple instances	select projectname, siteid, paperid, memberfirstname, memberlastname, memberdob, memberid from (     select      p.projectname,     s.siteid,     c.paperid,     m.memberfirstname,     m.memberlastname,     m.memberdob,     m.memberid,     count(1) over ( partition by m.memberid ) as cnt     from sites s, papers c, members m, projects p     where s.siteid=c.siteid     and c.memberid=m.memberid     and s.projectid=p.projectid     ) a where cnt > 1 order by projectname, memberfirstname, memberlastname 	0.000533389761600958
25754471	28168	get online users and offline users in a single query instead of two seperate queries?	select  id,          case           when last_activity + 300 > now() then 1           else 0          end as is_online from users 	0
25755887	1451	two rows of data combined into one	select invoice.reference, min(invoice.statuscode) as statuscode, min(invoice.statusdate) as statusdate, max(invoice.statusdate) as statusdate2 from invoice group by invoice.reference; 	0
25756796	26243	how get data in split string data for sql server	select * from [table] where ','+[data]+',' like '%,e55555,%' 	0.00110976691364544
25757285	29622	how to get sum() of count() column in mysql	select inst_id, inst_username, city_name,      sum(pms_student_bucket_id is null ) as not_assiged,     sum(num_bucket >=10 and num_bucket <= 20) as '10 - 20'     sum(num_bucket <= 50) as '1-50',     sum(num_bucket > 50) as ' > 50' from (   select t.inst_id, t.inst_username, tcm.city_name,psb.pms_student_bucket_id,              count(psb.pms_student_bucket_id) as num_bucket     from tbl_si_di t     join tbl_city_master tcm on tcm.city_id = t.city_ref_id     join tbl_si_students tss on tss.inst_ref_id = t.inst_id     left join pms_student_bucket psb on psb.user_ref_id = tss.user_ref_id     group by t.inst_id )t1 group by inst_id; 	0.000504034974406189
25757772	22152	finding the current status of each phone number in postgresql	select *  from   (   select p.record_id, p.responsecode, p.id, max(p.id) over (partition by p.record_id) max_id   from "provisioning" p   )  where id = max_id 	0
25758604	21700	grails: how to identify the primary key of a domain?	select column_name from information_schema.key_column_usage where table_schema = 'public'    and table_name = 'article'  order by ordinal_position  	0.000983810519200304
25759490	19932	sql: find different accounts in asset list	select b.amainnr,        b.asubnr,        b.account from atable b where b.amainnr in     (select a.amainnr      from atable a      group by a.amainnr having count(distinct(a.account)) > 1) 	0.00115881092591068
25760608	35315	handling null value in oracle table query	select master_drawing.*,    nvl((select prepacking_list.packing_status       from prepacking_list       where master_drawing.head_mark = prepacking_list.head_mark),'n/a'    ) status  from master_drawing where project_name = :projname 	0.517511026686114
25761601	38781	sqlite, convert values 1 and 0 to values read and not read	select case when origin = 1              then 'read'             else 'not read'        end as origin from your_table 	0.10755250636491
25762096	9606	sql query return one of each	select first_name, last_name, picture, last_active, id_participante1, id_participante2, id_user, [message], datahora ( select distinct first_name, last_name, picture, last_active, id_participante1, id_participante2, id_user, [message], datahora , row_number (partition by <add_yr_colist> order by last_avtive desc) as rnum  from chat_b_users inner join utilizadores on chat_b_users.id_participante2 = utilizadores.id_user left join chat_talks on chat_b_users.id_chat = chat_talks.id_chat where id_participante1 = 1 or id_participante2 = 1 )tvc where rnum = 1 	0.000155406880554604
25763250	36271	adding up the numeric parts of a matched string in sql	select name, sum(quantity) from @tablevar group by name 	0.00291674452566838
25763379	34141	mysql: retrieve data from multiple tables	select portfolio.*,client.name as "client name",provider.name as "provider name" from portfolio inner join client on portfolio.client_id=client.id inner join provider on client.provider_id = provider.id 	0.000333364876555376
25765253	6879	sum days by period with sql- oracle	select person_id,  sum(case        when         date_start >= to_date('01/05/2014','dd/mm/yyyy')         and date_end <= to_date('31/07/2014', 'dd/mm/yyyy')        then (date_end - date_start)       when        to_date('01/05/2014','dd/mm/yyyy') > date_start         and to_date('31/07/2014', 'dd/mm/yyyy') < date_end       then (to_date('31/07/2014','dd/mm/yyyy') - to_date('01/05/2014','dd/mm/yyyy'))        when        to_date('01/05/2014','dd/mm/yyyy') < date_start         and to_date('31/07/2014', 'dd/mm/yyyy') < date_end       then (to_date('31/07/2014','dd/mm/yyyy') - date_start)         when        to_date('01/05/2014','dd/mm/yyyy') > date_start         and to_date('31/07/2014', 'dd/mm/yyyy') > date_end       then (date_end - to_date('01/05/2014','dd/mm/yyyy'))         else 0     end) as days from table_name  group by person_id 	0.00316199989421325
25765945	34696	mysql select with limit 1 when using a join with 2 tables	select  a.itemname,   (select itemimagename     from amgb b     where a.userid = b.userid and a.itemid = b.itemid     limit 1   ) as itemimagename from amga a  where a.userid = 1 and a.itemid = 'us1'; 	0.167601322920772
25769901	2020	get count and sum for each ip from mysql table	select s.ip, s.name, sum(s.minutes) as totalminutes, count(s.name) as namecount from ip_stats s group by s.ip, s.name 	0
25770249	19158	how to select rows from a table where a word appears? (mysql + php)	select * from mutable where dvdtitle like '%keyword%' or description like '%keyword%'; 	6.89868982101106e-05
25770459	36207	compare row name with one cell in sql	select distinct      b.id, b.id_date,      menu =         case s.menu_number             when 'menu1' then b.menu1             when 'menu2' then b.menu2             when 'menu3' then b.menu3             else 'unknown'         end,     s.date from      ordering b     join menu_plan s on b.id_date = s.date  where      b.number = '4000859' 	7.5155391766308e-05
25772508	14893	sql server 2008 split 1 column into 3 (shipping dimensions)	select     left(dim, charindex('" l', dim)-1) as [length] ,   substring(dim, charindex('" l', dim)+6, charindex('" w', dim)-charindex('" l x ', dim) - 6) as [width] ,   substring(dim, charindex('" w', dim)+6, charindex('" h', dim)-charindex('" w x ', dim) - 6) as [height] from test 	0.00511073471659481
25773800	7897	substracting two timestamps(0) in teradata	select ticket_ttr_start_dtt - ticket_ttr_stop_dtt hour(4) to second(0) 	0.145131774047673
25773965	24567	similar queries to create third column in mysql using join	select          p.empnumber,         p.empfirstname as empfirstname1,               t.empfirstname as empfirstname2     from htg_techprops p      left join htg_techstaffsets s on p.empnumber=s.empnumber     left join htg_techprops t on t.empnumber=s.staffsetid union all select      p.empnumber,     p.empfirstname as empfirstname1,           t.empfirstname as empfirstname2 from htg_techprops p  left join htg_techstaffsets s on p.empnumber=s.staffsetid left join htg_techprops t on t.empnumber=s.empnumber order by p.empnumber 	0.103511464812887
25776002	21576	how do i get 10 customers that are tied to 4 agents?	select  a.email       , c.email  from agent a        cross apply (                     select top 10 pros.email                      from agentprospects as ap                     inner join prospects pros on ap.prospectid = pros.prospectid                     where ap.agentid = a.agentid                     ) c(email) where a.isdeleted = 0    and a.agentid in (1,2)    	0
25776684	27606	mysql show grouped results	select stamp,         substr(`values`,1,instr(`values`,',')-1) as value1,        nullif(trim(',' from substr(`values`,instr(`values`,',')+1)),'') as value2,        `values` from ( select stamp, `group`,concat( group_concat(`value`) ,',') as `values` from stamps group by stamp, `group` ) aggr 	0.00913438479349203
25778247	25894	count() function and select with distinct on multiple columns	select count (*) as 'distinct' from (     select distinct p.idd, p.num     from perf1 p     inner join mast1 m     on (m.id_table = p.id_table and m.source_table = p.source_table)     where m.date > '2012-12-31' ) temptable 	0.017860702933248
25778694	40404	how to get data from date and time range in mysql	select id from (   select id from <tablename>      where date('<datetimevalue>') between date(from_datetime) and date(to_datetime)      and time('<datetimevalue>') between time(from_datetime) and time(to_datetime)   union     select 0 as id from dual ) as a limit 1 	0
25780430	3440	report all roles that have some permission but not another	select  roleid  from    @test a  where   a.permissionid in (1,2)  and     roleid not in (select roleid from @test where permissionid in (3,4) group by roleid) group   by roleid 	0.000421112547734775
25784822	3747	how to select row which a certain text format?	select * from product_db where key regexp '^product[0-9]+$'; 	6.60702580666109e-05
25786900	21080	how to filter a database table	select distinct subcase_id from your_table  where subcase_id not in (select subcase_id from your_table where activity='closed') 	0.0180897900151174
25787141	13186	returning grouped groups in mysql query	select name, word, magnitude  from(     select name, word, magnitude, if(@a = name, @b := @b + 1, @b := 1) counting, @a := name     from(         select name, word, count(*) as magnitude          from tbl_words          group by name, word         order by name, magnitude desc     ) t     cross join(select @a := '', @b := 0)temp )t1 where counting <=3 	0.0506877251513415
25787846	41132	postgresql select query 'join multiple rows to one row'	select m.id, m.id2, m.id3, m.year,   sum(case when m.code = 'radio' then m.value end) as radio,   sum(case when m.code = 'tv' then m.value end) as tv,   sum(case when m.code = 'cable' then m.value end) as cable,   sum(case when m.code = 'dine' then m.value end) as dine from mytable m group by m.id, m.id2, m.id3, m.year 	0.0013017485383551
25788217	37001	select count/sum and true/false bit-flag at the same time	select item, sum(rated) as no_rated, sum(bought) as no_bought,         max(user = 1 and rated = 1) as rated_by_1,         max(user = 2 and rated = 1) as rated_by_2,         max(user = 1 and bought = 1) as bought_by_1,         max(user = 2 and bought = 2) as bought_by_2 from yourtable group by item 	0.000945999490368029
25788555	15851	ignoring duplicated primary keys when exporting data from one database to another in sql	select id, systemdatetime, etc.. from (   select *,row_number() over(partition by id order by systemdatetime) row   from [action]    where systemdatetime < getdate()      and systemdatetime > dateadd(month, -3, getdate()) ) tmp where row = 1 	0
25789188	80	complicate select in t-sql	select case when coltot > imp2014          then imp2014     else coltot end as st2014, case when (((coltot - imp2014) > imp2013) and (coltot > imp2014))         then imp2013     when coltot > imp2014         then coltot - imp2014     else null end as st2013, case (((coltot - imp2014 - imp2013) > imp2012) and (coltot > imp2014 + imp2013))         then imp2012     when (((coltot - imp2014) > imp2013) and (coltot > imp2014))         then coltot - imp2014 - imp2013     else null end as st2012, coltot, imp2014, imp2013, imp2012 	0.702823425820732
25789273	32382	query and list admin levels - join two tables	select u.uname from user u join      groups g      on u.gid = g.gid where g.level >= (select g2.level                   from user u2 join                        groups g2                        on u2.gid = g2.gid                   where u2.uname = 'jacky'                  ); 	0.0441340403051412
25791917	3358	calculate difference between two rows of the same type	select curr.vmnaam,        curr.memsize,        curr.totalstorage from   vmresourcetest curr left join           vmresourcetest nxt on curr.id < nxt.id                      and curr.vmnaam = curr.vmnaam                     and (curr.memsize != nxt.memsize                             or curr.totalstorage != nxt.totalstorage) and not exists (           select *           from vmresourcetest            where id > curr.id and id < nxt.id and vmnaam = curr.vmnaam) 	0
25792007	8356	return the list of points inside a rectangle	select point.lat, point.long from point where rect1.lat <= point.lat and point.lat <= rect2.lat and rect1.long <= point.long and point.long <= rect2.long 	0.00520968129327386
25799149	40585	how to choose execute from 2 queries depending of the result of a previous query in sqlite	select id_asiento as id from asientos_diario where (select count(id_asiento) from asientos_diario where id_paquete = 1) > 0  union all select id_cta as id from cuentasxpaq where (select count(id_asiento) from asientos_diario where id_paquete = 1) = 0 	0
25799676	18008	mysql cross join without duplicates	select table1.name,table1.address,table1.type from table1 union select table2.name,table2.address,table2.type, from table2 	0.72247968079591
25800645	29254	get previous record by group sql	select a.id     ,a.groupid     ,a.odate     ,a.otime     ,a.ovalue     ,(         select top 1 b.ovalue         from table1 b         where b.groupid = a.groupid             and b.id < a.id         order by id desc         ) as prev_ovalue     ,a.ovalue - (         select top 1 b.ovalue         from table1 b         where b.groupid = a.groupid             and b.id < a.id         order by id desc         ) as oresult from table1 a order by a.groupid     ,a.odate     ,a.otime 	0.000663502627223884
25804790	402	sql queries from multiple tables	select majortitle, username from student s join major m on s.majorcode = m.majorcode 	0.0255641368248877
25804817	27479	lookup positive and negative totals	select client_number , 'recon' from yrtablename  group by client_number having sum(balance) = 0 	0.010748494901502
25805893	34234	sql join in one row in a query	select a.username, group_concat(b.productname) from commands a inner join products b on a.id1 = b.id1 group by a.username 	0.0297270222773968
25806277	2086	how do i count values i've replaced in a select query?	select * from `xcart_orders` inner join (      select replace(upper(s_zipcode), ' ', '') as zip      from `xcart_orders`     group by replace(upper(s_zipcode), ' ', '')     having count(replace(upper(s_zipcode), ' ', '')) > 1 ) xxx on (replace(upper(s_zipcode), ' ', '') = xxx.zip) 	0.0378070141545252
25808600	21774	customize query of postgresql	select     date_trunc('day', minute) as day,     sum(minute_sum) as day_sum,     max(minute_sum) as max_minute_sum from (     select         minute,         coalesce(sum("dummy"),0) as minute_sum     from         generate_series(             '2014-09-06'::timestamp,             '2014-09-13'::timestamp - interval '1 minute',             '1 minute'         ) minutes(minute)         left join         report on             minutes.minute = date_trunc('minute', report.fetchdate)             and entity_id ='0'     group by minute ) s group by 1 order by 1 	0.411735820301866
25810183	25792	lookup table with best match query	select phonenumber,        (select country_id          from phonenumber_prefix pp         where pn.phonenumber like prefix ||'%'          order by length(calling_prefix) desc          limit 1        ) as country_id from phonenumbers pn; 	0.101109247964437
25810201	3252	mysql combine view of two table having different number of entry records in date range	select * from   (select sale.date as date, sale.description as saledescription, "" as   expensedescription, sale.amount as saleamount, "" as expenseamount    from sale    where sale.date >= '2014-09-01'    union all    select expense.date as date, "" as saledescription, expense.description as expensedescription, "" as saleamount, expense.amount as expenseamount    from expense    where expense.date >= '2014-09-01') as saleexpense order by   saleexpense.date asc 	0
25811755	10952	tsql 2 queries in 1	select  v_incident.reporteddate         , count(*) as basecount         , sum(case when v_incidentmaxworklog_category.work_log_type in ('general information', 'incident task / action', 'working log') then 1 else 0 end) as worklogfilteredcount from    v_incident         inner join v_incidentmaxworklog_category             on v_incident.incidentid = v_incidentmaxworklog_category.incident_number where   (v_incident.summary like n'intelligent incident for impacted ci%')         and (v_incident.customerfirstname = n'bmc')         and (v_incident.customerlastname = n'impact manager')         and (v_incident.reporteddate >= '7/1/2014')         and (v_incident.reporteddate >= dateadd(year, - 1, getdate())) group by v_incident.reporteddate from v_incident 	0.100379302021358
25813202	38300	sql query to pivot table on column value	select    max(case when teamid = 1 then playername else '' end) team1,   max(case when teamid = 2 then playername else '' end) team2 from (   select teamid,     playername,     (select count(*)      from yourtable d      where t.teamid = d.teamid        and t.playername <= d.playername) rn   from yourtable t ) d group by rn; 	0.0149392366908988
25815740	37779	php/mysql - friends list sql query	select u.emailaddress, u.gender, u.dob, u.location from user u left join friends f on u.userid = f.friend_id where f.user_id = 1; 	0.0256124800759833
25818174	30900	sql - info from multiple tables with two variants of the same field.	select d3.value, d4.value, u.user_email from wp_users u join      wp_cimy_uef_data d3      on u.id = d3.user_id and d3.field_id = 3 join      wp_cimy_uef_data d4      on u.id = d4.user_id and d4.field_id = 4; 	0
25819758	17283	how to convert 'september 2014' to '2014-09-01' in mysql	select str_to_date(concat('september 2013',',1'),'%m %y,%d'); 	0.659804298566527
25820768	25418	sql server: use different date format in select when selected date equals current date	select       case when g.modtime >= dateadd(day, datediff(day,0, getdate() ), 0)                 then ('today at ' + convert(varchar(5), g.modtime, 108))             else                 convert(varchar(11), g.modtime, 106)       end  as modtime from g 	0
25823935	13485	how to get the correct sql value on php	select * from a where studentid  not in (select studentid from b where 1=1) 	0.0031592679542965
25824813	18306	t-sql query to select rows with same values of several columns (azure sql database)	select t.* from (select t.*, count(*) over (partition by street, building) as cnt       from table t      ) t where cnt > 1; 	0
25827387	19289	mysql - select userid from table if it appears in multiple rows	select userid from users where exists     (select 1      from attributes      where users.userid = attributes.userid        and attributetype = 'skill'        and attributename in ('python',                              'mysql'))   and exists     (select 1      from attributes      where users.userid = attributes.userid        and attributetype = 'location'        and attributename = 'london') 	0.000256729118491038
25827985	9483	sqlite except on a single column	select * from table where condition1 and somecolumn not in (select somecolumn                        from table                        where condition2) 	0.00623532720210636
