SQLSERVER 使用 ROLLUP 汇总数据,实现分组统计,合计,小计

1、只有一个分类统计列,只需要一个合计。只需要增加with rollup即可

SELECT CASE WHEN GROUPING(GradeName)=1 THEN '合计' ELSE GradeName END AS 年级 ,
      SUM(CASE WHEN Sex=1 THEN 1 ELSE 0 END) AS 男生数,
      SUM(CASE WHEN Sex=0 THEN 1 ELSE 0 END) AS 女生数,
      COUNT(Sex) AS 总数
FROM dbo.Students
GROUP BY GradeName WITH ROLLUP
ORDER BY GradeName DESC

 

2、有多个分类汇总列,只需要一个合计。增加rollup之后,需要使用GROUPING函数判断。

GROUPING函数 指示是否聚合 GROUP BY 列表中的指定列表达式。 在结果集中,如果 GROUPING 返回 1 则指示聚合;返回 0 则指示不聚合。 如果指定了 GROUP BY,则 GROUPING 只能用在 SELECT <select> 列表、HAVING 和 ORDER BY 子句中。

SELECT CASE WHEN GROUPING(GradeName)=1 THEN '合计' ELSE GradeName END AS 年级 ,
        ClassName AS 班级 ,
      SUM(CASE WHEN Sex=1 THEN 1 ELSE 0 END) AS 男生数,
      SUM(CASE WHEN Sex=0 THEN 1 ELSE 0 END) AS 女生数,
      COUNT(Sex) AS 总数
FROM dbo.Students
GROUP BY GradeName,ClassName WITH ROLLUP
HAVING GROUPING(GradeName)=1 OR GROUPING(ClassName)=0
ORDER BY GradeName DESC

 

SELECT CASE WHEN GROUPING(GradeName)=1 THEN '合计' ELSE GradeName END AS 年级 ,
       ClassName AS 班级 ,
       Area AS 地区 ,
      SUM(CASE WHEN Sex=1 THEN 1 ELSE 0 END) AS 男生数,
      SUM(CASE WHEN Sex=0 THEN 1 ELSE 0 END) AS 女生数,
      COUNT(Sex) AS 总数
FROM dbo.Students
GROUP BY GradeName,ClassName,Area WITH ROLLUP
HAVING GROUPING(GradeName)=1 OR (GROUPING(ClassName)=0 AND GROUPING(Area) =0)
ORDER BY GradeName DESC

 3、有多个分类汇总列,需要显示全部的合计和小计。不需要增加判断。

SELECT CASE WHEN GROUPING(GradeName)=1 THEN '合计' ELSE GradeName END AS 年级 ,
       CASE WHEN GROUPING(GradeName)=0 AND GROUPING(ClassName)=1 THEN '小计' ELSE ClassName END AS 班级 ,
      SUM(CASE WHEN Sex=1 THEN 1 ELSE 0 END) AS 男生数,
      SUM(CASE WHEN Sex=0 THEN 1 ELSE 0 END) AS 女生数,
      COUNT(Sex) AS 总数
FROM dbo.Students
GROUP BY GradeName,ClassName WITH ROLLUP
ORDER BY GradeName DESC

  4、有多个分类汇总列,需要显示部分的合计和小计。增加rollup之后,需要增加判断

SELECT CASE WHEN GROUPING(GradeName)=1 THEN '年级合计' ELSE GradeName END AS 年级 ,
       CASE WHEN GROUPING(GradeName)=0 AND GROUPING(ClassName)=1 THEN '班级小计' ELSE ClassName END AS 班级 ,
       CASE WHEN GROUPING(ClassName)=0 AND GROUPING(Area)=1 THEN '地区小计' ELSE Area END AS 地区 ,
      SUM(CASE WHEN Sex=1 THEN 1 ELSE 0 END) AS 男生数,
      SUM(CASE WHEN Sex=0 THEN 1 ELSE 0 END) AS 女生数,
      COUNT(Sex) AS 总数,
      GROUPING(GradeName) AS GradeName_G,
      GROUPING(ClassName) AS ClassName_G,
      GROUPING(Area) AS Area_G
FROM dbo.Students
GROUP BY GradeName,ClassName,Area WITH ROLLUP
HAVING GROUPING(GradeName)=1 OR GROUPING(Area)=0 OR GROUPING(ClassName)=0
ORDER BY GradeName DESC

 

posted @ 2023-10-30 22:59  每天进步多一点  阅读(1742)  评论(0编辑  收藏  举报