// window reference

SQL DISTINCT inside window aggregates

DISTINCT inside a windowed aggregate works only on Oracle, and only over a whole partition; everywhere else it is an error and needs a rewrite.

Catégorie
Fenêtre
Returns
bigint
In this category
69 of 79

Syntaxe

COUNT(DISTINCT x) OVER (PARTITION BY g) | COUNT(DISTINCT x) OVER ()

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Not built in 'Use of DISTINCT is not allowed with the OVER clause'
PostgreSQL Not built in 'DISTINCT is not implemented for window functions'
MySQL Not built in 'doesn't yet support <window function>(DISTINCT ..)'
SQLite Not built in 'DISTINCT is not supported for window functions'
Oracle Oui supported with PARTITION BY only; ORDER BY in the OVER raises ORA-30487

Exemples

Any engine

-- portable: distinct the pairs, then window
WITH pairs AS (
  SELECT DISTINCT customer_id, product_id FROM orders
)
SELECT customer_id, product_id,
       COUNT(*) OVER (PARTITION BY customer_id) AS products_bought
FROM pairs;

Oracle

SELECT customer_id, product_id,
       COUNT(DISTINCT product_id) OVER (PARTITION BY customer_id) AS products_bought
FROM orders;

Bon à savoir

  • To keep every detail row, use two DENSE_RANKs: DENSE_RANK() OVER (PARTITION BY g ORDER BY x) + DENSE_RANK() OVER (PARTITION BY g ORDER BY x DESC) - 1 is the distinct count of x per partition, provided x has no NULLs.
  • The other route is to deduplicate (g, x) pairs in a CTE and window-count those, as in the first example; it is simple but returns one row per pair, not per detail row.
  • SUM(DISTINCT x) and AVG(DISTINCT x) follow the same matrix. They add each distinct value once, so two different orders of 50.00 count as one 50.00, rarely the intended number.

Questions about DISTINCT in Window Aggregates

Which engines allow COUNT(DISTINCT) OVER?

Only Oracle, and only with PARTITION BY (no ORDER BY, so no running distinct count). SQL Server, PostgreSQL, MySQL and SQLite all reject it with an error rather than returning a wrong count.

What is the simplest emulation that keeps every row?

The double DENSE_RANK: DENSE_RANK() OVER (PARTITION BY g ORDER BY x) + DENSE_RANK() OVER (PARTITION BY g ORDER BY x DESC) - 1. It runs on all five engines. If x can be NULL, NULL counts as one extra value, so subtract 1 for partitions that contain a NULL.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.