我在postgresql中有最大和最小价格值,并根据这个最大值和最小值之间的不同价格范围对结果集的计数进行分组,我的查询如下所示,任何想法如何按查询分组
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)
答案 0 :(得分: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'
THEN price BETWEEN 800 AND 1100 THEN '800-1100'
WHEN price > 1100 THEN '> 1100'
END AS range
FROM sales_sale
) range_table
GROUP BY range;
编辑:想到这一点,但答案已被接受,所以我不想完全改变我的答案。
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;