OVER clause can belong to commands working with so-called Window functions in SQL. These types of functions enable us to look at the data not only in their aggregated form (using GROUP BY), but we can also look at functional operations via multiple other attributes. We, in fact, create windows of some sort and we apply various computational operations above this bordered data. It sounds complicated but an example will later show you how easy it actually is:
We can apply the OVER command on these types of functions
Practical Example OVER (with or without PARTITION BY)
The source will look like this:
-- Database Adventureworks
SELECT c.CustomerKey, SalesOrderNumber, d.CalendarYear, SalesAmount
FROM FactInternetSales a
INNER JOIN DimCustomer c ON a.CustomerKey=c.CustomerKey
INNER JOIN DimDate d ON a.OrderDateKey=d.DateKey
WHERE a.CustomerKey IN (14718, 19383);
We display data for 2 customers [CustomerKey] (number 14718 and 19383). These customers have multiple different orders [SalesOrderNumber] and we earned money for them [SalesAmount].
The task is to write a script that will give us the same result as shown on the screenshot. 7 rows plus 2 columns added:
- [CustomerTotal] – earnings for every customer
- [TotalSales] – total sales
Solution
SELECT
c.CustomerKey
,SalesOrderNumber
,d.CalendarYear
,SalesAmount
,SUM(a.SalesAmount) OVER (PARTITION BY a.CustomerKey) AS Customertotal
,SUM(a.SalesAmount) OVER () AS TotalSales
FROM FactInternetSales a
INNER JOIN DimSalesTerritory b
ON a.SalesTerritoryKey=b.SalesTerritoryKey
INNER JOIN DimCustomer c
ON a.CustomerKey=c.CustomerKey
INNER JOIN DimDate d
ON a.OrderDateKey=d.DateKey
WHERE a.CustomerKey IN (14718, 19383);
Practical example using OVER, PARTITION BY and ROWS BETWEEN command (cumulation)
Let’s try to add one more column [RunningTotal] into the previous task. It will count the accumulation of a given row via customers. It will be done so in a manner wherewith increasing the number of rows will be the value [SalesAmount] added up to the sum of values from previous rows within the same customer.