逗号从多个sql列分隔列表

时间:2017-04-19 03:00:52

标签: sql sql-server tsql string-aggregation

使用SQL Server 2012,我有一个包含多个复选框字段的表,显然值为1或0。我需要拉出任何这些值为1的字段。

所以:

ID      Building            Heavy         Municipal       Industry
101        1                   1              0               1

结果:

ID               Type
101              Building, Heavy, Industry

我不能为我的生活弄清楚语法。

3 个答案:

答案 0 :(得分:2)

假设数列很少,可以使用IIF 2012+,否则就是

确定起始位置和结束的子串。

select ID, 
    SUBSTRING(
    IIF(Building=1,', Building','') + 
            IIF(Heavy=1,', Heavy','') + 
            IIF(Municipal=1,', Municipal','') + 
            IIF(Industry=1,', Industry','')
            ,3,100)   -- substring to start from pos 3 and ends at position 100 depends on the desired length
           Type
from table

答案 1 :(得分:1)

这样做的一种方法是, 步骤1.取消表格

SELECT ID, Sub, SubVal
INTO #t2
FROM (SELECT * FROM #t)t
UNPIVOT
(
    SubVal FOR Sub IN (Building,Heavy, Muncipal, Industry)
) as un

enter image description here

步骤2:用于FOR XML PATH,

SELECT DISTINCT ID,
    STUFF((
        SELECT ' , ' + t2.Sub  
        FROM #t2 t2
        WHERE SubVal = 1
        FOR XML PATH('')
    ), 1, 2, '')   AS Type
FROM #t2 ct

enter image description here

答案 2 :(得分:0)

您也可以使用CASE语句:

create table test (
    id int,
    building int,
    heavy int,
    municipal int,
    industry int
);
insert into test values (101, 1, 1, 0, 1);

with data as (
    select id,
        case when building = 1 then 'Building,' else '' end +
        case when heavy = 1 then 'Heavy,' else '' end +
        case when municipal = 1 then 'Municipal,' else '' end +
        case when industry = 1 then 'Industry,' else '' end as fld
    from test
)
select id, left(fld, len(fld)-1) as fld from data;

示例:http://rextester.com/CKGES46149

结果:

id  fld
101 Building,Heavy,Industry

如果需要逗号之后的空格,请添加一个稍微修改,如下所示:

with data as (
    select id,
        rtrim(
        case when building = 1 then 'Building, ' else '' end +
        case when heavy = 1 then 'Heavy, ' else '' end +
        case when municipal = 1 then 'Municipal, ' else '' end +
        case when industry = 1 then 'Industry, ' else '' end
        ) as fld
    from test
)
select id, left(fld, len(fld)-1) as fld from data;

结果:

id  fld
101 Building, Heavy, Industry

示例:http://rextester.com/OJNEQ98420