编辑:我在答案的末尾添加了一些解释。
DECLARE @Test TABLE(
id INT,
[uid] INT,
[action] INT
);
INSERT @Test(id , [uid] , [action])
SELECT 1 , 1 , 2
UNION ALL
SELECT 2 , 3 , 1
UNION ALL
SELECT 3 , 2 , 2
UNION ALL
SELECT 4 , 3 , 2
UNION ALL
SELECT 5 , 1 , 1;
DECLARE @last_action INT;
SET @last_action = 1; --or = 2
SELECT x.uid
FROM
(
SELECT t.uid,
t.action,
ROW_NUMBER() OVER(PARTITION BY t.[uid] ORDER BY t.id DESC) AS RowNum
FROM @Test t
) x
WHERE x.RowNum = 1
AND x.action = @last_action
结果:
uid
-----------
1
说明:
从派生表查询(...) x
将产生以下结果:
id uid action RowNum
-- --- ------ ------
5 1 1 1 <-- last action (1) for uid = 1
1 1 2 2
-- --- ------ ------
3 2 2 1 <-- last action (2) for uid = 2
-- --- ------ ------
4 3 2 1 <-- last action (2) for uid = 3
2 3 1 2
-- --- ------ ------