Oracle SQL如何两次链接两个表

cdmah0mi  于 2022-10-04  发布在  Oracle
关注(0)|答案(1)|浏览(135)

我有两个表case_hdr和locn_hdr

在case_hdr上,我有locn_id列和prev_locn_id列;在locn_hdr上,我有locn_id和locn_brcd列

我想创建报告,显示Case_NBR、Locn_id和Prev_Locn_id,但这两个位置都显示为Locn_BRCD??

有什么建议吗?

rt4zxlrg

rt4zxlrg1#

也许,只是可能,这是一个更换和混合身份证的案例。这是不可能的,但如果我猜对了,这可能会帮助你了解情况。

WITH
    case_hdr AS
        (
            Select 1 "LOCN_ID", 101 "PREV_LOCN_ID" From Dual Union All
            Select 2 "LOCN_ID", 102 "PREV_LOCN_ID" From Dual Union All
            Select 3 "LOCN_ID", 103 "PREV_LOCN_ID" From Dual Union All
            Select 4 "LOCN_ID", 104 "PREV_LOCN_ID" From Dual Union All
            Select 5 "LOCN_ID", 105 "PREV_LOCN_ID" From Dual 
        ),
    locn_hdr AS
        (
            Select 1 "LOCN_ID", 11 "LOCN_BRCD" From Dual Union All
            Select 102 "LOCN_ID", 12 "LOCN_BRCD" From Dual Union All
            Select 3 "LOCN_ID", 13 "LOCN_BRCD" From Dual Union All
            Select 4 "LOCN_ID", 14 "LOCN_BRCD" From Dual Union All
            Select 105 "LOCN_ID", 15 "LOCN_BRCD" From Dual 
        )
Select
    ch.LOCN_ID "LOCN_ID",
    ch.PREV_LOCN_ID "PREV_LOCN_ID",
    lh.LOCN_ID "LOCN_ID_FROM_LOCN_HDR",
    CASE WHEN lh.LOCN_ID = ch.LOCN_ID THEN 1 ELSE 2 END "CASE_NBR",
    CASE WHEN lh.LOCN_ID = ch.LOCN_ID THEN 'Linked by ID' ELSE 'Linked by previous ID' END "CASE_NOTE",
    CASE WHEN lh.LOCN_ID = ch.LOCN_ID THEN ch.LOCN_ID ELSE ch.PREV_LOCN_ID END "LOCN_BRCD",
    lh.LOCN_BRCD "LOCN_BRCD_FROM_LOCN_HDR"
From
    case_hdr ch
Inner Join
    locn_hdr lh ON(lh.LOCN_ID = ch.LOCN_ID OR lh.LOCN_ID = ch.PREV_LOCN_ID)
Order By 
    ch.LOCN_ID
/*  
   R e s u l t :
   LOCN_ID PREV_LOCN_ID LOCN_ID_FROM_LOCN_HDR   CASE_NBR CASE_NOTE              LOCN_BRCD LOCN_BRCD_FROM_LOCN_HDR
---------- ------------ --------------------- ---------- --------------------- ---------- -----------------------
         1          101                     1          1 Linked by ID                   1                      11 
         2          102                   102          2 Linked by previous ID        102                      12 
         3          103                     3          1 Linked by ID                   3                      13 
         4          104                     4          1 Linked by ID                   4                      14 
         5          105                   105          2 Linked by previous ID        105                      15

* /

相关问题