mysql各类统计查询场景-01

1、表结构:

-- 统计有多少个客户端ip上报数据

-- 方式一,只有select分类后统计
SELECT count(*) 
from (SELECT stability_result.ip_addr,count(*) from stability_result GROUP BY stability_result.ip_addr) AS newtable;
-- 方式二,通过DISTINCT去重,统计
SELECT count(DISTINCT stability_result.ip_addr) FROM stability_result;

-- 统计各业务运行结果,运用【 case when 条件 then 名称 end 】语法

SELECT stability_result.ip_addr,
count(case when stability_result.run_result = 0 then 0 end) AS '成功',
count(case when stability_result.run_result != 0 then 0 end) AS '失败',
count(case when stability_result.run_result = 101 then 101 end) AS '登录失败',
count(case when stability_result.run_result = 102 then 102 end) AS '应用:访问小应用失败',
count(case when stability_result.run_result = 103 then 103 end) AS '应用:访问大应用失败',
count(case when stability_result.run_result = 104 then 104 end) AS '应用:上传失败',
count(case when stability_result.run_result = 105 then 105 end) AS '应用:下载失败'
FROM stability_result GROUP BY stability_result.ip_addr;
 
SELECT stability_result.ip_addr,
count(case when stability_result.run_result = 0 then 0 end) AS '成功总数',
count(case when stability_result.run_result != 0 then 0 end) AS '失败总数',
count(case when stability_result.run_result = 101 then 101 end) AS '登录失败',
count(case when stability_result.run_result IN (103,102) then 103 end) AS '应用:访问应用失败',
count(case when stability_result.run_result IN (105,104) then 105 end) AS '应用:上传下载失败'
FROM stability_result GROUP BY stability_result.ip_addr;

2、表结构:

按ip分类后,只拉取每个ip最新的一条数据。这里有【INNER JOIN 其他表 ON 条件】的语法

-- 按ip分类后,只拉取每个ip最新的一条数据。这里有【INNER JOIN 其他表 ON 条件】的语法
SELECT a.ip_addr,a.datetime,pro1_cpu_time,pro1_mem,pro1_handle_num,pro1_thread_num,
pro2_cpu_time,pro2_mem,pro2_handle_num,pro2_thread_num,
pro3_cpu_time,pro3_mem,pro3_handle_num,pro3_thread_num
from stability_sys_proc_time a 
INNER JOIN (SELECT ip_addr,MAX(datetime) AS datetime FROM stability_sys_proc_time GROUP BY ip_addr) as newtables
ON a.ip_addr=newtables.ip_addr AND a.datetime=newtables.datetime;
 
-- 这里没用INNER的话,也可以查询,但是如果存在 多个ip有相同时间的数据,会查出一个ip多个时间的数据结果。不符合期望
-- 如 ip1,date1; ip2,date2; ip2,date1(这个就是因为ip1和ip2都有date1时间的数据)。
SELECT ip_addr,datetime,pro1_cpu_time,pro1_mem,pro1_handle_num,pro1_thread_num,
pro2_cpu_time,pro2_mem,pro2_handle_num,pro2_thread_num,
pro3_cpu_time,pro3_mem,pro3_handle_num,pro3_thread_num
from stability_sys_proc_time where datetime in 
(SELECT newtables.datetime from 
(SELECT ip_addr,MAX(datetime) AS datetime FROM stability_sys_proc_time GROUP BY ip_addr) AS newtables);
 

猜你喜欢

转载自blog.csdn.net/Mr_wilson_liu/article/details/129303655