67

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

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

行不通。但如果我删除 _count 并改用 count(*) ,它会起作用。

4

8 回答 8

104

请参阅CodeByMoonlight在对您最近的问题的回答中引用的文档。

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

  1. 首先形成from子句中所有表的乘积。
  2. 然后评估where子句以消除不满足 search_condition 的行。
  3. 接下来,使用group by子句中的列对行进行分组。
  4. 然后,排除有子句中不满足 search_condition 的组。
  5. 接下来,对select子句目标列表中的表达式求值。
  6. 如果select 子句中存在distinct关键字,则现在消除重复行。
  7. 在评估每个子选择后进行并集。
  8. 最后,根据order by子句中指定的列对结果行进行排序。
于 2010-01-15T00:51:27.067 回答
14

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

或者在 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
于 2010-01-15T00:52:12.107 回答
4

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

select Store_id as StoreId, count(*) as _count
    from StoreProduct
    group by Store_id
        having count(*) > 0
于 2010-01-15T00:50:54.180 回答
2

字段名称的别名仅用于命名结果中的列,它们永远不能在查询中使用。你也不能这样做:

select Store_id as Asdf
from StoreProduct
where Asdf = 42

但是,您可以安全地count(*)在这两个地方使用,并且数据库会识别它是相同的值,因此不会计算两次。

于 2010-01-15T00:55:26.910 回答
1

这是我的贡献(基于此处发布的代码):

select * from (
  SELECT Store_id as StoreId, Count(*) as StoreCount 
  FROM StoreProduct
  group by Store_id
  ) data
where data.StoreCount > 0
于 2017-05-17T00:20:59.097 回答
0

您可以在 SQL 中为聚合使用别名,但这只是为了在结果标题中显示别名。但是,当您想在其中使用聚合函数的条件时,您仍然需要使用聚合,因为它评估的是函数而不是名称。

于 2010-01-15T00:52:08.000 回答
0

在 Hive 0.11.0 及更高版本中,如果 hive.groupby.orderby.position.alias 设置为 true,则可以按位置指定列。

set hive.groupby.orderby.position.alias=true;
select Store_id as StoreId, count(*) as _count
from StoreProduct
group by 1

我不明白你查询的目的。鉴于您发布的查询的上下文,您的条件不是必需的,因为不存在的项目,即计数 0,永远不会是查询的结果......

于 2016-07-28T10:09:17.640 回答
-1

可能是因为这就是 sql 定义命名空间的方式。举个例子:

  select a as b, b as a
    from table
   where b = '5'
order by a

a 和 b 指的是什么?设计者只是选择让别名只出现在查询的“外部”。

于 2010-01-15T00:51:29.623 回答