查询以找到日期之间的最大差距
我有一个带有每个客户名称和日期列的表格,并想编写一个查询,以给我每个用户的间隙天数,
name date
ali 2022-01-01
ali 2022-01-04
ali 2022-01-05
ser 2022-03-01
答案应为Ali的3个,而SER的答案将为null。
这是我尝试的:
select name ,min(date) over (partition by name order by date) start_date , max(date) over (partition by name order by date) end_date from table
I have a table with the name of each customer and date columns and want to write a query to give me the number of gap days for each user,
name date
ali 2022-01-01
ali 2022-01-04
ali 2022-01-05
ser 2022-03-01
the answer should be 3 for ali and for ser will be null.
here is what I tried:
select name ,min(date) over (partition by name order by date) start_date , max(date) over (partition by name order by date) end_date from table
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实现此目的的一种方法是使用窗口函数(例如滞后,铅)来找到先前/第二天,然后使用日期函数(例如,当前和先验)使用netatediff函数找到差异。这样的东西..
One approach to achieve this is using a window function (like lag, lead) to find the prior/next day and then find the difference between the dates (current and prior, for example ) using datediff function. Something like this..
我的方法是将每个记录与最接近的日期匹配,然后找到最大差距,然后与原始表格一起使用,以获取每个用户的差距。
这是MySQL版本:
my approach is to match every record with the closest date then find the maximum gap and left join with the original table to get the gap for each user.
here's MySQL version: