透视查询可以使用两个单独的日期对透视结果进行日期过滤?

时间:2012-12-06 20:45:21

标签: sql pivot

以下是我的查询:

select employid,deprtmnt,jobtitle,[H-RT],[H-OT]
from 
(                  
 SELECT employid,deprtmnt,jobtitle,chekdate,UNTSTOPY,Category                  
 FROM 
 (                  
   SELECT employid,deprtmnt,jobtitle,chekdate,UNTSTOPY,payrolcd as     category              
   FROM [upr30300]    
   where DEPRTMNT like '600%'          
 ) t                  
 where chekdate = '2012-03-09' and Category in ('H-RT','H-OT')                  
) d             
PIVOT
(
  SUM(UNTSTOPY) 
  FOR Category IN ([H-RT],[H-OT])
)p

结果显示包括两个旋转的列(H-RT和H-OT)。我可以通过chekdate过滤并获得过滤器的结果,但我想弄清楚如何获得两个EXTRA列显示H-RT,H-OT,它会显示过滤后的chekdate加上14天。

我正在尝试使用dateadd函数,但无法弄清楚如何获得包含...... H-RT(period1),H-OT(period1),H-RT(period2),H的1个结果集-OT(期间2)......任何人都有指导或想法如何完成这项工作?

提前谢谢!

以下是示例数据:

EMPLOYID    DEPRTMNT    JOBTITLE    H-RT    H-OT
ABC123          600-20  CA      77.78000    7.47000
ABC124          600-80  CSA     55.65000    0.58000
ABC125          600-70  RAA     77.68000    0.03000

这是理想的数据:

EMPLOYID    DEPRTMNT    JOBTITLE    H-RT1   H-OT1      H-RT2      H-OT2
ABC123          600-20  CA      77.78000    7.47000    80.00      12.00
ABC124          600-80  CSA     55.65000    0.58000    74.00      16.00
ABC125          600-70  RAA     77.68000    0.03000    48.00       2.00

所需数据列H-RT1,H-OT1是chekdate ='2012-03-09',H-RT2,H-OT2列是chekdate ='2012-03-09'+ 14天。

1 个答案:

答案 0 :(得分:0)

你应该能够使用类似的东西:

select employid,
  deprtmnt,
  jobtitle,
  [H-RT_1],
  [H-OT_1], 
  [H-RT_2],
  [H-OT_2]
from 
(                  
 SELECT employid,
    deprtmnt,
    jobtitle,
    chekdate,
    UNTSTOPY,
    Category,
    case when chekdate = '2012-03-09' then Category+'_1' 
      when chekdate = dateadd(d, 14, '2012-03-09') then Category+'_2' end period
 FROM 
 (                  
   SELECT employid,
     deprtmnt,
     jobtitle,
     chekdate,
     UNTSTOPY,
     payrolcd as category              
   FROM [upr30300]    
   where DEPRTMNT like '600%'
 ) t                  
 where (chekdate = '2012-03-09' or chekdate = dateadd(d, 14, '2012-03-09'))
    and Category in ('H-RT','H-OT')                  
) d             
PIVOT
(
  SUM(UNTSTOPY) 
  FOR Category IN ([H-RT_1],[H-OT_1], [H-RT_2],[H-OT_2])
)p