【问题标题】:Aggregation function && group by聚合函数 && group by
【发布时间】:2014-08-24 05:25:33
【问题描述】:

我有这个 Sql 查询

select U.DisplayName, U.Reputation , nombre = count(B.Id) 
from Badges B, Users U
where U.Location like '%usa%'
and B.UserId = U.Id
group by B.Id

我不明白为什么会出现这个错误

Column 'Users.DisplayName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

  • 出现此错误的原因是什么?
  • 我该如何解决?

【问题讨论】:

  • U.displayname 不在分组列表中
  • 你是什么意思???我把group by B.Id

标签: sql select group-by aggregate-functions


【解决方案1】:

1/ 错误表示'Users.DisplayName' 列未包含在组列表中。意味着SELECTCLause 中的每一列都必须是聚合函数或包含在Groûp by List 中。

GROUP BY子句的形成规则如下:

  • GROUP BY 可以指定任意数量的有效表达式,包括表格的列。
  • 通常GROUP BY 用于指定表中将包含公共数据的列,以便将行“分组”在一起,以便对行集执行某种聚合函数。
  • SELECT 的选择列表中允许的唯一项目包括 GROUP BY 子句是
    • GROUP BY 中指定的表达式
    • 聚合函数
  • GROUP BY 中指定的表达式不必包含在 SELECT 语句的选择列表中

2/尝试在选择列表中包含该列:

select U.DisplayName, U.Reputation , nombre = count(B.Id) 
from Badges B, Users U
where U.Location like '%usa%'
and B.UserId = U.Id
group by U.DisplayName, B.Id

【讨论】:

    【解决方案2】:

    试试这个

    select U.DisplayName, U.Reputation , nombre = count(B.Id) 
    from Badges B, Users U
    where U.Location like '%usa%'
    and B.UserId = U.Id
    group by U.DisplayName,U.Reputation
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 2013-08-31
      • 2013-12-03
      • 2017-09-16
      相关资源
      最近更新 更多