我已经阅读了本网站以及其他有关使用PIVOT,UNPIVOT,UNION和CROSS JOIN的帖子,但我似乎无法得到我想要的结果。
我的表格如下:
EmployeeName Salary Address City State Zip AdditionalDetails
=========================================================================================
Doe, John 400000 111 Jackson Ave Nowhere CA 99999 Reliable
Blow, Joe 300000 222 Johnson St Somewhere ME 00000 Always late
我试图展示的内容如下:
EmployeeName Doe, John
Salary 400000
Address 111 Jackson Ave
City Nowhere
State CA
Zip 99999
AdditionalDetails Reliable
我最接近的是如下使用UNPIVOT,但问题是两列是换位的,我需要交换它们,虽然我不知道该怎么做。
SELECT *
FROM
(
SELECT EmployeeName, Salary, Address, City, State, Zip, AdditionalDetails
FROM EmployeeDetails
WHERE EmployeeDetails.EmployeeID=@EmployeeID
) AS SourceTable
UNPIVOT
(
Value FOR Header IN
(EmployeeName, Salary, Address, City, State, Zip, AdditionalDetails)
) AS UnpivotTable
所以我得到的是:
Value Header
Doe, John EmployeeName
400000 Salary
111 Jackson Ave Address
Nowhere City
CA State
99999 Zip
Reliable AdditionalDetails
如何在需要时显示数据?我首先要说的是,每次使用此查询只返回一条员工记录。我将此数据附加到CSV中,并且请求以这种方式显示员工记录。
答案 0 :(得分:3)
你快到了:
您拥有的代码是:
SELECT *
FROM
(
SELECT EmployeeName, Salary, Address, City, State, Zip, AdditionalDetails
FROM EmployeeDetails
WHERE EmployeeDetails.EmployeeID=@EmployeeID
) AS SourceTable
UNPIVOT
(
Value FOR Header IN
(EmployeeName, Salary, Address, City, State, Zip, AdditionalDetails)
) AS UnpivotTable
你应该:
SELECT Header, Value
FROM
(
SELECT EmployeeName, Salary, Address, City, State, Zip, AdditionalDetails
FROM EmployeeDetails
WHERE EmployeeDetails.EmployeeID=@EmployeeID
) AS SourceTable
UNPIVOT
(
Value FOR Header IN
(EmployeeName, Salary, Address, City, State, Zip, AdditionalDetails)
) AS UnpivotTable
结果: