我目前有一段代码可以对动态插入行数据的表进行透视。代码如下所示:
CREATE TABLE Table1
([empname] varchar(6), [empqual] varchar(10), [emprank] int, [empexp] int)
INSERT INTO Table1
([empname], [empqual], [emprank], [empexp])
VALUES
('Joyce', 'UNIVERSITY', 1, 11),
('Angela', 'MASTERS', 2, 10),
('Lily', 'MASTERS', 3, 9),
('Sasha', 'UNIVERSITY', 3, 9),
('Harry', 'UNIVERSITY', 3, 9)
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + 'Column' + CONVERT(VARCHAR,Row_Number() OVER (Order By emprank))
FROM Table1 c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query = '
SELECT *
FROM
(
SELECT ''Column'' + CONVERT(VARCHAR,Row_Number() OVER (Order By emprank)) AS Columns,
CONVERT(VARCHAR,empname) as e
FROM Table1
) p
PIVOT
(
MAX (e)
FOR Columns IN
(
' + @cols + ' )
) as pvt
UNION
SELECT *
FROM
(
SELECT ''Column'' + CONVERT(VARCHAR,Row_Number() OVER (Order By emprank)) AS Columns,
CONVERT(VARCHAR,empqual) as e
FROM Table1
) p
PIVOT
(
MAX (e)
FOR Columns IN
(
' + @cols + ' )
) as pvt
UNION
SELECT *
FROM
(
SELECT ''Column'' + CONVERT(VARCHAR,Row_Number() OVER (Order By emprank)) AS Columns,
CONVERT(VARCHAR,emprank) as e
FROM Table1
) p
PIVOT
(
MAX (e)
FOR Columns IN
(
' + @cols + ' )
) as pvt
UNION
SELECT *
FROM
(
SELECT ''Column'' + CONVERT(VARCHAR,Row_Number() OVER (Order By emprank)) AS Columns,
CONVERT(VARCHAR,empexp) as e,
FROM Table1
) p
PIVOT
(
MAX (e)
FOR Columns IN
(
' + @cols + ' )
) as pvt
'
EXECUTE (@query)
上述代码的结果如下图:
Column1 Column2 Column3 Column4 Column5
1 2 3 3 3
11 10 9 9 9
Joyce Angela Lily Sasha Harry
UNIVERSITY MASTERS MASTERS UNIVERSITY UNIVERSITY
现在,我的应用程序要求我分别显示该表中的每一列,即该表的每一列,而不是行,需要从该表中导出并可能转移到一个临时表中,它可以从中轻松显示。
我很清楚关系数据库的设计方式是将行而不是列视为单个实体。但是,我受到我正在处理的应用程序的限制,该应用程序需要按列提取此表中的数据的代码,以便它们可以单独显示。
我该怎么做呢?