如何 select 来自 postgres 中 n 个随机组的所有行

How to select all rows from n random groups in postgres

此问题与在 PostgreSQL 中制定查询有关 假设我有以下 table:

record   entity   docid   sentencid   
1   A   123   1231   
1   A   123   1232
1   A   100   1001
1   C   100   1002
1   B   121   1212
1   B   123   1234
2   B   102   1021
2   D   111   1111
2   D   102   1022
2   E   101   1011   
3   C   111   1115
3   C   111   1113
3   C   111   1114

是否有一个 PostgresSQL 查询可用于 select 此 table 中每条记录的 n 个(或更少)随机实体组的所有行?假设 n 为 2。因此查询应该 select 记录 3 的所有行和记录 1 和 2 的任意 2 个随机实体组的所有行。最终结果应按 accessionentity, docid, sentenceid.

这是 n=2 的示例结果:

record   entity   docid   sentencid   
1   A   100   1001
1   A   123   1231   
1   A   123   1232
1   B   121   1212
1   B   123   1234
2   D   102   1022
2   D   111   1111
2   E   101   1011   
3   C   111   1113
3   C   111   1114
3   C   111   1115

假设实体 A 和 B 是从记录 1 的实体集 (A、B、C) 中随机 select 编辑的,而实体 D 和 E 是从中随机 select 编辑的记录 2 的实体集 (B,D,E)。应为每条记录随机 select 编辑 n 个实体。

我广泛搜索了这个问题的答案,但没有找到任何有效的查询。感谢您对此进行调查!

您可以将 row_numberrandom() 命令一起使用,以在每个 record 组中随机 select n 个实体。然后加入你的主 table

select * from Table1 t1
join (
    select * from (
        select record, entity,
            row_number() over (partition by record order by random()) rn
        from Table1
        group by record, entity
    ) t where rn <= 2
) t2 on t1.record = t2.record and t1.entity = t2.entity

Demo