SQL Server 2008中的GROUPING SETS的应用实例
DECLARE @t TABLE(student nvarchar(50),class nvarchar(50),grade int)
/*insert some datas*/
INSERT INTO @t
SELECT N'孙小美',N'数学',10 UNION ALL
SELECT N'孙小美',N'语文',20 UNION ALL
SELECT N'孙小美',N'英语',30 UNION ALL
SELECT N'阿土伯',N'数学',40 UNION ALL
SELECT N'阿土伯',N'语文',50 UNION ALL
SELECT N'阿土伯',N'英语',60 UNION ALL
SELECT N'小叮铛',N'数学',70 UNION ALL
SELECT N'小叮铛',N'语文',80 UNION ALL
SELECT N'小叮铛',N'英语',90
SELECT * FROM
(
SELECT
ISNULL(student,'ALL') AS student,
ISNULL(class,'ALL') AS class,
SUM(grade) AS grade
FROM @t
GROUP BY GROUPING SETS((student,class),student,class,())
) AS t
PIVOT
(
MAX(grade) FOR class IN (数学,语文,英语,[ALL])
) AS p
ORDER BY student DESC
/*insert some datas*/
INSERT INTO @t
SELECT N'孙小美',N'数学',10 UNION ALL
SELECT N'孙小美',N'语文',20 UNION ALL
SELECT N'孙小美',N'英语',30 UNION ALL
SELECT N'阿土伯',N'数学',40 UNION ALL
SELECT N'阿土伯',N'语文',50 UNION ALL
SELECT N'阿土伯',N'英语',60 UNION ALL
SELECT N'小叮铛',N'数学',70 UNION ALL
SELECT N'小叮铛',N'语文',80 UNION ALL
SELECT N'小叮铛',N'英语',90
SELECT * FROM
(
SELECT
ISNULL(student,'ALL') AS student,
ISNULL(class,'ALL') AS class,
SUM(grade) AS grade
FROM @t
GROUP BY GROUPING SETS((student,class),student,class,())
) AS t
PIVOT
(
MAX(grade) FOR class IN (数学,语文,英语,[ALL])
) AS p
ORDER BY student DESC