3

我已经花了几个小时来解决这个问题,但我无法让计数起作用。希望有人能帮忙?!

我有一个项目表和任务表,链接在 project_id 上。我可以通过以下查询获取 project_id、project_name 和 status_id:

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

我想为每个项目选择一条记录,并根据 status_id 添加两个计数字段。在伪代码中:

SELECT 
    a.project_id, 
    a.project_name,
    (SELECT COUNT(*) FROM task_list WHERE status_id < 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

我的创建表脚本如下:

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`)
)

任何帮助深表感谢。谢谢!

编辑: 答案:

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
4

1 回答 1

4

问题在于,在您的子查询中,您正在计算整个表中的所有行,而不仅仅是具有正确project_id. 您可以通过修改WHERE每个子查询中的子句来解决此问题。

(SELECT COUNT(*)
 FROM task_list AS c
 WHERE c.status_id < 3
 AND a.project_id = c.project_id)

然而,更简单的方法是使用SUM布尔条件而不是COUNT计算匹配条件的行:

SELECT 
    a.project_id, 
    a.project_name,
    SUM(b.status_id < 3) AS not_completed,
    SUM(b.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

这是有效的,因为TRUE评估为1FALSE评估为0

于 2012-11-24T18:27:54.140 回答