简体   繁体   English

左外连接条件 sql

[英]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.我有带实际值的分类帐表和参考部门表,我想从中分配 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.但部门参考表包含 LC 编号或 = 'xx' 我想要做的是将分类帐表与 LCTRYNUM、LC 和 DEPTNUM 上的部门表连接起来,但在 LC = '**' 的情况下,连接将只是 LCTRYNUM 和 DEPTNUM。

Ledger acutal table分类帐实际表

LCTRYNUM密码 LC液晶显示器 DEPTNUM部门 Amount数量
618 618 40 40 30813 30813 100 100
618 618 50 50 30813 30813 200 200
618 618 60 60 30813 30813 300 300
618 618 10 10 30813 30813 100 100

Business Division reference table事业部参考表

LCTRYNUM密码 LC液晶显示器 DEPTNUM部门 BMDIV BMDIV
618 618 ** ** 30813 30813 30 30
618 618 10 10 30813 30813 2P 2P

Expected result would be this预期结果是这样的

LCTRYNUM密码 LC液晶显示器 DEPTNUM部门 Amount数量 BMDIV BMDIV
618 618 40 40 30813 30813 100 100 30 30
618 618 50 50 30813 30813 200 200 30 30
618 618 60 60 30813 30813 300 300 30 30
618 618 10 10 30813 30813 100 100 2P 2P

You can use two left join s, the first to bring in direct matches and the second for the default match:您可以使用两个left join s,第一个引入直接匹配,第二个用于默认匹配:

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 = '**'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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