Query to Return Top Items for Each Distinct Column Value

≡放荡痞女 提交于 2019-12-02 13:39:52

问题


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 SomeTime) for each SomeFK.

So, the result might look like

SomeFK    Sometime
0         2012-07-05 
0         2012-07-04 
0         2012-07-03 
1         2012-07-03 
1         2012-07-02 
1         2012-07-01 
2         2012-07-03 
2         2012-07-02 
2         2012-07-01 
....etc....

Returning the latest items for a particular SomeFK is easy, but i just can't think how to do it for the above. I also feel it should be dead simple!

EDIT:

Apologies, I missed a key bit of information. this is for SQL2000, so ROW_NUMBER() can't be used!


回答1:


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



回答2:


I think I understood you correctly, can you not select the max SomeTime and then group, like this:

select SomeFK, max(SomeTime) 
from Table
group by SomeFK

I could be off the mark here, as I'm not entirely sure what you mean by latest.




回答3:


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.



来源:https://stackoverflow.com/questions/11966774/query-to-return-top-items-for-each-distinct-column-value

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