I get, \"Msg 102, Level 15, State 1, Procedure duckbilledPlatypi, Line 21 Incorrect syntax near \'SUM\'.\" with this MS SQL Server Stored Procedure when I try to execut
Like I said in the comment, you should add a group by
. Others have pointed out you had a missing comma, I added that as well:
Select Description,
@BegDate BegDate,
@Week1End Week1End,
@Week1End Week2Begin,
@EndDate EndDate,
SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Usage ELSE 0 END) Week1Usage,
SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.Usage ELSE 0 END) Week2Usage,
SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END) Week1Price,
SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.Price ELSE 0 END) -
SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Usage ELSE 0 END) UsageVariance,
SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.Usage ELSE 0 END) -
SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END) PriceVariance,
(SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.Usage ELSE 0 END) -
SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END) )
/ SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END) PercentageOfPriceVariance
From InvoiceDetail Ind
Where Ind.Unit = @Unit
AND Ind.InvoiceDate BETWEEN @BegDate AND @EndDate
Group By Description
edit: Apparently the variables in the group by
are wrong
Typo:
SUM(CASE [..snip...][ END) UsageVariance
^--missing comma
which is why you get the syntax error on the SUM
in the next line. you have essentially SUM(...) SUM(...)
which is invalid.