在MySQL中过滤SUM()函数中的特定行

时间:2017-08-08 20:31:46

标签: mysql

我有一个计算学生分数的系统。目前,系统计算最好的六个科目,但我现在想要计算最好的6个包含英语标记,这意味着它是最好的5个加英语。英语商标必须包含在计算中。

这是我的代码。

 UPDATE `students` SET `term_1_avg` =(
     SELECT ROUND (SUM(sub_avg_term1/6)) AS term_1_avg 
     FROM (
         SELECT (sub_avg_term1) 
         FROM marks 
         WHERE marks.student_id = '$student_search_id' 
         ORDER BY sub_avg_term1 DESC LIMIT 6
    ) AS sub
 ) 
 WHERE students.student_id='$student_search_id'

我该怎么做?

1 个答案:

答案 0 :(得分:0)

你需要做5个顶部和英语的UNION。像

这样的东西
     UPDATE `students` SET `term_1_avg` =(
         SELECT ROUND (SUM(sub_avg_term1/6)) AS term_1_avg 
         FROM (
             (SELECT (sub_avg_term1) 
             FROM marks 
             WHERE marks.student_id = '$student_search_id' 
             AND marks.subject != 'English'
             ORDER BY sub_avg_term1 DESC LIMIT 5)
             UNION
             (SELECT (sub_avg_term1) 
             FROM marks 
             WHERE marks.student_id = '$student_search_id'
             AND marks.subject = 'English')
        ) AS sub
     ) 
     WHERE students.student_id='$student_search_id'

假设marks有一个subject字段,您将'English'作为主题之一。但您可以根据实际结构进行修改。