如何在mysql查询中获取总和?

时间:2018-09-24 06:54:40

标签: mysql sql

我现在有一个SQL查询来查找apiCount和javascriptCount我想一个计数为apiCount + javascriptCount我该怎么做请帮帮我。我尝试在Google上找到许多解决方案,但我无法完全解决我的问题

SELECT  display , 
  SUM(CASE WHEN category = 2 AND (statusCode != -1 AND statusCode != 400  AND statusCode != 401) THEN 1 ELSE 0 END) apiCount, 
  SUM(CASE WHEN category = 1 THEN 1 ELSE 0 END) javascriptCount 
FROM error 
WHERE  `occurance` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) 
GROUP BY display

这是我的查询,我想在同一查询中对apiCount和javascriptCount求和。

5 个答案:

答案 0 :(得分:1)

使用'+'运算符将其总计 或者您可以结合两种逻辑对其进行计数

SELECT  display , 
SUM(CASE WHEN category = 2 AND (statusCode != -1 AND statusCode != 400  AND statusCode != 401) THEN 1 ELSE 0 END)+SUM(CASE WHEN category = 1 THEN 1 ELSE 0 END) 
 totalCount,occurance 
 FROM error WHERE  `occurance` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) GROUP BY display

OR

SELECT  display , 
SUM(CASE WHEN (category i=2 AND (statusCode != -1 AND statusCode != 400  AND statusCode != 401)) OR category = 1 THEN 1 ELSE 0 END)
 totalCount,occurance 
 FROM error WHERE  `occurance` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) GROUP BY display

答案 1 :(得分:1)

您可以组合两个for表达式以获取组合的总和:

CASE

答案 2 :(得分:1)

将原始查询包装在派生表中。然后,您可以计算apiCount + javascriptCount:

function checkForChange(that) {
  if (that.value == "missing_person_report") {
  console.log(that.value);
  console.log('person');
  document.getElementById("missing_person_report_row").style.display = "block";              
}
}

答案 3 :(得分:0)

在mysql中,最简单的方法是可以使用条件SUM,条件成立时添加一个,否则不添加。

您可以尝试一下。

SELECT display, 
       SUM(category = 2 AND (statusCode != -1 AND statusCode != 400  AND statusCode != 401)) apiCount, 
       SUM(category = 1 ) javascriptCount,
       SUM((category = 2 AND (statusCode != -1 AND statusCode != 400  AND statusCode != 401)) OR category = 1) totalCount,
       occurance 
FROM error 
WHERE  `occurance` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) 
GROUP BY display

答案 4 :(得分:0)

嗨,请尝试以下查询。

SELECT  display , 
  SUM(CASE WHEN 
   (category = 2 AND (statusCode != -1 AND statusCode != 400  AND statusCode != 401)) -- apiCount
   OR (category = 1) -- javascriptCount
    THEN 1 ELSE 0 END) apiCount_and_javascriptCount,
  occurance 
 FROM error 
  WHERE  `occurance` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) GROUP BY display