6

I am using SQL Server 2012 for my database. Now, I have one table with following details.

ID                COLUMN1              COLUMN2
1                    A                    B

Now i want result like this.

ID                   Values
1                       A   
1                       B

Can any one suggest me how to do? I know i can do using pivot or unpivot. but i dont know how to do? and is there other way to do this?

Please help me out to write query for the same.

Thanks in advance.

Taryn
  • 242,637
  • 56
  • 362
  • 405
Brijesh Patel
  • 2,901
  • 15
  • 50
  • 73

2 Answers2

6

You can use UNPIVOT to get the final result:

select id, value
from yourtable
unpivot
(
  value
  for col in (COLUMN1, COLUMN2)
) u;

See SQL Fiddle with Demo

Or you can use CROSS APPLY to get it:

select id, value
from yourtable
cross apply
(
  values ('COLUMN1', COLUMN1), ('COLUMN2', COLUMN2)
) c (col, value)

See SQL Fiddle with Demo

Taryn
  • 242,637
  • 56
  • 362
  • 405
3
select id, col1 as value
from your_table
union all
select id, col2 as value
from your_table
juergen d
  • 201,996
  • 37
  • 293
  • 362