W
W
WebAnalytics12018-08-08 15:52:04
SQL
WebAnalytics1, 2018-08-08 15:52:04

How to write a SQL query using a variable?

Task: divide the data for today and yesterday into columns. If you use this query without variables, then everything works. Syntax analysis in excel writes "it is necessary to declare a scalar variable @today" although I kind of declared it at the beginning MSSQL 2016 is used

DECLARE @today as Date, @yesterday as Date;
Set @today = convert(date, getdate());
Set @yesterday = convert(date, dateadd(day, -1, getdate()));
SELECT n.Name, o.Created,
Count(DISTINCT(CASE WHEN Status =  'N' And  o.Date = @today Then ID END))  as NewQ,
Count(DISTINCT(CASE WHEN Status =  'N' And  o.Date = @yesterday Then ID END))  as YdNewQ,
Count(DISTINCT(CASE WHEN Status =  'W' And  o.Date = @today Then ID END)) as WaitingQ,
Count(DISTINCT(CASE WHEN Status =  'W' And  o.Date = @yesterday Then ID END)) as YDWaitingQ,
Count(DISTINCT(CASE WHEN Status =  'U' And  o.Date = @today Then ID END))  as ProblemQ,
Count(DISTINCT(CASE WHEN Status =  'U' And  o.Date = @yesterday Then ID END))  as YdProblemQ,
Count(DISTINCT(CASE WHEN Status =  'Z' And  o.Date = @today Then ID END))  as CancelledQ,
Count(DISTINCT(CASE WHEN Status =  'Z' And  o.Date = @yesterday Then ID END))  as YdCancelledQ

FROM Orders i 
LEFT JOIN OrderItems o ON o.OrderID = i.ID
LEFT JOIN NomenclUS m ON m.ID = o.ProductID

WHERE i.Status <> 'Z' AND o.Created >= dateadd(day, -2, getdate())

GROUP BY o.Created, n.CatID, n.CatName
ORDER BY o.Created, n.CatID

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2018-08-08
@WebAnalytics1

Your query is missing the from section, i.e. select with fields and where with conditions, but from which tables
it's all not to choose.
Your variables are declared correctly and if you execute the first three lines of the query, then there will be no errors.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question