获得4小时内的记录数量?

时间:2017-07-26 13:13:17

标签: sql-server

我目前正在尝试从4小时的重复时间段模式中获取记录数。以下是我现在拥有的数据示例。

DT	                 LD_VSL_M	LD_VOY_N
1/5/2017 10:14:00 AM	rmhp epjui	0023S
1/5/2017 10:16:00 AM	rmhp epjui	0023S
1/5/2017 10:18:00 AM	rmhp epjui	0023S
1/5/2017 10:32:00 AM	rmhp epjui	0023S
1/5/2017 11:18:00 AM	rmhp epjui	0023S
1/5/2017 11:25:00 AM	rmhp epjui	0023S
1/5/2017 11:31:00 AM	rmhp epjui	0023S
1/5/2017 12:18:00 PM	rmhp epjui	0023S
1/5/2017 10:14:00 AM	rfff rfff	0023N
1/5/2017 10:16:00 AM	rfff rfff	0023N
1/5/2017 10:18:00 AM	rfff rfff	0023N
1/5/2017 10:32:00 AM	rfff rfff	0023N
1/5/2017 11:18:00 AM	rfff rfff	0023N
1/5/2017 11:25:00 AM	rfff rfff	0023N
1/5/2017 11:31:00 AM	rfff rfff	0023N
1/5/2017 12:18:00 PM	rfff rfff	0023N

ST_C	    CT
F	    P
F	    P
F	    P
F           P
F	    P
F	    P
F	    P
F	    P
F	    P
F	    P
F	    P
F           P
F	    P
F	    P
F	    P
F	    P

例如,如果我想在4小时的基础上获取记录数,例如1/5/2017 0:00:00到1/5/2017 4:00:00,基于记录的数量在上面的例子中应该是0.这对于1/5/2017 4:00:00到1/5/2017 8:00:00也是如此。但是,从1/5/2017 8:00:00到1/5/2017 12:00:00,应该有7条记录。以下是我想要的输出。当LD_VSL_N,LD_VOY_N时。 ST_C和CT改变,它将从1/5/2017 0:00:00开始计数。

   DT             no_of_records 
1/5/2017 0:00         0
1/5/2017 4:00         0
1/5/2017 8:00         0
1/5/2017 12:00        7
1/5/2017 16:00        1
1/5/2017 20:00        0
1/5/2017 0:00         0
1/5/2017 4:00         0
1/5/2017 8:00         0
1/5/2017 12:00        7
1/5/2017 16:00        1
1/5/2017 20:00        0
LD_VSL_M	LD_VOY_N
rmhp epjui	0023S
rmhp epjui	0023S
rmhp epjui	0023S
rmhp epjui	0023S
rmhp epjui	0023S
rmhp epjui	0023S
rmhp epjui	0023S
rmhp epjui	0023S
rfff rfff	0023N
rfff rfff	0023N
rfff rfff	0023N
rfff rfff	0023N
rfff rfff	0023N
rfff rfff	0023N
rfff rfff	0023N
rfff rfff	0023N
现在,我正在尝试获取no_of_records列。请帮助我,因为我已经被困在这里很长一段时间了。

1 个答案:

答案 0 :(得分:0)

您可以查询如下:

;With Cte_hours as ( --hours generation
    Select top(6) hr = (Row_number() over (order by (Select NULL))-1)*4 from master..spt_values 
), cte2 as ( --getting range
    Select DateAdd(HH, c.hr, Convert(datetime,d.dts) ) as Dts_Start, DateAdd(MS, -2, DateAdd(HH, c.hr+ 4, Convert(datetime,d.dts) ) ) Dts_end
    from (select distinct convert(date, dt) as dts from #testData ) d
    cross apply Cte_hours c
) --actual query
Select c2.Dts_Start, Sum(case when t.Dt is not null then 1 else 0 end) 
from cte2 c2
Left Join #testData t
on t.Dt between c2.Dts_Start and c2.Dts_end
group by c2.Dts_Start

输出如下:

+-------------------------+---------------+
|           DT            | No_of_records |
+-------------------------+---------------+
| 2017-01-05 00:00:00.000 |             0 |
| 2017-01-05 04:00:00.000 |             0 |
| 2017-01-05 08:00:00.000 |             7 |
| 2017-01-05 12:00:00.000 |             1 |
| 2017-01-05 16:00:00.000 |             0 |
| 2017-01-05 20:00:00.000 |             0 |
+-------------------------+---------------+