SQL Join to get most recent record

后端 未结 2 640
無奈伤痛
無奈伤痛 2020-12-20 04:13

I have three tables:

  • Measurements (MeasureID, Time, Distance, Value)
  • Events(EventID, Time Value)
  • EventValues
相关标签:
2条回答
  • 2020-12-20 04:38

    You can use CROSS APPLY.

    SELECT  
        M.*, Data.* 
    FROM [Measure] M 
    CROSS APPLY
         (SELECT TOP 1 EV.* FROM [Event] E JOIN EventValues EV ON E.EventID = EV.EventID  
         WHERE M.Time >= E.Time ORDER BY E.Time DESC) AS Data
    ORDER BY M.Distance 
    
    0 讨论(0)
  • 2020-12-20 04:38

    Try something like this (not tested)

    SELECT * FROM
    (
        SELECT M.*, E.*, EV.EventDataID, EV.Type, EV.Value,
            Rank() over (Partition BY M.MeasureID order by M.Time - E.Time) as Rank
        FROM [Measure] M 
        INNER JOIN [Event] E ON M.Time >= E.Time
        INNER JOIN EventValues EV ON E.EventID = EV.EventID
    ) T
    WHERE Rank = 1
    

    EDIT

    SELECT * FROM
    (
        SELECT M.*, E.*, EV.EventDataID, EV.Type, EV.Value,
            Rank() over (Partition BY M.MeasureID order by M.Time - E.Time) as Rank
        FROM [Measure] M 
        LEFT JOIN [Event] E ON M.Time >= E.Time
        LEFT JOIN EventValues EV ON E.EventID = EV.EventID
    ) T
    WHERE Rank = 1
    
    0 讨论(0)
提交回复
热议问题