我的数据库中有一个名为tbl_grade的表
id | studentid | compid | subcompid | recordid | termid | grade
1 101 1 1 1 1 95
2 101 1 2 1 1 80
3 102 1 1 1 1 90
4 102 1 2 1 1 95
5 103 2 2 1 1 90
我希望在我看来像这样打印
studentid | grade in subcomp1 | grade in subcomp2 | total (of both grades)
101 95 80 175
102 90 95 185
在我的观点中回应一下,我有这个
<?php foreach ($this->UserModel->grades() as $grade): ?>
<?php if($grade->compid=='1' && $grade->subcompid==$subcomp->id && $grade->recordid==$subcomp->recordid && $grade->studentid==$student->studentid && $grade->termid == '1'){ ?>
<td class="text-center"><?php echo $grade->grade; ?></td>
<?php }
endforeach; ?>
有了这个,我得到了我想要的东西,并且能够根据学生打印成绩,但是我在回答总数时遇到了问题。我有这个代码
<?php foreach ($this->UserModel->grades() as $grade): ?>
<?php if ($grade->compid=='1' && $grade->studentid==$student->studentid && $grade->subcompid==$subcomp->id && $grade->recordid==$subcomp->recordid && $grade->termid == '1') { ?>
<td class="colScore text-center"><strong>
<?php
$mySum = 0;
foreach ($this->UserModel->gradeSum($student->studentid) as $sum):
if($sum->compid==1 && $sum->termid=='1'){
$mySum = $mySum + $sum->grade;
}
endforeach; echo $mySum;?></strong>
</td>
<?php }
endforeach; ?>
php标签内的代码正常工作,我可以得到正确的成绩总和。但是,它的输出方式是这样的
studentid | grade in subcomp1 | grade in subcomp2 | total (of both grades) |
101 | 95 | 175 | 80 | 175
102 | 90 | 185 | 95 | 185
它打印每个年级的总数。总数应该在最后。我的foreach循环可能有问题吗?我应该把它放在哪里?我已经盯着它看了几个小时z_z
*假设所有值都是从数据库中正确获取的
提前致谢!
答案 0 :(得分:0)
您可以使用数据透视查询在MySQL中实际处理此问题:
SELECT studentid,
MAX(CASE WHEN subcompid = 1 THEN grade END) AS grade_in_subcomp1,
MAX(CASE WHEN subcompid = 2 THEN grade END) AS grade_in_subcomp2,
SUM(grade) AS total
FROM tbl_grade
GROUP BY studentid