![](/img/trans.png)
[英]Using Mysql to select values from different tables with different names as credit and debit and calculate balance
[英]using mysql calculate balance of each currency where credit and debit in same column?
使用以下包含关联金额和货币的借方或贷方“操作”的 MySQL 表,如何选择每种currency
"balance"
非零的所有CLIENT_IDs
? 我试过了,但有些东西不能正常工作。
CLIENT_ID ACTION_TYPE ACTION_AMOUNT Currency
1 debit 1000 USD
1 credit 100 USD
1 credit 500 DR
2 debit 1000 EURO
2 credit 1200 DR
3 debit 1000 EURO
3 credit 1000 USD
4 debit 1000 USD
我的 MySQL 查询不起作用:
SELECT client_id,
SUM(if(action_type='credit',action_amount,0)) as credit,
SUM(if(action_type='debit',action_amount,0 )) as debit,
SUM(if(currency='USD' ,action_type='credit'- action_type='debit' )) as USD_balance,
SUM(if(currency='EURO',action_type='credit'- action_type='debit' )) as EURO_balance,
SUM(if(currency='DR' ,action_type='credit'- action_type='debit' )) as DR_balance
FROM my_table
GROUP BY client_id,currency
我期待的结果是这样的:
CLIENT_ID USD_Balance EURO_Balance DR_Balance
1 -900 0 500
2 0 -1000 1200
3 1000 -1000 0
4 -1000 0 0
我不知道还有什么可尝试的。 任何帮助都会很棒。
您可以Group By client_id
包括Conditional Aggregation
,如下所示
SELECT client_id,
SUM(case when action_type = 'credit' then action_amount else 0 end) as credit,
SUM(case when action_type = 'debit' then action_amount else 0 end) as debit,
SUM(case
when currency = 'USD' and action_type = 'credit' then
action_amount else 0
end) - SUM(case
when currency = 'USD' and action_type = 'debit' then
action_amount
else 0
end) as USD_balance,
SUM(case
when currency = 'EURO' and action_type = 'credit' then
action_amount else 0
end) - SUM(case
when currency = 'EURO' and action_type = 'debit' then
action_amount
else 0
end) as EUR_balance,
SUM(case
when currency = 'DR' and action_type = 'credit' then
action_amount
else 0
end) - SUM(case
when currency = 'DR' and action_type = 'debit' then
action_amount
else 0
end) as DR_balance
FROM my_table
GROUP BY client_id;
SELECT client_id
, currency
, SUM(CASE WHEN action_type = 'debit' THEN action_amount * -1 ELSE action_amount END) balance
FROM my_table
GROUP
BY client_id
, currency
其余的问题可以(并且应该)在应用程序代码中解决
仅对client_id
执行GROUP BY
,因为您正尝试在不同列中的多种货币上“旋转”。 您将需要使用两个级别的If()
语句来计算余额。
请尝试以下操作:
SELECT CLIENT_ID,
SUM(IF(Currency = 'USD', IF(ACTION_TYPE = 'credit', ACTION_AMOUNT, -ACTION_AMOUNT), 0)) AS USD_Balance,
SUM(IF(Currency = 'EURO', IF(ACTION_TYPE = 'credit', ACTION_AMOUNT, -ACTION_AMOUNT), 0)) AS EURO_Balance,
SUM(IF(Currency = 'DR', IF(ACTION_TYPE = 'credit', ACTION_AMOUNT, -ACTION_AMOUNT), 0)) AS DR_Balance
FROM my_table
GROUP BY CLIENT_ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.