gpt4 book ai didi

mysql - 重写mysql语句-select left join alias union join减法问题

转载 作者:行者123 更新时间:2023-11-30 22:03:51 24 4
gpt4 key购买 nike

我正在考虑重写这个的最佳方法:

SELECT
debits.account_title, debits.total - credits.total AS net_reduction
FROM
(
SELECT SUM(a) FROM
(
SELECT SUM(mainaccount_a_2017.amount) AS a FROM `mainaccount_a_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_a_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE mainaccount_a_2017.dr_cr_action = 'DR' AND asset_liability_income_expenditure_tbl.a_l_code = 'IN'

UNION ALL

SELECT SUM(mainaccount_b_2017.amount) AS a FROM `mainaccount_b_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_b_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE mainaccount_b_2017.dr_cr_action = 'DR' AND asset_liability_income_expenditure_tbl.a_l_code = 'IN'
)a
)AS debits
JOIN
(
SELECT SUM(a) FROM
(
SELECT SUM(mainaccount_a_2017.amount) AS a FROM `mainaccount_a_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_a_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE mainaccount_a_2017.dr_cr_action = 'CR' AND asset_liability_income_expenditure_tbl.a_l_code = 'IN'

UNION ALL

SELECT SUM(mainaccount_b_2017.amount) AS a FROM `mainaccount_b_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_b_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE mainaccount_b_2017.dr_cr_action = 'CR' AND asset_liability_income_expenditure_tbl.a_l_code = 'IN'
)a
)AS credits
ON debits.account_title = credits.account_title

最佳答案

试试这个:

SELECT B.account_title, 
SUM(CASE WHEN A.dr_cr_action = 'CR' THEN A.amount * -1 ELSE A.amount END) AS net_reduction
FROM (SELECT A.joint_account_number, A.dr_cr_action, A.amount
FROM mainaccount_a_2017 A
UNION ALL
SELECT B.joint_account_number, B.dr_cr_action, B.amount
FROM mainaccount_b_2017 B
) AS A
INNER JOIN chart_of_account B ON A.joint_account_number = B.joint_account_numbers
WHERE B.account_type = 'IN'
GROUP BY B.account_title;

检查 SQL FIDDLE DEMO :

::输出::

|           account_title | net_reduction |
|-------------------------|---------------|
| OTHER GRANTS AND GIFTS | 301200 |

关于mysql - 重写mysql语句-select left join alias union join减法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42417175/

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