在SQL中,如何在范围内“按”分组?假设我有一个带有数字列的表(让我们称之为“得分”)。我想要生成一个计数表,它显示在每个范围内出现了多少次分数。例如:score range | number of occurrences
-------------------------------------
0-9 | 11
10-19 | 14
20-29 | 3
... | ...在本例中,有11行的分数在0到9之间,14行的分数在10到19之间,3行的分数在20-29之间。有什么简单的方法来安排这件事吗?你有什么建议吗?
3 回答
德玛西亚99
TA贡献1770条经验 获得超3个赞
select t.range as [score range], count(*) as [number of occurences]from ( select case when score between 0 and 9 then ' 0- 9' when score between 10 and 19 then '10-19' else '20-99' end as range from scores) tgroup by t.range
select t.range as [score range], count(*) as [number of occurences]from ( select user_id, case when score >= 0 and score< 10 then '0-9' when score >= 10 and score< 20 then '10-19' else '20-99' end as range from scores) tgroup by t.range
慕村225694
TA贡献1880条经验 获得超4个赞
另一种方法是将范围存储在表中,而不是将它们嵌入查询中。最后你会有一张桌子,叫它恒河,看起来是这样的:
LowerLimit UpperLimit Range
0 9 '0-9'
10 19 '10-19'
20 29 '20-29'
30 39 '30-39'
一个类似于这样的查询:
Select
Range as [Score Range],
Count(*) as [Number of Occurences]
from
Ranges r inner join Scores s on s.Score between r.LowerLimit and r.UpperLimit
group by Range
这确实意味着设置一个表,但是当所需的范围发生变化时,它将很容易维护。没有代码更改的必要!
添加回答
举报
0/150
提交
取消