Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple counts in one SQL query with grouping

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)
like image 753
Daqqaq Avatar asked Jun 19 '26 09:06

Daqqaq


2 Answers

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)
like image 135
Aleksandr Fedorenko Avatar answered Jun 21 '26 01:06

Aleksandr Fedorenko


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)
like image 23
4b0 Avatar answered Jun 20 '26 23:06

4b0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!