*|select date_trunc('minute', __time__) as dt, sum(request_length)/60.0 as data from log group by dt order by data desc limit 3
查询所有日志,按照分钟分隔时间,统计request_length后处以60得到每秒data, 按照dt(分钟间隔)分组,按照data 从大到小排序,取前3个
日志服务中的每条日志都包含保留字段__time__,该字段的值为UNIX时间戳格式,例如1592374067,代表2020-06-17 14:07:47。
date_trunc函数会根据您指定的时间单位截断日期和时间表达式,并按照毫秒、秒、分钟,小时、日、月或年对齐。该函数常用于需要按照时间进行统计分析的场景。
date_trunc(unit, x)
unit时间单位,取值为millisecond、second、minute、hour、day、week、month、quarter、year
x 参数值为日期和时间表达式
date_trunc函数只能按照固定的时间间隔统计(例如每分钟、每小时等)。如果您需要按照灵活的时间维度统计,请使用数学取模方法进行分组,例如统计每5分钟的数据。
* | SELECT count(1) AS pv, time - time %300 AS time GROUP BY time LIMIT 100
*|
select
coalesce(max(data),0) as data
from (
select
date_trunc('minute', __time__) as dt, sum(request_length)/60.0 as data
from log
group by dt
order by data desc
limit 3)
取每秒data的最大值 无data值则默认取0
COALESCE表达式用于返回多个表达式中第一个非null的值。
*|select compare(data, 86400) as diff from (select coalesce(max(data),0) as data from (select date_trunc('minute', __time__) as dt, sum(request_length)/60.0 as data from log group by dt order by data desc limit 3))
[12657.483333333334,8549.75,1.4804506954394379]
compare函数用于对比当前时间周期内的计算结果与n秒之前时间周期内的计算结果
*|select
case
when diff[1] < 102 then concat(cast(round(diff[1],2) AS varchar), ' B/s')
when diff[1] < 1024*1024 then concat(cast(round(diff[1]/1024,1) AS varchar), ' KB/s')
when diff[1] < 1024*1024*1024 then concat(cast(round(diff[1]/1024.0/1024,1) AS varchar), ' MB/s')
when diff[1]/1024.0 < 1024*1024*1024 then concat(cast(round(diff[1]/1024.0/1024/1024,1) AS varchar), ' GB/s')
ELSE concat(cast(round(diff[1]/1024.0/1024/1024/1024,1) AS varchar), ' TB/s')
END
as value ,
if(diff[2]=0, 0, round(diff[3]-1, 2)) as ratio from (select compare(data, 86400) as diff from (select coalesce(max(data),0) as data from (select date_trunc('minute', __time__) as dt, sum(request_length)/60.0 as data from log group by dt order by data desc limit 3)))
round函数用于对x进行四舍五入。如果n存在,则保留n位小数;如果n不存在,则对x进行四舍五入取整数 round(x, n)
cast函数用于转换x的数据类型。使用cast函数转换数据类型时,如果某个值转换失败,将终止整个查询与分析操作。cast(x as type)
concat函数用于将多个字符串拼接成一个字符串。