从不同的组中选择每2个随机记录

时间:2018-05-02 06:15:22

标签: postgresql select random

这是我的表的截图,我的DBMS是postgresql

field_1是我记录的唯一键,field_2是组码,field_4是电话号码。

从这里我想从不同的组中选择2个随机记录。 换句话说,选择2个随机记录并按field_2分组

我只能在下面进行查询。

 select distinct(field_2) as group_name from mytable group by 1

.. 请帮我继续我的项目:(

enter image description here

3 个答案:

答案 0 :(得分:1)

尝试以下查询:

 getSettings('api-settings').then(val=>{
   console.log(val.apiKey);
   console.log(val.apiKeySecret);
});

这将返回SELECT DISTINCT ON (field_2) * FROM table ORDER BY (field_2),random() LIMIT 2 的两个随机记录:

field_2

答案 1 :(得分:0)

你可以写下面的查询:

SELECT * FROM mytable GROUP BY field_2 ORDER BY RAND()LIMIT 0,2

答案 2 :(得分:0)

我不知道您的预期输出,这可能对您有所帮助: 组中的第一个随机顺序(field_2) 选择第一个和第二个field_1,然后输出

with temp_shuffel as
(
select 
*
from public.tbl_test
order by field_2,  random()
),

temp_values as
(
select 
nth_value(field_1,1) over (PARTITION by field_2 order by field_2 rows between unbounded preceding and unbounded following) as f1,
nth_value(field_1,2) over (PARTITION by field_2 order by field_2 rows between unbounded preceding and unbounded following) as f2
 from temp_shuffel
)

select distinct on (f1,f2)
row1.field_1,
row1.field_2,
row1.field_4,

row2.field_1 as field2_1,
row2.field_2 as field2_2,
row2.field_4 as field2_4

from temp_values
left join public.tbl_test as row1  on row1.field_1 = temp_values.f1
left join public.tbl_test as row2 on row2.field_1 = temp_values.f2
order by f1,f2,row1.field_1