gpt4 book ai didi

mysql从不同的表中选择总和2行

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

我一直在尝试找到对 2 个不同表中的 2 行求和的正确方法。

我可以使用这两个查询轻松识别要求和的行:

select * 
from vui_trading_review_form_client
where month = '201202' and client_id='TOTALS';

+--------+------------+-----------+-----------------+-----------------+-----------------+----------------+----------+
| month | dt_end | client_id | amt_balance_GBP | amt_balance_EUR | amt_balance_USD | dt_working_day | order_no |
+--------+------------+-----------+-----------------+-----------------+-----------------+----------------+----------+
| 201202 | 2012-02-29 | TOTALS | 2 | 3 | 4 | 2012-02-29 | 2 |
+--------+------------+-----------+-----------------+-----------------+-----------------+----------------+----------+


select *
from vui_trading_review_form_bank
where month = '201202' and provider='TOTALS';

+--------+------------+----------+-----------------+-----------------+-----------------+----------+
| month | dt_end | provider | amt_balance_GBP | amt_balance_EUR | amt_balance_USD | order_no |
+--------+------------+----------+-----------------+-----------------+-----------------+----------+
| 201202 | 2012-02-29 | TOTALS | 1 | 1 | 1 | 3 |
+--------+------------+----------+-----------------+-----------------+-----------------+----------+

我想要实现的是一个如下所示的表格

+-----------------+-----------------+-----------------+
| amt_balance_GBP | amt_balance_EUR | amt_balance_USD |
+-----------------+-----------------+-----------------+
| 1 | 2 | 3 |
+-----------------+-----------------+-----------------+

前 3 个总计减去后 3 个总计。

我尝试过加入,但我真的很难获得正确的结果。

如有任何建议,我们将不胜感激。

最佳答案

试试这个:

SELECT  (a.amt_balance_GBP - b.amt_balance_GBP) Total_GBP,
(a.amt_balance_EUR - b.amt_balance_EUR) Total_EUR,
(a.amt_balance_USD - b.amt_balance_USD) Total_USD
FROM vui_trading_review_form_client a INNER JOIN vui_trading_review_form_bank b
on (a.Client_ID = b. provider) AND
(a.Month = b.Month)
WHERE a.month = '201202' and b.provider='TOTALS';

或者如果它不符合您的需求,请尝试使用LEFT JOIN

SELECT  (a.amt_balance_GBP - COALESCE(b.amt_balance_GBP,0)) Total_GBP,
(a.amt_balance_EUR - COALESCE(b.amt_balance_EUR,0)) Total_EUR,
(a.amt_balance_USD - COALESCE(b.amt_balance_USD,0)) Total_USD
FROM vui_trading_review_form_client a LEFT JOIN vui_trading_review_form_bank b
on (a.Client_ID = b. provider) AND
(a.Month = b.Month)
WHERE a.month = '201202' and b.provider='TOTALS';

关于mysql从不同的表中选择总和2行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10746621/

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