Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Trying to understand why this query produces results in descending order ``` SELECT DateDiff(minute, convert(datetime, SUBSTRING(MSH_07_DateTime, 1, 8) + ' ' + SUBSTRING(MSH_07_DateTime, 9, 2) + ':' + SUBSTRING(MSH_07_DateTime, 11, 2), 100), GetDate()) FROM EPDBHL7.DBO.[HL7MSH] WHERE MessageStatus <> 'o...
Unless you use an `ORDER BY` you cant guarantee any result order. So you probably get the order based in how the data is stored or how the planner get the data using the index just add ``` where MessageStatus <> 'ok' order by DateDiff(minute,convert(datetime, SUBSTRING ( MSH_07_DateTime ,1 , 8 ) + ' '+ SUBSTRING (...
If you are not specifying the ORDER BY clause then the order in which you are going to get the result is unspecified. > If you want to rely on the order of a query, ALWAYS add ORDER BY
Why does this SQL query returns data in descending order?
[ "", "sql", "sql-server", "t-sql", "" ]
I working with SQL Server data base in order to store very long Unicode string. The field is from type 'ntext', which theoretically should be limit to 2^30 Unicode characters. From [MSDN documentation](https://msdn.microsoft.com/en-us/library/ms187993.aspx): > ntext > > Variable-length Unicode data with a maximum str...
Based on what I've seen, you may just only be able to copy 43679 characters. It is storing all the characters, they're in the db(check this with Select Len(Reponse) From [table] Where... to verify this), and SSMS has problem copying more than when you go to look at the full data.
`NTEXT` datatype is deprecated and you should use `NVARCHAR(MAX)`. I see two possible explanations: 1. Your `ODBC` driver you use to connect to database truncate parameter value when it is too long (try using `SSMS`) 2. You write you generate your input string. I suspect you generate `CHAR(0)` which is **[`Null liter...
SQL Server NText field limited to 43,679 characters?
[ "", "sql", "sql-server", "sql-update", "ntext", "" ]
I am trying to Join 3 tables based on specific columns. data\_customer(main Table), data\_customer\_Address(Cust\_id as foreign key) and Data\_customer\_contacts (Cust\_id as foreign key) I have successfully achieved the result from below query: ``` SELECT cst.cust_companyName AS 'Company Name', cnt.cntct_fname...
You need to learn proper `join` syntax. Then you won't have such problems with your query. Simple rule: *Never* use commas in the `FROM` clause. *Always* use explicit `JOIN`. So, your QUERY should look like: ``` SELECT . . FROM data_customer cst JOIN data_customer_Address adr ON cst.cust_id = adr.cust_id J...
``` select cst.cust_companyName as 'Company Name', cnt.cntct_fname as 'Contact First Name', cnt.cntct_lName as 'Contact Last Name', cnt.cntct_mainPhone as 'Main Phn Number', cnt.cntct_Mobile as 'Mobile Number', cst.cust_mainEmail as 'Main Email', ...
SQL Join Query refactoring
[ "", "sql", "plsql", "sqlite", "" ]
I am using the AdventureWorks database and SQL Server 2012 T-SQL Recipes book and got myself into trouble on the following example : I have to check the SalesQuota in both 2007 and 2008 from Sales.SalesPersonQuotaHistory. ``` SELECT sp.BusinessEntityID , SUM(s2008.SalesQuota) AS '2008' , SUM(S2007.SalesQuota) AS '200...
Your first query is probably creating a cartesian product of the results. Instead, I would use conditional aggregation to get both values (which should match your second query): ``` SELECT sp.BusinessEntityID, SUM(CASE WHEN Year(spqh.QuotaDate) = 2007 then spqh.SalesQuota end) AS '2007', SUM(CASE WHEN Year(spqh....
If you aren't returning any columns from the `Sales.SalesPerson` table, you can exclude it and use `pivot` to get your desired results: ``` select BusinessEntityID, [2008], [2007] from ( select BusinessEntityID, year(QuotaDate) as SalesQuotaYear, sum(SalesQuot...
Table subsets comparison
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have a table with a varchar(max). I would like to know if it's possible to get all rows that contains any substring from a list of it. I know that for one value I can use like 'AAA%', but I don't know if like has any way to say something like where IN(). Something like this: ``` select * from TableA where TableA.F...
SQL Server includes the CONTAINS function so something like this will work fine. ``` SELECT * FROM TableA JOIN TableB ON CONTAINS(TableA.Field1, TableB.Fild1) AND TableB.field2 > 5 ``` You may need to adjust for your requirements. Here is the documentation on contains <https://msdn.microsoft.com/en-us/library/ms1877...
``` select * from TableA where exists (select 1 from TableB where TableA.Field1 like '%' + TableB.Fild1 + '%' and TableB.field2 > 5) ```
How can I get any row which substring is any?
[ "", "sql", "sql-server", "" ]
I would like to insert into one table from three different tables, but the first one statement below works, next one does not. What should I do? ``` SELECT * into NewTable from ta where farm like'%aa'; SELECT * into NewTable from tb where farm like'%aa'; SELECT * into NewTable from tc where farm like'%aa'; ```
try this way ``` select * into NewTable from ( SELECT * from ta where farm like'%aa' Union all SELECT * from tb where farm like'%aa' Union all SELECT * from tc where farm like'%aa' )a; ```
Query `select * into NewTable` in fact **creates** that `NewTable` according to results of select query and then insert these results. So in order to insert into existed table after first query, change second and third ones to ``` insert into NewTable select * from tb ... insert into NewTable select * from tc ... ...
'insert into' from more source-tables
[ "", "sql", "sql-server", "insert", "" ]
I came upon a rather interesting situation where I need guidance to help me design my Database schema that follows "best practises" or is done "the recommended way". My dilemma is as follows: I have an `Event` table with basic properties such as Id, Name, Date etc. It needs an address info so the most straight forwar...
For the reasons you give option 1 is a no-go. With option 2 you should not worry about unused Address records. In fact, they might turn useful during the creation of new Events or Users, as you could provide a search facility in your address "database". Taken further, you could even decide to pre-fill the Address tabl...
Addresses are tricky, indeed. First, address is an independent thing - its existence is beyond your control, rather it exists as long as its local council wants it to. Another important thing - addresses tend to be reused again and again, especially if we are talking about large events or short term rent accommodation...
What is the best solution to design sql table relationship for a table that will be used by other tables
[ "", "sql", "sql-server", "entity-framework", "database-design", "table-relationships", "" ]
How can I query a database that has the following columns : `id`, `name`. With the result having column 'name' rows displayed as list? ``` Id Name 1 name1 2 name2 3 name3 4 name4 Result: name1,name2,name2,name4 ``` Currently my query looks like this ``` SELECT name FROM banned ```
The [`group_concat`](https://dev.mysql.com/doc/refman/5.6/en/group-by-functions.html#function_group-concat) aggregate function should do the trick: ``` SELECT GROUP_CONCAT(name ORDER BY name) AS name FROM banned ``` EDIT: To answer the question in the comment, you could add a `separator` clause to replace the com...
SELECT GROUP\_CONCAT( DISTINCT Name ORDER BY Name SEPARATOR ',' ) FROM banned;
Column as list with comma between
[ "", "mysql", "sql", "select", "" ]
I have some SQL that selects columns from tables like normal. However, one of my columns (u.cmc\_rti\_type) is a number and I want it to output text instead. I assume I need some sort of if statement. Here is my sql: ``` SELECT '', s.student_number, s.lastfirst, s.grade_level, t.TEACHER, u.cmc_rti_tier, u.cmc_rti_...
You can use `CASE`: ``` SELECT '', s.student_number, s.lastfirst, s.grade_level, t.TEACHER, u.cmc_rti_tier, CASE u.cmc_rti_type WHEN 1 THEN 'Reading' WHEN 2 THEN 'Math' WHEN 3 THEN 'Enrichment' WHEN 4 THEN 'Both Math & Reading' ELSE NULL END AS cmc_rti_type FROM students s JO...
You can use `CASE` in following: ``` SELECT '', s.student_number, s.lastfirst, s.grade_level, t.TEACHER, u.cmc_rti_tier, CASE u.cmc_rti_type WHEN 1 THEN 'Reading' WHEN 2 THEN 'Math' WHEN 3 THEN 'Enrichment' WHEN 4 THEN 'Both M...
Translate SQL column result into text
[ "", "sql", "asp.net", "vb.net", "if-statement", "" ]
I have 5 tables. I want to find the unique discount values of all 5 tables using MYSQL. The form of the tables is: ``` table1(userid,discount) table2(userid,discount) table3(userid,discount) table4(userid,discount) table5(userid,discount) ```
You can use `UNION` to achieve this. The default behavior for `UNION` is that duplicate rows are removed from the result. The optional `DISTINCT` keyword has no effect other than the default because it also specifies duplicate-row removal. With the optional `ALL` keyword, duplicate-row removal does not occur and the ...
Use MySQL `union` ``` select * from ( select * from table1 union select * from table2 union select * from table3 union select * from table4 union select * from table5 )new group by new.discount ```
How to select unique discounts in multiple tables
[ "", "mysql", "sql", "" ]
I have the following SELECT statmentment ``` SELECT UserID ,UserName ,TradingParty ,Email ,[PrivDesc] ,LastLogin ,IsApproved FROM cte_getAll allUsers WHERE allUsers.TradingParty = COALESCE(@TradingParty, allUsers.TradingP...
If I understand your question correctly, you have a table variable that has values that you want to select from, but if they don't have any values in the table, you don't want the restriction at all. The reason you're getting the error you're getting is due to `COALESCE()` only expecting a single value to transform, b...
Since you are populating the temp table @selectedPriv prior to this statement just add an else there -- if the input is null have @selectedPriv = ``` SELECT DISTINCT PrivId FROM cte_getAll ``` This should be faster than a more complicated where statement that checks count(\*) in @selectedPriv which is the other way t...
SQL Subquery using IN Statment with coalesce
[ "", "sql", "subquery", "coalesce", "sql-in", "" ]
I have two tables, **tblFXRates** ``` Base Quote Rate USD JPY 1.5 USD GBP 2.5 USD EUR 1.75 EUR JPY 1.5 USD USD 1 ``` **tblHoldings** ``` FX FXRate EUR null EUR null USD null GBP null JPY null ``` What I would like to ...
You can use `UPDATE FROM JOIN`: ``` UPDATE th SET FXRate = tr.Rate FROM #tblHoldings th JOIN #tblFXRates tr ON th.FX = tr.Quote WHERE tr.Base = 'USD'; ``` `LiveDemo` Output: ``` ╔═════╦════════╗ ║ FX ║ FXRate ║ ╠═════╬════════╣ ║ EUR ║ 1.75 ║ ║ EUR ║ 1.75 ║ ║ GBP ║ 2.5 ║ ║ JPY ║ 1.5 ║ ║ USD ║ 1 ║ ...
Try this. ``` update h set h.FXRate = fx.rate from tblHoldings h inner join tblfxrates f on h.FX = f.Quote where h.base = 'USD' ```
update table with a join on a temporary table
[ "", "sql", "sql-server", "" ]
I have these data below ``` TABLE 1 SID CAMBORROW OTMARK S1 CAM1 1 S2 CAM2 1 S3 CAM3 0 TABLE 2 SID BOOKBORROW OTMARK S1 book1 1 S2 book2 0 S3 book3 0 TAB...
You have to `join` the tables with proper `join` syntax. [SQL Fiddle](http://sqlfiddle.com/#!4/dff63f/19) ``` SELECT t3.name, sum(nvl(t1.otmark,0)+nvl(t2.otmark,0)) FROM table3 t3 left join table2 t2 on t2.sid = t3.sid and t2.otmark =1 left join table1 t1 on t1.sid = t3.sid and t1.otmark =1 where t1.otmark is not...
This is your query: ``` Select table3.name SNAME,(table2.otmark+table1.otmark) COUNT From table3 inner join table2 on table3.sid=table2.sid inner join table1 on table1.sid=table2.sid Where table1.otmark>0 ```
How to get COUNT from several tables?
[ "", "sql", "oracle11g", "" ]
I can't seem to wrap my mind around getting this query right. I have three tables and want to combine them to show how many tickets are left at each location. I am running SQL Server 2008 R2. Location Table ``` LocationId | LocationName 1 | Location1 2 | Location2 3 | Location3 ``` Ticket...
You do need to move your tables around a little bit.. ``` SELECT l.LocationName, tpl.Amount, COALESCE(SUM(pt.Amount),0) Sold, tpl.Amount - COALESCE(SUM(pt.Amount),0) Remaining FROM Locations l INNER JOIN TicketsPerLocation tpl ON l.LocationID = tpl.LocationID LEFT JOIN Purch...
I can see a few problems in your query. See if fixing these solves it: 1. Since you want all locations, you should start with that table before the LEFT JOIN, not after it. 2. The Purchased Tickets table is an outer join, but you have it in your where clause. That's always a bad combination because those two things co...
Query that combines three tables to show total counts
[ "", "sql", "sql-server", "" ]
Need to check OR condition between multiple columns. ``` select * from tableA where (COL1 or Col2) is not null ``` how to fetch this? My actual query is something like : ``` select b.empname,b.hours,b.minutes from table1 a,table2 b where a.pk_id=b.fk_id and a.type='UT' and a.SOME_NUMBER='123' and b.hours is not nul...
``` select b.empname,b.hours,b.minutes from table1 a,table2 b where a.pk_id=b.fk_id and a.type='UT' and a.SOME_NUMBER='123' and COALESCE(b.hours,b.minutes) is not null; ``` worked fine for me. Thanks everyone for the input
Just use ``` select * from tableA where COL1 is not null or Col2 is not null ```
Oracle SQL - Fetch all rows if one among multiple columns not null
[ "", "sql", "oracle", "" ]
This is what I've got: ``` SELECT SUBJECT_ID, SUM(SOMETABLE.COLUMN) AS HOURS, POINTS, SEMESTER_ID FROM SOME_TABLES WHERE (GROUP = (SELECT TOP (1) GROUP FROM SOMETABLE2 WHERE (STUDENT_ID = 123))) GROUP BY SUBJECT_ID, POINTS, SEMESTER_ID HAVING (SUB...
You can use [**OVER**](https://msdn.microsoft.com/en-us/library/ms189461.aspx) clause, something like: **QUERY** ``` select distinct Id, sum(Hours) over (partition by SimId) Hours, sum(Points) over (partition by SimId) Points, SimId from #t ``` **SAMPLE DATA** ``` create table #t ( ...
Try this instead: ``` SELECT SUBJECT_ID,SEMESTER)ID ,SUM(HOURS) as HOURS ,SUM(POINTS) as POINTS FROM SOME_TABLES WHERE SUBJECT_ID = 12 GROUP BY SUBJECT_ID,SEMESTER)ID ```
How get multiple SUM() for different columns with GROUP BY
[ "", "sql", "sql-server", "t-sql", "group-by", "sum", "" ]
I have the two following tables: ***Person:*** ``` EntityId FirstName LastName ----------- ------------------ ----------------- 1 Ion Ionel 2 Fane Fanel 3 George Georgel 4 Mircea Mircel ``` ***SalesQuotaHistory**...
You have multiple rows for each year, so the first method is producing a Cartesian product. For instance, consider `EntityId` 100: ``` 1 1 1000 2014-01-01 00:00:00.000 2 1 1000 2014-01-02 00:00:00.000 3 1 1000 2014-01-03 00:00:00.000 ...
Is easy to see what is happening if you change your select to ``` SELECT * ``` and remove the `group by` You first approach need something like this **[Sql Fiddle Demo](http://sqlfiddle.com/#!6/18cc8/17)** ``` SELECT p.[EntityId] , p.FirstName , COALESCE(s2014,0) as [2014] , COALESCE(s2015,0) as [2015] FROM ...
Multiple joins with aggregates
[ "", "sql", "sql-server", "t-sql", "" ]
I am extracting some wildcards from a string type column using certain keywords but for certain keywords in my list i am getting some false positives which I do not want in my output. Some of the keywords in my wildcard select is 'old', 'older' and 'age' ``` select * from DESCRIPTIONS..LONG where (DESCR like '% old %'...
I suggest you to start looking at the LIKE Syntax from Microsoft: <https://msdn.microsoft.com/en-us/library/ms179859.aspx> Are you searching for a free text field? You could use the [] syntax: ``` SELECT FROM DESCRIPTION..LONG WHERE DESCR LIKE '%[ "\/-]age[,.:;'' "\/-]%' ``` You put inside square brackets everyt...
Assuming that spaces delineate the words, you can use this trick: ``` select * from DESCRIPTIONS..LONG where ' ' + DESCR + ' ' like '% old %' or ' ' + DESCR + ' ' like '% older %' or ' ' + DESCR + ' ' like '% age %'; ```
SQL Server wildcard select with a twist
[ "", "sql", "sql-server-2005", "" ]
I'm attempting to extract a username value from XML output that was loaded into a database column (file\_output). My query is bringing back a null value and not performing as I expect it to. Your help is appreciated. XML output: ``` <soap:Envelope xmlns:ones="http://onesource.gmtorque.com" xmlns:soap="http://www....
The problem that you’re running into is a bug with MySQL. The XML that you’re trying to parse is most likely too long. I’m pretty sure it’s related to this bug: <https://bugs.mysql.com/bug.php?id=62429>. To get around this bug, you can just extract the portion of the XML that you’re trying to navigate or just use anoth...
The XML sample you have is malformed as it is missing the closing `</soap:Envelope>` tag. [SQL Fiddle](http://sqlfiddle.com/#!9/63afd/1)
ExtractValue with MySQL
[ "", "mysql", "sql", "xml", "extract-value", "" ]
**I have a table budget like this:** ``` ╔════╦══════╦═══════╦═══════════╦══════╗ ║ Id ║ Site ║ Rayon ║ Date ║ Amt ║ ╠════╬══════╬═══════╬═══════════╬══════╣ ║ 1 ║ 20 ║ 23 ║ 2015-11-3 ║ 200 ║ ║ 2 ║ 40 ║ 2 ║ 2015-12-4 ║ 20 ║ ║ 3 ║ 20 ║ 3 ║ 2015-11-4 ║ 400 ║ ║ 4 ║ 30 ║ 13 ║ 2015-11-5 ...
With a problem such as this, the first thing you need to do is understand how to calculate "the end of this month" and "the end of this year". Using sql2008, you do not have access to a helpful function [`EOMONTH()`](https://msdn.microsoft.com/en-gb/library/hh213020.aspx) so you must calculate this yourself. There are...
For end of current month: ``` SELECT SUM(Amt) AS Amt FROM TableName WHERE Date >= CAST(GETDATE() AS DATE) AND Date < DATEADD(m, 1, DATEADD(dd, -DAY(GETDATE()) + 1, CAST(GETDATE() AS DATE))) ``` For end of current year: ``` SELECT SUM(Amt) AS Amt FROM TableName WHERE Date >= CAST(GETDATE() AS DATE) AND ...
Calculate sum of budget
[ "", "sql", "sql-server-2008", "" ]
The title may not seem to make sense, but I've been trying to get something to work here, but I must be missing a trick. To explain... For example, take these records containing the strings: ``` (1) 7 bla bla bla 17 bla bla 9 bla (2) Bla 12 bla bla 7 bla bla bla 54 bla bla (3) Bla bla bla 6 bla bla 17 bla bla bla 2 b...
You should probably be storing these values in a junction table, rather than in delimited lists. However, you can do what you want using `like`: ``` where ' ' + col + ' ' like '% 7 %' ``` That is, add delimiters to the beginning and end of the string and then use them in the pattern to match.
What about this - (include some spaces to exclude other values that include 7) ``` LIKE '7 %' OR LIKE '% 7 %' ```
In SQL Server, finding in a string record with 7 but not 17, but could have both
[ "", "sql", "sql-server", "" ]
i have two table here is `table_user` and `table_feedback` like below ``` table_user | id | name | |----|------| | 1 | john | | 2 | tony | | 3 | mona | table_feedback | id | rate | user_id | date | |----|------|---------|----------| | 1 | 1 | 3 |2015-11-2 | | 2 | 1 | 2 |2015-11-2 | | 3 | ...
The solution to this is an outer join. Anytime you find yourself thinking along the lines of "I need to see all rows from this table, regardless of a match in another table..." you should look to an outer join. We can use an outer join to select all users, and link them to the feedbackTable in our `JOIN` clause. This ...
My guess is you need to use `LEFT JOIN`: ``` SELECT table_user.id, table_user.name, table_feedback.rate, table_feedback.date FROM table_user LEFT JOIN table_feedback ON table_user.id = table_feedback.user_id AND table_feedback.date = '2015-11-2' ```
mysql help to make a report
[ "", "mysql", "sql", "" ]
So I have used [this](https://stackoverflow.com/questions/20719901/count-rows-per-hour-in-sql-server-with-full-date-time-value-as-result) post as a reference, however I would like to count all the rows based on a 15 minute time period. Here is what I have so far: ``` SELECT DateAdd(minute, DateDiff(minute, 0, [d...
To get 15 minutes, divide by 15 (and then multiply again): ``` SELECT DateAdd(minute, 15*(DateDiff(minute, 0, [datetime]) / 15), 0 ) as Timestamp, Count(*) as Tasks FROM [table] GROUP BY (DateDiff(minute, 0, [datetime]) / 15) ORDER BY Timestamp; ``` SQL Server does in...
``` SELECT ROUND(DATEDIFF(SECOND,{d '1970-01-01'},[datetime])/(15 * 60),0) as Timestamp, Count(*) as Tasks FROM [table] GROUP BY ROUND(DATEDIFF(SECOND,{d '1970-01-01'},[datetime])/(15 * 60),0) ORDER BY Timestamp ```
SQL Query by time interval
[ "", "sql", "sql-server", "" ]
I have a table Exams, where I have a date column in the following format: 'MM/DD/YYYY'. I have to sort this column and change the format to 'MONTH/DD/YYYY' My code is the following: ``` SELECT TO_CHAR(Exam_Date, 'MONTH/DD/YY') AS Exam_date FROM Exams WHERE Student_id = '0000049' ORDER BY Exam_dat...
You are not using sql server. It appears you are using Oracle. If you were using Sql Server, you could just cast to datetime, like the following: ``` ORDER BY cast(Exam_date as DATETIME) ``` I haven't used Oracle for a very long time... try using the following: ``` ORDER BY TO_DATE(Exam_Date) ```
I'm making the assumption that your underlying field in the Exams table for Exam\_date is a date or datetime type. If so, you need to understand that when you perform manipulations on a field and then call that expression the same thing as the underlying field name, you lose access to the base field when you attempt to...
SQL: How can I sort strings in Date format(MONTH/DD/YY)?
[ "", "sql", "string", "oracle", "sorting", "date", "" ]
Table 1 ``` 1 A 1 1 2 A 1 2 5 A 1 1 6 B 2 1 ``` Table 2 ``` 1 1 12 2 2 45 3 5 22 4 6 21 ``` table1.col1 is a FK to table2.col2 You want to duplicate values where col2 = A, and have col2 = AA : ``` 1 A 1 1 2 A 1 2 5 A 1 1 6 B 2 1 7 AA 1 1 <- New 8 AA 1 2 <- New 9 AA 1 1 <- New ``` How do you join Table ...
Untested: The logic seems solid, but I don't have data, test environment to try this... You could use a union and (inline view or a common table expression) to accomplish this. First we build table1 with both sets of desired data (inline view A below). This approach makes the join simple. This is accomplished using a...
consider each value A/B/AA in isolation and use window functions to find lag lead on col3 and col4 treat each "prev\_col3, col3, next\_col3, prev\_col4, col4, next\_col4" as a unique "context" identifier and join on that. this is how we can avoid confusing row 7 with row 9 in the data; they have distinct prev/next lag...
Joining on non unique columns
[ "", "sql", "sql-server", "join", "" ]
I'm selecting a `timestamptz` from a PosgreSQL database. I want my `SELECT` to return only the date, hours and minutes. No seconds. Can I set the date format in my psql `SELECT` to accommodate this?
You can use [**`date_trunc()`**](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC) to truncate seconds and still return a `timestamptz`: ``` SELECT date_trunc('minute', ts_col) ... ``` Or you can use [**`to_char()`**](https://www.postgresql.org/docs/current/functions-formatting...
With timezone: ``` SELECT date_trunc('minute', TABLE_NAME.COLUMN AT TIME ZONE '+03') FROM TABLE_NAME ```
Select timestamp with time zone, but ignore seconds
[ "", "sql", "postgresql", "timestamp-with-timezone", "" ]
I need to compare 2 dates and return the number of days in between. Here is a table as example: ``` +----+--------+-------------------------+-------------------------+ | id | userid | datestarted | datefinished | +----+--------+-------------------------+-------------------------+ | | |...
You can try this query. It gets the difference in minutes and multiply it by 2 in order to get a 0.5 day range. It then devide it by 24 hours and by 60 minutes before calculating the Ceiling value. Once you have it, it can be devide by 2 again. When the value is over 4.5\*24\*60 (4.5 days in minutes), it only has to b...
I believe this is what you're looking for - this will round the difference to 0.5 for anything under 4.5 hours in the day, and everything else over that will go to a full day: ``` Declare @StartDate DateTime = '2014-03-25 09:05:00.000', @EndDate DateTime = '2014-03-26 12:15:00.000' ;With TotalHours As ( ...
SQL calculate Datediff for half of the 8 working day
[ "", "sql", "sql-server", "" ]
My database has a cost table for items. Items can have more than one cost record. I want to grab only the items that have multiple cost records. The UPC field is F01, and the table is called COST\_TAB. I only want to grab items where there are multiple entries based on the F01 field. I'm struggling with how to write...
``` select F01 from COST_TAB group by F01 having count(*) > 1 ```
You need to use group by ``` select f01 from cost_tab group by f01 having count(f01) > 1 ```
How to select rows where that record has multiple entries?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table of contractors like so: ``` SELECT [ContractorID] ,[Contractor] ,[BWSLVendorCode] ,[PhoneNumber] ,[Address] ,[PreQualification] ,[GSTNumber] ,[Avg] FROM Contractor ``` And a Feedback table that stores individual rating and comments for each contractor like so: ``` SELECT [ID] ,[Contrac...
This will update the `Avg` column in the `Contractor` table with the average value of ratings of the contractor in the `Feedback` table. ``` ;with feedback_grouped AS ( SELECT f.ContractorID, AVG(CAST(f.rating as decimal(3,2))) as avg_rating FROM Feedback f GROUP BY f.ContractorID ) UPDATE Contractor SET av...
**EDIT** To automatically update the column value, you can use a trigger, which would look something like: ``` CREATE TRIGGER [DBName].[updateAvg] ON [DBName].Contractors AFTER UPDATE,INSERT AS BEGIN ;WITH avgRates AS ( SELECT [ContractorID] ,SUM([Rating]) as totalRating ,COUNT(*) as noOfRatings FROM Feedback...
SQL Server - How to get the average rating from another table and include it in current table?
[ "", "sql", "sql-server", "average", "calculated-columns", "" ]
I am trying to combine a date field and a number field into one in my query - I need the date to display as a number with the sequence number following. I have tried ``` SELECT CAST(movement_date AS int) + CAST(sequence_no AS int) AS MOVE ``` This gives the result 42312 for a date of 03/11/2015 and a sequence nu...
You need to cast it append it like a string as: ``` SELECT CAST(CAST(movement_date AS int) as varchar(5)) + CAST(CAST(sequence_no AS int) as varchar(6)) AS MOVE ``` **EDIT:** ``` SELECT (CAST(CAST(movement_date AS int) as varchar(5)) + RIGHT('00000'+ CAST(CAST(sequence_no AS int) as varchar(6)),6)) AS [MOVE] ``` ...
This is how you should do it. ``` SELECT {fn concat(CAST(CAST(movement_date AS int) AS varchar), CAST(CAST(sequence_no AS int) AS varchar))} AS MOVE FROM table_name ``` or ``` SELECT CONCAT(CAST(CAST(movement_date AS int) AS varchar), CAST(CAST(sequence_no AS int) AS varchar)) AS MOVE FROM table_name ``` If you s...
SQL SELECT Concatenate Date and Int fields and convert result to Int
[ "", "sql", "sql-server", "sql-server-2000", "" ]
I am not a db admin by any means so if semantics look a bit bizarre, I apologize. In SQL Server, is it possible to use a variable for a comparison operator like so? ``` declare @compare = '>'; declare @limit = '5'; select agentId, sessionId, duration from table_x where duration @compare @limit ``` I do not want to w...
You can, actually, by invoking different operators via a guard expression: ``` DECLARE @comparison varchar(2) = '>' DECLARE @limit int 5 = 123 SELECT Foo FROM Table WHERE ( @comparson = '>' AND Duration > @limit ) OR ( @comparson = '<' AND Duration < @limit ) OR ( @comparson = '=' AND Dura...
You can try doing this using dynamic sql, something like ``` declare @compare varchar(2) = '>'; declare @limit int = '5'; declare @dynamicQuery = nvarchar(max) = N'select agentId, sessionId, duration from table_x where duration' + @compare + @limit EXEC(@dynamicQuery) ```
Using variable in sql WHERE clause for Operation
[ "", "sql", "sql-server", "" ]
I've got this situation in a table ``` client staff code time1 time2 ------------------------ c1 null code1 c2 null code1 null s1 code1 null s2 code1 ``` Trying to grouping rows by staff and code : ``` SELECT GROUP_CONCAT(client),staff,code from table GROUP BY staff,code `...
(Little late answer :), but it may help someone else !) First, you must realize that a single `FROM` can't generate a row with **both** c1 and s1 (for example), and another row with **both** c1 and s2. Except, of course, a single row with `GROUP_CONCAT(client), GROUP_CONCAT(staff)`, but it wouldn't be useful, as it lo...
put the `where` clause before `group` like this :- ``` SELECT GROUP_CONCAT(client),staff,code from table where client IS NOT NULL AND staff IS NOT NULL GROUP BY staff,code ```
SQL group by exclude NULL value from grouping
[ "", "mysql", "sql", "group-by", "" ]
I created a table using the following migration: ``` class CreateProfilePictures < ActiveRecord::Migration def change create_table :profile_pictures do |t| t.integer :user_id, null: false t.integer :picture_id, null: false t.timestamps null: false end add_index :profile_pictures, :user...
There is a problem with the accepted answer: Rollbacks don't work correctly as the unique index is not restored. You could try this instead: ``` reversible do |dir| dir.up do remove_index :profile_pictures, :picture_id add_index :profile_pictures, :picture_id end dir.down do remove_index :profile_p...
You must remove your index with: ``` remove_index :profile_pictures, :picture_id ``` and add it again with: ``` add_index :profile_pictures, :picture_id ``` [ActiveRecord::Migration](http://api.rubyonrails.org/classes/ActiveRecord/Migration.html)
How can I remove a unique constraint from a database column in Rails?
[ "", "sql", "ruby-on-rails", "rails-migrations", "" ]
I have declared in MSSQL 2 variables that can be `null` so: ``` DECLARE @startCheckDate VARCHAR(10) = '2015-10-20' --this can be null DECLARE @endCheckDate VARCHAR(10) = '2015-10-31' -- this can be null ``` Variables can be both `null` or both not `null` no other option. Now in the `where` condition in my query I w...
If my understanding of this question is correct, you could do this with an `OR` condition in the `WHERE` clause as opposed to using `CASE`. **NOTE:** You should compare `DATE` values as dates. I've added conversions to change the values from strings to `DATE` values, but it would be easier if the values were of type `...
In SQL, when I need to dynamically build where clause, I build the query and run it using Exec. It helps me to reduce all these case statements which may be expensive in terms of performance. Something similar below. This way you can build where clause dynamically ``` declare @since varchar(10) = '2015-10-20' --this i...
Check if variables are null in where clause using case
[ "", "sql", "sql-server", "" ]
I have 2 tables: Table `objects`: ``` object_id | object_group_id ``` Table `attributes`: ``` attr_id | attr_object_id | attr_property_id | attr_value ``` Now, I want to get all `object_id` where `object_group_id = 1` and filters two attributes: ``` (attr_property_id = 1 AND attr_value <= '100000') AND (attr_...
After couple hours of combining and trying, I finally did: ``` SELECT * FROM objects as o /* filter1 join */ INNER JOIN attributes AS f1 ON o.object_id = f1.attr_object_id AND f1.attr_property_id = 1 AND f1.attr_value <= '100000' /* filter2 join */ INNER JOIN att...
I've come up with an alternative, possibly more understandable approach. Let's look at the problem step by step in a simple example. Our initial tables can have the following data: *objects* table: ``` object_id | object_group_id 1 1 2 1 3 1 4 ...
Filtering EAV table with multiple conditions
[ "", "mysql", "sql", "entity-attribute-value", "" ]
I am trying to find all items on hand from `@Supplier_ID` and summarize any sales since `@Begin_Date`. What is returned are all items on hand that have never been sold and those sold since `@Begin_Date`. Items on hand that were sold *before* `@Begin_Date` are excluded from the results. How do I fix that? I am using SQ...
You could move your `invoice_hdr.invoice_date >= @Begin_Date` to your join statement ``` FULL OUTER JOIN invoice_hdr ON invoice_line.invoice_no = invoice_hdr.invoice_no AND invoice_hdr.invoice_date >= @Begin_Date ``` Don't see a lot of `FULL OUTER JOIN`s. Sure you don't want `LEFT JOIN` here? You might...
Try changing ``` WHERE (inventory_supplier.supplier_id = @Supplier_ID) AND (invoice_hdr.invoice_date >= @Begin_Date OR invoice_hdr.invoice_date IS NULL) AND (inv_loc.qty_on_hand > 0) ``` to ``` WHERE (inventory_supplier.supplier_id = @Supplier_ID) AND (invoice_hdr.invoice_...
SQL: How do I show all Items in Inventory and Sum sales of items sold in a time period?
[ "", "sql", "sql-server", "reporting-services", "" ]
Is it possible in SQL to select values in a column then rename the duplicate ones? (assuming maximum of one possible duplicate only) Let's say I have a table.. ``` | id | name | 0or1_id | | 0 | Eddy | 0 | | 1 | Allan | 0 | | 2 | Eddy | 1 | | 3 | Allan | 1 | ``` What query can I do to m...
Assuming you want to actually change the data, use `update`: ``` update t join (select name, count(*) as cnt, min(id) as minid from t group by name having cnt > 1 ) tt on t.name = tt.name and t.id <> tt.minid set name = concat(name, '-copy'); ``` If you only want a `se...
This will work in SQL Server.. ``` select id , name ,0or1_id from ( select id , name ,0or1_id ,row_number() over (partition by name order by id ) as rnm from table)z1 where rnm =1 union select id , name || '- Copy' as new_name ,0or1_id from ( select id , name ,0or1_id ,row_number() over (partition by name order by id...
SQL - Select same values in column then rename them
[ "", "mysql", "sql", "" ]
I have a table with the following structure ``` Item Id, Start Date, End Date 1 , 2015-01-01, 2015-06-01 2 , 2015-01-01, 2015-02-01 3 , 2015-03-01, 2015-08-01 4 , 2015-06-01, 2015-10-01 ``` I would like to view results so i will have *each month in the column*. Each row will contain the ...
In order to use pivot, you can create a recursive cte get each item id and the list of months it covers, then pivot the cte. ``` ;WITH cte AS ( SELECT [Item Id], [Start Date], [End Date] FROM Table1 WHERE [Start Date] BETWEEN '2015-01-01' AND '2015-03-01' --Date Range you want OR [End Date]...
You most likely need to use dynamic SQL. > This is your data: ``` declare @first date = '20150101'; declare @last date = '20150301'; Create Table #items(ItemId int, StartDate date, EndDate date); Insert into #items(ItemId, StartDate, EndDate) values (1, '2015-01-01', '2015-06-01') , (2, '2015-01-01', '2015-02-01')...
SQL - possible pivot issue
[ "", "sql", "sql-server", "pivot", "" ]
Column name Subject Value = Something TEST001 something I need to get TEST001 from "Something TEST001 Something" If there are spaces or any specials characters after the 1 of TEST001 they will be removed. I only have this ``` SELECT Subject , REPLACE(SUBSTRING(MailSubject, CHARINDEX('TEST', MailSubject)...
Based on comments here is edited solution: ``` DECLARE @t TABLE(v VARCHAR(100)) INSERT INTO @t VALUES ('Something TEST001 something'), ('Something [TEST0001] something'), ('Something TEST001 something 123 something'), ('Something {TEST0001} something 123 something') ;WITH cte AS(SELECT SUBSTRING(v, CHARINDEX('TEST', ...
I would do this using a subquery. It is easier to handle the intermediate results. First, get rid of the part before the "TEST". Then, take the result up the first first space: ``` select left(ms1, charindex(' ', ms1)) as TestStuff from (select stuff(MailSubject, 1, charindex(' TEST', MailSubject), '') as ms1 fr...
How do i get a certain string from a column in sql
[ "", "sql", "sql-server", "t-sql", "" ]
I try to do a simple select for some duplicates but my sql statement always end up with this error: > Command not properly ended What I have is a table like this ``` EAN STR ============= ==== 8030524096397 AAAA 8030524096397 BBBB 8030524096731 XXXX 8030524096731 YYYY 8030524096324 CCC...
I don't think SQLBase 7.01 supports proper ANSI `JOIN` syntax (aside: what a good reason to use a more modern product). The error indicates a problem on the `INNER JOIN`. Here are two possible solutions. First, yucky archaic `join` syntax: ``` SELECT * FROM EAN E, ( SELECT EAN, COUNT(*) as cnt FROM ean GROUP BY...
Try this (adding aliases to the tables with `AS` keyword) ``` SELECT * FROM EAN AS E INNER JOIN (SELECT EAN, COUNT(*) FROM ean GROUP BY ean HAVING COUNT(*) > 1) AS R ON E.EAN = R.EAN; ```
SQL-Select ends up in an Error when combined
[ "", "sql", "sqlbase", "sqltalk", "" ]
Error: > Msg 121, Level 15, State 1, Procedure InsertNonExistingNode, Line 5 > The select list for the INSERT statement contains more items than the > insert list. The number of SELECT values must match the number of > INSERT columns. Procedure in SQL Management Studio: ``` USE NWatchEntitiesUnitTest GO CREATE PROC...
You have a missing column in your `INSERT` , the column is `Name` , you have `Name` column in your `SELECT` statement, but not in `INSERT`. To fix, just put `Name` in your insert statement between `NodeTypeId` and `Location`. Below are the correct query to remove your error, but it seems you `select` the name twice, ...
Your select clause has 14 columns ``` NodeTypeId, Name, Location, DisplayName, AccessLevel, IsEnabled, CreatedOn, CreatedBy, ModifiedOn, ModifiedBy, NativeId, SourceId, Name, Alias ``` But in your INSERT only 13 ``` NodeTypeId, /...
SQL Procedure Error - INSERT statement contains more items than the insert list
[ "", "sql", "sql-server", "stored-procedures", "" ]
I wrote a sql query which is as below ``` SELECT ryot_code, ryot_name, variety_group, SUM(total_area) FROM field_survey_trn WHERE unit_code = '01' AND season_cntrl = 20 AND crop_type_code NOT IN (11,12) AND ryot_code != 0 GROUP BY ryot_code, ryot_name, variety_group; ``` **output** [![enter image description h...
I wrapped the query in your original question in an outer query which performs a pivot on the `variety_group` column: ``` SELECT t.ryot_code, t.ryot_name, SUM(CASE WHEN t.variety_group = 10 THEN t.theSum ELSE 0 END) AS '10', SUM(CASE WHEN t.variety_group = 20 THEN t.theSum ELSE 0 END) AS '20', SUM(CASE WHE...
you can do this in SQL using `PIVOT`. ``` SELECT * FROM ( SELECT ryot_code, ryot_name, variety_group, total_area FROM field_survey_trn WHERE unit_code = '01' AND season_cntrl = 20 AND crop_type_code NOT IN (11,12) AND ryot_code != 0 ) as my_name PIVOT ( SUM(total_area) FOR [variety_group] IN ([1...
Sql: show data in a single row instead of different columns
[ "", "mysql", "sql", "" ]
Suppose I have the following table: [![enter image description here](https://i.stack.imgur.com/uOFXa.png)](https://i.stack.imgur.com/uOFXa.png) My goal is to display a select resultset that looks like this: [![enter image description here](https://i.stack.imgur.com/qt0ye.png)](https://i.stack.imgur.com/qt0ye.png) T...
You can calculate the average per booktype in a derived table and `join` it to the original table to get the result. ``` select book_num, t.booktype, x.avgcost, bookcost, x.avgcost-bookcost from tablename t join (select booktype, avg(bookcost) as avgcost from tablename group by booktype) x on t.booktype = x.booktype ...
you need use [analytic functions](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions004.htm) AVG per BookType ``` select b.*, avg(bookcost) over (PARTITION BY BookType) from book b ``` AVG for all books ``` select b.*, avg(bookcost) over () from book b ```
SQL query scenario.
[ "", "sql", "oracle", "group-by", "" ]
I have a table of data which has students and their subject results in it. The students will appear multiple times, once for each subject they have a result for. ``` **tableID,studentID,lastName,firstName,subject,grade** 1,1a,Student1,Name1,English,A 2,1a,Student1,Name1,Maths,A 3,1a,Student1,Name1,Science,A 4,2a,Stude...
I was able to get the results I want by using a sub-query: ``` SELECT studentID, lastName, firstName FROM table WHERE grade = "A" AND studentID NOT IN (SELECT studentID FROM table WHERE grade <> "A" GROUP BY studentID) GROUP BY studentID, lastName, firstName ``` This seems to exclude all students who received a resul...
Get all students with grade A except students with any other grade ``` SELECT studentID,lastName,firstName FROM (SELECT studentID,lastName,firstName FROM result WHERE grade = 'A' GROUP BY studentID,lastName,firstName) GradeA LEFT OUTER JOIN (SELECT studentID,lastName,firstName FROM re...
SQL Select entries where none of the entities have a value in a particular column
[ "", "sql", "ms-access", "" ]
I need to do an operation based on an other operations result. Something such as: ``` SELECT SUM(first_column) as res1, SUM(second_column) as res2, res1/res2 as res3 FROM my_table ``` But it seems that it's only possible to do operations on existing columns. What is the workaround for this use case?
You can use subquery to achieve that. Something like this: ``` SELECT res1, res2, res1/res2 as res3 (SELECT SUM(xxx) as res1, SUM(xxx) as res2 FROM yyy) as subquery ```
Try something like: ``` SELECT res1/res2 as res3 FROM (SELECT SUM(xxx) as res1, SUM(xxx) as res2 FROM yyy)) ```
MySQL query with an operation based on an other operation result
[ "", "mysql", "sql", "" ]
Good Afternoon, I have what seems like a simple problem that has turned out to be not so simple. I have 2 dates. BeginPeriod (2010-06-10) and EndPeriod (2011-06-11). What I would like to see if if these dates can be broken down into their respective monthly break downs. For the above example something like * 2010/06/...
CTE it is. ``` DECLARE @BeginPeriod DATETIME = '2010-06-10', @EndPeriod DATETIME = '2011-06-11' ;WITH cte AS ( SELECT DATEADD(month, DATEDIFF(month, 0, @BeginPeriod), 0) AS StartOfMonth, DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, @BeginPeriod) + 1, 0)) AS EndOfMonth UNION ALL SELECT DAT...
Another options with "Numbers" CTE ``` declare @df datetime, @dt datetime set @df = '20100610' set @dt = '20110611' ;WITH e1(n) AS ( SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL ...
SQL Split Period by Months
[ "", "sql", "sql-server", "t-sql", "common-table-expression", "" ]
I have a sql which is failing in a left outer join subquery with ``` ORA-01427: single-row subquery returns more than one row ``` Here is the `left outer join` query fragment: ``` LEFT OUTER JOIN (aa.location) LOCATION ON (location_info_300.client_num = location.client_num AND location_info_300.source = loc...
I think you're basically checking if the row exists in the subquery? If so, then just do an `EXISTS`: ``` LEFT OUTER JOIN (aa.location) LOC ON (location_info_300.client_num = loc.client_num AND location_info_300.source = loc.source ...
Your first subquery should return exactly one row, but it returns more than one. This is because you perform an analytic function, which is essentially supposed to return a varied amount of rows. The only way to assert that only one row will be returned is using an aggregate function or using conditions that will assu...
Oracle issue with a left outer join subquery
[ "", "sql", "oracle", "subquery", "left-join", "ora-01427", "" ]
I have a requirement of getting an employee id from department id (lets consider that one department will only contain 1 employee at most) I can do something like below: ``` Select emp_id from emp where dept_id = 101; ``` Now in case this row was not existing, I won't be getting any value. However since I am using...
Try: ``` select nvl(min(emp_id),-1) from emp where dept_id = 101; ```
You can try this code block : `select case when e.emp_id is null then -1 else e.emp_id end as emp_id from emp e where e.dept_id = 101`
SQL query to return a particular column or a default value in case of row not existing in the db
[ "", "sql", "oracle", "" ]
SQLFiddle : <http://sqlfiddle.com/#!9/9d5b2> I have the following tables under MYSQL 5.6 : ``` users id | name --------- 1 | John groups id | name --------- 1 | admin constaints id | name ------------ 1 | cons1 2 | cons2 user_to_group userid | groupid ---------------- 1 | 1 constraint_to_group constra...
You can perform a comparison between `constraint_to_group.constraintid` and `constraints.id`. So, instead of: ``` `groups`.id as group_id, `groups`.name as group_name ``` use: ``` IF(`constraint_to_group`.constraintid = `constraints`.id, `groups`.id, NULL) as group_id, IF(`constraint_to_grou...
Think I would split it to 2 unioned queries. Without doing too much checking, something like this:- ``` SELECT users.id, users.name, constraints.id as cons_id, constraints.name as cons_name, groups.id as group_id, groups.name as group_name FROM users LEFT JOIN user_to_group ...
MySQL 5.6 : multiple left join leads to incorrectly filled column
[ "", "mysql", "sql", "" ]
I am trying to select a row count from another table even if it's empty, so if it's empty it just shows the number 0 but still selects the main table's rows. Here's my sql: ``` SELECT training.*, count(distinct training_transactions.training_transaction_course) as completed_training_payments FROM training ...
Use LEFT JOIN instead of inner join to list all records from the table on the left of the join, plus you need to place the count() in a subquery to get all fields from the training table: ``` SELECT training.*, ifnull(T.transactioncount,0) as transactioncount FROM training LEFT JOIN (SELECT training_transactio...
INNER JOIN only selects records where records with join key in both tables exist. With LEFT JOIN / RIGHT JOIN, selections can be made where records on one side don't exist; their field values will be NULL (and when counted, they should be zero but I'm not COMPLETELY sure of that)
Selecting count from another table is only showing 1 row where it exists
[ "", "mysql", "sql", "" ]
Normally, in SQL Developer, if one does, let's say, `INSERT` statement, then there is an output in `Script output`: ``` insert into a (a) values (1); 1 rows inserted. ``` If, then, we compile it into procedure: ``` create or replace procedure testp as begin insert into a (a) values (1); end; PROCEDURE TESTP comp...
If you just want "detailed output" that will be printed out for users running a procedure interactively in an IDE with appropriate settings enabled, you could ``` create or replace procedure testp as begin insert into a (a) values (1); dbms_output.put_line( sql%rowcount || ' row inserted. ' ); end; ``` Assuming t...
> There is no output about how many rows were inserted. How then, can we turn on detailed output in procedure? SQL and PL/SQL are not same. In PL/SQL, you could use **SQL%ROWCOUNT** to get the total number of rows affected by the **DML**. To get this in the output buffer, use **DBMS\_OUTPUT.PUT\_LINE**. For example,...
Getting output in PLSQL procedure
[ "", "sql", "oracle", "plsql", "oracle-sqldeveloper", "" ]
I have query like this ``` SELECT P9_IR259_FI, FX_IR259_SYS_PROD_TYP, FX_IR259_SLS_POS, FX_IR259_SLS_CHNL, PX_IR259_OFC_CDE, FX_IR259_SPR_OFC_CDE, FX_IR259_NAME, SUPERNAME, SUPERCDE, SUPERPOS FROM IR259 K LEFT OUTER JOIN (SELECT FX_IR259_NAME AS SUPERNAME ,FX_IR259_SLS_POS AS SUPERPOS, PX_IR259_OFC_CDE...
You need to add another filter to the where clause. ``` WHERE FX_IR259_SLS_POS = '1' AND FX_IR259_SLS_CHNL = 'BRO' AND F9_IR259_CRE_TMS > 00000000000000000 AND SUPERNAME LIKE 'ME%' ```
You only need to add another condition in the where clause ``` SELECT P9_IR259_FI, FX_IR259_SYS_PROD_TYP, FX_IR259_SLS_POS, FX_IR259_SLS_CHNL, PX_IR259_OFC_CDE, FX_IR259_SPR_OFC_CDE, FX_IR259_NAME, SUPERNAME, SUPERCDE, SUPERPOS FROM IR259 K LEFT OUTER JOIN (SELECT FX_IR259_NAME AS SUPERNAME ,FX_IR259_SL...
SQL Query Left Outer Join with specific record
[ "", "sql", "oracle", "" ]
T-SQL User SSMS 2008 I am running two (what are supposed to be) effectively *identical* queries that pull records from a table (say, Table A), using a WHERE statement to define the date parameters by which records will be returned. The issue is, is that the 2 queries are returning different counts. Could anyone help m...
If you're working with datetime data (as opposed to purely dates, with no time components), I'd recommend forgoing between and using an *exclusive* endpoint: ``` select A.* from A where A.Date >='20150901' and A.Date < '20151001' ``` Exclusive endpoints tend to be easier to compute *and* you don't have to worry about...
Try changing the first query like this. It could be due to `time` part in your `Date` column ``` select A.* from A where cast(A.Date as date) between '9/1/2015' and '9/30/2015' ```
2 of the "same" WHERE statements returning different count of records
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have two tables, `customers` and `purchases`. `Purchases` has a `total_price` column and foreign key `cid` referencing `customers.cid`. I need to select names of customers (came) who made the highest total\_price purchase. I'm trying this ``` select cname from customers c where exists (select pid ...
You could just sum up the totals for each customer and then order it by highest totals like so: ``` select cname, sum(total_price) as totals from customers c inner join purchases p on c.cid = p.cid group by cname order by totals desc limit 1 ``` Here's an example with MySQL database: <http://sqlfiddle.com/#!9/133fa...
You can also store the highest purchase for each customer in a temporaly table(In SQL Server, for instance): ``` SELECT c.cid, cname, max(total_price) as total into #temp_customers_highest_purchase FROM customers c JOIN purchases p on c.cid = p.cid group by c.cid, cname ``` After that you can select the customer with...
SQL query to find name with max price purchase made?
[ "", "sql", "oracle", "" ]
I'm trying to join 2 tables based on a value that is present in another table, specifically where a field is null. Depending on if that field is null, I'd like to execute a LEFT JOIN in a different way. Example: ``` LEFT JOIN (SELECT report_transaction_id, line_number, sale_staff_id, item_type, article_id,...
I don't think you can use CASE like that, you will have to do something like this: ``` LEFT JOIN (SELECT TOP 1 article_id, merchandise_category, long_desc, division_code, division_desc, group_code, group_desc FROM [CRM].[Products]) p ON ti.MERCHANDISE_CATEGORY = p.MERCHANDISE_CATEGORY WHERE ti.article_id IS NULL LEFT ...
A big part of the problem may be in your use of TOP 1 in this subquery: ``` (SELECT TOP 1 article_id, merchandise_category, long_desc, division_code, division_desc, group_code, group_desc FROM [CRM].[Products]) ``` As written, TOP 1 here mean, "Independent of everything else in this query, randomly pic...
Joining Same Table using Different Fields Based on Previous Values
[ "", "sql", "left-join", "" ]
I have two queries: ``` 'SELECT * FROM `table `WHERE weight = 0 OR weight IS NULL' ``` and ``` 'SELECT * FROM `table ` ``` The first query returns around 4000 values, the second query returns around 4100. I'm attempting to create a query that will return the rows which are distinct between the two values, I'm atte...
I think this does what you want: ``` SELECT * FROM `table` WHERE NOT (weight = 0 OR weight IS NULL); ``` That is more simply written as: ``` SELECT * FROM `table` WHERE weight <> 0; ```
use MINUS operator as below ``` SELECT * FROM `table` MINUS SELECT * FROM `table` WHERE weight = 0 OR weight IS NULL ```
Creating a mySQL sub query to list distinct rows from two queries
[ "", "mysql", "sql", "" ]
I'm trying to come up with a query that will list all the task\_groups where all task\_names in a group are performed by the 'AUTO' user except for the 'Initial' task which will be manual. So for the below data I should only see Task\_Group '1' in the result and not Task\_Group '2' ``` CREATE TABLE [dbo].[QUERY_TST]( ...
This should get you what you're after: ``` SELECT DISTINCT task_group FROM query_tst As a WHERE ( (NOT EXISTS ( SELECT NULL FROM query_tst As b WHERE ( (a.task_group = b.task_group) And (b.task_name <> 'Initial') And (b.performed_by <> 'AUTO') ...
* All task less one is performed by `AUTO` * The Initial task is perfomen by `MANUAL` . ``` select [TASK_GROUP] from [dbo].[QUERY_TST] GROUP BY [TASK_GROUP] HAVING SUM(CASE WHEN [PERFORMED_BY] = 'AUTO' AND [TASK_NAME] <> 'Initial' THEN 1 ELSE 0 END) = COUNT(*)-1 AND SUM(CASE WHEN [PERFORMED_BY] = 'MANU...
SQL query for fetching a value where all but one row matches
[ "", "sql", "sql-server", "" ]
So I'm wondering which one is best performance wise and also if using an AND is simply bad practice here. Compare the two following queries ends : Using a "WHERE" at the end : ``` select c.cust_last_name, o.order_total, oi.quantity from customers c join orders o on (c.customer_id = o.customer...
In this instance, I doubt it would make much difference to Oracle which version of the query you used. You could check by looking at the explain plan for each query. However, it is only "safe" to move the `c.gender = 'M'` predicate into the join condition here because you're doing an inner join. If you were doing an o...
It makes no difference whether to put the condition in the WHERE clause or an ON clause. But yes, what you show *is* bad practise, because `and c.GENDER='M'` has nothing to do with which records to join from table `order_items`. The criteria in an ON clause should always belong with its table. An example with additio...
Using an sql join's "ON" statement with an "AND" instead of a "WHERE"
[ "", "sql", "oracle", "join", "" ]
I have three different models with association **user.rb** ``` has_many :products has_many :comments ``` **comment.rb** ``` belongs_to :user belongs_to :product ``` **Product.rb** ``` has_many :comments belongs_to :user def product_comments_object comments_object = self.comments.all.select(:id,:user_id,:comme...
you need to parse comment objects to get user name . parse each comment object and call `parse_comment` method which return a hash with user name. ``` def product_comments_object comments_object = [] self.comments.each do |comment| comments_object << parse_comment(comment) end {comments: comments_object} ...
Try this: ``` def product_comments_object comments_object = self.comments.all.joins('users') .where('users.id = comments.user_id') .select('comments.id, users.name AS user_name, comments.comment') { comments: comments_object } end ```
How to map user name to each comment
[ "", "sql", "ruby-on-rails", "model", "associations", "" ]
my connection string is saved in a string variable names str what i am trying to do is use an input from the user as part of the string the parts i want to take from the user are the ID and PASS i am simply trying to check the connection statues with the ID and the PASS as inputs from the user. ``` Dim str As String =...
So, you need to check if the user is allowed to log into the database or not. The way you have followed looks good, you define the connection string based on the given ID and password, and you try to establish a connection, if it fails, the user can't log in, else he can do that. However, the way you defined the strin...
The [SqlConnectionStringBuilder](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder%28v=vs.110%29.aspx) is an appropriate class to use in this case. You can add parts of the connection string to it via properties, so there is no chance of making mistakes: ``` Imports System.Data....
i am trying to use an input from the user as part of a connection string to a SQL database
[ "", "sql", "vb.net", "string", "" ]
I'm trying to migrate some data from an old Access database to a new one, some columns changed, for example the old "adress" used to be divided into street, number, city and postal code is now only one column. So I need to union all the columns into only one before update the new database. I get no error and no warning...
What you are trying to do can be accomplished concatenating columns in a SELECT statement like this: ``` SELECT Street & ' ' & Number & ' ' & PostalCode & ' ' & City & ' ' & State FROM Data WHERE Cod=@cod1 ``` *This SELECT works under the assumption that all columns are alphanumeric, if some of they are numeric, you...
I suspect you need just this (`||` is the SQL string concatenation operator): ``` //Union all the values Dim findAllAdress As New OleDb.OleDbCommand("SELECT Street || Number || City || State || postalCode FROM Data" & _ " WHERE Cod=@cod1", cnCompraAntigo) findAllAdress.Parameter...
UNION ALL only returns the fist column
[ "", "sql", "vb.net", "ms-access", "" ]
I want to use a variable to determine conditional GROUP BY in my SQL statement like so: ``` group by case when (@GroupByFirst is not null) then a.Name else b.Name end ``` Unfortunately I get an error that a.Name is ``` invalid in the select list because it is not contained in either an aggregate function or the GROU...
Your query should look like: ``` select (case when (@GroupByFirst is not null) then a.Name else b.Name end) as name from . . . group by (case when (@GroupByFirst is not null) then a.Name else b.Name end) ``` You cannot refer to either `a.Name` nor `b.Name` in the `SELECT` (without an aggregation function, that is). Y...
declare @GroupByFirst varchar(30)='s' select max(someval) from Login\_Master group by case when @GroupByFirst is not null then a.Name else b.Name end
Conditional GROUP BY with custom variable
[ "", "sql", "t-sql", "group-by", "" ]
Allow me to preface this by saying that I am fairly new to sql, and I'm sure there is an easy way to do this that I'm not understanding. Lets say we have a table: ``` X | Y 2 | 2 3 | 1 3 | 3 3 | 2 ``` I am trying to find values of y such that x contains both 2 and 3. Basically, y = 2 is the only value that satisfie...
You could probably try this: ``` select y from test where x in (2,3) group by y having count(*) = 2; ``` EDIT: Notice a good recommendation by Juan. In case your data contains X=2 and Y=2, a better way of writing the query would be this: ``` select y from test where x in (2,3) group by y having count(distinct ...
using a conditional `SUM`. If any group of `Y` contain `2` sum will be greater than 0, same with `3` ``` SELECT Y FROM YourTable GROUP BY Y HAVING SUM(CASE WHEN X = 2 THEN 1 ELSE 0 END) > 0 and SUM(CASE WHEN X = 3 THEN 1 ELSE 0 END) > 0 ```
Selecting certain values that contain every number but not only one
[ "", "sql", "oracle", "" ]
I've written a query to delete all rows from a table and then bulk insert from a txt. If there is a problem with the bulk insert I don't want to loose my old data so I want to rollback the transaction. This is what I've been trying: ``` BEGIN TRANSACTION DELETE Users_Login BULK INSERT Users_Login FROM '\\STRMV1234\ -...
I would give this a try. ``` BEGIN TRANSACTION DELETE FROM Users_Login BULK INSERT Users_Login FROM '\\STRMV1234\ - Some_Table.txt' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', FIRSTROW = 2, CODEPAGE = 'ACP') IF @@ERROR = 0 BEGIN COMMIT PRINT 'GOOD' END ELSE BEGIN ROLLBACK PRINT 'BAD' END ```
This works fine: ``` Begin Try Begin Tran Truncate Table data BULK INSERT data FROM '...\data.txt' WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 1, CODEPAGE = 'ACP') if @@TRANCOUNT > 0 Commit print 'ok' End Try Begin Catch print 'error' if @@TRANCOUNT > 0 Rollback End Cat...
SQL how to rollback transaction if bulk insert fails
[ "", "sql", "sql-server", "" ]
I have a table `Employee`. [![enter image description here](https://i.stack.imgur.com/Y9kmN.jpg)](https://i.stack.imgur.com/Y9kmN.jpg) How to get the table with aggregate of a column as separate column as shown in the image? [![enter image description here](https://i.stack.imgur.com/IplNs.jpg)](https://i.stack.imgur...
The exact problem I faced last year. Hope this help. ``` SELECT e1.EmpId, e1.EmpName e1.EmpSalary, SUM(e2.EmpSalary) AS Aggregate_Salary FROM Employee e1 JOIN Employee e2 ON e1.id >= e2.id GROUP BY e1.EmpId, e1.EmpName, e1.EmpSalary ```
Using a correlated sub-query: ``` select EmpId, EmpName, EmpSalary, (select sum(EmpSalary) from Employee e2 where e2.EmpId <= e1.EmpId) as AggregateSalary from Employee e1 ```
How to write a single SQL query to get aggregate of column as other column in SQL Server 2008?
[ "", "sql", "sql-server", "sql-server-2008", "cumulative-sum", "" ]
I'm currently trying to find all the entries with the same IDs in two sub queries and display the first table. I am having an issue with using aliases. ``` (SELECT * FROM personTable WHERE ID IN ( SELECT ID FROM workerTable ) AND firstName LIKE 'O%'); (SELECT * FROM ownsTable WHERE ...
Use `Exists` to do this ``` SELECT * FROM persontable p WHERE id IN (SELECT id FROM workertable) AND firstname LIKE 'O%' AND EXISTS (SELECT 1 FROM ownstable o WHERE phonenumberid IN (SELECT id ...
It sounds like you can just do a simple join for this: ``` SELECT p.* FROM personTable p JOIN ownsTable o ON o.id = p.id AND p.firstName LIKE 'O%' AND o.home <> '' AND o.work <> '' AND o.cell <> ''; ``` This will select all columns from the first table as long as the id exists in the second table, and the matching ro...
SQL Multiple Sub-query
[ "", "mysql", "sql", "" ]
I have **table A** that is linked to **table B**, which in turn is linked to **table C**. I can only get from A to C through a key in B. I must get all rows from A where ALL linked rows from C have C.value = 'Y' I tried the following code but it already selects the row from A once a match has been found in one of th...
This query returns all the rows from A where all the linked rows from C have C.value 'Y' or where there is no link to B or to C available. Regards to JB King for the suggestion. ``` SELECT * FROM A WHERE A.ID1 NOT IN ( SELECT DISTINCT A.ID1 FROM A JOIN B ON A.ID1=B.ID1 JOIN C ON B.ID2=C.ID2 WHERE C.value = '...
I think I understand the problem now.. try this. Might be a better way but this should work. ``` SELECT * FROM A LEFT JOIN B ON A.ID1 = B.ID1 LEFT JOIN C ON B.ID2 = C.ID2 WHERE C.ID2 in (SELECT ID2 FROM C WHERE VALUE = 'N') AND C.ID2 not in (SELECT ID2 FROM C WHERE VALUE <> 'N') ```
SQL Select rows from table where all joined rows match value
[ "", "sql", "join", "" ]
My Tables look like this ``` Table 1 Table 2 Users Options id name id user_id option ------- --- -------- -------- 1 Donald 1 1 access1 2 John 2 1 access2 3 Bruce 3 1 ...
You can do this using a EXISTS subquery (technically, a left semijoin): ``` SELECT id, name FROM table1 WHERE EXISTS( SELECT * FROM table2 WHERE table1.id = table2.user_id AND table2.option = 'access1' ) ``` If you want only users that have access1 and not any other access, add NOT EXISTS (a lef...
[`bool_and`](http://www.postgresql.org/docs/current/static/functions-aggregate.html) makes it simple ``` with users (id,name) as ( values (1,'donald'), (2,'john'), (3,'bruce'), (4,'paul'), (5,'ronald'), (6,'steve') ), options (id,user_id,option) as ( values (1,1,'access1'), (2,1,'access...
select distinct from join
[ "", "sql", "postgresql", "" ]
I have two tables ``` Table1 (Users) ID, NAME, COUNTRY 1, Joe Bloggs, 1 2, Joe Jnr, 1 3, Joe Snr, 2 Table2 (Orders) UsersID, Product 1, Apple TV 1, iPad Pro 1, MacBook Pro 2, iPad Mini 2, iPad Pro 3, iPad Air 3, iPad Pro ``` If i wanted a l...
Writing in classic SQL you have a layered sub-select. Code that should work: ``` Select Product from Orders Where Product <> 'MacBook Pro' -- you don't want MacBook Pro in results and UsersID in (Select ID from Users where country = '1' --get all Country 1 users that Purchased MacBooks and ID in (Select B.Us...
The quick answer for that is simple. First, select the users who bought a MacBook Pro and who are living in that country: ``` SELECT T_USERS.id FROM Users T_USERS INNER JOIN Orders T_ORDERS ON (T_USERS.id = T_ORDERS.UsersID) WHERE T_USERS.Country = 1 AND T_ORDERS.product = 'MacBook Pro' ``` And, then, use it in a...
SQL One to Many Condition Issue
[ "", "sql", "one-to-many", "" ]
Suppose I have a table with columns ID and Content populated with data. ``` ID | Content 1 | a 1 | b 1 | c 2 | b 2 | a 3 | b ``` I want to find every ID that has at least one of each 'a', 'b', and 'c' so the returned table would be : ``` ID | Content 1 | a 1 | b 1 | c ```
Using conditional `SUM` validate if inside the `group id` exist 1 or more of each element. Then select `DISTINCT ID, Content` to eliminate possible duplicates ``` SELECT DISTINCT ID, Content From YourTable WHERE ID IN (SELECT ID FROM YourTable GROUP BY ID HAVING SUM(case when Co...
``` select * from ( where Select ID ,SUM(case when Content = 'a' then 1 else 0 end) as sum_a ,UM(case when Content = 'b' then 1 else 0 end) as sum_b, SUM(case when Content = 'c' then 1 else 0 end) as sum_c FROM table Group by ID)x where x.sum_a >1 or sum_b>1 or sum_c>1 ```
SQL Counting rows with columns that satisfy a condition
[ "", "mysql", "sql", "" ]
I am including a SQLFiddle to show as an example of where I am currently at. In the example image you can see that simply grouping you get up to two lines per user depending on their status and how many of those statuses they have. [![enter image description here](https://i.stack.imgur.com/vWGS0.png)](https://i.stack....
Use conditional aggregation: ``` select PersonID, Name, sum(case when Status = 'Fail' then 1 else 0 end) as FailedTotal, sum(case when Status = 'Pass' then 1 else 0 end) as PassedTotal from UserReport group by PersonID, Name; ```
Use conditional aggregation if the number of values for `status` column is fixed. [Fiddle](http://sqlfiddle.com/#!3/9aa649/19) ``` select PersonID,Name, sum(case when "status" = 'Fail' then 1 else 0 end) as failedtotal, sum(case when "status" = 'Pass' then 1 else 0 end) as passedtotals from UserReport group by Pers...
SQL Multiple Rows to Single Row Multiple Columns
[ "", "sql", "join", "" ]
Sorry didn't know what title to give to this question as it might get confusing. My table has only two columns - userName1 and userName2 I have this: ``` SELECT * FROM `Friends` WHERE `userName1` = 'aName' UNION SELECT * FROM `Friends` WHERE `userName2` = 'aName' ``` The result of this sql statements brings me the r...
You can use: ``` select userName2 from friends where userName1 = 'aName' union select userName1 from friends where userName2 = 'aName'; ``` A method without `union`: ``` select distinct (case when userName1 = 'aName' then userName2 else userName1 end) from friends where 'aName' in (userName1, userName2); ```
I would try something like this : ``` SELECT userName2 as 'name' FROM Friends WHERE userName1 = 'aName' UNION SELECT userName1 as 'name' FROM Friends WHERE userName2 = 'aName' ``` You might also require that they can't be both equal to 'aName' ``` SELECT userName2 as 'name' FROM Friends WHERE userName1 = 'aName' and...
simple mysql statement that I can not find
[ "", "mysql", "sql", "union", "" ]
Every month I get sent a file from a external company which needs to be stored in a database, each file containing up to a million records. The main data fields are Month, Year, Postcode and TransactionType. I was proposing that we should save the data in our database as a new SQL table each month so we know there is ...
All "like" items should be stored together in a database for the following reasons: * You should be able to provide any subset of the items using a single `SELECT` statement only by changing the `WHERE` clause of that statement. With separate tables you will have to write code to decompose the request into the parts t...
A simpler method would be to add a column to that table which contains a datetimestamp of when that was loaded into the system. That way you can filter by that perticular column to segregate that data into the months/years that it was loaded in. Another advantage from a performance perspective, that if you regularly f...
Creating sql tables by month and year
[ "", "mysql", "sql", "t-sql", "bigdata", "" ]
Is it possible to add numbered bullets using Oracle's LISTAGG function? i.e.: I have a table: ``` PRODUCT_ID PRODUCT_NAME 1001 Bananas 1002 Apples 1003 Pears 1004 Oranges ``` SQL statement: ``` SELECT LISTAGG('*' || product_name, CHR(13)) WITHIN GROUP (ORDER BY product_name) ...
The `Product_Listing_1` gives you number bullets, the `Product_Listing_2` gives you letter bullets. ``` with products as ( select 1001 as product_id, 'Bananas' as product_name from dual union all select 1002 as product_id, 'Apples' as product_name from dual union all select 1003 as product_id, 'Pea...
You can use row\_number() in subquery to generate number ``` with products as ( select 1001 as product_id, 'Bananas' as product_name from dual union all select 1002 as product_id, 'Apples' as product_name from dual union all select 1003 as product_id, 'Pears' as product_name from dual union all select 1004 as produ...
Add numbered bullets using Oracle LISTAGG function
[ "", "sql", "oracle", "listagg", "" ]
``` SELECT TOP 1000 [pk_Id] ,[fk_resumeID] ,[fk_LoginID] ,[fk_CompanyId] ,Convert(nvarchar(11),ViewDate,105) FROM [RecruitingDB].[Recruiting].[tbl_ViewResumeStatus] where Convert(nvarchar(10),ViewDate,106) between Convert(nvarchar(10),'17-10-2015',106) and Convert(nvarchar...
You are comparing the alphabetic values. You should avoid that, when dealing with numeric or date values. Example `17-10-2015` would unintentionally be between `16-01-2015` and `18-01-2015` Use this instead: ``` SELECT TOP 1000 [pk_Id] ,[fk_resumeID] ,[fk_LoginID] ,[fk_CompanyId] ,Convert(cha...
Well it will do if you convert your dates to strings. Your query is looking for anything alphabetically between'17-10-2015' and '23-10-2015'. So for example that would include '18-09-2015'.
Getting wrong month
[ "", "sql", "sql-server", "" ]
I have the below code that is not working as expected: ``` DECLARE @MySelect varchar(max), @MyRecipients varchar(max), @MyId char(4),@MyResult varchar(max); SET @MyId = '1'; SET @MySelect = 'SELECT SQL_Script FROM AutoSendMail.dbo.A01_St WHERE ID =' + @MyId; USE msdb EXEC sp_send_dbmail @profile_name='Operator'...
You can do this without dynamic SQL, like so: ``` DECLARE @MyRecipients VARCHAR(MAX) , @MyId CHAR(4) = '1' , @MyResult VARCHAR(MAX); SET @MyId = '1'; SELECT TOP 1 @MyResult = SQL_Script FROM AutoSendMail.dbo.A01_St WHERE ID = @MyId USE msdb EXEC sp_send_dbmail @profile_name = 'Operator', @rec...
You can declare table variable, insert into it the results of executing your query and then select into your result variable: ``` DECLARE @t TABLE(SQL_Script varchar(max)) INSERT INTO @t EXEC(@MySelect) SELECT TOP 1 @MyResult = SQL_Script FROM @t ``` You can also use `sp_executesql` procedure with output parameters l...
Saving the result of a SQL query into a local SQL variable
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have 3 tables in sqlserver : ``` tbl_Users - User_ID, User_Name tbl_Roles - Role_ID, Role_Name tbl_Users_Roles_MTM - User_ID, Role_ID ``` A user can have multiple roles assigned to him, and that will show in the Many-To-Many table. In my stored-procedure I need `Role_Name` which are *...
Try this query: ``` SELECT r.Role_Name FROM tbl_Roles r WHERE NOT EXISTS ( SELECT 1 FROM tbl_Users_Roles_MTM ur WHERE ur.User_ID = @User_ID AND ur.Role_ID = r.Role_ID); ```
You can do this: ``` SELECT * FROM Roles WHERE Role_Name = @rolename AND NOT EXISTS(SELECT 1 FROM tbl_Roles AS r INNER JOIN tbl_Users_Roles_MTM AS ur ON ur.Role_ID = r.Role_ID WHERE r.role_Name = @rolename AND ur.User_ID = @User_ID); ``` The `N...
sql join Many-To-Many - 3 tables
[ "", "sql", "sql-server", "join", "many-to-many", "" ]
yeah sorry for the piss poor title. I created an example DB with sqlfiddle but I am so lost on this one I can't even start with the query. <http://sqlfiddle.com/#!3/940b7d> in the example DB I need all Account numbers that have equipment and can have equipment "CRAPY" but only if it has any other type of equipment as...
If we remove the 'CRAPY' records, any accounts left are ones you need to report (have equipment other than 'CRAPY') ``` select distinct account from testdb where Equipment not like 'CRAPY' ``` If you need to see what equipment they have, or need to doa quick sanity check: ``` select account, Equipment from testdb ...
I think you're suffering from a poor problem statement. A clearer statement is *Return any account number which has non-"CRAPY" equipment*. The existence of "CRAPY" equipment is largely irrelevant. You can do this with: ``` SELECT DISTINCT Account FROM testdb WHERE Equipment <> 'CRAPY' ``` which will ignore "CRAPY" ...
SQL Select Where does not include X only
[ "", "sql", "t-sql", "" ]
I have the following SQL query: ``` SELECT users.user_id, users.first_name, users.last_name, roles.role, roles.role_id, users.username, users.description, users_vs_teams.team_id, teams.team_name, teams.status FROM users INNER JOIN roles ON users.role_...
``` SELECT users.user_id, users.first_name, users.last_name, roles.role, roles.role_id, users.username, users.description FROM users INNER JOIN roles ON users.role_id = roles.role_id LEFT JOIN users_vs_teams ON users.user_id = users_vs_teams.us...
``` SELECT users.user_id, users.first_name, users.last_name, roles.role, roles.role_id, users.username, users.description, users_vs_teams.team_id, teams.team_name, teams.status FROM users INNER JOIN roles ON users.role_id = roles.role_id INNER JOIN users_vs_teams ON users.user_id <> users_vs_teams.user_i...
Select Command Where Users id does not appear in another table
[ "", "sql", "" ]
During execution of below query, the output is **2090**. ``` select to_char(to_date('10-OCT-90', 'DD-MON-YY'), 'YYYY') from dual; ``` Required output is **1990**, the date in the snippet is Birth Date. **EDIT:** The input date is fetched from a table, so the date is in DD-MON-YY format.
For alternative resolving the double-digit years in strings, Oracle has [the `RR` format element](http://docs.oracle.com/database/121/SQLRF/sql_elements004.htm#i116004). Thus, your query would be ``` select to_char(to_date('10-OCT-90', 'DD-MON-RR'), 'YYYY') from dual; ``` From the referenced Oracle doc: > The RR dat...
Use RR instead of YY. See here: <https://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#SQLRF00215>
Oracle date conversion outputs 2000s instead of required 1990s
[ "", "sql", "oracle", "date", "" ]
I'm using SQL Server 2012. I have two tables and I'm trying to see how many rows both tables contain. They have no common field on which they can join. Below is my query so far, which obviously doesn't work. How should it be? ``` ;with tblOne as ( select count(*) numRows from tblOne where DateEx = '2015-10-27' ),...
You don't need CTEs; you can just change them to subqueries: ``` select (select count(*) numRows from tblOne where DateEx = '2015-10-27') + (select count(*) numRows from tblTwo where Status = 0) ``` If you REALLY want to use CTEs then just do an implicit CROSS JOIN: ``` with tblOne as ( select count(...
You can use a `cross join`: ``` with tblOne as ( select count(*) as numRows from tblOne where DateEx = '2015-10-27' ), tblTwo as ( select count(*) as numRows from tblTwo where Status = 0 ) select tblOne.numRows + tblTwo.numRows from tblOne cross join tblTwo; ```
adding the sum of two select count queries
[ "", "sql", "sql-server", "" ]
I have a query that's something like this ``` select days, date(date_event) + interval '10' day from tbl_user_marketing_program as programtable ``` Now in place of the '10', I want to add the value present in the "days" column. How can I do that? I tried `select user_id, date(date_event) + interval user_id day from...
Unfortunately the "number" for an interval can't be an arbitrary expression, it has to be a string constant (which is a strange choice). You need to use a little workaround: ``` select days, date(date_event) + (days * interval '1' day) from tbl_user_marketing_program as programtable ``` But `date + integer` is also ...
You can quote `'10 days'`: ``` select days, date(date_event) + interval '10 days' from tbl_user_marketing_program as programtable ``` `SqlFiddleDemo` If you want add variable/column use: > **datetime + variable \* INTERVAL '1 day'** ``` select days, date(date_event) + column * interval '1 day' from tbl_user_mark...
Create interval using a column value postgresql
[ "", "sql", "postgresql", "" ]
I have two tables. Both of them contain (dutch) postalcodes. Those have the format 9999AA and are stored as varchar(6). In the left table the codes are complete ``` John Smith 1234AB Drew BarryMore 3456HR Ted Bundy 3456TX Henrov 8995RE My mother 8995XX ``` In the right table the c...
If you have no "duplicates" in the second table, you could use `like`: ``` SELECT t1.*, t2.col2 FROM table1 AS t1 JOIN table2 AS t2 ON t1.postalcode LIKE t2.postalcode + '%'; ``` However, this is not going to be efficient. Instead, an index on `table2(postalcode)` and a series of `LEFT JOIN`s is probably faster: ```...
Use `JOIN`. **Query** ``` SELECT t1.col1 as name, coalesce(t2.col2,'-unknown-') as col2 FROM table_1 t1 LEFT JOIN table_2 t2 ON t1.pcode LIKE t2.col1 + '%'; ``` [**SQL Fiddle**](http://sqlfiddle.com/#!3/9e93d/1)
compare strings of uneven length in TSQL
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "string-comparison", "" ]
sorry for the title but is a little difficult to explain the topic in a sigle row.. I have a table like this and i want to know (for each month in the year) the number of employee who have received bonus for the first time. ``` EMPLOYEE_NAME MONTH BONUS_RECEIVED AAA 1 1 BBB ...
You could use **ROW\_NUMBER()** analytic function. For example, **Setup** ``` CREATE TABLE t (EMPLOYEE_NAME varchar2(3), MONTH number, BONUS_RECEIVED number); INSERT ALL INTO t (EMPLOYEE_NAME, MONTH, BONUS_RECEIVED) VALUES ('AAA', 1, 1) INTO t (EMPLOYEE_NAME, MONTH, BONUS_RECEIVED) VA...
A double aggregation solves your problem: ``` select month, count(1) as total_bonus from ( select employee_name, min(month) as month from table_like_this where bonus_received = 1 group by employee_name ) group by month; ``` First, for each employee you find the first month he/she received a bonus. The...
Oracle SQL - Sum of distinct value belong year, for the first time
[ "", "sql", "oracle", "" ]
I have 2 tables: 1 with tasks, 1 with task\_actions. I'd like to have the task table with some info about the task\_actions column. That works fine when I use a LEFT JOIN like this: ``` SELECT *, wp_task_mgr.id AS task_id, wp_task_actions.id AS action_id, wp_task_actions.completion_percentage AS lastcom...
To solve that, MS SQL 2005+ use OUTER APPLY, but I don't sure MySQL can use it: ``` SELECT wp_task_mgr.*, wp_task_mgr.id AS task_id, A.id AS action_id, A.lastcompperc FROM wp_task_mgr OUTER APPLY ( SELECT DISTINCT id, id_task, (SELECT MAX(created_taskaction) AS lastcompperc ...
Have you tried quite literally combining your queries? LEFT JOIN your Max Date list to the wp\_task\_mgr and then LEFT JOIN on the Max Date list to subset the details to only ones that match the Max Date query result? eg: ``` SELECT wp_task_mgr.id AS task_id, wp_task_actions.id AS action_id, wp_task_acti...
How to JOIN two tables based on a WHERE that uses a complex statement in SQL
[ "", "mysql", "sql", "join", "left-join", "" ]
I have this query: ``` SELECT Count(*) AS GesamtanzahlMitarbeiter, (SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%80') AS "1980", (SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%81') AS "1981", (SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%82') AS "1982", (SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%83') AS ...
Use a conditional aggregation, add `case` in the `SUM` ``` SELECT COUNT(*) as GesamtanzahlMitarbeiter, SUM(CASE WHEN HIREDATE LIKE '%80'THEN 1 ELSE 0) as "1980", SUM(CASE WHEN HIREDATE LIKE '%81'THEN 1 ELSE 0) as "1981", SUM(CASE WHEN HIREDATE LIKE '%82'THEN 1 ELSE 0) as "1982", SUM(CASE WHEN HIRE...
You can use `count` without `group by` like this: ``` SELECT (SELECT Count(*) FROM EMP) AS GesamtanzahlMitarbeiter, (SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%80') AS "1980", (SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%81') AS "1981", (SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%82') AS "1982", (SELECT...
SQL one row output with count()
[ "", "sql", "oracle", "" ]
I have searched far and wide, but I can't seem find a way to convert julian to `yyyy-mm-dd`. Here is the format of my julian: The Julian format consists of the year, the first two digits, and the day within the year, the last three digits. For example, `95076` is `March 17, 1995`. The `95` indicates the year and the...
You can select each part of the date using `datepart()` ``` SELECT DATEPART(yy, 95076), DATEPART(dy, 95076) ``` +++EDIT: I misunderstood something. Here's my correction: +++++ ``` SELECT DATEADD(day, CAST(RIGHT('95076',3) AS int) – 1, CONVERT(datetime,LEFT('95076',2) + '0101', 112)) ```
**Edit: leaving this answer for Oracle and MySQL users** This will not work in T-SQL. Use this: ``` MAKEDATE(1900 + d / 1000, d % 1000) ``` For example: ``` SELECT MAKEDATE(1900 + 95076 / 1000, 95076 % 1000) ``` This returns `March, 17 1995 00:00:00`. [SQLFiddle](http://sqlfiddle.com/#!9/9eecb7d/29294)
Convert Julian Date to YYYY-MM-DD
[ "", "sql", "sql-server", "julian-date", "" ]
I am working with SQL Server 2008 R2. I have a table `seq_audit` which has an identity column. This is the definition of the table: ``` CREATE TABLE [dbo].[seq_audit] ( [id] [bigint] IDENTITY(1,1) NOT NULL, [value] [bit] NULL, PRIMARY KEY CLUSTERED ([id] ASC) WITH (PAD_INDEX = OFF, STATISTICS_...
This is caused by the fact that your table is empty. Try adding a single record and then everything will work. I have tried this and can confirm that it works. Also, if you use SQL Server Management studio you can use the design feature to change the seed values. and manually add and delete records.
<https://msdn.microsoft.com/es-es/library/ms176057(v=sql.120).aspx> ``` DBCC CHECKIDENT ( table_name, RESEED, new_reseed_value ) ``` > Current identity value is set to the new\_reseed\_value. If no rows have been inserted into the table since the table was created, or if all rows have been removed by using the TRUNCA...
Why setting current identity value is not working for me in SQL Server 2008 R2?
[ "", "sql", "sql-server", "sql-server-2008-r2", "identity", "" ]
I have two tables: followers: ``` followee_id | followers_id --------------|-------------- 1 | 2 1 | 3 2 | 3 3 | 1 ``` and users: ``` | user_id | user_name | etc... |---------|-----------|------- | 1 | user1 | | 2 | user2 | | ...
**[SqlFiddleDemo](http://sqlfiddle.com/#!9/18cc8/9)** Please double check, my main lenguaje isn't english so not sure who follow who. ``` SELECT T.*, if(f_to.followee_id is null, 'no', 'yes') is_followby_userid, if(f_him.followee_id is null, 'no', 'yes') is_following_userid FROM ( ...
Depending on the data: ``` (1,2), (1,3), (2,3), (3,1); ``` Results are: ``` User_id = 1 has 1 follower User_id = 2 has 1 follower User_id = 3 has 1 follower User_id = 1 follows 1 user (user_id = 3) User_id = 2 follows 1 user (user_id = 1) User_id = 3 follows 2 users (user_id = 1, user_id = 2) SELECT bb.user_id, bb...
MySQL Followers Query using Joins
[ "", "mysql", "sql", "join", "" ]
I have a Deaths table where each personID display that died. There is also a column for reason of death and a date for when he/she died. I need to count all the people that died by Illness, Accident, Suicide, etc. I want my output to be like this: `| Illness | Accident | Suicide | | 32 | 55 | 3 |` I can easily crea...
Simply use multiple subqueries: ``` CREATE VIEW viewDeaths AS SELECT Illness = (SELECT COUNT(*) FROM dbo.Deaths d WHERE d.Reason = 'Illness'), Accident = (SELECT COUNT(*) FROM dbo.Deaths d WHERE d.Reason = 'Accident'), Suicide = (SELECT COUNT(*) FRO...
In this way: ``` CREATE VIEW viewDeaths AS SELECT Reason, COUNT(personID) AS Illness -- WHERE Reason IN (.....) GROUP BY Reason ```
Count in a VIEW
[ "", "sql", "sql-server", "" ]
I have a select statement as follows: ``` SELECT firstName, lastName, CASE WHEN primaryEmail <> 'name@example.com' THEN primaryEmail WHEN secondaryEmail <> 'name@example.com' THEN secondaryEmail ELSE ternaryEmail END AS email FROM participant WHERE primaryEmail <> 'name...
``` SELECT firstName, lastName, CASE WHEN primaryEmail <> 'name@example.com' THEN primaryEmail WHEN secondaryEmail <> 'name@example.com' THEN secondaryEmail ELSE ternaryEmail END AS email FROM participant WHERE (primaryEmail <> ...
You need `or` logic, not `and` ``` where (firstName is not null or lastName is not null) and other conditions ```
Remove Empty Fields in Select Statement
[ "", "sql", "select", "where-clause", "" ]
I've got an error with a simple query using a join. My query : ``` SELECT users_sessions.user_id AS users_sessions_user_id, users.last_name AS users_last_name, users.first_name AS users_first_name FROM prefix_users_sessions AS users_sessions, prefix_users AS users INNER JOIN users_sessions ...
Your `from` clause is all messed up. A simple rule: *Never* use commas in the `FROM` clause. *Always* use explicit `JOIN` syntax. Also, use shorter table aliases so your query is easier to write and to read: ``` SELECT us.user_id AS users_sessions_user_id, u.last_name AS users_last_name, u.first_name AS...
You use name `users_sessions` twice. First as the alias of `prefix_users_sessions` and then as a normal table in the `INNER JOIN`. Also try to use `INNER JOIN`s and not selecting from two tables simultaneously e.g (in your query).: ``` FROM prefix_users_sessions AS users_sessions, prefix_users AS users ```
SQLSTATE Error Syntax error or access violation: 1066 Not unique table/alias: 'users_sessions'
[ "", "mysql", "sql", "select", "join", "mysql-error-1066", "" ]
I've got this table ## beds id name size room status hotel created\_at updated\_at I need to filter all beds that belong to a certain room. In order to do so, I've coded this lines. ``` public function index() { // $user = JWTAuth::parseToken()->authenticate(); $data = Input::get(...
Try this and see if it works. If not, can you provide the `var_dump` of `Input::get('room')` and the structure of the the beds table? ``` public function index() { // $user = JWTAuth::parseToken()->authenticate(); $data = Input::get('room'); if( $data ){ $beds = Bed::where('room', '=', $data );...
You have quite a few issues in your attempts: ``` return $bed->get( array('size', 'room', 'id') ); // runs SELECT size, room, id from `rooms` ``` so it returns all the rooms (why on earth would you like to do this in a foreach anyway?) --- ``` return $this->hasMany('Bed', 'id', 'room'); // should be: return $this->...
Laravel where query not working
[ "", "sql", "laravel", "eloquent", "" ]
I have two tables, lets say `table1` and `table2`. ``` table1 || table2 --------||------------- col1 || col1 | col2 --------||------|------ a || a | 4 b || a | 2 c || a | 5 d || b | 1 || b | 3 || d | 6 ``` With `SELECT table1.col1, table2.col2...
Alternative solution, use a correlated sub-query: ``` select col1, (select min(col2) from table2 t2 where t2.col1 = t1.col1) from table1 t1 ```
You need to use `MIN`: ``` SELECT t1.col1, MIN(t2.col2) AS col2 FROM table1 t1 LEFT JOIN table2 t2 ON t2.col1 = t1.col1 GROUP BY t1.col1 ``` [**SQL Fiddle**](http://sqlfiddle.com/#!6/9eecb7d/2545/0)
SQL left outer join to a min value of right table
[ "", "sql", "sql-server", "join", "" ]
Consider this example table "Table1". ``` Col1 Col2 A 1 B 1 A 4 A 5 A 3 A 2 D 1 B 2 C 3 B 4 ``` I am trying to fetch those values from Col1 which corresponds to all values (in this case, 1,2,3,4,5). Here the result of the query should return 'A' as none of...
You could use analytic **ROW\_NUMBER()** function. **[SQL FIddle](http://sqlfiddle.com/#!4/91c29/1)** for a setup and working demonstration. ``` SELECT col1 FROM (SELECT col1, col2, row_number() OVER(PARTITION BY col1 ORDER BY col2) rn FROM your_table WHERE col2 IN (1,2,3,4,5) ) WHERE rn =5; ``` --- ...
You can use listagg function, like ``` SELECT Col1 FROM (select Col1,listagg(Col2,',') within group (order by Col2) Col2List from Table1 group by Col1) WHERE Col2List = '1,2,3,4,5' ```
select query to fetch rows corresponding to all values in a column
[ "", "sql", "oracle", "" ]
I'm not a database guru and feel like I'm missing some core SQL knowledge to grok a solution to this problem. Here's the situation as briefly as I can explain it. **Context:** I have a SQLite database table that contains timestamped user event records. The records can be uniquely identified by the combination of time...
You could try this: ``` select user_id, max(last_updated) as latest from records group by user_id ``` This should give you the latest record per user. I assume you have an index on user\_id and last\_updated combined. In the above query, generally speaking - we are asking the database to group user\_id records. If t...
Well, in true "d'oh!" fashion, right after I ask this question, I find [the answer](https://stackoverflow.com/a/3814269/4463672). For my case, the answer is: ``` SELECT MAX(Last_Updated),User_ID FROM records GROUP BY User_ID ``` I was making this more complicated than it needed to be by thinking I needed to use JOIN...
SQLite: How to SELECT "most recent record for each user" from single table with composite key?
[ "", "sql", "sqlite", "greatest-n-per-group", "" ]
I am not sure what to call this but basically, my database has games that can be played by 1 to 4 players. The `Games` table has 4 foreign keys to the `PlayerGames` table. GameFirstPlace, GameSecondPlace... etc. They can be null. If they are not they point to an entry in the `PlayerGames` table. The `PlayerGames` ta...
``` SELECT Game.GameID ,Player1.Name AS FirstPlaceName ,Player2.Name AS SecondPlaceName ,Player3.Name AS ThirdPlaceName ,Player4.Name AS FourthPlaceName FROM Game LEFT OUTER JOIN PlayerGame as PlayerGame1 ON Game.GameFirstPlace = PlayerGame1.Id LEFT OUTER JOIN Player AS Player1 ON Playe...
You're going to have to duplicate all of the join logic four ways. ``` select g.GameID, p1.PlayerName as FirstPlaceName, p2.PlayerName as SecondPlaceName, p3.PlayerName as ThirdPlaceName, p4.PlayerName as FourthPlaceName from Games g left outer join PlayerGames pg1 on pg1.PlayerID = g.GameF...
Query that can get player's name if it is not null
[ "", "mysql", "sql", "" ]
I currently have a query where it returns the total number of accounts each customer holds, but how do I make it so that it returns only customers who has more than 1 account? ``` SELECT C.customerID, COUNT(O.accNumber) AS "total" FROM Customer C, Owns O WHERE C.customerID = O.customerID GROUP BY C.customerID ```
The answer to your question is `HAVING`. However, you need to learn to use proper`JOIN` syntax. Simple rule: *Never* use a comma in the `FROM` clause. *Always* use explicit `JOIN` syntax. ``` SELECT C.customerID, COUNT(O.accNumber) AS total FROM Customer C JOIN Owns O ON C.customerID = O.customerID GROUP BY ...
Add a HAVING clause ``` SELECT C.customerID, COUNT(O.accNumber) AS "total" FROM Customer C, Owns O WHERE C.customerID = O.customerID GROUP BY C.customerID HAVING COUNT(*) > 1 ```
SQL COUNT function for results "greater than or equal to"
[ "", "sql", "count", "" ]
I am using the following spooling script with [Oracle SQL Developer 4.1](http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index-097090.html): ``` set echo off set feedback off set termout off spool A.txt select /*csv*/ * from A where rownum <= 1000; spool off spool B.txt select /*csv*/ * from...
two things: 1. it's the default SQL\*Plus behavior, which we try to emulate 100% as much as possible 2. there's a bug - we're not supporting SET PAGESIZE 0. if you use this in conjunction with SET TRIMSPOOL ON, you'll lose the blank line(s) we've got it on the list for the next release 2020 Update Using Version 20....
That doesn't seem to be possible; it's been asked before but I don't see any resolution. (Tried with `set sqlformat csv` instead of the `/*csv*/` hint, just in case, but the behaviour is the same). If you export the query results from the grid as CSV (right-click the grid and choose Export...) then you don't get the b...
SQL Developer spooling: how to get rid of the first, empty line
[ "", "sql", "oracle", "output", "oracle-sqldeveloper", "flat-file", "" ]
i am not sure whether it is possible but appreciate if any one can help me on this. **if the column is blank for all the output rows then should not appear in the output.** sample data: ``` DECLARE @T TABLE ( BaseVehicle VARCHAR (50), SubModel VARCHAR (50), Make VARCHAR (50), Years VARCHAR (50), FromYear...
Check for the count of cells which is null with the count of all. If both matches, then the entire column in null. Then leave that column from the selection. **Query** ``` create table #T ( BaseVehicle VARCHAR (50), SubModel VARCHAR (50), Make VARCHAR (50), Years VARCHAR (50), FromYear VARCH...
Actually you can do this with temp table, because you can alter it. But I wouldn't recommend to do this: ``` DECLARE @T TABLE( BaseVehicle VARCHAR (50), SubModel VARCHAR (50), Make VARCHAR (50), Years VARCHAR (50), FromYear VARCHAR (50), ToYear VARCHAR (50)) INSERT @T SELECT '1979 Ford LTD','','FORD','1...
if blank value in entire column then remove from output
[ "", "sql", "sql-server", "database", "" ]