2013-10-02 141 views
1

我有一張表,列出了測試的分數列表,例如可以說分數爲30。按組百分比增加的SQL組

我想通過計算得分在一定百分比範圍內的人數來呈現數據。

例如:

Total % Bracket 
----------------- 
5  95-100% 
15  90-94% 
20  85-89% 
17  80-84% 
15  75-79% 
etc 

我想到了第一次計算每個百分比支架所需的分數,然後做一個SUM(CASE ....莫名其妙,但我似乎迷路了。

+0

你能分享預期的結果的例子嗎? – Kuzgun

+0

@Kuzgun我有它的問題。我想要統計一定百分比範圍內的總人數 –

+0

您正在使用哪個數據庫? – Kuzgun

回答

1

沒有時間來測試這一點,但東西長的線..

select t.pcbracket as [% Bracket], count(*) as [NumWithMark] 
from (
    select case 
    when mark between 0 and 9 then ' 0- 9' 
    when mark between 10 and 19 then '10-19' 
    when mark between 20 and 29 then '20-29' 
    when mark between 30 and 39 then '30-39' 
    else '40-100' end as pcbracket 
    from testresults) t 
group by t.pcbracket 
+0

謝謝,這讓我走上正軌,只需將分數轉換成一個百分比,然後使用你的方法。 –

0

我會用嵌套查詢來解決這個問題。 內部查詢我會使用簡單的百分比組,然後在它上面我會使用大小寫來指定百分比範圍並獲得輸出。

1

可以應用情況,但在這種情況下,你會錯過的間隔記錄0計數。所以,你可以做到這一點通過以下方式:

select t2.start,t2.finish, count(t.score) from t 
RIGHT JOIN 
(
select 0 as start, 4 as finish 
union all 
select 5 as start, 9 as finish 
union all 
select 10 as start, 14 as finish 
union all 
....... 
union all 
select 95 as start, 99 as finish 
) as t2 on t.score between t2.start and t2.finish 

group by t2.start,t2.finish 
order by t2.start 

Here is SQLFiddle demo