我的数据如下所示。第一个表有一列日期和两列代表一小时的时间窗口。第二个表具有日期时间和需要聚合和匹配的信息以适合适当的窗口。
declare @timetable table ( dateutc datetime , timestart time , timeend time )
insert into @timetable
select '2013-06-02 00:00:00.000' , '14:00:00.0000000' , '15:00:00.0000000'
union all select '2013-06-02 00:00:00.000' , '13:00:00.0000000' , '14:00:00.0000000'
union all select '2013-06-02 00:00:00.000' , '12:00:00.0000000' , '13:00:00.0000000'
union all select '2013-06-02 00:00:00.000' , '11:00:00.0000000' , '12:00:00.0000000'
declare @actiontable table ( datetimeutc datetime , parentid int , actioncount int )
insert into @actiontable
select '2013-06-02 12:56:01.403' , 3 , 1
union all select '2013-06-02 13:15:00.000' , 3 , 1
union all select '2013-06-02 13:14:01.453' , 3 , 1
union all select '2013-06-02 13:14:01.363' , 4 , 2
union all select '2013-06-02 14:00:07.006' , 4 , 2
union all select '2013-06-02 14:00:07.006' , 4 , 2
union all select '2013-06-02 14:00:07.006' , 5 , 1
union all select '2013-06-02 15:16:01.403' , 5 , 1
union all select '2013-06-02 15:16:01.403' , 5 , 1
union all select '2013-06-02 15:16:01.403' , 5 , 2
我迷失在如何“加入”数据集以使其如下所示。所有想法/帮助表示赞赏。
谢谢!
/*
dateutc , timestart , timeend , actioncount
2013-06-02 00:00:00.000 , 14:00:00.0000000 , 15:00:00.0000000 , 9
2013-06-02 00:00:00.000 , 13:00:00.0000000 , 14:00:00.0000000 , 4
2013-06-02 00:00:00.000 , 12:00:00.0000000 , 13:00:00.0000000 , 1
2013-06-02 00:00:00.000 , 11:00:00.0000000 , 12:00:00.0000000 , 0
*/
答案 0 :(得分:4)
SELECT
t.dateutc, t.timestart, t.timeend, ISNULL(SUM(A.actioncount), 0)
FROM
@timetable T
LEFT JOIN
@actiontable A ON t.dateutc + CAST(t.timestart AS datetime) <= A.datetimeutc AND A.datetimeutc < T.dateutc + CAST(t.timeend AS datetime)
GROUP BY
t.dateutc, t.timestart, t.timeend
ORDER BY
t.dateutc DESC, t.timestart DESC;