Skill/postgreSQL

postgreSQL GROUPING SETS

진열사랑 2024. 3. 20. 11:03

출처: https://ga-you-ni.tistory.com/m/238

[postgreSQL] [그룹함수] GROUPING SETS, ROLLUP, CUBE

--8)GROUPING SET절 --여러개의 UNION ALL을 이용한 SQL과 같은 결과를 도출할 수 있다. select C1, C2, 집계함수(C3) from TABLE_NAME group by grouping sets (--grouping set절을 이용하면 한번에 다양한 기준의 컬럼 조합으

ga-you-ni.tistory.com

select
case when grouping(BRAND) = 0 and grouping(SEGMENT) = 0 then '브랜드별+등급별'
when grouping(BRAND) = 0 and grouping(SEGMENT) = 1 then '브랜드별'
when grouping(BRAND) = 1 and grouping(SEGMENT) = 0 then '등급별'
when grouping(BRAND) = 1 and grouping(SEGMENT) = 1 then '전체합계'
else ''
end as "집계기준",
BRAND,
SEGMENT,
SUM(QUANTITY)
from sales s
group by
grouping sets (
(BRAND, SEGMENT),
(BRAND),
(SEGMENT),
()
)
order by BRAND, SEGMENT;