Just add them up using case
expressions:
(只需使用case
表达式将它们加起来即可:)
select name,
(case when chemistry = 'Excellent' then 1 else 0 +
case when physics = 'Excellent' then 1 else 0 +
case when biology = 'Excellent' then 1 else 0 +
case when math = 'Excellent' then 1 else 0
) as num_excellents,
. . .
from t;
A fancier method would use apply
and aggregation:
(更好的方法将使用apply
和Aggregation:)
select t.name, v.*
from t cross apply
(select sum(case when marks = 'Excellent' then 1 else 0 end) as excellent,
sum(case when marks = 'Good' then 1 else 0 end) as good,
sum(case when marks = 'Poor' then 1 else 0 end) as Poor
from (values (chemistry), (physics), (biology), (math)
) v(marks);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…