Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I want to split a string in this format Quote: ``` "date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8" ``` . Actually this string is only a sample one my original string is very large . i am not getting a point that if i break this string than how many variables i have to make to capture the data also after splitting the string i want that to be inserted into data table containing columns as date and age? What concept do i use?(I am getting this string from a web service) Thanks in advance..
In general, I'd suggest to write a CLR function which split strings by regex or SQL table-valued function, but in you case you can try something simple like converting your string to xml and parsing it: ``` declare @str nvarchar(max) = 'date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8' declare @data xml select @str = replace(@str, '=', '="') select @str = replace(@str, '|', '" ') select @str = replace(@str, '^', '"/><row ') select @str = '<row ' + @str + '"/>' select @data = cast(@str as xml) select t.c.value('@date', 'nvarchar(max)') as [date], t.c.value('@age', 'nvarchar(max)') as [age] from @data.nodes('row') as t(c) ``` [**`sql fiddle demo`**](http://sqlfiddle.com/#!3/d41d8/19337)
try this: ``` Declare @stringToSplit varchar(max)='date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8^date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8^date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8^date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8' DECLARE @YourTable table (RowID int, Layout varchar(max)) INSERT @YourTable VALUES (1,@stringToSplit) ;WITH SplitSting AS ( SELECT RowID,LEFT(Layout,CHARINDEX('^',Layout)-1) AS Part ,RIGHT(Layout,LEN(Layout)-CHARINDEX('^',Layout)) AS Remainder FROM @YourTable WHERE Layout IS NOT NULL AND CHARINDEX('^',Layout)>0 UNION ALL SELECT RowID,LEFT(Remainder,CHARINDEX('^',Remainder)-1) ,RIGHT(Remainder,LEN(Remainder)-CHARINDEX('^',Remainder)) FROM SplitSting WHERE Remainder IS NOT NULL AND CHARINDEX('^',Remainder)>0 UNION ALL SELECT RowID,Remainder,null FROM SplitSting WHERE Remainder IS NOT NULL AND CHARINDEX('^',Remainder)=0 ) select SUBSTRING(part,CHARINDEX('=',part)+1,(CHARINDEX('|',part)-CHARINDEX('=',part))-1) as [Date],RIGHT(part,CHARINDEX('=',reverse(part))-1) as [Age] from SplitSting ```
How to split a string in sql server 2008 using stored procedure and insert the data to table
[ "", "sql", "sql-server", "string", "sql-server-2008", "sqlxml", "" ]
I'm developing an appointment calendar application. Still newbie here. I need help in this area. I need to have a double looping in columns (`calendarID, Slot, AppointmentDate'). The 'slot' column will have a value of 1,2,3,4,5,6,7,8 upto 28 repeatedly while the calendarID will continuously loop to 868 value. The Appointment date will have the value from 1 Aug2013 to 31 Aug 2013 (actually I'm planning to do this for 1 whole year) expected result ``` calendarID | Slot | AppointmentDate ---------------------------------------------- 1 | 1 | 1 Aug 2013 2 | 2 | 1 Aug 2013 3 | 3 | 1 Aug 2013 4 | 4 | 1 Aug 2013 5 | 5 | 1 Aug 2013 6 | 6 | 1 Aug 2013 7 | 7 | 1 Aug 2013 8 |..until 28 | 1 Aug 2013 9 | 1 | 2 Aug 2013 10 | 2 | 2 Aug 2013 11 | 3 | 2 Aug 2013 ...until 868 | n | n Month 2013 ``` Here is my code that I try seems I'm very far from my desired output. I edited the code provided by Astrand ``` DECLARE @tblCalendar TABLE(CalendarEntryID INT, Slot INT, ADate Varchar(50)) DECLARE @x int, @y int , @d INT SET @X = 1 SET @y = 1 SET @d = 1 WHILE @X <= 868 BEGIN WHILE @Y <=28 AND @d <=31 AND @X <= 868 --LOOP FOR SLOT COLUMN BEGIN INSERT INTO @tblCalendar (CalendarEntryID,Slot, ADate) Values (@x, @y,@d +'/Aug/2013') SET @y = @y + 1 SET @x = @x + 1 SET @d = @d + 1 END SET @y = 1 END SELECT * FROM @tblCalendar ``` sorry for the trouble of asking and editing my original post.
Here is the answer to my post, just in case in the future someone like me will have the same question. ``` DECLARE @x int, @y int, @d date, @i date, @status Nvarchar(50) SET @X = 1 SET @y = 1 SET @d = DATEADD (dd, 1 , '31/Jul/2013') -- '2013/07/01' --default date to August SET @status = 'Available' WHILE @X <= 868 BEGIN WHILE @Y <=28 AND @X <= 868--LOOP FOR SLOT COLUMN BEGIN INSERT INTO tblCalendar (CalendarEntryID,Slot,Date,Status) Values (@x, @y,@d,@status) SET @x = @x + 1 SET @y = @y + 1 SET @i = @d END SET @d = DATEADD (dd, 1 , @i) -- THIS WILL INCREMENT THE DATE ACCORDING TO SLOT SET @y = 1 END SELECT * FROM tblCalendar ```
OK, this will get you the desired result, but it is questionable. I will try and improve it a bit after that. ``` DECLARE @tblCalendar TABLE( CalendarEntryID INT, Slot INT ) DECLARE @x int, @y int SET @X = 1 SET @y = 1 WHILE @X <= 100 BEGIN WHILE @Y <=8 AND @X <= 100--LOOP FOR SLOT COLUMN BEGIN INSERT INTO @tblCalendar (CalendarEntryID,Slot) Values (@x, @y) SET @y = @y + 1 SET @x = @x + 1 end SET @y = 1 END SELECT * FROM @tblCalendar ``` Another approach would be to make use of an [IDENTITY COLUMN](http://technet.microsoft.com/en-us/library/ms186775.aspx) Something like ``` DECLARE @tblCalendar TABLE( CalendarEntryID INT IDENTITY(1,1), Slot INT ) DECLARE @x int, @y int SET @X = 1 SET @y = 1 WHILE @X <= 100 BEGIN WHILE @Y <=8 AND @X <= 100--LOOP FOR SLOT COLUMN BEGIN INSERT INTO @tblCalendar (Slot) Values (@y) SET @y = @y + 1 SET @x = @x + 1 end SET @y = 1 END SELECT * FROM @tblCalendar ``` But personally I would have gone for ``` DECLARE @Max INT = 100, @MaxGroup INT = 8 ;WITH Val AS ( SELECT 1 CalendarEntryID UNION ALL SELECT CalendarEntryID + 1 FROM Val WHERE CalendarEntryID + 1 <= @Max ) SELECT CalendarEntryID, ((CalendarEntryID - 1) % @MaxGroup) + 1 Slot FROM Val OPTION (MAXRECURSION 0) ```
how to have a double while loop in sql server 2008
[ "", "sql", "sql-server-2008", "loops", "while-loop", "" ]
I have two querys. First: ``` SELECT TOP 10 NewsItemTitle , COUNT(1) AS CounterNews FROM [ACTIVITY] WHERE [UserLocation] = 'United States' GROUP BY NewsItemTitle ORDER BY CounterNews DESC ``` returns me this: ``` NewsItemTitle CounterNews Afinan plan para casas con cuota de $180.000 por mes 5 The Exploratoreum's STEM seller 4 Witnesses at Hasan trial describe carnage of Ft. Hood shootings. 2 U.S. returns to FIFA top 20 after two-year absence 2 Sunnyvale: Police shoot and kill man; body of woman found inside house 1 ... ``` and, in addition, I want to add on that query the fields `[NewsItemUrl]` and `[NewsItemPublisher]`: ``` SELECT [NewsItemUrl] , [NewsItemPublisher] FROM [ACTIVITY] ``` So, how can I combine those 2 querys into 1?
Try this one - ``` SELECT TOP 10 NewsItemTitle , [NewsItemUrl] = MAX([NewsItemUrl]) , [NewsItemPublisher] = MAX([NewsItemPublisher]) , COUNT(1) AS CounterNews FROM dbo.[ACTIVITY] WHERE [UserLocation] = 'United States' GROUP BY NewsItemTitle ORDER BY CounterNews DESC ``` Or this - ``` SELECT TOP 10 NewsItemTitle , [NewsItemUrl] , [NewsItemPublisher] , COUNT(1) AS CounterNews FROM dbo.[ACTIVITY] WHERE [UserLocation] = 'United States' GROUP BY NewsItemTitle , [NewsItemUrl] , [NewsItemPublisher] ORDER BY CounterNews DESC ```
If i understand you correctly you want to include two columns which are not part of the `GROUP BY`. That is not allowed normally, you either have to include them in the group by or aggregate them in another way(f.e. `MIN/MAX/COUNT`). But you could use a [ranking function](http://technet.microsoft.com/en-us/library/ms189798.aspx) like `ROW_NUMBER` in a common-table-expression: ``` WITH CTE AS ( SELECT NewsItemTitle, NewsItemUrl, NewsItemPublisher, CounterNews = COUNT(*) OVER (PARTITION BY NewsItemTitle), RN = ROW_NUMBER() OVER (PARTITION BY NewsItemTitle ORDER BY CounterNews DESC) FROM [ACTIVITY] WHERE [UserLocation] = 'United States' ) SELECT TOP 10 * FROM CTE WHERE RN = 1 ``` As you can see the [`OVER`](http://technet.microsoft.com/en-us/library/ms189461.aspx) clause works also on aggregate functions like `COUNT` which allows to count each group without using `GROUP BY`.
How to combine two selects or two querys?
[ "", "sql", "sql-server", "" ]
I need to do one INSERT or another depending if a column exist because of different versions of the same table. I did the approach at [this thread](https://stackoverflow.com/a/5369176/253329) but SQL Server's pre check or 'sort of compilation' detects an error that would not fail during execution time. Here's some code ``` IF COL_LENGTH('TableA', 'Column2') IS NOT NULL BEGIN INSERT INTO [dbo].[TableA]([Column1], [Column2], [Column3], [Column4]) SELECT value1, value2, value3, value4 END ELSE BEGIN INSERT INTO [dbo].[TableA]([Column1], [Column3], [Column4]) SELECT value1, value3, value4 END ``` Any workaround?
SQL will know that the column doesn't exist so it won't let you run the query. The solution would be to execute a dynamic query. ``` DECLARE @value1 AS VARCHAR(50) DECLARE @value2 AS VARCHAR(50) DECLARE @value3 AS VARCHAR(50) DECLARE @value4 AS VARCHAR(50) SET @value1 = 'somevalue1' SET @value2 = 'somevalue2' SET @value3 = 'somevalue3' SET @value4 = 'somevalue4' DECLARE @SQL AS VARCHAR(MAX) IF COL_LENGTH('TableA', 'Column2') IS NOT NULL BEGIN SET @SQL = 'INSERT INTO [dbo].[TableA]([Column1], [Column2], [Column3], [Column4]) SELECT ' + @value1 + ', ' + @value2 + ', ' + @value3 + ', ' + @value4 END ELSE BEGIN SET @SQL = 'INSERT INTO [dbo].[TableA]([Column1], [Column3], [Column4]) SELECT ' + @value1 + ', ' + @value3 + ', ' + @value4 END EXEC(@SQL) ```
Rather than approaching this dynamically, I would create stored procedures with a common signature, and add the appropraiate version to your various versions of the database eg: ``` create proc TableAInsert ( @col1 int, @col2 int, @col3 int, @col4 int ) ``` In this fashion, you create an `interface` definition for your database. If your database changes again, you can create a new version of this procedure with an optional parameter with a default value, and carry on calling it in the same manner as before.
SQL Insert depending if a column exists
[ "", "sql", "sql-server", "" ]
I'm trying to get the mode of a certain list of variables. When the mode is not unique, I want to return the average of the mode so that a subquery to get the mode (in a larger query) doesn't return two values. However, when the mode is unique, the average query returns a missing value for some reason. I have the following sample data: ``` data have; input betprice; datalines; 1.05 1.05 1.05 6 run; PROC PRINT; RUN; proc sql; select avg(betprice) from (select betprice, count(*) as count_betprice from have group by betprice) having count_betprice = max(count_betprice); quit; ``` If I add a few more observations to the betprice field so that the mode is not unique, I DO get returned the average value. ``` data have; input betprice; datalines; 1.05 1.05 1.05 6 6 6 run; PROC PRINT; RUN; ``` How can I change this query so that I'm always returned either the mode or the average of the two most frequent values. Thanks for any help on this.
This was pretty hard, after 12 years working with SAS, I can't remember I've been/seen using HAVING without GROUP BY, I guess it produces unexpected results. So for a single query my solution is not very nice since it does the grouping twice. A single query version: ``` proc sql; select avg(betprice) from ( select betprice , count(*) as count_betprice from work.have group by betprice) /* first summary */ where count_betprice = select max(count_betprice) from (select betprice , count(*) as count_betprice from work.have group by betprice) /* same summary here */; quit; ``` A bit of simplification using an intermediate table (or view if you need) instead of same subquery: ``` proc sql; create table work.freq_sum as select betprice , count(*) as count_betprice from work.have group by betprice ; select avg(betprice) from work.freq_sum where count_betprice = select max(count_betprice) from work.freq_sum; quit; ``` Pls, note you can calculate statistics like MODE and MEDIAN by PROC MEANS: ``` proc means data=have n mean mode median; var betprice; run; ```
You're in SAS, why not let SAS calculate the statistic, since that's sort of what it's good at... ``` ods output modes=want; proc univariate data=have modes; var betprice; run; ods output close; proc means data=want; var mode; output out=final(keep=betprice) mean=betprice; run; ``` This won't take terribly long, is much clearer to another programmer what you're doing, and is very easy to code. If you weren't taking the mean of the modes, you could do it in one step.
SAS: AVG() of a single observation
[ "", "sql", "sas", "" ]
Consider the following little script: ``` create table #test (testId int identity ,testColumn varchar(50) ) go create table #testJunction (testId int ,otherId int ) insert into #test select 'test data' insert into #testJunction(testId,otherId) select SCOPE_IDENTITY(),(select top 10 OtherId from OtherTable) --The second query here signifies some business logic to resolve a many-to-many --fails ``` This, however, will work: ``` insert into #test select 'test data' insert into #testJunction(otherId,testId) select top 10 OtherId ,(select SCOPE_IDENTITY()) from OtherTable --insert order of columns is switched in #testJunction --SCOPE_IDENTITY() repeated for each OtherId ``` The second solution works and all is well. I know it doesn't matter, but for continuity's sake I like having the insert done in the order in which the columns are present in the database table. How can I acheieve that? The following attempt gives a `subquery returned more than 1 value` error ``` insert into #test select 'test data' insert into #testJunction(otherId,testId) values ((select SCOPE_IDENTITY()),(select top 10 drugId from Drugs)) ``` EDIT: On a webpage a new row is entered into a table with a structure like ``` QuizId,StudentId,DateTaken (QuizId is an identity column) ``` I have another table with Quiz Questions like ``` QuestionId,Question,CorrectAnswer ``` Any number of quizzes can have any number of questions, so in this example `testJunction` resolves that many to many. Ergo, I need the SCOPE\_IDENTITY repeated for however many questions are on the quiz.
The version that fails ``` insert into #testJunction(testId,otherId) select SCOPE_IDENTITY(),(select top 10 OtherId from OtherTable) ``` will insert one row with `scope_identity()` in the first column and a set of 10 values in the second column. A column can not have sets so that one fails. The one that works ``` insert into #testJunction(otherId,testId) select top 10 OtherId ,(select SCOPE_IDENTITY()) from OtherTable ``` will insert 10 rows from `OtherTable` with `OtherId` in the first column and the scalar value of `scope_identity()` in the second column. If you need to switch places of the columns it would look like this instead. ``` insert into #testJunction(testId,otherId) select top 10 SCOPE_IDENTITY(), OtherId from OtherTable ```
You need the output clause. Look it up in BOL.
Inserting SCOPE_IDENTITY() into a junction table
[ "", "sql", "sql-server", "" ]
Is there a way to tell MySQL that while making something like this ``` SELECT id, MAX(seq) FROM t1 GROUP BY ident; ``` I can also get the id value? I know I shouldn't be using `id` if it's not in a group by but I feel like its strange to make a multi pass to get the row ids with the maximum seq field when it already passed it. So what is the most effective way to do this? `id` is the primary key
Mabye: ``` 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; ``` [Fiddle](http://sqlfiddle.com/#!9/5ba5e/1)
``` SELECT a.* FROM tableName INNER JOIN ( SELECT ident, MAX(seq) seq FROM tableName GROUP BY ident ) b ON a.ident = b.ident AND a.seq = b.seq ```
Selecting maximum column and row id
[ "", "mysql", "sql", "group-by", "max", "greatest-n-per-group", "" ]
Table: ``` CREATE TABLE logaction ( actype varchar(8) not null, actime DATETIME not null, devid int not null ); ``` SQL: ``` insert into logaction values ('TEST', '2013-08-22', 1); insert into logaction values ('TEST', '2013-08-22 09:45:30', 1); insert into logaction values ('TEST', 'xyz', 2); // shouldn't this fail? ``` The last record does make it into the table regardless of the non-datetime value for the actime column. Why and how can I enforce that only good data go in? Here is a [SQL Fiddle](http://sqlfiddle.com/#!7/b0c73/3).
Well, there's just no DATETIME type in Sqlite... > SQLite does not have a storage class set aside for storing dates > and/or times. Instead, the built-in Date And Time Functions of SQLite > are capable of storing dates and times as TEXT, REAL, or INTEGER > values: > > ``` > TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). > REAL as Julian day numbers, the number of days since noon in Greenwich > on November 24, 4714 B.C. according to the proleptic Gregorian calendar. > INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC. > ``` > > Applications can chose to store dates and times in any of these > formats and freely convert between formats using the built-in date and > time functions. see [doc](http://www.sqlite.org/datatype3.html) You could have created your table like that, it wouldn't have changed anything. ``` CREATE TABLE logaction ( actype varchar(8) not null, actime NonexistingType not null, devid int not null ); ```
Unfortunately, not really in sqlite - it doesn't have a datetime type - see section 1.2 in [here](http://www.sqlite.org/datatype3.html)
SQLite allows insert of string data into datetime column
[ "", "sql", "sqlite", "" ]
I am trying to figure out 1 query for a long time. I am new to mysql and query statements. I have below 2 queries which I would like to pass into 1 statement so that i can get the desired output. part 1 ``` select custid, fname from customertbl where createdate < 01-01-2011 ``` part 2 ``` select custid, orddate from ordertbl where orddate < 01-01-2011 ``` in general, what i need is the 1st query gives me the list of customer who are created before 01-01-2011. and 2nd query gives list of who has not made any order after 01-01-2011 . my desired output is list of customer whose createdate is before 01-01-2011 and have not made any order after 01-01-2011. I would really appreciate if you could help me out on this. forgot to mention that custid is same in both tables. thanks. --EDIT : to make a little more clear, many customers whose createdate is before 1-1-2011 are still active and i just want the list of customer who are inactive after 01-01-2011
``` 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' ) ``` I just read your edit and it seems you want to know customers that were created prior to 01-01-2011 and haven't placed any order after that date. This simplifies things and doesn't require a join unless you need to see their last order date
Try this ``` SELECT usr.custid, usr.fname, od.orddate FROM customertbl usr JOIN ordertbl od ON od.custid = usr.custid WHERE usr.createdate < '01-01-2011' AND od.orddate < '01-01-2011' ```
combining 2 select query in 1 mysql
[ "", "mysql", "sql", "database", "" ]
I need to copy 3 columns(with values) from one table to another table(this table will be created as new) and also need to add an extra column in the new formed table. Is it possible only in one sql query? I thought this might be an answer - ``` CREATE TABLE NEW_TBL(Col1,Col2,Col3,New_Col) AS SELECT Col1,Col2,Col3 FROM OLD_TBL ``` But the confusion is how to assign the data type of that new column? Is it possible with only one single SQL statement?
Here is an example using `create table as` syntax: ``` CREATE TABLE NEW_TBL AS SELECT Col1, Col2, Col3, 'Newcol' as Col4 FROM OLD_TBL; ``` To assign a data type, use `cast()` or `convert()` to get the type you want: ``` CREATE TABLE NEW_TBL AS SELECT Col1, Col2, Col3, cast('Newcol' as varchar(255) as Col4, cast(123 as decimal(18, 2)) as col4 FROM OLD_TBL; ``` By the way, you can also add the column directly to the old table: ``` alter table old_tbl add col4 varchar(255); ``` You can then update the value there, if you wish.
# MS SQL You didn't mention your database. Here is an example for MS SQL ``` SELECT Col1,Col2,Col3,'text field' as NEW_COL INTO NEW_TBL FROM OLD_TBL; ``` This query will create new table `NEW_TBL` and add all data from `OLD_TBL` with additional text field NEW\_COL. The type of the new field depends on constant type for example if you need INT type you can use `0` instead of `'text field'` constant. [SQLFiddle demo](http://sqlfiddle.com/#!6/70e28/1)
Copying Data from one table into another and simultaneously add another column
[ "", "sql", "" ]
With the help of you guys on here, I have the following SQL Query: ``` SELECT DataLog.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; ``` This returns a column "TimestampUTC" with YYYY-MM-DD hh:mm:ss. I'd like to drop the time within this column and only display YYYY-MM-DD. Any help you could give would be really appreciated. Thanks in advance.
``` 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; ```
In SQL Server you can convert to Date ``` select Convert(Date, Convert(datetime, '2013/01/01 12:53:45')) ``` results: ``` 2013-01-01 ```
Remove Time from DateTime values returned in Query
[ "", "sql", "sql-server-2008", "t-sql", "datetime", "" ]
I am getting an error when trying to get this table valued function up. I have an error when I try to modify it. It is > Incorrect syntax near the keyword 'Declare'. However when I use this outside of the function it all works great. So I was just wondering is there something I am missing or how should I be doing this. Thanks. ``` ALTER FUNCTION [dbo].[XXX]( @i_contactkey int, @v_scope varchar(15), @i_entrykey int = null, @i_staffcontactkey int = null, @d_startdate datetime, @d_today datetime) RETURNS TABLE AS begin Declare @temp as table (contactkey int, contactkey1 int, rolekey1 int,contactkey2 int, rolekey2 int, relationshipid int) insert into @temp (contactkey , contactkey1 , rolekey1 ,contactkey2 , rolekey2 , relationshipid ) select contactkey , contactkey1 , rolekey1 ,contactkey2 , rolekey2 , relationshipid from contact clcon LEFT JOIN contactassociation ca on ca.contactkey2 = clcon.contactkey where ca.rolekey1 in (4,5,6) and ca.relationshipid = 181 and ca.activeind = 1 and ca.associationkey = (select top 1 associationkey from contactassociation where contactkey2 = clcon.contactkey and activeind = 1 and relationshipid = 181 and rolekey1 in (4,5,6) order by begindate desc) SELECT clcon.contactkey'ClientId', clcon.Stat'ClientStatus', ctacct.optiondesc'account', ctlvl.optiondesc'levelid', (clcon.lastname+', '+clcon.firstname)'ClientName', clcon.firstname'ClientFirstName', clcon.lastname'ClientLastName', clcon.addressline1'address1', clcon.addressline2'address2', clcon.city'city', dbo.getcnfgoption(81,clcon.stateid,'D')'state', clcon.zipcode'zipcode', clcon.mainphone'mainphone', cgcon.contactkey'cgkey',(cgcon.firstname+' '+cgcon.lastname)'CGName', cgcon.firstname'CGFirstName', cgcon.lastname'CGLastName', cgcon.addressline1'cgaddressline1', cgcon.addressline2'cgaddressline2', cgcon.city'cgcity', dbo.getcnfgoption(81,cgcon.stateid,'D')'cgstate', cgcon.zipcode'cgzipcode', cgcon.mainphone'cgmainphone', dbo.getClientAltCGKeys_JSON(clcon.contactkey,'J')'AltCGsJSON', --dbo.getClientAltCGKeys(clcon.contactkey,'C')'AltCGNames', --dbo.getClientAltCGKeys(clcon.contactkey,'L')'altcgnamekeyslast', --dbo.getClientAltCGKeys(clcon.contactkey,'A')'altcgkeysaddress', dbo.getClientEventCount(clcon.contactkey, 'M', @d_startdate, @d_today) 'MLOA', dbo.getClientEventCount(clcon.contactkey, 'N', @d_startdate, @d_today) 'NMLOA', dbo.getClientEventCount(clcon.contactkey, 'A', @d_startdate, @d_today) 'Alts', dbo.getClientEventCount(clcon.contactkey, 'S', @d_startdate, @d_today ) 'Suspension', dbo.getClientEventCountAnnual(clcon.contactkey, 'C') 'MissingNotes', -- dbo.getContactVerificationStatus(clcon.contactkey, 'D')'clverification', -- dbo.getContactVerificationStatus(cgcon.contactkey, 'D')'cgverification', ed1.eventkey 'mdskey', dbo.getCnfgTableOption(54,ed1.eventstatusid,'D')'mdsstatus', ed1.ScheduledDate 'NextMDS', ed2.eventkey 'pockey', dbo.getCnfgTableOption(54,ed2.eventstatusid,'D')'pocstatus', ed2.ScheduledDate 'NextPoC', ed3.eventkey 'hvkey', dbo.getCnfgTableOption(54,ed3.eventstatusid,'D')'hvsstatus', ed3.ScheduledDate 'NextHV', ed4.eventkey 'medlistkey', dbo.getCnfgTableOption(54,ed4.eventstatusid,'D')'medstatus', ed4.ScheduledDate 'NextMedList', ed5.eventkey 'semikey', dbo.getCnfgTableOption(54,ed5.eventstatusid,'D')'semistatus', ed5.ScheduledDate 'NextSemi', ed6.eventkey'placementkey', ed6.startdate'placementstart', ed6.enddate'placementend', [dbo].[getClientCMName](clcon.contactkey)'cmname', [dbo].[getClientRNName](clcon.contactkey)'rnname', [dbo].[getClientCMKey](clcon.contactkey)'cmkey', [dbo].[getClientRNKey](clcon.contactkey)'rnkey', alertcount=(SELECT COUNT(eventalertkey) FROM veventalert WHERE alerttype='Alert' AND clientkey=clcon.contactkey AND viewedind=0 AND contactkey=COALESCE(@i_staffcontactkey,@i_contactkey)), alertkey=(SELECT MAX(eventalertkey) FROM veventalert WHERE alerttype='Alert' AND clientkey=clcon.contactkey AND viewedind=0 AND contactkey=COALESCE(@i_staffcontactkey,@i_contactkey)), msgcount=(SELECT COUNT(eventalertkey) FROM veventalert WHERE alerttype='Message' AND clientkey=clcon.contactkey AND viewedind=0 AND cgkey=cgcon.contactkey), msgkey=(SELECT MAX(eventalertkey) FROM veventalert WHERE alerttype='Message' AND clientkey=clcon.contactkey AND viewedind=0 AND cgkey=cgcon.contactkey), clcp.birthdate FROM (select dbo.getcontactstatus(contactkey,'ts')'Stat',* from contact where dbo.getcontactstatus(contactkey,'ts') is not null ) clcon INNER JOIN contactrole cr ON (clcon.contactkey = cr.contactkey) --Find caregiver contact info LEFT JOIN contactassociation ca on ca.contactkey2 = clcon.contactkey and ca.rolekey1 in (4,5,6) and ca.relationshipid = 181 and ca.activeind = 1 and ca.associationkey = (select max(associationkey) from contactassociation where contactkey2 = clcon.contactkey and activeind = 1 and relationshipid = 181 and rolekey1 in (4,5,6)) LEFT JOIN contact cgcon ON cgcon.contactkey = ca.contactkey1 and cgcon.activeind = 1 LEFT JOIN contactbu cbu ON (clcon.contactkey = cbu.contactkey) /*Account/Lvl Information*/ LEFT JOIN contactprofile clcp ON (clcon.contactkey=clcp.contactkey) LEFT JOIN cnfgtableoption ctlvl ON (clcp.svclevelid = ctlvl.tableoptionkey) LEFT JOIN cnfgtableoption ctacct ON (clcp.accountid = ctacct.tableoptionkey) LEFT JOIN eventdefinition ed1 /* MDS */ ON (clcon.contactkey=ed1.contactkey AND ed1.eventkey=dbo.getContactEventByWftask(clcon.contactkey, 181, 'MINOPEN')) LEFT JOIN eventdefinition ed2 /* POC */ ON (clcon.contactkey=ed2.contactkey AND ed2.eventkey=dbo.getContactEventByWftask(clcon.contactkey, 120, 'MINOPEN')) LEFT JOIN eventdefinition ed3 /* HV */ ON (clcon.contactkey=ed3.contactkey AND ed3.eventkey=dbo.getContactEventByWftask(clcon.contactkey, 341, 'MINOPEN')) LEFT JOIN eventdefinition ed4 /* MED */ ON (clcon.contactkey=ed4.contactkey AND ed4.eventkey=dbo.getContactEventByWftask(clcon.contactkey, 178, 'MINOPEN')) LEFT JOIN eventdefinition ed5 /* SEMI */ ON (clcon.contactkey=ed5.contactkey AND ed5.eventkey=dbo.getContactEventByWftask(clcon.contactkey, 122, 'MINOPEN')) LEFT JOIN eventdefinition ed6 /* Placement */ ON (clcon.contactkey=ed6.contactkey AND ed6.wftaskkey = 49 AND ed6.eventstatusid = 16 AND ed6.activeind = 1 AND ed6.enddate = (select MAX(enddate) from eventdefinition where contactkey = clcon.contactkey and wftaskkey = 49 and activeind = 1 and eventstatusid = 16)) WHERE --Contact info cr.rolekey = 8 AND cbu.entrykey = @i_entrykey --and dbo.getcontactstatus (clcon.contactkey,'TS') not in ('Closed','Discharged') and clcon.Stat not in ('Closed') and clcon.activeind=1 -- filter by branch entrykey (if param exists) --order by clcon.lastname,clcon.firstname ```
When you're using multiple statements in a function and returning a table, i.e. a **Table-Valued User-Defined Function**, you need a certain syntax, something like: ``` CREATE FUNCTION dbo.MyFunction(@ID int) RETURNS @Mytable TABLE ( -- Columns returned by the function ID int PRIMARY KEY NOT NULL, -- (Other columns as required) ) AS BEGIN --Various statements to populate @Mytable RETURN; -- Returns @Mytable END ``` See [Table-Valued User-Defined Functions](http://technet.microsoft.com/en-us/library/ms191165%28v=sql.105%29.aspx) for more information. If you have a function that just has `RETURNS TABLE` with no definition of the table being returned, this is an **Inline User-Defined Function**. > Inline user-defined functions are a subset of user-defined functions > that return a table data type. Inline functions can be used to achieve > the functionality of parameterized views. See [Inline User-Defined Functions](http://technet.microsoft.com/en-us/library/ms189294%28v=sql.105%29.aspx). The syntax for this is like: ``` CREATE FUNCTION dbo.MyFunction(@ID int) RETURNS TABLE AS RETURN ( SELECT * FROM MyTable WHERE ID = @ID ); ``` Here you don't define the table being returned and the body of the function can only be one `SELECT` statement. At the moment your code is somewhere between the two; you need to get this to work as the first option, i.e. the **Table-Valued User-Defined Function**; start by defining the table being returned in the `RETURNS` clause and go from there.
You have invalid function declaration. When returning table you should specify variable name that will hold your table, so your header may look like: ``` ALTER FUNCTION [dbo].[XXX](.....) RETURNS @temp TABLE (contactkey int, contactkey1 int, rolekey1 int,contactkey2 int, rolekey2 int, relationshipid int) AS begin ... ```
Table Variable In a table Valued function
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
I have a need to get columns for specific rows in the database, identified by more than one column. I'd like to do this in batches using an IN query. In the single column case, it's easy: ``` SELECT id FROM foo WHERE a IN (1,2,3,4) ``` But I'm getting a syntax error when I try multi columns ``` SELECT id FROM foo WHERE (a,b) IN ((1,2), (3,4), (5,6)) ``` Is there any way to do this? I can't just do two IN clauses because it potentially returns extra rows and also doesn't use the multi-column index as well.
This is Declan\_K's idea: To be able to use multi-column indexes and not having to update a separate column, you have to put the lookup values into a table which you can join: ``` CREATE TEMPORARY TABLE lookup(a, b); INSERT INTO lookup VALUES ...; CREATE INDEX lookup_a_b ON lookup(a, b); SELECT id FROM foo JOIN lookup ON foo.a = lookup.a AND foo.b = lookup.b; ``` (The index is not really necessary; if you omit it, the SQLite query optimizer will be forced to look up the `lookup` records in the `foo` table, instead of doing it the other way around.) If you want to avoid the temporary table, you could construct it dynamically using a subquery: ``` SELECT id FROM foo JOIN (SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 , 4 UNION ALL SELECT 5 , 6 ) AS lookup ON foo.a = lookup.a AND foo.b = lookup.b ``` This will still be able to use an index on `foo(a,b)`.
This command should use an index on (a, b): ``` SELECT id FROM foo WHERE a = 1 and b = 2 UNION ALL SELECT id FROM foo WHERE a = 3 and b = 4 UNION ALL SELECT id FROM foo WHERE a = 5 and b = 6 ``` It's tedious to write if you have a length list of pairs, but that can be automated.
How do you do an IN query that has multiple columns in sqlite
[ "", "sql", "sqlite", "" ]
I'm trying to create a function in mysql which will return boolean if the id already exist in the table. Most of the solutions that I found online require solutions using both php and mysql but what I'm trying to do is a solution purely in mysql in the form of a function. My simplifed mysql table will be as follow: ``` CREATE TABLE IF NOT EXISTS table1 ( `user_id` VARCHAR(12) UNIQUE, `name` VARCHAR(128), PRIMARY KEY (`user_id`) ); ``` My first attempt was below: ``` DELIMITER * DROP FUNCTION IF EXISTS CheckExistId* CREATE FUNCTION CheckExistId (user_id VARCHAR(12)) RETURNS BOOL BEGIN DECLARE isExist BOOL; SET isExist = 0; SELECT EXISTS(SELECT * FROM table1 WHERE `user_id`=user_id) INTO isExist ; RETURN isExist; END* DELIMITER ; ``` My second attempt: ``` DELIMITER * DROP FUNCTION IF EXISTS CheckExistId* CREATE FUNCTION CheckExistId (user_id VARCHAR(12)) RETURNS BOOL BEGIN DECLARE isExist BOOL; DECLARE countRow INT; SELECT COUNT(`user_id`) INTO countRow FROM table1 WHERE `user_id`=user_id; IF countRow = 0 THEN SET isExist = 1; ELSE SET isExist = 0; END IF; RETURN isExist; END* DELIMITER ; ``` Both didn't give me the result that I expected. Any suggestions on how to fix this?
Your first attempt was quite fine, except that you're using `*` as delimiter and using the same name for your parameter and column name. That's confusing MySQL. Write it like this: ``` DELIMITER $$ DROP FUNCTION IF EXISTS CheckExistId $$ CREATE FUNCTION CheckExistId (p_user_id VARCHAR(12)) RETURNS BOOL BEGIN DECLARE isExist BOOL; SET isExist = 0; SELECT EXISTS(SELECT * FROM table1 WHERE `user_id`=p_user_id) INTO isExist ; RETURN isExist; END $$ DELIMITER ; ```
``` DROP TABLE IF EXISTS `TableTT2`; CREATE TABLE IF NOT EXISTS TableTT2 ( `user_id` VARCHAR(12) UNIQUE, `name` VARCHAR(128), PRIMARY KEY (`user_id`) ); INSERT INTO `TableTT2` (`user_id`, `name`) VALUES (LEFT(UUID(), 12), 'a1'), (LEFT(UUID(), 12), 'a2'), (LEFT(UUID(), 12), 'a3'), (LEFT(UUID(), 12), 'a4'), (LEFT(UUID(), 12), 'a5'), (LEFT(UUID(), 12), 'a6'), (LEFT(UUID(), 12), 'a7'), (LEFT(UUID(), 12), 'a8'); DELIMITER $$ CREATE FUNCTION `CheckExistId`(usrId varchar(12)) RETURNS BOOL BEGIN DECLARE totalCnt INT; DECLARE resBool BOOL; SET totalCnt = 0 ; SELECT COUNT(*) INTO totalCnt FROM TableTT2 WHERE user_id = usrID; SET resBool = IF(totalCnt <> 0, TRUE, FALSE); RETURN resBool; END SELECT * FROM TableTT2; SELECT CheckExistId('fe3faa00-0b0'); SELECT CheckExistId('fe3faa00-111'); ``` Hope this helps. It might be an issue using \* delimiter and a second issue that i noticed your function parameter is a varchar even if you check by an integer id.
MySql function not returning the correct result
[ "", "mysql", "sql", "function", "" ]
Is there a way to solve something like this, without using a self join? Some way to use the min() function? I want to get the first fruit entry for each group of columns c1 and c2. (Assume dates cannot be identical) ``` DROP TABLE IF EXISTS test; CREATE TABLE test ( c1 varchar(25), c2 varchar(25), fruit varchar(25), currentTime Datetime ); INSERT INTO test VALUES ('a','b','pineapple','2013-01-28 20:50:00'), ('a','b','papaya','2013-01-28 20:49:00'), ('a','b','pear','2013-01-28 20:51:00'), ('a','c','peach','2013-01-28 18:12:00'), ('a','c','plum','2013-01-28 20:40:00'), ('a','c','pluot','2013-01-28 16:50:00'); ``` Here is my current query: ``` SELECT t2.* FROM (SELECT c1, c2, MIN(currentTime) AS ct FROM test GROUP BY c1, c2) as t1 JOIN test t2 ON t1.c1 = t2.c1 AND t1.c2 = t2.c2 AND t2.currentTime = t1.ct ``` This yields the earliest entry for each `c1/c2` pair, but is there a way to use `min()` and avoid the self join?
The answer is "yes". You can do it with just aggregation. The key is to use the `group_concat()`/`substring_index()` trick to get the first fruit: ``` select c1, c2, substring_index(group_concat(fruit order by currentTime), ',', 1) as fruit, min(currentTime) from test group by c1, c2; ``` This has been tested on your SQL Fiddle.
``` SELECT c1, c2, currentTime AS ct FROM test GROUP BY c1,c2 HAVING MIN(ct) ``` Or, if you would like to get the `fruit` column as well, try: ``` SELECT c1, c2, fruit, currentTime AS ct FROM test GROUP BY c1,c2 HAVING MIN(ct) ```
Retrieve all columns in row with min date?
[ "", "mysql", "sql", "date", "min", "" ]
Why doesn't the next Fiddle give me 102 ? I'm looking for the smallest number that doesn't exist in both columns. NOTICE: one column is a number, and the other is a varchar. ``` SELECT NVL(MIN(a1.id_int)+1, 111) FROM bPEOPLE a1 WHERE NOT EXISTS (SELECT 1 FROM PEOPLE a2 WHERE a2.id_int=a1.id_int+1 ) AND NOT EXISTS ( SELECT 1 FROM PEOPLE a3 WHERE TO_NUMBER(a3.id_str)=a1.id_int+1 ) AND a1.id_int + 1 > 100 AND a1.id_int + 1 < 110; ``` [Sql Fiddle](http://sqlfiddle.com/#!4/9adff/1/0)
Because your expression: ``` NVL(MIN(a1.id_int)+1, 111) ``` is only referencing the int column, in which the next value is 108. You need to combine the two columns into a single column, then get the MIN: ``` SELECT NVL(MIN(a.id_int)+1, 111) as next_id FROM ( SELECT id_int FROM PEOPLE UNION ALL SELECT TO_NUMBER(id_str) AS id_int FROM PEOPLE ) a WHERE NOT EXISTS ( SELECT 1 FROM PEOPLE b WHERE a.id_int + 1 IN (b.id_int, TO_NUMBER(b.id_str)) ); ``` **[Example on SQL Fiddle](http://sqlfiddle.com/#!4/9adff/44)**
You doesn't get 102 because you start from the `id_int` column and then add `1`. You have to have 101 in `id_int` column in order to have a chance to get 102. In other words, your error is, that you start with `MIN(a1.id_int)` and ignores `MIN(TO_NUMBER(a3.id_str))`. Here is probably what you want ``` SELECT NVL(MIN(n)+1, 111) FROM ( SELECT id_int as n FROM PEOPLE UNION SELECT TO_NUMBER(id_str) as n FROM PEOPLE ) p WHERE NOT EXISTS ( SELECT 1 FROM PEOPLE a2 WHERE a2.id_int=n+1 ) AND NOT EXISTS ( SELECT 1 FROM PEOPLE a3 WHERE TO_NUMBER(a3.id_str)=n+1 ) AND n + 1 > 100 AND n + 1 < 110; ```
Smallest not existing number in two different columns in Oracle SQL
[ "", "sql", "oracle", "" ]
I'm trying to get records based on applied search criteria. At a time I'm only selecting 50 rows(for pagination of the table used on webpage). But I also need the `total` number of rows that satisfies the search criteria (to show `1-50 out of <total> records` & so on). Following query gives me records group by userid. ``` select * from user group by userid where name like '%hhh%' limit 50 offset 0 ``` Here I'll will get first 50 records that satisfies the criteria, but total search results can be greater than 50. I need this total count along with other query result.
I'd use a separate query: ``` select count(*) from user group by userid where name like '%hhh%' ``` Your query will be much quicker and can be run each time another 50 rows are selected, then you can run this longer running query once, to get the total
try this query.. ``` select count(*) as total,userid from users where name like '%hhh%' group by userid limit 50 offset 0 ```
MySql count of group by result
[ "", "mysql", "sql", "" ]
There's a table `message` and a table `sender`, and I want to retrieve all "message information" associated to a specific id, along with the sender name and email. I have this query: ``` SELECT a.id, a.subject, a.body, a.sender_id, ( SELECT b.name FROM sender b WHERE b.id = a.sender_id LIMIT 1 ) AS sender_name, ( SELECT b.email FROM sender b WHERE b.id = a.sender_id LIMIT 1 ) AS sender_email, a.sent_time FROM message a WHERE a.id = <id> LIMIT 1; ``` It works, but it has to perform two different SELECT subqueries *to the same table*. In this case (which is an extremely simplified example) it probably doesn't hurt the performance at all, but in a real-life scenario where *a lot* of fields have to be retrieved from an external table, the best way to do it is using a JOIN statement? Isn't it possible to have a SELECT subquery that retrieves many fields? I'm using [MySQL](http://www.mysql.com/) with [MyISAM](http://dev.mysql.com/doc/refman/5.0/en/myisam-storage-engine.html) storage engine in case it matters.
Just join to the `sender` tables once in the `FROM` clause. ``` SELECT a.id, a.subject, a.body, a.sender_id, b.name, b.email, a.sent_time FROM message a INNER JOIN sender b ON b.id = a.sender_id WHERE a.id = <id> LIMIT 1; ```
Try this: ``` SELECT a.id, a.subject, a.body, a.sender_id, b.name AS sender_name, b.email AS sender_email, a.sent_time FROM message a, sender b WHERE a.id = <id> AND b.id = a.sender_id LIMIT 1; ```
Multiple SELECT subqueries to the same table into one
[ "", "mysql", "sql", "myisam", "" ]
Table1 ``` Id value 1 1 1 4 ``` Table2 ``` id Detailid value 1 1 1 1 2 2 1 3 3 1 4 4 1 5 5 1 6 6 ``` I want results ``` Id Detaild value 1 1 1 1 2 null 1 3 null 1 4 4 1 5 null 1 6 null ``` My query below gives me 2 extra rows with null ``` select distinct t1.id,t2.detailid ,case when t1.value IN(t2.Value) then t1.value else null end as value from table1 t1 left outer join table2 t2 on t1.id= t2.id ``` I am getting ``` Id Detaild value 1 1 null ----dont need 1 1 1 1 2 null 1 3 null 1 4 null ---dont need 1 4 4 1 5 null 1 6 null ```
From what you have given as data, this query will do the trick : ``` SELECT isnull(t1.Id,1), t2.Detailid, t1.value FROM Table2 AS t2 LEFT OUTER JOIN Table1 AS t1 ON t1.Detailid = t2.Detailid AND t1.ID = 1 ``` SQLFIDDLE : <http://www.sqlfiddle.com/#!3/4c808/8/0> EDIT : So take a look at the following query, based on you last edit : ``` SELECT t2.Id, t2.Detailid, t1.value FROM Table2 AS t2 LEFT OUTER JOIN Table1 AS t1 ON t1.Id = t2.Id AND t1.value = t2.value WHERE t2.Id = 1 ``` SQLFIDDLE : <http://www.sqlfiddle.com/#!3/94f21a/5/0> RE-EDIT : ``` SELECT t2.Id, t2.Detailid, t1.value FROM Table2 AS t2 LEFT OUTER JOIN Table1 AS t1 ON t1.Id = t2.Id AND t1.value = t2.value WHERE t2.id IN (SELECT Id FROM Table1) ``` SQLFIDDLE : <http://www.sqlfiddle.com/#!3/beede/7/0> If `(SELECT Id FROM Table1)` returns too many rows, try something like this instead : ``` SELECT DISTINCT t2.Id, t2.Detailid, t1.value FROM Table2 AS t2 INNER JOIN Table1 AS t ON t.Id = t2.Id LEFT OUTER JOIN Table1 AS t1 ON t1.Id = t2.Id AND t1.value = t2.value ``` SQLFIDDLE : <http://www.sqlfiddle.com/#!3/beede/9/0>
That's because you don't have a row in Table1 with a foreign key to DetailId 2 and 3, so how else can it return those in the join?
SQL left join issue
[ "", "sql", "sql-server-2008", "" ]
I have following data in my table: ``` URL TIME DATE -------------------------------------- /x 11 2013-08-01 /x 11 2013-08-01 /pl/ 11 2013-08-01 /pl/ 11 2013-08-03 /pl/XXX/ 11 2013-08-01 /pl/XXX/ 11 2013-08-04 /pl/XXX/1 11 2013-08-01 /pl/XXX/2 11 2013-08-01 /pl/YYY/ 11 2013-08-01 /pl/YYY/1 11 2013-08-01 /pl/YYY/2 11 2013-08-04 /pl/YYY/3 11 2013-08-04 ``` Is there a way to group by URL up to third slash (`/`) in SQL Server? Unfortunately there exists record which contains less than three.
One trick to count the number of slashes in a string is: ``` len(url) - len(replace(url,'/','')) ``` You can then use `charindex` three times to find the position of the third slash: ``` select BeforeThirdSlash , max([date]) from ( select case when len(url) - len(replace(url,'/','')) < 3 then url else substring(url, 1, charindex('/', url, charindex('/', url, charindex('/', url)+1)+1)-1) end as BeforeThirdSlash , * from @t ) as SubQueryAlias group by BeforeThirdSlash ``` [Live example at SQL Fiddle.](http://sqlfiddle.com/#!6/588d4/1/0)
A simple expression that lets you grab the substring up to the third `'/'` character is as follows: ``` case when patindex('%/%/%/%', url) = 0 then url else left(url,charindex('/',url,charindex('/',url,charindex('/',url)+1)+1)) end ``` The `patindex` checks that there are at least three slashes; the `left` extracts the substring up to and including the third one. With this expression in hand, writing a `group by` is simple: ``` SELECT url3, max(tm), max(dt) FROM ( SELECT CASE WHEN patindex('%/%/%/%', url) = 0 THEN url ELSE left(url,charindex('/',url,charindex('/',url,charindex('/',url)+1)+1)) END AS url3 , tm , dt FROM test ) x GROUP BY url3 ``` [Demo on SqlFiddle](http://sqlfiddle.com/#!3/7abb3c/1).
SQL group by part of string
[ "", "sql", "sql-server", "" ]
i really couldn't get it. code- ``` select * from Bill_Detail where DateTimeofBilling > '8/18/2013 12:00:00 PM' and DateTimeofBilling < '8/20/2013 12:00:00 AM' ``` psudocode- ``` select all from Bill_Detail where DateTimeofBilling greater than 8/18/2013 and DateTimeofBilling less than 8/20/2013 ``` i need to get the rows from the date 8/18/2013 to 8/20/2013 but the code returns nothing. i think this is enough explanation for this . can anyone help?
Try this.. ``` select * from Bill_Detail where DateTimeofBilling > '2013/08/18 12:00:00 PM' and DateTimeofBilling < '2013/08/20 12:00:00 AM' ```
Why do you use `PM` (noon, not midnight) for the "greater than" check? Your pseudocode assumes that you also want to use PM. ``` select * from Bill_Detail where DateTimeofBilling >= '20130818'-- if you want to include this day completely and DateTimeofBilling < '20130820' -- if you want to exclude this day completely ```
Getting rows from this date to this date
[ "", "sql", "sql-server", "database", "sql-server-2008", "" ]
I have a table with an auto increment field and another field `VARCHAR` filed. I would like to fill the string field with the newly generated id directly in the insert query. For example with table: ``` Person ( id auto_increment, name varchar ) ``` I would like to perform a query like this: ``` INSERT INTO Person(name) VALUE ('Person #' + ROWID()) ``` Anyway to do this?
This will use the last inserted row id with the increment of 1 to generate the next person id. **Keep in mind that for `last_insert_rowid()` you should not be doing concurrent inserts to the database.** ``` INSERT INTO Person (name) SELECT 'Person #' || (last_insert_rowid()+1); ``` Alternatively this will read the biggest ID you currently have and increment +1 to it and then concatenate it with the text. If it returns null it uses 1. ``` INSERT INTO Person (name) SELECT 'Person #' || (IFNULL((MAX(id)+1),1)) FROM Person LIMIT 1; ``` This one will get the index of autoincrement: ``` INSERT INTO Person (name) SELECT 'Person #' || (seq+1) FROM sqlite_sequence WHERE name="person" ``` You can also do something like this: ``` INSERT INTO Person (name) VALUES (NULL); INSERT INTO Person (name) VALUES (NULL); INSERT INTO Person (name) VALUES (NULL); INSERT INTO Person (name) VALUES (NULL); INSERT INTO Person (name) VALUES (NULL); INSERT INTO Person (name) VALUES (NULL); INSERT INTO Person (name) VALUES (NULL); INSERT INTO Person (name) VALUES (NULL); UPDATE Person SET name = 'Person #' || id WHERE name IS NULL; ``` Or: ``` INSERT INTO Person (name) VALUES ('Person'); UPDATE Person SET name = name || ' #' || id WHERE id = last_insert_rowid(); ``` This one will update the names that does not have a `#` with its row id: ``` INSERT INTO Person (name) VALUES ('Person'); INSERT INTO Person (name) VALUES ('Person'); INSERT INTO Person (name) VALUES ('Person'); INSERT INTO Person (name) VALUES ('Person'); UPDATE Person SET name = name || ' #' || id WHERE (LENGTH(name)-LENGTH(REPLACE(name, '#', ''))) = 0; ``` [**Live DEMO**](http://sqlfiddle.com/#!5/20d83/2/0)
You shouldn't store the same info twice. Just generate the string you want dynamically when you query: ``` SELECT name || '#' || id FROM Person ```
SQLite Insert with the newly generated id
[ "", "sql", "sqlite", "" ]
I've got the following table: ``` ID Name Sales 1 Kalle 1 2 Kalle -1 3 Simon 10 4 Simon 20 5 Anna 11 6 Anna 0 7 Tina 0 ``` I want to write a SQL query that only returns the rows that represents a salesperson with sum of sales > 0. ``` ID Name Sales 3 Simon 10 4 Simon 20 5 Anna 11 6 Anna 0 ``` Is this possible?
You can make it like this, I think the join will be more effective than the where name in() clause. ``` 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 ```
You can easily get names of the people with the sum of sales that are greater than 0 by using the a HAVING clause: ``` select name from yourtable group by name having sum(sales) > 0; ``` This query will return both `Simon` and `Anna`, then if you want to return all of the details for each of these names you can use the above in a WHERE clause to get the final result: ``` select id, name, sales from yourtable where name in (select name from yourtable group by name having sum(sales) > 0); ``` See [SQL Fiddle with Demo](http://sqlfiddle.com/#!2/605cf/2).
How to select items according to their sums in SQL?
[ "", "sql", "sum", "" ]
I use MSSQL Server 2008 and I have SQL request with simple condition which periodically deletes old records from table (~3 mil records in the table). This request executed significant time (~ 10 second) even if it affects 0 rows. This table has some indexes and in Actual Execution Plan I see that "Index Delete" operations consume all execution time. Why SQL Server does a lot work on indexes if there no any rows affected by delete operation? Update: Request: ``` delete t from Entity t where t.Revision <= x AND exists ( select 1 from Entity tt where tt.Id=t.Id and tt.Revision > t.Revision ) ``` Actual execution plan XML: pastebin.com/up2E3iP1
The work is all doing the hash join. All the other costs are bogus. The actual number of rows coming out of that is `0` but it estimates more. ![PLAN](https://i.stack.imgur.com/TdA1C.png) The costs shown in the rest of the plan are based on the (incorrect) estimates. You might find this performs better. ``` WITH T AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Revision DESC) AS RN FROM Entity ) DELETE FROM T WHERE RN > 1 AND Revision <= 12586705 ```
I've found joins to be much more performant that subqueries. Try this ``` delete t from Entity t inner join Entity tt ON tt.Id=t.Id where t.Revision <= x and tt.Revision > t.Revision ``` Also, ensure you have an index on Id and Revision.
SQL Delete Request spend significant time in "Index Delete" even if it affects 0 rows
[ "", "sql", "sql-server", "sqlperformance", "sql-delete", "" ]
I am getting the following message when trying to get a specific value in my query "The specified field could refer to more than one table" It is pretty clear that I am trying to search something present in more than one table, but how to do this right? now I have the following code: ``` SELECT Table1.CustomerId, Table1.Address, Table2.CustomerId, Table2.Telephone, Table3.CustomerId, Table3.Notes FROM (Table1 INNER JOIN Table2 ON Table1.CustomerId=TAble2.CustomerId) INNER JOIN Table3 ON Table2.CustomerId=Table3.CustomerId WHERE CustomerId = 0015 ``` the last sentence is the problem... any ideas?
The error message is pretty clear, the field `CustomerId` in the `WHERE` clause `WHERE CustomerId = 0015`, is presented in both the two tables. You have to determine from which table you want to use it from; `table1` or `table2`? for example: ``` SELECT Table1.CustomerId, Table1.Address, Table2.CustomerId, Table2.Telephone, Table3.CustomerId, Table3.Notes FROM (Table1 INNER JOIN Table2 ON Table1.CustomerId=TAble2.CustomerId) INNER JOIN Table3 ON Table2.CustomerId=Table3.CustomerId WHERE table1.CustomerId = 0015 ```
You should point what table is `CustomerId` from in the WHERE statement ``` SELECT Table1.CustomerId, Table1.Address, Table2.CustomerId, Table2.Telephone, Table3.CustomerId, Table3.Notes FROM (Table1 INNER JOIN Table2 ON Table1.CustomerId=TAble2.CustomerId) INNER JOIN Table3 ON Table2.CustomerId=Table3.CustomerId WHERE Table1.CustomerId = 0015 ```
SQL query with INNER JOIN and WHERE
[ "", "mysql", "sql", "database", "ms-access", "" ]
I am trying to delete several rows from a table table in SQL. The problem is that I can't figure out how to delete from that table using the result of a subquery, as there is no primary key in that table. The structure of the tables is as follows: `Friend ( ID1, ID2 )` The student with `ID1` is friends with the student with `ID2`. Friendship is mutual, so if `(123, 456)` is in the Friend table, so is `(456, 123)`. ``` Likes ( ID1, ID2 ) ``` The student with `ID1` likes the student with `ID2`. Liking someone is not necessarily mutual, so if `(123, 456)` is in the Likes table, there is no guarantee that `(456, 123)` is also present. ``` (No primary key) ``` The situation I am trying to solve is: "If two students A and B are friends, and A likes B but not vice-versa, remove the Likes tuple." Thanks in advance.
I have tried to develop an answer for this question. It works for my small test data, but please point out if it might be inefficient for bigger data, or how can it be made better with a better solution. ``` Delete from Likes where ID1 in (select Q.ID1 from (select x.ID1, x.ID2 from (select A.ID1,A.ID2,B.ID2 as se from Likes A left join Likes B on A.ID2=B.ID1) x where x.ID1 <> x.se or x.se is null) Q inner join Friend F where Q.ID1 = F.ID1 and Q.ID2 = F.ID2 order by Q.ID1) and ID2 in (select Q.ID2 from (select x.ID1, x.ID2 from (select A.ID1,A.ID2,B.ID2 as se from Likes A left join Likes B on A.ID2=B.ID1) x where x.ID1 <> x.se or x.se is null) Q inner join Friend F where Q.ID1 = F.ID1 and Q.ID2 = F.ID2 order by Q.ID1) ```
In most SQL dialects you can do: ``` delete from likes where not exists (select 1 from likes l2 where l2.id1 = likes.id2 and l2.id2 = likes.id1) and exists (select 1 from friends f where f.id1 = likes.id1 and f.id2 = likes.id2); ``` This is pretty much a direct translation of your two conditions.
Delete rows from table with no primary key, SQL
[ "", "sql", "sqlite", "" ]
I have a inventory table with a condition i.e. new, used, other, and i am query a small set of this data, and there is a possibility that all the record set contains only 1 or all the conditions. I tried using a case statement, but if one of the conditions isn't found nothing for that condition returned, and I need it to return 0 This is what I've tried so far: ``` select( case when new_used = 'N' then 'new' when new_used = 'U' then 'used' when new_used = 'O' then 'other' end )as conditions, count(*) as count from myDB where something = something group by( case when New_Used = 'N' then 'new' when New_Used = 'U' then 'used' when New_Used = 'O' then 'other' end ) ``` This returns the data like: ``` conditions | count ------------------ new 10 used 45 ``` I am trying to get the data to return like the following: ``` conditions | count ------------------ new | 10 used | 45 other | 0 ``` Thanks in advance
``` ;WITH constants(letter,word) AS ( SELECT l,w FROM (VALUES('N','new'),('U','used'),('O','other')) AS x(l,w) ) SELECT conditions = c.word, [count] = COUNT(x.new_used) FROM constants AS c LEFT OUTER JOIN dbo.myDB AS x ON c.letter = x.new_used AND something = something GROUP BY c.word; ```
try this - ``` DECLARE @t TABLE (new_used CHAR(1)) INSERT INTO @t (new_used) SELECT t = 'N' UNION ALL SELECT 'N' UNION ALL SELECT 'U' SELECT conditions, ISNULL(r.cnt, 0) AS [count] FROM ( VALUES('U', 'used'), ('N', 'new'), ('O', 'other') ) t(c, conditions) LEFT JOIN ( SELECT new_used, COUNT(1) AS cnt FROM @t --WHERE something = something GROUP BY new_used ) r ON r.new_used = t.c ``` in output - ``` new 2 used 1 other 0 ```
counting records on the same table with different values possibly none sql server 2008
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I need some help with my SQL logic, and I've been working (and researching) this for 2 days now with zero success. My goal is to try an pass a variable from an ASP page to a stored procedure, which is utilizing the variable as criteria for a column name in the where clause. So for example (a simplified version of my query): ``` @strDept nvarchar(10), @strUser nvarchar(30) -- The asp page will pass f18 to @strDept & Ted Lee to strUser -- f18 is the column name in my database that I need in the where. select x, y, z from table1 where @strDept in (@strUser) -- and this is the select statement, notice the where clause. ``` The stored procedure does execute, but it returns no values and I know its treating the @strDept as a literal nvarchar and not a column name. So I guess my question is, how do I get SQL Server 2005 to treat my @sqlDept variable as a column name?
If this is an internal company application why is everyone re-iterating and beating SQL Injection to death... Its very simple to just use Dynamic SQL. If you are comfortable that these are only internal users using this then its very simple. Here is the concept. You essentially write a SQL Statement that writes a string that is really a SQL statement and then execute it. ``` CREATE Procedure myDynamicProcedure @strDept nvarchar(10), @strUser nvarchar(30) as BEGIN ``` **1. Declare a variable to store the SQL Statement.** ``` DECLARE @SQL varchar(max) ``` **2. SET your @SQL Variable to be the SELECT Statement. Basically you are building it so it returns what you are wanting to write. Like this:** ``` SET @SQL = 'select x, y, z from table1 where' + @strDept + ' in ' + @strUser ``` **3. Execute the @SQL Statement and it will be exactly like you ran:** SELECT x,y,z from table1 where f18 = 'Ted Lee' ``` EXEC (@SQL) END ```
The reason you can't find guidance on how to do this is that it's a **really bad idea**. Sooner or later, someone is going to pass a "column name" of `1 ;drop database badidea`. Which will be a blessing for all concerned. Read up on SQL Injection, and rethink your design.
SQL Variables as Column names in Where Clause
[ "", "sql", "sql-server", "t-sql", "" ]
Table: Movie ``` mID title year director 101 Gone with the Wind 1939 Victor Fleming 102 Star Wars 1977 George Lucas 103 The Sound of Music 1965 Robert Wise 104 E.T. 1982 Steven Spielberg 105 Titanic 1997 James Cameron 106 Snow White 1937 <null> 107 Avatar 2009 James Cameron 108 Raiders of the Lost Ark 1981 Steven Spielberg ``` Table: Rating ``` rID mID stars ratingDate 201 101 2 2011-01-22 201 101 4 2011-01-27 202 106 4 <null> 203 103 2 2011-01-20 203 108 4 2011-01-12 203 108 2 2011-01-30 204 101 3 2011-01-09 205 103 3 2011-01-27 205 104 2 2011-01-22 205 108 4 <null> 206 107 3 2011-01-15 206 106 5 2011-01-19 207 107 5 2011-01-20 208 104 3 2011-01-02 ``` I need to fetch movies which are not rate yet. In this case Titanic (mID 105) and Star Wars (mID 102) never get rate in rating table. I figured out it with > select distinct movie.title from movie,rating where > rating.mid!=movie.mid except select distinct movie.title from > movie,rating where rating.mid=movie.mid however I think it might have better (easier/cleaner) way to do.
Simple: ``` SELECT Movies.* FROM Movies LEFT JOIN Rating ON Movies.mID = Rating.mID WHERE Rating.mID IS NULL ```
If I understood your question properly, that looks like textbook application of [outer joins](https://en.wikipedia.org/wiki/Join_%28SQL%29#Outer_join).
How I select record that not appear in another table
[ "", "sql", "sqlite", "" ]
Given the following three columns in a Postgres database: first, second, third; how can I create a constraint such that permutations are unique? E.g. If `('foo', 'bar', 'shiz')` exist in the db, `('bar', 'shiz', 'foo')` would be excluded as non-unique.
You could use hstore to create the unique index: ``` CREATE UNIQUE INDEX hidx ON test USING BTREE (hstore(ARRAY[a,b,c], ARRAY[a,b,c])); ``` [Fiddle](http://sqlfiddle.com/#!1/1f901/2) ## UPDATE Actually ``` CREATE UNIQUE INDEX hidx ON test USING BTREE (hstore(ARRAY[a,b,c], ARRAY[null,null,null])); ``` might be a better idea since it will work the same but should take less space ([fiddle](http://sqlfiddle.com/#!1/b9b7a/1)).
For only **three columns** this unique index using only basic expressions should perform very well. No additional modules like hstore or custom function needed: ``` CREATE UNIQUE INDEX t_abc_uni_idx ON t ( LEAST(a,b,c) , GREATEST(LEAST(a,b), LEAST(b,c), LEAST(a,c)) , GREATEST(a,b,c) ); ``` [fiddle](https://dbfiddle.uk/U8YFxv9n) Old [sqlfiddle](http://sqlfiddle.com/#!17/2dc0b/1) Also needs the least disk space: ``` SELECT pg_column_size(row(hstore(t))) AS hst_row , pg_column_size(row(hstore(ARRAY[a,b,c], ARRAY[a,b,c]))) AS hst1 , pg_column_size(row(hstore(ARRAY[a,b,c], ARRAY[null,null,null]))) AS hst2 , pg_column_size(row(ARRAY[a,b,c])) AS arr , pg_column_size(row(LEAST(a,b,c) , GREATEST(LEAST(a,b), LEAST(b,c), LEAST(a,c)) , GREATEST(a,b,c))) AS columns FROM t; ``` ``` hst_row | hst1 | hst2 | arr | columns ---------+------+------+-----+--------- 59 | 59 | 56 | 69 | 30 ``` Numbers are bytes for index row in the example in the fiddle, measured with [`pg_column_size()`](https://stackoverflow.com/a/7431468/939860). My example uses only single characters, the difference in size is constant.
Unique constraint for permutations across multiple columns
[ "", "sql", "postgresql", "database-design", "constraints", "unique-constraint", "" ]
If i write a sql: ``` select * from a,b where a.id=b.id(+) and b.val="test" ``` and i want all records from a where corresponding record in b does not exist or it exists with val="test", is this the correct query?
You're much better off using the ANSI syntax ``` SELECT * FROM a LEFT OUTER JOIN b ON( a.id = b.id and b.val = 'test' ) ``` You can do the same thing using Oracle's syntax as well but it gets a bit hinkey ``` SELECT * FROM a, b WHERE a.id = b.id(+) AND b.val(+) = 'test' ``` Note that in both cases, I'm ignoring the `c` table since you don't specify a join condition. And I'm assuming that you don't really want to join A to B and then generate a Cartesian product with C.
Move the condition into the `JOIN` clause and use the ANSI standard join pattern. ``` SELECT NameYourFields,... FROM A LEFT OUTER JOIN B ON A.ID = B.ID AND B.VAL = 'test' INNER JOIN C ON ... ```
How to use oracle outer join with a filter where clause
[ "", "sql", "oracle11g", "outer-join", "" ]
I have a table (call\_history) with a list of phone calls report, caller\_id is the caller and start\_date (DATETIME) is the call date. I need to make a report that will show how many people called for the first time for every day. For example: ``` 2013-01-01 - 100 2013-01-02 - 80 2013-01-03 - 90 ``` I have this query that does it perfectly, but it is very slow. There are indexes on both start\_date and caller\_id columns; is there an alternative way to get this information to speed the process up? Here is the query: ``` SELECT SUBSTR(c1.start_date,1,10), COUNT(DISTINCT caller_id) FROM call_history c1 WHERE NOT EXISTS (SELECT id FROM call_history c2 WHERE SUBSTR(c2.start_date,1,10) < SUBSTR(c1.start_date,1,10) AND c2.caller_id=c1.caller_id) GROUP BY SUBSTR(start_date,1,10) ORDER BY SUBSTR(start_date,1,10) desc ```
The following "WHERE SUBSTR(c2.start\_date,1,10)" is breaking your index (you shouldn't perform functions on the left hand side of a where clause) Try the following instead: ``` SELECT DATE(c1.start_date), COUNT(caller_id) FROM call_history c1 LEFT OUTER JOIN call_history c2 on c1.caller_id = c2.caller_id and c2.start_date < c1.start_date where c2.id is null GROUP BY DATE(start_date) ORDER BY start_date desc ``` Also re-reading your problem, I think this is another way of writing without using NOT EXISTS ``` SELECT DATE(c1.start_date), COUNT(DISTINCT c1.caller_id) FROM call_history c1 where start_date = (select min(start_date) from call_history c2 where c2.caller_id = c1.caller_id) GROUP BY DATE(start_date) ORDER BY c1.start_date desc; ```
You are doing a weird thing - using functions in `WHERE`, `GROUP` and `ORDER` clauses. MySQL **will never** use indexes when function was applied to calculate condition. So, you can not do anything with *this* query, but to improve your situation, you should alter your table structure and store your date as `DATE` column (and single column). Then create index by this column - after this you'll get much better results.
Slow SQL Query, how to improve this query speed?
[ "", "mysql", "sql", "" ]
I need a SQL query to get the value between two known strings (the returned value should start and end with these two strings). An example. "All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought." In this case the known strings are "the dog" and "immediately". So my query should return "the dog had been very bad and required harsh punishment immediately" I've come up with this so far but to no avail: ``` SELECT SUBSTRING(@Text, CHARINDEX('the dog', @Text), CHARINDEX('immediately', @Text)) ``` @Text being the variable containing the main string. Can someone please help me with where I'm going wrong?
The problem is that the second part of your substring argument is including the first index. You need to subtract the first index from your second index to make this work. ``` SELECT SUBSTRING(@Text, CHARINDEX('the dog', @Text) , CHARINDEX('immediately',@text) - CHARINDEX('the dog', @Text) + Len('immediately')) ```
I think what Evan meant was this: ``` SELECT SUBSTRING(@Text, CHARINDEX(@First, @Text) + LEN(@First), CHARINDEX(@Second, @Text) - CHARINDEX(@First, @Text) - LEN(@First)) ```
A SQL Query to select a string between two known strings
[ "", "sql", "sql-server", "substring", "" ]
Table1 ``` | MODULE | COUNT | YEAR | ------------------------- | M1 | 12 | 2011 | | M1 | 43 | 2012 | | M2 | 5 | 2011 | | M3 | 24 | 2011 | | M4 | 22 | 2011 | | M4 | 11 | 2012 | | M5 | 10 | 2012 | ``` I want to display like this ``` | MODULE | 2011 | 2012 | ---------------------------- | M1 | 12 | 43 | | M2 | 5 | - | | M3 | 24 | - | | M4 | 22 | 11 | | M5 | - | 10 | ```
This can be done using [PIVOT](http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx) query. Or the following: ``` 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 ``` [SQL Fiddle demo](http://sqlfiddle.com/#!6/512e0/1)
You can use [PIVOT](http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx) for that: ``` SELECT Module, [2011], [2012] FROM ( SELECT * FROM Table1 ) AS SourceTable PIVOT ( SUM([Count]) FOR [Year] IN ([2011], [2012]) ) AS PivotTable; ``` You can also use this dynamic query if you don't have limited `Year` ``` DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) SELECT @cols = STUFF((SELECT distinct ',' + QUOTENAME([Year]) from Table1 FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') SET @query = 'SELECT Module,' + @cols + ' FROM ( Select * FROM Table1 ) dta PIVOT ( SUM([Count]) FOR [Year] IN (' + @cols + ') ) pvt ' EXECUTE(@query); ``` Result: ``` | MODULE | 2011 | 2012 | ---------------------------- | M1 | 12 | 43 | | M2 | 5 | (null) | | M3 | 24 | (null) | | M4 | 22 | 11 | | M5 | (null) | 10 | ``` ### See [this SQLFiddle](http://sqlfiddle.com/#!3/736e6/1) --- ### Update You can also use this alternative dynamic method: (Dynamic of the query given by [@valex](https://stackoverflow.com/a/18397178/1369235)) ``` DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) SELECT @cols = STUFF((SELECT distinct ',' + ' SUM(CASE WHEN YEAR= ''' + CAST(Year AS varchar(50)) + ''' THEN [COUNT] ELSE ''-'' END) AS ' + QUOTENAME([Year]) from Table1 FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') SET @query = 'SELECT Module, ' + @cols + ' FROM Table1 GROUP BY Module' EXECUTE(@query); ``` ### See [this SQLFiddle](http://sqlfiddle.com/#!3/736e6/5)
SQL separate columns by rows value (pivot)
[ "", "sql", "sql-server", "join", "pivot", "" ]
I am in the situation where i want to match a date range with another date range, it might be simple but i am stuck at it. Below is table structure **Table - lifecycles** * life\_id * life\_start\_date * life\_end\_date then a few records as below ``` 1 - 07/23/2013 - 07/24/2013 2 - 07/15/2013 - 07/25/2015 3 - 03/10/2013 - 03/10/2014 ``` Now i want to search these records by date range and want to see if some life exists in that range; e.g. i want to find the lives between 08/01/2013 - 01/01/2014 As expected result it should select the life#2 and life#3 How can this be done with MySQL query? Any help is highly appreciated.
This query should do it: ``` SELECT * FROM lifecycles WHERE str_to_date(life_start_date, '%m/%d/%Y') <= '2014-01-01' AND str_to_date(life_end_date, '%m/%d/%Y') >= '2013-08-01'; ``` Which basically means life hasn't started before the end of the range you are looking for, and life didn't end before the range start. Since you keep dates in VARCHAR format, you need to use str\_to\_date function, which is bad since MySQL won't be able to utilize any possible indexes you have on start\_date or end\_date columns.
This might help you. ``` SELECT SUM( IF( '2014-01-02' BETWEEN from_date AND to_date, 1, 0 ) ) AS from_exist, SUM( IF( '2014-02-12' BETWEEN from_date AND to_date, 1, 0 ) ) AS to_exist FROM date_range ``` So based on the results you can check whether date is between existing date range or not.
How to check if selected date range is between another date range
[ "", "mysql", "sql", "date", "" ]
I have the following code in my sql function: ``` if @max_chi > -999 begin INSERT INTO CH_TABLE(X1, X2, VALUE) VALUES(cur_out.sessionnumber, maxpos, max_chi) commit end ``` The following is a SQL Server 2008 Query and it gives me an error: > Invalid use of a side-effecting operator 'INSERT' within a function. Why am I not allowed to do this? What can I do to fix this?
You can't use a function to insert data *into a base table*. Functions *return* data. This is listed as [the *very first* limitation in the documentation](http://technet.microsoft.com/en-us/library/ms191320.aspx): > User-defined functions cannot be used to perform actions that modify the database state. "Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way). You should be using a stored procedure, not a function.
Disclaimer: *This is not a solution, it is more of a hack to test out something. User-defined functions cannot be used to perform actions that modify the database state.* I found one way to make insert or update using sqlcmd.exe so you need just to replace the code inside `@sql` variable. ``` CREATE FUNCTION [dbo].[_tmp_func](@orderID NVARCHAR(50)) RETURNS INT AS BEGIN DECLARE @sql varchar(4000), @cmd varchar(4000) SELECT @sql = 'INSERT INTO _ord (ord_Code) VALUES (''' + @orderID + ''') ' SELECT @cmd = 'sqlcmd -S ' + @@servername + ' -d ' + db_name() + ' -Q "' + @sql + '"' EXEC master..xp_cmdshell @cmd, 'no_output' RETURN 1 END ```
Invalid use side-effecting operator Insert within a function
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have two tables where each one contains columns with numbers. I need to compare columns in both tables and extract the number that does exist in first table, and does not exist in second one. I don't need unique value. I wrote this query: ``` SELECT Table1.Numbers, Table1.Name FROM Table1, Table2 WHERE Table1.Numbers != Table2.numbers ``` Since I am working on several million records can someone recommend more efficient query which would provide me with identical results?
I would use `NOT EXISTS`: ``` SELECT Table1.Numbers, Table1.Name FROM Table1 WHERE NOT EXISTS( SELECT 1 FROM Table2 WHERE Table1.Numbers=Table2.Numbers ) ``` Other approaches: [**Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?**](http://www.sqlperformance.com/2012/12/t-sql-queries/left-anti-semi-join)
You can do this easily by checking for the existance on the number in Table2. ``` SELECT T1.Numbers ,T1.Name FROM Table1 T1 WHERE NOT EXISTS (SELECT 1 FROM Table2 T2 WHERE T2.Numbers = T1.Numbers) ```
How to extract non-duplicate values in two tables
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a postgres table with a SERIAL id. ``` id (serial) name age ``` Insert usually happens from a web application. *I inserted manually two new records setting the id as max (id)+1*\*\*\*\* After these 2 insert when the web app inserts 2 record it gives duplicate key error. Just for 2 records. After that everything works fine. The question is - Why didn't my manual insert increment the serial? Are auto increment and serial are different? What am I missing here? Do MySQL or any other SQL have the same issue?
When you create a [`serial` or `bigserial`](http://www.postgresql.org/docs/current/interactive/datatype-numeric.html#DATATYPE-SERIAL) column, PostgreSQL actually does three things: 1. Creates an `int` or `bigint` column. 2. Creates a sequence (owned by the column) to generate values for the column. 3. Sets the column's default value to the sequence's `nextval()`. When you INSERT a value without specifying the `serial` column (or if you explicitly specify `DEFAULT` as its value), `nextval` will be called on the sequence to: 1. Return the next available value for the column. 2. Increment the sequence's value. If you manually supply a non-default value for the `serial` column then the sequence won't be updated and `nextval` can return values that your `serial` column already uses. So if you do this sort of thing, you'll have to manually fix the sequence by calling [`nextval` or `setval`](http://www.postgresql.org/docs/current/interactive/functions-sequence.html). Also keep in mind that records can be deleted so gaps in `serial` columns are to be expected so using `max(id) + 1` isn't a good idea even if there weren't concurrency problems. If you're using `serial` or `bigserial`, your best bet is to let PostgreSQL take care of assigning the values for you and pretend that they're opaque numbers that just happen to come out in a certain order: don't assign them yourself and don't assume anything about them other than uniqueness. This rule of thumb applies to all database IMO. --- I'm not certain how MySQL's `auto_increment` works with all the different database types but perhaps [the fine manual](http://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html) will help.
If you want to insert a record into the table with `serial` column - just ommit it from the query - it will be automaticaly generated. Or you can insert its defaul value with something like: ``` insert into your_table(id, val) values (default, '123'); ``` Third option is to malually take values from serial sequence directly: ``` insert into your_table(id, val) values (nextval(pg_get_serial_sequence('your_table','id')), '123'); ```
Does Postgresql SERIAL work differently?
[ "", "mysql", "sql", "postgresql", "auto-increment", "" ]
There is probably a quite simple solution to my problem, but I'm having great touble formulating a good search phrase for it. I have a table containing timestamps and counts: ``` 2013-08-15 14:43:58.447 5 2013-08-15 14:44:58.307 12 2013-08-15 14:45:58.383 14 2013-08-15 14:46:58.180 0 2013-08-15 14:47:58.210 4 2013-08-15 14:48:58.287 6 2013-08-15 14:49:58.550 12 2013-08-15 14:50:58.440 2 2013-08-15 14:51:58.390 5 ``` As you can see, the count increases and then gets emptied once in a while. Searching for the rows where count = 0 is easy, but sometimes the count is increased before the zero count has been logged. At 14:49 the count is 12, it is then reset to 0 and incremented to 2 before the next log at 14:50. I need to list the timestamps where the count is less than the count before: ``` 2013-08-15 14:46:58.180 0 2013-08-15 14:50:58.440 2 ``` I started to make a join on the table itself, to compare two rows but the SQL soon got very messy.
Also in this case you can use [LEAD()](http://technet.microsoft.com/en-us/library/hh213125.aspx) function: ``` with CTE as ( select t.*, LEAD(ct) OVER (ORDER BY dt DESC) as LEAD_CT from t ) select dt,ct from CTE where LEAD_CT>CT ``` [SQLFiddle demo](http://sqlfiddle.com/#!6/3385f/4) UPD: [LEAD()](http://technet.microsoft.com/en-us/library/hh213125.aspx) is available from version SQLServer 2012. In 2008 you can replace it with a subquery: ``` select * FROM T as T1 where (SELECT TOP 1 ct FROM T WHERE T.dt<T1.DT ORDER BY dt DESC) >CT ``` [SQLFiddle demo](http://sqlfiddle.com/#!3/3385f/3)
What this does is it creates a row number based on the ts (datetime) column, then it is easier to join to the previous entry. It then compares the times and the counts to find the exceptions. ``` ;with cte as ( select * , ROW_NUMBER() over (order by ts) rn from yourtable ) select c1.* from cte c1 inner join cte c2 on c1.rn=c2.rn+1 and c1.c < c2.c ```
Finding discontinuities from a SQL table
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I get a deadlock situation in SQL Server 2012. After running SQL Server Profiler, I got a deadlock graph as below: ![Deadlock graph](https://i.stack.imgur.com/wedO5.png) When moved mouse over the processes(oval), both processes showed identical PrepareStatement queries (I'm using JDBC). The query I'm using is as follow: ``` MERGE INTO MA4TB_MT_LOG_MSG USING (VALUES (1)) AS S(Num) ON ( MSG_ID = ? ) WHEN MATCHED THEN UPDATE SET DIST_DATE = ?, DIST_CODE = ? WHEN NOT MATCHED THEN INSERT ( MSG_ID, DIST_DATE, DIST_CODE ) VALUES ( ?,?,? ); ``` The thing that bothers me is the Index name under the Key lock resource box. I don't have an index called '1' under the MA4TB\_MT\_LOG\_MSG table. MSG\_ID is the primary key of MA4TB\_MT\_LOG\_MSG and there are no indexes on DIST\_DATE, DIST\_CODE. Any forms of advice on this deadlock situation would be appreciated. Thanks in advance,
Lets start off answering your first question. I do not have a index id = 1. Yes you do!! Let's take a look at Adventure Works 2012 database on SQL Server 2014 CTP2. This is my laptop specification. There is a table name [AWBuildVersion]. It has a clustered index just like your table. Under indexes, we can see that the PK is showing up. If we get the object id of the table (sys.objects) and lookup the entry for the index (sys.indexes), we can see that the index is at position 1. In short, a primary key by default is a clustered index. <http://technet.microsoft.com/en-us/library/ms177443(v=sql.105).aspx> ![enter image description here](https://i.stack.imgur.com/A9jtr.jpg) Okay, so what does a table without an index have? Those tables are called heaps. An they do have their own index at position zero that points to the first IAM page. <http://technet.microsoft.com/en-us/library/ms188270(v=sql.105).aspx> The code below creates a schema called [crafty] and copies the [AWBuildVersion] table to a new schema using SELECT INTO. The nice thing about SELECT INTO is that no indexes are carried over. ``` use AdventureWorks2012 go create schema [crafty] authorization [dbo]; go select * into crafty.awbuildversion from dbo.awbuildversion go ``` In short, we can see the heap defined with a index at position zero. ![enter image description here](https://i.stack.imgur.com/6HlkJ.jpg) So what is a deadlock and what does request mode U mean? A deadlock is when two processes grab resources at the same time but not in the same order. In short, both processes can not proceed. The engine picks the session with the least amount of rollback time and kills the process. <http://technet.microsoft.com/en-us/library/ms178104(v=sql.105).aspx> A picture is worth a thousand words! Transaction 1 grabs resource 1. Transaction 2 grabs resource 2. When they try to grab each others resources, a deadlock is created. ![enter image description here](https://i.stack.imgur.com/yN7MS.gif) So what does a key lock and user mode U mean? To update your table, you need to update the data/index pages. But the data pages are really index pages (clustered index) in your table. The SQL Engine takes out a (U)PDATE lock. This lock will be escalated to a exclusive lock (X) during the actual update. When two processes request a Exclusive lock, there is a potential of a deadlock. To complete this topic, shared locks (SELECT) can be executed without blocking (at the same time) Usually a process starts off blocking then turns into a deadlock when the Engines deadlock process thread detects the cyclic graph. The default isolation level is Read Uncommitted. <http://technet.microsoft.com/en-us/library/ms175519(v=sql.105).aspx> At this point, you have a deadlock. Where do you go from here? 1 - There is probably more than one session (SPID) running the same code. Why? Can you change this so that only one process runs the code at a time? 2 - Grab the actual TSQL that is being generated by JDBC. This can be done with SQL profiler and/or looking through your DMV's. The merge statement does both an UPDATE and/or INSERT. Thus a compound operation. 3 - Can you change the Isolation level to serializable? <http://technet.microsoft.com/en-us/library/ms173763.aspx> This will add more locks and probably will change your deadlock issue into a timeout issue. See Kalen Daleny article on how LOCK\_TIMEOUT can be set. You will have to adjust your code to retry the operation again with some delay in between. <http://sqlmag.com/sql-server/inside-sql-server-controlling-locking> I hope this information helps you. Please post your TSQL if you need more help.
SQL Profiler generates more information than is displayed in that chart/mouseover, and that info may or may not shed more light on your problem. Try this: * Select the rows in Profiler that causes the graph to be displayed * Do a "copy" (ctrL+C, or menu option) * Paste this into a text editor (such as an SSMS query window) * What you want are the XML contents of the Profiler "Text" column -- delete everything else * Open this XML in an XML editor (whatever you have that makes it legible, I use MIcrosoft's XML Notepad) * Drill down. It takes a bit, but once you get the hang of the layout (hierarchy, tag names, etc.) things should be clear
Deadlock graph showing unknown Index name
[ "", "sql", "sql-server", "jdbc", "deadlock", "" ]
I don't understand why I get the error, could you explain please? ``` sqlite> create table a (id text, val text); sqlite> create table b (bid text, ref text, foreign key(ref) references a(text)); sqlite> insert into a values("1", "one"); sqlite> insert into b values("1", "one"); Error: foreign key mismatch ```
I think you've got a number of things slightly strange here. I would write this as follows: ``` create table a (id text, val text, primary key(id)); create table b (bid text, ref text, foreign key (ref) references a(id)); insert into a values("1", "one"); insert into b values("one", "1"); ``` Create a primary key on A and then reference it from B; not that I reference the field name not the datatype in the foreign key. The mismatch is because you're trying to "match" `one` and `1`. You should have switched round the values in the B insert. [SQL Fiddle](http://www.sqlfiddle.com/#!7/8fb05/1)
you don't have a field called `text` in table a.. You probably meant to do: ``` sqlite> create table a (id text, val text primary key(id)); sqlite> create table b (bid text, ref text, foreign key(ref) references a(val)); sqlite> insert into a values("1", "one"); sqlite> insert into b values("1", "one"); ```
Why do I get "foreign key mismatch" error?
[ "", "sql", "sqlite", "" ]
I have the fallowing update-statement: ``` update tmp set tmp.Anzahl=(select sum(a.BNANZ) from PAYMASTER_Journal a where a.BNARTID=tmp.ArtikelAutoID), tmp.Betrag=(select sum(a.BNBETR) from PAYMASTER_Journal a where a.BNARTID=tmp.ArtikelAutoID), tmp.Rabatt=(select sum(a.BNRMRBETR) from PAYMASTER_Journal a where a.BNARTID=tmp.ArtikelAutoID) from ##tmp1 tmp ``` On this way, for each record in ##tmp1, there are 3 subqueries executed. ##tmp1 contains 10'000 records -> totaly 30'000 subqueries. Because each subquery selects the same records from PAYMASTER\_Journal, I am searching for a way, to update ##tmp1 with executing only one subquery per record in ##tmp1. I hope, someone can help me about this.
Using `LEFT JOIN` try this ``` update tmp set tmp.Anzahl=BNANZ_accumulated, tmp.Betrag=BNBETR_accumulated, tmp.Rabatt=BNRMRBETR_accumulated from ##tmp1 tmp LEFT JOIN ( SELECT BNARTID, SUM(BNANZ) AS BNANZ_accumulated, SUM(BNBETR) AS BNBETR_accumulated, SUM(BNRMRBETR) AS BNRMRBETR_accumulated FROM PAYMASTER_Journal WHERE (ARTIKELAUSWAHL=0x30 AND BLBONSTO=0x30 AND BLZESTO=0x30 AND STORNO=0x30 AND BDDAT BETWEEN '20120301' AND '20130821' AND AdressID='d68e4d8f-e60e-4482-9730-76076948df43' AND BNFIL=5 AND ISNULL(Preisliste, 'VK-Preisliste') = 'VK-Preisliste' AND BNARTID=tmp.ArtikelAutoID) GROUP BY BNARTID) a ON a.BNARTID=tmp.ArtikelAutoID ``` this will leave you `NULL` when there is no rows in `PAYMASTER_Journal` for a given ##tmp1.ArtikelAutoID if you don't want to touch them, change the `LEFT JOIN` to `INNER JOIN`
You can do it with a single sub-query as follows. ``` UPDATE tmp T INNER JOIN (SELECT a.BNARTID ,sum(a.BNANZ) as BANAZ_SUM ,sum(a.BNBETR) as BNBETR_SUM ,sum(a.BNRMRBETR) as BNRMRBETR_SUM FROM PAYMASTER_Journal a WHERE a.BNARTID = tmp.ArtikelAutoID GROUP BY a.BNARTID ) SQ ON SQ.BNARTID = tmp.ArtikelAutoID SET tmp.Anzahl = SQ.BANAZ_SUM ,tmp.Betrag = SQ.BNBETR_SUM ,tmp.Rabatt = SQ.BNRMRBETR_SUM ```
Simplify update-statement
[ "", "sql", "sql-server-2008", "sql-update", "" ]
i have the following data ``` customer_id | text | i --------------------------- 001 | hi | 0 001 | all | 1 002 | do | 0 002 | not | 0 003 | copy | 0 ``` in my query, i `group_concat` the values of text so i should get results like these ``` customer_id | text --------------------------- 001 | hi all 002 | do not 003 | copy ``` now i only want to group\_concat customer\_ids if even 1 of records had i set to 1, while i can easily do it when customer\_id 001 has both records i value set to 1 when there is only 1 that has been set i get only that the situation that would lead to the data above being like that is that at first customer 001 only had "hi" however some time later "all" is added so i now want to update the customer with this data there is a customer table that has the customer ids however i can not set an update flag on the customer id as that table has different data which takes longer to process and the data above is for a separate system my query looks like this at the time being ``` SELECT GROUP_CONCAT(text,' ') FROM table WHERE i = 1 GROUP BY customer_id ``` what would i need to do in order to get customer\_id 001 to return "hi all" when only 1 of the 2 record's i value is 1 while at the same time not getting anything from customer\_id's 002 or 003
You can concat all values, and get the total `i` value. Then you can filter by this field, knowing that if at least one of the group has a 1 it will appear ``` selec customer_id, text from (SELECT customer_id, GROUP_CONCAT(text,' ') as text, sum(i) as total FROM table WHERE i = 1 GROUP BY customer_id) T where total > 0 ```
I'm not sure what you mean by "not getting anything from customers 002 and 003". The following filters them out: ``` SELECT GROUP_CONCAT(text,' ') FROM table GROUP BY customer_id HAVING max(i) = 1; ```
group concat 2 values when clause would return only 1
[ "", "mysql", "sql", "group-by", "group-concat", "" ]
I have a problem with the following code: ``` SELECT PM.PM_Eng_Name, ISNULL(SUM(PMOutput.Quantity),0) AS TotalOut FROM PM LEFT OUTER JOIN PMOutput ON PM.PM_code = PMOutput.PM_code WHERE (PMOutput.Output_Date BETWEEN ‘2013-01-01’ AND ‘2013-08-25’) GROUP BY PM.PM_Eng_Name ``` When I run this query I got the total output only for the materials that have output transactions during the selected date rang, while I need to generate the total output for all the PM\_Eng\_Names I have, with the value 0 for the materials that have no output transaction in the selected date range Note: I got the perfect report when I remove the WHERE clause, but the date is important for my project Anyone can help me please?
To get correct results, add dates condition into `join` instead of `where` and put `isnull` inside `sum`: ``` select PM.PM_Eng_Name, sum(isnull(PMOutput.Quantity, 0)) as TotalOut from PM left outer join PMOutput on PM.PM_code = PMOutput.PM_code and PMOutput.Output_Date BETWEEN ‘2013-01-01’ AND ‘2013-08-25’ group by PM.PM_Eng_Name ```
I think that is because the 'outer joined' columns from `PMOutput` contain only null, so they are filtered by the where clause what happens with : ``` WHERE PMOutput.Output_Date is null or (PMOutput.Output_Date BETWEEN ‘2013-01-01’ AND ‘2013-08-25’) ```
select data between 2 dates in SQL
[ "", "sql", "sql-server", "" ]
Hi I have conditional clause that I am wondering can be written differently with less line of code. ``` If Exists(select id from tTest where tId=@tId) begin set @flag=1; end else begin set @flag=0; end; ``` Is there a better way to write this so it is less code and does the same work? Thanks for your help.
Assuming `@flag` is defined as a `BIT`: ``` SELECT @flag = COUNT(*) FROM dbo.tTest WHERE tId = @tId; ``` Anything but `0` will set `@flag = 1`. However, I will say that focusing on terse code is not always going to do you any favors. Do you care more about short code or fast code? Depending on indexes and cardinality, the following code - while longer - has a chance to short circuit and perform less reads than a `COUNT`: ``` SELECT @flag = CASE WHEN EXISTS (SELECT 1 FROM dbo.tTest WHERE tId = @tId) THEN 1 ELSE 0 END; ```
You also may implement it without any aggregates and predicates like "exists". Just: ``` declare @flag [bit] set @flag = 0 select @flag = 1 from tTest where tId=@tId ```
Compacting a conditional statement
[ "", "sql", "sql-server", "t-sql", "" ]
I’m fairly proficient at SQL, however this question has had myself stumped for quite a while now. In the most basic sense, there are simply two tables: ``` Items +----+--------+ | id | title | +----+--------+ | 1 | socks | | 2 | banana | | 3 | watch | | 4 | box | | 5 | shoe | +----+--------+ ``` ...and the prices table: ``` Prices +---------+-----------+-------+------------+ | item_id | vendor_id | price | created_at | +---------+-----------+-------+------------+ | 1 | 1 | 5.99 | Today | | 1 | 2 | 4.99 | Today | | 2 | 1 | 6.99 | Today | | 2 | 2 | 6.99 | Today | | 1 | 1 | 3.99 | Yesterday | | 1 | 1 | 4.99 | Yesterday | | 2 | 1 | 6.99 | Yesterday | | 2 | 2 | 6.99 | Yesterday | +---------+-----------+-------+------------+ ``` (Please note: created\_at is actually a timestamp, the words “Today” and “Yesterday” were provided merely to quickly convey the concept). My goal is to get a simple result back containing the inventory item associated with the most recent, lowest price, including the reference to the vendor\_id who is providing said price. However, I find the stumbling block appears to be the sheer number of requirements for the statement (or statements) to handle: * Each item has multiple vendors, so we need to determine which price between all the vendors for each item is the lowest * New prices for the items get appended regularly, therefore we only want to consider the most recent price for each item for each vendor * We want to roll all that up into a single result, one item per row which includes the item, price and vendor It seems simple, but I’ve found this problem to be uncanningly difficult. As a note, I’m using Postgres, so all the fanciness it provides is available for use (ie: window functions).
Much simpler with `DISTINCT ON` in Postgres: ### Current price per item for each vendor ``` SELECT DISTINCT ON (p.item_id, p.vendor_id) i.title, p.price, p.vendor_id FROM prices p JOIN items i ON i.id = p.item_id ORDER BY p.item_id, p.vendor_id, p.created_at DESC; ``` ### Optimal vendor for each item ``` SELECT DISTINCT ON (item_id) i.title, p.price, p.vendor_id -- add more columns as you need FROM ( SELECT DISTINCT ON (item_id, vendor_id) item_id, price, vendor_id -- add more columns as you need FROM prices p ORDER BY item_id, vendor_id, created_at DESC ) p JOIN items i ON i.id = p.item_id ORDER BY item_id, price; ``` [->SQLfiddle demo](http://www.sqlfiddle.com/#!12/a57ff/8) Detailed explanation: [Select first row in each GROUP BY group?](https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group/7630564#7630564)
Try this ``` CREATE TABLE #Prices ( Iid INT, Vid INT, Price Money, Created DateTime) INSERT INTO #Prices SELECT 1, 1, 5.99 ,GETDATE() UNION SELECT 1, 2, 4.99 ,GETDATE() UNION SELECT 2, 1, 6.99 ,GETDATE() UNION SELECT 2, 2, 6.99 ,GETDATE() UNION SELECT 1, 1, 3.99 ,GETDATE()-1 UNION SELECT 1, 2, 4.99 ,GETDATE()-1 UNION SELECT 2, 1, 6.99 ,GETDATE()-1 UNION SELECT 2, 2, 6.99 ,GETDATE()-1 WITH CTE AS ( SELECT MyPriority = ROW_NUMBER() OVER ( partition by Iid, Vid ORDER BY Created DESC, Price ASC) , Iid , Vid , price , Created FROM #Prices ) SELECT * FROM CTE WHERE MyPriority = 1 ```
Selecting the most recent, lowest price from multiple vendors for an inventory item
[ "", "mysql", "sql", "postgresql", "greatest-n-per-group", "distinct-on", "" ]
I have following SQL Query: ``` SELECT campaigns.* , campaign_countries.points, offers.image FROM campaigns JOIN campaign_countries ON campaigns.id = campaign_countries.campaign_id JOIN countries ON campaign_countries.country_id = countries.id JOIN offers ON campaigns.offer_id = offers.id WHERE countries.code = 'US' ``` This works perfectly well. I want its rails active record version some thing like: ``` Campaign.includes(campaign_countries: :country).where(countries: {code: "US"}) ``` Above code runs more or less correct query (did not try to include offers table), issue is returned result is collection of Campaign objects so obviously it does not include Points My tables are: ``` campaigns --HAS_MANY--< campaign_countries --BELONGS_TO--< countries campaigns --BELONGS_TO--> offers ``` Any suggestions to write AR version of this SQL? I don't want to use SQL statement in my code.
If You have campaign, You can use `campaign.campaign_countries` to get associated campaign\_countries and just get points from them. ``` > campaign.campaign_countries.map(&:points) => [1,2,3,4,5] ``` Similarly You will be able to get image from offers relation. EDIT: Ok, I guess now I know what's going on. You can use `joins` with `select` to get object with attached fields from join tables. ``` cs = Campaign.joins(campaign_countries: :country).joins(:offers).select('campaigns.*, campaign_countries.points, offers.image').where(countries: {code: "US"}) ``` You can than reference additional fields by their name on `Campaign` object ``` cs.first.points cs.first.image ``` But be sure, that additional column names do not overlap with some primary table fields or object methods. EDIT 2: After some more research I came to conclusion that my first version was actually correct for this case. I will use my own console as example. ``` > u = User.includes(:orders => :cart).where(:carts => { :id => [5168, 5167] }).first > u.orders.length # no query is performed => 2 > u.orders.count # count query is performed => 5 ``` So when You use `includes` with condition on country, in `campaign_countries` are stored only `campaign_countries` that fulfill Your condition.
I some how got this working without SQL but surely its poor man's solution: in my controller I have: ``` campaigns = Campaign.includes(campaign_countries: :country).where(countries: {code: country.to_s}) render :json => campaigns.to_json(:country => country) ``` in campaign model: ``` def points_for_country country CampaignCountry.joins(:campaign, :country).where(countries: {code: country}, campaigns: {id: self.id}).first end def as_json options={} json = { id: id, cid: cid, name: name, offer: offer, points_details: options[:country] ? points_for_country(options[:country]) : "" } end ``` and in campaign\_countries model: ``` def as_json options={} json = { face_value: face_value, actual_value: actual_value, points: points } end ``` Why this is not good solution? because it invokes too many queries: 1. It invokes query when first join is performed to get list of campaigns specific to country 2. For each campaign found in first query it will invoke one more query on campaign\_countries table to get Points for that campaign and country. This is bad, Bad and BAD solution. Any suggestions to improve this?
Rails ActiveRecord Join Query With conditions
[ "", "sql", "ruby-on-rails", "activerecord", "" ]
I have a table: ``` ID | ITEMID | STATUS | TYPE 1 | 123 | 5 | 1 2 | 123 | 4 | 2 3 | 123 | 5 | 3 4 | 125 | 3 | 1 5 | 125 | 5 | 3 ``` Any item can have 0 to many entries in this table. I need a query that will tell me if an ITEM has all it's entries in either a state of 5 or 4. For example, in the above example, I would like to end up with the result: ``` ITEMID | REQUIREMENTS_MET 123 | TRUE --> true because all statuses are either 5 or 4 125 | FALSE --> false because it has a status of 3 and a status of 5. If the 3 was a 4 or 5, then this would be true ``` What would be even better is something like this: ``` ITEMID | MET_REQUIREMENTS | NOT_MET_REQUIREMENTS 123 | 3 | 0 125 | 1 | 1 ``` Any idea how to write a query for that?
Fast, short, simple: ``` SELECT itemid ,count(status = 4 OR status = 5 OR NULL) AS met_requirements ,count(status < 4 OR status > 5 OR NULL) AS not_met_requirements FROM tbl GROUP BY itemid ORDER BY itemid; ``` Assuming all columns to be `integer NOT NULL`. Builds on [basic boolean logic](http://www.postgresql.org/docs/current/interactive/functions-logical.html): `TRUE OR NULL` yields `TRUE` `FALSE OR NULL` yields `NULL` And NULL is not counted by `count()`. [->SQLfiddle demo.](http://sqlfiddle.com/#!12/ed17f/2)
``` WITH dom AS ( SELECT DISTINCT item_id FROM items ) , yes AS ( SELECT item_id, COUNT(*) AS good_count FROM items WHERE status IN (4,5) GROUP BY item_id ) , no AS ( SELECT item_id, COUNT(*) AS bad_count FROM items WHERE status NOT IN (4,5) GROUP BY item_id ) SELECT d.item_id , COALESCE(y.good_count,0) AS good_count , COALESCE(n.bad_count,0) AS bad_count FROM dom d LEFT JOIN yes y ON y.item_id = d.item_id LEFT JOIN no n ON n.item_id = d.item_id ; ``` Can be done with an outer join, too: ``` WITH yes AS ( SELECT item_id, COUNT(*) AS good_count FROM items WHERE status IN (4,5) GROUP BY item_id) , no AS ( SELECT item_id, COUNT(*) AS bad_count FROM items WHERE status NOT IN (4,5) GROUP BY item_id) SELECT COALESCE(y.item_id, n.item_id) AS item_id , COALESCE(y.good_count,0) AS good_count , COALESCE(n.bad_count,0) AS bad_count FROM yes y FULL JOIN no n ON n.item_id = y.item_id ; ```
SQL: Get multiple line entries linked to one item?
[ "", "sql", "postgresql", "aggregate-functions", "" ]
I have 2 unique values under 1 table in MySQL. ``` |id (PK)|varchar(255) UNIQUE| ----------------------------- | 1 | 1234abcde | | 2 | 5678fghij | | 3 | 9012klmno | ``` Do I have to set UNIQUE varchar as a PK or I can still use auto\_incremented id (int)? Is this a good or bad practice?
No it does not need to be a primary key. Additionally: you cannot have more than one 'primary key' (different than compound primary keys), and it frequently makes sense to have an auto-increment id field for convention alone and for some frameworks (e.g. ORM's like Hibernate and Entity Framework). To answer your second question, there are many business cases where you many enforce a unique constraint on multiple columns without making them your primary key - for example they may have to be unique, but you may need to be able to edit/change them: i.e. 1. Email addresses for usernames - forced unique, but users will likely need to update them 2. Password salts (if your generation is sound this is unlikely to require enforcement) 3. random strings used to generate one-time or time sensitive links (think bit.ly) So, the point being this is done all the time.
No, it doesn't have to be a primary. Primaries are unique, but not every unique is a primary.
In MySQL does a UNIQUE varchar have to be a PRIMARY KEY as well?
[ "", "mysql", "sql", "" ]
I have got a little problem with SQL. I'm trying to insert 2 values into my table. that's my query: INSERT INTO tableinfo (table,date) VALUES ('Sell','24 August'); But it doesnt work. I've got something like that: ``` SQL error: ERROR: syntax near "INTO" LINE 1: SELECT COUNT(*) AS total FROM (INSERT INTO tableinfo (table,... ^ In statement:: SELECT COUNT(*) AS total FROM (INSERT INTO tableinfo (table,date) VALUES ('Sell','24 August')) AS sub ``` It's pretty basic so I don't know why it doesnt work :( PostgreSQL 9.2.4
It's not the INSERT that is the problem, it is the invalid SQL that you are trying to issue. Try your insert first then a separate count(\*) query, or if you are using PostgreSQL 9.1+ you can use [Common Table Expressions](http://www.postgresql.org/docs/current/static/queries-with.html) and RETURNING ``` WITH ins AS ( insert into tableinfo ("table","date") values ('Sell','24 August') RETURNING "table" ) select count(*) from ins; ```
I've installed phpPgAdmin to try to reproduce your error. I got it right away when tried to create a test table: ![enter image description here](https://i.stack.imgur.com/n3fmM.png) So looks like phpPgAdmin wraping your query into `select count(*) as total from (...)`. I've found that it happens only when **checkbox "Paginate results"** on query page is set to on (obviously phpPgAdmin trying to count how many rows it will get and then show it page by page). Uncheck it and your query will work fine: ![enter image description here](https://i.stack.imgur.com/z00XW.png)
INSERT INTO PostgreSQL
[ "", "sql", "postgresql", "insert", "phppgadmin", "" ]
I have difficulty understanding the correct use of the GROUP by clause in MySQL. It is used in conjunction with aggregate functions. The pattern is: ``` SELECT column1, column2, ... column_n, aggregate_function (expression) FROM tables GROUP BY column1, column2, ... column_n; ``` But what I do not understand is whether I have to list, after GROUP BY, *all* columns I did not perform an aggregate function on or not ... Is this the simple rule or did I misunderstand something? Thanks..
The answer is you can but you don't have to. A query like the following would be illegal in standerd SQL but legal in MySQL: ``` SELECT o.custid, c.name, MAX(o.payment) FROM orders AS o, customers AS c WHERE o.custid = c.custid GROUP BY o.custid; ``` but then the server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Check this link for referemce: <http://dev.mysql.com/doc/refman/5.1/en/group-by-extensions.html>
you don't *need* to do this in **Mysql**, but you will get unpredictable results for the non grouped / non aggregated columns. As stated in mysql doc : > The server is free to choose any value from each group, so unless they > are the same, the values chosen are indeterminate. But I would really suggest to list them all, as it's ANSI, mandatory int most dbms, and will give you predictable results. **Unpredictable example** Imagine a table with ``` id, code, name ``` with values ``` 1, 2, 'a'; 2, 2, 'b'; ``` if you make ``` select code, name, count(*) group by code; ``` You will have only one line returned, but could have either 'a' or 'b' as returned value for name.
MySQL: difficulty understanding GROUP BY
[ "", "mysql", "sql", "" ]
I have three tables products, properties and product\_properties. The subset of table structures and values are given below: ``` products --------------------------------------------- | id | name | description | price | --------------------------------------------- | 1 | Camera | Color Camera | 100 | | 2 | Lens 1 | Camera Lens 1 | 20 | | 3 | Lens 2 | Camera Lens 2 | 30 | --------------------------------------------- properties ------------------------------------------ | id | name | display | ------------------------------------------ | 1 | lens_mount | Lens Mount | | 2 | image_circle | Image Circle | | 3 | focal_length | Focal Length | | 4 | lens_family | Lens Family | ------------------------------------------ product_properties ------------------------------------------------ | id | value | product_id | property_id | ------------------------------------------------ | 1 | F-Mount | 2 | 1 | | 2 | C-Mount | 3 | 1 | | 3 | 42.01 mm | 2 | 2 | | 4 | 13.00 mm | 3 | 2 | | 5 | 10.00 | 2 | 3 | | 6 | 12.00 | 3 | 3 | | 7 | Standard | 1 | 4 | | 8 | Standard | 2 | 4 | | 9 | Standard | 3 | 4 | ------------------------------------------------ ``` Here is my output condition: **Find all the Lenses for Camera 1 (match camera and lens by lens\_family, which is 'Standard' here) which have lens\_mount = 'F-Mount' and image\_circle >= 40 mm and focal\_length > 5** I tried following query for this: ``` SELECT * FROM products INNER JOIN product_properties ON products.id = product_properties.product_id INNER JOIN properties ON properties.id = product_properties.property_id WHERE (product_properties.value = 'Standard') AND (properties.name = 'lens_mount' AND product_properties.value = 'F-Mount') AND (properties.name = 'image_circle' AND product_properties.value >= ABS('40 mm')) AND (properties.name = 'focal_length' AND product_properties.value >= 5) ``` However this query only gives correct result if there is only one condition. With all the conditions it doesn't give any value. I tried with OR in place of AND in the where condition but that also didn't help to get the correct output. Can anyone sortout this please. Thanks in advance.
You want to do the logic in the `having` clause rather than in the `where` clause: ``` SELECT products.id FROM products INNER JOIN product_properties ON products.id = product_properties.product_id INNER JOIN properties ON properties.id = product_properties.property_id group by products.id having sum(properties.name = 'lens_family' AND product_properties.value = 'Standard') > 0 and sum(properties.name = 'lens_mount' AND product_properties.value = 'F-Mount') > 0 and sum(properties.name = 'image_circle' AND product_properties.value >= ABS('40 mm')) > 0 and sum(properties.name = 'focal_length' AND product_properties.value >= 5) > 0; ``` You are looking for a set of properties on a single product. No single row can match all the conditions -- they conflict with each other. Instead, use the `group by` clause to bring the rows together for a given product. Then count the number of rows that match each condition. Each clause in the `having` corresponds to one of your original clauses in the `where` statement, enclosed by `sum()`. This counts the number of rows that match. The conditions ensure that there is at least one row for each property.
Ah, the dreaded EVA schema. The first think you should do is create a view to normailze the data as per the following SQL. You can then use two copies of that view (one for the camera, one for the lens) and join them together to get what you need. ``` SELECT p.id ,p.name ,pp1.value as Lens_Mount ,pp2.value as Image_Circle ,pp3.value as Focal_Length ,pp4.value as Lens_Family from products p left outer join product_properties pp1 on pp1.product_id = p.id and pp1.property_id = 1 --lens Mount left outer join product_properties pp2 on pp2.product_id = p.id and pp2.property_id = 2 --Image Circle left outer join product_properties pp3 on pp3.product_id = p.id and pp3.property_id = 3 --Focal Length left outer join product_properties pp4 on pp4.product_id = p.id and pp4.property_id = 3 --Lens Family where p.name like 'Lens%' ```
MySQL Query with multiple conditions and multiple tables
[ "", "mysql", "sql", "multiple-tables", "multiple-conditions", "" ]
I have currently working on sql server and writing a stored procedure to retrieve some data. My requirement is as follows: ``` Table A:PersonId,FirstName,LastName,Address,CourseId (Primary Key For Table B,Foreign Key Here) Table B:CourseDescription,CourseId ``` Now for each course there might be multiple student enrolled to that course. My requirement is to concatenate each student ***LastName***,***FirstName***. If there are 3 or more student in a course we have to set another flag value as 'Y' in the result. I have done with Stored proc using temp table , and updating it step by step. My stored proc is also like this: temp table has column: ``` SeqId,CourseId,CourseDescription,StudentNameConcat,IsMoreThan3 ``` First I update course id,description. Then from this table I looped based on sequence id(SeqId) and retrieve list of student name as column value and concat it in declared variable. This approach is not good because it is not a set based approach and I believe there must be an alternative approach for it in a single query using inner query or loop join.I'm still reading and trying to implement it in a single query.But still not getting any clue.
You need another table to keep track of students enrolled at every course: ``` CREATE TABLE dbo.AsocCoursePerson( AsocCoursePerson INT PRIMARY KEY, CourseID INT NOT NULL REFERENCES dbo.Course(CourseID), PersonID INT NOT NULL REFERENCES dbo.Person(PersonID) ); ``` Solution ([SQL Fiddle demo](http://www.sqlfiddle.com/#!3/416da/2)): ``` SELECT c.CourseID, c.[Description] AS CourseDescription, STUFF(oa.XmlCol.value('(/result/@PersonsFullName)[1]','NVARCHAR(MAX)'),1,1,'') AS StudentNameConcat, ISNULL(oa.XmlCol.value('(/result/@PersonsCnt)[1]','INT'),0) AS StudentsCount, CASE WHEN ISNULL(oa.XmlCol.value('(/result/@PersonsCnt)[1]','INT'),0) >= 3 THEN 'Y' ELSE 'N' END AS IsMoreThan3 FROM dbo.Course c OUTER APPLY( SELECT ( SELECT p.FirstName + ' ' + p.LastName AS PersonFullName FROM dbo.AsocCoursePerson asoc JOIN dbo.Person p ON asoc.PersonID = p.PersonID WHERE asoc.CourseID = c.CourseID FOR XML RAW('row'), TYPE ).query(' <result PersonsFullName="{for $p in /row return concat(",",$p/@PersonFullName)}" PersonsCnt="{count(/row)}" /> ') XmlCol ) oa; ```
``` select c.CourseId, c.CourseDescription, stuff( ( select ', ' + s.FirstName + ' ' + s.LastName from Students as s where s.CourseId = c.CourseId for xml path(''), type ).value('.', 'nvarchar(max)') , 1, 2, '') as Students, case when (select count(*) from Students as s where s.CourseId = c.CourseId) >=3 then 'y' else 'n' end as flag from Courses as c ``` A brief explanation. First, you concat you strings into xml, but name is empty and element data is `', ' + s.FirstName + ' ' + s.LastName`. After that, you taking this xml as nvarchar(max) with `value` method (this will keep all special characters in names, like `&` or `>`). After that, you'll have your name concatenated, but you'll have a comma before, so you need to cut it, using [stuff](http://technet.microsoft.com/en-us/library/ms188043.aspx) function. [**`sql fiddle demo`**](http://sqlfiddle.com/#!3/32f3c/5)
Nested Single Query for concatenation of specific column in multiple row in single column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am formalating a query to give the number of reports submitted over the last year ordered by date. I get the current year and month with php: ``` $year = date('Y') - 1; $month = date('m'); ``` and execute the following query: SQL: ``` SELECT month(date_lm) AS `month` , count(*) AS `count` FROM `reports` WHERE (status = 'submitted') AND (date_lm > 2012-08) GROUP BY month(date_lm) ORDER BY month(date_lm) ASC ``` And because there has only been 1 submitted in the last year it gives me only 1 result... ``` | month | count | | 7 | 1 | ``` But I would like the result set to show: ``` | month | count | | 9 | 0 | | 10 | 0 | | 11 | 0 | | 12 | 0 | | 1 | 0 | | 2 | 0 | | 3 | 0 | | 4 | 0 | | 5 | 0 | | 6 | 0 | | 7 | 1 | | 8 | 0 | ``` Is that possible?
You should LEFT JOIN this table with 1..12 table. Something like this: ``` 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 ``` [SQL Fiddle demo](http://sqlfiddle.com/#!8/257e8/2)
In order to do this, you could create a 'month' table and then use a left outer join between that table and the reports table. I've never used mysql so apologies if the syntax is slightly off, but this would be the query: ``` SELECT months.monthNumber, count(reports.id) AS `count` FROM `months` left outer join `reports` on months.monthNumber = month(reports.date_lm) WHERE (status = 'submitted') AND (date_lm > 2012-08) GROUP BY monthNumber ORDER BY monthNumber ASC ``` Importantly, the count should be of a column in the reports table, not the months table, or else you would never get a zero.
How to get a count even if there are no results corresponding mysql?
[ "", "mysql", "sql", "" ]
I have **two Tables** as below.. 1. tbPatientEncounter 2. tbVoucher when i execute `select query` as below ``` Select EncounterIDP,EncounterNumber from tbPatientEncounter ``` ![enter image description here](https://i.stack.imgur.com/BAsIi.png) it returens me 180 rows. and Select VoucherIDP,EncounterIDF from tbVoucher ![enter image description here](https://i.stack.imgur.com/GX0IO.png) above query returns me 165 rows. but i want to execute select query that returns me data like EncounterIDP not in tbVoucher, for that i have tried below Select query... ``` Select * from tbPatientEncounter pe where pe.EncounterIDP not in (Select v.EncounterIDF from tbVoucher v ) ``` it doesn't returns any row. in first image it shows `EncounterIDP 9 in tbPatientEncounter`, but it not inserted in tbVoucher for that i have tried select Query like ``` Select * from tbVoucher where EncounterIDF = 9 ``` it returns me 0 rows. My question is `what is wrong with my above Not In Query.?`
In all likelihood, the problem is `NULL` values in `tbVoucher`. Try this: ``` Select * from tbPatientEncounter pe where pe.EncounterIDP not in (Select v.EncounterIDF from tbVoucher v where v.EncounterIDF is not NULL ) ```
Are you comparing the correct fields in tbVoucher? Try using a left join ``` Select EncounterIDP,EncounterNumber from tbPatientEncounter left join tbVoucher on EncounterIDP = EncounterIDF where EncounterIDF is null ```
select query with Not IN keyword
[ "", "sql", "sql-server", "select", "notin", "" ]
This is my first question here. Scenario: I have a list of newspapers, say: ``` NYT NJYT CIT DIT ABC DEF GHI ``` Each newspaper has several editions depending on the region of publication. For eg, ``` 1. NYT has michigan, atlanta, chicago, newyork, arizona..c 2. NJYT has florida, california, washington, michigan, atlanta, chicago, newyork 3. and so on........ ``` Requirement: I want to group multiple editions under each newspaper and store it in the database. How can I achieve this? Currently, I have a table named Publications with the following columns: ``` JournalID varchar(10) JournalFullName varchar(50) JournalShortName varchar(20) Language varchar(20) [No of Editions] int Since_Year date City_of_Origin varchar(50) ``` I'm very new to SQL. Any help would be greatly appreciated? Thanks,
You want to have a separate editions table, something like: ``` create table Editions ( EditionsId int not null identity(1, 1) primary key, JournalId varchar(10) references Publications(JournalId), EditionName varchar(255), . . . ) ```
You can create an edition table referencing the Journal table, so that you can have multiple editions for a journal. Something close to; ``` CREATE TABLE Edition ( EditionId INT IDENTITY(1,1) PRIMARY KEY, JournalId VARCHAR(10) FOREIGN KEY REFERENCES Publication(JournalId), EditionName VARCHAR(50) ); ``` This lets an edition reference a publication, which means that you can have multiple editions referencing the *same* publication. This is also known as a [one-to-many relationship](http://www.techopedia.com/definition/25122/one-to-many-relationship).
How To Store/Manage Multiple Values Under Single Value In SQL
[ "", "sql", "sql-server", "" ]
I want to create a references to foreign table. but i'm getting the following error: query: ``` CREATE TABLE category_ids (id INT, post_id INT, INDEX par_ind (post_id), FOREIGN KEY (post_id) REFERENCES post(id) ON DELETE CASCADE ) ENGINE=INNODB; ``` SHOW ENGINE INNODB STATUS\G: ``` ------------------------ LATEST FOREIGN KEY ERROR ------------------------ 2013-08-23 00:11:06 7f6f49e7b700 Error in foreign key constraint of table fun/category_ids: FOREIGN KEY (post_id) REFERENCES post(id) ON DELETE CASCADE ) ENGINE=INNODB: Cannot resolve table name close to: (id) ON DELETE CASCADE ) ENGINE=INNODB ``` posts table structure ``` mysql> describe post; +-------------+-----------------------+------+-----+---------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-----------------------+------+-----+---------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | ... +-------------+-----------------------+------+-----+---------------------+----------------+ 22 rows in set (0.00 sec) ```
Only InnoDB supports Foreign keys, MyISAM doesn't. Even if it would, you cannot create relations between tables of different type. Therefore you need to convert the table `post` into InnoDB. `ALTER TABLE post ENGINE = InnoDB;`
This error can also come when parent table is partitioned. Removing partitioning from the parent table allows foreign constraint to be created without any problem.
Cannot resolve table name close to
[ "", "mysql", "sql", "reference", "" ]
So I have a parameter. Lets say: ``` @Tags = 'Red,Large,New' ``` I have a field in my table called [Tags] Lets say one particular row that field contains "Red,Large,New,SomethingElse,AndSomethingElse" How can I break that apart to basically achieve the following logic, which I'll type for understanding but I know is wrong: ``` SELECT * FROM MyTable WHERE Tags LIKE 'FirstWordInString' AND Tags Like 'SecondWordInString' AND Tags Like 'ThirdWordInString' ``` But it knows where to stop? Knows if there's just one word? Or two? Or three? Workflow: Someone clicks a tag and the dataset is filtered by that tag. They click another and the tag is appended to the search box and the dataset is then filtered by both of those tags, etc. Thank you! Update: This is a product based situation. 1. When a product is created the creator can enter search tags separated by commas. 2. When the product is inserted, the search tags are inserted into a separate table called ProductTags (ProductID, TagID) So, in the Product table, I have a field that has them separated by string for display purposes in the application side, and these same tags are also found in the ProductTag table separated by row based on ProductID. What I'm not understanding is how to place the condition in the select that delivers results if all the tags in the search exist for that product. I thought it would be easier to just use the comma separated field, but perhaps I should be using the corresponding table (ProductTags)
One relational division approach using the `ProductTags` table is ``` DECLARE @TagsToSearch TABLE ( TagId VARCHAR(50) PRIMARY KEY ) INSERT INTO @TagsToSearch VALUES ('Red'), ('Large'), ('New') SELECT PT.ProductID FROM ProductTags PT JOIN @TagsToSearch TS ON TS.TagId = PT.TagId GROUP BY PT.ProductID HAVING COUNT(*) = (SELECT COUNT(*) FROM @TagsToSearch) ``` The `@TagsToSearch` table would ideally be a table valued parameter passed directly from your application but could also be populated by using a split function against your comma delimited parameter.
You just need to add wildcards: ``` SELECT * FROM MyTable WHERE ','+Tags+',' LIKE '%,FirstWordInString,%' AND ','+Tags+','Like '%,SecondWordInString,%' AND ','+Tags+','Like '%,ThirdWordInString,%' ``` UPDATE: I understand now the problem is that you have a variable you are trying to match the tags to. The variable has the string list of tags. If you split the list of user selected tags using a split string function, or can get the user selected tags from input form separately, then you can just use: ``` SELECT * FROM MyTable WHERE ',,'+Tags+',' LIKE '%,'+@tag1+',%' AND ',,'+Tags+',' LIKE '%,'+@tag2+',%' AND ',,'+Tags+',' LIKE '%,'+@tag3+',%' AND ',,'+Tags+',' LIKE '%,'+@tag4+',%' ``` etc. This will work for any number of entered tags, as an empty `@tag` would result in the double comma appended to the tags field matching `'%,,%'`.
I need to use a comma delimited string for SQL AND condition on each word
[ "", "sql", "sql-server", "relational-division", "" ]
i have 3 table. 1st is for user info. 2nd is for post where user insert to it and relation with user table by user\_id. 3rd is for user who i follow him and relation with user table by user\_id. now in home page i need to show all posts where i insert on it and where user i follow him insert into table post. i will try to make this MySQL by :- ``` SELECT * FROM users , (SELECT * FROM events where ev_user_id in ( ( select * from follow where follow.fo_user_id = '".$user_id."' ) , '".$user_id."' ) ) as post where post.ev_user_id = users.id order by post.ev_date DESC limit $to , $from ``` where `$user_id` is id for user. here i get error that:- ``` Operand should contain 1 column(s) ``` if i follow one user its work, but when i follow more than one user, its display above error. how can i get all post for me and for user who i follow him ==================================== events table is the table for post ``` CREATE TABLE `events` ( `ev_id` int(11) NOT NULL auto_increment, `ev_user_id` int(11) NOT NULL, `ev_type` varchar(222) NOT NULL, `ev_text` text NOT NULL, `ev_pic` varchar(222) NOT NULL, `ev_date` varchar(22) NOT NULL, PRIMARY KEY (`ev_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=211 ; ``` table for user which i follow him ``` CREATE TABLE `follow` ( `fo_id` int(11) NOT NULL auto_increment, `fo_user_id` int(11) NOT NULL, `fo_user_id_follow` int(11) NOT NULL, `fo_date` varchar(22) NOT NULL, PRIMARY KEY (`fo_id`), UNIQUE KEY `fo_user_id` (`fo_user_id`,`fo_user_id_follow`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=15 ; ``` table for user info ``` CREATE TABLE `users` ( `id` bigint(20) unsigned NOT NULL auto_increment, `fullname` varchar(222) NOT NULL, `username` varchar(60) NOT NULL, `password` varchar(64) NOT NULL, `email` varchar(50) NOT NULL, `address` varchar(300) NOT NULL, `phone` varchar(20) NOT NULL, `skype` varchar(20) NOT NULL, `facebook` varchar(40) NOT NULL, `msn` varchar(90) NOT NULL, `mobile` varchar(20) NOT NULL, `more` text NOT NULL, `time` varchar(50) NOT NULL, `lastlogin` varchar(50) NOT NULL, `role_id` tinyint(1) NOT NULL default '2', `code` varchar(7) NOT NULL, `active` tinyint(4) NOT NULL default '3', `wieght` int(11) NOT NULL, `tall` int(11) NOT NULL, `birthdate` varchar(20) NOT NULL, `gender` varchar(5) NOT NULL, `fat` int(11) NOT NULL, `fittnes` int(11) NOT NULL, `status` int(11) NOT NULL, `pic` varchar(222) NOT NULL, `regdate` varchar(22) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`), UNIQUE KEY `username` (`username`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=396 ; ```
This should get you the posts and user info of the users your $user\_id follows ordered by descending date. ``` SELECT * FROM events JOIN follow ON events.ev_user_id = follow.fo_user_id JOIN users ON events.ev_user_id = user.id WHERE follow.fo_user_id_follow = '".$user_id."' ORDER BY events.ev_date DESC LIMIT $to , $from ``` Is this what you wanted? not completelly sure. EDIT: to add also your own posts as well as the ones form the users you follow. ``` SELECT * FROM events JOIN follow ON events.ev_user_id = follow.fo_user_id JOIN users ON events.ev_user_id = user.id WHERE follow.fo_user_id_follow = '".$user_id."' OR events.ev_user_id = '".$user_id."' ORDER BY events.ev_date DESC LIMIT $to , $from ``` EDIT: the enquirer's exact solution, Daren had understood the follow relationship reversed. ``` SELECT * FROM events JOIN follow ON events.ev_user_id = follow.fo_user_id_follow JOIN users ON events.ev_user_id = users.id WHERE follow.fo_user_id = '".$user_id."' OR events.ev_user_id = '".$user_id."' ORDER BY events.ev_date DESC LIMIT $to , $from" ```
The error message you're getting, is because you're using the IN operator against a subquery that returns more than one column. Maybe rewrite your SQL to something like this: ``` SELECT * FROM users , (SELECT * FROM events where ev_user_id in ( ( select user_id from follow where follow.fo_user_id = '".$user_id."' ) , '".$user_id."' ) ) as post where post.ev_user_id = users.id order by post.ev_date DESC limit $to , $from ```
how can i get all post for me and for user who i follow him
[ "", "mysql", "sql", "" ]
I have a table in the database which consists of some postcodes with their latitude and longitude for example: ``` Id PostCode Latitude Longitude 1 ll29 8ht 53.2973289489746 -3.72970223426819 ``` The table is generated by MVC code-first application, Latitude and longitude data type is real I have a stored procedure that takes as input searchLatitude and searchLongitude and then calculates the distances: ``` CREATE PROCEDURE [dbo].[StockistSearch] @searchLat float = 0, @searchLng float = 0 AS BEGIN SET NOCOUNT ON; SELECT top 40 s.Id as Id, a.Company as Company, a.FirstName as FirstName, a.LastName as LastName, a.Address1 as Address1, a.Address2 as Address2, a.City as City, a.ZipPostalCode as ZipPostalCode, a.PhoneNumber as PhoneNumber, a.FaxNumber as FaxNumber, a.Email as Email, s.latitude as Latitude, s.longitude as Longitude, ( 3959 * acos( cos( radians(@searchLat) ) * cos( radians( s.latitude ) ) * cos( radians( s.longitude ) - radians(@searchLng) ) + sin( radians(@searchLat) ) * sin( radians( s.latitude ) ) ) ) AS Distance FROM Stockist s, Customer c, Address a where s.CustomerId = c.Id and c.ShippingAddress_Id = a.Id ORDER BY distance END ``` If I execute this through SQL server management studio, it executes the following: ``` DECLARE @return_value int EXEC @return_value = [dbo].[StockistSearch] @searchLat = 53.29, @searchLng = -3.72 SELECT 'Return Value' = @return_value GO ``` Which return the distance correctly (0.645 miles) However, when executed through the application using : ``` var result = this.Database.SqlQuery<TEntity>(commandText, parameters).ToList(); ``` which according to a trace, executes: ``` exec sp_executesql N'StockistSearch',N'@searchLat float,@searchLng float',@searchLat=53.29,@searchLng=-3.72 ``` which results in a completely different (and wrong) result for the calculated distance, (it returns distance 3688.96 miles!) I've stepped through the code in debug and the parameters are being entered correctly and have confirmed that the exec sp\_executesql is giving a different result that the EXEC when ran directly in the SQL server management studio I'm completely at a loss as to why this is happening and although the stored procedure seems to be functioning correctly, the results showing through the application are completely wrong. Please can someone please give me some advice before I go mad!! Thanks # UPDATE Thanks for all the comments so far and thanks to @McKay, I've narrowed it down to it ignoring the input parameters when called from exec sp\_executesql and is using the defaults 0 for both latitude and longitude. If i remove the defaults, I get the error: ``` Procedure or function 'StockistSearch' expects parameter '@searchLat', which was not supplied. ``` The SQL query is ``` exec sp_executesql N'StockistSearch', N'@searchLat real, @searchLng real',@searchLat=53.29,@searchLng=-3.72 ``` This sql is automatically generate by the entity framework (code-first MVC EF doesn't currently support stored procedures but should be able to query stored procedures using the following in the DbContext:) ``` var result = this.Database.SqlQuery<TEntity>(commandText, parameters).ToList(); ``` Would greatly appreciate any further help # FIXED :-) When calling : ``` var result = this.Database.SqlQuery<TEntity>(commandText, parameters).ToList(); ``` The command text has to have the parameters appended to it so ``` commandText = "StockistSearch @searchLat,@searchLng" ``` so the resulting sql is; ``` exec sp_executesql N'StockistSearch @searchLat,@searchLng', N'@searchLat real, @searchLng real',@searchLat=53.29,@searchLng=-3.72 ``` It now accepts the input parameters and calculates the correct distance
Numbers that are this different make me think that maybe it's using the default values for something? Have you taken out the defaults? Maybe you could also add the parameters to the select, to make sure you get what you're expecting. ``` SELECT top 40 @searchLatitude, @searchLongitude, l.Id as Id, l.Postcode as Postcode, l.latitude as Latitude, l.longitude as Longitude, ``` This might aid in your debugging process.
The difference is in how it's called. Your SSMS call returns the return value. Your `sp_executesql` call returns the dataset. I'm guessing the 40th closest stockist is 3688.96 miles away
Different results from executing a stored procedure using exec sp_executesql compared to EXEC
[ "", "sql", "sql-server", "entity-framework", "stored-procedures", "" ]
I am writing a program that recovers structured data as individual records from a (damaged) file and collects the results into a sqlite database. The program is invoked several times with slightly different recovery parameters. That leads to recovering often the same, but sometimes different data from the file. Now, every time I run my program with different parameters, it's supposed to add just the newly (different) found items to the same database. That means that I need a fast way to tell if each recovered record is already present in the DB or not, in order to add them only if they're not existing in the DB yet. I understand that for each record I want to add, I could first do a SELECT for all columns to see if there is already a matching record in the DB, and only add the new one if no same is found. But since I'm adding 10000s of records, doing a SELECT for each of these records feels pretty inefficient (slow) to me. I wonder if there's a smarter way to handle this? I.e, is there a way I can tell sqlite that I do not want duplicate entries, and so it automatically detects and rejects them? I know about the UNIQUE modifier, but that's not it because it applies to single columns only, doesn't it? I'd need to be able to say that the combination of COL1+COL2+COL3 must be unique. Is there a way to do that? Note: I never want to update any existing records. I only want to collect a set of different records. ***Bonus part - performance*** In a classic programming language, I'd use a key-value dictionary where the key is the sum of all a record's values. Similarly, I could calculate a Hash code for each added record and look that hash code up first. If there's no match, then the record is surely not in the DB yet; If there is a match I'd still have to search the DB for any duplicates. That'd surely be faster already, but I still wonder if sqlite can make this more efficient.
You could use UNIQUE column constraint or to declare a multiple columns unique constraint you can use [UNIQUE () ON CONFLICT](http://www.sqlite.org/lang_conflict.html) : ``` CREATE TABLE name ( id int , UNIQUE (col_name1 type , col_name2 type) ON CONFLICT IGNORE ) ``` *SQLite has two ways of expressing uniqueness constraints: PRIMARY KEY and UNIQUE. Both of them create an index and so the lookup happens through the created index.*
Try: ``` sqlite> create table foo ( ...> a int, ...> b int, ...> unique(a, b) ...> ); sqlite> sqlite> insert into foo values(1, 2); sqlite> insert into foo values(2, 1); sqlite> insert into foo values(1, 2); Error: columns a, b are not unique sqlite> ```
How to prevent adding identical records to SQL database
[ "", "sql", "sqlite", "" ]
I have this query: ``` select feature_requests.*, from feature_requests where feature_requests.status in ('open','closed','indevelopment') ``` I also have another status - denied. I need to also select all rows with status denied but another column on my features request table must equal something. So something that does this: ``` select feature_requests.*, from feature_requests where feature_requests.status in ('open','closed','indevelopment','denied') and if status = denied, instance_id = ? ``` Not sure of the correct syntax. Thanks for any help :)
The WHERE clause is the correct place to put these kind of conditions, but with a few differences: ``` SELECT `fr`.* FROM `feature_requests` fr WHERE (`fr`.`status` IN ('open','closed','indevelopment')) OR ((`fr`.`status` = 'denied') AND (`fr`.`instance_id` = ?)) ``` P.S - Notice I'm using an alias for `feature_requests` called `fr` instead of writing the whole name again and again. And You don't have to write its name at all because you're using only one table in your query, but I would still use it because it reduces the chances of future mistakes. For further reading - [SELECT Syntax](http://dev.mysql.com/doc/refman/5.0/en/select.html)
This should work: ``` SELECT feature_requests.* FROM feature_requests WHERE feature_requests.status IN ('open','closed','indevelopment') OR ( feature_requests.status='denied' AND instance_id=? ) ``` This can also be written without listing the table name over and over if it is the only table that you are using like this: ``` SELECT * FROM feature_requests WHERE status IN ('open','closed','indevelopment') OR ( status='denied' AND instance_id=? ) ``` When using `AND` and/or `OR` in your where clause please also remember to use parenthesis `(` `)` to show your actual meaning even when you know what takes precedence between the `AND` and `OR`. [For more information on precedence of operators with MySQl](http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html) Example: ``` color=blue AND shape=circle OR type=ball ``` means ``` (color=blue AND shape=cirlce) OR type=ball ``` but could easily be misinterpreted as ``` color=blue AND (shape=circle OR type=ball) ```
MYSQL - Select selecting rows where another column equals something
[ "", "mysql", "sql", "" ]
I'm trying to add a new column to an existing table, where the value is the row number/rank. I need a way to generate the row number/rank value, and I also need to limit the rows affected--in this case, the presence of a substring within a string. Right now I have: ``` UPDATE table SET row_id=ROW_NUMBER() OVER (ORDER BY col1 desc) FROM table WHERE CHARINDEX('2009',col2) > 0 ``` And I get this error: ``` Windowed functions can only appear in the SELECT or ORDER BY clauses. ``` (Same error for `RANK()`) Is there any way to create/update a column with the ROW\_NUMBER() function? FYI, this is meant to replace an incorrect, already-existing "rank" column.
You can do this with a CTE, something like: ``` with cte as ( select * , new_row_id=ROW_NUMBER() OVER (ORDER BY col1 desc) from MyTable where charindex('2009',col2) > 0 ) update cte set row_id = new_row_id ``` [SQL Fiddle with demo](http://sqlfiddle.com/#!3/45b11d/2).
If you are only updating a few thousand rows, you could try something like this: ``` select 'UPDATE MyTable SET ID = ' + CAST(RowID as varchar) + ' WHERE ID = ' + CAST(ID as varchar) From ( select MyTable, ROW_NUMBER() OVER (ORDER BY SortColumn) RowID from RaceEntry where SomeClause and SomeOtherClause ) tbl ``` Copy and paste the query results into the query editor and run. It's a bit sluggish and yukky bit it works.
How to add row number column in SQL Server 2012
[ "", "sql", "sql-server", "ranking", "row-number", "ranking-functions", "" ]
I have table having two column 1) ProductId(int) 2) PublishDate(varchar) data is like following ``` ProductId PublishDate 73 22/01/97 56 17/09/90 56 01/09/90 69 15/05/13 69 09/05/13 ``` I have to get record from this table but in PublishDate Order by Desc, as PublishDate is varchar, I am not able to do this can anyone please help me for this. I have tried following query: ``` SELECT T.ProductId, T.MYDATE FROM ( SELECT ProductId, CONVERT(varchar(max), PublishDate , 101) AS MYDATE FROM DateValidation ) T ORDER BY T.MYDATE DESC ```
**[Here is the SQLFIddel Demo](http://sqlfiddle.com/#!3/e843b/13)** **below is the Query Which You can try** ``` Select ProductId, Convert(Date,substring(PublishDate,4,3) + substring(PublishDate,1,3) + substring(PublishDate,7,2)) From DateValidation Order By 2 Desc ```
Yo don't need to change date format because it is stored in your needed format ( it is stored as varchar, this is a **dirty** pattern). But your issue is sorting by date. To sort by calendar date **you need to convert varchar to a valid date**: ``` SELECT ProductId, PublishDate FROM DateValidation ORDER BY CONVERT(DATE, PublishDate, 103) desc ``` **I encourage to you to store dates in a date format but varchar.**
Converting date in DD/MM/YY formate and order by it
[ "", "sql", "sql-server", "" ]
my table ``` +------+-------+---------+-------+--------+ | Name | Group1| Section | Marks | Points | +------+-------+---------+-------+--------+ | S1 | G1 | class1 | 55 | | | S16 | G1 | class1 | 55 | | | S17 | G1 | class1 | 55 | | | S28 | | class1 | 55 | | | S2 | | class2 | 33 | | | S3 | | class1 | 25 | | | S4 | G88 | class2 | 65 | | | S5 | G88 | class2 | 65 | | | S30 | G66 | class2 | 66 | | | S31 | G66 | class2 | 66 | | | S32 | | class1 | 65 | | | S7 | G5 | class1 | 32 | | | S18 | G5 | class1 | 32 | | | S19 | G5 | class1 | 32 | | | S33 | G4 | class2 | 60 | | | S34 | G4 | class2 | 60 | | | S35 | G4 | class2 | 60 | | | S10 | | class2 | 78 | | | S8 | G8 | class1 | 22 | | | S20 | G8 | class1 | 22 | | | S21 | G8 | class1 | 22 | | | S9 | | class2 | 11 | | | S12 | | class3 | 43 | | | S22 | G9 | class1 | 20 | | | S23 | G9 | class1 | 20 | | | S24 | G9 | class1 | 20 | | | S13 | G55 | class2 | 33 | | | S36 | G55 | class2 | 33 | | | S14 | | class2 | 78 | | | S25 | G10 | class1 | 55 | | | S26 | G10 | class1 | 55 | | | S27 | G10 | class1 | 55 | | +------+-------+---------+-------+--------+ ``` SQL FIDDLE : <http://www.sqlfiddle.com/#!2/5ce6c/1> I am trying to give specific points to first 3 groups with highest marks in each Section. I would like to add 5 points to each student in the 1st highest groups, 3 points for 2nd highest and 1 points for 3rd highest group. .Duplicate Marks may occur for group. I am using following code, this code works fine for individual students, dont know how to give points to the Group. ``` select t1.Name, t1.Section, t1.Marks from myTable t1 join (select Section, substring_index(group_concat (distinct Marks order by Marks desc), ',', 3) as Marks3 from myTable where Section = 'class1' group by Section ) tsum on t1.Section = tsum.Section and find_in_set(t1.Marks, tsum.Marks3) > 0 ORDER BY Section, Marks DESC, ID Desc ``` My final output looks for a Section. ``` +---------------------------------------------+ | | Name | Group1| Section | Marks | Points | | +---------------------------------------------+ | | S1 | G1 | class1 | 55 | 5 | | | | S16 | G1 | class1 | 55 | 5 | | | | S17 | G1 | class1 | 55 | 5 | | | | S28 | | class1 | 55 | | | | | S2 | | class2 | 33 | | | | | S3 | | class1 | 25 | | | | | S4 | G88 | class2 | 65 | | | | | S5 | G88 | class2 | 65 | | | | | S30 | G66 | class2 | 66 | | | | | S31 | G66 | class2 | 66 | | | | | S32 | | class1 | 65 | | | | | S7 | G5 | class1 | 32 | 3 | | | | S18 | G5 | class1 | 32 | 3 | | | | S19 | G5 | class1 | 32 | 3 | | | | S33 | G4 | class2 | 60 | | | | | S34 | G4 | class2 | 60 | | | | | S35 | G4 | class2 | 60 | | | | | S10 | | class2 | 78 | | | | | S8 | G8 | class1 | 22 | 1 | | | | S20 | G8 | class1 | 22 | 1 | | | | S21 | G8 | class1 | 22 | 1 | | | | S9 | | class2 | 11 | | | | | S12 | | class3 | 43 | | | | | S22 | G9 | class1 | 20 | | | | | S23 | G9 | class1 | 20 | | | | | S24 | G9 | class1 | 20 | | | | | S13 | G55 | class2 | 33 | | | | | S36 | G55 | class2 | 33 | | | | | S14 | | class2 | 78 | | | | | S25 | G10 | class1 | 55 | 5 | | | | S26 | G10 | class1 | 55 | 5 | | | | S27 | G10 | class1 | 55 | 5 | | +---------------------------------------------+ ``` Please help me.
I have found a solution to list the groups with their allocated points but I was having a hard time storing the result back into `myTable`, i.e. doing an `UPDATE` on the table. I managed at last (**see bottom of post!!**). But first, here is the group score-table generator (group overview): ``` SELECT mg,ms,mm, CASE WHEN @s=ms THEN CASE WHEN @m=mm THEN @i WHEN @i>2 THEN @i:=@i-2 ELSE null END ELSE @i:=5 END pt, @g:=mg gr,@s:=ms,@m:=mm FROM ( SELECT group1 mg,section ms,max(marks) mm FROM mytable WHERE group1>'' GROUP BY group1,section ) m ORDER BY ms,mm desc,mg ``` <http://sqlfiddle.com/#!2/bea2a2/1> It gives me this list: ``` | MG | MS | MM | PT | GR | @S:=MS | @M:=MM | ------------------------------------------------------ | G1 | class1 | 55 | 5 | G1 | class1 | 55 | | G10 | class1 | 55 | 5 | G10 | class1 | 55 | | G5 | class1 | 32 | 3 | G5 | class1 | 32 | | G8 | class1 | 22 | 1 | G8 | class1 | 22 | | G9 | class1 | 20 | (null) | G9 | class1 | 20 | | G66 | class2 | 66 | 5 | G66 | class2 | 66 | | G88 | class2 | 65 | 3 | G88 | class2 | 65 | | G4 | class2 | 60 | 1 | G4 | class2 | 60 | | G55 | class2 | 33 | (null) | G55 | class2 | 33 | ``` I **am** back (26.08.2013, after having asked for help myself, see [here](https://stackoverflow.com/questions/18429863)) and can now provide the **full answer**: ``` SET @s:=@m:=@i:='a'; -- variables *MUST* be "declared" in some -- way, otherwise UPDATE will not work! UPDATE mytable INNER JOIN (SELECT mg,ms,mm, CASE WHEN @s=ms THEN CASE WHEN @m=mm THEN @i WHEN @i>2 THEN @i:=@i-2 ELSE null END ELSE @i:=5 END pt, @s:=ms,@m:=mm FROM ( SELECT group1 mg,section ms,max(marks) mm FROM mytable WHERE group1>'' GROUP BY group1,section ) m ORDER BY ms,mm desc,mg ) t ON mg=group1 AND ms=section AND mm=marks SET Points=pt ``` see here <http://sqlfiddle.com/#!2/bb7f2> And finally - off-topic: Dear user @user2594154, why have you bombarded this board with the *same* question **8 times**?!? * Add specific points on highest marks Find sum of points and grouping * First three Groups with Highest Marks should have specific points (**this post**) * Grouping results by name and points Group each Sections by Points and * CompetitionName descending order Find highest points of two students * in a section Display 3 Maximum values of a Column, include duplicate * values with condition First three Groups with Highest Marks should * have specific points 5,3, 1 [duplicate] It would be much more helpful for everybody if you had kept your question in **one** post, explaining *exactly what you want* and also *what you have tried yourself* (!!). Then, in the course of the answering process, it is possible to edit it, making it more precise. New questions should only be posted, if their subject is actually *different*, see [here](https://stackoverflow.com/help/duplicates). No hard feelings - I learnt a lot in the process of solving this problem of yours. ;-)
That was challenging. To solve it I used several methods: 1. A [CASE statement](http://dev.mysql.com/doc/refman/5.0/en/case-statement.html) to convert the group's place in the top 3 into points. 2. [Rows numbering](https://stackoverflow.com/questions/3126972/mysql-row-number) with a *variable*. 3. *INNER* AND *LEFT* [JOIN](http://dev.mysql.com/doc/refman/5.0/en/join.html) to merge the results together. The following query was tested on your fiddle and works: ``` SELECT t1.`id`, t1.`name`, t1.`group1`, t1.`section`, t1.`MARKS`, `t_group_points`.`points` FROM `students` t1 #--- Join groups' points to the students LEFT JOIN ( ( #---- Join all groups and give points to top 3 avg's groups ---- SELECT `t4`.`group1`, `t_points`.`points` FROM (SELECT `t3`.`group1`, AVG(`t3`.`marks`) AS `avg` FROM `students` `t3` WHERE (`t3`.`section` = 'class1') AND (`t3`.`group1` IS NOT NULL) GROUP BY `t3`.`group1`) `t4` INNER JOIN ( #---------- Select top 3 avarages ---------- (SELECT `top`.`avg`, #-- Convert row number to points --- CASE @curRow := @curRow + 1 WHEN '1' THEN 5 WHEN '2' THEN 3 WHEN '3' THEN 1 ELSE NULL END 'points' FROM (SELECT DISTINCT `t_avg`.`avg` FROM (SELECT `t2`.`group1`, AVG(`t2`.`marks`) AS `avg` FROM `students` `t2` WHERE (`t2`.`section` = 'class1') AND (`t2`.`group1` IS NOT NULL) GROUP BY `group1`) `t_avg` ORDER BY `avg` DESC LIMIT 0, 3) `top`, (SELECT @curRow:=0) r ) AS `t_points`) ON (`t_points`.`avg` = `t4`.`avg`) ) AS `t_group_points`) ON (`t_group_points`.`group1` = `t1`.`group1`) ```
First three Groups with Highest Marks should have specific points
[ "", "mysql", "sql", "" ]
Is there a way to get the 'Script Table as' > 'CREATE To' option for tables in SQL Server Management Studio to preserve the collation types set for each column? I know it's possible to specify collation types for columns when creating tables so I find it odd that these settings aren't present in the script output by SSMS.
Go to Tools -> Options. Expand "Sql Server Object Explorer" -> Scripting and there is an option "Include collation" you can enable there in the "Table and view options" category (the default value is false). ![screenshot](https://i.stack.imgur.com/RQ7yB.png)
Right click on the database in Management Studio ---> Tasks --> Generate Scripts. On the final page of the wizard there is an Advanced button, which has a bunch of options, one of which is script collation. ![enter image description here](https://i.stack.imgur.com/Jgo0o.jpg)
'Script Table as' in SSMS Not Preserving Collation
[ "", "sql", "sql-server", "ssms", "" ]
The following SQL query will return all my programs that are in development or completed mode. The goal here is to get the latest state of all programs. I use the following query to return all my program states ``` SELECT PK_ProgramState, FK_Program, State FROM ProgramStates ``` I get the following results: ![Program states](https://i.stack.imgur.com/k3Zu6.png) As seen by the yellow highlight in the colored rectangles of this image, I want those "FK\_Program" records to be returned. The others who come before the last highlighted record state are not needed. I can't seem to figure out how to do it ... All the queries I've been trying give me bogus results. All help is appreciated. Thanks in advance.
``` SELECT s1.PK_ProgramStatee, s1.FK_Program, s1.State FROM ProgramStates s1 inner join ( SELECT max(PK_ProgramState) as mstate, FK_Program FROM ProgramStates group by FK_Program ) s2 on s2.mstate = s1.PK_ProgramState and s2.FK_Program = s1.FK_Program ```
Here is one way: ``` select fk_program from ProgramStates ps group by fk_program having substring_index(group_concat(State order by PK_ProgramState desc), ',', 1 ) in ('Development', 'Completed'); ``` This is finding the last state using `group_concat()` than then comparing it to the states that you want to look for. You could also write the `having` clause as: ``` having group_concat(State order by PK_ProgramState desc) like 'Completed%' or group_concat(State order by PK_ProgramState desc) like 'Development%' ``` The intention might be clearer in this form.
How to return the last record in a table with multiple states
[ "", "sql", "" ]
We want to obtain an auto-increment ID from mySQL without actually storing it until the other non-mysql related processes are successfully completed, so that the entry is not stored if an exception or application crash happens. We need to use the ID as a key for the other processes. In essence we want to “reserve” the auto-increment and insert the rows into mySQL as the last step. We don’t want to insert any row until we know the entire process has completed successfully. Is it possible to do this sort of auto-increment reservation in mySQL? Note: I know about the SQL transactions. But our process contains non-SQL stuff that need to happen outside of the DB. These process may take few mins to several hours. But we don't want any other process using the same auto-increment ID. That is why we want a "reserve" an auto-increment ID without really inserting any data into the DB. –
The only way to generate an auto-increment value is to attempt the insert. But you can roll back that transaction, and still read the id generated. In MySQL 5.1 and later, the default behavior is that auto-increment values aren't "returned" to the stack when you roll back. ``` START TRANSACTION; INSERT INTO mytable () VALUES (); ROLLBACK; SELECT LAST_INSERT_ID() INTO @my_ai_value; ``` Now you can be sure that no other transaction will try to use that value, so you can use it in your external processes, and then finally insert a value manually that uses that id value (when you insert a specific id value, MySQL does not generate a new value).
Have you considred using mysql tranactions? The essense of it, you start a transaction, if all sql statements are correct and can be complteted, then you commit your transaction. If not, then you rollback as if nothing happened. More details can be read in this link: <http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.html>
Reserving mySQL auto-incremented IDs?
[ "", "mysql", "sql", "transactions", "auto-increment", "" ]
I have procedure it is working but i want to improve it, by giving ability to search by couple letters in word. Procedure: ``` alter PROCEDURE SearchByIncIDroNameOfClientoStreetorEmpID @IncID int, @NameOfClient nvarchar (60), @StrID int, @EmpID int, @date date as select IncID,NameOfClient,EnterDate,StrName ,AppartmentNumber as 'appartment',Summary,IncStatus,e.LastName,EndDate from Incident i JOIN Streets s on i.StrID=s.StrID join Employee e on i.EmpID=e.EmpID where IncID =@IncID or NameOfClient = @NameOfClient or s.StrID = @StrID or i.EmpID=@EmpID or EnterDate =@date go ``` I need modify this part `NameOfClient = @NameOfClient` so it will show records which begins with provided letter. so right now if i want to searh for `John` i have to wright John but I want for example if i will give just `Jo` it should return me all of the records which starts from `Jo` I was trying to add % sign before `@NameOfClient` but it doesn't work. Any Ideas how I can do it?
You need to use `like` operator: ``` NameOfClient like @NameOfClient+'%' ```
``` NameOfClient like @NameOfClient + '%' ``` Doesn't this works?
select procedure which should find word by provided letters
[ "", "sql", "sql-server-2008", "t-sql", "select", "stored-procedures", "" ]
I have table like below : ``` ID ref num type time stamp ------------------------------ 1 456 X Time 1 2 456 Y updated Timestamp 3 678 X Time 3 4 678 Y updated timestamp ``` I would need help in building a query that shall give me the result as below : ``` ref num Type Time difference ------------------------------------ 456 X (Timestamp diff between Type X and Type Y for a ref num) 678 Y (Timestamp diff between Type X and Type Y for a ref num) ```
You can do this with conditional aggregation: ``` select t.refnum, (max(case when type = 'X' then timestamp end) - max(case when type = 'Y' then timestamp end) ) as TypeTimeStampDiff from t group by t.refnum; ```
One solution would be to use a co-related sub-query to get the corresponding time\_stamp value: ``` select t1.id, t1.ref_num, t1.type, t1.time_stamp - (select max(t2.time_stamp) from the_table t2 where t2.ref_num = t1.ref_num and t2.type = 'Y') as diff from the_table t1 where t1.type = 'X'; ``` The `max()` is just a precaution in case there is more than one row with the same ref\_num and `type = 'Y'`
Oracle SQL Query Help needed for below
[ "", "sql", "oracle", "" ]
I have a column of count and want to divide the column by max of this column to get the rate. I tried ``` select t.count/max(t.count) from table t group by t.count ``` but failed. I also tried the one without GROUP BY, still failed. Order the count desc and pick the first one as dividend didn't work in my case. Consider I have different counts for product subcategory. For each product category, I want to divide the count of subcategory by the max of count in that category. I can't think of a way avoiding aggregate func.
If you want the MAX() per category you need a correlated subquery: ``` select t.count*1.0/(SELECT max(t.count) FROM table a WHERE t.category = a.category) from table t ``` Or you need to `PARTITION BY` your `MAX()` ``` select t.count/(max(t.count) over (PARTITION BY category)) from table t group by t.count ```
The following works in all dialects of SQL: ``` select t.count/(select max(t.count) from t) from table t group by t.count; ``` Note that some versions of SQL do integer division, so the result will be either 0 or 1. You can fix this by multiplying by 1.0 or casting to a float. Most versions of SQL also support: ``` select t.count/(max(t.count) over ()) from table t group by t.count; ``` The same caveat applies about integer division.
sql divide column by column max
[ "", "sql", "" ]
Given the following PostgreSQL table: ``` items integer id integer parent_id string name unique key on [parent_id, name] parent_id is null for all root nodes ``` Currently I build the sql query manually, doing a join for every path element. But is seems quite ugly to me and of course it limits the possible depth. Example: ``` path: holiday,images,spain SELECT i3.* FROM items AS i1 , items AS i2 , items AS i3 WHERE i1.parent_id IS NULL AND i1.name = 'holiday' AND i2.parent_id=i1.id AND i2.name = 'images' AND i3.parent_id=i2.id AND i3.name = 'spain' ``` I wonder if there's a better way, probably using CTE? You can see how my current code works and what the expected output is here: <http://sqlfiddle.com/#!1/4537c/2>
This should perform very well, as it eliminates impossible paths immediately: ``` WITH RECURSIVE cte AS ( SELECT id, parent_id, name ,'{holiday,spain,2013}'::text[] AS path -- provide path as array here ,2 AS lvl -- next level FROM items WHERE parent_id IS NULL AND name = 'holiday' -- being path[1] UNION ALL SELECT i.id, i.parent_id, i.name ,cte.path, cte.lvl + 1 FROM cte JOIN items i ON i.parent_id = cte.id AND i.name = path[lvl] ) SELECT id, parent_id, name FROM cte ORDER BY lvl DESC LIMIT 1; ``` Assuming you provide a unique path (only 1 result). [->SQLfiddle demo](http://sqlfiddle.com/#!1/bb6bf/2)
**update2** here's a function, it peforms well, because search goes only within the path, starting from parent: ``` create or replace function get_item(path text[]) returns items as $$ with recursive cte as ( select i.id, i.name, i.parent_id, 1 as level from items as i where i.parent_id is null and i.name = $1[1] union all select i.id, i.name, i.parent_id, c.level + 1 from items as i inner join cte as c on c.id = i.parent_id where i.name = $1[level + 1] ) select c.id, c.parent_id, c.name from cte as c where c.level = array_length($1, 1) $$ language sql; ``` [**`sql fiddle demo`**](http://sqlfiddle.com/#!1/ba048/1) **update** I think you can do recursive traversal. I've written sql version of this, so it's a bit messy because of cte, but it's possible to write a function: ``` with recursive cte_path as ( select array['holiday', 'spain', '2013'] as arr ), cte as ( select i.id, i.name, i.parent_id, 1 as level from items as i cross join cte_path as p where i.parent_id is null and name = p.arr[1] union all select i.id, i.name, i.parent_id, c.level + 1 from items as i inner join cte as c on c.id = i.parent_id cross join cte_path as p where i.name = p.arr[level + 1] ) select c.* from cte as c cross join cte_path as p where level = array_length(p.arr, 1) ``` [**`sql fiddle demo`**](http://sqlfiddle.com/#!1/4537c/36) or you can build path for all of the elements using recursive cte for that and accumuate your path into array or string: ``` with recursive cte as ( select i.id, i.name, i.parent_id, i.name::text as path from items as i where i.parent_id is null union all select i.id, i.name, i.parent_id, c.path || '->' || i.name::text as path from items as i inner join cte as c on c.id = i.parent_id ) select * from cte where path = 'holiday->spain->2013'; ``` or ``` with recursive cte as ( select i.id, i.name, i.parent_id, array[i.name::text] as path from items as i where i.parent_id is null union all select i.id, i.name, i.parent_id, c.path || array[i.name::text] as path from items as i inner join cte as c on c.id = i.parent_id ) select * from cte where path = array['holiday', 'spain', '2013'] ``` [**`sql fiddle demo`**](http://sqlfiddle.com/#!1/4537c/13)
get last node given the full path of all ancestor's node attributes using cte
[ "", "sql", "postgresql", "common-table-expression", "recursive-cte", "" ]
I have a table "temp" with two attributes: integer, text[]. I would like to insert a record with the brace inside the array. For example a record like this: ``` 1, {'1{c}1','a'} ``` where 1 is the integer and '1{c}1' is the first element of the array and 'a' the second element of the array. I tried a simply insert like this: ``` INSERT INTO temp VALUES (id, '{'1{c}1','a'}'); ``` but it says that is malformed.
According to the [PostgreSQL documentation for arrays](http://www.postgresql.org/docs/current/static/arrays.html), > You can put double quotes around any element value, and must do so if it contains commas or curly braces. A correct syntax would like this: ``` INSERT INTO "temp" VALUES (1, '{"1{c}1",a}'); ``` You can see a complete, working [example on SQL fiddle](http://sqlfiddle.com/#!12/158dd/4).
As an addition, it's also possible to use array constructors, I think it's more safe to use, because array elements are just SQL constants and you also could use expressions inside the array constructors: ``` insert into "temp" values(1, array['1{c}1','a']); ``` it's clear that this is array of strings, and this too ``` insert into "temp" values(1, array['1','2']); ```
Braces inside the array - postgresql
[ "", "sql", "arrays", "postgresql", "" ]
I Have this cat id - post id relation table. ``` +----+--------+---------+ | id | cat_id | post_id | | | | | | 1 | 11 | 32 | | 2 | ... | ... | +----+--------+---------+ ``` I use `SELECT WHERE cat_id = 11 AND post_id = 32` and then if no result found, I do `INSERT`. Can I rewrite these two queries in One?
You can do something like this: ``` insert into cats_rel(cat_id, post_id) select 11, 32 where not exists (select 1 from cats_rel where cat_id = 11 and post_id = 32); ``` EDIT: Oops. That above doesn't work in MySQL because it is missing a `from` clause (works in many other databases, though). In any case, I usually write this putting the values in a subquery, so they only appear in the query once: ``` insert into cats_rel(cat_id, post_id) select toinsert.cat_id, toinsert.post_id from (select 11 as cat_id, 32 as post_id) toinsert where not exists (select 1 from cats_rel cr where cr.cat_id = toinsert.cat_id and cr.post_id = toinsert.post_id ); ```
You can use Replace ``` REPLACE INTO 'yourtable' SET `cat_id` = 11, `post_id` = 32; ``` if the record exists it will overwrite it otherwise it will be created; Update : For this to work you should add a unique key to the pair of columns not only one ``` ALTER TABLE yourtable ADD UNIQUE INDEX cat_post_unique (cat_id, post_id); ```
MySQL Insert if Condition
[ "", "mysql", "sql", "" ]
On the first answer on this post: [Update one MySQL table with values from another](https://stackoverflow.com/questions/5727827/update-one-mysql-table-with-values-from-another) it states that in order to speed up the query an index must be created. How do I do this? I know it's fairly simple I just can't figure out how..
[How to create index (official doc)](http://dev.mysql.com/doc/refman/5.5/en/create-index.html)
``` ALTER TABLE `your_table` ADD INDEX `your_index_name` (`column_that_should_be_indexed`) ``` The **[general syntax](http://dev.mysql.com/doc/refman/5.0/en/create-index.html)** for creating an index is as follows - ``` CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name [index_type] ON tbl_name (index_col_name,...) [index_type] index_col_name: col_name [(length)] [ASC | DESC] index_type: USING {BTREE | HASH} ```
Indexing sql columns to speed up join query
[ "", "mysql", "sql", "" ]
I am trying to load data into mysql database using ``` LOAD DATA LOCAL INFILE A.txt INTO DB LINES TERMINATED BY '|'; ``` the topic of this question is the response I get. I understand the local data offloading is off by default and I have to enable it using a the command `local-infile=1` but I do not know where to place this command.
You can specify that as an additional option when setting up your client connection: ``` mysql -u myuser -p --local-infile somedatabase ``` This is because that feature opens a security hole. So you have to enable it in an explicit manner in case you really want to use it. Both client and server should enable the local-file option. Otherwise it doesn't work.To enable it for files on the server side server add following to the `my.cnf` configuration file: ``` loose-local-infile = 1 ```
I find the answer [here](https://bugs.mysql.com/bug.php?id=72220). It's because the server variable `local_infile` is set to **FALSE|0**. Refer from the [document](https://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_local_infile). You can verify by executing: ``` SHOW VARIABLES LIKE 'local_infile'; ``` If you have SUPER privilege you can enable it (without restarting server with a new configuration) by executing: ``` SET GLOBAL local_infile = 1; ```
ERROR 1148: The used command is not allowed with this MySQL version
[ "", "mysql", "sql", "import", "" ]
I have a table in which data is something like this: ``` Name Salary Tom 10000 John 20000 Ram 20000 Danny 15000 Sandy 14000 Riddle 15000 ``` I can find 2nd highest salary using `cte`; ``` with cte as ( select ROW_NUMBER() over (order by Salary desc) as r, * from Employee e ) select * from cte where r=2 ``` But this gives the result 'Ram' with 20000 salary. What I would like returned is every record for people with the nth-ranking salary. For instance, if I'm looking for `n=2`, the result would be: ``` Danny 15000 Riddle 15000 ``` How do I modify the query to achieve this?
Use [`DENSE_RANK()`](http://technet.microsoft.com/en-us/library/ms173825.aspx): ``` ;WITH cte AS ( SELECT DENSE_RANK() OVER (ORDER BY Salary DESC) AS r, * FROM Employee e ) SELECT * FROM cte WHERE r = 2 ``` [SQL Fiddle](http://www.sqlfiddle.com/#!3/927e6/1)
I posted about this on my blog: <https://fullparam.wordpress.com/2015/03/31/sql-select-nth-rank-of-something-three-approaches/> Correlated subquery: ``` SELECT FirstName, LastName, BaseRate FROM DimEmployee e WHERE (SELECT COUNT(DISTINCT BaseRate) FROM DimEmployee p WHERE e.BaseRate=p.BaseRate) = 4 ``` Why is this a good answer? It’s not really but this will work on any SQL implementation. It’s fairly slow, it will do a lot of look ups. The subquery is evaluated every time a row is processed by the outer query. This query uses dense ranking and can return multiple rows. Double Order By with TOP statement: ``` SELECT TOP 1 FirstName, LastName, BaseRate FROM ( SELECT TOP 4 FirstName, LastName, BaseRate FROM DimEmployee ORDER BY BaseRate DESC) AS MyTable ORDER BY BaseRate ASC; ``` Why is this a good answer? Because it is an easy syntax to remember. Let’s look at the subquery, which returns the N highest salaries in the DimEmployee table in descending order. Then, the outer query will re-order those values in ascending (default) order, this means the Nth highest salary will now be the topmost salary. Keep in mind that the TOP statement is MS SQL server specific. MySQL would use LIMIT 1 for instance. In addition this solution cannot do DENSE ranking and only returns one row even if two employees share the same BaseRate. Use Windowing function: ``` SELECT FirstName, LastName, BaseRate FROM (SELECT FirstName, LastName, BaseRate, DENSE_RANK() OVER (ORDER BY BaseRate DESC) Ranking FROM DimEmployee) AS MyTable WHERE Ranking = 4 ``` Why is this a good answer? Because it performs the best – performance is king. The Syntax is also ANSI SQL however of the “Big 3” only Oracle and MS are using it. In addition you can chose to use ROW\_NUMBER, DENSE\_RANK or regular RANK.
How do I find the nth row from a sql query?
[ "", "sql", "sql-server-2008-r2", "" ]
I have 3 tables ``` sales ----------- date order_id product_details ----------- product_id cost price order_detail ----------- product_id order_id ``` I have to minus the sum of cost and price where date is between **\_\_ and \_\_** to show the profit or loss I have tried this but dont what is the result is showing ``` SELECT ( SUM(p.price) - SUM(p.cost) ) FROM   product_details AS p        LEFT JOIN order_detail AS o          ON o.product_id = p.product_id        JOIN sales AS s          ON s.order_id = o.order_id WHERE  s.[date] = ' 15.08.2013'  ```
Assuming product\_id and order\_id are unique: ``` 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' ```
Sounds like you need a `GROUP BY` in your clause, as you're looking for the total profit of each `product id`? ``` SELECT SUM(pd.price) - SUM(pd.cost) FROM product_details pd LEFT JOIN order_details od ON pd.product_id = od.product_id INNER JOIN sales s ON od.order_id = s.order_id -- This is where you'd change your date filter WHERE s.Date BETWEEN '20.07.2013' AND '20.08.2013' GROUP BY pd.product_id ```
join three tables sql
[ "", "sql", "sql-server", "" ]
I have two tables Orderitems: ``` "ORDER_ITEMS_CODE" VARCHAR2(20) NOT NULL ENABLE, "ORDER_CODE" VARCHAR2(20) NOT NULL ENABLE, "ITEM_CODE_ORDERS" VARCHAR2(20) NOT NULL ENABLE, "ORDER_QUANTITY" NUMBER(4,0) NOT NULL ENABLE, "ORDER_UNIT" VARCHAR2(5) NOT NULL ENABLE, "UNIT_PRICE" NUMBER(38,5), "ORDERED_IN" VARCHAR2(6), "OR_QUANTITY_TON" NUMBER(38,5), "Warehouse_CODE" VARCHAR2(20) NOT NULL ENABLE ``` the other table is Inventory: ``` "INVENTORY_CODE" VARCHAR2(20) NOT NULL ENABLE, "ITEM_CODE" VARCHAR2(20) NOT NULL ENABLE, "WAREHOUSE_CODE" VARCHAR2(20), "IN_Q_TON" NUMBER(38,5), "OR_Q_TON" NUMBER(38,5) ``` I created a trigger to calculate "OR\_QUANTITY\_TON" = Sum ("OR\_QN\_TON") ``` create or replace trigger sum_Or_IT after insert or update or delete on orderitems begin update INVENTORY set OR_Q_TON = ( select sum(or_quantity_ton) from orderitems where orderitems.item_code_orders = INVENTORY.item_code and warehouse_code = '1'); end; ``` this is an inventory table and the column OR\_Q\_TON is the sum of the ordered quantity for every item,, but if an item doesn't exist in the orders ,, I want the order quantity to be zero. I want to make an exception if the "item\_code\_orders" doesn't exist in the table "Orderitems" then the OR\_Q\_TON = 0 I tried this but it didn't work I got (-) not (0) ``` EXCEPTION WHEN NO_DATA_FOUND THEN update INVENTORY set OR_Q_TON = 0 ; ```
the trigger should be ``` create or replace trigger sum_Or_IT after insert or update or delete on orderitems begin update INVENTORY set OR_Q_TON = ( select coalesce(sum(or_quantity_ton),0) from orderitems where orderitems.item_code_orders = INVENTORY.item_code and warehouse_code = '1') end; ``` the problem solved by using coalesce function instead of the exception
its is not an exception , AND oracle will not raise excpetion in the case of an update above You need to use `sql%rowcount`, TRY: ``` IF SQL%ROWCOUNT = 0 THEN update INVENTORY set OR_Q_TON = 0 ; END IF; ```
Update trigger when row doesn't exist
[ "", "sql", "oracle", "plsql", "triggers", "oracle11g", "" ]
I have 3 tables, where one is a map between the other two. Given a list of tags I want to select all other tags in which the taggables are tagged with. I'll try to given a visual of my problem. ``` tags -------------- 1 | 'email' 2 | 'gmail' 3 | 'yahoo' 4 | 'hotmail' 5 | 'school' 6 | 'not used' taggables -------------------------- 1 | 'test1@gmail.com' 2 | 'test2@yahoo.com' 3 | 'test3@hotmail.com' 4 | 'test4@gmail.com' 5 | 'test5@myschool.edu' tagged ------ 1, 1 /* test1@gmail.com --> email */ 1, 2 /* test1@gmail.com --> gmail */ 2, 1 /* test2@yahoo.com --> email */ 2, 3 /* test2@yahoo.com --> yahoo */ 3, 1 /* test3@hotmail.com --> email */ 3, 4 /* test3@hotmail.com --> hotmail */ 4, 1 /* test4@gmail.com --> email */ 4, 2 /* test4@gmail.com --> gmail */ 5, 1 /* test5@myschool.edu--> email */ 5, 5 /* test5@myschool.edu--> school */ ``` So given a list of `'email', 'gmail'` the result set should be `'yahoo', 'hotmail', 'school'`. I've spent too much time on this and could use some help.
This approach gets all items with the tags you want. It then uses `in` to find all the tags on those items. If I understand your question correctly, this is what you are asking for: ``` select distinct td.* from tagged td join tags t on td.tagid = t.tagid where td.itemid in (select itemid from tagged td join tags t on td.tagid = t.tagid where t.tagname in ('gmail', 'email') ) and t.tagname not in ('gmail', 'email'); ```
``` SELECT DISTINCT T.tagname FROM tags T JOIN tagged TT ON T.id = TT.tagID -- getting only used tags LEFT JOIN taggables TG ON TT.taggabeId = TG.ID WHERE TG.id IS NULL -- getting unassigned tags AND T.tagname IN ('gmail', 'email') -- filtering by given confition ```
SQL select all or nothing with IN clause
[ "", "sql", "sqlite", "" ]
I require a query that selects rows where the time is less or equal to 12:00 I had something like this in mind: ``` SELECT daterow FROM datecolumn WHERE daterow <= TO_DATE('12:00, HH24:MI') ``` However i get an error: ``` ORA-01843: not a valid month ``` How would i go about to get all rows that have a time less than 12:00 mid-day?
In order to select all rows where time portion of the `daterow` column value is less than or equal to mid-day `12:00` you can use `to_char()` function to extract hour and minutes and `to_number()` to convert it to a number for further comparison: ``` -- sample of data. Just for the sake of demonstration SQL> with t1(col) as( 2 select sysdate - to_dsinterval('P0DT3H') from dual union all 3 select sysdate - to_dsinterval('P0DT2H') from dual union all 4 select sysdate - to_dsinterval('P0DT1H') from dual union all 5 select sysdate + to_dsinterval('P0DT3H') from dual union all 6 select sysdate + to_dsinterval('-P2DT0H') from dual 7 ) 8 select to_char(col, 'dd.mm.yyyy hh24:mi:ss') as res 9 from t1 t 10 where to_number(to_char(col, 'hh24mi')) <= 1200 11 ; ``` Result: ``` RES ------------------- 26.08.2013 08:10:59 26.08.2013 09:10:59 26.08.2013 10:10:59 24.08.2013 11:10:59 ```
Try This: ``` SELECT daterow FROM datecolumn WHERE TO_DATE(daterow,'HH24:MI') <= TO_DATE('12:00', 'HH24:MI'); ```
Select Dates where time is less or equal to '12:00' Oracle
[ "", "sql", "oracle", "select", "" ]
I need to write a stored procedure which will update into a particular column, based on parameters. This will be called from a C# app. The table to be updated is like this: TableA: Id, Col1, Col2, Col3. Something like this: ``` Create Procedure UpdateByCol @col_num int, @value string, @id int as Begin Update TableA Set *How do I specify the column here* = @value where Id = @id End ```
``` Declare @SQL varchar(max) Set @SQL = 'Update ' + @TableName + ' Set ' + @Col1 + ' = ' + @Col1Val.... Exec (@SQL) ``` This exposes you to SQL injection though...
There is a way to do this without dynamic sql. Create individual stored procs for each column that is eligible for updating. Then, in your master stored proc, call the applicable stored proc based on the paramter received.
How to dynamically specify a column in stored procedure
[ "", "sql", "stored-procedures", "" ]
It seems like there should be a way to make this more efficient. The difficulty is the arbitrary date ranges and number of said ranges. In this query I am attempting to retrieve rows from the tasks table where the date (regardless of time) is 2013-01-01, 2013-01-03, 2013-01-09 or 2013-02-01 ``` tasks |id | int | |begin_date| datetime | SELECT * FROM tasks WHERE (tasks.begin_date >= '2013-01-01' AND tasks.begin_date < '2013-01-01') OR (tasks.begin_date >= '2013-01-03' AND tasks.begin_date < '2013-01-04') OR (tasks.begin_date >= '2013-01-09' AND tasks.begin_date < '2013-01-10') OR (tasks.begin_date >= '2013-02-01' AND tasks.begin_date < '2013-02-02') ``` Is there a "proper" way to do this? or a significantly more efficient way? I'm using SQL Server 2008.
Please try this ``` select * from tasks where Convert(varchar,begin_date,103) in ('01/01/2013','04/01/2013','10/01/2013','02/02/2013') ``` or you can try this also. ``` select * from tasks where (Convert(varchar,begin_date,103) ='01/01/2013' OR Convert(varchar,begin_date,103) = '04/01/2013' OR Convert(varchar,begin_date,103) = '10/01/2013' OR Convert(varchar,begin_date,103) = '02/02/2013') ``` OR third way ``` SELECT * FROM tasks WHERE (tasks.begin_date BETWEEN '2013-01-01' AND '2013-01-01') OR (tasks.begin_date BETWEEN '2013-01-03' AND '2013-01-04') OR (tasks.begin_date BETWEEN '2013-01-09' AND '2013-01-10') OR (tasks.begin_date BETWEEN '2013-02-01' AND '2013-02-02') ```
Here is another one. ``` SELECT * FROM tasks WHERE YEAR(tasks.begin_date) = 2013 and ( (MONTH(tasks.begin_date) = 1 and DAY(tasks.begin_date) = 1) -- 2013-01-01 or (MONTH(tasks.begin_date) = 1 and DAY(tasks.begin_date) = 3) -- 2013-01-03 or (MONTH(tasks.begin_date) = 1 and DAY(tasks.begin_date) = 9) -- 2013-01-09 or (MONTH(tasks.begin_date) = 2 and DAY(tasks.begin_date) = 1) -- 2013-02-01 ) ``` You can also experiment with something like ``` Convert(DateTime, DATEDIFF(DAY, 0, tasks.begin_date)) = Convert(DateTime, ‘01/01/2013’) ```
Optimize query selecting based on several date ranges
[ "", "sql", "sql-server", "sql-server-2008", "" ]
How to find first day of year in SELECT? ``` SELECT `DATE`,`SomeValue1`,`SomeValue2` FROM `SomeTableName` WHERE (`DATE` >= [...first day of the year in date format...]) ``` I found this for month - but I don't QUITE have the grasp enough for year: (I was looking for this for a separate query to find data between beginning of month and now) ``` WHERE (`DATE` between DATE_FORMAT(NOW() ,'%Y-%m-01') AND NOW() ) ```
I think you need: ``` WHERE (`DATE` between DATE_FORMAT(NOW() ,'%Y-01-01') AND NOW() ) ``` To be honest, you could do: ``` WHERE (`DATE` between DATE_FORMAT(NOW() ,'%Y') AND NOW() ) ```
To get the first day of the current year, I use: ``` SELECT MAKEDATE(year(now()),1); ``` So in your query you would write: ``` where `date` >= MAKEDATE(year(now()),1) ``` I quite commonly do something like a sales report for the past full 2 years, but I always want to start at the beginning of a year. So shows 2 full years and the year to date. ``` where date>= MAKEDATE(year(now()-interval 2 year),1) ``` But to further complicate it, our financial years starts on the first of May. I always want to start on the first of May. ``` where date >= MAKEDATE(year(now()-interval 2 year),1) + interval 120 day ``` or as an alternative ``` where date >= MAKEDATE(year(now()-interval 2 year),121) ``` The first of May being the 121st day of a the year. But this method does not work in leap years. The leap year proof version is: ``` where date => select MAKEDATE(year(now()-interval 5 year),1) + interval 4 month ``` Which will always return a xxxx-05-01 date, whether a leap year or not.
MySQL Select First Day of Year and Month
[ "", "mysql", "sql", "date", "select", "" ]
I have a table which holds data, and one of those rows needs to exist in another table. So, I want a foreign key to maintain referential integrity. ``` CREATE TABLE table1 ( ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY, AnotherID INT NOT NULL, SomeData VARCHAR(100) NOT NULL ) CREATE TABLE table2 ( ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY, AnotherID INT NOT NULL, MoreData VARCHAR(30) NOT NULL, CONSTRAINT fk_table2_table1 FOREIGN KEY (AnotherID) REFERENCES table1 (AnotherID) ) ``` However, as you can see, the table I foreign key to, the column isn't the PK. Is there a way to create this foreign key, or maybe a better way to maintain this referential integrity?
If you really want to create a foreign key to a non-primary key, it MUST be a column that has a unique constraint on it. From [Books Online](http://technet.microsoft.com/en-us/library/ms175464%28v=sql.105%29.aspx): > A FOREIGN KEY constraint does not have to be linked only to a PRIMARY > KEY constraint in another table; it can also be defined to reference > the columns of a UNIQUE constraint in another table. So in your case if you make `AnotherID` unique, it will be allowed. If you can't apply a unique constraint you're out of luck, but this really does make sense if you think about it. Although, as has been mentioned, if you have a perfectly good primary key as a candidate key, why not use that?
As others have pointed out, ideally, the foreign key would be created as a reference to a primary key (usually an IDENTITY column). However, we don't live in an ideal world, and sometimes even a "small" change to a schema can have significant ripple effects to the application logic. Consider the case of a Customer table with a SSN column (and a dumb primary key), and a Claim table that also contains a SSN column (populated by business logic from the Customer data, but no FK exists). The design is flawed, but has been in use for several years, and three different applications have been built on the schema. It should be obvious that ripping out Claim.SSN and putting in a real PK-FK relationship would be ideal, but would also be a *significant* overhaul. On the other hand, putting a UNIQUE constraint on Customer.SSN, and adding a FK on Claim.SSN, could provide referential integrity, with little or no impact on the applications. Don't get me wrong, I'm all for normalization, but sometimes pragmatism wins over idealism. If a mediocre design can be helped with a band-aid, surgery might be avoided.
Foreign Key to non-primary key
[ "", "sql", "sql-server", "" ]
I have a mysql code and need to convert it Oracle syntax and I faced with this error. Could anyone help me? ``` SELECT SUM(T.SEND_UNREAD_DRAFT) SEND_UNREAD_DRAFT, SUM(T.SEND_READ_DRAFT) SEND_READ_DRAFT, SUM(T.SEND_APPROVED) SEND_APPROVED, SUM(T.SEND_COMPLETED) SEND_COMPLETED, SUM(T.SEND_FAILED)SEND_FAILED,SUM(T.RECEIVED_DRAFT)RECEIVED_DRAFT,SUM(T.RECEIVED_APPROVED)RECEIVED_APPROVED, Sum(T.Received_Accepted_Send)Received_Accepted_Send,Sum(T.Received_Rejected_Send)Received_Rejected_Send, Sum(T.Send_Canceled)Send_Canceled FROM (SELECT (CASE WHEN TYPE = 'OUT' THEN (CASE WHEN STATUS = 'DRAFT' THEN (CASE WHEN READ_FLAG = 'N' THEN 1 ELSE 0 END) ELSE 0 END) ELSE 0 END) SEND_UNREAD_DRAFT, (CASE WHEN TYPE = 'OUT' THEN (CASE WHEN STATUS = 'DRAFT' THEN (CASE WHEN READ_FLAG = 'Y' THEN 1 ELSE 0 END) ELSE 0 END) ELSE 0 END) SEND_READ_DRAFT, (CASE WHEN TYPE = 'OUT' THEN (CASE WHEN STATUS = 'APPROVED' THEN 1 ELSE 0 END) ELSE 0 END) SEND_APPROVED, (CASE WHEN TYPE = 'OUT' THEN (CASE WHEN STATUS = 'COMPLETED' THEN 1 ELSE 0 END) ELSE 0 END) SEND_COMPLETED, (CASE WHEN TYPE = 'OUT' THEN (CASE WHEN STATUS = 'FAILED' THEN 1 ELSE 0 END) ELSE 0 END) SEND_FAILED, (CASE WHEN TYPE = 'OUT' THEN (CASE WHEN STATUS = 'CANCELED' THEN 1 ELSE 0 END) ELSE 0 END) SEND_CANCELED, (CASE WHEN TYPE = 'OUT' THEN (CASE WHEN STATUS = 'DRAFT' THEN 1 ELSE 0 END) ELSE 0 END) RECEIVED_DRAFT, (CASE WHEN TYPE = 'OUT' THEN (CASE WHEN STATUS = 'APPROVED' THEN 1 ELSE 0 END) ELSE 0 END) RECEIVED_APPROVED, (CASE WHEN TYPE = 'IN' THEN (CASE WHEN STATUS = 'COMPLETED' THEN (CASE WHEN INVOICE_STATUS = 'ACCEPTED' THEN 1 ELSE 0 END) ELSE 0 END) ELSE 0 END) RECEIVED_ACCEPTED_SEND, (CASE WHEN TYPE = 'IN' THEN (CASE WHEN STATUS = 'COMPLETED' THEN (CASE WHEN INVOICE_STATUS = 'REJECTED' THEN 1 ELSE 0 END) ELSE 0 END) ELSE 0 END) RECEIVED_REJECTED_SEND From Eis_Invoice_Header Where Invoice_Date Between Sysdate()-365 And (sysdate + Interval '3' Month from dual)) as T ```
1. the query `select sysdate + interval '3' month , add_months(sysdate, 3) from dual;` are same. 2. in your query, use `where invoice_date between sysdate- 365 and sysdate + interval '3' month'`
You have to convert interval to add\_months and sysdate() to sysdate. And you could also change to case to make it simple. ``` SELECT SUM(T.SEND_UNREAD_DRAFT) SEND_UNREAD_DRAFT, SUM(T.SEND_READ_DRAFT) SEND_READ_DRAFT, SUM(T.SEND_APPROVED) SEND_APPROVED, SUM(T.SEND_COMPLETED) SEND_COMPLETED, SUM(T.SEND_FAILED) SEND_FAILED,SUM(T.RECEIVED_DRAFT) RECEIVED_DRAFT,SUM(T.RECEIVED_APPROVED) RECEIVED_APPROVED, Sum(T.Received_Accepted_Send) Received_Accepted_Send, Sum(T.Received_Rejected_Send) Received_Rejected_Send, Sum(T.Send_Canceled) Send_Canceled FROM( SELECT CASE WHEN TYPE = 'OUT' and STATUS = 'DRAFT' and READ_FLAG = 'N' THEN 1 ELSE 0 END SEND_UNREAD_DRAFT, CASE WHEN TYPE = 'OUT' and STATUS = 'DRAFT' and READ_FLAG = 'Y' THEN 1 ELSE 0 END SEND_READ_DRAFT, CASE WHEN TYPE = 'OUT' and STATUS = 'APPROVED' THEN 1 ELSE 0 END SEND_APPROVED, CASE WHEN TYPE = 'OUT' and STATUS = 'COMPLETED' THEN 1 ELSE 0 END SEND_COMPLETED, CASE WHEN TYPE = 'OUT' and STATUS = 'FAILED' THEN 1 ELSE 0 END SEND_FAILED, CASE WHEN TYPE = 'OUT' and STATUS = 'CANCELED' THEN 1 ELSE 0 END SEND_CANCELED, CASE WHEN TYPE = 'OUT' and STATUS = 'DRAFT' THEN 1 ELSE 0 END RECEIVED_DRAFT, CASE WHEN TYPE = 'OUT' and STATUS = 'APPROVED' THEN 1 ELSE 0 END RECEIVED_APPROVED, CASE WHEN TYPE = 'IN' and STATUS = 'COMPLETED' and INVOICE_STATUS = 'ACCEPTED' THEN 1 ELSE 0 END RECEIVED_ACCEPTED_SEND, CASE WHEN TYPE = 'IN' and STATUS = 'COMPLETED' and INVOICE_STATUS = 'REJECTED' THEN 1 ELSE 0 END RECEIVED_REJECTED_SEND From Eis_Invoice_Header Where Invoice_Date Between Sysdate-365 And add_months(sysdate ,3) ) as T ```
ORA-00905: Trouble converting Mysql syntax to oracle syntax
[ "", "sql", "oracle", "" ]
I have table where have over 100k information. ``` ID FirstName 1 Bob 2 Bob 3 Tom 4 John 5 John 6 John .. .... ``` Want procedure which will be count how much names are same, For example it must be like : ``` FirstName Count Bob 2 Tom 1 John 3 ``` Please help me to write it
It's very basic SQL example, [group by column + aggregating results](http://technet.microsoft.com/en-us/library/ms177673.aspx) ``` select FirstName, count(*) from Table1 group by FirstName ```
Try this ``` select FirstName,Count(FirstName) From TableA group by FirstName ```
Count distinct same names
[ "", "sql", "sql-server", "count", "" ]
We have some records in this table in production environment where a particular field called compiledlimitation contains values where single quotes are escaped by multiple backslashes. E.g. `Test\\'s` We tried selecting only such records, but a query like the following returns those records which have single backslash (proper records) in addition to those which have double backslashes - ``` select * from tablename where compiledlimitation like "%\\'%" ``` The above query returns both these rows - ``` Test\\'s Test\'s ``` How can I modify the query to fetch only rows with double backslashes. The field compiledlimitation is a text field. **Update** Problem not solved yet. Both of these queries return both the records - ``` select * from tablename where compiledlimitation like "%\\\\\'%" select * from tablename where compiledlimitation like "%\\\'%" ```
``` SELECT * FROM my_table WHERE my_column RLIKE '[\\]{2}'; ``` or something like that
To escape two slashes, you should just need to use four in your LIKE: ``` LIKE "%\\\\%" ``` See <http://dev.mysql.com/doc/refman/5.0/en/string-literals.html> **Table 9.1. Special Character Escape Sequences** ... \\ => A backslash (“\”) character. ...
Selecting records with single quotes escaped by double backslashes only
[ "", "mysql", "sql", "" ]
Good Afternoon to All, I have a question concerning on SQL Queries. is it possible to use an array as a parameter to a query using the "IN" command? for example, int x = {2,3,4,5} UPDATE 'table\_name' set 'field' = data WHERE field\_ID IN (x) the reason I am asking this is to avoid an iterative SQL Statement when I have to update data in a database. I also thought of using a for each statement in for the UPDATE Query but I don't know if it will affect the performance of the query if it will slow down the system if ever 100+ records are updated. I am using VB.Net btw. My Database is MySQL Workbench.
I have gotten the answer. I just simply need to convert each elements to a String then concatenate it with a "," for each element. so the parameter that i will pass will be a string. ANSWER: int x = {2,3,4,5} will become string x = "2,3,4,5" My Query string will become "UPDATE tablename SET field=value WHERE ID IN("&x&")" Thank you to all who helped.
If you have the query in a variable (not a stored procedure) and you don't have a huge amount of ids, you could built your own IN. I haven't tested the speed of this approach. This code won't compile, it's just to give you an idea. ``` query = "SELECT * FROM table WHERE col IN (" For t = 0 TO x.Length-1 If t > 0 Then query &= "," query &= "@var" & t Next query &= ")" ... For t = 0 TO x.Length-1 cmd.Parameters.Add("@var" & t, SqlDbType.Int).Value = x(t) Next ```
passing an Array as a Parameter to be used in a SQL Query using the "IN" Command
[ "", "mysql", "sql", "vb.net", "sql-in", "" ]
I have the following columns: ``` merchant_id euro ``` I would like to sum all euro records by `merchant_id` and only return the `total sum per merchant_id`. So if have 3 records like: ``` euro | merchant_id 4 | 1 5.4 | 2 2.5 | 1 ``` The result should be: ``` euro | merchant_id 6.5 | 1 5.4 | 2 ``` How on earth do i do this? Thanks.
You need to use group by and sum them up. ``` SELECT SUM(euro) AS euro,merchant_id FROM table_name GROUP BY merchant_id ```
``` select merchant_id ,sum(euro) from <your_table_name> group by merchant_id ```
-SQL- Summing by other column value
[ "", "sql", "sum", "" ]
I have one table (**customerselection**) that lists customer numbers and promo codes: ``` CustomerNumber | Promo 12345 | ABCDEF 54321 | BCDEFG 22334 | BCDEFG 54678 | BCDEFG 23454 | ABCDEF ``` And another table (**certificates**) that lists Certificates, Promos, and CustomerNumbers, but CustomerNumber is initially NULL: ``` Certificate | Promo | CustomerNumber 1111111111 | ABCDEF | NULL 2222222222 | BCDEFG | NULL 3333333333 | BCDEFG | NULL 4444444444 | ABCDEF | NULL ``` What I need to do is uniquely assign each Certificate in the second table to a customer in the first table. The promos need to match. Update the second table with a customer number from the first, only to one record, with a matching promo. I've done this in the past with a VB program - loop over records in the first table, update the first free record for the matching promo in the second table. But that program takes too long to run (there are usually around 600,000 records). Is there any way to do this right in SQL? Accomplish the task with an awesomely convoluted (or even awesomely simple) SQL query? (Or SQL Server functionality?) UPDATE There are many certificates per each promo. And many customers per promo. But each customer can be assigned to only one certificate. UPDATE 2 Let's call the first table **customerselection** and the second table **certificates**. **customerselection** is a selection of customers that we want to assign certificates to. **certificates** is a pool of certificates that can be assigned.
If I understand correctly you want to match certificates and customer so that every customer and every certificate appears once (for each promo). i.e. for a given promo ``` custD, custR, custA cert2 * cert1 * cert3 * cert6 cert7 ``` The important thing being that each row **and** each column have at most one match. ``` update certificates set CustomerNumber = t_cust.CustomerNumber from certificates, ( select Promo, CustomerNumber, row_number() over (partition by Promo order by CustomerNumber) as order_cust from customerselection ) t_cust, ( select Promo, Certificate, row_number() over (partition by Promo order by Certificate) as order_cert from certificates ) t_cert where t_cust.Promo = t_cert.Promo and t_cust.order_cust = t_cert.order_cert and certificates.Certificate = t_cert.Certificate ```
Try This ``` UPDATE B SET B.CustomerNumber = A.CustomerNumber FROM TableB B INNER JOIN TableA A ON B.Promo = A.Promo ```
SQL Server - Uniquely update one table based on category records in another table
[ "", "sql", "sql-server", "" ]
I am trying to write a query that will select items with only integer data such as: 019280498 as opposed to 0129830INK. These are sku's in a product database and my current solution is something to this effect: Column name is **SKU** ``` SELECT * FROM mydb WHERE SKU not like '%a%' or SKU not like '%b%' or SKU not like '%c%' ..... or SKU not like '%z%' ``` This would only return values with no characters in them. However it does not like what I have written and i'm sure there is a more elegant way to execute this.
Using your original method with `like`, you can do: ``` SELECT * FROM mydb WHERE SKU not like '%[^0-9]%'; ``` This has the advantage that expressions like `'3e9'` are not accepted as a numeric value. Or, if is specifically alphabetic characters that you want to keep out: ``` SELECT * FROM mydb WHERE SKU not like '%[a-z]%'; -- or for case sensitive collations '%[a-zA-Z]%' ```
There's an IsNumeric() function that could be used. ``` Select * from mydb Where IsNumeric(sku) = 0x1 ```
Selecting only integer data within a column with characters
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I used following query to get current week `select extract(week from current_timestamp)` and it is showing `34` thats fine. But how do i get the current week number of the current month.
You can find the first day of this week with: ``` trunc('week', current_date) ``` And the first day of the first week of this month with: ``` trunc('week', date_trunc('month', current_date)) ``` Subtract the two to find the in-month weeknumber: ``` extract('day' from date_trunc('week', current_date) - date_trunc('week', date_trunc('month', current_date))) / 7 + 1 ```
Try the following ``` SELECT to_char('2016-05-01'::timestamp, 'W'); ```
Current week number for current month
[ "", "sql", "postgresql", "" ]
I have a table named people\_temp\_1 that contains: ``` Name Age PersonID John 25 1 Jane 32 2 Chris 47 3 ``` And another named people\_temp\_2 that contains additional information that is linked by the PersonID in table1: ``` ID Profession Location 1 Web Developer Texas 2 Graphic Designer North Carolina 3 Sales California ``` And I want to create a new table called people that "merges" the data from both tables. How I am doing this now is: ``` INSERT INTO people(name, age, profession, location) SELECT people_temp_1.name AS name, people_temp_2.age AS age, (SELECT people_temp_2.profession FROM people_temp_2 WHERE people_temp_2.id = people_temp_1.personId) AS profession, (SELECT people_temp_2.location FROM people_temp_2 WHERE people_temp_2.id = people_temp_1.personId) AS location FROM people_temp_1 ``` As you can see I am using multiple select queries in the insert into query in order to get data that is relevant via the personId. It seems a little dirty to be doing multiple select queries when I should somehow be able to query the people\_temp\_2 table once and use all of its columns, but I can't figure out how to do that. Is there a better way to structure that insert into statement?
It's one of the basics of SQL - use [join](http://en.wikipedia.org/wiki/Join_%28SQL%29). In your case it's better to use `outer join` so you won't miss people from `people_temp1` who don't have corresponding records in `people_temp2`: ``` insert into people(name, age, profession, location) select p1.name, p1.age p2.profession, p2.location from people_temp1 as p1 left outer join people_temp2 as p2 on p2.id = p1.person_id ```
Try to use join syntax as below ``` INSERT INTO people(name, age, profession, location) SELECT p1.namename, p2.age, p2.profession, p2.location FROM people_temp_1 p1 JOIN people_temp_2 p2 on p2.id = p1.personId ``` **[More information about joins on mysql](http://dev.mysql.com/doc/refman/5.0/en/join.html)**
MySQL Insert Into Table From Multiple Tables Using Separate SELECT Queries
[ "", "mysql", "sql", "" ]
I'm working with spring 3, hibernate 4. I'm trying to follow this tutorial <http://www.mkyong.com/hibernate/hibernate-display-generated-sql-to-console-show_sql-format_sql-and-use_sql_comments/>, but my hibernate configuration is different: ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"> <!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with username root and blank password. Change below if it's not the case --> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/project"/> <property name="username" value="root"/> <property name="password" value="1234"/> <property name="validationQuery" value="SELECT 1"/> <property name="show_sql" value="true" /> <property name="format_sql" value="true" /> <property name="use_sql_comments" value="true" /> </bean> </beans> ``` And the properties show\_sql, format\_sql and use\_sql\_comments are not working this way. I get this exception: ``` Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'show_sql' of bean class [org.apache.commons.dbcp.BasicDataSource]: Bean property 'show_sql' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? ``` Is there anyway to achieve the tutorial with the definition of the bean??
show\_sql not a property of org.apache.commons.dbcp.BasicDataSource . You have to define it in session factory configuration. like this ``` <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="data" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop> <prop key="hibernate.current_session_context_class">thread</prop> <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> ```
The simplest approach probably is to set following logger to DEBUG: ``` org.hibernate.SQL ``` If you use log4j, find / create a log4j.properties file on your classpath root and add ``` log4j.logger.org.hibernate.SQL=DEBUG ``` See here for more info about log4j properties: <http://logging.apache.org/log4j/1.2/manual.html>
Display Hibernate SQL To Console (Spring)
[ "", "sql", "spring", "hibernate", "debugging", "" ]
I am using postgreSQL 9.1 and I want to delete duplicates from my table using this tip: <https://stackoverflow.com/a/3822833/2239537> So, my query looks like that: ``` WITH cte AS (SELECT ROW_NUMBER() OVER (PARTITION BY code, card_id, parent_id ORDER BY id DESC) RN FROM card) DELETE FROM cte WHERE RN > 1 ``` But it shows me ``` ERROR: relation "cte" does not exist SQL state: 42P01 Character: 157 ``` However this statement works fine: ``` WITH cte AS (SELECT ROW_NUMBER() OVER (PARTITION BY code, card_id, parent_id ORDER BY id DESC) RN FROM merchantcard) SELECT * FROM cte WHERE RN > 1 ``` Any ideas how to get it work? Thanks!
that's because CTE in PostgreSQL works differently than CTE in SQL Server. In SQL Server CTE are like an updatable views, so you can delete from them or update them, in PostgreSQL you cannot. you can join cte and delete, like: ``` with cte as ( select id, row_number() over(partition by code, card_id, parent_id order by id desc) as rn from card ) delete from card where id in (select id from cte where rn > 1) ``` On the other hand, you can write DDL statements inside CTE in PostgreSQL (see [documentation](http://www.postgresql.org/docs/current/static/queries-with.html)) and this could be very handy. For example, you can delete all rows from `card` and then insert only those having row\_number = 1: ``` with cte1 as ( delete from card returning * ), cte2 as ( select row_number() over(partition by code, card_id, parent_id order by id desc) as rn, * from cte1 ) insert into card select <columns here> from cte2 where rn = 1 ```
I know, you are asking how you can solve your problem using the WITH statement, and got a good answer already. But I suggest looking at alternatives in the same question you linked. What about this one? ``` DELETE FROM card WHERE id NOT IN ( SELECT MIN(id) FROM card GROUP BY code, card_id, parent_id ); ```
PostgreSQL with-delete "relation does not exists"
[ "", "sql", "postgresql", "postgresql-9.1", "" ]
I have a query like ``` SELECT 'Education' as Purpose,ate_sex, Age_range, COUNT(*) AS Total FROM ( SELECT dbo.ClientMain.ate_sex, dbo.ClientMain.ate_Id, CASE WHEN ate_Age BETWEEN 15 AND 19 THEN '15-19' WHEN ate_Age BETWEEN 20 AND 24 THEN '20-24' WHEN ate_Age BETWEEN 25 AND 34 THEN '25-34' WHEN ate_Age BETWEEN 35 AND 44 THEN '35-44' WHEN ate_Age BETWEEN 45 AND 54 THEN '45-54' WHEN ate_Age BETWEEN 55 AND 64 THEN '55-64' ELSE '80+' END AS Age_range FROM dbo.ClientMain INNER JOIN dbo.ClientSub ON dbo.ClientMain.ate_Id = dbo.ClientSub.ate_Id WHERE (dbo.ClientSub.chk_Name = N'Assistance') ) AS t group by ate_sex,Age_range ``` Which returns the data as: ![enter image description here](https://i.stack.imgur.com/8d2Im.png) But I want my result as when there is no record with he age range in 15-19, it have to return zero. As **Education Male 15-19 0** These are my tables ![enter image description here](https://i.stack.imgur.com/9K0kI.png) Can anybody please modify my query to get zeros for no records.
* Use a `LEFT JOIN` instead of `INNER JOIN` * Use `ISNULL(COUNT(*), 0)` instead of `COUNT(*)`. Alternatively, you can also use `Total = CASE WHEN COUNT(*) IS NULL THEN 0 ELSE COUNT(*) END`
Try This, ``` case when COUNT(*) = 1 then 0 else COUNT(*) end as exp ```
How to select all the records even if there is no data in sql
[ "", "sql", "sql-server", "select", "" ]
I need to change an application and the first thing I need is to change a field in a database table. In this table I now have 1 to 6 single characters, i.e. 'abcdef' I need to change this to '[a][b][c][d][e][f]' [edit] It is meant to stay in the same field. So before field = 'abcdef' and after field = '[a][b][c][d][e][f]'. What would be a good way to do this? rg. Eric
You can split string to separate characters using following function: ``` create function ftStringCharacters ( @str varchar(100) ) returns table as return with v1(N) as ( select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 ), v2(N) as (select 1 from v1 a, v1 b), v3(N) as (select top (isnull(datalength(@str), 0)) row_number() over (order by @@spid) from v2) select N, substring(@str, N, 1) as C from v3 GO ``` And then apply it as: ``` update t set t.FieldName = p.FieldModified from TableName t cross apply ( select (select quotename(s.C) from ftStringCharacters(t.FieldName) s order by s.N for xml path(''), type).value('text()[1]', 'varchar(20)') ) p(FieldModified) ``` [**SQLFiddle sample**](http://sqlfiddle.com/#!3/e270d/2)
``` DECLARE @text NVARCHAR(50) SET @text = 'abcdef' DECLARE @texttable TABLE (value NVARCHAR(1)) WHILE (len(@text) > 0) BEGIN INSERT INTO @texttable SELECT substring(@text, 1, 1) SET @text = stuff(@text, 1, 1, '') END select * from @texttable ```
SQL splitting a word in separate characters
[ "", "sql", "sql-server-2008", "" ]
I'm learning SQL through GALAXQL <http://sol.gfxile.net/galaxql.html> Im on lesson 17 - GROUP BY/HAVING Here is the scenario: > Let's look at couple of SELECT operations we haven't covered yet, > namely GROUP BY and HAVING. > > The syntax for these operations looks like this: ``` SELECT columns FROM table GROUP BY column HAVING expression ``` > The GROUP BY command in a SELECT causes several output rows to be > combined into a single row. This can be very useful if, for example, > we wish to generate new statistical data as a table. > > For example, to find out the highest intensities from stars for each > class, we would do: ``` Select Class, Max(Intensity) As Brightness From Stars Group By Class Order By Brightness Desc ``` > The HAVING operator works pretty much the same way as WHERE, except > that it is applied after the grouping has been done. Thus, we could > calculate the sum of brightnesses per class, and crop out the classes > where the sum is higher than, say, 150. ``` SELECT class, SUM(intensity) AS brightness FROM stars GROUP BY class HAVING brightness < 150 ORDER BY brightness DESC ``` > We could refer to columns that are not selected in the HAVING clause, > but the results might be difficult to understand. You should be able > to use the aggregate functions in the HAVING clause (for example, > brightness < MAX(brightness)\*0.5, but this seems to crash the current > version of SQLite. > > When combined with joins, GROUP BY becomes rather handy. To find out > the number of planets per star, we can do: ``` SELECT stars.starid AS starid, COUNT(planets.planetid) AS planet_count FROM planets, stars WHERE stars.starid=planets.starid GROUP BY stars.starid ``` **Hilight the star with most orbitals (combined planets and moons). (Note that the validation query is somewhat heavy, so be patient after pressing "Ok, I'm done..").** --- Here was my answer ``` SELECT stars.starid AS HighStar, (COUNT(planets.planetid) + COUNT(moons.moonid)) AS OrbitalsTotal FROM stars LEFT OUTER JOIN planets ON stars.starid = planets.starid LEFT OUTER JOIN moons ON planets.planetid = moons.planetid GROUP BY stars.starid ORDER BY OrbitalsTotal DESC; ``` **This query showed me that the star with the most oribtals has 170 orbitals** So then: ``` INSERT INTO hilight SELECT result.HighStar FROM result INNER JOIN stars ON result.HighStar = stars.starid WHERE result.OrbitalsTotal = 170 ``` My question to you is how can I make this query better? I don't want to have to hard code the 170 orbitals and I dont want to have to create a second query to insert the data.
``` SELECT stars.starid AS HighStar, (COUNT(planets.planetid) + COUNT(moons.moonid)) AS OrbitalsTotal FROM stars LEFT OUTER JOIN planets ON stars.starid = planets.starid LEFT OUTER JOIN moons ON planets.planetid = moons.planetid GROUP BY stars.starid HAVING OrbitalsTotal = (SELECT MAX(Orbitals) FROM (SELECT (COUNT(planets.planetid) + COUNT(moons.moonid)) Orbitals FROM stars LEFT OUTER JOIN planets ON stars.starid = planets.starid LEFT OUTER JOIN moons ON planets.planetid = moons.planetid GROUP BY stars.starid)) ```
Just use your first query, and add the clause `LIMIT 1` to return only the first record: ``` INSERT INTO hilight SELECT stars.starid AS HighStar FROM stars LEFT OUTER JOIN planets ON stars.starid = planets.starid LEFT OUTER JOIN moons ON planets.planetid = moons.planetid GROUP BY stars.starid ORDER BY COUNT(planets.planetid) + COUNT(moons.moonid) DESC LIMIT 1 ```
How can I make this query better?
[ "", "sql", "sqlite", "group-by", "having-clause", "" ]
So, lets say I want to do something like: ``` SELECT Query1.a, Query2.b FROM ( SELECT q as a FROM somewhere ), ( SELECT g as b FROM elsewhere ) where Query 1 is ( SELECT q as a FROM somewhere ) and Query2 is ( SELECT g as b FROM elsewhere ) ``` So, i want to select from two other select statements. Query 1 produces a table ``` a value1 ``` Query 2 produces a table ``` b value 2 ``` And Query 3 (the outer select statement) produces ``` a b value 1 value 2 ``` So, essentially, two result tables are combined as columns and not as rows. Thank you, if you have any hints.
You basically have your solution. You are only missing the names of your queries, so do like this: ``` SELECT Query1.a, Query2.b FROM ( SELECT q as a FROM somewhere ) Query1, ( SELECT g as b FROM elsewhere ) Query2 ```
It's not clear how you need to connect different rows from tables but it can be something like this: ``` select query1.a, query2.b FROM (select q as a, ROW_NUMBER() OVER (ORDER BY q) as RN from a) Query1 FULL JOIN (select q as b, ROW_NUMBER() OVER (ORDER BY q) as RN from b) Query2 ON Query1.RN=Query2.RN ``` [SQLFiddle example](http://sqlfiddle.com/#!4/a0839/5)
SELECT on two other queries in Oracle
[ "", "sql", "oracle", "select", "" ]