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
精彩评论