Query most recent TWO entries per widget

前端 未结 2 537
刺人心
刺人心 2021-01-26 12:50

I have two tables. One (Widgets) has a list of widgets (ID, widget_name, color, etc...) and data about them. The other one (Tests) has a list of tests run on the widgets (ID, d

相关标签:
2条回答
  • 2021-01-26 13:18

    (assuming all dates for the same widget are unique)

    select T.*
    from Widget W
    join Test T on T.widget_id = W.id
    where T.date >= (
        select max(T2.date)
        from Test T2
        where T2.widget_id = W.id
        and T2.date < (
            select max(T3.date)
            from Test T3
            where T3.widget_id = W.id
        )
    ) 
    or T.date == (
        select max(T2.date)
        from Test T2
        where T2.widget_id = W.id
    )
    
    0 讨论(0)
  • 2021-01-26 13:30

    If you need the two most recent tests overall, then

    Select * From Tests T
    Where (Select Count(*) From tests
           Where testDate > T.TestDate) < 2
    

    If you need the two most recent tests for each Widget, then

    Select * From Tests T
    Where (Select Count(*) From tests
           Where WidgetId = T.WidgetId 
               And testDate > T.TestDate) < 2
    
    0 讨论(0)
提交回复
热议问题