如何在SQL中组合表和聚合结果

时间:2017-01-31 20:33:27

标签: sql ms-access union aggregation

我在一些地区的学校有一份指标表(例如学生人数)。

我需要按地区汇总这些指标,我想在初始表的底部整理这些汇总:

我有:

district    school  students
District1   School1 10
District2   School2 20
District1   School3 30
District2   School4 40
District1   School5 50
District2   School6 60

我想最终进入同一张桌子:

district    school  students
District1   School1 10
District2   School2 20
District1   School3 30
District2   School4 40
District1   School5 50
District2   School6 60
District1   Total   90
District2   Total   120

我试过了

SELECT district, school, students
FROM enrolment
UNION 
SELECT district, "Total" as school, sum(students)
FROM enrolment
GROUP BY district;

但我实际上从许多不同的查询中提取了许多指标,并在另外两个级别(州和国家/地区)进行聚合,所以它非常慢。有没有最有效的方法呢?

1 个答案:

答案 0 :(得分:1)

如果您使用的是SQL-Server,则可以使用ROLLUP

示例数据:

CREATE TABLE #enrolment(district VARCHAR(25)
                  , school   VARCHAR(25)
                  , students INT);

INSERT INTO #enrolment
VALUES
      ('District1'
     , 'School1'
     , 10),
      ('District2'
     , 'School2'
     , 20),
      ('District1'
     , 'School3'
     , 30),
      ('District2'
     , 'School4'
     , 40),
      ('District1'
     , 'School5'
     , 50),
      ('District2'
     , 'School6'
     , 60);

QUERY:

SELECT district
    , ISNULL(school, 'Total') AS school
    , SUM(students) AS students
FROM   #enrolment
GROUP BY ROLLUP(district, school);

结果:

enter image description here