postgresql 實現取出分組中最大的幾條數據

看代碼吧~

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,
    SUBSTRING (zldwdm, 1, 9)
  ) AS A
 ORDER BY
  xzqdm,
  xzdm,
  sl
) SELECT
 xzqdm,
 xzdm,
 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,1,9) xzdm,count(*) sl from sddltb_qc where xzqdm in ('130432','210604') group by xzqdm,substring(zldwdm,1,9)) as a order by xzqdm,xzdm,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

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: