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

标签 sql sql-server alias

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

select Store_id as StoreId, count(*) as _count
    from StoreProduct
    group by Store_id
        having _count > 0

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

最佳答案

请参阅document referenced通过 CodeByMoonlightansweryour recent question .

HAVING 子句在 SELECT 之前计算 - 因此服务器尚不知道该别名。

  1. First the product of all tables in the from clause is formed.
  2. The where clause is then evaluated to eliminate rows that do not satisfy the search_condition.
  3. Next, the rows are grouped using the columns in the group by clause.
  4. Then, Groups that do not satisfy the search_condition in the having clause are eliminated.
  5. Next, the expressions in the select clause target list are evaluated.
  6. If the distinct keyword in present in the select clause, duplicate rows are now eliminated.
  7. The union is taken after each sub-select is evaluated.
  8. Finally, the resulting rows are sorted according to the columns specified in the order by clause.

关于sql - 为什么我不能在 count(*) "column"中使用别名并在having 子句中引用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2068682/

相关文章:

sql-server - 为什么 namespace 定义出现在此查询的内部元素以及外部元素上

sql-server - 有没有一种方法可以在不使用 SQL Server 中的 ComputerName 的情况下连接 LOCALHOST?

sql-server - 加入时使用 select 语句中的列作为函数中的参数

作为别名加入的 sql 不起作用

c# - ExecuteNonQuery:连接属性尚未初始化

iphone - 如何从经度/纬度获取附近的位置?

c++ - C++ 中的别名和引用是一回事吗?

c# - 如何定义命名空间范围的 C# 别名?

sql - TSQL - 通过智能减少记录数量 - 模式(崩溃影响数据)

sql - 如何在 Azure 中设置 SQL 数据库镜像