添加具有先前日期的列(不等于当前日期)[SQL,PrestoDB]

Add column with previous date (not equal current date)[SQL, PrestoDB]

我有一个 table 这样的:

current_date user_id
2021-10-01 1
2021-10-02 1
2021-10-02 1
2021-10-09 1
2021-10-15 1
2021-10-01 2
2021-10-01 2
2021-10-04 2
2021-10-04 2
2021-10-04 2
2021-10-11 2
2021-10-11 2

我想再添加一列之前的日期(不等于当前日期)。

所需的 table 应如下所示:

current_date user_id previous_date
2021-10-01 1
2021-10-02 1 2021-10-01
2021-10-02 1 2021-10-01
2021-10-09 1 2021-10-02
2021-10-15 1 2021-10-09
2021-10-01 2
2021-10-01 2
2021-10-04 2 2021-10-01
2021-10-04 2 2021-10-01
2021-10-04 2 2021-10-01
2021-10-11 2 2021-10-04
2021-10-11 2 2021-10-04

感谢您的帮助!

结合使用 LAG 函数,我们可以尝试:

WITH cte AS (
    SELECT *, LAG(current_date) OVER
                  (PARTITION BY user_id ORDER BY current_date) previous_date
    FROM (SELECT DISTINCT current_date, user_id FROM yourTable) t
)

SELECT t1.current_date, t1.user_id, t2.previous_date
FROM yourTable t1
INNER JOIN cte t2
    ON t2.user_id = t1.user_id AND t2.current_date = t1.current_date
ORDER BY t1.user_id, t1.current_date;

这是 SQL 服务器中的一个 demo,尽管相同的查询在 Presto 中应该 运行 需要最少的修改。