2013-06-30 50 views
0

一個表稱爲18_7_ChartOfAccounts(從MySQL結果創建)薩姆PHP陣列看起來像這樣:取決於MySQL的值在另一個MySQL柱

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);如果MySQL查詢使用SUM(j.Amount)得到陣列的一長串像

[31] => Array 
    (
     [Amount] => 26.03 
     [DebitAccount] => 2310 

[32] => Array 
    (
     [Amount] => 200.00 
     [DebitAccount] => 2310 

然後得到只有一筆總額(假設欄的總金額爲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 = "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); GET數組這樣

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

你會錯誤的。您可以通過MySql語句本身獲得總和。

使用aggrgate函數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)); 
} 
} 
2
SELECT DebitAccount, SUM(Amount) 
FROM 2_1_journal 
GROUP BY DebitAccount 
2

你必須在查詢中使用GROUP BY

SELECT DebitAccount, SUM(Amount) AS Amount FROM 2_1_journal GROUP BY DebitAccount 
相關問題