2016-04-29 26 views
1

我有一個名爲tbl_collection的mysql表和具有客戶名稱的另一個表。我做了一個內部連接。加入運作良好。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的總和。

的30002 = 200 + 250 + 122 = 572

(ach_val)的30003 = 500 = 500

(ach_val)的(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'"); 

回答

3
select customer,sum(ach_val) from tbl_collection group by customer,month(date); 
相關問題