Reputation: 151
I have a table like this:
col1 col2 col3
111 1 1
222 1 0
333 0 1
444 0 0
Here col2 = 1
means col1
is commercial, col3 = 1
means col1
is retail as well. How do I get a result like below?
ID Description
111 Commercial
111 Retail
222 Commercial
333 Retail
Upvotes: 7
Views: 124
Reputation: 35790
Can be done with UNPIVOT
also:
DECLARE @t TABLE
(
col1 INT ,
col2 INT ,
col3 INT
)
INSERT INTO @t
VALUES ( 111, 1, 1 ),
( 222, 1, 0 ),
( 333, 0, 1 ),
( 444, 0, 0 )
SELECT col1 ,
CASE WHEN col = 'col2' THEN 'Commercial'
ELSE 'Retail'
END AS Description
FROM @t UNPIVOT( r FOR col IN ( [col2], [col3] ) ) u
WHERE r <> 0
Upvotes: 0
Reputation: 1867
Uses almost the same as above but in a single result set
Select ID = col1, t.Description
from MyTable
cross apply (select Description = 'Commercial' where col2 = 1 union
select Description = 'Retail' where coll3 = 1)t
Upvotes: 1
Reputation: 726929
You can do it with a UNION ALL
:
SELECT ID = col1, 'Commercial' FROM MyTable WHERE col2=1
UNION ALL
SELECT ID = col1, 'Retail' FROM MyTable WHERE col3=1
Upvotes: 8