Query most recent TWO entries per widget

自古美人都是妖i 提交于 2020-01-11 13:22:32

问题


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, date, info1, info2, etc...).

What I want to do is display the most recent TWO tests. I dont think i really need to use the table Widgets for this but i described it so you would know where im coming from.

I have constructed a "Totals" query that uses the MAX() function and displays the single most recent Date for each ID. I then can use this query to construct another query that displays useful information about the test that happened on that date for that widget. What i really need, though is to have the most recent two test dates for each widget.


回答1:


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



回答2:


(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
)


来源:https://stackoverflow.com/questions/1395991/query-most-recent-two-entries-per-widget

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!