The select
clause is the last clause to be executed logically, except for order by
. The having
clause happens before select, so the aliases are not available yet.
If you really want to use an alias, not that I'd recommend doing this, an in-line view can be used to make the aliases available:
select StoreId, _count
from (select Store_id as StoreId, count(*) as _count
from StoreProduct
group by Store_id) T
where _count > 0
Or in SQL Server 2005 and above, a CTE:
; with T as (select Store_id as StoreId, count(*) as _count
from StoreProduct
group by Store_id)
select StoreId, _count
from T
where _count > 0