一个名为的表18_7_ChartOfAccounts
如下所示:
ID | AccountNumber
-------------
1 | 2310
2 | 2380
3 | 2610
另一个名为的表2_1_journal
如下所示:
ID | Amount | DebitAccount
--------------------------
1 | 26.03 | 2310
2 | 200.00 | 2310
3 | 3.63 | 2380
4 | 119.83 | 2380
5 | 33.86 | 2610
6 | 428.25 | 2610
目标是获得如下所示的结果:
DebitAccount 2310 total is: 226.03
DebitAccount 2380 total is: 123.46
DebitAccount 2310 total is: 462.11
本例中的 226.03 是 26.03 + 200.00 的总和
一开始的mysql代码
$query = "SELECT j.Amount, j.DebitAccount FROM 18_7_ChartOfAccounts AS c LEFT JOIN 2_1_journal AS j ON (c.AccountNumber = j.DebitAccount)";
$sql = $db->prepare($query);
$sql->execute();
$data = $sql->fetchAll(PDO::FETCH_ASSOC);
获得print_r($data);
长长的数组列表,例如
[31] => Array
(
[Amount] => 26.03
[DebitAccount] => 2310
[32] => Array
(
[Amount] => 200.00
[DebitAccount] => 2310
如果在 mysql 查询中使用SUM(j.Amount)
,则只获得一个总量(假设 Column 的总量Amount
)。
和
foreach($data as $result){
if(strlen($result['Amount']) > 0 ) {
echo "Amount ". $result['Amount']. "Account name ". $result['DebitAccount']. "<br>";
print_r (array_sum($result));
}
}
得到这样的东西
Amount 123.97Account name 2310
2433.97Amount 26.03Account name 2310
2336.03Amount 200.00Account name 2310
任何想法如何获得必要的结果(标记为粗体)?
更新
将 $query 更改为
$query = "SELECT SUM(j.Amount), j.DebitAccount FROM 18_7_ChartOfAccounts AS c LEFT JOIN 2_1_journal AS j ON (c.AccountNumber = j.DebitAccount) group by j.DebitAccount";
像print_r($data);
这样得到数组
Array
(
[0] => Array
(
[SUM(j.Amount)] =>
[DebitAccount] =>
)
[1] => Array
(
[SUM(j.Amount)] => 110900.16
[DebitAccount] => 2310
)
[2] => Array
(
[SUM(j.Amount)] => 3660.86
[DebitAccount] => 2380
)
使用数组似乎一切正常。现在与 foreach 更改为
echo "Amount ". $result['SUM(j.Amount)']. " Account name ". $result['DebitAccount']. "<br>";
得到
Amount 110900.16 Account name 2310
Amount 3660.86 Account name 2380
Amount 85247.40 Account name 2610
似乎还可以。谢谢