【发布时间】:2019-09-08 13:32:57
【问题描述】:
我在 Oracle 中有一个如下所示的表:
year month customer
------------------------
2011 Jan Smith
2011 Jan Smith
2012 Feb Howard
2013 Feb Howard
...
现在我想变成这样:
year Jan Feb ... Dec ytotal
-----------------------------------------------
2011 3 1 ... 5 27
2012 1 4 ... 11 45
... ...
2018 9 1 ... 1 21
mtotal 35 19 51 275
每个单元格中的数字对应于客户姓名的 DISTINCT 计数。
当我尝试执行此查询时:
SELECT DECODE(GROUPING(year), 1, 'mtotal:', year) year,
DECODE(GROUPING(month), 1, 'ytotal:', month) month,
COUNT(DISTINCT customer) AS cust_count
FROM mytable
GROUP BY ROLLUP(year, month)
我得到这个中间结果:
year month cust_count
--------------------------
2011 Jan 3
2011 Feb 1
...
2011 Dec 5
2011 ytotal 27
2012 Jan 1
2012 Feb 4
...
2012 Dec 11
2012 ytotal 45
...
2018 Jan 9
2018 Feb 1
...
2018 Dec 1
2018 ytotal 21
mtotal ytotal 275
当我将其用作子查询时,请执行枢轴:
SELECT * FROM (
SELECT DECODE(GROUPING(year), 1, 'mtotal:', year) year,
DECODE(GROUPING(month), 1, 'ytotal:', month) month,
COUNT(DISTINCT customer) AS cust_count
FROM mytable
GROUP BY ROLLUP(year, month)
)
PIVOT (
COUNT(month) FOR month IN ('Jan', 'Feb', ..., 'Dec', 'ytotal')
)
我没有得到预期的结果。请在答案中包含 ROLL UP/CUBE 和 PIVOT 的使用。
【问题讨论】:
标签: sql oracle group-by rollup