Sql 如何查找每行两个日期之间的行
我有下表:Sql 如何查找每行两个日期之间的行,sql,date,count,window-functions,presto,Sql,Date,Count,Window Functions,Presto,我有下表: topic_id conversation logical_date start_date end_date type 1 1 2020-01-01 09:00 2020-01-01 09:00 2020-01-01 09:50 phone call 1 2 2020-01-01 09:14
topic_id conversation logical_date start_date end_date type
1 1 2020-01-01 09:00 2020-01-01 09:00 2020-01-01 09:50 phone call
1 2 2020-01-01 09:14 text
1 3 2020-01-01 10:27 text
2 1 2020-02-03 08:40 text
此表表示支持请求。每个支持请求都有主题,主题有一个或多个对话
我想查找在电话开始日期和结束日期之间完成的所有文本请求
因此,对于上表,我想看到:
topic_id conversation_id start_date end_date sum
1 1 2020-01-01 09:00 2020-01-01 09:50 1
逻辑是:
对于每个主题id,键入='phone call'开始日期和结束日期
将它们与此主题中的type='text'对话进行比较\u id
将逻辑日期介于开始日期和结束日期之间的人相加
我知道我需要使用窗口功能来实现这一点,但我不确定如何实现
这就是我到目前为止所做的:
select topic_id, conversation_id, start_date, end_date, count(1 ) over partition by ()
from table
where type = 'phone call'
我正在使用Presto我想您需要:
select t.*
from t
where t.type = 'text' and
exists (select 1
from t t2
where t2.conversation_id = t.conversation_id and
t.logical_date between t2.start_date and t2.end_date and
t2.type = 'phone'
);
如果您确实需要两条记录中的信息,请使用join:
您可以使用相关子查询来计算每个“电话呼叫”记录的同一主题id可以找到多少“文本”记录: 为了提高性能,您需要一个关于主题id、类型、逻辑日期的索引 我不确定使用窗口函数是否更简单
select tt.*, tp.*
from t tt join
t tp
on tp.conversation_id = tt.conversation_id and
tt.logical_date between tp.start_date and tp.end_date and
tp.type = 'text' and
tp.type = 'phone';
select
t.*,
(
select count(*)
from mytable t1
where
t1.topic_id = t.topic_id
and t1.type = 'text'
and t1.logical_date >= t.start_date
and t1.logical_date < t.end_date
) cnt
from mytable t
where t.type = 'phone call'