我有一个包含示例数据的表,如下所示:
Date | hostname |bytesIn|bytesOut|
2018/02/26 11:57:37 | abc.com | 100 | 500
2018/02/26 11:57:37 | abc.com | 50 | 500
2018/02/25 11:57:37 | xyz.com | 100 | 300
2018/02/25 11:57:37 | abc.com | 100 | 500
2018/02/25 11:57:37 | def.com | 200 | 500
我想根据每天的总字节数(bytesIn+bytesOut)选择前 n 条记录。我需要计算 bytesIn 和 bytesOut 列的总和并格式化日期列(省略 hh:mm:ss 部分)以获得特定主机名的每日总字节数。然后我需要根据总字节数获取每天的前 n 个主机名。例如,我需要获取每天消耗带宽最多的主机名。
我看到了类似的问题,但无法将答案应用于我的问题。我怎样才能得到这些记录?
预期的输出应该是这样的(比方说,根据带宽的前 2 个主机名):
2018/02/26 | abc.com | 600
2018/02/26 | xyz.com | 550
2018/02/25 | def.com | 750
2018/02/25 | qwe.com | 300
2018/02/24 | asd.com | 550
2018/02/24 | sdf.com | 520
以下查询对您有帮助,
select hostname, Dates, totalBytes
from
( select @prev := '', @n := 0 ) init
join
( select @n := if( Dates != @prev, 1, @n + 1) AS n,
@prev := Dates,
hostname, Dates, totalBytes
from ( select hostname,DATE_FORMAT(dates, '%Y/%m/%d') as Dates,
(sum(bytesIn) + sum(bytesOut)) totalBytes
from your_table
group by hostname,dates
order by Dates desc, totalBytes desc
) T1
) T2
where n <= 2
n
指定每天的记录数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句