将类别转换为SQL Server中的列

时间:2015-07-01 02:44:45

标签: sql sql-server

我有一个查询,结果给出了一些属性,但我需要将每个类别转换为一列

这是我的疑问:

SELECT hist_statusevents.eqmt,
       hist_exproot.shiftdate,
       hist_statusevents.category, 
       Sum(hist_statusevents.duration/3600) as Value
FROM Powerview.dbo.hist_eqmtlist hist_eqmtlist, 
     Powerview.dbo.hist_exproot hist_exproot,   
      Powerview.dbo.hist_statusevents hist_statusevents
WHERE hist_exproot.shiftindex = hist_statusevents.shiftindex And 
      hist_statusevents.shiftindex = hist_eqmtlist.shiftindex And 
      hist_statusevents.eqmt = hist_eqmtlist.eqmtid And 
      hist_statusevents.eqmt like 'MOTO%'
GROUP BY hist_statusevents.eqmt, 
         hist_exproot.shiftdate,
         hist_statusevents.category

这是查询的输出:

eqmt            shiftdate         category   Value
MOTO705         2011-01-22 00:00:00  5      13,9597222805023
MOTO706         2011-01-28 00:00:00  3      0,280277773737907
MOTO704         2011-02-17 00:00:00  6      8,92749977111816
MOTO705         2011-02-09 00:00:00  6      10,07972240448
MOTO703         2011-03-15 00:00:00  1      22,6561107933521
MOTO704         2011-03-11 00:00:00  5      24
MOTO706         2011-01-27 00:00:00  1      9,95361125469208
MOTO703         2011-03-16 00:00:00  6      3,79916667938232
MOTO704         2011-01-08 00:00:00  6      24

但我需要得到结果:

eqmt            shiftdate            1  2  3  4  5  6  7
MOTO706         2011-01-28 00:00:00  values for each category
MOTO704         2011-02-17 00:00:00  
MOTO705         2011-02-09 00:00:00  
MOTO703         2011-03-15 00:00:00  

我一直在尝试选择案例,但我不能让结构工作

1 个答案:

答案 0 :(得分:1)

如果类别值是固定的并且在范围(1,7)内,那么您可以使用如下所示的基于案例的聚合 如果类别值是动态的,则需要使用动态sql来执行pivot

SELECT hist_statusevents.eqmt, 
       hist_exproot.shiftdate, 
       sum(case when hist_statusevents.category =1 then (hist_statusevents.duration/3600) else 0 end) as '1',
       sum(case when hist_statusevents.category =2 then (hist_statusevents.duration/3600) else 0 end) as '2',
       sum(case when hist_statusevents.category =3 then (hist_statusevents.duration/3600) else 0 end) as '3',
       sum(case when hist_statusevents.category =4 then (hist_statusevents.duration/3600) else 0 end) as '4',
       sum(case when hist_statusevents.category =5 then (hist_statusevents.duration/3600) else 0 end) as '5',
       sum(case when hist_statusevents.category =6 then (hist_statusevents.duration/3600) else 0 end) as '6',
       sum(case when hist_statusevents.category =7 then (hist_statusevents.duration/3600) else 0 end) as '7'

FROM Powerview.dbo.hist_eqmtlist hist_eqmtlist, Powerview.dbo.hist_exproot hist_exproot, Powerview.dbo.hist_statusevents hist_statusevents
WHERE hist_exproot.shiftindex = hist_statusevents.shiftindex And hist_statusevents.shiftindex = hist_eqmtlist.shiftindex And hist_statusevents.eqmt = hist_eqmtlist.eqmtid And hist_statusevents.eqmt like 'MOTO%'
GROUP BY hist_statusevents.eqmt, hist_exproot.shiftdate