I have a table with sometable:
name |test_date | score
-----------------------
jon |2012:07:01| 95
jon |2012:07:01| 60
jon |2012:07:01| 30
alex |2012:07:01| 80
alex |2012:07:01| 85
alex |2011:05:01| 40
emile|2011:01:01| 89
I want to get some rows for each name and give information about his score_grading with rules:
score>79=A,
80>score>49=B
otherwise C.
The problem is, I want: If in the same day there are more than one same score_grade for a student, than it will count as one score_grade.
For example, in the table we can see that alex get A two times in one day, I want it to be counted as only 1 A.
So the result will be
name | A | B | C
jon | 1 | 1 | 1
alex | 1 | 0 | 1
emily| 1 | 0 | 0
I only know code like:
SELECT name,
SELECT SUM(IF(score)>79),1,0)) as A,
SELECT SUM(IF(80>score>49),1,0)) as B,
SELECT SUM(IF(score)<50),1,0)) as C from sometable group by name
Nha, how do I put a “DISTINCT” on it?
Can anybody give a solution? Maybe it does not need a DISTINCT?
Thanks. ^^
You mean something like the following (sqlfiddle)?
This first shuffles your data into rows of
name, test_date, A, B, Cin the subquery. Then the outer query will aggregate these rows, taking a 1 if there is at least one score of that letter grade on the day, else taking a 0.This ought to work too (sqlfiddle):
I’m not sure which one would be better. This query uses a
DISTINCTas you suggest in your question. First it resolves each numeric grade into the corresponding letter grade, thenDISTINCTs out the duplicates. Finally it shuffles the data into columns.