A pipeline finished at 6 a.m. The dashboard says sales went up 30% overnight. Good news? Or did the same orders get loaded twice?
Before anyone celebrates, two questions: is anything missing? and is anything counted twice? Both are answered by the same five functions you already know, plus OVER.
Aggregate window functions answer "how much?" while every row stays where it is.
The data health check
| expression | counts | Customers table (5 rows) |
|---|---|---|
| COUNT(*) | rows | 5 |
| COUNT(1) | rows (a constant is never NULL) | 5 |
| COUNT(Score) | non-NULL values | 4: Anna has no score |
| COUNT(Country) | non-NULL values, duplicates included | 5, but only 2 distinct countries |
Missing values: COUNT(*) - COUNT(col) is the number of NULLs. Duplicates: partition by the column that should be unique and count.
SELECT * FROM ( SELECT OrderID, COUNT(*) OVER (PARTITION BY OrderID) AS CheckPK FROM Sales.OrdersArchive ) t WHERE CheckPK > 1;
OrderID CheckPK 4 2 4 2 6 3 6 3 6 3
Same query on Sales.Orders: CheckPK = 1 everywhere (OrderID is a real primary key). The archive has no constraint: 5 rows returned, but only 3 are extra copies. Deleting all 5 would delete the orders. Keeping one per ID is the job of ROW_NUMBER in the next episode.
COUNT(DISTINCT x) OVER (...) is not allowed in SQL Server (Msg 10759) and not in PostgreSQL either. Use a GROUP BY subquery for distinct counts.
Rows are complete and unique. Now: whose share is biggest? →
Completeness (NULLs) and uniqueness (duplicates): two COUNTs that decide whether any total can be trusted.
Part-to-whole, and the zero that lied
SELECT OrderID, Sales, Sales / SUM(Sales) OVER () * 100 AS PctOfTotal FROM Sales.Orders;
OrderID Sales PctOfTotal 1 10 0 8 90 0 <- should be 23.68
Sales is INT. INT / INT is integer division: 10 / 380 = 0, and 0 × 100 = 0. Multiplying by 100 comes too late.
ROUND(CAST(Sales AS FLOAT) / SUM(Sales) OVER () * 100, 2) AS PctOfTotal -- or: Sales * 100.0 / SUM(Sales) OVER ()
OrderID Sales PctOfTotal 1 10 2.63 4 60 15.79 8 90 23.68 ... ... sum = 99.99 (rounding drift, not a bug)
The top 3 orders (8, 4, 10) make up 55% of sales; the smallest 3 make up 12%. That uneven split is what part-to-whole analysis is for, and it's the start of a Pareto / ABC analysis.
Totals and shares done. But averages hide a NULL trap →
Divide decimals, not integers: CAST or * 100.0 before the division.
What does a NULL mean?
Aggregates skip NULLs. Replacing NULL with 0 (COALESCE(Sales, 0)) is a business decision, and it moves some functions but not others:
| Gloves sales 30, 70, ? | AVG | MIN | MAX |
|---|---|---|---|
| ? = NULL (skipped) | 50 | 30 | 70 |
| ? = 0 (COALESCE) | 33 | 0 | 70 |
Same on customers: AVG(Score) = 2500 / 4 = 625, AVG(COALESCE(Score, 0)) = 2500 / 5 = 500. A customer who was never scored and a customer who scored 0 are not the same thing. Decide once, write it down, use it everywhere in the report.
SELECT OrderID, ProductID, Sales, AVG(Sales) OVER (PARTITION BY ProductID) AS AvgProduct, MAX(Sales) OVER (PARTITION BY ProductID) AS MaxProduct, Sales - MIN(Sales) OVER () AS DeviationFromMin FROM Sales.Orders;
ProductID orders AvgProduct Min Max range 101 4 35 10 90 80 <- biggest total, most uneven 102 3 35 15 60 45 104 2 37 (37.5!) 25 50 25 105 1 60 60 60 0 <- 1 order: average isn't reliable
104 shows 37 because AVG on an INT column returns INT in SQL Server. PostgreSQL returns 37.5. Orders above the overall average (38): 4, 6, 8, 10, found with a subquery and WHERE Sales > AvgSales.
One more family of questions: how are we doing over time? →
COALESCE before AVG changes the denominator. Before MIN, it can make a missing value the minimum.
Running, rolling, moving
| frame | question | |
|---|---|---|
| running total | ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW | how much so far? (YTD vs target) |
| rolling total | ROWS BETWEEN 2 PRECEDING AND CURRENT ROW | how are the last 3 periods doing? |
| moving average | AVG + ORDER BY date (+ frame) | what is the smoothed trend? |
SELECT OrderID, ProductID, OrderDate, Sales, AVG(Sales) OVER (PARTITION BY ProductID) AS AvgByProduct, AVG(Sales) OVER (PARTITION BY ProductID ORDER BY OrderDate) AS MovingAvg, AVG(Sales) OVER (PARTITION BY ProductID ORDER BY OrderDate ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS RollingAvg FROM Sales.Orders;
ProductID OrderDate Sales AvgByProduct MovingAvg RollingAvg 101 2025-01-01 10 35 10 15 101 2025-01-10 20 35 15 55 101 2025-02-18 90 35 40 55 101 2025-03-10 20 35 35 20 <- no next order: frame shrinks 102 2025-01-05 15 35 15 22 <- 22.5 truncated 102 2025-02-15 30 35 22 45 102 2025-03-15 60 35 35 60
My mistakes on the way: a trailing comma before FROM (Msg 156) and the same alias used twice. The last MovingAvg of each product equals AvgByProduct: a free correctness check.
ROWS counts rows, not days. If May is missing, "2 preceding" from June reaches back to March.
| how to get a true time window | |
|---|---|
| PostgreSQL | SUM(sales) OVER (ORDER BY order_date RANGE BETWEEN INTERVAL '29 days' PRECEDING AND CURRENT ROW) |
| SQL Server | aggregate to one row per day, fill gaps from a calendar table, then ROWS 29 PRECEDING |
Last level: putting the checks into a pipeline →
Running totals only grow; rolling totals rise and fall. Sort by a real date, make it unique, mind the gaps.
In real data engineering
Post-load tests. Every load should prove two things: key columns are complete (COUNT(*) - COUNT(key) = 0) and keys are unique (MAX(COUNT(*) OVER (PARTITION BY key)) = 1, via a subquery). dbt ships these as not_null and unique tests. The duplicates in OrdersArchive are exactly what a staging table looks like when a source re-sends changed rows.
Reconciliation. COUNT(*) in the target vs the source file is the cheapest check there is. Log it on every run.
Dashboards. YTD lines are running totals per business line; trend lines are moving averages; "% of total" cards are part-to-whole. Computing them in SQL, at the right grain, keeps the Power BI model simple, and the NULL rule documented in one place.
Before you publish a number: no NULL keys, no duplicate keys, row counts match.
Found the duplicates, fixed a division that always returned 0, and learned that a NULL needs a decision, not a default. Next: removing those duplicates and crowning the best, on the podium.
next → ep09c · stand on the podium (soon)
Glossary
All the new words from this episode.
Boss level: quick quiz
No pressure, the cat isn't grading.
// sources
- PostgreSQL docs: Aggregate Functions
- PostgreSQL docs: Window Functions
- Microsoft Learn: SELECT - OVER clause (Transact-SQL)
- Lab data: the SalesDB sample database from the course I followed, run in SQL Server Management Studio.