一尘不染

在数据透视查询中使用if else块

sql

我有桌子

StudentID StudentName Subject Marks
      1   Savita      EC1     50
      1   Savita      EC2     55
      1   Savita      EC3     45
      1   Savita      EC4     34
      1   Savita      EC5     23
      2   Rajesh      EC1     34
      2   Rajesh      EC2     56
      2   Rajesh      EC3     12
      2   Rajesh      EC4     45
      2   Rajesh      EC5     23
      3   Smita       EC1     76
      3   Smita       EC2     45
      3   Smita       EC3     67
      3   Smita       EC4     56
      3   Smita       EC5     76
      4   Rahul       EC1     66
      4   Rahul       EC2     34
      4   Rahul       EC3     22
      4   Rahul       EC4     18
      4   Rahul       EC5     33

我写了一个查询

SELECT StudentName, EC1,EC2,EC3,EC4,EC5,TotalMarks, case  
  when EC1<30 and ec2<30 then 'fail'
  when EC1<30 and EC3<30 then 'fail'
  when EC1<30 and EC4<30 then 'fail'
  when EC1<30 and EC5<30 then 'fail'
  when EC2<30 and EC3<30 then 'fail'
  when EC2<30 and EC4<30 then 'fail'
  when EC2<30 and EC5<30 then 'fail'
  when EC3<30 and EC4<30 then 'fail'
  when EC3<30 and EC5<30 then 'fail'
  when EC4<30 and EC5<30 then 'fail'
  else 'pass'
  end as Result
FROM (SELECT StudentName, EC1, EC2, EC3, EC4, EC5, TotalMarks=EC1+EC2+EC3+EC4+EC5
      FROM Student
      PIVOT(sum(Marks) for subject in([EC1],[EC2],[EC3],[EC4],[EC5],[TotalMarks]))as pivotTable) A

给出在两个科目中得分不超过30分的学生的成绩为不及格或不及格

Rahul   66  34  22  18  33  173 fail
Rajesh  34  56  12  45  23  170 fail
Savita  50  55  45  34  23  207 pass
Smita   76  45  67  56  76  320 pass

我想为少于30的每个科目添加7分,并在添加7分后查看通过不及格的学生。例如-在添加7个标记之后,rajesh记录应该像

Rajesh 34 56 19 45 30 170 pass


阅读 215

收藏
2021-03-08

共1个答案

一尘不染

你可以试试这个

SELECT 
    StudentName,
    CASE WHEN EC1 < 30 THEN EC1 + 7 ELSE EC1 END AS EC1,
    CASE WHEN EC2 < 30 THEN EC2 + 7 ELSE EC2 END AS EC2,
    CASE WHEN EC3 < 30 THEN EC3 + 7 ELSE EC3 END AS EC3,
    CASE WHEN EC4 < 30 THEN EC4 + 7 ELSE EC4 END AS EC4,
    CASE WHEN EC5 < 30 THEN EC5 + 7 ELSE EC5 END AS EC5,
    Total = (EC1 + EC2 + EC3 + EC4 + EC5),
    CASE  
       WHEN EC1 < 23 AND EC2 < 23 THEN 'FAIL'
       WHEN EC1 < 23 AND EC3 < 23 THEN 'FAIL'
       WHEN EC1 < 23 AND EC4 < 23 THEN 'FAIL'
       WHEN EC1 < 23 AND EC5 < 23 THEN 'FAIL'
       WHEN EC2 < 23 AND EC3 < 23 THEN 'FAIL'
       WHEN EC2 < 23 AND EC4 < 23 THEN 'FAIL'
       WHEN EC2 < 23 AND EC5 < 23 THEN 'FAIL'
       WHEN EC3 < 23 AND EC4 < 23 THEN 'FAIL'
       WHEN EC3 < 23 AND EC5 < 23 THEN 'FAIL'
       WHEN EC4 < 23 AND EC5 < 23 THEN 'FAIL'
       ELSE 'PASS'
   END AS Result
FROM
(
   SELECT * FROM Student
) AS ST
PIVOT
(
    SUM(Marks) For [Subject] IN (EC1, EC2, EC3, EC4, EC5)
) AS PV

输出

Rahul   66  34  29  25  33  173 FAIL
Rajesh  34  56  19  45  30  170 PASS
Savita  50  55  45  34  30  207 PASS
Smita   76  45  67  56  76  320 PASS
2021-03-08