2017-04-19 136 views
1

使用SQL Server 2012,我有一個包含多個複選框字段的表格,其值顯然是1或0。我需要拉這些字段的任何地方的任何值都是1從多個sql列中逗號分隔的列表

所以:

ID  Building   Heavy   Municipal  Industry 
101  1     1    0    1 

結果:

ID    Type 
101    Building, Heavy, Industry 

我不能爲我的生活搞的語法。

回答

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 
+0

我認爲級聯必須改進,否則你可能會結束:'BuildingHeavyMunicipalIndustry'還是我錯了?哦,+1爲簡單的想法,雖然 –

+0

有一個額外的逗號..我會改善這個歡呼聲 – maSTAShuFu

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

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