SQL列和值为键和&值

时间:2015-05-20 12:57:13

标签: sql-server

我想从一个看起来像这样的SQL查询中转出记录......

// instead of 
parentCursor.get('mylist').splice(...);
// do:
parentCursor.update('mylist', list => list.splice(...));

到一个看起来像这样的键值对...

FirstName   Amount  PostalCode      LastName    AccountNumber
John        2.4     ZH1E4A          Fork        857685

我想在SQL中完成所有操作。我查看了枢轴示例,但我不确定它是否适用于此。我知道我可以使用临时表,联合但我希望有一个更优雅的解决方案。有人有建议吗?

谢谢你, 保罗

1 个答案:

答案 0 :(得分:1)

试试这个:

DECLARE @t table(FirstName varchar(10),   Amount money,  PostalCode varchar(10),      
                 LastName varchar(10),   AccountNumber int)
INSERT @t values('John', 2.4, 'ZH1E4A', 'Fork', 857685)

;WITH CTE AS
(
  SELECT 
    [FirstName], 
    cast([Amount] as varchar(10)) [Amount], 
    [PostalCode], 
    [LastName], 
    cast([AccountNumber] as varchar(10)) [AccountNumber]
  FROM @t
)
SELECT [Key],Value
FROM CTE  
UNPIVOT      
(Value FOR [Key] IN           
([FirstName], [Amount], [PostalCode], [LastName], [AccountNumber]) ) AS unpvt  

结果:

Key          Value
FirstName    John
Amount       2.40
PostalCode   ZH1E4A
LastName     Fork
AccountNumber 857685