ITMISS
2019-07-22 16:33:41
在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
提交
取消