0

我有这个 Sql Query 向我显示 Project 下有多少任务,但它不显示 Projects with 0 task 的问题有人可以帮助我吗?

SELECT Projects.projectName AS [Project Name],
    COUNT(Projects_tasks.taskID) AS #tasks,
    Projects.projectID AS [Project ID]

FROM Projects

INNER JOIN Projects_tasks
ON Projects.projectID = Projects_tasks.projectID 

GROUP BY Projects.projectName,
    Projects_tasks.taskID,
    Projects.projectID
4

7 回答 7

1

采用Left Join

SELECT     Projects.projectName AS [Project Name],
                  ISNULL(COUNT(Projects_tasks.taskID),0) AS #tasks, Projects.projectID AS [Project ID]

FROM       Projects LEFT JOIN
                  Projects_tasks ON Projects.projectID = Projects_tasks.projectID 

GROUP BY Projects.projectName,Projects.projectID

还删除column您在group by

于 2012-08-22T14:14:03.117 回答
1

使用 LEFT 连接、ISNULL(),并且不要按您正在计算的列进行分组。

SELECT     Projects.projectName AS [Project Name],
                  ISNULL(COUNT(Projects_tasks.taskID), 0) AS #tasks, Projects.projectID AS [Project ID]

FROM       Projects LEFT JOIN
                  Projects_tasks ON Projects.projectID = Projects_tasks.projectID 

GROUP BY Projects.projectName,Projects.projectID
于 2012-08-22T14:14:37.853 回答
0

您应该使用 LEFT JOIN 来确保包含 0 个任务的项目也包括在内

SELECT     Projects.projectName AS [Project Name],
           ISNULL(COUNT(Projects_tasks.taskID),0) AS #tasks, Projects.projectID AS [Project ID]
FROM       Projects LEFT JOIN
                  Projects_tasks ON Projects.projectID = Projects_tasks.projectID 

GROUP BY Projects.projectName,Projects_tasks.taskID,Projects.projectID
于 2012-08-22T14:14:01.113 回答
0

尝试将 INNER JOIN 更改为 LEFT JOIN

您没有看到 0,因为没有要加入的任务。

于 2012-08-22T14:14:48.427 回答
0

使用LEFT JOIN. 并且还COALESCE可以转换null值。COALESCE必须在COUNT函数内部,因为该列Projects_tasks.taskID可以是NULL

SELECT Projects.projectName AS [Project Name],
       COUNT(COALESCE(Projects_tasks.taskID, 0)) AS #tasks,
       Projects.projectID AS [Project ID]
FROM   Projects
         LEFT JOIN Projects_tasks
            ON Projects.projectID = Projects_tasks.projectID 
GROUP BY Projects.projectName,
    Projects_tasks.taskID,
    Projects.projectID
于 2012-08-22T14:15:09.100 回答
0

我怀疑您的查询是否会返回超过 1 个任务作为任务数。Projects_tasks.taskID 不应在 group 子句中。对于您的问题,您必须使用 LEFT JOIN 而不是内部连接,它会起作用。

SELECT Projects.projectName AS [Project Name],
    sum(case when Projects_tasks.taskID is null then 0 else 1 end) AS #tasks,
    Projects.projectID AS [Project ID]

FROM Projects  

LEFT JOIN Projects_tasks
ON Projects.projectID = Projects_tasks.projectID 

GROUP BY Projects.projectName,
    Projects.projectID
于 2012-08-22T14:15:52.860 回答
0

尝试将 INNER JOIN 更改为 LEFT JOIN

SELECT     Projects.projectName AS [Project Name],
       ISNULL(COUNT(Projects_tasks.taskID),0) AS #tasks, Projects.projectID AS [Project ID]

FROM Projects LEFT JOIN Projects_tasks ON Projects.projectID = Projects_tasks.projectID

GROUP BY Projects.projectName,Projects_tasks.taskID,Projects.projectID
于 2012-08-22T14:53:16.863 回答