2013-05-15 166 views
3

我在Oracle 10g的下表彙總基於國家值

Country State/city   No. of males  No. of females 
US   TN     500000     450000 
US   CA     200000     180000 
US   GA     600000     650000 
US   KY     100000     75000 
England Manchester    900000     750000 
England London    1000000     950000 
England Birmingham    250000     200000 
India Delhi     1000000    1000000 
India Mumbai    1000000     900000 
India Chennai    750000     500000 

我想有如下所示的一個輸出。

Country State/city   No. of males  No. of females 
US   TN     500000     450000 
US   CA     200000     180000 
US   GA     600000     650000 
US   KY     100000     75000 
Total       1400000    1370000 
England Manchester    900000     750000 
England London    1000000     950000 
England Birmingham    250000     200000 
Total       2150000    1500000 
India Delhi     1000000    1000000 
India Mumbai    1000000     900000 
India Chennai    750000     500000 
Total       2750000    19500000 

我嘗試使用ROLLUP輸出,但我只在所有行的末尾得到總計。我想計算每個國家的總數。

回答

8

這可以用GROUP BY GROUPING SETS表達來完成:

SELECT 
    country, 
    state, 
    SUM(males) AS males, 
    SUM(females) AS females 
FROM 
    stats 
GROUP BY GROUPING SETS 
    ((country, state), 
     (country), 
    ()       -- bonus: a Grand Total 
    ) ; 

測試在SQL-Fiddle