繁体   English   中英

如何为每个组选择随机记录

[英]How to select a random record for each group

我有一张像

 |    A   | B | C | D |
 |--------|---|---|---|
 | Value1 | x | x | x |
 | Value1 | y | x | y |
 | Value1 | x | x | x |
 |        ....        |
 | Value2 | x | x | x |
 | Value2 | x | x | x |
 | Value2 | x | x | x |
 |        ....        |
 | Value3 | x | x | x |
 | Value3 | x | x | x |
 | Value3 | x | x | x |

其中A列可以有一个集合中的一个值。 我想为A列中的每个唯一值获取随机记录。

您可以使用窗口函数:

select *
from (
    select 
        t.*,
        row_number() over(partition by a order by random()) rn
    from mytable t
) t
where rn = 1

row_number()为具有相同a组中的每条记录分配一个随机排名; 然后,外部查询每组过滤一条记录。

实际上,由于您正在运行 Postgres,您也​​可以使用distinct on ,这可以提供更好的性能(和更短的语法):

select distinct on (a) t.*
from mytable t
order by a, random();

您可以使用distinct on做到这一点:

select distinct on (a) a, b, c, d
from test t;

这是一个演示

使用 DISTINCT ON,您告诉 PostgreSQL 为 ON 子句定义的每个不同组返回一行。

有关该主题的更多信息: https : //www.geekytidbits.com/postgres-distinct-on/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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