SQL问题在同一表中查找值

时间:2019-01-29 19:31:37

标签: sql join null self-join

尝试在SQL中使用自联接以在表中查找值并将其应用。

她就是我得到的:

+ ----------------- + ----- + -------- + ----------- + < / p>

|实际输出| | | |

+ ----------------- + ----- + -------- + ----------- + < / p>

| TRKID | Fac | NewFac | BAG_TRKID |

| 449 | 11 | 11 | 999 |

| 473 | 11 | 11 | 737 |

| 477 | 11 | 11 | 737 |

| 482 | 11 | 11 | 737 |

| 737 | 89 | 89 | |


|期望卖出| | | |

| TRKID | Fac | NewFac | BAG_TRKID |

| 449 | 11 | 11 | 999 |

| 473 | 11 | 89 | 737 |

| 477 | 11 | 89 | 737 |

| 482 | 11 | 89 | 737 |

| 737 | 89 | 89 | |

+ ----------------- + ----- + -------- + ----------- + < / p>

这是下面的代码。我似乎无法获得想要的桌子。 Bag TrkID的设施编号不会成为TrkID新设施的编号。

Select 
    TABLEA.TRKID,
    TABLEA.FAC,
    NVL(TABLEA.FAC, TABLEB.FAC) as NEWFAC,
    TABLEA.BAG_TRKID        

FROM
    (
    Select
    HSD. TRKID,
    HSD.NLPT as FAC,
    SBPD.BAG_TRKID
    From
    HSD
    LEFT JOIN
    SBPD
    ON
    SBPD.BAG_TRKID = HSD. TRKID

Where
    HSD.SCANDT BETWEEN   ‘Yesterday’ and ‘Today’
) TABLEA

LEFT JOIN
(
    Select
    HSD. TRKID,
    HSD.NLPT as FAC,
    SBPD.BAG_TRKID
    From
    HSD
    LEFT JOIN
    SBPD
    ON
    SBPD.BAG_TRKID = HSD. TRKID

Where                              
    HSD.SCANDT BETWEEN   ‘Yesterday’ and ‘Today’
) TABLEB

ON
TABLEA.TRKID = TABLEB.BAG_TRKID

2 个答案:

答案 0 :(得分:0)

也许类似

select a.TrkID, a."Facility Number", a.BAG_TRKID, b.TrkID as "NEW Fac"
from tbl a
left join tbl b on (a.TrkID = b.trk_id_reference)

答案 1 :(得分:0)

鉴于您共享的信息有限,我可以通过以下查询获得预期的输出:

SELECT a.TrkID, a.facility_number, a.bag_trkid, b.facility_number as new_facility_number 
FROM test_tbl AS a 
 LEFT JOIN test_tbl AS b ON a.bag_trkid = b.trkid OR (a.bag_trkid IS NULL AND b.trkid = a.trkid);

您要根据其bag_trkid获取行的new_facility_number(可以通过LEFT JOIN test_tbl AS b ON a.bag_trkid = b.trkid实现)。 但是诀窍是要解决“左表”(我称为a)没有bag_trkid的情况。在这种情况下,我们将保持new_facility_number与a.facility_number相同,仅将trkid上的表连接起来:OR (a.bag_trkid IS NULL AND b.trkid = a.trkid)