Pivot组多列SQL

时间:2018-04-20 02:53:27

标签: sql sql-server tsql pivot sql-server-2014

在SQL中,如何将多个列合并到一个包含多行的列中? 例如:

name  |  age  |  gender
------+-------+---------
John  |   20  |    M
Jill  |   21  |    F
Exam  |   22  |    M

我想得到这张表:

Exam  |  John |  Jill
------+-------+---------
22    |   21  |   20
M     |   F   |   M

2 个答案:

答案 0 :(得分:4)

你可以这样做。

PIVOT使用两个UNION ALL查询将它们组合起来

SELECT CAST(Exam AS VARCHAR(10)) Exam,
       CAST(Jill AS VARCHAR(10)) Jill,
       CAST(John AS VARCHAR(10)) John
FROM
(
    select age,name
    from T
) as x
PIVOT 
(
    MAX(Age) FOR name IN ([Exam],[John],[Jill])
)AS P1
UNION ALL
SELECT Exam,Jill,John FROM
(
    select name,gender
    from T
) as x
PIVOT 
(
    MAX(gender) FOR name IN ([Exam],[John],[Jill])
)AS P1

sqlfiddle:http://sqlfiddle.com/#!18/a437d/6

答案 1 :(得分:2)

您可以使用单个查询执行此操作 - 基本上是无法转移和条件聚合:

select max(case when v.name = 'Exam' then v.val end) as exam,
       max(case when v.name = 'John' then v.val end) as john,
       max(case when v.name = 'Jill' then v.val end) as jill
from t cross apply
     (values (t.name, cast(t.age as varchar(10)), 1),
             (t.name, t.gender, 2)
     ) v(name, val, which)
group by which;

Here是SQL小提琴。

您可以将值转换为您喜欢的任何字符类型,以实现值之间的兼容性。您希望将数值和字符串放在同一列中,因此它们必须具有相同的类型。