我想运行一个查询来获取按年和月分组的开放事件和已关闭事件的计数,下面的查询在没有分组的情况下工作正常,但是一旦我添加了组,它将无法工作!
SELECT (SELECT COUNT(*) AS Opened FROM Incidents) AS Total
(SELECT COUNT(*) AS Solved FROM Incidents WHERE (MONTH(Closedate)=MONTH(Opendate))) AS Solved
GROUP BY YEAR(Incidents.Opendate)
答案 0 :(得分:3)
您可以使用带有CASE表达式的单个SELECT语句
SELECT YEAR(Incidents.Opendate) AS [Year],
MONTH(Incidents.Opendate) AS [Month],
COUNT(*) AS Total,
SUM(CASE WHEN MONTH(Closedate) = MONTH(Opendate) THEN 1 ELSE 0 END) AS Solved
FROM Incidents
GROUP BY YEAR(Incidents.Opendate), MONTH(Incidents.Opendate)
答案 1 :(得分:1)
尝试:
SELECT
(SELECT COUNT(*) FROM Incidents) as Total ,
(SELECT COUNT(*) FROM Incidents WHERE (Month(Closedate)=MONTH(Opendate))) as Solved
FROM Incidents
Group by YEAR(Incidents.Opendate)
答案 2 :(得分:0)
我设法解决了它,下面是查询
select COUNT(CASE WHEN Month(Closedate)=Month(Opendate) then 1 else null end) AS closed,COUNT(*) AS Opened
from incidents
Group by Year(Opendate), Month(Opendate)
Order by Year(Opendate), Month(Opendate)