如何找到所有时间戳记值之间的两个时间戳记录之间的每分钟间隔

时间:2019-08-03 16:58:35

标签: sql-server sql-timestamp

我有一个具有三个字段ID(整数)的表-唯一,打开日期(日期时间),关闭日期(日期时间):

Id  Open Date                  Close Date
1   2019-07-03 16:28:39.497    2019-07-04 16:28:39.497
2   2019-07-04 15:28:39.497    2019-07-05 19:28:39.497
…..N        

我想计算打开日期和关闭日期之间的所有时间戳,以每分钟为间隔。

所以我想要的最终输出是这样的:

Id  Open Date             Close Date                   TimeStamp Range
1   2019-07-03 16:28:39.497   2019-07-04 16:28:39.497   2019-07-03 16:29:00.0000
1   2019-07-03 16:28:39.497   2019-07-04 16:28:39.497   2019-07-03 16:30:00.0000
1   2019-07-03 16:28:39.497   2019-07-04 16:28:39.497   2019-07-03 16:31:00.0000
1   2019-07-03 16:28:39.497   2019-07-04 16:28:39.497   …..........................
1   2019-07-03 16:28:39.497   2019-07-04 16:28:39.497   2019-07-04 16:27:00.0000
2   2019-07-04 15:28:39.497   2019-07-05 19:28:39.497   2019-07-04 15:29:00.0000
2   2019-07-04 15:28:39.497   2019-07-05 19:28:39.497   2019-07-04 15:30:00.0000
2   2019-07-04 15:28:39.497   2019-07-05 19:28:39.497   2019-07-04 15:31:00.0000
2   2019-07-04 15:28:39.497   2019-07-05 19:28:39.497   ….................................
2   2019-07-04 15:28:39.497   2019-07-05 19:28:39.497   2019-07-05 19:27:00.0000
N   …............................   …...........................    …......................................

有人会为此编写SQL查询吗?

1 个答案:

答案 0 :(得分:0)

这里是使用临时计数/数字表和Declare @YourTable Table ([Id] int,[Open Date] datetime,[Close Date] datetime) Insert Into @YourTable Values (1,'2019-07-03 16:28:39.497','2019-07-04 16:28:39.497') ,(2,'2019-07-04 15:28:39.497','2019-07-05 19:28:39.497') Select A.* ,TSRange = DateAdd(Minute,N,convert(varchar(16),[Open Date],20)) From @YourTable A Cross Apply ( Select Top (DateDiff(MINUTE,[Open Date],[Close Date])-1) N=Row_Number() Over (Order By (Select NULL)) From master..spt_values n1, master..spt_values n2 ) B

的一种选择

示例

Option Explicit
Private Sub WorkSheet_Change(ByVal Target As Range)
Dim firstrow As Long, lastrow As Long
    If Not Intersect(Target, Range("A1")) Is Nothing Then
    If Target.Count > 1 Then Exit Sub
       firstrow = .Cells(Application.WorksheetFunction.Match("ABC", .Range("D:D"), 0), 6)
       lastrow = .Cells(fr).End(xlDown).Row
           With Range(firstrow, lastrow)
               .Formula = "=$F$1+G1"
           End With
    End If
End Sub

返回

enter image description here