为什么我不能在count(*)“列”中使用别名,并在having子句中引用它?

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

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

不会工作..但它工作,如果我删除_count并使用计数(*)来代替。

请参阅CodeByMoonlight 引用的文档 , 回答 最近的问题 。

HAVING子句在SELECT之前被计算 – 所以服务器还不知道这个别名。

  1. 首先形成from子句中所有表的乘积。
  2. 然后评估where子句以消除不满足search_condition的行。
  3. 接下来,使用group by子句中的列对行进行分组。
  4. 然后,淘汰在having子句中不满足search_condition的组。
  5. 接下来,评估select子句目标列表中的expression式。
  6. 如果在select子句中存在distinct关键字,那么重复行现在被删除。
  7. 在每个子select被评估之后采取联合
  8. 最后,结果行按照order by子句中指定的列进行sorting。

select子句是逻辑上要执行的最后一个子句,除了order byhaving子句发生在select之前,所以别名还没有可用。

如果你真的想使用一个别名,而不是我build议这样做,可以使用一个内联视图使别名可用:

 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子句中使用别名来计数,你不能在having语句中使用它,所以这个工作

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

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

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

 select Store_id as Asdf from StoreProduct where Asdf = 42 

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

在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,永远不会是查询的结果…

这是我的贡献(根据这里张贴的代码):

 select * from ( SELECT Store_id as StoreId, Count(*) as StoreCount FROM StoreProduct group by Store_id ) data where data.StoreCount > 0 

可能是因为这是sql定义名称空间的方式。 拿,例如:

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

a和b是指什么? devise者只是select使别名只出现在查询的“外部”。