Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm trying to create a function that sums the result of all of one query's values and compares it to a number of another, simple query. This is what I have, however I'm getting a syntax error near begin (2nd line): ``` CREATE FUNCTION trigf1(sbno integer, scid numeric(4,0)) RETURNS integer BEGIN declare sum int d...
I don't know which "textbook" you were using but if everything you wrote is exactly as in that book, that book is totally wrong: ``` CREATE FUNCTION trigf1(sbno integer, scid numeric(4,0)) RETURNS integer AS -- error #1: no AS keyword $body$ -- error #2: use dollar quoting to specify the function body...
I am not really a postgresSQL person, but I would have thought ``` declare max as SELECT totvoters FROM ballotbox WHERE cid=scid AND bno=sbno; ``` should be ``` declare max := SELECT totvoters FROM ballotbox WHERE cid=scid AND bno=sbno; ```
Syntax error when create Postgres function
[ "", "sql", "postgresql", "" ]
I have two tables, one that store product information and one that stores reviews for the products. I am now trying to get the number of reviews submitted for the products between two dates but for some reason I get the same results regardless of the dates i put. This is my query: ``` SELECT productName, CO...
If the result, given your sample data, that you're looking for is: ``` | productName | count | rating | |-------------|-------|--------| | productA | 5 | 4 | | productB | 3 | 3 | | productC | 1 | 2 | ``` This is the count and average of reviews made on any date between `2015-07-20`...
You should not use left join, because by doing so you retrieve all the data from one table. What you should use is something like : ``` select productName, count(*) as `count`, avg(rating) as `rating` from products p, reviews r where p.productID = r.productID and `date` between '2015...
Using MySQL group by clause with where clause
[ "", "mysql", "sql", "" ]
I have a trip that has sequence of stops ``` Trip Stop Time 1 A 1:10 1 B 1:15 1 B 1:20 1 B 1:25 1 C 1:30 2 A 2:10 2 B 2:15 2 C 2:20 2 B 2:25 ``` I want to transfer the table to: ``` Trip Stop Time WaitTime 1 A 1:10 0 1 B ...
Hi I figured it out myself! Here is the answer in case anyone needs ``` With TB AS (select t1.* ,sum(decode(t1.stop,t1.prev_stp,0,1)) over (partition by trip order by time) new_seq from (select t.* ,lag(stop) over (order by t.trip, t.time) prev_stp from test t order by tm) t1) SELECT trip,stop,new...
``` with y as (select trip, stop, min(time) mintime, max(time) maxtime from tablename group by trip, stop) select y.trip, y.stop, y.mintime, (y.maxtime-y.mintime) waittime from y join tablename t on t.trip = y.trip and t.stop = y.stop ```
Loop and group by only when some conditions occur
[ "", "sql", "cursor", "" ]
``` USE AQOA_Core SELECT TOP 10 p.Title, SUM(r.SalesVolume) AS Sales, c.WeekId AS ReleaseWeek FROM Product p INNER JOIN RawData r ON p.ProductId = r.ProductId INNER JOIN Calendar c ON r.DayId = c.DayId WHERE c.WeekId BETWEEN 20145227 AND 20145228 GROUP BY p.Title, c.WeekId ORDER BY S...
Have you tried: ``` SELECT TOP 10 p.Title, SUM(r.SalesVolume) AS Sales, Min(c.WeekId) AS ReleaseWeek FROM Product p INNER JOIN RawData r ON p.ProductId = r.ProductId INNER JOIN Calendar c ON r.DayId = c.DayId WHERE c.WeekId BETWEEN 20145227 AND 20145228 GROUP BY p.Title ORDER BY Sale...
You need to select the first 10 rows in a sub select. Then from the sub select, use an aggregate. This will choose the latest ReleaseWeek like your test data instead of the first ReleaseWeek as your text describes. You can change this to MIN, if that was what you meant: ``` ;WITH CTE as ( SELECT TOP 10 p.Title, r...
SQL: Get the first value of a GroupBY Clause
[ "", "sql", "sql-server", "" ]
Refer to my previous posting. [Sql Cleanup script, delete from one table that's not in the other](https://stackoverflow.com/questions/31676517/sql-cleanup-script-delete-from-one-table-thats-not-in-the-other])[1](https://i.stack.imgur.com/iNe0e.png) Using DB2 for IBM i (As400, Db2). I am executing the following sql a...
Do you have heard of the concepts "transaction" and "isolation"? Typically different processes running against the same database are shielded (isolated) against each other, so they are operating without seeing the immediate impact of any other transaction running at the same time. Logically two transactions (a process ...
To explain the Visual Explain, DB2 will check the inner expression before executing the DELETE clause - it has to, or else it won't know what rows are affected. The reason your archived rows aren't archived is because the delete script ran before the insert script.
In what sequence will the Delete SQL execute?
[ "", "sql", "db2", "ibm-midrange", "db2-400", "" ]
I have a string like this `'abc : efg : xyz'` for a column in a table, all the records for this column will be like this. I want substring of this string after the last colon(:). Please do need ful help example: ``` 'abc : efg : xyz' -> xyz </br> 'abc : efg : efghj'-> efghj ``` I have query for this as below, but...
What you want is: ``` REGEXP_REPLACE (INPUTSTR, '^([^:]+ : )*', '') ``` Specifically, this seeks a string starting from the beginning (initial caret `^`) with zero or more occurrences of a string with non-colons (`[^:]+`) followed by `:` . It replaces all of these leading strings terminated with the space-colon-space...
As you say the pattern is fixed, reversing the string and looking for and getting a substring till the first semi-colon would be the easiest. You can also use `trim` to eliminate any leading/trailing spaces. ``` select reverse(substr(reverse('abc : efg : efghj'), 1,instr(reverse('abc : efg : efghj'),':')-1))...
Oracle sql regular expression
[ "", "sql", "regex", "oracle", "" ]
The tabled I am presented with looks similar to this ``` CREATE TABLE user_status ( user_id NUMBER(10,0) PRIMARY KEY, applied TIMESTAMP, joined TIMESTAMP, last_attended TIMESTAMP, quit TIMESTAMP ); ``` The database is Oracle 11g. What SQL query could use if I would like to return APPLIED, JOINED, ACTIVE ...
If all have values, you can do: ``` select us.* (case when applied = greatest(applied, joined, last_attended, quit) then 'Applied' when joined = greatest(applied, joined, last_attended, quit) then 'Joined' when last_attended = greatest(applied, joined, last_at...
``` select user_id, case greatest(applied, joined, last_attended, quit) when applied then 'APPLIED' when joined then 'JOINED' when last_attended then 'ACTIVE' when quit then 'INACTIVE' end from user_status ``` In the event of a tie between fields, the first field in the `case` expression wins.
Oracle SQL: Return a string based on which column has the highest value
[ "", "sql", "oracle", "" ]
I want to retrieve data from my table `Card`. ``` table Card( MembershipNumber, EmbossLine, status, EmbossName ) ``` Such that only those rows should be returned that have repeating MembershipNumber i.e having `count` greater than 1. Like if I Have following records ``` (11,0321,'active','John') (11,0322,'ac...
Use `Count() Over()` window function to do this. ``` SELECT * FROM (SELECT *, Count(MembershipNumber)OVER(partition BY EmbossName) AS cnt FROM youurtable) A WHERE cnt > 1 ``` **Demo** ``` SELECT MembershipNumber, [status], EmbossName FROM (SELECT *, Count(Me...
Find the duplicates on empbossname and get the result ``` select t1.* from card as t1 inner join (select empbossname from card group by empbossname having count(*)>1) as t2 on t1.empbossname =t2.empbossname ```
Retrieve rows on the basis of repeating value of a column
[ "", "sql", "sql-server", "count", "" ]
I need to add to the `WHERE` clause one condition, which is always true, but it must reference one of the columns, for example: `ID` is the primary key (and therefore `NOT NULL`) and I will execute a select: ``` SELECT * FROM Table WHERE ID IS NOT NULL ``` Will this condition be ignored or checked for every row...
SQL Server can determine at compile time that this condition will always be true and avoid the need to check at runtime. ``` CREATE TABLE #T ( ID INT CONSTRAINT PK_ID PRIMARY KEY NONCLUSTERED, X INT CONSTRAINT UQ_X UNIQUE ) SELECT X FROM #T WHERE ID IS NOT NULL; DROP TABLE #T ``` [![enter image description he...
When you execute following query: ``` SELECT * FROM Table WHERE ID IS NOT NULL; ``` It will display all the rows in your table given that ID is defined as the primary key. This will be similar to `SELECT * FROM Table;` from the display point of view. However, the condition will not be ignored.(i.e. the `where` clause...
SQL Server - ignoring always true condition
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have a stored procedure to generate a text file, which one has a lot of filters, here it is ``` -- ============================================= -- Author: Ricardo Ríos -- Create date: 17/01/2014 -- Description: Genera el TXT para Importar a Saint -- ============================================= ALTER PROCEDURE...
`CASE` inside `IN` statements for this task seems not possible because `CASE` only capable of returning scalar value, [according to this post](https://stackoverflow.com/questions/11232267/using-case-statement-inside-in-clause). Also, SQL Server can't naturally deal with comma-separated value. If you can afford to chang...
Ah, the issue is that its treating it like a varchar, not an integer. What you need to do is split them out, either into another table or XML. Best explained here: [Passing a varchar full of comma delimited values to a SQL Server IN function](https://stackoverflow.com/questions/878833/passing-a-varchar-full-of-comma-...
How to convert nvarchar to int inside an IN filter on a stored procedure
[ "", "sql", "sql-server-2008", "stored-procedures", "" ]
I try to use `varchar` string declared as variable: ``` DECLARE @fsPath AS varchar = 'D:\win-develop\FSCat'; ``` But in usage: ``` ALTER DATABASE MyDb ADD FILE ( NAME = 'FSCatalog', FILENAME = @fsPath ) TO FILEGROUP MyDbFSGroup; GO ``` I got error: ``` Incorrect syntax near '@fsPath'. ``` What i doing wrong?
You are not specifying the length and the default length is "1" in this context. So: ``` DECLARE @fsPath AS varchar(max) = 'D:\win-develop\FSCat'; ``` However, that is only one problem. You are not permitted to use variables in `alter database`. SQL Server documentation is rather convoluted on this topic, but you can...
You need to use dynamic SQL in-order to achieve this. We cannot pass variables to ALTER Check out [ALTER DATABASE / ADD FILE / VARIABLE FILENAME?](https://stackoverflow.com/questions/5590448/alter-database-add-file-variable-filename)
How to use varchar variable in SQL?
[ "", "sql", "sql-server", "sql-server-2014", "" ]
I have a table with 10 rows with ids 1-10. I want to delete row 5 and 8 and I want to IDs to be updated so that they are 1-8 and not 1-4, 6-7 and 9-10. I don't want to run a massive amount of update statements or do it by hand. Also I need solutions that work for both SQLServer and Oracle databases. I think something l...
You should include what you have tried, anyways you can run this query until no more updates happen (if you don't care about performance, better order by id and use the row number as the other answers do): ``` UPDATE myTable t SET id = id - 1 WHERE id <> 1 AND NOT EXISTS (SELECT * FROM myTable s WHERE s.id = t.id -...
You really should not do that, as Gordon Linoff pointed out. If you still would do that, here is an `UPDATE`: ``` update t_table t set id = ( select newid from ( select id, row_number() over (order by id) newid from t_table ) x where x.id = t.id ) ``` The syntax should probably work in both Oracle...
Deleting rows from database while keeping id continuity
[ "", "sql", "sql-server", "oracle", "" ]
I have a SQL Server table with a column called `Category`. In my user interface, I have a dropdown list of the category. User can select a category and click on a `Search` button to filter the results by the category. In the dropdown, the first option is blank. Means if the user wants to see all records from all catego...
You can use an `OR` statement to join the clauses together: ``` Select * From Table Where Catg = @Catg OR @Catg IS NULL ```
How about ``` SELECT * FROM yourtable WHERE (Catg = @Catg) OR (Catg IS NULL) ```
Single Select SQL Statement for 2 different Values
[ "", "sql", "sql-server", "" ]
``` Table_A ID Number -- ------ 1 0 2 00 3 0123 4 000000 5 01240 6 000 ``` The 'Number' column is data type varchar. **EDIT for clarity.** My question is, can I easily pull back all rows of data which contain a variable length string of 0's? I have tried: ``` SELECT * FROM Table_A WHE...
So, you want a string that *doesn't* contain anything that *isn't* a `0`? Sounds like it's time for a double-negative: ``` SELECT * FROM Table_A WHERE NOT Number like '%[^0]%' AND number like '0%' --But we do want it to contain at least one zero ``` (The final check is so that we don't match the empty string)
Answer: ``` Where number like '%0%' ```
WHERE varchar = variable length of 0's
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have a simple senario where I am executind 2 queries first to get an ID from a table And then using this ID to access information from second table. ``` SELECT ID FROM TEST_1 WHERE name = 'Example 1' Select * FROM TEST_2 WHERE Parent_ID = %ID retrived from the above query% ```
Use `IN` (if subquery returns more than 1 ID) or `=` (if subquery returns only 1 ID): ``` Select * FROM TEST_2 WHERE Parent_ID = (SELECT ID FROM TEST_1 WHERE name = 'Example 1') ```
You could have something like this: just placeyour 1st query in the where clause ``` Select * FROM TEST_2 WHERE Parent_ID = (SELECT ID FROM TEST_1 WHERE name = 'Example 1') ```
Merging 2 simple queries to one query
[ "", "sql", "sql-server-2008", "" ]
Assume I have the following models in my web Application: ``` Table User: (attr1, attr2, attr3, ...) Table Prize: (condition1, condition2, condition3, prize_val) ``` The application logic is: if a user satisfies all the conditions of a Prize, I want to grant him the prize. The condition could either be NULL (Tr...
1. You have a matrix of conditions with prize in each row. 2. The condition values can change over time along with prize value So, it is advisable to keep in database. Data should be in database and logic should be in code. In your case the conditions are providing data, which changes. But logic remains constant. Hop...
Rule of thumb: `SQL Query` is always more efficient when comparing with `iterations` in the code. About filtering - when you filter on `SQL` it will return less data than if you filter in the App. Also I think that filter in the `query` is faster than filter in the `code`.
Should I put this filtering in SQL or my application code?
[ "", "sql", "database", "web", "" ]
Lets say that at some point after several `SELECT`s and `JOIN`s, I have a following result: ``` Col1 Col2 +------+------+ | 1 | 2 | | 1 | 3 | | 4 | 5 | | 4 | 6 | | 5 | 6 | | 6 | 7 | +------+------+ ``` Now I want to find "inconsistencies", i.e. to display rows that have the sam...
``` select t1.* from (select col1,count(*) from table1 group by col1 having count(*) > 1) t2 join table1 t1 on t1.c1 = t2.c1 ``` You should use a outer query after you find the counts which are > 1. SQL Fiddle: <http://sqlfiddle.com/#!9/211a9e/6>
``` SELECT * FROM Table1 WHERE Col1 IN ( SELECT Col1 FROM Table1 GROUP BY Col1 HAVING COUNT(Col1) > 1 ); ``` <http://sqlfiddle.com/#!9/8de26/2>
Finding inconsistency in the table
[ "", "mysql", "sql", "" ]
I need to write a query to retrieve values that respect the following condition, > Select Users from UserTable that I am (me@gmail.com) not friends with Here are my table formats: [![enter image description here](https://i.stack.imgur.com/5n4BU.jpg)](https://i.stack.imgur.com/5n4BU.jpg) My email is stated at UserID...
If the friend relationship can go both ways and you want to exclude not only rows where email = 'me@gmail.com' but also rows where FriendID = 'me@gmail.com', that is, both rows below ``` UserID FriendID me@gmail.com ddaabb@gmail.com kk@gmail.com me@gmail.com ``` then this query will do that: ```...
You can use `NOT EXISTS` to check that the `Email` not present in `friends` table like below ``` select * from UserTable ut where not exists ( select 1 from FriendsTable where UserID != ut.Email) and ut.Email = 'me@gmail.com'; ``` Another solution is to use a `LEFT JOIN` and choose the `NULL` like ``` select ut.* fr...
Writing SQL Query to retrieve data via a Subquery?
[ "", "sql", "azure-sql-database", "" ]
I'm using Postgres 9.4 and want to do something like this: ``` movement_id|counter|standardized_output --------------------------------------- 1 | 3| 10 1 | 3| 12 1 | 5| 10 2 | 4| 5 ``` I have the ...
As you want results for rows that don't have any values you first need to create a set consisting of the rows that should be there, in this case the cartesian product of `{movement_id} X {1,3,5}`. To do this we can use a cross join and the table value constructor, and then it's just a case of using a left join and a su...
You could probably put a `CASE` statement on the counter field? ``` CASE WHEN counter >= 5 THEN 5 WHEN counter >=3 THEN 3 WHEN counter >=1 THEN 1 ELSE 0 END ``` Then add it to the select and the group by clause. ``` SELECT movement_id, (CASE WHEN counter >= 5 THEN 5 WHEN counter >=3 THEN 3 WHEN count...
SQL greater than IN
[ "", "sql", "postgresql", "" ]
* `Table1` -> Id, CountryFk, CompanyName * `Table2` -> Id, CountryFk, CompanyName, Website I need to merge `Table1` and `Table2` into 1 master table. I know this can be done by something like the below query - ``` INSERT INTO masterTable(Id, CountryFk, CompanyName) SELECT * FROM Table1 UNION SELECT * FROM...
IMHO, if you need to ensure both `CompanyName` and `CountryFk` not duplicate in MasterTable, you should add an unique index on the column. Below query selects all distinct value in Table1 and Table2, and insert with existence checking for both `CompanyName` and `CountryFk`. ``` -- Id is identity, no need to insert va...
This may work ``` INSERT INTO masterTable(Id, CountryFk, CompanyName,Website) SELECT Id, CountryFk, CompanyName, NULL as Website FROM Table1 UNION SELECT Id, CountryFk, CompanyName,Website FROM Table2; ```
Inserting data from two similar tables into one master table in Sql Server
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
My data looks like this: ``` Col1 Col2 output 09:35 16:00 6,25 <-- need help with this ``` I would like to have the output show `H,m` (hours,minuts) ``` Datediff(Hours,Col1,Col2) ``` give me 7. I don't want to make any parameters if possible only use some simple functions.
I think I would just do this explicitly, by taking the difference in minutes and doing the numeric calculations: ``` select (cast(datediff(minute, col1, col2) / 60 as varchar(255)) + ',' + right('00' + cast(datediff(minute, col1, col2) % 60 as varchar(255)), 2) ) ```
What about getting the date diff in minutes and converting the result to the string you want: ``` SELECT CONCAT(DATEDIFF(MINUTE, '09:35', '16:00') / 60, ':', DATEDIFF(MINUTE, '09:35', '16:00') % 60 ); ```
Datediff between hours
[ "", "sql", "sql-server", "t-sql", "datediff", "" ]
I need help in creating a SQL query for my report. I need to extract data which will show: how many managers in my company have employees example: 2 Managers have 4 directs each. Like this: ``` Managers Employees 1 (number of managers not ID) 2 2 4 5 ...
This should work for you: ``` select count(b.SupervisorID) Managers, b.directs Employees from (SELECT A.SupervisorID, COUNT(A.Emplid) AS DIRECTS FROM swe A WHERE A.HRStatus <> 'Terminated' AND A.HRStatus <> 'Deceased' GROUP BY A.SupervisorID) b group by ...
Try this on your query: ``` SELECT A.SupervisorID, COUNT(A.Emplid) AS DIRECTS, A.HRStatus FROM swe as A WHERE A.HRStatus <> 'Terminated' AND A.HRStatus <> 'Deceased' GROUP BY A.SupervisorID, A.Emplid, A.HRStatus ```
Managers report
[ "", "sql", "excel", "ms-access", "vba", "" ]
I have a MySQL table with the following structure and data: ``` Increments id emp_id starting_salary increment_rate increment_frequency 2 340 5000 250 1 3 340 5000 250 4 ``` I need to have aliases, `a` and `b` wh...
I'm not clear on all the details, for example what should happen if there are three rows for one employee in increments? Anyhow, here's a sketch to start with: ``` select employee_id , ((a * 8) / 30 + (b * 22) / 30) as basic_salary from ( select x.employee_id , min(starting_salary + (increment_rate ...
based on the requirements you added i think something like this will solve your problems: ``` SELECT PS.id, PS.employee_id, ((A.value * 8) / 30 + (B.value * 22) / 30) AS basic_salary FROM PaySlips AS PS JOIN ( SELECT I.emp_id, I.starting_salary + (increment_rate * increment_frequency) A...
How to use value from two different rows of a table in another table
[ "", "mysql", "sql", "" ]
This is my table: ``` -------------- Names -------------- "Ben 52" "Dan 236" "Carter 73" "Harry" "Peter 53" "Connor 27" "Morgan" "Richard 675" ``` I want to create a query that puts the columns without numbers at the end of the list. This is basically the idea of what I'm trying to create:...
Just use `order by`. Most databases support some form of regular expression, something like this: ``` order by (case when names regexp '.*[0-9].*' then 0 else 1 end), names ``` The exact syntax varies depending on the database. Note: it works with just `names regexp '[0-9]'`. I added the wildcards because I...
`SELECT names FROM table1 ORDER BY SUBSTRING(names, LENGTH(names)-2, 1) DESC` Everything which ends with a number will be below anything which ends with a character.
MySQL select order by contains num
[ "", "mysql", "sql", "" ]
I need some help figuring out how best to transform an an array into a row-vector. My array looks like this: ``` +-----+-------+----------+ | ID | Grade | Quantity | +-----+-------+----------+ | Ape | Water | Y | | Ape | Juice | Y | | Ape | Milk | Y | +-----+-------+----------+ ``` Each ID can ...
How about; ``` ;WITH Feeding(id,grade,quantity) as ( select 'Ape','Water','Y' union all select 'Ape','Juice','Y' union all select 'Ape','Juice','Y' union all select 'Ape','Juice','Y' union all select 'Ape','Juice','Y' union all select 'Ape','Milk', 'N' ) SELECT * FROM (SELECT ID, Grade, Q...
you can try following query:- ``` SELECT ID, Quantity, CASE WHEN Grade = 'WATER' THEN 1 ELSE 0 END AS WATER, CASE WHEN Grade = 'JUICE' THEN 1 ELSE 0 END AS JUICE, CASE WHEN Grade = 'BEER' THEN 1 ELSE 0 END AS BEER, CASE WHEN Grade = 'MILK' THEN 1 ELSE 0 EN...
Transforming multiple rows into columns w. single row
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I need to run a simple select statement across all the databases in the same server. I have around 30-40 databases. This table has same structure in all the databases. ``` select * from table1 where condition ``` Can you please let me know how to get the records from all databases?? BTW i'm using SQL Server
I would use a cursor for this, `sp_msforeachdB` has a bad reputation for skipping databases. A solution with a cursor would look something like this..... ``` DECLARE @DB_Name SYSNAME; DECLARE @Sql NVARCHAR(MAX); DECLARE Cur CURSOR LOCAL FAST_FORWARD FOR SELECT Name FROM sys.databases WHERE name NOT IN ('master', 't...
``` Exec sp_msforeachdB 'select top 5 cola from dbo.tablea' ```
How to run single select statement across all the databases in the same server
[ "", "sql", "sql-server", "database", "" ]
I have a table: ``` Trip Stop Time ----------------- 1 A 1:10 1 B 1:16 1 B 1:20 1 B 1:25 1 C 1:31 1 B 1:40 2 A 2:10 2 B 2:17 2 C 2:20 2 B 2:25 ``` I want to add one more column to my query output: ``` Trip Stop Time Sequence -------...
``` create table test (trip number ,stp varchar2(1) ,tm varchar2(10) ,seq number); insert into test values (1, 'A', '1:10', 1); insert into test values (1, 'B', '1:16', 2); insert into test values (1, 'B', '1:20', 2); insert into test values (1 , 'B', '1:25', 2); insert into...
``` select *, dense_rank() over(partition by trip, stop order by time) as sqnc from yourtable; ``` Use `dense_rank` so you get all the numbers consecutively, with no skipped numbers in between.
ROW_NUMBER query
[ "", "sql", "oracle", "window-functions", "" ]
I'm using SQL Server 2008. I have this data returned in a query that looks pretty much like this ordered by Day and ManualOrder... ``` ID Day ManualOrder Lat Lon 1 Mon 0 36.55 36.55 5 Mon 1 55.55 54.44 3 Mon 2 44.33 44.30 10 Mon 3 36.55...
You can use aggregate function `MIN` with `OVER` to create your ranking groups and `DENSE_RANK` working on top of it like this. **Brief Explanation** 1. `MIN(ManualOrder)OVER(PARTITION BY Day,Lat,Lon)` gets the minimum `ManualOrder` for a combination of `Day`, `Lat` and `Lon`. 2. `DENSE_RANK()` just sets this value a...
Here is my attempt using `ROW_NUMBER`: [**SQL Fiddle**](http://sqlfiddle.com/#!6/b4dee/1/0) ``` WITH CteRN AS( SELECT *, Rn = ROW_NUMBER() OVER(PARTITION BY Day ORDER BY ManualOrder), Grp = ROW_NUMBER() OVER(PARTITION BY Day, Lat, Lon ORDER BY ManualOrder) FROM tbl ), CteBase AS( SELECT *,...
SQL Number - Row_Number() - Allow Repeating Row Number
[ "", "sql", "sql-server", "sql-server-2008", "row-number", "dense-rank", "" ]
I have a stored procedure that has a `State` parameter as optional, so if I pass state it should query table using both parameter, if I am not passing the state parameter I only need to query table with the template parameter. How I can do that? This is my stored procedure: ``` CREATE PROCEDURE [dbo].[Get_TempName] ...
``` Create[dbo].[Get_TempName] @TemType varchar(50) ,@State varchar(50) = NULL AS BEGIN SET NOCOUNT ON; SELECT [TempType] ,[TempName] ,[State] FROM [Template] WITH (NOLOCK) where TempType = @TempType and (([State] IS NULL) OR ([State] = @State)) END ```
You can use `OR` condition with `Is Null` check. Also pass `NULL` in `@state` parameter when you don't want to use it in filter ``` Create[dbo].[Get_TempName] @TemType varchar(50) ,@State varchar(50) AS BEGIN SET NOCOUNT ON; SELECT [TempType] ,[TempName] ,[State] FROM [Template] WITH (NOLOCK) ...
Have a optional parameter in stored procedure
[ "", "sql", "sql-server", "t-sql", "" ]
I want to update SQL in which row's time is 5 minutes ago (or longer than 5 minutes): ``` UPDATE mytable SET status='EXPIRED' WHERE (a column's time is 5 minutes or longer before now) ``` I tried to use `DATE_ADD(NOW(), INTERVAL 5 MINUTE)` but I had no luck!
You can compare `now()` with the row's date column plus 5 minutes: ``` UPDATE mytable SET status = 'EXPIRED' WHERE DATE_ADD(date_col, INTERVAL 5 MINUTE) <= NOW() ```
Not sure but considering that your time column is of `DATETIME` you can use `BETWEEN` operator like below ``` UPDATE mytable SET status='EXPIRED' WHERE your_time_column BETWEEN DATE_ADD(NOW(), INTERVAL -5 MINUTE) AND DATE_ADD(NOW(), INTERVAL 5 MINUTE) ```
Update SQL if row's time is 5 minutes or longer than now
[ "", "mysql", "sql", "date", "time", "sql-update", "" ]
I have a list returning from select statement. For example ``` select type, id from userlist ``` returns: ``` type id 1 102 2 125 3 156 ``` Now I want to assign variable values based on the type. Is it possible in single statement? Like ``` SELECT case when type = 1 then @frontenduser = id ...
Alternative to `pivot`: ``` select @frontenduser = case type when 1 then id else @frontenduser end, @backenduser = case type when 2 then id else @backenduser end, @newuser = case type when 3 then id else @newuser end from userlist ``` or the same, using `iif` operator (if you use SqlServer 2012 or later):...
You can if you pivot the table. ``` select @frontenduser = [1], @backenduser = [2], @newuser = [3] from ( select [type], id from userlist ) As tbl PIVOT ( MAX(id) FOR [type] IN([1],[2],[3]) ) As pivotTable ```
Assign multiple variable from multiple rows in a select statement in SQL Server
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I have tables: ``` User Table User_id| Preferences |Blood_Group|City Events Table Event_id|Event_type|Blood_Group|Event_city|Event_Addded_By|Description Commit Table User_id|Event_id ``` I will send the user\_id so that,I want a query to return those events which are the events as prefered by user and blood\_group ...
``` SELECT [User Table].User_id, [Events Table].* FROM [Commit Table] INNER JOIN [User Table] ON [Commit Table].User_id = [User Table].User_id INNER JOIN [Events Table] ON [Commit Table].Event_id = [Events Table].Event_id ```
This might help you: ``` SELECT [Required Columns] FROM [User Table] UT JOIN [Event Table] ET ON ET.Bloodgroup = UT.Bloodgroup AND ET.City = UT.City WHERE NOT EXISTS ( SELECT 1 FROM [Commit Table] CT WHERE CT.UserId = UT.UserId AND ET.EventId = CT.EventId ) AND UT.UserId = @UserId ```
Sql Query or Join for 3 tables
[ "", "mysql", "sql", "database", "stored-procedures", "" ]
I have a table with multiple `type` values and I'm wanting to get a sample records from some of them. My current query is as follows: ``` -- Pulling three sample records from each "type" SELECT * FROM example WHERE type = "A" LIMIT 3 UNION ALL SELECT * FROM example WHERE type = "B" LIMIT 3 UNION ALL SELECT * FROM exa...
Use parentheses: ``` (SELECT * FROM example WHERE type = "A" LIMIT 3) UNION ALL (SELECT * FROM example WHERE type = "B" LIMIT 3) UNION ALL (SELECT * FROM example WHERE type = "C" LIMIT 3); ``` [**Demo here**](http://sqlfiddle.com/#!9/d911c/3) This is documented in the [manual](http://dev.mysql.com/doc/refman/5.1/en/...
Put parentheses around the selects ``` (SELECT * FROM example WHERE type = "A" LIMIT 3) UNION ALL (SELECT * FROM example WHERE type = "B" LIMIT 3) UNION ALL (SELECT * FROM example WHERE type = "C" LIMIT 3) ``` ### [SQLFiddle](http://sqlfiddle.com/#!9/d911c/3)
LIMIT and UNION ALL not returning the requested number of records
[ "", "mysql", "sql", "" ]
I have a database with this structure: * users + id + username + ........ + user\_status * questions + id + asker\_id + asked\_id + ........ + question\_status * answers + id + question\_id + who\_answer\_id + ........ + answer\_status * likes + id + liker\_id + liked\_id + ...........
What does this trigger do? * List item * Define new trigger * Check if user\_status column is updated. * Check if user\_status is updated to 'deleted' * Take id of that user, and change status of all of it's questions, answers, and likes to 'deleted'. Code: ``` DELIMITER // CREATE TRIGGER user_delete BEFORE UPDATE ...
``` BEGIN IF NEW.user_status <> OLD.user_status THEN IF STRCMP('deleted',NEW.user_status) = 0 THEN UPDATE questions SET question_status = 'deleted' WHERE asker_id = NEW.id AND question_status != 'mod_deleted'; UPDATE answers SET answer_status = 'deleted' WHERE commentator_id = N...
Database multiple tables trigger
[ "", "mysql", "sql", "database", "database-design", "" ]
I have this table named **`table1`** ``` id uniquefield field1 field2 1 11 test test2 2 12 test2 test3 ``` and I have this value in my temp table **`#temp1`** ``` id uniquefield field1 field2 1 11 test test2 2 12 ...
Temp tables are no different in such cases like you mentioned. The difference is they are only available to the current connection for the user; and they are automatically deleted when the user disconnects from instances. So you can handle these tables like any other SQL table and use a MERGE query to achieve this data...
`Temp tables` are no different in such cases like you mentioned. The difference is they are only available to the current connection for the user; and they are automatically deleted when the user disconnects from instances. So you can handle these tables like any other SQL table. Assuming the `uniquefield` column can ...
Transfer data from temp table to physical table
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I want to make an SQL request to display a list of users but only the one who haven't accepted a mission since at least 60 days. A user have multiple user missions attached to him, so I need to look at all of them and display the user only if no missions have been accepted since 60 days. Here is what I have so far, bu...
I think a query using a correlated `not exists` predicate would work: ``` SELECT * FROM users_user u WHERE NOT EXISTS ( SELECT 1 FROM users_usermission um WHERE u.id = um.user_id AND um.date_accepted > CURRENT_DATE - interval '60 days' ); ``` This would only return users for which there does...
You can do what you want by using aggregation and a left join. I would do it like this: ``` SELECT u.username, u.id, u.email, date_part('days', now() - um.date_accepted) as "days since last mission" FROM users_user u LEFT JOIN (SELECT um.user_id, MAX(date_accepted) as maxda FROM users_usermission um ...
Select only if no date are under 60 days from now
[ "", "sql", "postgresql", "date", "" ]
How do I convert the date to a month spelled out? For example. `01/08/2015` = January I have it code in excel `=TEXT(value, "MMMM")` but we are shifting away from Excel to SQL Server. Thanks
You need to use the [`DATENAME`](https://msdn.microsoft.com/en-us/library/ms174395.aspx) function. For example: ``` SELECT DATENAME(mm, DateCol) AS [Month] FROM MyTable ```
``` select datename(month,convert(varchar,yourField,106)) as month from yourTable ```
How to convert date to text Month?
[ "", "sql", "t-sql", "sql-server-2008-r2", "" ]
I have a simple design ``` id | grpid | main ----------------- 1 | 1 | 1 2 | 1 | 0 3 | 1 | 0 4 | 2 | 0 5 | 2 | 1 6 | 2 | 0 ``` The question to answer is ``` What is the "id" of the main in each group? ``` The result should be ``` id --- 1 5 ``` Seriously at the moment, I'm not ...
The simplest way you can do this with: ``` select id from <table_name> where main=1 ``` but as you have mentioned you want `id` with group by `grpid` below query will work. ``` select id from <table_name> group by grpid, main having main = 1 ``` You have to apply `group by` on your group id and based on that check ...
Maybe i'm oversimplifying it here but couldn't you just do this: ``` select id, grpid from table where main = 1; ```
SQL group by can't find correct phrase
[ "", "sql", "sql-server", "group-by", "" ]
I have table A with following data sample. I want to select the number `between` the last two `/` [![Data Layout](https://i.stack.imgur.com/49P06.png)](https://i.stack.imgur.com/49P06.png)
Try this: ``` DECLARE @text VARCHAR(MAX); SET @text = '79011/67541/545415/5401dfd245/25405244'; SELECT REVERSE(LEFT(REPLACE(REVERSE(@text),LEFT(REVERSE(@text),CHARINDEX('/',REVERSE(@text))),''),CHARINDEX('/',REPLACE(REVERSE(@text),LEFT(REVERSE(@text),CHARINDEX('/',REVERSE(@text))),''))-1)); ``` Check and then replac...
One way of doing it - ``` SELECT REPLACE(RIGHT(SUBSTRING(PTH, 1, LEN(PTH) - CHARINDEX('/', REVERSE(PTH))) , CHARINDEX('/', REVERSE(PTH))),'/','') FROM A ```
How to select a value between a pattern from the right side in SQL
[ "", "sql", "sql-server-2008", "select", "sql-server-2008-r2", "" ]
I'm trying to determine the number of dates, in a date range, that a person held a particular status. I have three tables with the following (simplified) structure: ``` Table Fields Calendar Date DateRange RangeID, StartDate, EndDate StatusHistory PersonID, Status, Date ``` The Cal...
We'd have an easier time of this if you were on LUW, and had access to `LEAD` (window functions are nice), but we'll just have to emulate it. The first thing you need to ask is a conceptual question: what are you trying to count? The answer is "days" - yes, you have conditions, but that's what you're trying to count. ...
Here are two solutions: 1. Calculate all combinations and count them, so that 0s are displayed 2. Only show combinations with count > 0 by grouping The idea to get the correct status is to join with StatusHistory on the date where it is <= the calendar date, but there exists no date bigger than the one from the statu...
SQL - Count dates that a status was held in a date range
[ "", "sql", "db2", "" ]
I have some query: ``` select disconnect_reason as disconnectReason, disconnect_cause, count(*) as callsCount from calls group by disconnect_reason, disconnect_cause ``` How I need to get items with callsCount = 1 only. How can I get it without `having`?
Always you can use `Having` clause to filter the groups but if you want a another way then try something like this ``` select * from ( select disconnect_reason as disconnectReason, disconnect_cause, count(*) as callsCount from calls group by disconnect_reason, disconnect_cause ) A Where callsCount = 1 ```
try using **CTE** For **MS SQL SERVER** ``` with cte as ( select disconnect_reason as disconnectReason, disconnect_cause, count(*) as callsCount from calls group by disconnect_reason, disconnect_cause ) select * from cte where callsCount >0 ```
How can I filter intems by `count(*)` without `having`?
[ "", "sql", "" ]
Please help me to solve this. I have this table note: [Notes](http://sqlfiddle.com/#!3/615a5/12/0) I want only this display: [Highest note strength value, only 1 display if more than 1 same note strength value of distinct SubjectID and Stat](http://sqlfiddle.com/#!3/70112/1/0) The problem is there were notes that ha...
`SELECT ID,SubjectID,Stat,MAX([Note Strength Value]) AS [Note Strength Value] FROM dbo.Note WHERE SeasonContext = 2015 AND Days in (99999, 7, 14, 30, 60, 90, 77777, 88888) GROUP BY SubjectID,Stat)` Change to `SELECT ID,SubjectID,Stat,MAX([Note Strength Value]) AS [Note Strength Value] FROM dbo.Note WHERE SeasonContex...
``` SELECT n.ID ,n.SubjectID ,dbo.udf_StripHTML(ISNULL(n.Note,'')) AS [Note] ,n.[Note Strength Value] FROM dbo.[Note] n INNER JOIN (SELECT ID,SubjectID,Stat,MAX([Note Strength Value]) AS [Note Strength Value] FROM dbo.Note WHERE SeasonContext = 2015 AND Days in (99999, 7, 14, 30, 60, 90, 77777, 88888) GROUP BY ID,Su...
SQL Server GROUP BY that include column in SELECT but not in GROUP BY clause
[ "", "sql", "database", "database-administration", "" ]
Sorry for bad title, I don't know how do describe better if you have a better one please tell me ;) Please look at these small sql fiddle: <http://sqlfiddle.com/#!6/8f522/4/1> I need the "Value" from a specific "Title" in a new column ("Age"). But I need the "Value" in any row for the same "SN\_Main". The first query...
You can join back onto the same table ``` SELECT MAIN.SN_Main ,MAIN.Data ,DETA.SN_Deta ,DETA.Title ,DETA.Value ,DETA2.Value AS Age FROM MainData AS MAIN INNER JOIN DetaData AS DETA ON MAIN.SN_Main = DETA.SN_Main INNER JOIN DetaData as DETA2 ON DETA.SN_Main = DETA2.SN_Main and DETA2.Title = 'Age' ```
A proper index could also work : ``` CREATE NONCLUSTERED INDEX idx_DetaData_SN_Main_Title ON DetaData ( SN_Main, Title) INCLUDE (Value) ``` And rewrite your query with inner join: ``` SELECT MAIN.SN_Main, MAIN.Data, DETA.SN_Deta, DETA.Title, DETA.Value, DETA2.Value FROM MainData AS MAIN INNER JOIN DetaData AS DETA ...
SQL - new column with the same cell value in every row for the same id without subquery
[ "", "sql", "sql-server", "subquery", "" ]
I have a table that lists employee schedules. I need to write a query to determine if more than one person was working on the same task at the same time. My data is like the following: ``` EmployeeID JobID StartTime EndTime M Tu W Th F Sa Su ===========================================================...
You're close but you need to reference the same table twice. So, you need a `JOIN` to represent your overlap table. Try something like this: ``` SELECT * FROM Table1 AS t1 JOIN Table1 AS t1_overlap ON t1_overlap.JobID = t1.JobID AND t1_overlap.EmployeeID != t1.EmployeeID AND (t1_overlap.StartTime BETWEEN ...
You just need to `self join` on the same table like others have mentioned and make sure to join on these following conditions: ``` SELECT distinct t1.EmployeeID as FirstEmployee, t2.EmployeeID as SecondEmployee, t1.StartTime as FirstEmployeeStartTime, t2.StartTime as SecondEmployeeStartTime, ...
Check if Overlap in Schedules
[ "", "sql", "sql-server-2008", "" ]
I am looking for the syntax to add a column to a MySQL table with the current time as a default value.
**IMPORTANT EDIT:** It is now possible to achieve this with `DATETIME` fields since **MySQL 5.6.5**, take a look at the [other post](https://stackoverflow.com/a/10603198/4275342) below... It is now possible to achieve this with `DATETIME` fields since MySQL 5.6.5 But you can do it with `TIMESTAMP`: ``` create tabl...
Even so many persons have provided solution but this is just to add more information- If you just want to insert current timestamp at the time of row insertion- ``` ALTER TABLE mytable ADD mytimestampcol TIMESTAMP DEFAULT CURRENT_TIMESTAMP; ``` If you also want that this column should update if any update this r...
Adding a new column with the current time as a default value
[ "", "mysql", "sql", "timestamp", "ddl", "" ]
A brief explanation on the relevant domain part: A Category is composed of four data: 1. Gender (Male/Female) 2. Age Division (Mighty Mite to Master) 3. Belt Color (White to Black) 4. Weight Division (Rooster to Heavy) So, `Male Adult Black Rooster` forms one category. Some combinations may not exist, such as mighty...
The solution described here will work correctly in multi-user environment and when destination tables `CategorySet` and `CategorySet_Category` are not empty. I used schema and sample data from your [SQL Fiddle](http://sqlfiddle.com/#!6/56b17/1). **First part is straight-forward** (ab)use [`MERGE`](https://msdn.micros...
Here is not the full answer, but direction which you can use to solve this: 1st query: ``` select row_number() over(order by t, Id) as n, Championship_Id from ( select distinct 0 as t, b.Id, a.Championship_Id from FakeResultSet as a inner join Category as b on a.AgeDivision_Id=b.AgeDivision_Id and a.Gender=b.Gender ...
Insert into multiple tables
[ "", "sql", "sql-server", "sql-server-2014", "" ]
I have a situation where I need to use a select statement in a where but then also append and prepend wildcards to the value it returns. E.g something like: ``` select * from [Customers.customervisibility] where userId like '%,' (Select Id from [Users.Users] where name ='MyName') ',%' ``` but running this gives: > I...
Try this `where` clause If your DBMS support `Concat` the use this. ``` userId like concat('%' ,(Select top 1 cast(Id as varchar(50)) from [Users.Users] where name ='MyName') ,'%') ``` Else ``` userId like '%' +(Select top 1 cast(Id as varchar(50)) from [Users.Users] where name ='MyName') +'%' ``` I have used `Top...
Try this: ``` select * from [Customers.customervisibility] where convert(VARCHAR(100),userId) like '%'+(Select Id from [Users.Users] where name ='MyName')+'%' ```
Is it possible to have a where with a select statement which you add wildcards to
[ "", "sql", "select", "where-clause", "wildcard", "" ]
I am stuck with a simple query. What i want is to get all rows except one Kindly have a look at the following data. ``` COL_A COL_B B D B (null) B C G D G (null) G C ``` I want to get all rows except but **B C**. Kindly have a look at the [sqlfiddle](http://sqlfiddle.com/#!4/33a6...
Try ``` where not(col_A = 'B' and col_B = 'C') ``` or ``` where col_A <> 'B' or col_B <> 'C' ```
One possible solution. Maybe not the most elegant: ``` select req_for col_A, doc_typ col_B from a where (req_for IS NULL OR doc_typ IS NULL) OR (req_for,doc_typ) NOT IN (select 'B','C' from dual); ```
Oracle: Get All Rows Except One
[ "", "sql", "oracle", "oracle11g", "" ]
I have been asked to do a job which is beyond my SQL skills a little and having done some research online, cannot quite find the write solution to be done in SQL Server 2008 and not MySQL. I have a table where I need to update specific names by adding an additional string after a certain point whilst keeping the rest ...
with the help of `STUFF` we can achieve this ``` STUFF ( character_expression , start , length , replaceWith_expression ) SELECT STUFF('Name - Location - 0005', 5, 0, ' (West)'); ``` output would be `Name (West) - Location - 0005`
Use STUFF function ``` declare @names varchar(100) set @names='Name - Location - 0005' select stuff(@names,5,0,' (West)') ```
SQL Server 2008 - Add to string in particular position within name column
[ "", "sql", "sql-server", "sql-server-2008", "sql-update", "" ]
I have a SQL `User-Defined Table Type`. It used in many stored procedures.Now i need to change a column in that table type. I tried to drop and recreate the `User-Defined Table Type`.But SQL Server doesn't Allow that. It shows up following error. ``` Msg 3732, Level 16, State 1, Line 3 Cannot drop type 'dbo.UserDefine...
You have binding in `SP_DoSomething` stored procedure. The type you want to change is used in that stored procedure. You need to save script of that procedure. Drop it. Change `dbo.UserDefinedTableType` and create procedure again. There is a similar post [here](https://stackoverflow.com/questions/11410722/altering-us...
In total you should delete all Functions and Stored Procedures which use this User-Defined Table Type. Then you can drop User-Defined Table Type and recreate it. Then you should recreate all Stored Procedures and Functions which you deleted in previous step. You can use this command for drop and recreate all SPs and F...
Unable to Modify User-Defined Table Type
[ "", "sql", "sql-server", "stored-procedures", "sql-server-2012", "user-defined-types", "" ]
I have the following table say filenames. ``` filename flag fileA 1 fileB 0 fileC 0 fileD 1 fileA 1 ``` I want all distinct filenames from this table AND If the flag is 1 for any file name, i want that file name to be replaced with 4 file names as FilaA\_part\_1, FilaA\_part\_2, FilaA\...
a union should do: ``` SELECT FILENAME FROM FILENAMES WHERE FLAG = 0 UNION SELECT FILENAME + '_part_1' FROM FILENAMES WHERE FLAG = 1 UNION SELECT FILENAME + '_part_2' FROM FILENAMES WHERE FLAG = 1 UNION SELECT FILENAME + '_part_3' FROM FILENAMES WHERE FLAG = 1 UNION SELECT FILENAME + '_part_4' FROM FILENAMES WHERE...
Try this should swork in sql server 2000 ``` SELECT filename + '_part' + num FROM Yourtable CROSS JOIN (SELECT '_1' num UNION ALL SELECT '_2' UNION ALL SELECT '_3' UNION ALL SELECT '_4') A WHERE ...
Single conditional select query in SQL
[ "", "sql", "sql-server", "sql-server-2000", "" ]
I have the following query: ``` select * from from assignments dah, employees emp where dah.person_id=emp.person_id(+) and (dah.effective_end_date between emp.date_from(+) and emp.date_to(+) and dah.effective_end_date between emp.valid_from(+) and emp.valid_to(+)) or (dah.effective_start_date between emp.dat...
Since you have to use the old-style outer join syntax, here's one way (simplified, since you didn't supply us with sample data and/or table creation scripts): ``` with assignments as (select 1 assignment_id, 1 person_id, to_date('01/08/2015', 'dd/mm/yyyy') start_date, to_date('03/08/2015', 'dd/mm/yyyy') end_date from ...
Use explicit `left join` syntax: ``` select * from employees emp left join assignments dah on dah.person_id = emp.person_id and ((dah.effective_end_date between emp.date_from and emp.date_to and dah.effective_end_date between emp.valid_from and emp.valid_to ) or (dah.effe...
SQL Alternative for 'OR' in where clause when using outer join
[ "", "sql", "oracle", "select", "join", "" ]
I have problem with splitting 0.00xxx float values between numbers. Here is example of input [data](http://sqlfiddle.com/#!4/d03a0) 0 is sum of 1-3 float numbers. As result I want to see rounded numbers without loosing sum of 1-3: IN: ``` 0 313.726 1 216.412 2 48.659 3 48.655 ``` --- OUT: ``` 0 313.73 1 216.41 2 4...
pragamtic solution based on following rules: 1) check the difference between the rounded sum and sum of rounded parts. ``` select round(sum(value),2) - sum(round(value,2)) from test where id != 0; ``` 2) apply this difference e.g. if you get 0.01, this means *one* rounded part must be *increased by 0.01* if you g...
``` select id, value, case when id <> max(id) over () then round(value, 2) else round(value, 2) - sum(round(value, 2)) over () + round(first_value(value) over (order by id), 2) * 2 end val_rnd from test ``` Output: ``` ID VALUE VAL_RND ------ ---------- ----...
Split float between list of numbers
[ "", "sql", "oracle", "" ]
I have a simple table and I need to identified groups of four rows (the groups aren't consecutives), but each rows of each row has a +1 in the value. For example: ``` ---------------------- | language | id | ---------------------- | C | 16 | | C++ | 17 | | Java | 18 | | Python ...
``` select language, @n:=if(@m+1=id, @n, @n+1) `set`, (@m:=id) id from t1, (select @n:=0) n, (select @m:=0) m ``` [**Demo on sqlfiddle**](http://sqlfiddle.com/#!9/99105d/1)
``` SELECT language,id,g FROM ( SELECT language,id, CASE WHEN id=@lastid+1 THEN @n ELSE @n:=@n+1 END AS g, @lastid := id As b FROM t, (SELECT @n:=0) r ORDER BY id ) s ``` EDIT In case you want just 4 per group add a row number variable: ``` SELECT language,id,g,rn FROM ( SELECT language,id, ...
Group consecutively values in MySQL and add an id to such groups
[ "", "mysql", "sql", "database", "gaps-and-islands", "" ]
I'm having trouble to understand how to nest case statements properly. (MSSQL Server 2012) Let's have the following table given. The Column StatusMissing is what I want to create ``` +------+--+------+--+------+--+------+--+------+--+------+--+---------------+ | a1 | | a2 | | a3 | | b1 | | c1 | | d2 ...
I might suggest that you make two small modifications to your output: * Instead of "As", just say "A". * Instead of "AllOK", just leave the field blank. With these modifications, the rules are pretty easy: ``` select t.*, ((case when a1 is null or a2 is null or a3 is null then 'A' else '' end) + (case...
For the simplified table, assuming data type to be `nvarchar`. Try using `UPDATE`- ``` UPDATE [dbo].[StatusMissing] SET result=''; UPDATE [dbo].[StatusMissing] SET result= CONCAT(result , 'A') WHERE a1 is null or a2 is null; UPDATE [dbo].[StatusMissing] SET result= CONCAT(result , 'B') WHERE b1 is ...
Nested case with multiple sub conditions
[ "", "sql", "sql-server", "case", "case-statement", "multiple-conditions", "" ]
I'm creating a table using this script. ``` create table TimeFrames( Id int identity, Name varchar(100), Active bit ) ``` Before, I also altered the table by adding a primary key and anindex. However, now, I've forgotten to do the latter and, since I experience no difference in functionality, I wonder if it's o...
You did create the primary key, right? Indexes are there for performance reasons, unless they are also unique. In that case, they require each record to have a different value/set of values for the affected columns. A clustered index will also determine how the rows are physically stored in the database, but that pro...
Indexes exist almost exclusively for performance reasons. The one major exception that I can readily think of are unique indexes. These are also used to enforce `unique` constraints. There is also the issue that a `foreign key` constraint requires a unique or primary key constraint in the referenced table.
The impact of not creating indexes
[ "", "sql", "sql-server", "" ]
Our development database gets reset weekly. I find myself spending an hour or so on Monday mornings (like today) inserting all of my test data into the various tables and databases from individual scripts. First, of course, I have to verify that these tables do not have my data: ``` SELECT Count(*) FROM Table1 WHERE ...
You need to change that so that you only "select" those values that aren't there: ``` INSERT INTO TBLBARTRANS (UPC, CATALOG, VENDOR, ADD_DATE, INVLINK, WHO_ADDED, TYPE, VENDOR_ID) select * from ( values ('011010017760', 'LOVE', 'TES', '20150609', '19070105063041', 9388, 'P', '1013'), ('011010017760', 'HATE'...
In addition to what others have said, you might consider moving your data to csv files and load/ingest those instead of inserting them inside an sql statement. <https://www-01.ibm.com/support/knowledgecenter/SSEPGG_10.1.0/com.ibm.db2.luw.admin.cmd.doc/doc/r0057198.html?cp=SSEPGG_10.1.0%2F3-6-2-4-59> <https://www-01.i...
IBM DB2 INSERT when Count(*) = 0
[ "", "sql", "db2", "" ]
``` create table t1 (col1 int); ``` Leave the table empty. ``` select isnull(col1,0) from t1; ``` I want to replace null with zeros in the above case. However, `ISNULL()` does not work if there are no records in the table. How can I get around this?
Maybe you can first test if the table is empty: ``` IF NOT EXISTS (select * from t1) SELECT 0 ELSE select coalesce(col1,0) from t1; ``` Anyway, you should use COALESCE instead of ISNULL because it is standard SQL.
In case if you want to replace non existing value then surround another null check of mentioned select statement. like this ``` ISNULL(select isnull(col1,0) from t1,0) ```
Handle missing data in SQL Server 2012 SELECT statement
[ "", "sql", "sql-server", "t-sql", "null", "" ]
I have three tables , both with the same fields as in the example below: Table: ``` dog ------------- name, date ``` Table : ``` cat ------------- name, date ``` Table: ``` animal ------------- name, date ``` as I transfer the dog and cat data for animal table ? I tried the select into but could not do it with t...
Try this: ``` insert into animal select name, date from dog union all select name, date from cat ```
It can be done with the execution of a query ie:Join operation.Table 1, Table 2,table 3. We have the same attribute in all these three tables.Just join the attributes with table1.fieldname JOIN table2.fieldname JOIN table3.fieldname
How can I insert data from two tables into one?
[ "", "sql", "sql-server", "" ]
I have a column of type `number`. It has both positive and negative values. I need to get 4 values : Positive Maximum,Positive Minimum, Negative Maximum,Negative Minimum: a)To get Positive Maximum : I can use [Check out the Fiddle](http://sqlfiddle.com/#!4/6aa70/4) ``` select max(cola) from test; ``` b)To get Negati...
For question 1, you can easily use case to determine which values you do the min/max on. E.g.: ``` select max(case when cola >= 0 then cola end) max_positive, min(case when cola >= 0 then cola end) min_positive, max(case when cola < 0 then cola end) max_negative, min(case when cola < 0 then cola e...
use case expressions within the aggregation functions. e.g. max(when cola < 0 then cola end) max\_neg min(cola) min\_neg -- no need for case expression here [SQL Fiddle](http://sqlfiddle.com/#!4/6aa70/10) **Oracle 11g R2 Schema Setup**: ``` Create table test(COLA number); Insert into test values(1); Insert into ...
How to find Negative maximum and positive minimum in Oracle?
[ "", "sql", "oracle", "oracle11g", "max", "min", "" ]
Using [Remove part of string in table](https://stackoverflow.com/questions/23907373/remove-part-of-string-in-table) as an example, I want to change part of my string in my database column with a different string. Ex: Database says `E:\websites\nas\globe.png` , `E:\websites\nas\apple.png` and etc I want it to say `\\...
I found a reference at [how to replace string values of column values by SQL Stored Procedure](https://stackoverflow.com/questions/28297168/how-to-replace-string-values-of-column-values-by-sql-stored-procedure) by doing the following: ``` UPDATE t_class SET file_name = REPLACE (file_name, 'E:\websites\web\Class\Ma...
In Oracle, you may need to double up on the back slashes: ``` SELECT file_name, REPLACE(file_name,'E:\\websites\\', '\\\\nas\\') FROM t_class; ```
Replace part of string in table column
[ "", "sql", "string", "replace", "oracle10g", "" ]
I have a `users` table with columns `id`, `username`, `password` I also have an `orders` table with columns `id`, `user_id`, `price`, `status` In the `index` method of the `UsersController`, I would like to order my users based on the amount of purchases they have made. The purchases of each user can be gotten as t...
After some trials I got a good and simple solution ``` $users = User::leftJoin('orders', 'orders.user_id', '=', 'users.id') ->select('users.*', DB::raw( 'sum( orders.price ) as `total_purchase`' ) ) ->groupBy('users.id') ->orderBy('total_purchase', 'DSC') ->paginate(10); ```
The pure SQL for this will look something like this: ``` SET @rank = 0; SELECT @rank := @rank + 1 AS Rank ,Username FROM ( SELECT U.username AS Username FROM orders O JOIN users U ON U.id = O.user_id WHERE O.status = 4 GROUP BY O.user_id ORDER BY SUM(O.price) DESC ) X; -- Reset Rank ...
How to order queries of one table based on the sum of a column in a related table
[ "", "sql", "laravel", "laravel-4", "eloquent", "" ]
I have an Oracle database server running on a machine. Clients performs operations through a frontend application build from a different company, which generates corresponding SQL queries for these operations. The frontend application generates SQL queries that we cannot modify. What I would like to know if there is a...
You might enjoy this Oracle Database 12c feature, the SQL Translation Framework. Designed for taking T-SQL to SQL when migrating applications from Sybase or SQL Server to Oracle, it can also be used to help with hard-coded vendor SQL you need to optimize/fix. [Oracle Docs](https://docs.oracle.com/database/121/DRDAA/sq...
If I didn't understand correctly, you want to do two things. 1. Change tablespace for this table 2. Change metadata from this table You can do both easily. 1. `alter table [table_name] move [new_tablespace]; -- it must exists` ( check tablespace quota in this tb for this user ) 2. `alter table [table_anem] MODIFY...
Oracle SQL Query rewriting
[ "", "sql", "oracle", "" ]
I hope that i can explain it right, because i'm not a native english speaker. I have 2 tables- `Document` and `Vehicle`. As you can see in the `SELECT` query, the columns `Id(Vehicle)` and `VehicleId(Document)` are common. The columns `SeriePolita`,`NumarPolita`,`d.Status` are from the `Document` table and `v.CascoC...
the code you have can be rewritten as follows: ``` select d.SeriePolita, d.NumarPolita, d.Status, v.CascoCategorieVehicul, v.NumarInmatriculare from Document AS d inner join Vehicle AS v on v.Id = d.VehicleId where EndDate>'2015-06-30' and d.Class='CASCO' and Status in ('Polita', 'Anulat'); ``` mi...
`Vehicle v` is a reference to the `Vehicle` table by the alias `v`. The reason for doing this is so you don't have to type, for instance `inner join Vehicle on Vehicle.Id = Document.VehicleId` - it's shortened and more concise and you can refer to the alias in the `select` and `where` clause. Now suppose that there is...
How to explain "inner join Vehicle v on v.Id = d.VehicleId"?
[ "", "sql", "sql-server", "" ]
Can someone tell me what I'm doing wrong, and if I can get the expect result... (Keep in mind this is a `VIEW`) ``` SELECT [Id] , [Nome] , [Estado] , (SELECT COUNT(EstProc) FROM LoginsImp AS LI WHERE (EstProc = 'A1.' OR EstProc = 'A2.') AND LI.LogImpFiles_Id = LIF.Id) AS ItemsProcessamento , (SEL...
Use `JOIN` for your conditional aggregation instead of subquery. And as JamesZ pointed out, the `SUM` is not going to use the column alias. ``` SELECT [Id] , [Nome] , [Estado] , COUNT(CASE WHEN LI.EstProc = 'A1.' OR LI.EstProc = 'A2.' THEN LI.EstProc END) AS ItemsProcessamento , COUNT(CASE WHEN LI....
I am tempted to say "it is just your data". That is, your question doesn't have enough information. However, I suspect the problem is `NULL` values. The `+` returns `NULL` if either value is `NULL`. So, try this: ``` SUM(COALESCE(ItemsErroProcessamento, 0) + COALESCE(ItemSucessoProcessamento, 0) ) AS [ItemsProcess...
Sum result of SELECT...WHERE in SQL Server
[ "", "sql", "sql-server", "" ]
I need help verifying the empty or null values in mysql I tried to use this way in my case but is not working: ``` SELECT CASE WHEN account_type IS NULL THEN 'Uninformed' WHEN account_type = '' THEN 'Empty ' END as Type, COUNT(accounts.id) AS Total FROM acc...
Your query is correct. At last you need to add `group by account_type;`. Query should be like this. ``` SELECT CASE WHEN account_type IS NULL THEN 'Uninformed' WHEN account_type = '' THEN 'Empty ' END AS Type, COUNT(accounts.id) AS Total FROM accounts GROUP BY account_type ```
``` SELECT CASE WHEN account_type IS NULL THEN 'Uninformed' WHEN account_type = '' THEN 'Empty ' END as Type, COUNT(accounts.id) AS Total FROM accounts group by account_type ``` You are missing a `group by` clause.
MySQL check blank or null values
[ "", "mysql", "sql", "null", "case", "" ]
I'm tring to filter products with both `Id` 17 with value 97 and `Id` 6 with value 11. Here is the [SQL Fiddle](http://sqlfiddle.com/#!3/616573/2) for this. In this example, I need to return the row where `fkProductId = 24011`. Can you help me please? ``` CREATE TABLE AttributeBindings( fkProductId int, fkA...
You can self join the table on product id: ``` Select p1.fkProductId From AttributeBindings p1 inner join AttributeBindings p2 on p1.fkProductId = p2.fkProductId where (p1.fkAttributeId = 17 and p1.fkAttributeValueId = 97) and (p2.fkAttributeId = 6 and p2.fkAttributeValueId = 11) ```
``` SELECT fkproductid FROM AttributeBindings WHERE fkAttributeId = 17 AND fkAttributeValueId = 97 intersect SELECT fkproductid FROM AttributeBindings WHERE fkAttributeId = 6 AND fkAttributeValueId = 11 ``` You can use `INTERSECT` to get the result.
ms sql 2008 - one table , multiple filter
[ "", "sql", "sql-server-2008", "t-sql", "" ]
Is there a way to know all the possible (acceptable) keywords, after a SELECT statement in SQL before the list of fields? **Edit** Reference DB is MySQL
## PostgreSQL 9.4 <http://www.postgresql.org/docs/9.4/static/sql-select.html> ``` [ WITH [ RECURSIVE ] with_query [, ...] ] SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ] [ * | expression [ [ AS ] output_name ] [, ...] ] [ FROM from_item [, ...] ] [ WHERE condition ] [ GROUP BY expression [, ...
[**Reserved Keywords in MySql**](https://dev.mysql.com/doc/refman/5.0/en/keywords.html) Keywords are words that have significance in SQL. Certain keywords, such as SELECT, DELETE, or BIGINT, are reserved and require special treatment for use as identifiers such as table and column names. This may also be true for the ...
Reserved keywords after SELECT
[ "", "mysql", "sql", "select", "keyword", "" ]
I am building a locking system based on PostgreSQL, I have two methods, `acquire` and `release`. For `acquire`, it works like this ``` BEGIN while True: SELECT id FROM my_locks WHERE locked = false AND id = '<NAME>' FOR UPDATE if no rows return: continue UPDATE my_locks SET locked = true WHERE id ...
The test case plays out like this: * Thread-1 runs the `SELECT` and acquires the record lock. * Thread-2 runs the `SELECT` and enters the lock's wait queue. * Thread-1 runs the `UPDATE` / `COMMIT` and releases the lock. * Thread-2 acquires the lock. Detecting that the record has changed since its `SELECT`, it rechecks...
PostgreSQL [normally](http://www.postgresql.org/docs/9.4/static/explicit-locking.html#LOCKING-DEADLOCKS) aborts transactions which deadlock: > The use of explicit locking can increase the likelihood of deadlocks, wherein two (or more) transactions each hold locks that the other wants. For example, if transaction 1 acq...
Strange deadlock PostgreSQL deadlock issue with SELECT FOR UPDATE
[ "", "sql", "database", "postgresql", "transactions", "deadlock", "" ]
Hello everyone I'm trying to get all records without duplicate. Here my sample database records. ``` (`id`, `productName`, `description`) ----------------------------------------------- (1, 'OpenIDM', 'Platform for building enterprise provisioning solutions'), (2, 'OpenAM', 'Full-featured access managemen...
I think that you must use DISTINCT ``` select distinct productName,description from ForgeRock; ``` And this is mi result on fiddle: <http://sqlfiddle.com/#!9/6c924/132>
One method is to get data of minimum id ``` select min(`id`),`productname`,`description` from forgerock group by `productname`, `description` ```
How to get all records without duplicate
[ "", "sql", "duplicates", "" ]
I have a lot of data that I want to spool to a csv file. I need to `set heading off` so the heading will not repeat every page. However, I still need my produced file to contain headers. Is there a way to add a row of headers (not to the table itself) into the query that won't actually be considered a header when spool...
you could always try something like: ``` set heading off; select 'NAME1' name1, 'NAME2' name2, 'NAME3' name3 from dual union all select a.col1 as name1, a.col2 as name2, b.col3 as name3 from tab1 a, tab2 b where <join condition>; ``` ETA: If the column types returned by the main query aren't all strings, you'll have...
You want to try: ``` set pages <number of rows you expect> ``` E.g. `set pages 1000` Another way around could be a UNION like so: `SELECT 'name1', 'name2', 'name3' FROM DUAL UNION select a.col1 as name1, a.col2 as name2, b.col3 as name3 from tab1 a, tab2 b`
trouble creating headers using spool in sqlplus
[ "", "sql", "oracle", "sqlplus", "" ]
``` WITH hi AS ( SELECT ps.id, ps.brgy_locat, ps.municipali, ps.bldg_name, fh.gridcode, ps.bldg_type FROM evidensapp_polystructures ps JOIN evidensapp_floodhazard fh ON fh.gridcode=3 AND ST_Intersects(fh.geom, ps.geom) ), med AS ( SELECT ps.id, ps.brgy_locat, ps.municipali ,ps.b...
You probably want this instead: ``` WITH hi AS ( SELECT ps.brgy_locat, ps.municipali, ps.bldg_name, ps.bldg_type, fh.gridcode , count(*) OVER(PARTITION BY ps.bldg_name, ps.bldg_type) AS building_count FROM evidensapp_polystructures ps JOIN evidensapp_floodhazard fh ON fh.gridcode = 3 ...
Error is asking you to include the select list columns in the `GROUP BY` clause; you can do like below ``` SELECT brgy_locat, municipali, bldg_name, bldg_type, gridcode, building_count FROM (SELECT brgy_locat, municipali, bldg_name, gridcode, bldg_type, count( bldg_name) as building_count FROM hi G...
PostgreSQL: Query doesn't work using count
[ "", "sql", "postgresql", "group-by", "" ]
I have a SQL query that performs an INNER JOIN on two tables having >50M rows each. I wish to reduce the time it takes to search through the join by reducing the rows that are joined based on a column present on one of the tables. Say I have table1 with columns A,B,C and table2 with columns A,D,E. I wish to join based...
``` SELECT one.B, two.D FROM table1 one INNER JOIN table2 two -- WHERE two.E IN ('e') --> shouldn't use where here ON one.A = two.A and two.E = 'e' WHERE one.B > 10 AND two.D IN ('...') ``` Comments included in the code.
As vkp pointed out, the WHERE is improperly used. Instead you could also make a subquery to include that where statement. So that: ``` INNER JOIN table2 two WHERE two.E IN ('e') ``` becomes ``` INNER JOIN (select * from table2 WHERE E IN ('e')) two ```
Optimising SQL query
[ "", "sql", "oracle", "inner-join", "" ]
I have a table for my users scores like this: ``` id | kills ---------- 2 | 1 1 | 1 1 | 5 1 | 3 2 | 4 2 | 5 3 | 5 ``` I want to get the first 2 rows of each player which have more than 2 kills. So the result should look like this ``` id | kills ---------- 1 | 5 1 | 3 2 | 4 2 | 5 3 | 5 ``` I tried this b...
I suspect that you just want the two largest values for users that have kills > 2. If so, use variables: ``` select us.* from (select us.*, (@rn := if(@i = id, @rn + 1, if(@i := id, 1, 1) ) ) as seqnum from user_stats us cross join ...
Try this. I am coming from Oracle, where rownum is a count of rows selected. This should have the same effect. ``` select @rownum:=@rownum+1, us.* from user_stats us , (select @rownum := 0) r where id in ( select id from user_stats f group by id having count(*) > 2 ) and @rownum < 3; ```
first N row of each id in MySQL
[ "", "mysql", "sql", "group-by", "aggregate", "" ]
Why does this SQL not work? The: ``` 6371 * ACos( Cos(RADIANS(Latitude)) * Cos(RADIANS('50.017466977673905')) * Cos(RADIANS('24.69924272460935') - RADIANS(Longitude)) + Sin(RADIANS(Latitude)) * Sin(RADIANS('50.017466977673905')) ) ``` Clause just calculates the order from a search point. Which I am aliasing (becaus...
This happens because of natural query processing order, which is the following: 1. `FROM` 2. `ON` 3. `OUTER` 4. `WHERE` 5. `GROUP BY` 6. `CUBE` | `ROLLUP` 7. `HAVING` 8. `SELECT` 9. `DISTINCT` 10. `ORDER BY` 11. `TOP` You're assigning your alias in `SELECT` statement. As you can see `WHERE` is processed before `SELEC...
As to why you can't specify an alias in the `WHERE` clause, this is due to the logical order of query processing: (<http://tsql.solidq.com/books/insidetsql2008/Logical%20Query%20Processing%20Poster.pdf>). The `WHERE` clause is processed after the `SELECT` clause but `ORDER BY` is processed afterward. Column aliases ca...
Cannot use Alias name in WHERE clause but can in ORDER BY
[ "", "sql", "sql-server", "" ]
I have several related tables that I want to be able to duplicate some of the rows while updating the references. I want to duplicate a row in Table1, and all of it's related rows from Table2 and Table3, and I'm trying to figure out an efficient way of doing it short of iterating through rows. So for example, I have ...
Why dont you join on the FruitName to get a table with old and new FruitId's? Considering information would be added at the same time.... it may not be the best option but you wont be using any cycles. ``` INSERT INTO BASKET(BASKETNAME) VALUES ('COPY BASKET') DECLARE @iBasketId int SET @iBasketId = @@SCOPE_IDENTITY; ...
(ab)use [`MERGE`](https://msdn.microsoft.com/en-us/library/bb510625.aspx) with `OUTPUT` clause. `MERGE` can `INSERT`, `UPDATE` and `DELETE` rows. In our case we need only to `INSERT`. `1=0` is always false, so the `NOT MATCHED BY TARGET` part is always executed. In general, there could be other branches, see docs. `WH...
How to better duplicate a set of data in SQL Server
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I want to extract content from text in an SQL field after a keyword. I have a field called `Description` in a table, the content for that field is: > asdasf keyword dog > > aeee keyword cat > > ffffaa keyword wolf I want to extract and save the text after "keyword " (in this case `dog`,`cat` and `wolf`) and save it i...
Here is an example using `SUBSTRING()`: ``` SELECT SUBSTRING(YourField, CHARINDEX(Keyword,YourField) + LEN(Keyword), LEN(YourField)) ``` Another example: ``` declare @YourField varchar(200) = 'Mary had a little lamb' declare @Keyword varchar(200) = 'had' select SUBSTRING(@YourField,charindex(@Keyword,@YourField) + L...
Just to add to @psoshmo's answer If keyword is not found it will substring the original string, to counter this I have added a case like below ``` SUBSTRING(YourField, CHARINDEX('Keyword',YourField) + (CASE WHEN ', ' + YourField +',' LIKE '%Keyword%' THEN LEN('Keyword') ELSE 1 END), LEN(YourField)) ```
Extract string from a text after a keyword
[ "", "sql", "sqlite", "" ]
**EXPLAINATION** Imagine that I have 2 tables. `FormFields` where are stored column names as values, which should be pivoted and second table `FilledValues` with user's filled values with `FormFieldId` provided. **PROBLEM** As you see (below in *SAMPLE section*) in `FormFields` table I have duplicate names, but diff...
Since you are using PIVOT the data is being aggregated so you only return one value for each column being grouped. You don't have any columns in your subquery that are unique and being used in the grouping aspect of PIVOT to return multiple rows. In order to do this you need some value. If you have a column with a uniq...
Just adding `GroupId` in `Pivot source` query will fix your problem ``` SELECT * FROM ( SELECT FF.Name AS NamePiv, FV.Name AS Val1, ff.groupid FROM FormFields FF JOIN FilledValues FV ON FF.Id = FV.FormFieldId ) x PIVOT ( MIN(Val1) FOR NamePiv IN ([col1],[col2],[col3]) ) piv ``` [**SQLFIDDLE ...
Pivot duplicate column names and get all values for columns
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "pivot", "" ]
I have the following query. ``` with getstock as ( select a.bomparent, a.bomchild, a.bomqty, a.bompos, a.baltmethod, a.bomissue from bom a where bomparent = 'QZ10-0262601' and baltmethod = '1' union all select parent.bomparent, parent.bomchild, parent.bomqty, ...
You can not use multiple tables in `JOIN`. It's possible in `FROM`, but I won't suggest that. That's the old-style `JOIN` syntax. You should rewrite your query using explicit `JOIN`: ``` with getstock as ( select a.bomparent, a.bomchild, a.bomqty, a.bompos, a.baltmethod, a.bomissue from bom ...
``` with getstock as ( select a.bomparent, a.bomchild, a.bomqty, a.bompos, a.baltmethod, a.bomissue from bom a where bomparent = 'QZ10-0262601' and baltmethod = '1' union all select parent.bomparent, parent.bomchild, parent.bomqty, parent.bompos, parent.baltmethod, parent.bomissue fro...
Incorrect syntax error in join query sql
[ "", "sql", "sql-server", "" ]
Lets take we have: ``` SELECT Name, Surname, Salary, TaxPercentage FROM Employees ``` returns: ``` Name |Surname |Salary |TaxPercentage -------------------------------------- Moosa | Jacobs | $14000 | 13.5 Temba | Martins | $15000 | 13.5 Jack | Hendricks | $14000 | 13.5 ``` I want it to return: ```...
In sql server 2012 and above you can use the [`Lead`](https://msdn.microsoft.com/en-us/library/hh213125(v=sql.110).aspx) window function to get the value of the next row. Assuming you have some way to sort the data (like an identity column), you can use this to your advantage: ``` SELECT Name, Surname, ...
If for some reason you can't use `LEAD()` then this should work: ``` with T as ( SELECT Name, Surname, Salary, TaxPercentage, row_number() over (order by TaxPercentage /* ??? */) as rn FROM Employees ) select Name, Surname, Salary, nullif( TaxPercentage, (select t2.rn fr...
How to make a select statement to return "NULLs" if the value is a repetition in SQL
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I got a SelfJoin query ``` ;WITH t as ( SELECT ROW_NUMBER() OVER (ORDER BY dbo.DIM_PROJECT_TECH_OBJ.FUNCTIONAL_LOCATION,DATEADD(ms, DATEDIFF(ms, '00:00:00', CONVERT(VARCHAR,REPLACE(dbo.FACT_MEASUREMENT.Doc_Time,'24:00:00','23:59:59'),102)), CONVERT(DATETIME, dbo.DIM_TIME_USAGE.DATE)) ASC) AS Rowy, dbo.FACT_MEASUREME...
You can try with the following steps: * define this intermediate result AND the "calendar" table as a chain of the `WITH` statement * perform a `LEFT JOIN` of the "calendar" table and the intermediate result defined on the point above (some DB requires specifying `LEFT OUTER JOIN`) * perform the row-numbering join tec...
You need to `cross join` the result of your query with `calender` table. Something like this ``` WITH t AS (SELECT Row_number() OVER ( ORDER BY Q2.FUNCTIONAL_LOCATION) AS Rowy, Q1.FACT_MEASUREMENT_KEY, CONVERT(VARCHAR(255), Q1.Doc_Time, 102)...
SQL SelfJoin + Left Outer JOIN Calendar
[ "", "sql", "database", "calendar", "" ]
Trying to do a partial string match here but am getting a problem with the LIKE operator. I'm sure its the syntax but I cannot see it ``` SELECT Name FROM Table1 a INNER JOIN Table2 b ON a.Name = b.FullName LIKE '%' + a.Name + '%' ``` I get an error message when I execute this > Msg 156, Level 15, State 1, Line 4 ...
Try this ``` SELECT distinct Name, FullName FROM Table1 a INNER JOIN Table2 b ON (b.FullName LIKE '%' + a.Name + '%' OR a.Name like '%'+b.FullName+'%') ```
I had this exact issue with Postgres. Its a bit messy, but I used textcat to add the wildcard since the above '%'+ didn't play well with my query on Metabase Try this: ``` SELECT distinct Name, FullName FROM Table1 a INNER JOIN Table2 b ON b.FullName LIKE textcat(textcat('%',a.Name),'%') ```
Partial String match SQL - Inner Join
[ "", "sql", "sql-server", "join", "sql-like", "" ]
``` SELECT ItemID, Name FROM tblItem WHERE ItemID IN (4, 38, 39, 37, 16, 8, 15,14) ``` By using given above SQL query I am getting below result set which is in order by ItemID. I want the result set without Order By or with any effect of sorting. ``` 4 Item1 8 Item2 14 Item3 15 Item4 16 Item5 37 Item6 38 It...
To get the items in a specific order you have to sort them that way. Specifying the values in the `in` statement in a specific order won't make the database fetch them in that order. The values in the `in` statement will be processed in some way, like sorted or put in a hash set so that they can be matched to an index ...
If you want the result set as specified by the `in` clause (or anything else), then you need to do an `order by`. One way of doing this is using a `VALUES` clause and `join`: ``` SELECT i.ItemID, i.Name FROM tblItem iJOIN (VALUES(4, 1), (38, 2), (39, 3), (37, 4), (16, 5), (8, 6), (15, 7), (14, 8) ) ids(id, ...
SQL query without Order By
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
Maybe the title was not the best I could use to discribe the issue an example of the table structure I am dealing with is in the image below. I need to write a query to pull all records for "Manufactures" that have more than one record. So the end result I would have LINUX UBUNTU 5.6 and LINUX REDHAT 7.8 Just returnin...
> returning the duplicated MANUFACTURE is easy and I can do that with using grouping `having count(*) > 1` That's a good start. Now use that list of `manufacture`s to select the rest of the data: ``` SELECT * FROM software WHERE manufacture IN ( -- This is your "HAVING COUNT(*) > 1" query inside. -- It drives...
try this: ``` Select * from myTable Where Manufacture In (Select Manufacture from myTable Group By Manufacture Having count(*) > 1) ```
SQL Group by Having > 1
[ "", "sql", "sybase", "having", "" ]
I have a table named `Images` that looks like this: ``` ImageKey RefKey ImageParentKey Sequence -------- ------ -------------- -------- 1234570 111111 1234567 3 1234568 111111 1234567 1 1234569 111111 1234567 2 1234567 111112 1234567 0 1234571 111112 1234571 ...
Here's my approach: ``` SELECT * FROM Images i WHERE /* ImageKey equals its ImageParentKey */ i.ImageKey = i.ImageParentKey AND /* There's a RefKey that doesn't match other images with the same ImageParentKey */ EXISTS ( SELECT * FROM Images i2 WHERE i2.ImageParen...
You can do this with an exclusion join back to the same table: ``` SELECT i1.* FROM Images i1 LEFT JOIN Images i2 ON i2.ImageParentKey = i1.ImageParentKey AND i2.RefKey = i1.RefKey AND i2.Sequence <> i1.Sequence WHERE i1.ImageKey = i1.ImageParentKey AND i2.ImageKey IS NULL ``` Results: ``` 1234567 111112 1...
SQL Dependent on another SQL
[ "", "sql", "" ]
I want to copy 1 row from `Table A` to `Table A2`. Here is my code: ``` Insert into A2 select * from A1 where ID=290 ``` `Id` is a `Primary Key` and both tables have same structure. Obviously the above code failed because it cannot insert the `Primary Key`(And I don't want it to, I want a new `PK` be generated). ...
There is no `select * except some columns`. Your sql must contain the full list of columns except the id for both tables. However, this does not mean you have to manually type them. You can generate the columns list by selecting them from `sys.columns` or from `information_schema.columns`. If you are using SSMS, you...
Well, this might be a little bit overkill but it'll do what you want. This way no matter how big the tables get (columns added/removed) you'll get an exact copy. EDIT: In response to the comment below, and in the interest of full disclosure, the PK MUST be an identity and the columns MUST be in the same order. ``` SE...
How to insert one row from Table A to Table B But not Primay key
[ "", "sql", "sql-server", "t-sql", "" ]
I'm new to SQL and am wondering what is wrong in my syntax or logic here. I have my own table `clients` like ``` id | name | postid | sord | -------------------------------------------------------- 1 Paul Allen 19 1 2 McDermot 8 2 ``` and the `postid` column in that tabl...
MySQL does not support `full outer join`. But you don't need it anyway, if you have a proper foreign key relationship. For instance, if you want all clients, even those without posts: ``` SELECT c.id, c.name, c.postid, c.sord, p.guid FROM clients c LEFT JOIN wp_posts p ON c.postid = p.id ORDER BY c.sord; ``...
If you're using MySQL, there is no `FULL OUTER JOIN`. What you can do instead is a `LEFT OUTER JOIN`, a `UNION` and a `RIGHT OUTER JOIN`. This stack overflow answer has an example: <https://stackoverflow.com/a/10137216/4629105> ``` select * from A as a left outer join B as b on a.col = b.col union select * from A...
Where is the error in my full outer join?
[ "", "mysql", "sql", "" ]
I have a table similar to the one shown. It contains a list of user ids, the hour value for each hour of the day and an Avail flag to determine if that user is available on that hour. I need to list all User ids which are available for a number of consecutive hours defined as @n ``` ##################### # UID # Avai...
If you're using SQL Server 2012+ you could using a windowed SUM, but you have to specify the number of rows in the window frame in advance as it won't accept variables so it's not that flexible: ``` ;with cte as ( select distinct UID, SUM(avail) over (partition by uid orde...
Didn't have time to polish this ... but this is one option. * First CTE (c) creates the new column Id * Second CTE (mx) gets the max row number since you cannot use aggregates in recursive CTEs * Final CTE (rc) is where the meat is. ``` ;WITH c AS ( SELECT ROW_NUMBER() OVER (ORDER BY [UID],[Hour]) Id, ...
SQL Find consecutive numbers in groups
[ "", "sql", "sql-server", "" ]
I am doing the following to select nodes from an XML string, the first part is just to show you what I'm selecting from. The issue is I want to do this for various different XML columns and I'd like to not have to specify the node name for each column in my select, is there a way to select all nodes as columns automat...
I hope, this is what you are waiting for :) ``` DECLARE @MyXML XML SET @MyXML = (SELECT CAST ( '<AllowAdd>N</AllowAdd> <Allowed>NUMSEG</Allowed> <AllSegmentsEqualValue>N</AllSegmentsEqualValue> <ClusterLevelSA>Y</ClusterLevelSA> <ClusterLevelPremium>Y</ClusterLevelP...
Given your input XML, you can try to use this: ``` SELECT ColName = XC.value('local-name(.)', 'varchar(100)'), ColValue = xc.value('(.)[1]', 'varchar(100)') FROM @MyXML.nodes('/*') AS XT(XC) ``` This will output each XML element found under the root - its name and value - as a list: [![enter image desc...
Returning all child nodes as columns from XML in Sql Server
[ "", "sql", "sql-server", "xml", "sqlxml", "" ]
I have a list of customer\_ids, the date on which some information was changed, and the corresponding changes. I would like to number each change, by order of date, on each customer. So for example; I have something that looks like the following ``` Cust_id Date information --------------...
As Indian said, Try this : ``` select cust_id, Row_number() over(partition by cust_id order by date) change_number, Date, information from tablename; ```
If you want to order over a change number like that you need to use an inner select like this: ``` SELECT * FROM ( SELECT * , ROW_NUMBER() OVER (PARTITION BY Cust_id ORDER BY [Date]) As Change_Number FROM yourTable) t ORDER BY Cust_id, Change_Number; ```
SQL How to order each entry by date
[ "", "sql", "sql-server", "date", "label", "rank", "" ]
Is it possibile to select all childs of a parent without recursive system as WITH or WHILE? The structure is: ``` Father Child NULL 1 1 2 1 3 2 4 3 5 4 6 6 7 ``` I want the "childs" (all genealogy, childs of childs, etc. etc.) of 2, so I want: 4, 6, 7
Yes. Every recursive function has a non-recursive solution: [Can every recursion be converted into iteration?](https://stackoverflow.com/questions/931762/can-every-recursion-be-converted-into-iteration) Some other resources that might be helpful: <http://www.slideshare.net/rs_rs123/removal-of-recursion> <http://www...
If you know precisely what depth you want to go to, then sure, you don't have to use recursion. For example, to find the **first-level** descendants of a given parent, just do: ``` select Child from MyTable where Father = 2 ``` Even if you want multiple levels (grandchildren, grandparents, etc.), as long as you **kno...
Select all genealogy of a father in SQL without WITH or WHILE
[ "", "sql", "recursion", "genealogy", "" ]
I want To Select stockDate in ASC Order My `Table` Structure is.:- [![enter image description here](https://i.stack.imgur.com/6dsfG.png)](https://i.stack.imgur.com/6dsfG.png)
You have saved the dates as varchar and they are evil, you should use mysql native date data types. For this you first need to convert the varchar dates to real date using `str_to_date` function while doing the sorting, here how it works ``` mysql> select str_to_date('31/07/2015','%d/%m/%Y') as d ; +------------+ | d...
``` SELECT * from inventory_details ORDER BY str_to_date(stockDate,'%d/%m/%Y') desc ```
How can Select date(dd/mm/yyyy) in ascending order in sql
[ "", "mysql", "sql", "database", "date", "" ]
I need a select which brings two lines, one with the number of people with the " number of hits " > 0 and the other line with the number of people with the " number of hits " = 0 ``` SELECT u.name as 'Usuário',u.full_name as 'Nome do Usuário',count(l.referer) as 'Número de Acessos' FROM mmp_user u LEFT JOIN M...
You could wrap this query with another query and apply a `case` expression to the count: ``` SELECT access_code, COUNT(*) FROM (SELECT u.name, u.full_name, CASE WHEN COUNT(l.referer) > 0 THEN 'access' ELSE 'no access' E...
``` SELECT u.name Usuário, u.full_name [Nome do Usuário], count(l.referer) [Número de Acessos], Sum(case when NumberOfHits = 0 then 1 else 0 end) ZeroHitsCount, Sum(case when NumberOfHits > 0 then 1 else 0 end) HasSomeHitsCount FROM mmp_user u LEFT JOIN MMP_MMPUBLISH_LOG l on u.id=l.user_id ...
SQL count number of users hava a value > 1
[ "", "sql", "select", "" ]
I have two tables, table1 and table2. Each with the same columns: ``` key, c1, c2, c3 ``` I want to check to see if these tables are equal to eachother (they have the same rows). So far I have these two queries (<> = not equal in HIVE): ``` select count(*) from table1 t1 left outer join table2 t2 on t1.key=t2.key w...
The first one excludes rows where t1.c1, t1.c2, t1.c3, t2.c1, t2.c2, or t2.c3 is null. That means that you effectively doing an inner join. The second one will find rows that exist in t1 but not in t2. To also find rows that exist in t2 but not in t1 you can do a full outer join. The following SQL assumes that all co...
If you want to check for duplicates *and* the tables have exactly the same structure *and* the tables do not have duplicates within them, then you can do: ``` select t.key, t.c1, t.c2, t.c3, count(*) as cnt from ((select t1.*, 1 as which from table1 t1) union all (select t2.*, 2 as which from table2 t2) ) t...
Comparing two tables for equality in HIVE
[ "", "sql", "join", "hive", "left-join", "hiveql", "" ]
This post is in continuatation of a problem of another post [sql select min or max based on condition](https://stackoverflow.com/questions/31815050/sql-select-min-or-max-based-on-condition/31816877#31816877) I'm trying to get a row based on various conditions. **Scenario 1 -** get highest row if no hours exist agains...
Based on new data and last comment on the answer by asker, here's the updated query and fiddle :<http://sqlfiddle.com/#!6/87e2f/2> > hey i found an example that doesn't work... orderID '12M0003381'... > i've added data to your fiddle. I would expect to see operation 70 as > that's the last operation with a setup or pr...
This isn't the prettiest thing I have ever written but it works. I also tested it against the other fiddle with additional data. Modified to meet new requirement. ``` SELECT * FROM ( SELECT A.ProdID, MIN(A.OprNum) AS 'OprNum' FROM #ProdRoute AS A ...
sql select min or max based on condition part 2
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I'm trying to figure out a way, using SQL, to query for values that go out to, say, 5 or more decimal places. In other words, I want to see only results that have 5+ decimal places (e.g. 45.324754) - the numbers before the decimal are irrelevant, however, I still need to see the full number. Is this possible? Any help ...
Assuming your DBMS supports `FLOOR` and your datatype conversion model supports this multiplication, you can do this: ``` SELECT * FROM Table WHERE FLOOR(Num*100000)!=Num*100000 ``` This has the advantage of not requiring a conversion to a string datatype.
On SQL Server, you can specify: ``` SELECT * FROM Table WHERE Value <> ROUND(Value,4,1); ``` For an ANSI method, you can use: ``` SELECT * FROM Table WHERE Value <> CAST(Value*100000.0 AS INT) / 100000.0; ``` Although this method might cause an overflow if you're working with large numbers.
How to find values with certain number of decimal places using SQL?
[ "", "sql", "" ]
in a database table I have made a date attribute but I have set it's type to varchar and not Date. My question is, will I still be able to compare such dates in a SQL Query? Dates in my DB are stored in this format: > dd/mm/yyyy hh:mm:ss I have to do a SQL Query in PHP that looks something like this: ``` SELECT * F...
You'll need to convert/cast to compare: ``` SELECT * FROM DBtable WHERE DBname='$name' AND CAST(date AS DATETIME) >='2015-01-01' AND CAST(date AS DATETIME)<='2015-01-09' ; ``` Much better to store values as the appropriate data types to avoid this inefficiency. You could also use `DATE` instead of `DATETIME` if...
You can cast or convert a `varchar` to a `date` or `datetime` before you do any comparisons. But you'd have to do it *every single time* you compare the date to something. That's because the following comparisons are all true if you compare them as `varchar`: ``` '2/1/2015' > '1/5/2016' '25/1/2015' > '15/2/2015' '11/...
SQL Comparing Dates
[ "", "mysql", "sql", "date", "compare", "" ]
I am new to SQL and I need to find `count` of users every 7 days. I have a table with users for every single day starting from April 2015 up until now: ``` ... 2015-05-16 00:00 2015-05-16 00:00 2015-05-17 00:00 2015-05-17 00:00 2015-05-17 00:00 2015-05-17 00:00 2015-05-17 00:00 2015-05-18 00:00 2015-05-18 00:00 ... ``...
You should try following, ``` Select sum(Week1) + sum(Week2) + sum(Week3) + sum(Week4) + sum(Week5) as Total, sum(Week1) as Week1, sum(Week2) as Week2, sum(Week3) as Week3, sum(Week4) as Week4, sum(Week5) as Week5 From ( select case when week = 1 then 1 else 0 end as Week1, case when week = 2 t...
This is my test table: ``` user_id act_date 1 01/04/2015 2 01/04/2015 3 04/04/2015 4 05/04/2015 .. ``` This is my query: ``` select week_offset, count(*) nb from ( select trunc((act_date-to_date('01042015','DDMMYYYY'))/7) as week_offset from test_date) group by week_offset order by 1 ``` and this is the ou...
SQL count number of users every 7 days
[ "", "sql", "oracle", "" ]
I need to make a query that moves values of only one column one row up ↑ at a time: ``` +------------+----------------+ | anotherCOL | values_to_loop | +------------+----------------+ | 1 | 1 | | 2 | 2 | | 3 | 3 | | ...
Here's how you can do it within a single UPDATE query: ``` UPDATE tbl a INNER JOIN ( SELECT values_to_loop FROM (SELECT * FROM tbl) c ORDER BY anotherCOL LIMIT 1 ) b ON 1 = 1 SET a.values_to_loop = IFNULL( (SELECT values_to_loop FROM (SELECT * FROM tbl) c WHERE c.anotherC...
I`ve created a sample table and added both a select to get the looped values and update to loop the values in the table. Also, using a @start\_value variable to know the "1" which might be other. Try this: ``` CREATE TEMPORARY TABLE IF NOT EXISTS temp_table (other_col INT, loop_col int); INSERT INTO temp_table (ot...
Query for looping values in column
[ "", "mysql", "sql", "database", "" ]
Bit confused if we can perform order by on more than two columns. Here is the result:- ``` Select * from orderbytest order by FName desc, LName desc, YearOfBirth desc ``` Resulting output: ``` FName LName YearOfBirth ------------------------------------ Thomas More 1478 Thomas Jefferson...
Short answer - yes. When applying multiple `order by` expressions the results are sorted by the first one. When multiple rows have the same value in the first order by expression, they are sorted internally by the second one. When multiple rows have the same value in the first and second order by expressions they are ...
Yes you can perform however you like Just like Grouping. here; ``` Select * from orderbytest order by FName ,LName asc,YearOfBirth desc ``` Not that, when you do not write any keyword after a field the result will list in the default order.
Can we perform order by on more than 2 columns in SQL Server
[ "", "sql", "sql-server", "database", "select", "sql-order-by", "" ]