按年份和计数对SQL结果进行分组

时间:2016-05-14 20:06:46

标签: sql oracle count group-by

我有一张包含以下结构的表格:

enter image description here

我想使用以下格式的SQL来检索结果

enter image description here

我是SQL的新手,无法弄清楚如何去做。这可能不使用程序吗?我该如何实现这一目标? (实际数据量很大,我这里只给出了一个快照)

1 个答案:

答案 0 :(得分:1)

部分是旋转。行和列的总计(实际上,甚至是旋转)应该在报表应用程序中完成,而不是在SQL中完成。如果你坚持在SQL中这样做,有更好的方法,但下面的愚蠢查询就足够了。

with test_data (city, yr, ct) as (
        select 'Tokyo' , 2016,  2 from dual union all
        select 'Mumbai', 2013,  3 from dual union all
        select 'Mumbai', 2014,  5 from dual union all
        select 'Dubai' , 2011,  5 from dual union all
        select 'Dubai' , 2015, 15 from dual union all
        select 'Dubai' , 2016,  8 from dual union all
        select 'London', 2011, 16 from dual union all
        select 'London', 2012, 22 from dual union all
        select 'London', 2013,  4 from dual union all
        select 'London', 2014, 24 from dual union all
        select 'London', 2015, 13 from dual union all
        select 'London', 2016,  5 from dual
     ),
     test_with_totals as (
        select          city,   yr, ct       from test_data                  union all
        select          city, 9999, sum(ct)  from test_data   group by city  union all
        select 'Grand Total', yr  , sum(ct)  from test_data   group by yr    union all 
        select 'Grand Total', 9999, sum(ct)  from test_data
     )
select * from test_with_totals
pivot ( sum (ct) for yr in (2011, 2012, 2013, 2014, 2015, 2016, 9999 as "Total"))
order by "Total";

结果:

CITY              2011       2012       2013       2014       2015       2016      Total
----------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
Tokyo                                                                       2          2
Mumbai                                     3          5                                8
Dubai                5                                          15          8         28
London              16         22          4         24         13          5         84
Grand Total         21         22          7         29         28         15        122