将SQL列转置为行

时间:2019-03-13 15:27:04

标签: sql sql-server tsql

我有下表,想在SQL中进行转置,我曾尝试使用sql PIVOT,但是却无济于事。非常感谢您的帮助。

CID ActID   ActType         ActDate
1   10      Assessment      2017-08-09
1   11      StartOfPOC      2017-11-01
1   22      POC1            2017-11-03
1   22      POC2            2017-11-03
2   44      Report          2017-11-03
2   44      Planning        2017-11-03
3   66      Assessment      2017-11-06
3   66      POC1            2017-11-06
3   77      EndOfPOC        2017-11-06

我想将此表转置到下面

CID     ActType1    ActDate1    ActType2    ActDate2    ActType3    ActDate3    ActType4    ActDate4    ActType4    ActDate4        
1       Assessment  2017-08-09  StartOfPOC  2017-11-01  POC1        2017-11-03  POC2        2017-11-03
2       POC1        2017-11-03  Planning    2017-11-03
3       Assessment  2017-11-06  POC1        2017-11-06  EndOfPOC    2017-11-06

下面是我想要的,但是想从这里得到改善。

SELECT * FROM (
  Select
     CID
    ,ActID   
    ,ActType         
    ,ActDate
  from #tbl r
  where r.ActType in ('Assessment','Start of POC','POC1','POC2','Report','Planning','EndOfPOC')  
) x
PIVOT( MAX(ActDate)
FOR ActType IN (
     [Assessment]
    ,[Start of POC]
    ,[POC1]
    ,[POC2]
    ,[Reporting]
    ,[Planning]
    ,[End of POC]
    )
) p

谢谢

1 个答案:

答案 0 :(得分:7)

而不是PIVOT,我将与Row_Number()配合使用条件聚合

示例

Select CID
      ,AcctType1 = max(case when RN = 1 then ActType end)
      ,AcctDate1 = max(case when RN = 1 then ActDate end)
      ,AcctType2 = max(case when RN = 2 then ActType end)
      ,AcctDate2 = max(case when RN = 2 then ActDate end)
      ,AcctType3 = max(case when RN = 3 then ActType end)
      ,AcctDate3 = max(case when RN = 3 then ActDate end)
      ,AcctType4 = max(case when RN = 4 then ActType end)
      ,AcctDate4 = max(case when RN = 4 then ActDate end)
From (
        Select * 
              ,RN= Row_Number() over (Partition By CID Order by ActDate)
         From YourTable
     ) A
 Group By CID

返回

enter image description here