2.34 GSTR* (Grouping Sets To Rollup) Grouping Sets를 Rollup으로 변환하라

  • Grouping Sets은 기본적으로 UNION ALL로 변환되나 Rollup으로 변경가능한 경우 Rollup으로 변환한다..
{code:SQLtitle= 예제borderStyle=solid}
select e.department_id, e.job_id, sum(e.salary) avg_sal
from employees e
group by grouping sets((e.department_id, e.job_id), (e.department_id));

============
Plan Table
============




























--

IdOperationNameStartsA-RowsA-TimeBuffersOMem1MemUsed-Mem




























--

0SELECT STATEMENT13200:00:00.017
1SORT GROUP BY ROLLUP13200:00:00.017204820482048 (0)
2TABLE ACCESS FULLEMPLOYEES110700:00:00.017




























--


* Plan상에서 Rollup이 발생하였다.|
| * SQL을 풀어서 확인하면 다음과 같다.
{code:SQL|title= SQL 비교 |borderStyle=solid}
-- Grouping Set을 expand_gset_to_union방식으로 변환
select e.department_id, e.job_id job_id, avg(e.salary) avg_sal
  from employees e
 group by e.department_id, e.job_id
union all
select e.department_id, Null job_id, avg(e.salary) avg_sal
  from employees e
 group by e.department_id;

-- Rollup으로 변환
select e.department_id, e.job_id, avg(e.salary) avg_sal
  from employees e
 group by e.department_id, rollup(job_id);


rollup응용 설명

SELECT A, B, C, SUM(D)
FROM T
GROUP BY C, ROLLUP(A, B)

-->
GROUP BY C, A, B
UNION ALL
GROUP BY C, A
UNION ALL
GROUP BY C, NULL