SQL Server使用ID作为列名称的列转置为列



我有一个具有以下字段的大文件:

表1:

+---------+--------+-----------+
| User_Id | Key_Id | Value     | 
+---------+--------+-----------+
| 100     | 74     | 37        |
| 100     | 65     | Male      |
| 100     | 279    | G235467   |
+---------+--------+-----------+

我还有另一个文件,该文件告诉每个" key_id"(它们是列名(,例如

表2:

+--------+------------------+
| Key_Id | Key              |
+--------+------------------+
| 65     | Gender           |
| 66     | Height           |
| 74     | Age              |
| 279    | ReferenceNo      |

我想使用表2的密钥列中的key_id名称创建一个表,将所有值从表1转移到表2中,但还包括从表1中包含user_id,因为这与个人有关。<<<<<<<<<<<<<<<<<</p>

ps。表2具有将近300个键,需要变成单个字段

所以最终我想要一张看起来像这样的桌子:

+---------+---------+--------+-------+--------------+--------+
| User_Id | Gender  | Height | Age   | ReferenceNo  |  etc   |
+---------+---------+--------+-------+--------------+--------+
| 100     | Male    |        | 37    | G235467      |        |

使每个user_id都是一行,所有键都是具有其各自值的列

您可以使用下面的动态SQL查询。

查询

declare @sql as varchar(max);
select @sql = 'select t1.[User_Id], ' + stuff((select +
    ', max(case t2.[Key_Id] when ' + cast([Key_Id] as varchar(100)) + 
    ' then t1.[Value] end) as [' + [Key] + '] '
    from Table2 
    for xml path('')
), 1, 2, '') + 
'from Table1 t1 left join Table2 t2 on t1.[Key_Id] = t2.[Key_Id] group by t1.[User_Id];'
exec(@sql);

在此处找到一个演示

您需要在t-sql中使用的300个关键名称的昏迷列表,如此处所述

https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot

您可以使用以下枢轴:

Select * from (
    Select u.UserId, k.[key], u.[Value] from table1 u
       join table2 k on u.keyid = k.keyid   ) a
pivot ( max([Value]) for [key] in ([Gender], [Height], [Age], [ReferenceNo]) ) p

对于键的动态列表,您可以使用Dynamic SQL如下:

Declare @cols1 varchar(max)
Declare @query nvarchar(max)
Select @cols1 = stuff((select ','+QuoteName([Key]) from table2 group by [Key] for xml path('')),1,1,'')
Set @Query = 'Select * from (
    Select u.UserId, k.[key], u.[Value] from table1 u
       join table2 k on u.keyid = k.keyid   ) a 
pivot ( max([Value]) for [key] in (' + @cols1 + ') ) p '
Select @Query  --Check the generated query and execute by uncommenting below query
--exec sp_executesql @Query 

最新更新