Oracle Reporting 2 - Subtotals and Grand Total

来源:互联网 发布:as3与js交互 编辑:程序博客网 时间:2024/04/30 13:38
Oracle provides rollup, cube, and grouping sets extensions to group to calculate subtotals and grandtotals. Each one fits into different scenarios. To start with, let's take a look at the following query.
select channel_id, sum(amount_sold) amount_soldfrom salesgroup by channel_id;


What if I want the grant total as the last row? 
select decode(grouping(channel_id), 1, 'Grand-Total', to_char(channel_id)) channel_id, sum(amount_sold) amount_soldfrom salesgroup by rollup(channel_id);

In this query, I used grouping() function and rollup extension to group by.
Grouping
Using a single column as its argument, GROUPING returns 1 when it encounters a NULL value created by a ROLLUP or CUBE operation. That is, if the NULL indicates the row is a subtotal, GROUPING returns a 1. Any other type of value, including a stored NULL, returns a 0.
Rollup
ROLLUP enables a SELECT statement to calculate multiple levels of subtotals across a specified group of dimensions. It also calculates a grand total. To further illustrate the rollup extension. Let's examine this query:
select deptno, job, sum(sal)from empgroup by rollup(deptno, job);

In here, there're three levels of aggregations:
Group by deptno, job
Group by deptno
Grand total.
Keep in mind that the order of columns in the group by extension does matter. See:
select deptno, job, sum(sal)from empgroup by rollup(job, deptno);

The aggregations here are - group by job, deptno, group by job and grand total. Now, let's move on to grouping sets. With grouping sets, user is able to specify the aggregation levels.
select deptno, job, sum(sal)from empgroup by grouping sets((job, deptno), (job), (deptno))order by deptno;


The aggreagations here are: group by (job, deptno), group by job, group by deptno. And here's no grand total. Oracle calculates the aggregations specified in the grouping sets extension, no more and no less. 

Finally, let's take a look at cube extension:

select deptno, job, sum(sal)from empgroup by cube(deptno, job)order by deptno;



If user specifies cube, Oracle calculates all possible aggregations. Here, they're group by (job, deptno), group by job, group by deptno and grand total.
0 0
原创粉丝点击