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

后端 未结 3 1089
情深已故
情深已故 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:46

    You can also try to do it with a subquery in the select statement:

    select  [LinkedId],
            (select top 1 [Date] from [Table] where [LinkedId]=x.[LinkedId] order by abs(DATEDIFF(DAY,[Date],@date)))
    from    [Table] X
    group by [LinkedId]
    

提交回复
热议问题