Return 单条记录的列作为行

Return Columns as Rows for Single Record

我已经在本网站以及其他网站上阅读了很多关于使用 PIVOT、UNPIVOT、UNION 和 CROSS JOIN 的帖子,但我似乎无法完全获得我正在寻找的结果。

我的 table 如下所示:

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 中,并请求以这种方式显示员工记录。

你快到了:

您的密码是:

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

结果: