Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I would like to round up a value to the next nearest power of 2 in a mysql query, so ``` select RoundUpToNearestPowerOfTwo(700) -- Should give 1024 ``` I need this solution as part of a much larger query to generate and read some bitmask. Using custom stored functions is not an option, since I cannot use those in our production environment, so I'm looking for a smart way to do this inline in the query. [Edit] One possible way I can think of, is creating some enumerator, use a power in that, and choose the smallest value larger than my value: ``` select min(BOUND) from (select 700 as VALUE) v inner join (select POW(2, @pow := @pow + 1) as BOUND from (select @pow := 0) x, MY_RANDOM_TABLE t ) x on x.BOUND > v.VALUE ``` But as you can tell, it's pretty verbose, so a leaner solution would be welcome.
Try this. ``` FLOOR(POW(2,CEIL(LOG2(1025)))) ``` The CEIL and FLOOR cope with the boundary conditions correctly.
Try this: ``` select power(2, 1 + floor(log2(XXX))) ``` MySQL conveniently has the `log2()` function, which does most of the work. EDIT: I think this may be what you want: ``` select (case when floor(log2(XXX)) <> log2(XXX) then power(2, 1 + floor(log2(XXX))) else power(2, floor(log2(XXX))) end) ``` Or something like: ``` select power(2, 1 + floor(log2(XXX*0.999999))) ``` There is a boundary condition on actual powers of 2.
Round up a value to the nearest power of 2 in MySQL query
[ "", "mysql", "sql", "" ]
I am using SQL Server Compact 4.0 and am trying to get one query to return a single record with a column `Alarm` based on the maximum identity when another column `Cleared` is `NULL`. This works: ``` SELECT Id, Alarm FROM Alarm_History WHERE Cleared IS NULL ``` Giving me half the answer. The problem is that it returns several records. This also works: ``` SELECT MAX(Id) FROM Alarm_History WHERE Cleared IS NULL ``` And it gives me the other half of the answer, but I can't get the value "Alarm" that I am looking for. But they DON'T work together as in: ``` SELECT Id, Alarm FROM Alarm_History WHERE Cleared IS NULL AND Id = MAX(Id) ``` OR ``` SELECT MAX(Id), Alarm FROM Alarm_History WHERE Cleared IS NULL ``` With the queries above I can do two consecutive queries to get the result back, but I don't think this is very efficient. Is there a way to do this in one trip to the database? Thanks Jeff
You could do it with max and a join, but that would be far too complicated. Instead, you can just try: ``` SELECT TOP 1 Id, Alarm FROM Alarm_History WHERE Cleared IS NULL ORDER BY Id DESC ``` **Note:** what happens if two alarms have max id ? Well, that shouldn't happen (Id is unique). But that's an interesting problem nevertheless (suppose the field is not Id but Price, and you want all alarms with max price, and you don't know how many there'll be, so you cannot use TOP 1 anymore). You'll have to use a CROSS JOIN; ``` SELECT Id, Price FROM Alarms JOIN (SELECT MAX(Price) as maxPrice FROM Alarms) b WHERE Alarms.Price = b.maxPrice ```
Don't think "max". Think "order by". Try this: ``` SELECT TOP 1 Id, Alarm FROM Alarm_History WHERE Cleared IS NULL ORDER BY Id DESC; ``` That way, you can get all the fields you want associated with the max id.
SQL Server CE retrieve a field from the record with the MAX(Id)
[ "", "sql", "sql-server-ce", "" ]
I have created a calendar table that contains all the calendar dates of a year, incl. the corresponding quarter / week / month / day etc. information. The following Select gives me all Fridays in December. What would be the best way here to get only the second out of these ? ``` SELECT * FROM Calendar WHERE (yearCal = '2014') AND (monthCal = '12') AND (weekDayCal = '6') ``` Many thanks in advance, Mike.
Assuming that you have a `day_of_month` type of field, the second Friday must be day 8 to 14. ``` SELECT * FROM Calendar WHERE (yearCal = 2014) AND (monthCal = 12) AND (weekDayCal = 6) AND (dayInMonth BETWEEN 8 AND 14) ``` You could use a `Week of month` field, but this can get complex depending on what you define as a week. Normally it would by Monday-Sunday or similar, meaning that `week1` of `month12` ***may*** only be 2 days long, and not include a Friday.
If this is a recurring requirement, then you should add a column `weekInMonthCal` and include it in the constraint clause. It is possible to count in SQL but, as this involves aggregation in the result set, it is expensive.
SQL Server: proper use of Select with calendar table
[ "", "sql", "sql-server", "date", "stored-procedures", "calendar", "" ]
I am very new to SQL and I would appreciate it if you could help me. I have a table that has a field with many IDs and that field is in number format. The same ID may repeat different number of times, e.g. 5 times, 6 times. I want to display records of **all fields** only when the same ID is repeated less than x times in this field. Which sql statement will get this done? Thanks in advance.
Try this: ``` SELECT T1.* FROM TableName T1 INNER JOIN (SELECT ID,COUNT(ID) as Count FROM TableName GROUP BY ID HAVING COUNT(ID) < 5) T2 ON T1.ID=T2.ID ``` **EDIT:** Try your query using alias names: ``` SELECT APropertyID,BPropertyID,Ayy,Byy from (SELECT a.PropertyID as APropertyID, b.PropertyID as BPropertyID, a.yy as Ayy,b.yy as Byy FROM tableA a full outer join tableB b on a.PropertyID=b.PropertyID ) a1 inner join (SELECT PropertyID,COUNT(PropertyID) as Count FROM tableA GROUP BY PropertyID HAVING COUNT(PropertyID) < 5) c on a1.APropertyID=c.PropertyID ```
SQL Server allows for an [OVER Clause](http://technet.microsoft.com/en-us/library/ms189461.aspx) in aggregates (which is a useful but "nonstandard" SQL feature) that is handy in cases like this. > Determines the partitioning and ordering of a rowset before the associated window function is applied. That is, the OVER clause defines a window or user-specified set of rows within a query result set. A window function then computes a value for each row in the window. You can use the OVER clause with functions to compute aggregated values such as moving averages, cumulative aggregates, running totals, or a top N per group results. Example: ``` SELECT cts.* FROM ( -- Build intermediate result where each record also has -- a count of how many times that value appears. SELECT t.*, COUNT (1) OVER (PARTITION BY value) as valueCount FROM t ) as cts -- Filter intermediate result based on collected count. WHERE cts.valueCount < 5 ``` (I've used `value` instead of `ID` above - the same approach holds.)
Select records from a table only where a field value is repeated less than x times
[ "", "sql", "sql-server", "" ]
In [this fiddle](http://sqlfiddle.com/#!2/a4f5f/1) I have a single table called "tags". It has four columns: ``` id counter sessionid tag (1, 1, 'session1', 'start'), (2, 2, 'session1', 'sessionname1'), (3, 3, 'session1', 'unimportant tag'), (4, 4, 'session1', 'unimportant tag'), (5, 5, 'session1', 'end'), (6, 1, 'session2', 'start'), (7, 2, 'session2', 'sessionname2'), (8, 3, 'session2', 'end') ``` I want to display ALL columns of this table **PLUS** a **additional** row called "name". The data in this column is generated from the following conditions: The name is written in the second row of **each** sessionid. This means in fact that I check which row has the tag "**start**". Then the name of the session is written in the column tag **where** counter is **1 higher** than the row with tag = "start". I tried a first query which works for the first **sessionid**, but then fails at second sessionid because it writes "sessionname1" in every row. The **correct** query would return name = "sessionname2" for the rows with id 6,7,8. ``` SELECT t1.*, (SELECT top 1 t2.tag FROM tags t2 JOIN ( SELECT * FROM tags WHERE tag = 'start' ) t3 ON (t2.counter = t3.counter + 1) AND t3.sessionid = t2.sessionid ) AS name FROM tags t1 ``` What do I have to change to get the correct name in each row? Checkout my [SQL Fiddle](http://sqlfiddle.com/#!2/a4f5f/1) ## UPDATE The expected output of course shows **ALL** rows. It would look like the following: ``` id counter sessionid tag name (1, 1, 'session1', 'start', 'sessionname1'), (2, 2, 'session1', 'sessionname1', 'sessionname1'), (3, 3, 'session1', 'unimportant tag','sessionname1'), (4, 4, 'session1', 'unimportant tag','sessionname1'), (5, 5, 'session1', 'end', 'sessionname1'), (6, 1, 'session2', 'start', 'sessionname2'), (7, 2, 'session2', 'sessionname2', 'sessionname2'), (8, 3, 'session2', 'end', 'sessionname2') ``` **IMPORTANT NOTE:** It's important that the trackingcounter column is 1 **bigger** than the row with "start". It is **NOT** every time 2, there is also the possibility that the row with "start" has trackingcounter = 80 and then trackingcounter would have to be 81.
Something like the following should work for you: ``` SELECT tags.*, tagnames.tag AS sessionname FROM tags INNER JOIN (SELECT sessionid, tag FROM tags WHERE counter = 2) AS tagnames ON tags.sessionid = tagnames.sessionid ``` This method works by creating a table that consists only of the session identifier and the name (this is the INNER JOIN subquery) which we then join back on to the main set to allow us to bring in the session name as a distinct column. It makes two assumptions: 1. The `INNER JOIN` specifies that we always expect there to be a name for our session 2. The name tag will always be identified with a session id having `counter = 2` **EDIT:** From your comment, I see we cannot identify the name row by having `counter = 2` BUT it will always be the `second` row for a given sessionid. Therefore, we can do the following to pick out the 2nd row per sessionid: ``` SELECT @previous_session := null; SELECT sessionid, counter, tag, @counter_rank := IF(@previous_session = sessionid, @counter_rank + 1, 1) AS counter_rank, @previous_session := sessionid FROM tags ORDER BY sessionid, counter ASC ``` This generates an "artifical" row number using a [user defined variable](http://dev.mysql.com/doc/refman/5.0/en/user-variables.html) per session group so we can always locate the second record sorted by sessionid and counter. Incorporating this into the first query gives us: ``` SELECT @previous_session := null; SELECT tags.*, tagnames.tag AS sessionname FROM tags INNER JOIN (SELECT countranks.sessionid, countranks.tag FROM ( SELECT sessionid, counter, tag, @counter_rank := IF(@previous_session = sessionid, @counter_rank + 1, 1) AS counter_rank, @previous_session := sessionid FROM tags ORDER BY sessionid, counter ASC ) AS countranks WHERE countranks.counter_rank = 2 ) AS tagnames ON tags.sessionid = tagnames.sessionid; ``` Here's the [sql in action](http://sqlfiddle.com/#!2/a4f5f/44/0)
You can try: ``` SELECT tags.id, tags.counter, tags.sessionid, tags.tag, t.name FROM (tags LEFT JOIN (SELECT sessionid, tag as name FROM tags WHERE counter = 2) as t ON tags.sessionid = t.sessionid ) ; ``` Looks fine tested on [this fiddle](http://sqlfiddle.com/#!2/a4f5f/8)
SQL SELECT generate additional column from same table with special condition
[ "", "mysql", "sql", "select", "inner-join", "conditional-statements", "" ]
I got this similar question but it doesn't help me. ([Anorm parse float values](https://stackoverflow.com/questions/11180429/anorm-parse-float-values)). And I can honestly say I didn't understand the solution of that question. I am getting this complie time error: ``` could not find implicit value for parameter c: anorm.Column[Float] ``` at ``` def getInformation(id: Long): List[(Float, Float, Float)] = { DB.withConnection { implicit con => val query = SQL("select principal,interest,value from myTable where userId={id} and status=true").on("id"->id) val result = query().map { row => Tuple3(row[Float]("principal"), row[Float]("inetrest"), row[Float]("value")) // ^ }.toList return result } } ```
try this... ``` def getInformation(id: Long): List[(Float, Float, Float)] = { DB.withConnection { implicit con => val query = SQL("select principal,interest,value from myTable where userId={id} and status=true").on("id"->id) val result = query().map { row => Tuple3(row[Float]("principal").asInstanceOf[Float], row[Float]("inetrest").asInstanceOf[Float], row[Float]("value").asInstanceOf[Float]) }.toList return result } } implicit def rowToFloat: Column[Float] = Column.nonNull { (value, meta) => val MetaDataItem(qualified, nullable, clazz) = meta value match { case d: Float => Right(d) case _ => Left(TypeDoesNotMatch("Cannot convert " + value + ":" + value.asInstanceOf[AnyRef].getClass + " to Float for column " + qualified)) } } ```
Maybe a short review of implicits help you. Let's construct a very basic example: ``` // some class which will be used as implicit (can be anything) case class SomeImplicitInformation(maybe: Int, with: Int, data: Int) // lets assume we have a function that requires an implicit def functionRequiringImplicit(regularParameters: Int)(implicit imp: SomeImplicitInformation) { // ... } // now if you try to call the function without having an implicit in scope // you would have to pass it explicitly as second parameter list: functionRequiringImplicit(0)(SomeImplicitInformation(0,0,0)) // instead you can declare an implicit somewhere in your scope: implicit val imp = SomeImplicitInformation(0,0,0) // and now you can call: functionRequiringImplicit(0) ``` The error you get simply says that `anorm.Column[Float]` in not in the scope as implicit. You can solve it by adding it implicitly to your scope or pass it explicitly. More detailed instructions for you: Since the `Column` companion object only provides an implicit for `rowToDouble` you simply have to use [the code that is linked in your question](https://stackoverflow.com/a/11184772/1804173). To get it to work put it before your result computation. Later you might want to place it in a `val` in some enclosing scope.
Could not find implicit value for parameter c: anorm.Column[Float]
[ "", "mysql", "sql", "scala", "playframework", "anorm", "" ]
I am trying to create a `sp_send_dbmail` that uses HTML formatting that will send two different tables within 1 email. But I keep getting: > The data types varchar(max) and varchar(max) are incompatible in the '&' operator This script is pulling info from 2 different Views that populate the 2 different tables. I am using SQL Server 2012. ``` DECLARE @MTDResults varchar(max) SET @MTDResults = N'<style type="text/css"> #box-table { font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif; font-size: 12px; text-align: center; border-collapse: collapse; border-top: 7px solid #9baff1; border-bottom: 7px solid #9baff1; } #box-table th { font-size: 13px; font-weight: Bold; background: #b9c9fe; border-right: 2px solid #9baff1; border-left: 2px solid #9baff1; border-bottom: 2px solid #9baff1; color: #039; } #box-table td { border-right: 1px solid #aabcfe; border-left: 1px solid #aabcfe; border-bottom: 1px solid #aabcfe; color: #669; } tr:nth-child(odd) { background-color:#eee; } tr:nth-child(even) { background-color:#fff; } </style>'+ N'<H1><font color="Black">MTD Results</H1>'+ N'<table id="box-table">'+ N'<tr><font color = "Black"> <th> Type </th> <th> Sales </th> <th> Cost </th> <th> Margin </th> <th> Percentage </th> <th> Tons </th> </tr>' + CAST ( ( Select TD = Type,'', TD = Sales,'', TD = Cost,'', TD = Marg,'', TD = Tons from [dbo].[Daily_Sales_MTD_HTML] FOR XML PATH ('tr') ) as varchar(max)) + '</table>' DECLARE @Top10CustMTD varchar(max) SET @Top10CustMTD = N'<style type="text/css"> #box-table { font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif; font-size: 12px; text-align: center; border-collapse: collapse; border-top: 7px solid #9baff1; border-bottom: 7px solid #9baff1; } #box-table th { font-size: 13px; font-weight: Bold; background: #b9c9fe; border-right: 2px solid #9baff1; border-left: 2px solid #9baff1; border-bottom: 2px solid #9baff1; color: #039; } #box-table td { border-right: 1px solid #aabcfe; border-left: 1px solid #aabcfe; border-bottom: 1px solid #aabcfe; color: #669; } tr:nth-child(odd) { background-color:#eee; } tr:nth-child(even) { background-color:#fff; } </style>'+ N'<H1><font color="Black">Top 10 Customers For the Month</H1>'+ N'<table id="box-table">'+ N'<tr><font color = "Black"> <th> Customer Name </th> <th> Sales </th> <th> Margin </th> <th> Percentage </th> </tr>' + CAST ( ( Select TD = Custname,'', TD = Sales,'', TD = Margin,'', TD = Perc,'' from [dbo].[Daily_Sales_10CustMTD_HTML] FOR XML PATH ('tr') ) as varchar(max)) + '</table>' DECLARE @Mergedtable NVARCHAR(max) set @Mergedtable = @MTDResults & @Top10CustMTD EXEC msdb.dbo.sp_send_dbmail @recipients = 'JSmith@email.com', @copy_recipients = '', @subject = 'Daily Sales', @body = @Mergedtable, @body_format = 'html' ```
Change `set @Mergedtable = @MTDResults & @Top10CustMTD` to `set @Mergedtable = @MTDResults + @Top10CustMTD`. `&` is not valid for string concatenation.
`&` in TSQL is, unlike Visual Basic, used for boolean operations, not for varchar concatenations. For it, you should use `+`, providing that both of the entries are varchars: ``` set @Mergedtable = @MTDResults + @Top10CustMTD ``` If one of them is not varchar, you will first have to convert it to varchar (not your case, just for future reference): ``` set @Mergedtable = @MTDResults + convert(varchar(max),@Top10CustMTD) ``` For more info on how `&` is used, see [Ampersand (&) operator in a SQL Server WHERE Clause](https://stackoverflow.com/questions/670230/ampersand-operator-in-a-sql-server-where-clause)
The data types varchar(max) and varchar(max) are incompatible in the '&' operator
[ "", "sql", "sql-server", "sql-server-2012", "" ]
``` ID amount account number(varchar) 5105 0.70 23423423 5105 0.0 null 5105 0.0 null 5104 0.0 null 5104 0.0 null 5104 0.0 null 5106 0.0 32132111 5106 0.0 null ``` I want to get the distinct id for which all of its amount value is 0.0 and account number is null . basicly from this table i want the result as 5104. Can anyone please help i am new to SQL.
``` Select DISTINCT ID FROM TableName GROUP BY ID HAVING SUM(amount)=0.0 ``` Update for another condition( another column which is varchar. It should be null) ``` Select DISTINCT ID FROM TableName WHERE AnotherColumn IS NULL GROUP BY ID HAVING SUM(amount)=0.0 ``` SQL Fiddle: <http://sqlfiddle.com/#!2/145504/3>
``` Select DISTINCT ID FROM TableName GROUP BY ID HAVING min(amount)=0.0 and max(amount)=0.0 ```
SQL Query to select records for rows having value =0 in one column and unique id in another column
[ "", "mysql", "sql", "sql-server", "" ]
I have a field that returns a string value in this format `xxxxxxx(xxxxx)`. Now I need to extract the content of the string inside () as well the ones before (). How can I achieve this?
``` declare @str varchar(100) set @str='xxxxx(aaa)' ---- extracts xxxxx select SUBSTRING(@str,0,CHARINDEX('(',@str)) ---- extracts aaa select SUBSTRING(@str,CHARINDEX('(',@str)+1,CHARINDEX(')',@str)-CHARINDEX('(',@str)-1) ```
Please try: ``` declare @var nvarchar(100)='xxxxxxx(xxxxx)' select @var, LEFT(@var, charindex('(', @var, 1)-1), replace(right(@var, charindex('(', @var, 1)-1), ')', '') ```
Extracting a part of String in SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have a table which contains strings which is needed to be searched [like below image] ![search table](https://i.stack.imgur.com/wmJD9.png) TableA After that, I have a table which stores data [like below image] ![enter image description here](https://i.stack.imgur.com/IDGpt.png) TableB And what the search function does is to select from TableB only if the record contains the string in TableA [i.e. The expected result should be like below image(TableC)] ![enter image description here](https://i.stack.imgur.com/KuxOO.png) TableC I've tried using the SQL below, but the SQL had some error while trying to run [`Incorrect syntax near 'select'`] , also, the SQL is a bit complicated, is there any way to make the SQL simplier? ``` select * from TableB a where exists (select colA from TableB b where b.colA = a.ColA and Contains (b.ColA, select searchCol from TableA)) ```
Please try: ``` select a.* From tblA a inner join tblB b on b.Col like '%'+a.Col+'%' ``` [SQL Fiddle Demo](http://sqlfiddle.com/#!3/1bde1/1)
One of these should work according to me ``` SELECT b.colA FROM TableB b join TableA a WHERE colA like '%' + a.ColA + '%'; SELECT b.colA FROM TableB b join TableA a WHERE INSTR(b.colA, '{' + a.colA + '}') > 0; ```
SQL select from table where column contains specific strings
[ "", "sql", "sql-server", "aggregate-functions", "" ]
I have theses two queries ``` SELECT course, COUNT(*) AS countp FROM table1 WHERE pickout='Yes' GROUP BY course SELECT course, COUNT(*) AS countw FROM table1 WHERE pickout='Yes' AND result='Won' GROUP BY course ``` what I am trying to achieve is a table with three columns `Course`, `Countp`, `Countw` but I am having trouble combining the two into one query. Basically I am looking for a list of course with number of picks and then number of wins.
In MySQL the result of conditions evaluate to `1` or `0`. You can sum that up ``` SELECT course, sum(pickout='Yes') AS countp, sum(pickout='Yes' AND result='Won') AS countw FROM table1 GROUP BY course ```
Try the following SQL: ``` SELECT Course, COUNT(*) AS CountP, SUM(CASE WHEN result='Won' THEN 1 ELSE 0 END) AS CountW FROM table1 WHERE pickout = 'Yes' GROUP BY Course ```
Combining two Count Queries into one
[ "", "mysql", "sql", "" ]
I have two SQL queries that I thought should be equivalent: ``` SELECT COUNT(*) FROM ( SELECT distinct(e.id) FROM entity as e join organization_feature as o on o.entity_id = e.id where exists ( select * from entity where o.feature_id = 2086 and o.string_value is not null ) and ( o.feature_id = 2038 ) GROUP BY e.id ) as res ``` This is the first one and here is the second: ``` SELECT COUNT(*) FROM ( SELECT distinct(e.id) FROM entity as e join organization_feature as o on o.entity_id = e.id where ( o.feature_id = 2038 ) or (o.feature_id = 2086 and o.string_value is not null) GROUP BY e.id having count(*)=2 ) as res ``` The problem is that the first gives me 0 as the count results while the second one gives me 13411. For more information on the structure of my database or to better understand the queries [see here](https://stackoverflow.com/q/23126518/966097) (if people would like me to repost the information here I'm happy to). Can anyone explain why they are not equivalent and provide a "where exists" clause that I will be able to use? EDIT: Thank you everyone for your help, thanks to your advice I realised that I should be using: ``` SELECT COUNT(*) FROM ( SELECT distinct(e.id) FROM entity as e join organization_feature as o on o.entity_id = e.id where exists ( select * from organization_feature as of where of.feature_id = 2086 and of.string_value is not null and of.entity_id = e.id ) and ( o.feature_id = 2038 ) GROUP BY e.id ) as res ``` to accomplish what I was trying to do. as I needed a third variable of to be joined to accomplish the query I was attempting, this provides a solution that is identical to query\_2 as I was trying. Thank you again everyone.
In the other post you are mentioning, if you look at the answer with the `where exists` clause you would see that in this clause **a join was made between the table in your where exists clause and at least one of the tables in your main join** - which you haven't done so in your first query. Based on the queries you posted, the second one should yield you the results that you are interested in.
``` where exists ( select * from entity where o.feature_id = 2086 and o.string_value is not null ) and ( o.feature_id = 2038 ) ``` from the first select is actually suposed to be ``` where exists ( select * from entity where o.feature_id = 2086 and o.string_value is not null ) or ( o.feature_id = 2038 ) ``` since you can't have a record that has the id = 2086 AND id = 2038
Can anyone explain why this first SQL query gives 0 when this second query gives me results
[ "", "mysql", "sql", "" ]
I need to match some gender specific data in a SQL query and am having some difficulty in getting the where clause logic correct. I am attempting to use a case statement, but am getting stuck... maybe the case statement isn't the best way to do this, and if so, any viable alternatives would be appreciated. First, I have a local variable @gender. It will either be 'male', 'female', or null. The table I am pulling the data from has a column called gender, with one of three values, but will never be null: 'male', 'female', or 'either'. The logic is simple. If the local variable is 'male', then I want to retrieve any record that has a gender value of 'male' or 'either'. If the local variable is 'female', then I want to retrieve any record that has a gender value of 'female' or 'either'. If the local variable is null, then I want to retrieve the record no matter what the gender value is, so all three, 'male', 'female' or 'either. Here is what I've attempted so far, and I'm not sure how to proceed: ``` select x from y where UPPER(d.Gender) = case when upper(@gender) = 'MALE' then 'MALE' when upper(@gender) = 'FEMALE' then 'FEMALE' when @gender is null then 'EITHER' end ```
``` select x from y where (( UPPER(d.Gender) = UPPER(@gender) OR UPPER(d.Gender) ='EITHER') AND @gender IS NOT NULL ) OR (@gender IS NULL AND 1=1) ``` `1=1` condition in `WHERE clause` always evaluates to true and is a hack to essentially ignore WHERE statement , so here if `@gender` is passed `NULL` then all rows of table containing gender **'Male' , 'Female' or 'Either'** are returned ie all all rows returned irrespective of gender
Not sure why you are using a case conversion. Is your DB case sensitive? Try this ``` select x from y where UPPER(d.Gender) = upper(@gender) OR UPPER(d.Gender) = UPPER(isnull(@gender,'EITHER')) ```
sql case statement contained in where clause - conditional logic
[ "", "sql", "sql-server", "t-sql", "" ]
Using SQL Server I have two tables Table 1 contains each username and his manager ``` User HisManager John Micheal Gib Mai Sara Mai ``` And Table 2 contains All records for the Users ``` Id UserName Comment Date 1 John [Any comment] [Any Date] 2 Sara [Any comment] [Any Date] ``` Now @ManagerX is logged in into the a page I want to retrieve All records from Table 2 Where @ManagerX is their manager
``` SELECT * from Table2 a inner join (SELECT * FROM Table1 WHERE Manager = 'ManagerX') b ON a.User = b.Username ```
``` SELECT Table2.* FROM Table1 INNER JOIN Table2 ON Table1.User=Table2.UserName WHERE Table2.HisManager = @ManagerX ```
SQL Command - Advanced selecting
[ "", "sql", "sql-server", "database", "select", "" ]
I want to split date in column in 3 fields, I use this query ``` SELECT SUBSTRING(Account.date, 1, 2) AS "Month", SUBSTRING(Account.date, 4, 2) AS "Day", SUBSTRING(Account.date, 7, 4) AS "Year" FROM Account ``` Almost all data is in format `02/11/2000`, but some of it can be `02/November/2000` or `2/11/2000`. Only common thing is that data separated by `/`. How can I separate this column using the delimiter?
Surprisingly `CAST('2/November/2000' as datetime)` works (checked on SQL Server 2008), gives value **2000-11-02 00:00:00.000** ``` SELECT Month(CAST(Account.date AS DateTime)) "Month", Day(CAST(Account.date AS DateTime)) "Day", Year(CAST(Account.date AS DateTime)) "Year", FROM Account ``` But as rightly pointed out in comment how do you know if "02/11/2000" is November 2, 2000 or February 11, 2000? Also the spelling of Month names must be absolutely correct else conversion fails. Since you are storing dates as string there is chance that entry like November , Agust etc could have been made . You should never store date values as strings.
You can do it this way by using `CHARINDEX` and `SUBSTRING` functions ``` select LEFT(Account.date, CHARINDEX('/', Account.date) - 1), SUBSTRING(Account.date, CHARINDEX('/', Account.date) + 1, LEN(Account.date) - CHARINDEX('/', Account.date) - CHARINDEX('/', Account.date, CHARINDEX('/', Account.date)) - 2), REVERSE(LEFT(REVERSE(Account.date), CHARINDEX('/', REVERSE(Account.date)) - 1)) FROM Account ```
SQL Server : split string in SELECT statement
[ "", "sql", "sql-server", "substring", "" ]
I have a table which contain `identity primary key id`, `CNum`, `CUID` and some other columns. I want to select distinct records based on `CNum` and `CUID`, in other words if two records have the same `CNum` and `CUID` I want to get the top one, I tried to group by but it will not work since the want the whole row. ``` with a as (SELECT distinct CNum, CUID FROM Con) select c.CNum from Con c inner join a on a.CNum = c.CNum and a.CUID= c.CUID order by id ``` This approach still gets duplicate records. Anyone knows how to solve the problem?
If you want to select the first row of a set of rows with the same characteristics, you can use the [ROW\_NUMBER() function](http://technet.microsoft.com/en-us/library/ms186734.aspx) and PARTITION BY clause. Something like this: ``` SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY CNum, CUID ORDER BY Id) AS ROWNUM FROM Con ) x WHERE x.ROWNUM = 1 ``` The subquery adds a row number to each row having the same values for CNum/CUID.
You missing `distinct` from final select statement ``` select distinct c.CNum from Con c inner join a on a.CNum = c.CNum and a.CUID= c.CUID order by id ```
Select distinct columns sql server
[ "", "sql", "sql-server", "t-sql", "distinct", "distinct-values", "" ]
I am building a hotel booking system and I just got stuck when trying to make a query that retrieves all available room types in a given range. I have two tables `Rooms` and `Reservations`. The `Rooms` table hold the rooms in the hotel. Their number (`id`) and their type (`type`). Table `Reservations` holds the reservations made by the clients. The reservation number (`id`), the associated room number (`room_id`), and date range (`from` and `to`) I have tried this query: ``` SELECT room_id as available_room_number, type FROM roomstesting LEFT JOIN reservations ON roomstesting.id = reservations.room_id WHERE reservations.id NOT IN (reservations.e_from <='"2014-03-07 19:00:00' AND reservations.e_to >='2014-03-08 19:00:00') ``` I was trying to get all the available room types in the range from March 7 to March 8. I was expecting to get the `modern room` as result of the query. Because `modern room id 4` has no reservations made overlapping with the date range and all the other 3 rooms all have reservations made from March 6 to March 9. But I am not getting the result I want. Below is the structure of my database (simplified) Rooms ``` | id | type | ||||||||||||||||||||| | 1 | master suite | | 2 | master suite | | 3 | modern room | | 4 | modern room | ``` Reservations ``` | id | room_id | from | to | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| | 1 | 1 | 2014-03-05 08:00:00 | 2014-03-09 08:00:00 | | 2 | 2 | 2014-03-05 08:00:00 | 2014-03-09 08:00:00 | | 3 | 3 | 2014-03-05 08:00:00 | 2014-03-09 08:00:00 | ``` Expected result ``` | available_room_number | type | |||||||||||||||||||||||||||||||||||||| | 4 | modern room| ``` If anyone here can tell me how I should approach this that would be perfect. Looking forward to your replies.
Try this: ``` SELECT * FROM Rooms WHERE ID NOT IN(SELECT room_id FROM reservations WHERE '2014-03-07 19:00:00' < e_to AND '2014-03-08 19:00:00' > e_from) ```
Why not just reverse the comparison signs WHERE reservations.e\_from >'2014-03-07 19:00:00' AND reservations.e\_to <'2014-03-08 19:00:00'
Select available rooms in given date range
[ "", "mysql", "sql", "" ]
I am trying to deploy the shared dataset in Visual Studio 2010 solution to Sql server 2012 reporting services. But always getting the below error: > The feature: "Shared dataset" is not supported in this edition of Reporting Services.
Depends on what version of SQL Server you're using. If it's Express Edition Advanced or Workgroup or Web edition, I think it's not supported. [www.katieandemil.com](http://www.katieandemil.com/ssrs-the-feature-shared-dataset-is-not-supported-in-this-edition-of-reporting-services)
Shared dataset are absent in express, web & workgroup versions [see msdn link](http://msdn.microsoft.com/en-us/library/ms365156.aspx)
Shared Dataset is not supported with sql server 2012 reporting services
[ "", "sql", "sql-server", "reporting-services", "sql-server-2012", "ssrs-2008", "" ]
In PostgreSQL, is it possible to generate a series of repeating numbers? For example, I want to generate the numbers 1 to 10, with each number repeated 3 times: ``` 1 1 1 2 2 2 3 3 3 .. and so on. ```
You could cross join it to a series of 3: ``` SELECT a.n from generate_series(1, 100) as a(n), generate_series(1, 3) ```
You could try integer division like this: ``` SELECT generate_series(3, 100) / 3 ```
How can I generate a series of repeating numbers in PostgreSQL?
[ "", "sql", "postgresql", "generate-series", "" ]
I want to combine two queries on the same table that has group by. Here is my table : ``` Date##### | Value1 | Value2 | Value3 | Type ------------------------------------------------------ 23/04/2014 | 1,2 | 12,3 | 10 | Green 23/04/2014 | 11,2 | 3 | 10,3 | Non-Green 24/04/2014 | 10,9 | 3 | 11 | Green 24/04/2014 | 2,3 | 12,3 | 8 | Green 24/04/2014 | 10 | 1 | 11 | Non-Green 25/04/2014 | 10 | 2 | 10,8 | Non-Green 25/04/2014 | 1,4 | 5 | 12 | Green ``` The values are of `Decimal` type. Count the value1, value2, value3 >= 10. the expected result: ``` Date##### | Green |Non-Green ------------------------------ 23/04/2014 | 2 | 2 24/04/2014 | 3 | 2 25/04/2014 | 1 | 2 ``` The value on green and non-green was from counting >= 10 of value1, value2, value3, here is my first query : ``` Dim strCommand As String = "SELECT d, LW, cnt FROM(SELECT TOP 7 [date] AS d, [Type] as LW, SUM(CASE WHEN Value1 >= 10 THEN 1 ELSE 0 END + CASE WHEN Value2 >= 10 THEN 1 ELSE 0 END + CASE WHEN Value3 >= 10 THEN 1 ELSE 0 END) AS cnt FROM tbBooth where Type = 'Green' GROUP BY [date],[Type] ORDER BY [date] DESC) x ORDER BY d ASC" ``` It display : ``` Date##### | Cnt |Type ------------------------ 23/04/2014 | 2 | Green 24/04/2014 | 3 | Green 25/04/2014 | 1 | Green ``` My second query : ``` Dim strCommand As String = "SELECT d, LW, cnt FROM(SELECT TOP 7 [date] AS d, [Type] as LW, SUM(CASE WHEN Value1 >= 10 THEN 1 ELSE 0 END + CASE WHEN Value2 >= 10 THEN 1 ELSE 0 END + CASE WHEN Value3 >= 10 THEN 1 ELSE 0 END) AS cnt FROM tbBooth where Type = 'Non-Green' GROUP BY [date],[Type] ORDER BY [date] DESC) x ORDER BY d ASC" ``` It display : ``` Date##### | Cnt |Type ------------------------ 23/04/2014 | 2 | Non-Green 24/04/2014 | 2 | Non-Green 25/04/2014 | 2 | Non-Green ``` I want to combine both query to become one, and take the **date**, result of **green** and result of **non-green**. Assume that I have a lot of group of date, I want it to display only the last 7 group of date based on `ASC` order. Is there anyway how to do it? I tried to look on other SO post, like using UNION or PIVOT but I don't have any clue how to implement it on my code. Sorry, I already post this question yesterday, this is an edit with the expected result.... Thanks in advance....
``` SELECT d, sum(CASE WHEN LW = 'Green' THEN cnt ELSE 0 END) [Green], sum(CASE WHEN LW = 'Non-Green' THEN cnt ELSE 0 END) [Non-Green] FROM ( SELECT [date] AS d, [Type] as LW, CASE WHEN Value1 >= 10 THEN 1 ELSE 0 END + CASE WHEN Value2 >= 10 THEN 1 ELSE 0 END + CASE WHEN Value3 >= 10 THEN 1 ELSE 0 END AS cnt, DENSE_RANK() over (ORDER BY [date] DESC) dr FROM tbBooth WHERE Type in ('Green','Non-Green') ) x WHERE dr < 8 GROUP BY d ORDER BY d ASC ```
You could use two case statements, one for each value; here I'm splitting the rows up in a common table expression first to simplify the cases somewhat; ``` WITH cte AS ( SELECT date, type, value1 value FROM tbBooth UNION ALL SELECT date, type, value2 value FROM tbBooth UNION ALL SELECT date, type, value3 value FROM tbBooth ) SELECT date d, SUM(CASE WHEN type='Green' AND value>=10.0 THEN 1 ELSE 0 END) Green, SUM(CASE WHEN type='Non-Green' AND value>=10.0 THEN 1 ELSE 0 END) NonGreen FROM cte GROUP BY [date] ORDER BY [date] DESC ``` [An SQLfiddle to test with](http://sqlfiddle.com/#!3/ecad3/1).
SQL Server : how to combine two select queries from the same table and take the result on Column
[ "", "sql", "sql-server", "select", "pivot", "union", "" ]
``` CREATE TABLE orders ( id SERIAL PRIMARY KEY, productid INTEGER[] NOT NULL, amount INTEGER[] NOT NULL, totalprice FLOAT NOT NULL, ordertime TIMESTAMP NOT NULL, FOREIGN KEY (productid) REFERENCES products(id) ); ``` I was trying to create a table to record orders. Since that one order may contain more than one product, I plan to use an array to record the productids of every product, same thing with amount. However when I want to make the productid a foreign key which references the id attribute of table product, I found that productid is an array but products(id) is just one number. How can I solve this to make every element of the productid array reference the products(id)?? I am using postgresql btw. Thx adhead!
I think to solve this issue you can use a table for "orders" and another table for "products" if the relationship between them one:many put the FOREIGN KEY in "products" table however, it seems that the relationship is many:many, so create a new table "order-product" that has the two key from the other two tables.
Arrays of foreign keys are not supported by PostgreSQL at this time. Support was proposed for PostgreSQL 9.4, but performance and implementation quality issues lead to its being dropped from the release. It might be added in a future release, or might not. As of 9.6 I don't see anybody working on it. You *can not* use a `CHECK` constraint instead, as they do not support subqueries, a `FROM` clause, or references to columns in other tables. While it's possible to trick the parser by writing a function to hide the query of the other table then using the function in the `CHECK` expression, this *is not correct and will not work reliably*. I strongly suggest normalising the table instead, so you use multiple individual records instead of arrays.
SQL Foreign Key Array referencing non-array
[ "", "sql", "postgresql", "" ]
I am trying to count total Logged In time for every user for my application. I am providing necessary DDL and DML queries for necessary test data [here](http://sqlfiddle.com/#!2/61bb7/1). I tried this Query for resolving my purpose. ``` select userId, sum(loginTimeInHour) as loginTimeInHour from( select e1.userId, (TIME_TO_SEC(TIMEDIFF(IFNULL(e2.time,NOW()),e1.time)))/(60*60) as loginTimeInHour from EventLog e1 left join EventLog e2 on e1.userId = e2.userId and e2.eventType = 'LOGOUT' and e1.time < e2.time where e1.eventType = 'LOGIN' group by e1.id having min(IFNULL(e2.time,NOW()) - e1.time) ) temp group by userId; ``` Here I am getting wrong result in one scenario. Suppose any user1 **login at time t1**, then suppose any how **System didn't able to capture logout** event for user1. And after that user1 **login again at time t2** in the System and **logout at time t3**. So I have to ignore that first event of login which happened at time t1. My Query can't do this. My Query returns me **(t3-t2)+(t3-t1).** My expected result for this scenario is **(t3-t2).** Any help? Thanks in Advance.
You could just find all login/logout without an event between them, and sum the intervals; ``` SELECT e1.userid, SUM(UNIX_TIMESTAMP(COALESCE(e2.time, NOW())) - UNIX_TIMESTAMP(e1.time))/3600 total FROM eventlog e1 LEFT JOIN eventlog e2 ON e1.userid = e2.userid AND e2.eventType='LOGOUT' AND e1.time < e2.time LEFT JOIN eventlog e3 ON e1.userid = e3.userid AND e1.time < e3.time AND e3.time < e2.time WHERE e1.eventType='LOGIN' AND e3.time IS NULL GROUP BY e1.userid ``` [An SQLfiddle to test with](http://sqlfiddle.com/#!2/54c84/1). Note that this (as your original query) does not take time zones into account. The best way to solve that problem is probably to save all times in UTC and use UTC\_TIMESTAMP() instead of NOW() for the query.
You need to check for two conditions. You only want adjacent pairs of login/logout. One way to do this is to find the next logout record. Then, count the number of login records between them. Only choose the number that have no other login records. I prefer to do "next" type calculations using correlated subqueries, rather than non-equijoins and aggregation. Here is how I would write this query: ``` select userid, sum(TIME_TO_SEC(TIMEDIFF(coalesce(el.nextLogoutTime, now()), time))/(60*60)) as loginTimeInHour from (select el.*, (select count(*) from EventLog el2 where el2.userId = el.userId and el2.eventType = 'LOGIN' and el2.time < el.nextLogoutTime and el2.time > el.time ) as NumLogIns from (select el.*, (select max(time) from EventLog el2 where el2.userId = el.userId and el2.eventType = 'LOGOUT' and el2.time > el.time ) as nextLogoutTime from EventLog el where el.eventType = 'LOGIN' ) el ) el where NumLogins = 0 group by el.userid; ```
MySQL count Total Logged In Time for Application
[ "", "mysql", "sql", "" ]
I'm working with Sql server 2008.i have a table contains following columns, ``` Id, Name, Date ``` this table contains more than one record for same id.i want to get distinct id having maximum date.how can i write sql query for this?
Use the ROW\_[NUMBER() function](http://technet.microsoft.com/en-us/library/ms186734.aspx) and PARTITION BY clause. Something like this: ``` SELECT Id, Name, Date FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Date desc) AS ROWNUM FROM [MyTable] ) x WHERE ROWNUM = 1 ```
If you need only `ID` column and other columns are NOT required, then you don't need to go with `ROW_NUMBER` or `MAX` or anything else. You just do a `Group By` over `ID` column, because whatever the maximum date is you will get same ID. ``` SELECT ID FROM table GROUP BY ID --OR SELECT DISTINCT ID FROM table ``` If you need `ID` and `Date` columns with maximum date, then simply do a `Group By` on `ID` column and select the `Max` Date. ``` SELECT ID, Max(Date) AS Date FROM table GROUP BY ID ``` If you need all the columns but 1 line having Max. date then you can go with `ROW_NUMBER` or `MAX` as mentioned in other answers. ``` SELECT * FROM table AS M WHERE Exists( SELECT 1 FROM table WHERE ID = M.ID HAVING M.Date = Max(Date) ) ```
how to get the distinct records based on maximum date?
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2008-r2", "sql-server-2012", "" ]
Provided this sort of db structure how might one write a query to find only movies that have both male and female patrons? ``` movie movID name ticket TID movID patronID patron PID gender ```
I'd say do two queries to get all male patrons and female patrons and then join those based on movID: ``` WITH malePatrons AS ( SELECT name, m.movID FROM movie JOIN ticket tic ON movie.movID = tic.movID JOIN patron pat ON pat.PID = tic.patronID WHERE pat.gender = "male" ), femalePatrons AS ( SELECT name, m.movID FROM movie JOIN ticket tic ON movie.movID = tic.movID JOIN patron pat ON pat.PID = tic.patronID WHERE pat.gender = "female" ) Select * FROM malePatrons JOIN femalePatrons fem ON malePatrons.movID = fem.movID ```
You don't need to query the tables multiple times. My comment may have been a but too obscure, but I was trying to hint you towards something like: ``` select m.name from movie m join ticket t on t.movid = m.movid join patron p on p.pid = t.patronid group by m.movid, m.name having count(distinct p.gender) = 2; ``` This looks for all tickets for all movies, and counts the number of distinct genders of the patron who had those ticketss. (This assumes there are only two genders of course, for simplicity; if you have more then you can add a filter). The `having` clause checks that the count is 2. If a movie only has male or female patrons, not both, the count would be 1, and it would be excluded from the result. [SQL Fiddle demo](http://sqlfiddle.com/#!4/40166/2).
SQL Multiple Values in Same Column
[ "", "sql", "oracle", "" ]
I need to generate a report 12 months before the current date. Today is 2014-04-29. So my date range would be 2013-04-29 to 2014-04-29. These is my sample data: ``` -------------------------------------- -- user_id | lead_id | date_entered -- -- 1 | 1 | 2013-12-05 -- -- 1 | 2 | 2014-03-15 -- -- 1 | 3 | 2014-04-24 -- -------------------------------------- ``` Expected output should be: ``` -------------------------- -- month | year | total -- -- Apr | 2013 | 0 -- -- May | 2013 | 0 -- -- Jun | 2013 | 0 -- -- Jul | 2013 | 0 -- -- Aug | 2013 | 0 -- -- Sep | 2013 | 0 -- -- Oct | 2013 | 0 -- -- Nov | 2013 | 0 -- -- Dec | 2013 | 1 -- -- Jan | 2014 | 0 -- -- Feb | 2014 | 0 -- -- Mar | 2014 | 1 -- -- Apr | 2014 | 1 -- -------------------------- ``` Here is my query: ``` select a.month, a.year, IFNULL(d.total, 0) AS total from ( SELECT 'Apr' month, 2013 year, 1 monthOrder UNION SELECT 'May' month, 2013 year, 2 monthOrder UNION SELECT 'Jun' month, 2013 year, 3 monthOrder UNION SELECT 'Jul' month, 2013 year, 4 monthOrder UNION SELECT 'Aug' month, 2013 year, 5 monthOrder UNION SELECT 'Sep' month, 2013 year, 6 monthOrder UNION SELECT 'Oct' month, 2013 year, 7 monthOrder UNION SELECT 'Nov' month, 2013 year, 8 monthOrder UNION SELECT 'Dec' month, 2013 year, 9 monthOrder UNION SELECT 'Jan' month, 2014 year, 10 monthOrder UNION SELECT 'Feb' month, 2014 year, 11 monthOrder UNION SELECT 'Mar' month, 2014 year, 12 monthOrder UNION SELECT 'Apr' month, 2014 year, 13 monthOrder ) AS a left join ( SELECT date_entered, count(id) AS total FROM leads AS b WHERE user_id = 1 AND is_deleted = 0 AND date_entered BETWEEN "2013-04-29" AND "2014-04-29" GROUP BY YEAR(b.date_entered), MONTH(b.date_entered) ) AS d on a.month = DATE_FORMAT(d.date_entered, "%b") ORDER BY a.monthOrder asc ``` My query's output: ``` -------------------------- -- month | year | total -- -- Apr | 2013 | 1 -- -- May | 2013 | 0 -- -- Jun | 2013 | 0 -- -- Jul | 2013 | 0 -- -- Aug | 2013 | 0 -- -- Sep | 2013 | 0 -- -- Oct | 2013 | 0 -- -- Nov | 2013 | 0 -- -- Dec | 2013 | 1 -- -- Jan | 2014 | 0 -- -- Feb | 2014 | 0 -- -- Mar | 2014 | 1 -- -- Apr | 2014 | 1 -- -------------------------- ``` Because on my `on a.month = DATE_FORMAT(d.date_entered, "%b")` I compare the month that's why `Apr 2013 has a total 1`. How do I fix this issue? Can someone help me? is there a way I can compare both month and year? How do I do that? Thanks
You need to query year on grouping too, using `WHERE a.year=DATE_FORMAT(d.date_entered, "%Y")` as extra condition at top select level. ``` select a.month, a.year, IFNULL(d.total, 0) AS total from ( SELECT 'Apr' month, 2013 year, 1 monthOrder UNION SELECT 'May' month, 2013 year, 2 monthOrder UNION SELECT 'Jun' month, 2013 year, 3 monthOrder UNION SELECT 'Jul' month, 2013 year, 4 monthOrder UNION SELECT 'Aug' month, 2013 year, 5 monthOrder UNION SELECT 'Sep' month, 2013 year, 6 monthOrder UNION SELECT 'Oct' month, 2013 year, 7 monthOrder UNION SELECT 'Nov' month, 2013 year, 8 monthOrder UNION SELECT 'Dec' month, 2013 year, 9 monthOrder UNION SELECT 'Jan' month, 2014 year, 10 monthOrder UNION SELECT 'Feb' month, 2014 year, 11 monthOrder UNION SELECT 'Mar' month, 2014 year, 12 monthOrder UNION SELECT 'Apr' month, 2014 year, 13 monthOrder ) AS a left join ( SELECT date_entered, count(id) AS total FROM leads AS b WHERE user_id = 1 AND is_deleted = 0 AND date_entered BETWEEN "2013-04-29" AND "2014-04-29" GROUP BY YEAR(b.date_entered), MONTH(b.date_entered) ) AS d on a.month = DATE_FORMAT(d.date_entered, "%b") WHERE a.year=DATE_FORMAT(d.date_entered, "%Y") -- this added ORDER BY a.monthOrder asc ``` Or use `AND` instead of `WHERE`, this should have the same effectm as proposed in comments. `on a.month = DATE_FORMAT(d.date_entered, "%b") AND a.year=DATE_FORMAT(d.date_entered, "%Y")`
I think you should simplify and use this hack... basically you format the date in year/month format and group by it as a string, and count. This query alone should give you all the report you need. ``` select concat( DATE_FORMAT(date_entered ,'%Y%m')) as `yearmonth`, count(*) as `total` from leads where user_id=1 and is_deleted = 0 and date_entered BETWEEN "2013-04-29" AND "2014-04-29" group by 1 order by date_entered ``` Try it and tune it according to your needs. Do not add other columns because it will group by those too and you will get wrong results.
Generate report by month and year in mysql
[ "", "mysql", "sql", "report", "" ]
I have a table with a column (`dateDT`), formatted as datetime and a variable input for the year (`@selYear`) in my Select, formatted as int. How can I replace the year within a date from my table with the variable input and return the result in datetime format (within a Select) ? **I have tried the following but this returns wrong dates / years:** ``` CONVERT(DATETIME, (@selYear + MONTH(dateDT) + DAY(dateDT))) AS dateDT, ``` **Example:** ``` @selYear = 2014 dateDT = 2010-05-02 00:00:00.000 ``` **In this case my result should be:** ``` dateDT = 2014-05-02 00:00:00.000 ```
A solution using [DATEADD](https://learn.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql) function: ``` DECLARE @selYear VARCHAR(4) = 2014 DECLARE @dateDT DATETIME = '2010-05-02 00:00:00.000' SELECT DATEADD(YEAR,@selYear - YEAR(@dateDT),@dateDT) ``` --- This is example with smaller then current year: ``` DECLARE @selYear INT = 2009 DECLARE @dateDT DATETIME = '2010-05-02 00:00:00.000' SELECT DATEADD(YEAR,@selYear - YEAR(@dateDT),@dateDT) ```
You can use [DATEFROMPARTS](https://learn.microsoft.com/en-us/sql/t-sql/functions/datefromparts-transact-sql) in sqlserver 2012 ``` DECLARE @selYear int = 2014 DECLARE @dateDT datetime = '2010-05-02' SELECT DATEFROMPARTS(@selYear, DATEPART(m, @dateDT), DATEPART(d, @dateDT)) ```
Replace year in datetime date
[ "", "sql", "sql-server", "t-sql", "datetime", "" ]
I've noticed something odd with Rails (4.1) ActiveRecord, where `select` and `count` sometimes mix badly: ``` User.all.count => 103 User.all.size => 103 User.all.length => 103 ``` So far, so good. I can select on `id`: ``` User.select(:id).all.count => 103 User.select(:id).all.size => 103 User.select(:id).all.length => 103 ``` Still good. I can also select on `email`: ``` User.select(:email).all.count => 103 User.select(:email).all.size => 103 User.select(:email).all.length => 103 ``` But now problems begin. When I select on *both* `id` and `email`: ``` User.select(:id, :email).all.count (0.4ms) SELECT COUNT(id, email) FROM `users` Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' email) FROM `users`' at line 1: SELECT COUNT(id, email) FROM `users` ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' email) FROM `users`' at line 1: SELECT COUNT(id, email) FROM `users` User.select(:id, :email).all.size (0.4ms) SELECT COUNT(id, email) FROM `users` Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' email) FROM `users`' at line 1: SELECT COUNT(id, email) FROM `users` ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' email) FROM `users`' at line 1: SELECT COUNT(id, email) FROM `users` User.select(:id, :email).all.length => 103 ``` Why is it that `count` and `size` (which in this case aliases to `count`) are throwing an exception, and only when I select *more than one* attribute? Is there an explanation for this? I find this quite unexpected.
This is a bug in Rails 4.1. See <https://github.com/rails/rails/issues/13648>
When you use `select` and you have more than one columns for an argument, you need to put it in a string, in this format: ``` User.select("id, email") ``` In other words, the list of columns should only be passed in [pure string](http://guides.rubyonrails.org/active_record_querying.html#pure-string-conditions) format
Rails select() and count() don't seem to play nice
[ "", "sql", "ruby-on-rails", "activerecord", "ruby-on-rails-4", "ruby-on-rails-4.1", "" ]
I executed a Stored Procedure in SQL Server Management Studio 2005 but then i didn't check if the Stored Procedure executed succesfully. I used below command: ``` exec [Stored Procedure name] '[param1]' , '[param2]' ``` Now, i want to find : a) if the Stored Procedure executed succesfully b)what were the results from this execution I could not find any relevant documentation. Can you help?
One other way would be to put the entire body of the sp into an `try-catch` block. At the end of the **try**, `insert into` an audit/log table some values that you are interested in (eg: scope\_identity for inserts, plain text like 'Done!', some time stamps to see when it was ran, etc..) while in the **catch** you do the same but with different values depending on your needs: `ERROR_MESSAGE, ERROR_NUMBER`, 'Error occurred!', etc. There are plenty of ways to 'audit' a stored procedure, you just need to pick one that best suits your needs.
if these are SELECT only, you can only see the output in Result Pane of SSMS or in the application that call the stored procedure. In the server the records will be loaded (cached). To see what is cached in SQL Server memory, see this page [What is cached by sql server](https://dba.stackexchange.com/questions/43572/how-to-see-what-is-cached-in-memory-in-sql-server-2008)
Find results from execution of stored procedure
[ "", "sql", "sql-server", "sql-server-2005", "stored-procedures", "exec", "" ]
I'm using Oracle SQL and I have two tables: ``` Employee: VARCHAR VARCHAR EMP_NUM EMP_NAME ------- -------- 1 Jane 1 Jane 1 Jane 1 Jane 2 Alex 2 Alex 2 Alex 3 Danny 3 Danny Assignment: NUMBER FLOAT FLOAT VARCHAR ASSIGN_NUM ASSIGN_HOURS ASSIGN_CHARGE EMP_NUM ---------- ------------ ------------- ------- 1 3.5 290 1 2 2.6 68.2 3 3 2 406 3 4 4.7 541 2 5 3.3 76 1 ``` and I need to combine them into something like this: ``` TempTable: VARCHAR VARCHAR FLOAT FLOAT EMP_NUM EMP_NAME SUM_HOURS SUM_CHARGE ------- -------- --------- ---------- 1 Jane 27.2 1464 2 Alex 14.1 1623 3 Danny 9.2 948.4 ``` I've tried using this, but it doesn't work: ``` SELECT Assignment.EMP_NUM, Employee.EMP_NAME, SUM(Assignment.ASSIGN_HOURS) SUM_HOURS, SUM(Assignment.ASSIGN_CHARGE) SUM_CHARGE FROM Employee, Assignment WHERE Employee.EMP_NUM = Assignment.EMP_NUM GROUP BY Assignment.EMP_NUM ; ``` But SQL complains with: ``` Error starting at line 1 in command: SELECT Assignment.EMP_NUM, Employee.EMP_NAME, SUM(Assignment.ASSIGN_HOURS) SUM_HOURS, SUM(Assignment.ASSIGN_CHARGE) SUM_CHARGE FROM Employee, Assignment WHERE Employee.EMP_NUM = Assignment.EMP_NUM GROUP BY Assignment.EMP_NUM Error at Command Line:3 Column:5 Error report: SQL Error: ORA-00979: not a GROUP BY expression 00979. 00000 - "not a GROUP BY expression" *Cause: *Action: ``` Even if I remove the `GROUP BY` line, I get an error at `Line:2 Column:5` saying `not a single-group group function`. **Is there any way to get this table**
The query should be like this, you need to list all fields in SELECT clause: ``` SELECT Assignment.EMP_NUM, Employee.EMP_LNAME, SUM(Assignment.ASSIGN_HOURS) SUM_HOURS, SUM(Assignment.ASSIGN_CHARGE) SUM_CHARGE FROM Employee, Assignment WHERE Employee.EMP_NUM = Assignment.EMP_NUM GROUP BY Assignment.EMP_NUM, Employee.EMP_LNAME ; ```
You forgot to include `Employee.EMP_LNAME` in your `GROUP BY` clause. Code should be: ``` SELECT Assignment.EMP_NUM, Employee.EMP_LNAME, SUM(Assignment.ASSIGN_HOURS) SUM_HOURS, SUM(Assignment.ASSIGN_CHARGE) SUM_CHARGE FROM Employee, Assignment WHERE Employee.EMP_NUM = Assignment.EMP_NUM GROUP BY Assignment.EMP_NUM, Employee.EMP_LNAME ```
How do I both sum 1 table and combine that result with another?
[ "", "sql", "oracle", "" ]
I'm following the Stanford's Coursera database course, and there's this query I do not understand. The instructor says that it returns colleges paired with the highest GPA of their applicants. ``` select distinct College.cName, state, GPA from College, Apply, Student where College.cName = Apply.cName and Apply.sID = Student.sID and GPA >= all (select GPA from Student, Apply where Student.sID = Apply.sID and Apply.cName = College.cName); ``` I don't understand the `GPA >= all` part. Doesn't that mean we are looking for rows with GPA that is `>=` ALL applicants, instead of just applicants to a particular college? In other words, I think the query is returning colleges that have applicants with GPA highest everywhere.
``` College.cName = Apply.cName ``` This provides the limit to a particular college. Try removing it.
No, because the select statement following the "GPA >= ALL" statement is correlated to the outer clause - they share the same table correlation names "College" "Apply" "Student". That means that you'll effectively get a a look up against the "College" currently being referenced by the WHERE clause - i.e. for College\_A we look up all students within College\_A, for College\_B we look up all students within College\_B etc.
Not understanding this SQL query
[ "", "sql", "syntax", "" ]
Now I union 3 table and select become below show. ``` |remark|totalA|totalB|tatalC| ----------------------------- | a | 123 | NULL | NULL | | a | NULL | 123 | NULL | | a | NULL | NULL | 123 | ``` How to let it become 1 row as below show? ``` |remark|totalA|totalB|tatalC| ----------------------------- | a | 123 | 123 | 123 | ``` I trying group and distinct it but it show below ``` |remark|totalA|totalB|tatalC| ----------------------------- | a | 123 | NULL | NULL | ```
``` select remark, sum(totalA) as totalA, sum(totalB) as totalB, sum(totalC) as totalC from the_table group by remark ```
Use`sum` along with `group by` as ``` select remark, sum(totalA), sum(totalB), sum(totalC) from table_name group by remark ```
MYSQL - How to let 3 row data become 1 row data
[ "", "mysql", "sql", "" ]
I've got a small issue that I'm not sure how to resolve - I've never encountered it before. I'm using MS SQL and have a SQL JOIN query that queries two tables - Insurance and Creditors. The insurance table holds all the policy details, while the Creditor table holds the company details (Insurance Company/Broker name etc). The Insurance table holds two foreign keys named CreditorID and BrokerID. Both of these foreign keys relate to the same field, being the CreditorID field in the Creditor table (because some creditors are both insurance companies AND insurance brokers). What I'm not sure of is how to write the query. E.g. The Insurance table might look something like this: ``` lInsuranceID lCreditorID lBrokerID mLastPremium dDatePaid sPolicyNumber 1 1 null 1000.00 28/03/2014 12345 2 14 1 2000.00 17/03/2014 67891 ``` And the Creditor table might look something like this: ``` lCreditorID sCreditorName 1 Frank's Insurance COMPANY 14 Frank's Insurance BROKER ``` So the issue is, when I retrieve the information for a particular property, I need to pull info from the Creditor table twice - once with Insurance.CreditorID = Creditor.CreditorID and again with Insurance.CreditorID = Creditor.BrokerID. But I don't know how to do that in one join. I tried this, but it didn't work (I get an error that says "Creditor.sCreditorName" could not be bound: ``` SELECT Insurance.sPolicyNumber, Insurance.dDatePaid, Insurance.dRenewal, Insurance.mLastPremium, Creditor.sCreditorName FROM Insurance INNER JOIN Creditor cred ON Insurance.lCreditorID = cred.lCreditorID INNER JOIN Creditor cred1 ON Insurance.lBrokerID = cred1.lCreditorID WHERE Insurance.lOwnersCorporationID = '1' ``` Any suggestions? **EDIT** Ok thanks for all the tips, peeps. I amended the query to look like this and it appears to be working (I'm such a JOIN noob. Even though it works, I'm not sure why) ``` SELECT Insurance.sPolicyNumber, Insurance.dDatePaid, Insurance.dRenewal, Insurance.mLastPremium, cred.sCreditorName as Company, cred1.sCreditorName as Broker FROM Insurance LEFT JOIN Creditor cred ON Insurance.lCreditorID = cred.lCreditorID LEFT JOIN Creditor cred1 ON Insurance.lBrokerID = cred1.lCreditorID WHERE Insurance.lOwnersCorporationID = '1' ```
You just need to use the table alias in the SELECT expression list: ``` SELECT i.sPolicyNumber, i.dDatePaid, i.dRenewal, i.mLastPremium, c.sCreditorName, b.sCreditorName FROM Insurance i LEFT JOIN Creditor c ON c.lCreditorID = i.lCreditorID LEFT JOIN Creditor b ON b.lCreditorID = i.lBrokerID WHERE Insurance.lOwnersCorporationID = '1' ``` Notice that I switched to LEFT OUTER JOINs. That is because you have shown that the referencing values may be NULLable. If you don't use OUTER JOINs you will loose rows from the Insurance table, which I think is undesirable for you.
In you original query, you are refer "Creditor.sCreditorName", however you are using the alias cred in the join. also, you are using inner joins, which may lead out some entries, in case the FK is null. Eg your entry with lInsuranceID = 1 would be missed out. A correct query could be ``` SELECT ins.sPolicyNumber, ins.dDatePaid, ins.dRenewal, ins.mLastPremium, cred.sCreditorName as CreditorName, brok.sCreditorName as BrokerName FROM Insurance ins LEFT JOIN Creditor cred ON ins.lCreditorID = cred.lCreditorID LEFT JOIN Creditor brok ON ins.lBrokerID = brok.lCreditorID WHERE ins.lOwnersCorporationID = '1' ``` Some testing in MSSQL: ``` declare @Insurance table ( lInsuranceID int, lCreditorID int, lBrokerID int, mLastPremium money, dDatePaid date, sPolicyNumber int ) INSERT INTO @Insurance (lInsuranceID, lCreditorID, lBrokerID, mLastPremium, dDatePaid, sPolicyNumber) SELECT 1, 1, null, 1000.00, '2014-03-28', 12345 UNION ALL SELECT 2, 14, 1, 2000.00, '2014-03-17', 67891 declare @Creditor table ( lCreditorID int, sCreditorName varchar(64) ) INSERT INTO @Creditor (lCreditorID, sCreditorName) SELECT 1, 'Frank''s Insurance COMPANY' UNION ALL SELECT 14, 'Frank''s Insurance BROKER' SELECT ins.sPolicyNumber, ins.dDatePaid, ins.mLastPremium, brok.sCreditorName as BrokerName, cred.sCreditorName as CreditorName FROM @Insurance ins LEFT JOIN @Creditor cred on cred.lCreditorID = ins.lCreditorID LEFT JOIN @Creditor brok on brok.lCreditorID = ins.lBrokerID ```
SQL Join Query - two FK, one field
[ "", "sql", "sql-server", "join", "" ]
In my Rails 4 app, I have the following models: ``` class Person < ActiveRecord::Base has_many :addresses end class Address < ActiveRecord::Base belongs_to :person belongs_to :city end class City < ActiveRecord::Base has_many :addresses end ``` I'm using the `:includes` function to return query result into one variable: ``` Address.includes(:person, :city).where("person_id = 1") ``` **It works as expected, except that I do not want the query to return every single column.** Here's what I've tried: * use `select` and specify table name and column names explicitly, e.g. "`city.name`", but Rails generates a big query with outer joins, that can be very costly, especially when there are lots of concurrent requests, so prefer a better solution. * don't want to hard code complete and raw SQL statements, because of maintenance issue later on * create a new "dummy" `belongs_to` relationship like in Address: `belongs_to :city_select_columns, -> { select('name') }, :class => 'City'`, but that doesn't work (actually I'm not sure if that `select` is even supported, only came across documentation about `where` so far). * maybe define `scope` in City and Person? but I'm not sure how it should be defined or if it'd make sense to do it this way Suggestions? Thanks
Have you tried this? ``` class Person < ActiveRecord::Base has_many :addresses has_many :cities, :through => :addresses end class Address < ActiveRecord::Base belongs_to :person belongs_to :city end class City < ActiveRecord::Base has_many :addresses end ``` Then: ``` Person.find(1).cities.pluck(:name) ``` Looks like this generates an `INNER JOIN` but with indexes it shouldn't be too costly?
Did you try `select`? ``` Address.select(<output_columns>).includes(:person, :city).where("person_id = 1") ```
Efficient way to return select columns from Rails 4 ActiveRecord nested query
[ "", "sql", "ruby-on-rails", "ruby-on-rails-4", "scope", "rails-activerecord", "" ]
I'll calculate the amount of employee performance: ``` select Job_Id, Sum(money1) as m1 from T1 where Job_Id='8' group by Job_Id ``` Then I calculated the amount of his salary(in other Table = T2): ``` select Job_Id, Sum(money2) as m2 from T2 where Job_Id='8' group by Job_Id ``` Now, I will get the following: `m1 - m2` How?
I found it: ``` select (select Sum(money1) from T1 where Job_Id='8') - (select Sum(money2) from T2 where Job_Id='8') ```
I think this will do what you want: ``` SELECT job, m1-m2 FROM ( SELECT T1.Job_Id AS job, Sum(money1) as m1, Sum(money2) as m2 FROM T1 LEFT JOIN T2 ON T1.Job_id=T2.Job_id WHERE T1.Job_Id='8' group by T1.Job_Id ) ```
Calculate the credit amount the employee
[ "", "sql", "sql-server", "" ]
I have table article related to another table article\_has\_type The structure of article table is ``` CREATE TABLE `articles` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `titre` VARCHAR(255) NULL DEFAULT NULL, `description` TEXT NULL, ) ``` structure for table article\_has\_type is ``` CREATE TABLE `arhastypes` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `article_id` INT(11) NULL DEFAULT NULL, `type_id` INT(11) NULL DEFAULT NULL, ) ``` I want to get the last article added to each type. Thank you.
Since `id` column is `AUTO INCREMENT`, you can do this: To get the last record in `articles`: ``` SELECT * FROM articles WHERE id=(SELECT MAX(id) FROM articles) ``` To get the details of last records in `arhastypes` for each types: ``` SELECT * FROM arhastypes WHERE id IN (SELECT MAX(id) FROM arhastypes GROUP BY type_id) ``` **EDIT:** To select records from both tables, you can do this: ``` SELECT ART.id,ART.titre,ART.description,ARH.id as arhastypes_id,ARH.type_id FROM arhastypes ARH JOIN articles ART ON ARH.article_id=ART.id WHERE ARH.id IN (SELECT MAX(id) FROM arhastypes GROUP BY type_id) ```
Are looking for this? ``` Select * from articles where id in (select max(id) from articles) Select * from arhastypes where id in (select max(id) from arhastypes) ```
SQL query to retrieve the last record
[ "", "sql", "" ]
I have a table order\_history that is similar to the following: ``` +-------------------------------------------------------------+ | order_history_id | order_id | order_status_id | date_addded | +-------------------------------------------------------------+ | 1 | 1 | 1 | 2014-03-20 | | 2 | 1 | 2 | 2014-03-21 | | 3 | 1 | 3 | 2014-03-29 | | 4 | 2 | 1 | 2014-03-20 | | 5 | 2 | 2 | 2014-03-21 | | 6 | 2 | 3 | 2014-04-02 | | 7 | 3 | 1 | 2014-04-20 | | 8 | 3 | 2 | 2014-04-21 | | 9 | 3 | 3 | 2014-04-22 | +-------------------------------------------------------------+ ``` The order\_status represents the status of an order ``` +-------------------------------+ | order_status_id | name | +-------------------------------+ | 1 | received | | 2 | processed | | 3 | shipped | +-------------------------------+ ``` what i want to do is to pull out all the orders that have been received before 2014-04-01 but not shipped until after 2014-04-01. So in this case the query would just return order\_id 2 as this is the only order that was received before 2014-04-01 yet shipped after. I can't even seem to get started... Any help, hints, or pointers much appreciated.
You can do so ,by joining your tables and count the statues shipped for each order by using expression in sum i.e `SUM(os.name ='shipped') shipped` ``` SELECT o.* ,SUM(os.name ='shipped') shipped FROM orders o LEFT JOIN orders_status os USING(order_status_id) WHERE o.date_addded < '2014-04-01' GROUP BY o.order_id HAVING shipped =0 ``` [**Fiddle Demo**](http://www.sqlfiddle.com/#!2/1799f/13)
You can use INNER JOIN with this, if I get what you really want you can try this: ``` SELECT DISTINCT order_id FROM order_history A INNER JOIN order_status B ON A.order_status_id = B.order_status_id WHERE (A.order_Status_id = '1' AND A.date_added < @date) AND (A.order_status_id = '3' AND A.date_added < @date) ```
SQL select orders depending on status and date
[ "", "mysql", "sql", "opencart", "" ]
Using SQL Server 2005 I need to get the `datediff` of 2 dates that are in the same column, table looks like this: ``` OrderNo OpNo ResType LoadedStartDate ----------------------------------------------------- 12345 1 PAINT 2014-05-01 00:00:00.000 12345 2 PAINT 2014-05-02 00:00:00.000 12345 3 PAINT 2014-05-03 00:00:00.000 12345 4 ASMB 2014-05-04 00:00:00.000 67890 1 PAINT 2014-05-02 00:00:00.000 67890 2 PAINT 2014-05-03 00:00:00.000 67890 3 PAINT 2014-05-04 00:00:00.000 67890 4 ASMB 2014-05-05 00:00:00.000 ``` I need to get the date diff of OpNo 1 and OpNo 4 where they are the same order number. The OpNo will always be 1 and 4 as the ones I am trying to compare, as will the ResType. Output would need to look like this: ``` OrderNo Difference ---------------------- 12345 3 67890 3 ``` Thanks for any help :)
Just join the table to itself: ``` SELECT t1.OrderNo,DATEDIFF(day,t1.LoadedStartDate,t2.LoadedStartDate) FROM UnnamedTableFromQuestion t1 INNER JOIN UnnamedTableFromQuestion t2 on t1.OrderNo = t2.OrderNo WHERE t1.OpNo = 1 and t2.OpNo = 4 ```
Should be pretty straightforward ``` SELECT DATEDIFF(day, (SELECT LoadedStartDate FROM Orders WHERE OrderNo = 12345 AND OpNo = 1), (SELECT LoadedStartDate FROM Orders WHERE OrderNo = 12345 AND OpNo = 4) ) ``` Since inner selects return scalar values - they can be used as parameters for DATEDIFF function To make this work for all orders in a table you can do something like this: ``` SELECT DISTINCT OrderNo, DATEDIFF(day, (SELECT LoadedStartDate FROM Orders WHERE OrderNo = Ord.OrderNo AND OpNo = 1), (SELECT LoadedStartDate FROM Orders WHERE OrderNo = Ord.OrderNo AND OpNo = 4) ) AS Diff FROM Orders Ord ``` **Demo: <http://sqlfiddle.com/#!3/bc085/5>**
DateDiff of 2 dates in the same column SQL
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I use SQL Server 2008 . I try to Make an report and need to calculate a new Column about each row of my table . I write this function : ``` SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Author,,Name> -- Create date: <Create Date, ,> -- Description: <Description, ,> -- ============================================= ALTER FUNCTION [dbo].[fn_CalcProductStock] ( @ProductID INT = NULL , @ToDate DATETIME = NULL , @FinYear INT = NULL , @InventoryID INT = NULL ) RETURNS FLOAT AS BEGIN DECLARE @stock FLOAT SET @stock = ISNULL(( SELECT SUM(IDI.InvDocItemNumbers) FROM InvDocItem IDI LEFT OUTER JOIN InvDoc ID ON IDI.CenterID = ID.CenterID AND IDI.InvDocID = ID.InvDocID WHERE IDI.ProductID = @ProductID AND ID.FinYearID = @FinYear AND ( ID.InventoryID = @InventoryID OR @InventoryID IS NULL ) AND ID.InvDocDate < @ToDate AND ( ID.InvTransTypeID = 1 OR ID.InvTransTypeID = 4 OR ID.InvTransTypeID = 6 OR ID.InvTransTypeID = 13 OR ID.InvTransTypeID = 9 ) ), 0) - ISNULL(( SELECT SUM(II.InvoiceItemNumbers) FROM InvoiceItem II LEFT OUTER JOIN Invoice I ON ( II.CenterID = I.CenterID AND II.InvoiceID = I.InvoiceID ) WHERE II.ProductID = @ProductID AND I.FinYearId = @FinYear AND I.InvoiceDate < @ToDate AND ( I.InventoryID = @InventoryID OR @InventoryID IS NULL ) --Tehran:1 Tehrantakh:101 Mashhad:21 Tabriz:6 AND ( I.InvoiceType = 1 OR I.InvoiceType = 3 ) ), 0) + ISNULL(( SELECT SUM(II.InvoiceItemNumbers) FROM InvoiceItem II LEFT OUTER JOIN Invoice I ON II.CenterID = I.CenterID AND II.InvoiceID = I.InvoiceID WHERE II.ProductID = @ProductID AND I.FinYearId = @FinYear AND I.InvoiceDate < @ToDate AND ( I.InventoryID = @InventoryID OR @InventoryID IS NULL ) AND ( I.InvoiceType = 2 OR I.InvoiceType = 4 ) ), 0) - ISNULL(( SELECT SUM(IDI.InvDocItemNumbers) FROM InvDocItem IDI LEFT OUTER JOIN InvDoc ID ON IDI.CenterID = ID.CenterID AND IDI.InvDocID = ID.InvDocID WHERE IDI.ProductID = @ProductID AND ID.InvTransTypeID = 3 AND ID.FinYearID = @FinYear AND ( ID.InventoryID = @InventoryID OR @InventoryID IS NULL ) AND ID.InvDocDate < @ToDate ), 0) -- Return the result of the function RETURN @stock END ``` also I try to use this fonction in this case : ``` SELECT Prdct.InventoryID , Prdct.ProductID , ( dbo.fn_CalcProductStock(Prdct.ProductID, '2014-04-29', 92, 101) ) FROM ProductInv AS Prdct ``` This have true Calculation Result , but takes long time Like as 40 mins ...!!! for 3000 Products How i can Make it's Performance better ?
You may want to try a [table-valued function](http://technet.microsoft.com/en-us/library/ms189294%28v=sql.105%29.aspx) instead: ``` CREATE FUNCTION Calculated_Product_Stock (@toDate DATETIME, @finYear INT, @inventoryId INT = NULL) RETURNS table AS RETURN (SELECT COALESCE(Doc.productId, Inv.productId) AS productId, COALESCE(Doc.stock, 0) + COALESCE(Inv.stock, 0) AS stock FROM (SELECT Item.productId, SUM(CASE WHEN Doc.invTransTypeId = 3 THEN 0 - Item.invDocItemNumbers ELSE Item.invDocItemNumbers END) AS stock FROM InvDoc Doc JOIN InvDocItem Item ON Item.centerId = Doc.centerId AND Item.invDocId = Doc.invDocId WHERE (@inventoryId IS NULL OR Doc.inventoryId = @inventoryId) AND Doc.finYearId = @finYear AND Doc.invDocDate < @toDate AND Doc.invTransTypeId IN (1, 3, 4, 6, 9, 13) GROUP BY Item.productId) Doc FULL JOIN (SELECT Item.productId, SUM(CASE WHEN Inv.invoiceType IN (1, 3) THEN 0 - Item.invoiceItemNumbers ELSE Item.invoiceItemNumbers END) AS stock FROM Invoice Inv JOIN InvoiceItem Item ON Item.invoiceId = Inv.invoiceId AND Item.centerId = Inv.centerId WHERE (@inventoryId IS NULL OR Inv.inventoryId = @inventoryId) AND Inv.finYearId = @finYear AND Inv.invoiceDate < @toDate AND Inv.invoiceType IN (1, 2, 3, 4) GROUP BY Item.productId) Inv ON Inv.productId = Doc.productId); ``` The function can then be included in a query like so: ``` SELECT Product.inventoryId, Product.productId, COALESCE(Invoice.stock, 0) FROM ProductInv Product LEFT JOIN Calculated_Product_Stock('2014-04-29', 92, 101) Invoice ON Invoice.productId = Product.productId ``` (nothing's been tested, as I have nothing to run it against. And I've never used this feature) As always, test to see if it works for your situation.
I think this will work ``` CREATE FUNCTION [dbo].[usp_CalcProductStock] ( -- Add the parameters for the function here @ProductID INT = NULL ,@ToDate DATETIME = NULL ,@FinYear INT = NULL ,@InventoryID INT = NULL ) RETURNS FLOAT AS BEGIN DECLARE @stock FLOAT DECLARE @DocItems TABLE ( InvTransTypeID INT ,SumOfInvDocItemNumbers BIGINT ) INSERT INTO @DocItems SELECT ID.InvTransTypeID ,SUM(IDI.InvDocItemNumbers) AS SumOfInvDocItemNumbers FROM ( SELECT InvDocItemNumbers ,CenterID ,InvDocID FROM InvDocItem WHERE ProductID = @ProductID ) IDI LEFT JOIN ( SELECT CenterID ,InvDocID ,InvTransTypeID FROM InvDoc WHERE ID.FinYearID = @FinYear AND ( ID.InventoryID = @InventoryID OR @InventoryID IS NULL ) AND ID.InvDocDate < @ToDate ) ID ON IDI.CenterID = ID.CenterID AND IDI.InvDocID = ID.InvDocID HERE GROUP BY ID.InvTransTypeID DECLARE @InvoiceItems TABLE ( InvoiceType NVARCHAR(250) ,SumofInvoiceItemNumbers BIGINT ) INSERT INTO @InvoiceItems SELECT I.InvoiceType ,SUM(II.InvoiceItemNumbers) AS SumofInvoiceItemNumbers FROM ( SELECT CenterID ,InvoiceID ,InvoiceItemNumbers FROM InvoiceItem WHERE ProductID = @ProductID ) II LEFT JOIN ( SELECT CenterID ,InvoiceID ,InvoiceType FROM Invoice WHERE I.FinYearId = @FinYear AND I.InvoiceDate < @ToDate AND ( I.InventoryID = @InventoryID OR @InventoryID IS NULL ) ) I ON II.CenterID = I.CenterID AND II.InvoiceID = I.InvoiceID GROUP BY I.InvoiceType DECLARE @DocItems_I FLOAT; DECLARE @DocItems_II FLOAT; DECLARE @InvoiceItems_I FLOAT; DECLARE @InvoiceItems_II FLOAT; SELECT @DocItems_I = ISNULL(SUM(SumOfInvDocItemNumbers), 0) FROM @DocItems WHERE InvTransTypeID IN ( 1 ,4 ,6 ,9 ,13 ) SELECT @InvoiceItems_I = ISNULL(SUM(SumofInvoiceItemNumbers), 0) FROM @InvoiceItems WHERE InvoiceType IN ( 1 ,3 ) SELECT @InvoiceItems_II = ISNULL(SUM(SumofInvoiceItemNumbers), 0) FROM @InvoiceItems WHERE InvoiceType IN ( 2 ,4 ) SELECT @DocItems_II = ISNULL(SUM(SumOfInvDocItemNumbers), 0) FROM @DocItems WHERE InvTransTypeID IN (3) SET @stock = @DocItems_I - @InvoiceItems_I + @InvoiceItems_II - @DocItems_II RETURN @stock END GO ```
How to Optimize this SQL Script
[ "", "sql", "sql-server", "performance", "sql-server-2008", "t-sql", "" ]
I've spent a bit of time trying to bend regex to my will but its beaten me. Here's the problem, for the following text... ``` --to be matched UPDATE dbo.table UPDATE TOP 10 PERCENT dbo.table --do not match UPDATE #temp UPDATE TOP 10 PERCENT #temp ``` I'd like to match the first two updates statements and not match the last two update statements. So far I have the regex... ``` UPDATE\s?\s+[^#] ``` I've been trying to get the regex to ignore the TOP 10 PERCENT part as its just gets in the way. But I haven't been successful. Thanks in advance. I'm using .net 3.5
I assume you're trying to parse real SQL syntax (looks like SQL Server) so I've tried something that is more suitable for that (rather than just detecting the presence of `#`). You can try regex like: ``` UPDATE\s+(TOP.*?PERCENT\s+)?(?!(#|TOP.*?PERCENT|\s)).* ``` It checks for `UPDATE` followed by optional `TOP.*?PERCENT` and then by something that is not `TOP.*?PERCENT` and doesn't start with `#`. It doesn't check just for the presence of `#` as this may legitimately appear in other position and not mean a temp table.
As I understand it, you want a regex to interact with SQL code, not actually querying a database? You can use a negative look ahead to check if the line has `#temp`: ``` (?m)^(?!.*#temp).*UPDATE ``` `(?!...)` will fail the whole match if what's inside it matches, `^` matches the beginning of the line when combined with the `m` modifier. `(?m)` is the inline version of this modifier, as I don't know how/where you plan on using the regex. See [demo here](http://regex101.com/r/vL3rR1).
Parse SQL with REGEX to find Physical Update
[ "", "sql", "regex", "" ]
I have list of date in MySQL in the format of "MM-DD-YYYY" and When I was trying to fetch the latest date from table it just return the last date of a Year like `12-01-2014` instead of return latest date `03-16-2016`. Payment history table: ``` to_date 03-16-2016 12-01-2014 11-07-2014 10-03-2014 01-09-2014 ``` --- I used following query: ``` SELECT MAX(to_date) FROM paymenthistory WHERE empid=59; ``` `Result : 12-01-2014` Related post: [Get the latest date from grouped MySQL data](https://stackoverflow.com/questions/8470311/get-the-latest-date-from-grouped-mysql-data) Thanks in advance
You're working with strings, not native dates, so you're getting the maximum date. Either convert those strings to ACTUAL mysql date/datetime values, or you'll have to go with ugly hacks, like ``` SELECT MAX(STR_TO_DATE(to_date, '%m-%d-%Y')) ``` and performance will be massively bad. MySQL's native date format is `yyyy-mm-dd hh:mm:ss`, which is a natural "most significant first" format. If your date strings were formatted like that, then even a max(string) would work.
It sounds like your date column is actually a VARCHAR format since it is seeing 12-01-2014 as the last date which is only true if stored as a VARCHAR. Be sure your to\_date column is a DATE type.
How to select latest date from database in MySQL
[ "", "mysql", "sql", "max", "" ]
we implement search on a table like this ``` create proc prcSearchMember ( @UserId uniqueidentifier, @MemberFirstName varchar(20), @MemberMiddleName varchar(20), @MemberLastName varchar(20), @FamilyHeadName varchar(50), @FatherName varchar(50), @MotherName varchar(50), @DOB datetime, @GotraID int, @SectID int, @BloodGroupID int, @EducationLevelID int, @EducationFieldID int, @HouseNumber varchar(20), @StreetName varchar(50), @Area varchar(50), @LandMark varchar(50), @StateID int, @CountryID int, @CityID int, @PhoneNumber varchar(15), @EmailAddress varchar(50), @MaritalStatus varchar(20), @OccupationTypeID int, @Gender varchar(10), @IsSubmit bit ) as if(@MemberFirstName is not null ) Begin Select MemberFirstName,UserId from MemberInfo where MemberFirstName like @MemberFirstName end else if (@MemberMiddleName is not null ) Begin Select MemberFirstName,UserId from MemberInfo where MemberMiddleName like @MemberMiddleName end else if (@MemberMiddleName is not null ) Begin Select MemberFirstName,UserId from MemberInfo where MemberLastName like @MemberLastName end else if (@MemberLastName is not null ) Begin Select MemberFirstName,UserId from MemberInfo where FamilyHeadName like @MemberLastName end else if (@MemberLastName is not null ) Begin Select MemberFirstName,UserId from MemberInfo where FatherName like @FatherName end else if (@MemberLastName is not null ) Begin Select MemberFirstName,UserId from MemberInfo where MotherName like @MotherName end else if (@DOB is not null ) Begin Select MemberFirstName,UserId from MemberInfo where DOB like @DOB end else if (@GotraID is not null ) Begin Select MemberFirstName,UserId from MemberInfo where GotraID like @GotraID end else if (@SectID is not null ) Begin Select MemberFirstName,UserId from MemberInfo where SectID=@SectID end else if (@BloodGroupID is not null ) Begin Select MemberFirstName,UserId from MemberInfo where BloodGroupID like @BloodGroupID end else if (@EducationLevelID is not null ) Begin Select MemberFirstName,UserId from MemberInfo where EducationLevelID=@EducationLevelID end else if (@EducationFieldID is not null ) Begin Select MemberFirstName,UserId from MemberInfo where EducationFieldID like EducationFieldID end else if (@HouseNumber is not null ) Begin Select MemberFirstName,UserId from MemberInfo where HouseNumber like @HouseNumber end else if (@StreetName is not null ) Begin Select MemberFirstName,UserId from MemberInfo where StreetName like @StreetName end else if (@Area is not null ) Begin Select MemberFirstName,UserId from MemberInfo where Area like @Area end else if (@LandMark is not null ) Begin Select MemberFirstName,UserId from MemberInfo where LandMark like @LandMark end else if (@CountryID is not null ) Begin Select MemberFirstName,UserId from MemberInfo where CountryID like @CountryID end else if (@StateID is not null ) Begin select MemberFirstName,UserId from MemberInfo where StateID like @StateID end else if (@CityID is not null ) Begin Select MemberFirstName,UserId from MemberInfo where CityID like CityID end else if (@OccupationTypeID is not null ) Begin Select MemberFirstName,UserId from MemberInfo where OccupationTypeID like @OccupationTypeID end else if (@PhoneNumber is not null ) Begin Select MemberFirstName,UserId from MemberInfo where PhoneNumber like @PhoneNumber end else if (@EmailAddress is not null ) Begin Select MemberFirstName,UserId from MemberInfo where EmailAddress like @EmailAddress end else if (@MaritalStatus is not null ) Begin Select MemberFirstName,UserId from MemberInfo where MaritalStatus like @MaritalStatus end else if (@Gender is not null ) Begin Select MemberFirstName,UserId from MemberInfo where Gender like @Gender end else if (@UserId is not null ) Begin Select MemberFirstName,UserId from MemberInfo where UserId like @UserId ``` these all are the columns of single table so if there is any method to implement search query like this in this way ``` foreach (column_name in INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTableName') select primary_key_coumn from table_name where column_name like @column_name ``` where `@column_name` is the value of particular `column`
Try the following, ``` DECLARE @ColName varchar(126) = 'col_name' DECLARE @ColVal varchar(64) = 'col_val' DECLARE @SQL AS nvarchar(MAX) SET @SQL = '' SELECT @SQL = @SQL + 'SELECT * FROM ' + IST.TABLE_SCHEMA + '.' + IST.TABLE_NAME +' where '+ @ColName +' = '''+ @ColVal +''' ' + CHAR(13) FROM INFORMATION_SCHEMA.TABLES IST INNER JOIN INFORMATION_SCHEMA.COLUMNS ISC ON IST.TABLE_NAME = ISC.TABLE_NAME WHERE ISC.COLUMN_NAME = @ColName EXEC (@SQL) ```
I'm not that sure what it is you're trying to achieve. Are you asking "Is there a beter way fo writing this search?". If so, then yes, absolutely. As far as I can see each `IF` branch selects the same columns so if you make sure all your stored proc arguments are defaulted to `NULL` in the declaration then you can do the following: ``` SELECT MemberFirstName, UserId FROM MemberInfo WHERE (MemberFirstName LIKE @MemberFirstName OR @MemberFirstName IS NULL) AND (MemberMiddleName LIKE @MemberMiddleName OR @MemberMiddleName IS NULL) AND (MemberLastName LIKE @MemberLastName OR @MemberLastName IS NULL) AND --You get the picture by now. Keep adding your conditions here. ``` The optimizer is intelligent enough to not bother with any condition which evaluates to `NULL` (which is why you must make sure the arguments are defaulted to `NULL`). Note that a number of your branches will never be executed because you have: ``` else if (@MemberLastName is not null ) Begin Select MemberFirstName,UserId from MemberInfo where FamilyHeadName like @MemberLastName end else if (@MemberLastName is not null ) Begin Select MemberFirstName,UserId from MemberInfo where FatherName like @FatherName end else if (@MemberLastName is not null ) Begin Select MemberFirstName,UserId from MemberInfo where MotherName like @MotherName end ``` Only the first of those branches will ever be executed. I'm not sure why you're asking about primary key columns and why you want to iterate the columns in a table to get the primary key column? Within a single table the primary key column(s) for that table will be the same for every column name in that table you examine. What difference will that make to you? What is the actual problem you are trying to solve? It is also worth pointing out that since SQL Server 2005 it is recommended that you use the system catalog views and not `INFORMATION_SCHEMA`, and they're pretty simple to use.
Search query on multiple columns of a table?
[ "", "sql", "sql-server-2008", "search", "" ]
Why is there a syntax error near 'for' as SQL Server 2012 reports? Is not DEFAULT FOR syntax available when creating a table, but when altering it? Here is a tutorial about altering a table and adding a default constraint [link](http://www.tutorialsqlserver.com/Create/Default-Value-in-Sql-Server.htm), but I can't get it right when creating it. ``` CREATE TABLE Meal ( MealID int IDENTITY PRIMARY KEY, MealName varchar(50) NOT NULL, IsVege char NOT NULL, MealDescription varchar(150) NOT NULL, CONSTRAINT Ckh_Meal_IsVege CHECK (IsVege in ('t', 'f')), CONSTRAINT Def_Meal_IsVege DEFAUlT ('t') FOR IsVege, ); ```
It's a quirk of the [`CREATE TABLE`](http://technet.microsoft.com/en-us/library/ms174979.aspx) syntax that you can only declare a `DEFAULT` constraint inline, as per [StuartLC's answer](https://stackoverflow.com/a/23366968/15498). You *can* also create table constraints, but these are only: ``` < table_constraint > ::= [ CONSTRAINT constraint_name ] { { PRIMARY KEY | UNIQUE } [ CLUSTERED | NONCLUSTERED ] (column [ ASC | DESC ] [ ,...n ] ) [ WITH FILLFACTOR = fillfactor |WITH ( <index_option> [ , ...n ] ) ] [ ON { partition_scheme_name (partition_column_name) | filegroup | "default" } ] | FOREIGN KEY ( column [ ,...n ] ) REFERENCES referenced_table_name [ ( ref_column [ ,...n ] ) ] [ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ] [ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ] [ NOT FOR REPLICATION ] | CHECK [ NOT FOR REPLICATION ] ( logical_expression ) } ```
Add it immediately after the column definition and lose the `FOR`: ``` IsVege char NOT NULL CONSTRAINT Def_Meal_IsVege DEFAULT 't' ``` [Fiddle here](http://sqlfiddle.com/#!3/1c058)
SQL Server DEFAULT FOR Syntax
[ "", "sql", "sql-server", "default-constraint", "" ]
How to Write Query to Getting Below Output? In database: Table 1: ``` id Company_accountNo 1 123 2 235 3 456 ``` Table 2: ``` id cheque_no company_accnopky amount 1 258 1 100 2 963 1 200 3 147 2 500 4 148 3 800 5 852 2 300 ``` How get output like this? ``` Account_no Total_Amount No_of_Cheque 123 300 2 235 800 2 456 800 1 ``` Thanks in advance..
Try This: ``` SELECT T1.Company_accountNo As Account_no, sum(T2.Amount) As Total_Amount, count(T1.Company_accountNo) AS No_of_Cheque FROM Table1 T1 Inner Join Table2 T2 ON T1.id = T2.company_accnopky Group By T1.Company_accountNo ``` I Think You are Missing **Group By**
``` SELECT a.Company_accountNo Account_no, SUM(b.amount) Total_Amount, COUNT(*) No_of_Cheque FROM table1 a LEFT JOIN table2 b ON a.id=b.company_accnopky GROUP BY a.Company_accountNo ```
How to get each total from database?
[ "", "sql", "oracle", "oracle9i", "" ]
This is my Original Data: ``` Attempt Value Time 1 suspend 1391685762 2 suspend 1391686288 3 suspend 1391686413 4 suspend 1392648082 5 suspend 1392648230 6 suspend 1393255593 7 suspend 1393255953 8 suspend 1393257567 9 suspend 1393257738 9 75 1393341840 10 suspend 1393359336 10 62 1393361876 11 suspend 1393422454 11 87 1393425173 12 suspend 1394622268 13 suspend 1394622275 14 suspend 1394622304 14 85 1394623834 15 suspend 1394622379 16 suspend 1394622441 17 suspend 1394622543 18 suspend 1394622785 19 suspend 1394622968 20 suspend 1394623375 ``` And this is my Target Query Result: ``` Attempt Value Time 1 suspend 1391685762 2 suspend 1391686288 3 suspend 1391686413 4 suspend 1392648082 5 suspend 1392648230 6 suspend 1393255593 7 suspend 1393255953 8 suspend 1393257567 9 75 1393341840 10 62 1393361876 11 87 1393425173 12 suspend 1394622268 13 suspend 1394622275 14 85 1394623834 15 suspend 1394622379 16 suspend 1394622441 17 suspend 1394622543 18 suspend 1394622785 19 suspend 1394622968 20 suspend 1394623375 ``` In the original data, there are two records for Attempts 9, 10, 11, and 14. I need a query that looks at the Value field, if it's a number, then "picks" that record over the one with a value of "suspend". I tried using a group by query like: ``` SELECT Attempt, min(Value), max(Time) FROM t GROUP BY Attempt ``` But this is not what I needed because max(Time) does not correspond to min(Value). I need the original Value, Time pair. Can anyone help me with this query?
You could use a sub query to achieve this result. ``` SELECT Attempt, min(Value) as Value, (SELECT Time FROM t as t1 WHERE t1.Value = min(t.Value) AND t.Attempt = t1.Attempt) as Time FROM t as t GROUP BY Attempt ```
This is the solution I'd go for, which would in my opinion be the fastest: ``` SELECT DISTINCT(`attempt`) as `attempt`, IF(MAX(`value`)=0,'suspend',MAX(`value`)) as `value`, `time` FROM( SELECT `attempt`, IF(`value`='suspend',0,`value`) as `value`, `time` FROM `t` ) as `a` GROUP BY `attempt` ```
SQL picking one record over another
[ "", "mysql", "sql", "" ]
I receive the syntax error message when I try to execute the code shown below > Msg 156, Level 15, State 1, Line 3 > Incorrect syntax near the keyword 'join'. > Msg 156, Level 15, State 1, Line 7 > Incorrect syntax near the keyword 'order'. But when I execute the 2nd query without the brackets () the results are ok. So when I execute the query in a new query window with the brackets in place, I receive this message. A query must be able to run within brackets ?!? Thanks for reading (and hopefully answering XD) my question. I tried to add spaces for readability, I hope it works. ``` SELECT faknr, tot_bdr as verkooporderbedrag FROM [001].[dbo].[frhkrg] faktuur WHERE dagbknr = 70 JOIN (SELECT SUM(amutas.bedrag) AS totaalbedrag_regels, amutak.bkstnr, amutas.reknr, amutas.faktuurnr AS faknr FROM [001].[dbo].[amutak] INNER JOIN [amutas] ON amutak.bkstnr = amutas.bkstnr WHERE amutak.dagbknr = 90 AND status NOT IN ('V', 'O') AND amutas.reknr = 1160 GROUP BY amutak.bkstnr, amutak.bkstnr, amutas.reknr, amutas.faktuurnr ORDER BY amutak.bkstnr DESC) memoriaal ON faktuur.faknr = memoriaal.faknr ``` I've changed the query to the following: ``` SELECT faktuur.faknr, tot_bdr AS verkooporderbedrag, SUM(totaalbedrag_regels) AS Totaalbedrag_verdeling FROM [001].[dbo].[frhkrg] faktuur JOIN (SELECT SUM(amutas.bedrag) AS totaalbedrag_regels,amutak.bkstnr,amutas.reknr,amutas.faktuurnr AS faknr FROM [001].[dbo].[amutak] INNER JOIN [amutas] ON amutak.bkstnr = amutas.bkstnr WHERE amutak.dagbknr = 90 AND status NOT IN ('V', 'O') AND amutas.reknr = 1161 GROUP BY amutak.bkstnr,amutak.bkstnr,amutas.reknr,amutas.faktuurnr) memoriaal ON faktuur.faknr = memoriaal.faknr GROUP BY faktuur.faknr,tot_bdr,totaalbedrag_regels ORDER BY faknr ``` Although my last GROUP BY statement, he still doesn't SUM (and GROUP) the results correctly. Several records are still separate: ``` faknr verkooporderbedrag Totaalbedrag_verdeling 14700218 5115 4880,05 14700218 5115 234,95 ``` The data type of "Totaalbedrag\_verdeling" is a number (I can do mathematical actions with it) and the other two values are the same... Someone has an update? /ME STUPID: A column that must be SUM (or MAX etc) may not be included in the GROUP BY statement ....
The `where` clause comes after the `from` clause: ``` SELECT faknr, tot_bdr as verkooporderbedrag FROM [001].[dbo].[frhkrg] faktuur join (SELECT SUM(amutas.bedrag) as totaalbedrag_regels,amutak.bkstnr,amutas.reknr,amutas.faktuurnr as faknr FROM [001].[dbo].[amutak] inner join [amutas] on amutak.bkstnr = amutas.bkstnr WHERE amutak.dagbknr = 90 and status not in ('V', 'O') and amutas.reknr = 1160 GROUP BY amutak.bkstnr,amutak.bkstnr,amutas.reknr,amutas.faktuurnr ) memoriaal on faktuur.faknr = memoriaal.faknr where faktuurdagbknr = 70; ``` Also, the `order by` in the subquery is superfluous.
Move where clause after the JOIN ON clause and move ORDER BY clause outside subquery ``` SELECT faknr, tot_bdr as verkooporderbedrag FROM [001].[dbo].[frhkrg] faktuur join (SELECT SUM(amutas.bedrag) as totaalbedrag_regels,amutak.bkstnr,amutas.reknr,amutas.faktuurnr as faknr FROM [001].[dbo].[amutak] inner join [amutas] on amutak.bkstnr = amutas.bkstnr WHERE amutak.dagbknr = 90 and status not in ('V', 'O') and amutas.reknr = 1160 GROUP BY amutak.bkstnr,amutak.bkstnr,amutas.reknr,amutas.faktuurnr ) memoriaal on faktuur.faknr = memoriaal.faknr where dagbknr = 70 ORDER BY amutak.bkstnr desc ```
SQL Server 2005 returns error when executing a query with a select query as join
[ "", "sql", "sql-server", "syntax-error", "" ]
Is there any fast way to get rows that are excluded by a query. For instance I run: ``` select * from tblUsers where user_type = 3 ``` I'm looking for a fast to get the rows that were excluded by this query. I understand I can easily change the where clause, but some queries are very complex and take some time to change. With lots of large queries, this task can take very long to do by hand.
Dump the results of your super complex query into a temporary table. ex. ``` create table #Temp ( First varchar(50), Last varchar(50) ) go select * from #Temp ``` then do a join off the original data to get what you are looking for.
For an actual exclusion, you could do: ``` select * from tblUsers EXCEPT select * from tblUsers where user_type = 3 ``` But why not just do ``` select * from tblUsers where user_type <> 3 ```
get rows that were excluded by sql query
[ "", "sql", "sql-server", "" ]
I have a SQLite table like this: ``` GroupID UserID 1 1 1 2 1 3 2 4 2 1 ``` ...and so on. Then, given a list of UserID, I would like to get a groupID that has all those userIDs and only those userIDs. For example, in this table, given a list (1,2,3), the value returned should be 1. For the list (1,4) it should be 2. For the lists (1,2) or (3,4), nothing should be returned. What would be the best way to do this?
``` select GroupID from your_table where UserID in (1,2,3) GROUP BY GroupID HAVING COUNT(*) = 3 ```
You are a little unclear in the question. Would "1" be returned if the list were 2 and 3? This is an example of a set-within-sets subquery. The most general and flexible approach is to use aggregation with a `having` clause: ``` select GroupId from table t group by GroupId having sum(case when UserId = 1 then 1 else 0 end) > 0 and sum(case when UserId = 2 then 1 else 0 end) > 0 and sum(case when UserId = 3 then 1 else 0 end) > 0 and sum(case when UserId not in (1, 2, 3) then 1 else 0 end) = 0; ``` Each clause counts the number of times that each user appears. The `> 0` requires that each user appear at least once. You might find it easier to express this as: ``` select GroupId from table t group by GroupId having count(distinct case when UserId in (1, 2, 3) then UserId) = 3 and count(distinct UserId) = count(*); ``` However, you have to be sure that the "3" matches the number of elements in the `in` statement.
Select based on WHERE-clause on multiple rows
[ "", "sql", "sqlite", "" ]
I can run the following query in SQL: ``` SELECT TOP 1000 [Sample ID] FROM [database].[dbo].[table] ``` And it will output a table with values. I want to get the count of row for the table by doing the following: ``` SELECT COUNT([Sample ID]) FROM [database].[dbo].[table] AS [Total] ``` But I get the following error: `Invalid column name 'Sample ID'.` How can I fix the issue?
Try this: ``` SELECT COUNT(*) [TOTAL] FROM [database].[dbo].[table] ```
You probably mean ``` SELECT COUNT([Sample ID]) AS [Total] FROM [database].[dbo].[table] ```
Why column name is invalid
[ "", "sql", "sql-server", "date", "" ]
I have a table ``` CREATE TABLE tblHistory ( ID INT IDENTITY PRIMARY KEY , Added DATETIME , value1 INT , Value2 INT ) ``` with a lot of history data. As result I want a maximum of 100 rows but from the beginning to the end. In this example [SQL Fiddle](http://sqlfiddle.com/#!3/fe54b/1/0 "SQL Fiddle") I've got 197 rows of data in my table. I want a maximum of 100 rows from beginning to end, in this example.. every second row in my result, so that I don't have more than max 100 rows. If my `History` table has 500 entries, I want for example every fifth entry from my `History` table and so on... I hope someone can help me. Thanks in advance.
If we assume that `id` has no gaps, the following should do what you want, relatively efficiently: ``` select h.* from tblHistory h cross join (select count(*) as cnt from tblHistory) as c where floor(id * 100.0 / cnt) <> floor((id + 1) * 100.0 / cnt); ``` This will select about 100 rows evenly spaced in the data. If `id` doesn't meet these conditions, then use `row_number()` in a subquery.
to get every fifth entry try this: ``` select * from tblHistory where id % 5 = 0 ``` so if you want to get around 100 entries, try something along the lines of this: ``` select * from tblHistory where id % (select round(count(*)/100,0) from tblHistory) = 0 ``` where you take the number of records in tblHistory, divide it by 100 and use that as the amount of records to skip each time
SQL Server 2005: Selecting number of data from a History (From start to end max 100 results)
[ "", "sql", "sql-server", "" ]
I know how left join working for two tables, but how does it work for three (or more ) tables ? ``` SELECT col FROM table1 t1 LEFT JOIN table2 t2 ON t1.col = t2.col LEFT JOIN table3 t3 ON t1.col = t3.col LEFT JOIN table4 t4 ON t1.col = t4.col -- ... WHERE ... ``` How to interpret this statement ? **Update**: What results do you get if you make triple left join ? Consequence of applying of left joins ?
There are different ways you can configure LEFT JOIN when you have 4 tables. ### Query 1 In the question you have (more or less): ``` SELECT t1.col, t2.info2, t3.info3, t4.info4 FROM table1 t1 LEFT JOIN table2 t2 ON t1.col = t2.col LEFT JOIN table3 t3 ON t1.col = t3.col LEFT JOIN table4 t4 ON t1.col = t4.col WHERE ... ``` Note that I've made sure that each table is needed by selecting a value from each table. If there was no column selected from Table4, for example, then the query optimizer would probably spot that and deduce that it does not need to even look at Table4. The query is a bit like a snowflake; Table1 is (left) joined in turn Table2, Table3 and Table4. All the rows in Table1 that match the criteria in the WHERE clause will appear in the output (at least once). If there are any rows in Table2 that match the `ON t1.col = t2.col` condition, they will be selected; if there are no such rows, a row of NULLs will be used instead. Suppose that there are 2 rows in Table2 that match R1 from Table1, and 3 rows in Table3 that match R1 from Table1, and 4 rows in Table4 that match R1. Then there will be 24 rows in the output for R1 (unless the WHERE clause eliminates some of those). ### Query 2 ``` SELECT t1.col, t2.info2, t3.info3, t4.info4 FROM table1 t1 LEFT JOIN table2 t2 ON t1.col = t2.col LEFT JOIN table3 t3 ON t2.col = t3.col LEFT JOIN table4 t4 ON t3.col = t4.col WHERE ... ``` This is a different query altogether. It is a long chain: Table1 is joined to Table2; Table2 is joined to Table3; and Table3 is joined to Table4. Clearly, you can have other ways of joining the tables too if you wish. ### Sample data Consider this data. The syntax is correct for Informix, but if the TEMP notation for creating a temporary table doesn't work for your DBMS, drop the keyword TEMP and it should be OK. ``` CREATE TEMP TABLE table1 (col CHAR(2) NOT NULL PRIMARY KEY, info1 CHAR(15) NOT NULL); INSERT INTO table1 VALUES('R1', 'Info T1 R1'); INSERT INTO table1 VALUES('R2', 'Info T1 R2'); INSERT INTO table1 VALUES('R3', 'Info T1 R3'); INSERT INTO table1 VALUES('R4', 'Info T1 R4'); INSERT INTO table1 VALUES('R5', 'Info T1 R5'); INSERT INTO table1 VALUES('R6', 'Info T1 R6'); INSERT INTO table1 VALUES('R7', 'Info T1 R7'); INSERT INTO table1 VALUES('R8', 'Info T1 R8'); CREATE TEMP TABLE table2 (col CHAR(2) NOT NULL, info2 CHAR(15) NOT NULL, sub2 INTEGER, PRIMARY KEY(col, sub2)); INSERT INTO table2 VALUES('R1', 'Info T2 R1 V1', 1); INSERT INTO table2 VALUES('R1', 'Info T2 R1 V2', 2); INSERT INTO table2 VALUES('R2', 'Info T2 R2 V1', 1); INSERT INTO table2 VALUES('R5', 'Info T2 R5 V1', 1); INSERT INTO table2 VALUES('R6', 'Info T2 R6 V1', 1); INSERT INTO table2 VALUES('R7', 'Info T2 R7 V1', 1); CREATE TEMP TABLE table3 (col CHAR(2) NOT NULL, info3 CHAR(15) NOT NULL, sub3 INTEGER, PRIMARY KEY(col, sub3)); INSERT INTO table3 VALUES('R1', 'Info T3 R1 V1', 11); INSERT INTO table3 VALUES('R1', 'Info T3 R1 V2', 12); INSERT INTO table3 VALUES('R1', 'Info T3 R1 V3', 13); INSERT INTO table3 VALUES('R3', 'Info T3 R3 V1', 11); INSERT INTO table3 VALUES('R5', 'Info T3 R5 V1', 11); INSERT INTO table3 VALUES('R6', 'Info T3 R6 V1', 11); CREATE TEMP TABLE table4 (col CHAR(2) NOT NULL, info4 CHAR(15) NOT NULL, sub4 INTEGER, PRIMARY KEY(col, sub4)); INSERT INTO table4 VALUES('R1', 'Info T4 R1 V1', 21); INSERT INTO table4 VALUES('R1', 'Info T4 R1 V2', 22); INSERT INTO table4 VALUES('R1', 'Info T4 R1 V3', 23); INSERT INTO table4 VALUES('R1', 'Info T4 R1 V4', 24); INSERT INTO table4 VALUES('R4', 'Info T4 R4 V1', 21); INSERT INTO table4 VALUES('R5', 'Info T4 R5 V1', 21); INSERT INTO table4 VALUES('R5', 'Info T4 R5 V2', 22); ``` The output from the two queries is different. The WHERE clause was omitted altogether. ### Output from Query 1 ``` R1 Info T2 R1 V1 Info T3 R1 V1 Info T4 R1 V1 R1 Info T2 R1 V1 Info T3 R1 V1 Info T4 R1 V2 R1 Info T2 R1 V1 Info T3 R1 V1 Info T4 R1 V3 R1 Info T2 R1 V1 Info T3 R1 V1 Info T4 R1 V4 R1 Info T2 R1 V2 Info T3 R1 V1 Info T4 R1 V1 R1 Info T2 R1 V2 Info T3 R1 V1 Info T4 R1 V2 R1 Info T2 R1 V2 Info T3 R1 V1 Info T4 R1 V3 R1 Info T2 R1 V2 Info T3 R1 V1 Info T4 R1 V4 R1 Info T2 R1 V1 Info T3 R1 V2 Info T4 R1 V1 R1 Info T2 R1 V1 Info T3 R1 V2 Info T4 R1 V2 R1 Info T2 R1 V1 Info T3 R1 V2 Info T4 R1 V3 R1 Info T2 R1 V1 Info T3 R1 V2 Info T4 R1 V4 R1 Info T2 R1 V2 Info T3 R1 V2 Info T4 R1 V1 R1 Info T2 R1 V2 Info T3 R1 V2 Info T4 R1 V2 R1 Info T2 R1 V2 Info T3 R1 V2 Info T4 R1 V3 R1 Info T2 R1 V2 Info T3 R1 V2 Info T4 R1 V4 R1 Info T2 R1 V1 Info T3 R1 V3 Info T4 R1 V1 R1 Info T2 R1 V1 Info T3 R1 V3 Info T4 R1 V2 R1 Info T2 R1 V1 Info T3 R1 V3 Info T4 R1 V3 R1 Info T2 R1 V1 Info T3 R1 V3 Info T4 R1 V4 R1 Info T2 R1 V2 Info T3 R1 V3 Info T4 R1 V1 R1 Info T2 R1 V2 Info T3 R1 V3 Info T4 R1 V2 R1 Info T2 R1 V2 Info T3 R1 V3 Info T4 R1 V3 R1 Info T2 R1 V2 Info T3 R1 V3 Info T4 R1 V4 R2 Info T2 R2 V1 R3 Info T3 R3 V1 R4 Info T4 R4 V1 R5 Info T2 R5 V1 Info T3 R5 V1 Info T4 R5 V1 R5 Info T2 R5 V1 Info T3 R5 V1 Info T4 R5 V2 R6 Info T2 R6 V1 Info T3 R6 V1 R7 Info T2 R7 V1 R8 ``` ### Output from Query 2 ``` R1 Info T2 R1 V1 Info T3 R1 V1 Info T4 R1 V1 R1 Info T2 R1 V1 Info T3 R1 V1 Info T4 R1 V2 R1 Info T2 R1 V1 Info T3 R1 V1 Info T4 R1 V3 R1 Info T2 R1 V1 Info T3 R1 V1 Info T4 R1 V4 R1 Info T2 R1 V1 Info T3 R1 V2 Info T4 R1 V1 R1 Info T2 R1 V1 Info T3 R1 V2 Info T4 R1 V2 R1 Info T2 R1 V1 Info T3 R1 V2 Info T4 R1 V3 R1 Info T2 R1 V1 Info T3 R1 V2 Info T4 R1 V4 R1 Info T2 R1 V1 Info T3 R1 V3 Info T4 R1 V1 R1 Info T2 R1 V1 Info T3 R1 V3 Info T4 R1 V2 R1 Info T2 R1 V1 Info T3 R1 V3 Info T4 R1 V3 R1 Info T2 R1 V1 Info T3 R1 V3 Info T4 R1 V4 R1 Info T2 R1 V2 Info T3 R1 V1 Info T4 R1 V1 R1 Info T2 R1 V2 Info T3 R1 V1 Info T4 R1 V2 R1 Info T2 R1 V2 Info T3 R1 V1 Info T4 R1 V3 R1 Info T2 R1 V2 Info T3 R1 V1 Info T4 R1 V4 R1 Info T2 R1 V2 Info T3 R1 V2 Info T4 R1 V1 R1 Info T2 R1 V2 Info T3 R1 V2 Info T4 R1 V2 R1 Info T2 R1 V2 Info T3 R1 V2 Info T4 R1 V3 R1 Info T2 R1 V2 Info T3 R1 V2 Info T4 R1 V4 R1 Info T2 R1 V2 Info T3 R1 V3 Info T4 R1 V1 R1 Info T2 R1 V2 Info T3 R1 V3 Info T4 R1 V2 R1 Info T2 R1 V2 Info T3 R1 V3 Info T4 R1 V3 R1 Info T2 R1 V2 Info T3 R1 V3 Info T4 R1 V4 R2 Info T2 R2 V1 R3 R4 R5 Info T2 R5 V1 Info T3 R5 V1 Info T4 R5 V1 R5 Info T2 R5 V1 Info T3 R5 V1 Info T4 R5 V2 R6 Info T2 R6 V1 Info T3 R6 V1 R7 Info T2 R7 V1 R8 ```
When you use multiple LEFT JOIN like you post you have to interpret this as the possibility of null values on the tables. In your example, for your query to return values only Table1 needs to have records. You could have empty table2, table3 and table4 and your query will return values anyway. Take this query for instance: ``` SELECT * FROM Prices P RIGHT JOIN Articles A ON P.ArticleID = A.ArticleID LEFT JOIN Sales S ON S.ArticleID = A.ArticleID ``` In this case you get your entire Articles Table, and if you have prices or sales for a certain article, you also get that info, but you always get ALL your articles.
How to understand A Left join B on .... Left join C on..?
[ "", "sql", "left-join", "" ]
I have a table containing information about records. There can be several drafts of each record. To query the info for the highest draft I currently do: ``` select record_id, record_name, record_date from RECSTABLE where record_number = XXXXX AND record_draft = (select max(record_draft) from RECSTABLE where record_number = XXXXX) ``` This returns the correct results, but it's cumbersome. I want to do something more advanced. I have a list or record\_numbers I want to run this query for. The question is how can I do this recursively, how can I optimise this query? Thanks
How about something like this: ``` SELECT RECORD_ID, RECORD_NAME, RECORD_DATE FROM RECSTABLE r INNER JOIN (SELECT RECORD_NUMBER, MAX(RECORD_DRAFT) AS MAX_RECORD_DRAFT FROM RECSTABLE GROUP BY RECORD_NUMBER) m ON (m.RECORD_NUMBER = r.RECORD_NUMBER) WHERE r.RECORD_NUMBER IN (xxxxx, yyyyy, zzzzz) AND r.RECORD_DRAFT = m.MAX_RECORD_DRAFT; ``` Share and enjoy.
Don't use analytic functions for this, but use [LAST](http://docs.oracle.com/cd/E16655_01/server.121/e17209/functions090.htm#SQLRF00653) aggregate function, because it's [faster](http://rwijk.blogspot.nl/2012/09/keep-clause.html). Something like this: ``` select max(record_id) keep (dense_rank last order by record_draft) record_id , max(record_name) keep (dense_rank last order by record_draft) record_name , max(record_date) keep (dense_rank last order by record_draft) record_date from recstable where record_number = XXXXX group by record_number ```
Oracle 10g - SQL - Optimise query and call recursively
[ "", "sql", "oracle", "" ]
I have two tables. Videos; ID, Artist, Title runlog; VideoID, 'joins to videos.ID datetime I'd like to run a query on the Videos table excluding records on three conditions. (as examples. I have multiple conditions, but if I get some help on these, I can probably figure everything else out. * Any video that shows up in Runlog in the past hour will not show up in the results * Any Artist that has had a video show up in the runlog in the past hour will not have any other records by the same Artist show up at all in the query * Any Artist that has had a video show up in the runlog three times in the past 24 hours will not have any other records by the same Artist show up at all in the query This gets me the first result requirement but I feel it could be written better. ``` SELECT ID,Artist, Title FROM videos join runlog on runlog.videoID = videos.id where (select COUNT(*) from runlog where datetime > DATEADD(hh,-12,GETDATE()) and runlog.videoID = videos.id) = 0 order by Artist, Title ``` The second requirement I can't figure out how to put together in the same query.
This query enforces your latter two constraints explicitly and the first implicitly (enforcing the second implicitly enforces the first). It's untested but it should get you on the right track. ``` select ID, Artist, Title from Video where Artist not in ( select V.Artist from Video V, Runlog R where V.ID = R.VideoID and R.datetime > dateadd(hour, -1, getdate()) union select V.Artist from Video V, Runlog R where V.ID = R.VideoID and R.datetime > dateadd(hour, -24, getdate()) group by V.Artist having count(*) > 2 ); ```
``` SELECT ID, Artist, Title FROM videos v join runlog l on l.videoID = v.id WHERE -- 1. All in past hour will not show datetime < DATEADD(hour,-1,GETDATE()) -- 2. and not exists ( select 1 from videos v2 join runlog l2 on l2.videoID = v2.id where v2.Artist = v1.Artist and datetime > DATEADD(hour,-1,GETDATE()) ) -- 3. and not exists ( select 1 from ( select count(1) recordCount from videos v3 join runlog l3 on l3.videoID = v3.id where v3.Artist = v1.Artist and datetime > DATEADD(hour,-24,GETDATE()) ) where recordCount>=3 ) order by Artist, Title ``` OR ``` SELECT ID, Artist, Title FROM videos v join runlog l on l.videoID = v.id WHERE -- 1. All in past hour will not show datetime < DATEADD(hour,-1,GETDATE()) and v1.Artist in ( -- 2. select Artist from videos v2 join runlog l2 on l2.videoID = v2.id where datetime > DATEADD(hour,-1,GETDATE()) union all -- 3. select Artist from videos v3 join runlog l3 on l3.videoID = v3.id where datetime > DATEADD(hour,-24,GETDATE()) group by v3.Artist having count(1) >= 3 ) ```
Exclude records from query based on table join results
[ "", "sql", "sql-server", "" ]
In my sqlplus (for oracle) command line, the backespace doesn't work. How could I configure sqlplus for deleting characters from the command line with backspace? I don't use frequently sqlplus command line, only for making quickly interventions in my DB, it is very hazard for me the times I need to use. Kind Regards. Thanks
which platform are you working on? in case it's linux, have a look at [this section of a wikipedia article on the bash](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29#Keyboard_shortcuts) for some keyboard shortcuts. you should be able to navigate the sqlplus command line with the same shortcuts when you call sqlplus from the shell (bash). specifically, `ctrl-b` would be backspace.
Following the instructions [here](http://www.beyondoracle.com/2008/10/22/improve-sqlplus-before-you-get-crazy/) I was able to do the following and get this working: 1. Type `stty erase` in the terminal 2. Press `CTRL+v` on your keyboard 3. Press the `Backspace Key` on the keyboard (when I did this it put `^H` on the line so my final line looked like `stty erase ^H`) 4. Press enter Now if I start up sql plus I can use the backspace key to delete mistyped characters.
Backspace doesn't work in sqlplus command line
[ "", "sql", "oracle", "sqlplus", "" ]
The only examples I can find addressing this sort of scenario are pretty old, and I'm wondering what the best way is to do this with the latest version of ORMLite... Say I have two tables (simplified): ``` public class Patient { [Alias("PatientId")] [Autoincrement] public int Id { get; set; } public string Name { get; set; } } public class Insurance { [Alias("InsuranceId")] [Autoincrement] public int Id { get; set; } [ForeignKey(typeof("Patient"))] public int PatientId { get; set; } public string Policy { get; set; } public string Level { get; set; } } ``` Patients can have multiple Insurance policies at different "levels" (primary, secondary, etc). I understand the concept of blobbing the insurance information as a Dictionary type object and adding it directly to the [Patient] POCO like this: ``` public class Patient { public Patient() { this.Insurances = new Dictionary<string, Insurance>(); // "string" would be the Level, could be set as an Enum... } [Alias("PatientId")] [Autoincrement] public int Id { get; set; } public string Name { get; set; } public Dictionary<string, Insurance> Insurances { get; set; } } public class Insurance { public string Policy { get; set; } } ``` ...but I need the insurance information to exist in the database as a separate table for use in reporting later. I know I can join those tables in ORMLite, or create a joined View/Stored Proc in SQL to return the data, but it will obviously return multiple rows for the same Patient. ``` SELECT Pat.Name, Ins.Policy, Ins.Level FROM Patient AS Pat JOIN Insurance AS Ins ON Pat.PatientId = Ins.PatientId (Result) "Johnny","ABC123","Primary" "Johnny","987CBA","Secondary" ``` How can I map that into a single JSON response object? I'd like to be able to map a GET request to "/patients/1234" to return a JSON object like: ``` [{ "PatientId":"1234", "Name":"Johnny", "Insurances":[ {"Policy":"ABC123","Level":"Primary"}, {"Policy":"987CBA","Level":"Secondary"} ] }] ``` I don't have a lot of hope in this being do-able in a single query. Can it be done in two (one on the Patient table, and a second on the Insurance table)? How would the results of each query be added to the same response object in this nested fashion? Thanks a ton for any help on this! # Update - 4/29/14 Here's where I'm at...In the "Patient" POCO, I have added the following: ``` public class Patient { [Alias("PatientId")] [Autoincrement] public int Id { get; set; } public string Name { get; set; } [Ignore] public List<Insurance> Insurances { get; set; } // ADDED } ``` Then, when I want to return a patient with multiple Insurances, I do two queries: ``` var patientResult = dbConn.Select<Patient>("PatientId = " + request.PatientId); List<Insurance> insurances = new List<Insurance>(); var insuranceResults = dbConn.Select<Insurance>("PatientId = " + patientResult[0].PatientId); foreach (patientInsurance pi in insuranceResults) { insurances.Add(pi); } patientResult[0].Insurances = insurances; patientResult[0].Message = "Success"; return patientResult; ``` This works! I get nice JSON with nested items for Insurances while maintaining separate related tables in the db. What I don't like is that this object cannot be passed back and forth to the database. That is, I can't use the same nested object to automatically insert/update both the Patient and InsurancePolicy tables at the same time. If I remove the "[Ignore]" decorator, I get a field in the Patient table called "Insurances" of type varchar(max). No good, right? I guess I'm going to need to write some additional code for my PUT/POST methods to extract the "Insurances" node from the JSON, iterate over it, and use each Insurance object to update the database? I'm just hoping I'm not re-inventing the wheel here or doing a ton more work than is necessary. Comments would still be appreciated! Is Mythz on? :-) Thanks...
An alternate more succinct example: ``` public void Put(CreatePatient request) { var patient = new Patient { Name = request.Name, Insurances = request.Insurances.Map(x => new Insurance { Policy = i.Policy, Level = i.Level }) }; db.Save<Patient>(patient, references:true); } ```
References are here to save the day! ``` public class Patient { [Alias("PatientId")] [Autoincrement] public int Id { get; set; } public string Name { get; set; } [Reference] public List<Insurance> Insurances { get; set; } } public class Insurance { [Alias("InsuranceId")] [Autoincrement] public int Id { get; set; } [ForeignKey(typeof("Patient"))] public int PatientId { get; set; } public string Policy { get; set; } public string Level { get; set; } } ``` I can then take a JSON request with a nested "Insurance" array like this: ``` { "Name":"Johnny", "Insurances":[ {"Policy":"ABC123","Level":"Primary"}, {"Policy":"987CBA","Level":"Secondary"} ] } ``` ...to create a new record and save it like this: ``` public bool Put(CreatePatient request) { List<Insurance> insurances = new List<Insurance>(); foreach (Insurance i in request.Insurances) { insurances.Add(new Insurance { Policy = i.Policy, Level = i.Level }); } var patient = new Patient { Name = request.Name, Insurances = insurances }; db.Save<Patient>(patient, references:true); return true; } ``` Bingo! I get the new Patient record, plus 2 new records in the Insurance table with correct foreign key references back to the PatientId that was just created. This is amazing!
One-to-Many relationship with ORMLite
[ "", "sql", "json", "ormlite", "ormlite-servicestack", "" ]
``` Level1 | Level2 | Level3 | Level4 key | value | key |value | key | value | key | value ---------------------|----------------|---------------------|----------------- setting1 | true | | setting1 | true |setting1 | false |setting2 | false| |setting2 | false | | |setting3 | true ``` I have 4 tables. Level1, Level2, Level3, Level4. Each has key value pair. I want to get key, value pair such that if key value pair is present in level1 then it should not check level2,3,4. If it's not present in level1 then it should go to level2 if not then level3. Value will always be present in level4. So final o/p is of type map. ``` key | value --------------------- setting1 | true setting2 | false setting3 | true ``` Is it possible with sql query or do I need to write function or procedure for it?
One approach would be to use CASE - WHEN structure. See this [SQLFiddle](http://sqlfiddle.com/#!12/560b2/1) ``` SELECT CASE WHEN t1."key" IS NOT NULL THEN t1."key" ELSE CASE WHEN t2."key" IS NOT NULL THEN t2."key" ELSE CASE WHEN t3."key" IS NOT NULL THEN t3."key" ELSE t4."key" END END END as "key", CASE WHEN t1."value" IS NOT NULL THEN t1."value" ELSE CASE WHEN t2."value" IS NOT NULL THEN t2."value" ELSE CASE WHEN t3."value" IS NOT NULL THEN t3."value" ELSE t4."value" END END END as "value" FROM table4 t4 LEFT JOIN table1 t1 ON t4."key" = t1."key" LEFT JOIN table2 t2 ON t4."key" = t2."key" LEFT JOIN table3 t3 ON t4."key" = t3."key" ```
You want [DISTINCT ON](http://www.postgresql.org/docs/9.3/static/sql-select.html) with UNION ALL (although a straight UNION would work here too) ``` BEGIN; CREATE TEMP TABLE settings1 (key text, value text, PRIMARY KEY (key)); CREATE TEMP TABLE settings2 (key text, value text, PRIMARY KEY (key)); CREATE TEMP TABLE settings3 (key text, value text, PRIMARY KEY (key)); INSERT INTO settings1 VALUES ('a', 'a1'); INSERT INTO settings2 VALUES ('a', 'a2'); INSERT INTO settings2 VALUES ('b', 'b2'); INSERT INTO settings3 VALUES ('b', 'b3'); INSERT INTO settings3 VALUES ('c', 'c3'); SELECT DISTINCT ON (key) key, value FROM ( SELECT 1 AS lvl, key, value FROM settings1 UNION ALL SELECT 2 AS lvl, key, value FROM settings2 UNION ALL SELECT 3 AS lvl, key, value FROM settings3 ORDER BY key, lvl ) AS settings; ROLLBACK; ``` Gives: ``` key | value -----+------- a | a1 b | b2 c | c3 (3 rows) ```
How to write postgres query for below issue?
[ "", "sql", "postgresql", "select", "" ]
For my database, having these four table First one, DEPARTMENT ``` //DEPARTMENT D# DNAME ------------------ 1 RESEARCH 2 IT 3 SCIENCE ``` Second one, EMPLOYEE ``` //Employee E# ENAME D# ----------------------- 1 ALI 1 2 SITI 2 3 JOHN 2 4 MARY 3 5 CHIRS 3 ``` Third, PROJECT ``` //PROJECT P# PNAME D# ----------------------- 1 Computing 1 2 Coding 3 3 Researching 3 ``` Fourth, WORKSON ``` //WORKSON E# P# Hours -------------------- 1 1 3 1 2 5 4 3 6 ``` So my output should be something like ``` E# ENAME D# TOTAL HOURS/W -------------------------------------------- 1 ALI 1 8 2 SITI 2 0 3 JOHN 2 0 4 MAY 3 6 5 CHIRS 3 0 ``` Display 0 because the employee has no project to works on. my currently statement using ``` SELECT E#,ENAME,D# and sum(Hours) as TOTAL HOURS/W FROM EMPLOYEE,PROJECT,WORKSON WHERE EMPLOYEE.P# ``` no idea how should it select
You should use an left join like this. You only need 2 tables `employee` and `workson`. Try this query: ``` SELECT e_tbl.E#, e_tbl.ENAME, e_tbl.D#, coalesce(SUM(w_tbl.Hours), 0) as "Total Hours/W" FROM EMPLOYEE e_tbl LEFT JOIN WORKSON w_tbl ON e_tbl.E# = w_tbl.E# GROUP BY e_tbl.E# ```
You need to use GROUP BY and JOINS , in order to achieve your output
SELECT sql with four different tables with primary key and foreign key
[ "", "mysql", "sql", "sql-server", "oracle", "" ]
I have the following table: ``` Date Value 4/13/2014 25 4/14/2014 35 4/15/2014 30 4/16/2014 25 4/17/2014 21 4/18/2014 20 4/19/2014 42 4/20/2014 54 4/21/2014 44 4/22/2014 47 4/23/2014 48 4/24/2014 34 4/25/2014 32 4/26/2014 18 4/27/2014 20 4/28/2014 32 4/29/2014 34 ``` Which updates daily. How can I have a SQL query which adds the total `Value` from last week (Sunday-Saturday)? In this case, the Sunday is 4/20 and Saturday is 4/26. I currently have the following query which gets the week from this week: ``` SELECT * , DATENAME(WEEKDAY, Date) AS [DAY], CAST(CONVERT(VARCHAR(12), DATEADD(DAY , 7-DATEPART(WEEKDAY,GETDATE()),GETDATE()), 110) AS DATE) AS 'WeekEnding' FROM [database].[dbo].[table] WHERE Date >= cast(dateadd(day,1-datepart(dw, getdate()), getdate()) as date) --SUNDAY to SATURDAY ```
If I understand your question correctly, you'd like to get the `SUM` of the `Value` field within the timespan of the last Sunday-Saturday. Since you said that the table is updated daily, I'll assume that you mean the last *actual* week, and not just the last week that happens to be in the DB. Here's one query that sums the records by filtering between Sunday-Saturday. In your example data, the total is `277`. ``` SELECT SUM(Value) AS TotalValue FROM ValueTable WHERE Date >= DATEADD(day, -((DATEPART(dw, GETDATE()) + @@DATEFIRST) % 7) - 6, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) AND Date <= DATEADD(day, -(DATEPART(dw, GETDATE()) + @@DATEFIRST) % 7, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) ``` Explanation: the `DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)` parts simply removes the time portion of the current datetime. The other part, `DATEADD(day, -(DATEPART(dw, GETDATE()) + @@DATEFIRST) % 7)` subtract the difference between the current date's `weekday` and Saturday, yield a date of last Saturday.
For Oracle you could try. IW - week number in a year, according to ISO standard: ``` SELECT to_char( Date , 'IW' ), SUM (Value) FROM TableA GROUP BY to_char( Date , 'IW' ); ```
How to get the last week date from Sunday to Saturday
[ "", "sql", "date", "" ]
I have an event system and for my repeat events I am using a cron like system. Repeat Event: ``` +----+----------+--------------+ | id | event_id | repeat_value | +----+----------+--------------+ | 1 | 11 | *_*_* | | 2 | 12 | *_*_2 | | 3 | 13 | *_*_4/2 | | 4 | 14 | 23_*_* | | 5 | 15 | 30_05_* | +----+----------+--------------+ ``` NOTE: The cron value is day\_month\_day of week Event: ``` +----+------------------------+---------------------+---------------------+ | id | name | start_date_time | end_date_time | +----+------------------------+---------------------+---------------------+ | 11 | Repeat daily | 2014-04-30 12:00:00 | 2014-04-30 12:15:00 | | 12 | Repeat weekly | 2014-05-06 12:00:00 | 2014-05-06 13:00:00 | | 13 | Repeat every two weeks | 2014-05-08 12:45:00 | 2014-05-08 13:45:00 | | 14 | Repeat monthly | 2014-05-23 15:15:00 | 2014-05-23 16:00:00 | | 15 | Repeat yearly | 2014-05-30 07:30:00 | 2014-05-30 10:15:00 | +----+------------------------+---------------------+---------------------+ ``` Anyway I have a query to select the events: ``` SELECT * FROM RepeatEvent JOIN `Event` ON `Event`.`id` = `RepeatEvent`.`event_id` ``` That produces: ``` +----+----------+--------------+----+------------------------+---------------------+---------------------+ | id | event_id | repeat_value | id | name | start_date_time | end_date_time | +----+----------+--------------+----+------------------------+---------------------+---------------------+ | 1 | 11 | *_*_* | 11 | Repeat daily | 2014-04-30 12:00:00 | 2014-04-30 12:15:00 | | 2 | 12 | *_*_2 | 12 | Repeat weekly | 2014-05-06 12:00:00 | 2014-05-06 13:00:00 | | 3 | 13 | *_*_4/2 | 13 | Repeat every two weeks | 2014-05-08 12:45:00 | 2014-05-08 13:45:00 | | 4 | 14 | 23_*_* | 14 | Repeat monthly | 2014-05-23 15:15:00 | 2014-05-23 16:00:00 | | 5 | 15 | 30_05_* | 15 | Repeat yearly | 2014-05-30 07:30:00 | 2014-05-30 10:15:00 | +----+----------+--------------+----+------------------------+---------------------+---------------------+ ``` However, I want to select events within a month. I will only have certain conditions: daily, weekly, every two weeks, month and yearly. I want to put in my where clause a way to divide the string of the repeat value and if it fits any of the following conditions to show it as a result (repeatEvent is row that is being interrogated, search is the date being looked for): ``` array(3) = string_divide(repeat_value, '_') daily = array(0) monthy = array(1) dayOfWeek = array(2) if(daily == '*' && month == '*' && dayOfWeek == '*') //returns all the daily events as they will happen return repeatEvent if(if(daily == '*' && month == '*' && dayOfWeek == search.dayOfWeek) //returns all the events on specific day return repeatEvent if(daily == search.date && month == '*' && dayOfWeek == '*') //returns all the daily events as they will happen return repeatEvent if (contains(dayOfWeek, '/')) array(2) = string_divide(dayOfWeek,'/') specificDayOfWeek = array(0); if(specificDayOfWeek == repeatEvent.start_date.dayNumber) if(timestampOf(search.timestamp)-timestampOf(repeatEvent.start_date)/604800 == (0 OR EVEN) return repeatEvent if(daily == search.date && month == search.month && dayOfWeek == '*') //returns a single yearly event (shouldn't often crop up) return repeatEvent //everything else is either an unknown format of repeat_value or not an event on this day ``` To summarise I want to run a query in which the repeat value is split in the where clause and I can interrogate the split items. I have looked at cursors but the internet seems to advise against them. I could process the results of selecting all the repeat events in PHP, however, I imagine this being very slow. Here is what I would like to see if looking at the month of April: ``` +----------+--------------+----+------------------------+---------------------+---------------------+ | event_id | repeat_value | id | name | start_date_time | end_date_time | +----------+--------------+----+------------------------+---------------------+---------------------+ | 11 | *_*_* | 11 | Repeat daily | 2014-04-30 12:00:00 | 2014-04-30 12:15:00 | +----------+--------------+----+------------------------+---------------------+---------------------+ ``` Here is what I would like to see if looking at the month of May ``` +----------+--------------+----+------------------------+---------------------+---------------------+ | event_id | repeat_value | id | name | start_date_time | end_date_time | +----------+--------------+----+------------------------+---------------------+---------------------+ | 11 | *_*_* | 11 | Repeat daily | 2014-04-30 12:00:00 | 2014-04-30 12:15:00 | | 12 | *_*_2 | 12 | Repeat weekly | 2014-05-06 12:00:00 | 2014-05-06 13:00:00 | | 13 | *_*_4/2 | 13 | Repeat every two weeks | 2014-05-08 12:45:00 | 2014-05-08 13:45:00 | | 14 | 23_*_* | 14 | Repeat monthly | 2014-05-23 15:15:00 | 2014-05-23 16:00:00 | | 15 | 30_05_* | 15 | Repeat yearly | 2014-05-30 07:30:00 | 2014-05-30 10:15:00 | +----------+--------------+----+------------------------+---------------------+---------------------+ ``` Here is what I would like to see if looking at the month of June ``` +----------+--------------+----+------------------------+---------------------+---------------------+ | event_id | repeat_value | id | name | start_date_time | end_date_time | +----------+--------------+----+------------------------+---------------------+---------------------+ | 11 | *_*_* | 11 | Repeat daily | 2014-04-30 12:00:00 | 2014-04-30 12:15:00 | | 12 | *_*_2 | 12 | Repeat weekly | 2014-05-06 12:00:00 | 2014-05-06 13:00:00 | | 13 | *_*_4/2 | 13 | Repeat every two weeks | 2014-05-08 12:45:00 | 2014-05-08 13:45:00 | | 14 | 23_*_* | 14 | Repeat monthly | 2014-05-23 15:15:00 | 2014-05-23 16:00:00 | +----------+--------------+----+------------------------+---------------------+---------------------+ ```
You could put a bandaid on this, but no one would be doing you any favors to tell you that that is the answer. If your MySQL database can be changed I would strongly advise you to split your current column with underscores `day_month_day of year` to three separate columns, `day`, `month`, and `day_of_year`. I would also advise you to change your format to be `INT` rather than `VARCHAR`. This will make it faster and MUCH easier to search and parse, because it is designed in a way that doesn't need to be translated into computer language through complicated programs... It is most of the way there already. Here's why: # Reason 1: Your Table is not Optimized Your table is not optimized and will be slowed regardless of what you choose to do at this stage. SQL is not built to have multiple values in one column. The entire point of an SQL database is to split values into different columns and rows. The advantage to normalizing this table is that it will be far quicker to search it, and you will be able to build queries in MySQL. Take a look at [Normalization](http://en.wikipedia.org/wiki/Database_normalization). It is a complicated concept, but once you get it you will avoid creating messy and complicated programs. # Reason 2: Your Table could be tweaked slightly to harness the power of computer date/time functions. Computers follow time based on Unix Epoch Time. It counts seconds and is always running in your computer. In fact, computers have been counting this since, as the name implies, the first Unix computer was ever switched on. Further, each computer and computer based program/system, has built in, quick date and time functions. [MySQL](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_year) is no different. I would also recommend also storing all of these as integers. `repeat_doy` (day of year) can easily be a `smallint` or at least a standard `int`, and instead of putting a month and day, you can put the actual 1-365 day of the year. You can use `DAY_OF_YEAR(NOW())` to input this into MySQL. To pull it back out as a date you can use `MAKEDATE(YEAR(NOW),repeat_doy)`. Instead of an asterisk to signify all, you can either use 0's or NULL. With a cron like system you probably will not need to do that sort of calculation anyway. Instead, it will probably be easier to just measure the day of year elsewhere (every computer and language can do this. In Unix it is just `date "%j"`). # Solution Split your one repeat\_value into three separate values and turn them all into integers based on UNIX time values. Day is 1-7 (or 0-6 for Sunday to Saturday), Month is 1-12, and day of year is 1-365 (remember, we are not including 366 because we are basing our year on an arbitrary non-leap year). If you want to pull information in your `SELECT` query in your original format, it is much easier to use `concat` to merge the three columns than it is to try to search and split on one column. You can also easily harness built in MySQL functions to quickly turn what you pull into real, current, days, without a bunch of effort on your part. To implement it in your SQL database: ``` +----+----------+--------------+--------------+------------+ | id | event_id | repeat_day | repeat_month | repeat_doy | +----+----------+--------------+--------------+------------+ | 1 | 11 | * | * | * | | 2 | 12 | * | * | 2 | | 3 | 13 | * | * | 4/2 | | 4 | 14 | 23 | * | * | | 5 | 15 | 30 | 5 | * | +----+----------+--------------+--------------+------------+ ``` Now you should be able to build one query to get all of this data together regardless of how complicated your query. By normalizing your table, you will be able to fully harness the power of relational databases, without the headaches and hacks. **Edit** Hugo Delsing made a great point in the comments below. In my initial example I provided a fix to leap years for `day_of_year` in which I chose to ignore Feb 29. A much better solution removes the need for a fix. Split `day_of_year` to `month` and `day` with a compound index. He also has a suggestion about weeks and number of weeks, but I will just recommend you read it for more details.
Try to write where condition using this: ``` substring_index(repeat_value,'_', 1) ``` instead of daily ``` substring_index(substring_index(repeat_value,'_', -2), '_', 1) ``` instead of monthly and ``` substring_index(substring_index(repeat_value,'_', -1), '_', 1) ``` instead of dayOfWeek
mysql split a string in a where clause
[ "", "mysql", "sql", "" ]
Say I have an table like this: ``` DROP TABLE tmp; CREATE TABLE tmp (id SERIAL, name TEXT); INSERT INTO tmp VALUES (1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five'); SELECT id, name FROM tmp; ``` It's like this: ``` id | name ----+------- 1 | one 2 | two 3 | three 4 | four 5 | five (5 rows) ``` Then I have an array of `ARRAY[3,1,2]`. I want to get query the table by this array, so I can get an array of `ARRAY['three', 'one', 'two']`. I think this should be very easy but I just can't get it figured out. Thanks in advance.
To preserve the array order, it needs to be unnested with the index order (using `row_number()`), then joined to the `tmp` table: ``` SELECT array_agg(name ORDER BY f.ord) FROM ( select row_number() over() as ord, a FROM unnest(ARRAY[3, 1, 2]) AS a ) AS f JOIN tmp ON tmp.id = f.a; array_agg ----------------- {three,one,two} (1 row) ```
Use `unnest` function: ``` SELECT id, name FROM tmp WHERE id IN (SELECT unnest(your_array)); ``` There is a different technique as suggested by Eelke: You can also use the `any` operator ``` SELECT id, name FROM tmp WHERE id = ANY ARRAY[3, 1, 2]; ```
How to SELECT by an array in postgresql?
[ "", "sql", "postgresql", "" ]
I have a stored procedure that is run by the SQL Agent every x minutes. The stored procedure has a while loop that reads each row and does something with them. I want to handle errors as they occur in the while loop. I need to use `Throw` in the `CATCH` block because then SQL Server Agent will not notify if an error occurred. But the problem is if I use the throw block it breaks out of the while loop but does not process the other records. How can I use `TRY CATCH` in a while loop and if an error occurs it should continue with while loop? This is my code: ``` WHILE @i<@Count OR @Count IS NULL BEGIN SELECT @Id = NULL --Clear variable SELECT TOP 1 @Id = Id, @TableNo = [TableNo], @Action = [Action], @RecId = [RecId], @NDB = dbo.GetDB(CId) FROM dbo.alot WITH (NOLOCK) WHERE CId = @Cid AND Error = 0 AND (@Table IS NULL OR TableNo = @Table) AND Tableno <> 50109 ORDER BY Id IF @Id IS NOT NULL BEGIN SELECT @SQL = N'EXECUTE @RC = ['+dbo.GetDB(@CId)+'].[dbo].[alot_web] @TableNo, @Action, @RecId, @NaviDB' BEGIN TRY IF @RecId = '0-761345-27353-4' BEGIN SELECT 1 / 0; -- Generate an error here. END EXEC master.dbo.sp_executesql @SQL, N'@TableNo nvarchar(12), @Action tinyint, @RecId nvarchar(36), @NDB varchar(12), @RC int OUTPUT' , @TableNo, @Action, @RecId, @NaviDB, @Rc OUTPUT END TRY BEGIN CATCH DECLARE @Description VARCHAR(1024); SELECT @Description = 'WebQueue ID: ' + ISNULL(CAST(@Id AS VARCHAR), '') + ' CompanyID: ' + ISNULL(@Cid, '') + ' Action: ' + ISNULL(CAST(@Action AS VARCHAR), '') + ' RecID: ' + ISNULL(CAST(@RecId AS VARCHAR), '') + ' @RC: ' + ISNULL(CAST(@RC AS VARCHAR), ''); EXEC dbo.LogError @Description; THROW; END CATCH IF @RC = 0 AND @@ERROR = 0 BEGIN IF EXISTS(SELECT * FROM Queue WHERE CId = @CId AND [Action] = @Action AND TableNo = @Tableno AND RecId = @RecID AND Id <> @Id) BEGIN DELETE FROM Queue WHERE CId = @CId AND [Action] = @Action AND TableNo = @Tableno AND RecId = @RecID SELECT @Ok += @@ROWCOUNT END ELSE BEGIN DELETE FROM Queue WHERE Id = @Id SELECT @Ok += @@ROWCOUNT END END ELSE BEGIN IF EXISTS(SELECT * FROM Queue WHERE CId = @CId AND [Action] = @Action AND TableNo = @Tableno AND RecId = @RecID AND Id <> @Id) BEGIN UPDATE Queue SET Error = 1 WHERE CId = @CId AND [Action] = @Action AND TableNo = @Tableno AND RecId = @RecID SELECT @Failed += @@ROWCOUNT END ELSE BEGIN UPDATE Queue SET Error = 1 WHERE Id = @Id SELECT @Failed += @@ROWCOUNT END END END ELSE BREAK SELECT @i += 1 /*IF @i>0 BEGIN--logging >> INSERT INTO [AdminDB].[dbo].[Replication_Log] ([Date],[CId],[Loops],[DurationSS],[Ok],[Failed]) SELECT Getdate(),@CId,@i,DATEDIFF(ss,@Startdt,getdate()),@Ok,@Failed END */ END ```
Replace your THROW with CONTINUE; this way the next record will be processed without Canceling the code. (EDITED!) since you log your errors with ``` EXEC dbo.LogError @Description; ``` i think you don't need to rethrow the error. Since you stated you don't want the program to end. example of CONTINUE: ``` DECLARE @intFlag INT SET @intFlag = 1 WHILE (@intFlag <=5) BEGIN PRINT @intFlag SET @intFlag = @intFlag + 1 CONTINUE; IF @intFlag = 4 -- This will never executed BREAK; END GO ``` source : <http://blog.sqlauthority.com/2007/10/24/sql-server-simple-example-of-while-loop-with-continue-and-break-keywords/> EDIT: for your job agent: create a new variable at the top of your procedure : ``` int @ErrorAmount = 0 ``` your catch would need to look like this: ``` BEGIN CATCH DECLARE @Description VARCHAR(1024); SELECT @Description = 'WebQueue ID: ' + ISNULL(CAST(@Id AS VARCHAR), '') + ' CompanyID: ' + ISNULL(@Cid, '') + ' Action: ' + ISNULL(CAST(@Action AS VARCHAR), '') + ' RecID: ' + ISNULL(CAST(@RecId AS VARCHAR), '') + ' @RC: ' + ISNULL(CAST(@RC AS VARCHAR), ''); EXEC dbo.LogError @Description; SET @ErrorAmount = @ErrorAmount+1; --add this line CONTINUE; --REPLACE THROW with CONTINUE END CATCH ``` at the end of your procedure Add ``` if @ErrorAmount > 0 BEGIN THROW 6000,'Your message' , 1; END ``` this way your Agent will show you the error and your whole process still did the job.
Your `THROW` raises an exception which causes the SP to stop processing. Essentially you are catching any errors that occur but rethrowing them which will indeed break out of the `while` loop. Remove it and the sp should then just continue as normal.
SQL Server Try Catch
[ "", "sql", "sql-server", "t-sql", "" ]
I have a problem with closing the SQLconnection in my application. My application is in VB.net. I have a reference in my application to a class with code to open and close the database connection and to execute all sql scripts. The error occurs when i close my application. In the formClosing event of my main form I call a function that closes all the connections. But just before I close the connections I perform an SQLquery to delete a row from a table with the function below. ``` Public Function DeleteFunction(ByVal mySQLQuery As String, ByVal cmd As SqlCommand) As Boolean Try cmd.Connection = myConnection cmd.CommandText = mySQLQuery cmd.ExecuteNonQuery() Return True Catch ex As Exception WriteErrorMessage("DeleteFunction", ex, Logpath, "SQL Error: " & mySQLQuery) Return False End Try End Function ``` In my application I check the result of the boolean. If it returns True, then i call the function to close the database connection. The returned boolean is True and the requested row is deleted in my database. This means i can close my connection which I do with the function below. ``` Public Sub DatabaseConnClose() myCommand.CommandText = "" myConnection.Close() myCommand = Nothing myConnection = Nothing End Sub ``` After executing this code I receive an error in my logfile from the DeleteFunction. It says: "Connection property has not been initialized." It seems very strange to receive an error from a function that was completely executed, or am i wrong to think that? Can anyone tell me why I receive this error and how I can solve the problem?
Thanks for your help. I finally solved the problem. All my code was executed in the FormClosing event of my form. But now i've separated the code in two pieces. The piece of code I left in the FormClosing event is the call of the delete function. I moved the code that called the function to close the database connection to the **FormClosed** event. So there was nothing wrong with my code, only the place was wrong.
I believe that you have two problem which have both been answered. Handling the connection and the formClosing event firing. I see that "myConnection" and "myCommand" as not locally scoped. This objects should be not be held at class level (your form). You should open your connection in a using block and let the connection be disposed as soon as possible. (as @PaulG as stated) If you are using connection pooling then using a using block will allow for the connection to be returned to pool. If you dont that you could be in for a variety of problems. Once you are handling your connections correctly, you might still have a problem as the formClosing event could fire more than once (as @SysDragon has already said.) I simple boolean flag should help you out.
Error while closing SQL Connection
[ "", "sql", "sql-server", "vb.net", "" ]
Suppose I have a list of values, such as `1, 2, 3, 4, 5` and a table where some of those values exist in some column. Here is an example: ``` id name 1 Alice 3 Cindy 5 Elmore 6 Felix ``` I want to create a `SELECT` statement that will include all of the values from my list as well as the information from those rows that match the values, i.e., perform a `LEFT OUTER JOIN` between my list and the table, so the result would be like follows: ``` id name 1 Alice 2 (null) 3 Cindy 4 (null) 5 Elmore ``` How do I do that without creating a temp table or using multiple `UNION` operators?
If in Microsoft SQL Server 2008 or later, then you can use [Table Value Constructor](http://technet.microsoft.com/en-us/library/dd776382.aspx) ``` Select v.valueId, m.name From (values (1), (2), (3), (4), (5)) v(valueId) left Join otherTable m on m.id = v.valueId ``` Postgres also has this construction [VALUES Lists](https://www.postgresql.org/docs/9.4/queries-values.html): ``` SELECT * FROM (VALUES (1, 'one'), (2, 'two'), (3, 'three')) AS t (num,letter) ``` Also note the possible [Common Table Expression](https://www.postgresql.org/docs/9.1/queries-with.html) syntax which can be handy to make joins: ``` WITH my_values(num, str) AS ( VALUES (1, 'one'), (2, 'two'), (3, 'three') ) SELECT num, txt FROM my_values ``` With Oracle it's possible, though heavier [From ASK TOM](https://asktom.oracle.com/pls/apex/asktom.search?tag=value-list-items-that-are-not-in-the-table): ``` with id_list as ( select 10 id from dual union all select 20 id from dual union all select 25 id from dual union all select 70 id from dual union all select 90 id from dual ) select * from id_list; ```
the following solution for oracle is adopted from [this source](http://rebustechnologies.com/convert-a-csv-string-into-rows-using-oraclesql/). the basic idea is to exploit oracle's hierarchical queries. you have to specify a maximum length of the list (100 in the sample query below). ``` select d.lstid , t.name from ( select substr( csv , instr(csv,',',1,lev) + 1 , instr(csv,',',1,lev+1 )-instr(csv,',',1,lev)-1 ) lstid from (select ','||'1,2,3,4,5'||',' csv from dual) , (select level lev from dual connect by level <= 100) where lev <= length(csv)-length(replace(csv,','))-1 ) d left join test t on ( d.lstid = t.id ) ; ``` check out [this sql fiddle](http://sqlfiddle.com/#!4/21891/1) to see it work.
Joining a list of values with table rows in SQL
[ "", "sql", "sql-server", "oracle", "" ]
I am working on a simple SQL query in SQL Developer and I can't seem to get this one right. My query is: "Retrieve the names of all the tutors that have had *all their* appointments with 'place name here'" Here is my SQL: ``` SELECT Appt.TUTOR_USER_ID, TUTORS.FIRST_NAME, TUTORS.LAST_NAME FROM Appt, ( SELECT Tutor.USER_ID, USR.FIRST_NAME, USR.LAST_NAME FROM Tutor, "USER" USR WHERE Tutor.USER_ID = USR.ID ) TUTORS, ( SELECT USR.ID, USR.FIRST_NAME, USR.LAST_NAME FROM Student, "USER" USR WHERE Student.USER_ID = USR.ID ) USERS WHERE (Appt.TUTOR_USER_ID = TUTORS.USER_ID AND Appt.STUDENT_USER_ID = USERS.ID) AND (USERS.FIRST_NAME = 'John' AND USERS.LAST_NAME = 'Smith'); ``` What this gives me is all the tutors that has had appointments with John Smith, but not ALL THEIR appointments with John Smith. So I get tutors that have had appointments with other people besides John Smith. Can anyone give me a hand with the right statements or logic here.
You are only looking for records that match that name, so there is currently nothing to count or exclude anything else. You could add a `and not exists` clause that queries for any other students; or since it's in your question title, a `minus` that does the same: ``` select a.tutor_user_id, tu.first_name, tu.last_name from appt a join tutor t on t.user_id = a.tutor_user_id join student s on s.user_id = a.student_user_id join "USER" tu on tu.id = t.user_id join "USER" su on su.id = s.user_id where su.first_name = 'John' and su.last_name = 'Smith' minus select a.tutor_user_id, tu.first_name, tu.last_name from appt a join tutor t on t.user_id = a.tutor_user_id join student s on s.user_id = a.student_user_id join "USER" tu on tu.id = t.user_id join "USER" su on su.id = s.user_id where not (su.first_name = 'John' and su.last_name = 'Smith'); ``` But I'd do it in one hit using `group by` and a `having` clause to count the number of appointments for John Smith and for anyone else: ``` select a.tutor_user_id, tu.first_name, tu.last_name from appt a join tutor t on t.user_id = a.tutor_user_id join student s on s.user_id = a.student_user_id join "USER" tu on tu.id = t.user_id join "USER" su on su.id = s.user_id group by a.tutor_user_id, tu.first_name, tu.last_name having count(case when su.first_name = 'John' and su.last_name = 'Smith' then 1 else null end) > 0 and count(case when su.first_name = 'John' and su.last_name = 'Smith' then null else 1 end) = 0; ``` [SQL Fiddle demo](http://sqlfiddle.com/#!4/98869/1) with some simple data, your original query (which also shows duplicates), and both these versions. As JosephB and Serpiton mentioned, and I forgot to say, you don't actually need to go via the `tutor` or `student` tables as they aren't really adding anything; you can join to the `"USER"` table directly from the `appt` columns: ``` select a.tutor_user_id, tu.first_name, tu.last_name from appt a join "USER" tu on tu.id = a.tutor_user_id join "USER" su on su.id = a.student_user_id group by a.tutor_user_id, tu.first_name, tu.last_name having count(case when su.first_name = 'John' and su.last_name = 'Smith' then 1 else null end) > 0 and count(case when su.first_name = 'John' and su.last_name = 'Smith' then null else 1 end) = 0; ``` [As shown here](http://sqlfiddle.com/#!4/98869/12). In both cases I've reworked your original to use ANSI `join` syntax rather than the old Oracle style, and removed the subqueries while I was there as all the joining can be done on one level. I would strongly suggest, though, that you rethink your table names so you don't have to use a quoted identifier; maybe call them `users`, `tutors` and `students` instead?
Another way to go is to first filter the appointments to get the ones where the tutor only see a student, and use it as base for the main query ``` WITH tutor_appt As ( SELECT tutor_user_id , MAX(student_user_id) student_user_id FROM appt GROUP BY tutor_user_id HAVING COUNT(DISTINCT student_user_id) = 1 ) SELECT a.tutor_user_id, tu.first_name, tu.last_name FROM tutor_appt a INNER JOIN "USER" tu on tu.id = a.tutor_user_id INNER JOIN "USER" su on su.id = a.student_user_id where su.first_name = 'John' and su.last_name = 'Smith'; ``` If the database is sane there is no need to join the `Tutor` and the `Student` table to `appt` before joining `USER`: the `tutor_user_id` and `student_user_id` columns can be joined to `USER` directly.
SQL Query Select or Minus Help SQL Developer
[ "", "sql", "oracle", "select", "join", "oracle-sqldeveloper", "" ]
I have table `dbo.Students_Old` with columns : > Name(varchar), DocNum(int), Group(varchar), Form(varchar). It have no primary key and I need to normalize this table. So I am going to make three tables: > dbo.Students(StudentId(int primary key), Name(varchar), Group(int fk), > Form(int fk), > > dbo.Forms(FormId(int pk), FName(varchar)), dbo.Groups(GroupId(int pk), > GName(varchar)). And also I need to fill all this tables with data from `dbo.Students_Old`. My code is: ``` CREATE TABLE dbo.Groups(GroupId int IDENTITY(1,1) PRIMARY KEY, GName nvarchar(10)); GO INSERT INTO dbo.Groups(GName) select Group from dbo.Students_Old group by Group GO CREATE TABLE dbo.Forms(FormId int IDENTITY(1,1) PRIMARY KEY, Form nvarchar(20)); INSERT INTO dbo.Forms(Form) select Form from dbo.Students_Old group by Form GO CREATE TABLE dbo.Students (StudentId int PRIMARY KEY, Name nvarchar(50), Form int NOT NULL, Group int NOT NULL, CONSTRAINT Form FOREIGN KEY(StudentId) REFERENCES dbo.Forms(FormId), CONSTRAINT Grup FOREIGN KEY(StudentId) REFERENCES dbo.Groups(GroupId)); GO INSERT INTO dbo.Students(StudentId, Name, Form, Group) select DocNum, Name, f.FormId, g.GroupId from dbo.Students_Old s join dbo.Forms f on s.Form=f.Form join dbo.Groups g on s.Group=g.GName ``` Also Students\_Old.DocNum is unique. Tables creates normaly, but on the insert statement i have an error: ``` The INSERT statement conflicted with the FOREIGN KEY constraint "Form". The conflict occurred in database "DBNames", table "dbo.Forms", column 'FormId'. ``` Help me please.
Execute the below query on a new database ``` CREATE TABLE dbo.Groups(GroupId int IDENTITY(1,1) PRIMARY KEY, GName nvarchar(10)); GO INSERT INTO dbo.Groups(GName) select Group from dbo.Students_Old group by Group GO CREATE TABLE dbo.Forms(FormId int IDENTITY(1,1) PRIMARY KEY, Form nvarchar(20)); INSERT INTO dbo.Forms(Form) select Form from dbo.Students_Old group by Form GO CREATE TABLE dbo.Students (StudentId int PRIMARY KEY, Name nvarchar(50), Form int NOT NULL, [Group] int NOT NULL, CONSTRAINT Form FOREIGN KEY(Form) REFERENCES dbo.Forms(FormId), CONSTRAINT Grup FOREIGN KEY(Group) REFERENCES dbo.Groups(GroupId)); GO INSERT INTO dbo.Students(StudentId, Name, Form, Group) select DocNum, Name, f.FormId, g.GroupId from dbo.Students_Old s join dbo.Forms f on s.Form=f.Form join dbo.Groups g on s.Group=g.GName ``` I've changed to following lines ``` CONSTRAINT Form FOREIGN KEY(Form) REFERENCES dbo.Forms(FormId), CONSTRAINT Grup FOREIGN KEY([Group]) REFERENCES dbo.Groups(GroupId)); ``` In your code the foreign key is made on `StudentID` column
Not sure if that is the case, since you get the FOREIGN KEY error, but try avoiding column names like GROUP or other reserved words. While you can avoid errors on table creation step, you can face serious problems during modifications/updates on such tables.
Insert statement error
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm having an issue coming up with an SQL statement. CANNOT get my head around multi table interaction in MySQL. So I have 2 tables: This is my `users` table: ![This is my users table.](https://i.stack.imgur.com/08UR5.png) This is my `messages` table: ![This is my messages table.](https://i.stack.imgur.com/545uG.png) What I want to do is generate a table that basically shows: IF I AM USER 1 `Daniel - Melbourne University` I only want his name to appear if I have sent a message to him, or received one from him. Totally lost on how to do this, any ideas? Thanks so much!
There are a few ways. ``` SELECT users.* FROM users INNER JOIN ( SELECT DISTINCT messages_senderid AS user_id FROM messages WHERE messages_receiverid = 1 UNION SELECT DISTINCT messages_receiverid AS user_id FROM messages WHERE messages_senderid = 1 ) contacts ON users.users_userid = contacts.user_id ``` Or perhaps... ``` SELECT users.* FROM users WHERE EXISTS (SELECT * FROM messages WHERE messages_senderid = users.users_userid AND messages_receiverid = 1) OR EXISTS (SELECT * FROM messages WHERE messages_receiverid = users.users_userid AND messages_senderid = 1) ```
``` SELECT users_name,users_university FROM users WHERE users_userid IN (SELECT messages_senderid FROM messages WHERE messages_receiverid=1) OR users_userid IN (SELECT messages_receiverid FROM messages WHERE messages_senderid=1) ``` Another method ``` SELECT users_name,users_university FROM users WHERE users_userid IN ( SELECT CASE WHEN messages_receiverid=1 THEN messages_senderid WHEN messages_senderid=1 THEN messages_receiverid END FROM messages ) ```
INNER JOIN? Two table joining of userid with other userid
[ "", "mysql", "sql", "" ]
I have a query in which date is in 'YYYY-MM-DD' format, and I am looking to sort this. So, I used ``` SELECT DATE_FORMAT(AudiEvent.EventDate,'%d-%m-20%y') as Event_Date from AudiEvent ORDER BY Event_Date ``` Actual Output - ``` Event_Date 06-12-2013 09-11-2013 18-12-2013 26-11-2013 ``` Expected Output - ``` Event_Date 09-11-2013 26-11-2013 06-12-2013 18-12-2013 ```
You need to add `AudiEvent` before EventDate ``` SELECT DATE_FORMAT(AudiEvent.EventDate,'%d-%m-20%y') as Event_Date from AudiEvent ORDER BY AudiEvent.EventDate ```
Please use `AudiEvent.EventDate` date field in sorting ``` SELECT DATE_FORMAT(AudiEvent.EventDate,'%d-%m-20%y') as Event_Date from AudiEvent ORDER BY AudiEvent.EventDate ```
Sorting the date in ascending order
[ "", "mysql", "sql", "" ]
My table has one record per employee per year. How do I select one record per employee getting the latest year for that employee? Columns are `employee_ref, firstname, lastname, employment_year`. Each `employee_ref` will have several records, each with different values of `employment_year` I want to select one record per `employee_ref`, where `employment_year` has the highest value for that `employee_ref` and show the `firstname` and `lastname` from this record. Though I know SQL, my skills are not up to this one.
You can do this with a sub-selected: ``` SELECT employee_ref, firstname, lastname FROM table WHERE employment_year = ( SELECT MAX(employment_year) FROM table b WHERE b.employee_ref = table.employee_ref) ```
Something like this should work. ``` select firstname, lastname, maxyear from table join ( select employee_ref, max(employment_year) maxyear from table group by employee_ref) temp on table.employee_ref = temp.employee_ref and employment_year = maxyear ```
Table has one record per employee per year. How do I select the record for each employee for the latest year for that employee?
[ "", "sql", "" ]
I am not an expert in sql. My wordpress started to return timeouts and respond really slow. when I started digging, I noticed that the slow\_query log has a lot to tell me. unfortunately I have a lot of slow queries. for example: ``` # Time: 140425 17:03:29 # User@Host: geektime[geektime] @ localhost [] # Query_time: 7.024031 Lock_time: 0.000432 Rows_sent: 0 Rows_examined: 0 SET timestamp=1398434609; SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id) LEFT JOIN wp_postmeta AS order1 ON order1.post_id = wp_posts.ID AND order1.meta_key = '_event_start_date' LEFT JOIN wp_postmeta AS order2 ON order2.post_id = wp_posts.ID AND order2.meta_key = '_event_start_time' WHERE 1=1 AND wp_posts.post_type = 'event' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future' OR wp_posts.post_status = 'draft' OR wp_posts.post_status = 'pending') AND ((wp_postmeta.meta_key = '_event_start_date' AND CAST(wp_postmeta.meta_value AS CHAR) BETWEEN '2014-04-11' AND '2014-04-17') OR (mt1.meta_key = '_event_end_date' AND CAST(mt1.meta_value AS CHAR) BETWEEN '2014-04-11' AND '2014-04-17')) GROUP BY wp_posts.ID ORDER BY order1.meta_value, order2.meta_value ASC; ``` The columns post\_id, meta\_id and meta\_key are indexed in wp\_postmeta table. The columns ID, post\_name, post\_type, post\_status, post\_date,post\_parent, post\_author and guid are indexed in wp\_posts table. however, the columns ID and GUID are indexed twice, is it bad? and there are 4 indexs with the same key\_name: type\_status\_date, is it bad? How could it be that I have 60K rows in wp\_posts and 3M rows in wp\_postmeta? I know its a lot to ask but I really tried to understand from researching online. thanks in advance.
> however, the columns ID and GUID are indexed twice, is it bad? There are two different columns, so no, unless you're meaning that both have *two* indexes on them — in which case yes, it's bad and likely a bug in one of your theme or plugins (or a prior bug in WP itself). > and there are 4 indexs with the same key\_name: type\_status\_date, is it bad? Same as above: if you mean four identical indexes, it's either a theme or plugin or WP bug and you can safely drop the duplications. > How could it be that I have 60K rows in wp\_posts and 3M rows in wp\_postmeta? Because the WP meta API sucks and enforces a database anti-pattern called the Entity Attribute Value (also known as EAV): <http://en.wikipedia.org/wiki/Entity-attribute-value_model> Cursory googling SO will yield plenty of threads that explain why it is a bad idea to store data in an EAV or equivalent (json, hstore, xml, whatever) if the stuff ever needs to appear in e.g. a where, join or order by clause. You can see the inefficiencies first-hand in form of the slow query you highlighted. The query is joining the meta table four times, does so twice with a cast operator to boot — and it casts the value to char instead of date at that. Adding insult to injury, it then proceeds to order rows using values stored within it. It is a recipe for poor performance. There is, sadly, little means of escaping the repulsive stench of this sewage, short of writing your own plugins that create proper tables to store, index and query the data you need in lieu of using the WP meta API, its wretched quoting madness, and the putrid SQL that results from using it. One thing that you *can* do as temporary duct tape and WD-40 measure while you rewrite the plugins you're using from the ground up, is to toss callbacks on one or more of the filters you'll find in the giant mess of a class method that is `WP_Query#get_posts()`. For instance the `posts_request` filter, which holds the full and final SQL query, allows you to rewrite anything to your liking using regex-foo. It's no magic bullet: doing so will allow you to fix bugs such as integer values getting sorted lexicographically and such, as well as toss in very occasional query optimizations; little more. Edit: Upon re-reading your query, methinks you're mostly in luck with respect to that last point. Your particular query features the following abomination: ``` INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id) LEFT JOIN wp_postmeta AS order1 ON order1.post_id = wp_posts.ID AND order1.meta_key = '_event_start_date' LEFT JOIN wp_postmeta AS order2 ON order2.post_id = wp_posts.ID AND order2.meta_key = '_event_start_time' ``` Two of those have `_event_start_date` in common, so you can factor it out: ``` SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) AND wp_postmeta.meta_key = '_event_start_date' INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id) AND mt1.meta_key = '_event_end_date' INNER JOIN wp_postmeta AS order2 ON order2.post_id = wp_posts.ID AND order2.meta_key = '_event_start_time' WHERE 1=1 AND wp_posts.post_type = 'event' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future' OR wp_posts.post_status = 'draft' OR wp_posts.post_status = 'pending') AND (CAST(wp_postmeta.meta_value AS CHAR) BETWEEN '2014-04-11' AND '2014-04-17' OR CAST(mt1.meta_value AS CHAR) BETWEEN '2014-04-11' AND '2014-04-17') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value, order2.meta_value ASC; ```
Among other things, slow performance is caused by the use of functions like this: ``` AND CAST(wp_postmeta.meta_value AS CHAR) BETWEEN '2014-04-11' AND '2014-04-17') ``` Assuming that field is a date field, you will get better performance with something like this: ``` and wp_postmeta.meta_value >= AStartDateVariable and wp_postmeta.meta_value < TheDayAfterAnEndDateVariable ``` That will be even more true if meta\_value is indexed. I assume you will be sending these variables as query parmameters.
mysql slow queries and timeout in wordpress
[ "", "mysql", "sql", "wordpress", "indexing", "" ]
I am trying to retrieve names and address of all guests with bookings for a hotel in London, alphabetically ordered by name in MySQL using subqueries and getting this Error: ``` Error Code: 1242. Subquery returns more than 1 row ``` Here's the query that I run: ``` select * from guest where guest_no = ( select guest_no from booking where hotel_no = (select hotel_no from hotel where city = 'London') ); ``` and here's the schema for hotel, booking and guest: ``` hotel (hotel_no, hotel_name, city) booking (hotel_no, guest_no, date_from, date_to, room_no) guest (guest_no, g_name, g_address) ``` additionally, here's the schema for room: ``` room (room_no, hotel_no, type, price) ``` Please help me with the above mentioned error and possible solutions. Thanks and regards.
why not use join as ``` select g.guest_no, g.g_name, g.g_address from guest g inner join booking b on b.guest_no = g.guest_no inner join hotel h on h.hotel_no = b.hotel_no where h.city = 'London' ```
When you use '=', it means that the result of your subquery is exactly 1 row. If you expect multiple results, you need to use the `IN` keyword, like so: ``` select * from guest where guest_no IN (select guest_no from booking where hotel_no IN (select hotel_no from hotel where city = 'London')); ``` EDIT: As @flaschenpost mentions, the performance could be degraded in case there is no proper indexing on the columns involved in the subqueries. You would probably do well to use `JOIN` rather than such nested subqueries.
MySQL subquery on multiple tables
[ "", "mysql", "sql", "" ]
I have the following table | ID | Name | CodSituation | | --- | --- | --- | | 1 | John | 1 | | 2 | Mary | 2 | | 3 | Mary | 3 | | 4 | Mary | 4 | | 5 | John | 5 | | 6 | John | 2 | | 7 | Mary | 1 | I want to select the Names, ID's and CodSituation for all users where their last entry is CodSituation=2 In these results I will get just the id 6 As Mary's last entry was CodeSituation=4 if more than one users have their latest CodSituation=2 I want them too.
I found an easier way concatenating fieds and using max solve this problem... Thanks! ``` SELECT right( max( right(('0000000' + CONVERT(varchar,id) + '-'+ convert(varchar,codsituation)),4)),10), name FROM TABLE_NAME GROUP BY name HAVING right( max( right( ('0000000' + CONVERT(varchar,id) + '-'+ convert(varchar,codsituation)) ,4)),1) = 2 ``` <http://sqlfiddle.com/#!3/3dc1c/10>
[FINAL EDIT] After seeing what was posted at the end of this answer I figured out that the user was asking the wrong question: What they were asking was 'show me everyone who has CodSituation=2' when they meant 'Show me all the users who's last entry in CodSituation field=2' Here is the correct query for that: ``` select a.ID, a.Name, a.CodSituation from table_name a inner join ( select Name, max(ID) as MaxID from table_name group by Name ) b on a.Name = b.Name and a.ID = b.MaxID where a.CodSituation = 2; ``` Here is the fiddle for that: <http://sqlfiddle.com/#!2/a731d> [END] [here are the previous queries, for reference] Looks to me like you just need: ``` select * from table_name where CodSituation=2 ``` To get all of the people with situation 2 To get only the last entry using mysql: ``` select * from table_name where CodSituation=2 order by id desc limit 1 ``` To get the last entry using sql-server: ``` select top 1 * from table_name where CodSituation=2 order by ID desc; ``` See a working example here: <http://sqlfiddle.com/#!6/022fb/4> [edit] OP supplied an actual dataset: ``` select Name from table_name where CodSituation=2 group by Name; ``` This shows all the unique users with a CodSituation of 2 (with one entry per person) <http://sqlfiddle.com/#!3/be404/2>
SQL Select list of last records with condition
[ "", "sql", "sql-server", "" ]
I have `Table 1`: ``` ID UserString Date ------------------------- 1 KRBS 4/25/2014 2 WEFG 4/24/2014 ``` And `Table 2`: ``` ID UserString + Other user info ---------------------------------- 1 KRBS + . . .. . ``` I'm preforming insert into Table 1 but I would like to make a condition to only insert if the user is already available in Table 2 (only only insert row in table 1 if user already exist in table2) I'm currently doing two separate SQL checks (one if user exist then insert) but I'm sure there is a better way
Best way to achieve this is to define a `FOREIGN KEY` on the table. This is the simplest and most implicit way to do it, some reference on that can be found on [MSDN](http://technet.microsoft.com/en-us/library/ms190273%28v=sql.105%29.aspx). That means you will not ever be able to a) insert an entry to this table if no corresponding FK exists, and b) delete from the base table if entries with foreign key are here (in your case, delete the user if it already has the settings ). It will look like: ``` ALTER TABLE NameOfTheTable ADD CONSTRAINT FK_SomeNameForTheKey FOREIGN KEY (nameOfColFromThisTable) REFERENCES NameOfTheOtherTable (NameOfTheCOlumnYouAreReferencing); ```
try this on mysql: ``` if {{ userId }} in (select UserString from Table2 where UserString = {{ userId }}) then insert into Table1 (ID, UserString, Date) values ({{ id }}, {{ userId }}, '{{ date }}') end if ``` or this on sql server ``` if {{ userId }} in (select UserString from Table2 where UserString = {{ userId }}) insert into Table1 (ID, UserString, Date) values ({{ id }}, {{ userId }}, '{{ date }}') ``` change {{ var }} to your actual values
SQL Insert - Only insert on this condition
[ "", "sql", "sql-server", "database", "insert", "" ]
Let's say I have a table with 1,000,000 rows and running a `SELECT * FROM TableName` on this table takes around 10 seconds to return the data. *Without* a NOLOCK statement (putting to one side issues around dirty reads) would this query lock the table for 10 seconds meaning that no other process could read or write to the table? I am often informed by DBAs then when querying live data to diagnose data issues I should use NOLOCK to ensure that I don't lock the table which may cause issues for users. Is this true?
The `NOLOCK` table hint will cause that no shared locks will be taken for the table in question; same with `READUNCOMMITTED` isolation level, but this time applies not to a single table but rather to everything involved. So, the answer is 'no, it won't lock the table'. Note that possible schema locks will still be held even with readuncommitted. Not asking for shared locks the read operation will potentially read dirty data (updated but not yet committed) and non-existent data (updated, but rolled back), transactionally inconsistent in any case, and migh even skip the whole pages as well (in case of page splits happening simultaneously with the read operation). Specifying either `NOLOCK` or `READUNCOMMITTED` is not considered a good practice. It will be faster, of course. Just make sure you're aware of consequences. Also, support for these hints in UPDATE and DELETE statements will be removed in a future version, according to docs.
Your query will try to obtain a table level lock as you're asking for all the data. So yes it will be held for the duration of the query and all other processes trying to acquire Exclusive locks on that table with be put on wait queues. Processes that are also trying to read from that table will not be blocked. Any diagnosis performed on a live system should done with care and using the NOLOCK hint will allow you to view data without creating any contention for users. EDIT: As pointed out update locks are compatible with shared locks. So won't be blocked by the read process.
Understanding the NOLOCK hint
[ "", "sql", "sql-server", "transaction-isolation", "nolock", "" ]
Considering the following table ``` +-----+-----+-----+-----+-----+-----+ |Col01|Col02|Col03|Col04|Col05|Col06| <===header +-----+-----+-----+-----+-----+-----+ |data1|data2|NULL |hi |Hello|Folks| <===a row +-----+-----+-----+-----+-----+-----+ ``` Now I would like to have a query which returns the name of column ( in this case `COL03`) or the column number as result which has a null value. How can I achieve this in PostgreSQL?
Would something like this do? ``` select case when col01 is null then 'col1' when col02 is null then 'col2' when col03 is null then 'col3' when col04 is null then 'col4' when col05 is null then 'col5' else null end which_col from tableX ``` If you want to construct this dynamically, I think you have to go procedural. You can get the name of the columns by querying information\_schema.columns. Then create a query like this using that information.
This will return row for each column in your table that has null value. ``` SELECT 'Col1' FROM MyTable WHERE col1 IS NULL UNION ALL SELECT 'Col2' FROM MyTable WHERE col2 IS NULL UNION ALL SELECT 'Col3' FROM MyTable WHERE col3 IS NULL ```
Query for retrieving columns with null value
[ "", "sql", "postgresql", "" ]
I have two tables: ``` create table xyz (campaign_id varchar(10) ,account_number varchar) Insert into xyz values ( 'A', '1'), ('A', '5'), ('A', '7'), ('A', '9'), ('A', '10'), ( 'B', '2'), ('B', '3'), ( 'C', '1'), ('C', '2'), ('C', '3'), ('C', '5'), ('C', '13'), ('C', '15'), ('D', '2'), ('D', '9'), ('D', '10') create table abc (account_number varchar) insert into abc values ('1'), ('2'), ('3'), ('5') ``` Now, I want to write a query where all the four account\_number `1, 2, 3, 5` are included in a `Campaign_id`. The answer is C. [My aim is to find the Campaign Code that includes account\_number 1, 2, 3 & 5. This condition is only satisfied by campaign code C.] I tried using `IN` and `ALL`, but don't work. Could you please help.
I think what you are after is a inner join. Not sure from your questions which way around you want your data. However this should give you a good clue how to procede and what keywords to lock for in the documentation to go further. ``` SELECT a.* FROM xyz a INNER JOIN abc b ON b.account_number = a.account_number; ``` EDIT: Seems I misunderstood the original question.. sorry. To get what you want you can just do: ``` SELECT campaign_id FROM xyz WHERE account_number IN ('1', '2', '3', '5') GROUP BY campaign_id HAVING COUNT(DISTINCT account_number) = 4; ``` This is called relational division if you want to investigate further.
``` SELECT campaign_id FROM ( SELECT campaign_id, COUNT(*) AS c, total_accounts FROM xyz JOIN abc ON xyz.account_number = abc.account_number CROSS JOIN (SELECT COUNT(*) AS total_accounts FROM abc) AS x GROUP BY campaign_id HAVING c = total_accounts) AS subq ``` [DEMO](http://www.sqlfiddle.com/#!2/ff0e8/3)
SQL - ALL, Including all values
[ "", "sql", "sap-iq", "" ]
I have this sql query and this takes very long time to finish. How can i speed this up? t\_inter\_specises\_interaction has 60k rows and t\_pathway has 100k. uniprot\_id\_1,uniprot\_id\_2,uniprot\_id are varchar types. In this query, i want to select uniprot\_id\_1 and uniprot\_id\_2 which are both present in t\_pathway : ``` select distinct uniprot_id_1,uniprot_id_2 from t_intra_species_interaction where uniprot_id_1 in (select uniprot_id from t_pathway) and uniprot_id_2 in (select uniprot_id from t_pathway) ``` In this one, i want to select uniprot\_id which is present in the set uniprot\_ids returned by the first query above. ``` select distinct uniprot_id,id from t_pathway as t where uniprot_id in ( select distinct uniprot_id_2 from t_intra_species_interaction where uniprot_id_1 in (select uniprot_id from t_pathway) and uniprot_id_2 in (select uniprot_id from t_pathway) union select distinct uniprot_id_1 from t_intra_species_interaction where uniprot_id_1 in (select uniprot_id from t_pathway) and uniprot_id_2 in (select uniprot_id from t_pathway) ) ``` Thanks.
The subqueries are identical, therefore they can be merged into one, and moved to a join ``` SELECT DISTINCT i.uniprot_id_1, i.uniprot_id_2 FROM t_intra_species_interaction i INNER JOIN t_pathway p ON p.uniprot_id IN (i.uniprot_id_1, i.uniprot_id_2) ``` **Second query** It would have be better to open a new question referring to this, but looking at my previous query it should be easy to see that to get your second answer, you only need to get the column from t\_pathway instead of t\_intra\_species\_interaction ``` SELECT DISTINCT p.uniprot_id, p.id FROM t_intra_species_interaction i INNER JOIN t_pathway p ON p.uniprot_id IN (i.uniprot_id_1, i.uniprot_id_2) ```
You may want to use INNER JOIN: ``` select distinct uniprot_id_1,uniprot_id_2 from t_intra_species_interaction i inner join t_pathway p1 on p1.uniprod_id = t.uniprot_id_1 inner join t_pathway p2 on p2.uniprod_id = t_uniprot_id_2 ```
More Efficient Way For SQL IN Clause
[ "", "mysql", "sql", "performance", "" ]
I have two tables friends and birthdays. birthdays schema: userid and birthday\_date friends schema: userid and userid2. How can I find out the friends of the people who have a birthday day today? I am thinking something like this: ``` SELECT * FROM friends WHERE userid2 IN (SELECT userid FROM birthdays WHERE birthday_date='05/02') ``` Is this the best way to do it? Here is the EXPLAIN response that I get: ``` +----+--------------------+-----------------------------+-----------------+-----------------------+---------+---------+------+-----------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+--------------------+-----------------------------+-----------------+-----------------------+---------+---------+------+-----------+--------------------------+ | 1 | PRIMARY | friends | index | NULL | userid2 | 8 | NULL | 4192662 | Using where; Using index | | 2 | DEPENDENT SUBQUERY | birthdays | unique_subquery | PRIMARY,birthday_date | PRIMARY | 8 | func | 1 | Using where | +----+--------------------+-----------------------------+-----------------+-----------------------+---------+---------+------+-----------+--------------------------+ ``` It doesn't seem optimized if it is searching 4 million rows. Also, there are indexes on every column.
TO make the query faster you need proper index on both tables in conjunction with the JOIN. Here is an example ``` create table birthdays (userid int,birthday_date varchar(20)); insert into birthdays values (1,'1980-01-01'); insert into birthdays values(2,'1980-01-02'); insert into birthdays values(3,'1980-01-03'); insert into birthdays values(4,'1980-01-04'); insert into birthdays values(5,'1980-01-05'); insert into birthdays values(6,'1980-01-06'); insert into birthdays values(7,'1980-01-07'); create table friends(userid int, userid2 int); insert into friends values(3,1); insert into friends values(1,3); insert into friends values(1,5); insert into friends values(2,3); insert into friends values (7,6); alter table birthdays add index bday_idx (`birthday_date`); alter table birthdays add index iduser_idx (`userid`); alter table friends add index userid2_idx(userid2) ``` Now if I run the following query it will be for sure way faster ``` SELECT f.* FROM friends f inner join birthdays b on b.userid = f.userid2 WHERE b.birthday_date='1980-01-01' ID SELECT_TYPE TABLE TYPE POSSIBLE_KEYS KEY KEY_LEN REF ROWS EXTRA 1 SIMPLE b ref bday_idx,iduser_idx bday_idx 63 const 1 Using where 1 SIMPLE f ref userid2_idx userid2_idx 5 db_2_99839.b.userid 1 Using where ``` **[DEMO](http://sqlfiddle.com/#!2/99839/2)** > NOTE : When you join 2 tables with a common key make sure both of them > are of same datatype and length, in the above example its joining > userid (birthday) and userid2(friends) so they are of same data type > and length. Where condition column needs to be indexed for faster > fetch and the optimizer will take index into account.
Try Below Query Example ``` SELECT friends.* FROM friends inner join birthdays on friends.userid2 = birthdays.userid WHERE birthdays.birthday_date='05/02/2014' ``` Always use `datetime` datatype for date values.
Simple mysql join for specific date
[ "", "mysql", "sql", "" ]
``` SELECT * FROM products WHERE name LIKE '%a%' ``` This works fine when case sensitive, but how to search case insensitively? Thx ahead
Simple answer: ``` SELECT * FROM products WHERE lower(name) LIKE '%a%' ```
``` SELECT * FROM products WHERE nam LIKE BINARY '%a%' ``` `collate` option can also be used and [here](http://dev.mysql.com/doc/refman/5.0/en/charset-collate.html) is how to make it case sensitive from mysql tutorial.
In SQL how to check if a string contains a substring in(case insensitive)?
[ "", "sql", "psql", "" ]
Say we have this value in a column ``` <color="blue" size="5"><color="red"> ``` How do I replace the "red" with blue using a SQL statement? (the value dynamic so using regular REPLACE won't do) I'm really puzzled by how to solve it.
[`REGEXP_REPLACE`](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions130.htm) uses regular expressions to allow you to specify a *pattern* you wish you replace in a given string. Since your two `color` tags differ in structure, you can take advantage of this to specify a pattern which matches the second instance but not the first [like so (SQL Fiddle)](http://www.sqlfiddle.com/#!4/3d8b4/11) ``` SELECT your_column, REGEXP_REPLACE(your_column, '(.*)<color=".+">', '\1<color="blue">') AS "your_column_fixed" FROM your_table ; ``` This will take an input of the form `<color="blue" size="5"><color="???">` and transform it to one with the second tag replaced with `<color="blue">`. The [`.` operator](http://docs.oracle.com/cd/B19306_01/server.102/b14200/ap_posix001.htm#i690819) in regular expressions matches any non-null character. The `+` modifier means to match one or more occurrences of `.`. Surrounding an operator with parentheses means that the value matched will be available in the replace argument as `\n` where *n* is the corresponding position in the pattern.
I would play around with [substrings](http://technet.microsoft.com/en-us/library/ms187748.aspx) and [patindex](http://technet.microsoft.com/en-us/library/ms188395.aspx). ``` DECLARE @COLOR varchar(20), @YOUR_VALUE varchar(100) SET @YOUR_VALUE = SUBSTRING(@YOUR_VALUE, 8, LEN(@YOUR_VALUE)) SET @COLOR = SUBSTRING(@YOUR_VALUE, 0, PATINDEX('%"%', @YOUR_VALUE)) ``` The above removes 'color=" which will always be length 8, then finds the index of the next '"', then sets @COLOR to a substring up to that index.
Select column modification
[ "", "sql", "" ]
I would like to select `1` if current date falls between 2 dates through Oracle SQL. I wrote an SQL after reading through other questions. [https://stackoverflow.com/questions/2369222/oracle-date-between-query](https://stackoverflow.com/questions/2369222/oracle-date-between-query "Oracle date “Between” Query") [https://stackoverflow.com/questions/2399753/select-from-table-by-knowing-only-date-without-time-oracle](https://stackoverflow.com/questions/2399753/select-from-table-by-knowing-only-date-without-time-oracle "Select from table by knowing only date without time (ORACLE)") But it returned only null. `sysdate` is the current date that is `01/05/2014` in date format `DD/MM/YYYY`. The SQL I wrote is: ``` select 1 from dual WHERE to_date(sysdate,'DD/MM/YYYY') BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY'); ``` and ``` select 1 from dual WHERE to_date(sysdate,'DD/MM/YYYY') >= TO_DATE('28/02/2014', 'DD/MM/YYYY') AND to_date(sysdate,'DD/MM/YYYY') < TO_DATE('20/06/2014', 'DD/MM/YYYY'); ```
You don't need to apply `to_date()` to `sysdate`. It is already there: ``` select 1 from dual WHERE sysdate BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY'); ``` If you are concerned about the time component on the date, then use `trunc()`: ``` select 1 from dual WHERE trunc(sysdate) BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY'); ```
``` SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.* FROM emp_log A WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS') AND to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS') ORDER BY emp_login_date ```
Check if current date is between two dates Oracle SQL
[ "", "sql", "oracle", "date", "between", "sysdate", "" ]
i have one `SQL table` in which many records, i want to know how many names are in it and how much time one name in it. Table NameMst ``` Name john,smith,alax,rock smith,alax,sira john,rock rock,sira ``` I want to find how much name are there and count of its. expected output should be like this ``` Name Count john 2 smith 2 alax 2 rock 3 sira 2 ``` help me to resolved it.
``` SELECT y.Name, count(*) Count FROM (VALUES ('john,smith,alax,rock'), ('smith,alax,sira'), ('john,rock'), ('rock,sira')) x(names) CROSS APPLY ( SELECT t.c.value('.', 'VARCHAR(2000)') Name FROM ( SELECT x = CAST('<t>' + REPLACE(x.names, ',', '</t><t>') + '</t>' AS XML) ) a CROSS APPLY x.nodes('/t') t(c) ) y GROUP BY y.Name ``` Result: ``` Name Count alax 2 john 2 rock 3 sira 2 smith 2 ```
You can extract the names using a recursive CTE and some string parsing. The rest is just aggregation: ``` with cte as ( select (case when names like '%,%' then left(names, charindex(',', names) - 1) else names end) as name, (case when names like '%,%' then substring(names, charindex(',', names) + 1, len(names)) end) as names from names union all select (case when names like '%,%' then left(names, charindex(',', names) - 1) else names end) as name, (case when names like '%,%' then substring(names, charindex(',', names) + 1, len(names)) end) from cte where names is not null ) select name, count(*) from cte group by name; ``` As you have probably figured out, storing comma delimited lists in SQL Server is a bad idea. You should have an association/junction table with one row per name (and other columns describing the list it is in).
split comma seprate value from table in sql server
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
Just found out that this query: ``` SELECT 1 / 1000000; ``` will return `0`, which is a small catastrophe for our economical program when doing vat calculations. How to set the default number of decimals without changing every query? **Edit** The example at hand is to get the vat part from a net value, with 6% vat. `6 / 106 = 0.056603773...`, but `SELECT 6 / 106 = 0.0566`.
As documented under [Arithmetic Operators](http://dev.mysql.com/doc/en/arithmetic-functions.html): > In division performed with [`/`](http://dev.mysql.com/doc/en/arithmetic-functions.html#operator_divide), the scale of the result when using two exact-value operands is the scale of the first operand plus the value of the [`div_precision_increment`](http://dev.mysql.com/doc/en/server-system-variables.html#sysvar_div_precision_increment) system variable (which is 4 by default). For example, the result of the expression `5.05 / 0.014` has a scale of six decimal places (`360.714286`). Therefore, either: * Increase [`div_precision_increment`](http://dev.mysql.com/doc/en/server-system-variables.html#sysvar_div_precision_increment) to suit your needs: ``` SET div_precision_increment = 6; ``` Or, to set globally (i.e. across all future sessions): ``` SET GLOBAL div_precision_increment = 6; ``` Or even set it in the `[mysqld]` section of your option file / on the command-line to ensure that it survives server restarts. * Explicitly cast the result of your operation to a type having your desired scale: ``` SELECT CAST(1 / 1000000 AS DECIMAL(10,8)); ```
You can cast result to any data type. Below sql cast the result to decimal with precision 10. ``` select cast(1 / 1000000 as decimal(10,10)); ``` **EDIT:** Result depends on your data types. Try this: SELECT 6.000000 / 106.000000; If your data is decimal with required precision then your result will be decimal with enough precision. So I think you should update date type in your database.
MySQL, change default rounding to more than four digits
[ "", "mysql", "sql", "precision", "" ]
this is my first time asking a question on here, and I can usually find what I need just from seaching, however this time I'm stuck and I'm hoping someone here can help. Here's the gist. I have created a database for a hair dressing studio. there are five tables. The only one's this question deals with is the Customers table (stores customer details), the ProductSales table (store details about each product sale, and HairCuts table, store details about each cut. I need a query that will list the total spent on both hair cuts and products for each customer in the customers table. I have two separate queries that work fine. Each one calculates the total spent by each customer for EITHER hair cuts or products. I need to somehow combine these into one that will show the total. ``` SELECT c.customer_ID, c.first_Name, c.last_name, SUM(hc.cost) AS hc_sales_total FROM Customers c, HairCuts hc WHERE c.customer_ID = hc.customer_ID GROUP BY c.customer_ID; SELECT c.customer_ID, c.first_Name, c.last_name, SUM(ps.cost) AS ps_sales_total FROM Customers c,ProductSales ps WHERE c.customer_ID = ps.customer_ID GROUP BY c.customer_ID; ``` I believe the issues I am havng are stemming from the fact that, while all customers have purchased at least one hair cut, not all have purchased products. Anyway, any help would be much appreciated.
`UNION` your two queries together. Then you'll have a table with all the costs. From then you can treat that as the source for a new query, to total up these results ``` SELECT customer_ID, first_name, last_name, sum(hc_sales_total) as totalsales FROM ( SELECT c.customer_ID, c.first_Name, c.last_name, SUM(hc.cost) AS hc_sales_total FROM Customers c INNER JOIN HairCuts hc ON c.customer_ID = hc.customer_ID GROUP BY c.customer_ID UNION ALL SELECT c.customer_ID, c.first_Name, c.last_name, SUM(ps.cost) AS ps_sales_total FROM Customers c INNER JOIN ProductSales ps ON c.customer_ID = ps.customer_ID GROUP BY c.customer_ID ) sales GROUP BY customer_ID, first_name, last_name ``` Of course, the inner grouping is superfluous, so ``` SELECT customer_ID, first_name, last_name, sum(cost) as totalsales FROM ( SELECT c.customer_ID, c.first_Name, c.last_name, hc.cost FROM Customers c INNER JOIN HairCuts hc ON c.customer_ID = hc.customer_ID UNION ALL SELECT c.customer_ID, c.first_Name, c.last_name, ps.cost FROM Customers c INNER JOIN ProductSales ps ON c.customer_ID = ps.customer_ID ) sales GROUP BY customer_ID, first_name, last_name ```
If you want all three sums, you can do this using a `union all`/`group by` approach: ``` SELECT c.customer_ID, c.first_Name, c.last_Name, SUM(hp.hc_sales) as hp.hc_sales_total, SUM(hp.ps_sales) as hp.ps_sales_total, SUM(hp.hc_sales_total + hp.ps_sales_total) as Total FROM ((SELECT hc.customer_ID, hc.cost AS hc_sales, 0 as ps_sales FROM HairCuts hc ) UNION ALL (SELECT ps.customer_ID, 0, ps.cost AS ps_sales FROM ProductSales ps ) ) hp JOIN Customers c on c.customer_ID = hp.customer_ID GROUP BY c.customer_ID, c.first_Name, c.last_Name; ``` Note the ways that this query differs from yours: 1. The two join's have been factored out, so each subquery is working on only one table. 2. The join after the `union all` uses explicit `join` syntax, with the conditions going in the `on` clause. 3. There is only one aggregation.
SQL total spent per customer
[ "", "sql", "sql-server", "sqlite", "" ]
I want data from past 1 year, for example today is 02-05-2014, i need data from May 2013, June 2013..till April 2014 as separate columns. If anybody can help with this code in t-sql that will be very helpful for me. Thanks ok here i want the data. below is my column ``` created date ------------ 02-05-2013 16-05-2013 05-06-2013 22-07-2013 01-08-2013 09-08-2013 02-09-2013 03-10-2013 19-11-2013 11-12-2013 03-01-2014 29-02-2014 15-03-2014 19-04-2014 ``` I want the result as ``` May 2013 June 2013 July 2013 August 2013 till April 2014 -------- --------- --------- ----------- ---------- 02-05-2013 05-06-2013 22-07-2013 01-08-2013 19-04-2014 16-05-2013 09-08-2013 ``` and also I want to make **Columns dynamically** which is very important for my query
Although everyone was quick to suggest using `PIVOT`, that really won't work here because `PIVOT` would need to aggregate each column into one (max, min, whatever) date for that month and year. I gave this question some attention because it was actually an interesting challenge. The reality is, this is best done by some reporting tool, such as SSRS, because your output is really a timeline report. Because of the requirement for dynamic columns and such, I really don't see how this can be done without variables and some dynamic sql, so assuming that is acceptable, the following is tested and will output exactly what you described. It essentially creates 12 CTE tables, each containing the dates for a month and year, (counting backwards from whatever month and year you run the sql). It then creates the report simply by using a `FULL OUTER JOIN` of all the tables. However, if you full joined just the 12 tables, each column would have its values randomly over several rows with many nulls in betweeen. To line the dates in each column up at the top, it was necessary to add a base table with sequential numbers that each mo/yr table can join on. The sequential numbers are generated up to the max number of dates for any given mo/yr. (Note: with the base number table, a `LEFT OUTER JOIN` would have sufficed as well...) This assumes the table name is `dbo.MyTable` and the date column is `CreatedDate`: ``` DECLARE @cteSql nvarchar(MAX) = ''; DECLARE @tblSql nvarchar(MAX) = ''; DECLARE @frmSql nvarchar(MAX) = ''; DECLARE @colNm varchar(10); DECLARE @tblNm varchar(3); DECLARE @i int = 0; /* today's date */ DECLARE @td date = GETDATE(); /* max number of dates per yr/mo */ DECLARE @maxItems int = (SELECT MAX(CNT) FROM (SELECT COUNT(*) AS CNT FROM dbo.MyTable GROUP BY YEAR(CreatedDate), MONTH(CreatedDate)) T) /* a table of sequential numbers up to the max per yr/mo; this is so the full outer join is laid out neatly */ SET @cteSql = 'WITH T(id) AS( SELECT id = 1 UNION ALL SELECT id + 1 FROM T WHERE id + 1 <= ' + CAST(@maxItems AS varchar(16)) + ')'; /* count down from current date to past 12 months */ WHILE @i > -12 BEGIN /* a simple name for each CTE: T0, T1, T2 etc */ SET @tblNm = 'T' + CAST((@i*-1) AS varchar(2)); /* rpt column names; [Jan 2014], [Feb 2014] etc */ SET @colNm = '[' + RIGHT(CONVERT(varchar(11), DATEADD(m, @i, @td), 106),8) + ']'; /* each CTE contains a sequential id and the dates belonging to that month and yr */ SET @cteSql += ', ' + @tblNm + '(id, ' + @colNm + ')' + ' AS (SELECT ROW_NUMBER() OVER(ORDER BY CreatedDate) AS id, CreatedDate FROM dbo.MyTable WHERE YEAR(CreatedDate) = ' + CAST(YEAR(DATEADD(m, @i, @td)) AS varchar(4)) + ' AND MONTH(CreatedDate) = ' + CAST(MONTH(DATEADD(m, @i, @td)) AS varchar(2)) + ')'; /* this will eventually be the SELECT statement for the report...just the month columns, not the id */ SET @tblSql = ', ' + @colNm + @tblSql; /* concatenate all the columns using FULL OUTER JOIN with the first table of simple sequential numbers as the driver */ SET @frmSql += ' FULL OUTER JOIN ' + @tblNm + ' ON T.id = ' + @tblNm + '.id '; SET @i -= 1; END /* put all the sql together */ SET @tblSql = @cteSql + ' SELECT' + STUFF(@tblSql, 1, 1, '') + ' FROM T ' + @frmSql /* view the generated sql */ -- SELECT @tblSql AS X /* this should generate the report you described above, showing the last 12 months from whatever date you run it */ EXECUTE (@tblSql) ``` Output: ``` Jun 2013 Jul 2013 Aug 2013 Sep 2013 Oct 2013 Nov 2013 Dec 2013 Jan 2014 Feb 2014 Mar 2014 Apr 2014 May 2014 ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- 2013-06-05 2013-07-22 2013-08-01 2013-09-02 2013-10-03 2013-11-19 2013-12-11 2014-01-03 2014-02-28 2014-03-15 2014-04-19 NULL 2013-06-07 NULL 2013-08-09 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 2013-08-10 NULL NULL NULL NULL NULL NULL NULL NULL NULL ``` As it turns out, the sql generated is conceptually similar to what @Hogan suggested, although I did not realize it at first. It really just adds the dynamic naming plus the segregation by yr/mo and not just month.
Here is a way to do it without a dynamic pivot. I only did it for 2013, you can see what is needed to add more columns: (working fiddle: <http://sqlfiddle.com/#!6/d9797/1>) ``` with nums as ( select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =1 union all select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =2 union all select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =3 union all select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =4 union all select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =5 union all select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =6 union all select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =7 union all select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =8 union all select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =9 union all select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =10 union all select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =11 union all select [create date], MONTH([create date]) as M, ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN from table1 where MONTH([create date]) =12 ),maxrn as ( select MAX(RN) as maxnum from nums ), rowNumbers as ( select 1 as RN union all select RN+1 AS RN from rowNumbers where RN < (select maxnum from maxrn) ) SELECT nJan.[create date] as [Jan 2013], nFeb.[create date] as [Feb 2013], nMar.[create date] as [Mar 2013], nApr.[create date] as [Apr 2013], nMay.[create date] as [May 2013], nJun.[create date] as [Jun 2013], nJul.[create date] as [Jul 2013], nAug.[create date] as [Aug 2013], nSep.[create date] as [Sep 2013], nOct.[create date] as [Oct 2013], nNov.[create date] as [Nov 2013], nDec.[create date] as [Dec 2013] FROM rowNumbers n LEFT JOIN nums nJan ON n.RN = nJan.RN and nJan.M = 1 LEFT JOIN nums nFeb ON n.RN = nFeb.RN and nFeb.M = 2 LEFT JOIN nums nMar ON n.RN = nMar.RN and nMar.M = 3 LEFT JOIN nums nApr ON n.RN = nApr.RN and nApr.M = 4 LEFT JOIN nums nMay ON n.RN = nMay.RN and nMay.M = 5 LEFT JOIN nums nJun ON n.RN = nJun.RN and nJun.M = 6 LEFT JOIN nums nJul ON n.RN = nJul.RN and nJul.M = 7 LEFT JOIN nums nAug ON n.RN = nAug.RN and nAug.M = 8 LEFT JOIN nums nSep ON n.RN = nSep.RN and nSep.M = 9 LEFT JOIN nums nOct ON n.RN = nOct.RN and nOct.M = 10 LEFT JOIN nums nNov ON n.RN = nNov.RN and nNov.M = 11 LEFT JOIN nums nDec ON n.RN = nDec.RN and nDec.M = 12 ORDER BY n.RN ASC ```
how can I get data from every month from past one year in t-sql and each month should be in different column
[ "", "sql", "sql-server", "" ]
I am trying to calculate values in a column called Peak, but I need to apply different calculations dependant on the 'ChargeCode'. Below is kind of what I am trying to do, but it results in 3 columns called Peak - Which I know is what I asked for :) Can anyone help with the correct syntax, so that I end up with one column called Peak? ``` Use Test Select Chargecode, (SELECT 1 Where Chargecode='1') AS [Peak], (SELECT 1 Where Chargecode='1242') AS [Peak], Peak*2 AS [Peak], CallType from Daisy_March2014 ``` Thanks
You want a `case` statement. I think this is what you are looking for: ``` Select Chargecode, (case when chargecode = '1' when chargecode = '1242' then 2 else 2 * Peak end) as Peak, CallType from Daisy_March2014; ```
Thanks Gordon, I have marked you response as Answered. Here is the final working code: ``` (case when chargecode in ('1') then 1 when chargecode in ('1264') then 2 else Peak*2 end) as Peak, ```
SQL sub query logic
[ "", "sql", "" ]
I have three separate tables which stores data. **Table1 (executes and stores weekly. use data from last week (e.g. 4/27 to 5/3))**: ``` Date Value1 Value2 5/3/2014 56 13 5/10/2014 12 25 5/17/2014 90 52 5/24/2014 82 36 5/31/2014 76 98 6/7/2014 34 25 6/14/2014 13 63 6/21/2014 45 98 ... ``` **Table2 (executes and stores weekly. use data from last week (e.g. 4/27 to 5/3))**: ``` Date Value3 Value4 5/3/2014 54 62 5/10/2014 43 36 5/17/2014 90 43 5/24/2014 54 35 5/31/2014 76 45 6/7/2014 34 43 6/14/2014 23 37 6/21/2014 34 56 ... ``` **Table3 (executes and stores daily from 4/27 and so forth)**: ``` Date Value5 Value6 4/27/2014 56 45 4/28/2014 34 34 4/29/2014 23 34 4/30/2014 15 90 5/1/2014 34 23 5/2/2014 45 12 5/3/2014 46 35 5/4/2014 67 38 5/5/2014 34 23 ... ``` How can I write a query which will calculate each column by MONTH? My table will look like this: ``` Month Value1 Value2 Value3 Value4 Value5 Value6 April NULL NULL NULL NULL 128 203 May 316 224 317 221 226 131 ``` I have the query which gets the first of the current month: ``` CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, @DATE) as DATE) ``` First of the next month: ``` CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, DATEADD(m, 1, @DATE)) as DATE) ``` I am thinking my query can be something like this: ``` SELECT DATENAME(MONTH, @DATE) as [Date], (SELECT [Value1] From [database].[dbo].[Table1] WHERE [Date] >= CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, @DATE) as DATE) AND [Date] < CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, DATEADD(m, 1, @DATE)) as DATE) ) AS [VAL1], (SELECT [Value2] From [database].[dbo].[Table1] WHERE [Date] >= CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, @DATE) as DATE) AND [Date] < CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, DATEADD(m, 1, @DATE)) as DATE) ) AS [VAL2], (SELECT [Value3] From [database].[dbo].[Table2] WHERE [Date] >= CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, @DATE) as DATE) AND [Date] < CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, DATEADD(m, 1, @DATE)) as DATE) ) AS [VAL3], (SELECT [Value4] From [database].[dbo].[Table2] WHERE [Date] >= CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, @DATE) as DATE) AND [Date] < CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, DATEADD(m, 1, @DATE)) as DATE) ) AS [VAL4], HOW TO DO VALUE5, HOW TO DO VALUE6 INTO [database].[dbo].[tablemonthly] ``` I am requesting some help in completing the above query. Also, how can I use an `IIF` statement with the above query so it only adds the row once and update only Value5 and Value6 as it is DAILY and keep the other intact because it will be part of a bigger Stored Procedure which is ran daily? My Three tables is: ![enter image description here](https://i.stack.imgur.com/s7Rai.png)
To make sure you get all the months you need to have a reference table -- here I use a CTE but you could just make the table. You could also use a recursive CTE to build the table based on input instead of hard coding the values as I did here. Note I'm using the technique that Gordon mentioned to join all the data together in a union. ``` WITH Ranges AS ( SELECT 'April' AS M, '4/1/2014' AS [START], '4/30/2014' AS [END] UNION ALL SELECT 'May', '5/1/2014', '5/31/2014' -- etc ), Data AS ( select [date], value1, value2, NULL as value3, NULL as value4, NULL as value5, NULL as value6 from table1 union all select [date], NULL, NULL, value3, value4, NULL, NULL from table2 union all select [date], NULL, NULL, NULL, NULL, value5, value6 from table3 ) , Joined AS ( SELECT M as [Month], Value1, Value2, Value3, Value4, Value5, Value6 FROM Ranges R JOIN Data D ON D.[DATE] >= R.[START] AND D.[Date] <= R.[END] ) SELECT [Month], SUM(Value1), SUM(Value2), SUM(Value3), SUM(Value4), SUM(Value5), SUM(Value6) FROM Joined GROUP BY [Month] ```
This query lists the YEAR, MONTH, and totals for VALUE#s. Even though the query may be long, it would run very quickly, because the joins operate on a smaller subset of Table1, Table2, and Table3 (because they are first filtered). Then, they are joined using the Month and Year parts of the Date column. Finally, the data is ordered by Month and Year. ``` SELECT COALESCE(DATENAME(YEAR, Table1.[Date]), DATENAME(YEAR, Table2.[Date]), DATENAME(YEAR, Table3.[Date])) AS Year , COALESCE(DATENAME(MONTH, Table1.[Date]), DATENAME(MONTH, Table2.[Date]), DATENAME(MONTH, Table3.[Date])) AS Month , COALESCE(SUM(Table1.Value1), 0) Value1 , COALESCE(SUM(Table1.Value2), 0) Value2 , COALESCE(SUM(Table2.Value3), 0) Value3 , COALESCE(SUM(Table2.Value4), 0) Value4 , COALESCE(SUM(Table3.Value5), 0) Value5 , COALESCE(SUM(Table3.Value6), 0) Value6 FROM ( SELECT * FROM Table1 WHERE [Date] >= CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, @DATE) as DATE) AND [Date] < CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, DATEADD(m, 9, @DATE)) as DATE) ) Table1 FULL JOIN ( SELECT * FROM Table2 WHERE [Date] >= CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, @DATE) as DATE) AND [Date] < CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, DATEADD(m, 9, @DATE)) as DATE) ) Table2 ON DATENAME(MONTH, Table1.[Date]) = DATENAME(MONTH, Table2.[Date]) AND DATENAME(YEAR, Table1.[Date]) = DATENAME(YEAR, Table2.[Date]) FULL JOIN ( SELECT * FROM Table3 WHERE [Date] >= CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, @DATE) as DATE) AND [Date] < CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, DATEADD(m, 9, @DATE)) as DATE) ) Table3 ON DATENAME(MONTH, Table1.[Date]) = DATENAME(MONTH, Table3.[Date]) AND DATENAME(YEAR, Table1.[Date]) = DATENAME(YEAR, Table3.[Date]) GROUP BY COALESCE(DATENAME(YEAR, Table1.[Date]), DATENAME(YEAR, Table2.[Date]), DATENAME(YEAR, Table3.[Date])) , COALESCE(DATENAME(MONTH, Table1.[Date]), DATENAME(MONTH, Table2.[Date]), DATENAME(MONTH, Table3.[Date])) ORDER BY COALESCE(DATENAME(YEAR, Table1.[Date]), DATENAME(YEAR, Table2.[Date]), DATENAME(YEAR, Table3.[Date])) , MONTH(CAST(COALESCE(DATENAME(MONTH, Table1.[Date]), DATENAME(MONTH, Table2.[Date]), DATENAME(MONTH, Table3.[Date])) + ' 1 2014' AS DATETIME)); ``` Here is the updated `SQL Fiddle demo`, which contains data for all sorts of combinations.
How to get monthly data from three separate table
[ "", "sql", "sql-server", "date", "" ]
I have an entries table: id, name Users can enter as many times as they want. I want to retrieve the total of users who have entered 2 times. So if the table looked like this: ``` user_id name ------- ---- 3 chuck 4 larry 5 george 3 chuck 4 larry ``` The query would return 2, since user\_id 3 and 4 were the only user's who had two entries into the entries table.
Try This: ``` select user_id , count(name) as c from table_name GROUP BY user_id having count(*) = 2 ``` [**SQL FIDDLE**](http://sqlfiddle.com/#!2/1ab3de/7)
use `count(*)` method ``` select userid,count(*) as count from (select count(*) as c,userid from entries here c>=2 group by user_id) as dummy_table ```
total of entries where record/row count equals 2
[ "", "mysql", "sql", "" ]
I want to search a column for all instances of a string For example, if I have this a column with the value `all good all bad all better` I want to find the number of instances of `all`. I tried ``` select instr(column, 'all') from test_table; ``` but that only returns the position of the first occurrence of `all`. I'm using Oracle 11g database. Is there a way I can find all instances of a specific string in Oracle db?
Since you're on 11g, you can use the [`regexp_count` function](http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions135.htm#SQLRF20014). If you want to do a case-sensitive count ``` SELECT regexp_count( column, 'all' ) FROM table_name ``` If you want a case-insensitive count ``` SELECT regexp_count( column, 'all', 1, 'i' ) FROM table_name ```
``` SELECT REGEXP_COUNT(column, 'all') AS Cnt FROM test_table; ```
Finding all instances of a word in a string with SQL
[ "", "sql", "oracle", "oracle11g", "" ]
My below tables are excel sheet data converted as access table using VBA. I'm sorting the data where *EID<>7006* or *EID<>3456* i.e sorting all column data but not either EID=7006 or EID=3456. But sometimes EID=7006 won't present in the table based on the excel file i convert. Table1 has EID=7006 and EID=3456 ``` Description EID Basecode ----------- ---- --------- ssdad 3456 S2378797 gfd 1002 S1164478 gfdsffsdf 1003 R1165778 ssdad 3456 M0007867 gfd 1005 N7765111 gfdsffsdf 7006 W5464111 gfd 1005 N7765111 ``` some times Table1 does not have EID=7006 ``` Description EID Basecode ----------- ---- --------- ssdad 3456 S2378797 gfd 1002 S1164478 gfdsffsdf 1003 R1165778 ssdad 3456 M0007867 gfd 1005 N7765111 gfdsffsdf 88 W5464111 gfd 1005 N7765111 ``` If i specify my query ignoring both *7006* or *3456* like in table1, since i don't know whether *EID=7006* present or not, i represent in the query like ``` SELECT Description,EID,Basecode from table2 where EID<>7006 or EID<>3456 ``` Still i see *7006* and *3456* in the result query.
Looks like your issue is using OR when you mean AND ``` SELECT Description,EID,Basecode from table2 where EID<>7006 AND EID<>3456 ```
A *slightly* cleaner query would be: ``` SELECT Description, EID, Basecode FROM table2 WHERE EID NOT IN (7006, 3456) ```
Sorting specified data in WHERE clause access sql
[ "", "sql", "ms-access-2010", "" ]
I have a table in SQL Server called `Personal_Info`. Tthis table has a column called `Vol_ID` and the `(Is Identity)` property is `Yes`. Now I inserted about 175568 rows as a test. And then I deleted about 568 rows, BUT when I insert the data again the column `Vol_ID` start from 175569 not from 175001. I want to insert the data and let the column `Vol_ID` start from the last number in it. For example if the last row is 15, the next row should be start from 16, even if I already inserted but I delete it. I need a stored procedure or a trigger that can force the insert operation to filled that missing id's, check the last exist row and if there is missing id's after the exist one then filled it. I have this procedure to make the insertion ``` USE [VolunteersAffairs] go /****** Object: StoredProcedure [dbo].[AddVolunteer] Script Date: 05/02/2014 21:12:36 ******/ SET ansi_nulls ON go SET quoted_identifier ON go ALTER PROCEDURE [dbo].[Addvolunteer] @Vol_Name NVARCHAR(255), @Vol_Zone NVARCHAR(255), @vol_street NVARCHAR(255), @Vol_Sex INT, @Vol_Date_of_Birth DATE, @Vol_Home_Phone INT, @Vol_Work_Phone INT, @Vol_Mobile1 INT, @Vol_Mobile2 INT, @Vol_Email NVARCHAR(255), @Vol_Job NVARCHAR(255), @Vol_Affiliation NVARCHAR(255), @vol_Education INT, @vol_Education_Place NVARCHAR(255), @vol_Education_Department NVARCHAR(255), @vol_Interesting INT, @vol_Notes NVARCHAR(255), @Team_ID INT AS INSERT INTO personal_info (vol_name, vol_zone, vol_street, vol_sex, vol_date_of_birth, vol_home_phone, vol_work_phone, vol_mobile1, vol_mobile2, vol_email, vol_job, vol_affiliation, vol_education, vol_education_place, vol_education_department, vol_interesting, team_id, vol_notes) VALUES (@Vol_Name, @Vol_Zone, @vol_street, @Vol_Sex, @Vol_Date_of_Birth, @Vol_Home_Phone, @Vol_Work_Phone, @Vol_Mobile1, @Vol_Mobile2, @Vol_Email, @Vol_Job, @Vol_Affiliation, @vol_Education, @vol_Education_Place, @vol_Education_Department, @vol_Interesting, @Team_ID, @vol_Notes) ``` Please Help me to write the missing id's
you need to reseed the identity column like below ``` DBCC CHECKIDENT(Personal_Info, RESEED, 175001) ``` Quoted from MSDN > Permission: > > Caller must own the table, or be a member of the sysadmin fixed server > role, the db\_owner fixed database role, or the db\_ddladmin fixed > database role. So. it's either the owner of the table (OR) DBA can do the `reseed` of identity column and not normal user. moreover, why will you even allow your application user to reseed identity columns value? that won't make sense at all. **EDIT:** In that case check @Brennan answer below. in a nutshell, you should perform your insert from stored procedure. I mean your APP should call SP and perform the insert. Like below(a sample code). Also, in such case remove the identity property of vol\_id column (vol\_id should just be `vol_id int not null unique`) ``` create procedure sp_insert-person @name varchar(10) as begin declare @last_id int; select @last_id = top 1 Vol_ID from Personal_Info order by Vol_ID desc; insert into Personal_Info(Vol_ID,name) values(@last_id+1,@name); end ``` Your application will call the procedure like ``` exec sp_insert-person @name = 'user2251369' ``` **Final EDIT:** See this post [RESEED identity columns on the database](https://stackoverflow.com/questions/4165100/reseed-identity-columns-on-the-database) about why you should avoid `reseeding` IDENTITY value (A nice small explanation given by marc\_s). Your Final procedure should look like below ``` USE [VolunteersAffairs] GO /****** Object: StoredProcedure [dbo].[AddVolunteer] Script Date: 05/02/2014 21:12:36 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER procedure [dbo].[AddVolunteer] @Vol_Name nvarchar(255), @Vol_Zone nvarchar(255), @vol_street nvarchar(255), @Vol_Sex int, @Vol_Date_of_Birth date, @Vol_Home_Phone int, @Vol_Work_Phone int, @Vol_Mobile1 int, @Vol_Mobile2 int, @Vol_Email nvarchar(255), @Vol_Job nvarchar(255), @Vol_Affiliation nvarchar(255), @vol_Education int, @vol_Education_Place nvarchar(255), @vol_Education_Department nvarchar(255), @vol_Interesting int, @vol_Notes nvarchar(255), @Team_ID int As BEGIN DECLARE @last_vol_id int; select top 1 @last_vol_id = Vol_ID from Personal_Info order by Vol_ID desc; insert into Personal_Info (Vol_Id, Vol_Name, Vol_Zone, vol_street, Vol_Sex, Vol_Date_of_Birth, Vol_Home_Phone, Vol_Work_Phone, Vol_Mobile1, Vol_Mobile2, Vol_Email, Vol_Job, Vol_Affiliation, vol_Education, vol_Education_Place, vol_Education_Department, vol_Interesting, Team_ID, vol_Notes) values (@last_vol_id+1, @Vol_Name, @Vol_Zone, @vol_street, @Vol_Sex, @Vol_Date_of_Birth, @Vol_Home_Phone, @Vol_Work_Phone, @Vol_Mobile1, @Vol_Mobile2, @Vol_Email, @Vol_Job, @Vol_Affiliation, @vol_Education, @vol_Education_Place, @vol_Education_Department, @vol_Interesting, @Team_ID, @vol_Notes); END ```
What you are trying to do is not what the identity column was made for - there is no guarantee that there won't be gaps, and deleting records does not re-use the missing identities. If you really need a sequential, auto increment id field, with no gaps, then you are better of either using a stored procedure to do your inserts (to which you will need to add the logic to re-use missing id's), or else define a trigger that enforces what you want - but trying to force the identity column to do what you are trying to do is the wrong way to go about it.
How to reseed the identity column in SQL Server?
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2008-r2", "" ]
I am pretty new to SQL and might be doing something wrong here so I hope someone can help me with this. I have a longer stored procedure that ends with the below. The idea here is to combine two queries into one so that I don't need a separate stored procedure but still have the results separated as one selects by a country (`selCountry`) and the other selects by a date (`selDate`). When I try to save it this way I get the error: "`Incorrect syntax near the keyword 'UNION'`. When I run them in separate procedures then everything works fine. ``` -- create final output SELECT CONVERT(DATETIME, dDay) AS dDay, CONVERT(VARCHAR(11), dDay, 106) AS dLong, CONVERT(VARCHAR(10), dDay, 126) AS dShort, countries, regions, mode, dName, dDesc FROM @tempFix WHERE countries LIKE '%'+@selCountry+'%' OR regions LIKE '%'+@selCountry+'%' ORDER BY dDay UNION ALL SELECT CONVERT(DATETIME, dDay) AS dDay, CONVERT(VARCHAR(11), dDay, 106) AS dLong, CONVERT(VARCHAR(10), dDay, 126) AS dShort, countries, regions, mode, dName, dDesc FROM @tempFix WHERE DAY(dDay) = DAY(@selDate) AND MONTH(dDay) = MONTH(@selDate) FOR XML PATH('dDays'), ELEMENTS, TYPE, ROOT('root') ``` Many thanks in advance for any help with this, Mike.
Please remove the ORDER BY and add it to the very end. You cannot place ORDER BY before UNION / UNION ALL. **[Here](http://blog.sqlauthority.com/2012/10/30/sql-server-union-all-and-order-by-how-to-order-table-separately-while-using-union-all/)**'s more information about this syntax.
you can't include `ORDER BY` until after the last query in the `UNION`.
SQL Server: issue with UNION ALL and two Selects
[ "", "sql", "sql-server", "select", "union", "union-all", "" ]
I am trying to calculate the total amount for charity. Each row has a bid amount and a charity percentage. The structure of the fields looks like this: CurrentBid INT CharityPercentage INT <-- 0-100, where 100 is donating all to charity So i tried this: ``` SELECT CurrentBid, CharityPercentage, CurrentBid * (CharityPercentage / 100) AS TotalCharity FROM Items ``` However it yields this: ``` 50 100 50 70 100 70 25 50 0 50 25 0 30 10 0 55 15 0 ``` It works as long as the percentage is 100. Anything below and its 0. My guess is that it has to do with the int column. Any ideas on how to solve it? I have also tried to convert the int using a CAST in the select statement but that did not work. Its a very big procedure to change the INT column to something else.
Explicitly make at least one value a decimal/float/etc. In your case, you already have a literal numeric value, `100`; so, simply change it to, `100.0`: ``` CurrentBid * CharityPercentage / 100.0 AS TotalCharity ```
don't CAST -- instead, just multiply by 1.00. This does the CASTing implicitly. ``` SELECT CurrentBid, CharityPercentage, (1.00 * CurrentBid * CharityPercentage) / 100 AS TotalCharity FROM Items ```
Calculate percentage in MS SQL Server with int columns
[ "", "sql", "sql-server", "" ]
Having these 3 tables DEPARTMENT ``` //DEPARTMENT DNAME ----------- RESEARCH IT SCIENCE ``` PROJECT ``` //PROJECT P# TITLE ---------------- 1 COMPUTING 2 CODING 3 SEARCHING ``` DP <-- Assume constraint references done, just i didn't show the code here ``` //DP DNAME P# --------------- RESEARCH 1 IT 2 RESEARCH 3 ``` When using this statement ``` SELECT d.DNAME,P.TITLE FROM DEPARTMENT d INNER JOIN PROJECT INNER JOIN DP ON d.DNAME=DP.DNAME AND P.P#=DP.P#; ``` How should i change in order to get output like this, only show the DNAME that have projects ``` DNAME TITLES --------------------- RESEARCH COMPUTING RESEARCH SEARCHING IT CODING ```
Try this query ``` SELECT d.DNAME,P.TITLE from DEPARTMENT d INNER JOIN DP ON d.DNAME=DP.DNAME INNER JOIN PROJECT P ON P.P#=DP.P# order by d.DNAME DESC, P.TITLE ASC ```
Your `DEPARTMENT` data is already there in `DP` table. So use it. ``` select DNAME, TITLE from DP d, PROJECT p where d.p# = p.p# order by 1 ```
SELECT clause using 3 different tables
[ "", "sql", "oracle", "" ]
Considering the below table where is have 4 difference customers with more than 1 orders each. I need to updated the column XYZ to 1 for each customer depending on the date created column. ``` Update the table1 set xyz = 1 ``` condition only the latest ( date created ) order should have XYZ value as 0 ``` Customerid Orderid Date Created XYZ 12193438 13393354 09/08/2011 16:35 0 12193438 13384318 05/08/2011 14:08 0 12193438 13384458 08/08/2011 14:01 0 21801966 13379456 06/08/2011 12:59 0 21801966 13380639 06/08/2011 16:42 0 21971567 13385322 22/08/2011 18:00 0 21971567 13380200 09/08/2011 21:03 0 66697824 13389263 07/08/2011 13:44 0 66697824 13380162 08/08/2011 15:48 0 ``` IT should look as below ``` Customerid Orderid Date Created XYZ 12193438 13393354 09/08/2011 16:35 0 12193438 13384318 05/08/2011 14:08 1 12193438 13384458 08/08/2011 14:01 1 21801966 13379456 06/08/2011 12:59 1 21801966 13380639 06/08/2011 16:42 0 21971567 13385322 22/08/2011 18:00 0 21971567 13380200 09/08/2011 21:03 1 66697824 13389263 07/08/2011 13:44 1 66697824 13380162 08/08/2011 15:48 0 ```
DECLARE @customerid INT -- used for file name DECLARE db\_cursor CURSOR FOR SELECT distinct customerid FROM orders OPEN db\_cursor FETCH NEXT FROM db\_cursor INTO @customerid WHILE @@FETCH\_STATUS = 0 BEGIN UPDATE Orders set XYZ = 1 where Orderid <> (select top 1 Orderid from orders where Customerid = @customerid order by DateCreated desc) and Customerid = @customerid ``` FETCH NEXT FROM db_cursor INTO @customerid ``` END CLOSE db\_cursor DEALLOCATE db\_cursor
``` UPDATE thetable tt SET xyz = 1 WHERE EXISTS ( SELECT * FROM thetable ex WHERE ex.customerId = tt.customerId AND ex.dateCreated > tt.dateCreated ); ```
SQL table update all but the most recent record for every Id
[ "", "mysql", "sql", "" ]
On my filter form i have two edit and they are give the result like this "01.12.2014"... This is the turkish standard and format is dd.mm.yyyy In the code section i have controlled them and convert the value with formatdatetime. and create aa select sql. ``` if edtTar1.Value>0 then tar1:=FormatDateTime('yyyymmdd',edtTar1.Value); if edtTar2.Value>0 then tar2:=FormatDateTime('yyyymmdd',edtTar2.Value); tarsart := ' and ( Convert(nvarchar(8), Sip_Tarih, 112) >= Convert(nvarchar(8), cast('+QuotedStr(tar1)+' as datetime), 112) '+ ' and Convert(nvarchar(8), Sip_Tarih, 112) <= Convert(nvarchar(8), cast('+QuotedStr(tar2)+' as datetime), 112)) ' ; ``` Tar1 and Tar2 are string values. Sip\_tarih is datetime field. My question is can i get the record by date without using CAST in my SQL? Regards
Yes, this should work ``` tarsart := ' and Sip_Tarih >= cast('+QuotedStr(tar1)+' as datetime)) '+ ' and Sip_Tarih <= cast('+QuotedStr(tar2)+' as datetime)) ' ; ``` And depending on your SQL settings, this might work too ``` tarsart := ' and Sip_Tarih >= '+QuotedStr(tar1)+ ' and Sip_Tarih <= '+QuotedStr(tar2) ; ```
You should be able to do this easily by eliminating all the extra `Convert` statements: ``` tarsart := ' and (Sip_Tarih >= cast('+QuotedStr(tar1)+' as datetime) '+ ' and Sip_Tarih <= cast('+QuotedStr(tar2)+' as datetime)) '; ``` Now, this said, it would also be a good idea for you to look into paramaterized SQL queries. Not only does it eliminate the need to cast strings in your SQL, but it also protects your application from SQL Injection. Depending on the SQL server, it may also improve performance since compiled queries can be reused with different parameters.
How to select records by date without using CAST?
[ "", "sql", "delphi", "" ]
I'm having a problem with my SQL; the query selects only one row, even there are more rows it should select. ## Select statement ``` SELECT p.id, p.product_name, p.product_date, coalesce(t.unique_hits, 0) AS unique_hits, coalesce(t.total_hits, 0) AS total_hits, coalesce(COUNT(s.product_id), 0) AS total_sales, coalesce(SUM(s.amount), 0) AS total_revenue FROM products p LEFT OUTER JOIN tracking_hits t ON p.id = t.product_id LEFT OUTER JOIN transactions s ON p.id = s.product_id WHERE p.vendor_id = 10; ``` Example with DDL here: <http://sqlfiddle.com/#!2/b393df/3> I added two products with same vendor id and when I run the query, it selects only one product, even it should select both. ## SQL to create tables and data ``` CREATE TABLE products(id int, product_name varchar(100) , product_date varchar(100), vendor_id int); CREATE TABLE tracking_hits(id int, product_id int, unique_hits int , total_hits int); CREATE TABLE transactions(id int, product_id int, amount double); ``` Insert some data ``` INSERT INTO products(id, product_name, product_date, vendor_id) VALUES(0, "Product", "2014-05-02", 10); INSERT INTO products(id, product_name, product_date, vendor_id) VALUES(1, "Product", "2014-05-02", 10); INSERT INTO tracking_hits(id, product_id, unique_hits, total_hits) VALUES(0, 0, 10, 52); INSERT INTO tracking_hits(id, product_id, unique_hits, total_hits) VALUES(1, 1, 52, 124); INSERT INTO transactions(id, product_id, amount) VALUES(0, 0, 19.00); INSERT INTO transactions(id, product_id, amount) VALUES(1, 0, 19.00); INSERT INTO transactions(id, product_id, amount) VALUES(2, 0, 19.00); INSERT INTO transactions(id, product_id, amount) VALUES(3, 1, 29.00); ``` Whats the problem here?
You are missing group by while doing the aggregate function `sum()` ``` SELECT p.id, p.product_name, p.product_date, coalesce(t.unique_hits, 0) AS unique_hits, coalesce(t.total_hits, 0) AS total_hits, coalesce(COUNT(s.product_id), 0) AS total_sales, coalesce(SUM(s.amount), 0) AS total_revenue FROM products p LEFT OUTER JOIN tracking_hits t ON p.id = t.product_id LEFT OUTER JOIN transactions s ON p.id = s.product_id WHERE p.vendor_id = 10 group by p.id ; ```
Here is your query: ``` SELECT p.id, p.product_name, p.product_date, coalesce(t.unique_hits, 0) AS unique_hits, coalesce(t.total_hits, 0) AS total_hits, coalesce(COUNT(s.product_id), 0) AS total_sales, coalesce(SUM(s.amount), 0) AS total_revenue FROM products p LEFT OUTER JOIN tracking_hits t ON p.id = t.product_id LEFT OUTER JOIN transactions s ON p.id = s.product_id WHERE p.vendor_id = 10; ``` It is an aggregation query without a `group by` (because of the use of the aggregation functions `sum()` and `count()` in the `select`). Such a query always returns one row. I think you want: ``` SELECT p.id, p.product_name, p.product_date, coalesce(t.unique_hits, 0) AS unique_hits, coalesce(t.total_hits, 0) AS total_hits, coalesce(COUNT(s.product_id), 0) AS total_sales, coalesce(SUM(s.amount), 0) AS total_revenue FROM products p LEFT OUTER JOIN tracking_hits t ON p.id = t.product_id LEFT OUTER JOIN transactions s ON p.id = s.product_id WHERE p.vendor_id = 10 GROUP BY p.id, t.unique_hits, t.total_hits; ```
SQL Query With Joins Selects Only 1 row
[ "", "mysql", "sql", "" ]
I am trying to do a `CASE` statement that combines two columns that are not alike. However, these two columns are names and the name could actually be the same except it might sometimes contain a suffix. So for instance, I want to bring back the following: ``` LastName1 | LastName2 ------------------------ Ross | Ross, Jr. Lee | Lee Smith | Collins Martin | Martin Pierce, Sr. | Pierce ``` So, my statement looks like this: ``` SELECT CASE WHEN LastName1 <> LastName2 THEN LastName1 + ', ' + LastName2 ELSE LastName1 END AS LastName ``` This returns the results as such: ``` LastName --------- Ross, Ross, Jr. Lee Smith, Collins Martin Pierce, Pierce, Sr. ``` But I would like to use a `NOT LIKE` (or something similar) and if the first few characters of the `LastName1` column are similar to `LastName2`, only bring back one instance of the name. So my result set would look like: ``` LastName --------- Ross Lee Smith, Collins Martin Pierce ```
You can use left to take the first *n* characters. It is pretty clean LEFT(col, *n*) ``` SELECT CASE WHEN left(LastName1,4) <> left(LastName2,4) THEN LastName1 + ', ' + LastName2 ELSE LastName1 END AS LastName ``` But this will be prone to getting false positives, be carful with your data set and the number of characters you select on. In you example you have **,** which break the data from the suffix. If that is consistent you could select all the text before **,**. [Here is an example](https://stackoverflow.com/questions/8299176/how-to-select-only-the-characters-appearing-before-a-specific-symbol-in-a-sql-se)
I would extend your comparison using `like` comparison: ``` SELECT (CASE WHEN LastName1 like LastName2 + '%' THEN LastName1 WHEN LastName2 like LastName1 + '%' THEN LastName2 ELSE LastName1 + ', ' + LastName2 END) AS LastName ```
CASE statement to combine two columns except when first characters not similar
[ "", "sql", "t-sql", "" ]
**UPDATE** I have modified the SQL Fiddle to make the department names more reflective of what I am trying to get to. If you look at the fiddle there are 3 select statements. 1. Lists the departments in the correct order from the data 2. Result from my attempt at a pivot 3. Fake select so show what I am TRYING to get to In the result of my pivot attempt the second row is displaying a null for departmentLevel1 and departmentLevel3 should NOT be in this row. I have tried various combination of row\_number and partitions but I can't seem to figure this out. *Totally frustrated!* Here is my latest fiddle <http://sqlfiddle.com/#!3/175af/40> **BEFORE YOU VOTE TO CLOSE** Please read this question and then read the question sited as a duplicate. The question sited is MUCH more simplistic. Not only is my question asking about pivoting but grouping the pivot results and doing much more that pivoting start and stop times. I think are only looking at the title. If you don't want to read the whole question that is ok but don't assume it is the same as some other question with a similar title please. I realize that I must have an aggregate so I tried using max but I am really just trying to display this info in more tabular way so I can join this to another data set. Here is the starting data: ``` select departmentID, departmentParentID, departmentName, departmentGroupSortBy, departmentLevel, sortBy from vDepartmentList where regionID = 3 order by departmentGroupSortBy, departmentLevel, sortBy departmentID departmentParentID departmentName departmentGroupSortBy departmentLevel sortBy --------------------------------------------------------------------------------------------------- 111 neth test dept 1 1 1 115 111 test sub1 1 2 1 112 test2 2 1 2 113 112 new sub2 2 2 1 114 112 new sub 3a 2 2 2 116 114 should L3 2 3 1 ``` If I run this query: ``` select departmentParentID, [1] as departmentLevel1, [2] as departmentLevel2, [3] as departmentLevel3 from ( select departmentParentID, departmentLevel, departmentName from vDepartmentList where regionID = 3 ) p pivot ( max(departmentName) for departmentLevel in ([1],[2],[3]) ) as pvt order by departmentParentID ``` I get this result : ``` departmentParentID departmentLevel1 departmentLevel2 departmentLevel3 ---------------------------------------------------------------------------- test2 111 test sub1 112 new sub2 114 should L3 ``` But What I am trying to get is : ``` departmentParentID departmentLevel1 departmentLevel2 departmentLevel3 ---------------------------------------------------------------------------- 111 neth test dept test sub1 112 test2 new sub2 112 test2 new sub 3a should L3 ``` Does anyone have a suggestion as to where I have gone wrong?
Since you need to return 3 levels of a hierarchy data structure it might be significantly easier to use JOINs instead of using a PIVOT. You would start by returning the parent rows: ``` select p.departmentName from dbo.department p where p.departmentParentID is null; ``` This will get you all of the top level rows. Then you start adding a join for each additional level that you need, in your case you need a total of three levels so you will add two joins. The final query will be the following: ``` select p.departmentName department1, c.departmentName department2, gc.departmentName department3 from dbo.department p -- parent level left join dbo.department c -- child level on p.departmentID = c.departmentParentID left join dbo.department gc -- grandchild level on c.departmentID = gc.departmentParentID where p.departmentParentID is null; ``` See [SQL Fiddle with Demo](http://sqlfiddle.com/#!3/97141/1). It seems that this will be easier to get the result using a JOIN instead of using the PIVOT. This uses the source data not the recursive view that you created. This gives a result of: ``` | DEPARTMENT1 | DEPARTMENT2 | DEPARTMENT3 | |-------------|-------------|--------------| | depart1 | d1 sub1 | (null) | | depart2 | d2 sub | (null) | | depart2 | d2 sub2 | d2s2 subSub1 | ``` If you want to use a recursive query to get the result, then you could alter your current view slightly to return the 3 columns of names instead of the level numbers: ``` ;with cte as ( select departmentID, departmentParentID, departmentName as Department1, cast(null as varchar(100)) Department2, cast(null as varchar(100)) Department3, 1 as Level from dbo.department where departmentParentID is null union all select d.departmentID, d.departmentParentID, Department1, case when Level + 1 = 2 then d.departmentName else Department2 end, case when Level + 1 = 3 then d.departmentName else Department3 end, Level + 1 from dbo.department d inner join cte h on d.departmentParentID = h.departmentID ) select * from cte; ``` See [SQL Fiddle with Demo](http://sqlfiddle.com/#!3/97141/3). You could then do some filtering using a WHERE clause to return the rows that have all of the department values that you need.
i created below sql based on your view sql. you almost get the result in there. i use @temp table to remove the order by clause. probably you can remove the @temp table in the implementation. please try below sql: ``` declare @temp table ( id int identity, departmentLevel1 int, departmentLevel2 int, departmentLevel3 int, xRow int ) insert into @temp select d.lvl1, d.lvl2, d.lvl3 ,Rrow from ( select a.lvl1, a.lvl2, a.lvl3 ,row_number() over(partition by a.lvl1,a.lvl2 order by a.lvl1,a.lvl2) as Rrow ,departmentGroupSortby, departmentlevel, sortby from vDepartmentList a ) d where (d.lvl2 is not null) order by departmentGroupSortby, departmentlevel, sortby ; select c.departmentLevel1 as departmentParentID ,Case when c.departmentLevel1 = d.departmentid then d.DepartmentName else null end as DepartmentLevel1 ,Case when c.departmentLevel2 = e.departmentid then e.DepartmentName else null end as DepartmentLevel2 ,Case when c.departmentLevel3 = f.departmentid then f.DepartmentName else null end as DepartmentLevel3 --,d.departmentId ,e.departmentid ,f.departmentid from ( select a.id, a.departmentLevel1,a.departmentLevel2,a.departmentLevel3 ,a.xRow from @temp a inner join ( select cast(departmentLevel1 as nvarchar(5)) + cast(departmentLevel2 as nvarchar(5)) as xrow, count(cast(departmentLevel1 as nvarchar(5)) + cast(departmentLevel2 as nvarchar(5))) as xcount from @temp group by cast(departmentLevel1 as nvarchar(5)) + cast(departmentLevel2 as nvarchar(5)) ) b on cast(a.departmentLevel1 as nvarchar(5)) + cast(a.departmentLevel2 as nvarchar(5)) = b.xrow and a.xRow = b.xcount ) c left join department d on c.departmentLevel1 = d.departmentId left join department e on c.departmentLevel2 = e.departmentid left join department f on c.departmentLevel3 = f.departmentid ``` **Result** ``` departmentParentID DepartmentLevel1 DepartmentLevel2 DepartmentLevel3 ------------------ ---------------- ---------------- ---------------- 111 depart1 d1 sub1 NULL 112 depart2 d2 sub NULL 112 depart2 d2 sub2 d2s2 subSub1 ``` Hope this is help
SQL pivot with no aggregate
[ "", "sql", "sql-server", "pivot", "" ]
I would like to ask if my Mysql statement is correct or not.. When I run this under mysql it does not return any error but I cannot retrieve the row for it. Here's my statement: ``` SELECT * FROM timekeeping WHERE createddate = NOW() ``` Here's what my table looks like ![enter image description here](https://i.stack.imgur.com/8z48j.png)
[MySQL compare now() (only date, not time) with a datetime field](https://stackoverflow.com/questions/14533914/mysql-compare-now-only-date-not-time-with-a-datetime-field) Try this: ``` SELECT * FROM timekeeping WHERE DATE(createddate) = DATE(NOW()); ```
Most likely the `createddate = NOW()` is an exact time comparison , you are probably only interested in the year, month, day being the the same. See here for details on how to do what you are trying to do: <http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html>
mysql statement (SELECT) based on date now
[ "", "mysql", "sql", "select", "" ]
I'm basically trying to fetch the next three future events including today from the database m below is my query and it says that derived tables must have an alias , I'm new to this .. what would be the fix ? ``` select * from events where event_start_date in (select event_start_date from (select distinct event_start_date from events where event_start_date >= '2014-05-02' order by event_start_date) WHERE rownum <= 3) ```
> "derived tables must have an alias" That error means that when you use a subquery in the `FROM` clause, it's called a *derived table* and you must declare an alias for that. Here's a simpler form of your query that should work: ``` SELECT events.* FROM events JOIN (SELECT DISTINCT event_start_date FROM events WHERE event_start_date >= '2014-05-02' ORDER BY event_start_date LIMIT 3) AS d USING (event_start_date) ``` I provided an alias for the derived table where you see `AS d`. It doesn't matter what you choose as the alias, it just has to have one. > "Unknown column 'rownum' in 'where clause'" `ROWNUM` is an Oracle-specific feature that automatically provides an imaginary column to every result set, with an integer corresponding to the row number of that result set. But this is not standard SQL, and MySQL doesn't support it. So I removed the reference to the implicit `ROWNUM` column, and replaced it with a `LIMIT` clause.
Assuming that you have a column named `rownum`: ``` select * from events where event_start_date in (select distinct event_start_date from events where event_start_date >= '2014-05-02' AND rownum <= 3 order by event_start_date) T ``` **EDIT:** If you are trying something like `rownum` as in oracle, you can use `LIMIT`: ``` select * from events where event_start_date in (select distinct event_start_date from events where event_start_date >= '2014-05-02' order by event_start_date LIMIT 3) T ```
What's wrong with my SQL query ?? It won't fetch data
[ "", "mysql", "sql", "phpmyadmin", "" ]
I am trying to calculate running total in following query ``` select a.ICode, MONTH(a.VDate), YEAR(a.vdate) , sum(isnull(a.qty, 0)) , sum(isnull(a.qty, 0)) OVER (partition by a.icode order by a.icode) AS 'total' from t_Stock as a group by a.ICode, MONTH(a.VDate), YEAR(a.vdate) order by a.icode, YEAR(a.vdate), MONTH(a.VDate) ``` but I am getting an error: > Msg 8120, Level 16, State 1, Line 3 > Column 't\_Stock.Qty' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. Why does '`t_Stock.Qty`' needs to be in `GROUP BY` clause as I am already using aggregate function `(Sum(a.Qty))` ? Some demo data : ``` icode vtype qty vdate 32114 Sales -2 2013-06-03 18:09:17.953 33459 Sales -1 2013-06-03 19:39:59.843 34446 Sales -1 2013-06-03 20:46:17.030 39914 Tra -3 2014-01-07 13:02:31.000 30899 Sales -1 2013-06-04 11:48:06.267 25676 Sales -3 2013-06-04 17:34:01.470 32126 Sales -1 2013-06-04 18:12:44.267 34688 Sales -1 2013-06-04 18:40:52.750 31550 Sales -1 2013-06-04 19:26:40.937 32795 Sales -1 2013-06-05 12:03:00.250 ```
When using window functions with aggregation, you actually need to nest the results. Here is a version of your query that should work: ``` select a.ICode, MONTH(a.VDate), YEAR(a.vdate), sum(isnull(a.qty, 0)), sum(sum(isnull(a.qty, 0))) OVER (partition by a.icode order by a.icode) AS total from t_Stock a group by a.ICode, MONTH(a.VDate), YEAR(a.vdate) order by a.icode, YEAR(a.vdate), MONTH(a.VDate); ``` I'm not sure what you intend to do with this. Having the `order by` contain the same value as the `partition by` is unusual. I would expect something like this: ``` select a.ICode, MONTH(a.VDate), YEAR(a.vdate), sum(isnull(a.qty, 0)), sum(sum(isnull(a.qty, 0))) OVER (partition by a.icode order by year(a.vdate), month(a.vdate) ) AS total from t_Stock a group by a.ICode, MONTH(a.VDate), YEAR(a.vdate) order by a.icode, YEAR(a.vdate), MONTH(a.VDate); ```
write as: ``` select a.ICode,MONTH(a.VDate), YEAR(a.vdate) , sum(isnull(a.qty,0)) OVER(partition by a.icode order by a.icode) AS 'Runningtotal' , sum(isnull(a.qty,0)) OVER(partition by a.icode,MONTH(a.VDate), YEAR(a.vdate) order by a.icode,YEAR(a.vdate),MONTH(a.VDate)) AS 'total' from t_Stock as a --group by a.ICode ,MONTH(a.VDate), YEAR(a.vdate) order by a.icode,YEAR(a.vdate),MONTH(a.VDate) ```
sql server running total with over, partition
[ "", "sql", "sql-server", "sql-server-2012", "" ]