MySQL - 根据同一个表中的相同字段获取列值的总和

时间:2016-04-29 05:24:02

标签: php mysql sum

我有一个名为 tbl_collection 的mysql表和另一个具有客户名称的表。我做了一个内心的联系。加入效果很好。

这是我的 tbl_collection

+-----------+------------+---------------+
| customer  |    date    |    ach_val    | 
+-----------+------------+---------------+
|     30002 | 2012-02-02 | 200           |
|     30002 | 2012-02-05 | 250           | 
|     30002 | 2012-02-06 | 122           |
|     30003 | 2012-02-03 | 500           |
|     30004 | 2012-02-04 | 425           |
|     30004 | 2012-02-06 | 225           |
|     30004 | 2012-02-10 | 300           |
+-----------+------------+---------------+

我想要的是每个月获得每个客户ach_val的总和。

例如2012-02中每位客户的ach_val总和。

(ach_val)30002 = 200 + 250 + 122 = 572

(ach_val)30003 = 500 = 500

(ach_val)为30004 = 425 + 225 + 300 = 950

这就是我想要做的事情。

$r = mysql_query("select tbl_collection.customer, sum(tbl_collection.col_ach) as coll from tbl_collection inner join tbl_mas_customer on tbl_mas_customer.customer = tbl_collection.customer where rep = '503' and DATE_FORMAT(date, '%Y-%m') = '2012-02'");

1 个答案:

答案 0 :(得分:3)

from collections import defaultdict

d = defaultdict(dict)

phonemes = ["T", "UH", "T"]
graphemes = ["t", "oo", "t"]
# Create offset list for dict key
graphemes_offset = ['^'] + graphemes[:len(graphemes)-1]

for ph, g, g_o in zip(phonemes, graphemes, graphemes_offset):
  d[(ph,g_o)][g] = d[(ph, g_o)].setdefault(g,0) + 1