SQL

요약값을 보여주는 cube

에어팟맥스 2022. 7. 7. 17:28

rollup : 합계를 맨 아래에 표시

cube: 합계를 맨 위에 표시

 

----- >>>>> 요약값(rollup, cube, grouping sets) <<<<< ------
  /*
      1. rollup(a,b,c) 은 grouping sets( (a,b,c),(a,b),(a),() ) 와 같다.
    
         group by rollup(department_id, gender) 은
         group by grouping sets( (department_id, gender), (department_id), () ) 와 같다.
  
      2. cube(a,b,c) 은 grouping sets( (a,b,c),(a,b),(b,c),(a,c),(a),(b),(c),() ) 와 같다.
 
         group by cube(department_id, gender) 은
         group by grouping sets( (department_id, gender), (department_id), (gender), () ) 와 같다.
  */

select decode( grouping(department_id), 0, NVL(to_char(department_id), '인턴'), '전체') 부서번호
         , decode( grouping(gender), 0, gender, '전체') 성별
         , count(*) 인원수
         , TO_CHAR( round( count(*)/(select count(*) from employees) * 100 , 1 ), '990.0') 퍼센티지
    from 
    (
        select case when substr(jubun, 7,1) in ('2','4') then '여' else '남' end as GENDER
             , department_id
        from employees
    ) V
    group by CUBE(department_id, gender);
    
    -- 또는
    
    select decode( grouping(department_id), 0, NVL(to_char(department_id), '인턴'), '전체') 부서번호
         , decode( grouping(gender), 0, gender, '전체') 성별
         , count(*) 인원수
         , TO_CHAR( round( count(*)/(select count(*) from employees) * 100 , 1 ), '990.0') 퍼센티지
    from 
    (
        select case when substr(jubun, 7,1) in ('2','4') then '여' else '남' end as GENDER
             , department_id
        from employees
    ) V
    group by GROUPING SETS( (department_id, gender), department_id, gender, () )
    order by 1;
    
    
        /*
    ------------------------------------
    부서번호     성별     인원수    퍼센티지
    ------------------------------------
    인턴		   전체		1	   0.9
	전체		   전체	   107	 100.0
	전체			남		56	   52.3
    ...         ...     ...       ...
    50          남       23       21.5
    50          여       22       20.6
    ...         ...     ...       ...
    
 
 */

 

'SQL' 카테고리의 다른 글

누적(누계)  (0) 2022.07.07
having 그룹함수조건절  (0) 2022.07.07
요약값을 보여주는 rollup, grouping sets  (0) 2022.07.05
그룹 함수 - group by 절  (0) 2022.07.05
그룹 함수(집계 함수)  (0) 2022.07.05