簡體   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