简体   繁体   中英

Left outer join with condition sql

would anybody know if there is way to do conditional left outer join? I have ledger tables with actuals and reference department table from which I want to assign BMDIV. But department reference table contains LC number or = 'xx' What I want to do is to join ledger table with department table on LCTRYNUM, LC and DEPTNUM but in the case of LC = '**' join would be only LCTRYNUM and DEPTNUM.

Ledger acutal table

LCTRYNUM LC DEPTNUM Amount
618 40 30813 100
618 50 30813 200
618 60 30813 300
618 10 30813 100

Business Division reference table

LCTRYNUM LC DEPTNUM BMDIV
618 ** 30813 30
618 10 30813 2P

Expected result would be this

LCTRYNUM LC DEPTNUM Amount BMDIV
618 40 30813 100 30
618 50 30813 200 30
618 60 30813 300 30
618 10 30813 100 2P

You can use two left join s, the first to bring in direct matches and the second for the default match:

select a.*, coalesce(d.bmdiv, d_default.bmdiv) as bmdiv
from actual a left join
     divisions d
     on a.lc = d.lc left join
     divisions d_default
     on d_default.lc = '**'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM