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

Time:01-27

I have a table like this:

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

I want to add one more column with previous date (not equal current date).

Desired table should looks like this:

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

Thanks for your help!

CodePudding user response:

Using a join along with the LAG function, we can try:

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;

Here is a demo in SQL Server, though the same query should run in Presto with minimal modifications needed.

  •  Tags:  
  • Related