Query to Return Top Items for Each Distinct Column Value

前端 未结 3 1282
闹比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:59

    SELECT SomeFk, SomeTime 
    FROM 
        (
        SELECT *, ROW_NUMBER() OVER (PARTITION BY SomeFK ORDER BY sometime desc) rn
        FROM yourtable
        ) v
    WHERE rn<=3
    ORDER BY somefk, rn
    

    For SQL 2000, I recommend upgrading to a supported platform.

    But if you insist.

    select *
    from yourtable t1
    where
        (select COUNT(*)
         from yourtable
         where somefk = t1.somefk
         and sometime>=t1.sometime
        ) <=3
    

提交回复
热议问题