🗄️ Databases

Window Function

Window Function

A SQL function that computes an aggregate result for each row within a group while keeping individual rows. Unlike GROUP BY, it does not collapse rows, and calculates within a window (set of rows) defined by the OVER clause.

📖 Detailed Explanation

Window Function is a SQL function that performs calculations on a group of rows while retaining the individual rows. GROUP BY aggregates into one row per group, but a window function preserves all rows and adds a calculated value to each row.

The window is defined through the OVER clause. PARTITION BY divides the rows into groups (optional), and ORDER BY specifies the sort order. In addition, ROWS or RANGE can be used to fine-tune the window frame (the range of rows included in the calculation).

Representative window functions include: ROW_NUMBER (sequential row number), RANK (ties get the same rank, the next rank is skipped), DENSE_RANK (ties get the same rank, the next rank is consecutive), LAG/LEAD (reference the previous/next row value), SUM/AVG/COUNT OVER (cumulative/moving aggregates), FIRST_VALUE/LAST_VALUE (first/last value), and others.

It is essential for analytical tasks such as ranking, running totals, moving averages, row-to-row comparisons, and ratio calculations, and it is also advantageous in terms of performance because complex calculations can be performed with a single table scan without a subquery.

💻 Code Example

-- ============================================
-- 순위 함수: ROW_NUMBER, RANK, DENSE_RANK
-- ============================================

-- ROW_NUMBER: 연속 순번 부여
SELECT
    name,
    department,
    salary,
    ROW_NUMBER() OVER (ORDER BY salary DESC) as overall_rank,
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) as dept_rank
FROM employees;

-- RANK vs DENSE_RANK 비교 (동점 처리)
-- salary: 100, 100, 90 일 때
-- RANK:       1, 1, 3  (동점 후 순위 건너뜀)
-- DENSE_RANK: 1, 1, 2  (동점 후 순위 연속)
SELECT
    name,
    salary,
    RANK() OVER (ORDER BY salary DESC) as rank,
    DENSE_RANK() OVER (ORDER BY salary DESC) as dense_rank
FROM employees;


-- ============================================
-- LAG / LEAD: 이전/다음 행 참조
-- ============================================
SELECT
    order_date,
    revenue,
    LAG(revenue, 1, 0) OVER (ORDER BY order_date) as prev_day,
    revenue - LAG(revenue, 1) OVER (ORDER BY order_date) as daily_change,
    LEAD(revenue, 1) OVER (ORDER BY order_date) as next_day
FROM daily_sales;


-- ============================================
-- 누적 합계 (Running Total)
-- ============================================
SELECT
    order_date,
    amount,
    SUM(amount) OVER (ORDER BY order_date) as running_total,
    SUM(amount) OVER () as grand_total,  -- 전체 합계
    ROUND(amount * 100.0 / SUM(amount) OVER (), 2) as pct_of_total
FROM orders;


-- ============================================
-- 윈도우 프레임: 이동 평균
-- ============================================
SELECT
    order_date,
    amount,
    -- 최근 3일 이동 평균 (현재 행 포함 앞 2행)
    AVG(amount) OVER (
        ORDER BY order_date
        ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
    ) as moving_avg_3days,
    -- 전후 1일 포함 평균
    AVG(amount) OVER (
        ORDER BY order_date
        ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
    ) as centered_avg
FROM daily_sales;
-- ============================================
-- 실무 분석 쿼리 예제
-- ============================================

-- 1. 부서별 Top 3 급여자 추출
WITH ranked AS (
    SELECT
        name,
        department,
        salary,
        DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) as rn
    FROM employees
)
SELECT * FROM ranked WHERE rn <= 3;


-- 2. 고객별 최근 주문 3개
SELECT * FROM (
    SELECT
        customer_id,
        order_id,
        order_date,
        total_amount,
        ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) as rn
    FROM orders
) t WHERE rn <= 3;


-- 3. 월별 매출 + 전월 대비 증감률
SELECT
    DATE_TRUNC('month', order_date) as month,
    SUM(amount) as revenue,
    LAG(SUM(amount)) OVER (ORDER BY DATE_TRUNC('month', order_date)) as prev_month,
    ROUND(
        (SUM(amount) - LAG(SUM(amount)) OVER (ORDER BY DATE_TRUNC('month', order_date)))
        * 100.0 / NULLIF(LAG(SUM(amount)) OVER (ORDER BY DATE_TRUNC('month', order_date)), 0),
        2
    ) as growth_rate_pct
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;


-- 4. 부서별 급여 분포 (본인 vs 부서 평균/최대)
SELECT
    name,
    department,
    salary,
    ROUND(AVG(salary) OVER (PARTITION BY department), 0) as dept_avg,
    MAX(salary) OVER (PARTITION BY department) as dept_max,
    salary - AVG(salary) OVER (PARTITION BY department) as diff_from_avg,
    FIRST_VALUE(name) OVER (PARTITION BY department ORDER BY salary DESC) as top_earner
FROM employees;


-- 5. 제품별 카테고리 내 순위 + 전체 순위
SELECT
    product_name,
    category,
    sales,
    RANK() OVER (PARTITION BY category ORDER BY sales DESC) as category_rank,
    RANK() OVER (ORDER BY sales DESC) as overall_rank,
    NTILE(4) OVER (ORDER BY sales DESC) as quartile  -- 4분위
FROM product_sales;
# pandas에서 윈도우 함수 구현
import pandas as pd

# 샘플 데이터
df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
    'department': ['Sales', 'Sales', 'IT', 'IT', 'IT'],
    'salary': [60000, 55000, 70000, 65000, 70000]
})

# ROW_NUMBER: 그룹별 순번
df['dept_row_num'] = df.groupby('department').cumcount() + 1

# RANK: 그룹별 순위 (동점 시 같은 순위)
df['dept_rank'] = df.groupby('department')['salary'].rank(method='min', ascending=False)

# DENSE_RANK
df['dept_dense_rank'] = df.groupby('department')['salary'].rank(method='dense', ascending=False)

# LAG: 이전 행 값
df_sorted = df.sort_values(['department', 'salary'], ascending=[True, False])
df_sorted['prev_salary'] = df_sorted.groupby('department')['salary'].shift(1)

# 누적 합계 (Running Total)
df['cumsum_salary'] = df.groupby('department')['salary'].cumsum()

# 이동 평균 (Rolling)
sales_data = pd.DataFrame({
    'date': pd.date_range('2024-01-01', periods=10),
    'amount': [100, 120, 90, 110, 130, 100, 140, 120, 150, 130]
})
sales_data['moving_avg_3'] = sales_data['amount'].rolling(window=3).mean()

# 전체 대비 비율
df['pct_of_total'] = df['salary'] / df['salary'].sum() * 100
df['pct_of_dept'] = df['salary'] / df.groupby('department')['salary'].transform('sum') * 100

print("=== 부서별 순위 ===")
print(df[['name', 'department', 'salary', 'dept_rank', 'dept_dense_rank']])

print("\n=== 누적 합계 ===")
print(df[['name', 'department', 'salary', 'cumsum_salary']])

print("\n=== 이동 평균 ===")
print(sales_data[['date', 'amount', 'moving_avg_3']])

🗣️ Say It Like This in Practice

💬 In a Data Analysis Request
"I need to get only the 3 most recent orders for each customer."

"Assign row numbers with ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC), then filter with WHERE rn <= 3. A combination of GROUP BY and LIMIT won't work."
💬 In a Performance Optimization Meeting
"This query is calculating the overall average and the department average separately with two subqueries."

"You can solve it in one go with a window function. AVG(salary) OVER() is the overall average, and AVG(salary) OVER(PARTITION BY dept) is the department average. The table scans drop from 3 to 1."
💬 In a technical interview
"Can you explain the difference between RANK and DENSE_RANK?"

"The difference appears when values are identical. For example, if the scores are 100, 100, 90, RANK gives 1, 1, 3 and DENSE_RANK gives 1, 1, 2. RANK skips as many subsequent ranks as there are ties, while DENSE_RANK assigns consecutive ranks."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions & Best Practices

❌
Cannot be used directly in the WHERE clause

Window functions can only be used in SELECT and ORDER BY. To filter in WHERE, you must wrap them in a subquery or CTE.

❌
Processing large data without PARTITION BY

Without PARTITION BY, the entire data set becomes a single window, which can cause memory usage to spike. Partition appropriately whenever possible.

❌
Watch the default frame

When ORDER BY is specified, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. It may differ from what you intend, so specify it explicitly.

✅
Using indexes

If the columns used in PARTITION BY and ORDER BY have an index, performance improves significantly. It is especially essential for large-scale data.

🔗 Related Terms

📚 Learn More