PostgreSQL:How 使用 GROUPING SETS、CUBE 和 ROLLUP 进行汇总

PostgreSQL:How to use GROUPING SETS, CUBE, and ROLLUP for summary totals

我在 MySQL 5.6 中编写了以下代码块:

INSERT INTO Totals
SELECT 
  Zone,
  State,
  COUNT(Sponsored),
  COUNT(Enrolled),
  COUNT(PickedUp)
FROM MasterData
GROUP BY Zone, StateName
  WITH ROLLUP;

产生以下总计:

Zone 1        Sponsored Enrolled Picked Up
  Alaska          0        0        0
  Arizona         1        3        1
  California      3        6        0
  Colorado        0        4        2
  Guam            0        0        0
  Hawaii          0        1        0
  (totals)        4        14       3
Zone 2
  Idaho           1        0        0
  Montana         0        1        1
  Nevada          0        0        1
  New Mexico      0        1        4
  North Dakota    4        8        4
  Oregon          0        0        1
  South Dakota    0        1        0
  Utah            0        1        0
  Washington      0        1        1
  Wyoming         0        1        1
  (totals)        5        14       13
  (gr. totals)    9        28       16

我正在迁移到 PostgreSQL 9.5,需要生成这些相同类型的总计。我感觉新实现的(自 9.5 起)GROUPING SETSCUBEROLLUP 函数可能会有所帮助,但我不知道如何使用它们来获得这些结果。据我所知,这些功能应该可以更容易地生成这样的摘要报告。

the documentation:

SELECT
  Zone,
  State,
  COUNT(Sponsored),
  COUNT(Enrolled),
  COUNT(PickedUp)
FROM MasterData
GROUP BY rollup(Zone, State);

  zone  |     state     | sum | sum | sum
--------+---------------+-----+-----+-----
 Zone 1 |  Alaska       |   0 |   0 |   0
 Zone 1 |  Arizona      |   1 |   3 |   1
 Zone 1 |  California   |   3 |   6 |   0
 Zone 1 |  Colorado     |   0 |   4 |   2
 Zone 1 |  Guam         |   0 |   0 |   0
 Zone 1 |  Hawaii       |   0 |   1 |   0
 Zone 1 |               |   4 |  14 |   3
 Zone 2 |  Idaho        |   1 |   0 |   0
 Zone 2 |  Montana      |   0 |   1 |   1
 Zone 2 |  Nevada       |   0 |   0 |   1
 Zone 2 |  New Mexico   |   0 |   1 |   4
 Zone 2 |  North Dakota |   4 |   8 |   4
 Zone 2 |  Oregon       |   0 |   0 |   1
 Zone 2 |  South Dakota |   0 |   1 |   0
 Zone 2 |  Utah         |   0 |   1 |   0
 Zone 2 |  Washington   |   0 |   1 |   1
 Zone 2 |  Wyoming      |   0 |   1 |   1
 Zone 2 |               |   5 |  14 |  13
        |               |   9 |  28 |  16
(19 rows)