<!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"/@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.5pt; mso-bidi-font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体; mso-font-kerning:1.0pt;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:595.3pt 841.9pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:42.55pt; mso-footer-margin:49.6pt; mso-paper-source:0; layout-grid:15.6pt;} div.Section1 {page:Section1;} -->
Grouping 的用法:
指示是否聚合 group by 列表中的指定表达式。在结果集中,如果 Grouping 返回 1 ,表示聚合;如果 Grouping 返回 0 ,表示非聚合。如果指定了 Group by ,那么只能用在 Select , Having , Order by 中。
注释:
GROUPING 用于区分标准空值和由 ROLLUP 、 CUBE 或 GROUPING SETS 返回的空值。作为 ROLLUP 、 CUBE 或 GROUPING SETS 操作结果返回的 NULL 是 NULL 的特殊应用。它在结果集内作为列的占位符,表示全体。
举例:
CREATE TABLE tt ( 产地 CHAR ( 8), 水果 CHAR ( 8), 重量 INT )
INSERT tt VALUES ( ' 北方 ' , ' 香蕉 ' , 3)
INSERT tt VALUES ( ' 北方 ' , ' 水蜜桃 ' , 2)
INSERT tt VALUES ( ' 南方 ' , ' 桔子 ' , 3)
INSERT tt VALUES ( ' 北方 ' , ' 水蜜桃 ' , 5)
INSERT tt VALUES ( ' 南方 ' , ' 香蕉 ' , 3)
INSERT tt VALUES ( ' 南方 ' , ' 水蜜桃 ' , 6)
INSERT tt VALUES ( ' 北方 ' , ' 桔子 ' , 8)
select
CASE WHEN ( GROUPING ( 产地 ) = 1) THEN ' 总计 '
ELSE ISNULL ( 产地 , 'UNKNOWN' )
END AS 产地 ,
CASE WHEN ( GROUPING ( 水果 ) = 1) THEN ' 小计 '
ELSE ISNULL ( 水果 , 'UNKNOWN' )
END AS 产地 ,
SUM ( 重量 ) 总重量
FROM TT
GROUP BY 产地 , 水果
WITH ROLLUP
结果:
/************************
北方 桔子 8
北方 水蜜桃 7
北方 香蕉 3
北方 小计 18
南方 桔子 3
南方 水蜜桃 6
南方 香蕉 3
南方 小计 12
总计 小计 30
*************************/