gpt4 book ai didi

mysql - 使用条件语句选择

转载 作者:行者123 更新时间:2023-11-29 12:41:33 25 4
gpt4 key购买 nike

-------------------------------
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(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

关于mysql - 使用条件语句选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26048801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com