使用SQL Server 2012,我有一個包含多個複選框字段的表格,其值顯然是1或0。我需要拉這些字段的任何地方的任何值都是1從多個sql列中逗號分隔的列表
所以:
ID Building Heavy Municipal Industry
101 1 1 0 1
結果:
ID Type
101 Building, Heavy, Industry
我不能爲我的生活搞的語法。
使用SQL Server 2012,我有一個包含多個複選框字段的表格,其值顯然是1或0。我需要拉這些字段的任何地方的任何值都是1從多個sql列中逗號分隔的列表
所以:
ID Building Heavy Municipal Industry
101 1 1 0 1
結果:
ID Type
101 Building, Heavy, Industry
我不能爲我的生活搞的語法。
假設數列是少數可以只使用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
您還可以使用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
我認爲級聯必須改進,否則你可能會結束:'BuildingHeavyMunicipalIndustry'還是我錯了?哦,+1爲簡單的想法,雖然 –
有一個額外的逗號..我會改善這個歡呼聲 – maSTAShuFu