如何对行的数据求和具有相同的id

时间:2015-12-02 10:05:56

标签: php mysql pdo

我的查询:

"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 个答案:

答案 0 :(得分: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_who分组的特定GROUP BY sent_who的sent_amount的所有值。

所以你会得到你想要的数组。