Skip to content
Advertisement

SQL Pivot String Data

I have a tables in SQL Server: Product

Product Table:

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

This is the output that I need:

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

An ImageID can have maximum 3 ProductID It is not necessary that all ImageID will have 3 products [eg. 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

Advertisement

Answer

Your were very close, you just needed to incorporate Row_Number()

Example

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
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement