Postgresql: Identifying Return Visitors Based On Date - Joins Or Window Functions?
I am looking to identify return visitors to a website within a 7 day window. A data sample and attempt at solving are included below: visitor_id(integer) session_id(integer) event_
Solution 1:
First, I remove event_sequence
with a DISTINCT
(assuming that all events are on the same day), then I use the window function lead
and compare with the date of the next visit:
SELECT visitor_id,
session_id,
COALESCE(
lead(d_date) OVER w - d_date,
10
) < 7 AS revisited,
d_date
FROM (SELECT DISTINCT visitor_id,
session_id,
d_date
FROM "table"
) t
WINDOW w AS (PARTITION BY visitor_id
ORDER BY d_date
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
)
ORDER BY visitor_id, session_id;
┌────────────┬────────────┬───────────┬────────────┐
│ visitor_id │ session_id │ revisited │ d_date │
├────────────┼────────────┼───────────┼────────────┤
│ 1 │ 1 │ t │ 2017-01-01 │
│ 1 │ 2 │ f │ 2017-01-05 │
│ 1 │ 3 │ t │ 2017-01-20 │
│ 1 │ 4 │ f │ 2017-01-25 │
│ 2 │ 1 │ t │ 2017-01-02 │
│ 2 │ 2 │ f │ 2017-01-02 │
│ 2 │ 3 │ f │ 2017-01-18 │
└────────────┴────────────┴───────────┴────────────┘
(7 rows)
Post a Comment for "Postgresql: Identifying Return Visitors Based On Date - Joins Or Window Functions?"