将SQL列转换为行

4

我有下面的表格,并希望在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

以下是目前的内容,但我希望从这里开始进行改进。
注:此处为html标签,请勿翻译。
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
为什么不把你的 PIVOT 尝试也展示给我们看呢? - jarlh
如果我可以问,你为什么要做那样的事情呢? - Davide Vitali
如果你不展示给我们你的SQL代码,我们怎么能帮你修复它呢? - Thom A
1
我认为PIVOT的语法非常晦涩难懂。我更喜欢使用交叉表,也称条件聚合。这里有一篇关于这个主题的好文章。http://www.sqlservercentral.com/articles/T-SQL/63681/ 如果你需要一个动态版本,可以看看这篇文章:http://www.sqlservercentral.com/articles/Crosstab/65048/ - Sean Lange
1个回答

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

返回值

输入图片描述


John,感谢您的付出,这非常出色,正是我想要的。非常感谢。 - jk1844
@jk1844 很高兴能够帮助。 - John Cappelletti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接