如何总结使用组中的位置或案例?

时间:2017-05-22 18:16:44

标签: sql sql-server

我通过表达式从组中获得此结果集:

enter image description here

这是来自:

SELECT
    list.Id, 
    SUM(answer.score) totalScoreOfList
    --,sum(answer.score) score of student id 5.. something like sum(answer.score) where studentId = 5
    -- or case when studenti.id = 5 then sum(answer.score) else 0 end
FROM
    list
LEFT JOIN student ...
LEFT JOIN answer ...
GROUP BY 
    exercise.id

我可以用什么技术来获得上面的结果?

enter image description here

2 个答案:

答案 0 :(得分:1)

正如您的问题标题所示,您需要使用CASE表达式:

SELECT
    list.Id, 
    SUM(answer.score) totalScoreOfList,
    SUM(CASE WHEN studentId = 5 THEN answer.score END) [score of student id 5]
FROM
    list
LEFT JOIN student ...
LEFT JOIN answer ...
GROUP BY 
    list.id;

答案 1 :(得分:1)

您可以使用以下案例:

SELECT
    list.Id, 
    SUM(answer.score) totalScoreOfList,
    SUM(case when StudentId = 5 then answer.score else 0 end) as TotalScoreOfStudentWithid5
...