Thursday, October 30, 2008

SQL GROUP BY Functions

GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.
EX:select customer,sum(order) from order group by customer;
This gives the sum of all the orders customer wise.

ROLLUP enables a SQL statement to calculate multiple levels of subtotals across a specified group of dimensions and also calculates a grand total.ROLLUP is a simple extension to the GROUP BY clause.
EX:select deptno,job,count(*),sum(sal) from emp GROUP BY ROLLUP(deptno,job);

CUBE is used with the GROUP BY only.CUBE creates a subtotal of all possible combinations of the set of column in its argument.For GROUP BY CUBE,there will be 2^n sets of totals,where n is the number of columns in the GROUP BY.
EX:select deptno,job,count(*) from emp GROUP BY CUBE(deptno,job);
In the above example,GROUP BY CUBE clause produces a subtotal line for each department number, and calculates a total for each job in each department,a grand total at the end of the query,and a total for each job.

GROUPING returns 1 when it encounters a NULL value created by a ROLLUP or CUBE operation.GROUPING = 0 is a stored NULL not created by ROLLUP or CUBE and GROUPING = 1 is a NULL value created by ROLLUP or CUBE.
EX:select deptno,job,count(*),sum(sal),GROUPING(Job) FROM emp GROUP BY ROLL UP(deptno,job);

GROUP BY GROUPING SETS is an alternative to GROUP BY CUBE.It lets to specify just the combinations of totals you're interested in.It's more efficient because it doesn't have to compute aggregations that are not needed.
Syntax:GROUP BY GROUPING SETS ( (list), (list) ... )where (list) is a list of columns in parentheses,the combination of which is to generate a total.To add a grand total,add (NULL) as one of the grouping sets.

No comments:

Post a Comment

Disclaimer