SQL Server将行值转换为列

时间:2019-05-15 04:38:15

标签: sql sql-server

我有一个这样的SQL表

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

如何以以下格式查询这些结果:

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

3 个答案:

答案 0 :(得分:5)

使用cross apply

DEMO

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

输出:

name    department  location
Jhon    IT           London
Alex    Marketing    Seattle
Mark    Sales        Paris
Dan     R&D T        Tokyo

答案 1 :(得分:3)

您可以尝试使用SQL Server的from django.shortcuts import render, get_object_or_404 from .models import Post def home (request) : context = { 'titel': 'homepage', 'posts': post.objects.all() } return render (request, 'site.html', context) def post_detail(request, post_id): post = get_object_or_404(Post,id=post_id) context = { 'title': post, 'post': post, } return render(request, 'details.html', context) 运算符,但老实说,普通的联合查询甚至可能会更好:

UNPIVOT

关于期望的顺序,原始表中没有ID列,该ID列维护每个记录所属的名称对。所以,我上面写的可能是我们在这里可以做的最好的事情。

答案 2 :(得分:0)

尝试一下:

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