以10s,20s等组返回标记行

时间:2012-10-12 10:33:47

标签: mysql sql mysqli

我有一个座位号码表和这样的标记:

seat    marks
61      45
62      25
63      45
64      23
65      25
66      9
67      23

最大标记为100.现在我想显示有多少候选人在10s,20s,30,...... 100s内确保标记

marks     candidates_count
10        1
20        4
30        0
..        ..

等等。 现在我知道了这个

SELECT seat, marks, count(marks) as counts from <table> group by marks order by counts desc;

或每10s,20s和30s执行此操作

SELECT seat, marks from <table> where marks>10 and marks<=20 group by marks;

并获取我的php中返回的行数并返回结果,但这不是很优雅。必须有一种方法可以直接在MySQL中执行此操作,而无需使用MySQL for循环。

3 个答案:

答案 0 :(得分:2)

试试这个:

select (marks/10)*10 as marks,
       count(*) as candidates_count
from <table>
group by (marks/10)*10

答案 1 :(得分:2)

以下一定会对你有用

select (FLOOR(`marks`/ 10)+1)*10 as marks,
       count(*) as candidates_count
from <table>
group by (FLOOR(`marks`/ 10)+1)*10;

答案 2 :(得分:0)

尝试:

select ((marks/10)+1)*10, count(1) 
from tab
group by ((marks/10)+1)*10

但是如果你想看到0,你必须准备预期的标记:

create table tab2
(  
  marks int
)

insert into tab2 values(10)
insert into tab2 values(20)
insert into tab2 values(30)
insert into tab2 values(40)
insert into tab2 values(50)
insert into tab2 values(60)
....
insert into tab2 values(100)

并使用right join

select t2.marks, count(tab.marks) 
from tab
right join tab2 t2 on t2.marks = ((tab.marks/10)+1)*10
group by t2.marks
order by 1