以示例为例,我有一个与以下表格相似的表格,
+----+--------------+------------+-------+
| 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-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()
:
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);