Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying a table in SQL Server based on permutation of column2 and 3

Tags:

sql

sql-server

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  
like image 549
user1415173 Avatar asked Jun 05 '15 06:06

user1415173


2 Answers

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
like image 128
Sergey Kalinichenko Avatar answered Nov 05 '22 01:11

Sergey Kalinichenko


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
like image 32
Azar Avatar answered Nov 05 '22 01:11

Azar