I was trying to figure out how to approach to the following:
I have table registrations
:
+---------+---------------------+
| user_id | reg_date |
+---------+---------------------+
| a | 2018-11-01 20:47:46 |
| b | 2018-11-02 21:07:15 |
| c | 2018-11-03 05:24:31 |
+---------+---------------------+
And table with logins
:
+---------+---------------------+
| user_id | login_date |
+---------+---------------------+
| a | 2018-11-01 21:30:46 |
| a | 2018-11-01 21:35:15 |
| a | 2018-11-01 22:22:22 |
| ... | |
+---------+---------------------+
So I need to get users who logged at least once during the day after registration (between 24 and 48 hours after registration) and display user_id
, register_date
and the highest value for the login on the second day.
I ended up with following solution:
WITH a
AS (SELECT registrations.user_id,
registrations.reg_date,
logins.login_date,
Row_number()
OVER(
partition BY registrations.user_id
ORDER BY logins.login_date DESC) row_num
FROM registrations
INNER JOIN logins
ON registrations.user_id = logins.user_id
WHERE logins.login_date BETWEEN Hours_add(registrations.reg_date, 24)
AND
Hours_add(registrations.reg_date, 48))
SELECT *
FROM a
WHERE row_num = 1
But I am not sure about my solution, though it looks fine. Could you please check it and suggest easier way to calculate this?
This should work
SELECT r.user_id,
r.reg_date,
Max(l.login_date),
Count(l.login_date)
FROM registrations r,
logins l
WHERE r.user_id = l.user_id
AND l.login_date BETWEEN ( r.reg_date + interval '1' day ) AND (
r.reg_date + interval '2' day )
group by l.login_date
having Count(l.login_date)>=1
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.