结合SQL字段和从位转换为可读句子

时间:2011-10-03 10:17:28

标签: sql

例如,如果我有两个字段,如“狗”和“猫”,则定义一个人是否有狗或猫;而且,它们是比特类型。并且,我想为每个人组合这些字段来说出像USER这样的东西,“有一只狗和一只猫”,如下所示: -

SQL原创 -

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'

是否有人对使用SQL实现此类功能的最佳方式有任何想法。或者,我在哪里可以获得类似功能的副本。

谢谢,

里克。

1 个答案:

答案 0 :(得分:3)

试试这个:

 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 

更新:对于超过2列的动态,您需要通过这种方式将文本设置为可读句子:

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