Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've got a table, let's call it `values` with a primary key and five integer fields, like this: ``` id val1 val2 val3 val4 val5 1 4 3 4 5 3 2 2 3 2 2 2 3 5 4 1 3 3 4 1 4 3 4 4 ``` Now I need to select all rows where at least any two of t...
You can use [**`VALUES`**](https://msdn.microsoft.com/en-us/library/dd776382.aspx) to construct an inline table containing your fields. Then query this table to get rows having at least two fields equal to 4: ``` SELECT * FROM mytable CROSS APPLY ( SELECT COUNT(*) AS cnt FROM (VALUES (val1), (val2), (val3), (val4)...
Although `cross apply` is fast, it might be marginally faster to simply use `case`: ``` select t.* from t where ((case when val1 = 4 then 1 else 0 end) + (case when val2 = 4 then 1 else 0 end) + (case when val3 = 4 then 1 else 0 end) + (case when val4 = 4 then 1 else 0 end) + (case when val...
T-Sql: Select Rows where at least two fields matches condition
[ "", "sql", "t-sql", "" ]
I have two tables. Something like table1 and table2 given below: table1 has ID (primary key) and columns Aid, Bid and Cid which are primary key of table 2. ``` table1 ID Aid Bid Cid ----------------- 1 X Y Z 2 X Z Z 3 Y X X ----------------- table2 ID NAME ------------------ X Abc Y Bcd Z...
This should work: ``` select table1.ID, a.NAME AS A, b.NAME AS B, c.NAME AS C from table1 join table2 a on table1.Aid = a.ID join table2 b on table1.Bid = b.ID join table2 c on table1.Cid = c.ID ``` Otherwise: ``` select table1.ID, a.NAME, b.NAME, c.NAME from table1 join (select * from table2) a on table1.Aid = a...
You can try this. `INNER JOIN` & `ORDER` - ``` SELECT a.ID, b.NAME, c.NAME, d.NAME FROM table1 a INNER JOIN table2 b ON b.ID = a.Aid INNER JOIN table2 c ON c.ID = a.Bid INNER JOIN table2 d ON d.ID = a.Aid ORDER BY a.ID ```
Mysql query with inner join
[ "", "mysql", "sql", "inner-join", "" ]
I'm trying to do the following. ``` UPDATE account SET new_finalleadsource = CASE WHEN new_jtrack_source IS NOT NULL AND new_jtracksource <> '' THEN new_jtrack_source CASE WHEN new_jtrackofflinesource IS NOT NULL AND new_jtrackofflinesource <> '' THEN new_jrackofflinesource CASE WHEN new_leadsource IS NOT NULL ...
You don't need multiple `CASE` statements, instead use single `Case` statement with multiple `WHEN` expression's Try this way ``` UPDATE account SET new_finalleadsource = CASE WHEN new_jtrack_source IS NOT NULL AND new_jtracksource <> '' THEN ne...
This is not how the case statement works. The case statement is like a series of checks of WHEN THEN. Sort of like C switch with a break before each WHEN. So what you want is ``` UPDATE account SET new_finalleadsource = CASE WHEN new_jtrack_source IS NOT NULL AND new_jtracksource <> '' THEN new_jtrack_source ...
SQL UPDATE based on conditions of other columns
[ "", "sql", "sql-server", "" ]
I have a database with products. When I selected a product I want to get the next product in my database. For Example: I have the product with ID 188 and I want to get the next product with ID 167. Database: ``` SELECT * FROM product ORDER BY title ASC, description ASC +----+----------------------+------------------...
You've got the right approach. Only one small change is required, changing that first comparison to be "*greater than* ***or equal to***" instead of just "*greater than*". As long as the `(title,description)` tuple is unique, that will work just fine. This is the pattern you want: ``` WHERE ( title >= ? ) AND ( tit...
Your sorting on title with a `>`. Assuming you've got record 188, the title is `Adjustment housing` If you look you'll set the first record with a `title < 'Adjustment housing'` is in fact record 102. Change it to be : ``` SELECT * FROM product WHERE title >= ? AND description >= ? AND id != ? ORDER BY title ASC,...
mysql get next row ordered by multiple columns
[ "", "mysql", "sql", "database", "range", "row", "" ]
Basicly, I have a table with a priority attribute and a value, like ``` TargetID Priority_Column (int) Value_column 1 1 "value 1" 1 2 "value 2" 1 5 "value 5 2 1 "value 1" 2 2 ...
One way is using `outer apply`: ``` select t2.*, t1.* from table2 t2 outer apply (select top 1 t1.* from table1 t1 where t2.id = t1.targetid order by priority desc ) t1; ``` I should note that in SQL Server, this is often the most efficient method. It will take good advantage of an index o...
There are several options for this. Here's one using `row_number`: ``` select * from anothertable a join ( select *, row_number() over (partition by targetid order by priority desc) rn from yourtable) t on a.id = t.targetid and t.rn = 1 ```
table join with priority attribute
[ "", "sql", "sql-server", "" ]
I've searched this and found this problem, and the solution that worked for most people (using an outer join) is not working for me. I originally had an inner join, and switched it to an outer join but I am getting the same results. This is based off certain account numbers and it shows their total sales. If an account...
I think that `RIGHT JOIN` will not work, since there are conditions in `WHERE`. Try this: ``` SELECT c.accountnumber, COALESCE(SUM(a.totalsales),0) AS Amount, c.companyname FROM Accounts c LEFT OUTER JOIN Sales a ON a.Accountnumber = c.Accountnumber AND a.Salesdate BETWEEN '1/1/2016' AND '1/27/2016'...
You should have two options. 1. Modify the query to select from the Accounts table first and then join the Sales table afterwards. ``` FROM Accounts c LEFT OUTER JOIN Sales a on (a.Accountnumber = c.Accountnumber) ``` 2. Use a RIGHT join instead of a LEFT one. ``` FROM Sales a RIGHT OUTER JOIN ...
Query to return sales excludes results that are 0
[ "", "mysql", "sql", "ssms", "" ]
I am using a Select query to select Members, a variable that serves as a unique identifier, and transaction date, a Date format (MM/DD/YYYY). ``` Select Members , transaction_date, FROM table WHERE Criteria = 'xxx' Group by Members, transaction_date; ``` My ultimate aim is to count the # of unique members by month (i...
This will give distinct count per month. `SQLFiddle Demo` ``` select month,count(*) as distinct_Count_month from ( select members,to_char(transaction_date, 'YYYY-MM') as month from table1 /* add your where condition */ group by members,to_char(transaction_date, 'YYYY-MM') ) a group by month ``` So f...
You might want to try this. This might work. SELECT REPLACE(CONVERT(DATE,transaction\_date,101),'-','/') AS [DATE], COUNT(MEMBERS) AS [NO OF MEMBERS] FROM BAR WHERE REPLACE(CONVERT(DATE,transaction\_date,101),'-','/') IN ( SELECT REPLACE(CONVERT(DATE,transaction\_date,101),'-','/') FROM BAR ...
Changing a Select Query to a Count Distinct Query
[ "", "sql", "postgresql", "" ]
I want to exclude the weekend and the holiday from my table: [![enter image description here](https://i.stack.imgur.com/XkE7H.png)](https://i.stack.imgur.com/XkE7H.png) for example in this picture I would like to exclude the date 19.01. and 10.01 from my table or it should show only 0 in 10.01.2016. this is my code:...
I think the best approach is create a table in your database and store all weekend and holidays dates then use that table to filter your query. Something like this: ``` SELECT * FROM ( Select intervaldate as Datum, tsystem.Name as Name, SUM(case when Name = 'Maschine 1' then Units else 0 end) as Maschine1, S...
Right click the row group in your tablix and select Row Visibility. In the Change display options, select Show or hide based on an expression. In the expression, this should work: ``` =iif(CDate(Fields!Date.Value).DayOfWeek = DayOfWeek.Saturday, true, iif(CDate(Fields!Date.Value).DayOfWeek = DayOfWeek.Sunday, true, fa...
exclude some data from a table SSRS
[ "", "sql", "reporting-services", "" ]
This might be a simple solution but its a headache to me from last couple of hours when i run this query ``` insert into payment set id ='13914', amount ='48.00', discount ='0.00', total ='48.00', fees ='2', charges ='', staus ='2' ``` The value `48.00` saves in db column as just `48`. db column type is double.
Easily found in [docs](http://dev.mysql.com/doc/refman/5.7/en/floating-point-types.html): > Because floating-point values are approximate and not stored as exact values, attempts to treat them as exact in comparisons may lead to problems. They are also subject to platform or implementation dependencies. Further [more...
Your data is stored correctly. 48 == 48.00 when you use DOUBLE. When you retrieve your data try ``` SELECT ROUND(amount,2) amount, ROUND(discount, 2) discount FROM payment ``` if you really have to see the `.00` at the end of your numbers. And please, *please*, for the good of the profession and your futur...
Saving a 48.00 value to MySQL data type double it saves as 48
[ "", "mysql", "sql", "floating-point", "" ]
What this is doing is selecting all columns from TABLE where a specific date time column is between last Sunday and this coming Saturday, 7 days total (no matter what day of the week you are running the query on) I would like to have help converting the below statement into Oracle since I found out that it will not wo...
After poking around a bit more I was able to find something that worked for my specific problem with no administrator restrictions for whatever reason: ``` SELECT * FROM TABLE WHERE DATE_TIME_COLUMN BETWEEN TIMESTAMPADD(SQL_TSI_DAY, DayOfWeek(Current_Date)*(-1) + 1, Current_Date) AND TIMESTAMPADD(SQL_TSI_DAY, ...
Use `TRUNC()` to truncate to the start of the week: ``` SELECT * FROM TABLE WHERE DATE_TIME_COLUMN BETWEEN trunc(sysdate, 'WW') and trunc(sysdate + 7, 'WW'); ``` `sysdate` is the current system date, `trunc` truncates a data, and `WW` tells it to truncate to the week (rather than day, year, etc.).
DB2 to Oracle Conversion For Basic Date Time Column Between Clause
[ "", "sql", "oracle", "date", "db2", "between", "" ]
My first post, so bear with me. I want to sum based upon a value that is broken by dates but only want the sum for the dates, not for the the group by item in total. Have been working on this for days, trying to avoid using a cursor but may have to. Here's an example of the data I'm looking at. BTW, this is in Oracle ...
In order to get the sums you are looking for you need a way to group the values you are interested in. You can generate a grouping ID by using the a couple of `ROW_NUMBER` analytic functions, one partitioned by the key value. However due to your need to duplicate the `KEY` column values this will need to be done in a c...
I'm not sure what your example data has to do with the queries (your sample data is one table, for instance and the sample queries have many queries). But, for assigning the keys, you can use `LAG()` with the `IGNORE NULLS` option: ``` select s.*, lag(key ignore nulls) over (order by start) as new_key from samp...
Running total over repeating group by items based on time in Oracle SQL
[ "", "sql", "oracle", "sum", "window-functions", "" ]
I tried with below queries and bit confused about working of `EXISTS` clause, although I know it evaluates for `TRUE/FALSE`. Below #1 SQL sub-query anyhow returns 0, but still the result of the combined query is 1. ``` 1. SELECT 1 WHERE EXISTS ( SELECT 0 WHERE 1 = 1 ) 2. SELECT 1 WHERE EXISTS ( SELECT 0 WHERE 1 = 0 ...
From documentation [EXISTS](https://msdn.microsoft.com/en-us/library/ms188336.aspx): > Specifies a subquery to test for the existence of rows. ``` SELECT 1 WHERE EXISTS ( SELECT 0 WHERE 1 = 1 ) -- there is row SELECT 1 WHERE EXISTS ( SELECT 0 WHERE 1 = 0 ) -- no row returned by subquery SELECT 1 WHERE EXISTS ( 1 ...
EXISTS returns true when the subquery within it has any rows. A logically equivalent (but not recommended) way of rewriting an EXISTS expression is: ``` SELECT 1 WHERE (SELECT COUNT(*) FROM (SELECT 0 WHERE 1 = 1)) > 0 ``` In this rewriting, your last query looks like: ``` SELECT 1 WHERE (SELECT COUNT(*) FROM 1) > 0 ...
How does the EXISTS Clause work in SQL Server?
[ "", "sql", "sql-server", "" ]
## my table structure ``` id zoneid status 1 35 IN starting zone 2 35 OUT 1st trip has been started 3 36 IN 4 36 IN 5 36 OUT 6 38 IN last station zone 1 trip completed 7 38 OUT returning back 2nd trip has start 8 38 OUT 9 36 IN 10 36 OUT 11 35 IN whe...
So you don't want to look at the status, but only look at the `zoneid` changes ordered by id. `zoneid` 36 is irrelevant, so we select 35 and 38 only, order them by id and count changes. We detect changes by comparing a record with the previous one. We can look into a previous record with LAG. ``` select sum(ischange) ...
I am suggesting this without any testing. Does the following query produce the correct number of rows? Note if there is a date\_created (datetime) column then I would suggest using that column to order by instead of id. ``` select ca.in_id, t.id as out_id, ca.in_status, t.status as out_status from table1 t cros...
count trip in sql server
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I'm working on a SQL quiz as follows: Write an SQL Statement to retrieve all thepeople who work on the same projects assmith with the same amount of hours withrespect to each Project. With the sampledata, only Smith and Brown should be retrieved. Oaks is disqualified since Oakshas worked on Project Y for 10 hours only ...
``` select t1.* from workson t1 inner join workson t2 on t2.name = 'Smith' and t2.project = t1.project and t2.hours = t1.hours where t1.name in ( select i1.name from workson i1 inner join workson i2 on i2.name = 'Smith' and i2.project = i1.project and i2.hours = i1.hours group by i1.name having count(*) = (se...
I had some problems with the above answer, but it gave me a very good framework so I can't really take credit for this answer: ``` SELECT name, project, hours FROM workson w2 WHERE name IN (SELECT name FROM workson w INNER JOIN (SELECT project, hours FROM workson WHERE name = 'Smith') q1 ON q1.project = w.project AN...
SQL - Filtering result to match TWO columns in TWO different rows
[ "", "sql", "select", "" ]
[![enter image description here](https://i.stack.imgur.com/n7IZN.jpg)](https://i.stack.imgur.com/n7IZN.jpg) The following query I tried... ``` select d.deptID, max(tt.total) from dept d, (select d.deptID, d.deptName, sum(days) as total from vacation v, employee e, dept d where v.empId = e.empID and d.deptID = e.deptI...
Try using limit since your inner query already does the calculation. ``` select TOP 1 * from ( select d.deptID, d.deptName, sum(days) as total from vacation v, employee e, dept d where v.empId = e.empID and d.deptID = e.deptID group by d.deptID, d.deptName) order by total desc; ``` Depends on the dbms you're using.. ...
Using Top: ``` Select top 1 with ties * from (Select D.DepartmentName, sum(V.Days) as SumDays from Vacations V inner join Employee E on E.EmployeeID=V.EmployeeID inner join Department D on D.DepartmentID=E.DepartmentID group by D.DepartmentName)SumDays Order by SumDays desc ```
What would be the result of the following query?
[ "", "sql", "" ]
I have three tables: tblAreas, which describes various areas of the UK; tblNewsletters, which lists quarterly dates when we publish newsletters; tblIssues, which is a many-to-many table linking the previous two. tbl Issues describes each newsletter produced by each area in each quarter (one newsletter per area per quar...
``` Select * from tblArea a left join tblIssues i on i.AreaId = a.Id where i.AreaId is null ``` For a specific quarter, you will have to use a subquery. ``` Select * from tblArea a left join (select AreaId from tblIssues ii inner join Newsletters n on n.Id = ii.NewsLetterId where n...
You need to first build the cartesian product of all areas and newsletters, which is `SELECT a.ID, n.ID FROM tblAreas a, tblNewsletter n` *(just saw there is no `cross join` in access)* Then you need to cross out all issues, that do actually exist. Normally you would use a syntax like `MINUS SELECT i.AreaLookup, i.N...
Find those who have NOT written a letter
[ "", "sql", "ms-access", "vba", "" ]
I need to show related record id based document no as reference in same table. I try many time and direction but cannot get a right output. This below are table and data: [Table A](https://i.stack.imgur.com/l0aBE.png) Basically Record ID no 2,4 and 10 are related based on Reference Document No. For example if I sele...
I assume you're using postgres, since this is tagged with it. You can make a recursive query that will accomplish what you want when you're querying for a given docno: ``` WITH RECURSIVE t AS ( SELECT docno, refdocno FROM <table> WHERE docno = 'T0003' UNION SELECT blah.docno, blah.refdocno FR...
Are you wanting to link all documents on the parent document? If you wanted to, say get a document and find all related documents for docno XY001 (assuming XY001 is the parent Document otherwise link the other way around) You could use ``` SELECT * FROM TableA AS parentDoc LEFT OUTER JOIN TableA AS referentialDoc ON p...
How To Find Related Record ID Based Reference Document No on SQL Statement
[ "", "sql", ".net", "postgresql", "relationship", "" ]
I've got a 2 part problem where through the use of google managed to find the answer to the first part at [SQL get the last date time record](https://stackoverflow.com/questions/16550703/sql-get-the-last-date-time-record) User **Osy** code work really well for me, Osy's code below! ``` select filename, dates, statu...
Continuing with your posted example code, again perform one more `JOIN` with `Table2` like ``` select t2.ref, xx.Dates, xx.Status from Table2 t2 join ( select filename, dates, status from yt a where a.dates = ( select max(dates) from yt b where a.filename = b.filename )) xx on t2.filename = xx.filename; ```
This might be faster way to do it. ``` SELECT [ref], [dates], [status] FROM (SELECT a.[filename], a.[dates], a.[status], t2.[ref], ROW_NUMBER() OVER (PARTITION BY a.[filename] ORDER BY a.[dates] DESC) [Rn] FROM yt a ...
SQL Server query to join two tables
[ "", "sql", "sql-server", "date", "join", "" ]
This question might be a duplicate but I’ve tried all the answers of the other questions and none of the answers did help. I'm trying to compare a datetime value against a static one ( I need every record with a date lager then 1/1/2016 ) ``` CREATE PROCEDURE Cursusoverzicht as SELECT tblBijeenkomst.bijeenkomstdatum,...
It appears you are almost there: ``` CREATE PROCEDURE Cursusoverzicht as SELECT tblBijeenkomst.bijeenkomstdatum ,tblCursussen.cursus_id ,tblCursussen.cursustitel FROM tblCursussen INNER JOIN [dbo].[tblCursusDocenten] on [dbo].[tblCu...
Try adjusting the format of your datetime to 2016-01-01 00:00:00.000. This is the SQL Server default format. You can test this for yourself using the [GETDATE()](https://msdn.microsoft.com/en-GB/library/ms188383.aspx) function. This returns the current date and time as a [DATETIME](https://msdn.microsoft.com/en-GB/lib...
Comparing datetime values in MS SQL
[ "", "sql", "sql-server", "database", "datetime", "" ]
I have two table like belew ``` Table1: CId -- Name -- Price -- MId 1 A 100 -- 1 2 B 110 -- 1 3 C 120 -- 1 4 D 120 -- 2 Table2: Id -- UserId -- CId -- Price 1 1 2 200 1 2 2 200 ``` I want to get data from Table one But if there is...
You can get by `left join` where you check `null` value in second table. if second price is `null` then use `first table's price`. ``` SELECT t1.CId, t1.name CASE WHEN t2.price IS NULL THEN t1.price ELSE t2.price END AS Price FROM table1 t1 LEFT JOIN table2 t2 ON t1.CId = t2.CId WHERE WHERE t1.MId = 1 AND (t2....
[SQL FIDDLE](http://sqlfiddle.com/#!9/b26d2/1) try this ``` select t1.cid,t1.name, case when t2.cid is null then t1.price else t2.price end as Price from table1 t1 left join table2 t2 on t1.cid =t2.cid where t1.mid =1 AND (t2.UserId = 1 OR t2.UserId IS NULL); ```
join two table to replace new value from 2th table if exist
[ "", "mysql", "sql", "database", "join", "" ]
I'm using SQL Server and I'm having a difficult time trying to get the results from a SELECT query that I want. I've to select records from 3 tables given below: Client(clientID,name,age, dateOfBirth) Address(clientID, city, street ) Phone(ClientID, personalPhone, officePhone, homePhone) In my input I could have (d...
This is almost the same as Mureinik's answer, but he didn't use left outer joins, so if you had a client with an address but without a phone number, they would be excluded from the result-set UNLESS you use an outer join: ``` SELECT DISTINCT client_id FROM client c LEFT OUTER JOIN address a ON c.client_id = a...
You could short circuit the logic using `or` conditions. Let's assume you denote the arguments with a `@`: ``` SELECT DISTINCT client_id FROM client c LEFT JOIN address a ON c.client_id = a.client_id LEFT JOIN phone p ON c.client_id = p.client_id WHERE (@date_of_birth IS NULL OR c.date_of_birth = @date_of_...
Select from multiple tables with OR condtions
[ "", "sql", "sql-server", "" ]
I have a column name `source` which has values like `JBInfotech_CLC_4120_20160128`. How do I update the last character to `7`. There are hundreds of records I want to update at the same time. Which is these records: ``` SELECT * FROM [JBINFOTECH].[dbo].[leads] WHERE id <= 985 ORDER BY id DESC; ``` This is permanentl...
You can try like this, ``` DECLARE @table TABLE ( col1 VARCHAR(100) ) INSERT INTO @table VALUES ('ABCDEF123'), ('JBInfotech_CLC_4120_20160128') SELECT * FROM @table UPDATE @table SET col1 = Stuff(col1, Len(col1), 1, '7') SELECT * FROM @table ```
Try: ``` update [JBINFOTECH].[dbo].[leads] Set [Source]=Concat(Left([Source],len([Source])-1), '7') WHERE id <= 985 ```
SQL Server update query replace last character of a value
[ "", "sql", "sql-server", "sql-update", "" ]
I am using SQL Server Express 2014 and I need to pull out the last record for few (3 for now) tags with different IDs from one table. So far I made it but not at all. I am using ``` SELECT TOP 1 [TagItemId], [TagValue] FROM [DB].[dbo].[Table] where [TagItemId] like 'Random.Int1' order by [TagTimestamp] desc SELECT ...
You could do this using Row\_Number ``` SELECT [TagItemId], [TagValue] FROM ( SELECT [TagItemId], [TagValue], ROW_NUMBER() OVER (PARTITION BY [TagItemId] ORDER BY [TagTimestamp] DESC) Rn FROM [DB].[dbo].[Table] WHERE [TagItemId] IN ('Random.Int...
There are several ways to accomplish this: ``` SELECT MT.TagItemID, MT.TagValue FROM My_Table MT INNER JOIN ( SELECT TagItemID, MAX(TagTimestamp) FROM My_Table WHERE MT.TagItemID IN ('Random.Int1', 'Random.Int2', 'Random.Int3') GROUP BY TagItemID) SQ ON SQ.TagItemID = MT.TagItemID W...
Need to join 3 select queries that refers to same table
[ "", "sql", "sql-server", "select", "" ]
Consider a table T, with columns 1. ID = e.g Customer ID 2. Expense = amount spent on buying an item 3. Date = Date of transaction 4. Item = item bought I want to perform following select operation on T. I want to find for each ID, the most expensive item that was bought on an earliest date. For example if the tabl...
Try: ``` Select * from (select row_number() over (partition by ID order by Expense desc, date asc) RN, id, expense, date, item from T)T where RN=1 ```
**Edit:** This answer is wrong, because the question was originally tagged wrong. I'd edit, but there is already another correct answer here. I'm leaving this here because it still demonstrates a viable solution that even works on MySql, but you should really vote for the `row_number()` solution. --- Think of doing t...
SQL query for the given select operation
[ "", "sql", "db2", "" ]
I have this query, ``` SELECT * FROM users WHERE user_ip IN (SELECT user_ip FROM users GROUP BY user_ip having count(*) > 1) ORDER BY user_ip ``` This works to list all users which has at least 1 repeated IP with another user. I need to order all users by total of repeated IP. ex. this users table ``` id, username...
Here is an approach which uses an `INNER JOIN`: ``` SELECT u1.ip, u1.username, u2.total FROM users u1 INNER JOIN ( SELECT ip, COUNT(*) AS total FROM users GROUP BY ip ) u2 ON u1.ip = u2.ip ORDER BY u2.total DESC ``` Click the link below for a running demo: [**SQLFiddle**](http://sqlfiddle.com/#!9/b3982/2...
``` SELECT ip, username, count(*) total FROM user_ip WHERE ip in ( SELECT ip FROM user_ip GROUP BY 1 HAVING count(*) > 1 ) GROUP BY 1,2 ORDER BY 3 DESC,1,2 ```
List users with the same IP
[ "", "mysql", "sql", "" ]
I'm trying to compare two "lists" in same table and get records where `customerId` exists but `storeid` doesn't exist for that `customerid`. Lists (table definition) ``` name listid storeid customerid BaseList 1 10 100 BaseList 1 11 100 BaseList ...
If the table definition contains a column `Name` (as you said), then the statement below returns your result. I didn't understand your select statement. ``` SELECT * from @table WHERE NAME = 'NewList' AND customerID IN (SELECT CustomerID FROM @table WHERE NAME = 'BaseList') AND storeID NOT IN (SELECT storeID FROM...
This dynamic pivot will show you all your list values and where else the same combination exists: I add one more group: ``` insert into Lists(name, listid, storeid, customerid) values('AnotherNew',3,11,100); insert into Lists(name, listid, storeid, customerid) values('AnotherNew',3,11,102); insert into Lists(name, li...
Compare records in database where one column exists but another doesn't
[ "", "sql", "sql-server", "" ]
I'm joining 2 tables and displaying data for InvNumber, InvAmount and JobNumber. I only need to display InvNumber and InvAmount in the first row. The Invoice has multiple Job numbers which should be displayed. HEre is the DDL ``` DECLARE @Date datetime; SET @Date = GETDATE(); DECLARE @TEST_DATA TABLE ( DT_ID INT...
You can do something like this with ROW\_NUMBER and CASE expressions. ``` SELECT DT_ID, CASE WHEN RN = 1 THEN InvNumber ELSE '' END InvNumber, CASE WHEN RN = 1 THEN InvAmount ELSE '' END InvAmount, JobNumber FROM (SELECT DT_ID, ...
you can't really easily do that with SQL. You can use the GROUP BY clause, in the select statement, to group the JobNumbers by Invoice though.
Display only first row in SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I am trying to find the number of sellers that made a sale last month but didn't make a sale this month. I have a query that works but I don't think its efficient and I haven't figured out how to do this for all months. ``` SELECT count(distinct user_id) as users FROM transactions WHERE MONTH(date) = 12 AND YEAR(date...
Use conditional aggregation: ``` SELECT count(*) as users FROM ( SELECT user_id FROM transactions -- 1st of previous month WHERE date BETWEEN SUBDATE(SUBDATE(CURRENT_DATE, DAYOFMONTH(CURRENT_DATE)-1), interval 1 month) -- end of current month ...
if you want to generify it, you can use `curdate()` to get current month, and `DATE_SUB(curdate(), INTERVAL 1 MONTH)` to get last month (you will need to do some if clause for January/December though): ``` SELECT count(distinct user_id) as users FROM transactions WHERE MONTH(date) = MONTH(DATE_SUB(curdate(), INTERVAL ...
SQL Query to find rows that didn't occur this month
[ "", "mysql", "sql", "" ]
I have 3 tables: [![enter image description here](https://i.stack.imgur.com/4CLmy.png)](https://i.stack.imgur.com/4CLmy.png) I have tried this so far: ``` SELECT T1.P_id as id, T2.D_id, COALESCE(T2.count , 0) AS count FROM ( SELECT DISTINCT P_id FROM Comp_prod WHERE company_id = '15' ) AS T1 LEFT JOIN ( SE...
Hope this helps ``` select sub.C_id,sub.D_id,sub.P_id,count(Userlogs.D_id) from (select Comp_prod.C_id,D_id,P_id from Comp_prod join Departments on Comp_prod.C_id = Departments.C_id ORDER by Comp_prod.C_id asc, Departments.D_id ASC, Comp_prod.P_id ASC) as sub left join Userlogs ...
You can generate all rows, using `cross join` and then bring in the existing results (if any) for aggregation: ``` select d.c_id, d.D_id, p.P_id, count(ul.c_id) as cnt from comp_prod p cross join departments d left join user_logs ul on ul.c_id = d.c_id and ul.d_id = d.d_id and ul.p_id = p.p_id group by ...
Issue with SQL joining
[ "", "mysql", "sql", "" ]
I have four tables : 1. Batch(batch\_id, batch\_start\_date, batch\_strength, course\_id) 2. Course(course\_id, course\_name, course\_category, course\_fees, course\_duration) 3. Enrollment(batch\_id, student\_id, enrollment\_date) 4. Student(student\_id, student\_name, student\_mail, student\_date\_of\_birth, student...
Non-analytic solution just for the fun of it: ``` with r as ( select min(c.course_name) as course_name, min(c.course_fees) * count(*) as revenue from course c inner join batch b on b.course_id = c.course_id inner join enrollment e on e.batch_id = b.batch_id group by c.course_id ) se...
Use `row_number()`: ``` select * from (select c.course_name, c.course_fees*count(c.course_name) as Total_Revenue, row_number() over (order by c.course_fees*count(c.course_name)) as seqnum from batch b join enrollment e on b.batch_id = e.batch_id join course c ...
How to extract second highest row from a table
[ "", "sql", "oracle", "oracle11g", "top-n", "" ]
I have table that looks like this: ``` | id | user | data | -------------------- | 1 | 11 | aaa1 | | 2 | 11 | aaa2 | | 3 | 11 | aaa3 | | 4 | 22 | aaa4 | | 5 | 33 | aaa5 | | 6 | 33 | aaa6 | | 7 | 44 | aaa7 | ``` I want to select all rows, with all data, and I want to add data with `max id` per `us...
**[SQL Fiddle Demo](http://sqlfiddle.com/#!9/a24413/6)** ``` SELECT t1.*, t2.id AS f_id, t2.data AS f_data FROM table1 t1 JOIN table1 t2 ON t1.user = t2.user AND t2.id = (SELECT MAX(t2.id) FROM table1 t3 WHERE t3.user = t1.user) ```
This will do it. ``` SELECT t1.*, t3.id AS f_id, concat(SUBSTRING(t1.data, 1, CHAR_LENGTH(t1.data)-1),t3.id) AS f_data FROM table1 t1 INNER JOIN (select max(t2.id) as id, t2.user as userid from table1 t2 group by t2.user) t3 on t3.userid = t1.user ``` Sqlfiddle : <http://sqlfiddle.com/#!9/a24...
MySQL select all rows having latest value per id
[ "", "mysql", "sql", "join", "max", "" ]
I have two tables, t1 and t2, with identical columns(id, desc) and data. But one of the columns, desc, might have different data for the same primary key, id. I want to select all those rows from these two tables such that t1.desc != t2.desc ``` select a.id, b.desc FROM (SELECT * FROM t1 AS a UNION ALL ...
`UNION ALL` dumps all rows of the second part of the query *after* the rows produced by the first part of the query. You cannot compare `a`'s fields to `b`'s, because they belong to different rows. What you are probably trying to do is locating records of `t1` with `id`s matching these of `t2`, but different descripti...
`Union` is not going to compare the data.You need `Join` here ``` SELECT * FROM t1 AS a inner join t2 AS b on a.id =b.id and a.desc != b.desc ```
using where clause with Union
[ "", "sql", "oracle", "" ]
i am trying to delete e-mail duplicates from table nlt\_user this query is showing correctly records having duplicates: ``` select [e-mail], count([e-mail]) from nlt_user group by [e-mail] having count([e-mail]) > 1 ``` now how can i delete all records having duplicate but one? Thank you
Try this : ``` delete n1 from nlt_user n1 inner join nlt_user n2 on n1.e-mail=n2.e-mail and n1.id>n2.id; ``` This will keep record with minimum ID value of duplicates and deletes remaining duplicate records
If MySQL version is prior 5.7.4 you can add a `UNIQUE` index on the column e-mail with the `IGNORE` keyword. This will remove all the duplicate e-mail rows: ``` ALTER IGNORE TABLE nlt_user ADD UNIQUE INDEX idx_e-mail (e-mail); ``` If > 5.7.4 you can use a temporary table (`IGNORE` not possible on `ALTER` anymore): `...
Delet just one record of duplicate
[ "", "mysql", "sql", "" ]
I'm very new to SQL and learning. Currently I am working with a Select statement to only show orders from the current month. I am using ``` SELECT ORDERS.ORDERID, ORDERS.CUSTOMERID, ORDERS.ORDERDATE, ORDERS.SHIPDATE FROM ORDERS WHERE Date >= '01-JAN-16' and Date <= '31-JAN-16' ``` But that fails with Invali...
If the field "Date" is really the name of your field, you will need to enclude it in tic marks as follows in your WHERE clause: ``` ... WHERE `Date` >= '01-JAN-16' and `Date` <= '31-JAN-16' ``` Because Date is a reserved word. It looks like ORDERDATE and SHIPDATE are your field names ... should you be using one of th...
It is caz' of your date format. Better way is the next query: ``` SELECT ORDERS.ORDERID, ORDERS.CUSTOMERID, ORDERS.ORDERDATE, ORDERS.SHIPDATE FROM ORDERS WHERE EXTRACT(month from date) = 1; --take records for january ```
SQL Select Query fails when trying to show results in current month
[ "", "sql", "oracle", "" ]
I want to use an id as a primary key for my table. In each record, I am also storing an id from an other source, but these ids are in no way sequential. Should I add an (auto-incremented) column with a "new" id? It is very important that queries by the id are as fast as possible. Some info: * The content of my table...
As long as you are sure the supplied id's are unique, there's no need to create another (surrogate) id to use as primary key.
Under most circumstances, an index on the existing id should be sufficient. You can make it slightly faster by declaring it as a primary key. From what you describe a new id is not necessary for performance. If you do add one, the table will be slightly larger, which has a (very small) negative effect on performance. ...
Database: Should ids be sequential?
[ "", "sql", "sql-server", "database", "" ]
I have a reservation table like this ``` place day name1 floor1 name2 floor2 --------- -------- --------- --------- --------- --------- Anaheim Monday Sean 3rd Jenny 2nd Anaheim Monday Jenny 2nd Sean 3rd Cerritos Saturday Dennis 4th Sean ...
First of all, if you want to compare `floor1` for more than 9 floors, then `2nd` would be greater than `11th`. To overcome this, you need to extract floor number from `floor1` and then compare it. Having said that, you can use this query if it is working for your db/version. `SQLFiddle Demo Fast version` . The gene...
Use a clever `GROUP BY`: ``` SELECT t1.place, t1.day, t1.name1, t1.floor, t1.name2, t1.floor2 FROM table t1 INNER JOIN ( SELECT t1.place, t1.day, MAX(t1.floor, t1.floor2) AS floor1, MIN(t1.floor, t1.floor2) AS floor2 FROM table t1, table t2 GROUP BY t1.place, t1.day, MAX(t1.floor, t1.floor2), ...
Get rid of a duplicate row from SQL table
[ "", "sql", "sqlite", "" ]
Assume I have two tables as follows, Table A ``` +-------+-------+-------+-------+ | col_a | col_b | col_c | col_d | +-------+-------+-------+-------+ | | | | | +-------+-------+-------+-------+ ``` Table B ``` +-------+-------+-------+-------+ | col_a | col_b | c...
If you don't have a unique key on `col_b, col_c, col_d` of `table_b`, this will result in a violation when copying over. You can identify problematic rows with a query like this: ``` SELECT col_b, col_c, col_d FROM table_b GROUP BY col_b, col_c, col_d HAVING COUNT(*) > 1 ``` A similar query can be run on `table...
If I correctly understand your need, maybe something like this can find the rows that will give problems: ``` select * from table_a a inner join table_b b on (a.col_b = b.col_b and a.col_c = b.col_c and a.col_d = b.col_d and a.col_a != b.col_a ) ```
How to find the record that violate unique key constraint?
[ "", "sql", "oracle", "" ]
Sorry for the title but that was the best way I could think to explain it... Here is my scenario I have a table that stores rows for communications with my clients. Something like this ``` | UserID | CommunicationID ----------------------------- | User1 | com1 | User1 | com2 | ...
Try this: ``` SELECT UserID FROM mytable WHERE CommunicationID IN ('Com1', 'Com2', 'Com3') GROUP BY UserID HAVING COUNT(DISTINCT CommunicationID) = 3 ``` The above query selects the `UserID` values of all users having *all three* `CommunicationID` values, *irrespective* of how many times each distinct `Communication...
This approach uses `WHERE` clauses to treat it as three different elements, joining them to each other. At the end of the join, only those that have survived all three hops will be left in your result set. ``` SELECT DerivedCom3.UserID FROM ( SELECT DISTINCT UserID FROM YourTable WH...
sql, return rows when multiple rows have specific values?
[ "", "sql", "join", "" ]
I am using Postgresql, I created two subqueries that return results as follows: ``` firm_id type_1 fee_1 1 2 100 2 4 300 5 1 100 firm_id type_2 fee_2 1 3 200 2 3 200 3 2 ...
``` SELECT coalesce( t1."firm_id", t2."firm_id" ) as firm_id, coalesce( t1."type_1", 0 ) as type_1, coalesce( t2."type_2", 0 ) as type_2, coalesce( t1."fee_1", 0 ) + coalesce( t2."fee_2", 0 ) as total_fee FROM table1 t1 FULL JOIN table2 t2 ON t1."firm_id" = t2."firm_id" ``` where ta...
Use `FULL JOIN` and `coalesce()`: ``` with q1(firm_id, type_1, fee_1) as ( values (1, 2, 100), (2, 4, 300), (5, 1, 100)), q2 (firm_id, type_2, fee_2) as ( values (1, 3, 200), (2, 3, 200), (3, 2, 150), (4, 5, 300)) select firm_id, coalesce(type_1, 0) type_1, coalesce(...
Merging results from two subqueries Postgresql
[ "", "sql", "postgresql", "" ]
Suppose I have something like ``` CREATE TABLE Foo ( id INT NOT NULL PRIMARY KEY IDENTITY(1,1), . . . ); CREATE TABLE Bar ( . . foo_id INT REFERENCES Foo(id), . . ); ``` Do/should I instead have ``` foo_id INT NOT NULL REFERENCES Foo(id) ``` or is that implicit in the fact that ...
The foreign key column on `Bar` can be `NULL`, if it's possible that a `Bar` record may exist without that value. > the fact that the value it's referencing is guaranteed to be NOT NULL If the value in `Bar` is `NULL` then it's simply not referencing a record in `Foo`. It *can* reference a record, but doesn't have to...
No, it's not necessary and it's by purpose. You can still put a `NULL` value into foreign key and it means that it actually doesn't reference anything.
If a primary key is NOT NULL, then should a foreign key that references it be specified also as NOT NULL?
[ "", "sql", "sql-server", "t-sql", "database-design", "" ]
I'm trying to get the total of votes for each FANOF\_ID (ex: Me). The problem is that a FAN can vote each day for the same FANOF\_ID (ex: David Bowie RIP) So each day I could vote for David Bowie as my favorite singer ``` ID CREATED FAN_ID FANOF_ID 15 2016-01-24 3 3 16 2016-01-25 3 3 17 2016-01-25 2 ...
You want `COUNT(DISTINCT)`. However, you have to be careful about what you are counting (`fan_id`) and what you are aggregating by `(fanof_id`): ``` SELECT fov.fanof_id, COUNT(DISTINCT fov.fan_id) AS total FROM fans_fanofvote fov GROUP BY fov.fanof_id ORDER BY total DESC; ``` Note that table aliases make the q...
You didn't mention expected output earlier so it was confusing. ``` SELECT `fans_fanofvote`.`fanof_id`, COUNT(`fans_fanofvote`.`fan_id`) AS `total` FROM `fans_fanofvote` GROUP BY `fans_fanofvote`.`fanof_id` ORDER BY `total` DESC ```
mySQL statement get last record
[ "", "mysql", "sql", "" ]
Here I have a list of ids provided by one SELECT, and one simple insert example ``` SELECT idUnit FROM dbo.GetUnitsTree(10) INSERT INTO [Profession_Ext] ([FK_Personnal] ,[FK_Profession]) VALUES (50 ,<FK_Profession, int,>) ``` I want the same result that this, but dyna...
> Here I have a dynamic list of int (provided by a SELECT) I would either insert directly from the original `SELECT` if you don't need the results for anything other than the INSERT: ``` INSERT INTO Profession_Ext ([FK_Personnal] ,[FK_Profession]) SELECT {select list here} ``` or change your SELECT to populate a tem...
Write following one Bulk Insertion with Select statement: ``` INSERT INTO [Profession_Ext] ([FK_Personnal] ,[FK_Profession]) SELECT 50 AS [FK_Personnal], tbl.[FK_Profession] FROM ( SELECT 1 AS FK_Profession UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL ...
Multiple insert with one list of int
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have a table like below ``` BILL BILL_DATE TYPE AMOUNT BILL01300002 2016-01-30 15:34:48.957 1 250.00 BILL01300003 2016-01-30 15:38:00.000 5 150.00 BILL01300004 2016-01-30 15:49:48.000 5 200.00 BILL01300002 2016-01-30 16:37:...
``` SELECT *, ( CASE B.BILL WHEN (SELECT A.BILL FROM #TAB AS A WHERE TYPE IN( 1, 2, 3 ) GROUP BY A.BILL HAVING Count(A.BILL) >= 3) THEN amount ELSE 0 END ) AS amount2 FROM #TAB AS B ``` :) Hoping to help...
You can try like this, ``` SELECT *, CASE WHEN ( Count(bill) OVER ( partition BY bill, CONVERT(DATE, bill_date)) ) > 1 AND type IN ( 1, 2, 3 ) THEN coalesce((SELECT amount FROM #TAB ...
How to achive the below scenario in T-SQL
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
So I have a table of items. Each item has a status that can be "daily", "monthly", "yearly", or "outstanding". What I'm trying to do is create a single Activerecord (or SQL) query that arranges the outstanding items first (by created\_at) and then the rest of the items (regardless of their status) by their created\_at...
Firstly, just define a scope like this: ``` class Item < ActiveRecord::Base scope :ordered, -> { joins("LEFT OUTER JOIN ( SELECT id, created_at, status FROM items WHERE items.status = 'outstanding' ) AS temp ON temp.id = items.i...
Though it's not a single query in worst case scenario (2 queries), but it solves your problem: ``` items = Item.where(:status => "outstanding").order('created_at DESC').limit(15) items = (items.size == 15) ? items : items + Item.where('status != ?', "outstanding").order('created_at DESC').limit(15-items.size) ```
Activerecord sort by column and then created_at?
[ "", "sql", "ruby-on-rails", "activerecord", "" ]
Ok so now i have a problem which is when i select the data from table i want to count data and select it the data in this table consist of ``` | Name | Fruits | | Ben | Apple | | Tim | Orange | | Tim | Pear | | Tim | Grape | ``` So here's how want it to be viewed ``` | Name | Fruits Number | | Ben ...
``` SELECT Name, CASE WHEN Count(*) > 2 THEN CONCAT(COUNT(*), ' Have too many fruits') ELSE CAST(COUNT(*) As CHAR) END AS 'Fruits Number' FROM MyTable Group By Name ``` In your fruits example a case should work. Of course you can base it on a sub query and reduce the `COUNT()`'s
This does exactly what you asked for: ``` SELECT name, IF (fruitcount > 1, concat(fruitcount, ' Have too many fruits'), cast(fruitcount as char)) AS 'Fruits number' FROM ( SELECT name, Count(*) as fruitcount FROM fruits_table GROUP BY Name ) AS z; ``` But this is probably a better way to do it,...
How to select and check values of indiviual rows and add text to it data SQL
[ "", "mysql", "sql", "select", "" ]
I am passing a simple query where I am searching for specific rows where `OrderID` is an even number ``` SELECT * FROM Orders WHERE mod(OrderID,2) = 0; ``` Error : > Syntax error (missing operator) in query expression 'mod(OrderID,2) = 0'.
You are not using Oracle, so you should be using the modulus operator: ``` SELECT * FROM Orders where OrderID % 2 = 0; ``` The `MOD()` function exists in Oracle, which is the source of your confusion. Have a look at [this SO question](https://stackoverflow.com/questions/3756928/select-row-if-the-value-2-1-mod) which...
``` SELECT * FROM Orders where OrderID % 2 = 0;///this is for even numbers SELECT * FROM Orders where OrderID % 2 != 0;///this is for odd numbers ```
Select Rows with id having even number
[ "", "sql", "sql-server", "sql-function", "" ]
I have a view and a table that I'm trying to get data out of. My view has basic order information based on an order number. The table I'm getting data out of has very detailed pieces of data based on an order number. When I run the view by itself, I get basic order header information. When I query the table, I get bill...
I attempted the following: ``` SELECT o.ORDER_NUMBER, Description, Price, Quantity, o.ORDER_NUMBER + '-' + COALESCE(dd.Shippment, '') AS [Ship_Set] FROM vw_OrderData o LEFT JOIN DetailData dd ON o.ORDER_NUMBER = dd.ORDER_NUMBER; ``` It returned the same amount of rows because there were multiple line items per...
If it gives you multiple rows, but only need the first one, you could use the `SELECT TOP(1)` option such as : ``` SELECT TOP(1) x.ORDER_NUMBER, Description, Price, Quantity, x.ORDER_NUMBER+'-'+y.Shippment AS [Ship_Set] FROM vw_OrderData AS x join DetailData AS y ON(x.ORDER_NUMBER = y.ORDER_NUMBER) ``` Therefore ...
Grab one row from a table
[ "", "sql", "sql-server", "sql-server-2012", "left-join", "outer-join", "" ]
I have a table like this : ``` id product_property_id product_id amount type 1 1 145 10 0 2 4 145 12 0 3 6 145 13 1 4 23 147 2 0 5 4 145 15 1 6 4 ...
If I understand correctly, this is just a query using conditional aggregation: ``` select product_id, product_property_id, sum(case when type = 1 then amount when type = 0 then - amount else 0 end) as new_amount from likethis group by product_id, product_property_id; `...
This should work: ``` SELECT product_id, product_property_id, SUM(CASE WHEN [type] = 1 THEN amount END) - SUM(CASE WHEN [type] = 0 THEN amount END) new_amount FROM dbo.YourTable WHERE product_id = 145 AND product_property_id = 4 GROUP BY product_id, product_property_id; ```
Minus/Sum a table with itself
[ "", "mysql", "sql", "" ]
So I have a query that looks something like this: ``` SELECT IncidentNumber, ToiletType, ToiletDangers, IncidentDate FROM Core.LostLawsuits ``` ...which returns the following results sort of like this: ``` +----------------+------------+---------------------------+---------------+ | IncidentNumber | To...
A CASE expression would work for your example: ``` case ToiletType when 'A' then 'Automatic Standard' when 'P' then 'Portable Potty' end ``` i.e. ``` SELECT IncidentNumber, case ToiletType when 'A' then 'Automatic Standard' when 'P' then 'Portable Potty' end as ToiletType,...
In this case, I think you want `CASE`: ``` SELECT IncidentNumber, (CASE ToiletType WHEN 'A' THEN 'Automatic Standard' WHEN 'P' THEN 'Portable Potty' ELSE ToiletType END) as ToiletType, ToiletDangers, IncidentDate FROM Core.LostLawsuits; ```
Oracle SQL: Alternative to nested REPLACE() in Select statement?
[ "", "sql", "oracle", "" ]
I have gone through lot of sites to understand normalization but it seems like I have to memorize the rules. After a week or later I forget it and seems like every thing is new for me. Is any better way to understand the first three normal forms. I need some easy practical examples to understand and remember it always...
There is a good explanation [on Dream in Code](http://www.dreamincode.net/forums/topic/179103-relational-database-design-normalization/). For examples, try remembering the most common violations: 1. First and last name in a single field 2. Storing name and price of an item along with the order for that item 3. Storin...
The first nomal form should be clear. **You have atomic values and create redundancy in your table**. At this point it means: Your current primary keys are not longer unique. The 2NF means that you should elimnate redundant data. The attributes **need to be functional dependent to your primary key and not to other non...
How to easily understand normalization - Database
[ "", "sql", "database", "" ]
How can I exclude in sql a datetime and the associated team: I´ve tried this here: ``` IntervalDate not like ('2015-01-10 00:00:00' + 'Team C') ```
you have split the condition as :- ``` IntervalDate not like '2015-01-10 00:00:00' and Team not like 'Team C') ```
As per other comments. I suspect that the "Team C" value resides in a separate column to `IntervalDate` and that `IntervalDate` is an SQL `datetime` (or similar) column. If you can show us your table schema we can suggest what is correct, however it is going to be something like: ``` WHERE (IntervalDate NOT LIKE '2015...
Exclude a datetime and the associated team sql
[ "", "sql", "sql-server", "" ]
I'm playing around on <https://www.documentdb.com/sql/demo>, which allows me to query against sample documents that look like: ``` { "id": "19015", "description": "Snacks, granola bars, hard, plain", "tags": [ { "name": "snacks" } ], "version": 1, "isFromSurvey": false, "foodGroup": "Snacks...
EDIT: ARRAY\_CONTAINS now supports partial match as Jim Scott points out below, which I think is a better answer than this accepted one. You `servings` array only has one entry `{"amount": 1, "description": "bar", "weightInGrams": 21}`. This should work for your example with a single serving: ``` SELECT root FROM ro...
Not sure if this functionality was available when you were looking at the API originally but the [ARRAY\_CONTAINS](https://learn.microsoft.com/en-us/azure/cosmos-db/sql-query-array-contains) now supports an optional Boolean value at the end to provide partial match support. ``` SELECT root FROM root WHERE ARRAY_CONTAI...
DocumentDB SQL with ARRAY_CONTAINS
[ "", "sql", "azure-cosmosdb", "" ]
Can anyone please help me with the query to list all the tables in all the databases in a single server?. Thanks in advance.
AS stated [here](https://dba.stackexchange.com/a/61855/33311) by Try with dynamic query You need a query for each database against `sys.tables`. ``` select 'master' as DatabaseName, T.name collate database_default as TableName from master.sys.tables as T union all select 'tempdb' as DatabaseName, ...
Use `sp_MSforeachdb` to iterate through all databases and `INFORMATION_SCHEMA.TABLES` to query the tables in each: ``` sp_MSforeachdb 'USE [?]; SELECT * FROM INFORMATION_SCHEMA.TABLES' ```
To view all the tables in a database server
[ "", "sql", "sql-server", "" ]
I want to find out the count of people who have rented from 2 stores. THe schema is as below. ``` Rental table ---------------------------------------------------- rental_id int(11) NO PRI rental_date datetime NO MUL inventory_id mediumint(8) unsigned NO MUL customer_id smallint(5) unsigned NO MUL...
``` select count(*) from( select customer_id from rental r , inventory i where r.inventory_id = i.inventory_id group by customer_id having count(distinct i.store_id) = 2); ``` You will have to aggregate you results in the inner query for that matter, So u'll have to rap the query with another o...
You would use two aggregations. The first gets the people who have rented from two stores. The second adds them up. So: ``` select count(*) from (select r.customer_id from rental r join inventory i on r.inventory_id = i.inventory_id group by r.customer_id having count(distinct i...
MySql finding the total count after a group by
[ "", "mysql", "sql", "group-by", "" ]
Suppose we have: ``` CREATE TABLE #Users(id INT PRIMARY KEY, name VARCHAR(100), suggestions XML); INSERT INTO #Users(id, name, suggestions) SELECT 1, 'Bob', N'<Products> <Product id="1" score="1"/> <Product id="2" score="5"/> <Product id="3" score="4"/> ...
After trying around a while I think this is not possible... There is similar question here: [XQuery adding or replacing attribute in single SQL update command](https://stackoverflow.com/q/3854308/5089204) The `.modify(insert Expression1 ... )` does not allow to get data **within** an XML passed in via `@sql:variable(...
Try something like this,it is easy to understand ,but it is lengthy. Let me know,if you have any problem. ``` declare @Users TABLE(id INT PRIMARY KEY, name VARCHAR(100), suggestions XML); INSERT INTO @Users(id, name, suggestions) SELECT 1, 'Bob', N'<Products> <Product id="1" score="1"/> ...
SQL Server - merge two XML using only .modify()
[ "", "sql", "sql-server", "xml", "t-sql", "xpath", "" ]
It is often convenient in PosgreSQL to create "tables" on the fly so to refer to them, e.g. ``` with selected_ids as ( select 1 as id ) select * from someTable where id = (select id from selected_ids) ``` Is it impossible to provide multiple values as `id` this way? I found [this answer](https://stackoverflow.com/q...
You can use arguments in the query alias: ``` with selected_ids(id) as ( values (1), (3), (5) ) select * from someTable where id = any (select id from selected_ids) ``` You can also use `join` instead of a subquery, example: ``` create table some_table (id int, str text); insert into some_table values (1, 'alfa'...
You can pass `id` and `animal` field in WITH like this ``` with selected_ids(id,animal) as ( values (1,'dog'), (2,'cat'), (3,'elephant'),(4,'rat')--,..,.. etc ) select * from someTable where id = any (select id from selected_ids) ```
Creating tables on-the-fly
[ "", "sql", "postgresql", "" ]
I have a table like so: ``` DECLARE @deadCommunityList TABLE (community VARCHAR(12)) INSERT INTO @deadCommunityList (community) VALUES ('000') , ('253'), ('COU'), ('COV') , ('D2T'), ('D3T'), ('DEW') , ('DIT'), ('E2T'), ('E3T') , ('EL2'), ('EL3'), ('ELC') , ('ELI'), ('ELT'), ('ERI') , ('FA1'), (...
Try this: ``` SELECT DISTINCT AREA_DESC FROM V_CONSTAT_PROJ_DATES WHERE AREA_ID NOT IN (SELECT community FROM @deadCommunityList) ORDER BY AREA_DESC ``` `@deadCommunityList` is a *table* variable, so you have to `SELECT` from its values.
``` DECLARE @deadCommunityList TABLE ( community VARCHAR(12) PRIMARY KEY --WITH (IGNORE_DUP_KEY=ON) ) INSERT INTO @deadCommunityList ... SELECT DISTINCT AREA_DESC FROM V_CONSTAT_PROJ_DATES WHERE AREA_ID NOT IN (SELECT e.community FROM @deadCommunityList е) ORDER BY AREA_DESC --OPTION(RECOMPILE) ```
SQL Stored Procedure WHERE item is not in table
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I got two sql statements: ``` SELECT username AS userA FROM WHERE username='abc' SELECT username AS userB FROM WHERE username='abcd' AND password='abcd' ``` I want to output the result as below: ``` userA | userB ---------------- abc | abcd ``` How to combine two SQL statements?
``` SELECT tableA.username as userA tableB.username as userB FROM tableA CROSS JOIN table B WHERE tableA.username='abc' AND tableB.username='abcd' AND tableB.password='abcd'; ``` CROSS JOIN! :P CARTESIAN PRODUCT!
You can combine tables and fields with the syntax: ``` SELECT tableA.username as userA tableB.username as userB FROM tableA JOIN table B WHERE tableA.username='abc' AND tableB.username='abcd' AND tableB.password='abcd'; ``` Unless there's some kind of relation between the tables, you'll be getting the cro...
SQL to make new column(mySQL)
[ "", "mysql", "sql", "" ]
I have three tables like below. ``` Courses: Id Name 1 A 2 B 3 C 4 D Prices: Id CId Price 1 1 200 2 2 150 3 3 500 4 4 300 Payment: Id CId 1 1 2 4 ``` If a record of payment for Course record exists, then Price should be -1. I want to get result like below: ``` Id Name Price 1 A -1 2...
Try This ``` SELECT c.Id, c.name, CASE WHEN pa.id IS NOT NULL THEN -1 ELSE pr.price END as Price FROM Courses c LEFT JOIN Prices pr ON c.Id = pr.CId LEFT JOIN Payment pa ON c.id = pa.CId; ``` OR ``` SELECT c.Id, c.name, CASE WHEN pa.id IS NULL THEN pr.price ELSE -1 END as Price FROM Courses c LEFT JOIN Prices pr...
SELECT p.id,c.NAME, CASE WHEN p.cid=e.cid THEN -1 ELSE p.price END AS price FROM prices p LEFT JOIN courses c ON c.id=p.ID LEFT JOIN payment e ON p.cid=e.cid
Joining three table in mysql
[ "", "mysql", "sql", "database", "" ]
I am working on a project and I realized I am unsure about how to use multiple primary keys. I have a table named "User\_Details" that has the details of Customer ID, email address and password. From my understanding, I can use both Customer ID and email address as the primary key. In this case do I use only one as Pri...
You can only have one primary key, but you could definitely have other unique fields. Usually using an integer / id as primary key is preferred over a string key, and an id is presumably auto assigned, where as email could change - which would be a problem for foreign key relations. Since you already use customer Id ...
You can only have one primary key, but you can have multiple columns in your primary key, alternatively you can also have Unique Indexes on your table, which will work a bit like a primary key in that they will enforce unique values, and will speed up querying of those values. Easiest way tho is a **Composite Primary ...
Two primary non composite keys in a table
[ "", "mysql", "sql", "rdbms", "" ]
Is there a way to inner join two different Excel spreadsheets using VLOOKUP? In SQL, I would do it this way: ``` SELECT id, name FROM Sheet1 INNER JOIN Sheet2 ON Sheet1.id = Sheet2.id; ``` Sheet1: ``` +----+------+ | ID | Name | +----+------+ | 1 | A | | 2 | B | | 3 | C | | 4 | D | +----+------+ ```...
First lets get a list of values that exist in both tables. If you are using excel 2010 or later then in Sheet 3 A2 put the following formula: ``` =IFERROR(AGGREGATE(15,6,Sheet2!$A$1:$A$5000/(COUNTIF(Sheet1!$A$1:$A$5000,Sheet2!$A$1:$A$5000)>0),ROW(1:1)),"") ``` If you are using 2007 or earlier then use this array form...
You can acheive this result using Microsoft Query. First, select `Data > From other sources > From Microsoft Query` [![enter image description here](https://i.stack.imgur.com/o8CpQ.png)](https://i.stack.imgur.com/o8CpQ.png) Then select "Excel Files\*". In the "Select Workbook" windows, you have to select the curren...
How to inner-join in Excel (eg. using VLOOKUP)
[ "", "sql", "excel", "inner-join", "vlookup", "" ]
Normally we use a column to filter a sql sentence ``` SELECT col_id, col_name FROM dataTable WHERE col__id>5 ``` It is possible use a position to ORDER: `ORDER BY 1 DESC` Is it possible use a position to filter?? Something like "this": ``` SELECT col_id, col_name FROM dataTable WHERE #2 LIKE '%Peter%' ```
No. The `WHERE` clause is (logically) evaluated before the `SELECT` list, so it cannot refer to `SELECT` list items by number, as they haven't been numbered yet. It's possible to do it in the `ORDER BY` as that's evaluated *after* the list of selected columns is evaluated, so you can refer to columns by number (though...
**WHERE** Clause run before select clause here is Logical Query Flow 1. [From] 2. [Where] 3. [Aggregations] 4. [SELECT] 5. [Order By] 6. [Over] 7. [Distinct] 8. [Top] [FOR EXAMPLE](http://sqlearth.blogspot.in/2015/05/how-sql-select-statement-logically-works.html)
Is it possible to SELECT sqlserver data using WHERE with position?
[ "", "sql", "sql-server", "" ]
I have a requirement where I have to show data in cumulative concatenation style, just like running total by group. Sample data ``` Col1 Col2 1 a 1 b 2 c 2 d 2 e ``` Expected output: ``` Col1 Col2 1 a 1 b,a 2 c 2 d,c 2 e,d,c ``` The concatenation ...
Assuming something on the way you need to order, this can be a solution, based on [Hierarchical Queries](https://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm): ``` with test as ( select 1 as col1, 'a' as col2 from dual union all select 1 as col1, 'b' as col2 from dual union all s...
Try: ``` WITH d AS ( select col1, col2, row_number() over (partition by col1 order by col2) as x from tab_le ), d1( col1, col2, x, col22) as ( SELECT col1, col2, x, col2 col22 FROM d WHERE x = 1 UNION ALL SELECT d.col1, d.col2, d.x, d.col2 || ',' || d1.col22 FROM d JOIN d1 ON (d.col1 = d1...
Cumulative string concatenation
[ "", "sql", "oracle", "" ]
I have a data-set with a timestamp column and multiple identifier columns. I want to condense it to a single row for each "block" of adjacent rows with equal identifiers, when ordered by the timestamp. The min and max timestamp for each block is required. Source Data: ``` TSTAMP ID1 ID2 t1 A B <= start of ...
You can use [an analytic 'trick'](https://stackoverflow.com/questions/4324623/sql-group-by-only-rows-which-are-in-sequence/4324654#4324654) to identify the gaps and islands, comparing the position of each row just against the `tstamp` across all rows with its position against `tstamp` just for that `id2, id2` combinati...
[Tabibitosan](http://rwijk.blogspot.com/2014/01/tabibitosan.html) to the rescue! ``` with sample_data as (select 't1' tstamp, 'A' id1, 'B' id2 from dual union all select 't2' tstamp, 'A' id1, 'B' id2 from dual union all select 't3' tstamp, 'C' id1, 'D' id2 from dual union all ...
Oracle 11.2 SQL - help to condense data in ordered set
[ "", "sql", "oracle", "gaps-and-islands", "" ]
I Have Table ( **emp** ): [![emp Table](https://i.stack.imgur.com/7E6BF.png)](https://i.stack.imgur.com/7E6BF.png) I want to get **First Column** * **DeptNo** Second Column * **SUM of salaries of the employees of each department whose name start with 'A'** and Third column * **Total Salaries of all the employees...
If your DBMS supports `CASE`, you can do something like this: ``` select deptno, sum(case when ename like 'A%' then salary else 0 end) as ASalary, sum(salary) as AllSalaries from emp group by deptno ``` This produces ``` deptno ASalary AllSalaries ------ ------- ----------- 10 300 500 12 ...
You can do it with a subquery: ``` SELECT DeptNo, SUM(Salary) AS 'Name Contains A', (SELECT SUM(Salary) FROM emp) AS 'Total Salary' FROM emp WHERE Ename LIKE 'A%' GROUP BY DeptNo ```
How to Get Sum of Specific Records and Sum of all Records in One Query?
[ "", "mysql", "sql", "database", "" ]
This static query using a parameter returns one row: ``` DECLARE @sqltext nvarchar(max) DECLARE @status varchar(100) SET @status = 'Active: Complete' select * from status where StatusTitle = @status and type_id = 800 ``` --- However, using the parameter in a dynamic SQL query as follows does not return any rows at ...
You need to format the `@status` into the statement. Executing a statement using `sp_executesql` creates a new scope and local variables from another scope will not be visible. In your statement you can remedy this by adding extra quotes around `@status`. But to guard against SQL injection, you first need to replace s...
this will also save you from sql injection ``` DECLARE @sqltext nvarchar(max) DECLARE @status varchar(100) SET @status = 'Active: Complete' SET @sqltext = 'SELECT s.StatusID FROM [Status] s WHERE ( ( s.StatusTitle = @status ) AND s.[type_id] = 800 )' DECLARE @params NVARCHAR(99) SET @params = '@status nvarchar(99...
Using local variable inside dynamic SQL does not work
[ "", "sql", "sql-server", "dynamic-sql", "" ]
I have 2 tables :- `Movies(movieID,movieTitle,Director)` and `Rating(ratingID,movieID,movieRating,ratingDate)` Now i write the following syntax to be queried on these Tables - `SELECT movieTitle,max(movieRating) FROM Movie M,Rating R WHERE R.movieID = M.movieID GROUPBY R.movieID;` What i would like to ask is: Pr...
GROUP BY will group records and return distinct values. In your case, the records all share the same movie title and id. The only distinct value is the rating, and you're requesting the max, not the actual ratings associated with each record. Compare your result to the result from: ``` SELECT R.movieTitle,M.movieRati...
You're grouping by the `movieID`, which means that you'll get only one row for each `movieID` with all aggregates rolled up to those groups. If those rows had the same `movieTitle`, but some rows had different `movieID` values then you would see multiple rows, but that's a quirk in MySQL. I believe that most RDBMSs wil...
How does an aggregate function affect the columns queried along with it?
[ "", "mysql", "sql", "database", "" ]
The problem is that i have a table Employee in which a field employeeAddress(varchar(200)), I m creating a View EmployeeView in SQL Server and i want to change it to the employeeAddress(varchar(50)), means i want to show only 50 characters of employeeAddress column and after that concatenate with '...'. For Example :-...
Most of the existing answers seem to be missing the need for the conditional ellipsis: ``` CREATE VIEW dbo.EmployeeView WITH SCHEMABINDING AS SELECT /* Other Columns */ CASE WHEN LEN(EmployeeAddress) > 50 THEN SUBSTRING(EmployeeAddress,1,50) + '...' ELSE EmployeeAddr...
You can try this ``` create view DemoView as select name=SUBSTRING(name,1,50)+'...' from tableName; ```
How to change the size of a column in a view dynamically
[ "", "sql", "sql-server", "" ]
I have a sql table named Parentids of ids and their parent's id (where 0 represents no parent) like follows: ``` id | parentid -------------- 1 | 0 2 | 0 3 | 1 4 | 0 5 | 2 6 | 2 7 | 3 8 | 1 ``` From this table I need to a sql query to return a table with the number of children for each id that...
You could do it with **group by** on parentId, Only members with children: ``` select parentId, COUNT(*) from Parentids where parentId <> 0 group by parentId ``` **EDIT:** All members, to match exact OP expected result: ``` select parentId, COUNT(*) from Parentids group by parentId orde...
One method is using a `left join` and aggregation. However, a correlated subquery might even work better: ``` select p.id, (select count(*) from parentids p2 where p2.parentid = p.id ) as childrenCnt from parentids p; ```
sql hierarchy count
[ "", "mysql", "sql", "sum", "hierarchy", "" ]
I have a report that has multiple multi-value parameter. What I wanted to do is if the parameter is = Select All I'll remove that parameter to my SQL Script. Example is I have a Product group and Product Name parameter and what I want is if the user selects all the product group my script will be like: ``` SELECT * FR...
As far as I know, you cannot detect when "Select All" has been checked by the user. To remove the filter completely when the user selects all the choices in a multi-valued parameter you would have to employ logic in your stored procedure that checks to see if all the choices were passed to it in the parameter, and if ...
You can add your own `ALL` value to the parameter. In the dataset query check if the user have selected 'ALL' if so don't use the parameter. Something like this: ``` IF ('ALL' IN @ProductGroup) BEGIN SELECT * FROM TABLE WHERE PRODUCT_NAME IN (@ProductName) END ELSE SELECT * FROM TABLE WHERE PRODUCT_NAME IN (@Pro...
SSRS: When Multi-value Parameter = Select ALL remove filter in Script
[ "", "sql", "sql-server", "reporting-services", "ssrs-2012", "" ]
Good Afternoon, Currently I have functioning code that works for determine the number of opened work orders and the number of closed work orders during a period of time. I now want to add the number of work orders that were opened prior to that period of time; I have the code that produces the results I want but I am ...
Try using a sub select. I also had to CONVERT the dates to be able to compare them to o.dateinfo. This way you don't have to manually build the dates since they already exist in dateinfo. ``` SELECT o.dateinfo , (SELECT COUNT(*) FROM wkaw WHERE (CONVERT(CHAR(6), cmpl_date, 112) >= o.dateinfo OR cmpl_date IS NULL) ...
You could make a table that stores all the start-of-month dates you need. (This could either be a utility table that you generate once, or it could be a temp table that gets generated on the fly.) In your case we can probably cheat a little. **As long as each month has at least one work order in it** we can use the wo...
Unsure how to do multiple nested SELECT statements while using GROUP BY
[ "", "sql", "sql-server", "" ]
I am strugling forming a query to accomplish what I need using LEFT JOIN. I'm afraid that I'm going about this the wrong way, so I reach out to the community. I have two databases, one for **categories** and one for **items** as follows ``` CATEGORIES id name private 1 Apples 1 2 O...
``` select c.* from categories c, (select distinct category from items) i where c.id = i.category and c.private = 1 ```
What you need is `INNER JOIN` and `DISTINCT` ``` SELECT DISTINCT name FROM CATEGORIES INNER JOIN ITEMS ON CATEGORIES.id=ITEMS.category WHERE CATEGORIES.private=1 ```
How to form a query across two tables
[ "", "mysql", "sql", "" ]
``` BREAK ON DEPTNO SKIP 1 compute sum of sal on deptno SELECT deptno, empno, ename,sal FROM (SELECT deptno, empno, ename, sal FROM emp ) WHERE EXISTS (SELECT deptno FROM dept) order by 1,2 , sal desc ; ``` How can I get two highest sal from emp, and what is wrong with my code?
It is not entirely clear what you want. In the title you say "two highest salary", but in the comment you mention something about a sum. The following will show the two highest salaries. If there are multiple "highest" salaries, all will be shown ``` select deptno, empno, ename, sal from ( SELECT deptno, empno, ena...
If you want all rows with the two highest distinct salaries in each department, then use `dense_rank()` as follows: ``` select deptno, empno, ename, sal from (select e.*, dense_rank() over (partition by deptno, order by sal desc) as seqnum from emp e ) e where seqnum <= 2 order by deptno, sal ...
How to get two highest salary in emp table?
[ "", "sql", "oracle", "rownum", "" ]
I have 10 columns (items) in one table, 10 in another table. I want to identify cases where any one of the columns/items in the one table match any one of the columns/items in the other table. My code below is for three items and is inefficient - how can it be modified for 10 columns/items? ``` CASE WHEN (t1.[ite...
I don't know if this is more efficient, but it's simpler to write: Use IN instead of equality test. e.g., ``` WHEN t1.item1 IN (T2.item1, T2.item2, T2.item3) ``` For a more efficient way, (but more involved process) use UNPIVOT to convert each column value into a separate row for each table. If the new tables are onl...
If you do not want to normalize the table you can use "IN" syntax and generate case condition in program: ``` SELECT tbl1.id, tbl1.a, tbl1.b, tbl1.c, MAX(CASE WHEN tbl1.a IN (tbl2.a,tbl2.b,tbl2.c) OR tbl1.b IN (tbl2.a,tbl2.b,tbl2.c) OR tbl1.c IN (tbl2.a,tbl2.b,tbl2.c) THEN 1 ELSE 0 END) AS match FROM (VALUES (1,1,...
SQL Server : CASE when any of 10 columns agree
[ "", "sql", "sql-server-2008", "case", "" ]
I have a workers table and an associated workerGeofence table. ``` CREATE TABLE IF NOT EXISTS `workergeofences` ( `ID` int(11) NOT NULL, `WorkerID` varchar(20) NOT NULL, `GeofenceID` int(11) NOT NULL, `isActive` tinyint(4) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=107 DEFAULT CHARSET=latin1; ``` I need to return ...
First of all , your join is wrong! you are not comparing any common column on both table, you should add where workerGeofences.workerID = w.id like this: ``` SELECT w.ID, Title, FName, SName, Email, Birthday, Address, Phone, description, companyID FROM Workers w join workerGeofences WHERE worke...
You are on the right track, but you shouldn't need `select distinct`. This slows down queries, unless you know there are duplicates -- and that is unlikely because you are selecting `WOrkers.Id`. ``` SELECT w.* FROM Workers w WHERE w.companyID = ? AND EXISTS (SELECT 1 FROM workerGeofences wg ...
optimise IN subquery
[ "", "mysql", "sql", "join", "query-optimization", "in-subquery", "" ]
I have a field in our SQL Server database that is basically two fields concatenated together. It has a descriptor and a number. I want to build a view with just the number so that I can relate it to other tables. The number is actually typed as a nvarchar on the other tables. So from data like this I want to query for ...
If your prefix is always `tst_desc:` then you can simply strip it off with `replace`: ``` select replace(ProgramField, 'tst_desc:', '') as ProgramNum from yourTable ``` If prefix can be different but always separated from value with colon, you can use something like: ``` select right(ProgramField, len(Progra...
Easiest way is using STUFF ``` SELECT STUFF(ProgramField, 1, charindex(':', ProgramField), '') FROM yourtable ``` If you have dirty data with more than one colon in some row or colon is missing, you can search from right to left for the first none numeric character, you could use this method, This can handle all sort...
How to De-Concatenate a Field
[ "", "sql", "sql-server", "t-sql", "" ]
I tried to write a SQL function in OrientDB to do inserts on a table `Feature`. The function body looks like this and it accepts two parameters `w` and `t`. `insert into Feature (weight, title) values (w, t) return @rid` When I execute this function with the parameters specified as `12` and `some title` the response ...
You can use this query ``` insert into Feature (weight, title) values (:w, :t) return @rid ```
I think you executed the command `insert into Feature (weight, title) values (w, t) return @rid` but you forgot to insert the quotes when you pass the parameters w and t. Try this code: ``` var g=orient.getGraph(); var ins = g.command('sql','insert into Feature (weight, title) values ('+w+', "'+t+'")'); return ins; ...
OrientDB SQL function parameter values are not accessible inside the function body
[ "", "sql", "function", "orientdb", "" ]
I have a data that looks like this: ![table1](https://s23.postimg.org/3laz5cit7/row_num.png) What I want is to have a row number that is group by GroupCode,Group Description,SubGroup and subgroup class and I want to retain the ordering by account code that will look like this: ![table2](https://s17.postimg.org/cjie8gv...
You are looking for `dense_rank()`: ``` select dense_rank() over (order by GroupCode, GroupDescription, SubGroup) . . . ``` However, this doesn't guarantee the ordering by `accountCode`. That will require more work. First, determine the minimum account code for each grouping, then use `dense_rank()` on that: ``` sel...
You're looking for the `DENSE_RANK` window function: ``` SELECT rn = DENSE_RANK() OVER(ORDER BY GroupCode, GroupDescription, SubgroupClass), * FROM tbl ORDER BY rn, AccountCode ```
ROW_NUMBER and Grouping of data
[ "", "sql", "sql-server", "" ]
How to Split SQL string with (# and ;)? Billing Column where string is saved in below format ``` 548784545S#15/01/2016;84854555545#13/01/2016;45454554545#21/01/2016 ``` Split # and ; I want below format ``` 548784545S 15/01/2016 84854555545 13/01/2016 45454554545 21/01/2016 ``` So Far what i did ``` SELECT S...
``` DECLARE @t VARCHAR(MAX) = '548784545S#15/01/2016;84854555545#13/01/2016;45454554545#21/01/2016' ;WITH cte AS ( SELECT x = CONVERT(XML,'<p>' + REPLACE(@t, ';', '</p><p>') + '</p>') ) SELECT PARSENAME(val, 2), PARSENAME(val, 1) FROM ( SELECT val = REPLACE(t.c.value('.', 'VARCHAR(MAX)'), '#', '.') FROM ct...
First create a `Table valued` function to split the string with a delimiter of `;`. **Function : fn\_Split** ``` CREATE FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20) = ' ') RETURNS @Strings TABLE ( position int IDENTITY PRIMARY KEY, value varchar(8000) ) AS BEGIN DECLARE @index int S...
Split Multipile delimiter from SQL String
[ "", "sql", "sql-server", "" ]
I am currently having to use two different queries to get back the results that I'm looking for. I have tried combining the two queries together, but that ends with me getting a large amount of extra(duplicates) data that I do not need. Below I have the working query listed. ``` SELECT p1.note as Itemcode, ...
if you don't want duplicates use a Union in between them, move you order by clause to the bottom of the second one. Make sure you select columns are in the same order in both statements. ``` select (your columns) From (tables and joins) where (your where) UNION select (your columns) From (tables and joins) where (yo...
Per chatroom clarification, I have come up with the the following for you to start with and minimally adjust as needed. ``` SELECT u.id_unit, u.count as TotalUnits, u.group as BatchNo, p1.ID_PieceOrder as Piece1Order, p1Cut.ID_Process as Piece1CutProcessID, i1Cut.Count as Item1Cut...
SQL join in the where statement
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have a Table With the below data ``` Table X Seq_no A Claim Payment Balance (to be calculated) 1 abc 100 10 90 (100-10) 2 abc 50 40 (90-50) 3 abc 20 20 (40-20) 1 xyz 150 10 140 (150-10) 1 ...
You cannot reference balance before create it. You can use a "running sum" for what you want to achieve. Notice that I partitioned by A because you want another balance for every A. ``` Select Seq_no, a, Claim, Payment, sum(nvl(claim,0) - payment) over (partition by A order by seq_no) as Balance from X; ```...
In order to use `balance` as a column identifier, you must go one level deep, i.e. make your existing query as a **sub-query**. **Working demo:** ``` SQL> WITH sample_data AS( 2 SELECT 1 Seq_no, 'abc' A, 100 Claim, 10 Payment FROM dual UNION ALL 3 SELECT 2 Seq_no, 'abc' A, NULL Claim, 50 FROM dual UNION ALL 4...
SQL: Difference in amounts between rows and columns
[ "", "sql", "database", "oracle", "" ]
I was going through the different commands in SQL and I came across `ALTER` command which is referred as DDL (Data Definition Language). We can alter the column and values in it, so we can manipulate the data with this command so why does alter command is not referred as DML (Data Manipulation Language). I have google...
`ALTER` command is used to alter the *structure* of the database. And this is what DDL does, i.e. DDL statements are used to define the *database structure* or *schema*. Whereas DML statement is used to manage *data within schema* objects.
DDL - alter the *schema*. This including creating tables, renaming columns, dropping views, etc. Such statements are DDL even though such might create (default value), alter (by conversion), or even lose (removed column) data as part of the process. Basically, any `CREATE/DROP/ALTER` command is DDL. DML - alter the *...
Why ALTER command is referred as DDL and not DML?
[ "", "sql", "ddl", "alter", "dml", "" ]
I want to get some data from my database for the past 31 days. When column 'finalized' is NULL I want to get data from column 'today', but if column 'finalized' isn't NULL I want to get data from column 'finalized'. I always want to get the last entered row. TABLE MyEarnings ``` id INT(11) AI date dat...
You need conditional aggregation, but it is a bit tricky. I think this does what you want: ``` SELECT DATE_FORMAT(date, '%Y-%m-%d'), COALESCE(MAX(finalized), MAX(today)) as earn FROM MyEarnings GROUP BY DATE_FORMAT(date, '%Y-%m-%d') ORDER BY date ASC LIMIT 0 , 31; ``` This returns the maximum value of `today`...
use `CASE` `WHEN` like this: ``` CASE WHEN finalized IS NULL THEN today ELSE finalized END AS earn ``` Replace query: ``` SELECT date, (CASE WHEN finalized IS NULL THEN today ELSE finalized END; ) AS earn FROM MyEarnings GROUP ...
Trouble with SELECT CASE
[ "", "mysql", "sql", "select", "case", "" ]
I am trying to setup an Offset and Limit, I have tried the following: ``` SELECT [Job_No] , ROW_NUMBER() OVER (ORDER BY [Job_No]) AS [rownumber] , [BaselineStart] , [BaselineFinish] , [ExpectedStart] , [ExpectedFinish] , [ScheduledStart] , [ScheduledFinish] , [ActualStart] , [ActualFinish] FROM ...
You should add another step to your query. `ROW_NUMBER()` can't be used in the same query in which you define it, so you have to wrap it all in another select like below. The where clause relates to all the fields in the `FROM` table/query, so rownumber doesn't exist yet. ``` select * from (SELECT Job_No, ROW_...
In SQL 2012+ you can use the new [OFFSET and FETCH NEXT](http://sqlmag.com/sql-server-2012/using-new-offset-and-fetch-next-options) arguments in the `ORDER BY` clause: ``` SELECT Columns FROM MyTable ORDER BY SomeColumn OFFSET 10 ROWS --this means start with row 11 FETCH NEXT 10 ROWS ONLY --this means limit the resul...
SQL Server OFFSET and LIMIT
[ "", "sql", "sql-server", "" ]
My table in SQL is like:- ``` RN Name value1 value2 Timestamp 1 Mark 110 210 20160119 1 Mark 106 205 20160115 1 Mark 103 201 20160112 2 Steve 120 220 20151218 2 Steve 111 210 20151210 2 Steve 104 206 20151203 ``` Desired Output:- ``` RN...
I've assumed that RN and Name are linked here. It's a bit messy, but if each RN always has 3 values and you always want to check them in this order, then something like this should work. ``` SELECT t1.Name , AVG(CASE WHEN table_ranked.Rank = 1 THEN table_ranked.value1 ELSE NULL END) - AVG(CASE WHEN table_ranke...
There are other answers here, but I think your problem is calling for [analytic functions](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions004.htm#SQLRF06174), specifically [LAG()](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions082.htm#SQLRF00652): ``` select rn, name, -- cal...
Difference between the values of multiple rows in SQL
[ "", "sql", "oracle", "difference", "window-functions", "oracle-analytics", "" ]
I have **ONLY 1** table called `Meeting` that stores all meeting requests. This table can be **EMPTY**. It has several columns including **requestType** (which can only be "MT") **meetingStatus** (can only be either `pending`, `approved`, `denied` or `canceled`) and **meetingCreatedTime** I want to count how many req...
``` SELECT RT.requestType, SUM(CASE WHEN M.meetingStatus = 'Approved' THEN 1 ELSE 0 END) AS Approved, SUM(CASE WHEN M.meetingStatus = 'Pending' THEN 1 ELSE 0 END) AS Pending, SUM(CASE WHEN M.meetingStatus = 'Canceled' THEN 1 ELSE 0 END) AS Canceled, SUM(CASE WHEN M.meetingStatus = 'Denied' THEN 1 EL...
This is one possible approach to force one line to be visible in any case. Adapt this to your needs... Copy it into an empty query window and execute... play around with the WHERE part... ``` DECLARE @Test TABLE (ID INT IDENTITY, GroupingKey VARCHAR(100)); INSERT INTO @Test VALUES ('a'),('a'),('b'); SELECT TOP 1 tb...
How to show 0 value using COUNT and SELECTon a SQL query
[ "", "sql", "sql-server", "count", "" ]
I have a table like this: ``` id unit 1 mm 2 cm 3 kg ``` When I perform pivot operation on this, I am getting result as follows: ``` 1 2 3 mm cm kg ``` Is it possible to get custom column names here, something like this: ``` d1 d2 d3 mm cm kg ``` I am using Pivot for this as: ``` IF OBJECT_ID('te...
``` IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t GO CREATE TABLE #t ( id VARCHAR(10), unit VARCHAR(100) ) INSERT INTO #t (id, unit) VALUES ('1', 'kg'), ('2', 'cm'), ('3', 'mm'), ('4', 'mm') DECLARE @SQL NVARCHAR(MAX), @columns NVARCHAR(MAX) SELECT @columns = STUFF(( SELECT ',[...
Just add a prefix to your ID. Example ``` SELECT @statement = 'select * INTO ##temp from ( SELECT [id] = ''d''+id,[unit] FROM #t ) as s PIVOT (max(unit) FOR id in(' + @columns + ')) as pvt ' ``` Also it's terrible practice to use global temp tables! Esp...
How to provide custom name to column in pivoting
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "pivot", "" ]
I have two tables, say `Table1` and `Table2` **Table1** ``` ╔════╦════╗ ║ ID ║ RN ║ ╠════╬════╣ ║ 11 ║ 1 ║ ║ 12 ║ 2 ║ ║ 13 ║ 3 ║ ║ 14 ║ 4 ║ ║ 15 ║ 5 ║ ║ 16 ║ 6 ║ ║ 17 ║ 7 ║ ║ 18 ║ 8 ║ ║ 19 ║ 9 ║ ║ 10 ║ 10 ║ ╚════╩════╝ ``` **Table2** ``` ╔════╦════════╦══════╗ ║ ID ║ FromRN ║ ToRN ║ ╠════╬════════╬══════╣ ...
You can do an `INNER JOIN` of the two tables to filter out those records from `Table1` whose `RN` values do not fall into any range in `Table2`: ``` SELECT t1.ID, t1.RN FROM Table1 t1 INNER JOIN Table2 t2 ON t1.RN >= t2.FromRN AND t1.RN <= t2.ToRN ``` Follow the link below for a running demo (courtesy of the OP):...
You can try this: ``` select t1.Id, t1.RN from table1 t1 inner join table2 t2 on t1.Rn between t2.FromRn and t2.ToRn ```
Select Records between Range from another table
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm exectuting command on large table. It has around 7 millons rows. Command is like this: ``` select * from mytable; ``` Now I'm restriting the number of rows to around 3 millons. I'm using this command: ``` select * from mytable where timest > add_months( sysdate, -12*4 ) ``` I have an index on timest column. Bu...
using an index for 3 out of 7 mio. of rows would most probably be even more expensive, so oracle makes a full table scan for both queries, which is IMO correct. You may try to do parallel FTS (Full Table Scan) - it should be faster, BUT it will put your Oracle server under higher load, so don't do it on heavy loaded m...
To select a *very small number of records from a table use index*. To select a **non-trivial part use partitioning**. In your case an effective acces would be enabled with range partitioning on `timest` column. The big advantage is that only relevant partitions are accessed. Here an exammple ``` create table test(t...
Performance of a sql query
[ "", "sql", "oracle", "performance", "oracle11g", "" ]
I have this 2 tables ``` Items ID Type ClientID ======================== 1 0 123 2 0 123 Texts ItemID Language Text ================================ 1 Eng Hi there! 1 Spa Holla! 2 Eng bye! 2 Spa bye in Sp...
I don't see why a join is necessary. You can just use conditional aggregation: ``` select t.itemid, max(case when t.language = 'Eng' then t.text end) as Eng, max(case when t.language = 'Spa' then t.text end) as Spa from texts t group by t.itemid; ```
Use nesting to make two joins on same table with a filter (where clause) . Below i have tested on MySQL ``` SELECT i.id, eng_table.text AS eng, spa_table.text AS spa FROM i LEFT OUTER JOIN (SELECT ItemID AS ID, Text FROM t WHERE Language = 'ENG') AS eng_table ON i....
SQL combine relationship table as separate columns
[ "", "sql", "sql-server", "" ]
Like the title says, I am trying to do a SELECT statement where I am selecting 1 specific record (the one the person searched for) but I also want to get 5 records (the 5 that come before and after the specific one) to the right and left of the specific searched record, while keeping the current/focused record on the s...
For a table named [MyTable] ``` ID -------- 16020493 16020494 16020495 16020496 16020497 16020498 16020499 16020500 16030001 16030002 16030003 16030004 16030005 16030006 16030007 ``` we can get the starting ID of the range centred around ID=16020500 by using the query ``` SELECT MIN(ID) AS StartID FROM ( ...
I have to imagine this is won't be fast though it is a fairly elegant way to think about the problem. This was more common when `top` didn't exist. The initial filter should help restrict the search to a window of ids around the previous two months (assuming there are always at least five records in a month). ``` sele...
Is there a (effective) way to get 5 records to the left and right of a specific record with Access SQL?
[ "", "sql", "vba", "ms-access", "" ]
I have a table that contains many rows such as: ``` id file ----------------------------------- 1 7-Zip Portable 4.42 2 7-Zip Portable 4.42 Rev 2 3 7-Zip Portable 4.57 4 7-Zip Portable 4.62 5 7-Zip Portable 4.64 6 SeaMonkey Portable 2.35 7 SeaMonkey Portable 3 8 ...
I got an answer ``` SELECT * FROM `post` WHERE `title` LIKE '%7-Zip%' OR '%Portable%' OR '%4.42%' ```
You could use `LIKE` ``` SELECT * FROM table_name WHERE file LIKE '7-Zip Portable%' ```
How to find related rows in sql
[ "", "sql", "" ]
[![enter image description here](https://i.stack.imgur.com/q6UiH.png)](https://i.stack.imgur.com/q6UiH.png) I want all item\_nos not present in location 100, THat is 1003,1005,1006,1007. What would be the query? WHat I was trying ``` Select distinct item_no from location where location_no not in (100) ``` But this...
You can use `group by` and `having` for this: ``` select l.item_no from location l group by l.item_no having sum(case when l.location = 100 then 1 else 0 end) = 0; ``` The `having` clause counts the number of times each item is in location 100. The `= 0` specifies that it is never in that location. Assuming you have...
You can also use NOT IN statement to check what are the item\_no that have location = 100 and select everyone besides them ``` SELECT distinct t.item_no from Location t WHERE t.item_no NOT IN(select distinct s.item_no from Location s where s.location_no = 100) ```
Oracle Unique items not in a particular location
[ "", "sql", "oracle", "oracle11g", "" ]
The relevant part of my database schema looks like this (Ruby on Rails migration code, but should be easy to read): ``` create_table "team_memberships" do |t| t.integer "team_id" t.integer "user_id" end create_table "users" do |t| t.integer "id" t.string "slug" end create_table "performance_points" do |t|...
I have discovered that there actually wasn't a problem with the query, but with the data. There were some users who were on multiple teams more than once and that have issues.
If `slug` is unique per user: ``` SELECT u.id, u.slug, SUM(pp.points) AS total FROM users u JOIN performance_points pp ON u.id = pp.user_id WHERE pp.date > '2015-08-02 13:57:14.042221' GROUP BY u.id, u.slug ORDER BY total DESC LIMIT 50 ``` Otherwise you can't `SELECT` `slug` because it's not a grouping column, so the...
Issues with SQL query using SUM
[ "", "sql", "postgresql", "" ]
I have table like this below where it save all data with reference id :- ``` ID Name RefID A AAAA null B BBBB A C CCCC B D DDDD C E EEEE D F FFFF E ``` Firstly I need some query where I can scan which are the top three reference id level only and show up. --- Example: When D added b...
Postgreql version (|| instead of '+' for concatenation and quoted level alias): ``` select ID, 'Level(' || cast(level as varchar(255)) || ')', RefID from ( select t0.ID, case level.level when 1 then t1.ID when 2 then t2.ID when 3 then t3.ID end RefID, level.level from Test...
``` create table Test( ID varchar(10), Name varchar(10), RefID varchar(10) ) insert into Test select 'A','AAAA',null union all select 'B','BBBB','A' union all select 'C','CCCC','B' union all select 'D','DDDD','C' union all select 'E','EEEE','D' --union all --select 'F','FFFF','E' select ID, 'Level(' + cast(leve...
How To Query Top Three Reference ID only and How I can query until 3 Level Group below only Based Reference ID
[ "", "sql", "postgresql", "relationship", "" ]
The original format: ``` 123-456-7890 ``` My goal format: ``` (123)456-7890 ``` I wanted to go the route of concatenating between substrings but I continually get flagged for errors. I am unsure of a better method to go about implementing a way to format. My query: ``` select || '(' || substr(telephone,0, 3)|| ')...
You have an extra dangling parenthesis at the end of your `SELECT`, and you also have a dangling concatenation operator `||` in the front. Try this: ``` SELECT '(' || SUBSTR(telephone, 0, 3) || ')' || SUBSTR(telephone, 4, 3) || ' ' || SUBSTR(telephone, 7, 4) AS telephone FROM book ``` **Update:** You should real...
Using **SUBSTR**: ``` SQL> WITH sample_data AS( 2 SELECT '123-456-7890' num FROM dual 3 ) 4 -- end of sample_data mimicking real table 5 SELECT num, 6 '(' 7 || SUBSTR(num, 1, 3) 8 || 9 ')' 10 || SUBSTR(num, 5, 8) AS my_num 11 FROM sample_data; NUM MY_NUM ------------ ---...
Oracle SQL inserting parenthesis into phone number
[ "", "sql", "oracle", "formatting", "substring", "concatenation", "" ]
I am looking to reconcile data from 2 different tables where I need to carry out a concatenation and substr to create columns that I can use to carry out a match against.The following separate queries reflect the select statements from each table that produces the matching values that reflect `sitenn.zonenn` (e.g. `sit...
Use `left join` to find it. It is faster than `minus`,`not in`,`not exists` etc. ``` SELECT a.nodename FROM (SELECT DISTINCT( regexp_substr(B.node_name, '*site*.*') ) AS nodename FROM opc_act_messages A, opc_node_names B WHERE A.message_group = 'Ebts_Status_Alarms' ...
One simple way: use `MINUS` ``` SELECT distinct(REGEXP_SUBSTR(B.NODE_NAME,'*site*.*')) as nodename FROM OPC_ACT_MESSAGES A,OPC_NODE_NAMES B WHERE A.MESSAGE_GROUP = 'Ebts_Status_Alarms' AND A.SEVERITY <> 2 AND A.NODE_ID = B.NODE_ID MINUS SELECT 'site'||site_id||'.zone'||zone_id as nodename FROM aw_active_alarms GR...
Oracle sql join against extracted values
[ "", "sql", "oracle", "" ]
Using PIVOT/UNPIVOT I was able to get from here... ``` Period Store1 Store2 -------------------------------------- Jan15 123 456 Feb15 789 101 Mar15 112 131 Apr15 415 161 ``` ...to here, dynamically (no matter how many stores my cur...
One possible solution, without pivot/unpivot: ``` create table #tab( Store nvarchar(50), period nvarchar(50), value int ) declare @ColumnName table(columnName nvarchar(50)) insert into @ColumnName (columnName) select A.name from ( select name from sys.columns ...
Easy way of doing it would just be to union your original: ``` DECLARE @t AS TABLE(period VARCHAR(15), store1 INT, store2 INT) INSERT INTO @t ( [period], [store1], [store2] ) VALUES ('Jan15',123,456), ('Feb15',789,101), ('Mar15',112,131) SELECT T1.[period], 'Store1...
TSQL Pivot - Collapsing Columns to Rows
[ "", "sql", "sql-server", "t-sql", "pivot", "unpivot", "" ]
I have a table with effective start date and end date that is history data for employees. This table should contain all the details of th employee. I need to find out through a query wherever there are breaks between dates. For example : ``` Table ABC : EMP_NO EFF_START_DATE EFF_END_DATE ORG ...
You can also find the solution by comparing, for each row, the start\_date with the previous end\_date for the same employee: ``` select src.*, src.start_date - src.prev_end_date gap_days from ( select out_tab.emp_no, (select max(in_tab.end_date) from ABC in_tab where in_tab.emp_no =...
It is a typical **[Gaps and Islands](https://lalitkumarb.com/category/gaps-and-islands/)** problem. You need to find out the **missing values in the sequence of dates**. For example, ``` SQL> WITH sample_data(dates) AS( 2 SELECT DATE '2015-01-01' FROM dual UNION 3 SELECT DATE '2015-01-02' FROM dual UNION 4 ...
QUERY to find gap in dates in a table
[ "", "sql", "oracle", "gaps-and-islands", "" ]
I have a table `dictionary` which contains a list of words Like: ``` ID|word --------- 1|hello 2|google 3|similar ... ``` so i want if somebody writes a text like "helo iam looking for simlar engines for gogle". Now I want to check every word if it exists in the database, if not it should get ...
There is a function that does roughly want you want, but it's intensive and will slow queries down. You might be able to use in your circumstances, I have used it before. It's called Levenshtein. You can get it here [How to add levenshtein function in mysql?](https://stackoverflow.com/questions/13909885/how-to-add-leve...
you can use [soundex()](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_soundex) function for comparing phonetically your query should be something like: ``` select * from table where soundex(word) like soundex('helo'); ``` and this will return you the `hello` row
MYSQL search for right words | fixing spelling errors
[ "", "mysql", "sql", "spelling", "" ]