SQL组按百分比增量

时间:2013-10-02 10:18:23

标签: sql sql-server-2005 group-by percentage

我有一张表,其中包含一个测试分数列表,例如,我可以说30分。

我想通过计算得分在特定百分比范围内的人数来提供数据。

例如:

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

我考虑先计算每个百分比所需的分数,然后以某种方式进行SUM(CASE ....,但我似乎迷失了方向。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以使用CASE WHEN,但在这种情况下,您将错过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

答案 2 :(得分:0)

我会使用嵌套查询来解决此问题。 内部查询我将使用简单的百分比组,然后在它上面我将使用大小写指定百分比范围并获得输出。