简体   繁体   中英

SQL to get the closest date

I have this query which is giving me the closest date but not properly, it works only one way

select *
from Table1
where id = 80
  and startdate = (select top 1 startdate 
                   from Table1 
                   where id = 80
                   order by abs(convert(float, getdate() - StartDate)))

Where I want to make sure that if there is date which is bigger and date which is lesser to the selected date has least difference, it should pick that record.

Any idea what I am missing here?

If you want the rows with a data similar to the startdate with id = 80 you can use something like this:

select top (3) t1.*
from (select t1.*,
             max(case when id = 80 then startdate end) over () as date_80
      from Table1 t1
     ) t1
order by abs(datediff(day, startdate, date_80));

If you want one record:

select top (1) t1.*
from (select t1.*,
             max(case when id = 80 then startdate end) over () as date_80
      from Table1 t1
     ) t1
where id <> 80
order by abs(datediff(day, startdate, date_80))

in case of a scenario like it is today 10th Dec and you have 15th Dec and 5th Dec, sub-ordering the records that are nearest by startdate descending has to put the later date at the top of the list.

I would also use the built in function DATEDIFF, treating dates as FLOAT is an old technique with some drawbacks, including possible confusions regarding fractions of days

    select * from Table1 where id = 80 
         and startdate = (select top 1 startdate from Table1 
         where id = 80 
            order by 
                abs(DATEDIFF(day,getdate(),startdate)) ASC,  --use a built in function over FLOAT
                StartDate DESC)    --If there are equidistant dates, this will take the higher of those dates

I guess you just need to add startdate<>t1.startdate as below in your query. The absence of which might have cause same startdates as output

     select * from Table1 t1
      where id = 80 
     and startdate = (select top 1 
    startdate from Table1 
     where id = 80 and startdate<>t1. 
     startdate order by 
    abs(convert(float,getdate() - 
     StartDate)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM