'GROUP by multiple ranges in postgresql
I have max and min values of prices in postgresql, and group the count of result set according to different ranges of prices between this max and min values, my query is like below, any ideas how group by query should be
SELECT COUNT(*)
FROM sales_sale
WHERE transfer >='2004-02-01' AND transfer < '2012-02-01'
# GROUP BY RANGES OF PRICES BETWEEN LIST ITEMS (200, 500, 800,1100)
Solution 1:[1]
SELECT range,
COUNT(*)
FROM (
SELECT item_id,
price,
CASE WHEN price < 200 THEN '< 200'
WHEN price BETWEEN 200 AND 500 THEN '200-500'
WHEN price BETWEEN 500 AND 800 THEN '500-800'
WHEN price BETWEEN 800 AND 1100 THEN '800-1100'
WHEN price > 1100 THEN '> 1100'
END AS range
FROM sales_sale
) range_table
GROUP BY range;
EDIT: Just thought of this, but the answer was already accepted, so I didn't want to change my answer altogether.
SELECT CASE WHEN price < 200 THEN '< 200'
WHEN price BETWEEN 200 AND 500 THEN '200-500'
WHEN price BETWEEN 500 AND 800 THEN '500-800'
WHEN price BETWEEN 800 AND 1100 THEN '800-1100'
WHEN price > 1100 THEN '> 1100'
END,
COUNT(*)
FROM sales_sale
GROUP BY 1;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Shiva |