PostgreSQL:如何使用GROUPING SETS,CUBE和ROLLUP进行汇总总计

时间:2016-07-18 03:22:35

标签: mysql postgresql group-by rollup

我在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函数可能有所帮助,但我对如何使用它们来获得这些结果毫无头绪。根据我的阅读,这些函数应该可以更容易地生成这样的摘要报告。

1 个答案:

答案 0 :(得分:5)

请参阅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)