Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a query which uses needs to know how many days passed since 1st of January in the current year. Which means that if the query runs for example in: > 2nd Jan 2017 than it should return 2 (as 2 days passed since 1st Jan > 2017). > > 10th Feb 2016 than it should return 41 (as 41 days passed since 1st > Jan 2016)....
An easier approach may be to extract the day of year ("doy") field from the date: ``` db=> SELECT EXTRACT(DOY FROM CURRENT_DATE); date_part ----------- 41 ``` And if you need it as a number, you could just cast it: ``` db=> SELECT EXTRACT(DOY FROM CURRENT_DATE)::int; date_part ----------- 41 ``` ...
Another solution is to use **DATEDIFF** ``` SELECT DATE_PART('day', now()::timestamp - '2016-01-01 00:00:00'::timestamp); ```
How to get how many days passed since start of this year?
[ "", "sql", "postgresql", "date", "select", "" ]
The SQL query looks like this: ``` Declare @Values nvarchar(max) , @From int , @To int Set @Values = 'a,b,c,d,e,f,g,h,i,j' Set @From = 3 , @To = 7 ``` The values must be split into rows based on `@From` and `@To`. Based on the above query, required output is ``` c d e f g ``` Any help would be appreciated.
**Disclaimer**: I'm the owner of the project [Eval SQL.NET](http://eval-sql.net/) If you have a C# background, you may might consider this library which let you use C# syntax directly in T-SQL ``` DECLARE @Values NVARCHAR(MAX) , @From INT , @To INT SELECT @Values = 'a,b,c,d,e,f,g,h,i,j' , @From = 3 ...
You need a string splitter for this. Here is [DelimitedSplit8k](http://www.sqlservercentral.com/articles/Tally+Table/72993/) by Jeff Moden. ``` DECLARE @Values NVARCHAR(MAX), @From INT, @To INT SELECT @Values = 'a,b,c,d,e,f,g,h,i,j', @From = 3, @To = 7 SELECT STUFF(( ...
SQL Server : comma-separated List based on offset values
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I want to grab a list of values from an SQL table, and then run a query using each of these values to update other fields in the same table. In another language, I'd use a for loop for this, but I've read that looping operations should be avoided/aren't supported in SQL. Conceptually (obviously the code isn't valid), ...
You should be able to join the table with a subset of itself: ``` UPDATE my_table t1 INNER JOIN (SELECT item_id FROM my_table WHERE value = "my_value" AND field_id = 1) t2 ON t1.item_id = t2.item_id SET t1.meta_value = "my_value" WHERE t1.field_id = 2 ```
Try this update with join statement: ``` update My_Table t JOIN My_Table s on(t.item_id = s.item_id and t.field_id = 2 and s.field_id = 1) set t.meta_value = 'my_value' where s.value = 'MY_VALUE' ```
Proper way to update SQL table without using loops
[ "", "mysql", "sql", "loops", "" ]
I have following two queries how do i use `union` so as to see both the results in the single query execution ``` select TOP 1 AGE, DIAGNOSIS_CODE_1, count(DIAGNOSIS_CODE_1) as total_count from Health where age = 7 group by AGE, DIAGNOSIS_CODE_1 order by total_count DESC; select TOP 1 AGE, DIAGNOSIS_CODE_1, count(DIA...
Just add UNION ALL in between those queries. The ORDER BY clause wont accept when UNION ALL applied. So i concluded it by taking them in a inner set. ``` SELECT * FROM ( SELECT TOP 1 AGE, DIAGNOSIS_CODE_1, COUNT(DIAGNOSIS_CODE_1) AS TOTAL_COUNT FROM HEALTH WHERE AGE = 7 GROUP BY AGE, DIAGNOSIS_COD...
You can do this by `row_number() over(partition by..` like, ``` select AGE, DIAGNOSIS_CODE_1, total_count from ( select AGE, DIAGNOSIS_CODE_1, count(DIAGNOSIS_CODE_1) as total_count, row_number() over (partition by AGE order by count(DIAGNOSIS_CODE_1) desc) rnk ...
How to use union of two queries in SQL that has order by and count()
[ "", "sql", "sql-server", "union", "" ]
Could somebody explain me whats wrong in this? My query is like this... ``` select t1.year, t1.empid, t2.tcost from (select year,empid,sum(cost) as total from orders group by year,empid) t1 inner join (select year, max(total) from t1 group by year) t2 on t1.year= t2.year ``` I am getting error message as below ``` E...
If in your query you use self-join, there is usually an equivalent query based on analytical functions. The advantage is, in most cases, shorter execution time. Here you could use [`max ... keep dense rank ...`](https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions056.htm): ``` select year, empid, sum_cost ...
``` SELECT t1.year, t1.empid, t2.tcost FROM (SELECT year, empid, sum(cost) AS total FROM orders GROUP BY year, empid) t1 INNER JOIN (SELECT year, max(total) **AS tcost** FROM t1 **<-- ?? No, you need to specify a table** GROUP BY year) t2 ON t1.year = t2.year ...
how can I join two queries in which one is derived from other?
[ "", "sql", "oracle", "join", "" ]
I want to index data in height dimensions (128 dimensional vectors of integers in range of [0,254] are possible): ``` | id | vector | | 1 | { 1, 0, ..., 254} | | 2 | { 2, 128, ...,1} | | . | { 1, 0, ..., 252} | | n | { 1, 2, ..., 251} | ``` I saw that PostGIS implemented R-Trees. So can I use these tr...
Perhaps a better choice would be the [cube extension](http://www.postgresql.org/docs/current/static/cube.html), since your area of interest is not individual integer, but full vector. Cube supports GiST indexing, and Postgres 9.6 will also bring KNN indexing to cubes, supporting [euclidean, taxicab (aka Manhattan) and...
(Addendum to selected answer) For people wanting more than 100 dimensions, beware: there's [a 100 dimensions limit in cube extension](https://www.postgresql.org/docs/current/static/cube.html#AEN176262). The tricky part is that postgres allows you to create cubes with more than 100 dimensions just fine. It's when you ...
indexing and query high dimensional data in postgreSQL
[ "", "sql", "postgresql", "multidimensional-array", "indexing", "postgresql-9.3", "" ]
I'm getting a syntax error while following the MySQL guide for `IF` syntax. My query is: ``` if 0=0 then select 'hello world'; end if; ``` Logically, this should select `'hello world'`, but instead I get ``` ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL se...
Your query is only valid in a stored procedure/function context. See [there](http://dev.mysql.com/doc/refman/5.7/en/if.html) for reference.
using if statements like this is valid only inside stored procedure or functions. What you'd probably like to use is the [if()](http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#function_if) function, and then you can use: ``` select IF(0=0, 'hello world',''); ```
IF syntax error
[ "", "mysql", "sql", "if-statement", "syntax", "syntax-error", "" ]
I have two tables: university and university\_list Table1 - university [![enter image description here](https://i.stack.imgur.com/6Q1rA.png)](https://i.stack.imgur.com/6Q1rA.png) Table2 - university\_list [![enter image description here](https://i.stack.imgur.com/5Qe6E.png)](https://i.stack.imgur.com/5Qe6E.png) I ad...
``` UPDATE university_list a JOIN university b ON a.name = b.university_name SET a.university_id = b.id ```
``` select a.id,b.name from table1 as a inner join table2 as b on a.university_name = b.name ``` Above query will return id and name of university if match. Hold both value in variable and pass variable in update query. ``` update table2 set university_id = '$val' where b.name = '$name'; ```
SQL How to connect two tables together by a specific column?
[ "", "mysql", "sql", "phpmyadmin", "" ]
I've got a query which gets the total sales figure for the current day ``` SELECT SUM(cso.SubTotal) - ( SELECT SUM(cso.CreditAvailable) / 1.1 FROM dbo.CustomerCredit cso WHERE CONVERT(VARCHAR(10), cso.DateCreated, 102) = CONVERT(VARCHAR(10), SYSDATETIME(), 102) ) AS total_value FROM...
You can use query like this: ``` ;with date_cur_month as( select convert(datetime, convert(varchar(6), getdate(), 112) + '01', 112) as dt union all select dateadd(day, 1, dt) as dt from date_cur_month where datepart(month, dateadd(day, 1, dt)) = datepart(month, getdate())) select convert(nvarchar(8), d.dt, 3) as ...
First, I believe your query can be written as: ``` SELECT SUM(SubTotal) - (SUM(CreditAvailable) / 1.1) AS total FROM dbo.CustomerInvoice WHERE CAST(InvoiceDate AS DATE) = CAST(SYSDATETIME() AS DATE) ``` To get the total for each date, just add a `GROUP BY`: ``` SELECT SUM(SubTotal) - (SUM(CreditAvailable) / ...
Get daily sales for every day this month
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have two tables.They have the same data but from different sources. I would like to find all columns from both tables that where id in table 2 occurs more than once in table 1. Another way to look at it is if table2.id occurs only once in table1.id dont bring it back. I have been thinking it would be some combinatio...
If you using MSSQL try using a Common Table Expression ``` WITH cte AS (SELECT T1.ID, COUNT(*) as Num FROM Table1 T1 INNER JOIN Table2 T2 ON T1.ID = T2.ID GROUP BY T1.ID HAVING COUNT(*) > 1) SELECT * FROM cte INNER JOIN Table1 T1 ON cte.ID = T1.ID INNER JOIN Table2 T2 ON cte.ID ...
I find this a much simpler way to do it: ``` select TableA.*,TableB.* from TableA inner join TableB on TableA.id=TableB.id where TableA.id in (select distinct id from TableA group by id having count(*) > 1) ```
SQL Query to Bring Back where Row Count is Greater than 1
[ "", "sql", "sql-server", "group-by", "" ]
I have this request ``` select COALESCE (SUBSTR(description, 0, INSTR(description, '#')-1),description) FROM dual ``` Test: When : description = `123456789 # 11` => Result = `123456789` When : description = `123456789` => Result = `123456789` Is there any idea how to less complicated , because like you see it's so...
To remove all characters after `#` use the regexp\_replace in the first line; note, that the trailing blank is preserved. ``` regexp_replace(description, '([^#]*).*', '\1') ``` The second line `D2` removes anything after the first `#` or *blank* ``` regexp_replace(description, '([^ #]*).*', '\1') ``` Here the sam...
You can use `regexp_substr()`: ``` select regexp_substr(description, '^[^ #]*[ ]') ``` I doubt this would be any faster.
How to less complicated this request
[ "", "sql", "oracle", "" ]
We have the following tree structure. The aim is to construct a table in the database using postgresql query. The table should contains the following information. The first column contains the node. And the second contains the parent node. ``` |--node1.1.1 |-node1.1--| ...
thank you for all your contributions. Thanks to that we have succeeded to solve the issue as follow: ``` WITH RECURSIVE hierarchy(node, node_parent) AS ( SELECT node, node_parent FROM tree UNION ALL SELECT t.node, h.node_parent FROM hierarchy h J...
Take a look at [with statement](http://www.postgresql.org/docs/current/static/queries-with.html). Your final query will look like the following. ``` with recursive hierarchy(node, node_parent, level) as ( select node, node_parent, 0 from tree where node_parent is null union all select t.node, t.nod...
Processing a generated tree dynamically
[ "", "sql", "postgresql", "" ]
My understanding of using summary functions in SQL is that each field in the select statement that doesn't use a summary function, should be listed in the `group by` statement. ``` select a, b, c, sum(n) as sum_of_n from table group by a, b, c ``` My question is, why do we need to list the fields? Shouldn't the SQL s...
To decrease the chances of errors in your statement. Explicitly spelling out the `GROUP BY` columns helps to ensure that the user wrote would they intended to write. You might be surprised at the number of posts that show up on Stackoverflow in which the user is grouping on columns that make no sense, but they have no ...
This is required to determine explicitly how do you want to group the records because, for example, you may use columns for grouping that are not listed in result set. However, there are RDBMS which allow to not specify `GROUP BY` clause using aggregate functions like MySQL.
SQL Syntax - Why do we need to list individual fields in an SQL group-by statement?
[ "", "sql", "" ]
[![sample table](https://i.stack.imgur.com/655fK.png)](https://i.stack.imgur.com/655fK.png) I have this issue and I cant find out a correct solution. The following image shows a table where I have different records going in. The keys for the records are `RID` and `NAME`, and I would like to create a query that returns...
Since maximum `ID` is related to maximum `CREATED` you can use aggregates to find maximum `CREATED` and `ID` for each distinct pair of `RID, NAME`: ``` select RID, NAME, max(ID), max(CREATED) from <your-table-name> group by RID, NAME ```
I solve this by using this query: ``` SELECT * FROM <table> as o inner join ( select RID, NAME, max(CREATED) as CREATED from <table> group by RID, NAME ) as t on t.NAME=o.NAME and t.RID=o.RID and o.CREATED=t.CREATED order by ID ``` I would appreciate if you can find a better solution to it so I can also ...
SQL Get most recent date from table to be included in a VIEW with inner join
[ "", "sql", "t-sql", "date", "datetime", "join", "" ]
I'm looking to copy the values of two columns (Column 1, Column 2, and Column 3) to another table; however, I don't want values to be copied if there is a duplicate value in Column 2. An example is below: ``` UserID Item Date ------------------------ 101 1 < 2-10-2016 101 1 < 2-9-2016 101 ...
Just do a `GROUP BY UserId, Item` and use `HAVING` to determine the group population: ``` INSERT INTO TableB (Col1, Col2) SELECT UserId, Item FROM TableA GROUP BY UserId, Item HAVING COUNT(*) = 1 ``` This will insert only non duplicated `UserId, Item` pairs into TableB. If you want to insert **all** `UserId, Item` ...
Try ``` INSERT INTO TableB (Col1, Col2) SELECT UserId, Item, Max([Date]) FROM TableA GROUP BY UserId, Item ``` Use Min() if you want the smallest date to be inserted.
How to copy a column without duplicate values? SQL
[ "", "sql", "database", "t-sql", "" ]
I need to know query result structure . Let's say i have this query : ``` SELECT T.name as names FROM (SELECT name,sex FROM user) T WHERE T.sex='male' ``` What i need to know is the structure of the result of this query , something like this : ``` column_name : names TYPE : varchar(60) ``` Is there a way to get th...
This can be a bit complicated to do. One method that works across databases is to do the following: * Create a table or view with the structure * Investigate the metadata In MySQL, you can do: ``` create table temp_table as select t.name as names from (select name, sex from user) t where t.sex = 'male' ...
First create a `view` ``` CREATE VIEW view_name AS SELECT T.name as names FROM (SELECT name,sex FROM user) T WHERE T.sex='male' ``` Then simply run a `desc` or `describe` on the `view` like ``` desc view_name ``` You can get the result of this query using your code and use it as you need.
Sql query result structure
[ "", "mysql", "sql", "select", "subquery", "" ]
I have two tables named `tblStockManagement` and `tblFolding` in my database. i have column `Name` in `tblFolding` table and column `FoldingID` as Foreign Key in `tblStockManagement` table. now i have comboBox in my Winform and i want `Names` of Items in combobox from `tblFolding` Table but only those items that are no...
This is you need.Basically a sub query which gets all folding id and using not in operator I exclude those matching sets. ``` SELECT Name FROM tblFolding WHERE FoldingID NOT IN ( SELECT FoldingID FROM tblStockManagement ) ; ```
`NOT EXISTS` version: ``` select * from tblFolding f where not exists (select * from tblStockManagement SM where sm.FoldingID = f.FoldingID) ``` `NOT EXISTS` is "NULL safe", which `NOT IN` isn't.
SQL Query to match if data is not present in another table
[ "", "sql", "sql-server", "" ]
This is probably a very simple question, but my attempts to search for an answer are thwarted by Google finding answers showing how to reuse a query by making a stored procedure instead. I want to reuse the results of a query inside a stored procedure. Here's a cut-down example where I've chopped out `NOCOUNT`, `XACT_...
You can INSERT result of the SELECT into a temporary table or table variable, but it doesn't automatically mean that the overall performance would be better. You need to measure it. **Temp Table** ``` CREATE PROCEDURE Do_Something @userId UNIQUEIDENTIFIER AS BEGIN CREATE TABLE #Temp(id int); INSERT INTO...
If the subquery is fast and simple - no need to change anything. Item's data is in the cache (if it was not) after the first query, locks are obtained. If the subquery is slow and complicated - store it into a table variable and reuse by *the same subquery* as listed in the question. If your question is not related to...
Reuse results of SELECT query inside a stored procedure
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
Using this SQL query: ``` Select CityName, count(UserID) as UserCount from tblUsers group by CityName ``` I get these results: ``` CityName UserCount --------------------- City 1 10 City 2 15 ``` Expected output: ``` CityName UserCount Perc --------------------------- City 1 10 40 C...
Try using a sub query to select the total count like this: ``` Select CityName, count(userID) as userCount, count(UserID)/(select count(*) from tblUsers)*100 as Perc from tblUsers group by CityName ``` You can also try JOIN like this: ``` SELECT t.CityName, t.userCount, t.userCount/s.tota...
The simplest way is to use window functions: ``` Select CityName, count(UserID) as UserCount , count(UserId) * 100.0 / sum(count(UserId)) over () as Perc from tblUsers group by CityName; ``` A subquery is not necessary.
Get % of rows based on total number of rows when using GROUP BY clause in SQL Server
[ "", "sql", "sql-server", "database", "sql-server-2008", "" ]
I've 2 tables: A device table and a User table. Device Table has 2 columns: ID, and MacAddress. User Table has 4 columns: ID, Name, Phone, MacAddress. There will be a fixed list populating the User Table for example: 1, Steve Marks, 219-373-1485, 5A:2B:3C:8D 2, Dan Marks, 310-248-1455, 5C:3A:2B:8A Every 5 m...
As I understood your Users table contains all users of a WLAN hotspot for example. And the device list containts all mac addresses having accessed the hotspot at a given time. What about ``` SELECT name, macAddress, count(macAddress) FROM Device INNER JOIN USER ON User.MacAddress = Device.MacAddress GROUP BY name...
You can use this query ``` SELECT name,phone, MacAddress, COUNT(name) as total FROM user GROUP BY name HAVING ( COUNT(name) > 1 ) ```
MySQL query with if condition
[ "", "mysql", "sql", "database", "" ]
My problem here is to find a non-active person that didn't have any activity since or before Dec-01-2011. ``` PersonID Activity ---------------------- Alvin Jan-08-2010 Alvin Mar-11-2011 Alvin Feb-11-2015 Simon Nov-20-2010 Simon Jan-23-2011 Simon Jul-03-2011 Simon Nov-04-2011 Theod...
A simple `GROUP BY` and `HAVING` will do the trick: [**SQL Fiddle**](http://sqlfiddle.com/#!6/690fdc/1/0) ``` SELECT PersonID FROM tbl GROUP BY PersonID HAVING COUNT(CASE WHEN Activity > '20111201' THEN 1 END) = 0 ```
Off the top of my head.. something like this should do it ``` SELECT PersonID FROM TableName GROUP BY PersonID HAVING MAX(Activity) <= '2011-12-01' ```
Finding a person with no Activity before a certain date
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have 3 tables (stars mach the ids from the table before): ``` product: prod_id* prod_name prod_a_id prod_b_id prod_user keywords: key_id** key_word key_prod* kay_country data: id dat_id** dat_date dat_rank_a dat_traffic_a dat_rank_b dat_traffic_b ``` I want to run a query (in a func...
If you only want to do this for one key\_id at a time (as alluded to in your responses to other answers) and only want two rows, you can just do: ``` SELECT p.prod_id, p.prod_name, p.prod_a_id, p.prod_b_id, k.key_id, k.key_word, k.key_country, ...
For SQL ``` WITH CTE AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY dat_id ORDER BY dat_date ASC) AS RowNo FROM data ) SELECT * FROM CTE INNER JOIN keywords ON keywords.key_id = CTE.dat_id INNER JOIN prods ON keywords.ke...
SQL: How to get cells by 2 last dates from 3 different tables?
[ "", "mysql", "sql", "" ]
I have a table like this: ``` DECLARE @T TABLE (note VARCHAR (50)) INSERT @T SELECT 'Amplifier' UNION ALL SELECT ';' UNION ALL SELECT 'Regulator' ``` How can I replace the semicolon (`';'`) with blank (`''`). Expected Output: ``` Amplifier '' -- here semicolon replace with blank Regulator ```
If you want to replace ALL semicolons from any outputted cell you can use `REPLACE` like this: ``` SELECT REPLACE(note,';','') AS [note] FROM @T ```
Fetching from the given table, use a `CASE` statement: ``` SELECT CASE WHEN note = ';' THEN '' ELSE note END AS note FROM @T; ``` [replace()](https://msdn.microsoft.com/en-us/library/ms186862.aspx) would replace *all* occurrences of the character. Doesn't seem like you'd want that. This expression only replaces exact...
Replace ; with blank in SQL
[ "", "sql", "" ]
I am currently generating a table which converts the rows value to the new column, the following is my code: ``` SELECT ref_no, (CASE WHEN code = 1 THEN code END) AS 'count_1', (CASE WHEN code = 2 THEN code END) AS 'count_2', (CASE WHEN code = 3 THEN code END) AS 'count_3', (CASE WHEN code = 4 THEN cod...
The answer is: YES By using GROUP BY and MAX like this: ``` SELECT ref_no, max(CASE WHEN code = 1 THEN code END) AS 'count_1', max(CASE WHEN code = 2 THEN code END) AS 'count_2', max(CASE WHEN code = 3 THEN code END) AS 'count_3', max(CASE WHEN code = 4 THEN code END) AS 'count_4', max(CASE WHEN c...
The easiest would either be to use GROUP BY or a PIVOT function. GROUP BY example below: ``` SELECT ref_no, sum(CASE WHEN code = 1 THEN code ELSE 0 END) AS 'count_1', sum(CASE WHEN code = 2 THEN code ELSE 0 END) AS 'count_2', sum(CASE WHEN code = 3 THEN code ELSE 0 END) AS 'count_3', sum(CASE WHEN cod...
Remove duplicate rows when using CASE WHEN statement
[ "", "sql", "sql-server", "" ]
I have this query that locates all users that have the same email as (memberid) in the membership table and brings back any other users with matching emails ``` select tenant,first,last,memberid,email,ipaddress,password from membership where email IN ( SELECT email FROM membership where memberid = <Parameters.Memb...
Hogan got posted the correct answer before I was done +1 Can also use a join ``` select match.email, match.tenant, match.first, match.last , match.memberid, match.ipaddress, match.password , count(match.memberid) OVER (partition by match.ipaddress) as ipCount , count(match.memberid) OVER (partition...
In many platforms (including sql server) you can use a windowing function. A windowing function would allow you to give a count of the users that have the same password or ipaddress as the current row. If this is what you want ``` select tenant,first,last,memberid,email,ipaddress,password, count(memberid) OVER ...
Returning count in SQL grouped by two other partitions with an in clause on an id
[ "", "sql", "sql-server", "" ]
I have a table with many columns, among which the fields **year**, **folder** and **seq\_no** serve as an identification method for the record. I'd like to assign the same id to those records that have this combination the same, and (if possible) the total of ids must be sequential, to make good use of the id column va...
I would not try to store such IDs and especially COUNT in the table. Imagine, that in your example you want to insert one more row with ``` +-----+------+------+ |year |folder|seq_no| +-----+------+------+ |1973 | 5 | 11 | +-----+------+------+ ``` The server would have to find all existing rows with the same c...
Do it at query time: ``` with t (year, folder, seq_no) as (values (1973,5,11), (2010,4,7), (1973,11,12), (1973,5,11), (1500,4,4), (2010,4,7) ) select dense_rank() over (order by year, folder, seq_no) as id, year, folder, seq_no, count(*) over (partition by year, folder, seq_no) as "...
Assign same id to rows with same combination of data
[ "", "sql", "postgresql", "" ]
I just hit a wall with my SQL query fetching data from my MS SQL Server. To simplify, say i have one table for sales, and one table for customers. They each have a corresponding userId which i can use to join the tables. I wish to first `SELECT` from the sales table where say price is equal to 10, and then join it on...
A `SELECT` has a certain order of its components In the simple form this is: * What do I select: column list * From where: table name and joined tables * Are there filters: WHERE * How to sort: ORDER BY So: most likely it was enough to change your statement to ``` SELECT * FROM Sales INNER JOIN Customers ON Sales....
The `WHERE` clause must follow the joins: ``` SELECT * FROM Sales INNER JOIN Customers ON Sales.userId = Customers.userId WHERE price = 10 ``` This is simply the way SQL syntax works. You seem to be trying to put the clauses in the order that you think they should be applied, but SQL is a declarative languages, not a...
Specifying SELECT, then joining with another table
[ "", "sql", "sql-server", "" ]
What mistake am I making? ``` $ sqlite3 test.db SQLite version 3.8.5 2014-08-15 22:37:57 Enter ".help" for usage hints. sqlite> create table t (s text not null, i integer); sqlite> select * from t where s="somestring"; /* works */; sqlite> select * from t where i=0; /* works */; sqlite> select * from t where s="somest...
You don't need to specify where 2 times in this query ``` sqlite> select * from t where s="somestring" and i=0; ``` should be enough.
try ``` select * from t where s="somestring" and i=0; ``` instead of ``` select * from t where s="somestring" and where i=0; ```
sqlite: multiple where clause syntax: where s="somestring" and where i=0;
[ "", "sql", "sqlite", "android-sqlite", "" ]
I'm trying to create a view in Postgresql , but when I run this code appears this error: > syntax error at or near " THEN " ``` CREATE OR REPLACE VIEW VW_MONITOR_DEVICE AS SELECT P.POSIZIONE_DEVICE_ID AS MONITOR_DEVICE_ID, P.VALID AS VALID, [...] IF (VALID == FALSE THEN 'Valid' EL...
You should use [CASE](http://www.postgresql.org/docs/9.5/static/functions-conditional.html) > The SQL **CASE** expression is a generic conditional expression, similar > to **if/else** statements in other programming languages ``` CASE WHEN condition THEN result [WHEN ...] [ELSE result] END ``` So, ``` CRE...
you can use case ``` case when VALID = FALSE THEN 'Valid' ELSE P.REASON_FOR_INVALID end DESCRIPTION, ```
Postgresql Syntax error at or near " THEN "
[ "", "sql", "postgresql", "syntax-error", "create-view", "" ]
I've selected table: **A1** and joined **A2** to **A1**, AND **A3** joined to **A2**. **A1**.level and **A2**.level always not null **A3**.level means that that joined row is null. **A1**.level is bigger then **A2**.level. IF **A3**.level is smaller than **A2**.level or setted to (NULL) SO, I need result lik...
You need to add parentheses: ``` SELECT A1.level, A2.level, A3.level FROM A1 JOIN A2 -- no need for LEFT JOIN ON A1.parentID = A2.id LEFT JOIN A3 ON A2.parentID = A3.id WHERE (A1.level > A2.level) AND (A2.level > A3.level OR A3.level IS NULL) ``` Otherwise the order of precedence is: ``` NOT - AND - OR ``...
Use parenthesis; ``` SELECT A1.level, A2.level, A3.level FROM A1, LEFT JOIN A2 ON A1.parentID = A2.id LEFT JOIN A3 ON A2.parentID = A3.id WHERE (A1.level is not null and A2.level is not null) and --A1.level and A2.level always not null (A1.level > A2.level) and --A1.level is bigger then A2.level. (A2.leve...
SQL: whats wrong with this "where if" query?
[ "", "mysql", "sql", "" ]
I'm building a system that should show when the students missed two days in a row. For example, this table contains the absences. ``` day | id | missed ---------------------------------- 2016-10-6 | 1 | true 2016-10-6 | 2 | true 2016-10-6 | 3 | false 2016-10-7 | 1 | true 2...
Use inner join to connect two instances of the table- one with the 'first' day, and one with the 'second' day, and then just look for rows where both are missed: ``` select a.id from yourTable as a inner join yourTable as b on a.id = b.id and a.day = b.day-1 where a.missed = true and b.missed = true ``` **EDIT*...
similar approach as other answers, but different syntax ``` select distinct id from t where missed=true and exists ( select day from t as t2 where t.id=t2.id and t.day+1=t2.day and t2.missed=true ) ```
How to select where there are 2 consecutives rows with a specific value using MySQL?
[ "", "mysql", "sql", "select", "group-by", "" ]
I have an SQL query that returns the following values: ``` BC - Worces BC Bristol BC Central BC Torquay BC-Bath BC-Exeter BC-Payroll ``` So, we have some BC with just a space, some with a dash and some with a dash with spaces on either side. When returning these values, I want to replace any of these BC variants with...
You could use a case on the select ``` CASE WHEN Left(`colname`, 5) = 'BC - ' THEN CONCAT('Business Continuity: ', SUBSTRING(`colname`, 6)) WHEN Left(colname, 3) = 'BC ' THEN CONCAT('Business Continuity: ', SUBSTRING(`colname`, 4)) WHEN Left(`colname`, 3) = 'BC-' THEN CONCAT('Business Continuity: ', SUBSTRIN...
You can use [`REPLACE`](http://dev.mysql.com/doc/refman/5.7/en/replace.html) function along with `CASE` statement for this. ``` SELECT CASE WHEN `col_name` LIKE 'BC %' THEN REPLACE(`col_name`, 'BC ', 'Business Continuity: ') WHEN `col_name` LIKE 'BC-%' THEN REPLACE(`col_name`, 'BC-', 'Business Continuity: ')...
Check for a substring in MySQL and return a value based on it
[ "", "mysql", "sql", "string", "substring", "" ]
I got two tables A and B.One to many relationship exists between A and B. A\_Id is a foreign key . ``` Create table A(Id int,Name varchar(50)) create table B(Id int,A_Id int,Title varchar(50)) insert into A Values(1,'name1'); insert into A Values(2,'name2'); insert into A Val...
You can use a derived table that uses `ROW_NUMBER` to enumerate records within `A_Id` partitions: ``` select A.Id, A.Name, B.Title from A inner join ( select A_Id, Title, ROW_NUMBER() OVER (PARTITION BY A_Id ORDER BY Id DESC) AS rn from B ) AS B on A.Id = B.A_Id and B.rn = 1 ``` The record of derived ...
This may not be too performance effective, but surely works :) SELECT a.\*, b.title FROM a,b where a.id=b.a\_id and b.id = (select max(b.id) from b where A\_Id=a.id)
sql select from one to many
[ "", "sql", "join", "greatest-n-per-group", "" ]
I am taking a Cousera course talking about SQL and there is one line of code I cannot understand. What does it mean by 'hex(name || age)'? I know it turns the string into hexadecimal format using the hex() function, but what does 'name || age' do? I cannot find any document about the '||' operator.
`||` is the SQLite concatenation operator. So `hex(name || age)` will pass a concatenated string of `name` and `age` into the `hex()` function. From the SQLite [documentation](https://www.sqlite.org/lang_corefunc.html): > The hex() function interprets its argument as a BLOB and returns a string which is the upper-cas...
The [documentation](http://www.sqlite.org/lang_expr.html#collateop) says: > The **||** operator is "concatenate" - it joins together the two strings of its operands.
SELECT hex(name || age) AS X FROM Ages ORDER BY X
[ "", "sql", "sqlite", "hex", "" ]
I have a table and I am trying to get the first person in the table with gender = 'M' and the first person with gender = 'F' First person in this case = ORDER BY name in alphabetical order ``` name | gender | .......other data A M B M C F D F E F M G F ``` **How...
You can use `row_number()` function for that like this: ``` SELECT name,gender from ( SELECT name,gender, row_number() OVER(PARTITION BY gender ORDER BY name ASC) as rnk FROM YourTable) WHERE rnk = 1 ``` You can add your other columns after the gender if you want.
``` SELECT name, gender FROM your table WHERE gender = "M" ORDER BY NAME Fetch first row only Union all SELECT name, gender FROM your table WHERE gender = "F" ORDER BY NAME Fetch first row only ```
How to get the first instance of a value partitioned by another column?
[ "", "sql", "postgresql", "" ]
Raw sql query: ``` SELECT * FROM (SELECT p.id, p.title, p.mark, (SELECT max(created) FROM comments c WHERE c.post_id=p.id AND c.mark=1) AS latest_at FROM posts p) AS Post WHERE Post.latest_at IS NOT NULL ORDER BY latest_at DESC LIMIT 10 ``` I'm trying to write equiva...
Try this: ``` SELECT p.id, p.title, p.mark, c.latest_at FROM posts p LEFT JOIN ( SELECT post_id, MAX(created) AS latest_at FROM comments WHERE mark = 1 GROUP BY post_id ) AS c ON c.post_id = p.id WHERE c.latest_at IS NOT NULL ORDER BY c.latest_at DESC LIMIT 10 ``` or just this: ``` SELECT p...
I would suggest that: ``` SELECT p.id, p.title, p.mark, c.latest_at FROM posts p LEFT OUTER JOIN (select post_id, max(created) latest_at from comments where mark=1 group by post_id ...
How can i write equivalent sql query with join?
[ "", "mysql", "sql", "" ]
I'm trying to load data from csv into an SQL table. My DDL: ``` CREATE TABLE pcm.dbo.partitiondocumentcount ( partitionkey NVARCHAR(30) NOT NULL, documentcount INT NOT NULL, datetime DATETIME2(3) DEFAULT CURRENT_TIMESTAMP, CONSTRAINT pk_partitiondocumentcount PRIMARY KEY (...
The solution was simply add a column. I guess since my table had three columns it expected three in the file. My file (I also tried without the quote marks, didn't work as well) : Here's the working one ``` partition-1,1, partition-2,1, ```
I see one problem in your approach, but I'm not sure it would generate that error. The table has three columns but your data only has two. Even with a `default` constraint, `bulk insert` still looks for the third column. It might get that error because it is looking for a comma but encounters an end-of-line. The solut...
Bulk load data conversion error
[ "", "sql", "sql-server", "" ]
I have table like this for example: I need to select each uniq column by ver and to calculate how much is total of rows by each uniq ver column I think each total to add into the new column ``` table: id name ver 1 one 5 2 two 5 3 three 6 4 four 6 5 five 8 ``` SELECT, something like this ```...
**Query** ``` select MIN(id) as id, ver, COUNT(ver) as total from your_table_name group by ver; ```
I think what you are looking for is: ``` select min(id), ver, count(id) from table group by ver; ```
How to select rows with uniq value of column and to calculate count?
[ "", "mysql", "sql", "" ]
This is for SQL Server 2008 R2, I'm a novice at SQL so please be as specific as you can. `Table1` has some recursive structure built into it, where the `ParentId` is either `Null` meaning it's the root, or `ParentId` is the `Id` of another row in `Table1` which denotes it as a child. Example data set: ``` Table1Id ...
You can use a CTE and traverse the hierarchy ``` IF OBJECT_ID('tempdb..#testData') IS NOT NULL DROP TABLE #testData CREATE TABLE #testData ( Table1Id INT ,ParentId INT NULL ) INSERT INTO #testData ( Table1Id, ParentId ) VALUES (1, NULL ) ...
This query do the job. ``` with CTE as ( Select Table1ID as ID, Table1ID as Ancestor, 0 as level from Table1 UNION ALL Select ID, ParentID, level + 1 from Table1 inner join CTE on CTE.Ancestor = Table1.Table1ID where ParentID is not NULL ) , R_only as ( Select ID as ID, MAX(level) a...
How to use recursive logic to return only the Root row in a sql table (SQL Server 2008 R2)
[ "", "sql", "sql-server-2008-r2", "recursive-query", "" ]
I can't find a solution about how to split a comma-delimited string in ORACLE. Searched a lot, nothing works for my case Code ``` DECLARE TYPE T_ARRAY_OF_VARCHAR IS TABLE OF VARCHAR2(2000) INDEX BY BINARY_INTEGER; MY_ARRAY T_ARRAY_OF_VARCHAR; MY_STRING VARCHAR2(2000) := '12 3,456,,abc,def'; BEGIN FOR CURRENT_R...
Try this for the parsing the list part. It handles NULLS: ``` SQL> select regexp_substr('12 3,456,,abc,def', '(.*?)(,|$)', 1, level, null, 1) SPLIT, level from dual connect by level <= regexp_count('12 3,456,,abc,def',',') + 1 ORDER BY level; SPLIT LEVEL ----------------- ---------- 12 3 ...
Try xmltable and flwor expresion. The following example is not secure and throw error if you put string without comma. But is simpler to understand. ``` select xmlcast(column_value as varchar2(2000)) value_list from xmltable('for $val in ora:tokenize($strList,",") return $val' ...
Oracle- Split string comma delimited (string contains spaces and consecutive commas)
[ "", "sql", "oracle", "plsql", "split", "" ]
I'm able to join three tables together, but I can't figure out a way to save the resulting table. The join statement I am using is: ``` SELECT * FROM Table1 INNER JOIN Table2 ON Table1.id = Table2.id INNER JOIN Table3 ON Table1.id = Table3.id ``` I've tried INSERT INTO, SELECT INTO, etc., and I am still unable to fin...
``` SELECT Table1.*, Table2.OtherColumn, Table3.AnotherColumn, Table3.OneMoreColumn INTO TablesAsOf_20160215 FROM Table1 INNER JOIN Table2 ON Table1.id = Table2.id INNER JOIN Table3 ON Table1.id = Table3.id ```
The problem you are having is that you cannot create a new table with the same column names. Since your tables share some of the same fields, you have to rename those when inserting by aliasing them. Here's a quick example: ``` select t1.id as t1id, t2.id as t2id, t3.id as t3id into Table4 from Table1 t1 join Tab...
Save the results of a join statement? SQL
[ "", "sql", "t-sql", "" ]
I have the three tables following in my SQL Server 2008 database: * Cars * Drivers * UnavailableDrivers What I want is to show unavailableDrivers to the end users if they set @isAvailable = 0. On the other hand, if isAvailable=1, then the end user should see only available drivers. Finally, if isAvailable is NULL the...
The following query do you want: ``` SELECT * FROM Cars c INNER JOIN Drivers d ON (c.driverId = d.Id) WHERE (@isAvailable IS NULL) -- will not join to UnavailableDrivers is isAvailable is null OR (@isAvailable = 0 AND c.driverId IN (SELECT uc.id FROM UnavailableDrivers uc)) -- will join to UnavailableDrivers only if i...
Terrible approach, but you asked for it ``` USE [DB] GO CREATE PROCEDURE [GetDrivers] @isAvailable bit AS BEGIN IF (@isAvailable = 0) BEGIN Select * From Cars c Inner join Drivers d on (c.driverId = d.Id) inner j...
Joining a table (or not) based on a condition in SQL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table with following schema in my DB2 database. ``` CREATE TABLE IDN_OAUTH_CONSUMER_APPS ( CONSUMER_KEY VARCHAR (255) NOT NULL, CONSUMER_SECRET VARCHAR (512), USERNAME VARCHAR (255), TENANT_ID INTEGER DEFAULT 0, APP_NAME VARCHAR (255), OAUTH_VERSION VARCHAR (128...
I could do this successfully using following set of queries. ``` ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN ID INTEGER NOT NULL DEFAULT 0 CREATE SEQUENCE IDN_OAUTH_CONSUMER_APPS_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE CREATE TRIGGER IDN_OAUTH_CONSUMER_APPS_TRIGGER NO CASCADE BEFORE INSERT ON IDN_OAUTH_CONSU...
I recommend using this approach. It does not require creating any satellite objects - no triggers, sequences, etc... ``` alter table test.test2 add column id integer not null default 0; alter table test.test2 alter column id drop default; alter table test.test2 alter column id set generated always as identity; call ...
DB2 add auto increment column to an existing table
[ "", "sql", "db2", "auto-increment", "dbmigrate", "" ]
Really this is two related questions **Question:** Why would a query run faster with a function in a select clause than in the where clause **Question:** Why would an inline view take longer when moving the where clause from the inline view to the outer query. I'm not going to dump the entire query since it has colu...
How many times is the function being executed in each case? Without seeing query plans, I would wager that the query runs quickly when the other predicates are evaluated first, paring the result set down as much as possible before the function is called. When the function is only called 93 times (plus however many add...
you didn't give us much information, so i will guess... the following query does most probably make use of some indexes so it runs faster compared to FTS (Full Table Scan): ``` SELECT * FROM ( SELECT COL1, COL2, COL3, my_package.my_function(:bind_var, COL1) as fn_indc FROM my_table WHERE [CONDITIONS...] ) t...
Oracle SQL Function in WHERE clause takes longer to run than in SELECT clause
[ "", "sql", "oracle", "oracle11g", "" ]
I have the problem that I need to insert into a table with 2 entries, where one value is constant but fetched from another table, and the other one is the actual content that changes. Currently I have something like ``` INSERT INTO table (id, content) VALUES ((SELECT id FROM customers WHERE name = 'Smith'), 1), ...
Yet another solution: ``` insert into table (id, content) select id, unnest(array[1, 2, 5]) from customers where name = 'Smith'; ```
You can cross join the result of the select with your values: ``` INSERT INTO table (id, content) select c.id, d.nr from ( select id from customers where name = 'Smith' ) as c cross join (values (1), (2), (5) ) as d (nr); ``` This assumes that the name is unique (but so does your original solution).
PostgreSQL: How to insert multiple values without multiple selects?
[ "", "sql", "postgresql", "sql-insert", "" ]
I have Two Tables Called Table\_A and Table\_B like bellow. **Table\_A** ``` +-------+------------+------+---------+-----+ |MonthId|DepartmentId|Salary|Deduction| Paid| +-------+------------+------+---------+-----+ |01/2016| DEP01 | 1000 | 100 | 900| |01/2016| DEP02 | 2000 | 50 | 1950| |01/2016| ...
I suspect you want aggregation: ``` SELECT MonthId, DepartmentId, Salary, Deduction, Paid, MAX(Bank_1), MAX(Bank_2) FROM (SELECT MonthId, DepartmentId, Salary, Deduction, Paid, Null AS Bank_1, Null AS Bank_2 FROM Table_A WHERE MonthId = '02/2016' UNION ALL SELECT MonthId, DepartmentId, Salary,...
I think a `LEFT JOIN` should do it: Sample data: ``` CREATE TABLE #Table_A (MonthId VARCHAR(10), DepartmentId varchar(10), Salary int ,Deduction int, Paid int) INSERT INTO #Table_A VALUES ('01/2016','DEP01','1000','100','900'), ('01/2016','DEP02','2000','50','1950'), ('01/2016','DEP03','1500','0','1500'), ('02/20...
How do I Union two tables with different columns
[ "", "sql", "" ]
I'm importing an Excel document into a SQL table via the Import Wizard. My table contains many columns and a few of them contain phone numbers, and number/letter identifiers that are rather long (10+ numbers). Once the Excel document is imported, these numbers get modified. An example: 22222222222222200000 gets stored...
I've seen this issue before, it's Excel that is the issue not SSIS. Excel samples the 1st few rows and then infers the data type even if you explicitly set it to text. What you need to do is put this into the Excel file connection string in the SSIS package. This instruction tells Excel that the columns contain mixed d...
there is an option to edit the mappings of the columns to the data type you choose. it's in one of the last stages of the wizard. be careful not to loose the 0 at the beginning of phone numbers due to data transformation, this can sometime be a real headache when you miss it
Importing Excel into SQL with mixed columns - Large Numbers Contain E+
[ "", "sql", "excel", "t-sql", "" ]
I have a Transactions table with over 2,500,000 rows and three columns (that are relevant): id, company\_id, and created\_at. id identifies the transaction, company\_id identifies which company received it, created\_at is a timestamp with the time that transaction was performed. What I want is to get a list of the dif...
To get a result like the one it looks like you're expecting, I will sometimes make use of MySQL user-defined variables, and have MySQL perform the processing of the rows "in order", so I can compare the current row to values from the previous row. For this to run efficiently, we'll want an appropriate index, to avoid ...
Try this ``` SELECT t1.company_id, t2.created_at - t1.created_at as diff FROM Transactions t1 LEFT JOIN Transactions t2 on t2.created_at > t1.created_at and t2.company_id = t1.company_id ```
MySQL timestamp differences between two rows large table
[ "", "mysql", "sql", "" ]
consider the following table ``` id Part_no cust. work_order 1 abc xyz 111 2 abc xyz 123 3 abc xyz 121 4 qqq xyz 222 ``` Now when I enter a particular work order I want the following display. ``` part_no cust work_order abc xyz 111 abc xyz 123 a...
@Wyatt Shipman's answer should work. Here's another way to do it: ``` select a.part_no, a.cust, a.work_order from thetable as a inner join thetable as b on a.part_no = b.part_no where a.work_order = 111; ``` [SQL Fiddle](http://sqlfiddle.com/#!15/03923/2)
If you use mysql You can force a specific order by based an value for a fields ``` select part_no, cust, work_order from your_table where part_no = 'abc' order by FIELD(work_order,111,123,121); ``` for Oracle yuo can use decode ``` select part_no, cust, work_order from your_table where part_no = 'abc' order by...
How to display columns having same value?
[ "", "sql", "" ]
There are the tables: User ``` id | login | password | creationDate _____________________________________ 1 | user1 | 123 | 12.12.12 2 | user2 | 123 | 12.12.12 3 | user3 | 123 | 12.12.12 ``` AdditionalParams ``` id | userId | name | value _______________________________ 1 | 1 | petName | jim 2 | 1 ...
You can use: ``` SELECT u.id, u.login, u.password, ap2.value AS petName FROM User AS u INNER JOIN AdditionalParams AS ap ON u.Id = ap.userId AND ap.name = 'favTea' AND ap.value = 'black' LEFT JOIN AdditionalParams AS ap2 ON u.Id = ap2.userId AND ap2.name = 'petName' ``` It's just a query with two `JOIN` operations...
Just a shot in the dark but I think you could replace your entire query with something this simple. Please note that storing passwords in clear text is horrific. Passwords should be salted and hashed at all times. The original value should NOT be recoverable. I would also make the join the AdditionalParams a left join ...
Select from 2 table
[ "", "sql", "sql-server", "database", "select", "" ]
As mentioned in the title, I would like to have the optimal query to do the following: **WITHOUT SUBQUERIES** I have this [![enter image description here](https://i.stack.imgur.com/O9bsF.png)](https://i.stack.imgur.com/O9bsF.png) So Here, each client has commands(Orders) each client has factures (bills) and a bill co...
You can use correlated sub queries like this: ``` SELECT t.idClient, (select sum(s.montantcommande) from Commande s Where t.idClient = s.idClientCommande) as TotalCommande, (select sum(f.montantfactore) from Facture f Where t.idClient = f.idClientFacture) as TotalFacture FROM Client t ```...
Please use this query ``` SELECT idClient,SUM(MontantCommande) AS TotalCommande , SUM(MontantFacture) AS TotalFacture from client c Inner join commande a on c.IdClient = a.idClientCommande inner join facture b on a.IdCommande = b.IdCommandFacture AND a.idClientCommande = b.idclientFacture group by idClient ```
Get sum of two different columns on two different tables linked to a third table
[ "", "sql", "sql-server", "t-sql", "" ]
I am trying to incorporate old help desk records into a newer help desk app. I still have all the data from the old help desk app and it uses the same fields as the new one but its in a different file. This select statement works fine for the newer application to search all the past calls for something specific, whethe...
I don't know if this is specific to the web app generator that I am using or if you can use it other places in different SQL, but you can reference the parameters and pass them behind the scenes with something called a **parameter parameter** which are the ??1, ??2, ??3 in the second half of the union. This solved the ...
You can always just put the where in both select statements that you're trying to union. Might be faster than combining both tables, then filtering. ``` SELECT * FROM helpdesk.table1 WHERE UPPER(allocated_to) = coalesce(?, allocated_to) AND identity = coalesce(?, identity) AND description = coalesce(?, de...
SQL Union with coalesce(?) in where clause
[ "", "sql", "web-applications", "db2", "union", "" ]
I need Oracle SQL that returns the 'working' week number in year: * no overflowing weeks from one year to another * each week starts from monday * first few days in year are week 01 So the result should be: ``` 2015-12-28 - MON - week 53 2015-12-29 - TUE - week 53 2015-12-30 - WED - week 53 2015-12-31 - THU - week 5...
I found the answer myself, `TO_CHAR(date,'IW')` format is of no use because the very first week in a year according to this standard (ISO) can start after the New Year but also before it (look at `TO_CHAR(TO_DATE('2014-12-31','YYYY-MM-DD'),'IW')=01` the first week that belongs to the next year!) ``` | DAY |...
> W - week number in a month > > WW - week number in a year, **week 1 starts at 1st of Jan** > > IW - week number in a year, according to ISO standard For your requirement, you need to use combination of `IW` and `WW` format. You could combine them using a **CASE** expression. If you want to generate the list of date...
SQL working week in Oracle
[ "", "sql", "oracle", "week-number", "" ]
I've below query: ``` DECLARE @url varchar (max)='http://v.mercola.com/blogs/public_blog/New-Diet-Pill-Expands-1-000-Times-in-Your-Stomach-24728.aspx' SELECT replace(replace(RIGHT(@URL , CHARINDEX ('/' ,REVERSE(@URL))-1),'.aspx',''),'-',' ') as abc ``` Which returns below output: **Actual output** - [![enter image...
Try this ``` DECLARE @url VARCHAR (max)='http://v.mercola.com/blogs/public_blog/New-Diet-Pill-Expands-1-000-Times-in-Your-Stomach-24728.aspx' SELECT Reverse(LEFT(mid, Charindex('/', mid) - 1)) FROM (SELECT Substring(Reverse(@url), Charindex('-', Reverse(@url)) + 1, Len(@url)) AS mid) a ```
Something like this: ``` DECLARE @url varchar (max)='http://v.mercola.com/blogs/public_blog/New-Diet-Pill-Expands-1-000-Times-in-Your-Stomach-24728.aspx' declare @suffix varchar(max) select @suffix = RIGHT(@URL , CHARINDEX ('/' ,REVERSE(@URL))-1) select left(@suffix, len(@suffix) - charindex('-', reverse(@suffix)))...
Return a substring from a specified string in SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "substring", "charindex", "" ]
I have two tables `Products` and `ProductProperties`. ``` Products name - string description - text etc etc ProductProperties product_id - integer property_id - integer ``` There is also a table `Properties` which basically stores the list of property names and their attributes **How can I implement a SQL...
You need to define intermediate resultsets on a property group basis: ``` SELECT DISTINCT p.* FROM products p JOIN product_properties groupA ON groupA.product_id = p.id AND groupA.deleted_at IS NULL AND groupA.property_id IN ('504') JOIN product_properties groupB ON groupB.product_id = p.id AND groupB.deleted_at IS ...
Hi try this queries i just thinking about it so i didn't try any of them check i got the idea i want to do ``` SELECT DISTINCT "products".* FROM products pr WHERE id IN ( SELECT product_id FROM ProductProperties WHERE property_id IN (504,520) GROUP BY product_id HAVING Count(*) = 2 ) AND "products"."del...
WHERE Clause for One-To-Many Association
[ "", "sql", "postgresql", "join", "" ]
I'm honestly really confused here, so I'll try to keep it simple. We have Table A: id Table B: id || number Table A is a "prefilter" to B, since B contains a lot of different objects, including A. So my query, trying to get all A's with a filter; ``` SELECT * FROM A a JOIN B b ON b.id = a.id WHERE CAST(SUBSTRING(b...
You can use the regex substr function to remove everything but digits: `CAST(substring(B.number from '\d') AS integer)`. See working example here: <http://sqlfiddle.com/#!15/cd7e6e/18>
SQL is a declarative language. For a select statement, you declare the criteria the data you are looking for must meet. You don't get to choose the execution path, your query isn't executed procedurally. Thus the optimizer is free to choose any execution plan it likes, as long as it returns records specified by your c...
Query applying Where clause BEFORE Joins?
[ "", "sql", "postgresql", "" ]
What is the best way to format a date in a MySQL query? I am currently running the query below which selects the data but doesn't order the information correctly, I presume this is due to the current format of the 'updatetime' row. ``` SELECT * FROM updates WHERE udcode='Remote Connection' ORDER BY updatetime DESC ...
Use: ``` ORDER BY DATE_FORMAT(updatetime, '%Y-%m-%d %H:%i:%S') DESC ```
you can change the format of your date in MySQL with DATE\_FORMAT ``` SELECT *, DATE_FORMAT(`updatetime`, '%Y-%m-%d %H:%i:%S') AS mydate FROM updates WHERE udcode='Remote Connection' ORDER BY mydate DESC LIMIT 20; ``` <http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format>
MySQL Date Format For Ordering By Date
[ "", "mysql", "sql", "" ]
Guys i have four queries: Query #1: ``` select satisfaction_score,count(satisfaction_score) as Satisfaction_count from j_survey_response where satisfaction_score != 0 group by satisfaction_score ``` The output will be ``` satisfaction_score Satisfaction_count 1 5 2 ...
You can `UNION ALL` the separate queries and apply *conditional* aggregation on the resulting set: ``` select score, max(case when type = 'satisfaction' then count end) as satisfaction_count, max(case when type = 'response' then count end) as response_count, max(case when type = 'responder' then c...
Move them in subqueries and join them by score columns. Like this ``` select q1.satisfaction_score as score, q1.satisfaction_count, q2.response_count, q3.responder_count , q4.service_count, from (query 1) q1 join (query 2) q2 on q1.satisfaction_score=q2.response_score join (query 3) q3 on q1....
count multiple columns in one query
[ "", "mysql", "sql", "" ]
I have the following table: ![product](https://i.stack.imgur.com/x5Ejt.png) where the products are in different categories and i am excepting the output: ![output](https://i.stack.imgur.com/57k05.png) like product and its cost need to be displayed under category(For category cost value i want to display total produ...
Here it goes: Sample Data: ``` CREATE TABLE #product (ID INT, Category VARCHAR(50), Product VARCHAR(50), Value INT) INSERT INTO #product VALUES(1,'Non-veg','Chicken',150), (2,'Non-veg','Mutton',200), (3,'Non-veg','Fish',220), (4,'Non-veg','Prawns',250), (5,'Veg','Gobi',100), (6,'Veg','Parota',45), (7,'Veg','vegbirani...
Using Rollup you would do it like this. ``` SELECT COALESCE(product,category,'Total') Category, SUM(VALUE) cost FROM products GROUP BY ROLLUP(category,product) ```
How to display products under Category in sql in a table
[ "", "sql", "sql-server", "grouping", "rollup", "" ]
I have one master table and 5 child table called ``` @POWER_CHILD, @AUDIO_CHILD, @RESISTOR_CHILD, @CAPACITOR_CHILD, @INDUCTOR_CHILD ``` I need to pull data only when there is an match with child table but any column contain blank i.e no data in master table That will be treated as valid and appear in the output. I ...
Not sure what is described about *blanks* but to return rows from `master` and related details (if any) `LEFT JOIN` may be applied: ``` SELECT * FROM @MASTER m LEFT JOIN @POWER_CHILD pc on pc.PowerAmplifierID = m.PowerAmplifierID LEFT JOIN @AUDIO_CHILD ac on ac.AudioAmplifierID = m.AudioAmplifierID LEFT JOIN @RESISTOR...
Heres my sql - I use multiple left joins and coalesce to replace the nulls. You could add a where clause to remove completely unmatched lines. ``` select m.PowerAmplifierID , Coalesce(pc.PowerAmplifier,'') as PowerAmplifier, m.AudioAmplifierID , Coalesce(ac.AudioAmplifier,'') as AudioAmplifier, m.ResistorID ...
Complicated Join in SQL Server 2008
[ "", "sql", "sql-server", "t-sql", "" ]
By using the below query the output is displayed as below ``` SELECT dlr_acc_acct_id , ( NVL (dlr_jan, 'D') || NVL (dlr_feb, 'D') || NVL (dlr_mar, 'D') || NVL (dlr_apr, 'D') || NVL (dlr_may, 'D') || NVL (dlr_jun, 'D') || NVL (d...
If you are on 11gR2 and above, use **LISTAGG**: ``` SELECT DLR_ACC_ACCT_ID, listagg(PAYMENT_HISTORY_PROFILE, '') within GROUP( ORDER BY PAYMENT_HISTORY_PROFILE) PAYMENT_HISTORY_PROFILE FROM table_name GROUP BY DLR_ACC_ACCT_ID; ``` Use appropriate column in the `ORDER BY` clause.
Pushing what you have down into a subquery and adding the year for ordering listagg(), the following should work: ``` SELECT dlr_acc_acct_id , listagg(payment_history_profile,'') WITHIN GROUP (ORDER BY dlr_year) as full_history_profile FROM ( SELECT dlr_acc_acct_id ,dlr_year , ( NVL (dlr_jan, 'D')...
to combine the output of three rows in to single value in sql
[ "", "sql", "oracle", "" ]
I have two tables: `Products` and `CategoryProducts`. `CategoryProducts` contains: ``` PrdID Category ----------------- ``` `Products` contains: ``` PrdID Barcode Url ----------------------- ``` I have Product's Barcode value, for example 111111. > Need to select all Products.Url with the same Category, a...
Based on your comment, this is what you want: ``` SELECT t.Url FROM Products t INNER JOIN CategoryProducts s ON(s.PrdID = t.PrdID) WHERE s.CategoryID = (select p.categoryID from CategoryProducts p INNER JOIN Products f ON(p.prdID = f.prdID) WHERE f.barcode = 42244) ``` Sel...
``` SELECT p.url FROM Products p JOIN CategoryProducts cp ON cp.PrdID = p.id // WHERE p.id = 175 GROUP BY p.url, p.Category ``` And if you need add comment query
Sqlite select statement from 2 tables
[ "", "sql", "sqlite", "" ]
I need some help in this my **case** is 1-two parameters date from , date to 2-number of team parameter that manually enter by user for later on use in some calculation **rquirement** count only working days (6days per week ) without Friday based on filtered period (date from and date to) **Code** ``` =(COUNT(IIF...
Try this: ``` =(DATEDIFF(DateInterval.Day, CDATE("2016-02-14"), CDATE("2016-02-17")) + 1) -(DATEDIFF(DateInterval.WeekOfYear, CDATE("2016-02-14"), CDATE("2016-02-17")) * 2) -(IIF(WeekdayName(DatePart(DateInterval.Weekday,CDATE("2016-02-14"),FirstDayOfWeek.System))="sunday",1,0) -(IIF(WeekdayName(DatePart(DateInterval....
The most sustainable solution for this kind of question, in the long term, is to create a "[date dimension](https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/)" aka "calendar table". That way any quirks in the classification of dates that don't conform to some neat ma...
SSRS count working days only
[ "", "sql", "reporting-services", "ssrs-2012", "reportbuilder3.0", "" ]
Started BI Publisher about a week ago. When working on a new data model, about one or two queries in, I get this error when I try to save: ``` Failed to load servlet/res?s=%252F~developer1%252Ftest%252FJustin%2520Tests%252FOSRP%2520Information.xdm&desc=&_sTkn=9ba70c01152efbcb413. ``` I can no longer save my data mode...
After restarting your server once you won't get this issue.It happens some time due to the connection problem.so restart should work for this.It resolved my problem.
None of the proposed solutions worked for me. I found out, on my own, that any unnecessary brackets around CASE in a select statement will cause this error. Remove the unnecessary brackets and the error goes away.
BI Publisher - Fail to load and save data model
[ "", "sql", "datamodel", "bi-publisher", "" ]
I have a result set which provide me 2 columns named `Sequence` and `CorrectAns` and it contains N rows(100 rows right now to be specific). Now what I want is to divide these 100 rows to N columns(right now into 4 columns). So, how to do that? Any help would be appreciated. [![enter image description here](https://i...
What you want is to pivot your data. Aside from the `PIVOT` command, one way to do that is to use conditional aggregation: [**SQL Fiddle**](http://sqlfiddle.com/#!6/ce882/1/0) ``` ;WITH Cte AS( SELECT *, grp = (ROW_NUMBER() OVER(ORDER BY Seq) -1) % (SELECT CEILING(COUNT(*) / (4 * 1.0)) FR...
use the following query, ``` SELECT * FROM ( SELECT Seq, CorrectAns, gro FROM your_table ) as t PIVOT ( SUM(gro) FOR CorrectAns IN (A,B,C,D....) )AS pvt ```
Divide N rows to N columns
[ "", "sql", "sql-server", "" ]
It is possible to insert multiple rows in one table using values from select statement? an example: ``` INSERT INTO SomeTable (UserID, ModuleID, ModuleRights) VALUES (u.UserId, 1, 15), (u.UserId, 2, 1), (u.UserId, 4, 3), (u.UserId, 8, 7) SELECT * FROM Users u ```
Yes, but you need to be careful how you do it. In this case, it appears you want a `cross join`: ``` INSERT INTO SomeTable (UserID, ModuleID, ModuleRights) SELECT u.UserId, v.ModuleID, v.ModuleRights FROM Users u CROSS JOIN (VALUES (1, 15), (2, 1), (4, 3), ...
``` INSERT INTO SomeTable (UserID, ModuleID, ModuleRights) SELECT u.UserID, u.ModuleID, u.ModuleRights FROM Users u; ``` If your `ModuleID` and `ModuleRights` are not part of the `users` table then insert nulls or dummy values and replace on needed condition.
Inserting multiple rows into some table using values from select statement
[ "", "sql", "sql-server", "" ]
I need to join data from two different tables as shown below. Is that possible with only one sql query? If the "key" and "name" are on both tables, then it those are identical. "Status" is always "-" on table1 and "T" on table2. Also "name" and "comp" are match on both tables (example: Name3-C and Name4-B). I have tr...
If I understand correctly, you want a `full outer join`: ``` select coalesce(t1.name, t2.name) as name, t1.time as time1, t2.time as time2, coalesce(t1.comp, t2.comp) as comp, coalesce(t1.key, t2.key) as key, t2.status from table1 t1 full outer join table2 t2 on t1.key = t2.key an...
``` SELECT T1.time AS Time1, T2.Time AS Time2, ISNULL(T1.COMP,T2.Comp) AS Comp, ISNULL(T1.Key,T2.Key) FROM TABLE1 T1 FULL OUTER JOIN TABLE2 T2 ON T1.key = T2.key ```
SQL query, join two tables
[ "", "sql", "join", "union", "" ]
I have one query which is like this: ``` CREATE TABLE #Employee (Id INT, Name NVARCHAR(100), Status TINYINT) GO INSERT INTO #Employee ( Id, Name, Status) Values (1, 'Basavaraj Biradar', 0), (2, 'Shree Biradar', 0), (3, 'Kalpana Biradar', 0) GO DECLARE @LoopCounter INT = 1, @MaxEmployeeId INT = 10 , ...
This can be done without a `WHILE` loop or a `CURSOR`. All you need is a [Tally Table](https://stackoverflow.com/questions/32096103/selecting-n-rows-in-sql-server/32096374#32096374): [**SQL Fiddle**](http://sqlfiddle.com/#!6/292b8/1/0) ``` DECLARE @MaxEmployeeId INT = 10; DECLARE @N INT; SELECT @N = CEILING(@MaxEmp...
You will need two loops. The outer loop defines the number of repetitions, while the inner loop will print all available names from the table. Try this - ``` CREATE TABLE #Employee (Id INT, Name NVARCHAR(100), Status TINYINT) GO INSERT INTO #Employee ( Id, Name, Status) Values (1, 'Basavaraj Biradar', 0), (2, ...
How to update incrementally the data into another table using loops?
[ "", "sql", "sql-server", "t-sql", "" ]
Basic SQL question but I have a mind blank. I have a table with the following setup: ``` date eventType ----------------------- 01/01/2016 0 02/01/2016 0 03/01/2016 2 03/01/2016 2 04/01/2016 6 04/01/2016 6 04/01/2016 6 04/01/2016 6 05/01/2016 0 06/01/2016 ... ``` I want to retur...
I have a different solution, check this: ``` DECLARE @dtEventType DATE = '20160101' DECLARE @table TABLE ( cDate DATE , eventType TINYINT ) INSERT INTO @table VALUES( '20160101' , 0 ) , ( '20160102' , 0 ) , ( '20160103' , 2 ) , ( '20160103' , 2 ) , ( '20160104' , 6 ) , ( '20160104' , 6 ) , ( '20160104' , 6 ) , ( '2...
Hmmm. I think this may be a bit trickier than it seems. This does what you want for the data in the question: ``` select e.* from events e cross join (select top 1 eventType from events where date > getdate() and eventType <> 0 order by date ) as nexte where e.date > getdate() and e.e...
SQL Server query return next date with an event
[ "", "sql", "sql-server", "" ]
I would like to know what options we have to do not make dynamic queries. For example: ``` IF @Mail <> '' BEGIN SELECT @Where = @Where + ' AND Mail = @Mail ' END ELSE IF @Phone <> '' BEGIN SELECT @Where = @Where + ' AND Phone like ''%'' + @Phone ' END ``` I would like not do do this, I would like to avoid d...
You can try this ``` AND ((ISNULL(@Mail,'') = '' or mail = @mail) OR (ISNULL(@Phone,'') = '' or Phone like '%' + @Phone)) ```
If you are going for performance, the best solution is to make separate queries for each of the cases. Gordon's solution is fine, but SQL server will not use any indexes you may want to use on the columns you filter by. It can be enhanced to use indexes by adding OPTION(RECOMPILE), but this will cause to recompile the...
SQL Server alternative to dynamic query
[ "", "sql", "sql-server", "dynamic-sql", "" ]
I have this Oracle table which I want to clean from time to time when I reach 2000 rows of data: ``` CREATE TABLE AGENT_HISTORY( EVENT_ID INTEGER NOT NULL, AGENT_ID INTEGER NOT NULL, EVENT_DATE DATE NOT NULL ) / ``` How I can delete the oldest row from the table when the table reaches 2000 rows?
You can delete all but the newest 2000 rows with the following query: ``` DELETE FROM agent_history a WHERE 2000 < ( SELECT COUNT(1) cnt FROM agent_history b WHERE b.event_date < a.event_date ) ``` The query checks every row in the table (a) to see how many rows have an event\_date LESS than that row. If there are m...
Create a DBMS\_JOB or DBMS\_SCHEDULER, that kicks off after certain interval and call a procedure. In that procedure check the count and delete the rows based on event\_date. --- Sorry, I didn't see your comment until now. Here is the code you were looking for. Make sure you have the grants to create scheduler progra...
Delete Oracle rows based on size
[ "", "sql", "oracle", "oracle11g", "oracle10g", "" ]
I want to select rows where some precise column has different values while another precise column has the same value. Exemple : ``` COLUMN_A | COLUMN_B __________|___________ | 1 | 2002 1 | 2002 2 | 2001 2 | 2007 3 | 2010 3 | 2010 ``` Now, suppo...
This is the case for Count(**Distinct** *ColumnName*). It ensures that only unique values are taken into account. ``` With Src As ( Select * From (Values (1, 2002), (1, 2002), (2, 2001), (2, 2007), (3, 2010), (3, 2010) ) V (COLUMN_A, COLUMN_B) ) Select * From...
You can use: ``` SELECT COLUMN_A FROM dbo.YourTable GROUP BY COLUMN_A HAVING MIN(COLUMN_B) <> MAX(COLUMN_B); ``` Another way can be using `EXISTS`: ``` SELECT * FROM dbo.YourTable A WHERE EXISTS(SELECT 1 FROM dbo.YourTable WHERE COLUMN_A = A.COLUMN_A AND COLUMN_B <> A.COLUMN_B); ```
SQL select row where (this column has many different values in the other)
[ "", "sql", "sql-server", "" ]
Hello I need to take most countable countries from DB. how it looks like: ``` id name country 1 fsdf Sweden 2 dfdf Brazil 3 fgfg Sweden 4 gfgg Germany 5 fgfg Germany 6 fgfg Poland 7 fdff Germany 8 iuii Brazil 9 tyyt Sweden 10 tyut Sweden 11 gfgf Germany 12 fdff Holland ``` And I want output from this - from ...
The correct syntax in MySQL uses `LIMIT`, not `TOP`: ``` select country, count(*) as cnt from list_ots group by country order by cnt desc limit 5; ```
Use must use `LIMIT` to get top 5: ``` SELECT country, count(*) as count FROM list_ots GROUP BY country ORDER by count desc LIMIT 5; ```
Selecting top 5 most count countries in SQL
[ "", "mysql", "sql", "database", "" ]
I am running into a problem where a part of one of my triggers is failing. This failure is causing the transaction that wraps the trigger to rollback. The problem comes in that it is not raising an error to the invoke point of the command. It is acting like there was no error within the transaction and the only way it ...
The `RAISERROR` statement is not a severe error that halts processing. In fact, [MSDN says](https://msdn.microsoft.com/en-us/library/ms188792(v=sql.110).aspx): > The THROW statement honors SET XACT\_ABORT. RAISERROR does not. New > applications should use THROW instead of RAISERROR. You can verify this behavior by ru...
Some exceptions have [severity](https://msdn.microsoft.com/en-us/library/ms164086.aspx) that is not enough to break execution of current batch. It just goes on and performs subsequent statements. If I'm not mistaken, constraint violation is not a batch-breaking error for example. To ensure whole batch breaks on notice...
TSQL: Prevent trigger suppressing error but rolling back transaction
[ "", "sql", "sql-server", "hibernate", "t-sql", "" ]
I'm using SSRS/SSDT in Visual Studio 2015 and SQL Server 2014. There's a bug that's been present for > 8 years where [you can't select multiple columns from different tables that have the same name](https://stackoverflow.com/questions/14466874/in-ssrs-why-do-i-get-the-error-item-with-same-key-has-already-been-added-wh)...
I feel very stupid for this, but apparently it works to just call `p.Id` in the subquery. It knows that I'm referencing the parent query's value even though it's in the subquery. Thank you everyone for your help. ``` SELECT t.[Description], t.RequestedCompletionDate, t.CommitDate, t.StatusId, ...
> current code (doesn't work because the subquery returns multiple > rows). So instead of this ``` AND ( SELECT StatusId FROM Project -- WHERE ? ) NOT IN (3, 4) ``` You could do ``` AND EXISTS ( SELECT 1 FROM Project p2 WHERE p2.StatusId IN (3, 4) AND p2.Id = p.Id ) ```
Pass parameter to subquery
[ "", "sql", "sql-server", "reporting-services", "" ]
could you please help me to get a solution for my issue. I was using sybase database. I have two table trans\_status, trans\_ref trans\_status :- ``` | Corre_ID | Pro_type | Desc | Datetime | |----------|----------|-----------|-------------------------| | ABC_01 | Books | Started | 17/02/2...
So what you want is this: ``` SELECT t.Corre_ID,s.Payment_ID, max(case when t.Desc = 'Started' then t.Datetime end) as startDate, max(case when t.Desc = 'Finished' then t.Datetime end) as startDate, TIMESTAMPDIFF(HOUR,max(case when t.Desc = 'Started' then t.Datetime end), max(...
You must join the trans\_status Table twice to get the start and end date. Since the end date may be missing you have to make the second join a left join. Try the following query: ``` SELECT r.Corre_ID, Payment_ID, s_start.Datetime AS StartDate, s_end.Datetime AS EndDate, TIMEDIFF(s_end.Datetime, s_start.Dat...
How to get start/end date from single date column from an sql query
[ "", "mysql", "sql", "sybase", "" ]
I got a problem in Mysql sine a few days and i can't solve it (i'm pretty bad with DB) and I hope you can help me :) I'm going to simplify the problem so you can see where I'm stuck ! I got two tables : ``` current_stock (article_id, ...) stock_record (id, article_id) ``` Current\_stock describes the actual stock an...
You can use variables to enumerate records. Then join on row number and ignore rows having a match in `stock_record`: ``` SELECT t1.* FROM ( SELECT *, @rn1 := IF(@aid = article_id, @rn1 + 1, IF(@aid := article_id, 1, 1)) AS rn1 FROM current_stock CROSS JOIN (SELECT @rn1 := 0, @aid ...
Your correct exists() query: ``` SELECT * FROM current_stock t WHERE NOT EXISTS (SELECT * FROM stock_record s where t.article_id = s.article_id) ``` The problem in your query, that you need to check if a **specific** id not exists in stock\_record, and not if any id not exists there. And your cor...
Mysql : How to find non duplicate rows with left join?
[ "", "mysql", "sql", "database", "join", "exists", "" ]
Im building a code that learns tic tac toe, by saving info in a database. I have two tables, `Games(ID,Winner)` and `Turns(ID,Turn,GameID,Place,Shape)`. I want to find parent by multiple child infos. For Example: ``` SELECT GameID FROM Turns WHERE GameID IN (WHEN Turn = 1 THEN Place = 1) AND GameID IN (WHEN Turn = 2...
This very simple query will do the trick in a single scan, and doesn't require you to violate **First Normal Form** by storing multiple values in a string (shudder). ``` SELECT T.GameID FROM Turns AS T WHERE (T.Turn = 1 AND T.Place = 1) OR (T.Turn = 2 AND T.Place = 4) GROUP BY T.GameID HAVING Count(*) = 2; ``` ...
The general solution to your problem can be accomplished by using a sub-query that contains a self-join between two instances of the Turns table: ``` SELECT * FROM Games WHERE GameID IN ( SELECT Turns1.GameID FROM Turns AS Turns1 INNER JOIN Turns AS Turns2 ON Turns1.GameID = Turns2.GameID WHERE ...
Selecting rows from Parent Table only if multiple rows in Child Table match
[ "", "sql", "ms-access", "" ]
I have the below Table Table1 ``` Emp ID | Emp Name 001 | ABC 002 | DEF 003 | GHI 004 | ABC 005 | XYZ ``` I am trying to get EMP ID and Emp Name where Emp Name is same but Emp ID is different. There is primary key in the table Here the output will be ``` Emp ID | Emp Name 001 | ABC 004 | ABC `...
You didn't specify your DBMS, so this is ANSI SQL: ``` select emp_id, emp_name from ( select emp_id, emp_name, count(*) over (partition by emp_name) as name_count from employee ) t where name_count > 1^; ```
I have the same problem yesterday :) and i believe below code will give you what you want. Use `INNER JOIN` to make a self join query, then use `HAVING` clause. ``` CREATE TABLE #Table1 (Emp_ID int, Emp_Name varchar(50)) INSERT INTO [#Table1] ( [Emp_ID], [Emp_Name] ) SELECT '001','ABC' UNION ALL SELECT '002'...
SQL Query to get name that appear twice
[ "", "sql", "" ]
I need a query to get string with space in between. i.e it should not return strings like ``` ' abc', 'abc ' and ' abc ' ``` and it should return strings like ``` 'ab c' ,' ab c', 'ab c ' and ' ab c ' ``` i tried with below query. ``` select user_fname,user_lname from user where user_fname like '% %'; ``` but it...
`%` matches [*zero* or more characters](https://msdn.microsoft.com/en-us/library/ms179859.aspx). I'd suggest adding some `_`s in: ``` select user_fname,user_lname from user where user_fname like '%_ _%'; ``` If that's still matching too much, perhaps: ``` select user_fname,user_lname from user where user_fname like ...
Try this: ``` SELECT user_fname,user_lname FROM user WHERE user_fname LIKE '% %' AND user_fname NOT LIKE ' %' AND user_fname NOT LIKE '% ' ```
Strings with space in between
[ "", "sql", "string", "sql-server-2008", "" ]
I have two models `Product` and `ProductProperties`. So, I store the properties for products in the Product Properties model which is associated with another model `Properties` How can I implement a scope that finds a product with the properties (A or B or C) AND (X or Y or Z) Filters I currently have are like so -- ...
So this is the join that I used -- ``` def self.find_with_properties property_ids, group_name joins(:product_properties).joins('JOIN product_properties '+group_name+' ON '+group_name+'.product_id = products.id AND '+group_name+'.property_id IN ('+property_ids.to_s.tr('[', '').tr(']', '').tr('"', '') +')') ...
First of all I think you should not use scope for this task You should create a Class method to do it. It's best practice to not use scope when complex logic is involved. Secondly it's nothing wrong the above mentioned code. It's about calling them wrong. I recon you are chaining above scopes. By definition both abov...
Filtering with Joins - Rails
[ "", "sql", "ruby-on-rails", "activerecord", "" ]
I have a table like: ``` +------------+-------------------+--------------+------------+ | listing_id | transaction_title | image_thumb | sale_date | +------------+-------------------+--------------+------------+ | 226835186 | Title Version 11 | Img Style 11 | 2016-02-08 | +------------+-------------------+--------...
You can use row\_number base approach with data sorted descending first on listing\_id and sale\_date and then picking the rows with row\_number 1. This will give you the required dataset. A query template for this approach is as follows: ``` SELECT INVW.listing_id, INVW.transaction_title, INVW.image_thumb, INVW.sale...
You can use a derived table containing maximum dates per `listing_id`. If you `INNER JOIN` to this table you can get the exprected result set: ``` select t1.listing_id, transaction_title, image_thumb, sale_date from mytable as t1 inner join ( select listing_id, max(sale_date) max_date from mytable group by li...
Select the latest version based on date for each ID in MYSQL
[ "", "mysql", "sql", "max", "distinct", "mysql-num-rows", "" ]
When a particular form loads I need to grab a distinct list of locations from a table, with the eventual goal of displaying them to the user (baby steps though, I'll get to that). The code below generates no error, but when I try to loop through the recordset returned by my query, I get an error in relation to the int...
If I'm not missing something, you could just use *GetRows*: ``` Dim locations As Variant RS.MoveLast i = RS.RecordCount RS.MoveFirst locations = RS.GetRows(i) ```
Thanks to @Arvo who commented that I had forgotten to move to the next record in my `do` loop. Adding `RS.MoveNext` to the loop fixed the problem. ``` Do Until RS.EOF = True locations(i) = RS![AD Location] i = i + 1 ReDim Preserve locations(i) RS.MoveNext Loop ```
Recordset with few results causing 'Overflow' error
[ "", "sql", "ms-access", "distinct", "" ]
I faced the following requirement. The following query is called by a procedure. The value `p_pac_code` is the input parameter of the procedure. The requirement is the query should have an additional condition `sp_sbsp.SUBSPCLTY_CODE!='C430` if the `p_pac_code` value is '008'. For any other `p_pac_code` value, it sho...
Just add: ``` AND NOT ( NVL( sp_sbsp.SUBSPCLTY_CODE, 'x' ) = 'C430' AND NVL( p_pac_code value, 'x' ) = '008' ) ``` to the where clause. The `NVL` function is used so that it will match `NULL` values (if they exist in your data); otherwise, even though `NULL` does not match `C430` you will still fin...
You can simply add a condition like this: ``` ... and ( ( sp_sbsp.SUBSPCLTY_CODE!='C430' and p_pac_code = '008') OR NVL(p_pac_code, '-') != '008' ) ``` This can be re-written in different ways, this one is quite self-explanatory
change where condition based on column value
[ "", "sql", "oracle", "" ]
This is being done on Oracle 11, and I'm trying to create a trigger where if the incoming meets certain values, to update another table. ``` --CREATE TRIGGER ON ITX CREATE OR REPLACE TRIGGER TRG_I_LAST_RECEIVED AFTER INSERT ON ITEM_TRANSACTION_LOG FOR EACH ROW WHEN ( NEW.ITEM_CONDITION_ID = 5005 ...
Your `update` statement is missing a semicolon at the end. Since it sounds like you come from a T-SQL background, in SQL Server, semicolons are generally optional. They're always required in Oracle ``` BEGIN UPDATE PART SET LAST_REPAIRED = SYSDATE WHERE PART_NO = :NEW.ITEM_PART_NO; END; ```
Most probably you have missed the ":" before "NEW.ITEM\_CONDITION\_ID" and others columns, and ofcourse as "Justin Cave" mentioned you need ";" after update statement.
Creating a Trigger on Oracle
[ "", "sql", "oracle11g", "triggers", "" ]
I have a non periodic art course. Every day I add a new "present" entry to a table. I would like to know what are the student that missed the last 2 days. Just the last 2 days. > Important, each student choose a different weekday to have a class. and some of them 2 days per week. I do have 2 tables, **Students** and...
Lots of problems with your query. Try rewriting it to use `joins`. You also have to define the last 2 days. I've attempted to do that with a `subquery` below. Then you need to use `aggregation` to see if the student missed both days. Here's something that should be close: ``` select s.id, s.name from students s inn...
Another solution with one subuqery. Please check if it meets your requirement. ``` SELECT s.id, s.name, ( SELECT SUM(p.present = false) FROM p WHERE p.student_id = s.id ORDER BY p.day DESC LIMIT 2 ) AS misses_two_last_days FROM s; ```
SQL how count last entries for each id based on a criteria
[ "", "mysql", "sql", "nested", "" ]
I'm trying to create a computed column in order to have a unique index on a nullable column that ignores NULL rows1. I've composed this test case: ``` SELECT TEST_ID, CODE, UNIQUE_CODE, CAST(UNIQUE_CODE AS VARBINARY(4000)) AS HEX FROM ( SELECT TEST_ID, CODE, ISNULL(CODE, CONVERT(VARCHAR, SPACE(10)) + CONVERT(V...
There you go with `" 3"` ``` SELECT TEST_ID, CODE, UNIQUE_CODE, CAST(UNIQUE_CODE AS VARBINARY(4000)) AS HEX FROM ( SELECT TEST_ID, CODE, ISNULL(CODE, CONVERT(VARCHAR(20), SPACE(10)) + CONVERT(VARCHAR(20), TEST_ID)) AS UNIQUE_CODE FROM ( SELECT 1 AS TEST_ID, cast('ABCDEFGHIJ' as varchar(20)) AS CODE...
It looks like SQL is trying to help out to define the column length in your inner query. By casting/converting to a specific size this fixes the problem. Once your `UNIQUE_CODE` field exceeds this value, the returned value is limited to the size of the column. ``` SELECT TEST_ID, CODE, UNIQUE_CODE, CAST(UNIQUE_CODE AS...
Computed column does not include one of the values
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
I have this query, that will return me the ids of the favorited audios by the user, ordered by the date when they marked that ID as favorite: ``` SELECT audio_id FROM favorites WHERE user_id = ? ORDER BY `time` DESC ``` Now, I try to display those audios in the screen, ordered also by date ``` SELECT * FROM audios W...
The reason that it is not ordered by time is because your `ORDER BY` is in the inner `SELECT` statement. so it does not apply to the outer `SELECT` This should work for you: ``` SELECT DISTINCT A.* FROM audios AS A INNER JOIN favorites AS F ON A.id = F.audio_id AND F.user_id = ? AND A.status = '1' ORDER BY...
The `ORDER BY` on the query in the `WHERE` clause does not have an impact on the data in the `SELECT` statement. Making the query a join, allows the data to be stored in it's current location, and still be able to sort accordingly. ``` SELECT A.*, f.[time] FROM audios A INNER JOIN favorites f ON A.au...
Order result of query with the order of IN subquery
[ "", "mysql", "sql", "" ]
``` SELECT departments.department_id, department_name, departments.manager_id, first_name, max(salary) as Maximum_Salary, min(salary) Minimum_Salary FROM departments,employees WHERE departments.department_id = employees.department_id AND departments.manager_id = employee_id GROUP BY depa...
You have to make two JOINs to the employees table : first join between employee and manager\_id, and second join between employee and department\_id. Something like this should work: ``` SELECT d.department_id, d.department_name, d.manager_id, m.first_name, max(e.salary) as Maximum_Salary, mi...
You'll need to select the employees table as following: *employees.salary* and *employees.first\_name*. The query will look like this: ``` select departments.department_id,department_name,departments.manager_id,employees.first_name,max(employees.salary) as Maximum_Salary,min(employees.salary) Minimum_Salary from depa...
How to get the maximum and minimum salary of all the departments along with department name,manager id, manager name of each department?
[ "", "sql", "" ]
I have a question regarding SQL dates. The table I am working with has a date field in the following format: "22-SEP-08". The field is a date column. I am trying to figure out how to output records from 1/1/2000 to present day. The code below is not filtering the date field: ``` Select distinct entity.lt_date from ...
DATEs do ***not*** have "a format". Any format you *see* is applied by the application *displaying* the date value. You can either change the configuration of SQL Developer to display dates in a different format, or you can use `to_char()` to format the date the way you want. --- The reason your statement does not w...
My guess is the data type isn't a Date. Just in case its a char type, try to convert it using the Oracle TO\_DATE() function. The Oracle documentation below should help you with parameters. <http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions183.htm>
SQL Date Format Conversion
[ "", "sql", "oracle", "" ]
**Data:** ``` id uid type 1 20 A 2 20 B 3 20 A 4 6 A 5 1 A 6 3 A 7 6 A 8 1 B ``` **Scenario:** I want to group by `type` and sort it by `id`. I am using group by to group the `uid`. **Current Query:** ``` SELECT type, GROUP_CONCAT(DISTINCT ...
The mistery of MySQL. Actually the engine takes first value in ASC order, no matter that you are asking for DESC by ID, so first "flip" the table, then: ``` SELECT type, GROUP_CONCAT(DISTINCT uid ORDER BY id DESC) AS users, COUNT(type) AS typeCount FROM (SELECT * FROM `test2` ORDER BY id DESC) test2 G...
The answer from @mitkosoft is already right. I am posting this just to analyze the right expected result. From the following output, we can see that, for type 'A' group, before DISTINCT taking effect, after ORDER BY id DESC, the rows are: 6 3 1 6 20 20 Then DISTINCT can produce two possible results: 6,3,1,20 or 3,1...
Sorting in group_concat
[ "", "mysql", "sql", "group-by", "group-concat", "" ]
I am trying to do a three table join to display all columns. Only two of the tables have a key in common. Below is the code for the tables I already have: ``` CREATE TABLE Faculty ( FacultyID int, FirstName varchar(30), LastName varchar(30), EMail varchar(60), BirthDate DATE, Numbr_Courses int, PRIMARY KEY (FacultyID)...
I would change your `Faculty_Courses` table: ``` CREATE TABLE Faculty_Courses( InstanceID int, FacultyID int, CourseID int, PRIMARY KEY (InstanceID), FOREIGN KEY (FacultyID) REFERENCES Faculty(FacultyID), FOREIGN KEY (CourseID) REFERENCES Courses(CourseID) ); ``` And then join all three tables together: ...
I'm surprised your `factory_courses` table doesn't have a reference to `courses`. Either way, with your current query, you are selecting from `faculty` and `courses` but aliasing `faculty_courses` -- you cannot do that. This is what your current query should look like: ``` select * from faculty f join faculty_cou...
Trying to do a three table join displaying all columns
[ "", "sql", "inner-join", "" ]
I have a table in SQL Server database that has a 2 fields X, Y. These fields represent coordinates on a field (american football field). 0,0 (X,Y) is the starting point with the largest value and furthest away point being 145,90 (X,Y). Each row in the table is a coordinate from the pitch. I want to be able to measure...
You can use the Geometry type. <https://msdn.microsoft.com/en-us/library/bb895270.aspx> Here's some quick examples. Use a derived column to create a Point: ``` CREATE TABLE #Test ( X INT, Y INT, POINT AS GEOMETRY::STGeomFromText('POINT('+CONVERT(VARCHAR(20),X)+' '+CONVERT(VARCHAR(20),Y)+')',0 ) ) INSERT INTO ...
Do you remember the Pythagorean Theorem from algebra class? <http://betterexplained.com/articles/measure-any-distance-with-the-pythagorean-theorem/> That is what is used the measure the "long" side of a triangle which is what you are measuring here. You don't need anything special other some basic math for this. You kn...
Storing custom coordinates in SQL Server
[ "", "sql", "sql-server", "geospatial", "geography", "" ]
I need to write a query in sql server that let's me get get month registered in my table and somehow covert those months into 4 seasons(autumn,fall,spring,summer). Does anyone know how to make this done??
One method is a `case`. Your question doesn't clarify the logic, but here is an example: ``` (case when month(date) in (12, 1, 2) then 'winter' when month(date) in (3, 4, 5) then 'spring' when month(date) in (6, 7, 8) then 'summer' when month(date) in (9, 10, 11) then 'autumn' end) as season ```
``` (CHOOSE(month(TheDate),'Winter', 'Winter', 'Spring', 'Spring', 'Spring', 'Summer', 'Summer', 'Summer', 'Autumn', 'Autumn', 'Autumn', 'Winter')) ```
Sql Query that somehow converts months to 4 seasons
[ "", "sql", "sql-server", "" ]
I have a large data set which for the purpose of this question has 3 fields: * Group Identifier * From Date * To Date On any given row the `From Date` will always be less than the `To Date` but within each group the time periods (which are in no particular order) represented by the date pairs could overlap, be contai...
The solution from book "Microsoft® SQL Server ® 2012 High-Performance T-SQL Using Window Functions" ``` ;with C1 as( select GroupID, FromDate as ts, +1 as type, 1 as sub from dbo.table_name union all select GroupID, dateadd(day, +1, ToDate) as ts, -1 as type, 0 as sub from dbo.table_name), C2 as( select C1.* ...
I'd use a `Calendar` table. This table simply has a list of dates for several decades. ``` CREATE TABLE [dbo].[Calendar]( [dt] [date] NOT NULL, CONSTRAINT [PK_Calendar] PRIMARY KEY CLUSTERED ( [dt] ASC )) ``` There are many ways to [populate such table](http://sqlperformance.com/2013/01/t-sql-queries/generat...
Condense Time Periods with SQL
[ "", "sql", "sql-server", "sql-server-2012", "" ]
Data in Phone\_number column of my Temp\_table looks like this ``` 1234560200 1234560201 1234560202 2264540300 2264540301 2264540302 2264540303 2264540304 2264540305 2264540306 ``` I want it to find sequence of last 4 digits and and find First and Last number of sequence of it. For eg. There is sequence of first 3 ro...
I think something like this might work: ``` select min (substr (phone_number, -4, 4)) as first, max (substr (phone_number, -4, 4)) as last from temp_table group by substr (phone_number, -4, 2) ```
One method to get sequences is to use the difference of row numbers approach. This works in your case as well: ``` select substr(phone_number, 1, 6), min(substr(phone_number, 7, 4)), max(substr(phone_number, 7, 4)) from (select t.*, (row_number() over (order by phone_number) - row_num...
Finding sequence in data and grouping by it
[ "", "sql", "oracle", "gaps-and-islands", "" ]
I am working using SQL Server for a client and they have given me a request. They have a table `products` with many columns, one of which is `article`. There are about 28,000 rows in `products`. They wish to create a new table `articles` that contains only the article numbers from `products`, but set up so that the n...
If I understand your question correctly, you want to transform rows of `article` into a table with 3 columns. Here is a try: ``` ;WITH Cte AS( SELECT article, grp = (ROW_NUMBER() OVER(ORDER BY article) -1) % (SELECT CEILING(COUNT(*) / (3 * 1.0)) FROM products) FROM products ), CteFinal ...
You can use NOT EXISTS clause, like when inserting in articles2 table, you can check it like NOT EXISTS (SELECT ARTICLE\_ID FROM ARTICLES2). I hope you are getting my point. Apart from that, if you can modify the structure of main ARTICLE table, then you can add a column with the name say PROCESSED (it would be a bool...
SQL Server long column into multiple shorter columns
[ "", "sql", "sql-server", "sql-update", "sql-insert", "ssms-2014", "" ]
When I hit the below code without where clause, it shows row with `NULL` value but when I put where clause like below then there is no row with `NULL` value. I want the row with `NULL` value with where clause. ``` SELECT * FROM project_category as a LEFT OUTER JOIN project_estimate_detail as b ON a.id = b.proj...
Try this: ``` SELECT * FROM project_category as a LEFT OUTER JOIN project_estimate_detail as b ON a.id = b.project_cat_id where (b.project_cat_id IS NULL) OR (b.project_cat_id not in ('21','22','2')) ``` When `b.project_cat_id` is `NULL` then `NOT IN` evaluates to `NULL`. So you have to *explicitly* check fo...
``` SELECT * FROM project_category AS a LEFT OUTER JOIN project_estimate_detail AS b ON a.id = b.project_cat_id WHERE b.project_cat_id NOT IN ( '21', '22', '2' ) AND b.project_cat_id IS NULL ```
Also show row with NULL value
[ "", "mysql", "sql", "" ]
This question is regarding query optimization to avoid multiple call to database via PHP. So Here is scenario, I have two tables one contains information you can call this as reference table and another one is data table, fields `key1` and `key2` are common in both table, based on these fields, we can join them. I do...
try this one ``` SELECT key1, key2, info1, info2, SUM(Scount) AS serial_count, GROUP_CONCAT(Skey1, ' ', Skey2) AS serial_ids, SUM(Pcount) AS product_data_count, GROUP_CONCAT(Pkey1, ' ', Pkey2) AS product_data_ids FROM ( SELECT DISTINCT IF(b.serial < 10 OR b.product_data IS NOT NULL,a.key1...
How about combining your two queries with a JOIN? SQL: ``` SELECT tbl1.key1, tbl1.key2, tbl1.info1, tbl1.info2, tbl1.serial_count, tbl1.serial_ids, tbl2.product_data_count, tbl2.product_data_ids FROM ( select * , count(*) as serial_count,GROUP_CONCAT(key1,' ',key2) as serial_ids from ( SELECT distinct ...
Mysql group_concat of repeated keys and count of repetition of multiple columns in 1 query ( Query Optimization )
[ "", "mysql", "sql", "join", "mariadb", "" ]
Does it make any difference omitting the "AS" before defining the name of a column when creating a new view? ``` SELECT T.STUFF AS MY_STUFF ``` VS ``` SELECT T.STUFF MY_STUFF ```
A view is just a [stored query](http://docs.oracle.com/cd/E11882_01/server.112/e40540/schemaob.htm#CNCPT311), so [the `select` syntax](http://docs.oracle.com/cd/E11882_01/server.112/e41084/statements_10002.htm#i2126854) applies. As you can see from the syntax diagram for the select list items: [![enter image descripti...
It doesn't make any difference from the DB's point of view. Personally, I prefer the explicit `AS` and a separate line in my SQL statement per column for a couple of reasons: * you can easily search for a given column alias (just grep for `AS <alias>`) * without the `AS`, you might forget a comma - this results in one...
Oracle column alias in select: is "AS" mandatory?
[ "", "sql", "oracle", "oracle11g", "" ]