简体   繁体   English

SQL 根据日期范围查询获取数据

[英]SQL Query to fetch data based on the date range

I have a data which has index and date I need to perform logic in which I need to compare the first date with next date if the date range is lesser than 31 remove the second, again compare the first with third if it's greater than 31 keep the first and third and compare the third with fourth if less remove or if greater add keep on like this.我有一个具有索引和日期的数据我需要执行逻辑,如果日期范围小于 31,我需要将第一个日期与下一个日期进行比较删除第二个,如果它大于 31,则再次将第一个与第三个进行比较保留第一个和第三个并将第三个与第四个进行比较,如果较少删除或较大添加,则继续这样。 Can anyone help me out on this logic谁能帮我解决这个逻辑

Simply first record should be compared with prior records with greater of 31只需将第一个记录与大于 31 的先前记录进行比较

index     DATE
1     2020-01-01
1     2020-01-15
1     2020-01-30
1     2020-02-02
1     2020-02-20
1     2020-03-05
1     2020-03-25
2     2020-04-30

Required output需要 output

index     DATE
1     2020-01-01
1     2020-02-02
1     2020-03-05
2     2020-04-30

This answers the original question which was tagged MySQL.这回答了标记为 MySQL 的原始问题。

You need to use a recursive CTE for this type of operation:对于这种类型的操作,您需要使用递归 CTE:

with recursive cte(ind, date) as (
      select ind, min(date) as date
      from t
      group by ind
      union all
      select cte.ind,
             (select min(t2.date)
              from t t2
              where t2.ind = cte.ind and t2.date > cte.date + interval 30 day
             )
      from cte
      where exists (select 1
                    from t t2
                    where t2.ind = cte.ind and t2.date > cte.date + interval 30 day
                   )
     )
select *
from cte;

Here is a db<>fiddle. 是一个 db<>fiddle。

Try this below query试试下面的查询

create table indextbl(indexid int, dt date)
insert into indextbl values(1,     '2020-01-01')
,(1,'2020-01-15')
,(1,'2020-01-30')
,(1,'2020-02-02')
,(1,'2020-02-20')
,(1,'2020-03-05')
,(1,'2020-03-25')
,(2,'2020-04-30')

select indexid, MIN(dt) from indextbl
group by indexid, LEFT(dt,7)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM