【问题标题】:SQL Pivot String DataSQL 透视字符串数据
【发布时间】:2019-05-14 19:50:24
【问题描述】:

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

【问题讨论】:

    标签: sql sql-server tsql pivot


    【解决方案1】:

    我只会使用条件聚合:

    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() 枚举产品。

    【讨论】:

      【解决方案2】:

      你们已经很亲近了,你只需要加入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
      

      【讨论】:

        猜你喜欢
        • 2010-09-06
        • 1970-01-01
        • 2018-10-05
        • 1970-01-01
        • 1970-01-01
        • 2014-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多