Analytical Window Functions & Reporting

Analytical Window Functions & Reporting in Oracle Database: Analytical Functions (also known as Window Functions) compute values over a defined group (window)…

Analytical Functions (also known as Window Functions) compute values over a defined group (window) of rows without collapsing the result set into a single summary row. This makes them indispensable for financial ledgers, moving averages, and comparative analytics.


Ranking Functions: ROW_NUMBER vs RANK vs DENSE_RANK

SELECT 
    product_category,
    product_name,
    unit_sales,
    -- Strictly unique sequential number (1, 2, 3, 4)
    ROW_NUMBER() OVER (PARTITION BY product_category ORDER BY unit_sales DESC) AS row_num,
    -- Leaves gaps on ties (1, 2, 2, 4)
    RANK() OVER (PARTITION BY product_category ORDER BY unit_sales DESC) AS rnk,
    -- No gaps on ties (1, 2, 2, 3)
    DENSE_RANK() OVER (PARTITION BY product_category ORDER BY unit_sales DESC) AS dense_rnk
FROM product_sales;

Navigational Functions: LAG and LEAD

LAG looks backward into preceding rows, and LEAD looks forward into subsequent rows. Ideal for calculating month-over-month growth:

SELECT 
    fiscal_month,
    revenue,
    -- Fetch previous month revenue with 0 fallback for the first row
    LAG(revenue, 1, 0) OVER (ORDER BY fiscal_month) AS prev_month_rev,
    -- Calculate growth percentage directly
    ROUND(
        (revenue - LAG(revenue, 1, revenue) OVER (ORDER BY fiscal_month)) / 
        NULLIF(LAG(revenue, 1, revenue) OVER (ORDER BY fiscal_month), 0) * 100, 
        2
    ) AS mom_growth_pct
FROM monthly_financials
ORDER BY fiscal_month;

Window Framing: ROWS vs RANGE

The framing clause defines exactly which surrounding rows are included in moving aggregate calculations:

SELECT 
    transaction_date,
    daily_volume,
    -- 7-Day Moving Average (Current row and preceding 6 physical rows)
    AVG(daily_volume) OVER (
        ORDER BY transaction_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS moving_avg_7day,
    
    -- Cumulative Lifetime Revenue
    SUM(daily_volume) OVER (
        ORDER BY transaction_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS cumulative_volume
FROM exchange_telemetry
ORDER BY transaction_date;

String Aggregation with LISTAGG

Oracle provides LISTAGG to aggregate column values from multiple rows into a single delimited string:

SELECT 
    d.department_name,
    COUNT(e.employee_id) AS total_employees,
    LISTAGG(e.first_name || ' ' || e.last_name, ', ') 
        WITHIN GROUP (ORDER BY e.hire_date) AS employee_roster
FROM departments d
JOIN employees e ON d.department_id = e.department_id
GROUP BY d.department_name;

Exercises

  1. Write a query that retrieves the top 3 highest-earning employees in every department using DENSE_RANK() inside a Common Table Expression (CTE).
  2. Calculate a 30-day moving average on daily transaction volumes using ROWS BETWEEN 29 PRECEDING AND CURRENT ROW.
  3. Use LISTAGG with ON OVERFLOW TRUNCATE to safely aggregate comma-separated tag lists without exceeding the 4,000 character limit.