oracle 希望子查询返回非空值

6jjcrrmo  于 2022-11-28  发布在  Oracle
关注(0)|答案(1)|浏览(217)

我在查询中使用了三个表; AP_INVOICES_INTERFACEAP_INVOICE_LINES_INTERFACEPO_HEADERS_ALL作为子查询。
AP_INVOICE_LINES_INTERFACE表仅在从AP_INVOICE_LINES_INTERFACE到PO_HEADERS_ALL中的SEGMENT1PO_NUMBER上与PO_HEADERS_ALL联接。我希望使用REQ_BU_ID值填写列'REQ_BU_ID2',该值基于SEGMENT1等于LN.PO_NUMBER,而不是NULL

SELECT HDR.INVOICE_ID  , HDR.PO_NUMBER , LN.PO_NUMBER LN_PO_NUMBER

, (SELECT PO2.REQ_BU_ID
    FROM PO_HEADERS_ALL PO2
    WHERE PO2.SEGMENT1 = LN.PO_NUMBER
       AND PO2.REQ_BU_ID IS NOT NULL
       AND LN.PO_NUMBER IS NOT NULL
       --AND HDR.PO_NUMBER IS NOT NULL
       AND rownum = 1    ) REQ_BU_ID2

FROM AP_INVOICES_INTERFACE HDR
INNER JOIN AP_INVOICE_LINES_INTERFACE LN ON LN.INVOICE_ID = HDR.INVOICE_ID
AND HDR.INVOICE_ID = 300000136747640

即使LN.PO_NUMBERNULL,我也要填充行的REQ_BU_ID2(非空)值,因此我认为通过在子查询中使用AND LN.PO_NUMBER IS NOT NULL条件,将只返回非空值,但是,正如您所看到的,它仍然在结果中返回Null

上述查询的当前结果:

预期结果:

编辑:

INVOICE_ID        REQ_BU_ID2        PO_NUMBER   LN_PO_NUMBER
300000136747640   300000006290049               K11004499
300000136747640
300000136747640
300000136747640   300000006290049               K11004499
wgxvkvu9

wgxvkvu91#

下面使用CTE为所有INVOICE_ID提供相同的LN_PO_NUMBER
如果它们可以合法地***曾经***拥有不同的“非NULL”PO_NUMBER,这将不起作用。
然后,您的子查询已被修改为使用ORDER BY REQ_BU_ID DESC FETCH NEXT 1 ROWS ONLY,以便以确定性的方式精确地查找一个REQ_BU_ID,首选非NULL值。
同样,如果任何PO_NUMBER可以合法地关联到多于1个非NULL REQ_BU_ID,这将不起作用。
同样,如果找到ZERO REQ_BU_ID,它仍返回NULL

WITH
  PO_LOOKUP
AS
(
  SELECT
    HDR.INVOICE_ID,
    HDR.PO_NUMBER,
    MAX(LN.PO_NUMBER) OVER (PARTITION BY HDR.INVOICE_ID)   AS LN_PO_NUMBER
  FROM
    AP_INVOICES_INTERFACE        HDR
  INNER JOIN
    AP_INVOICE_LINES_INTERFACE   LN
      ON LN.INVOICE_ID = HDR.INVOICE_ID
)
SELECT
  PO_LOOKUP.*,
  (
    SELECT REQ_BU_ID
      FROM PO_HEADERS_ALL
     WHERE SEGMENT1 = PO_LOOKUP.LN_PO_NUMBER
  ORDER BY REQ_BU_ID ASC
     FETCH NEXT 1 ROWS ONLY
  )
    AS REQ_BU_ID
FROM
  PO_LOOKUP
WHERE
  INVOICE_ID = 300000136747640

演示:https://dbfiddle.uk/N9fb6W9I

***编辑:***或者...

SELECT
  HDR.INVOICE_ID,
  HDR.PO_NUMBER,
  LN.MAX_PO_NUMBER,
  PO.MAX_REQ_BU_ID
FROM
  AP_INVOICES_INTERFACE        HDR
INNER JOIN
(
  SELECT
    AP_INVOICE_LINES_INTERFACE.*,
    MAX(PO_NUMBER) OVER (PARTITION BY INVOICE_ID)  AS MAX_PO_NUMBER
  FROM
    AP_INVOICE_LINES_INTERFACE
)
  LN
    ON LN.INVOICE_ID = HDR.INVOICE_ID
INNER JOIN
(
  SELECT
    SEGMENT1,
    MAX(REQ_BU_ID)   AS MAX_REQ_BU_ID
  FROM
    PO_HEADERS_ALL
  GROUP BY
    SEGMENT1
)
  PO
    ON PO.SEGMENT1 = LN.MAX_PO_NUMBER
WHERE
  HDR.INVOICE_ID = 300000136747640

相关问题