SQL计算总时间,但如果差距很大,则重置总计

时间:2011-09-28 17:23:09

标签: sql sql-server tsql sql-server-2008

我有一个包含设备移动的表格。

MoveID DeviceID Start End

我想知道是否有办法总结每台设备到现在的总运动天数。但是,如果在结束日期和下一个开始日期之间存在6周的间隔,则重置时间计数。

MoveID    DeviceID    Start     End
1           1         2011-1-1  2011-2-1
2           1         2011-9-1  2011-9-20
3           1         2011-9-25 2011-9-28

设备总数应为24天,因为差距超过6周。此外,我想知道自2011-11-1最新统计小组开始以来,该小组第一次移动的天数为28天

我以为我可以使用存储过程和光标等(这不好)只是想知道是否有更好的东西?

由于

格雷姆

2 个答案:

答案 0 :(得分:2)

create table #test
(
MoveID int,
DeviceID int,
Start date,
End_time date
)
--drop table #test
insert into #test values
(1,1,'2011-1-1','2011-2-1'),
(2,1,'2011-9-1','2011-9-20'),
(3,1,'2011-9-25','2011-9-28')

select 
   a.DeviceID, 
   sum(case when datediff(dd, a.End_time, isnull(b.Start, a.end_time)) > 42 /*6 weeks = 42 days*/ then 0 else datediff(dd,a.Start, a.End_time)+1 /*we will count also the last day*/ end) as movement_days,

总和(dateiff(dd,a.End_time,isnull(b.Start,a.end_time))> 42 / 6周= 42天 /然后0其他dateiff(dd, a.Start,a.End_time)+1 / 当b.MoveID为null然后是datediff(dd,a.Start,a.End_time)+ 1时,我们也将计算最后一天 / end + case其他0结束)作为total_days
    从        #test a        左连接#test b           在a.DeviceID = b.DeviceID上              和a.MoveID + 1 = b.MoveID     通过...分组        a.DeviceID

如果您需要一些解释,请告诉我 - 有更多方法可以做到这一点......

答案 1 :(得分:1)

DECLARE @Times TABLE
(
    MoveID INT,
    DeviceID INT,
    Start DATETIME,
    [End] DATETIME
)

INSERT INTO @Times VALUES (1, 1, '1/1/2011', '2/1/2011')
INSERT INTO @Times VALUES (2, 1, '9/1/2011', '9/20/2011')
INSERT INTO @Times VALUES (3, 1, '9/25/2011', '9/28/2011')

INSERT INTO @Times VALUES (4, 2, '1/1/2011', '2/1/2011')
INSERT INTO @Times VALUES (5, 2, '3/1/2011', '4/20/2011')
INSERT INTO @Times VALUES (6, 2, '5/1/2011', '6/20/2011')

DECLARE @MaxGapInWeeks INT
SET @MaxGapInWeeks = 6

SELECT
    validTimes.DeviceID,
    SUM(DATEDIFF(DAY, validTimes.Start, validTimes.[End]) + 1) AS TotalDays,
    DATEDIFF(DAY, MIN(validTimes.Start), MAX(validTimes.[End])) + 1 AS TotalDaysInGroup
FROM 
    @Times validTimes LEFT JOIN
    @Times timeGap 
        ON timeGap.DeviceID = validTimes.DeviceID
        AND timeGap.MoveID <> validTimes.MoveID
        AND DATEDIFF(WEEK, validTimes.[End], timeGap.Start) > @MaxGapInWeeks
WHERE timeGap.MoveID IS NULL
GROUP BY validTimes.DeviceID