日期:2014-05-17  浏览次数:20908 次

在oracle数据库中进行分组统计
比如说table   a如下
id   type     num
1       A           1
2       B           2
3       C           5
4       A           3
5       C           2

其中type的值可为{A,B,C,D}
我现在想对table   a进行分组统计,如下
type       sum      
  A             4
  D             0
  B             2
  C             7
 
合计         13

sql语句应该怎么写呢,各位帮帮忙


------解决方案--------------------
select type,sum(num) from temp group by type
union all
select '合计 ' type,sum(num) from
(select sum(num) num from temp group by type)
------解决方案--------------------

select zz.ty as type, sum(zz.nu) num
from (select tt.type ty, nvl(a.num, 0) nu
from A a,
(select 'A ' as type
from dual
union
select 'D ' as type
from dual
union
select 'B ' as type
from dual
union
select 'C ' as type from dual) tt
where a.type = tt.type(+)) zz
group by zz.ty
union
select '合计 ' a.type, sum(a.num) num
from (select sum(a.num) from A a group by a.type);