drop table if exists clients_initial_timestamps;


create temporary table clients_initial_timestamps as
select
	entity_id,
	created_at as init_time
FROM
	(SELECT 
		entity_id,
		created_at,
		row_number() over by_users as place
	from 
		db1.test.chat_messages cm 
	where created_by = 0
	window by_users as 
		(partition by entity_id, created_by order by created_at)) t1
where t1.place = 1;

select * from clients_initial_timestamps;

drop table if exists managers_response_timestamps;
create temporary table managers_response_timestamps as
select 
	entity_id,
	created_by as mop_id,
	created_at as responce_time
from 
	(SELECT 
		entity_id,
		created_by,
		created_at,
		row_number() over by_users as place
	from 
		db1.test.chat_messages cm 
	where created_by <> 0
	window by_users as 
		(partition by entity_id, created_by order by created_at)) t1
where 
	t1.place = 1;
	
select * from managers_response_timestamps;	
	
	
select 
	*,
	mrt.responce_time - cit.init_time as delta
from 
	clients_initial_timestamps as cit
	join 
	managers_response_timestamps as mrt
	on cit.entity_id = mrt.entity_id;

select 
	entity_id,
	count(*) as cnt
from 
	db1.test.chat_messages cm
group by entity_id 
order by cnt desc

select	
	created_by,
	created_at,
	rank() over(order by created_by) as dr
from 
	db1.test.chat_messages cm 	
where entity_id = 36541651
order by created_at 
	
	
select
	*,
	row_number() over(partition by entity_id order by created_at)
from 
	chat_messages cm 

	
	
	
	
	
select
	type,
	entity_id,
	created_by,
	created_at,
	created_at - lag(created_at) over(partition by entity_id, type order by created_at) as prev_msg_time,
	rank() over(partition by entity_id, type order by created_at) as nm
from 
	chat_messages cm
where 
	entity_id = 37529075
order by created_at 
offset 1;


-- result
with tmp as
(select 
	*,
	created_at - lag(created_at) over(order by created_at) as diff
from 
	chat_messages cm 
)
select 
--	*
	tmp.created_by,
	avg(diff)
from 
	tmp
where 
	tmp.diff is not null 
	and
	tmp.created_by <> 0
group by tmp.created_by	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	