计算SQL查询中的计数并在同一查询中比较它们

时间:2018-06-05 17:32:06

标签: sql count

我想获取具有特定条件的行数,然后比较同一查询中的计数。我怎么能这样做?

我需要获取启动列正常且测试列失败的设备列表。我不知道如何通过整个表循环来完成这些计数比较。

SELECT type,device,
 (SELECT (COUNT(*) WHERE Started = "OK" from table1) AS t1, 
 (SELECT (COUNT(*) WHERE tested = "FAILED" from table1) AS t1
 from table1
      where remediated = "Remediated"
      GROUP BY type,device
      HAVING (SELECT (COUNT(*) WHERE Started = "OK" from table1) = (SELECT (COUNT(*) WHERE tested = "FAILED" from table1)

1 个答案:

答案 0 :(得分:1)

使用条件聚合:

SELECT type, device,
       SUM(CASE WHEN Started = 'OK' THEN 1 ELSE 0 END) as num_ok,
       SUM(CASE WHEN Started = 'FAILED' THEN 1 ELSE 0 END) as num_failed
FROM table1
WHERE remediated = 'REMEDIATED'
GROUP BY type, device
HAVING num_ok = num_failed;

这与您的查询完全不同,因为它会在remediated上过滤计数和行。但是,我怀疑这是你打算

注意:并非所有数据库都支持HAVING中的表别名。如果需要,您可以重复表达式:

HAVING SUM(CASE WHEN Started = 'OK' THEN 1 ELSE 0 END) = SUM(CASE WHEN Started = 'FAILED' THEN 1 ELSE 0 END);