如何根据创建日期获取上一条和下一条记录,并在单个查询中按另一列分组?
How to get the previous and next record based on creation date and group by another column in a single query?
举个例子,我有一个类似于下面的 table,
+----+--------------+------------+-------+
| 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 |
+----+--------------+------------+-------+
有没有一种方法可以在单个查询中根据 810
等特定标记获取 2010-08-23
等特定日期前后的 date_col
数据。
这样我就可以得到 2010-08-02
和 2010-09-03
,即 Record 9
和 Record 2
作为结果。
您可以使用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()
和 window 帧:
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);
举个例子,我有一个类似于下面的 table,
+----+--------------+------------+-------+
| 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 |
+----+--------------+------------+-------+
有没有一种方法可以在单个查询中根据 810
等特定标记获取 2010-08-23
等特定日期前后的 date_col
数据。
这样我就可以得到 2010-08-02
和 2010-09-03
,即 Record 9
和 Record 2
作为结果。
您可以使用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()
和 window 帧:
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);