列值总和直到当前记录

时间:2012-04-11 12:41:15

标签: php mysql sum

如何查询并显示每条记录中学生金额总和的记录?

 Student ID   Student Name   Student Money 
 ---------    -----------     --------------
   1           John            100
   2           Jenny           200
   3           Ben             100
   4           Andy            200
   5           Lynna           100

上面是我的表格,我想以这种格式检索记录:

 Student ID   Student Name   Student Money     totalCounting 
 ---------    -----------     --------------   ---------
   1           John               100           100
   2           Jenny              200           300
   3           Ben                100           400
   4           Andy               200           600
   5           Lynna              100           700

2 个答案:

答案 0 :(得分:0)

Select s.*, (SELECT SUM(s2.`Money`) from students as s2 WHEre s2.`ID` = s.`ID`) as 'totalCounting' from students AS s;

像这样。

答案 1 :(得分:-1)

在php中,我希望在使用foreach循环的查询构建的数组中构建一个额外的键。我的SQL不够强大,无法将其构建到Query中,所以......

$total = 0;
foreach ($queryResults as $key=>$row){
    $total = $total + $row['student_money'];
    $queryResults[$key]['total_money'] = $total;
}

然后使用带有新列的$ queryResults构建表。