Oracle SQL - 用于选择特定内连接的IF / CASE语句

时间:2018-04-25 15:08:35

标签: sql oracle

这是我的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 
   LEFT JOIN
      PO_DISTRIBUTIONS_ALL PDA 
      ON INV.INVOICE_ID = PDA.PO_DISTRIBUTIONS_ALL 
WHERE
   AID.LINE_TYPE_LOOKUP_CODE NOT IN 
   (
      'REC_TAX',
      'NONREC_TAX'
   )
   AND LINES.LINE_TYPE_LOOKUP_CODE NOT IN 
   (
      'TAX'
   )

END


ORDER BY
   AID.INVOICE_ID,
   LINES.LINE_NUMBER

我正在寻找类似下面的内容。我想说的是,如果PO.SEGMENT为null,则使用指定的连接从表中选择列。根据PO.SEGMENT是否为null,在连接中使用不同的列。这容易实现吗?

CASE 

WHEN PO.SEGMENT IS NOT NULL 
THEN SEGMENT1,SEGMENT2,SEGMENT3,SEGMENT4 
FROM GCC.CODE_COMBINATION_ID 
WHERE PDA.CODE_COMBINATION_ID = GCC.CODE_COMBINATION_ID

WHEN PO.SEGMENT IS NULL 
THEN SEGMENT1,SEGMENT2,SEGMENT3,SEGMENT4 
FROM GCC.CODE_COMBINATION_ID 
WHERE AID.DIST_CODE_COMBINATION_ID = GCC.CODE_COMBINATION_ID

END 

1 个答案:

答案 0 :(得分:1)

如何重新构造逻辑,以便只有一个ON子句:

ON
    (PO.SEGMENT IS NOT NULL AND PDA.CODE_COMBINATION_ID = GCC.CODE_COMBINATION_ID) OR
    (PO.SEGMENT IS NULL AND AID.DIST_CODE_COMBINATION_ID = GCC.CODE_COMBINATION_ID)

我遗漏了其余查询的其他详细信息,但我建议这样做,因为有可能通过谨慎的逻辑来实现您想要的目标。