亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在SQL中,如何在范圍內“按”分組?

在SQL中,如何在范圍內“按”分組?

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個贊

在SQLSERVER 2000上,投票最高的答案都不正確。也許他們使用的是不同的版本。

以下是SQLSERVER 2000上這兩種語言的正確版本。

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


查看完整回答
反對 回復 2019-07-22
?
慕村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

這確實意味著設置一個表,但是當所需的范圍發生變化時,它將很容易維護。沒有代碼更改的必要!


查看完整回答
反對 回復 2019-07-22
  • 3 回答
  • 0 關注
  • 883 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號