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
209 views
in Technique[技术] by (71.8m points)

SQL Server datetime ranges between records

What would be the best way to get datetime ranges between records in SQL Server? I think it would be easiest to explain with an example.

I have the following data - these records start and end datetime ranges would never overlap:

ID Start End
1 1/27/2021 06:00:00 1/27/2021 09:00:00
2 1/27/2021 10:00:00 1/27/2021 14:00:00
3 1/27/2021 21:00:00 1/28/2021 04:00:00
4 1/28/2021 06:00:00 1/28/2021 09:00:00
question from:https://stackoverflow.com/questions/65929834/sql-server-datetime-ranges-between-records

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

1 Answer

0 votes
by (71.8m points)

Use lead():

select t.*
from (select id, end as start, lead(start) over (order by start) as end
      from t
     ) t
where end is not null;

Note: end is a lousy name for a column, given that it is a SQL keyword. I assume it is for illustrative purposes only.

Here is a SQL Fiddle.


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

...