需要按非数字条件和GROUP BY汇总所有行

时间:2014-05-29 17:01:08

标签: mysql sql group-by sum

我有一个表格,其中包含我需要测试的条件,并由一个组合计,然后获得等于一个值的组的总数。

示例:

  • 第1组总条件= 1
  • 第2组总条件= 14
  • 第3组总条件= 5
  • 第4组总条件= 1

我需要计算每组的总数,然后得到总数= 1

的组

这是我用来完成基本组总计的基本代码。 (我正在使用SUM(IF(条件=真,1,0))来构建一个可以用作子查询的查询):

SELECT SUM(IF(`Condition` <> '' AND `Condition` IS NOT NULL,1,0)) AS TotalErrors 
FROM Site_Analytics 
GROUP BY FourID;

当然这与:

相同
SELECT COUNT(*) AS TotalErrors 
FROM Site_Analytics 
GROUP BY FourID 
WHERE `Condition` <> '' AND `Condition` IS NOT NULL;

返回具有组总计的每个GROUP的行。然后我需要通过GROUP TOTAL对GROUP组进行分组。

无论哪种方式,我都需要获得= 1(或2,3,4等)的GROUPS(FourID)数量

我正在寻找的最终结果是生成一个包含多个组的报告:= 1,2,3,4,5,5 +

我已尝试将上述查询用作子查询,但没有成功,例如:

SELECT 
SUM((SELECT SUM(IF(`Condition` <> '' AND `Condition` IS NOT NULL,1,0)) FROM Site_Analytics GROUP BY FourID) AS `SitesWith1Error`
FROM SiteLog_Master;

这是我用于获取类似报告的其他总计的查询:

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;

1 个答案:

答案 0 :(得分:0)

这就是我想出的。我将子查询移动到FROM子句,而不是尝试在SELECT子句中全部执行:

SELECT SUM(t.TotalErrors) FROM (SELECT SUM(IF(`Condition` <> '' AND `Condition` IS NOT NULL,1,0)) AS TotalErrors FROM Site_A nalytics GROUP BY FourID HAVING TotalErrors = 1) t;

子查询返回45行,然后SELECT子句中的SUM将其加总为单行。

对此,我将添加我需要的剩余突破。我可能会在select子句SUM中执行IF()并从FROM子句中删除HAVING,这样我就可以创建其他总计的总数:

    SELECT 
    SUM(IF(t.TotalErrors = 1,1,0)) AS Group1, 
    SUM(IF(t.TotalErrors = 2,1,0)) AS Group2, 
    SUM(IF(t.TotalErrors = 3,1,0)) AS Group3, 
    SUM(IF(t.TotalErrors = 4,1,0)) AS Group4, 
    SUM(IF(t.TotalErrors >= 5,1,0)) AS Group5  
    FROM (SELECT SUM(IF(`Condition` <> '' AND `Condition` IS NOT NULL,1,0)) 
AS TotalErrors FROM Site_Analytics GROUP BY FourID) t;

返回:

组1 45
第2组76
Group3 90
Group4 57
Group5 + 360