【问题标题】:Count number of records in subgroup while keeping a number of records in a group计算子组中的记录数,同时保留组中的许多记录
【发布时间】:2013-06-25 08:22:29
【问题描述】:

我有一个结构如下的表(这是一个简化版本,只是为了展示想法):

name    |  city
------------------
John    | New York
Thomas  | Berlin
Hans    | Berlin
Boris   | Moscow
Boris   | Moscow
Vasiliy | Moscow

我可以使用group by 获取每个城市的总人数,如下所示:

select count(*) from my_table group by city

但我需要更多一点,我无法理解它:我需要在同一个城市获取所有同名的人的数量,同时保持该城市的总人数。结果应该是这样的:

name    | totalWithThisName | totalInThisCity | city
--------------------------------------------------------
John    |         1         |        1        | New York
Thomas  |         1         |        2        | Berlin
Hans    |         1         |        2        | Berlin
Boris   |         2         |        3        | Moscow
Vasiliy |         1         |        3        | Moscow

我知道我可以从 db 中获取原始数据,并在我的 java 程序中进行计算,但是用纯 SQL 进行计算会很棒。

更新:我正在使用mysql,但我不能使用over 子句。

【问题讨论】:

标签: sql group-by grouping


【解决方案1】:
select  distinct name
,       count(*) over (partition by Name) as TotalWithThisName
,       count(*) over (partition by City) as TotalInThisCity
,       city
from    YourTable

【讨论】:

【解决方案2】:

到目前为止我所做的解决方案是使用带有join 的子查询。它看起来像这样:

select
    name,
    city,  
    count(*) as totalWithThisName,
    T.totalInThisCity
from 
    my_table 
    join (select
              count(*) as totalInThisCity,
              city
          from
              my_table
          group by city) T on my_table.city = T.city
group by 
    city, name;

【讨论】:

  • 这是一个旧答案,但我不明白的一件事是分组是在城市名称上完成的,但 T.totalInThisCity 既不聚合也不分组。这是如何工作的。
猜你喜欢
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多