从估算日期到每个唯一用户的前六个月数据-PostgreSQL



我希望根据另一个日期(由标志表示,并将被称为索引日期(获得数据集中唯一用户的最后六(6(个月的数据。

";索引日期";本质上是在数据中捕获的标志。作为标志的1存在,0表示不存在。

因此,如果用户1在2020年7月1日显示了一个标志(索引日期(,我希望他们的历史记录在2020年1月1日之前6个月(一直到2020年1日(,以及他们在该时间段内的数据中显示的内容。

示例数据表:

<1>
用户 日期 标志(索引日期(
用户1 10-01-2019 0
用户1 12-15-2019 0
用户1 12-21-20219 0
用户1 03-01-2020 0
用户1 2020年5月15日 0
用户1 07-01-2020
用户1 07-15-2020 0
用户1 08-01-2020 0

您可以尝试以下查询:

with cte as 
(select user_,date_ from test where flag=1
)
select 
t.*,
case when t.flag=1 then t.date_ end "Flag (Index Date)"
from test t 
inner join cte on t.user_=cte.user_ 
where t.date_ between cte.date_ - interval '6 month' and cte.date_
order by user_,date_

演示

您也可以在没有cte的情况下完成:

select  *
from  test t1
where exists (
select 1 from test t2
where t2.flag = 1
and t1.user = t2.user
and t1.date between t2.date - interval '6 month' and t2.date
)
order by  user, date

假设您的数据中每个用户只有一个标志=1