0

到目前为止我的查询是

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所有类别中得分最高的候选人

注意:有多个候选人

4

4 回答 4

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
于 2013-03-19T14:10:40.050 回答
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

于 2013-03-19T14:04:56.663 回答
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

你基本上只需要添加你没有总结到分组依据的所有其他列。

编辑。对不起,把小组放在错误的地方。

于 2013-03-19T14:03:36.960 回答
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;
于 2013-03-19T14:08:14.500 回答