0

我有下表:

Region_id | Region_name
1           Europe
2           Americas
3           Asia
4           Middle East and Africa

这个查询:

SELECT region_id, region_name
  FROM hr.regions
 GROUP BY CUBE(region_id, region_name);

返回:

Region_id | Region_name
(null)      (null)
(null)      Asia
(null)      Europe
(null)      Americas
(null)      Middle East and Africa
1           (null)
1           Europe
2           (null)
2           Americas
3           (null)
3           Asia
4           (null)
4           Middle East and Africa

问题和问题:如何进行另一个返回与上述结果相同但使用联合和相交等 SET 操作而不是 SET 操作的查询group by cube(...)

4

1 回答 1

2

你会使用:

select region_id, region_name
from hr_regions
union all
select NULL as region_id, region_name
from hr_regions
union all
select region_id, NULL as region_name
from hr_regions
union all
select NULL as region_id, NULL as region_name
from dual;

您的示例数据在任一列中都没有重复。所以不需要聚合或select distinct。一个例外是最后一个查询。NULL要仅获取具有两个值的一行,请从 中选择dual

于 2020-05-31T13:53:13.710 回答