gpt4 book ai didi

mysql - 当有不同的货币时如何获得买卖平衡?

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

下面的 MySQL 表中包含不同货币的买入和卖出金额,如何根据每个货币选择买入、卖出和余额的总和?我已尝试过,但有些地方无法正常工作。

id      currency    buy  change_Currency     sell
1 USD 1000 DR 3670
2 EURO 100 USD 130
3 DR 500 USD 136
4 USD 500 EURO 600
5 USD 1200 DR 3800

我的 MySQL 查询不起作用:

SELECT currency,SUM(buy)-SUM(sell) AS 余额 FROM deal GROUP BY currency ,更改货币

我想要的结果是这样的:

currency    buy     sell    balance
USD 2700 266 2434
DR 500 7470 -6970
EURO 100 600 -500

我不知道还能尝试什么。任何帮助都会很棒。

最佳答案

将表分组两次,一次用于购买,一次用于销售,然后加入结果:

select 
t1.currency,
t1.total buy,
t2.total sell,
t1.total - t2.total balance
from (
select currency, sum(buy) total from deal
group by currency
) t1 inner join (
select change_currency, sum(sell) total from deal
group by change_currency
) t2 on t2.change_currency = t1.currency

参见 demo .
结果:

| currency | buy  | sell | balance |
| -------- | ---- | ---- | ------- |
| DR | 500 | 7470 | -6970 |
| EURO | 100 | 600 | -500 |
| USD | 2700 | 266 | 2434 |

关于mysql - 当有不同的货币时如何获得买卖平衡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57125898/

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