如何在mysql中找到行总和?

时间:2013-08-18 19:45:50

标签: php mysql

我想从表中获取所有行。我可以正常地完成这项工作。但问题来自于我将每行值作为百分比并尝试将百分比相加。例如,我使用以下查询输出所有行:

SELECT SUM( Mark_score ) / SUM( Full_mark ) *50 AS Score
FROM nuexam
WHERE regd = '22'
GROUP BY subject

通过上面的查询,我得到了以下输出:

Query Output

我想总计这个Score。到目前为止,我可以输出。很感谢任何形式的帮助。我也欢迎php解决方案。

3 个答案:

答案 0 :(得分:3)

只需运行嵌套查询即可:

SELECT SUM(s) as Score
FROM (SELECT SUM( Mark_score ) / SUM( Full_mark ) *50 AS s
    FROM nuexam
    WHERE regd = '22'
    GROUP BY subject) table

答案 1 :(得分:3)

如果您想获得个人得分以及总得分,请使用with rollup。您的数据的正确方法是:

select coalesce(subject, 'Total'), sum(t.Score)
from (SELECT subject, SUM( Mark_score ) / SUM( Full_mark ) *50 AS Score
      FROM nuexam
      WHERE regd = '22'
      GROUP BY subject
     ) t
group by subject with rollup;

答案 2 :(得分:2)

http://sqlfiddle.com/#!2/a505a/4

select sum(t.Score) from 
(SELECT SUM( Mark_score ) / SUM( Full_mark ) *50 AS Score
FROM nuexam
WHERE regd = '22'
GROUP BY subject ) t