我需要计算应用使用期限的每周平均值(每次使用都有自己的持续时间日志)。 问题是我想比较某个事件发生之前和之后的平均值(每个用户的不同日期)。因此,如果事件发生在一个月前的星期二,我想计算在特定星期二之前和之后的星期二开始的每周平均值。
相关数据如下: 事件
User ID || date of event
3fin2d..|| 19/03/17
2f4j34..|| 20/03/17
USAGE
UID || timestamp start || timestamp end || Duration
3fin2d.. || 11/03/17 11:20:00 || 11/03/17 12:00:00 || 00:40
3fin2d.. || 18/03/17 11:20:00 || 18/03/17 12:00:00 || 00:40
2f4j34.. || 19/03/17 18:20:00 || 19/03/17 18:40:00 || 00:20
2f4j34.. || 19/03/17 19:20:00 || 19/03/17 20:00:00 || 00:40
3fin2d.. || 19/03/17 19:30:00 || 19/03/17 20:00:00 || 00:30
2f4j34.. || 20/03/17 19:20:00 || 20/03/17 20:00:00 || 00:40
编辑: 用户
UID || Created On
3fin2d.. || 11/03/17 11:00:00
2f4j34.. || 18/03/17 13:00:00
预期结果:
UID ||Average Duration before even||Average Duration After event
3fin2d.. || 00:40:00 || 00:30:00
2f4j34.. || 01:00:00 || 00:40:00
当然应考虑使用0周的周数。 在上面的例子中,我假设当前日期是20/03/17(否则应该计算更多的零)。
谢谢
答案 0 :(得分:0)
http://rextester.com/USBJ20378
select uid,
avg(u.duration) filter (where usage_start < e.event_date) as before,
avg(U.duration) filter (where usage_start >= e.event_date) as after
from
usage u
inner join
events e using (uid)
where usage_start between e.event_date - 7 and e.event_date + 7
group by uid
;
uid | before | after
--------+----------+----------
2f4j34 | 00:30:00 | 00:40:00
3fin2d | 00:40:00 | 00:30:00