T-SQL Tutorial

OVER clause


The OVER clause is a powerful feature in SQL Server that allows you to perform calculations across multiple rows or partitions within a result set. The OVER clause is used in conjunction with aggregate functions and window functions to produce complex analytical results.


Syntax

The basic syntax of the OVER clause is as follows:

SELECT column1, column2,
aggregate_function(column3) OVER
(PARTITION BY partition_column ORDER BY order_column ROWS/RANGE BETWEEN start_clause AND end_clause) AS column_alias
FROM table_name

Let's break down the different components of this syntax:

column1, column2, column3 These are the columns you want to include in your query.
aggregate_function(column3) This is the aggregate function you want to apply to column3. Examples of aggregate functions include SUM, COUNT, AVG, MAX, and MIN.
PARTITION BY partition_column This clause allows you to group the rows in your result set into partitions based on a particular column. The aggregate function will be applied separately to each partition.
ORDER BY order_column This clause allows you to specify the order in which the rows should be processed within each partition.
ROWS/RANGE BETWEEN start_clause AND end_clause This clause allows you to specify the range of rows or values to be included in the calculation. The ROWS clause specifies a fixed number of rows, while the RANGE clause specifies a range of values.
column_alias This is the name you want to give to the calculated column in your result set.


Example

Here's an example of how you might use the OVER clause to calculate the running total of sales for each product:

SELECT product_name, sales_date, sales_amount,
SUM(sales_amount) OVER (PARTITION BY product_name ORDER BY sales_date) AS running_total
FROM sales_table

In this example, the SUM function is applied to the sales_amount column, and the result is partitioned by product_name and ordered by sales_date. The running_total column displays the running total of sales for each product, which is the sum of the sales amounts up to and including the current row.

Overall, the OVER clause is a powerful tool for performing complex analytical calculations in SQL Server. With its ability to partition and order result sets, it allows you to perform sophisticated analyses that would be difficult or impossible with simple aggregate functions.