SQL Server 将多行合并为多列

ldfqzlk8  于 2022-11-28  发布在  其他
关注(0)|答案(1)|浏览(330)

我正在处理一个项目,在该项目中,我需要合并到一个现有的表,因此我需要将具有相同ID的所有行转换为多个列。
该表如下所示,对于一个产品,可以有多个佣金人员(最多6个),并且佣金ID是唯一的。

ProudctID  |  Name  |   Label  | Commission| CommissionID 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 47        |  John  |   Owner  |   50.0    |   1
 47        |  Steve |   Owner  |   40.0    |   2
 47        |  Giana |   Manager|   10.0    |   3

我需要将此表与产品表合并,以生成一个报告,其中每个产品ID都有多个包含佣金数据的列。

ProudctID  |  Name1  |   Label1  | Commission1 |  Name2  |   Label2  | Commission2 |  Name3  |   Label3  | Commission3 | 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
47         |  John   |   Owner   |    50.0     |  Steve  |   Owner   |   40.0      |  Giana  |   Manager |   10.0      |

我试过像这样的PIVOT,但它不起作用,我也试过改变透视变量,但它没有产生任何结果。只是在新列中为NULL。

Select * from 
    (select PC.CommissionID, 
        PC.ProductID, 
        PC.Commission, 
        PC.Name,
        PC.Label
     from ProductCommission PC
     where PC.ProductID = 47 and PC.Deleted = 0
     ) d
     pivot (max(CommissionID) for Name in ( 
     Name1, CommisionLabel1,  Commission1,
     Name2, CommisionLabel2,  Commission2,
     Name3, CommisionLabel3,  Commission3)) 
     pvt;
brgchamk

brgchamk1#

如果列数已知或达到最大值,则可以使用以下条件聚合
条件聚合提供了比PIVOT更大的灵活性,并且它们可以维护数据类型

Select ProductID  
      ,Name1       = max(case when RN=1 then A.Name end)
      ,Label1      = max(case when RN=1 then A.Label end)
      ,Commission1 = max(case when RN=1 then A.Commission end)
      ,Name2       = max(case when RN=2 then A.Name end)
      ,Label2      = max(case when RN=2 then A.Label end)
      ,Commission2 = max(case when RN=2 then A.Commission end)
      ,Name3       = max(case when RN=3 then A.Name end)
      ,Label3      = max(case when RN=3 then A.Label end)
      ,Commission3 = max(case when RN=3 then A.Commission end)
      ,Name4       = max(case when RN=4 then A.Name end)
      ,Label4      = max(case when RN=4 then A.Label end)
      ,Commission4 = max(case when RN=4 then A.Commission end)
 From  (
        Select *
              ,RN = row_number() over (partition by ProductID order by (select null)) 
         from YourTable
       ) A 
 Group By ProductID

结果

相关问题