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 database that has a table `Parameters_XML` with columns. ``` id, application, parameter_nr flag, value ``` The `parameter_nr` is for example 1 and the value for that parameter is the following: ``` <Root> <Row> <Item id="341" flags="1"> <Str>2</Str> </Item> <Item id="342" flags="1"> ...
Try someting like this: ``` SELECT CAST(x.Value AS XML).value('(/Root/Row/Item[@id="341"]/Str)[1]', 'nvarchar(100)') FROM dbo.Parameters_Xml x WHERE parameter_nr = 1 ``` You're telling SQL Server to go find the `<Item>` node (under `<Root> / <Row>`) with and `id=341` (that what I'm assuming - your value in the q...
``` DECLARE @str XML; SET @str = '<Root> <Row> <Item id="341" flags="1"> <Str>2</Str> </Item> <Item id="342" flags="1"> <Str>10</Str> </Item> <Item id="2196" flags="1"> <Str>7REPJ1</Str> </Item> </Row> </Root>' -- if you want specific values then SELECT xmlData.Col.value...
Querying XML data in SQL Server 2012
[ "", "sql", "sql-server", "t-sql", "" ]
Hi all consider following as my table structure ``` Col1 Col2 Col3 A 1 Aa A 2 Bb A 1 Aa A 4 Bb B 2 Bb C 1 Aa C 5 Bb D 3 Aa ``` As you can see Col3 contains distint values of Aa and Bb. I am trying to write a query which return only rows with ...
``` SELECT * FROM TableName T WHERE EXISTS ( SELECT 1 FROM TableName WHERE T.Col1 = Col1 AND Col3 = 'Aa') ```
One other approach is to use `intersect` and `union`. [Fiddle with sample data](http://www.sqlfiddle.com/#!3/878b2/3) ``` select * from t where col1 in ( select col1 from t where col3 = 'Aa' intersect select col1 from t where col3 = 'Bb' union select col1 from t where col3 = 'Aa') ```
How to select rows with column containing provided values
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I am looking for help with the following scenario: I have an SQL Server DB, with a table that stores historical data. For example lets use the following as a sample set. ``` CAR, SERVICE DATE, FINDINGS 1234, 21/01/2001, Fuel Filter 1234, 23/09/2009, Oil Change 1234, 30/09/2015, Tyres 3456, 30/09/2015, Clutch ``` I w...
Use an [EXISTS](https://msdn.microsoft.com/en-us/library/ms188336.aspx) clause: ``` SELECT cur.car, cur.[service date], cur.findings FROM tablename cur WHERE cur.[service date] = @mydate AND EXISTS ( SELECT 1 FROM tablename past WHERE past.car = cur.car AND past.[service ...
This question had many conditions like > * One of the service should happen on specified date. > * Previous service to that date shoule only be 'Oil Change'. If previous service is not 'Oil Change' then don't include it in result, > even if it meets condition 1. Along with this, if car has record of > OIL Chagne i...
SQL Query - Query on Current Date but condition from the past
[ "", "sql", "sql-server", "" ]
I´d like to check for dupes in MySQL comparing two columns: Linked duplicate doesn't match as it's about finding the duplicate values on specific columns. This question is about finding the rows which have said duplicate values. Example: ``` id Column1 Column2 ------------------------- 3 1 ...
You can use this to find the duplicates: ``` SELECT column1, column2 FROM yourtable GROUP BY column1, column2 HAVING count(*) > 1; ``` And to show the actual duplicate rows you can `JOIN` against results of the above query: ``` SELECT * FROM yourtable yt1 JOIN (SELECT column1, column2 FROM yourtable GROUP BY c...
``` select * , count(column1) from table group by column1, column2 having (count(column1) >1) ``` that is one solution. you will get all columns which exist more than one time, through the having. and the group by collects all together. the count could also go on both or column 2, that is not so important
Check for dupes in db with TWO rows
[ "", "mysql", "sql", "" ]
I have two tables which are interlinked: Table #1: CheckList ``` ID_CHECKLIST(PK) | NAME_CHECKLIST | VERSION(PK) 1 XYZ 1.0.0 1 XYZ 1.1.0 1 XYZ 1.2.0 2 PQR 1.0.0 3 ABC ...
You'd want to LEFT JOIN the tables on the composite key, and look for a NULL value on the right table in the join. This will tell you where you are missing data. ``` SELECT CheckList.ID_CHECKLIST, CheckList.NAME_CHECKLIST, CheckList.VERSION FROM Machine_CHECKLIST LEFT JOIN CheckList ON Machine_Checklist.ID_C...
Try an Inner Join. You don't have to return columns of both tables, but you can use both tables for filtering. ``` SELECT CHECKLIST.ID_CHECKLIST, CHECKLIST.NAME_CHECKLIST, CHECKLIST.VERSION FROM CHECKLIST INNER JOIN Machine_CHECKLIST ON CHECKLIST.ID_CHECKLIST = Machine_CHECKLIST.ID_CHECKLIST AND CHECKLIST.VER...
How to filter records when foreign table has combined primary key in SQL
[ "", "sql", "sql-server", "foreign-keys", "" ]
I have the following query: ``` SELECT pics.e_firedate FROM et_pics ``` Result: ``` NULL 2014-12-01 00:00:00.000 2015-04-03 00:00:00.000 NULL NULL ``` I want to replace `NULL` values to ''. ``` CASE WHEN pics.e_firedate IS NULL THEN '' ELSE pics.e_firedate END ``` makes `NULL` transforming to `19...
That's because when using `CASE` expressions, the return values must have the same data type. In case they have different data types, all values are converted to the type with a [**higher data type precedence**](https://msdn.microsoft.com/en-us/library/ms190309.aspx). And since `DATETIME` has a higher datatype than `V...
Try: ``` select isNUll(CONVERT(VARCHAR, pics.e_firedate, 120), '') e_firedate FROM et_pics ```
TSQL Null data to '' replace
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "" ]
I have a bit tricky question. E.g. I have a start\_date: 15/01/2015 and an end date: 17/03/2015 for given record and I would like to generalize that to know, if the record with those exact start and end date belongs to January (by my definition even if it is 31/01/2015, then it belongs to January). I did the following...
Just use `trunc` instead of `round`. `Trunc` with parameter `'MONTH'` will truncate the date to the first day of month. If you test with `between` using first day of month it's ok.
``` SELECT expected, CASE WHEN to_date('01/01/2015','DD/MM/YYYY') = ALL (trunc(start_date,'MONTH'), trunc(end_date,'MONTH')) THEN 1 ELSE 0 END flag_jan FROM (SELECT 'notmatch 0' expected , to_date('15/01/2015','DD/MM/YYYY') start_date ...
how to compare date parts in SQL Oracle
[ "", "sql", "oracle", "date", "" ]
I need to create an Oracle DB function that takes a string as parameter. The string contains letters and numbers. I need to extract all the numbers from this string. For example, if I have a string like **RO1234**, I need to be able to use a function, say `extract_number('RO1234')`, and the result would be **1234**. T...
You'd use `REGEXP_REPLACE` in order to remove all non-digit characters from a string: ``` select regexp_replace(column_name, '[^0-9]', '') from mytable; ``` or ``` select regexp_replace(column_name, '[^[:digit:]]', '') from mytable; ``` Of course you can write a function `extract_number`. It seems a bit like overki...
You can use **regular expressions** for extracting the number from string. Lets check it. Suppose this is the string mixing text and numbers 'stack12345overflow569'. This one should work: ``` select regexp_replace('stack12345overflow569', '[[:alpha:]]|_') as numbers from dual; ``` which will return "12345569". also ...
Extract number from string with Oracle function
[ "", "sql", "oracle", "oracle11g", "oracle-sqldeveloper", "sqltools", "" ]
I would like to have a query that uses the greater of two values/columns if a certain other value for the record is true. I'm trying to get a report account holdings. Unfortunately the DB usually stores the value of Cash in a column called `HoldingQty`, while for every other type of holding (stocks, bonds, mutual fund...
Your query is correct but need few syntax arrangement, try below code ``` SELECT h.account_name, h.security_name, h.security_type, h.price, CASE WHEN security_type = 'cash' then CASE when h.qty > h.holdingqty then h.qty else h.holdingq...
Almost there! ``` SELECT h.account_name , h.security_name , h.security_type , h.price , CASE WHEN security_type = 'cash' THEN CASE WHEN h.qty > h.holdingqty THEN h.qty ELSE h.holdingqty END ELSE qty END AS quantity , h.total_value FROM ...
Select case comparing two columns
[ "", "sql", "sql-server", "t-sql", "select", "case-when", "" ]
I get a row, which contains non-zero values in two columns: `FixHours` and `AddHours`: ``` FixHours | AddHours | CalculatedValue ---------+----------+---------------- 0,5 | 1,5 | 16.5 ``` How can I split it into two rows such as: ``` FixHours | AddHours | CalculatedValue ---------+----------+---...
Assuming I understand your question correctly, I think something like this is what you are looking for: ``` SELECT FixHours, AddHours, CalculatedValue FROM tbl WHERE FixHours = 0 OR AddHours = 0 UNION SELECT FixHours, 0, CalculatedValue FROM tbl WHERE FixHours <> 0 AND AddHours <> 0 UNION SELECT 0, AddHours, Calcu...
Something like this should do it: ``` select case when x=1 THEN 0 ELSE fixHours END as fixHours, case when x=2 THEN 0 ELSE addHours END as addHours, calculatedValue from input cross join (select 1 as x UNION select 2 as x) ```
How to split row into two rows in MS SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table which stores 0-6 as weekday value, and I want to display weekday name. E.g. if value is `0`, it will display `Sunday`, if value is `1`, it will display `Monday`, likewise. Is there any inbuilt MySQL function for getting day name from Index? Thanks in Advance!!
`DAYNAME( date_value )` is available in MySql; however, this takes a date, not an int. So if you have the date available, you can just use `DAYNAME(CURDATE())`, `DAYNAME('2014-01-07')`, etc. If all you have available is the int representing the weekday, then a CASE statement might be your best bet. `CASE WHEN 0 THEN ...
As @Aliminator mentioned, you could use [`DAYNAME`](https://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_dayname) with a `DATE`. However, if you don't want to change your schema, here is a nifty hack for you: ``` SELECT DAYNAME(CONCAT("1970-09-2", dayIndex)) FROM your_table; ``` This is bas...
Get Weekday name from index number in MYSQL
[ "", "mysql", "sql", "date", "" ]
I have a varchar2 field in my db with the format of for example - ``` 2015-08-19 00:00:01.0 2014-01-11 00:00:01.0 etc. ``` I am trying to convert this to a date of format DD-MON-YYYY. For instance, 2015-08-19 00:00:01.0 should become 19-AUG-2015. I've tried ``` select to_date(upgrade_date, 'YYYY-MM-DD HH24:MI:SS') ...
You have details upto milli seconds, for which, you have to use `TO_TIMESTAMP()` with format model '`FF`' ``` select to_timestamp('2015-08-19 00:00:01.0' ,'YYYY-MM-DD HH24:MI:SS.FF') as result from dual; RESULT --------------------------------------------------------------------------- 19-AUG-15 12.00.01.000000000 AM...
Why do you store datetimes in a string??? Anyhow. To get from '2015-08-19 00:00:01.0' to a datetime with milliseconds (which is a `TIMESTAMP` in Oracle) use `to_timestamp`: ``` to_timestamp('2015-08-19 00:00:01.0', 'yyyy-mm-dd hh24:mi:ss.ff') ``` Then to get the desired output format, use `to_char`: ``` to_char(the...
convert string literal to a date
[ "", "sql", "oracle", "oracle11g", "" ]
Consider a database that maintains a list of persons and their contact information, including addresses and such. Sometimes, the contact information changes. Instead of simply updating the single person record to the new values, I like to keep a history of the changes. I like to keep the history in a way that when I ...
Must you keep ***structured*** history information? * Quite often, the history of changes does not have to be structured, because the history is needed for auditing purposes only, and there is no actual need to be able to perform queries against the historical data. + So, what quite often suffices is to ***simply l...
This is generally referred to as [Slowly Changing Dimension](https://en.wikipedia.org/wiki/Slowly_changing_dimension) and linked Wikipedia page offers several approaches to make this thing work. Martin Fowler has a list of [Temporal Patterns](http://martinfowler.com/eaaDev/timeNarrative.html) that are not exactly DB-s...
SQL schema pattern for keeping history of changes
[ "", "sql", "database-schema", "" ]
I get these [Challenge on HackerRank](https://www.hackerrank.com/challenges/weather-observation-station-6) > Write a query to print the list of CITY that start with vowels (a, e, > i, o, u) in lexicographical order. Do not print duplicates. **My solution:** ``` Select DISTINCT(City) From Station Where City like 'A%'...
Regular expressions in MySQL / MariaDB: ``` select distinct city from station where city regexp '^[aeiouAEIOU]' order by city ```
In SQLserver You can use a reg-ex like syntax with like: ``` select distinct city from station where city like '[aeuio]%' Order by City ```
Wildcard with multiple values?
[ "", "sql", "" ]
I have this example table: ``` sort_order product color productid price ---------- ------- ------ --------- ----- 1 bicycle red 2573257 50 2 bicycle red 0983989 40 3 bicycle red 2093802 45 4 bicycle ...
You can use an additional query in the `SELECT` clause to effectively perform an aggregate query on the same data: ``` SELECT t.product, Avg ( t.price ) AS average_price, ( SELECT IF ( Count(*) = t4.count, NULL, t2.color ) 'color' FROM products t2 ...
``` SELECT m.product , AVG(m.price) avg_price , n.color most_frequent FROM my_table m JOIN ( SELECT x.product , x.color FROM ( SELECT product , color , COUNT(color) total FROM my_table GROUP ...
how to return most frequent value for a certain column for each group in GROUP BY query?
[ "", "mysql", "sql", "group-by", "" ]
I need to find all employees whose supervisor's supervisor has a SSN of '888665555' I can't seem to figure out what I'm not doing correctly. Here is a copy of the table being used. ``` Fname Lname Ssn Super_ssn john smith 123456789 333445555 franklin wong 333445555 888665555 alicia zelaya 9998...
I found the answer thanks to NSNoob. ``` SELECT EMPLOYEE.Fname, EMPLOYEE.Lname FROM EMPLOYEE WHERE EMPLOYEE.Super_ssn IN (SELECT EMPLOYEE.Ssn FROM EMPLOYEE WHERE EMPLOYEE.Super_ssn = '888665555'); ``` This takes each of the results instead of only accepting one.
Your subquery below is returning more than one results. ``` (SELECT EMPLOYEE.Ssn FROM EMPLOYEE WHERE EMPLOYEE.Super_ssn = '888665555'); ``` Modify it like ``` (SELECT top 1 EMPLOYEE.Ssn FROM EMPLOYEE WHERE EMPLOYEE.Super_ssn = '888665555'); ``` Or something like that which returns you only one result by ...
Find employees whose supervisor's supervisor is a specific person
[ "", "sql", "ms-access", "" ]
I have a `users` table and an `emails` table. A user can have many emails. I want to grab only those users that have more than one email. Here is what I have so far: ``` SELECT Users.name, emails.email FROM Users INNER JOIN emails On Users.id=Emails.user_id /*specify condition to only grab duplicates here */ ```
``` SELECT u.id FROM Users u INNER JOIN emails e On u.id = e.user_id group by u.id having count(distinct e.email) > 1 ``` Use `group by` and `having`
You can also use a CTE: ``` ;WITH CTE AS ( SELECT Users.name, emails.email, ROW_NUMBER() OVER (PARTITION BY emails.email ORDER BY emails.email) AS 'Rank' FROM Users INNER JOIN emails On Users.id=Emails.user_id) SELECT * FROM CTE WHERE Rank > 1 ```
Return Only Duplicate Records After Inner Join
[ "", "mysql", "sql", "" ]
I've got 2 tables - **dishes** and **ingredients**: in **Dishes,** I've got a list of pizza dishes, ordered as such: [![Dishes Table](https://i.stack.imgur.com/1O23n.png)](https://i.stack.imgur.com/1O23n.png) In **Ingredients,** I've got a list of all the different ingredients for all the dishes, ordered as such:[![I...
**1. The logic of the DB structuring - am I doing it correctly?** * This is denormalized data. To normalize it, you would restructure your database into three tables: + `Pizza` + `PizzaIngredients` + `Ingredients` `Pizza` would have `ID`, `name`, and `type` where `ID` is the primary key. `PizzaIngredients` wou...
It seems to me that a better Database Structure would have a **Dishes\_Ingredients\_Rel** table, rather than having a bunch of columns for Ingredients. ``` DISHES_INGREDIENTS_REL DishesID IngredientID ``` Then, you could just do a much simpler JOIN. ``` SELECT Ingredients.Name FROM Dishes_Ingredients_Rel INNER J...
SQL Inner Join With Multiple Columns
[ "", "mysql", "sql", "join", "inner-join", "" ]
I am trying to create a numerator(num) and denominator(den) column that I will later use to create a metric value. In my numerator column, I need to have a criteria that my denominator column does not have. When I add the where clause to my sub query, I am getting the error below. I do not want to add INRInRange to my ...
Create a sub-query that counts `PersonDetailB.INRInRange` and LEFT OUTER JOIN it with the original query. ``` SELECT Main.PracticeAbbrevName, InRange.Num AS num, Main.den FROM (SELECT dbo.PersonDetailSpecialty.PracticeAbbrevName, COUNT(DISTINCT dbo.Problem.PID) AS den FROM ...
The problem with this statement: ``` SELECT dbo.PersonDetailSpecialty.PracticeAbbrevName, (SELECT COUNT(DISTINCT dbo.Problem.PID) WHERE PersonDetailB.INRInRange = 'True') AS num, COUNT(DISTINCT dbo.Problem.PID) AS den ``` is that `PersonDetailB.INRInRange1` doesn't have a unique value in each group. I...
Subquery Where clause invalid in select list
[ "", "sql", "sql-server", "join", "group-by", "subquery", "" ]
I want to add condition to below select sql code. ``` select rtrim(ltrim(SUBSTRING(line,1,CHARINDEX('|',line) -1))) as drivename ,round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('|',line)+1, (CHARINDEX('%',line) -1)-CHARINDEX('|',line)) )) as Float)/1024,0) as 'capacity(GB)' ,round(cast(rtrim(ltrim(S...
Multiple ways to do this.. `Temp table` and `CTE` may seems like the same but try to understand difference between them from [here.](https://dba.stackexchange.com/a/13117/72998) > **By using Temporary table** ``` select * into ##t from (select rtrim(ltrim(SUBSTRING(line,1,CHARINDEX('|',line) -1))) as drivename, ...
Use CTE or subquery: ``` ;WITH cte as ( select rtrim(ltrim(SUBSTRING(line,1,CHARINDEX('|',line) -1))) as drivename ,round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('|',line)+1, (CHARINDEX('%',line) -1)-CHARINDEX('|',line)) )) as Float)/1024,0) as 'capacity(GB)' ,round(cast(rtrim(ltrim(SUBSTRING(line,...
SQL Server - Where condition usage
[ "", "sql", "sql-server", "t-sql", "" ]
I am tryng to complete a new column in a table. I need that the value of this new column be the creation date of the row. My best efford for the previous values of the table is use the ORA\_ROWSCN. I achieve select this value in a query but the update fails: ``` UPDATE mytable AA SET AA.reg_date = SCN_TO_TIMESTAM...
I'm afraid that the only reliable way of retrieving the creation date would have been by making sure you persisted that information when you created the rows. Using `scn_to_timestamp` with `ora_rowscn` to retrieve the creation timestamp can't work for the following reasons: * If it works, it will only give you an app...
ORA\_ROWSCN is by default the last update of the whole block, so all rows within the block will have the same (the one assigned during last DML). The table would need to have created with ROWDEPENDENCIES to store the SCN for each row (requires additional space). Also SCN\_TO\_TIMESTAMP function is limited in range wha...
use ORA_ROWSCN value for update a column in oracle 10g
[ "", "sql", "oracle", "oracle10g", "" ]
I have a MySQL table with data as:- ``` country | city --------------- italy | milan italy | rome italy | rome ireland | cork uk | london ireland | cork ``` I want query this and group by the country and city and have counts of both the city and the country, like this:- ``` country | city | city_count |...
You can use a correlated sub-query: ``` SELECT country, city, count(city) as city_count, (SELECT count(*) FROM jobs AS j2 WHERE j1.country = j2.country) AS country_count FROM jobs AS j1 GROUP BY country, city ``` [**Demo here**](http://sqlfiddle.com/#!9/f99e86/1)
You can just do it in subquery on results. ``` SELECT jm.country, jm.city, count(city) as city_count, (select count(*) from jobs j where j.country = jm.country) as country_count FROM jobs jm GROUP BY jm.country, jm.city ``` [SQL Fidlle example](http://sqlfiddle.com/#!9/c7def/6/0)
SQL Group By and Count on two columns
[ "", "mysql", "sql", "group-by", "" ]
I am using healthcare data and need to identify a patient's number of stays and admit date and leave date in location 'X'. However, the problem is that patients move between different locations and I need to account for the time in between. Sometimes a patient will start in location 'X', move to location 'Y', and then ...
Not sure if this is what you tried to do, but this combines first the adjacent stays in the same location into one, then filters out the ones that are in y and over 48 hours, then it combines all the stays that are adjacent together. Sorry for the bad table aliases, maybe CTEs could be more clear. ``` select patienti...
Neat! This got me digging into the documentation for recursive CTEs. ``` declare @data table (patientID bigint ,Location char,InDateTime datetime ,OutDateTime datetime ) INSERT INTO @DATA (PatientID,Location,InDateTime,OutDateTime) VALUES( 1, 'x', '7-9-2003 10:00am', '7-9-2003 1:00pm') IN...
Calculate length of stay in certain location (include in-between stays at other locations if less than 48 hrs)
[ "", "sql", "sql-server", "t-sql", "" ]
I am trying to convert XML node values to comma separated values but, getting a > Incorrect syntax near the keyword 'SELECT'. > error message ``` declare @dataCodes XML = '<Root> <List Value="120" /> <List Value="110" /> </Root>'; DECLARE @ConcatString VARCHA...
Try this; ``` DECLARE @dataCodes XML = '<Root> <List Value="120" /> <List Value="110" /> </Root>'; DECLARE @ConcatString VARCHAR(MAX) SELECT @ConcatString = COALESCE(@ConcatString + ', ', '') + Code FROM ( SELECT T.Item.value('@Value[1]', 'VARCHAR(MAX...
For future readers, XML data can be extracted into arrays, lists, vectors, and variables for output in comma separated values more fluidly using general purpose languages. Below are open-source solutions using OP's needs taking advantage of `XPath`. **Python** ``` import lxml.etree as ET xml = '<Root>\ <Lis...
Converting XML node values to comma separated values in SQL
[ "", "sql", "sql-server", "" ]
What's the problem with syntax. I tried to do `INNER JOIN` 3 tables, but I am getting below error message > **Additional information: Incorrect syntax near the keyword 'on'.** ``` SELECT train.id, train.class_id, train.type_id, train.m_year, train_type.type, train_type.avarage_speed...
You have syntax error in your [join.](http://www.w3schools.com/sql/sql_join_inner.asp) The syntax for join is as follows: ``` SELECT column_name(s) FROM table1 JOIN table2 ON table1.column_name=table2.column_name; ``` Hence your query will be like the following: ``` " SELECT train.id, train.class_id, train.type_id,...
You have missed the 2nd and 3rd tables while using INNER JOIN. ``` INNER JOIN <Table 2> on train.class_id = train_class.id INNER JOIN <Table 3> on train.type_id = train_type.id ```
vb.net INNER Join 3 tables: Additional information: Incorrect syntax near the keyword 'on'
[ "", "sql", "vb.net", "inner-join", "" ]
I have the following query: ``` SELECT DISTINCT T0.DocNum, T0.Status, T1.ItemCode, T2.ItemName, T1.PlannedQty, T0.PlannedQty AS 'Net Quantity' FROM OWOR T0 INNER JOIN WOR1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN OITM T2 ON T0.ItemCode = T2.ItemCode WHERE T0.Status = 'L' AND T1.I...
See the SQL code below. ``` declare @input_tbl table ( doc_num int, item_code varchar(15), item_name varchar(10), planned_qty decimal(15,9), net_qty decimal(15,9) ) declare @ouput_tbl table ( doc_num int, item varchar(15), name varchar(10), quantity decimal(15,9) ) -- Inserting sample data shown by you. You will have...
You should use a UNION. I guess ``` (/*your original query*/) UNION SELECT DISTINCT T0.DocNum, T0.Status, 'BurnLoss' AS ItemCode, T2.ItemName, SUM(T1.PlannedQuantity)-T0.PlannedQuantity AS PlannedQuantity, T0.PlannedQuantity AS 'Net Quantity' FROM OWOR T0 INNER JOIN WOR1 T1 ON T0.DocEntry = T1.Do...
Transforming a column into a row
[ "", "sql", "sql-server-2012", "" ]
I am struggling to get this answer for some reason. I have two tables, table1 and table2 which look like this: Table1: ``` ID Location Warehouse 1 London Narnia 2 Cyprus Metro 3 Norway Neck 4 Paris Triumph ``` Table2: ``` ID Area Code 1 London Narnia 2 Cyprus Metro 3 ...
Use `exists`: ``` select t.location, t.warehouse from table1 t where exists (select 1 from table2 t2 where t.location = t2.area and t.warehouse = t2.code ); ``` I should point out that some databases support row constructors with `in`. That allows you to do: ``` select t.loca...
Maybe I'm missing something, but a simple join on the two conditions would give you the result in your example: ``` select t1.* from table1 t1 join table2 t2 on t1.Location = t2.Area and t1.Warehouse = t2.Code; ``` Result: ``` | ID | Location | Warehouse | |----|----------|-----------| | 1 | Londo...
Where clause to check against two columns in another table
[ "", "sql", "join", "where-clause", "where-in", "" ]
We have a table Phone whose values are ``` (Name, Number) -------------- (John, 123) (John, 456) (Bravo, 789) (Ken, 741) (Ken, 589) ``` If the question is to Find the guy who uses only one number, the answer is Bravo. I solved this using `aggregate` function. But I don't know how to solve without using aggregate fun...
Here is my solution: ``` SELECT * FROM test t WHERE NOT EXISTS ( SELECT 1 FROM test WHERE NAME = t.NAME AND number <> t.number); ``` And a sample [SQLFiddle](http://sqlfiddle.com/#!3/faae5/3). I'm not sure about this representation in relational algebra (and it's most likely not c...
You can use `LEFT JOIN` and use the same table in your `JOIN` , something like this.. ``` SELECT a.NAME, a.NUMBER FROM test a LEFT JOIN test b ON a.name = b.name AND a.number <> b.number WHERE b.name IS NULL; ``` Hope this helps. :)
Relational algebra without aggregate function
[ "", "sql", "aggregate-functions", "relational-algebra", "" ]
I'm stuck on a pretty simple task. An image is better than words so here's a sample of my table : I'd like to retrieve every distinct product\_id that are both in groups 27 and 16 for exemple. So I made this request : ``` SELECT DISTINCT product_id FROM my_table WHERE group_id = 27 AND group_id = 16 ``` It's not w...
You may do as ``` SELECT product_id FROM my_table WHERE group_id in(27,16) group by product_id having count(DISTINCT group_id) >= 2 ```
You can use `EXISTS`: ``` SELECT DISTINCT m1.product_id FROM my_table m1 WHERE m1.group_id = 27 AND EXISTS (SELECT 1 FROM my_table m2 WHERE m1.product_id = m2.product_id AND m2.group_id = 16); ```
MySQL : Check condition on two rows
[ "", "mysql", "sql", "" ]
I want to query db rows using two standards: A first, B second. That is: Order by A, if A values are the same, Order by B as the second standard How to write the sql? Example: query table: ``` id | A | B _ _ _ _ _ _ 1 | 1 | 1 _ _ _ _ _ _ 2 | 2 | 2 _ _ _ _ _ _ 3 | 2 | 1 _ _ _ _ _ _ 4 | 3 | 1 ``` query result: ``...
Order by is used to sort the result from a table in ASC | DESC based on one or more column names. It sorts by ASC in default. Example: `Select * from Table1 order by A, B` In this example the results from Table1 is sorted in ASC by A as well as B. If A has the same values, then the results will be sorted by B in ASC
You can simply have multiple order-by's: `ORDER BY A DESC,B` for example.
Query rows using Order by A, if A values are the same, Order by B as the second standard
[ "", "mysql", "sql", "sql-order-by", "" ]
Imagine a database like this: [![test database](https://i.stack.imgur.com/zihAk.png)](https://i.stack.imgur.com/zihAk.png) And looking for all the students - teachers sets that don't share any courses. Result should be a `(Student.Name - Teacher.Name)` tuple. This idea is near the solution but not exactly what wante...
You could start with a cross join and then remove any pair that has a relationship: ``` SELECT s.firstname, s.lastname, t.firstname, t.lastname FROM students s CROSS JOIN teachers t WHERE NOT EXISTS (SELECT * FROM stu_cou sc JOIN tea_cou tc ON sc.courses...
In Oracle you can use `minus`, or SQL Server or PostgreSQL's `except` set operator: (functionally equivalent) ``` select s.firstname as stud_fname, s.lastname as stud_lname, t.firstname as teac_fname, t.lastname as teac_lname from students s cross join teachers t minus select s.firstname, ...
SQL for retrieving tuples of not related records
[ "", "sql", "select", "cross-join", "" ]
In have table called "MYGROUP" in database. I display this table data in tree format in GUI as below: ``` Vishal Group | |-------Vishal Group1 | |-------Vishal Group1.1 | |-------Vishal Group1.1.1 | |-------Vishal Group2 | |-------Vishal Group2.1 | |-------Vish...
You can use recursive stored procedure like this : ``` SET TERM ^ ; create or alter procedure MYGROUP_PROC ( IPARENT varchar(64)) returns ( PK_GROUP varchar(64), DESCRIPTION varchar(255), LINKED_TO_GROUP varchar(64)) as declare variable I integer; BEGIN FO...
As a cleaner alternative to a recursive stored procedure, here is a stored procedure using CTE(Common Table Expressions): ``` SET TERM ^ ; CREATE OR ALTER procedure RECURSIVE_MYGROUP ( PK_GROUP_IN GUID) returns ( PK_GROUP GUID, DESCRIPTION varchar(255), LINKED_TO_GROUP GUID) as begin for with recurs...
How To Get Entire Linked Group Details using SQL?
[ "", "sql", "firebird", "common-table-expression", "recursive-query", "firebird2.5", "" ]
I have an excel sheet with several values which I imported into SQL (book1$) and I want to transfer the values into ProcessList. Several rows have the same primary keys which is the ProcessID because the rows contain original and modified values, both of which I want to keep. How do I make SQL ignore the duplicate prim...
> How do I make SQL ignore the duplicate primary keys? Under no circumstances can a transaction be committed that results in a table containing two distinct rows with the same primary key. That is fundamental to the nature of a primary key. SQL Server's `IGNORE_DUP_KEY` option does not change that -- it merely affects...
try this `INSERT IGNORE INTO ProcessList SELECT Edited, ProcessId, Name, Amount, CreationDate, ModificationDate FROM Book1$ SELECT * FROM ProcessList`
How to ignore duplicate Primary Key in SQL?
[ "", "sql", "duplicates", "primary-key", "" ]
is there a way to reverse an entire column? Example: ``` ID ColX ColY ColZ 0 001 010 100 1 002 020 200 2 003 030 300 ``` shall be: ``` ID ColX ColY ColZ 0 003 030 300 1 002 020 200 2 001 010 100 ``` So the Column ID shall be ...
You can do it using variables: ``` SELECT t2.ID, ColX, ColY, ColZ FROM (SELECT ID, ColX, ColY, ColZ, @row_number := @row_number + 1 AS rn FROM mytable CROSS JOIN (SELECT @row_number := 0) AS var ORDER BY ID) AS t1 INNER JOIN ( SELECT ID, @rn := @rn + 1 AS rn FROM ...
If you don't have gaps in your ID, then you can use [this select query](http://sqlfiddle.com/#!9/63227/1): ``` SELECT max_id-ID AS ID, ColX, ColY, ColZ FROM mytable CROSS JOIN (SELECT MAX(ID) AS max_id FROM mytable) m ORDER BY ID ``` or this [update query](http://sqlfiddle.com/#!9/8aa69d/1) (but it will w...
SQL Reverse entire column
[ "", "mysql", "sql", "reverse", "" ]
How can I check how many products added by a,b,c,d respectively by using a query? table1 ``` admin_id admin_name 3 a 4 b 5 c 6 d ``` table2 ``` admin_id products 3 pDeal 3 pSeal 4 pAeal 5 pZeal 6 pXeal 3 pHeal 6 ...
You need a simple JOIN and a COUNT query: ``` SELECT table1.admin_name, COUNT(*) as cnt FROM table1 INNER JOIN table2 ON table1.admin_id = table2.admin_id GROUP BY table1.admin_name ```
Try this... ``` SELECT a.admin_name, COUNT(b.products) as 'CountOfProducts' FROM table1 a INNER JOIN table2 b ON a.admin_id = b.admin_id GROUP BY a.admin_name ```
Select count with join in SQL query
[ "", "mysql", "sql", "" ]
I have the following table, which represent Customers for each day: ``` +----------+-----------+ | Date | Customers | +----------+-----------+ | 1/1/2014 | 4 | | 1/2/2014 | 7 | | 1/3/2014 | 5 | | 1/4/2014 | 5 | | 1/5/2014 | 10 | | 2/1/2014 | 7 | | 2/2/2014 | 4...
I think this might be easier by using `lag()` and an aggregation sub-query. The ANSI Standard syntax is: ``` Select t.*, tt.sumCustomers, tt.prev_sumCustomers From table t join (select extract(year from date) as yyyy, extract(month from date) as mm, sum(Customers) as sumCustomers, lag(su...
The previous month is a bit tricky. What's your Teradata release, TD14.10 supports `LAST_VALUE`: ``` SELECT dt, customers, Sum_of_Current_month, -- return the previous sum COALESCE(LAST_VALUE(x ignore NULLS) OVER (ORDER BY dt ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECED...
SQL sum over partition for preceding period
[ "", "sql", "teradata", "" ]
Need some help with this query, I just want to know if what I am doing is fine or do I need JOIN to get it better. Sorry if this a silly question but I am little worried as I query the same table thrice. Thanks in advance ``` Select * from TableA where (A_id in (1, 2, 3, 4) and flag = 'Y') or (A_id in...
Your approach is indeed way too complicated. Select from A where flag = Y or the sum of related B > 0. Do the latter in a subquery. ``` select * from a where a_id in (1,2,3,4) and ( flag = 'Y' or (select sum(qty) from b where b.a_id = a.a_id) > 0 ) ```
There's nothing badly wrong with the query you've presented, but there are improvements that can be made. If you move the test for Flag='N' into your first select from TableA and correlate your select from TableB with your first select from TableA, then you can dispense with the second select from TableA: ``` Select *...
Need help in SQL Select Query
[ "", "sql", "select", "join", "" ]
I need to identify the first character in my data as numeric or character in SQL Server. I am relatively new to this and I don't know where to begin on this one. But here is what I have done to this point. I had data that looked like this: ``` TypeDep Transfer From 4Z2 Transfer From BZZ Transfer From 123 Transfer From...
Using `LEFT` and `ISNUMERIC()`, however be aware that `ISNUMERIC` thinks some additional characters such as `.` are numeric ``` UPDATE #decode SET SecondPartType = CASE WHEN ISNUMERIC(LEFT(firstPartType, 1)) = 1 THEN'Numeric' ELSE 'Alpha' END FROM #decode; ```
A more robust approach is to use the limited regex functionality of sql server. ISNUMERIC will return false positives for single characters like .,$ to name a few. ``` SELECT CASE WHEN left(firstPartType, 1) like '[0-9]' THEN 'Numeric' ELSE 'Alpha' END AS SecondPartType ```
How do identify the first character of a string as numeric or character in SQL
[ "", "sql", "sql-server", "" ]
I have a table where I insert the year, month number, week number of the year, and day number of the year with each record. I'm using those fields to filter records instead of full date because I have millions of records, and I want to increase the performance by comparing integers instead of dates. I was able to sel...
Your method of storing the dates is exactly wrong for what you want to do. The general form would be: ``` where (year = 2014 and day >= 275 or year > 2014) and (year = 2015 and day <= 176 or year < 2015) ``` This will work for any pair of years, not just those that are one year apart. Now, if you stored the da...
``` SELECT COUNT(id) AS records_count FROM table1 WHERE (year = 2014 and day >= 275) OR (year = 2015 and day <= 176) ``` And as baao commented - an indexed date column is super fast and easier to query.
MySQL select records between day of the year and year
[ "", "mysql", "sql", "date", "select", "date-range", "" ]
I cannot figure out how to do this. I have looked through my book on oracle SQL and it has nothing of sort about this function. I am not sure if my instructor did not mean to ask this question or if there is a way to do it.
[`INSTR`](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions068.htm) > The INSTR functions search string for substring. The function returns > an integer indicating the position of the character in string that is > the first character of this occurrence. > > Note: If substring is not found in string, then...
You can also perform ``` SELECT * FROM your_table WHERE INSTR(name, q'!'!') > 0; ```
How to search for all names with an apostrophe by using the INSTR function in ORACLE?
[ "", "sql", "oracle", "" ]
I searched this in stackoverflow and found [Concatenate multiple columns](https://stackoverflow.com/questions/32137399/concatenate-values-from-multiple-columns-in-oracle) and also [Concatenate multiple rows](https://stackoverflow.com/questions/4686543/sql-query-to-concatenate-column-values-from-multiple-rows-in-oracle)...
This with some modification from [here](https://stackoverflow.com/questions/4686543/sql-query-to-concatenate-column-values-from-multiple-rows-in-oracle) . Added `||` (concatenate) in `LISTAGG` ``` SELECT ID, LISTAGG ( CASE WHEN TIPE = 'v' THEN C_STRING ELSE TO_CHAR (C_NUMBER) ...
Your hunch is correct. In this solution, I assume that c\_string and c\_number are mutually exclusive, i.e. exactly one will be not null. ``` with t as ( select id, listagg(nvl(c_string, c_number)||' '||op, ' ') within group (order by urut) result from komponen group by id ) select id, substr(result, 1, length(r...
Concatenate multiple columns from multiple rows in Oracle
[ "", "sql", "oracle", "" ]
I have an sql database called roottesting and I manage it at the ip 192.168.1.121. I also have a simple java application that connects to it (or rather, is supposed to connect to it) over the Internet with a user named 'user' that has a host of '%', which I know will make it usable for any computer that uses it. Here i...
The IP Address you are connecting to is what is called a [Reserved IP Address](https://en.wikipedia.org/wiki/Reserved_IP_addresses) It is local to your network only ( 192.168.0.0/16 ). With that aside let's address 2 things. If you are allowed to connect to your own computer from the internet (IE: Firewall and ports ...
192.168.1.121 is a local IP, you need a Public IP. If you have internet you can use something like www.whatismyip.com to know your public ip. The problem with that IP is may change with the time so your app also may broke in the future. Or use a firewall to reruote public IP to your pc in case you are behind a router
Why Can't I Connect to My Database Over the Internet
[ "", "mysql", "sql", "" ]
I have two tables. The first is full of books each with a `book_id`. The second table is a `book_id` to `keyword_id` relationship table. ``` SELECT b.* FROM books_table b INNER JOIN keywords_table k ON b.book_id = k.book_id AND k.keyword_id NOT IN(1,2,3) WHERE b.is_hardcover = 1 GROUP BY b.book_id ``` ## *Desired ...
You can do so ``` SELECT b.* FROM books_table b INNER JOIN keywords_table k ON b.book_id = k.book_id WHERE b.is_hardcover = 1 GROUP BY b.book_id HAVING SUM(k.keyword_id = 1) =0 AND SUM(k.keyword_id = 2) =0 AND SUM(k.keyword_id = 3) =0 ```
As you noted, this query will produce any book that has at least one keyword that isn't 1, 2 or 3, which isn't what you want. Instead, you'd want to explicitly exclude books with these keywords. A `join` isn't really the right took for the job here. Instead, you could use the `exists` operator: ``` SELECT b.* FROM ...
Excluding MYSQL query results with an INNER JOIN
[ "", "mysql", "sql", "select", "subquery", "" ]
I have following table: ``` | id | name | |-------|--------| | 00001 | Item A | | 00001 | Item A | | 00002 | Item B | | 00003 | Item C | | 00004 | Item C | ``` What MySQL query I should use if I want to check if there's same name for 2 or more different ids? I have tried using `LEFT JOIN` and `UNION` in my queri...
If you want to return the original rows, then you need to `join` something back to the original data: ``` select t.* from t join (select name, count(distinct id) as cnt from t group by name ) tt on t.name = tt.name where cnt >= 2; ``` If you just want the names, then the subquery is suffici...
Join the table with itself `ON` same `name` and different `id`. **Query** ``` select t1.id,t1.name from tbl1 t1 join tbl1 t2 on t1.id <> t2.id and t1.name = t2.name; ``` [**SQL Fiddle**](http://www.sqlfiddle.com/#!9/69d72/1)
MySQL selecting duplicate name for 2 or more ids
[ "", "mysql", "sql", "" ]
Sorry if my title isn't very specific. I just have no idea what this is called, and since I tend to let Rails abstract DB queries for me, more complex ones escape me. I have this query that rails generated: ``` SELECT "stocks".* FROM "stocks" INNER JOIN "parts" ON "parts"."id" = "stocks"."part_id" INNER JOIN "feature...
The inner query finds the features that match your criteria which are then grouped per part id. The matches features are in different rows of data to verify that a part matches on multiple criteria you have to count the number of rows in that group. ``` SELECT stocks.* FROM stocks WHERE part_id IN ( SELECT part_id...
I think you need an aggregation: ``` SELECT s.* FROM "stocks" s INNER JOIN "parts" p ON p."id" = s."part_id" INNER JOIN "features" f ON f."part_id" = p."id" INNER JOIN "feature_titles" ft ON ft."id" = f."feature_title_id" WHERE p."category_id" = 20 AND s."manufacturer_id" = 4 AND f...
SQL query that matches multiple rows through several AND clauses in a three table INNER JOIN
[ "", "sql", "postgresql", "" ]
I have two different result sets: ``` Result 1: +--------------+--------------+ | YEAR_MONTH | UNIQUE_USERS | +--------------+--------------+ | 2013-08 | 1111 | +--------------+--------------+ | 2013-09 | 2222 | +--------------+--------------+ Result 2: +--------------+----------------+ ...
Try: ``` select a.YEAR_MONTH, a.UNIQUE_USERS, b.UNIQUE_ACTIONS from ( SELECT TO_CHAR(ACCESS_DATE, 'yyyy-mm') YEAR_MONTH, COUNT(DISTINCT EMPLOYEE_ID) UNIQUE_USERS FROM CORE.DATE_TEST GROUP BY TO_CHAR(ACCESS_DATE, 'yyyy-mm') ) a join ( SELECT TO_CHAR(ACCESS_DATE, 'yyyy-mm') YEAR_MONTH, CO...
If both tables have many records, a Cartesian join is a poor solution and may not actually provide the answer you want. I'd solve this problem something like this: ``` SELECT TO_CHAR (COALESCE (t1.year_month, t2.year_month), 'yyyy-mm') AS year_month, t1.unique_users, t2.unique_actions F...
Three-Column Group-By in Oracle?
[ "", "sql", "oracle", "" ]
I have a table with product prices. There are two price types: A = offer price, B = standard price. Example: ``` product_id | price | price_type ------------------------------------- 001 | 0.99 | A 001 | 1.49 | B ``` I'm looking for a SELECT-statement that returns * the standard price ...
This can be done with a left join. I am assuming that you will at least always have a standard price row for a product. ``` select p1.product_id, coalesce(p2.price, p1.price) as price from product_prices p1 left join product_prices p2 on p2.product_id = p1.product_id and p2.price_type = 'A' where p1...
You could left join two queries on the table and use `coalesce` to determine if there's an offer or not: ``` SELECT b.product_id, COALESCE(a.price, b.price) FROM (SELECT product_id, price FROM products WHERE price_type = 'B') b LEFT JOIN (SELECT product_id, price FROM prod...
Exclusive Disjunction
[ "", "sql", "select", "oracle11g", "" ]
Trying to get date difference in `day - hours - mins - sec` from a string entry of date. Also the time entry is having `AM, PM`. I am trying to use substring and converting it date time, but `AM - PM` is making it difficult. I have: `06-OCT-15 09.30.20.000000 AM` and `06-OCT-15 09.45.20.000000 PM` I am trying to get:...
See below SQL Server query. I know this will work as I have some experience in this. ``` WITH CTE AS ( SELECT CAST( DATEDIFF( DAY, '2015-10-06 08:00:00.00 AM', '2015-10-06 09:00:00.00 PM' ) AS VARCHAR(1000) ) + ' day(s)' AS Days, ...
it may help <http://www.w3schools.com/sql/func_datediff.asp> Example to get hours you have to change you date string like select datediff(hour,CONVERT(datetime, '06-OCT-15 09:00:00.000 AM'),'06-OCT-15 08:00:00.000 PM') AS DiffDate result: 11
Get date difference in days, hours, mins and secs (AM/PM date)
[ "", "mysql", "sql", "date-difference", "" ]
Running a SQL statement to CREATE a table if this table does not exist in 'sysobjects'. The table creates successfully when it does not exist, however, I get an error when running it once the table then does exist. This table must always remain and not be dropped, this is just for first run instance. ``` IF NOT EX...
If you only want to avoid errors.. If the table is existing then do not create the table, here is the code for easy checking to avoid errors. ``` IF OBJECT_ID('[tablename]') IS NULL BEGIN CREATE TABLE '[tablename]' ( jobID int, fileName varchar (255), pa...
you don't need quotes in table name, creation: ``` IF NOT EXISTS (SELECT * FROM sysobjects WHERE name = '[tablename]') CREATE TABLE [tablename] ( jobID int, fileName varchar (255), pathName varchar (255), ); ``` you are creating a table named `'[tablename]'` and you are looking for a table nam...
There is already an object named ' ' in Database
[ "", "sql", "sql-server", "" ]
I have three columns - * `TheDate` - Obviously a date. * `TheID` - A strictly increasing ID. * `TheType` - A Record type. I want these to sort by `TheID` in almost all cases except for just one record type. Records of the special record type must appear at the end of all records with the same date. Example: [![Move...
This is complicated. First you must find consecutive date records, so with ``` thedate theid thetype 2014-07-12 5001 59 2014-07-12 5002 101 2014-07-12 5003 88 2014-07-13 5004 10 2014-07-12 5005 60 ``` you would identify 2014-07-12 as one occurrence for the first three recor...
Taking the liberty granted in comments to assume that `TheDate` is non-decreasing with ascending `TheId`, if `r1.TheId < r2.TheId` then it must be the case that `r1.TheDate <= r2.TheDate` (that's the definition of non-decreasing). In that case, ordering first by `TheDate` and then by `TheId` produces the same order as ...
Sliding certain records to the end of a run of the same date
[ "", "sql", "oracle", "sorting", "" ]
**I am designing a SQL database that needs to be a five-table database to meet Air-Crewe’s requirements. I have the following so far:** **I have this for UNF:** CrewID, Crew Type, Title, Forename, Surname, Gender, CAALicenceNum, FlightID, FlightNum, IATADep, IARAArr, Date, SchDep,SchArr, Comments, A/CType, A/CRe...
Accepted answer can have more Aircrafts for a flight, I do not think that is correct. ``` TBLCrew(CrewID[PrimaryKey], CrewType, CreweTitle, Forename, Surname, gender, CAALicenceNum) TBLFlight(FlightNum[PrimaryKey], IATADep, IATAArr, Date, SchArr, A/CReg[composite/compoundKey]) TBLCrewFlight(CreweID[composite/compoun...
First of all - I am unsure even of the 1st form. `Comments` implies multiple instances of a comment, therefore it probably isn't atomic and I would make a table for them too. It would have three attributes - comment\_ID, comment, FlightID. In the 3rd form every non-prime attribute of the table is non-transitively depe...
Normalisation - SQL - 3NF
[ "", "sql", "normalization", "" ]
I am generating a temp table with duplicate entries for each "account ID". And I want all records with the same account ID to have an identifier. For example, all records with account ID: 1234 should have an identifier of 1. All records with account ID: 4321 should have an identifier of 2. I have added a column to my ...
You don't need an additional identifier, just group by your account number and select the max(date) for each, like: ``` Select accountID, max(lastUpdated) from t group by accountID ```
You can use [DENSE\_RANK()](https://msdn.microsoft.com/en-GB/library/ms173825.aspx) function with `ORDER BY AccountId`; ``` SELECT *, DENSE_RANK() OVER (ORDER BY AccountId) Identifier FROM YourTable ``` **[Fiddle demo](http://sqlfiddle.com/#!3/42696/1)**
How can I add a unique identifier for each "account ID" in my database table?
[ "", "sql", "sql-server", "" ]
This questions is a simplified version of a problem I have at work. I'm using a custom database that supports all standard SQL queries. I suppose this question applies to any RDMS that supports SQL though. Suppose I have the table `events`, including three columns: `event_type` (string), `details` (string), and `times...
Here is a working query for you ([SQL Fiddle](http://sqlfiddle.com/#!6/8fdea/1)): ``` SELECT E.* FROM dbo.Events E WHERE E.event_type IN ('access', 'power') AND ( SELECT TOP 1 details FROM dbo.Events E2 WHERE E.timestampid >= E2.timestampid AND E2.event_type = 'power' ORDER BY E2.ti...
You can identify all rows where the previous "power" row was for "outage" and not "good". I think that gets you the information you want. ``` select e.* from events e where 'outage' = (select e2.details from events e2 where e2.event_type = 'power' and e2.tim...
How do I select rows between rows that match a condition?
[ "", "sql", "" ]
I have a big query (MYSQL) to join several tables: ``` SELECT * FROM `AuthLogTable`, `AppTable`, `Company`, `LicenseUserTable`, `LicenseTable`, `LicenseUserPool`, `PoolTable` WHERE `LicenseUserPool`.`UserID`=`LicenseUserTable`.`UserID` and `LicenseUserTable`.`License`=`LicenseTab...
You can try running this query without 'order by' clause on your data and see if it makes a difference (also run 'explain'). If it does, you can consider adding index/indices on the fields you sort by. `Using temporary; using filesort;` means that the temp table is created and then sorted, without index that takes time...
First of all consider modifying your query to use JOINS properly. Also, make sure that you have indexed the columns used in `JOIN ON` clause ,`WHERE` condition and `ORDER BY` clause. ``` select * from `AuthLogTable` join `AppTable` on `AppTable`.`AppID` = `AuthLogTable`.`AppID` join `LicenseTable` on `AuthLogTable`.`...
How to Optimize this MYSQL Query - Join several tables
[ "", "mysql", "sql", "" ]
I have two tables, `Teachers` and `Departments`. `Teachers` works at a department, so teacher table has a `department_id` foreign key. Each department has one teacher as its chairman. Therefore, `Department` has a foreign key `chairman` referring to the `Teachers` table. However, teachers table can contain teachers ...
Your design makes a number of assumptions. 1. A teacher can only be in one department. 2. Each department can have only one chairman. 3. Chairman is the only position you'll want to store. 4. You don't want to know anything more about the chairman. 5. Only teachers can be chairmen. If these assumptions hold true in r...
It is not a bad database design, because from a relational point of view, the relationships are fine. Your requirement is an application concern, so it is okay to handle it at the application layer, meaning, to take pains in the application which makes use of this database to ensure that the chairman will always belon...
Is this a bad database design?
[ "", "sql", "database-design", "" ]
I have a string which I want to trim. What I am looking for is way to get the value from string up to the last `Y`. Ex: 1. `AB Y bc Y dc Y1` -> `AB Y bc Y dc Y` 2. `ABYBCY` -> `ABYBCY` 3. `ABY BCY DC` -> `ABY BCY` I am trying below query but I amn not getting what I need. ``` DECLARE @name varchar(200)='RAM, Y SHAM...
You can do this with `stuff()` and `reverse()`. Something like this ``` SELECT STUFF( @name, LEN(@name) - CHARINDEX('Y', REVERSE(@name)), LEN(@name), '' ) string ``` **Note:** This assumes that there is at least one "Y" in the given string. [Here is a SQL Fiddle.](...
You can also try something like: ``` Select substring(@name,1, len(@name) - (charindex('Y', reverse(@name)))+1) ```
SQL query to get char from string based on criteria
[ "", "sql", "sql-server", "" ]
Let's say we have the following Fruits table: ``` Fruit | Qty ------------- Apple | 2 Apple | 5 Apple | 2 Orange | 3 Orange | 4 Orange | 0 Banana | 2 Banana | 5 Pear | 2 Mango | 1 Mango | 0 ``` If I want to get the top 3 fruit I would create a query like this: ``` SELECT TOP 3 Fruit, SUM(Qty) AS ...
You need to RANK the sums and add another SUM for the final result: ``` with cte as ( SELECT Fruit, SUM(Qty) AS Qty, ROW_NUMBER() OVER (ORDER BY SUM(Qty) DESC) AS rn FROM Fruits GROUP BY Fruit ) select case when rn > 3 then 'Other' else fruit end as fruit, sum(Qty) from cte group by case ...
This is one way of doing it by ranking rows based on `sum(qty)`. ``` with totals as (SELECT Fruit, SUM(Qty) AS Total FROM Fruits GROUP BY Fruit) , rownums as (select *, dense_rank() over(order by total desc) as rank from totals) select case when rank > 3 then 'Other' else fruit end as fruit, total from rownums ``` I...
Aggregate rows outside the top
[ "", "sql", "sql-server", "aggregate", "sql-server-2014", "" ]
I have three tables (examples here). Two with data and one that is a junction table to handle many:many relationships. **Users**: ``` ID | UserName ==================== 1 | Jeremy Coulson 2 | Someone Else ``` **Repositories**: ``` ID | RepositoryURI ==================== 1 | http://something 2 | http://another `...
You aren't actually giving a correct join condition for your second `INNER JOIN`. It should be: ``` SELECT U.UserName FROM RepositoriesUsers RU INNER JOIN Users U ON U.ID = RU.UserID INNER JOIN Repositories R ON RU.RepositoryID = R.ID WHERE R.RepositoryURI = 'http://another'; ``` Also, you should try to us...
I think a simple correction is needed to your join: ``` select UserName from RepositoriesUsers join Users on Users.ID = RepositoriesUsers.UserID join Repositories on Repositories.ID = RepositoriesUsers.RepositoryID where Repositories.RepositoryURI = 'http://another'; ```
SQL Server: How can I get data from junction table that only has IDs?
[ "", "sql", "sql-server", "join", "junction-table", "" ]
I need to find patients having multiple genders recorded. (I wish I knew how to create a table.) ``` [Hospital Number] [Sex Code] 0000001 M 0000002 F 0000003 M 0000003 F ``` Here we can see patient 1 and 2 are okay, but patient 3 has multiple genders. (There are 4 available ge...
Alternative solution, do a self join: ``` select distinct p1.[hospital number] FROM patients AS p1 INNER JOIN patients AS p2 ON p1.[hospital number] = p2.[hospital number] AND p1.[Sex code] <> p2.[Sex code] ``` Return `[hospital number]` if same `[hospital number]` but different `[Sex code]` is found. Now edite...
You do not need a subquery in MS Access. You can just compare the minimum and maximum values: ``` SELECT [hospital number] FROM patients GROUP BY [hospital number] HAVING MIN([Sex Code]) <> MAX([Sex Code]); ``` This should also have better performance than the count distinct. It does not return rows where `[Sex Code]...
Find patients with multiple gender
[ "", "sql", "ms-access", "" ]
So, i´m trying to select rows between two dates. In db, the dates also have time. Therefor i need to use LIKE. **SQL** ``` $query = "SELECT * FROM table WHERE date >= LIKE :selectedDateFrom AND <= LIKE :selectedDateTo"; $query_params = array(':selectedDateFrom' => $selectedDateFrom.="%", ':selectedDateTo' => $se...
> In db, the dates also have time. > Therefor i need to use LIKE. No, you don't. To select all date/times where the date component is between (from) and (to), inclusive, you can write it as ``` SELECT * FROM table WHERE date >= :selectedDateFrom AND date < :selectedDateToPlusOne ``` (Note the `<` instead of `<=`,...
you can't use like with dates in SQL SO use this: ``` $query = "SELECT * FROM table WHERE date >= :selectedDateFrom AND date <= :selectedDateTo"; ```
SQL: How to use 'LIKE' with a date 'between'?
[ "", "sql", "mariadb", "" ]
I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102...
You should be able to do that with a CTE to grab [ROW\_NUMBER](https://msdn.microsoft.com/en-us/library/ms186734.aspx), and then [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx) to only use that number where the value is NULL: ``` WITH cte AS( SELECT empId, empExtension, ROW_NUMBER() OVER(ORDER BY ...
If you just want to create a unique random 5 digit number for those `empExtension` column values are null, then **Query** ``` ;with cte as ( select rn = row_number() over ( order by empId ),* from employeeDetails ) select t1.empId,t2.deptName, case when t1.empExtension is null then t1.rn + (c...
Populate auto-increment INT 5 digit value in case of null in SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I'm trying to count the occurrences when a user perform something in consecutive months. Ex. ``` | Person | Datetime | | person_01 | '2015-01-02 10:40:15' | | person_01 | '2015-02-02 10:40:15' | | person_01 | '2015-07-05 10:40:15' | | person_02 | '2015-01-02 10:40:15' | | person_02 | '2015-0...
You can do this by combination of rownumber generation and `timestampdiff` [**SQL Fiddle Demo**](http://sqlfiddle.com/#!9/87c20/9) ``` SET @row_number1:=0; SET @row_number2:=0; SELECT T1.person, ,SUM(CASE WHEN TIMESTAMPDIFF(MONTH,T1.ddatetime,T2.ddatetime)=1 THEN 1 ELSE 0 END) CNT CNT FROM (SELECT @row...
You may be able to do something like this: ``` select base.person, count(subq.dt) consequtive -- get distinct person from (select distinct person from test) base -- join with a subquery left join ( select a.* from -- convert date to first day of the month (select person, cast(concat(left(dt,7), '...
MySQL: Count continuous months
[ "", "mysql", "sql", "date", "" ]
I have a table called `users` another table called `user_flags`, and another table called `flags` The `users` table contains a `name` and `id` The `flags` table contains a `name` and `id` The `user_flags` contains a `user_id` and `flag_id` If I want to get all the users which have any of the provided flag names, wh...
You need to join the tables on their id values and use a where clause for the flag color name. Something like this: ``` select * from Users U join UsersFlags UF on UF.user_id = U.id join Flags F on F.id = UF.flag_id where F.name = 'red' ```
Try this query: ``` SELECT u.name FROM users u INNER JOIN user_flags uf ON u.id = uf.user_id INNER JOIN flags f ON uf.flag_id = f.id WHERE F.name = 'red' ``` [**SQL Fiddle**](http://sqlfiddle.com/#!9/ac105/3) Note that in the fiddle the table and column names are slightly different from what you used in your origina...
Select records from table A that have at least X records on table B
[ "", "sql", "postgresql", "" ]
I want to update `OFFICE_ID,OFFICE_TYPE` of `FA_SUBLEDGER_MST` table, by using `OFFICE_ID,OFFICE_TYPE` from `EMPLOYEE_MST` table based on following conditions: `EMPLOYEE_MST.SL_CODE=FA_SUBLEDGER_MST.SL_CODE EMPLOYEE_MST.OFFICE_ID<>SL.OFFICE_ID OR EMPLOYEE_MST.OFFICE_TYPE<>SL.OFFICE_TYPE AND EMPLOYEE_MST.OFFICE_TYPE!='...
**Finally found a solution:** ``` merge into FA_SUBLEDGER_MST s1 using ( select SL_CODE, OFFICE_ID, OFFICE_TYPE from EMPLOYEE_MST where OFFICE_TYPE != 'DHB' ) emp on (s1.SL_CODE = emp.SL_CODE) when matched then update set s1.OFFICE_ID = emp.OFFICE_ID, s1.OFFICE...
TRY THIS: ``` WHERE (FA_SUBLEDGER_MST.OFFICE_ID != EMPLOYEE_MST.OFFICE_ID AND FA_SUBLEDGER_MST.OFFICE_TYPE !=EMPLOYEE_MST.OFFICE_TYPE) --AND will be converted to OR by SQL Engine AND FA_SUBLEDGER_MST.SL_CODE = EMPLOYEE_MST.SL_CODE AND EMPLOYEE_MST.OFFICE_TYPE! ='DHB' AND sl.STATUS = 'A' ```
Updating row of one table using rows of another table based on specific conditions
[ "", "sql", "database", "oracle", "oracle11g", "" ]
I have a plsql procedure which take an input variable. This variable (my\_plsql\_var) I need to decide the where clause of my select statement. If my variable is A then I need to query a specific where clause, if it is B it uses that specific where clause and same goes for C. I have tried some queries but they do not w...
Can this not just be simplified to this? ``` SELECT ID, my_plsql_var || ' GROUP' AS Group FROM my_table WHERE ID = 100 AND NAME = 'Smith' AND ( (my_plsql_var = 'A' AND my_col1 IN ('A') AND my_col2 = 'A') OR (my_plsql_var = 'B' AND my_col1 IN ('B') AND my_col2 = 'B' AND my_special_col = '...
``` Hello you need to build the SELECT Clause dynamically based upon your input. Below is the example for this. CREATE OR REPLACE PROCEDURE TEST1_DYN( p_in IN VARCHAR2, p_ref OUT sys_refcursor ) AS lv_select LONG; BEGIN lv_select:='SELECT ID, ...
Conditional Where Clause Oracle SQL based on procedure input varaible
[ "", "sql", "oracle", "plsql", "" ]
I have a table which looks like this `<SubCodeReport3>` which has a column called `Rank`. For each row I need to the what is the Rank and based on that value I need to unpivot SubCode columns (SubCode1,SubCode2 & Subcode3 etc) and convert them into rows. [![enter image description here](https://i.stack.imgur.com/BuzlV...
Start with a CTE or derived table that does a full unpivot of the table, and adds a partitioned row\_number so that for each row in the original table, SubCode1 will be on row\_number 1, SubCode2 on row\_number 2, etc. Then select from that CTE where row\_number is less than or equal to [Rank].
This is what worked for me. ``` WITH CodesReportCTE ( [Number] ,[ S-ID] ,[Rank] ,[AGE] ,[SchoolCode] ,[Code] ) AS ( SELECT ROW_NUMBER() over (PARTITION BY [ S-ID],[SchoolCode] ORDER BY [ S-ID],[SchoolCode]) AS Number ,[ S-ID] ,[Rank] ,[AGE] ,[Schoo...
Conditional Unpivot SQL table
[ "", "sql", "sql-server", "pivot", "unpivot", "" ]
If you have a composite clustered index say: `(ClientId, Date, OrderId, ProductId)`. (All fields are non-null) Given the query: `SELECT * FROM products WHERE ClientId = 33 AND OrderId = 4 AND ProductId = 2 ORDER BY Date` Will this query take advantage of the covering index fully by having the `ORDER BY Date` or does...
For MySQL, your index can't be used. MySQL's indexes apply left->right: ``` (ClientId, Date, OrderId, ProductId) ``` since your query involves only `ClientID` and `ProductID`, the index can't be used - you'd have to use include `Date` and `OrderID` in the query as well. Note that the specific ordering of the fields i...
It really depends on many things , like * how many rows in the table ? * how much time it takes for to get values from index leaf ? * What is inside the \* that you are getting from ... etc. Thats why they invented "explain plan" Use it when you want to know
Covering Index with ORDER BY
[ "", "mysql", "sql", "sql-server", "database", "oracle", "" ]
I have a table very similar to the one below, except there are 20 of both the v and p values. ``` |--------------Table 1-------------| | part_id | v1 | v2 | p1 | p2 | | 1 | 250 | 8 | 1 | 2 | | 2 | 1348 | 9 | 28 | 88 | | 4094 | 580 | 230 | 207 | 726 | | 7111 | 12 | 14 | 223 | 195 |...
Create a format from the values/parameter data set and then use an array within a data set to loop through and create the descriptions you need. Here's a sample for the parameter table that should get you started. I haven't tested this code though :). ``` data param_fmt; fmtname='param_fmt'; start=p_id; label=value; r...
## Formats If your dimension tables are simple and small then convert them into formats. ``` data cntlin ; set values ; by v_id; retain fmtname 'VALUES'; rename v_id = start value = label; run; proc format cntlin=cntlin; run; ``` Then you do not even need to modify your input table. You can use it as is and ...
Can I reduce the amount of joins used in this query?
[ "", "sql", "oracle", "sas", "" ]
i have this table (500,000 row) ``` CREATE TABLE IF NOT EXISTS `listings` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `type` tinyint(1) NOT NULL DEFAULT '1', `hash` char(32) NOT NULL, `source_id` int(10) unsigned NOT NULL, `link` varchar(255) NOT NULL, `short_link` varchar(255) NOT NULL, `cat_id` me...
One important general note as to why your query isn't getting any faster despite your attempts is that `DESC` on indexes is not currently supported on MySQL. See this [SO thread](https://stackoverflow.com/a/10130260/1935338), and [the source](https://wikivs.com/wiki/MySQL_vs_PostgreSQL) from which it comes. In this ca...
This query: ``` SELECT * FROM listings WHERE (publishedon BETWEEN 1441105258 AND 1443614458) AND (published = 1) AND (cat_id in (1,2,3,4,5)) AND (source_id in (1,2,3,4,5)); ``` Is hard to optimize with only indexes. The best index is one that starts with `published` and then has the other columns --...
MySQL indexes - what are the best practices according to this table and queries
[ "", "mysql", "sql", "indexing", "query-optimization", "" ]
In my company front end system shows the "proper" date but when i am querying the database from embarcaderoRapid SQL it shows me date as a below (database) . Its a problem for me as in our front end view we are not able to group results etc and i can do it in embarcadero. But i need to understand what is the logic be...
``` DECLARE @TS bigint Set @TS ='1427842800000' SELECT DATEADD(MINUTE,60,DATEADD(MILLISECOND, @TS % 1000, DATEADD(SECOND, @TS / 1000, '19700101'))) ``` **Edit**: to Account for Timezone
I'm not sure I understand your question. In the database you have a date stored as a timestamp, i.e. the number of seconds since 1/1/1970. In your frontend, the date is displayed as we usually see a date. See: <http://www.unixtimestamp.com/>, when i'm writing this answer the date is `1444122272`. **EDIT** : by the w...
Date coding issue
[ "", "mysql", "sql", "sql-server", "date", "datetime", "" ]
I'm having issues with what I assumed would be a simple problem, but googling isn't helping a great load. Possibly I'm bad at what I am searching for nether the less. ``` SELECT ORDER_NUMB, CUSTOMER_NUMB, ORDER_DATE FROM ORDERS WHERE FORMAT(ORDER_DATE, 'DD-MMM-YYYY') = '07-JUN-2000'; ``` It tells me I am using an inv...
There are multiple issues related to your **DATE** usage: > WHERE FORMAT(ORDER\_DATE, 'DD-MMM-YYYY') = '07-JUN-2000'; 1. **FORMAT** is not an **Oracle** supported built-in function. 2. Never ever compare a **STRING** with **DATE**. You might just be lucky, however, you force Oracle to do an **implicit data type conve...
try this: ``` SELECT ORDER_NUMB, CUSTOMER_NUMB, ORDER_DATE FROM ORDERS WHERE trunc(to_date(ORDER_DATE, 'DD-MMM-YYYY')) = trunc(to_date('07-JUN-2000')); ```
How to compare date in Oracle?
[ "", "sql", "oracle", "date-arithmetic", "" ]
I have a sql query which is working perfectly to return the number of hours a worker is working in any particular job ``` SELECT worker.WorkerID, worker.fullname, job.JobCode, job.jobName, Count(slottime.FK_Hour) AS NUMBER_OF_HOURS_WORKED FROM ( ( (job INNER JOIN slot ON job.JobCode =...
Try this below ``` SELECT worker.WorkerID, worker.fullname, job.JobCode, job.jobName, Case When manager.is_the_boss = 1 Then Count(slottime.FK_Hour) + 2 Else Count(slottime.FK_hour End AS NUMBER_OF_HOURS_WORKED FROM ( ( (job INNER JOIN slot ON job.JobCode = slot.fk_JobCode ) INNE...
Your query is rather hard to follow. Why have all those parentheses in the `from` clause (unless you are using MS Access and you have no choice)? It is simpler to just list the tables with the `join` criteria. Solving your problem requires counting the number of job codes where the worker is the boss. You can do this ...
MySQL: Add to Count with case... then
[ "", "mysql", "sql", "count", "case", "" ]
In an oracle procedure, I need to insert data in EmployeeHeader table and then later insert the PK id of this table as the FK id of EmployeeDetails table. How can we achieve this? ``` INSERT INTO EmployeeHeader( HEADER_PK_ID empNo ) VALUES( HE...
Use the `RETURNING` clause of the INSERT statement: ``` DECLARE nHeader_pk_id NUMBER; BEGIN INSERT INTO EmployeeHeader (HEADER_PK_ID, EMPNO) VALUES (HEADER_PK_ID_SEQ.NEXTVAL, 'SOMETHING') RETURNING HEADER_PK_ID INTO nHeader_pk_id; INSERT INTO EmployeeDetails (DTLHEADER_PK_ID, HEADER_FK_ID, EMPN...
You can use `currval` in most cases: ``` select HEADER_PK_ID_SEQ.CURRVAL from dual; ``` You might need to wrap the two inserts in a single transaction, if you want the values to be safe for concurrent inserts.
In oracle procedure how to fetch the PKId just added to be added as FK ID for next table
[ "", "sql", "oracle", "plsql", "" ]
I'm trying to figure out how to retrieve all rows with a ID which have a specific value in the other column. The database looks like this: [![Database Illustration](https://i.stack.imgur.com/kZX56.png)](https://i.stack.imgur.com/kZX56.png) I want to retrieve those rows which have a VAL of 2 and the corresponding ID ...
One method is exists: ``` select t.* from test t where exists (select 1 from test t2 where t2.id = t.id and t2.val = 2); ```
you'll need a subquery (or join or cte or derived table) Subquery is easist to visualise Select \* from Test where ID IN (SELECT ID from Test where VAL = 2)
Compare rows with a column value
[ "", "sql", "database", "sqlite", "" ]
I need to create a sales summary based on data with an optional "Elected" flag, which is user controlled. The flag determines whether or not to group items belonging to the same class of item. If none of the items within a class have the Elected flag set to 1, the items appear as individual rows in the summary. If one...
You need both individual rows and aggregates, so this is a task for a `Group Sum` and some additional logic: ``` WITH cte AS ( SELECT *, -- either the individual Price or the Group Sum CASE WHEN Elected = 1 THEN SUM(Price) OVER (PARTITION BY Class) ELSE Price END AS T...
You can select for each class min itemid which is elected and then it is simple grouping: ``` ;with cte as(select *, (select isnull(min(itemid), t1.itemid) from t t2 where t2.class = t1.class and t2.elected = 1) as parentid from t t1) select p.itemid, ...
SQL - Group By based on optional flag
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have a list of users (Field = UserName) that I got from a table (Users). Some are duplicates. Where there is a duplicate record, I need to delete the most current record (CreatedOn) created. Also, if it trips up on the ability to delete because there are 'relationships established to this user ID' in the database, ...
Adding on from Diego's answer with a check that the UserName is not the oldest instance in the table. ``` DELETE FROM Users WHERE UserName IN (SELECT UserName FROM Users GROUP BY UserName HAVING COUNT(UserName) > 1) AND CreatedOn != (SELECT MIN(CreatedOn) FROM Users T1 WHERE UserName = T1.U...
You can try something like this: ``` Delete from Users where nameuser in (select nameuser from Users Group by nameuser Having count(nameuser) > 1) ```
Deleting Records Based on Criteria
[ "", "sql", "sql-delete", "" ]
``` orders ( o_id INT AUTO_INCREMENT, o_status TINYINT, o_description VARCHAR(50), ) orders_products ( op_id INT AUTO_INCREMENT, op_order_id INT(11), op_product_id INT(11), op_price DECIMAL(19, 2), ) ``` How to select all orders that have ONLY products with id = 1 and id = 2. Thank you and sorry from m...
There are different ways to get the desired result, this utilizes conditional aggregation: ``` select * from orders where o_id in ( select op_order_id from orders_products having count(case when op_product_id = 1 then 1 end) > 0 -- at least one row with 1 and count(case when op_product_id = 2 then 1 ...
You could first find all the distinct order and product combination for product 1 or 2 or both, and then look for orders that have both. ``` create table orders (o_id INT); create table orders_products (op_order_id INT(11), op_product_id INT(11)); insert into orders values (1), (2); insert into orders_products values...
sql select all if column has only two particular values
[ "", "mysql", "sql", "select", "foreign-keys", "inner-join", "" ]
I need to concatenate a real datetime reference day with a varchar value representing hours/mns informations. I have read [documentation](https://technet.microsoft.com/en-us/library/ms186724%28v=sql.105%29.aspx) about DateTime operations but haven't find how to do this. Here is my sample : ``` DECLARE @ref_day [date...
Try this: ``` DECLARE @ref_day [datetime] DECLARE @hours [varchar](15) DECLARE @result [datetime] SET @ref_day = '2015-10-06' SET @hours = '07:30' SET @result = DATEADD(day, DATEDIFF(day, 0, @ref_day), @hours) ```
Using [`DATETIMEFROMPARTS`](https://msdn.microsoft.com/en-us/library/hh213233.aspx) SQL Server 2012+: **[LiveDemo](https://data.stackexchange.com/stackoverflow/query/372397)** ``` DECLARE @ref_day DATETIME; DECLARE @hours VARCHAR(100); DECLARE @result DATETIME; SET @ref_day = '2015-10-06' SET @hours = '07:30'; SELE...
DateTime creation in T-SQL
[ "", "sql", "sql-server", "t-sql", "datetime", "" ]
I have found below query in one of our existing Stored Procedures. This query used to take records between two datetime values. ``` SELECT office FROM officebudget WHERE officeid = @officeid AND ( (CONVERT(DATE, DateFrom) BETWEEN @wkstdate AND @wkenddate) OR (CONVERT(DATE, DateT...
I suspect that you are refactoring your query to make it sargable and to use possible indexes on columns `DateFrom` and `DateTo`. Those will not result in same results because your query will omit rows where date part of `wkenddate` equals datepart of `DateFrom` or `DateTo` column values. For example let's say `wkendd...
The difference is that in the first query, you use a function (CONVERT) on the filtered columns (FateFrom and DateTo), then the engine could not use the index on it if it exists and so the first query would tend to be slower. In the second query, you have entered manually the date like this : `2015-09-30`. It is bette...
Get records between two datetimes in SQL Server
[ "", "sql", "sql-server", "t-sql", "" ]
I'm working on a query in SQL Server 2005 that looks at a table of recorded phone calls, groups them by the hour of the day, and computes the average wait time for each hour in the day. I have a query that I think works, but I'm having trouble convincing myself it's right. ``` SELECT DATEPART(HOUR, CallTime) AS H...
The grouping happens on the values that get spit out of `datepart(hour, ...)`. You're already filtering on that value so you know they're going to range between 6 and 18. That's all that the grouping is going to see. Now of course the `datepart()` function does what you're looking for in that it looks at the clock and...
Yes if you use the AVG function with a GROUP BY only the items in that group are averaged. Just like if you use the COUNT function with a GROUP BY only the items in that group are counted. You can use windowing functions (OVER/PARTITION) to conceptually perform GROUP BYs on different criteria for a single function. e...
Calculating the AVG value per GROUP in the GROUP BY Clause
[ "", "sql", "sql-server-2005", "group-by", "average", "" ]
So I been struggling with this one for a while. The question is as follows: Find all the Employees to whom no other employee reports to. Print the Id, and the first and last name of such employees. The Relationship Sets can be found here: <https://chinookdatabase.codeplex.com/wikipage?title=Chinook_Schema&referringT...
**[SQL Fiddle Demo](http://sqlfiddle.com/#!6/e585b/2)** ``` SELECT E.* FROM Employee E LEFT JOIN Employee R -- R for report to ON E.EmployeeID = R.ReportTo WHERE R.EmployeeID IS NULL ``` **OUTPUT** ``` | EmployeeID | LastName | ReportTo | |------------|----------|----------| | 3 | Peacock | ...
This should give you what you are wanting: ``` Select E.EmployeeId ,E.FirstName ,E.LastName From Employee E Where E.EmployeeID NOT IN (SELECT DISTINCT ReportsTo FROM Employee WHERE ReportsTo is not null) ``` Selects every employee that has no one ...
SQL ReportsTo Query
[ "", "sql", "" ]
I have a SQL table with data like the following. ``` key entry_no type_1 type_2 text 1 1 A Y text 1 1 2 B Y text 2 1 3 B Y text 3 1 4 A Y text 4 1 5 B text 5 1 6 C Y te...
Usually this type of query is called `top-N-per-group`. In SQL Server there are at least two methods to get the result. One uses `ROW_NUMBER`, another `CROSS APPLY`. If you have a lot of groups and few rows per group, then it is more efficient to use `ROW_NUMBER`. If you have few groups, but each group has a lot of row...
``` select max(entry_no) from table group by type_1 where key = 1 and type_2 = 'Y' ```
Select the most recent entry for a key with relevant sub-values
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Newby coder here so excuse the ignorance: Table 1 (title table) list different titles like mr, mrs, dr, prof, etc (column name = 'title\_name') and the primary key is named 'id' which is marked from 1 to 4 (linking that to the title obviously) Table 2 (member table) has a column named 'title' that show 1,2,3,4, etc a...
Join on the correct column: ``` select title_name from member, title where member.title=title.ID ```
You can link data by using a JOIN operation. For example with the query I'm giving here you get all the members with the related record from title: ``` select * from member as m left join title t on t.id = m.title; ``` If you need specific fields from the query you can just replace "\*" with the names of the field...
How to Populate Title Field in SQL
[ "", "mysql", "sql", "" ]
My query is quite big but for understanding purpose I paste here ``` SELECT DISTINCT ISNULL(CD.InteractionID,'') AS InteractionID , ISNULL(CD.CaseID,'') AS CaseID , ISNULL(CD.AnalysisMonth,'') + '-' + CAST( AnalysisYear AS VARCHAR(10)) AS M...
Like @zedfoxus commented, the problem is this part: ... THEN (SELECT SubSystemID FROM IT\_COMPLAINTS.ITC\_SystemUserMapping Since if that returns more than 1 value, there is no place to put that value. You should replace this with something like this: ``` CD.SubSystemID IN ( SELECT SubSystemID FROM ...
instead of this: ``` FROM [IT_COMPLAINTS].[ITC_Casedetails] CD WITH (NOLOCK) ... AND CD.SystemID IN ( CASE WHEN @SystemID = 0 THEN (SELECT SystemID FROM IT_COMPLAINTS.ITC_SystemUserMapping WHERE ...) ELSE @SystemID END) AND CD.SubSystemID IN ...
Subquery returned more than 1 value even with IN operator
[ "", "sql", "sql-server", "" ]
I have a table with the following structure and Example data: [![enter image description here](https://i.stack.imgur.com/waQnc.png)](https://i.stack.imgur.com/waQnc.png) Now I want to query the records that have `value` equals to `#` and `@`. For example according to the above image, It should returns `1` and `2` ...
You can use a group by and having to get the distinct Id's that contain a distinct count of the number of items you're looking for ``` SELECT Id FROM Table WHERE Value IN ('#','$') GROUP BY Id HAVING COUNT(DISTINCT Value) = 2 SELECT Id FROM Table WHERE Value IN ('#','$','@') GROUP BY Id HAVING COUNT(DISTINCT Value) =...
There's several ways to do this. The subquery method: ``` SELECT DISTINCT Id FROM Table WHERE Id IN (SELECT Id FROM Table WHERE Value = '@') AND Id IN (SELECT Id FROM Table WHERE Value = '@'); ``` The correlated subquery method: ``` SELECT DISTINCT t.Id FROM Table t WHERE EXISTS (SELECT 1 FROM Table a WHERE a.I...
Query a table that have 2 cols with multiple criteria
[ "", "sql", "performance", "sqlite", "android-sqlite", "" ]
I have a field in a db2 database which is on hexadecimal format i.e 0x0a which is number 10 in decimal format. The hex field's datatype is `char(1) for bit data`. ``` hex(myfield) gives me the hexadecimal 0A ``` How can i convert 0x0a to 10 in a query on db2? I have tried: `cast(hex(myfield),integer)` and `int(hex(m...
AFAIK, there is no such single function built into DB2 that would perform that conversion, but there is a [blog post showing how to define such a function](https://web.archive.org/web/20200101052310/https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/bit_arithmetic19?lang=en). The following function...
I'm sure you could simplify the following ``` WITH fred (x) AS (VALUES 'f1'), nurk (a) as (SELECT UPPER(substr(x,1)) from fred union all select UPPER(substr(a,2)) from nurk where substr(a,1,1) <> ' '), bare (b, c) as (select substr(a,1,1), (length...
How to convert hexadecimal to decimal on DB2
[ "", "sql", "database", "db2", "hex", "" ]
have two SQL selects on same table. 1st select Shows desired user data. 2nd select finds how many times "initials" are used. That value tends to be used multiple times though it shouldn't I don't want to have less rows as in query 1 but to add "Initial Count on all" -- First Query showing all desired data ``` SELECT...
You can use `COUNT()` with `OVER()` to get the count per group (defined by `PARTITION BY`) without a `GROUP BY`: ``` SELECT UserID , Username , Initials , COUNT(*) OVER(PARTITION BY Initials) AS InitialCount FROM dbo.Users ``` Commonly referred to as analytic or window functions, `OVER()` can be...
``` SELECT UserID, Username, Inititials, (SELECT COUNT(*) FROM dbo.Users U2 WHERE U2.Inititals = U1.Initials) InitialCount FROM dbo.Users U1 ```
Merge two SQL selects into one result
[ "", "sql", "sql-server", "report", "" ]
I've been at this for about an hour now and am making little to no progress - thought I'd come here for some help/advice. So, given a sample of my table: ``` +-----------+-----------------------------+--------------+ | MachineID | DateTime | AlertType | +-----------+-----------------------------...
Not sure, but: ``` select * from [Table] WHERE [DateTime] IN ( SELECT MIN([DateTime]) as [DateTime] FROM [Table] WHERE AlertType = 2000 GROUP BY MachineId UNION ALL SELECT MAX([DateTime]) as [DateTime] FROM [Table] ...
It looks like your outer section takes all records between 2015-10-05 to 2015-10-06, which includes all the records sorted by date. The inner portion only happens when no records fit the outer date range. Looks like GSazheniuk has it right, but I am not sure if you just want the 2 records or everything that matches th...
SQL Find First Occurrence
[ "", "sql", "sql-server", "ssms", "" ]
I have a table `artist` with several columns like `name`, `type` ... I want the column `name` to be returned and ordered alphabetically, but the column name should be adjusted. If the name of the artist starts with *'the '* (case insensitive) then it should be removed and placed behind the name in uppercase, for exam...
Use `ELSE` clause in `CASE`: ``` SELECT CASE WHEN UPPER(name) LIKE 'THE %' THEN CONCAT(RIGHT(name, length(name)-4),', THE') ELSE name END AS name FROM artist ORDER BY name ```
### Query ``` SELECT CASE WHEN name ILIKE 'THE %' -- simpler THEN right(name, -4) || ', THE' -- simpler, faster ELSE name END AS name -- but better use a distinct alias , * FROM artist ORDER BY 1; -- positional reference to 1st output column ``` ### Rationale * The simplest and f...
ORDER BY changed column with same name
[ "", "sql", "postgresql", "replace", "pattern-matching", "sql-order-by", "" ]
We have an SQL job that runs every 30s where we logged every step (SQL Server 2012) Sometimes, without any reason, and without any "job failed" message, the job stops and even hangs (behavior that we would like to analyse). What we would like to achieve is to query out log table and detect when a record is missing (d...
This shows all periods longer than 30 seconds ``` select A.CREATION_DATE as Start, min(N.CREATION_DATE) as Finish from logTable A left join logTable N on A.CREATION_DATE < N.CREATION_DATE group by A.CREATION_DATE having datediff(second, A.CREATION_DATE, min(N.CREATION_DATE)) > 30 ```
This is my "dirty" solution while trying to make the solution by Luis to work (looks better than mine) ``` SELECT TOP 1000 [PROCEDURE_NAME] ,[CREATION_DATE] ,[MESSAGE] , DATEDIFF(SECOND, (SELECT top 1 [CREATION_DATE] FROM [mactac].[mactac].[ERROR_LOG] f ...
SQL: detect when a recurring log (every 30s) is missing
[ "", "sql", "select", "sql-server-2012", "periodicity", "" ]
As my question states, I would like to know what we call types of queries with that type of condition in the `WHERE` clause, i.e.: ``` SELECT * FROM mytable WHERE (col1, col2) < (1, 2); ``` In other words: ***Give me all records where `col1` is less than '1' or if it equals '1' then `col2` must be less than '2' - a...
Common terms for the operation you demonstrate are **"Row values"**, **"Row value comparison"**, [**"Row constructor comparison"**](https://www.postgresql.org/docs/current/functions-comparisons.html#ROW-WISE-COMPARISON) or **"Row-wise comparison"**. Commonly used in **"keyset pagination"**. That feature has been in ...
``` WHERE (col1, col2) < (val1, val2) ``` Above syntax is called **Row Value Constructor**/**tuple syntax**/**Row Subquery**. From [doc](https://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-tuple) > ANSI SQL **row value constructor syntax**, sometimes referred to AS **tuple > syntax**, ...
SQL syntax term for 'WHERE (col1, col2) < (val1, val2)'
[ "", "sql", "hibernate", "postgresql", "pagination", "criteria", "" ]
I have a table like this and there are only two feature for all user in this table ``` +-------+---------+-----------+----------+ | User | Feature | StartDate | EndDate | +-------+---------+-----------+----------+ | Peter | F1 | 2015/1/1 | 2015/2/1 | | Peter | F2 | 2015/3/1 | 2015/4/1 | | John | F1 ...
If you are using SQL Server 2005 or up by any chance, [`PIVOT`](https://technet.microsoft.com/library/ms177410.aspx) is what you are looking for.
Use [UNPIVOT & PIVOT](https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx) like this: Test data: ``` DECLARE @t table (User1 varchar(20),Feature char(2),StartDate date,EndDate date) INSERT @t values ('Pete','F1','2015/1/1 ','2015/2/1'), ('Pete','F2','2015/3/1 ','2015/4/1'), ('John','F1','2015/5/1 '...
How to transform rows into column?
[ "", "sql", "sql-server", "" ]
I have a table like this: ``` +--------+--------+ | userid | events | +--------+--------+ | 1 | blog | | 2 | blog | | 1 | site | | 1 | move | | 2 | move | | 3 | blog | | 2 | blog | +--------+--------+ ``` I want to display all users who participated in all the events t...
``` SELECT DISTINCT userid FROM table_name WHERE events = 'blog' AND userid IN ( SELECT DISTINCT userid FROM table_name WHERE events = 'move' ) ``` Here is the [SQLFiddle](http://sqlfiddle.com/#!4/b4504c/2)
``` select userid from your_table where events in ('blog','move') group by userid having count(distinct events) = 2 ``` If you have 3 events to check then use ``` having count(distinct events) = 3 ```
SQL - Table sort by events
[ "", "mysql", "sql", "" ]
I designed below query for my delete operation. I am new to SQL and just wanted to check with experienced people here if it is fine or any better way to do this. I am using DB2 database ``` DELETE FROM TableD WHERE B_id IN ( SELECT B.B_id FROM TableB tB INNER JOIN TableA tA ...
There isn't necessarily anything wrong with your method. However, a useful alternative technique to know is [merge](https://www-01.ibm.com/support/knowledgecenter/SSEPGG_9.7.0/com.ibm.db2.luw.sql.ref.doc/doc/r0010873.html): ``` merge into TableD using ( select distinct B.B_id from TableB tB ...
You can use merge like this too : ``` merge into TableD using TableB tB on B.B_id = TableD.B_id and tB.A_id in (select A_id from TableA tA where A_id = 123) and C_id in (1,2,3) when matched then delete; ```
Is there any better way to write this query
[ "", "sql", "db2", "sql-delete", "" ]
Is there any expressions to get `QUARTER`, `WEEK` and `DAYOFWEEK` of a DateTime field in Hive (v0.14.1) which do the same thing as these buildin functions in MySql? here is the specification of what I want (from MySql doc): [QUARTER](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_quarte...
Suppose the DateTime field is `order_time` * DAYOFWEEK: `PMOD(DATEDIFF(order_time, '2012-01-01'), 7)` * WEEK: `WEEKOFYEAR(order_time)` * QUARTER (hive <1.3): `(INT((MONTH(order_time)-1)/3)+1)` * QUARTER (hive >=1.3): `QUARTER(order_time)`
It always helps to know how to turn a month into a quarter using just math: ``` floor((cast(substr(visit_date, 6,2) as int) - 1) / 3) + 1 ```
Hive DateTime Truncators (QUARTER, WEEK, DAYOFWEEK)?
[ "", "sql", "datetime", "hive", "hiveql", "" ]
I am currently having troubles with filtering my SQL records. I need something like what it results in the following concept: **I wanted to results of some records based on the results of another field in the same table. Say, like the following:** ``` SELECT [Field1], [field2] FROM [table] WHERE [Field1] IN ('value1...
Starting with the top answer (@Siyual's), you can optimize it to lessen maintenance : ``` SELECT [Field1], [field2] FROM [table] WHERE ([Field1] = 'value2' AND [field2] NOT IN ('val1','val2')) OR ([Field1] = 'value1') ``` Using `[Field1] = 'value1'` or `[Field1] in('value1', 'value3', 'value...', 'valueN'...
Small bit of logic for two fields. ``` SELECT [Field1], [field2] FROM [table] WHERE [Field1] IN ('value 1' , ... ) -- Other non value 2 values OR (Field1 = 'Value 2' AND [field2] NOT IN ('val1','val2')) ```
MS SQL: SELECT field1, field2 from [table] where field2 NOT IN ('val1', val2') when field1 = 'value2'
[ "", "sql", "sql-server", "database", "subquery", "" ]
I am using MS Access 2010, split in front end / back end; on a network drive (WAN) with 16+ table with one table of **users (1.3 Million)** which is mostly used for user information and is not insert heavy and few other tables, which will receive **upto 2000+ inserts daily**. I have been able to optimize most of the r...
If you have now ``` S = "SELECT SomeId, SomeBoolean, SomeOtherBoolean " & _ "FROM recTable WHERE someCriteria" Set rec = DB.OpenRecordset(S) ``` change your statements into ``` "INSERT INTO TransportationDetails (TransportationId, SomeId) " & _ "SELECT " & vTransportationId & ", SomeId " & _ "FROM recTable WHERE...
I should point out that in the case of inserting rows, you will find FAR better performance by using a recordset. A SQL “action” query will ONLY perform better if you operating on a set of data. The instant you are inserting rows, then you don’t have a “set” insert, and using a DAO recordset will result in MUCH better ...
Increase Ms Access Insert Performance
[ "", "sql", "ms-access", "insert", "ms-access-2010", "query-performance", "" ]
So I have this problem where I need to find the rows where a coloumn have a specfic value. The table I use is created like this: ``` select table.CID, table2.PID from table inner join table2 on table2.OID = table.OID ``` The table looks like this: ``` +------------ table --------------+ |____table.CID___|___table2...
This query finds the rows with `47`: ``` SELECT ... FROM MyTable JOIN Table2 USING (OID) WHERE Table2.PID = 47; ``` The `CID` values of these rows can then be used to filter the original query: ``` SELECT MyTable.CID, Table2.PID FROM MyTable JOIN Table2 USING (OID) WHERE MyTable.CID IN (SELECT MyTable.CID ...
Use `exists`: ``` select t.* from table t where exists (select 1 from table t2 where t2.cid = t.cid and t2.pid = 47); ```
Find rows based on two coloumns in two tables
[ "", "mysql", "sql", "database", "sqlite", "" ]
Would anybody help me with this problem? (Please see attached image below) `Sample Table` [![enter image description here](https://i.stack.imgur.com/PRjBx.jpg)](https://i.stack.imgur.com/PRjBx.jpg) `what should be the result` [![enter image description here](https://i.stack.imgur.com/qQX3g.jpg)](https://i.stack.img...
This looks like a case for [RANK()](https://msdn.microsoft.com/en-us/library/ms176102.aspx) See this example: ``` SELECT EmployeeCode , Timestamp , Value FROM ( SELECT RANK() OVER (PARTITION BY EmployeeCode ORDER BY Timestamp) AS RN , EmployeeCode , Timestamp , Value FROM dbo.S...
``` You can use Row_number() also to generate minimum result : SELECT EMPLOYEECODE, TIMESTAMP, VALUE FROM (SELECT Row_number() OVER ( PARTITION BY EMPLOYEECODE ORDER BY TIMESTAMP)RN, EMPLOYEECODE, TIMESTAMP, V...
How to get the rows that have min timestamp using SQL
[ "", "sql", "sql-server", "sql-server-2008", "sqlite", "" ]
I have got a table `names` in MySQL with following columns `ID, type, row, value` The composite primary key is `ID, type, row` The purpose of this table is to save all names and professions of a specified person in multiple rows - one data per row. For example: Commonly in Spain people have two first names and two l...
This will return users that have the name José Laguna with the same ID: ``` select t1.id, t1.name, t2.name from yourTable t1 join (select * from yourTable where name = 'Laguna') t2 on t1.id = t2.id where t1.name = 'José' ```
I use `José` You could use a variable `@searchText` ``` SELECT * FROM YourTable WHERE ID IN (SELECT DISTINCT ID FROM YourTable WHERE value = 'José') ``` Or maybe use an `IN` if multiple parameters ``` WHERE value IN ('José', 'Laguna') ```
How to SELECT same ID of values occuring in the same column?
[ "", "mysql", "sql", "" ]