3

I want to run a query to get a count of open incident and closed incidents grouped by year and month, the below query works fine without the grouping, but once I add the group it will not work!

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)

3 Answers 3

3

You can use single a SELECT statement with CASE expression

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)
Sign up to request clarification or add additional context in comments.

Comments

1

Try:

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)

1 Comment

Shree, the query above did not worked. I got this error (Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'as'.)
0

I have managed to solve it, below is the query

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)

1 Comment

You can probably omit the else null bit. I think most SQL products allow that, defaulting the missing ELSE clause to ELSE NULL. However, isn't this essentially same as @Alexander Fedorenko's answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.