如何根据创建日期获取上一条和下一条记录,并在单个查询中按另一列分组?

问题描述 投票:-1回答:1

以示例为例,我有一个与以下表格相似的表格,

+----+--------------+------------+-------+
| id | date_col     | label      | tag   |
+----+--------------+------------+-------+
| 1  | 2010-09-07   | Record 1   | 810   |
| 2  | 2010-09-03   | Record 2   | 810   |
| 3  | 2010-08-23   | Record 3   | 811   |
| 4  | 2010-08-23   | Record 4   | 809   |
| 5  | 2010-08-23   | Record 5   | 810   |
| 6  | 2010-08-12   | Record 6   | 809   |
| 7  | 2010-08-06   | Record 7   | 811   |
| 8  | 2010-08-06   | Record 8   | 809   |
| 9  | 2010-08-02   | Record 9   | 810   |
| 10 | 2010-08-01   | Record 10  | 811   |
+----+--------------+------------+-------+

[是否有一种方法,可以在单个查询中根据像date_col这样的特定标签来获取2010-08-23这个特定日期之前和之后的810数据。

因此我可以得到2010-08-022010-09-03,即得到Record 9Record 2

mysql sql max aggregate min
1个回答
0
投票

您可以使用lag() / lead()

select t.*
from (select t.*, 
             lag(date_col) over (partition by tag order by date) as prev_date,
             lead(date_col) over (partition by tag order by date) as next_date
      from t
      where tag = 810
     ) t
where '2010-08-23' in (prev_date, next_date);

您在同一日期没有重复标签的示例,因此我认为这是不可能的。如果可能的话,您需要稍微复杂一点的解决方案。

要处理重复的标签,可以对窗口框架使用累积的max() / min()

select t.*
from (select t.*, 
             max(date_col) over (partition by tag order by date rows between unbounded preceding and interval 1 day preceding) as prev_date,
             min(date_col) over (partition by tag order by date rows between interval 1 following and unbounded following) as next_date
      from t
      where tag = 810
     ) t
where '2010-08-23' in (prev_date, next_date);
© www.soinside.com 2019 - 2024. All rights reserved.