今天很高兴看到了三思兄发的一个总结帖---sql精妙语句总结,令我兴奋的是里面有一句小计总计的语句,关键字是group by grouping sets..........,这是我一直想要找的,不过也有点惭愧,用了这么久oracle,才知道有grouping sets可以设置多个分组,真是孤陋寡闻呀,以后要更努力点。
SQL> SELECT CASE
2 WHEN a.deptno IS NULL THEN
3 '合计'
4 WHEN a.deptno IS NOT NULL AND a.empno IS NULL THEN
5 '小计'
6 ELSE
7 '' || a.deptno
8 END deptno,
9 a.empno,
10 a.ename,
11 SUM(a.sal) total_sal
12 FROM scott.emp a
13 GROUP BY GROUPING SETS((a.deptno),(a.deptno, a.empno, a.ename),());
DEPTNO EMPNO ENAME TOTAL_SAL
---------------------------------------- ----- ---------- ----------
10 7782 CLARK 2450
10 7839 KING 5000
10 7934 MILLER 1300
小计 8750
20 7369 SMITH 800
20 7566 JONES 2975
20 7788 SCOTT 3000
20 7876 ADAMS 1100
20 7902 FORD 3000
小计 10875
30 7900 JAMES 950
30 7499 ALLEN 1600
30 7521 WARD 1250
30 7654 MARTIN 1250
30 7698 BLAKE 2850
30 7844 TURNER 1500
小计 9400
合计 29025
这个语句是三思给的例子。
下面是我自己的测试(对生产单做颜色小计,一张单小结和所有单总计)
select case
when o.ordno is null then
'总计'
when o.ordno is not null and oicl.cl is null and oisz.sz is null then
o.ordno||'总计'
when o.ordno is not null and oicl.cl is not null and oisz.sz is null then
o.ordno|| '颜色小计'
else
o.ordno
end ordno
,oicl.cl,oisz.sz,sum(oitl.qty) qty from ord o,orditm oi,orditmcl oicl,orditmsz oisz,orditmdtl oitl
where o.ordseq=oi.ordseq
and o.ordty='C'
and o.stfg='A'
and oi.ordseq=oicl.ordseq
and oi.itmno= oicl.itmno
and oi.ordseq=oisz.ordseq
and oi.itmno=oisz.itmno
and oicl.ordseq=oitl.ordseq
and oicl.itmno = oitl.itmno
and oicl.clno = oitl.clno
and oisz.ordseq = oitl.ordseq
and oisz.itmno = oitl.itmno
and oisz.szno = oitl.szno
group by grouping sets((o.ordno),(o.ordno,oicl.cl),(o.ordno,oicl.cl,oisz.sz),());
要注意case when,when之间不用','隔开,这是很容易出错的。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/13387766/viewspace-481947/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/13387766/viewspace-481947/