SQL hypothetical-set aggregates
Ranks a hypothetical row as if it were inserted, without inserting it.
- 카테고리
- Aggregates
- Returns
integer or numeric- In this category
- 48 of 52
구문
RANK(v) WITHIN GROUP (ORDER BY col) | CUME_DIST(v) WITHIN GROUP (ORDER BY col)
엔진 지원
| 엔진 | Support | 메모 |
|---|---|---|
| SQL Server | Not built in | same UNION ALL emulation |
| PostgreSQL | 예 | Supported under this name. |
| MySQL | Not built in | emulate with UNION ALL of the hypothetical value plus a window function |
| SQLite | Not built in | same UNION ALL emulation |
| Oracle | 예 | Supported under this name. |
예시
PostgreSQL
SELECT rank(1500) WITHIN GROUP (ORDER BY salary) FROM employees;
Oracle
SELECT RANK(1500) WITHIN GROUP (ORDER BY salary) FROM employees;
알아 두면 좋은 정보
- The hypothetical row's values are the function's arguments; the ORDER BY list must match in count and sortability.
- RANK(v) is 1 plus the number of existing values that sort strictly before v; existing values equal to v tie with it rather than push it down.
- The window versions of RANK and friends rank rows that exist; the WITHIN GROUP versions rank a value that does not.
- Emulation recipe elsewhere: SELECT ... UNION ALL the value, then window-rank and filter out the injected row.
Questions about RANK
What is a hypothetical-set aggregate for?
Placement questions: 'what rank would a salary of 1500 get?' without writing the row first.
How is it different from window RANK?
Window RANK ranks existing rows after PARTITION BY; the hypothetical form ranks an argument value against the data.
Which engines support it?
PostgreSQL and Oracle; MySQL, SQL Server and SQLite need the UNION ALL plus window-function emulation.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Top-N with ties per group Snippet
- Rank rows within a category Snippet
- Mix window functions with GROUP BY Snippet
- SQL aggregation & HAVING interview questions Interview questions
Cheat sheets for the engines that have it: PostgreSQL, 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.