如何将所有YES记录连接到一个列表中?

时间:2013-04-30 15:03:40

标签: sql xml tsql list concatenation

如何将所有“是”记录合并到一个列表中?我有以下脚本,我想组合成一个varchar列表,​​理想情况下使用XML或本机SQL函数。这些值是1或0.我希望这些值仅在1:

时出现
select
x.Energetic,
x.Undistressed,
x.Wellnourished,
x.Goodhygiene

From
health_x x

在这个例子中,如果Energetic和Wellnourished是1而其他人是0,那么我希望它显示为:

Energetic, Wellnourished

2 个答案:

答案 0 :(得分:1)

select stuff((
select 
case when x.Energetic = 1 then ', Energetic' else '' end + 
case when x.Undistressed = 1 then ', Undistressed' else '' end + 
case when x.Wellnourished = 1 then ', Wellnourished' else '' end + 
case when x.Goodhygiene = 1 then ', Goodhygiene' else '' end

From
health_x x
for xml path('')
),1,2,'');

答案 1 :(得分:1)

您可以使用条件连接执行此操作。

诀窍是正确放入分隔符。此版本在每个字符串前放置,,然后使用stuff()删除第一个匹配项:

select STUFF((case when x.Energetic = 1 then ', Energetic' else '' end) +
             (case when x.Undistressed = 1 then ', Undistressed' else '' end) +
             (case when x.Wellnourished = 1 then ', Wellnourished' else '' end) +
             (case when x.Goodhygiene = 1 then ', Goodhygiene' else '' end),
             1, 2, ''
            )
from health_x x