본문 바로가기
카테고리 없음

집계 쿼리 grouping set, rollup, cube

by 인디코더 2020. 2. 18.

select 
       brand
       , segment 
       , sum(quantity)
  from
       sales
group by brand, segment
union all
select 
       brand
       , null
       , sum(quantity)
  from
       sales
group by brand --, segment;
union all
select 
         null
       , segment 
       , sum(quantity)
  from
       sales
group by segment --brand, ;
union all
select 
       null
       ,null 
       ,sum(quantity)
  from
       sales
;

  select
        brand
        , segment
    from 
        sales
group by
grouping sets
(
(BRAND, SEGMENT)
,brand
,SEGMENT
,()
);

  select
   GROUPING(BRAND) GROUPING_BRAND
   , GROUPING(SEGMENT) GROUPING_SEGMENT
        , brand
        , segment
    from 
        sales
group by
grouping sets
(
(BRAND, SEGMENT)
,brand
,SEGMENT
,()
);

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
 group by 
       grouping sets
       (
         (BRAND, SEGMENT)
         ,(BRAND)
         ,(SEGMENT)
         ,()
       );

--- ROLL UP
select 
BRAND
, SEGMENT
, SUM(QUANTITY)
  from
        SALES
group by 
        rollup (BRAND,segment)
order by 
        BRAND, SEGMENT;
--> 브랜드별, 브랜드|등급별, 브랜드 총 별 이렇게 나뉨 
--> GROUP BY별 합계 + ROLLUP 앞에 컬럼 기준의 합계 + 전체 합계
       
select 
BRAND
, SEGMENT
, SUM(QUANTITY)
  from
        SALES
group by 
        rollup (segment,BRAND)
order by 
        BRAND, SEGMENT;

select 
SEGMENT
        , BRAND
, SUM(QUANTITY)
  from
        SALES
group by SEGMENT,
  rollup (BRAND)
order by 
        BRAND;
    
        
--> 부분 ROLLUP = GROUP BY 별 합계 + 맨 앞에 쓴 컬럼별 합계 + (전체합계X)

       
-- CUBE 절 
select
      SEGMENT,
      BRAND,
      SUM(QUANTITY)
from sales
group by 
CUBE(SEGMENT,BRAND);
-- GROUP BY 절 합계 + BRAND별 + SEGMENT별 + 전체
select
      SEGMENT,
      BRAND,
      SUM(QUANTITY)
from sales
group by 
ROLLUP(SEGMENT,BRAND);
 

select
      SEGMENT,
      BRAND,
      SUM(QUANTITY)
from sales
group by BRAND ,
CUBE(SEGMENT);     
        
select
      SEGMENT,
      BRAND,
      SUM(QUANTITY)
from sales
group by SEGMENT ,
CUBE(BRAND);  

반응형