Skip to content

Instantly share code, notes, and snippets.

@mariokonschake
Created December 11, 2012 15:36
Show Gist options
  • Save mariokonschake/4259408 to your computer and use it in GitHub Desktop.
Save mariokonschake/4259408 to your computer and use it in GitHub Desktop.
Query a histogram of prices in postgres (number of bis = 20)
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