-------------------------------
StudentID| SubCode  | Marks   |
-------------------------------
B016124  |   112    |     89  |
B016124  |   114    |     91  |
B016124  |   116    |     99  |
-------------------------------
B016129  |   112    |     78  |
B016129  |   114    |     88  |
B016129  |   116    |      0  |




输出:

            SubCode=112   SubCode=114  SubCode=116  tot of 112+114 |Tot 112+114+116
-----------------------------------------------------------------------------------
StudentID  | PractEx112  | PractEx114| TotalPract    |ExamMrks116  | TotalMarks   |
-----------------------------------------------------------------------------------
B016124    |       89    |     91    |      180      |    90       |      270     |
-----------------------------------------------------------------------------------
B016129    |       78    |     88    |      166      |     0       |        0     |
-----------------------------------------------------------------------------------


Select StudentID,
        , sum(CASE WHEN SubCode = 112 THEN Marks END) AS PractEx112
        , sum(CASE WHEN SubCode = 114 THEN Marks END) AS PractEx114
        , sum(CASE WHEN SubCode IN(112,114) THEN Marks END) AS TotalPract
        , sum(CASE WHEN SubCode = 116 THEN Marks END) AS ExamMrks116

FROM STUDENTS
GROUP BY StudentID


如何在上述select语句中计算TotalMark,其中
如果学生未参加ExamMrks116(SubCode = 116),则TotalMarks = 0。

否则使用PractEx112(SubCode = 112),PractEx114(SubCode = 114)和ExamMrks116(SubCode = 116)的总和

最佳答案

一种选择是将这些结果放在子查询中,然后使用case

select StudentID, PractEx112, PractEx114, PractEx116,
    case when PractEx116 = 0 then 0 else TotalOverall end total
from (
    select StudentID,
        sum(case when SubCode = 112 then Marks end) AS PractEx112 ,
        sum(case when SubCode = 114 then Marks end) AS PractEx114 ,
        sum(case when SubCode in (112,114) then Marks end) AS TotalPract ,
        sum(case when SubCode = 116 then Marks end) AS ExamMrks116
        sum(case when SubCode in (112,114,116) then Marks end) AS TotalOverall
    from students
    group by StudentID
) t

09-19 17:43