oracle分组函数

1.rollup(a,b)
功能:统计的分组列包括()、(a)和(a,b)
用法:
select earnmonth, area, sum(personincome)  
from earnings  
group by rollup(earnmonth,area);
 
解释:这条语句相当于分组三次
第一次,a,b两个约束条件,即a相同,b也相同的分为同一组;
第二次,只是用a一个条件进行分组,把上一次形成的结果在进行分组,把a相同的分为一组;
第三次,没有约束条件,将整个表数据分为一组;
这样三次之后,我们就有了三个分组条件,那么sum函数,就会给每一个分组都执行一次计算总和。
 
2.cube(a,b)
功能:统计的分组列包括()、(a)、(b)和(a,b)
用法:
select earnmonth, area, sum(personincome)  
from earnings  
group by cube(earnmonth,area)  
order by earnmonth,area nulls last;  --nulls last 是把空值放在最后
 
3.grouping
功能: 在以上例子中,是用rollup和cube函数都会对结果集产生null,这时候可用grouping函数来确认
用法:带一个参数,参数为字段名,结果是根据该字段得出来的就返回1,反之返回0
select decode(grouping(earnmonth),1,'所有月份',earnmonth) 月份,  
    decode(grouping(area),1,'全部地区',area) 地区,  sum(personincome) 总金额  
from earnings  
group by cube(earnmonth,area)  
order by earnmonth,area nulls last;
 
 
 
 
 
posted @ 2021-05-18 20:48  闲云野鹤古刹  阅读(126)  评论(0编辑  收藏  举报