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

后端 未结 3 952
情深已故
情深已故 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条回答
  •  醉梦人生
    2021-01-05 21:37

    you can try this.

    DECLARE @Date DATE = '10/01/2010';
    
    WITH cte AS
        (
        SELECT ID, LinkedID, ABS(DATEDIFF(DD, @date, DATE)) diff,
            ROW_NUMBER() OVER (PARTITION BY LinkedID ORDER BY ABS(DATEDIFF(DD, @date, DATE))) AS SEQUENCE
        FROM MyTable
        )
    
    SELECT *
    FROM cte
    WHERE SEQUENCE = 1
    ORDER BY ID
    ;
    

    You didn't indicate how you want to handle the case where multiple rows in a LinkedID group represent the closest to the target date. This solution will only include one row And, in this case you can't guarantee which row of the multiple valid values is included.

    You can change ROW_NUMBER() with RANK() in the query if you want to include all rows that represent the closest value.

提交回复
热议问题