// SQL snippet

Median per group

Average the middle row (or two) per group: the median that runs on every engine.

Main statement
All engines

The task

Averages lie when one whale order skews the mean. You want the median amount per customer, and PERCENTILE_CONT is not available on your engine.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
WITH ordered AS (
  SELECT customer_id, amount,
         ROW_NUMBER() OVER (PARTITION BY customer_id
                            ORDER BY amount) AS rn,
         COUNT(*)    OVER (PARTITION BY customer_id) AS n
  FROM orders
)
SELECT customer_id,
       AVG(amount) AS median_amount
FROM ordered
WHERE 2 * rn IN (n, n + 1, n + 2)
GROUP BY customer_id
ORDER BY customer_id;

工作原理

Each row learns its position (rn) and its group size (n). The test 2 * rn IN (n, n + 1, n + 2) keeps the single middle row when n is odd (2 * rn = n + 1) and the two middle rows when n is even (2 * rn = n and n + 2), and the outer AVG averages them. It avoids dividing, because MySQL and Oracle return 2.5 for 5 / 2 where the other engines return 2, which makes the usual (n + 1) / 2 formula pick the wrong rows on even groups. On SQL Server, AVG of an integer column returns an integer and would round 2.5 down to 2, so write AVG(amount * 1.0) there if amount is an integer.

Variations

PERCENTILE_CONT aggregate (PostgreSQL, Oracle)

PostgreSQL Oracle
SELECT customer_id,
       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount) AS median_amount
FROM orders
GROUP BY customer_id;

Questions that come up

Median of an even-sized group: middle two or lower?

Convention here is the mean of the two middle values, which matches PERCENTILE_CONT(0.5). For the lower middle (PERCENTILE_DISC(0.5) behaviour) change the filter to 2 * rn IN (n, n + 1). SQL Server only has PERCENTILE_CONT as a window function, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount) OVER (PARTITION BY customer_id), and Oracle also offers MEDIAN(amount).

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.