-------------------------------
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语句中计算TotalMarks 如果学生没有参加ExamMrks116(SubCode = 116),TotalMarks = 0。
否则使用PractEx112(SubCode = 112),PractEx114(SubCode = 114)&的总和。 ExamMrks116(子码= 116)
答案 0 :(得分:1)
一种选择是将这些结果放在子查询中,然后使用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