问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/57340413/how-to-find-all-the-timestamp-values-interval-by-each-minute-between-the-two-tim