SQL Server选择具有相同最后一个操作的行列表

时间:2012-04-28 10:31:45

标签: php sql-server

我有桌子:

id | uid | action
-----------------
 1 |  1  |   2
 2 |  3  |   1
 3 |  2  |   2
 4 |  3  |   2
 5 |  1  |   1

如何在例如1的最后一个动作中选择uid?在这种情况下只有最后一行。

更新:正如你在uid = 3中看到的那样,我们首先有action = 1,然后是action = 2,因为uid = 3对我们来说不是“好”行。但是对于uid = 1,最后一个动作是1,所以“好”行。

UPDATE2 :操作= 1输入,操作= 2退出。最后,我需要获取现在正在构建的用户列表,或者至少列出每个用户的最后一个操作列表。

3 个答案:

答案 0 :(得分:4)

编辑:我在答案结尾处添加了一些解释。

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
-- --- ------ ------

答案 1 :(得分:1)

要获取表格中的最后一行,您可以按id排序(看起来每次为一行递增)。然后,您可以使用TOP 1为每个查询过滤1行。

SELECT TOP 1 * FROM Table
WHERE action = 1
ORDER BY id DESC

答案 2 :(得分:0)

SQLServer方言,一种方式(很多)...... - 假设列id定义了订单...升序... - 假设id是唯一的,至少对于每个uid

select uid
from (
    select uid, max(id) as lastid
    from t
    group by uid
) l
join t on t.uid = l.uid and t.id = l.lastid
where t.action = 1
另一种方式......

select uid
from t
where id in (select max(id) from t t2 where t2.uid = t.uid)
    and t.action = 1