Oracle SELECT 查询:配对日期时折叠空值
我有以下 Oracle 查询:
SELECT id,
DECODE(state, 'Open', state_in, NULL) AS open_in,
DECODE(state, 'Not Open', state_in, NULL) AS open_out,
FROM (
SELECT id,
CASE WHEN state = 'Open'
THEN 'Open'
ELSE 'Not Open'
END AS state,
TRUNC(state_time) AS state_in
FROM ...
)
这给了我如下所示的数据:
id open_in open_out
1 2009-03-02 00:00:00
1 2009-03-05 00:00:00
1 2009-03-11 00:00:00
1 2009-03-26 00:00:00
1 2009-03-24 00:00:00
1 2009-04-13 00:00:00
我想要的是这样的数据:
id open_in open_out
1 2009-03-02 00:00:00 2009-03-05 00:00:00
1 2009-03-11 00:00:00 2009-03-24 00:00:00
也就是说,保留 id
/open_in
的所有唯一对并将 open_in
之后最早的 open_out
与它们配对。给定 id
可以有任意数量的唯一 open_in
值,也可以有任意数量的唯一 open_out
值。唯一的 id
/open_in
可能没有匹配的 open_out
值,在这种情况下,open_out
应该该行的值为 null
。
我觉得一些分析函数,也许LAG
或LEAD
,在这里会很有用。也许我需要将 MIN
与 PARTITION
一起使用。
I have the following Oracle query:
SELECT id,
DECODE(state, 'Open', state_in, NULL) AS open_in,
DECODE(state, 'Not Open', state_in, NULL) AS open_out,
FROM (
SELECT id,
CASE WHEN state = 'Open'
THEN 'Open'
ELSE 'Not Open'
END AS state,
TRUNC(state_time) AS state_in
FROM ...
)
This gives me data like the following:
id open_in open_out
1 2009-03-02 00:00:00
1 2009-03-05 00:00:00
1 2009-03-11 00:00:00
1 2009-03-26 00:00:00
1 2009-03-24 00:00:00
1 2009-04-13 00:00:00
What I would like is data like this:
id open_in open_out
1 2009-03-02 00:00:00 2009-03-05 00:00:00
1 2009-03-11 00:00:00 2009-03-24 00:00:00
That is, keep all the unique pairs of id
/open_in
and pair with them the earliest open_out
that follows open_in
. There can be any number of unique open_in
values for a given id
, and any number of unique open_out
values. It is possible that a unique id
/open_in
will not have a matching open_out
value, in which case open_out
should be null
for that row.
I feel like some analytic function, maybe LAG
or LEAD
, would be useful here. Perhaps I need MIN
used with a PARTITION
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以做得更简单一点。首先让我们创建一个示例表:
数据等于 select 语句的输出:
这是稍微简单一点的查询:
问候,
抢。
It can be done a little bit simpler. First let's create a sample table:
The data equals the output of your select statement:
And here is the slightly easier query:
Regards,
Rob.
我认为 Stack Overflow 一定是鼓舞人心的,或者至少它可以帮助我更清晰地思考。经过一整天的努力,我终于明白了:
更新:看起来这并不完全有效。它与我的问题中的示例配合得很好,但是当有多个唯一的 id 时,LAG 内容会发生变化,并且日期并不总是对齐。 :(
I think Stack Overflow must be inspirational, or at least it helps me think clearer. After struggling with this thing all day, I finally got it:
Update: looks like this doesn't completely work. It works fine with the example in my question, but when there are multiple unique
id
's, theLAG
stuff gets shifted and dates don't always align. :(