根据时间检索每个组的最新值
问题:
考虑以下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中文网其他相关文章!