具有SELECT,LEFT JOIN和WHERE子句的算术运算符

时间:2017-02-22 23:00:18

标签: php mysql join

我需要帮助。我有下面的代码工作正常,但它没有实现我的目标。我想要一个列“account_title”,其中每个计算值在减法之前的一侧,最终应该给出减去的值的差值。感谢您的期待。

SELECT
(
    SELECT SUM(amount)
    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 a_l_code = 'FA' AND dr_cr_action = 'DR'
)
-
(
    SELECT SUM(amount)
    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 a_l_code = 'FA' AND dr_cr_action = 'CR'
)

1 个答案:

答案 0 :(得分:0)

更改要按account_title分组的子查询,然后加入它们。

SELECT debits.account_title, debits.total - credits.total AS net_reduction
FROM (
    SELECT mainaccount_a_2017.account_title, SUM(amount) AS total
    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 a_l_code = 'FA' AND dr_cr_action = 'DR'
    GROUP BY mainaccount_a_2017.account_title
) AS debits
JOIN (
    SELECT mainaccount_b_2017.account_title, SUM(amount) AS total
    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 a_l_code = 'FA' AND dr_cr_action = 'CR'
    GROUP BY mainaccount_b_2017.account_title
) AS credits ON debits.account_title = credits.account_title

DEMO