0

一个名为的表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

似乎还可以。谢谢

4

3 回答 3

4

你做错了。您可以通过 MySql 语句本身获得总和。

将聚合函数 sum 与 group by 子句一起使用。

像这样,

SELECT DebitAccount,sum(Account) from  2_1_journal group by DebitAccount

您的完整代码:

$query = " SELECT DebitAccount,sum(Account) as Total from  2_1_journal group by DebitAccount";
$sql = $db->prepare($query);
$sql->execute();
$data = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $result){
if(strlen($result['Total']) > 0 ) {
echo "DebitAccount ". $result['DebitAccount']. "Total is: ". $result['Total']. "<br>";
print_r (array_sum($result));
}
}
于 2013-06-30T14:53:32.500 回答
2
SELECT DebitAccount, SUM(Amount) 
FROM 2_1_journal 
GROUP BY DebitAccount
于 2013-06-30T14:52:38.377 回答
2

您必须GROUP BY在查询中使用

SELECT DebitAccount, SUM(Amount) AS Amount FROM 2_1_journal GROUP BY DebitAccount
于 2013-06-30T14:54:55.823 回答