1

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

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

4

You could try to use SQL Server's UNPIVOT operator, but honestly a plain union query might even perform better:

SELECT Name1 AS Name, Department1 AS Department, Location1 AS Location FROM yourTable
UNION ALL
SELECT Name2, Department2, Location2 FROM yourTable;

Regarding your expected ordering, there is no sort of id column in your original table which maintains to which name pair each record belongs. So, what I have written above might be the best we can do here.

Comments

0

Try This:

DECLARE @TestDemo AS TABLE(Name1 VARCHAR(10),Name2 VARCHAR(10),Department1 VARCHAR(10),Department2 VARCHAR(10),Location1 VARCHAR(10),Location2 VARCHAR(10))

    INSERT INTO @TestDemo VALUES('Jhon','Alex','IT','Marketing','London','Seattle')
    INSERT INTO @TestDemo VALUES('Mark','Dan','Sales','R&D','Paris','Tokyo')

    SELECT Name1 'Name',Department1 'Department',Location1  'Location' FROM @TestDemo
    UNION ALL
    SELECT Name2 'Name',Department2 'Department',Location2  'Location' FROM @TestDemo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.