mysqldistinctsum_mysql–SQL:在SUM中放置⼀个Distinct 我有⼀张桌⼦可⽤:
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):
distinct查询
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重复.最后,它将数据混合到列中.

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。