2013-06-03 42 views
0

我有如下所示的数据。第一个表格有一个日期列和两个列表示一个小时的时间窗口。第二个表格包含日期时间和信息,这些信息需要进行汇总和匹配才能适应相应的窗口。SQL Server 2012聚合分割日期时间?

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
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; 
+0

你是正确的,需要演员。我已经测试过它......但在sqlfiddle中没有更改到sqlserver2012! – danihp

+0

+1我还没有意识到SQLS2012的变化 – bummi

+0

这个答案是纯粹的热度。谢谢! – Snowy