如何在以30秒为间隔的时间戳之间选择数据

时间:2018-10-11 16:34:59

标签: sql sql-server

美好的一天。我有两个表,TableATableBTableA有开始和结束时间。 TableB的数据带有时间戳。我正在尝试将TableA分离到一个较大的表中,该表以30秒的间隔分隔开,并使TableBs数据连接到开始时间和停止时间之间最近的30秒时间戳记。

如何有效地创建一个以30秒为间隔的表,并根据最近的时间戳联接另一个表数据?任何帮助深表感谢。

TableA

pkid     dateEntered
    1       2018-10-09 14:18:34.823
    2       2018-10-09 14:28:30.963

TableB

processVal  dateEntered
55.2431   2018-10-09 14:18:34.953
55.2158   2018-10-09 14:19:04.960
54.7972   2018-10-09 14:19:34.963
54.7933   2018-10-09 14:20:04.963
54.7661   2018-10-09 14:20:34.967
54.7427   2018-10-09 14:21:04.967
54.7193   2018-10-09 14:21:34.970
54.6921   2018-10-09 14:22:04.970
54.6668   2018-10-09 14:22:34.973
54.6375   2018-10-09 14:23:04.973
54.6142   2018-10-09 14:23:34.977
54.585    2018-10-09 14:24:04.977
54.5597   2018-10-09 14:24:34.980
54.5363   2018-10-09 14:25:04.980
54.509    2018-10-09 14:25:34.983
54.4857   2018-10-09 14:26:04.987
54.4584   2018-10-09 14:26:34.987
54.435    2018-10-09 14:27:04.987
54.4097   2018-10-09 14:27:34.990
54.3825   2018-10-09 14:28:04.990

所需结果

55.2431   2018-10-09 14:18:30.000
55.2158   2018-10-09 14:19:00.000
54.7972   2018-10-09 14:19:30.000
54.7933   2018-10-09 14:20:00.000
54.7661   2018-10-09 14:20:30.000
54.7427   2018-10-09 14:21:00.000
54.7193   2018-10-09 14:21:30.000
54.6921   2018-10-09 14:22:00.000
54.6668   2018-10-09 14:22:30.000
54.6375   2018-10-09 14:23:00.000
54.6142   2018-10-09 14:23:30.000
54.585    2018-10-09 14:24:00.000
54.5597   2018-10-09 14:24:30.000
54.5363   2018-10-09 14:25:00.000
54.509    2018-10-09 14:25:30.000
54.4857   2018-10-09 14:26:00.000
54.4584   2018-10-09 14:26:30.000
54.435    2018-10-09 14:27:00.000
54.4097   2018-10-09 14:27:30.000
54.3825   2018-10-09 14:28:00.000

1 个答案:

答案 0 :(得分:1)

您可以尝试使用CASE语句和DATEADD()函数遵循SQL Select

declare @startdate datetime = '2018-10-09 14:18:34.823'
declare @enddate datetime = '2018-10-09 14:28:30.963'

select 
    case when DATEPART(ss, DateEntered) < 30 
    then 
        dateadd(ms,-1 * (DATEPART(ms, DateEntered) ), dateadd(ss,-1 * (DATEPART(ss, DateEntered) ),DateEntered))
    else 
        dateadd(ms,-1 * (DATEPART(ms, DateEntered) ), dateadd(ss,60 -1 * (DATEPART(ss, DateEntered) ),DateEntered)) 
    end
from TableB
where
DateEntered between @startdate and @enddate