3

我想运行一个查询来获得按年和月分组的打开事件和已关闭事件的计数,下面的查询在没有分组的情况下工作正常,但是一旦我添加了组,它就不起作用了!

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

3 回答 3

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)
于 2013-06-16T08:04:15.863 回答
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)
于 2013-06-16T06:41:23.257 回答
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)
于 2013-06-17T04:29:22.633 回答