Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7189279
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T19:16:08+00:00 2026-05-28T19:16:08+00:00

For you T-SQL gurus: I have the following table: ID Arrival 1 06:16:00 2

  • 0

For you T-SQL gurus:

I have the following table:

ID              Arrival
1       06:16:00
2       06:17:00
3               07:19:00
4       08:21:00
5       10:22:00
6       13:21:00
7       20:22:00

Say the time is currently 08:00 AM and I want to select 2 records before and after record with closest time to now. Result should return records with IDs 2,3,4,5 and 6.

Getting the records before and after record with ID=4 is straight forward but so far, I cannot figure out how to return the complete set as part of the same query. I have these two select statements:

SELECT TOP(2) * FROM Schedules 
where (datepart(hour, Arrival) - datepart(hour, getdate()))*60 + datepart(minute, Arrival) - datepart(minute, getdate())  < 0
order by (datepart(hour, Arrival) - datepart(hour, getdate()))*60 + datepart(minute, Arrival) - datepart(minute, getdate())

SELECT TOP(2) * FROM Schedules 
where (datepart(hour, Arrival) - datepart(hour, getdate()))*60 + datepart(minute, Arrival) - datepart(minute, getdate())  >= 0
order by (datepart(hour, Arrival) - datepart(hour, getdate()))*60 + datepart(minute, Arrival) - datepart(minute, getdate()) asc

which return records before and after. I tried using a union on both statements but this requires dropping the first order by clause which invalidates my query criteria.

Any ideas will help, thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T19:16:09+00:00Added an answer on May 28, 2026 at 7:16 pm

    We can use ROW_NUMBER to partition on if the arrival is before or after and order by the absolute value of the difference between the arrival and the input time.

    DECLARE @CurrentTime as  time 
    SET @CurrentTime = '08:00 AM'
    
    DECLARE @Schedules  table  (id int, arrival time)
    INSERT INTO @Schedules
    VALUES (1 , '06:16:00' ),
    (2, '06:17:00' ),
    (3, '07:19:00'),
    (4, '08:21:00'),
    (5, '10:22:00'),
    (6, '13:21:00'),
    (7, '20:22:00')
    
    DECLARE @closestTime as time
    SELECT TOP 1 @closestTime = arrival  FROM @Schedules ORDER BY ABS(DATEDIFF(mi, @CurrentTime ,arrival))
    
    ;WITH cte 
         AS (SELECT id, 
                    arrival, 
                    Row_number() OVER (PARTITION BY (CASE WHEN @closestTime > arrival THEN 1 
                                                          WHEN @closestTime < arrival THEN 2 END) 
                                       ORDER BY Abs(Datediff(mi, @closestTime, arrival))) rn 
             FROM   @Schedules) 
    SELECT * 
    FROM   cte 
    WHERE  rn < 3 
            OR arrival = @closestTime 
    ORDER  BY id
    

    Results in

    id          arrival          rn
    ----------- ---------------- --------------------
    2           06:17:00.0000000 2
    3           07:19:00.0000000 1
    4           08:21:00.0000000 1
    5           10:22:00.0000000 1
    6           13:21:00.0000000 2
    

    See working example at this data.se query

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

a simple question for all you SQL gurus: I have the following table structures
SQL gurus I have a table structure as follows Id Name IdPartner Id1 name1
Another one for you SQL Server gurus... I have a table like so... AccountManager
I have a table in SQL Server where, for each row r at time
I have quick question for you SQL gurus. I have existing tables without primary
SQL Server 2005 I have an SQL Function (ftn_GetExampleTable) which returns a table with
Sql Service Broker uses the following heuristic to determine when you have messages in
i have few questions for SQL gurus in here ... Briefly this is ads
Ok SQL and Oracle gurus I have a somewhat complicated query that I'm trying
Alright SQL Server Gurus, fire up your analyzers. I have a list of titles

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.