Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting a JOIN query with two counts from joined table
    primarykey
    data
    text
    <p>I've spent a few hours fighting with this, but I can't get the counts to work. Hopefully someone can help?!</p> <p>I have a project table and task table, linked on the project_id. I can get the project_id, project_name, and the status_id with the query below:</p> <pre><code>SELECT a.project_id, a.project_name, b.status_id FROM project_list as a INNER JOIN task_list as b ON a.project_id=b.project_id </code></pre> <p>I'd like to select a single record for each project and add two count fields based on the status_id. In pseudo code:</p> <pre><code>SELECT a.project_id, a.project_name, (SELECT COUNT(*) FROM task_list WHERE status_id &lt; 3) as not_completed, (SELECT COUNT(*) FROM task_list WHERE status_id = 3) as completed FROM project_list as a INNER JOIN task_list as b ON a.project_id=b.project_id GROUP BY project_id </code></pre> <p>My create table scripts are below:</p> <pre><code>CREATE TABLE `project_list` ( `project_id` int(11) NOT NULL AUTO_INCREMENT, `topic_id` int(11) DEFAULT NULL, `project_name` varchar(45) DEFAULT NULL, PRIMARY KEY (`project_id`) ) CREATE TABLE `task_list` ( `task_id` int(11) NOT NULL AUTO_INCREMENT, `project_id` int(11) DEFAULT NULL, `task_name` varchar(45) DEFAULT NULL, `status_id` int(11) DEFAULT '0', PRIMARY KEY (`task_id`) ) </code></pre> <p>Any help is much appreciated. Thanks!</p> <p>EDIT: ANSWER:</p> <pre><code>SELECT a.project_id, project_name, SUM(status_id != 3) AS not_completed, SUM(status_id = 3) AS completed, SUM(status_id IS NOT NULL) as total FROM tasks.project_list as a INNER JOIN tasks.task_list as b ON a.project_id=b.project_id GROUP BY a.project_id </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload