T-SQL按日期和对象计算X期间的总计分组

时间:2015-10-31 18:04:48

标签: sql tsql sql-server-2008-r2 aggregate-functions

我有一个大型数据集,我需要为数据集中的每一天计算每一行的前5天,7天和10天的总活动,而不是仅针对当前日期,这不是一个直接运行的总时间..但在特定时期。

我有为活动构建的每日聚合,但无法聚合日期和对象,然后计算每个行的过去X间隔。

我正在使用MS SQL Server 2008 R2。

例如,使用-1天(昨天), - 2天,-3天

  • 第-1天(前一天/昨天)

    • 对象A 2
    • 对象B 231
    • 对象C 232
  • 第2天

    • 对象A 5
    • 对象B 117
    • 对象C 127
  • 第-3天
    • 对象A 9
    • 对象B 200
    • 对象C 175

我的预期结果将在当天(但不是当前日期)运行

  • 日期,_TID,1D,2D,3D(列)
  • 日期,对象A,2,7,16
  • 日期,对象B,231,579,779
  • 日期,对象C,232,359,534

我查看了How to Query Totals for Last 7 Days和更好的SQL SUM of Last X Records,但这是过去X期间和所有记录中所有活动的总和,并为所有行返回了它,因为我需要查询聚合特定于对象的时间段。

;WITH [stSUM] AS
(
SELECT 
	  TX._TID
	  ,CAST(TX.DT_Req AS DATE) as AgrGrp
      ,TX.DayofYr
	  ,TX.MofY
	  ,TX.DayofM
	  ,TX.DayofW
	  ,TX.TrdPayDay
	  ,TX.Hdy_Govt
	  ,TX.Hdy_Novel
      ,SUM(CASE WHEN TX.TX_BG = 'Evt' THEN 1 ELSE 0 END) as EvtCnt
	  ,SUM(CASE WHEN TX.TX_Yes=1 THEN TX.Rqt_Amt ELSE 0 END) as Amt
FROM CRS1.dbo.JustData
  Group By 
	   CAST(TX.DT_Req AS DATE)
	  ,TX._TID
      ,TX.DayofYr
	  ,TX.MofY
      ,TX.DayofM
	  ,TX.DayofW
	  ,TX.TrdPayDay
	  ,TX.Hdy_Govt
	  ,TX.Hdy_Novel
) 
SELECT  AgrGrp, _TID,
		(select sum(Amt) from (select top 7 * from stSUM bd2 where bd2.AgrGrp <= AgrGrp order by AgrGrp desc) t1 )
        as Measured7,
	     (select sum(Amt) from (select top 5 * from stSUM bd2 where bd2.AgrGrp <= AgrGrp order by AgrGrp desc) t2 )
        as Measured5
FROM [stSUM] 
GROUP BY AgrGrp, _TID
ORDER BY AgrGrp

但它产生的输出不正确,因为每行应该有一个不同的值,仅反映前几天_TID的内容。 这是Measured7回到2014-12-01,Measured5回到2014-12-03。

AgrGrp	    _TID	Measured7	Measured5
2014-12-08	0101 	14400	    8620
2014-12-08	0558 	14400	    8620
2014-12-08	0537 	14400	    8620

1 个答案:

答案 0 :(得分:1)

我的方法是使用BETWEEN日期在子查询中总结我想要的日期范围。

;with DayInfo as
(
select cast(runtime as date) [Date], 
targetType,
round(sum(duration),0) as duration
from Logs
group by cast(runtime as date), 
targetType)


select di.Date,
di.targetType,
di.duration,
d2.d2DurationSum,
d7.d7DurationSum
from DayInfo di
join (select d2.Date,
      d2.targetType,
      sum(dd2.duration) d2DurationSum
      from DayInfo d2
      join DayInfo dd2
      on dd2.Date between dateadd(day, -1, d2.Date) and d2.Date
      and d2.targetType = dd2.targetType
      group by d2.Date,
      d2.targetType) as d2
on di.Date = d2.Date
and di.targetType = d2.targetType
join (select d7.Date,
      d7.targetType,
      sum(dd7.duration) d7DurationSum
      from DayInfo d7
      join DayInfo dd7
      on dd7.Date between dateadd(day, -6, d7.Date) and d7.Date
      and d7.targetType = dd7.targetType
      group by d7.Date,
      d7.targetType) as d7
on di.Date = d7.Date
and di.targetType = d7.targetType
order by 1, 2

这给出了你描述的输出。

enter image description here