[英]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). 如果学生未参加ExamMrks116(SubCode = 116),如何在上面的select语句中计算TotalMarks = 0,因此我如何计算TotalMarks。
Else use the sum of PractEx112(SubCode=112), PractEx114(SubCode=114) & ExamMrks116(SubCode=116) 否则使用PractEx112(SubCode = 112),PractEx114(SubCode = 114)和ExamMrks116(SubCode = 116)的总和
One option is to put these results in a subquery, and then use case
: 一种选择是将这些结果放在子查询中,然后使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.