The PIVOT & UNPIVOT運營商比他們的價值更痛苦。 Unpivoting列是使用交叉應用更容易,速度更快...
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
考慮使用'UNPIVOT'。 –
[Unpivot with column name]可能重複(https://stackoverflow.com/questions/19055902/unpivot-with-column-name) –
@TimBiegeleisen unpivot? –