MySQL中不同值的总和

时间:2016-05-08 14:58:12

标签: mysql group-by sum distinct

我有三个表,结构如下所示。

此表(称为contest_submissions)存储提交和竞赛的关系。

ContestID | SubmissionID

1           1000
1           1001
1           1002
1           1003

第二个表(称为submissions)存储提交的详细信息:

SubmissionID | ProblemID | User | Score | Time

1000           1000        A      100     1000
1001           1000        A      40      1250
1002           1001        A      50      1500
1003           1001        B      20      1750

另一个表(称为contest_contestants)包含:

ContestID | User

1           A
1           B

我写了以下SQL:

SELECT *, (
    SELECT SUM(score)
    FROM  contest_submissions cs
    NATURAL JOIN submissions
    WHERE user = cc.user
    AND SubmissionID = cs.SubmissionID
) AS TotalScore, (
    SELECT SUM(Time)
    FROM contest_submissions cs
    NATURAL JOIN submissions
    WHERE user = cc.user
    AND SubmissionID = cs.SubmissionID
) AS TotalTime
FROM contest_contestants cc
WHERE contestID = 1

我得到了以下结果(假设为ContestID = 1):

contestID | User | Total Score | Total Time
1           A      190           3750
1           B      20            1750

其中190 = 100 + 40 + 50

但是,我希望得到以下结果:

contestID | User | Total Score | Total Time
1           A      150           2500
1           B      20            1750

其中150 = MAX(100, 40) + 50,因为10040来自同一问题(具有相同的ProblemID)。

我该怎么办?

BTW,我正在使用MySQL。

3 个答案:

答案 0 :(得分:3)

你可以尝试这样的事情:

select User, sum(MaxScore)
from
(
select User, ProblemID, max(Score) as MaxScore
from submissions
group by User, ProblemId
) as t
group by User

答案 1 :(得分:1)

嗯。我认为有一种方法可以只使用一个group by

select s.user, sum(s.score)
from submissions s
where s.submissionId = (select s2.submissionId
                        from submissions s2
                        where s2.user = s.user and s2.ProblemId = s.ProblemId
                        order by s2.score desc
                        limit 1
                       )
group by s.user;

我提供此解决方案是因为submissions(user, ProblemId, score, submissionId)上的索引应该比具有两个聚合的解决方案具有更好的性能。

答案 2 :(得分:0)

您可以使用嵌套查询 - 内部查询来获取用户'每个问题的最佳答案和外部问题的总结:

SELECT   user, SUM(score) AS total_score
FROM     (SELECT   user, problemid, MAX(score) AS score
          FROM     submission
          GROUP BY user, problemid) t
GROUP BY user