周期时间内的总和值

Sum value in periodic time

我想要在 table 中节省的机器工作时间总和,但我需要周期性时间总和 例如在 2019.07.10 和 2018.04.05 之间每 7 天求和值。

使用递归 CTE returns 指定日期之间的所有 7 天间隔:

declare @mindate date = '2018-04-05';
declare @maxdate date = '2019-07-10';
with cte as (
  select 
    @mindate startdate, 
    dateadd(day, 6, @mindate) enddate 
  union all 
  select 
    dateadd(day, 1, enddate),  
    case 
      when dateadd(day, 6, enddate) > @maxdate then @maxdate
      else dateadd(day, 6, enddate)
    end  
  from cte 
  where cte.enddate < @maxdate
)
select c.startdate, c.enddate, sum(hours) totalhours 
from cte c left join tablename t
on t.date between c.startdate and c.enddate
group by c.startdate, c.enddate

查看简化版 demo
结果:

> startdate  | enddate    | totalhours
> :----------| :--------- | ---------:
> 05/04/2018 | 11/04/2018 |         14
> ....................................
> 16/08/2018 | 21/08/2018 |         11
> ....................................
> 28/08/2018 | 02/09/2018 |          1
> ....................................

创建过程 spCalculateWorkingHours 声明@DaysGap tinyint 作为 开始 声明@MinWorkingDate 日期 声明@MaxWorkingDate 日期 声明@weekStratDay 日期 声明@WeekEndDay 日期

create table #temp
(WeekStartDay date,
 WeekEndDay date,
 WorkingHours int)

select @minWorkingdate = min(workingdate) from yourtable
select @MaxWorkingDate = Max(workingdate) from yourtable
set @daysGap=7
set @weekStratDay=@MinWorkingDate

while (@weekStratDay<@MaxWorkingDate)
    begin
        set @WeekEndDay dateadd(day,@DaysGap,@weekStratDay)

        insert into #temp
        select @minWorkingdate,@WeekEndDay,sum(hours) from yourtable where workingdate between @minWorkingdate and @WeekEndDay
        group by @minWorkingdate,@WeekEndDay

        set @weekStratDay=dateadd(day,1,@WeekEndDay)
    end

select * from #temp

结束

我会减去较小的值并将差值除以 7。像这样:

select min(datecol), sum(worktime)
from t
group by datediff(day, '2018-04-05', <datecol>) / 7
order by min(datecol);

如果您每天都有数据,这应该正是您所需要的。