Combining Row Updating Case with Alias SQL

时间:2015-07-28 15:51:56

标签: sql sql-server

The query originally worked, but when I added the case statement for user readability for future reports that I want to work on, it ended up breaking.

Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '='.

Something with the o.status's period conflicting with the = sign. I know that this case works because I've used the same exact one in a different query but without the alias. Should I approach this a different way or am I missing something simple?

SELECT 
    o.status = CASE status
                  WHEN 'C' THEN 'Complete'
                  WHEN 'I' THEN 'Paid'
                  WHEN 'N' THEN 'Unpaid'
                  WHEN 'X' THEN 'Cancelled'
               END
    , COUNT(so.salesid) AS 'Number Of Burgers'
    , SUM(so.totalamt) AS 'Amount' 
FROM 
    orders o
INNER JOIN 
    burgerSupply bs ON bs.salesid = o.salesid
GROUP BY 
    so.status

Thanks so much!

1 个答案:

答案 0 :(得分:0)

Just repeat the as:

SELECT (CASE so.status
            WHEN 'C' THEN 'Complete'
            WHEN 'I' THEN 'Paid'
            WHEN 'N' THEN 'Unpaid'
            WHEN 'X' THEN 'Cancelled'
        END) as status,
       COUNT(so.salesid) AS [Number Of Burgers],
       SUM(so.totalamt) AS Amount 
FROM orders o INNER JOIN
     burgerSupply bs
     ON bs.salesid = o.salesid
GROUP BY so.status;

Also, don't use single quotes for column names. Only use single quotes for date and column constants; otherwise, unexpected errors might pop up in your code.