Created
January 9, 2012 15:23
-
-
Save tokumine/1583399 to your computer and use it in GitHub Desktop.
calculating equal frequency buckets, or n-tile ranges in postgresql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- To calculate flexible quantile ranges in postgresql, for example to calculate n equal | |
-- frequency buckets for your data for use in a visualisation (such as binning for a | |
-- choropleth map), you can use the following SQL: | |
-- this functions returns 6 equal frequency bucket ranges for my_column. | |
SELECT ntile, avg(my_column) AS avgAmount, max(my_column) AS maxAmount, min(my_column) AS minAmount | |
FROM (SELECT my_column, ntile(6) OVER (ORDER BY my_column) AS ntile FROM my_table) x | |
GROUP BY ntile ORDER BY ntile | |
-- more on the ntile() function and windowing here: | |
-- http://database-programmer.blogspot.com/2010/11/really-cool-ntile-window-function.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment