**윈도우함수 OVER(PARTITION BY 그룹을 나눌 칼럼 ORDER BY 정렬 칼럼) AS 별칭**
SUM() OVER(PARTITION BY col ORDER BY col2 ) AS name
윈도우 함수는 크게 탐색함수, 순위함수, 집계분석함수로 나뉨.
SELECT
user_id,
date,
cnt,
LAG(cnt, 2) OVER (PARTITION BY user_id ORDER BY date) AS cnt_lag_2,
LEAD(cnt, 2) OVER (PARTITION BY user_id ORDER BY date) AS lead_cnt_2,
FIRST_VALUE(cnt) OVER (PARTITION BY user_id ORDER BY date) AS first_cnt,
LAST_VALUE(cnt) OVER (PARTITION BY user_id ORDER BY date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_cnt
FROM
your_table;
SELECT
user_id,
score,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY score DESC) AS row_num,
RANK() OVER (PARTITION BY user_id ORDER BY score DESC) AS rank,
DENSE_RANK() OVER (PARTITION BY user_id ORDER BY score DESC) AS dense_rank
FROM
your_table;
SELECT
user_id,
score,
SUM(score) OVER (PARTITION BY user_id ORDER BY date) AS cumulative_score,
AVG(score) OVER (PARTITION BY user_id ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_average,
COUNT(score) OVER (PARTITION BY user_id ORDER BY date) AS cumulative_count,
MIN(score) OVER (PARTITION BY user_id ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS min_score,
MAX(score) OVER (PARTITION BY user_id ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS max_score
FROM
your_dataset.your_table;
SELECT
employee_id,
salary,
SUM(salary) OVER (ORDER BY employee_id
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS running_total
FROM
employees;
2. RANGE
SELECT
order_id,
order_date,
SUM(amount) OVER (ORDER BY order_date
RANGE BETWEEN INTERVAL '1 DAY' PRECEDING AND CURRENT ROW) AS total_sales
FROM
orders;
INTERVAL
은 RANGE절에서 주로 사용됨SELECT
order_id,
order_date,
SUM(order_amount) OVER (
ORDER BY order_date
RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW
) AS weekly_sales
FROM orders;
윈도우 함수로 나온 값을 필터링
WHERE는 데이터 실행 전 필터링 실행.
QUALIFY는 윈도우 함수 사용시 적용되며, 윈도우 함수 결과를 바탕으로 필터링되는 차이점
급여 랭크가 1인 사람 조회하는 예시. RANK를 사용한 윈도우 함수 이후에 QUALIFY문이 실행됨.
SELECT
employee_id,
department_id,
salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rank
FROM employees
QUALIFY salary_rank = 1;