윈도 함수

SQL로 비즈니스 데이터 분석하기

Michel Semaan

Data Scientist

윈도 함수 - 개요

  • 윈도 함수: 현재 행과 관련된 행 집합에 연산을 수행합니다
  • 예시
    • 누적 합계 계산
    • 이전/다음 행의 값 가져오기
SQL로 비즈니스 데이터 분석하기

누적 합계

누적 합계: 변수의 과거 값들을 누적한 합

예시

x    x_rt
---  ----
1    1
2    3
3    6
4    11
5    16
SQL로 비즈니스 데이터 분석하기

등록 누적 합계 - 쿼리

WITH reg_dates AS (
  SELECT
    user_id,
    MIN(order_date) AS reg_date
  FROM orders
  GROUP BY user_id),

registrations AS ( SELECT DATE_TRUNC('month', reg_date) :: DATE AS delivr_month, COUNT(DISTINCT user_id) AS regs FROM reg_dates GROUP BY delivr_month)
SELECT delivr_month, regs, SUM(regs) OVER (ORDER BY delivr_month ASC) AS regs_rt FROM registrations ORDER BY delivr_month ASC LIMIT 3;
SQL로 비즈니스 데이터 분석하기

등록 누적 합계 - 결과

delivr_month  regs  regs_rt
------------  ----  -------
2018-06-01    123    123
2018-07-01    140    263
2018-08-01    157    420
SQL로 비즈니스 데이터 분석하기

지연된 MAU - 쿼리

WITH maus AS (
  SELECT
    DATE_TRUNC('month', order_date) :: DATE AS delivr_month,
    COUNT(DISTINCT user_id) AS mau
  FROM orders
  GROUP BY delivr_month)

SELECT delivr_month, mau, COALESCE( LAG(mau) OVER (ORDER BY delivr_month ASC), 1) AS last_mau FROM maus ORDER BY delivr_month ASC LIMIT 3;
SQL로 비즈니스 데이터 분석하기

지연된 MAU - 결과

delivr_month  mau  last_mau
------------  ---  --------
2018-06-01    123  1
2018-07-01    226  123
2018-08-01    337  226
SQL로 비즈니스 데이터 분석하기

윈도 함수

SQL로 비즈니스 데이터 분석하기

Preparing Video For Download...