MySql Sum有两个表

时间:2015-01-30 08:58:46

标签: mysql sql sum

我有两张桌子

t1

id  Name    Total
1   Alex    100
2   Bob     100 
1   Alex    100

t2

id  Amount 
1   2   
1   3   
1   4   
2   12  
2   13

我需要得到总和和金额的总和。

**select Name, sum(Total) as Total, sum(Amount) as Amount,day
from t1,t2
Where t1.id=t2.id
group by Name**

结果:

Alex 600    18 
Bob  200    25

金额总和不正确!

**select Name, sum(distinct Total) as Total, sum(Amount) as Amount,day
from t1,t2
Where t1.id=t2.id
group by Name**

结果:

Alex100 18

Bob 100 25

金额总和不正确。

MySql使用distinct by value,我需要通过id区分 需要的核心结果是

 Alex 200 18  
 Bob  100 25

如何获得此结果?

1 个答案:

答案 0 :(得分:1)

select t1.Name, 
       sum(t1.Total) as Total, 
       sum(t2.Amount) as Amount,
       day
from t1
left join 
(
  select id, sum(Amount) as Amount
  from t2
  group by id
) t2 on t1.id = t2.id
group by t1.Name