I have a table like the following one:
id user_id task task_closed
1 1 1 0
2 1 2 1
3 1 3 0
4 2 3 0
5 2 4 1
6 3 4 0
What I need is a query that for a given task will return all the uses that have this task and for each of them the number of overall un-closed tasks they have.
so that if we are talking about task 3 I want to get
user_id pending
1 2
2 1
as in
SELECT tasks.user_id,
( SELECT COUNT(*)
FROM tasks t2
WHERE t2.user_id=tasks.user_id AND t2.task_closed=0
)
FROM tasks
WHERE tasks.id=?
I would also re-write this as
SELECT user_id,COUNT(*)
FROM tasks
WHERE task=? AND task_closed=0
GROUP_BY user_id
WHERE user_id IN (SELECT t2.user_id from tasks t2 WHERE task=?);
But I have a strong feeling that there should be a more efficient way to do this by somehow joining the table with itself.
any ideas on how I should do that ?