我有一张这样的表:
-----------+------------+-------
first | last | bytes
-----------+------------+-------
1441013602 | 1441013602 | 10
-----------+------------+-------
1441013602 | 1441013603 | 20
-----------+------------+-------
1441013603 | 1441013605 | 30
-----------+------------+-------
1441013610 | 1441013612 | 30
哪个
'第一'列正在切换流量的第一个数据包的时间
'最后'列正在切换流量最后一个数据包的时间
'字节'是交通流量。
如何计算从1441013602到1441013612的每秒带宽使用情况?
我想要这个:
1441013602 20 B/s
1441013603 20 B/s
1441013604 10 B/s
1441013605 10 B/s
1441013606 0 B/s
1441013607 0 B/s
1441013608 0 B/s
1441013609 0 B/s
1441013610 10 B/s
1441013611 10 B/s
1441013612 10 B/s
答案 0 :(得分:2)
您可以使用PostgreSQL的generate_series
功能。生成一系列行,每秒一行,因为这就是你想要的。然后在信息表上保持连接,这样每个数据流每秒都会获得一行。 GROUP BY
秒,sum
数据流字节。
e.g:
SELECT seconds.second, coalesce(sum(t.bytes::float8 / (t.last::float8-t.first::float8+1)),0)
FROM generate_series(
(SELECT min(t1.first) FROM Table1 t1),
(SELECT max(t1.last) FROM Table1 t1)
) seconds(second)
LEFT JOIN table1 t
ON (seconds.second BETWEEN t.first and t.last)
GROUP BY seconds.second
ORDER BY seconds.second;
http://sqlfiddle.com/#!15/b3b07/7
请注意,我们计算流量的每秒字节数,然后将流量的秒数与所有流量的总和相加。这只是一个估计值,因为我们不知道流量在流量持续时间内是否稳定。
要格式化字节,请使用format
功能和/或pg_size_pretty
。
答案 1 :(得分:2)
PostgreSQL 9.3架构设置:
create table t ( first int, last int, bytes int );
insert into t values
(1441013602 , 1441013602 , 10 ),
(1441013602 , 1441013603 , 20 ),
(1441013603 , 1441013605 , 30 ),
(1441013610 , 1441013612 , 30 );
查询:
with
bytes as
( select first, last,
( last - first ) as calc_time,
bytes
from t
where ( last - first )>0 ),
bytes_per_second as
( select first, last, bytes / calc_time as Bs
from bytes ),
calc_interval as
( SELECT * FROM generate_series(1441013602,1441013612) )
select
i.generate_series, bps.Bs
from
calc_interval i
left outer join
bytes_per_second bps
on i.generate_series between bps.first and bps.last - 1
order by
i.generate_series
<强> Results 强>:
| generate_series | bs |
|-----------------|--------|
| 1441013602 | 20 |
| 1441013603 | 15 |
| 1441013604 | 15 |
| 1441013605 | (null) |
| 1441013606 | (null) |
| 1441013607 | (null) |
| 1441013608 | (null) |
| 1441013609 | (null) |
| 1441013610 | 15 |
| 1441013611 | 15 |
| 1441013612 | (null) |
说明: