利用GROUPING来做分组汇总
在用SQL时,我们经常会碰到这样的问题,要求分级求合计数,你是不是经常为怎么在一张表里分级统计而烦恼?这里我们可以用GROUPING()函数来解决该问题。 下面用实际的例子来说明,例子是一个行政区、单位、销售额的数据表。 注意:在运行这个示例时,注意删掉其中全角的空格,s会造成查询分析器报错。 --创建表并插入数据 Create Table T_SendMoney(StateCode varchar(6),DepCode varchar(6),SendMoney Money) Insert Into T_SendMoney Select '100001','310001',1000 UNION ALL Select '100001','310001',2000 UNION ALL Select '100001','310002',1500 UNION ALL Select '100002','320001',3000 UNION ALL Select '100002','320001',1200 UNION ALL Select '100003','330001',1800 UNION ALL Select '100003','330002',2100 UNION ALL Select '100004','340001',2500 --按GROUPING来实现分级汇总数据 Select CASE WHEN GROUPING(StateCode)=1 THEN 分级合计:' ELSE StateCode END as StateCode ,CASE WHEN GROUPING(DepCode)=1 THEN '总计:' ELSE DepCode END as DepCode ,Sum(SendMoney) AS SendMoney From T_SendMoneyGROUP BY ROLLUP(StateCode,DepCode)
注意 :
不能在 90 兼容模式下使用 CUBE () 和 ROLLUP ()。使用 WITH CUBE、WITH ROLLUP 或 GROUPING SETS 语法。 |
则语句改为
Create Table T_SendMoney(StateCode varchar(6),DepCode varchar(6),SendMoney Money)
Insert Into T_SendMoney Select '100001','310001',1000 UNION ALL
Select '100001','310001',2000 UNION ALL
Select '100001','310002',1500 UNION ALL
Select '100002','320001',3000 UNION ALL
Select '100002','320001',1200 UNION ALL
Select '100003','330001',1800 UNION ALL
Select '100003','330002',2100 UNION ALL
Select '100004','340001',2500
--按GROUPING来实现分级汇总数据
Select CASE WHEN GROUPING(StateCode)=1 THEN '分级合计:' ELSE StateCode END as StateCode
,CASE WHEN GROUPING(DepCode)=1 THEN '总计:' ELSE DepCode END as DepCode ,
Sum(SendMoney) AS SendMoney From T_SendMoney GROUP BY StateCode ,DepCode with ROLLUP
drop table T_SendMoney