accumulate ( 누적, 누계 )

양혜정·2024년 2월 25일

Oracle

목록 보기
13/49

누적(누계)

  • sum(누적되어야할 컬럼명) over(order by 누적되어질 기준이 되는 컬럼명 asc[desc] )
  • sum(누적되어야할 컬럼명) over(partition by 그룹화 되어질 컬럼명 order by 누적되어질 기준이 되는 컬럼명 asc[desc] )

응용

  1. 모든제품에 대한 일별판매량, 일별누적판매량, 일별누적판매량퍼센티지(%)
select jepumname as 제품명
     , to_char(panmaedate,'yyyy-mm-dd') as 판매일자
     , sum(panmaesu) as 일별판매량
     -- sum(누적되어야할 컬럼명) over(
     -- partition by 그룹화 되어질 컬럼명 
     -- order by 누적되어질 기준이 되는 컬럼명 asc[desc] )
     , sum(sum(panmaesu)) over(
        partition by jepumname
        order by to_char(panmaedate,'yyyy-mm-dd') asc) 
        as 일별누적판매량
        
      , to_char(round(
         sum(sum(panmaesu)) over(
         partition by jepumname 
         order by to_char(panmaedate,'yyyy-mm-dd') asc)
    	/ (select sum(panmaesu) 
       	   from tbl_panmae 
           where jepumname = P.jepumname)
       -- tbl_panmae 에서의 jepumname 과 tbl_panmae P 에서 
       -- 그룹핑해서 선택된 jepumname 과 같은 경우
       * 100
       -- 일별누적판매량 / 해당제품에서의 일별누적판매량 * 100
       ,1),'990.0') as "일별누적판매량퍼센티지(%)"
   
    from tbl_panmae P   -- 별칭 P (as 생략 가능)
    group by jepumname, to_char(panmaedate,'yyyy-mm-dd')
    order by 1;
  1. 전체사원수를 연령대별로 인원수를 확인
WITH
V AS
(
SELECT trunc(case when current_year_birthday 
		> to_date(to_char(sysdate,'yyyymmdd'),'yyyymmdd')
            then extract(year from sysdate) - birthyear - 1 
            else extract(year from sysdate) - birthyear
            end, -1) as AGE_LINE
FROM
(
   	select to_date(to_char(sysdate,'yyyy') 
    || substr(jubun,3,4), 'yyyymmdd') 
    as "CURRENT_YEAR_BIRTHDAY" -- 올해생일 
        , case when substr(jubun,7,1) in('1','2') 
        then '19' else '20'
        end || substr(jubun,1,2)  
        as BIRTHYEAR -- 태어난 년도 
    from employees
)
)
SELECT count(age_line) as 전체사원수
        , sum(decode(age_line, 10,1)) as "10대"  
		-- count,sum 모두 가능
		-- sum 은 그룹함수이므로 null 값을 더하지 않는다.
        -- null 값을 0으로 바꾸고 싶을 경우, 
        -- 반드시 sum 을 사용해야 한다. =>(count X)
        , sum(decode(age_line, 20,1,0)) as "20대"    
        , sum(decode(age_line, 30,1)) as "30대"
        , sum(decode(age_line, 40,1)) as "40대"
        , sum(decode(age_line, 50,1)) as "50대"
        , sum(decode(age_line, 60,1)) as "60대"
FROM V;

정리

-> local_hr에서작업한것

0개의 댓글