【问题标题】:Prior six months of data per unique user from an imputed date - PostgreSQL从估算日期开始每个唯一用户的前六个月数据 - PostgreSQL
【发布时间】:2021-05-19 17:03:57
【问题描述】:

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

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

因此,如果用户 1 的标志(索引日期)出现在 2020 年 7 月 1 日 - 我希望他们的历史记录在 2020 年 7 月 1 日之前 6 个月(所以一直到 2020 年 1 月 1 日)以及他们数据中存在的任何内容那个时间范围。

示例数据表:

User Date Flag (Index Date)
User 1 10-01-2019 0
User 1 12-15-2019 0
User 1 12-21-20219 0
User 1 03-01-2020 0
User 1 05-15-2020 0
User 1 07-01-2020 1
User 1 07-15-2020 0
User 1 08-01-2020 0

示例输出:

User Date Flag (Index Date)
User 1 03-01-2020 NULL
User 1 05-15-2020 NULL
User 1 07-01-2020 1
User 2 02-24-2020 NULL
User 2 03-12-2020 NULL
User 2 04-28-2020 1

【问题讨论】:

  • 编辑问题并提供基表结构
  • 你能详细说明一下吗?我不明白。
  • 你刚刚给出了你想要的输出。为了帮助您,我们需要您的输入表结构和带有逻辑解释的示例数据。
  • 进一步修改。
  • 标志会告诉索引日期吗?

标签: postgresql


【解决方案1】:

你可以试试这个查询:

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_

DEMO

【讨论】:

    【解决方案2】:

    不用 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 个

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      相关资源
      最近更新 更多