1:N关联SQL查询结果重复 如何仅获取首行或末行实现去重
SQL 1:N关联查询重复行解决方案
- 重复根因:查询关联了存在1:N关系的表(通常是
endorsement_contract_covered_element_version版本表存在同一主记录对应多版本的情况),关联后生成了多条返回字段一致的重复数据。
方案1:直接去重(返回字段完全重复时适用)
如果业务上没有指定取哪条的规则,仅需要去重,直接在SELECT后加DISTINCT关键字即可:
select DISTINCT eccev.extra_data , c.id, case when (eccev.extra_data::json->'tns')::VARCHAR = 'false' then 'NON' else case when coalesce((eccev.extra_data::json->'tns')::VARCHAR, '') = '' then 'EMPTY VALUE' else 'OUI' end end as tns from endorsement_contract_covered_element_version eccev, endorsement_contract_covered_element ecce, endorsement_contract ec, contract c, endorsement e, party_party pp WHERE ec.endorsement = e.id and e.applicant = pp.id and c.subscriber = pp.id AND eccev.covered_element_endorsement = ecce.id and ecce.contract_endorsement = ec.id and c.contract_number = 'CT20200909112'
方案2:窗口函数取指定行(按业务规则取首行/末行时适用)
如果需要按规则取指定行(比如最新版本、最早版本),用ROW_NUMBER()窗口函数实现,灵活性更高:
SELECT extra_data, id, tns FROM ( select eccev.extra_data , c.id, case when (eccev.extra_data::json->'tns')::VARCHAR = 'false' then 'NON' else case when coalesce((eccev.extra_data::json->'tns')::VARCHAR, '') = '' then 'EMPTY VALUE' else 'OUI' end end as tns, -- PARTITION BY后填写去重维度,示例按合同id分组,可根据需求加多个字段 -- ORDER BY后填写排序规则,ASC正序取首行,DESC倒序取末行,可替换为版本号、创建时间等业务字段 ROW_NUMBER() OVER(PARTITION BY c.id ORDER BY eccev.id DESC) AS rn from endorsement_contract_covered_element_version eccev, endorsement_contract_covered_element ecce, endorsement_contract ec, contract c, endorsement e, party_party pp WHERE ec.endorsement = e.id and e.applicant = pp.id and c.subscriber = pp.id AND eccev.covered_element_endorsement = ecce.id and ecce.contract_endorsement = ec.id and c.contract_number = 'CT20200909112' ) t WHERE rn = 1
内容的提问来源于stack exchange,提问作者Òkami
相关产品推荐
相关产品推荐

