sql - 从每个组中获取随机唯一记录
问题描述
我们有两张桌子
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 条记录。首先,它需要满足唯一条件,然后才能获得剩余的记录。
基于子表和父表的组合从父表中获取记录。
请帮助我如何以有效的方式编写查询
解决方案
推荐阅读
- functional-programming - 为什么 x = x +1 在 Elixir 中有效?
- javascript - Mongoose Populate - 如何动态或编程执行字段选择
- json - 如何将飞镖列表反序列化为 json 对象?
- python - 在 pandas 中使用 for 循环的虚拟变量和连接数据帧
- python - 从Python中的字符串中提取正确的字符
- python - 线程结束时如何终止主程序?还在等待进程在 python 中分离吗?
- java - sparql 使用 live.dbpedia 并在结果中获取 XML Schema
- list - 在理解列表理解中的列表切片时需要帮助,
- ios - 使用开关控制流从函数推断返回类型
- spring-boot - 401 Unauthorized 对 REST API 的每个请求