mysql使用max函数+将类似"123"的字符型数据转换成数据类型

一 获取每天用户数最多的时段

从最多一词可以看出,我们如要去除用户数最多的时段,需要使用max()函数了,
数据表result中个字段为:stat_day,usernum,stat_hour,部分数据如下所示
stat_day usernum stat_hour
20181210 190 2018121000
20181210 112 2018121001
20181210 71 2018121002
......
20181211 118 2018121101
......
20181212 1110 2018121022
...
20181213 448 2018121023
...
20181214 210 2018121100
...
取值sql如下:
select stat_day,usernum ,stat_hour
from result t1
where usernum = (select max(usernum) from result as t2
where t1.stat_day = t2.stat_day)
发现结果如数据不符,究其原因是userum数据导入数据库的时候有数据库自动创建的字段,为字符类型,若要按照数据类型进行排序则需要首先将数据库的usernum字段修改为数值类型

数据类型转换(字符型-数值类型)

转换方式有以下三种
方法一:SELECT CAST('12345' AS SIGNED);
方法二:SELECT CONVERT('12345',SIGNED);
方法三:SELECT '12345'+0;
修改后的查询sql如下:
select stat_day,CAST(usernum AS SIGNED),stat_hour
from result t1
where CAST(usernum AS SIGNED) = (select max(CAST(usernum AS SIGNED)) from result as t2
where t1.stat_day = t2.stat_day)
此时结果已经正常输出

猜你喜欢

转载自blog.51cto.com/maoxiaoxiong/2334032