Query to Return Top Items for Each Distinct Column Value

前端 未结 3 1287
闹比i
闹比i 2021-01-25 09:07

If I have a table with the following fields

ID, SomeFK, SomeTime

How would I write a query return the latest/top 3 items (based on SomeTi

3条回答
  •  太阳男子
    2021-01-25 09:54

    Based on the this link (supplied as a comment to the original question). One soltion is:

    SELECT DISTINCT ID, SomeFK, SomeTime
    FROM SomeTable t1
    WHERE ID IN (SELECT TOP 3 ID
                   FROM SomeTable t2
                  WHERE t2.SomeFK= t1.SomeFK
                  ORDER BY SomeTime DESC)
    ORDER BY SomeFK, SomeTime DESC
    

    Although I've prefer the accepted solution now.

提交回复
热议问题