2
WITH DATA
     AS ( select ACCT_ID_1,  ACCT_ID, ACCT_ID_2 ... from two tables joined by criteria ),
DATA1
     AS (SELECT D1.*
           FROM DATA D1
          WHERE ACCT_ID_1 = ACCT_ID AND ACCT_ID_1 = '101'),
DATA2
     AS (SELECT D2.*
           FROM DATA D2
          WHERE ACCT_ID_2 = ACCT_ID AND ACCT_ID_2 = '101')

如果 data1 中有数据(没有来自 data2 的数据),我需要获取 data1,否则我需要从 data2 获取。可以使用 SQL 吗?

4

2 回答 2

4

这可能是我的做法:

WITH data1 AS (
  SELECT 1
  FROM dual
  WHERE 1=2 -- Set to 1 to reverse result
)
, data2 AS (
  SELECT 2
  FROM dual  
)
SELECT *
FROM data1
UNION ALL
SELECT *
FROM data2
WHERE NOT EXISTS (
  SELECT 1
  FROM data1
)

SQLFiddle为例。

于 2012-11-20T22:30:54.863 回答
0
SELECT ACCT_ID_1,  ACCT_ID, ACCT_ID_2, ...,
  IF EXISTS (SELECT D1.*
       FROM DATA D1
      WHERE ACCT_ID_1 = ACCT_ID AND ACCT_ID_1 = '101')
  THEN (SELECT D1.ACCT_ID_1
       FROM DATA D1
      WHERE ACCT_ID_1 = ACCT_ID AND ACCT_ID_1 = '101')
  ELSE (SELECT D2.ACCT_ID_2
       FROM DATA D2
       WHERE ACCT_ID_2 = ACCT_ID AND ACCT_ID_2 = '101')
  END IF
于 2012-11-20T22:18:46.683 回答