开发者

Combine SQL fields and Convert from bit to readable sentence

开发者 https://www.devze.com 2023-04-10 10:56 出处:网络
If, for example, I had two fields such as \'Dog\' and \'Cat\' that defines whether a person has a dog or cat; and, they are bit types. And, I wanted to combine these fields for each person to say some

If, for example, I had two fields such as 'Dog' and 'Cat' that defines whether a person has a dog or cat; and, they are bit types. And, I wanted to combine these fields for each person to say something开发者_StackOverflow社区 like USER, 'has a dog and a cat' such as the following:-

SQL original --

select username, dog, cat from table
username   dog    cat
john       1      0
tim        1      1

SQL with combined --??

username   petstatus
john       'has a dog but no cat'
tim        'has a dog and a cat'

Does anybody have any ideas on what would be the best way to achieve this type of functionality using SQL. Or, where can I get a copy of similar functionality.

Thanks,

Ric.


Try this :

 select username, 
       case when dog = 1 and cat = 1 then 'has a dog and a cat' 
       when dog = 1 and cat = 0 then 'has a dog but no cat' 
       when dog = 0 and cat = 1 then 'has a cat but no dog' 
       when dog = 0 and cat = 0 then 'has a no cat and no dog' end as petstatus
from table 

UPDATE : For more than 2 columns dynamically, you need to set text as like readable sentence by this way :

select username, 'has' +  
        replace(replace(dog,'1',' a dog'),'0',' no dog') +
        replace(replace(cat,'1',' a cat'),'0',' no cat') 
from table 
0

精彩评论

暂无评论...
验证码 换一张
取 消