postgresql 實現取出分組中最大的幾條資料
阿新 • • 發佈:2021-01-04
看程式碼吧~
WITH Name AS ( SELECT * FROM ( SELECT xzqdm,SUBSTRING (zldwdm,1,9) xzdm,COUNT (*) sl FROM sddltb_qc WHERE xzqdm IN ('130432','210604') GROUP BY xzqdm,9) ) AS A ORDER BY xzqdm,xzdm,sl ) SELECT xzqdm,sl FROM ( SELECT *,ROW_NUMBER () OVER ( PARTITION BY xzqdm ORDER BY sl DESC ) AS Row_ID FROM Name ) AS A WHERE Row_ID <= 2 ORDER BY xzqdm
其中
select * from (select xzqdm,substring(zldwdm,count(*) sl from sddltb_qc where xzqdm in ('130432','210604') group by xzqdm,9)) as a order by xzqdm,sl
執行結果:
新增行序號:ROW_NUMBER () OVER (ORDER BY A.bsm ASC) AS 序號
分組新增序號:ROW_NUMBER () OVER (PARTITION BY xzqdm ORDER BY A.bsm ASC) AS 序號
補充:pgsql 表隨機取幾條資料
取100條
select * from map_route_info_composite order by random() limit 100
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。