foreach循环存在问题,其中group by one列,但php中的另一列具有多个值



db_table=>承诺

ref_no comm_date
1 2022-10-05
2 2022-10-05
3 2022-10-06
4 2022-10-07
5 2022-10-07
6 2022-10-08

因此,在SQL中,只有此查询对应于具有group_concat的解决方案。。。?我试图回答以帮助那些只在SQL中寻找解决方案的人。

select COM.ref_no, 
if(COL.ref_no is not null,group_concat(COL.trnx_date,' (',COL.amount,')' separator '+'),'') as 'collection summary details',
if(COL.ref_no is not null,sum(COL.amount),0) as 'collection summary'
from commitment as COM 
left join collection as COL on COM.ref_no=COL.ref_no 
group by COM.ref_no

我是这么想的。想象一下,你有一张关于金额的表格。它将通过sql:解决

Select ref_no, comm_date, sub(summary) as collect_summary from amount;

然而,您可以使用其他方式与php进行分组,例如:

<?php

$amount = [
['ref_no'=> 1, 'amount'=>500 , 'date'=>'2022-10-05'],
['ref_no'=> 2, 'amount'=>100 , 'date'=>'2022-10-05'],
['ref_no'=> 1, 'amount'=>700 , 'date'=>'2022-10-05'],
['ref_no'=> 3, 'amount'=>400 , 'date'=>'2022-10-05'],
['ref_no'=> 3, 'amount'=>600 , 'date'=>'2022-10-05'],
['ref_no'=> 5, 'amount'=>800 , 'date'=>'2022-10-05'],
['ref_no'=> 1, 'amount'=>700 , 'date'=>'2022-10-05'],   
];

$result = [];

foreach($amount as $item) {
$ref = $item['ref_no'];
if(isset($result[$ref])) {
$result[$ref]['collect_amount'] = $result[$ref]['collect_amount'] + $item['amount'];

}else{
$result[$ref] = [
'ref_no' => $ref,
'date' => $item['date'],
'collect_amount' =>$item['amount']
];
}
}
echo '<pre>';
print_r($result);

最新更新