T-SQL - SELECT by nearest date and GROUPED BY ID

后端 未结 3 954
情深已故
情深已故 2021-01-05 21:26

From the data below I need to select the record nearest to a specified date for each Linked ID using SQL Server 2005:

ID     Date      Linked ID         


        
3条回答
  •  -上瘾入骨i
    2021-01-05 21:38

    You want to look at the absolute value of the DATEDIFF function (http://msdn.microsoft.com/en-us/library/ms189794.aspx) by days.

    The query can look something like this (not tested)

    with absDates as 
    (
       select *, abs(DATEDIFF(day, Date_Column, '2010/10/01')) as days
       from table
    ), mdays as
    ( 
       select min(days) as mdays, linkedid
       from absDates
       group by linkedid
    )
    select * 
    from absdates
    inner join mdays on absdays.linkedid = mdays.linkedid and absdays.days = mdays.mdays
    

提交回复
热议问题