Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display two column values as two row in SQL

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.

like image 666
Brijesh Patel Avatar asked Oct 10 '13 08:10

Brijesh Patel


People also ask

How do I make two rows into two columns in SQL?

atable ) SELECT Name, [Value+] = [1], [Value-] = [2] FROM ranked PIVOT (MIN(Value) FOR RN IN ([1], [2])) AS p ; As you can see it gives the ranking of 1 to each row with the lower Sequence per Name , and ranking of 2 to that with the higher Sequence .

How do I view two rows in SQL?

You may use the IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple rows. Contents: Using IN operator with a Multiple Row Subquery. Using NOT IN operator with a Multiple Row Subquery.

How do I display two rows in one row in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.


2 Answers

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

like image 143
Taryn Avatar answered Oct 29 '22 06:10

Taryn


select id, col1 as value
from your_table
union all
select id, col2 as value
from your_table
like image 33
juergen d Avatar answered Oct 29 '22 07:10

juergen d