2013-06-25 25 views
3

我有以下结构的表中多条记录(这是一个简化版本,只是为了显示这个想法):计数,同时保持一组

name | city 
------------------ 
John | New York 
German | Berlin 
Gans | 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 
German |   1   |  2  | Berlin 
Gans |   1   |  2  | Berlin 
Boris |   2   |  3  | Moscow 
Vasiliy |   1   |  3  | Moscow 

我知道我可以从数据库中取原始数据,并在我的java程序的计算,但是这将是巨大的,使其在一个普通的SQL。

更新:我使用的是mysql,我不能使用over子句。

+0

这是非常相似: http://stackoverflow.com/questions/1503959/how-to-count-occurrences-of-a-column-value-efficiently- in-sql –

回答

3

我到目前为止所做的解决方案是使用子查询与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; 
5
select distinct name 
,  count(*) over (partition by Name) as TotalWithThisName 
,  count(*) over (partition by City) as TotalInThisCity 
,  city 
from YourTable 
+0

我忘了说我正在使用'mysql',我不能使用'over'子句。 – aga

+0

请参阅此处以获取解决方法http://explainextended.com/2009/03/10/analytic-functions-first_value-last_value-lead-lag/ –

相关问题