簡體   English   中英

DISTINCT ON,但獲得第二行,而不是第一行

[英]DISTINCT ON, but get the second row, not the first

我正在使用 PostgreSQL。
我想為每個唯一 ID 選擇 1 行,我有這個查詢:

SELECT DISTINCT ON (station_id) *
FROM readings
ORDER BY station_id,reading_id DESC;

我有 2 張桌子:

readings (我希望內容不重要):

station_id  reading_id    temp   air_pressure
--------------------------------------------
  147          100         10       800
  148          101         20       850
  149          102         30       900
  148          103         40       950
  148          104         50       1000
  147          105         60       1050

stations (我希望內容不重要):

id   station_name   lat   lng
-----------------------------
147      
148     
149    

所以站內的readings.station_idstation.id應該是一樣的。

我的查詢有效,但現在我想選擇第二個最新的(第二個最高的 id):忽略第一行(最新讀數)並選擇第二個。

基於上述樣本的期望結果:

station_id   reading_id   temp   air_pressure
----------------------------------------------
   148          103        40        950        
   147          100        10        800

我想要每個station_id (第二個最新讀數)具有第二高reading_id的行。

如果它不會選擇只有一行但不是必需的行,那就太好了。

我不確定如何實現這一目標。 我已經嘗試了很多offsetlimit等也嘗試了一些嵌套的選擇查詢......

我想使用distinct on因為我需要從每個唯一 ID 中選擇第二行。 但是,如果distinct on不可能,那沒關系。

最好的查詢很大程度上取決於未公開的信息。

假設:

  • 當前的 Postgres 14(至少從 Postgres 9.3 起都應該可以工作)
  • 大桌子(?)
  • 每個station_id有很多行(?)
  • (station_id, reading_id) (?) 上沒有重復項
  • 一個stations表,每個車站 1 行 ✅
  • reading_id定義為NOT NULL (?)
SELECT r.*
FROM   station s
CROSS  JOIN LATERAL (
   SELECT *
   FROM   readings r
   WHERE  r.station_id = s.station_id
   ORDER  BY reading_id DESC
   OFFSET 1
   LIMIT  1
   ) r
ORDER  BY r.station_id;  -- optional

db<> 在這里擺弄

對於少於兩行的車站,您不會獲得任何行。

這對於每個站點的多行數和readings(station_id, reading_id DESC)的索引非常有效。

關於LATERAL加入:

如果您沒有單獨的stations表,請參閱:

如果可能有重復(似乎並非如此),和/或每組只有幾行,這可能會更好:

SELECT (r).*
FROM  (
   SELECT r, dense_rank() OVER (PARTITION BY station_id
                                ORDER BY reading_id DESC) AS rnk
   FROM   readings r
   ) r
WHERE  rnk = 2;

在這里,對於具有少於兩個不同reading_id的電台,您沒有任何行。 但每個站可能不止一個並列第二位。

有關的:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM