用pl / sql中的子查询替换不匹配的值

时间:2013-08-29 08:42:53

标签: mysql sql sql-server oracle

考虑下表

Table

SELECT QUEUENAME, 
       PRIORITY 
  FROM QUEUES 
 WHERE QUEUENAME IN ('Windows','Macintosh')

根据上述查询和表值,{strong>" Macintosh" 没有QueueName。因此,我希望只要在where子句中没有匹配的值,就应该选择QueueName "未知" 的值及其值。

请告诉我如何实现此查询?

我正在寻找的输出是

| QUEUENAME | PRIORITY |
|-----------|----------|
|   Windows |        1 |
|   Unknown |        3 |

3 个答案:

答案 0 :(得分:2)

更新你在找这样的东西吗?

SELECT COALESCE(q.queuename, q2.queuename) queuename,
       COALESCE(q.priority, q2.priority) priority
  FROM 
(
  SELECT 'Windows' queuename FROM dual
  UNION ALL
  SELECT 'Macintosh' FROM dual
) s LEFT JOIN queues q
    ON s.queuename = q.queuename JOIN queues q2
    ON q2.queuename = 'Unknown'

输出:

| QUEUENAME | PRIORITY |
|-----------|----------|
|   Windows |        1 |
|   Unknown |        3 |

这是 SQLFiddle 演示(Oracle)
这是 SQLFiddle 演示(SQL Server)

答案 1 :(得分:0)

create table queues as
select 'Windows' as queuename, 1 as priority from dual union all
select 'Linux'   as queuename, 2 as priority from dual union all
select 'Unknown' as queuename, 3 as priority from dual
;

with data_(qname) as (
select 'Windows'   from dual union all
select 'Macintosh' from dual
)
select coalesce(queues.queuename, default_.queuename) as queuename,
       coalesce(queues.priority, default_.priority) as priority
from data_
left outer join queues on queues.queuename = data_.qname
inner join queues default_ on default_.queuename = 'Unknown'
;

QUEUENA   PRIORITY
------- ----------
Windows      1
Unknown      3

答案 2 :(得分:0)

这是一个查询

select * from queues where queuename in ('Windows','Macintosh')
UNION ALL
select * from queues where queuename in 
(
select decode
(
(
select count(queuename) from queues 
where queuename NOT IN  ('Windows','Macintosh')
),1,NULL,'Unknown')
queuename from queues where queuename NOT in ('Windows','Macintosh'))

查询提供您的预期结果

如果你给windows Macintosh它会给windows未知。 如果你给linux macintosh它给linux未知 如果你给windows不知道它给windows不知道 如果你给Linux不知道它给linux提供了未知数 如果你给Linux windows它会给linux windows

我在过去的4个月里只为oracle编写代码,所以有些经验丰富的代码可以提供比这更简单的代码......

你必须在3个地方给出位置