查询以选择具有最高值的记录

时间:2013-11-13 07:36:12

标签: sql database ms-access-2007

在Microsoft Access 2007中,我有一个包含以下列的表:

col1    mmonth yyear      col4   
a1  5      2013       Pete
a1  4      2013       John
a1  3      2013      Don
a2  7      2013      Elsa
a2  8      2012      Rick
a3  9      2009      Betty
a3  10     2001      Vera
a3  8      2013      Ronald

通过查询,我想要达到mmonth和yyear中编号最大的记录,如下所示:

col1    mmonth yyear      col4   
a1  5      2013       Pete
a2  7      2013      Elsa
a3  8      2013      Ronald

2 个答案:

答案 0 :(得分:0)

您可以使用RANK()功能:

SELECT *
FROM   (SELECT *, RANK() OVER (ORDER BY yyear DESC, mmonth DESC) AS rk
        FROM   some_table) t
WHERE  t.rk <= <number of records you want>

答案 1 :(得分:0)

this should do it

with cte as (

select col4,col1,max(month) as mm,max(year) as yy,RANK() over(order by year desc,month desc) as rn from table
group by col1,year,month,col4

)

select col1,yy,mm,col4 from cte where rn <4