You could group by
user_id, and then add a having
clause to include only users with count(distinct bag_id) >= 3
.
Then limit
that to 3, and order by
to get the latest date max(created_at)
Does that help?
Implementation would look something like this:
select
user.id,
max(history.created_at) as third_bag_received_at
from
(
select
user.id,
max(history.created_at)
from
users
inner join bags
on user.id = bags.user_id
inner join history
on bags.id = history.bag_id
where history.state = 'processed'
group by
user.id
having
count(history.bag_id >= 3)
limit 3
order by 2 -- does this work in mySql? (It means "column 2" in MS SQL)
)
Limit 1
EDIT: How to address join/aggregation to other tables in a computed column:
Rather than adding this as a calculated column, I would probably create a view with whatever info you needed for this requirement, including the third_bag_received
column based on this query.
But if you really did need to implement this as a calculated column on your table:
I'd recommend creating a user function that accepts your user.id
as an input, and returns the value of third_bag_received_at
(again, based on the logic of the above query).
Then call this function from your calculated column. Refer to @user10635's answer on this SO question.