假设下表:
id value
-----------
1 3
2 5
3 15
4 18
5 19
6 30
我希望分类并计入几个小组:
group amount
---------------
'1-5' 2
'6-10' 0
'11-20' 3
'21-50' 1
如何在一个查询中执行此操作?
答案 0 :(得分:1)
最简单的方法是在以下情况下将组写入案例:
SELECT grp, count(*)
FROM
(
SELECT
CASE
WHEN value BETWEEN 1 AND 5 THEN '1-5'
WHEN value BETWEEN 6 AND 10 THEN '6-10'
...and so on...
ELSE '21-50'
END as grp
FROM
sourcetable
)a
GROUP BY grp
基本上,您根据它们所处的范围将值从一种形式转换为另一种形式,然后计算转换后的值。注意,我已经在21-50范围内使用了ELSE,假设价值从未超过50,如果确实如此,则需要改变范围,否则技术上,100将在" 21下提交。 -50"还
答案 1 :(得分:1)
另一种方法是使用生成的范围表:
;WITH CTE_Groups AS (
SELECT 1 AS min, 5 AS max, '1-5' AS grp
UNION ALL
SELECT 6 AS min, 10 AS max, '6-10' AS grp
UNION ALL
SELECT 11 AS min, 20 AS max, '11-20' AS grp
UNION ALL
SELECT 21 AS min, 50 AS max, '21-50' AS grp
)
SELECT
G.grp,
COUNT(T.id) AS amount
FROM
CTE_Groups G
LEFT OUTER JOIN My_Table T ON T.value BETWEEN G.min AND G.max
GROUP BY
G.grp, G.min
ORDER BY
G.min