我的表看起来像这样
Col1 col2 col3 col4 col5 --------------------------------------------- data1 data2 data3 data4 data5
我想将该记录显示为
heading1 heading2 ---------------------- Col1 data1 Col2 data2 col3 data3 col4 data4 col5 data5
答案 0 :(得分:1)
您可以使用UNPIVOT
来实现此目的:
select P.Heading1, P.Heading2
from Temp T
unpivot
(
Heading2
for Heading1 in (Col1,col2,col3,col4, col5)
) P;
可以找到更多信息here。
答案 1 :(得分:0)
见这个小例子:
SELECT * INTO T FROM
(VALUES
(1,2,3)
) T(A,B,C)
SELECT * FROM T
基准表:
A B C
- - -
1 2 3
逆透视:
SELECT * FROM T
UNPIVOT (X FOR Y IN (A,B,C)) U
结果
X Y
- -
1 A
2 B
3 C
答案 2 :(得分:0)
样本数据
IF OBJECT_ID('dbo.TempData') IS NOT NULL
DROP TABLE TempData
;With cte(Col1,Col2,Col3,Col4,Col5)
AS
(
SELECT 'data1','data2','data3','data4','data5'
)
SELECT * INTO TempData FROM cte
SELECT * FROM TempData
使用交叉应用动态Sql
DECLARE @Sql NVARCHAR(MAX) , @dynCoulmn NVARCHAR(MAX)
SELECT @dynCoulmn=STUFF((SELECT distinct ', '+TempCol FROM
(
SELECT '('+COLUMN_NAME+','+''''+COLUMN_NAME+''''+')' AS TempCol
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='TempData'
)dt2
FOR XML PATH ('')),1,1,'')
SET @Sql='
SELECT heading1,heading2 FROM TempData
CROSS APPLY ( Values '+@dynCoulmn+'
) A (heading2,heading1)
'
PRINT @Sql
EXEC (@Sql)
交叉申请前的结果
Col1 Col2 Col3 Col4 Col5
-------------------------------------
data1 data2 data3 data4 data5
结果后交叉
heading1 heading2
---------------------
Col1 data1
Col2 data2
Col3 data3
Col4 data4
Col5 data5