3

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

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子句。

4

2 回答 2

5
select  distinct name
,       count(*) over (partition by Name) as TotalWithThisName
,       count(*) over (partition by City) as TotalInThisCity
,       city
from    YourTable
于 2013-06-25T08:33:30.923 回答
5

到目前为止,我所做的解决方案是将子查询与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;
于 2013-06-25T13:29:16.193 回答