【问题标题】:How can I select groups of rows from an Oracle table?如何从 Oracle 表中选择行组?
【发布时间】:2015-04-29 09:42:54
【问题描述】:

我在 Oracle 表中的三列(时间戳、状态和值)中有数百万条数据。

从 temp_table rownum

1 2015-04-28T12:41:34.1616834Z 预订 100
2 2015-04-28T12:41:34.1888649Z 删除 100
3 2015-04-28T12:55:59.3789387Z 执行 200
4 2015-04-28T12:55:59.3825833Z 坚持 200
5 2015-04-28T12:55:59.3898336Z 书 200
6 2015-04-28T12:55:59.3903645Z 删除 200

7 2015-04-28T12:57:37.5718992Z 预订 200
8 2015-04-28T12:57:37.5723847Z 删除 200
9 2015-04-28T12:57:37.5725199Z 预订 300
10 2015-04-28T12:57:37.5728888Z 删除 300

我对按 Execute、Persist、Book 和 Delete 分组的四个时间戳列表感兴趣,这些时间戳在当天的每个 orderId 中一起出现。

我对第 7 行和第 8 行不感兴趣,即使 orderId 相同 [因为它们没有按 Execute、Persist、Book 和 Delete 分组]。

我可以通过解析函数来做到这一点吗?

谢谢

【问题讨论】:

  • 你为什么用plsql标记这个?你想要一个存储过程吗?
  • 您想要当天的前 4 个时间戳吗?为什么第 8 行被排除在外 - 它的状态是“删除”
  • 我希望当天的所有时间戳都出现在 Execute、Persist、Book 和 Delete 的有序组集中。
  • 我认为这可以在 PL/SQL 中完成,但我想知道这是否可以使用解析函数。

标签: oracle plsql


【解决方案1】:

不是很优雅,但可以查询:

with t1 as (
  select tstamp ts, status st, orderid oid, 
      decode(status, 'Execute', 1, 'Persist', 2, 'Book', 3, 'Delete', 4, 5) ds
    from temp_table),
t2 as (
  select ts, st, oid, ds
    , decode(ds, 1, 1, lag(ds, ds-1) 
        over (partition by oid, trunc(ts) order by ts, ds)) d1
    , case when ds = 1 then lead(ds) over (partition by oid, trunc(ts) order by ts, ds)
           when ds = 2 then 2
           when ds = 3 then lag(ds) over (partition by oid, trunc(ts) order by ts, ds)
           when ds = 4 then lag(ds, 2) over (partition by oid, trunc(ts) order by ts, ds)
      end d2
    , case when ds = 1 then lead(ds, 2) over (partition by oid, trunc(ts) order by ts, ds)
           when ds = 2 then lead(ds) over (partition by oid, trunc(ts) order by ts, ds)
           when ds = 3 then 3
           when ds = 4 then lag(ds) over (partition by oid, trunc(ts) order by ts, ds)
      end d3
    , decode(ds, 4, 4, lead(ds, 4-ds) 
        over (partition by oid, trunc(ts) order by ts, ds)) d4
  from t1 )
select ts, st, oid from t2
  where (d1, d2, d3, d4) in ((1, 2, 3, 4))
  order by oid, ts, ds

【讨论】:

  • SQLFiddle.com 网站有问题,无论如何here 是我使用的数据。
猜你喜欢
  • 1970-01-01
  • 2012-05-08
  • 1970-01-01
  • 2023-01-13
  • 2015-10-01
  • 2017-08-02
  • 1970-01-01
  • 2012-02-13
  • 1970-01-01
相关资源
最近更新 更多