截取memory_usage字段中的小数值 并计算平均百分比
表数据
select * from test;
1.截取
1.1 substring_index(关键字的索引开始截取,-1由最后往前截)
1.1.1 从"("开始截取
select substring_index(memory_usage,'(',-1) as substr from test;
1.1.2 再次截取(1 从最前完后截取,截取到%之前)
select substring_index(substring_index(memory_usage,'(',-1),'%',1) as substr from test;
1.2 substring
配合获取索引的函数 instr()以及left 从左开始截取到某个索引为止, 同样可以实现
1.2.1 INSTR
select substring(memory_usage,INSTR(memory_usage,'(')+1) from test;
1.2.2 left
select left(substring(memory_usage,INSTR(memory_usage,'(')+1),INSTR(substring(memory_usage,INSTR(memory_usage,'(')+1),'%')-1) from test;
2.累加计算求平均
select sum(substring_index(substring_index(memory_usage,'(',-1),'%',1))/(select count(1) from test) as avgstr from test;
3.取两位小数
select round(sum(substring_index(substring_index(memory_usage,'(',-1),'%',1))/(select count(1) from test),2) as avgstr from test;
4.拼接%
select concat(round(sum(substring_index(substring_index(memory_usage,'(',-1),'%',1))/(select count(1) from test),2),'%') avgstr from test;
5.非0判断,分母不能为0,null->0 (select count(1) from test)
select
case when (select count(1) from test)>0
then concat(round(sum(substring_index(substring_index(memory_usage,'(',-1),'%',1))/(select count(1) from test),2),'%')
else 0 end as avgstr
from test;
其它:
CAST函数用于将某种数据类型的表达式显式转换为另一种数据类型。
语法:CAST (expression AS data_type)