为什么我不能在count(*)"column"中使用别名并在having子句中引用它?

And*_*ena 57 sql sql-server alias

我想知道为什么我不能在count(*)中使用别名并在having子句中引用它.例如:

select Store_id as StoreId, count(*) as _count
    from StoreProduct
    group by Store_id
        having _count > 0
Run Code Online (Sandbox Code Playgroud)

不会工作..但如果我删除_count并使用count(*)代替它.

mar*_*ton 94

引用文档通过CodeByMoonlight回答你最近的问题.

在SELECT之前评估HAVING子句 - 因此服务器还不知道该别名.

  1. 首先,形成from子句中所有表的乘积.
  2. 那里,然后条款进行评估,以消除不符合search_condition行.
  3. 接下来,使用group by子句中的列对行进行分组.
  4. 然后,消除不满足having子句中的search_condition的组.
  5. 接下来,将评估select子句目标列表中的表达式.
  6. 如果select子句中存在distinct关键字,则现在会删除重复的行.
  7. 联盟是各个子选择进行评估后作出.
  8. 最后,生成的行根据order by子句中指定的列进行排序.

  • 我要补充一点,评估的顺序是SQL中的逻辑概念.实际上,只要结果与遵循逻辑顺序相同,查询优化器就可以选择不同的操作顺序. (7认同)
  • http://blog.sqlauthority.com/2009/04/06/sql-server-logical-query-processing-phases-order-of-statement-execution/不是真正的问题,但他有一个很好的清单命令sql执行.当然有一个更正式的名单.1. FROM 2. ON 3. OUTER 4. WHERE 5. GROUP BY 6. CUBE | ROLLUP 7. HAVING 8. SELECT 9. DISTINCT 10 ORDER by 11. TOP (3认同)

Sha*_*nce 12

select子句是逻辑上执行的最后一个子句,除了order by.该having子句在select之前发生,因此别名尚不可用.

如果你真的想使用别名,而不是我建议这样做,可以使用内嵌视图来使别名可用:

select StoreId, _count
from (select Store_id as StoreId, count(*) as _count
    from StoreProduct
    group by Store_id) T
where _count > 0
Run Code Online (Sandbox Code Playgroud)

或者在SQL Server 2005及更高版本中,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
Run Code Online (Sandbox Code Playgroud)


Gle*_*ven 5

您可以在 select 子句中使用 count 的别名,但不能在having 语句中使用它,所以这可以工作

select Store_id as StoreId, count(*) as _count
    from StoreProduct
    group by Store_id
        having count(*) > 0
Run Code Online (Sandbox Code Playgroud)