组合SQL字段并将位转换为可读语句

组合SQL字段并将位转换为可读语句,sql,Sql,例如,如果我有两个字段,例如“Dog”和“Cat”,用于定义一个人是养狗还是养猫;而且,它们是位类型。我想把这些字段组合起来,让每个人都说“有一只狗和一只猫”,如下所示:- SQL原始-- SQL与组合-- 有没有人对使用SQL实现这类功能的最佳方式有什么想法。或者,在哪里可以获得类似功能的副本 谢谢 Ric.试试这个: select username, case when dog = 1 and cat = 1 then 'has a dog and a cat'

例如,如果我有两个字段,例如“Dog”和“Cat”,用于定义一个人是养狗还是养猫;而且,它们是位类型。我想把这些字段组合起来,让每个人都说“有一只狗和一只猫”,如下所示:-

SQL原始--

SQL与组合--

有没有人对使用SQL实现这类功能的最佳方式有什么想法。或者,在哪里可以获得类似功能的副本

谢谢

Ric.

试试这个:

 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 

这里有很多字段,而不仅仅是dog和cat。这只是一个例子,所以要做到这一点,所有的可能性都是不可行的。我需要一些更像单个if语句的东西附加到一个字段上,然后你需要考虑动态查询。我相信我会发现你给我的东西对其他查询有用,但我有发现我可以使用作为查询一部分执行的函数返回结果。所以从表中选择username,function(username),然后function将使用if语句返回一个组合结果。
 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 
select username, 'has' +  
        replace(replace(dog,'1',' a dog'),'0',' no dog') +
        replace(replace(cat,'1',' a cat'),'0',' no cat') 
from table