【问题标题】:Why group by requires all non aggregate columns为什么 group by 需要所有非聚合列
【发布时间】:2014-02-06 17:46:53
【问题描述】:

在 sql 中,此查询的语法无效:

select country,city, sum(income) from table1 group by country.

因为 group by 需要国家和城市,而不仅仅是国家。 但为什么会这样呢?因为我可能希望结果仅按国家/地区分组。所以在下表中:

country   city            income

canada    toronto          100
canada    montreal          100
us        LA               200
us        NY               300

如果我想输出:

country   city           sum( income)

canada    toronto          200
canada    montreal          200
us        LA               500
us        NY               500

我的 group by 子句应该是什么?

【问题讨论】:

  • group by country, city。但是,如果每个国家/城市组合只有一行,为什么需要汇总数据?
  • 如果我使用按国家、城市分组,那么输出将与输入相同,因为您提到的原因:每个国家/城市组合只有一行

标签: sql group-by


【解决方案1】:

如果您使用的是 Sql Server,您可以这样做

select 
  country,
  city, 
  sum(income) over (partition by country)
from 
  table1 

或者,如果您正在使用另一个数据库,您可以使用子查询

  select 
      t1.country,
      t1.city, 
      (select sum(t2.income) from table1 t2 where t1.country = t2.country)
    from 
      table1 t1

【讨论】:

  • 谢谢。在第二种情况下,我们不需要 group by 子句?
  • @Victor - 不,您不需要 group by 子句,因为您没有汇总结果,您只是“添加”了一个额外的列
  • +1 。 . .我对你理解问题的能力印象深刻。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 2011-02-16
  • 1970-01-01
  • 2016-10-28
  • 1970-01-01
  • 2021-11-07
相关资源
最近更新 更多