如何对照另一个表上的一系列日期查询表日期

时间:2018-09-18 16:28:49

标签: sql oracle

我有两个表,INVOICES和INV_PRICES。我试图根据发票表上的Invoice_Dt从Inv_Prices中找到发票表的单价;如果Invoice_Dt在Inv_Prices的最大EFF_DT之间(大于但小于)或大于最大EFF_DT,则返回该零件的价格。

我对以下代码感到厌倦,但没有运气。我要么得不到所有部分,要么得不到多条记录。

    SELECT DISTINCT A.INVOICE_NBR, A.INVOICE_DT, A.PART_NO,
CASE WHEN TRUNC(A.INVOICE_DT) >= TRUNC(B.EFF_DT) THEN B.DLR_NET_PRC_AM
     WHEN (TRUNC(A.INVOICE_DT)||ROWNUM >= TRUNC(B.EFF_DT)||ROWNUM)  AND (TRUNC(B.EFF_DT)||ROWNUM <= TRUNC(A.INVOICE_DT)||ROWNUM) THEN B.DLR_NET_PRC_AM
     /*MAX(B.EFF_DT) THEN B.DLR_NET_PRC_AM*/
 ELSE 0
 END AS PRICE   
FROM INVOICES    A,
     INV_PRICES  B
WHERE A.PART_NO = B.PART_NO
ORDER BY A.INVOICE_NBR

有人可以协助吗?如果需要的话,我有每个表的样本。

1 个答案:

答案 0 :(得分:0)

将条件置于JOIN条件不是可行的吗?您可以使用LEAD()计算价格有效的期限:

SELECT i.INVOICE_NBR, i.INVOICE_DT, i.PART_NO,
       COALESCE(ip.DLR_NET_PRC_AM, 0) as price
FROM INVOICES i LEFT JOIN
     (SELECT ip.*, LEAD(eff_dt) OVER (PARTITION BY PART_NO ORDER BY eff_dt) as next_eff_dt
      FROM INV_PRICES ip
     ) ip
     ON i.PART_NO = ip.PART_NO AND
        i.invoice_dt >= ip.eff_dt AND
        (i.invoice_dt < ip.next_eff_dt or ip.next_eff_dt is null)
ORDER BY i.INVOICE_NBR