Case Statement in SQL

Abhilash Pullakanti 41 Reputation points
2022-03-29T14:13:44.367+00:00

Hi Everyone,

i have wrote below case statement in

SELECT OD.OrderID, OD.Quantity,
CASE
WHEN OD.Quantity > 30 THEN 1
WHEN OD.Quantity = 30 THEN 0
ELSE 0
END AS QuantityText,

CASE
WHEN OD.QuantityText = 1, THEN 'A'
ELSE 'B' as AB
FROM OrderDetails OD

When i use OD.QuantityText in second case statement i am receving error

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,454 questions
0 comments No comments
{count} votes

Accepted answer
  1. Olaf Helper 36,001 Reputation points
    2022-03-29T14:18:53.067+00:00

    There are 2 syntax error in your SQL, a comma after =1 and a missing END.

    And you can not use a calculated column in an other calculation in the same SELECT statement, you could e.g. use a CTE like

    ;with cte as
        (SELECT OD.OrderID, OD.Quantity,
         CASE
         WHEN OD.Quantity > 30 THEN 1
         WHEN OD.Quantity = 30 THEN 0
         ELSE 0
         END AS QuantityText
         FROM OrderDetails OD)
    select *,
    CASE
    WHEN cte.QuantityText = 1 THEN 'A'
    ELSE 'B' END as AB
    from cte
    

1 additional answer

Sort by: Most helpful
  1. Tom Cooper 8,451 Reputation points
    2022-03-29T14:45:38.927+00:00

    One way is to use derived table instead of CTE

     select *,
     CASE
     WHEN q.QuantityText = 1 THEN 'A'
     ELSE 'B' END as AB
     from (SELECT OD.OrderID, OD.Quantity,
          CASE
          WHEN OD.Quantity > 30 THEN 1
          WHEN OD.Quantity = 30 THEN 0
          ELSE 0
          END AS QuantityText
          FROM OrderDetails OD) q;
    

    Tom