Where is the 'Incorrect syntax near 'SUM'' in this SP?

前端 未结 2 957
太阳男子
太阳男子 2021-01-29 01:35

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

相关标签:
2条回答
  • 2021-01-29 01:55

    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

    0 讨论(0)
  • 2021-01-29 02:07

    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.

    0 讨论(0)
提交回复
热议问题