SQL Server convert row values to columns

问题: I have an SQL table like this Name1 Name2 Department1 Department2 Location1 Location2 ------------------------------------------------------------------...

问题:

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

回答1:

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

回答2:

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.


回答3:

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
  • 发表于 2019-05-19 21:38
  • 阅读 ( 142 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除