🧠 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?