SQL Quest · episode 09b · world 2 · window saga 2/4

SUM IT
UP

Totals that never forget the details. COUNT, SUM, AVG, MIN and MAX over windows: health checks, shares, comparisons, and running totals.

2026-11-17·15 min read·#sql #window-functions #aggregates #data-quality

the cat counted the rows. twice. (duplicate detected)

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.

level 01COUNT

The data health check

expressioncountsCustomers table (5 rows)
COUNT(*)rows5
COUNT(1)rows (a constant is never NULL)5
COUNT(Score)non-NULL values4: Anna has no score
COUNT(Country)non-NULL values, duplicates included5, 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.

// lab · duplicates in the archive table
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.

// gotcha · COUNT(DISTINCT) and windows

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

💾 save point · the cat says

Completeness (NULLs) and uniqueness (duplicates): two COUNTs that decide whether any total can be trusted.

level 02SUM

Part-to-whole, and the zero that lied

// lab · each order's % of total sales
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 →

💾 save point · the cat says

Divide decimals, not integers: CAST or * 100.0 before the division.

level 03AVG · MIN · MAX

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, ?AVGMINMAX
? = NULL (skipped)503070
? = 0 (COALESCE)33070

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.

// lab · compare each order with its product
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? →

💾 save point · the cat says

COALESCE before AVG changes the denominator. Before MIN, it can make a missing value the minimum.

level 04over time

Running, rolling, moving

running total vs rolling total (2 preceding)2020Jan3030Feb6060Mar6545Apr135105Jun175115Julrunning · keeps everythingrolling · drops the oldest
Running totals only grow: good for tracking progress against a target. Rolling totals go up and down: good for spotting the recent trend.
framequestion
running totalROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWhow much so far? (YTD vs target)
rolling totalROWS BETWEEN 2 PRECEDING AND CURRENT ROWhow are the last 3 periods doing?
moving averageAVG + ORDER BY date (+ frame)what is the smoothed trend?
// lab · moving average per product over time
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.

// trap · "last 30 days" is not ROWS 29 PRECEDING

ROWS counts rows, not days. If May is missing, "2 preceding" from June reaches back to March.

how to get a true time window
PostgreSQLSUM(sales) OVER (ORDER BY order_date RANGE BETWEEN INTERVAL '29 days' PRECEDING AND CURRENT ROW)
SQL Serveraggregate to one row per day, fill gaps from a calendar table, then ROWS 29 PRECEDING

Last level: putting the checks into a pipeline →

💾 save point · the cat says

Running totals only grow; rolling totals rise and fall. Sort by a real date, make it unique, mind the gaps.

level 05DE angle

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.

💾 save point · the cat says

Before you publish a number: no NULL keys, no duplicate keys, row counts match.

// episode cleared

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

  1. PostgreSQL docs: Aggregate Functions
  2. PostgreSQL docs: Window Functions
  3. Microsoft Learn: SELECT - OVER clause (Transact-SQL)
  4. Lab data: the SalesDB sample database from the course I followed, run in SQL Server Management Studio.
← ep09a · See Through the Windowep09c · Stand on the Podium (soon) →