我有下表:
unixtime byte_sent byte_received session_id
---------------------------------------------------
1543569405 8 12 1
1543569404 8 12 1
1543569403 8 12 1
1543569402 8 12 1
1543569401 8 12 1
1543569410 15 25 2
1543569409 15 25 2
1543569408 15 25 2
1543569407 15 25 2
1543569411 10 30 3
1543569410 10 30 3
1543569409 10 30 3
1543569408 10 30 3
1543569407 10 30 3
1543569406 10 30 3
1543569405 10 30 3
然后我有以下SQL查询:
select
session_id,
max(unixtime) as session_end_time,
sum(byte_sent) as byte_sent_tot,
sum(byte_received) as byte_received_tot,
count(*) as duration
from
table
group by
session_id
order by
session_end_time
结果如下:
session_id session_end_time byte_sent_tot byte_received_tot duration
----------------------------------------------------------------------------
1 1543569405 40 60 5
2 1543569410 60 100 4
3 1543569411 70 210 7
我需要反向查询才能从结果返回到原始表。
假设持续时间的每一秒都应将session_end_time一次跨一,并且总字节数可以除以持续时间,这样我将获得字节/秒的平均值。
谢谢。
答案 0 :(得分:0)
假定列的每个session_id的记录分布均匀 我们可以执行以下操作
with data
as (select session_id, /*This is the Input query which the user has obtained.*/
max(unixtime) as session_end_time,
sum(byte_sent) as byte_sent_tot,
sum(byte_received) as byte_received_tot,
count(*) as duration
from t
group by session_id
order by session_end_time
)
select a.session_id
,a.session_end_time - b.col + 1 as unixtime
,b.col
,a.byte_sent_tot/a.duration as byte_sent /*Distribute evenly based on the count*/
,a.byte_received_tot/a.duration as byte_received
from data a
cross join generate_series(1,a.duration) as b(col)