sql - Maximum difference between MORE than two dates in SQL?
问题描述
Can someone help me with this? It is to perform a query in SQL on a REDSHIFT database. The table has the data loaded as follows. A client, for example, has a date field that determines her activity in an application:
ID | DATE |
---|---|
customer_1 | 2019-01-18 |
customer_1 | 2019-08-25 |
customer_1 | 2020-02-25 |
customer_1 | 2020-06-18 |
customer_2 | 2019-08-21 |
customer_2 | 2020-02-13 |
customer_2 | 2020-06-30 |
customer_3 | 2020-01-18 |
customer_3 | 2020-04-04 |
I need to group by client and know their MAXIMUM period of inactivity. I call MAXIMUM inactivity the longest period between TWO dates in which it did not interact. To do this with SQL, you should go through all the dates of the same user (customer_x) which is PK. I do not know if you can help me think about it since I have not been able to do it alone. Thanks.
ID | Maximum inactivity (in days) |
---|---|
customer_1 | 94 |
customer_2 | 60 |
customer_3 | 45 |
解决方案
你可以用LAG()
这个。
例如:
select
id,
max(inactivity) as max_inactivity
from (
select
id,
datediff(day, lag(date) over(partition by id order by date), date)
as inactivity
from t
) x
group by id
推荐阅读
- database - SQL Reporting Services - Visual Studio 中的共享数据源
- python - PySpark 多线程读取 Py4JNetworkError:Java 端的答案为空
- java - onDataChange 与 Firebase 崩溃
- mysql - 虚构(自制)组中的 MYSQL OrderBy
- python - 元组到python中的dict
- python - 为什么 Pandas 和 Seaborn 为相同的数据生成不同的 KDE Plot?
- amazon-web-services - AWS API Gateway - 自定义域 - 由于并发修改无法完成操作
- php - 为什么我在 wsdl 上有这个?
- reactjs - 如何获取 REST API 正文信息(JSON)?
- java - Jboss eap 6.4 到 Wildfly 14/18 迁移