简体   繁体   English

MYSQL-单个查询中有多个计数

[英]MYSQL - Multiple counts in a single query

I'm trying to do multiple counts in a single query but still not getting the results I want. 我正在尝试在单个查询中进行多次计数,但仍然没有得到想要的结果。 There are 6 servers on 5F / 6F and I want to count how many servers on 5F / 6F are using CPU more than 50% or how many servers on 5F / 6F are using CPU less than 50%. 5F / 6F上有6台服务器,我想计算5F / 6F上有多少服务器使用的CPU超过50%,或者5F / 6F上有多少服务器使用的CPU少于50%。

I tried to send the below query but the result is not separated by group. 我尝试发送以下查询,但结果未按组分开。

SELECT room, (SELECT count( > 50) FROM table WHERE empty > 50),
(SELECT count( < 50) FROM table WHERE empty < 50) FROM table GROUP BY location;

Table: 表:

| name  | location | CPU usage |
| host1 | 5F       | 60        |
| host2 | 5F       | 20        |
| host2 | 5F       | 80        | 
| host3 | 6F       | 30        |
| host4 | 6F       | 40        |
| host5 | 6F       | 90        |

Desired output: 所需的输出:

| location | > 50 | < 50 |
| 5F       | 2    | 1    |
| 6F       | 1    | 2    |

Could you try this? 你可以试试这个吗?

SELECT location, SUM(IF(cpu_usage > 50, 1, 0)), SUM(IF(cpu_usage <=50, 0, 1))
FROM table
GROUP BY location

Updated 更新

As ScayTrase mentioned, cpu_usage > 50 itselfs return 0 or 1 for true or false respectively. 正如ScayTrase所述, cpu_usage > 50本身分别返回0或1(表示true或false)。 So, preceding query could be simplified as follows. 因此,先前的查询可以简化如下。

SELECT location, SUM(cpu_usage > 50), SUM(cpu_usage <=50)
FROM table
GROUP BY location

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

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