sql - 连续几个月购买的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功能
解决方案
如果要汇总用户和年月
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<>在这里摆弄
推荐阅读
- typescript - 使用通用值修改接口键
- java - SpringBoot JPA 存储库 bean 命名策略
- python - Tensorflow Keras 损失为 NaN
- node.js - 用数据保存渲染的 PUG 的 HTML
- php - laravel 8 中如何自定义默认登录错误信息
- python - Html to Docx 不应用标题样式
- python - ModuleNotFoundError:运行 nvidia/deeplearningexamples reponstory 时没有名为“nvidia.dali.backend_impl”的模块
- asp.net-web-api - Asp.net core 3.1版本响应码400
- c++ - 没有“getline”实例与参数列表匹配
- vba - 通过 VBA 发送 Rest 请求时出现运行时错误