如何select每组随机记录
How to select a random record for each group
我有一个table喜欢
| 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
列中的每个唯一值获取一个随机记录。
您可以使用 window 函数:
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;
With DISTINCT ON, You tell PostgreSQL to return a single row for each
distinct group defined by the ON clause.
更多关于该主题的信息:https://www.geekytidbits.com/postgres-distinct-on/
我有一个table喜欢
| 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
列中的每个唯一值获取一个随机记录。
您可以使用 window 函数:
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;
With DISTINCT ON, You tell PostgreSQL to return a single row for each distinct group defined by the ON clause.
更多关于该主题的信息:https://www.geekytidbits.com/postgres-distinct-on/