Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

sql server - How to find all the timestamp values interval by each minute between the two timestamp records

I have a table having three fields Id (Integer) - Unique, Open Date (Datetime), Close Date(DateTime):

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        

I want to calculate the all the timestamps between open date and close date with an interval of each minute.

So the final output I want is like this:

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   …............................   …...........................    …......................................

Would someone write the SQL query for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is one option using an ad-hoc tally/numbers table and a Cross Apply

Example

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

Returns

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...