如何在单个mysql select语句中使用Multiple where子句?

时间:2013-11-27 10:42:21

标签: mysql sql

我有一个名为marksheet的表,我存储了学生的标记。我想从每个单元考试中取出20%的分数,每周一次的考试分数为30%,期末考试分数为50%。单元考试,每周考试和期末考试的所有名称都存储在一个列名Name_of_exam下。我可以用

SELECT regd, 
       Sum(mark_score)/sum(Full_mark)*20 as scored 
FROM marksheet 
WHERE Name_of_exam='First Unit Exam' 
   OR Name_of_exam='Second Unit Exam' 
   OR Name_of_exam='Third Unit Exam' 
GROUP BY regd;

但问题是我不知道如何能够取出学生得分的30%: Where (Name_of_exam='First Weekly Test or Name_of_exam='Second Weekly Test' or Name_of_exam='Third Weekly Test') 并且50%的分数得分为Where Name_of_exam='Final Exam'。在同一个select语句中我必须做多个where子句。请帮忙。我还附上了如何在excel表中进行计算。

Image showing marksheet

2 个答案:

答案 0 :(得分:3)

您不能使用多个WHERE部分,但始终可以使用逻辑运算符来加入条件。

WHERE会在您的treshholds下找到得分的结果:

SELECT regd, names, subjects, 
  sum( score ) * (CASE WHEN (Name_of_exam='First Weekly Test or Name_of_exam='Second Weekly Test' or Name_of_exam='Third Weekly Test') THEN 0.2 
       WHEN ( Name_of_exam='First Unit Exam' or Name_of_exam='Second Unit Exam' OR Name_of_exam='Third Unit Exam')  THEN 0.3
       WHEN ( Name_of_exam='Final Exam' ) THEN 0.5 )
  AS scored
FROM marksheet
GROUP BY regd, names, subjects, test_type

答案 1 :(得分:1)

试试这个:

SELECT names, subjects, 
SUM(
  CASE 
  WHEN name_of_exam = 'First Weekly Test' THEN (score/full_marks)*20 
  WHEN name_of_exam = 'First Unit Exam' THEN (score/full_marks)*30 
  WHEN name_of_exam = 'Final Unit Exam' THEN (score/full_marks)*50 
  END) AS scored
FROM marksheet
GROUP BY names, subjects