Spec
Spec

Reputation: 329

How to list groups and counts of uncompleted tasks?

I have two db tables:

tasks:
task_id (unique id, autoincrement)
group_id (from the next table: groups, where task belongs to)
task_name
status (if task has been completed or not)

groups:
group_id (unique id, autoincrement)
group_name

My goal is to list all groups along with number of uncompleted tasks in them (task status 0). I achieve that by this query:

$sql_query = "SELECT g.id, g.name, count(g.id) as count
FROM task_groups g, tasks t
WHERE g.status = 0 AND t.group =  g.id AND t.status = 0
GROUP BY g.id
ORDER BY g.id ASC";

And I get results like this:

Group1  3 uncompleted
Group2 13 uncompleted
Group3 30 uncompleted

But empty task groups (there are no any tasks that belong to a specific group) are not being listed.

Result should be like this:

Group1  3 uncompleted
Group2 13 uncompleted
Group3 30 uncompleted
Group4  0 uncompleted
Group5  0 uncompleted

How can I achieve that?

Upvotes: 1

Views: 109

Answers (1)

JYelton
JYelton

Reputation: 36522

You're on the right track. GROUP BY the group, but instead of counting the group id, try instead doing a SUM on tasks that are incomplete, like this:

SELECT g.id, g.name,
SUM(IF(t.status = 0, 1, 0)) incomplete_tasks
FROM task_groups g
LEFT JOIN tasks t ON (t.group_id = g.id)
GROUP BY g.id ASC
HAVING incomplete_tasks > 0;

Omit the HAVING clause if you want to list all task groups.

Note: I didn't see the purpose of g.status in your query, and status wasn't listed as a column in the groups table so I've left it out of my example.

Upvotes: 2

Related Questions