2017-04-27 34 views
0

我想找出具有空值的特定字段的記錄百分比。在這種情況下,我有2個表; 'Requirements'和'Deliverables',這兩個表都有一個'Completion_Date'列。我想統計'Completion_Date'有多少個需求有一個空值,以及'Completion_Date'有多少個可交付物有一個空值。我已經完成了內連接和左連接以獲取需求和交付物的總量,但是我的計數沒有顯示正確數量的空字段。MySQL計數與內部連接的空值

我的當前查詢:

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

任何幫助,將不勝感激謝謝

+0

嘗試做一個'SELECT del.Completion_Date FROM requirements req inner join ...'查看哪些行/值被計算。 – Solarflare

回答

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 

注意嘗試,在此查詢我假設在deliverables表中的列deliverableID的存在。您可能必須將其替換爲右欄。