我在一个组织工作,其中用户有时按“拆分”时间表工作,并且数据的结构如下所示:
用户 | 时间开始 | 时间结束 | 类型 |
---|---|---|---|
用户 1 | 3/29/23 上午 8:00 | 3/29/23 晚上 8:00 | 打开 |
用户 1 | 3/29/23 中午 12:00 | 3/29/23 下午 4:00 | 关闭 |
用户 2 | 3/29/23 上午 10:00 | 3/29/23 晚上 10:00 | 打开 |
用户 2 | 3/29/23 下午 2:00 | 3/29/23 下午 6:00 | 关闭 |
问题是我需要知道他们的工作时间而不是他们的“关闭”时间——我该怎么做才能使最终结果看起来像这样:
用户 | 时间开始 | 时间结束 |
---|---|---|
用户 1 | 3/29/23 上午 8:00 | 3/29/23 中午 12:00 |
用户 1 | 3/29/23 下午 4:00 | 3/29/23 晚上 8:00 |
用户 2 | 3/29/23 上午 10:00 | 3/29/23 下午 2:00 |
用户 2 | 3/29/23 下午 6:00 | 3/29/23 晚上 10:00 |
我试过使用 PARTITION BY 但看在我的份上无法得到我想要的结果...可能是我做错了
这里是可以使用的查询。
它依赖于相当重的假设:
With
pairs as (
select
jc.user,
jo.timestart o_start,
jc.timestart c_start,
jc.timeend c_end,
jo.timeend o_end
from
journal jo
join journal jc on (
j1.user = j2.user
and trunc (j1.timestart) = trunc (j2.timestart)
and jc.type = 'Closed'
)
Where
jo.type = 'Open'
),
open_only as (
--Only open ones
select
j1.user,
j1.timestart,
jc.timeend
from
journal j1
where
type = 'Open' not exists (
select
1
from
journal j2
where
j1.user = j2.user
and trunc (j1.timestart) = trunc (j2.timestart)
and j2.type = 'Closed'
)
)
select
user,
timestart,
timeend
from
open_only
UNION ALL -- First part of shift
select
user,
o_start,
c_start
from
pairs
UNION ALL -- First part of shift
select
user,
c_end,
o_end
from
pairs
这个查询结合了三个部分: