Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I would like to exclude a row in the query result if all 3 sum columns are zero.
```
Select Name
,sum(case when cast(Date as date) <= Convert(datetime, '2014-05-01') then 1 else 0 end) as 'First'
,sum(case when cast(Date as date) <= Convert(datetime, '2014-04-01') then 1 else 0 end) as 'Second'
,sum(case when cast(Dat... | this may work for you :
```
select * from
(
.......your query......
) as t
where First <> 0 or Second <> 0 or Third <> 0
``` | You can repeat the expressions in the `having` clause:
```
having sum(case when cast(Date as date) <= Convert(datetime, '2014-05-01') then 1 else 0 end) > 0 or
sum(case when cast(Date as date) <= Convert(datetime, '2014-04-01') then 1 else 0 end) > 0 or
sum(case when cast(Date as date) <= Convert(datetim... | Exclude multiple sum rows when all zero | [
"",
"sql",
"sql-server",
"database",
""
] |
I have a query
```
Select Id,DeviceId,TankCount,Tank1_Level,Tank2_Level,ReadTime from Table
Id TankCount DeviceId Tank1_Level Tank2_Level ReadTime
1 1 123 20 50 2014-11-07 14:39:33.277
2 2 456 52 78 2014-11-07 14:39:3... | ```
SELECT Id,
DeviceId,
TankCount,
Tank1_Level,
CASE WHEN Tank2_Level = '50' and TankCount != '2'
THEN NULL
ELSE Tank2_Level
END AS [Tank2_Level],
ReadTime
FROM table
``` | Is `Tank2_Level` a number or a string? Let me assume it is a number:
```
select <other columns>,
(case when Tank2_Level = 50
then 'null or empty'
else cast(Tank2_Level as varchar(255))
end) as Tank2_Level
from . . .;
``` | How to use Case in SQL? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
This is a simple query using with CTE but is not behaving the way I want to.
The idea is to filter those records wit precio\_90 = null and then update the field precio\_90 with the price from mytable2 where codigo=codigo on a specific date.
At present I get all records updated without the actual filter.
```
DECLARE @... | Well, first, you don't use the CTE anywhere in your update, which is why your results aren't filtered right. Second, you don't need a CTE for this... you can filter `precio_90 is null` right in the update.
```
UPDATE t1
SET t1.precio_90= t2.[precio]
from @mytable1 as t1
INNER JOIN @mytable2 as t2 ON t1.codigo = t2.co... | From your sample `@mytable1` INSERTS, all the records inserted with codigo = 'stock1'. Therefore, on your `UPDATE` statement, you update all the records from @mytable1 to stock1 level from @mytable2.
For example, if your sample table 1 had records with stock2 like this:
```
INSERT INTO @mytable1(codigo, precio_90)
VA... | CTE with update | [
"",
"sql",
"sql-server",
""
] |
In my stored procedure, I want to export select result to a `.CSV` file. I need to write a stored procedure which selects some data from different tables and saves it to a `.CSV` file.
Selecting part is ready
```
SELECT DISTINCT
PER.NREGNUMBER_PERNUM AS [Registration Number],
PE... | The task was I had to export from database some data to **.CSV** at specified time. In the begining we wanted to use windows scheduler for running stp. The STP had to be able to export data. But I couldn't find a way. Instead the thing what we did was creating simple STP which brings only data . And we created **batch*... | i have build a procedure to help you all
```
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- example exec Sys_Database_exportToCsv 'select MyEmail from
QPCRM.dbo.Myemails','D:\test\exported.csv'
create PROCEDURE Sys_Database_exportToCsv
(
@ViewName nvarchar(50),
@exportFile nvarchar(50)
)
AS
BEGIN
SET NO... | SQL Server stored procedure to export Select Result to CSV | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
"export-to-excel",
""
] |
I am trying to get a list of values from the same column in a table by running two queries.
This is what the table looks like:
```
******************************************
Key | Short_text | UID | Boolean_value
******************************************
Name | John | 23 | null
******************************... | I am unsure what you are trying to accomplish but basing on your code I think this is what you want
```
SELECT SHORT_TEXT_VALUE
FROM Table
WHERE KEY='Name'
and UID in(SELECT UID
FROM Table
WHERE KEY = 'Male'
AND BOOLEAN_VALUE = 1)
```
But on a more important note. You might want to think about your ... | You can join your table with itself:
```
SELECT
t1.UID,
t1.Short_text
FROM
tablename t1 INNER JOIN tablename t2
ON t1.UID=t2.UID
WHERE
t1.Key='Name' AND t2.Key='Male' AND t2.Boolean_value=TRUE
```
or this with EXISTS:
```
SELECT
t1.UID,
t1.Short_text
FROM
tablename t1
WHERE
t1.Key='Name' AND
EXIS... | SQL get multiple values (from the same column) from same table using multiple queries | [
"",
"mysql",
"sql",
""
] |
I got a table with the following Columns: ID, IsRunningTotal and Amount (like in the CTE of the SQL sample).
The Amount represents a Value or a RunningTotal identified by the IsRunningTotal Flag.
If You wonder about the UseCase just imagine that the ID represents the month of the Year (e.g. ID:1 = Jan 2014), so the Am... | The following utilizes CTE to calculate the true breakdowns and running totals.
```
DECLARE @Data TABLE (ID INT, IsRunTot BIT, Amount INT)
INSERT @Data VALUES (
1,0,1000),(
2,0,1000),(
3,1,3000),(
4,1,4000),(
5,0,1000),(
6,0,1000),(
7,1,7000),(
8,1,8000)
; WITH CTE AS (
SELECT TOP 1
ID,
IsRunTot,
... | This solution subtracts the previous running total and all values in between.
```
;WITH MySet (ID, IsRunTot, Amount)
AS
(
SELECT 1, 0, 1000
UNION SELECT 2, 0, 1000
UNION SELECT 3, 1, 3000
UNION SELECT 4, 1, 4000
UNION SELECT 5, 0, 1000
UNION SELECT 6, 0, 1000
UNION SELECT 7, 1, 70... | SQL Server: break down Running totals from mixed Set (Running Totals and Values) | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"cumulative-sum",
""
] |
How can I get the highlighted rows from the table below in SQL? (Distinct rows based on User name with the highest Version are highlighted)

In case you need plain text table:
```
+----+-----------+---+
| 1 | John | 1 |
+----+-----------+---+
... | this might help you :
```
select id, user, version
from
(
select id, user, version, row_number() over (partition by user order by version desc) rownum
from yourtable
) as t
where t.rownum = 1
```
[sql fiddle](http://sqlfiddle.com/#!3/1a060/6) | ```
SELECT USER, max(VERSION) VERSION
FROM TABLE GROUP BY USER;
```
If you need an ID then
```
SELECT ID, USER, VERSION FROM (
SELECT ID, USER, VERSION,
RANK() OVER(PARTITION BY USER ORDER BY VERSION DESC) RNK
FROM TABLE
) WHERE RNK = 1;
```
if you have
```
| 2 | Brad | 5 |
+----+--------... | Getting distinct values with the highest value in a specific column | [
"",
"sql",
"oracle",
"select",
"distinct",
""
] |
I have a table testtable having fields
```
Id Name Status
1 John active
2 adam active
3 cristy incative
4 benjamin inactive
5 mathew active
6 thomas inactive
7 james active
```
I want a query that should dispaly the reuslt like
```
Id Name Statu... | This query sorts on interleaved active/inactive state:
```
SELECT [id],
[name],
[status]
FROM (
(
SELECT
Row_number() OVER(ORDER BY id) AS RowNo,
0 AS sorter,
[id],
[name],
[status]
... | Finally i got the answer
```
SET @rank=0;
SET @rank1=0;
SELECT @rank:=@rank+1 AS rank,id,name,status FROM `testtablejohn` where status='E'
UNION
SELECT @rank1:=@rank1+1 AS rank,id,name,status FROM `testtablejohn` where status='D'
order by rank
``` | SQL query interleaving two different statuses | [
"",
"sql",
""
] |
Please consider a table of vendors having two columns: `VendorName` and `PayableAmount`
I'm looking for a query which returns top ten vendors sorted by `PayableAmount` descending and sum of other payable amounts as "other" in 11th row.
Obviously, `sum of PayableAmount` from `Vendors` table should be equal to `sum of ... | This would perform the query you're looking for. Firstly extracting those in the top 10, then `UNION` ing that result with the higher ranked vendors, but calling those `'Other'`
```
WITH rank AS (SELECT
VendorName,
PayableAmount,
ROW_NUMBER() OVER (ORDER BY PayableAmount DESC) AS rn
FROM vendors)
SELECT VendorName,
r... | Technically, it's possible to do in one query:
```
declare @t table (
Name varchar(50) primary key,
Amount money not null
);
-- Dummy data
insert into @t (Name, Amount)
select top (20) sq.*
from (
select name, max(number) as [Amount]
from master.dbo.spt_values
where number between 100 and 100000
and name ... | Sorting top ten vendors and showing remained vendors as "other" | [
"",
"sql",
"sql-server",
""
] |
I'm trying to query the table CANCELLATION\_DEFINITION, and count the amount of rows that have an ACTION\_TYPE value that isn't "-". Unfortunately, the query is giving me inaccurate results. For example, it returns 3 for this table when there are 6 rows in the table that have an ACTION\_TYPE value other than "-". Code ... | Try:
```
SELECT COUNT(*)
FROM (
SELECT ACTION_TYPE
FROM CANCELLATION_DEFINITION WHERE ACTION_TYPE != '-'
)AS distinctified
```
Hope that helps | When you perform a select distinct, it only returns distinct (ie different) values. So if you have action\_type ["INSERT", "UPDATE", "UPDATE", "DELETE"] it will only give you 3 results because it merges UPDATE and UPDATE.
What you really want is
```
SELECT COUNT(ACTION_TYPE)
FROM CANCELLATION_DEFINITION
WHERE ACTIO... | Select Count Query Giving Inaccurate Results | [
"",
"sql",
""
] |
I have 2 tables with foreign key constraint:
```
Table A:
[id] int identity(1, 1) PK,
[b_id] INT
```
and
```
Table B:
[id] int identity(1, 1) PK
```
where [b\_id] refers to [id] column of Table B.
The task is:
On each insert into table A, and new record into table B and update [b\_id].
Sql Server 2008 r2 is used.... | Having misread this the first time, I am posting a totally different answer.
First if table B is the parent table, you insert into it first. Then you grab the id value and insert into table A.
It is best to do this is one transaction. Depending on what the other fields are, you can populate table A with a trigger fro... | Without removing identity specification you can use the following option:
**SET IDENTITY\_INSERT B ON**
Try this:
```
CREATE TRIGGER trgAfterInsert ON [dbo].[A]
FOR INSERT
AS
IF @@ROWCOUNT = 0 RETURN;
SET NOCOUNT ON;
SET IDENTITY_INSERT B ON
DECLARE @B_Id INT
SELECT @B_Id = ISNULL(MAX(Id), 0) FROM B;
WITH RES... | For each inserted row create row in other table with foreign key constrain | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I m doing an export using SQL\*Plus using the following code:
```
Set echo off
Set verify off
Set feedback off
Set heading off
Set termout on
Set pages 50000
Set linesize 1000
Set newpage none
Set colsep ","
spool Z:\ff\ss.csv
Select Client_ID, Cust_ID from cust;
spool off;
exit;
```
I get the correct output, but i... | `echo off` only works to remove the SQL> prompts when run from a file. Put your commands in a file called export\_client\_data.sql and run them using the @ command:
```
SQL>@export_client_data.sql
```
SQL\*Plus, being a reporting tool, will format output to the column width as defined in the table. Using TRIM() doesn... | Try this options :
SET TRIMSPOOL ON otherwise every line in the spoolfile is filled up with blanks until the linesize is reached.
SET TRIMOUT ON otherwise every line in the output is filled up with blanks until the linesize is reached.
SET WRAP OFF Truncates the line if its is longer then LINESIZE. This should not ha... | Remove leading spaces and the SQL> tags when spooling | [
"",
"sql",
"oracle",
"formatting",
"sqlplus",
"spool",
""
] |
I have a view where I get some values and diffs from my database. I use this code:
```
Select DATEDIFF(minute, 0, DATEADD(day, 0, t1.HorasEfe)) as Soma, t1.IDDiligencia
from DiligenciaSub t1
group by t1.IDDiligencia,t1.HorasEfe
order by t1.HorasEfe
```
I get this as output:
)) as Soma, t1.IDDiligencia
from DiligenciaSub t1
group by t1.IDDiligencia
``` | remove sum and group by from your original query then
insert your result into temp table #t
and then use this query
```
select sum(soma) as sum_soma,IDDiligencia as idd
from #t
group by IDDiligencia
```
you will get the following result
 | Aggregation and Sum with one Group By | [
"",
"sql",
"sql-server",
"view",
""
] |
If we have a table like:
```
col1 | col2
-----------
A | 1
B | 2
A | 1
C | 16
B | 3
```
How it can be determined if the all rows for given value in col1 are the same?
For example, here whe have only '1's for A, but for B we have '2' and '3'.
Something like:
```
A | true
B | false
C | true
``` | ```
select col1, case when count(distinct col2) = 1
then 'true'
else 'false'
end as same_col2_results
from your_table
group by col1
``` | I have a preference for using `min()` and `max()` for this purpose, rather than `count(distinct)`:
```
select col1,
(case when min(col2) = max(col2) then 'true' else 'false' end) as IsCol2Same
from table t
group by col1;
```
Then comes the issue of `NULL` values. If you want to ignore them (so a column could a... | SQL Compare grouped values | [
"",
"sql",
"oracle",
""
] |
I have a SQL database that I am querying as part of a project - I only have read access to it.
There is a column called `ResultStatus` - possible values are "Passed" and "Failed". However, there were some typos by the original data inputter so some of them say "Fialed" as well.
I want to count the number of "Failed" e... | You can correct the spelling yourself
```
SELECT Case When ResultStatus = 'Fialed' then 'Failed' Else ResultStatus End AS ResultStatus, Count(*)
FROM [DB_018].[dbo].[ProjectData]
GROUP BY Case When ResultStatus = 'Fialed' then 'Failed' Else ResultStatus End
```
What this is doing is replacing the incorrect spelling ... | You need to get a distinct list of ResultStatus and add them all to the case statement below. I prefer this method to Raj's as you don't need to use a CTE (not available in all version of SQL Server) or adjusting the group by.
```
SELECT
ResultStatus,count(*) [Count]
FROM(
SELECT
CASE
WHEN... | How do you count misspelled fields using a SQL query? | [
"",
"sql",
"sql-server",
""
] |
I have table with following structure:
TestTable (ID INT, LoanID INT, Amount INT)
```
ID LoanID Amount
1 1 20
2 1 30
3 1 15
4 2 40
5 2 20
6 3 50
```
I want to calculate LoanAmounts with this scenario
```
ID LoanID Amount Sum
1 1 20 20
2 1 ... | You can use a correlated sub-query to get the [running-totals](http://en.wikipedia.org/wiki/Running_total):
```
SELECT t.ID, t.LoanID, t.Amount,
[Sum] = (SELECT SUM(AMOUNT)
FROM TestTable t2
WHERE t.LoanID=t2.LoanID
AND t2.ID <= t.ID)
FROM TestTable t
```
`Demo` | Unfortunately SQL Server 2008 doesn't have a clean function to do a cumulative sum, so you need to add up all of the "previous" rows with the same `LoadID`:
```
SELECT
ID,
LoanID,
Amount,
(SELECT SUM(Amount) FROM TestTable t2 WHERE t2.LoanID = t.LoanID AND t2.ID <= t.ID) Sum
FROM TestTable t
``` | Using Sum function | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
i want to get column value that has some other value and null but don't want value that equal to some point.
**Example**
```
ID|VID |IC |
1 |v001 |123 |
2 |v001 |null|
3 |v003 |456 |
4 |v004 |null|
```
so i want to get ID which IC is not equal to 123. but i only get ID 3 but ID 2 and 4 will not shown out in sql. i... | You want `OR`, not `AND`:
```
select * from table where IC != 123 OR IC IS NULL
```
Any comparison with `NULL` produces the [third logic value](http://en.wikipedia.org/wiki/Three-valued_logic), `UNKNOWN`, and any negation of `UNKNOWN` produces `UNKNOWN`, so you have to treat the `NULL`s separately - but, of course, f... | ```
SELECT * FROM table WHERE IC != '123' OR IC IS NULL
``` | Sql select where clause operation <> | [
"",
"sql",
"sql-server",
""
] |
I have a dataset with multiple ids. For every id there are multiple entries. Like this:
```
--------------
| ID | Value |
--------------
| 1 | 3 |
| 1 | 4 |
| 1 | 2 |
| 2 | 1 |
| 2 | 2 |
| 3 | 3 |
| 3 | 5 |
--------------
```
Is there a SQL DELETE query to delete (random) rows for ... | I tried the given answers with HSQLDB but it refused to execute those queries for different reasons (join is not allowed in delete query, ignore statement is not allowed in alter query). Thanks to Andrew I came up with this solution (which is a little bit more circumstantial, but allows it to delete random rows):
Add ... | Try this:
```
alter ignore table a add unique(id);
```
Here `a` is the table name | Delete rows except for one for every id | [
"",
"sql",
"hsqldb",
"delete-row",
""
] |
```
Declare @xml xml,
@y int
set @xml= '<ContactUpdates>
<Contact VendorID="4"><LastName>McCrystle</LastName>
<FirstName>Timothy</FirstName>
</Contact>
<Contact VendorID="10">
<LastName>Flynn</LastName>
<FirstName>Erin</FirstName>
</Contact></ContactUpdates>'
Exec s... | You have a mix of both attribute-centric and element centric-projections. The reason why `VendorId` is mapped, but not the two elements, is because attribute centric is the default. In a mixed / complex hierarchy scenario, as [per here](http://msdn.microsoft.com/en-us/library/ms186918.aspx), you will need to explicitly... | Use the proper, native XQuery support in SQL Server :
```
SELECT
VendorID = xc.value('@VendorID', 'int'),
FirstName = xc.value('(FirstName)[1]', 'varchar(50)'),
LastName = xc.value('(LastName)[1]', 'varchar(50)')
FROM
@xml.nodes('/ContactUpdates/Contact') AS XT(XC)
```
Easily gives you this nice outp... | OpenXml returns null for elements inside XML | [
"",
"sql",
"sql-server",
"sql-server-2008",
"openxml",
""
] |
I am new to sql, I am in trouble with date formats I know I can use cast or convert function but I was looking to dateformat (we use format dd/mm/yy). I looks quite interesting function and very easy but there is a problem.
IF I run this dataview
```
SELECT hotel, id, codicecliente, prodotto, CAST(REPLACE(numeros,... | The error when creating the view with `SET DATEFORMAT dmy` is due to a view being an encapsulation of a single query, not multiple commands. If you need multiple commands, then you would have to use a Multistatement Table-Valued Function. But using a TVF is not necessary here.
Use [TRY\_CONVERT](http://msdn.microsoft.... | It looks like you are probably Italian?? If so, you should change your default language to Italian on the server. This will also by default change your DATEFORMAT to accept European-style dates. I am assuming all your char-formatted dates will be stored in that format? This will show you how:
[How to change default la... | DATEFORMAT FUNCTION IN SQL | [
"",
"sql",
"sql-server",
""
] |
I have some dates that I would like to filter with SQL.
I want to be able to pass a flag to say keep all the FIRST Mondays of the months from X date to Y Date.
So essentially, I want to pass in a date and be able to tell if it's the first, second, third, fourth or last Monday (for example) of a given month.
I have a... | you can do this
```
alter function IsDateFirstOfMonth(@date as datetime)
returns int
as
begin
declare @first datetime,
@last datetime,
@temp datetime,
@appearance int
declare @table table(Id int identity(1,1),
StartDate datetime,
... | For this kind of problem it's usually much easier to implement a table with the required date information and join on tthat table, and filter using it. I.e. create a table with this info:
```
CREATE TABLE Dates(
Date DATE PRIMARY KEY CLUSTERED,
PositionInMoth TINYINT,
LastInMonth BIT)
```
Then fill up this tabl... | SQL - Check if a date is the first occurrence of that day in its month | [
"",
"sql",
"sql-server",
"t-sql",
"datetime",
""
] |
I have two tables in an Oracle database:
The first table has a date range and I need help in writing a SQL query to find all the records from second table as in the result table below. The first four digits in the date is year and last two are session (10-Fall; 20-Spring; 30-Summer).
1) Table1
```
seqnum | min_dat... | To do this as simply as possible:
```
select t2.seqnum, t2.b_date, coalesce(t1.c_id, t3.max_id) as c_id
from table2 t2
left outer join table1 t1
on t2.b_date between t1.min_date and t1.max_date
cross join (select max(c_id) as max_id from table1) t3
order by t1.c_id, t2.b_date
```
[SQLFiddle here](http://s... | **Fiddle:** <http://sqlfiddle.com/#!4/45c72/10/0>
```
select t2.seqnum,
t2.b_date,
case when t2.b_date < min_rg then x.c_id
when t2.b_date > max_rg then y.c_id
else t1.c_id
end as c_id
from (select min(min_date) as min_rg, max(max_date) as max_rg from table1) z... | Oracle Join tables with range of dates in first table and dates in second table | [
"",
"sql",
"database",
"oracle",
"join",
""
] |
I have two tables: `USERS` and `USER_TOKENS`
`USERS` is structured as follows:
```
id (INT)
name (VARCHAR)
pass (VARCHAR)
birthdate (DATETIME)
...
etc
```
`USER_TOKENS` is structured as follows:
```
user_id (INT)
key (VARCHAR)
value (VARCHAR)
```
Essentially `USERS` contains basic data, whereas `USER_TOKENS... | If you need really all matching users and their respective tokens as one resultset, you can try this:
```
SELECT u.id, ut.key, ut.value -- and list also other required fields
FROM Users u
LEFT JOIN User_tokens ut ON u.id = ut.user_id
WHERE u.name = 'bob'
```
Try not to use `SELECT *` because you get duplicate fiel... | ```
SELECT u.*, t.* FROM users AS u, users_tokens AS t
WHERE u.name = 'bob' AND t.user_id = u.id;
``` | SQL query: combining data from two tables | [
"",
"mysql",
"sql",
""
] |
I'm trying to pull two things from my database: entries where one attribute is TRUE and the entries where the attribute is FALSE. I then want to divide the first result by the second result to get a percentage of entries where the attribute is TRUE.
```
SELECT product, COUNT(entries) FROM myTable
WHERE has_bug = 1
AN... | You can (ab)use MySQL's automatic type-conversion logic:
```
SELECT product, (SUM(entries = 0) / SUM(entries = 1)) AS ratio
FROM myTable
WHERE date > '2014-07-01'
GROUP BY product
```
The boolean true/false of the `entries = X` comparisons will get converted to integer `0` or `1` by MySQL, and summed up, essentially... | Use conditional aggregation. Actually, the following will do what you want, assuming `has_bug` only takes on the values of `0` and `1`:
```
select product, avg(has_bug)
from mytable
where date > '2014-07-01'
group by product;
```
A more explicit match to your query is:
```
select product, sum(has_bug = 1) / count(*... | SQL: Selecting two different things and doing calculations on the results in one query | [
"",
"mysql",
"sql",
""
] |
Let's suppose I created this table:
```
CREATE TABLE T (
NAME VARCHAR(10),
A INT NOT NULL,
B INT NOT NULL
)
```
I want to create a view that has two attributes, T.Name and a char that is `'Y' if A >= B or 'N' otherwise`.
How can I build this second attribute? Thank you | Just use a `case` statement:
```
create view v as
select t.name, (case when t.a >= t.b then 'Y' else 'N' end) as attribute
from table t;
``` | ```
CREATE VIEW YourViewName
AS
SELECT name , (CASE WHEN A >= B THEN 'Y' ELSE 'N' END) as your_name
FROM T
``` | SQL - Insert conditioned values in a View | [
"",
"sql",
"create-view",
""
] |
Suppose I fetch a set of rows from several tables. I want to know the total sum of values in column `x` in these rows, as well as sum of only those values in `x` where the row satisfies some additional condition.
For example, let's say I fetched:
```
X Y
1 0
10 0
20 100
35 100
```
I want to have a sum of all... | You could use a `case` expression inside the `sum`:
```
SELECT SUM (x) all_x,
SUM (CASE WHEN x > y THEN x ELSE 0 END) some_x
FROM my_table
``` | You're looking for the `CASE` operator :
```
SELECT sum(X) all_x,
sum(CASE WHEN X>Y THEN X ELSE 0 END) some_x
FROM Table1
```
In this case (no pun) you would get 11 for `some_x`
You can use whatever condition you want instead of `X>Y` after the `WHEN`, and select whatever value instead of `X`.
[SQL fiddle](... | SQL: Computing sum of all values *and* a sum of only values matching condition | [
"",
"sql",
"oracle",
"select",
"sum",
"aggregate-functions",
""
] |
Consider this query:
```
select
count(p.id),
count(s.id),
sum(s.price)
from
(select * from orders where <condition>) as s,
(select * from products where <condition>) as p
where
s.id = p.order;
```
There are, for example, 200 records in products and 100 in orders (one order can contain one or mor... | If the `products` table is really more of an "order lines" table, then the query would make sense. You can do what you want by in several ways. Here I'm going to suggest conditional aggregation:
```
select count(distinct p.id), count(distinct s.id),
sum(case when seqnum = 1 then s.price end)
from (select o.* fr... | You are not interested in single product records, but only in their number. So join the aggregate (one record per order) instead of the single rows:
```
select
count(*) as count_orders,
sum(p.cnt) as count_products,
sum(s.price)
from orders as s
join
(
select order, count(*) as cnt
from products
where <... | Aggregate after join without duplicates | [
"",
"sql",
"postgresql",
"select",
"join",
""
] |
I am having what seems to be a rather simplistic issue, but its hampering what I need to do.
Essentially, I want to present all records (including NULLS) when I evaluate my `CASE` statement in my SQL. Right now its filtering out the NULL values
Table
## fname | lname
steve | smith
NULL | jones
Query:
```
SELECT
... | OK I could not find a SQL solution to this but in SSRS I found a way of getting around it, since this is a report that goes through SSRS.
On the front end table tablix I applied a filter with conditions.
```
=iif(Parameters!RPfname.Value="All", Parameters!RPfname.Value,Fields!fName.Value) = =Parameters!RPname.Value
`... | Use an `OR` as nothing is equal to `NULL`
```
WHERE
@param = 'All'
OR
fname = @param
``` | SQL Server / SSRS 2005 CASE evaluation of Parameter and NULL | [
"",
"sql",
"sql-server",
"null",
"case",
"reportingservices-2005",
""
] |
I have a table with transaction history for 3 years, I need to compare the sum ( transaction) for 12 months with sum( transaction) for 4 weeks and display the customer list with the result set.
```
Table Transaction_History
Customer_List Transaction Date
1 200 01/01/2014
2 200... | the query below will work, except your sample data doesnt make sense
total for customer 1 for the last 12 months in your data set = 400
total for customer 1 for the last 4 weeks in your data set = 200
unless you want to exclude the last 4 weeks, and not be a part of the last 12 months?
then you would change the "hav... | I suggest a self join.
```
select yourfields
from yourtable twelvemonths join yourtable fourweeks on something
where fourweek.something is within a four week period
and twelvemonths.something is within a 12 month period
```
You should be able to work out the details. | SQL Comparison Query Error | [
"",
"sql",
"sql-server",
""
] |
I am only a beginner in SQL, and I have problem that I can not solve.
The problem is the following:
i have four tables
```
Student: matrnr, name, semester, start_date
Listening: matrnr<Student>, vorlnr<Subject>
Subject: vorlnr, title, sws, teacher<Professor>
Professor: persnr, name, rank, room
```
I need to list al... | Your approach is good. Only, you want to show students, but join students with listings thus getting student-listing combinations.
Moreover you use a join syntax that is out-dated. It was replaced more than twenty years ago with explicit joins (INNER JOIN, CROSS JOIN, etc.)
You can do it with subqueries only:
```
se... | When you have an SQL problem, a good way of presenting the problem is to show us the tables as `CREATE TABLE` statements. Such statements show details such as the types of the columns and which columns are primary keys. Additionally this allows us to actually build a little database in order to reproduce a faulty behav... | Connecting 4 tables | [
"",
"sql",
"database",
"oracle",
"oracle-sqldeveloper",
""
] |
I imported a txt file into my table column B which is of datatype varchar
the data is like 10.00 GB, 20 TB , 100 MB etc
```
column a column b
host A 100 TB
host B 20 GB
host C 100 MB
```
I did try convert (int,column name) which returned error advising cannot convert data type varchar to type in... | You can split the column using:
```
select t.a, t.b,
cast(left(b, charindex(' ', b)) as int) as num,
right(b, 2) as units
from t;
```
This assumes that the values are all in exactly this format.
You can put it in one column by using multiplication:
```
select t.a, t.b,
(cast(left(b, charindex('... | I know that 1000 is not the same as 1024, but depending on your exact needs, this is a pretty simple method:
`select cast(ROUND(replace(replace(replace(columnB, ' TB', '000000000'), ' GB', '000000'), ' MB', '000') ,0,1) as int) from t` | SQL update column from varchar data type to int | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
"sql-server-2008-express",
""
] |
I want to retrain last 25 entered records and delete remaining records according to id.
```
DELETE * FROM list
WHERE id NOT IN
(
SELECT *
FROM (
SELECT *
FROM 'list'
ORDER BY id DESC LIMIT 25
) as rows
)
``` | ```
DELETE *
FROM 'list'
WHERE id NOT IN ( SELECT id
FROM 'list'
ORDER BY id DESC
LIMIT 25 )
``` | Deleting while selecting from the same table isn't permitted in MySQL.
You can try something like this:
```
SELECT @rows_to_delete:=COUNT(*)-25 FROM list;
DELETE FROM list ORDER BY id ASC LIMIT 0, @rows_to_delete;
```
**NB: this is not tested please test before running it on real data.** | select last 25 records from SQL table | [
"",
"mysql",
"sql",
""
] |
What I whant is to rearrange the numerical data in column for example BookID. If I have column with data like this:
```
BookID ; BookTitle
1 name1
4 name2
11 name3
```
How can I rearrange to look like this:
```
BookID ; BookTitle
0 name1
1 name2
2 name3
``` | Is this what you want?
```
select row_number() over (order by BookId) - 1 as BookId, BookTitle
from books b;
```
If you want to change the ids in the data, you *can* do that. But, it is not recommended. The primary key on a row does not need to have any meaning. It gets used for foreign key references in other tables... | To update BookID in sequential order. Use the below update query.
```
UPDATE A SET A.BookID = B.NewBookID
FROM Books A
INNER JOIN (
SELECT BookID, NewBookID = ROW_NUMBER() OVER (ORDER BY BookTitle) - 1
FROM Books
) AS B
ON A.BookID = B.BookID
``` | How can I rearrange the numerical data of some columns | [
"",
"sql",
"sql-server",
""
] |
Suppose I have three tables
```
Student Student_Interest Interest
======= ================ ========
Id Student_Id Id
Name Interest_Id Name
```
Where Student\_Interest.Student\_Id refers to Student.Id
and Student\_Interest.Interest\_Id refers to Interest.Id
Let's say... | > How can we get the list of students that have both "Java" and "C" as
> their interests?
We can write t(t.c,...) to say that row (t.c,...) is in table t. Let's alias Student to s, Student\_Interest to sij and sic and Interest to ij and ic. We want rows (s.Id,s.Name) where
```
s(s.Id,s.Name)
AND sij(sij.Student_I... | Simply get the Java and C records from student\_interest, group by student and see if you get the complete number of interests for a student. With such students found you can display data from the student table.
```
select *
from student
where id in
(
select student_id
from student_interest
where interest_id in ... | Matching one value in one column with more than one values in other column in SQL | [
"",
"mysql",
"sql",
""
] |
If I have string like
```
select field1 + N' ' + field2 + N' ' + field3 from table1
```
how to make so that I could change or replace the characters starting from third place to fifth?
I mean if select statement above returns a string `ABCD EFGH IJKL`, then I want to replace `CD(space)` with `*`
Thanks. | Use the stuff function:
```
SELECT STUFF('ABCD EFGH IJKL', 3, 3, '*');
select STUFF(field1 + N' ' + field2 + N' ' + field3, 3, 3, '*') from table1
```
Syntax:
```
STUFF ( character_expression , start , length , replaceWith_expression )
``` | I feel STUFF function is the best way to go about it.
Below is a small example on how i would approach the same
```
CREATE TABLE TESTDATA
(
DATA NVARCHAR(MAX),
DATA1 NVARCHAR(MAX),
DATA2 NVARCHAR(MAX)
)
INSERT INTO TESTDATA VALUES('ABCD','HGHG','HGFD')
INSERT INTO TESTDATA VALUES('HHGG','ADFS', 'ERET')
INSE... | Replace the string characters in SQL Server | [
"",
"sql",
"sql-server",
"ssms",
""
] |
Between table1 and table2 there are an 1 N relation. "code" column of table2 is foreign key of table1.
I want to delete all rows in table1 who don't have any row related in table2. I try
```
delete * from table1 r
inner join table2 a
where (r.code!=a.code)
```
but this delete all rows in two tables... | Maybe this is what you want?
```
delete from table1
where code not in (
select code from table2
)
```
before you run the delete you might want to verify that the correct rows will be deleted using a select query:
```
select * from table1
where code not in (
select code from table2
)
``` | You may try this:
```
delete from table1 r
where not exists (select 1 from table2 a where r.code = a.code);
``` | Delete rows from two tables related | [
"",
"sql",
"delete-row",
""
] |
I want to display the `subtraction` of two values from `two` different rows using a `SQL` query.
This is the table structure:
```
------------------------------------
id | name | sub1 | sub2 | date
------------------------------------
1 | ABC | 50 | 75 | 2014-11-07
2 | PQR | 60 | 80 | 2014-11-08
```
I wa... | You can use a join to get the rows and then subtract the values:
```
SELECT(t2.sub1 - t1.sub1) AS sub1, (t2.sub2 - t1.sub2) AS sub2
FROM table t1 CROSS JOIN
table t2
WHERE t1.date = '2014-11-08' AND t2.id = '2014-11-07';
``` | I feel like you're leaving out an important part of your actual needs where you'll probably want to group by some specific field and return corresponding values, so the answer will be kind of limited. You can double reference the table like the example above, but it's usually much better if you can somehow only referen... | How can I subtract two row's values within same column using sql query? | [
"",
"sql",
""
] |
I have a table that has only one record as below
```
Date1 Date2 Amount CountDays
2014-01-01 2014-01-4 1000 4
```
field "CountDays" will be calculatd by a trigger. i want to write a query that returns below result:
```
Date Amount
2014-01-01 250
2014... | This should work:
```
WITH Nums AS(
SELECT DISTINCT Value = number
FROM master..[spt_values]
)
SELECT Date = DATEADD(d, n.Value - 1, t.Date1),
Amount = t.Amount / t.CountDays * 1.0
FROM Nums n CROSS JOIN TableName t
WHERE n.Value BETWEEN 1 AND t.CountDays
```
[**Demo**](http://sqlfiddle.com/#!6/9339a... | Creating test data:
```
create table yourtable (Id int, Date1 datetime, Date2 datetime, Amount int, CountDays decimal);
insert into yourtable values (1, '2014-01-01','2014-01-04', 1000, 4);
insert into yourtable values (2, '2014-01-13','2014-01-19', 1200, 6);
```
And the sql query (common table expression with recur... | Select All dates between two dates | [
"",
"sql",
"sql-server-2008",
""
] |
I am trying to select some data from different tables using join.
First, here is my SQL (MS) query:
```
SELECT Polls.pollID,
Members.membername,
Polls.polltitle, (SELECT COUNT(*) FROM PollChoices WHERE pollID=Polls.pollID) AS 'choices',
(SELECT COUNT(*) FROM PollVotes WHERE PollVotes.pollChoice... | Your INNER JOIN with `PollChoices` is bringing in more than 1 row for a given `poll` as there are 2 choices for the poll 10000036 as indicated by `choices` column.
You can change the query to use `GROUP BY` and get the counts.
In case you don't have entries for each member in the `PollVotes` or `Polls` table, you nee... | This query result is telling you the number of votes **per choice** in each poll.
In your example, this voter named TestName answered the poll (with ID 10000036) and gave one choice 1 vote, and the second choice 0 votes. This is why you are getting two rows in your result.
I'm not sure if you are expecting just one r... | SQL select with join are returning double results | [
"",
"sql",
"inner-join",
"redundancy",
""
] |
I have the 3 below statements,
1. Selects the Order Numbers that dont exist
> ```
> select Orders.OrderNumber
> FROM Orders
> inner join InvoiceControl on Orders.OrderNumber = InvoiceControl.OrderNumber
> where not exists (select OrderNumber from Orders where InvoiceControl.OrderNumber = Orders.OrderNumber)
> ```
... | Because your `INNER JOIN` will already create all correspondents between `Orders.OrderNumber = InvoiceControl.OrderNumber`.
After this result set is built, you actually filter out everything based on the condition in your `WHERE`.
`where not exists (select OrderNumber from Orders where InvoiceControl.OrderNumber = Or... | In the first query, you first asked for rows in both Orders and InvoiceControl (by way of the FROM and JOIN tables), and then you added in your WHERE clause a request to exclude all rows that exist in Orders. Since your starting set only includes rows that are in Orders, if you ask for all of those rows to be excluded,... | SQL Server WHERE NOT EXISTS not working | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I'm trying to create a query using `SELECT CASE` that would return the accumulative results.
Here is my query, it works but doesnt return the correct result.
```
SELECT total, count(*) as count FROM
(
SELECT case
WHEN ( X ) < 1 THEN '1 km'
... | Another approach is to calculate the results independently then union them:
```
SELECT 1 AS total, COUNT(*) AS cnt FROM `store` WHERE store.pending != 1 AND ( X ) < 1
UNION ALL
SELECT 3 AS total, COUNT(*) AS cnt FROM `store` WHERE store.pending != 1 AND ( X ) < 3
UNION ALL
SELECT 5 AS total, COUNT(*) AS cnt FROM `stor... | In addition to the accumulation, you also want a total value at the end with `-1`. This is a bit of a pain, but it can be accomplished.
The simplest way to do cumulative sums in MySQL is using variables. The basic idea is this:
```
SELECT total, cnt, (@cnt := @cnt + cnt) as count
FROM (SELECT (case WHEN ( X ) < ... | SELECT CASE to return accumulative results | [
"",
"mysql",
"sql",
""
] |
I have created three tables like Product, Brands and ProductBrands in ms sql server
These tables contains data as the following
Products (PId - PName)
* 1 - Mobiles
* 2 - T.V
* 3 - A.C
Brands (BId - BName)
* 1 - Samsung
* 2 - Sony
* 3 - L.G
ProductsBrands (PBId - PId - BId)
* 1 - 1 - 1
* 2 - 1 - 2
* 3 - 1 - 3
* 4... | ```
SELECT P.PId ,
P.PName,
B.BId,
B.BName
FROM Products P
JOIN ProductsBrands PB On PB.PId = P.PId
JOIN Brands B ON B.BId = PB.BId
```
See, whether this is what you are looking for. | If my understanding is correct:(Fetch all brands assigned to a Product)
```
select BName from Brands where BId in
(select distinct Bid from ProductsBrands where PId = (select PId from Products where PName = @input))
``` | How to fetch data from tables where there is one to many relationship? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Pretty straight forward question, I want to store feet and inches in 1 column using a decimal, but I dont want it truncated like how the float type does. | Store all your data in MKS (metric). When presenting and storing convert the data into an international standard. and store it in a decimal type.
Thus if your tool to gather the data is in 6'2" format convert it into cm and save in your data table. Then reverse this for display.
By saving in a standard format decimal... | The imperial unit system still used in Myanmar, Liberia and that one country in North America is unfortunately not very arithmetics-friendly. There is [no native data-type](http://msdn.microsoft.com/en-us/library/ms187752.aspx) to handle the strange base12/base3/base1860 math for it.
You should really use the much mor... | whats the best datatype to store height? | [
"",
"sql",
"sql-server",
"types",
""
] |
I want to sort a list of record from the database. The records retrieved is sorted based on a column with int values. The possible int values are 1,2,3,4,5. The sorting order required is 1,3,2,4,5
so i cannot use `Order by table.a asc`. What should be my query to retrieve the desired order? for example my table has th... | you can add case statements to your order by clause
```
SELECT name, to_order
FROM Table1
ORDER BY
(
CASE
WHEN to_order = 1 THEN 0
WHEN to_order = 3 THEN 1
ELSE 2
END
),
to_order
```
Add case for 3 so it would be prioritize againts other numbers. I included 1 as case sin... | I would write this as:
```
order by (case when to_order = 2 then 3
when to_order = 3 then 2
else to_order
end)
``` | sql sort by int, except for one int value which has a different order | [
"",
"mysql",
"sql",
"sorting",
""
] |
In Oracle/SQL how to select rows where the value of the columns remained the same
I have a list of budget, each budget spread over 12 months, with fixed salary each month. I would like to return a list of budgets for which the value of the salary remained the same over 12 months.
```
BUDGET MONTH SALARY
5468 1 ... | Count the `distinct` salary for every budget
```
select budget
from your_table
group by budget
having count(distinct salary) = 1
``` | ```
SELECT BUDGET,SALARY FROM BUDTGET_TAB
HAVING COUNT(MONTH)=12
GROUP BY BUDGET,SALARY
ORDER BY 1,2
``` | In Oracle/SQL how to select rows where the value of the columns remained the same | [
"",
"sql",
"oracle",
"oracle11g",
"oracle10g",
""
] |
I know how to do this in SQL Server thanks to this clever bit of code
```
Use <database>
SELECT execquery.last_execution_time AS [Date Time], execsql.text AS [Script]
FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
ORDER BY execquery.last_execution_time DESC... | If you have the privileges then:
```
SELECT * FROM v$sql
```
If not then press `F8` to bring up a list of previously ran queries. | [This](http://www.solveitproblems.net/2012/11/restore-unsaved-and-lost-plsql-code-in.html) has saved my butt several times.
> It is really a problem when you lose unsaved code. For about a
> month I have been working on a big procedure, and forgot to save the
> code in SVN. If you read this and remember have such unsa... | Recover unsaved SQL query Scripts in Oracle SQL Developer | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
""
] |
I am having a ~90 MB SQLite database on a SSD consisting mostly on message attachments including a BLOB column content, that stores the binary attachment data.
Now I found that the following query
```
SELECT message_id FROM attachments WHERE length(content) IS NULL;
```
is 500x faster (0.5ms vs. 250ms) than the orig... | In SQLite, the length and type of each column value are stored [at the beginning of the row](http://www.sqlite.org/fileformat2.html#record_format).
This allows the `length()` and `typeof()` functions to be optimized to avoid loading the actual value.
The IS NULL operator has no such optimization (although it would be ... | I made a script to benchmark both functions. `length(x) IS NULL` is faster unless you have mostly `NULL` values.
## Results:
* 50% alternating between random data and null:
+ `IS NULL`: 11.343180236999842
+ `length(x) IS NULL`: 7.824154090999855
* Entirely blobs, no nulls:
+ `IS NULL`: 15.019244787999924
+ `l... | Is 'length() IS NULL' equivalent and faster than 'IS NULL' for BLOBs? | [
"",
"sql",
"sqlite",
""
] |
I am attempting to get the average rating (1-10) for each of 6 games that were rated.
Here is an example of the table:

I can select the average of one of the 6 games like this:
```
SELECT ROUND(AVG(overallRating), 0), COUNT(*) AS Total, gameID
FROM... | Try:
```
SELECT ROUND(AVG(overallRating), 0), count(*) as Total, gameID
FROM gameSurvey
GROUP BY gameID
``` | As everyone else has stated, you should use group by.
What this does, as it is implied, is group together certain rows based on a given column. In this case, you want to group all gameID values into one row. Then, any aggregate functions (such as AVG) are preformed within these groups, so the average value you see in ... | How can I get multiple averages from multiple rows using Mysql | [
"",
"mysql",
"sql",
""
] |
I have one field for date contains year and months. Field name new\_TarikhSebenarTamatPengajian. Exmaple of data 199110 (Format:YYYYMM). I want to add date to set a new format require are (YYYYMMDD).
For the available data Can I add date follow end of the month for that month.
Example 199101 = 19910130 OR 199102 = 1991... | Try this one:
```
SELECT id,crse_date,
CASE
WHEN RIGHT(crse_date,2) = 01 THEN CONCAT(crse_date,31)
WHEN RIGHT(crse_date,2) = 02 THEN CONCAT(crse_date,28)
WHEN RIGHT(crse_date,2) = 03 THEN CONCAT(crse_date,31)
WHEN RIGHT(crse_date,2) = 04 THEN CONCAT(crse_date,30)
END ... | Assuming your column name is DateWithOutMonth :
```
Select Convert(nvarchar(8), Dateadd(day, -1, Dateadd(month, 1, Convert(datetime, DateWithOutMonth + '01'))) , 112)
from your table
```
Code explained :
* first, add `01` to the end of your date value, so the value will always is the beginning of a month
* convert ... | SQL field add date change format to YYYYMMDD | [
"",
"sql",
"datefield",
""
] |
I have some trouble writing well performing query. Now I have two tables:
Cars:
```
id brand model_name
1 'Audi' 'A4'
2 'Audi' 'A4'
3 'Audi' 'A4'
4 'Audi' 'A6'
5 'Audi' 'A7'
```
Buyers:
```
id cars_id name activly_looking
1 2 'Brad' 'no'
2 2 'Kim' 'maybe'
3 ... | Another way using conditional aggregation to filter all cars that have `actively_looking = yes` buyers.
The inner join ensures that the car has at least 1 buyer and the having clause ensures that none of the buyers are actively looking.
```
select count(*) from (
select c.id from cars c
join buyers b on b.car... | You can use `exists` and `not exists` to check your conditions and then just do an aggregation query:
```
select count(*)
from cars c
where exists (select 1 from buyers b where b.cars_id = c.id) and
not exists (select 1 from buyers b where b.cars_id = c.id and b.acively_looking = 'yes')
``` | Simple way to count all where has 0 relations with specific value | [
"",
"sql",
"postgresql",
""
] |
I have this table:
```
[SDate - DateTime] [Value] - Represents a boolean
2010-11-16 10:10:00 1
2010-11-16 10:11:00 0
2010-11-16 10:12:00 1
2010-11-16 10:13:00 1
```
I need a query to count how many times t... | You can do this with `lag()`:
```
select count(*)
from (select t.*, lag(value) order by (sdate) as prev_value
from table t
) t
where prev_value <> value ;
``` | This should work in earlier versions too..
```
;WITH cte
AS (SELECT Row_number()OVER(ORDER BY sdates) rn,*
FROM <tablename>)
SELECT Sum(CASE WHEN a.boolvalue = b.boolvalue THEN 0 ELSE 1 END)
FROM cte a
JOIN cte b
ON a.rn = b.rn + 1
``` | Counting how many times a boolean value changes in SQL Server | [
"",
"sql",
"t-sql",
"sql-server-2012",
""
] |
I am using MSSQL database SQL Server 2008
I have query to database
```
select *, DateDiff(n,StartDateTime,EndDateTime) as DateDifference
from result
where Project='Sample' AND SubProject='Sample' and
(StartDateTime)>='11/01/2013 00:00:00' AND (EndDateTime)<='11/11/2014 23:59:59'
order by EndDateTime desc
```
I... | Here is an answer might help:
```
SELECT TestCaseName,
userName,
StartDatetime,
EndDateTime,
Datediff(N, StartDatetime, EndDateTime) AS datedifference
FROM (SELECT *,
ROW_NUMBER()
OVER (
partition BY testcasename
ORDER ... | I hope group by and max will be work
```
WITH CTE(Testcasename,userName,StartDatetime)
AS
(
SELECT Testcasename,userName,MAX(StartDatetime) StartDatetime
FROM result
GROUP BY Testcasename,Username
)
SELECT A.*,DateDiff(DD,A.StartDateTime,A.EndDateTime) as DateDifference FROM
RESULT A INNER JOIN CTE B ON A.Testcasena... | How to self query table in order to get last executed testcase from same table | [
"",
"sql",
""
] |
I've searched stackoverflow but could not get an answer to my question.
Table 1 has two columns
1. employee\_id
2. employee\_name
Table 2 has two columns
1. employee\_id
2. Manager\_id
Manager\_id is a subset of Employee\_id, which in turn means that Manager's name will be available in Employee\_name list.
How do... | You need to join back to `table1`:
```
select
employees.employee_name.employee_id,
employees.employee_name,
managers.employee_name as manager_name
from table1 as employees
left join table2
on table2.employee_id = employees.employee_id
left join table1 as managers
on managers.employ... | You need a 2nd join.
* 1st join is from t1 to t2 to get the manager of the employee.
* The next join would be from t2 back to t1 again to get the name of the manger.
I'm assuming you want all employees and the name of the manger if one is defined.
```
SELECT emp.employee_id,
emp.employee_name,
mgr.empl... | need help joining two tables, sql | [
"",
"sql",
"join",
"oracle-sqldeveloper",
""
] |
I'm trying to check if a stored procedure exists, and then if it doesn't, create it.
I'm getting the error
> Incorrect Syntax Near SET. Expecting EXTERNAL
Code:
```
IF (NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = 'dbo'
AND ROUTINE_NAME = 'E... | You got that error because that is not the right for checking the existence of a object(procedure) and if not exists then creating it . try something like this.
```
IF NOT EXISTS (SELECT *
FROM sys.objects
WHERE object_id = Object_id(N'[dbo].[ELMAH_GetErrorXml]')
... | ```
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF EXISTS (SELECT 1 FROM sys.objects where name = 'ELMAH_GetErrorXml' and type ='P')
Drop Procedure [dbo].[ELMAH_GetErrorXml]
Go
CREATE PROCEDURE [dbo].[ELMAH_GetErrorXml]
(
@Application NVARCHAR(60),
@ErrorId UNIQUEIDENTIFIER
)
AS
SET NOCOUNT ON
SELECT
[All... | Incorrect Syntax Near SET. Expecting EXTERNAL | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I'd like identify all views and procedures in a HANA DB that use a given table. In SQL Server, one can query `sysobjects` and `syscomments` like the following:
```
SELECT
o.name
FROM sysobjects o
JOIN syscomments c
ON o.id = c.id
WHERE c.comment LIKE '%tableName%'
```
Is there an equivalent in HANA? | Well that didn't take long to find. An answer can be found on the [SCN](http://scn.sap.com/thread/3526533).
```
SELECT
Procedure_Name
FROM sys.procedures
WHERE Definition LIKE '%tableName%'
``` | I believe the best approach would be to search them using the Public Synonyms of the system, since the current user may not have SELECT privilege on schema SYS.
All objects can be found using:
```
SELECT *
FROM OBJECTS
```
For procedures, you can just
```
SELECT *
FROM PROCEDURES
```
For more public synonyms av... | HANA Equivalent of syscomments | [
"",
"sql",
"hana",
""
] |
Hopefully simple enough but cannot find the answer. Trying to run:
SQL Server
```
left outer join exchanges fx (nolock) on
v1.ccy = fx.ccy and v1.date = fx.date
```
The problem is that fx.ccy may not exist on fx.date. I would therefore like to join on the next available date.
Many thanks,
José | Possible solution:
```
....
left outer join exchanges fx (nolock) on
v1.ccy = fx.ccy and fx.date = (
select min(date) from exchanges where date >= v1.date and ccy = v1.ccy)
``` | ```
left outer join exchanges fx (nolock) on
v1.ccy = fx.ccy and fx.date = (select min(date)
from exchanges x
where v1.ccy = x.ccy
and x.date >= v1.date)
``` | SQL - Coalesce until next available date | [
"",
"sql",
"join",
"coalesce",
""
] |
I have a table that has 3 columns: date,name,salary
I want to query the table and add in the result set another calculated column that can have 2 values: 'new' and 'same'.
The rule to assign the value is: order records by date ascending. if the name of the current record is different from the name of the previous rec... | It would seem that DB2 (versions after 9.7 at least) support the LAG() window function, so this query should work (although I haven't been able to test it):
```
SELECT
date,
name,
salary
CASE
WHEN lag(name, 1) OVER (ORDER BY date ASC) = name THEN 'same'
ELSE 'start'
END AS calc_col
F... | Depends on the database you are using, MS SQL has a lag function : <http://msdn.microsoft.com/en-us/library/hh231256.aspx>
There is a mysql hack for this, check out this question : [Simulate lag function in MySQL](https://stackoverflow.com/questions/11303532/simulate-lag-function-in-mysql)
[how to do lag operation in ... | Get previous record column value in SQL | [
"",
"mysql",
"sql",
"db2",
"record",
"recordset",
""
] |
So I have a table that looks like this:
```
ID amt_1 amt_2 amt_3 amt_4
001 100.00 300.00 50.00 200.00
002 200.00 400.00 100.00 200.00
003 700.00 50.0 200.00 700.00
```
And I want to make a new column that carries only the greatest value per ID ie:
```
ID am... | Using `CASE Statement` you can find the largest value among the columns.
```
SELECT ID,
amt_1,
amt_2,
amt_3,
amt_4,
CASE
WHEN amt_1 >= amt_2 AND amt_1 >= amt_3 AND amt_1 >= amt_4 THEN amt_1
WHEN amt_2 >= amt_1 AND amt_2 >= amt_3 AND amt_2 >= amt_4 THEN amt_2
... | Using SQL, you can use subselect to do something like this :
```
SELECT MAX(SELECT amt_1 FROM table_name
UNION
SELECT amt_2 FROM table_name
UNION
SELECT amt_3 FROM table_name
// ...) as maxValue, id FROM table_name
```
I'm just thinking loudly, try to see if this pseudo code works, note that you can create a view or ... | Need the greatest value in new column | [
"",
"sql",
"max",
"calculated-columns",
""
] |
I am getting stuck on some SQL with a CASE condition.
Its a back end for a SSRS 2005 report and the user can select ALL, < 50k, or > 50K
The guts are..
```
SELECT LOANAMOUNT
FROM LOANS
WHERE loanAmount (CASE WHEN @Parameter 'All' THEN = loanAmount --Ignore the variable
ELSE @parameter = 1 THEN <= 50k
ELSE @paramet... | *All*=Select All Records
or depends upon `@Parameter` values will be filtered
```
SELECT *
FROM LOANS
WHERE
(@Parameter = 'All') OR
(@Parameter = '1' AND loanAmount <= 50000) OR
(@Parameter = '2' AND loanAmount > 50000)
``` | You don't need a `case` at all
```
SELECT LOANAMOUNT
FROM LOANS
WHERE @Parameter 'All'
OR (@parameter = '1' AND loanAmount <= 50000)
OR (@parameter = '2' AND loanAmount > 50000)
``` | SQL, BETWEEN and CASE (3 COndition Parameter) | [
"",
"sql",
"sql-server",
"case",
"reportingservices-2005",
"between",
""
] |
I have around 10 Linked Servers, i need to get GETDATE() datetime from each of these Linked Server and store it in a table. Please help me out to how to achieve this. | ```
insert into table
(all_Dates)
SELECT *
FROM OPENQUERY(USLinkedServer, 'SELECT getdate()')
union
SELECT *
FROM OPENQUERY(UKLinkedServer, 'SELECT getdate()')
union
SELECT *
FROM OPENQUERY(AUSLinkedServer, 'SELECT getdate()')
.
.
.
```
Remember, OPENQUERY requires that the linked server is already set up | You can use **OPENQUERY** to get the result set from **remote server** which are added as **linked server**.
The syntax is **OPENQUERY ( linked\_server ,'query' )**
Any user can execute **OPENQUERY**. The permissions that are used to connect to the remote server are obtained from the settings defined for the linked s... | How to get GETDATE() from multiple linked Servers | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I am trying to restore a database in PMA but only have access to frm and ibd files - not the ib\_log files which I understand you need.
I know I may not be able to recover the database data but is it possible to recover the structure of the tables from the frm files? | I restored the table from only `.frm` and `.idb` files.
### Get the SQL query to create the tables
If you already know the schema of your tables, you can skip this step.
1. First, install [MySQL Utilities](http://dev.mysql.com/downloads/utilities/).
Then you can use `mysqlfrm` command in command prompt (cmd).
2. ... | InnoDB needs the ib\_log files for data recovery, but it also needs the ibdata1 file which contains the data dictionary and sometimes contains pending data for the tables.
The data dictionary is kind of a duplicate system that records table structure and also matches a table id to the physical .ibd file that contains ... | Restore table structure from frm and ibd files | [
"",
"mysql",
"sql",
"phpmyadmin",
"innodb",
""
] |
I have found myself in a challenging scenario which I cannot figure out. I have a table "#PriceChange" which i need to figure out the various profit losses, between two dates, based on the price change
Example:
Product 1001 (Black Jeans), has change price 3 times.
* 2014-11-02: 10.99 > 8.99 (50 sold)
* 2014-11-03: 8... | ```
with cteprice as
( select *,
row_number() over(partition by product order by validfrom) as rnk
from #PriceChange)
select p1.Product,
sum((p1.CurrentPrice - p2.CurrentPrice)* p2.SoldBetweenValidDates)
from cteprice p1
join cteprice p2 on p1.rnk + 1 = p2.rnk and p1.Product = p2.Product
group b... | Hope this helps:
```
WITH cte AS (
SELECT
p1.Product
, OverallDiff
FROM
#PriceChange p1
CROSS APPLY
(
SELECT
MIN(p2.ValidFrom) as ValidP2
FROM
#PriceChange p2
WHERE
p1.Product = p2.Product
... | How do I have a running sum count/calculation? | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I have s table that lists absences(holidays) of all employees, and what we would like to find out is who is away today, and the date that they will return.
Unfortunately, absences aren't given IDs, so you can't just retrieve the max date from an absence ID if one of those dates is today.
However, absences **are** giv... | So based on what I believe you're asking, you want to return a list of the people that are off today and when they are expected back based on the holidays that you have recorded in the system, which should only work only on consecutive days.
## [SQL Fiddle Demo](http://sqlfiddle.com/#!6/8accc/4)
**Schema Setup**:
``... | You'd need to do a few things to get this data into a usable format. You need to be able to work out where a group begins and ends. This is difficult with this example because there is no straight forward grouping column.
So that we can calculate when a group starts and ends, you need to create a CTE containing all th... | Finding most recent date based on consecutive dates | [
"",
"sql",
"sql-server",
"greatest-n-per-group",
""
] |
I have two tables:
```
data a;
input a b c;
datalines;
1 2 .
;
run;
data b;
input a b c;
datalines;
1 . 3
;
run;
```
The result I want from these tables is replacing the missings by the values that are not missing:
```
a b c
-----
1 2 3
```
How can I do it with mostly less piece of code?
EDIT:
I wrote the code an... | Using `proc SQL`, you can do this with aggregation:
```
proc sql;
select max(a) as a, max(b) as b, max(c) as c
from (select a, b, c from a union all
select a, b, c from b
) x;
```
If, as I suspect, the first column is an id for matching the two tables, you should instead do:
```
proc sql;
... | If the values are consistent, ie, you never have:
```
1 2 3
1 3 .
```
and/or are happy for them to be overwritten, then UPDATE is excellent for this.
```
data c;
update a b;
by a;
run;
```
`UPDATE` will only replace values with non-missing values, so `.` gets replaced by `3` but `2` is not replaced by `.`. Agai... | Replace missings SAS | [
"",
"sql",
"sas",
""
] |
I have a table with two DateTime columns, `_dateEntry` and `_dateUpdate`.
I've to create a query and choose the right datetime column based on these conditions: take the most recent between `_dateEntry` and `_dateUpdate`. `_dateUpdate` might be null, so I wrote this condition
```
SELECT id, description, ISNULL(_dateU... | I suppose \_dateEntry is never NULL. If can be NULL tell me because I change my query
Try this:
```
SELECT id, description,
CASE
WHEN _dateUpdate IS NULL THEN _dateEntry
WHEN _dateUpdate > _dateEntry THEN dateUpdate
ELSE _dateEntry
END as date
FROM mytable
ORDER BY
CASE
WHEN _dateUpdate IS NULL THEN _... | You can use a case to return what you want:
```
SELECT
id
, description
, CASE WHEN _dateEntry > ISNULL(_dateUpdate,0)
THEN _dateEntry ELSE _dateUpdate END AS date
FROM
mytable
``` | Query between datetime columns | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have an application with forty questions. I'm holding the questions in tbQuestion and their corresponding answers in tbAnswer along with what answer the user chose in tbResult.
Here's the table structure:
```
tbQuestion: tbAnswer: tbResult:
QuestionID AnswerID ResultID
QuestionText Que... | Move the condition in your WHERE clause to the ON clause of the outer join:
```
select q.questionid,
q.questiontext,
a.answerid,
a.answertext,
r.anseredid as answered
from tbquestion q
join tbanswer a
on q.questionid = a.questionid
left join tbresult r
on q.questionid = r.ques... | Try just LEFT OUTER JOIN tbAnswer
```
SELECT tbQuestion.QuestionID ,
QuestionText ,
tbAnswer.AnswerID ,
AnswerText ,
tbResult.AnseredID AS Answered
FROM tbQuestion
LEFT OUTER JOIN tbAnswer
ON tbQuestion.QuestionID = tbAnswer.QuestionID
LEFT OUTER JOIN tbResult
ON tbQuestion... | Need SQL query for a quiz application | [
"",
"sql",
"sql-server",
""
] |
# The Query needs to Check for null value and replace with the most recent not null value.
For example consider the source data provided below .
Query needs to check the null value and found it in second row, now it should replace the null value with recent not null data and the data is"colmin".
Again the Query need... | Try this:
```
declare @input table (id bigint not null identity(1,1), OutputData nvarchar(16) null)
insert @input select 'Colmin'
insert @input select NULL
insert @input select NULL
insert @input select NULL
insert @input select NULL
insert @input select 'columnxy'
insert @input select 'column99'
insert @input sel... | What is "most recent" ? I hope you've got some field to sort on. Row number MUST NOT ALWAYS be in right order! Though I'd use `orderField` which is will be used to determine the row order.
```
UPDATE myTable
SET a = (
SELECT a
FROM myTable
WHERE a IS NOT NULL
AND orderField > (
SELECT orderField
... | Check for null and replace the most recent not null value | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I've a table with 2 columns in `SQL`
```
+------+--------+
| WEEK | OUTPUT |
+------+--------+
| 1 | 10 |
| 2 | 20 |
| 3 | 30 |
| 4 | 40 |
| 5 | 50 |
| 6 | 50 |
+------+--------+
```
How do I calculate to sum up output for 2 weeks before (ex : on week 3, it will sum up the ou... | I think you want something like this :
```
SELECT *,
(SELECT Sum(output)
FROM table1 b
WHERE b.week IN( a.week, a.week - 1, a.week - 2 )) AS SUM
FROM table1 a
```
OR
In clause can be converted to `between a.week-2 and a.week`.
[sql fiddle](http://sqlfiddle.com/#!3/4f2b8/4) | You can use a self-join. The idea is to put you table beside itself with a condition that brings matching rows in a single row:
```
SELECT * FROM [output] o1
INNER JOIN [output] o2 ON o1.Week between o2.Week and o2.Week + 2
```
this select will produce this output:
```
o1.Week o1.Output o2.Week o2.Output
--... | How to calculate moving average in SQL? | [
"",
"sql",
"sql-server",
"moving-average",
""
] |
I need to prevent the Order By SettingID at the bottom of this SQL from re-ordering everything. I want to Order my first select by UserID and my second select by OrderID. How do put a bound on the bottom Order By? I tried parentheses but I'm a T-SQL beginner so couldn't get that figured out. I tried using @ResultA and ... | You should not depend on the ordering of rows in a table, even table variables. In SQL, tables represent *unordered* sets. You can do what with a single query:
```
SELECT SettingID, GroupID, UserID
FROM Table1
ORDER BY (CASE WHEN (GroupID = @GroupID AND UserID = @UserID) THEN 1 ELSE 0 END) DESC,
GroupID
```
... | Use commas to add ORDER BY layers:
```
SELECT * FROM @Result ORDER BY UserID, OrderID
```
You can and should remove the order by in the queries that populate your table variable. | How I prevent the bottom Order By from effecting everything in @Result? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-order-by",
""
] |
I have table
```
id color image_id
1 red 2
2 green 2
3 pink 2
4 black 2
5 gray 2
6 orange 2
7 purple 2
8 yellow 2
9 greenish 2
10 white 2
select image_id,count(image_id) from colors group by image_id having count(image_id) > 5... | You want to keep the first five rows for each image id. Here is a method that uses variables:
```
delete i
from images i join
(select i.*,
(@rn := if(@id = id, @rn + 1,
if(@id := id, 0, 0)
)
) as rn
from ima... | ```
delete from colors
where id not in
(select id
from colors
order by id
limit 5)
``` | Delete if image_id count is greater than 5? | [
"",
"mysql",
"sql",
"select",
""
] |
I am doing analysis on the Stack Overflow dump.
Problem statement: I have 4 tables and require result in the format given.
```
Table 1: UserID Year QuestionsOnTopicA
Table 2: UserID Year AnswersOnTopicA
Table 3: UserID Year QuestionsOnTopicB
Table 4: UserID Year AnswersOnTopicB
```
Desired Output:
```
UserID Year Q... | Ok, this works as intended:
```
SELECT COALESCE(A.UserID,B.UserID,C.UserID,D.UserID) UserID,
COALESCE(A.[Year],B.[Year],C.[Year],D.[Year]) [Year],
ISNULL(A.QuestionsOnTopicA,0) QuestionsOnTopicA,
ISNULL(B.AnswersOnTopicA,0) AnswersOnTopicA,
ISNULL(C.QuestionsOnTopicB,0) QuestionsOnTopi... | Use this SQL may be?
```
SELECT a.UserID, a.Year,
a.QuestionsOnTopicA,
b.AnswersOnTopicA,
c.QuestionsOnTopicB,
d.AnswersOnTopicB
FROM Table 1 a,
Table 2 b,
Table 3 c,
Table 4 d
WHERE a.UserID = b.UserID
AND b.UserID = c.UserID
AND c.UserID = d.UserID
AND d.UserID = a.Us... | Return results from multiple tables | [
"",
"sql",
"database",
"join",
"data.stackexchange.com",
""
] |
I am having trouble figuring out a query to only display consecutive dates (minimum 3) in SQL. After searching stack exchange, there are a few solutions but I can't get them to work exactly how I want it to. Consider the following table (actual data and table names changed for security):
```
code food ... | You can do this using window functions. You can identify groups of consecutive dates by subtracting `row_number()` from the date. With the group, you can then count the number of rows, and choose only those that have 3 or more rows:
```
select code, food, date
from (select t.*, count(*) over (partition by code, food, ... | Simple change to your original code should make it work:
```
select code, FOOD,grp, count(*) as NumInSequence, min([date]) AS MIN_date, max([date]) AS MAX_Date
from (select CODE,FOOD,[DATE],(DATEDIFF(D,'1/1/1900',[date])) - row_number() over (partition by code,FOOD order by [date]) as grp from @T t ) t
group by code, ... | Find All Consecutive Dates in SQL | [
"",
"sql",
"sql-server",
""
] |
I am writing a feature for a store website that will suggest other products that other customers bought with the products in the current customer's shopping cart.
My plan is to have a job that trawls the orders database and updates a many-to-many table tracking how often each pair of products were associated with one ... | In your `also_bought` table, add a `check` constraint to make sure that `product_a_id < product_b_id`. Make your job add entries in that order. That avoids duplication in the table.
But since you want to be able to look up pairs of product IDs in a simple way, create a view that's a union of `also_bought` with itself,... | You could exclude flipped pairs altogether with:
```
product_a_id <> product_b_id
AND product_a_id < product_b_id
```
You could also do this in one `UPDATE`:
```
SET times_together = times_together + 1 WHERE product_a_id IN (12,53) AND product_b_id IN (12,53);
``` | avoiding duplicate data in a "customers also bought" table | [
"",
"sql",
""
] |
Below is the result set from `SELECT` query,
```
mysql> select * from mytable where userid =242 ;
+--------+-----------------------------+------------+---------------------+---------------------+
| UserId | ActiveLinks | ModifiedBy | DateCreated | DateModified |
+--------+--------------... | Dealing with lists stored in data is a pain. In MySQL, you can use `substring_index()`. The following should do what you want:
```
SELECT userid,
substring_index(substring_index(l.ActiveLinks, '||', n.n), '|', -1) as link
FROM (select 1 as n union all select 2 union all select 3 union all select 4) n join
... | If this is just a list of values that do not relate to anything on another table I would do it the same way as Gordon (if needs be you can cross join the sub query that gets the lists of numbers to easily generate far larger ranges of numbers). One minor issue is that if the range of number is bigger than the number of... | MySql SELECT by Spliting multiple values separated by || | [
"",
"mysql",
"sql",
"database",
""
] |
I have two tables that one list the transactions and one that list that are cancelled. How do you only show the transactions that are not cancelled and omit the cancelled ones?

I just want to show the transactions that are not cancelled, in this cas... | ```
SELECT *
FROM TRANSACTION_TABLE
WHERE transaction_id
NOT IN (
SELECT transaction_id
FROM CANCELED_TABLE);
```
However, looking at your example I would suggest to add a field "canceled" to TRANSACTION\_TABLE instead of using a seperate table. | When building a somewhat complex query, the best way is to build it in stages, looking over the results you get at every stage. You know that to see the transactions that have not been canceled a left outer join is needed. Ok then, write it. (See `SQL Fiddle` for details):
```
select *
from Xaction x
left join Ca... | SQL Left Join Omit Rows Found | [
"",
"sql",
"left-join",
"rows",
""
] |
I have an input table which looks as follows:
```
ID NAME PARENT_ID
------------------------------------
1 ABC 0
2 DEF 1
3 XYZ 1
4 PQR 2
5 GHI 0
6 JKL 5
7 MNO 6
8 STU 6
```
I wan... | you can do something like this.
If you want you can check in your SQL I have also created insert query for you just check that.
**Data For Check The Output**
```
create table tbl
(
ID int,
NAME varchar(20),
PARENT_ID int
)
insert into
tbl
values
(1 ,'ABC', 0),
(2, 'DEF', 1),
(3 ,'XYZ', 1),
(4 ,'PQR', 2)... | If you want retrieve a hierarchical list :
```
with cte_1(ID, PARENT_ID, LABEL)
as (
select ID, PARENT_ID, cast(NAME as varchar(512))
from a_table
where PARENT_ID = 0
union all
select a.ID, a.PARENT_ID, cast(b.LABEL + ' --> ' +a.NAME as varchar(512))
from a_table a
join cte_1 b on a.PARENT_ID = b.ID
)
sel... | How to retrieve All childrens using a Select SQL Server query | [
"",
"sql",
"sql-server-2008",
"recursion",
""
] |
My fields are
```
ID | Name | StartTime | EndTime | Date | Description
```
I am looking for a way to select all rows with the same entries in all fields except for the ID.
I am not that familiar with SQL so I tried [this](https://stackoverflow.com/questions/2112618/finding-duplicate-rows-in-sql-server) approach but ... | This should do what you need:
```
select Name, Date, StartTime, EndTime, Description
from table
group by Name, Date, StartTime, EndTime, Description
having count(*) > 1
``` | This query should work for you:
```
SELECT ID, Name, StartTime, EndTime, Date, Description
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID, Name, Date, StartTime, EndTime, Description) AS 'IndexNr'
, ID
, Name
, StartTime
, EndTime
, Date
, Desc... | Find duplicate rows in SQL Server by multiple conditions | [
"",
"sql",
"sql-server",
""
] |
Rather than manually going through millions of records, is there a way to find the records which has difference in two amount columns? Is there a query to do it for me?
For example, Table A contains ColA and ColB with amountss on this and the datatype is "Money" on both columns. There are few instances where values ar... | As both are same datatype. You just need to check ColA <> ColB.
```
SELECT * FROM TableA WHERE ColA <> ColB
``` | To consider rows where ColA or ColB are null you can write as:
```
select ColA, ColB
from TableA
where Isnull(ColA,0) - Isnull(ColB ,0) != 0
```
`Demo` | How to identify or extract the rows where two column values (Amount fields) are different in SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
"comparison",
"compare",
""
] |
I got a table like this :
```
value | version1 | version2 | version3
--------|----------|----------|---------
aaa| 1| 1| 1
aaa| 1| 1| 2
aaa| 1| 2| 1
aaa| 1| 2| 2
aaa| 3| 1| 1
... | Edited:
Looking at your further explanation, you need to partition your output per different value.
You can then use the `ROW_NUMBER()` function, limiting the output to just one row per different value.
Example:
```
SELECT
value, version1, version2, version3
FROM (
SELECT
ROW_NUMBER() OVER (
PA... | This might help you :
```
select value,version1,version2,version3
from
(
select *,row_number() over(partition by value order by version1 desc, version2 desc, version3 desc) as rn
from yourtable
) as t
where rn = 1
``` | select max version over several fields | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
The question is simple, I have two pieces of code and do not understand how they produce different results. In fact, the first piece of code in some instances produces over twice as many results as the second piece of code. Please help me to understand how these differ, I thought they would perform the same thing.
```... | Your first is like
> paymentterms == '0' || paymentterms == '0.000' && postingdateyear = '2014'
(EDIT 1: Please see the [Operator Precedence](https://docs.oracle.com/cd/E17952_01/refman-5.1-en/operator-precedence.html) reference; note that `&&` is of a higher priority than `||`)
Your first statement will be evaluate... | Comment and other answer are correct, but just thought I'd try to clarify for you:
```
WHERE TRIM(PAYMENTTERMS) IN ('0', '0.000')
AND POSTINGDATEYEAR = '2014'
```
Includes only records with `POSTINGDATEYEAR` of 2014 that also have `PAYMENTTERMS` of either 0/0.0000,
While:
```
WHERE TRIM(PAYMENTTERMS) = '0'
O... | Oracle Riddle, using 'IN' versus using 'Or' | [
"",
"sql",
"oracle",
""
] |
I have a `SELECT` Statement that shows details on Orders.
It uses the below code
```
SELECT Orders.OrderID, Orders.invoiceID, Items.itemName AS 'Item Name', Orders.quantity, DATENAME(mm, Orders.OrderDate) + ' ' + DATENAME(dd, Orders.OrderDate) + ', ' + DATENAME(yyyy, Orders.OrderDate) AS 'Order Date', (Orders.price *... | try this
```
SELECT Orders.OrderID,
Orders.invoiceID,
Items.itemName AS 'Item Name',
Orders.quantity,
DATENAME(mm, Orders.OrderDate) + ' ' + DATENAME(dd, Orders.OrderDate) + ', ' + DATENAME(yyyy, Orders.OrderDate) AS 'Order Date',
'$' + Convert(VARCHAR(50), Orders.price * Orders... | You could just explicitly concat it:
```
SELECT Orders.OrderID,
Orders.invoiceID,
Items.itemName AS 'Item Name',
Orders.quantity,
DATENAME(mm, Orders.OrderDate) + ' ' + DATENAME(dd, Orders.OrderDate) + ', ' + DATENAME(yyyy, Orders.OrderDate) AS 'Order Date',
... | Inserting "$" in a SELECT Statement SQL Server | [
"",
"sql",
"sql-server",
""
] |
I Need to generate a random number between two numbers for each row.
For Eg:
select ColName,***(Random nos between 1500 to 2000)*** from TableName
Thanks in advance | ```
DECLARE @start INT
DECLARE @end INT
SET @start = 1500
SET @end = 2000
SELECT Round(( ( @end - @start - 1 ) * Rand() + @start ), 0)
```
**Update :** To get random number for each row.
```
select ABS(Checksum(NewID()) % (@end-@start)) + @start
``` | Random number formula is
**RANDOM DECIMAL RANGE**
```
SELECT RAND()*(b-a)+a;
```
**Example**
```
SELECT RAND()*(25-10)+10; // Random between 10 to 25
```
**RANDOM INTEGER RANGE**
```
SELECT FLOOR(RAND()*(b-a)+a);
```
**Example**
```
SELECT FLOOR(RAND()*(25-10)+10);
``` | Random Number Generation in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"random",
"sql-server-2012",
""
] |
**Query 1**
```
select test_id, count (student_id)*100/
(select count(distinct student_id)from test_taken)as "pass rate"
from test_taken
where result>50
group by test_id;
```
**Query 2**
```
select test_id, count (student_id)*100/
(select count(distinct student_id)from test_taken)as "fail rate"
from test_t... | If the result of the two queries is equal in terms of column numbers and column types, you can use `UNION` to get one table result :
```
SELECT test_id,
COUNT (student_id) * 100 / (SELECT COUNT(DISTINCT student_id)
FROM test_taken)AS rate
FROM test_taken
WHERE result > 50... | ```
SELECT test_id,
sum(case when result > 50 then 1 else 0 end) * 100 / (SELECT COUNT(DISTINCT student_id)
FROM test_taken) AS "pass rate",
sum(case when result < 50 then 1 else 0 end) * 100 / (SELECT COUNT(DISTINCT student_id)
FR... | Combining two queries into one query | [
"",
"sql",
""
] |
I have the following table:
```
select * from [Auction].[dbo].[Bids]
```

I need to select a row with the highest BidValue. When I do
```
SELECT bids.itemId, max(bids.[bidValue]) as HighestBid
FROM [Auction].[dbo].[Bids] bids
WHERE bids.itemId = 2
... | You can simply do:
```
select TOP 1 * from Bids where ItemId = 2 order by BidValue desc
``` | Try this
```
select top 1 * from Bids order by BidValue desc
``` | SQL statement to select only row containing max value in one of the columns | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table `vehicles` with these columns
```
id license_number created_at updated_at pump_number
1 ABC123 2014-10-28 13:43:58.679812 2014-10-28 13:43:58.679812 1
2 XYZ224 2014-10-29 05:24:18.163042 2014-10-29 05:24:18.163042 2
3 AB1111 2014... | I found similar question [here](https://stackoverflow.com/questions/15969614/in-sql-how-to-select-the-top-2-rows-for-each-group). check that for reference.
This should work for you :
```
SELECT *
FROM vehicles t1
WHERE (SELECT Count(*)
FROM vehicles t2
WHERE t1.pump_number = t2.pump_number
... | Below query will return last 2 records for every pump number:
```
select * from (select * from vehicles order by updated_at desc)a group by pump_number
Union
select * from (select * from vehicles order by updated_at desc where id not in
(select id from (select * from vehicles order by updated_at desc) group by p... | Order By and Limit on columns | [
"",
"mysql",
"sql",
"activerecord",
""
] |
I have two tables
Table 1.
```
Name Grade Math
---------------------------
Chris A 30
Julie AA 35
Ross AA 32
```
Table 2
```
Name English
-------------------------
Julie 29
Chris 22
Ross 20
```
I want to get the sum of the scores fo... | Try this,
```
SELECT Sum(B.English) Total
FROM #Table_1 A
JOIN #Table_2 B ON A.Name = B.Name
WHERE Grade = 'AA'
```
If you want the marks separately use this
```
SELECT A.Name,
Sum(B.English) Total
FROM #Table_1 A
JOIN #Table_2 B ON A.Name = B.Name
WHERE Grade = 'AA'
GROUP BY A.Name
``` | Try
```
SELECT SUM(t2.English)
FROM Table1 t1
JOIN Table2 t2
ON t1.Name = t2.Name
WHERE t1.Grade = 'AA'
``` | Extracting Data from two tables in SQL | [
"",
"sql",
"sql-server",
""
] |
I have a table `my_table`:
```
id x_id type
--- ---- ----
1 31 a
2 14 b
3 31 c
4 12 c
5 31 b
6 12 c
7 14 a
```
I want to return all rows where `x_id` has a `type` meeting all elements in the array `arr`.
**Edit: However, the actual values in that array and their number are unknown... | ```
select *
from my_table
where x_id in (select x.x_id
from (select x_id from my_table where type = 'b') x
join (select x_id from my_table where type = 'c') y
on x.x_id = y.x_id)
and type in ('b', 'c')
```
**Fiddle test:** <http://sqlfiddle.com/#!2/f8601/2... | Here's a somewhat ugly way to do it:
```
SELECT * FROM my_table
WHERE x_id IN
(
SELECT x_id FROM
(
SELECT x_id, type
FROM my_table x
WHERE type IN ('b', 'c')
GROUP BY x_id, type
) y
GROUP BY x_id
HAVING COUNT(x_id) = 2
) AND type IN ('b', 'c')
``` | Filter for rows with column condition on an array | [
"",
"mysql",
"sql",
"dynamic-sql",
""
] |
```
;with CTEima(PersonId,IsEmployeeActive)
as
(select count(*)
from custom.viwSSAppsEmpMasterExtended vem
where vem.SupervisorPersonId = @p_PersonId
union all
select CTEima.IsEmployeeActive
from Custom.viwSSAppsEmpMasterExtended vem
join CTEima on CTEima.PersonId = vem.SupervisorPersonId
)
set @v_IsMan... | You can not set values with the `SET` keyword in the `SELECT` statement.
You can either assign the fields from the query to variables in the `SELECT` statement:
```
WITH CTE AS (
/** .. Your Query Here .. **/
)
SELECT
@YourVariable = FieldNameOrSubquery -- In short: Expression
FROM
CTE
```
**In this case all fi... | Replace your last line with this:
```
select @v_IsManager = count(*) from CTEima where IsEmployeeActive = 'Y'
``` | how to assign cte value to variable | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008",
"common-table-expression",
""
] |
I have a data set where 1 column may have 2 different values for each ID. I want to know if there is a way to find out which IDs don't have one of the values.
Here's what a sample of my data set looks like.
```
Object ID | Relate Type
------------------------
1 | P
1 | S
2 | P
... | I came up with this other option. Tell me if this is faster in your case. :)
```
SELECT [obj_id]
FROM [Prim].[dbo].[relations]
GROUP BY [obj_id]
HAVING MAX(CASE WHEN [relate_type] = 'S' THEN 1 ELSE 0 END) = 0
``` | This should work:
```
SELECT *
FROM [Prim].[dbo].[relations] r
WHERE NOT EXISTS(SELECT 1 FROM [Prim].[dbo].[relations]
WHERE [relate_type] = 'S'
AND obj_id = r.obj_id)
``` | SQL Server: How to determine if a value exists for a row | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
SQL Server 2008 r2
I have 2 tables
**Table 1**
```
Col1 Col2 Col3 Col4
123 08 1 1
123 08 1 1
123 08 2 1
```
**Table 2**
```
Col1 Col2 Col3
123 08 6
```
Table 1 is the main column so most of the data comes from this table and it must be a LEFT OUTER JOIN on to Table2 because Table1 has val... | If you do not want to sum across the records, you can add `b.Col3` to the GROUP BY:
```
SELECT
a.Col2,
SUM(a.Col3),
SUM(a.Col4),
b.Col3
FROM
Table 1 a
LEFT OUTER JOIN Table2 b
ON a.col1 = b.col1 AND a.col2 = b.col2
GROUP BY a.Col2, b.Col3
``` | Please try this. This will also take care if you have two records in table2 for same col1 and col2.
```
SELECT
a.Col2,
SUM(a.Col3),
SUM(a.Col4),
MAX(b.Col3) FROM
Table 1 a
LEFT OUTER JOIN (select col1, col2, sum(col3) as col3 from Table2 group by col1, col2) b ON a.col1 = b.col1 AND a.col2 = b.col2
GROUP BY
a.Col2
``... | SQL - One to Many join with left outer join | [
"",
"sql",
"sql-server",
"join",
"sql-server-2008-r2",
""
] |
I am trying to concatenate the results of two of my queries into the same result table and I am not sure how to do this. I tried to play around with the UNION and JOIN operators, but could not figure it out. This is the SQL for the two queries that I want to concatenate. Both individual queries get the results that the... | Just pack multiple Sub-Selects into one statement!
You have two queries which count rows, so they should be written as two queries each with a COUNT(\*) because you count rows, or you should be using a COUNT(item\_num) because you count items and not stores, this will be clearer for the reader.
You then simply select... | Judging from your columns, a UNION is not what you want. A couple of different options would be to use a JOIN or sub query instead. I don't know how all of your data is set up, but this should be close.
```
SELECT s.Store_Num || ': ' || s.Store_Name AS "Store",
COUNT(e.Store_Num) AS "Total Rented", (
... | Add Column From Second Query SQL | [
"",
"sql",
"oracle",
"join",
"union",
""
] |
I've got a database with a SQLServer back end which was migrated from Access and an Access front end. After the migration one problem I keep running into is that autonumbers are not generated until after the record is saved (kind of obvious but Access didn't seem to care). I have a form that opens to create a new recor... | Access databases return + generate the autonumber when the record is dirty. In the case of SQL server + Access you cannot use nor does the form display the autonumber UNTIL record save time.
The simple solution is to thus force a save in the forms data, and then any following/existing code you have will continue to wor... | What you are referring to is the AutoNumber column in Access which is an Identity field in SQL.
The only way to accomplish this functionality in SQL is to insert the record when your form is opening and then use the @@Identity in SQL to retrieve the most recent value.
When your Access application was combined togethe... | VBA Access Need to obtain autonumber before saving new record | [
"",
"sql",
"vba",
"ms-access",
""
] |
I have tables A, B and C. A has many B and C. For A I have 6 B records and half of them are marked as deleted (deleted\_at != null).
When I select with query
```
SELECT a.id, COUNT(b.id)
FROM table_a a
INNER JOIN table_b b ON a.id = b.a_id AND b.deleted_at IS NULL
WHERE a.id = 5;
```
answer is correct (id: 5, count... | As othered have mentioned you can count distinct b IDs here.
However, your problem is quite common when one needs aggregates from various tables. The problems occur, because people join all records and then try to get the aggregates.
For instance:
```
SELECT a.id, SUM(b.value)
FROM table_a a
INNER JOIN table_b b ON... | you could count distinct values
```
SELECT a.id, COUNT(DISTINCT b.id)
FROM table_a a
INNER JOIN table_b b ON a.id = b.a_id AND b.deleted_at IS NULL
INNER JOIN table_c c ON a.id = c.a_id AND c.deleted_at IS NULL
WHERE a.id = 5;
``` | Second inner join doubles count result | [
"",
"mysql",
"sql",
""
] |
if the query :
```
select 1 'id member',2 'material total'
select 1 'id member',4 'cash total'
```
Result:
```
id member material total
----------- --------------
1 2
id member cash total
----------- -----------
1 4
```
I want join that result. Desired Result:
```
id member | material to... | For the given example, the other answer by SonalPM is correct.
However, as a general solution where your data is not *hard coded*, use SQL **JOIN**.
In this case, you can join the two result sets based on `id member`
e.g.
```
SELECT x.id_member, x.mat_total, y.cash_total
FROM
(SELECT 1 `id_member`, 2 `mat_total`)... | Just use a join like this:
```
SELECT a.idm,
a.mat,
b.cash
FROM (SELECT 1 `idm`, 2 `mat`) a
JOIN (SELECT 1 `idm`, 4 `cash`) b ON a.idm = b.idm
``` | How to combine 2 select result with same ID to right in single record | [
"",
"sql",
""
] |
I have a table like this:
```
------------------
sl no | Error type
------------------
1 | err1
------------------
2 | err2
------------------
3 | err1
------------------
4 | err2
------------------
5 | err2
------------------
6 | err3
------------------
```
Result I want:
```
---------------... | This query will perform the `count(*)` per row. I'd query it once, and cross join it to the individual counts:
```
SELECT a.error, a.cnt, 100 * a.cnt / b.total_count AS percentage
FROM (SELECT error, COUNT(*) as cnt
FROM logs
GROUP BY error) a
CROSS JOIN (SELECT COUNT(*) AS tota... | Before you go and try to optimize any query, you should review the execution plan. For example, in MSSQL, the query plan will look something like this:

You can very clearly see two index scans (top and bottom branches to the right of "Nested Loops"). The top branch i... | Optimizing percentage calculation SQL query | [
"",
"mysql",
"sql",
"aggregate-functions",
""
] |
I have a `datetime` like this: `01-Jan-2014 16:30`
How do i search for records which are `between` the following times in any year, month or day:
```
SELECT *
FROM TABLE
WHERE ORDERDATE BETWEEN '01-Jan-2014 16:30' AND '01-Jan-2014 17:00'
``` | A query using `cast` to extract the time from datetime field
```
where cast(ORDERDATE as time) between '16:30' and '17:00'
``` | ```
DECLARE @F time='16:30'
DECLARE @L time='17:00'
SELECT *
FROM TABLE
WHERE cast(ORDERDATE as time) BETWEEN @F AND @L
``` | Searching for records based on time range using SQL | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
How to I can update only one record in a table?
Table:
```
name name1 name2
----------------------------
xx xy xz
xx xx xx
xx xx xx
xx xx xx
xy xx zz
```
Update query:
```
UPDATE table1
SET name2 = '01'
WHERE name1='x... | you can use ROWCOUNT
```
SET ROWCOUNT 1
UPDATE table1
SET name2 = '01'
WHERE name1='xx'
SET ROWCOUNT 0
```
or you can use update top
```
UPDATE TOP (1) table1
SET name2 = '01'
WHERE name1='xx'
``` | ```
UPDATE table1
SET name2 = '01'
WHERE name1='xx'
LIMIT 1;
``` | How to update only one row in a table? | [
"",
"sql",
"sql-server",
"sql-update",
""
] |
I have some data related to customers and the number of transactions they perform every day. I would like to see how many "new" customers do we get each week. The data looks like the following:
```
Custnum Created Revenue
1 2014/10/23 30
4 2014/10/23 20
5 2014/10/23 40
2 2014/10/30 13
3 ... | ### My understanding of your question
I took these statements:
* I would like to see how many "new" customers do we get each week.
* [customers] that have never done business with us in the past
* I want the number of totally new customers for each week
Do you want
```
CustCount Created
2 week1 -... | Sounds like you want to work with a subset of ORDERS that only has each customer's first order date.
```
select
count(custnum),
DATEADD(wk, DATEDIFF(wk, 0, created), 0) as Date
from
(Select custnum, min(created) as created From Orders Group by custnum) o
where created > '2013-01-01'
group by
DATEADD... | Get new customers every week in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I am trying to use my query to find the specific Worker.wname that has none of his relations with the animal.wild is TRUE.
for example from the following table I need to return "Yossi" since he has no row with wild = t
```
wname | type | wild
-------+-----------+------
David | Capricorn | f
David | goat ... | ```
SELECT worker.wname
FROM resposibility
LEFT JOIN worker ON resposibility.wid = worker.wid
LEFT JOIN cage ON resposibility.cno = cage.cno
LEFT JOIN animal ON cage.cno = animal.cno
GROUP BY worker.wname
HAVING sum(case when animal.wild = 't' then 1 else 0 end) = 0
ORDER BY worker.wname
``` | You could also use the [bool\_or](http://www.postgresql.org/docs/9.3/static/functions-aggregate.html) as follow:
```
SELECT worker.wname
FROM resposibility
LEFT JOIN worker ON resposibility.wid = worker.wid
LEFT JOIN cage ON resposibility.cno = cage.cno
LEFT JOIN animal ON cage.cno = animal... | Ignore multiple records in LEFT JOIN query by case | [
"",
"mysql",
"sql",
"postgresql",
"left-join",
""
] |
This is my current SQL query:
```
DECLARE
@FromDate datetime=NULL,
@ToDate datetime=NULL
SET @FromDate = '10/11/2014'
SET @ToDate = '11/11/2014'
SELECT *
FROM
tblUSer
WHERE
((convert(VARCHAR(10), CreatedDate, 103) BETWEEN convert(VARCHAR(10), @FromDate, 103) AND convert(VARCHAR(10), @ToDate, 103))
```
But ... | This worked for me
```
DECLARE
@FromDate datetime=NULL,
@ToDate datetime=NULL
SET @FromDate = '10/11/2014'
SET @ToDate = '11/11/2014'
SELECT *
FROM
tblUSer
WHERE
CreatedDate >= @FromDate AND
CreatedDate <= DATEADD(DAY, 1, @ToDate)
``` | Try this Query:
```
DECLARE @FromDate AS datetime, @ToDate AS datetime
SET @FromDate = '12/12/2008'
SET @ToDate = '12/12/2009'
SELECT *
FROM tblUSer
WHERE CreatedDate BETWEEN @FromDate AND @ToDate
``` | Retrieve dates between two given dates | [
"",
"sql",
"sql-server-2008",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.