0

我有如下所示的数据。第一个表有一列表示日期,两列表示一小时的时间窗口。第二个表包含日期时间和需要聚合和匹配以适应适当窗口的信息。

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
*/
4

1 回答 1

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;
于 2013-06-03T14:50:09.387 回答