Here's the sample table 'test0608':
product_name color amount
Product1 Red 123
Product1 Blue 126
Product2 Blue 103
Product2 Red NULL
Product2 Red 89
Product1 Red 203
I'm trying to find all products with red ones more than blue ones. And here's my code:
select
product_name
,sum(case when color = Blue then 1 else 0 end ) as blue_num
,sum(case when color = Red then 1 else 0 end ) as red_num
,(red_num- blue_num) as difference
from test0608
group by product_name
However, I get the error 'Unknown column 'red_num' and 'blue_num'' which means I CAN'T use the two sums I just calculated in the select statement. Why?