SQL PIVOT a table 基于具有 ID 的列

SQL PIVOT a table based on a column with ID's

我有 Table

喜欢

 ID, ID_CLIENT, ID_TYPE, PRICE

如何创建一个新的 "CTE"table,其中每个 ID_Client 都有 1 条记录。 对于一些 (5) ID_TYPE priceType 列。

喜欢

ID_CLIENT, PRICEFORID_TYPE1, PRICEFORIDTYPE_2,.......
1              10                15               
2              20                30

我的第一个想法是使用 PIVOT table 但后来发布了 1 我无法过滤 ID_TYPE。

假设您需要 DYNAMIC

例子

Declare @SQL varchar(max) = '
Select *
 From (
        Select [ID_CLIENT]
              ,[Item] = concat(''PRICEFORID_TYPE'',[ID_TYPE])
              ,[Price]
         From YourTable
      ) A
 Pivot (max([Price]) For [Item] in (' + Stuff((Select Distinct ','+QuoteName(concat('PRICEFORID_TYPE',[ID_TYPE])) 
                                               From YourTable  
                                               Order By 1 
                                               For XML Path('')),1,1,'')  + ') ) p'
Exec(@SQL);
--Print @SQL

Returns

生成的 SQL 看起来像这样

Select *
 From (
        Select [ID_CLIENT]
              ,[Item] = concat('PRICEFORID_TYPE',[ID_TYPE])
              ,[Price]
         From YourTable
      ) A
 Pivot (max([Price]) For [Item] in ([PRICEFORID_TYPE1],[PRICEFORID_TYPE2]) ) p