简体   繁体   English

如何使用 SQL 将列/行对转换为键/值?

[英]How to convert column/row pair to key/value by using SQL?

[PlayerCode] | [Name]   | [Age] | [Club]
142          | Messi    | 34    | PSG
333          | Ronaldo  | 36    | Manchester United
532          | Pique    | 34    | FC Barcelona

[PlayerCode] | [Key]    | [Value]
142          | Name     | Messi
142          | Age      | 34 
142          | Club     | PSG
333          | Name     | Ronaldo
333          | Age      | 36
333          | Club     | Manchester United
532          | Name     | Pique
532          | Age      | 34
532          | Club     | FC Barcelona

I want to convert the first table to the second key/value table by using SQL Server.我想使用 SQL Server 将第一个表转换为第二个键/值表。 I assume that the 'unpivot' function will be used to do the conversion, but I don't know how..我假设 'unpivot' 函数将用于进行转换,但我不知道如何..

Does anyone know how to do this?有谁知道如何做到这一点?

Two quick options.两个快速选项。

More Performant (and offers a bit more flexibility)更高性能(并提供更多灵活性)

 Select A.[PlayerCode]
       ,B.*
  From  YourTable A
  Cross Apply ( values ('Name',[Name])
                      ,('Age' ,concat('',[Age]))
                      ,('Club',[Club])
              ) B([Key],[Value])    

More Dynamic (any number of columns)更动态(任意数量的列)

 Select A.[PlayerCode]
       ,B.[Key]
       ,B.[Value]
  From  YourTable A
  Cross Apply OpenJSON( (Select A.* For JSON Path,Without_Array_Wrapper ) ) B
  Where [key] not in ('PlayerCode')

Note that we just need to exclude [PlayerCode] and there is no need for conversion of datatypes.请注意,我们只需要排除[PlayerCode]并且不需要转换数据类型。 Also NULL values will be excluded. NULL 值也将被排除在外。

I see there are more answers, but I left my answer here because it is the only one that uses UNPIVOT.我看到有更多答案,但我将答案留在这里,因为它是唯一使用 UNPIVOT 的答案。 Maybe it is useful for you or for any other one:也许它对您或任何其他人有用:

create table players (
  [PlayerCode] int,
  [Name]   varchar(50),
  [Age] int,
  [Club] varchar(50)
)

insert into players values 
(142, 'Messi', 34, 'PSG'),
(333, 'Ronaldo', 36, 'Manchester United'),
(532, 'Pique', 34, 'FC Barcelona')

SELECT PlayerCode, [Key], Value  
FROM   
   (SELECT PlayerCode, Name, cast(Age as varchar(50)) Age, Club
   FROM players) p  
UNPIVOT  
   (Value FOR [Key] IN   
      (Name, Age, Club)  
)AS unpvt; 

You could use a union:您可以使用联合:

SELECT PlayerCode, [Key], [Value]
FROM
(
    SELECT PlayerCode, 'Name' AS [Key], Name AS [Value], 1 AS pos FROM yourTable
    UNION ALL
    SELECT PlayerCode, 'Age', CAST(Age AS varchar(3)), 2 FROM yourTable
    UNION ALL
    SELECT PlayerCode, 'Club', Club, 3 FROM yourTable
) t
ORDER BY PlayerCode, pos;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM