CUBE
是使用所有可能的组合,与GROUPING SETS
相同。
因此,这个(使用CUBE
)
GROUP BY CUBE (C1, C2, C3, ..., Cn-2, Cn-1, Cn)
使用 GROUPING SETS
,与此相同。
GROUP BY GROUPING SETS (
(C1, C2, C3, ..., Cn-2, Cn-1, Cn) -- All dimensions are included.
,( , C2, C3, ..., Cn-2, Cn-1, Cn) -- n-1 dimensions are included.
,(C1, C3, ..., Cn-2, Cn-1, Cn)
…
,(C1, C2, C3, ..., Cn-2, Cn-1,)
,(C3, ..., Cn-2, Cn-1, Cn) -- n-2 dimensions included
,(C1 ..., Cn-2, Cn-1, Cn)
…
,(C1, C2) -- 2 dimensions are included.
,…
,(C1, Cn)
,…
,(Cn-1, Cn)
,…
,(C1) -- 1 dimension included
,(C2)
,…
,(Cn-1)
,(Cn)
,() ) -- Grand total, 0 dimension is included.
如果您不需要所有组合,应该使用GROUPING SETS
而不是CUBE
。
ROLLUP
和CUBE
运算符生成一些相同的结果集,并执行一些与OLAP应用程序相同的计算。 CUBE
运算符生成可用于交叉制表报告的结果集。 ROLLUP
操作可以计算等效于OLAP维度或层次结构。
单击此处查看Grouping Sets的等效项
更新
我认为这里举个例子会有所帮助。假设您有一个按国家和性别分类的UFO目击次数表格,如下所示:
╔═════════╦═══════╦═════════╗
║ COUNTRY ║ GENDER║
╠═════════╬═══════╬═════════╣
║ USA ║ F ║ 450 ║
║ USA ║ M ║ 1500 ║
║ ITALY ║ F ║ 704 ║
║ ITALY ║ M ║ 720 ║
║ SWEDEN ║ F ║ 317 ║
║ SWEDEN ║ M ║ 310 ║
║ BRAZIL ║ F ║ 144 ║
║ BRAZIL ║ M ║ 159 ║
╚═════════╩═══════╩═════════╝
如果您想了解每个国家的男女总数和总计,那么您应该使用 GROUPING SETS
select Country, Gender, sum(Number_Of_Sights)
from Table1
group by GROUPING SETS((Country), (Gender), ())
order by Country, Gender
SQL Fiddle
要使用GROUP BY
获得相同的结果,您可以使用UNION ALL
:
select Country, NULL Gender, sum(Number_Of_Sights)
from Table1
GROUP BY Country
UNION ALL
select NULL Country, Gender, sum(Number_Of_Sights)
from Table1
GROUP BY GENDER
UNION ALL
SELECT NULL Country, NULL Gender, sum(Number_Of_Sights)
FROM TABLE1
ORDER BY COUNTRY, GENDER
SQL Fiddle
然而,使用CUBE无法获得相同的结果,因为它将返回所有可能性。
现在,如果你想知道所有可能的组合,那么你应该使用CUBE
。