SQL Case语句如果Null选择表X中Y = Z的列

时间:2018-05-01 14:29:15

标签: sql oracle

我试图编写一份自定义报告,其中发票将在PO_Number列中有一个采购订单编号,或者他们不会。

如果他们没有采购订单编号,我希望从4列(Segment1,Segment2,Segment3和Segment4)获取数据,其中2个ID编号相同。如果有一个采购订单编号,我会在相同的声明中提取相同的4列,但其中有2个不同的ID号匹配。

我到目前为止的SQL是:

SELECT DISTINCT
AID.INVOICE_ID,
AID.AMOUNT,
AID.PERIOD_NAME,
GCC.SEGMENT1 as Organisation,
GCC.SEGMENT2,
GCC.SEGMENT3,
GCC.SEGMENT4,
INV.INVOICE_NUM,
INV.CREATION_DATE,
PO.SEGMENT1 as PO_Number,
SUP.VENDOR_NAME,
AID.LINE_TYPE_LOOKUP_CODE,
LINES.LINE_NUMBER


FROM
AP_INVOICES_All INV 
INNER JOIN
  AP_INVOICE_LINES_ALL LINES 
  ON INV.INVOICE_ID = LINES.INVOICE_ID 
INNER JOIN
  AP_INVOICE_DISTRIBUTIONS_ALL AID 
  ON INV.INVOICE_ID = AID.INVOICE_ID 
INNER JOIN
  GL_CODE_COMBINATIONS GCC 
  ON AID.DIST_CODE_COMBINATION_ID = GCC.CODE_COMBINATION_ID 
INNER JOIN
  POZ_SUPPLIERS_V SUP 
  ON INV.VENDOR_ID = SUP.VENDOR_ID 
LEFT JOIN
  PO_HEADERS_ALL PO 
  ON LINES.PO_HEADER_ID = PO.PO_HEADER_ID

WHERE
AID.LINE_TYPE_LOOKUP_CODE NOT IN 
(
  'REC_TAX',
  'NONREC_TAX'
)
AND LINES.LINE_TYPE_LOOKUP_CODE NOT IN 
(
  'TAX'
)

ORDER BY
AID.INVOICE_ID,
LINES.LINE_NUMBER

如果有PO,我希望匹配完成:

PO_DISTRIBUTIONS_ALL.CODE_COMBINATION_ID = GCC.CODE_COMBINATION_ID

如果没有PO:

AID.DIST_CODE_COMBINATION_ID = GCC.CODE_COMBINATION_ID

(我知道我需要在某处引用PO_DISTRIBUTIONS_ALL表,但不确定在哪里)

任何帮助都会很棒,因为我对SQL很陌生,并且不知道如何表达我想要在SQL代码中实现的目标。

如果我对任何部分都不清楚,请告诉我

1 个答案:

答案 0 :(得分:0)

您可以离开加入PO_DISTRIBUTION_ALL并在GL_CODE_COMBINATIONS上创建条件加入,如下所示:

SELECT DISTINCT
AID.INVOICE_ID,
AID.AMOUNT,
AID.PERIOD_NAME,
GCC.SEGMENT1 as Organisation,
GCC.SEGMENT2,
GCC.SEGMENT3,
GCC.SEGMENT4,
INV.INVOICE_NUM,
INV.CREATION_DATE,
PO.SEGMENT1 as PO_Number,
SUP.VENDOR_NAME,
AID.LINE_TYPE_LOOKUP_CODE,
LINES.LINE_NUMBER
FROM AP_INVOICES_All INV 
INNER JOIN  AP_INVOICE_LINES_ALL LINES 
  ON INV.INVOICE_ID = LINES.INVOICE_ID 
INNER JOIN  AP_INVOICE_DISTRIBUTIONS_ALL AID 
  ON INV.INVOICE_ID = AID.INVOICE_ID 
LEFT JOIN PO_HEADERS_ALL PO 
  ON LINES.PO_HEADER_ID = PO.PO_HEADER_ID
LEFT JOIN PO_DISTRIBUTIONS_ALL PDA 
  ON PO.PO_HEADER_ID = PDA.PO_HEADER_ID
INNER JOIN  GL_CODE_COMBINATIONS GCC
  ON GCC.CODE_COMBINATION_ID = nvl(PDA.CODE_COMBINATION_ID, AID.DIST_CODE_COMBINATION_ID)
INNER JOIN
  POZ_SUPPLIERS_V SUP 
  ON INV.VENDOR_ID = SUP.VENDOR_ID 
WHERE AID.LINE_TYPE_LOOKUP_CODE NOT IN (  'REC_TAX',  'NONREC_TAX')
AND LINES.LINE_TYPE_LOOKUP_CODE NOT IN ('TAX')
ORDER BY
AID.INVOICE_ID,
LINES.LINE_NUMBER