如果我有一个包含以下字段的表格
ID, SomeFK, SomeTime
我将如何编写查询以返回每个的最新/前3个项目(基于SomeTime)SomeFK。
SomeTime
SomeFK
因此,结果可能看起来像
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....
返回特定的最新项目SomeFK很容易,但是我只是不认为如何针对上述情况进行操作。我也觉得它应该死得很简单!
编辑:
抱歉,我错过了一些关键信息。这是针对SQL2000的,因此ROW_NUMBER()无法使用!
ROW_NUMBER()
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
对于SQL 2000,我建议升级到受支持的平台。
但是如果你坚持的话。
select * from yourtable t1 where (select COUNT(*) from yourtable where somefk = t1.somefk and sometime>=t1.sometime ) <=3