1

Using SQL Server 2012, I have a table containing multiple checkbox fields where the values are 1 or 0, obviously. I need to pull any of these fields where any of these values are 1.

So:

ID      Building            Heavy         Municipal       Industry
101        1                   1              0               1

Results:

ID               Type
101              Building, Heavy, Industry

I cannot for the life of me figure out the syntax.

RobF
  • 11
  • 2

3 Answers3

2

assuming the number columns are few can just use IIF 2012+ otherwise case

Substring to determine starting position and ending.

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
RoMEoMusTDiE
  • 4,739
  • 1
  • 17
  • 26
2

One way to do this is, Step 1. Unpivot the table

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

Step 2: Use for 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

observer
  • 316
  • 3
  • 9
0

You can also use CASE statement like so:

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;

Example: http://rextester.com/CKGES46149

Result:

id  fld
101 Building,Heavy,Industry

If a space after comma is needed, add a slight modification like so:

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;

Result:

id  fld
101 Building, Heavy, Industry

Example: http://rextester.com/OJNEQ98420

zedfoxus
  • 35,121
  • 5
  • 64
  • 63