如何在php中获取此mysql查询的两行的总和值

时间:2014-02-14 12:28:42

标签: php mysql sql

我的mysql查询有问题。我需要计算两行金额的总和。这里我的查询是

   SELECT cs.school_id, 
          SUM( ss.strength * cr.rate_offered ) AS str
     FROM tbl_school_course_strength cs, 
          tbl_school_strength ss, 
          tbl_course_rates cr
    WHERE cs.school_id = ss.school_id
      AND ss.class >= cs.from_class
      AND ss.class <= cs.to_class
      AND cs.school_id = cr.school_id
      AND cs.course_id = cr.course_id
      AND cs.school_id = '$school_name[school_id]'
 GROUP BY cs.school_id

这里的输出就像这样

school_id   str 

----------------      
28  326250
29  218250
30  372900

现在我想要这三个School_id金额值的总和。你能帮我解决这个问题。提前谢谢。

4 个答案:

答案 0 :(得分:1)

将您的mysql查询更新为下面的查询,该查询不包含group by和schoold id。

SELECT SUM( ss.strength * cr.rate_offered ) AS str
FROM tbl_school_course_strength cs, tbl_school_strength ss, tbl_course_rates cr
WHERE cs.school_id = ss.school_id
AND ss.class >= cs.from_class
AND ss.class <= cs.to_class
AND cs.school_id = cr.school_id
AND cs.course_id = cr.course_id
AND cs.school_id = '$school_name[school_id]'

答案 1 :(得分:0)

SELECT SUM(str) strtotal FROM
(SELECT cs.school_id, SUM( ss.strength * cr.rate_offered ) AS str
FROM tbl_school_course_strength cs, tbl_school_strength ss, tbl_course_rates cr
WHERE cs.school_id = ss.school_id
AND ss.class >= cs.from_class
AND ss.class <= cs.to_class
AND cs.school_id = cr.school_id
AND cs.course_id = cr.course_id
AND cs.school_id = '$school_name[school_id]'
GROUP BY cs.school_id)x

答案 2 :(得分:0)

试试这个:

select sum(str) as total from (SELECT cs.school_id, SUM( ss.strength * cr.rate_offered )     AS str
FROM tbl_school_course_strength cs, tbl_school_strength ss, tbl_course_rates cr
WHERE cs.school_id = ss.school_id
AND ss.class >= cs.from_class
AND ss.class <= cs.to_class
AND cs.school_id = cr.school_id
AND cs.course_id = cr.course_id
AND cs.school_id = '$school_name[school_id]'
GROUP BY cs.school_id)

答案 3 :(得分:0)

试试这个:

Select SUM(str) as total from (SELECT cs.school_id, SUM( ss.strength * cr.rate_offered ) AS str
FROM tbl_school_course_strength cs, tbl_school_strength ss, tbl_course_rates cr
WHERE cs.school_id = ss.school_id
AND ss.class >= cs.from_class
AND ss.class <= cs.to_class
AND cs.school_id = cr.school_id
AND cs.course_id = cr.course_id
AND cs.school_id = '$school_name[school_id]'
GROUP BY cs.school_id) as temp