重写这个mysql语句

时间:2017-03-19 12:25:35

标签: mysql join case inner-join

我正在尝试使用join(inner或join)将另一个表中的两个字段添加到此语句中。我最好怎么写这个? 我只按要求添加了相关表格link所需结果                | a_l_code | dr_cr_code_inc | |----------|-------------------| | FA | DR |

select B.joint_account_numbers,
    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
group by B.joint_account_numbers;

1 个答案:

答案 0 :(得分:0)

Figured it out!    

    select B.joint_account_numbers,
    B.account_title, C.a_l_code, C.dr_cr_code_inc,
    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
    inner join asset_liability_income_expenditure_tbl C on B.account_type = C.a_l_code
    group by B.joint_account_numbers;`