Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query ; horizontal to vertical

I'm stuck with a SQL query (SQL Server) that involves converting horizontal rows to vertical rows

Below is my data

No      Flag_1    Flag_2    Flag_3
---      ----      -----     -----
A         1         2         3
B         4         1         6

After conversion , the table should be

No     FlagsName    Flag_value
--      ----        ----------
A        Flag_1        1
A        Flag_2        2  
A        Flag_3        3
B        Flag_1        4
B        Flag_2        1
B        Flag_3        6

Any input on this would be helpful?

I'm trying to play around ROW_NUMBER over partition. but it is not working somehow !!!

Thanks !!!

like image 347
user1141584 Avatar asked Sep 19 '12 19:09

user1141584


People also ask

How do I show SQL results vertically?

You can output query results vertically instead of a table format. Just type \G instead of a ; when you end you queries in mysql prompt.

How do I display a string vertically in SQL?

DECLARE @string VARCHAR(256) = 'welcome' DECLARE @cnt INT = 0; WHILE @cnt < len(@string) BEGIN SET @cnt = @cnt + 1; PRINT SUBSTRING ( @string ,@cnt , 1 ) END; In essence you loop through the length of the string. You print the character at the location of the index of the loop and print that.


1 Answers

You can use a UNION ALL:

select No, 'Flag_1' as FlagName, Flag_1 as Flag_Value
from yourtable
union all
select No, 'Flag_2' as FlagName, Flag_2 as Flag_Value
from yourtable
union all
select No, 'Flag_3' as FlagName, Flag_3 as Flag_Value
from yourtable

Or an UNPIVOT:

select no, FlagsName, flag_value
from yourtable
unpivot
(
    flag_value
    for FlagsName in (Flag_1, Flag_2, Flag_3)
) u

See SQL Fiddle With Demo

like image 90
Taryn Avatar answered Sep 18 '22 00:09

Taryn