PostgreSQL:如何为每个列值选择N个随机条目

xlpyo6sf  于 2023-04-20  发布在  PostgreSQL
关注(0)|答案(2)|浏览(204)

我有以下代码

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

我想知道如何调整它以返回每个学生2个随机条目。

xa9qqrwz

xa9qqrwz1#

将您的选择 Package 到外部并添加where row_sort<=2

select id, student, category, score
  from(
select *,
     row_number() over (partition by student order by random()) as row_sort
from my_table) inner_t
where row_sort<=2

演示here
| 身份证|学生|范畴|刻痕|
| --------------|--------------|--------------|--------------|
| 二|亚历克斯|D|五|
| 二|亚历克斯|B|五十|
| 三|比尔|A|八十一|
| 七|卡尔|D|10个|
| 七|卡尔|A|五十五|

2lpgd968

2lpgd9682#

窗口函数的值只能在查询运行后访问,因此使用第二个CTE就可以了

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)
),
CTE2 as (select *,
     row_number() over (partition by student order by random()) as row_sort
from my_table)
SELECT id, student, category, score
  FROM CTE2
WHERE row_sort <= 2
身份证学生范畴刻痕
亚历克斯C八十三
亚历克斯D
比尔A八十一
卡尔A八十六
卡尔B二十一
SELECT 5

fiddle

相关问题