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

解决方法:

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)
上一篇:vue3.0学习笔记(一)


下一篇:rollup函数 和cube函数 的区别?