I am trying to query few users from a table joined to a bookings table but there are conditions to satisfy and I don't know how to get the expected results.
Conditions
- Return unique users
- Only if lasts 3 completed bookings are eq to
notified is null
Tables
Users
id | name
---+-----
1 | Jonh
2 | Jim
3 | Jen
Bookings
id | user_id | state | notified
---+---------+-------------+----------------------
12 | 1 | 'completed' | NULL
11 | 2 | 'completed' | NULL
10 | 3 | 'completed' | '2018-01-01 00:00:00'
9 | 1 | 'completed' | '2018-01-01 00:00:00'
8 | 2 | 'completed' | NULL
7 | 3 | 'completed' | NULL
6 | 1 | 'completed' | '2018-01-01 00:00:00'
5 | 2 | 'completed' | NULL
4 | 3 | 'completed' | NULL
3 | 1 | 'completed' | '2018-01-01 00:00:00'
2 | 2 | 'completed' | '2018-01-01 00:00:00'
1 | 3 | 'completed' | NULL
Query a have so far
SELECT users.id, bookings.id, bookings.notified
FROM users
JOIN bookings ON users.id = bookings.user_id
WHERE bookings.state = 'completed'
GROUP BY users.id, bookings.id, bookings.notified
HAVING (bookings.notified IS NULL)
ORDER BY bookings.id DESC;
Expected
user_id
-------
2
notified = nullORDER BY bookings.notified DESC. By being NULL, they can never be among the last.