我的数据库中有一个名为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几个小时
*假设从数据库中正确获取所有值
提前致谢!
1 回答
您可以使用数据透视查询在MySQL中实际处理此问题: