Tuesday, February 02, 2010

T-SQL Group Sets

This is generic way to provide union of the aggregates based on the columns specified in each set in the Grouping set. you can write corresponding statements to replace the specific CUBE and ROLLUP funtion.

You can use Group Sets to understand how CUBE and ROLLUP work.

CUBE Equivalent:

SELECT c1, c2,avg(c3)
from tbl
Group BY
CUBE (c1, c2)

Equals to:
SELECT c1, c2, avg(c3)
from tbl
GROUPING SETS
(
(c1, c2),
(c1),
(c2) ,
()
)

ROLLUP Equivalent:
SELECT c1, c2, avg(c3)
from tbl
Group BY
ROLLUP (c1, c2)

Equals to:
SELECT c1,c2, avg(c3)
from tbl
Group BY
Grouping Sets
(
(C1, C2),
(c1),
()
)

No comments: