본문 바로가기

SQL

[SQL] FIRST_VALUE / LAST_VALUE

FIRST_VALUE

window의 가장 첫번째에 위치한 데이터를 가져온다.

partition by는 생략 가능하지만, order by는 반드시 필요하다.

window절은 생략 가능. 생략시 range between unbounded precding and current row

 

   select empno, ename, deptno, hiredate, sal
        , first_value(sal) over (partition by deptno order by hiredate) as first_hiredate_sal
     from hr.emp;

 

LAST_VALUE

window의 가장 마지막에 위치한 데이터를 가져온다.

window절이 rows between unbounded preceding and unbounded following이 되어야 한다.

partition by는 생략 가능하지만 order by는 반드시 필요하다.

window절은 생략 가능하고, 생략 시 range between unbounded preceding and current row

 

select empno, ename, deptno, hiredate, sal
     , last_value (sal) over (partition by deptno order by hiredate rows between unbounded preceding and unbounded following) as first_hiredate_sal
  from hr.emp;

 

LAST_VALUE사용 시, window절을 없앤 경우?

window절을 없앤 경우에 range between unbounded preceding and current row와 동일한 결과가 나타난다.

 

아래의 쿼리는 원하는 결과 값이 나오지 않았다.

partition by내의 마지막 행의 hiredatesal 값을 가져와야 하는데, 아래의 쿼리는 current rowsal값이 last_value가 되기 때문이다.

그렇기 때문에 반드시 rows between unbounded preceding and unbounded following를 사용해야한다.

   select empno, ename, deptno, hiredate, sal
        , last_value (sal) over (partition by deptno order by hiredate range between unbounded preceding and current row) as first_sal_1
        , last_value (sal) over (partition by deptno order by hiredate) as first_sal_2
     from hr.emp;

 

출처

https://www.inflearn.com/course/%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%B6%84%EC%84%9D-sql-%ED%8E%80%EB%8D%94%EB%A9%98%ED%83%88/dashboard

 

데이터 분석 SQL Fundamentals - 인프런 | 강의

SQL의 핵심 요소에 대한 상세한 강의와 실습을 통해, 여러분이 SQL 분석 전문가로 성장할 수 있도록 흔들리지 않는 뼈대를 만들어 드리겠습니다., SQL 분석 전문가로 되기 위한 첫걸음! 💪상세한

www.inflearn.com