代码之家  ›  专栏  ›  技术社区  ›  Chris

具有聚合[重复]的非常基本的SQL脚本

  •  -1
  • Chris  · 技术社区  · 10 年前
    select Customers.cust_id, count(Orders.cust_id)  
    from Customers left outer join Orders  
    on Customers.cust_id=Orders.cust_id  
    group by Customers.cust_id
    

    这将正确显示所有内容。

    select Customers.cust_id, ***Customers.cust_name***, count(Orders.cust_id)  
    from Customers left outer join Orders  
    on Customers.cust_id=Orders.cust_id  
    group by Customers.cust_id  
    

    ,,您的查询不包括指定的表达式“cust_name”作为聚合函数的端口。“

    这是为什么?Customers中的每个cust_id在cust_name中都有一个名称。为什么会收到此错误消息?

    2 回复  |  直到 10 年前
        1
  •  2
  •   Andy G    10 年前

    使用聚合函数时 count() 所有其他字段(未与聚合函数一起使用)必须出现在 Group By 条款


    以下是我对原因的解释:

    聚合函数跨组运行。

    (也就是说,除非未指定组或其他字段,否则默认情况下,它们会在整个记录集中运行。例如, SELECT Sum(Salary) FROM Staff 工程。)

    如果按分组 cust_id 然后它知道输出什么,每个输出一个计数 客户id .但它会用 cust_name 是吗?哪一个 客户_名称 它会,还是应该,为每个人显示 客户id 输出如果有几个 客户_名称 是用于 客户id ? 每行只显示一行 客户id ,那么它旁边应该显示什么名称?它不会假设只有一个 客户_名称 对应于一个 客户id .

    如果有一个 客户_名称 客户id 然后按两者分组将产生相同数量的行(对于 客户id 并提供一致、可靠的行为。

        2
  •  0
  •   Ani Menon    10 年前
    select Customers.cust_id, Customers.cust_name, count(Orders.cust_id)  
    from Customers left outer join Orders  
    on Customers.cust_id=Orders.cust_id  
    group by Customers.cust_id, Customers.cust_name