依時間擷取每組的最新值
問題:
考慮以下Oracle表:
<code>id date quantity 1 2010-01-04 11:00 152 2 2010-01-04 11:00 210 1 2010-01-04 10:45 132 2 2010-01-04 10:45 318 4 2010-01-04 10:45 122 1 2010-01-04 10:30 1 3 2010-01-04 10:30 214 2 2010-01-04 10:30 5515 4 2010-01-04 10:30 210</code>
目標是按id組檢索最新的值(及其時間戳記)。預期輸出應為:
<code>id date quantity 1 2010-01-04 11:00 152 2 2010-01-04 11:00 210 3 2010-01-04 10:30 214 4 2010-01-04 10:45 122</code>
解:
為此,建立一個內聯視圖,根據降序時間戳對id組中的每一行進行排名:
<code class="language-sql">SELECT RANK() OVER (PARTITION BY id ORDER BY ts DESC) AS rnk, id, ts, qty FROM qtys</code>
然後過濾排名為1的記錄以取得最新值:
<code class="language-sql">SELECT x.id, x.ts AS "DATE", x.qty AS "QUANTITY" FROM (SELECT * FROM qtys) x WHERE x.rnk = 1</code>
進階選項:
<code class="language-sql">WHERE x.ts >= sysdate - INTERVAL 'XX' MINUTE</code>
<code class="language-sql">SELECT x.id || '-' || y.idname AS "ID", x.ts AS "DATE", x.qty AS "QUANTITY" FROM (SELECT * FROM qtys) x LEFT JOIN another_table y ON x.id = y.id</code>
以上是Oracle中如何根據時間戳記檢索每個群組的最新值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!