如何在sql中基于两个日期提取数据

cbwuti44  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(424)

只需要显示在上一个请求id过期后创建的记录。
https://i.stack.imgur.com/jum97.png
Jmeter 板-

REQUEST_ID  CREATED_DATE    EXPIRY_DATE
1           2020-06-02      2020-06-06  
2           2020-06-04      2020-06-10  
3           2020-06-08      2020-06-12  
4           2020-06-09      2020-06-16  
5           2020-06-09      2020-06-15              
6           2020-06-18      2020-06-20              
7           2020-06-21      2020-06-25

o/p-

REQUEST_ID  CREATED_DATE    EXPIRY_DATE
    1       2020-06-02      2020-06-06
    3       2020-06-08      2020-06-12
    6       2020-06-18      2020-06-20
    7       2020-06-21      2020-06-25
q8l4jmvw

q8l4jmvw1#

如果您运行的是mysql 8.0,则可以使用窗口函数:

select request, created_at, expiry_date
from (
    select 
        t.*,
        lag(expiry_date) over(order by request) lag_expiry_date
    from mytable t
) t
where lag_expiry_date is date or created_at > lag_expiry_date

另一方面,如果您想根据与上一个有效记录的差异以增量方式选择记录,那么就要复杂一些。您需要某种迭代过程,它建议使用递归查询。基本上,您可以用 row_number() ,然后逐一处理,决定保留哪一个。

with recursive 
    data as (
        select t.*, row_number() over(order by created_date) rn from mytable t
    ),
    cte as (
        select d.*, 1 to_keep, expiry_date last_expiry_date 
        from data d 
        where rn = 1 
        union all
        select 
            d.*,
            (d.created_date > c.last_expiry_date),
            case when d.created_date > c.last_expiry_date 
                then d.expiry_date 
                else c.last_expiry_date
            end
        from cte c
        inner join data d on d.rn = c.rn + 1
    )
select request_id, created_date, expiry_date 
from cte 
where to_keep
order by rn

db小提琴演示:

| request_id | created_date | expiry_date |
| ---------- | ------------ | ----------- |
| 1          | 2020-06-02   | 2020-06-06  |
| 3          | 2020-06-08   | 2020-06-12  |
| 6          | 2020-06-18   | 2020-06-20  |
| 7          | 2020-06-21   | 2020-06-25  |

相关问题