如果在Oracle SQL中第一个字段具有值,如何使第二个字段为空

时间:2019-02-07 20:59:16

标签: sql oracle calculated-columns

我在ORACLE中有两个计算列(Ex3和EX12)。因此,无论哪个字段都有一个值(例如:ID 118189AC),id都希望将其保留在EX3中,但将EX12变为NULL。有什么建议吗?

SELECT *

FROM 
(SELECT ID,

CASE
    WHEN PORT IN ('CAP')
    THEN 3
    ELSE NULL
END AS EX3,

CASE
    WHEN PORT NOT IN ('TEST1', 'TEST2', 'TEST3')
    THEN 12
    ELSE NULL
END AS EX12

FROM LAN.DETAILS)
WHERE (EX3 IS NOT NULL OR EX12 IS NOT NULL)
ORDER BY ID ASC


ID         EX3     EX12
118051PU            12
118052PU            12
118189AC    3       12
118397PU            12
118451AC    3       12
119343AC    3       12
119387PU            12
119484PU            12
119772PU            12
119997PU            12
120320AC    3       12

3 个答案:

答案 0 :(得分:1)

我认为您只想使用case表达式:

select id, ex3,
       (case when ex3 is not null and ex12 is not null then null else ex12 end) as ex12
. . .

答案 1 :(得分:1)

NVL2(a, b, c)如果b不为null,则返回a,否则返回c

在您的情况下:NVL2(ex3, null, ex12)不为空时,null将返回ex3。否则,它将返回ex12

https://docs.oracle.com/cd/B12037_01/server.101/b10759/functions096.htm

答案 2 :(得分:0)

我最终在WHERE子句中创建了一个子查询,该子查询限制了为EX3返回的ID。谢谢大家