Skip to content
Advertisement

SQL Server convert row values to columns

I have an SQL table like this

 Name1    Name2    Department1    Department2    Location1   Location2  
 ----------------------------------------------------------------------
 Jhon     Alex     IT             Marketing      London      Seattle
 Mark     Dan      Sales          R&D            Paris       Tokyo

How can I query these results in this format:

 Name        Department      Location
 ---------------------------------------
 Jhon        IT              London
 Alex        Marketing       Seattle
 Mark        Sales           Paris
 Dan         R&D             Tokyo

Advertisement

Answer

Use cross apply

DEMO

select name,department,location
from t
cross apply
(
  values(name1,department1,location1),(name2,department2,location2)
)cc (name, department,location)

OUTPUT:

name    department  location
Jhon    IT           London
Alex    Marketing    Seattle
Mark    Sales        Paris
Dan     R&D T        Tokyo
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement