这里有两张表,即租金和student_hostel。租金表如下所示
id date stud_id paid balance
18 10-2016 94 15000 15000
19 10-2016 94 10000 5000
20 10-2016 96 25000 5000
21 10-2016 96 5000 0
我的student_hostel表看起来像这样..
id first_name last_name stud_id admit_date hostel class room bed status
94 ss ff PHBH00094 01-10-2016 12 16 115 501A P
96 maltu uv PHBH00096 01-10-2016 12 16 115 501C p
为了获得最后插入的stud_id的余额,我使用了这样的代码,
public function rent_outstanding($hos,$dt)
{
$sql = "select s.stud_id ,s.admit_date ,s.class,first_name,sum(paid) as rt_paid,balance,rt.stud_id
from student_hostel s, rent rt where s.id=rt.stud_id and hostel=? and rt.date=?
and rt.id = (select max(id) from rent r where r.stud_id = rt.stud_id and r.date='$dt')
and status!= 'G' and status!= 'R' GROUP BY rt.stud_id";
$query=$this->db->query($sql, array($hos, $dt));
return $query;
}
我面临的问题是我无法将相同stud_id的付费列下的值相加。 我得到的输出是这样的
SI.No STUDENT ID NAME RENT PAID BALANCE
1 PHBH00094 Ss 30000 10000 5000
2 PHBH00096 Maltu 30000 5000 0
我需要得到的所需输出就像这样
SI.No STUDENT ID NAME RENT PAID BALANCE
1 PHBH00094 Ss 30000 25000 5000
2 PHBH00096 Maltu 30000 30000 0
答案 0 :(得分:1)
您最终解决的问题是:
select s.stud_id ,s.admit_date ,s.class,first_name,sum(paid) as rt_paid,
(select r.balance from rent r where r.stud_id = rt.stud_id and r.date='$dt' order by r.id desc limit 1) as balance ,rt.stud_id
from student_hostel s join rent rt on s.id=rt.stud_id where hostel=? and rt.date=?
and status!= 'G' and status!= 'R' GROUP BY s.stud_id
我已在您现有的查询rt.id = (select max(id) from rent r where r.stud_id = rt.stud_id and r.date='$dt')
您的(select max(id) from rent r where r.stud_id = rt.stud_id and r.date='$dt')
表示始终只获得最后一行rt.id
,例如19 (for PHBH00094)
或21 (for PHBH00096)
。
这就是为什么你最后一次计算的原因。