윈도우 함수란?
- 행과 행 간의 관계를 정의하기 위해서 제공되는 함수
- 순위, 합계, 평균, 행 위치 등을 조작할 수 있다.
기본 구조
- ARGUMENTS(인수) : 윈도우 함수에 따라 0~N개의 인수를 설정
- Partition by : 그룹화할 기준 Column
- Order by : 정렬할 기준 Column
SELECT window function (ARGUMENTS)
OVER (Prtition by 그룹화_기준_칼럼
Order by 정렬_기준_칼럼)
FROM 테이블명;
특정 기준으로 순위를 매겨주는 기능 : Rank
rank() over (partition by 랭킹 붙여줄 그룹
order by 랭킹을 붙이는 기준 + 오름차순이면 desc 추가)
1. 음식 타입별, 음식점별 주문 건수 집계하기
select cuisine_type,
restaurant_name,
count(1) as order_count
from food_orders
group by 1, 2
--------------------------------------------------
2. Rank 함수 적용하기
select cuisine_type,
restaurant_name,
rank() over (partition by cuisine_type
order by order_count desc) as rn,
order_count
from
(
select cuisine_type,
restaurant_name,
count(1) as order_count
from food_orders
group by 1, 2
) a
--------------------------------------------------
3. 3위까지 조회하고, 음식 타입별, 순위별로 정렬하기
select cuisine_type,
restaurant_name,
order_count,
rn as "순위"
from
(
select cuisine_type,
restaurant_name,
rank() over (partition by cuisine_type
order by order_count desc) as rn,
order_count
from
(
select cuisine_type,
restaurant_name,
count(1) as order_count
from food_orders
group by 1, 2
) a
) b
where rn<=3
order by 1, 4
누적합 혹은 카테고리별 합계를 구하는 기능 : Sum
sum(합하는 컬럼)
over (partition by 랭킹 붙여줄 그룹
order by 랭킹을 붙이는 기준 + 오름차순이면 desc 추가)
1. 음식 타입별, 음식점별 주문 건수 집계하기
select cuisine_type,
restaurant_name,
count(1) as order_count
from food_orders
group by 1, 2
--------------------------------------------------
2. 카테고리별 합, 카테고리별 누적합 구하기
select cuisine_type,
restaurant_name,
order_count,
sum(order_count)
over (partition by cuisine_type) as sum_cuisine_type,
sum(order_count)
over (partition by cuisine_type
order by order_count,
restaurant_name) as cumulative_sum
from
(
select cuisine_type,
restaurant_name,
count(1) as order_count
from food_orders
group by 1, 2
) a
--------------------------------------------------
3. 각 음식점이 차지하는 비율 구하고, 음식점별 주문건수 오름차순으로 정렬하기
select cuisine_type,
restaurant_name,
order_count,
order_count/sum_cuisine_type*100 "음식점의 차지비율",
cumulative_sum "누적합"
from
(
select cuisine_type,
restaurant_name,
order_count,
sum(order_count)
over (partition by cuisine_type) as sum_cuisine_type,
sum(order_count)
over (partition by cuisine_type
order by order_count, restaurant_name) as cumulative_sum
from
(
select cuisine_type,
restaurant_name,
count(1) as order_count
from food_orders
group by 1, 2
) a
) b
order by 1, 5
주의사항
- Group by 구문과 병행하여 사용할 수 없다.
참고사항
- WINDOW 함수의 PARTITION 구문과 GROUP BY 구문은 둘 다 파티션을 분할한다는 의미에서는 유사하다.
- 윈도우 함수로 인해 결과 건수가 줄어들지 않는다.
- sum, max, min 등과 같은 집계 윈도우 함수를 사용할 때 윈도우 절과 함께 사용하면 집계 대상이 되는 레코드 범위를 지정할 수 있다.
참고한 사이트