How to use a temp column in the where clause How to use a temp column in the where clause sql sql

How to use a temp column in the where clause


Use HAVING instead:

Select    product_brand,    (CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count  FROM products  GROUP BY product_brand  HAVING brand_count = 1

WHERE is evaluated before the GROUP BY. HAVING is evaluated after.


Because in SQL the columns are first "selected" and then "projected".


You have to use the full clause, so you will need:

Select   product_brand,   (CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count FROM products WHERE   (CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END)  = 1 GROUP BY product_brand

This is the same for any calculated field in any SQL statement .

To simplify:

Select Max(Points) as Highest where Highest > 10

won't work, but:

Select Max(Points) as Highest where Max(Points) > 10

will. It's the same in your case.