首页 > 解决方案 > 连续几个月购买的id用户如何退货?

问题描述

如何从下面的数据中获取所有值,从列中的给定开始日期开始,连续几个月user_id包含相同user_id值的所有行。date

例如,给定下表....

日期 用户身份
2018-11-01 13
2018-11-01 13
2018-11-01 14
2018-11-01 15
2018-12-01 13
2019-01-01 13
2019-01-01 14

...假设我想user_id在(但不包括)之前连续几个月获取值,2019-01-01那么我会将其作为我的输出:

用户身份 我的耳朵
13 2018-11
13 2018-12
13 2019-01

大概可以应用windows功能

标签: sqlpostgresql

解决方案


如果要汇总用户和年月

select 
 t.user_id, 
 to_char(date_trunc('month',t.date),'YYYY-MM') as m_year
from yourtable t
where t.date < '2019-02-01'::date
group by t.user_id, date_trunc('month',t.date)
order by t.user_id, m_year

但是如果你只想要那些连续几个月的,那么需要一点额外的。

select 
 user_id, 
 to_char(ym,'YYYY-MM') as m_year
from
(
  select t.user_id
  , date_trunc('month',t.date) as ym
  , lag(date_trunc('month',t.date)) 
   over (partition by t.user_id order by date_trunc('month',t.date)) as prev_ym
  , lead(date_trunc('month',t.date)) 
   over (partition by t.user_id order by date_trunc('month',t.date)) as next_ym
  from yourtable t
  where t.date < '2019-02-01'::date
  group by t.user_id, date_trunc('month',t.date)
) q
where (ym - prev_ym <= '31 days'::interval or 
       next_ym - ym <= '31 days'::interval)
order by user_id, ym
用户 ID | 我的耳朵
------: | :------
     13 | 2018-11
     13 | 2018-12
     13 | 2019-01

db<>在这里摆弄


推荐阅读