我尝试了以下查询:
SELECT Name,startdate,address from employee
我得到的数据是这样的:
Name StartDate Address
John 01/01/2017 na
虽然我想要这样的数据:
Name | John
------------------------
StartDate | 01/01/2017
Address | NA
如何编写正确的查询以获得预期的结果?
答案 0 :(得分:3)
PIVOT& UNPIVOT操作员比他们的价值更痛苦。使用交叉应用...
可以更容易(更快)地旋转列IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL
DROP TABLE #TestData;
CREATE TABLE #TestData (
f_Name VARCHAR(10),
StartDate DATE,
Address VARCHAR(30)
);
INSERT #TestData(f_Name, StartDate, Address)
VALUES ('Johm', '2017-01-01', 'n/a');
--=================================================
SELECT
cav.ColLabel,
cav.ColValue
FROM
#TestData td
CROSS APPLY ( VALUES
(1, 'Name', td.f_Name),
(2, 'StartDate', CAST(td.StartDate AS VARCHAR(10))),
(3, 'Address', td.Address)
) cav (SortVal, ColLabel, ColValue)
ORDER BY
cav.SortVal;
结果...
ColLabel ColValue
--------- ------------------------------
Name Johm
StartDate 2017-01-01
Address n/a