oracle 在SQL中使用CASE WHEN子句时如何将相关子查询转换为连接

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

我有一个疑问:

CASE WHEN T3.ID_NUMBER IN (20216) THEN 'Retired'

我想向其中添加一个子查询:

CASE WHEN T3.ID_NUMBER IN (20216) 
AND T1.DEPARTMENT 

NOT IN 

(SELECT T1.DEPARTMENT WHERE
((T.JOB_TYPE IN ('TESTING') AND T2.GROUP IN ('A', 'C', 'D')) OR 
((T.JOB_TYPE IN ('PRODUCTION') AND T2.GROUP IN ('G', 'E')))

THEN 'Retired'

由于SQL中的CASE WHEN子句不支持相关子查询(这里是not in子句后的子查询),那么我们如何将其转换为JOIN呢?
要转换为联接的子查询:

(SELECT T1.DEPARTMENT WHERE
((T.JOB_TYPE IN ('TESTING') AND T2.GROUP IN ('A', 'C', 'D')) OR 
((T.JOB_TYPE IN ('PRODUCTION') AND T2.GROUP IN ('G', 'E')))

运行上面的代码,显示:不支持这种形式的相关查询-请考虑重写。
如何将其转换为JOIN?

os8fio9y

os8fio9y1#

编辑了我的答案:
在子查询中尝试使用左连接和非重复连接,如下所示:

LEFT JOIN (SELECT DISTINCT T1.DEPARTMENT AS DEPARTMENT WHERE
((T.JOB_TYPE IN ('TESTING') AND T2.GROUP IN ('A', 'C', 'D')) OR 
((T.JOB_TYPE IN ('PRODUCTION') AND T2.GROUP IN ('G', 'E'))) TT1 ON T1.DEPARTMENT = TT1.DEPARTMENT

select语句中的case应如下所示:

CASE WHEN T3.ID_NUMBER IN (20216) AND TT1.DEPARTMENT IS NOT NULL THEN 'Retired' ELSE '' END AS Retired

相关问题