MySQL使用内连接计算空值

时间:2017-04-27 12:56:36

标签: mysql

我试图找出某个字段具有空值的记录百分比。在这种情况下,我有2个表; “要求”和“可交付成果”,两个表都有一列'Completion_Date'。我想计算有多少要求具有'Completion_Date'的空值加上有多少可交付物具有'Completion_Date'的空值。我已经完成了内连接和左连接以获得需求和交付项的总数,但我的计数没有显示正确的空字段数。

我当前的查询:

SELECT count(*) as countAll, count(del.Completion_Date) as countNotNull , count(*) - count(del.Completion_Date)  as countNull,
100.0 * count(del.Completion_Date) / count(*) as PercentNotNull, 100.0 * (count(*) - count(del.Completion_Date)) / count(*) as PercentNull
FROM requirements req
INNER JOIN projects pro 
    ON req.Project_ID = pro.Project_ID
INNER JOIN assigned_users u
    ON u.Project_ID=pro.Project_ID
LEFT JOIN deliverables del
    ON del.Project_ID=u.Project_ID
WHERE u.User_ID=4

当前返回10为总数(正确),6为非空(应为8)和4为空(应为2)。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

如果没有看到您的表格数据很难说,但我认为问题可能是多个用户可以分配到同一个项目,因此可交付成果的总数可以成倍增加。

我会尝试这样的事情

SELECT  count(*) as countAll,
        count(distinct case when del.Completion_Date is not null then del.deliverableID end) as countNotNull,
        count(distinct case when del.Completion_Date is null then del.deliverableID end) as countNull,
        100.0 * count(distinct case when del.Completion_Date is not null then del.deliverableID end) / count(*) as PercentNotNull,
        100.0 * count(distinct case when del.Completion_Date is null then del.deliverableID end) / count(*) as PercentNull
FROM    projects pro
JOIN    requirements req 
ON      req.Project_ID = pro.Project_ID
JOIN    assigned_users u
ON      u.Project_ID=pro.Project_ID
LEFT JOIN
        deliverables del
ON      del.Project_ID=u.Project_ID
WHERE   u.User_ID = 4

请注意,在此查询中,我假设deliverableID表中存在deliverables列。您可能必须使用正确的列替换它。