在每个窗口中查找最新记录 - MariaDB/MySQL
Posted
技术标签:
【中文标题】在每个窗口中查找最新记录 - MariaDB/MySQL【英文标题】:Finding the latest record in each window - MariaDB/MySQL 【发布时间】:2022-01-24 04:05:48 【问题描述】:在 MariaDb 10.3 中,如何为每个窗口(或分区,我对这里的术语不太清楚)找到最新的(基于时间戳)行?
考虑下表的数据
ItemID | Itemname | Value | Timestamp |
---|---|---|---|
1 | A | 22 | 2021-12-22 20:01:00 |
1 | A | 2 | 2021-12-22 15:09:44 |
1 | A | 3 | 2021-12-22 14:39:49 |
2 | B | 54 | 2021-12-22 12:46:37 |
2 | B | 23 | 2021-12-22 12:17:52 |
2 | B | 43 | 2021-12-22 11:19:11 |
1 | A | 23 | 2021-12-22 04:00:58 |
1 | A | 53 | 2021-12-22 03:00:58 |
3 | C | 21 | 2021-12-21 04:00:58 |
2 | B | 74 | 2021-12-21 04:06:58 |
2 | B | 36 | 2021-12-21 04:06:09 |
1 | A | 34 | 2021-12-21 03:08:09 |
期望的输出
ItemID | ItemName | Value | Timestamp |
---|---|---|---|
1 | A | 22 | 2021-12-22 20:01:00 |
2 | B | 54 | 2021-12-22 12:46:37 |
1 | A | 23 | 2021-12-22 04:00:58 |
3 | C | 21 | 2021-12-21 04:00:58 |
2 | B | 74 | 2021-12-21 04:06:58 |
1 | A | 34 | 2021-12-21 03:08:09 |
【问题讨论】:
什么是“数据集”?相同的 ItemID 和 ItemName? 【参考方案1】:以下查询生成预期结果
WITH ordered AS (
SELECT
*,
LAG(`ItemID`) OVER (ORDER BY `Timestamp` DESC) AS LastItem
FROM dataset
)
SELECT `ItemID`, `ItemName`, `Value`, `Timestamp`
FROM ordered
WHERE `ItemID` <> `LastItem` OR `LastItem` IS NULL
ORDER BY `Timestamp` DESC
demo
【讨论】:
或许应该解释一下原因。 :)以上是关于在每个窗口中查找最新记录 - MariaDB/MySQL的主要内容,如果未能解决你的问题,请参考以下文章