又一个SQL Pivot

时间:2017-04-19 22:13:54

标签: sql-server pivot

关于旋转的快速问题。我有以下数据:

c1  | c2  | c3  | c4  | c5
pk1 | r12 | r13 | r14 | r15
pk2 | r22 | r23 | r24 | r25
pk3 | r32 | r33 | r34 | r35

我想将其旋转如下

[c1] | pk1 | pk2 | pk3
 c2  | r12 | r22 | r32
 c3  | r13 | r23 | r33
 c4  | r14 | r24 | r34
 c5  | r15 | r25 | r35

在我的示例中,case列c1是主键。 提前感谢您的帮助。

PS:在那之前我会再给它一次。

2 个答案:

答案 0 :(得分:1)

你可以UNPIVOT然后PIVOT表。 这是hardcode版本。

DECLARE @SampleData AS TABLE
(
   c1 varchar(10),
   c2 varchar(10),
   c3 varchar(10),
   c4 varchar(10),
   c5 varchar(10)
)

INSERT INTO @SampleData
VALUES 
('pk1', 'r12','r13','r14','r15'),
('pk2', 'r22','r23','r24','r25'),
('pk3', 'r32','r33','r34','r35')

;with pvt AS
   (
   SELECT c1, ColName, Value 
   FROM 
   (
      SELECT * FROM @SampleData sd
   ) src
   UNPIVOT
   (
      Value FOR ColName IN (c2,c3,c4,c5)
   ) pvt
)

SELECT ColName AS [c1], [pk1], [pk2], [pk3]
FROM 
(
   SELECT * FROM pvt p
) src
PIVOT
(
   Max(Value) FOR c1 IN ([pk1], [pk2], [pk3])
) pvt

演示链接:Rextester

答案 1 :(得分:0)

这有点长而且难看,但它会转动你的数据。

WITH pk1 AS (
 SELECT c1,c2 'pk1'
 FROM Table_1
 WHERE c1 = 'pk1'
 UNION 
 SELECT c1,c3 'pk1'
 FROM Table_1
 WHERE c1 = 'pk1'
 UNION 
 SELECT c1,c4 'pk1'
 FROM Table_1
 WHERE c1 = 'pk1'
 UNION 
 SELECT c1,c5 'pk1'
 FROM Table_1
 WHERE c1 = 'pk1'),
pk1_rn AS
(SELECT ROW_NUMBER() OVER(PARTITION BY c1 ORDER BY pk1 ASC) AS Row#, pk1
FROM pk1),

pk2 AS (
 SELECT c1,c2 'pk2'
 FROM Table_1
 WHERE c1 = 'pk2'
 UNION 
 SELECT c1,c3 'pk2'
 FROM Table_1
 WHERE c1 = 'pk2'
 UNION 
 SELECT c1,c4 'pk2'
 FROM Table_1
 WHERE c1 = 'pk2'
 UNION 
 SELECT c1,c5 'pk2'
 FROM Table_1
 WHERE c1 = 'pk2'),
pk2_rn AS
(SELECT ROW_NUMBER() OVER(PARTITION BY c1 ORDER BY pk2 ASC) AS Row#, pk2
FROM pk2),

pk3 AS (
 SELECT c1,c2 'pk3'
 FROM Table_1
 WHERE c1 = 'pk3'
 UNION 
 SELECT c1,c3 'pk3'
 FROM Table_1
 WHERE c1 = 'pk3'
 UNION 
 SELECT c1,c4 'pk3'
 FROM Table_1
 WHERE c1 = 'pk3'
 UNION 
 SELECT c1,c5 'pk3'
 FROM Table_1
 WHERE c1 = 'pk3'),
pk3_rn AS
(SELECT ROW_NUMBER() OVER(PARTITION BY c1 ORDER BY pk3 ASC) AS Row#, pk3
FROM pk3)

SELECT pk1_rn.pk1,pk2_rn.pk2,pk3_rn.pk3
FROM pk1_rn
 JOIN pk2_rn ON pk1_rn.Row# = pk2_rn.Row#
 JOIN pk3_rn ON pk1_rn.Row# = pk3_rn.Row#