我有一张这样的表:
Id | Modified | OwnerId| Mode
----+----------+---------+-----
1 | 14/01/14 | 101 | On
2 | 14/02/21 | 102 | Off
3 | 14/03/21 | 102 | On
4 | 14/04/21 | 102 | Off
5 | 14/05/21 | 102 | On
6 | 14/05/22 | 105 | Off
7 | 14/06/21 | 102 | Off
我想找到每个OwnerId的最后一次出现,其中Mode等于' Off'像这样:
Id | Modified | OwnerId| Mode
----+----------+---------+-----
6 | 14/05/22 | 105 | Off
7 | 14/06/21 | 102 | Off
我将如何实现这一目标?
答案 0 :(得分:2)
这样应该可行:
SELECT Id, Modified, OwnerId, Mode
FROM (
SELECT Id, Modified, OwnerId, Mode,
ROW_NUMBER() OVER(PARTITION BY OwnerId ORDER BY Modified DESC) As rn
FROM MyTable
Where Mode = 'Off'
) t
WHERE t.rn = 1