-
Notifications
You must be signed in to change notification settings - Fork 0
/
window_aggregates.sql
61 lines (48 loc) · 1.13 KB
/
window_aggregates.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
USE TestDB
GO
-- Window aggregates 2005 version
-- No PARTITION BY, ORDER BY
SELECT
CustomerID
, OrderID
, MIN(OrderDate) OVER() FirstOrder
, MAX(OrderDate) OVER() LastOrder
, COUNT(*) OVER() OrderCount
, SUM(Freight) OVER() TotalFreightAmount
FROM
Orders
ORDER BY
CustomerID, OrderID
-- With PARTITION BY clause
SELECT
CustomerID
, OrderID
, MIN(OrderDate) OVER(PARTITION BY CustomerID) FirstOrder
, MAX(OrderDate) OVER(PARTITION BY CustomerID) LastOrder
, COUNT(*) OVER(PARTITION BY CustomerID) OrderCount
, SUM(Freight) OVER(PARTITION BY CustomerID) TotalFreightAmount
FROM
Orders
ORDER BY
CustomerID, OrderID
-- Accumulating aggregates. From SQL Server 2012 onwards
SELECT
CustomerID
, OrderID
, OrderDate
, Freight
, SUM(Freight) OVER(PARTITION BY CustomerID ORDER BY OrderID) RunningTotal
FROM
dbo.Orders
-- Adding a frame to the window.
SELECT
YEAR(OrderDate) AS OrderYear
, MONTH(OrderDate) AS OrderMonth
, COUNT(*) AS OrderCount
, AVG(COUNT(*)) OVER(ORDER BY YEAR(OrderDate), MONTH(OrderDate)
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) ThreeMonthAverage
FROM
dbo.Orders
GROUP BY
YEAR(OrderDate)
, MONTH(OrderDate)