简体   繁体   English

MYSQL查询中的多个计数

[英]Multiple Counts in MYSQL query

I would like to count a specific database column with TWO different count criteria so i can calculate a percentage 我想用两个不同的计数标准来计数一个特定的数据库列,以便我可以计算一个百分比

For example lets same the database column is called Latency, and the data in the column contains the number of seconds. 例如,让相同的数据库列称为延迟,而列中的数据包含秒数。

I would like to count the number of Latency messages > 50 seconds but also the TOTAL number of Latency messages in the same query ( ie > 0 seconds) 我想计算> 50秒的延迟消息的数量,还要计算同一查询中延迟消息的总数(即> 0秒)

My current query for > 50 seconds is as follows 我当前的查询> 50秒如下

select COUNT(*) from table WHERE date = 20180701 and CAST(Latency As Signed) > 50

How would i include counts > 0 seconds in the same query ?? 我将如何在同一查询中包括> 0秒的计数?

Use conditional aggregation: 使用条件聚合:

SELECT
    COUNT(CASE WHEN CAST(Latency As Signed) > 50 THEN 1 END) AS latency,
    COUNT(CASE WHEN CAST(Latency As Signed) > 0  THEN 1 END) AS total,
    100.0 * COUNT(CASE WHEN CAST(Latency As Signed) > 50 THEN 1 END) /
            COUNT(CASE WHEN CAST(Latency As Signed) > 0  THEN 1 END) AS percentage
FROM table
WHERE date = 20180701;

This maybe helpful to you, @John, How to get multiple counts with one SQL query? @John,这可能对您有帮助, 如何通过一个SQL查询获得多个计数? It uses count together with aggregate functions in order to target multiple count function in one query.. 它结合使用count和聚合函数,以便在一个查询中定位多个count函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM