Created
December 11, 2012 15:36
-
-
Save mariokonschake/4259408 to your computer and use it in GitHub Desktop.
Query a histogram of prices in postgres (number of bis = 20)
This file contains hidden or 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
SELECT | |
( | |
(VALUES ((SELECT max(price/20) FROM prices))) * bin | |
)::float AS lower_bin_edge, | |
COALESCE(count, 0) AS count | |
FROM ( | |
SELECT | |
floor( | |
price / | |
(VALUES ((SELECT max(price/20) FROM prices))) | |
) AS filled_bin, | |
count(*) | |
FROM prices | |
GROUP BY filled_bin | |
) AS histogram | |
RIGHT OUTER JOIN ( | |
SELECT * FROM generate_series(0,20) AS bin | |
) AS range | |
ON (histogram.filled_bin = range.bin); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment