Sql 查询自连接或cte最佳解决方案?
我有一张如下所示的表格:Sql 查询自连接或cte最佳解决方案?,sql,presto,Sql,Presto,我有一张如下所示的表格: userID | Date | Type | B 2018-01-19 03:14:07 Start B 2019-06-23 02:11:03 End V 2017-01-19 03:14:07 Start V 2019-08-19 02:33:07 End C 2019-01-20 03:14:07 Start C 2019-10-19 03:11:07 End
userID | Date | Type |
B 2018-01-19 03:14:07 Start
B 2019-06-23 02:11:03 End
V 2017-01-19 03:14:07 Start
V 2019-08-19 02:33:07 End
C 2019-01-20 03:14:07 Start
C 2019-10-19 03:11:07 End
C 2019-05-19 03:33:07 Mid
如果我想按ID计算每个用户的不同天数,我可以使用cte对每个cte进行筛选,类型为'Start'和'End',然后加入它们,还是使用ID自加入?每个表将在何处进行类型筛选
因此,cte如:
with start as
(select id, date,
from table
where type = 'Start')
with end as
(select id, date,
from table
where type = 'End')
select s.id, date_diff('day', s.date, e.date) as duration
from start s
join end e
on s.id = e.id
自动加入为:
select s.id, date_diff('day', s.date, e.date) as duration
from table t
join table t2
on t.id = t2.id
where t.type = 'start' and t2.type = 'end'
两者都能正确地给出预期的输出吗
谢谢你的评论,时间太长了,所以请发帖回答 这并不是一种更好的方法,但如果您认为如果不使用CTE、子查询和联接就无法做到这一点,您可以使用窗口函数。它不关心type列,因此即使您有多个日期,它也可以正常工作
select distinct
id,
date_diff('day', min(date) over (partition by id), max(date) over (partition by id)) as duration
from your_table;
这两个查询是等价的。谢谢,所以它会给我相同的预期输出,即相同用户在开始和结束日期的差异?