tags:

views:

37

answers:

2

I have a table 'articles' : id / uid / last_update / content.

I want to construct a sql statement that selects an arbitrary number(say 3) of records of each user(identified by uid) that are most recently updated from the table. How can I do that?

+1  A: 
DECLARE @Top tinyint;

SELECT @Top = ABS(CHECKSUM(NEWID())) % 5 + 1;

;WITH MyCTE AS
(
    SELECT
        stuff, things, 
        ROW_NUMBER() OVER (PARTITION BY uid ORDER BY UpdatedDateTime DESC) AS Ranking
    FROM
        MyTable
)
SELECT
    stuff, things
FROM
    MyCTE
WHERE
    Ranking <= @Top
gbn
TopCount = @Top
eugeneK
+4  A: 

In SQL Server and Oracle, you can use ROW_NUMBER() to label records per user. The following query tags rn=1 on the latest row for that user, rn=2 on the second latest, and so on:

select *
from (
    select
        row_number() over (partition by uid order by UpdateDt desc) 
        as rn
    ,   *
    from YourTable
) sub
where rn <= 3

The subquery is required because you can't use ROW_NUMBER() in a WHERE clause directly.

If you're using MySQL, this problem is much harder. Here's a link to a solution with user variables.

Andomar