我有一张桌子可用:
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
我想为每个名称获取一些行,并通过规则提供有关其score_grading的信息:
得分> 79 = A,
80 GT;得分> 49 = B
否则C.
问题是,我想:如果在同一天,学生有多个相同的score_grade,那么它将被计为一个score_grade.
例如,在表格中我们可以看到alex在一天内获得A两次,我希望它只被计为1 A.
结果将是
name | A | B | C
jon | 1 | 1 | 1
alex | 1 | 0 | 1
emily| 1 | 0 | 0
我只知道代码:
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
不,我怎么把“DISTINCT”放在上面?
任何人都可以提供解决方案吗?也许它不需要DISTINCT?
谢谢. ^^
最佳答案 你的意思是如下(
sqlfiddle)?
SELECT name, SUM(IF(A>=1,1,0)) as A, SUM(IF(B>=1,1,0)) as B,
SUM(IF(C>=1,1,0)) as C
FROM
(
SELECT name, test_date, SUM(IF(score>79,1,0)) as A,
SUM(IF(score BETWEEN 49 AND 79,1,0)) as B, SUM(IF(score<50,1,0)) as C
FROM sometable
GROUP BY name, test_date
) daygroups
GROUP BY name
这首先将您的数据混合到子查询中的名称,test_date,A,B,C行.然后外部查询将聚合这些行,如果当天至少有一个该字母等级的分数,则取1,否则取0.
这应该也有效(sqlfiddle):
SELECT name, SUM(IF(lettergrade = 'A',1,0)) AS A,
SUM(IF(lettergrade = 'B',1,0)) AS B, SUM(IF(lettergrade = 'C',1,0)) AS C
FROM
(
SELECT DISTINCT name, test_date,
CASE WHEN score>79 THEN 'A'
WHEN score BETWEEN 49 AND 79 THEN 'B'
ELSE 'C'
END AS lettergrade
FROM sometable
) lettergrades
GROUP BY name
我不确定哪一个更好.此查询使用您在问题中建议的DISTINCT.首先,它将每个数字等级解析为相应的字母等级,然后DISTINCTs重复.最后,它将数据混合到列中.