如何查找具有重复值的列中的最后一行

时间:2011-07-27 09:02:06

标签: sql sql-server tsql

我公司的某个人写了一个封闭的存储过程,它给出了这些结果:

rowNumber   userid  DateCreated
1             500   2011-07-20 11:03:24.590
2             500   2011-07-21 11:03:24.590
3             500   2011-07-22 11:03:24.590
1             502   2011-07-20 11:03:24.590
2             502   2011-07-21 11:03:24.590
1             504   2011-07-20 11:03:24.590
2             504   2011-07-21 11:03:24.590

我无法更改使用row_number的原始查询,因此上面的列表是我的只读数据源。

我需要通过max rownumber获得每个userId的完整数据,即

 3            500   2011-07-22 11:03:24.590
 2            502   2011-07-21 11:03:24.590
 2            504   2011-07-21 11:03:24.590

重要的是我不再使用rownumber。

2 个答案:

答案 0 :(得分:1)

select t.* 
from 
(
    select userid, max(rownumber) m 
    from table
    group by userid
) c
    inner join table t
         on c.userid = t.userid and c.m = t.rownumber

答案 1 :(得分:0)

SELECT test.rownumber, test.userid, test.datecreated
FROM test
     INNER JOIN (SELECT MAX(rownumber) AS Expr1, userid
                 FROM test AS test_1
                 GROUP BY userid) AS t1
     ON test.userid = t1.userid AND test.rownumber = t1.Expr1
     ORDER BY test.userid