2015-12-02 74 views
1

我的查詢:如何總結行的數據具有相同的ID

"SELECT sent_who, sent_amount FROM game1 ORDER BY sent_who ASC;" 

輸出:

array (size=4) 
    0 => 
    array (size=4) 
     'sent_who' => string '1' (length=1) 
     0 => string '1' (length=1) 
     'sent_amount' => string '1' (length=1) 
     1 => string '1' (length=1) 
    1 => 
    array (size=4) 
     'sent_who' => string '2' (length=1) 
     0 => string '2' (length=1) 
     'sent_amount' => string '1' (length=1) 
     1 => string '1' (length=1) 
    2 => 
    array (size=4) 
     'sent_who' => string '2' (length=1) 
     0 => string '2' (length=1) 
     'sent_amount' => string '1' (length=1) 
     1 => string '1' (length=1) 
    3 => 
    array (size=4) 
     'sent_who' => string '2' (length=1) 
     0 => string '2' (length=1) 
     'sent_amount' => string '1' (length=1) 
     1 => string '1' (length=1) 

我想要什麼:

array (size=4) 
    0 => 
    array (size=4) 
     'sent_who' => string '1' (length=1) 
     0 => string '1' (length=1) 
     'sent_amount' => string '1' (length=1) 
     1 => string '1' (length=1) 
    1 => 
    array (size=4) 
     'sent_who' => string '2' (length=1) 
     0 => string '2' (length=1) 
     'sent_amount' => string '3' (length=1) 
     1 => string '1' (length=1) 

我想在陣列合併相同sent_who ,也在同一陣列中加上sent_amount。 如果我使用GROUP BY而不是ORDER BY它適用於sent_who,但它不給出sent_amount

回答

1

總和試試這個:

SELECT sent_who, SUM(sent_amount) as total_sent_amount 
FROM game1 
GROUP BY sent_who 
ORDER BY sent_who ASC 

使用SUM(sent_amount)將總結sent_amount的所有值的具體sent_who這我們使用GROUP BY sent_who進行分組。

所以你會得到你想要的數組。

相關問題