查询自连接或cte最佳解决方案?
Query self join or cte best solution?
我有一个 table,如下所示:
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?每个 table 将根据类型进行过滤?
这样的 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'
两者都能正确给出预期的输出吗?
谢谢
评论太长,所以张贴作为答案..
这并不是一个更好的方法,但如果您认为不使用 CTEs
、subqueries
和 joins
就无法做到,您可以使用window-functions
。它不关心类型列,因此即使您有多个日期,它也能正常工作。
select distinct
id,
date_diff('day', min(date) over (partition by id), max(date) over (partition by id)) as duration
from your_table;
我有一个 table,如下所示:
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?每个 table 将根据类型进行过滤?
这样的 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'
两者都能正确给出预期的输出吗?
谢谢
评论太长,所以张贴作为答案..
这并不是一个更好的方法,但如果您认为不使用 CTEs
、subqueries
和 joins
就无法做到,您可以使用window-functions
。它不关心类型列,因此即使您有多个日期,它也能正常工作。
select distinct
id,
date_diff('day', min(date) over (partition by id), max(date) over (partition by id)) as duration
from your_table;