使用 T-SQL 旋转 row/column
Pivoting row/column using T-SQL
以下场景的 T-SQL 查询如何:
Select * from Table1
col1|col2|col3
--------------
xxxx|1111|2222
yyyy|3333|4444
至
col1|col2
---------
xxxx|yyyy
1111|3333
2222|4444
也许是这样的。添加另一列用于演示目的,请注意它仅在数据类型相同时才有效:
;WITH CTE AS
(
SELECT
row_number() over (order by (select null)) row1,
col1, col2, col3
FROM
-- this would be replaced by your table
(values('xxxx', '1111', '2222'),('yyyy', '3333', '4444')) p(col1,col2,col3)
), CTE2 as
(
SELECT
items,
row1,
row_number() over(partition by row1 order by (select 1)) pos
FROM CTE
UNPIVOT
(Items FOR Seq IN ([col1], [col2], [col3])) AS unpvt
)
SELECT
[1] col1, [2] col2, [3] col3
FROM
cte2
PIVOT (max(items) FOR [row1] IN ([1], [2], [3])) AS pvt
结果:
col1 col2 col3
xxxx yyyy NULL
1111 3333 NULL
2222 4444 NULL
你可以试试这个:
DECLARE @DataSource TABLE
(
[Col1] VARCHAR(4)
,[Col2] VARCHAR(4)
,[Col3] VARCHAR(4)
);
INSERT INTO @DataSource ([Col1], [Col2], [Col3])
VALUES ('xxxx', '1111', '2222')
,('yyyy', '3333', '4444');
SELECT [1] AS [col1]
,[2] AS [col2]
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS [RowID]
,[Col1]
,[Col2]
,[Col3]
FROM @DataSource
)DS
UNPIVOT
(
[Value] FOR [Column] IN ([Col1],[Col2], [Col3])
) UNPVT
PIVOT
(
MAX([Value]) FOR [RowID] IN ([1], [2])
) PVT
以下场景的 T-SQL 查询如何:
Select * from Table1
col1|col2|col3
--------------
xxxx|1111|2222
yyyy|3333|4444
至
col1|col2
---------
xxxx|yyyy
1111|3333
2222|4444
也许是这样的。添加另一列用于演示目的,请注意它仅在数据类型相同时才有效:
;WITH CTE AS
(
SELECT
row_number() over (order by (select null)) row1,
col1, col2, col3
FROM
-- this would be replaced by your table
(values('xxxx', '1111', '2222'),('yyyy', '3333', '4444')) p(col1,col2,col3)
), CTE2 as
(
SELECT
items,
row1,
row_number() over(partition by row1 order by (select 1)) pos
FROM CTE
UNPIVOT
(Items FOR Seq IN ([col1], [col2], [col3])) AS unpvt
)
SELECT
[1] col1, [2] col2, [3] col3
FROM
cte2
PIVOT (max(items) FOR [row1] IN ([1], [2], [3])) AS pvt
结果:
col1 col2 col3
xxxx yyyy NULL
1111 3333 NULL
2222 4444 NULL
你可以试试这个:
DECLARE @DataSource TABLE
(
[Col1] VARCHAR(4)
,[Col2] VARCHAR(4)
,[Col3] VARCHAR(4)
);
INSERT INTO @DataSource ([Col1], [Col2], [Col3])
VALUES ('xxxx', '1111', '2222')
,('yyyy', '3333', '4444');
SELECT [1] AS [col1]
,[2] AS [col2]
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS [RowID]
,[Col1]
,[Col2]
,[Col3]
FROM @DataSource
)DS
UNPIVOT
(
[Value] FOR [Column] IN ([Col1],[Col2], [Col3])
) UNPVT
PIVOT
(
MAX([Value]) FOR [RowID] IN ([1], [2])
) PVT