簡體   English   中英

將多行組合成多列

[英]Combine multiple rows into multiple columns

我正在處理一個項目,我需要在其中合並到現有表,因此我需要將具有相同 ID 的所有行轉換為多列。

表格如下所示,對於 1 個產品,可能有多個佣金人(最多 6 個),並且 CommissionID 是唯一的。

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 但它不起作用,我也嘗試更改 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;

如果您有已知列數或最大列數,這里是一個條件聚合

條件聚合比 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

結果

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM