我想知道为什么我不能在 count(*) 中使用别名并在 having 子句中引用它。例如:
select Store_id as StoreId, count(*) as _count
from StoreProduct
group by Store_id
having _count > 0
行不通。但如果我删除 _count 并改用 count(*) ,它会起作用。
我想知道为什么我不能在 count(*) 中使用别名并在 having 子句中引用它。例如:
select Store_id as StoreId, count(*) as _count
from StoreProduct
group by Store_id
having _count > 0
行不通。但如果我删除 _count 并改用 count(*) ,它会起作用。
请参阅CodeByMoonlight在对您最近的问题的回答中引用的文档。
HAVING 子句在 SELECT 之前评估 - 因此服务器还不知道该别名。
- 首先形成from子句中所有表的乘积。
- 然后评估where子句以消除不满足 search_condition 的行。
- 接下来,使用group by子句中的列对行进行分组。
- 然后,排除有子句中不满足 search_condition 的组。
- 接下来,对select子句目标列表中的表达式求值。
- 如果select 子句中存在distinct关键字,则现在消除重复行。
- 在评估每个子选择后进行并集。
- 最后,根据order by子句中指定的列对结果行进行排序。
该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
您可以在 select 子句中使用 count 的别名,但不能在 having 语句中使用它,所以这会起作用
select Store_id as StoreId, count(*) as _count
from StoreProduct
group by Store_id
having count(*) > 0
字段名称的别名仅用于命名结果中的列,它们永远不能在查询中使用。你也不能这样做:
select Store_id as Asdf
from StoreProduct
where Asdf = 42
但是,您可以安全地count(*)
在这两个地方使用,并且数据库会识别它是相同的值,因此不会计算两次。
这是我的贡献(基于此处发布的代码):
select * from (
SELECT Store_id as StoreId, Count(*) as StoreCount
FROM StoreProduct
group by Store_id
) data
where data.StoreCount > 0
您可以在 SQL 中为聚合使用别名,但这只是为了在结果标题中显示别名。但是,当您想在其中使用聚合函数的条件时,您仍然需要使用聚合,因为它评估的是函数而不是名称。
在 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,永远不会是查询的结果......
可能是因为这就是 sql 定义命名空间的方式。举个例子:
select a as b, b as a
from table
where b = '5'
order by a
a 和 b 指的是什么?设计者只是选择让别名只出现在查询的“外部”。