连接2个数据库表获得总和值输出

时间:2013-09-19 11:29:44

标签: php mysql

我会更清楚地说明这一点,因为我已经意识到它并不像它应该的那样清晰。

表一

ID, COMPANY_ID, OPPORTUNITY, DATE_CREATE

表二

ID,ASSIGNED_BY_ID

我要做的是为每个ASSIGNED_ID添加OPPORTUNITY中的所有值。 表格一中的COMPANY_ID与表格二中的ID相同。

例如:

表一

COMPANY_ID | OPPORTUNITY | DATE_CREATE 
1000       | 50          | 2013/09/19
1000       | 100         | 2013/09/18
1000       | 200         | 2013/09/18
1005       | 100         | 2013/09/18
1005       | 200         | 2013/09/18

表二

ID         | ASSIGNED_BY_ID 
1000       | 4
1000       | 4
1000       | 4
1005       | 2
1005       | 2

所以我想要一个能提供这些结果的SELECT语句:

ASSIGNED_BY_ID  | OPPORTUNITY
4               | 350
2               | 300

我希望每个ASSIGNED_BY_ID个别选择语句。

这怎么可能?

2 个答案:

答案 0 :(得分:2)

试试这个。

SELECT t1.ID,SUM(OPPORTUNITY) AS total 
FROM table1 t1
INNER JOIN table2 t2 ON t1.COMPANY_ID=t2.ID
WHERE t1.DATE_CREATE BETWEEN '$fromdate' AND '$todate' AND t2.ASSIGNED_BY_ID=1 
GROUP BY t1.ID

<强>更新

SELECT t2.ASSIGNED_BY_ID,SUM(OPPORTUNITY) AS total 
FROM table1 t1
INNER JOIN table2 t2 ON t1.COMPANY_ID=t2.ID
WHERE t1.DATE_CREATE BETWEEN '$fromdate' AND '$todate' 
GROUP BY t2.ASSIGNED_BY_ID

答案 1 :(得分:0)

请使用

   SELECT SUM(a.OPPORTUNITY) AS total, a.ID FROM table1 a inner join table2 b on a.COMPANY_ID =    b.ID  WHERE a.DATE_CREATE BETWEEN '$fromdate' AND '$todate' AND b.ASSIGNED_BY_ID=1 group by a.ID;