I have a situation like, I need to find out which record is having minimum difference of days between atleast 2 dates. Like –
Table Data is like
Input Parameter : [aDate = 12-Nov-2020, Infold = 2]
Result should be:
Need to find the date difference between the input dates and existing dates, find the record which is having minimum days gap.
I am trying in this way:
select/update query where <here not sure what to put> = MIN ( select existing.aDate::date - input.aDate::date from table, select input.aDate::date - existing.aDate::date from table )
I just need to identify that particular record, kindly advise.
Advertisement
Answer
You can use order by
and limit
to identify the “closest” record to a given date:
select t.* from mytable t order by abs(adate - date '2020-11-12')) limit 1
If you want an update
statement:
update mytable t set infold = 2 from ( select pk from mytable order by abs(adate - date '2020-11-12')) limit 1 ) t1 where t1.pk = t.pk