postgresql將查詢出來的記錄根據某個字段去重,只取記錄集中相同記錄的第一條


1.可以循環表取出相同字段的第一條去建立臨時表或視圖

2.使用pg的row_number 函數對相同字段記錄分組排序,取出排序分組記錄中的第一個。

下例即取出查詢結果集合中產品對應date最新的那一條數據集合,相當於根據product_id去重,保留date最大的一條

select s.product_id, s.price
from (
    select *, row_number() over (partition by ttt.product_id order by ttt.date desc) as group_idx
    from (
         select distinct (kpol.product_id),kpol.price, sm.date from
            kthrp_purchase_order_line kpol
            left join stock_move sm on split_part(sm.ref, ',', 1) = 'kthrp.purchase.order.line' and split_part(sm.ref, ',', 2)::INTEGER = kpol.id
            left join product_product pp on pp.id = kpol.product_id
         where sm.date is not null
            order by sm.date desc
             ) ttt
) s
where s.group_idx = 1;

可以簡化為:

select s.field_name_s, s.field_name_x
from (
    select *, row_number() over (partition by ttt.field_name_a order by ttt.field_name_b desc) as group_idx
    from 子查詢 ttt
) s
where s.group_idx = 1;

1.row_number() 為返回的記錄定義各行編號

2.pritition by 分組

3.order by 排序


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM