sqladvanced
SQL Window Functions for Analytics
Use window functions for running totals, rankings, moving averages, and gap detection in analytics.
sqlPress ⌘/Ctrl + Shift + C to copy
-- Running total
SELECT
date,
revenue,
SUM(revenue) OVER (ORDER BY date) AS running_total
FROM daily_sales;
-- 7-day moving average
SELECT
date,
revenue,
AVG(revenue) OVER (
ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_avg_7d
FROM daily_sales;
-- Rank within partition
SELECT
department, name, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank
FROM employees;
-- Percent of total
SELECT
product,
revenue,
ROUND(100.0 * revenue / SUM(revenue) OVER (), 2) AS pct_of_total
FROM product_sales;
-- Gap detection (find missing dates)
SELECT date, next_date, next_date - date AS gap_days
FROM (
SELECT date, LEAD(date) OVER (ORDER BY date) AS next_date
FROM daily_sales
) t
WHERE next_date - date > 1;Use Cases
- Building cumulative revenue dashboards
- Detecting data gaps in time-series pipelines
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
sqladvanced
SQL Window Functions for Analytics
Advanced SQL window functions for running totals, rankings, moving averages, and gap analysis.
Best for: Building analytics dashboards with running totals
#sql#window-functions
sqlintermediate
SQL Running Totals and Cumulative Metrics
Calculate running totals, cumulative counts, and percent-of-total using window functions and partitions.
Best for: Building cumulative revenue dashboards
#sql#window-functions
pythonadvanced
PySpark Window Functions
Use PySpark window functions for running totals, rank, lag/lead, and percentile computations.
Best for: sales analytics
#pyspark#spark
pythonbeginner
DuckDB In-Memory Analytics
Run fast analytical SQL on pandas DataFrames or Parquet files without a server using DuckDB.
Best for: serverless analytics
#duckdb#analytics