Friday, January 6, 2012

Grouping set in SQL Server 2008


Aggregation is primary need when you are building reports.  The simple GROUP BY is not sufficient when you are building reports.  The ROLLUP and CUBE are handy features for cumulative aggregates.  These ROLLUP and CUBE are replaced with GROUPING SET in SQL 2008.  

The features like ROLLUP, CUBE exists for backward compatibility, so in if you are in SQL 2008 start using GROUPING SET.  

Instead of explaining GROUPING SET, I just listed set of query and output which is self explanatory. .

Sample Table
EmpId
Yr
Sales
1
2005
12000.00
1
2006
18000.00
1
2007
25000.00
2
2005
15000.00
2
2006
6000.00
SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY EmpId, Yr WITH ROLLUP

OR

SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY ROLLUP(EmpId, Yr)
EmpId
Yr
Sales
1
2005
12000
1
2006
18000
1
2007
25000
1
NULL
55000
2
2005
15000
2
2006
6000
2
NULL
21000
NULL
NULL
76000
SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY EmpId, Yr WITH CUBE

OR

SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY CUBE(EmpId, Yr)
EmpId
Yr
Sales
1
2005
12000
2
2005
15000
NULL
2005
27000
1
2006
18000
2
2006
6000
NULL
2006
24000
1
2007
25000
NULL
2007
25000
NULL
NULL
76000
1
NULL
55000
2
NULL
21000
SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY GROUPING SETS((EmpId, Yr), (EmpId), ())
EmpId
Yr
Sales
1
2005
12000
1
2006
18000
1
2007
25000
1
NULL
55000
2
2005
15000
2
2006
6000
2
NULL
21000
NULL
NULL
76000
SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY GROUPING SETS((EmpId, Yr), (EmpId))
EmpId
Yr
Sales
1
2005
12000
1
2006
18000
1
2007
25000
1
NULL
55000
2
2005
15000
2
2006
6000
2
NULL
21000
SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY GROUPING SETS((EmpId, Yr), (EmpId))
EmpId
Yr
Sales
1
2005
12000
1
2006
18000
1
2007
25000
1
NULL
55000
2
2005
15000
2
2006
6000
2
NULL
21000
SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY GROUPING SETS((EmpId), (Yr))
EmpId
Yr
Sales
NULL
2005
27000
NULL
2006
24000
NULL
2007
25000
1
NULL
55000
2
NULL
21000
SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY GROUPING SETS((EmpId, Yr))
EmpId
Yr
Sales
1
2005
12000
2
2005
15000
1
2006
18000
2
2006
6000
1
2007
25000
SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY GROUPING SETS((EmpId, Yr), (EmpId) )

OR

SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY GROUPING SETS((EmpId), (Yr, EmpId))

EmpId
Yr
Sales
1
2005
12000
1
2006
18000
1
2007
25000
1
NULL
55000
2
2005
15000
2
2006
6000
2
NULL
21000



No comments:

Post a Comment

Teams PowerShell

 The PowerShell helps to get quick meta data around Teams. Install-Module -Name MicrosoftTeams Connect-MicrosoftTeams Get-TeamAllChannel...