# 获取一段时间后返回的用户

**URL:** <https://meta.discourse.org/t/get-users-who-returned-after-a-period-of-time/225137>\
**Category:** Data & reporting\
**Tags:** sql-query\
**Created:** [2022 年4 月 24 日 07:41 UTC](https://meta.discourse.org/t/get-users-who-returned-after-a-period-of-time/225137 "2022-04-24T07:41:38Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

作者： ![simon](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/simon/32/339122_2.png) [@simon](https://meta.discourse.org/u/simon)\
发布日期： [2022 年5 月 3 日 22:51 UTC](https://meta.discourse.org/t/get-users-who-returned-after-a-period-of-time/225137/6 "2022-05-03T22:51:54Z")

</div>

> [@Senpai](#):
>
> Is it possible to check if someone came back to the forum after an interval of time since their last visit?

您需要的信息在 `user_visits` 表中。对我来说棘手的部分是从每个访问条目中减去上一次访问的值。这似乎需要一个[窗口函数](https://www.postgresql.org/docs/current/functions-window.html)。根据 StackExchange 上[这个问题](https://dba.stackexchange.com/questions/300023/postgresql-subtract-to-each-row-the-previous-row)的回复，`LEAD` 函数似乎可以解决这个问题。

试试这个查询，看看它是否返回了您需要的数据。它默认返回两次访问之间间隔超过 180 天的所有用户访问。可以通过设置查询的 `days_away` 参数来调整该值。

```sql
--[params]
-- integer :days_away = 180
WITH days_between_visits AS (
SELECT
user_id,
visited_at,
LEAD(visited_at) OVER (PARTITION BY user_id ORDER BY visited_at DESC) AS previous_visit,
visited_at - LEAD(visited_at) OVER (PARTITION BY user_id ORDER BY visited_at DESC) AS time_away
FROM user_visits
)

SELECT * FROM days_between_visits WHERE time_away >= :days_away
ORDER BY visited_at DESC

```

如果您发现返回的数据有任何问题，请告诉我。

---

_[View the full topic](https://meta.discourse.org/t/get-users-who-returned-after-a-period-of-time/225137)._
