当我需要验证select查询的返回是空的还是有值时,可以执行SELECT CASE,decode,nvl或其他查询函数? 例如,我有这个:
Record | type | id_customer
-------+--------+-------------
1 | T | cus1
2 | A | cus2
3 | T | cus3
4 | | cus4
如果我这样做:
select decode(type,'T','Main','A','Adicional','none') from table where record=1;
我得到了主。
如果我这样做:
select decode(type,'T','Main','A','Adicional','none') from table where record=4;
我没有。
但如果我这样做:
select decode(type,'T','Main','A','Aditional','none') from table where record=5;
我什么都没得到,而且是逻辑。所以,我需要在行存在时获取解码值,如果行不存在则需要文本。
所以,我尝试使用SELECT CASE但是无法使用COUNT获取值。例如:
SELECT
CASE
WHEN count(1)>0 THEN decode(type,'T','Main','A','Aditional','none')
ELSE '-'
END
FROM TABLE WHERE record=5;
得到一个' - '或如果记录为2则相同,获得' Aditional'
非常感谢。
答案 0 :(得分:2)
您可以使用汇总函数min
或max
外表达式:
select max(decode(type,'T','Main','A','Aditional','none'))
from table
where record=5;
如果查询返回一行,则获得该行的值。如果查询返回0行,则会得到NULL
然后,您可以使用NULL
替换nvl
:
select nvl(max(decode(type,'T','Main','A','Aditional','none')), ' - ')
from table
where record=5;
修改强>
此外,如果您需要从几个中选择一个字符串:
select decode(max(decode(type,'T', 2, 'A', 1, 0)), 0, 'none', 1, 'Additional', 2, 'Main', null, ' - ')
from table
where record=5;
答案 1 :(得分:1)
这是一个选项:
select decode(type,'T','Main','A','Aditional','none')
from table
where record = 5
union all
select '-'
from dual
where not exists (select 1 from table where record = 5);
如果没有record
= 5的记录退出,则会选择'-'
= 5的记录并将其与record
统一。请查看此Fiddle。