鉴于以下数据:
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;
我是如此接近,但问题是,我已经连续几周获得双栏,其中既有已解决的问题也有未解决的问题。
我错过了什么?有更好的方法吗?
答案 0 :(得分:1)
请勿按已解决的分组 - 最后两行应该是
GROUP BY WEEKOFYEAR(NOW())-WEEKOFYEAR(BugDate)
ORDER BY WeeksOld DESC;
答案 1 :(得分: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;
请注意,这会从Resolved
中删除group by
。它会将resolved
的计算更改为使用sum()
而不是count()
。它添加了Rate
列。它改变了Unresolved
的计算。你可以把后者写成:
count(*) - sum(Resolved)