我有一张 table :
| P_id | Month | Year | Name |
624 09 2009 Test1
600 10 2010 Test2
624 10 2010 Test6
600 09 2011 Test7
我想按
P_id
降序、Year
升序、Month
升序对表格进行排序根据顺序,我想要每个
P_id
的最后一条记录。
运行步骤 1 后:
| P_id | Month | Year | Name |
624 09 2009 Test1
624 10 2010 Test6
600 10 2010 Test2
600 09 2011 Test7
期望的输出:
| P_id | Month | Year | Name |
624 10 2010 Test6
600 09 2011 Test7
最佳答案
您可以使用row_number
:
select *
from (
select row_number() over (
partition by p_id
order by year desc, month desc) as rn
, *
from YourTable
) as SubQueryAlias
where rn = 1
子查询是必需的,因为您不能在 where
子句中直接使用 row_number
。
关于sql - 按记录分组,然后从每组中获取最后一个升序排序记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10676308/