MySQL查询:根据数字落入的范围多次选择一个int字段

时间:2010-08-24 09:00:28

标签: sql mysql

我的表int中有一个scores字段。它可以是0到100之间的数字。该表中有超过1000行。我想选择介于0-25,26-50,51-75和76-100之间的行数。

所以基本上,如果这是我的scores

score (int)
------------
 10
 20
 12
 56
 43
 90
 87

查询的输出应如下所示(让我们调用范围R1,R2,R3,R4)

R1   R2   R3   R4
------------------
3    1    1    2

如果有些事情不清楚,请告诉我。

编辑我到目前为止

SELECT CASE score
WHEN score BETWEEN 0 AND 25 THEN 'R1'
WHEN score BETWEEN 26 AND 50 THEN 'R2' 
WHEN score BETWEEN 51 AND 75 THEN 'R3' 
ELSE 'R4'
END, COUNT(*)
FROM scores

但是当我在END之后放置AS range时,我收到错误。 (更新:nvm这个,它应该是AS'范围',带引号)

此外,如果得分为0,则它​​显示在R2下而不是R1。那是为什么?

2 个答案:

答案 0 :(得分:2)

尝试下面的内容(警告:未经测试):

SELECT   CASE WHEN score BETWEEN 0 AND 25 THEN 'R1' 
              WHEN score BETWEEN 26 AND 50 THEN 'R2' 
              WHEN score BETWEEN 51 AND 75 THEN 'R3' 
              WHEN score BETWEEN 76 AND 100 THEN 'R4' 
         END AS r,
         COUNT(*)
FROM     scores
GROUP BY r

现在我不记得MySQL是否会让你按别名分组。如果不是,请改为按CASE表达式分组。

更新:事实上,MySQL似乎会让你按别名分组。

答案 1 :(得分:2)

    create table scores (score int)

    insert into scores values(5);
    insert into scores values(15);
    insert into scores values(25);
    insert into scores values(30);
    insert into scores values(35);
    insert into scores values(40);
    insert into scores values(45);
    insert into scores values(55);
    insert into scores values(65);
    insert into scores values(80);
    insert into scores values(90);
    insert into scores values(95);
    insert into scores values(75);
    insert into scores values(50);


     select SUM(case t.rank when 1 then c else 0 end) as R1,
             SUM(case t.rank when 2 then c else 0 end) as R2,
             SUM(case t.rank when 3 then c else 0 end) as R3,
             SUM(case t.rank when 4 then c else 0 end) as R4
      from
      (         
        select TRUNCATE(score / 26,  0) + 1 rank, count(*) c
         from scores
        group by truncate(score / 26, 0) + 1
      ) t

结果:

R1   R2  R3 R4
--------------
3    5    3  3