sql 服务器中的数据透视表

pivot tables in sql server

有一个 table 数据为:

 d1  d2  MON REPORT_DATE   

 67 46  Dec 2014-12-19 06:19:05.337

 69 46  Dec 2014-12-22 06:21:47.430

 67 85  Jan 2015-01-23 06:08:09.030

我需要一个结果集

      DEC  JAN
D1    69    67

D2    46    85

到目前为止

SELECT *
FROM  (SELECT PerValueStreamOnAutoDiags,
              PerProdSupportOnAutoDiags,
              LEFT(Datename(Month, ReportDate), 3)[Month],
              ReportDate
       FROM   Temp_AutoApprovalMembercnt)AS s
      PIVOT ( Max(ReportDate)
            FOR [month] IN (dec,
                            jan) )AS p 

您需要旋转数据 重新聚合它,因为您正在交换行和列。这是一种使用聚合和 union all:

的方法
select 'd1' as col, max(case when mon = 'Dec' then d1 end) as dec,
       max(case when mon = 'Jan' then d1 end) as Jan
from Temp_AutoApprovalMembercnt
union all 
select 'd2' as col, max(case when mon = 'Dec' then d2 end) as dec,
       max(case when mon = 'Jan' then d2 end) as Jan
from Temp_AutoApprovalMembercnt;

这应该有效:

;with cte as
(select * from 
 (select PerValueStreamOnAutoDiags,
          PerProdSupportOnAutoDiags,
          LEFT(Datename(Month, ReportDate), 3)[Month] 
  from Temp_AutoApprovalMembercnt) as s
 unpivot
 (val
  for cols in (PerValueStreamOnAutoDiags,PerValueStreamOnAutoDiags)) as u)

select * from
(select * from cte) as s
pivot
(max(val)
 for [Month] in (DEC,JAN)) as p

Demo

首先 unpivot 数据以将 PerValueStreamOnAutoDiagsPerProdSupportOnAutoDiags 从列中带入行,然后旋转以获得按月汇总的数据。