MySql 用两个表求和
MySql Sum with two tables
我有两张桌子
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 使用按值区分,我需要按 id 区分
需要的正确结果是
Alex 200 18
Bob 100 25
如何得到这个结果?
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
我有两张桌子
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 使用按值区分,我需要按 id 区分 需要的正确结果是
Alex 200 18
Bob 100 25
如何得到这个结果?
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