oracle使用union all的语句只能使用列号来排序

以下两个语句查询结果是一样的,但是前者只能使用列号来排序,性能上,后者高于前者。

select p_org_no,org_type,sort_no,count(*),grouping(p_org_no),grouping(org_type),grouping(sort_no)
from o_org group by p_org_no,org_type,sort_no 
 union all
select p_org_no,null,sort_no,count(*),grouping(p_org_no),1,grouping(sort_no)
from o_org group by p_org_no,sort_no
 union all
select null,org_type,sort_no,count(*),1,grouping(org_type),grouping(sort_no)
from o_org group by org_type,sort_no
 union all 
select null,null,sort_no,count(*),1,1,grouping(sort_no)
from o_org group by sort_no
order by 1,2,3 ;
---结果等价为以下语句:
select p_org_no,org_type,sort_no,count(*),grouping(p_org_no),grouping(org_type),grouping(sort_no) 
from o_org group by
grouping sets((p_org_no,org_type,sort_no),(p_org_no,sort_no),(org_type,sort_no),sort_no)
order by p_org_no,org_type,sort_no ;

原文地址:https://www.cnblogs.com/caibird2005/p/1370892.html