PostgreSQL
 SQL >> Datenbank >  >> RDS >> PostgreSQL

Nth-Perzentile in PostgreSQL berechnen

Seit PostgreSQL 9.4 gibt es native Perzentil-Unterstützung, implementiert als Ordered-Set-Aggregatfunktionen:

percentile_cont(fraction) WITHIN GROUP (ORDER BY sort_expression) 

continuous percentile: returns a value corresponding to the specified fraction in the ordering, interpolating between adjacent input items if needed

percentile_cont(fractions) WITHIN GROUP (ORDER BY sort_expression) 

multiple continuous percentile: returns an array of results matching the shape of the fractions parameter, with each non-null element replaced by the value corresponding to that percentile

Vollständige Details in der Dokumentation: https://www.postgresql.org/docs/current/static/functions-aggregate.html

Und einige Beispiele hier: https://github.com/michaelpq/michaelpq.github.io/blob/master/_posts/2014-02-27-postgres-9-4-feature-highlight-within-group.markdown

CREATE TABLE aa AS SELECT generate_series(1,20) AS a; --SELECT 20 WITH subset AS ( SELECT a AS val, ntile(4) OVER (ORDER BY a) AS tile FROM aa ) SELECT tile, max(val) FROM subset GROUP BY tile ORDER BY tile; tile | max ------+----- 1 | 5 2 | 10 3 | 15 4 | 20 (4 rows) 

Hier teilt ntile(4) die Zeilen in vier etwa gleich große Gruppen und liefert so eine schnelle quartile-artige Aufschlüsselung.