我有以下情况(下表),我想根据它们是否为NULL来选择“X”或“Y”。
X Y pick
null not null Y
not null not null X
not null null X
包含数据'X'和'Y'或UNION ALLed的行如下所示:
select 'X' as a
union all
select 'Y' as a
所以我尝试了以下SQL,但不确定“rownum< = 1”部分。仅当UNION ALL保留时,这将起作用(对于X和Y都不为空的情况) 我查询两行的顺序。
select a from
(
select 'X' as a
union all
select 'Y' as a
) where a is not null and rownum<=1;
select a from
(
select null as a
union all
select 'Y' as a
) where a is not null and rownum<=1;
select a from
(
select 'X' as a
union all
select null as a
) where a is not null and rownum<=1;
以上是正确的方法吗?任何见解都将非常感激
答案 0 :(得分:1)
答案 1 :(得分:0)
如果您想在SQL中使用特定订单,则必须要求它。你可以扩展你的联盟:
select a from (
select a,rownum as rn from
(
select 'X' as a, 0 as Priority from dual
union all
select 'Y' as a, 1 as Priority from dual
) where a is not null order by Priority
) where rn = 1
虽然我承认我对甲骨文不太好。我相信rownum在WHERE
子句中做了奇怪的事情,这就是为什么我引入了额外级别的查询。