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.
- 카테고리
- 창
- Returns
bigint- In this category
- 69 of 79
구문
COUNT(DISTINCT x) OVER (PARTITION BY g) | COUNT(DISTINCT x) OVER ()
엔진 지원
| 엔진 | Support | 메모 |
|---|---|---|
| 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 | 예 | supported with PARTITION BY only; ORDER BY in the OVER raises ORA-30487 |
예시
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;
알아 두면 좋은 정보
- 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.
Related on SQLly
Cheat sheets for the engines that have it: Oracle.
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.