Grouping

来源:互联网 发布:c输入不定长度的数组 编辑:程序博客网 时间:2024/05/20 18:46

 

<!-- /* 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,表示非聚合。如果指定了Groupby,那么只能用在SelectHavingOrder by中。

注释:

GROUPING用于区分标准空值和由 ROLLUPCUBE GROUPINGSETS 返回的空值。作为ROLLUPCUBE 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

*************************/

原创粉丝点击