I have a table that contains a condition that I need to test for and total it by a group then get the total of the number of groups that equal a value.
Example:
- Group 1 total of conditions = 1
- Group 2 total of conditions = 14
- Group 3 total of conditions = 5
- Group 4 total of conditions = 1
etc.
I need to calculate the total of each group then get the total groups that = 1
This is the base code that I have come up with to do the basic group totals. (I'm am using a SUM(IF(condition = true,1,0)) in an effort to build a query that can then be used as a subquery):
SELECT SUM(IF(`Condition` <> '' AND `Condition` IS NOT NULL,1,0)) AS TotalErrors
FROM Site_Analytics
GROUP BY FourID;
of course this is the same as:
SELECT COUNT(*) AS TotalErrors
FROM Site_Analytics
GROUP BY FourID
WHERE `Condition` <> '' AND `Condition` IS NOT NULL;
Returns a row for each GROUP with the group total. I then need to GROUP the GROUPS by GROUP TOTAL.
Either way I then need to get the number of GROUPS (FourID) that = 1 (or 2,3,4 etc)
The end result I'm looking for is to generate a report that has number of groups that = 1, 2,3,4,5,5+
I have tried using the above queries as sub-queries but with no success such as:
SELECT
SUM((SELECT SUM(IF(`Condition` <> '' AND `Condition` IS NOT NULL,1,0)) FROM Site_Analytics GROUP BY FourID) AS `SitesWith1Error`
FROM SiteLog_Master;
This is a query I used for getting other totals for a similar report:
SELECT
(SELECT COUNT(`FourID`) FROM SiteLog_Master) AS `TotalSites`,
(SELECT COUNT(`Condition`) FROM Site_Analytics WHERE (`Condition` <> '' AND `Condition` IS NOT NULL)) AS `TotalFieldsWithErrors`,
(SELECT COUNT(DISTINCT m.FourID) FROM SiteLog_Master m LEFT JOIN Site_Analytics USING (FourID) WHERE (`Condition` IS NULL OR `Condition` <> '')) AS `TotalSitesWithErrors`,
(SELECT COUNT(`Condition`) FROM Site_Analytics WHERE `Condition` LIKE '%Required%') AS `TotalMissingRequiredFields`,
(SELECT COUNT(DISTINCT `Condition`) FROM Site_Analytics WHERE (`Condition` <> '' AND `Condition` IS NOT NULL)) AS `TotalUniqueTypesOfErrors`
FROM SiteLog_Master LIMIT 1;