구름조아
윈도우함수 본문
1. 윈도우 함수
- 데이터를 분석하거나 통계적인 계산을 하는 함수로 주로 사용된다.
- 함수 자체를 중첩하여 사용 할 수 없다.
- 복잡하게 구해야 하는 로직을 쉽게 처리 할 수 있게 한다.
순서, 순위 | RANK, DENSE_RANK, ROW_NUMBER |
집계, 계산 | SUM, AVG, COUNT, MAX, MIN |
ROWS, 위치 | FIRST_VALUE, LAST_VALUE, LAG, LEAD |
백분율, 비율 | CUME_DIST, RATIO_TO_REPORT, PERCENT_RANK, NTILE |
select class_num ,student_no ,score ,row_number() over (partition by class_num order by score) as class_rank ,dense_rank() over (partition by class_num order by score) as class_rank ,sum(score) over (partition by class_num) as sum_score ,avg(score) over (partition by class_num) as avg_score ,sum(score) over (partition by class_num order by student_no) as sum_score from exam_result; |
2. FIRST_VALUE
- 특정 기준값에 따른 다른 컬럼의 값을 출력.
3. LAG
- 특정 기준값의 순서에 따라서 이전 값이나 이후 값을 출력 할 수 있음.
select class_num ,student_no ,score ,first_value(student_no) over (partition by class_num order by score desc) as high_score ,lag(score, 2) over (partition by class_num order by score) lag_ from exam_result; |
4. PERCENT_RANK
- 기준 파티션 내 순서별 백분율을 계산하여 0~1 사이 값으로 출력.
5. NTILE
- 파라미터 값으로 등분하여 어느 구간에 들어가는지 출력
select class_num ,student_no ,score ,percent_rank() over (partition by class_num order by score desc) as percent_rank ,ntile(3) over (partition by class_num order by score) as ntile; from exam_result; |
6. ROWS 함수
- 특정 값을 기준으로 데이터를 줄 세운 뒤 ROW를 기준으로 연산하여 출력.
7. RANGE 함수
- 특정 값을 기준으로 데이터를 줄 세운 뒤 값의 범위를 기준으로 연산하여 출력.
select class_num , student_no , socre , sum(score) over(order by score rows between current row and 1 following) as rows_ , count(*) over (order by score range between 10 preceding) and 10 following) as range_ from exam_result; |
'SQLD자격증공부 > SQL활용' 카테고리의 다른 글
그룹함수, Rollup, Grouping Sets, Cube (0) | 2023.05.11 |
---|---|
계층형 SQL (0) | 2023.05.11 |
비등가조인, 집합연산자, Union all, Intersect (0) | 2023.05.11 |
서브쿼리, 스칼라 서브쿼리, 인라인뷰, Exsits (0) | 2023.05.11 |
Join, Cross Join, Inner Join, Natural Join, Outer Join (0) | 2023.05.09 |