So far, Xorthax has been using SUM() with OVER().
But totals arenโt the only useful metric.
You can apply many aggregate functions using the same pattern.
SUM(...) OVER (...)
COUNT(...) OVER (...)
AVG(...) OVER (...)
MIN(...) OVER (...)
MAX(...) OVER (...)
Each function:
| OrderID | CustomerID | Amount |
|---|---|---|
| 1 | A | 100 |
| 2 | A | 150 |
| 3 | B | 200 |
| 4 | B | 50 |
SELECT OrderID, CustomerID, Amount,
SUM(Amount) OVER (PARTITION BY CustomerID) AS Total,
COUNT(*) OVER (PARTITION BY CustomerID) AS OrderCount,
AVG(Amount) OVER (PARTITION BY CustomerID) AS AvgAmount,
MIN(Amount) OVER (PARTITION BY CustomerID) AS MinAmount,
MAX(Amount) OVER (PARTITION BY CustomerID) AS MaxAmount
FROM Orders;
Result:
| OrderID | CustomerID | Amount | Total | OrderCount | AvgAmount | MinAmount | MaxAmount |
|---|---|---|---|---|---|---|---|
| 1 | A | 100 | 250 | 2 | 125 | 100 | 150 |
| 2 | A | 150 | 250 | 2 | 125 | 100 | 150 |
| 3 | B | 200 | 250 | 2 | 125 | 50 | 200 |
| 4 | B | 50 | 250 | 2 | 125 | 50 | 200 |
Each row now includes multiple metrics for its customer.
PARTITION BY CustomerID creates a group for each customer.
Each function runs across that group:
SUM() โ total amount over the partitionCOUNT() โ number of rows over the partitionAVG() โ average value over the partitionMIN() โ smallest value over the partitionMAX() โ largest value over the partitionThe results are attached to every row in the group.
For each order, show the average totalamount for that customer using a window function.
| Column | Type |
|---|---|
| orderid | bigint |
| customerid | bigint |
| orderdate | timestamp without time zone |
| totalamount | double precision |
| status | text |
| Column |
|---|
| customerid |
| orderid |
| totalamount |
| avg_order_amount |
So far, each function looks at all rows in the group.
Next, youโll learn how to control which rows are included.