简体   繁体   中英

PostgreSQL - divide query result into quintiles

There is a PostgreSQL SQL SELECT results. I need to divide rows into quintiles and update quintil value to the specific row.

Is there some possibility to do this requirement in SELECT without need to do it in application? I would like to avoid situation when I need to select data to application and do the ranking out of PostgreSQL server.

Data example - first column is value, second column is quintil

4859 - 5
4569 - 5
4125 - 4
3986 - 4
3852 - 3
3562 - 3
3452 - 2
3269 - 2
3168 - 1
3058 - 1

Thank you.

There is a window function called "ntile" to produce this: you give it a parameter specifying how many "tiles" the output it covers should be divided into (5 in this case).

For example:

select t.id, ntile(5) over (order by t.id)
from t

See window function tutorial for an introduction to window functions, and window functions for a list of the standard ones supplied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM