到目前为止我的查询是
SELECT callSign,event,rubric,score
FROM scores LEFT JOIN candidates
ON scores.candidateID=candidates.id
WHERE candidateID IN
(SELECT id
FROM candidates
WHERE assessmentID='1321')
ORDER BY candidateID,event
返回如下数据集:
callSign event score
V021 Amazing Race Planning 5
V021 Amazing Race Planning 3
V021 Amazing Race Planning 5
V021 Individual Analyst Exam 3
V021 PSA 5
V021 Team Analyst Exam 5
V021 Team Analyst Exam 5
V021 Team Analyst Exam 3
V021 Team Analyst Exam 5
V022 PSA 1
V022 Team Tech Exam 5
V022 Team Tech Exam 3
我正在寻找的是每个候选人加上每个事件的分数,所以它看起来像:
callSign event score
V021 Amazing Race Planning 13
V021 Individual Analyst Exam 3
V021 PSA 5
V021 Team Analyst Exam 18
V022 PSA 1
V022 Team Tech Exam 8
我确定我需要某种SUM()
和GROUP BY
的组合,但我似乎无法弄明白。然后我需要ORDER BY
所有类别中得分最高的候选人
注意:有多个候选人
答案 0 :(得分:2)
其他答案也是正确的,但我会删除IN .. subselect语句。这是不必要的。
按照您要分组的字段进行分组,并将您想要的字段相加。
SELECT callSign, event, SUM(score) score
FROM scores
JOIN candidates
ON scores.candidateID = candidates.id
WHERE candidates.assessmentID = '1321'
GROUP BY callSign, event
ORDER BY candidateID, event
答案 1 :(得分:1)
SELECT callSign,event, SUM(score)
FROM scores LEFT JOIN candidates
ON scores.candidateID=candidates.id
WHERE candidateID IN
(SELECT id
FROM candidates
WHERE assessmentID='1321')
GROUP BY event, callSign
ORDER BY candidateID,event
通常,主要分组(在您的情况下为event
)是第一列。但是,由于您所需的结果集具有相同callSign
的多行,因此它必须是次要分组列,而不是主要分组列。
如果您希望主要分组适合候选人,请在查询中包含候选字段,并将其包含在此类分组GROUP BY candidateID, event, callSign
答案 2 :(得分:0)
SELECT callSign,event,rubric,SUM(score)
FROM scores LEFT JOIN candidates
ON scores.candidateID=candidates.id
WHERE candidateID IN
(SELECT id
FROM candidates
WHERE assessmentID='1321')
GROUP BY callSign,event,rubric
ORDER BY candidateID,event
您基本上只需要将您未汇总的所有其他列添加到该组中。
EDIT。抱歉把小组放在了错误的地方。
答案 3 :(得分:0)
只是一个猜测......
SELECT callSign
, event
, SUM(score) total
FROM scores s
LEFT
JOIN candidates c
ON c.id = s.candidateID
AND c.assessmentID=1321
GROUP
BY callsign
, event;