代码之家  ›  专栏  ›  技术社区  ›  Andre Pena

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

  •  54
  • Andre Pena  · 技术社区  · 15 年前

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

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

    不起作用……但是,如果我删除计数并改用计数(*),它就可以工作。

    8 回复  |  直到 8 年前
        1
  •  88
  •   Community CDub    8 年前

    查看 document referenced 通过 CodeByMoonlight 在一个 answer your recent question .

    HAVING子句在select之前进行了评估,因此服务器还不知道该别名。

    1. 首先是中所有表的乘积 子句已形成。
    2. 这个 在哪里? 然后对子句进行计算,以消除不满足条件的行 搜索条件。
    3. 接下来,使用中的列对行进行分组。 小组通过 条款。
    4. 然后,不满足搜索条件的组 有 条款 被淘汰。
    5. 接下来,中的表达式 选择 子句目标列表为 评价的。
    6. 如果 不同的 关键字存在于select子句中,重复行 现在被淘汰。
    7. 这个 联盟 在评估每个子选择之后进行。
    8. 最后,根据列对结果行进行排序。 在中指定 按顺序 条款。
        2
  •  11
  •   Shannon Severance    15 年前

    这个 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
    
        3
  •  3
  •   Glenn Slaven    15 年前

    您可以在select子句中使用count别名,但不能在having语句中使用它,因此这是可行的。

    select Store_id as StoreId, count(*) as _count
        from StoreProduct
        group by Store_id
            having count(*) > 0
    
        4
  •  0
  •   Jose Chama    15 年前

    您可以在SQL中为聚合使用别名,但这只是为了在结果头中显示别名。但是,当您希望将聚合函数的条件设置为“有”时,仍然需要使用聚合,因为它计算的是函数而不是名称。

        5
  •  0
  •   Guffa    15 年前

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

    select Store_id as Asdf
    from StoreProduct
    where Asdf = 42
    

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

        6
  •  0
  •   rafaelvalle    9 年前

    在配置单元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)永远不会是查询的结果…

        7
  •  0
  •   New Dawg Learning Old Tricks    8 年前

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

    select * from (
      SELECT Store_id as StoreId, Count(*) as StoreCount 
      FROM StoreProduct
      group by Store_id
      ) data
    where data.StoreCount > 0
    
        8
  •  -1
  •   Jimmy    15 年前

    可能是因为这就是SQL定义名称空间的方式。例如:

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

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