SQL Pivot字符串数据

时间:2018-12-13 14:52:53

标签: sql sql-server tsql pivot

我在SQL Server中有一个表:产品

产品表

ImageID  ProductID  
-------  ---------- 
1           P1
1           P2             
1           P3             
2           S1
2           S2
2           S3
3           M1

这是我需要的输出:

ImageID  Product1ID     Product2ID      Product3ID
----------- ---------- ----------    ----------
1           P1             P2           P3
2           S1             S2           S3
3           M1             null         null

一个ImageID最多可以有3个ProductID 并非所有ImageID都有3种产品[例如, ImageID = 3]

SELECT ImageID, [Product1ID], [Product2ID], [Product3ID]
FROM    
(  
        SELECT ImageID,  ProductID
        FROM ProductTable
) AS P
PIVOT 
(  
    max( ImageID) 
    FOR ProductID IN ([Product1ID], [Product2ID], [Product3ID])
) AS  PVT

2 个答案:

答案 0 :(得分:4)

我只会使用条件聚合:

SELECT ImageID,
       MAX(CASE WHEN seqnum = 1 THEN ProductID END) as Product1ID,
       MAX(CASE WHEN seqnum = 2 THEN ProductID END) as Product2ID,
       MAX(CASE WHEN seqnum = 3 THEN ProductID END) as Product3ID
FROM (SELET pt.*, ROW_NUMBER() OVER (PARTITION BY ImageId ORDER BY ProductID) as seqnum
      FROM ProductTable
     ) P
GROUP BY ImageID;

但是,关键思想是使用ROW_NUMBER()来枚举产品。

答案 1 :(得分:3)

您非常接近,您只需要合并Row_Number()

示例

Select *
 From  (
        Select ImageID
              ,Item = concat('Product',row_number() over (partition by ImageID order by ProductID),'ID') 
              ,ProductID
         From ProductTable
       ) src
Pivot (max(ProductID) for Item in ([Product1ID], [Product2ID], [Product3ID])) pvt