Window Function SQL
Window Function SQL
Window functions are a powerful concept in SQL that allow you to perform calculations on a set
of rows within a partition or ordered result set. They differ from aggregate functions (like SUM,
COUNT, AVG) in that they can access and process data from multiple rows within a window
defined by you. This enables you to perform more complex calculations and data manipulations
within a single query.
Ranking Functions: Assign a rank or position to each row within a window based on a
specified ordering (e.g., RANK, DENSE_RANK, ROW_NUMBER).
Analytic Functions: Perform calculations on values within a window, often used for
moving averages or cumulative totals (e.g., SUM, AVG, MIN, MAX, LAG, LEAD).
PARTITION BY: Divides the result set into partitions before applying the window
function. Calculations are performed independently within each partition.
ORDER BY: Specifies the ordering of rows within each partition. The order by which
the window function "sees" the data.
Example:
Imagine you have a table sales that tracks product sales for each month. You want to calculate
the average sales for each product, along with the current month's sales for comparison. Here's
how you can achieve this using a window function:
SQL
SELECT
product,
month,
sales,
AVG(sales) OVER (PARTITION BY product) AS average_sales,
SUM(sales) OVER (PARTITION BY product ORDER BY month ROWS BETWEEN CURRENT
ROW AND CURRENT ROW) AS current_month_sales
FROM sales;
Use code with caution.
content_copy
This query calculates the average sales for each product (using AVG) and the current month's sales
for each product (using SUM with the ROWS BETWEEN clause).
Learning Resources:
https://learn.microsoft.com/en-us/sql/t-sql/queries/select-window-transact-sql?view=sql-
server-ver16
https://www.postgresql.org/docs/current/tutorial-window.html
https://www.youtube.com/watch?v=Ww71knvhQ-s (video tutorial)
Remember: Window functions add power and flexibility to your SQL queries. By
understanding their concepts and practicing with various functions, you can unlock new
possibilities for data analysis within your database.