重写mysql语句 - 选择左连接别名union join减法问题

时间:2017-02-23 13:30:47

标签: mysql join left-join union alias

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

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

1 个答案:

答案 0 :(得分:0)

试试这个:

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

<强> :: OUTPUT ::

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