我遇到了一部分查询,无法提取日期差异至少为三个月的row_numbers。所以在下面的例子中,我想提取row_number 1(总是第一个),5和6.所以在row_number 1之后row_numbers有一个date_diff> 3个月(并且在第二次提取row_number之后再次应用此条件,直到无。在SQL中是否有任何允许这样的条件的函数或方法?
table_name: users
id row_number User date
---|----------|-------|---------------------|
1 |1 | Usr1 | 2017-10-01 12:35:00 |
2 |2 | Usr1 | 2017-10-01 12:35:00 |
3 |3 | Usr1 | 2017-12-03 07:47:00 |
4 |4 | Usr1 | 2018-01-10 07:47:00 |
5 |5 | Usr1 | 2018-02-10 07:47:00 |
6 |6 | Usr1 | 2018-04-10 07:47:00 |
答案 0 :(得分:0)
您可以使用lag()
函数计算差异:
select *
from (
select id, row_number, "User", date,
date - lag(date) over (order by id) as diff
from users
) t
where diff is null -- first row
or diff > interval '3 month';
答案 1 :(得分:0)
我不确定你想将间隔比较为几个月。我认为它们通常表示为几天。
所以,我会这样说:
select u.*
from (select u.*, lag(date) over (order by id) as prev_date
from users u
) u
where prev_date is null or prev_date < date - interval '3 month';
如果or
困扰您,您可以使用lag()
中的默认值将其删除:
select u.*
from (select u.*, lag(date, 1, date - interval '100 year') over (order by id) as prev_date
from users u
) u
where prev_date < date - interval '3 month';