gpt4 book ai didi

MySql Sum 与两个表

转载 作者:行者123 更新时间:2023-11-29 12:26:29 25 4
gpt4 key购买 nike

我有两张 table

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

关于MySql Sum 与两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28232350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com