4

I have a table of seat numbers and marks like this:

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

The max mark is 100. Now I want to display how many candidates are securing marks in 10s, 20s, 30, .... 100s

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

And so on. Now I know this

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

or do this for each 10s, 20s and 30s

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

and get the num of rows returned in my php and return the results, but thats not very elegant. There must be a way to do that directly in MySQL and without using MySQL for loops.

4

3 に答える 3

2

try this:

select (marks/10)*10 as marks,
       count(*) as candidates_count
from <table>
group by (marks/10)*10
于 2012-10-12T10:36:22.757 に答える
2

Following will definitely work for you

select (FLOOR(`marks`/ 10)+1)*10 as marks,
       count(*) as candidates_count
from <table>
group by (FLOOR(`marks`/ 10)+1)*10;
于 2012-10-12T10:53:16.197 に答える
0

Try:

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

But if you want to see 0 you have to prepare expected marks:

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)

and use 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
于 2012-10-12T10:56:45.927 に答える