Window Functions

Aggregate Functions with Context
Ranking and Percentiles
Moving Averages and Trends
๐ Mastering SQL Window Functions: Enhance Your Data Analysis Skills! ๐
Are you looking to level up your SQL skills? Let's dive into the powerful world of SQL Window Functions! ๐
SQL Window Functions allow you to perform advanced analytics directly in your SQL queries, providing insights that traditional SQL queries can't easily achieve. Here are a few key benefits and examples:
1๏ธโฃ Aggregate Functions with Context: Window Functions like SUM(), AVG(), and COUNT() can be applied across specific windows of data, giving you aggregated results within partitions or ranges.
SELECT department, employee_name, salary,
SUM(salary) OVER (PARTITION BY department) AS department_total_salary,
AVG(salary) OVER (PARTITION BY department) AS department_avg_salary
FROM employees;
2๏ธโฃ Ranking: Easily rank data using functions like RANK(), DENSE_RANK() and ROW_NUMBER()
SELECT product_id, sales_amount,
RANK() OVER (ORDER BY sales_amount DESC) AS rank,
DENSE_RANK() OVER (ORDER BY sales_amount DESC) AS dense_rank,
ROW_NUMBER() OVER (ORDER BY sales_amount DESC) AS row_number
FROM sales_table;
3๏ธโฃ Moving Averages and Trends: Analyze trends over time with functions like LAG() and LEAD()
SELECT order_date, sales_amount,
AVG(sales_amount) OVER (ORDER BY order_date ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS moving_avg_sales,
Lag(sales_amount) OVER (ORDER BY sales_amount DESC) AS previous_sales,
Lead(sales_amount) OVER (ORDER BY sales_amount DESC) AS next_sales
FROM sales_table;
Mastering these functions can transform how you analyze data, providing deeper insights and more sophisticated reporting capabilities. ๐ก
Are you ready to take your SQL skills to the next level? Share your favorite SQL Window Function examples or ask questions in the comments below! Let's learn and grow together. ๐๐ฌ
Subscribe to my newsletter
Read articles from Shahnawaz Khan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Shahnawaz Khan
Shahnawaz Khan
๐ญ I am Shahnawaz Khan, I did my Bachelor of Technology (B-Tech) in 2018 from Maharashtra Institute of Technology (MIT), Aurangabad. ๐ญ I am Data Analyst with 4+ years of experience in Excel, SQL, Power BI, Power Query, Python, Statistics, Machine Learning, PySpark, Databricks and Snowflake.