Select Case, when no data return

余生长醉 提交于 2019-12-11 10:37:39

问题


it is possible do a SELECT CASE, decode, nvl or another query function when I need verify if the return of a select query is empty or has a value? For example, I have this:

Record |  type  | id_customer
-------+--------+-------------
1      |    T   | cus1
2      |    A   | cus2
3      |    T   | cus3
4      |        | cus4

If I do this:

select decode(type,'T','Main','A','Adicional','none') from table where record=1;

I get Main.

If I fo this:

select decode(type,'T','Main','A','Adicional','none') from table where record=4;

I get none.

But if I do this:

select decode(type,'T','Main','A','Aditional','none') from table where record=5;

I get nothing, and is logic. So, I need get the decode value when the row exist and a text if the rows no exist.

So, I tried with SELECT CASE but is not posible get a value using COUNT. For example like this:

SELECT 
CASE 
WHEN count(1)>0 THEN decode(type,'T','Main','A','Aditional','none')
ELSE '-'
END
FROM TABLE WHERE record=5;

And get a ' - ', or the same if the record is 2, get 'Aditional'

Thanks a lot.


回答1:


You can use aggregate functions min or max outside expression:

select max(decode(type,'T','Main','A','Aditional','none')) 
from table
where record=5;

If query returns one row, you get value of that row. If query returns 0 rows, you get NULL.
Then you can replace NULL using nvl:

select nvl(max(decode(type,'T','Main','A','Aditional','none')), ' - ')
from table
where record=5;

EDIT
Also, if you need to choose one string from several:

select decode(max(decode(type,'T', 2, 'A', 1, 0)), 0, 'none', 1, 'Additional', 2, 'Main', null, ' - ')
from table
where record=5;



回答2:


This is an option:

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);

It selects records with record = 5 and unifies them with '-', if no records exits with record = 5. Check out this Fiddle.



来源:https://stackoverflow.com/questions/29707937/select-case-when-no-data-return

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!