我有表tblTask,数据如下。
TID StartTime Uid WId
1 2011-06-06 09:30:00.000 10 1.5
2 2011-06-06 09:40:00.000 10 2.5
3 2011-06-06 09:50:00.000 10 1.8
4 2011-06-06 09:55:00.000 10 2.5
5 2011-06-06 10:30:00.000 10 1.5
6 2011-06-06 11:30:00.000 11 3.0
我需要写入查询以根据每个Starttime的时间差和另一个时间差为1小时或接近1小时的开始时间计算sum(Wid)。
例如取第一个开始时间(2011-06-06 09:30:00.000); < = 1小时的最近开始时间是(2011-06-06 10:30:00.000),SUM(Wid)是1.5 + 2.5 + 1.8 + 2.5 + 1.5 = 9.8。同样,我需要计算所有行。
所需的输出将是:
TID StartTime EndTime TimeDIff(Min) Uid WId
1 2011-06-06 09:30:00.000 2011-06-06 10:30:00.000 60 10 9.8
2 2011-06-06 09:40:00.000 2011-06-06 10:30:00.000 50 10 8.3
答案 0 :(得分:2)
这能满足您的需求吗?
SELECT t1.TID, min(t1.StartTime) AS StartTime, MAX(t2.StartTime) AS EndTime,
MAX(DATEDIFF(MI, t1.StartTime, t2.StartTime)) AS [TimeDiff(Min],
t1.Uid, SUM(t2.WId) AS WId
FROM MyTable t1
JOIN MyTable t2 on datediff(MI, t1.starttime, t2.StartTime) BETWEEN 0 AND 60
GROUP BY t1.TID, t1.Uid
ORDER BY t1.TID
答案 1 :(得分:0)
此代码块会为您提供StartTime
和EndTime
DECLARE @STARTDATE DATETIME = '10:15:45'
DECLARE @ENDDATE DATETIME = '14:00:15'
DECLARE @24DATE DATETIME
SET @24DATE = '23:59:59.000'
IF (@STARTDATE > @ENDDATE)
SELECT DATEADD(SECOND, 1, CONVERT(TIME(0), (@24DATE -(@ENDDATE - @STARTDATE))))
ELSE
SELECT CONVERT(TIME(0), ((@ENDDATE - @STARTDATE)))