Can i use 'alias' AS in CASE Statement PostgreSQL

460 views Asked by At
SELECT 
    id
    , quantity
    , unit_price 
    , (antity * unit_price) as price    
CASE
    WHEN quantity * unit_price > 5000 THEN (quantity * unit_price) * 0.2
    WHEN quantity * unit_price > 3000 THEN (quantity * unit_price) * 0.15 
    ELSE null 
END 

AS discount

FROM OrderDetails;

I tried to use the alias price in CASE but it doesn't work. In the above code, I repeated quantity * unit_price 5 times. Do exist any better way to realize this code? Is there way to avoid repetition in the CASE statement?

1

There are 1 answers

0
JohanB On BEST ANSWER

You could use a CTE

WITH CTE as (
SELECT 
    id
    , quantity
    , unit_price,
    (antity * unit_price) as price
FROM OrderDetails
)
SELECT 
    id
    , quantity
    , unit_price 
    , price    
CASE
    WHEN price > 5000 THEN price * 0.2
    WHEN price > 3000 THEN price * 0.15 
    ELSE null 
END 

AS discount

FROM OrderDetails;