๐Ÿง  Aggregate Window Functions: SUM, COUNT, AVG, MIN, MAX

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.




๐Ÿš€ Aggregate Functions + OVER()

SUM(...)   OVER (...)
COUNT(...) OVER (...)
AVG(...)   OVER (...)
MIN(...)   OVER (...)
MAX(...)   OVER (...)

Each function:

  • Looks across multiple rows
  • Returns a value for each row



๐Ÿ“Š Example: Multiple Metrics per Customer

OrderID CustomerID Amount
1A100
2A150
3B200
4B50

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
1A1002502125100150
2A1502502125100150
3B200250212550200
4B50250212550200

Each row now includes multiple metrics for its customer.




๐Ÿง  Whatโ€™s Happening Here?

PARTITION BY CustomerID creates a group for each customer.

Each function runs across that group:

  • SUM() โ†’ total amount over the partition
  • COUNT() โ†’ number of rows over the partition
  • AVG() โ†’ average value over the partition
  • MIN() โ†’ smallest value over the partition
  • MAX() โ†’ largest value over the partition

The results are attached to every row in the group.




๐Ÿงช Practice What You Just Learned

Average Order Amount Per Customer

For each order, show the average totalamount for that customer using a window function.


Tables Used
orders
ColumnType
orderid bigint
customerid bigint
orderdate timestamp without time zone
totalamount double precision
status text
Expected Output
Column
customerid
orderid
totalamount
avg_order_amount
Write Your Query:



โžก๏ธ Next Step

So far, each function looks at all rows in the group.

Next, youโ€™ll learn how to control which rows are included.




Want to go deeper?