计算子组中的记录数,同时保留组中的记录数

aga*_*aga 3 sql grouping group-by

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

name    |  city
------------------
John    | New York
German  | Berlin
Gans    | Berlin
Boris   | Moscow
Boris   | Moscow
Vasiliy | Moscow
Run Code Online (Sandbox Code Playgroud)

我可以group by用来获得每个城市的总人数,如下:

select count(*) from my_table group by city

但是我需要更多一点,我可以"绕过它:我需要在同一个城市中获得同名的所有人,同时保持该城市的总人数.这是结果的样子:

name    | totalWithThisName | totalInThisCity | city
--------------------------------------------------------
John    |         1         |        1        | New York
German  |         1         |        2        | Berlin
Gans    |         1         |        2        | Berlin
Boris   |         2         |        3        | Moscow
Vasiliy |         1         |        3        | Moscow
Run Code Online (Sandbox Code Playgroud)

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

更新:我正在使用mysql,我不能使用over条款.

And*_*mar 5

select  distinct name
,       count(*) over (partition by Name) as TotalWithThisName
,       count(*) over (partition by City) as TotalInThisCity
,       city
from    YourTable
Run Code Online (Sandbox Code Playgroud)


aga*_*aga 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;
Run Code Online (Sandbox Code Playgroud)