Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL数据透视字符串数据_Sql_Sql Server_Tsql_Pivot - Fatal编程技术网

SQL数据透视字符串数据

SQL数据透视字符串数据,sql,sql-server,tsql,pivot,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

我在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

您的关系非常密切,只需合并
行号()

示例

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

我只想使用条件聚合:

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;
不过,关键的想法是使用
行数()
枚举产品