以下场景的T查询将如何处理:
Select * from Table1
col1|col2|col3
--------------
xxxx|1111|2222
yyyy|3333|4444至
col1|col2
---------
xxxx|yyyy
1111|3333
2222|4444发布于 2015-07-31 10:00:52
你可以试试这个:
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

发布于 2015-07-31 09:59:10
也许是这样的。为演示目的添加了另一列,请注意,只有在数据类型相同的情况下,它才能工作:
;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 NULLhttps://stackoverflow.com/questions/31742511
复制相似问题