首页 > 解决方案 > 从每个组中获取随机唯一记录

问题描述

我们有两张桌子

ds (parent table):  id, survey_id, village_id, mandal_id, district_id, status, assigned_to_user, created_at

ds_details (child table):  id, ds_id(foreign_key), sub_survey_id, crop_id, crop_variety_id

每个父母都有多个子记录

我编写了如下查询,以获取每个组的 30 条记录。

with group_mandal_wise_crops as (
                select distinct dd.id as detail_record_id, dd.crop_id, dd.variety_id, dd.sub_survey_id, d.id, d.survey_id, d.village_id, d.mandal_id, row_number() over(partition by d.mandal_id) as mandal_wise_rows
             from ds_details dd join ds d on d.id = dd.ds_id where dd.status = 0 and d.assigned_to_user is null
            )
   select distinct id, survey_id, village_id, mandal_id from group_mandal_wise_crops
   where mandal_wise_rows <= 30 

我得到了每个组的唯一记录,但没有得到 30 条记录。因为在某些组中,唯一记录只有 10 或 15。我需要每组明智的 30 条记录。首先,它需要满足唯一条件,然后才能获得剩余的记录。

基于子表和父表的组合从父表中获取记录。

请帮助我如何以有效的方式编写查询

标签: sqlpostgresql

解决方案


推荐阅读