I have a mysql table like:
Sample Data
ID STUDENT_ID Branch_id Class_id Exam_id Subject_id Numbers Date 1 653 5 1 1 8 60 2012-01-01 2 653 5 1 1 9 40 2012-01-01 3 653 5 1 1 10 80 2012-01-01 4 653 5 1 1 11 50 2012-01-01 5 653 5 1 1 12 65 2012-01-01 6 653 5 1 1 13 33 2012-01-01 7 653 5 1 1 15 86 2012-01-01 8 222 5 1 1 8 100 2012-01-01 9 222 5 1 1 9 80 2012-01-01 10 222 5 1 1 10 92 2012-01-01 11 222 5 1 1 11 50 2012-01-01 12 222 5 1 1 12 65 2012-01-01 13 222 5 1 1 13 33 2012-01-01 7 222 5 1 1 15 86 2012-01-01
I need to get rank of student in class even if there two student are equal in marks. example if two students get 600 marks out of 600 marks that means both are on first position.
I search many site and I found this post that works what I need but in this post the correct column already sum of marks but in my table I need to sum(numbers) then get rank of of student depend on there total marks.
This all when I fetched the result of single student.
At same data when I fetched result for all class there is two thing needs. First row to column pivot query that display result in excel format so I use row to colum query like:
SELECT m.*
FROM (
select student_id, branch_id, class_id, numbers, exam_id, date
, sum(numbers*(1-abs(sign(subject_id-1)))) as subs1
, sum(numbers*(1-abs(sign(subject_id-2)))) as subs2
, sum(numbers*(1-abs(sign(subject_id-3)))) as subs3
, sum(numbers*(1-abs(sign(subject_id-4)))) as subs4
, sum(numbers*(1-abs(sign(subject_id-5)))) as subs5
, sum(numbers*(1-abs(sign(subject_id-6)))) as subs6
from results
GROUP BY student_id, branch_id, class_id, exam_id
) m
where branch_id = '6'
and class_id = '1'
and exam_id = '1'
and YEAR(date) = '2013'
Required Result In class query like:
ID Name Math English Science Total Percent Position Rank
And I got result fine by this query. but still there is problem in rank how to get rank of students in same query?
Can any one help?
Select from a subquery instead of a table.
I don’t fully understand your second question, and don’t see the relation to the first. Please write separate posts to ask separate questions.
You can write this as
sum(numbers*(subject_id = 1))as MySQL uses 0 for false and 1 for true when evaluating a boolean operation like this comparison.One more note: it would be better in terms of performance to move the
WHEREconditions inside the subquerym.