2014-01-28 72 views
0

鑑於以下數據:MySQL的 - 組由導致重複行

CREATE TABLE Bugs 
    (`ID` int, `BugDate` DATE, `resolved` int) 
; 

INSERT INTO Bugs 
    (`ID`, `BugDate`, `Resolved`) 
VALUES 
    (1, '2014-01-01', 1), 
    (2, '2014-01-01', 0), 
    (3, '2014-01-10', 1), 
    (4, '2014-01-10', 1), 
    (5, '2014-01-31', 0), 
    (6, '2014-01-31', 0) 
; 

我需要像輸出如下:

weeks old Resolved Unresolved total Rate 
--------- -------- ---------- ----- ---- 
    1  1   1  2  50% 
    2  2   0  2 100% 
    3  0   2  0 100% 

我在看的問題的列表,我想看看每週的總數和每週解決的數量。我已經接受了,我可能需要計算前端的總體和速度列,而不是讓MySQL做它。

我曾嘗試以下,但它不是很乘車路線:

SELECT 
    WEEKOFYEAR(NOW())-WEEKOFYEAR(BugDate) as WeeksOld, 
    COUNT(Resolved) as NumberResolved, 
    (/* get the total number of issues for this time period */ 
    SELECT COUNT(Resolved) 
    FROM Bugs 
    WHERE WEEKOFYEAR(NOW())-WEEKOFYEAR(BugDate) = WeeksOld 
) - COUNT(Resolved) as Unresolved 
FROM Bugs 
GROUP BY WEEKOFYEAR(NOW())-WEEKOFYEAR(BugDate), Resolved 
ORDER BY WeeksOld DESC; 

我是如此接近,但問題是,我得到的雙列周那裏都得到解決和未解決的問題。

我錯過了什麼?有一個更好的方法嗎?

這裏是一個小提琴:http://sqlfiddle.com/#!2/eeb34/12

回答

1

你只是想有條件聚集:

SELECT WEEKOFYEAR(NOW())-WEEKOFYEAR(BugDate) as WeeksOld, 
     SUM(Resolved) as NumberResolved, 
     SUM(1 - Resolved) as Unresolved, 
     concat(format(AVG(Resolved)*100, 1), '%') as Rate 
FROM Bugs 
GROUP BY WEEKOFYEAR(NOW())-WEEKOFYEAR(BugDate) 
ORDER BY WeeksOld DESC; 

注意這將從group by中刪除Resolved。它將resolved的計算更改爲使用sum()而不是count()。它添加了Rate列。它改變了Unresolved的計算。你可以寫後者爲:

count(*) - sum(Resolved) 
+0

這是mysql的功夫天才。謝謝。沒有「總計」欄,但我可以計算出來。 – pbarney

1

通過解決不羣 - 的最後兩行應

GROUP BY WEEKOFYEAR(NOW())-WEEKOFYEAR(BugDate) 
ORDER BY WeeksOld DESC; 
+0

很好的接收。但另一個答案給了我一個更明顯的方式或實現了我的目標。謝謝。 – pbarney