Sql 周期时间和值

Sql 周期时间和值,sql,sql-server,sql-server-2017,Sql,Sql Server,Sql Server 2017,我想要表中保存的机器的总工作时间,但我需要周期时间的总和 例如,在2019.07.10和2018.04.05之间,每7天求和一次值。使用递归CTE返回指定日期之间的所有7天间隔: declare @mindate date = '2018-04-05'; declare @maxdate date = '2019-07-10'; with cte as ( select @mindate startdate, dateadd(day, 6, @mindate) endda

我想要表中保存的机器的总工作时间,但我需要周期时间的总和
例如,在2019.07.10和2018.04.05之间,每7天求和一次值。

使用递归CTE返回指定日期之间的所有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

创建过程spCalculateWorkingHours 声明@DaysGap tinyint 像 开始 声明@MinWorkingDate日期 声明@MaxWorkingDate日期 声明@weekStratDay日期 在周末日期声明

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);

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

您应该提供示例数据和所需结果。
select min(datecol), sum(worktime)
from t
group by datediff(day, '2018-04-05', <datecol>) / 7
order by min(datecol);