简体   繁体   中英

SQL question: how to select arbitrary numbers of records in each record group?

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM