Wednesday, February 4, 2009

ROLLUP and CUBE operators with GROUP BY clause

ROLLUP operator is used with GROUP BY clause and produces cumulative aggregates, such as subtotals.
Ex:
SQL> select * from sample order by sno;

SNO SNAME SALARY
---------- -------------------- ----------
1 vinay 3000
1 vinay 9000
1 vinay 3000
1 vinay 8000
2 suman 4000
2 suman 2000
2 suman 4000
3 ravi 3000
3 ravi 5000
4 sai 8000
4 sai 2000

SNO SNAME SALARY
---------- -------------------- ----------
5 test 1000
6 sdf 3223

13 rows selected.

SQL> select sno, sname, sum(salary) from sample
where sno<6 style="color: rgb(51, 102, 255);">rollup(sno, sname);

SNO SNAME SUM(SALARY)
---------- -------------------- -----------
1 vinay 20000
1 vinay 3000
1 23000
2 suman 6000
2 suman 4000
2 10000
3 ravi 3000
3 ravi 5000
3 8000
4 sai 2000
4 sai 8000

SNO SNAME SUM(SALARY)
---------- -------------------- -----------
4 10000
5 test 1000
5 1000
52000

15 rows selected.

In the above example, highlighted with
red: indicates a group totaled by both sno and sname
green: indicates a group totaled by sno
blue: indicates grand total

CUBE operator with GROUP BY clause is used to produce cross tabulation values. Can be applied to all aggregate functions (MIN, MAX, SUM, AVG and COUNT). CUBE produces subtotals for all possible combinations of groupings specified in the GROUP BY clause, and a grand total.

Ex:
SQL> select sno, sname, sum(salary) from sample
2 where sno<6 style="color: rgb(51, 51, 255); font-weight: bold;"> 52000
sai 2000
sai 8000
ravi 3000
test 1000
ravi 5000
suman 6000
vinay 20000
suman 4000
vinay 3000
1 23000

SNO SNAME SUM(SALARY)
---------- -------------------- -----------
1 vinay 20000
1 vinay 3000
2 10000
2 suman 6000
2 suman 4000
3 8000
3 ravi 3000
3 ravi 5000
4 10000
4 sai 2000
4 sai 8000

SNO SNAME SUM(SALARY)
---------- -------------------- -----------
5 1000
5 test 1000

In the above example, the highlighted color
blue: indicates grand total
green: indicates rows totaled by 'sname'
red: indicates rows totaled by 'sno' and 'sname'
purple: indicates rows totaled by only 'sno'

No comments:

Post a Comment