create table events (
fk_user integer,
event varchar(40),
time integer
);
Insert into events (fk_user, event, time)
VALUES
('1', 'view', '1'),
('1', 'view', '3'),
('1', 'view', '4'),
('1', 'lead', '5'),
('1', 'view', '6'),
('1', 'view', '7'),
('1', 'lead', '9'),
('2', 'view', '1'),
('2', 'lead', '2'),
('2', 'lead', '3'),
('2', 'view', '6'),
('2', 'view', '7'),
('2', 'view', '8'),
('5', 'view', '1'),
('5', 'view', '2'),
('2', 'view', '4'),
('2', 'lead', '5'),
('2', 'view', '9');
我想要找到的是:有3个观点'在“领先”之前从顶部发生。我想取平均时间'前三次发生。是否可以使用窗口功能?
预期输出应为:(1 + 3 + 4)/ 3 = 2.666(如果取整数则为3)
答案 0 :(得分:0)
您可以使用min
窗口函数和case
语句查找每first_lead_time
fkuser
,然后使用派生表获取平均值在views
first_lead_time
行
select fkuser, avg(time) from (
select * ,
min (case when event = 'lead' then time end) over (partition by fkuser) as first_lead_time
from events
) t where time < first_lead_time
and event = 'view'
group by fkuser
另一种方式
select e.fk_user, avg(e.time)
from events e
join (
select min(time) first_lead_time, fkuser
from events
where event = 'lead'
group by fkuser
) t on t.fkuser = e.fkuser
where e.time < t.first_lead_time
group by e.fkuser