Tina31
Tina31

Reputation: 13

Select with conditional statement

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

output:

            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

How do I calculate the TotalMarks within the above select statement where TotalMarks = 0 if a student did not take ExamMrks116(SubCode=116).

Else use the sum of PractEx112(SubCode=112), PractEx114(SubCode=114) & ExamMrks116(SubCode=116)

Upvotes: 0

Views: 61

Answers (1)

sgeddes
sgeddes

Reputation: 62841

One option is to put these results in a subquery, and then use 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

Upvotes: 1

Related Questions