LITTLE BY LITTLE

SQL 예제 (WINDOWING 절) 본문

SQL/데이터 분석을 위한 SQL레시피

SQL 예제 (WINDOWING 절)

위나 2024. 1. 15. 23:42

Q1.
emp 테이블 내 사원 이름, 직업, 월급을 출력하고, 직업 별 사원들의 월급 합계를 높은 순으로 보여주시오.

select ename, job, sal,
	sum(sal) over(partition by job order by sal desc
	range between unbounded preceding and unbounded following) as "직업별 합계"
from emp;

 

select ename, job, sal,
	sum(sal) over(partition by job order by sal desc
	range between unbounded preceding and current row) as "직업별 합계"
from emp;

  unbounded following이었을 때에는, clerk의 직업별 합계 값이 모두 동일하게 job 별로 집계되어 3,050이었던 반면, current row까지로 입력한 결과 직업별 합계가 current row까지 job 별로 집계된 모습


윈도우 함수 - WINDOWING 절

" RANGE BETWEEN ... AND ...."

※ default는 range between unbounded preceding and current row이다.
 

  → range는 집합으로 묶인 그룹을 1개의 행으로 인식


예제 (emp, dept 테이블)

emp table

 
1.rows between .. and ..

-- rows를 이용한 예제
select dept, id, salary,
       sum(salary) over (partition by dept order by id rows between unbounded preceding and current row) col
  from (
          select 20 dept, 100 id, 20000 salary union all
          select 20 dept, 101 id, 30000 salary union all
          select 20 dept, 101 id, 10000 salary union all
          select 20 dept, 102 id,  9000 salary union all
          select 20 dept, 103 id, 17000 salary
       ) D;
rows

 default로 unbounded preceding(1번째 행)부터 current(현재 행)까지 계산된 col 값이 id별로 각각 나오는 모습

 
2.range between .. and .. 

(같은 쿼리 range로만 변경)

range

 

→ order by 로 묶은 id 별로 같은 col 값이 나오는 모습 (묶인 그룹을 1개의 행으로 인식)

 
 
 
참고

https://gent.tistory.com/473

[Oracle] ROWS와 RANGE 차이 및 사용법 (WINDOWING 절)

오라클에서 OVER 절에 WINDOWING 절을 처음 사용할 때 ROWS와 RANGE가 어떤 차이점이 있는지 많이 헷갈릴 수 있다. 간단히 설명하면 ROWS는 각 행의 위치고, RANGE는 값의 범위라고 생각하면 된다. 아래의

gent.tistory.com

 

Comments