1

下面的 SQL 查询总结了会话中每个问题的每个罚分:

SELECT s.SessionId,q.QuestionId,SUM(pm.PenaltyMarks)
    FROM Session s
    INNER JOIN Question q ON s.SessionId = q.SessionId
    INNER JOIN Penalty_Marks pm ON q.QuestionId = pm.QuestionId
    WHERE (s.SessionId = 30)
    GROUP BY s.SessionId,q.QuestionId

以下是输出显示的内容:

SessionId  QuestionId  Sum(pm.PenaltyMarks)
30         77          4
30         38          3
30         39          4

但我现在想要做的是总结会话中的所有罚分。所以在上面的例子中,它将把第 30 节的罚分加起来,输出总罚分为11. 但我的问题是如何做到这一点?

所以下面是它的样子:

SessionId  TotalPenaltyMarks
30         11
4

1 回答 1

2

消除q.QuestionId

SELECT  s.SessionId, 
        SUM(pm.PenaltyMarks) TotalPenaltyMarks
FROM    Session s
        INNER JOIN Question q ON s.SessionId = q.SessionId
        INNER JOIN Penalty_Marks pm ON q.QuestionId = pm.QuestionId
WHERE   s.SessionId = 30
GROUP   BY s.SessionId

GROUP BY子句已经是可选的,因为您已经在过滤特定的SessionId.

于 2013-01-19T10:36:32.653 回答