【问题标题】:oracle sql to get min timestamp when the count of results large than a number当结果计数大于数字时,oracle sql 获取最小时间戳
【发布时间】:2015-04-25 23:15:34
【问题描述】:

为了提高性能,我需要一个sql来实现以下需求。

如果有一个表并且有以下列:

id timestamp value

当结果计数 > 100000 时,如何获取最小时间戳(例如:t1)?

那么下面的sql结果--count(*)将> 100000

select count(*) from table where  timestamp < :t1

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    我对你的问题的理解是:在表中找到至少有 100,000 早行的最早时间戳。

    可能有很多方法可以做到;主要的困难是想出一个有效的方法。

    我认为分析函数方法最有可能运作良好。最明显的选择是使用 COUNT:

    select min(timestamp) from (
      select timestamp, count(*) over (order by timestamp rows between unbounded preceding and 1 preceding) earlier_rows
      from table
    )
    where earlier_rows >= 100000
    

    但我怀疑使用 RANK 或类似的东西会更快:

    select min(timestamp) from (
      select timestamp, rank() over (order by timestamp) time_rank
      from table
    )
    where time_rank > 100000
    

    我并不确定,但如果有重复的时间戳,这些结果可能会略有不同。

    【讨论】:

    • 但查询需要我 6 秒
    【解决方案2】:

    这将为您提供最小值和最大值以及计数

    select 
        count(t.*), 
        min(t.timestamp),
        max(t.timestamp)
    from table t
    where ( select count(*) from table t where  t.timestamp < :t1 ) > 10000
    

    【讨论】:

    • 不回答问题,条件 > 100000 缺失
    • WHERE 子句中不允许使用聚合函数。
    • 是的,它试图快速将查询的第一部分复制到 where。这将运行两次查询,因为它获取了 where select 语句的所有记录,并再次获取实际查询的所有记录,认为最好像下面那样运行查询并检查运行查询的任何结果检查它是否超过 10000 select count(t.*), min(t.timestamp), max(t.timestamp) from table t t.timestamp
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2016-05-31
    • 2020-07-13
    • 1970-01-01
    • 2012-04-03
    • 2020-06-04
    相关资源
    最近更新 更多