PostgreSQL:如何按学生分组选取2条随机记录
实现每个学生返回2条随机记录的PostgreSQL代码调整
你可以通过筛选随机排序后的前2条记录来实现需求,具体调整如下:
原代码回顾
with my_table (id, student, category, score) as (values (1, 'Alex', 'A', 11), (2, 'Alex', 'D', 4), (2, 'Alex', 'B', 50), (2, 'Alex', 'C', 83), (2, 'Alex', 'D', 5), (3, 'Bill', 'A', 81), (6, 'Carl', 'C', 5), (7, 'Carl', 'D', 2), (7, 'Carl', 'B', 21), (7, 'Carl', 'A', 55), (7, 'Carl', 'A', 86), (7, 'Carl', 'D', 10) ) select *, row_number() over (partition by student order by random()) as row_sort from my_table
调整后的代码
with my_table (id, student, category, score) as (values (1, 'Alex', 'A', 11), (2, 'Alex', 'D', 4), (2, 'Alex', 'B', 50), (2, 'Alex', 'C', 83), (2, 'Alex', 'D', 5), (3, 'Bill', 'A', 81), (6, 'Carl', 'C', 5), (7, 'Carl', 'D', 2), (7, 'Carl', 'B', 21), (7, 'Carl', 'A', 55), (7, 'Carl', 'A', 86), (7, 'Carl', 'D', 10) ) select id, student, category, score from ( select *, row_number() over (partition by student order by random()) as row_sort from my_table ) t where row_sort <= 2;
核心逻辑说明
- 保留原有的
row_number() over (partition by student order by random()),它会给每个学生的记录按随机顺序分配行号 - 把原查询作为子查询,在外层添加
where row_sort <= 2的筛选条件,只保留每个学生的前2条随机记录 - 如果某个学生的记录不足2条(比如示例里的Bill只有1条),会返回该学生的所有现有记录
内容的提问来源于stack exchange,提问作者Joehat
相关产品推荐
相关产品推荐

