我有一个返回此结果的简单查询
TransactionIdentifier TransactionType DateTimeStamp 1 Destruction Dec 23 2015 7:43AM 2 Management May 21 2013 2:01AM
我想将其转换为以下格式
TransactionIdentifier ColumnName Value 1 TransactionIdentifier 1 1 TransactionType Destruction 1 DateTimeStamp Dec 23 2015 7:43AM 2 TransactionIdentifier 2 2 TransactionType Management 2 DateTimeStamp May 21 2013 2:01AM
这是我目前的查询
SELECT V.ColumnName, V.Value FROM (SELECT CONVERT( VARCHAR(4000), TransactionIdentifier) AS TransactionIdentifier, CONVERT( VARCHAR(4000), TransactionType) AS TransactionType, CONVERT( VARCHAR(4000), DateTimeStamp) AS DateTimeStamp FROM Transactions WHERE TransactionIdentifier IN(1, 2)) AS A1 UNPIVOT(Value FOR ColumnName IN(TransactionIdentifier,TransactionType,DateTimeStamp)) AS V
它返回此
ColumnName Value TransactionIdentifier 1 TransactionType Destruction DateTimeStamp Dec 23 2015 7:43AM TransactionIdentifier 2 TransactionType Management DateTimeStamp May 21 2013 2:01AM
如何将TransactionIdentifier字段添加到结果中?
答案 0 :(得分:1)
只需从unpivot
移除 TransactionIdentifier ,然后将其添加到Select
语句
SELECT TransactionIdentifier ,V.ColumnName, V.Value
FROM (SELECT CONVERT( VARCHAR(4000), TransactionIdentifier) AS TransactionIdentifier,
CONVERT( VARCHAR(4000), TransactionType) AS TransactionType,
CONVERT( VARCHAR(4000), DateTimeStamp) AS DateTimeStamp
FROM Transactions
WHERE TransactionIdentifier IN(1, 2)) AS A1
UNPIVOT(Value FOR ColumnName IN(TransactionType,DateTimeStamp)) AS V
输出:
TransactionIdentifier ColumnName Value
1 TransactionType Destruction
1 DateTimeStamp Dec 23 2015 7:43AM
2 TransactionType Management
2 DateTimeStamp May 21 2013 2:01AM
希望有所帮助。