Why can't I use alias in a count(*) “column” and reference it in a having clause?

前端 未结 8 1852
一整个雨季
一整个雨季 2020-11-28 02:46

I was wondering why can\'t I use alias in a count(*) and reference it in the having clause. For instance:

select Store_id as StoreId, count(*) as _count
             


        
8条回答
  •  情深已故
    2020-11-28 03:15

    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
    

提交回复
热议问题