【发布时间】:2015-04-25 23:15:34
【问题描述】:
为了提高性能,我需要一个sql来实现以下需求。
如果有一个表并且有以下列:
id timestamp value
当结果计数 > 100000 时,如何获取最小时间戳(例如:t1)?
那么下面的sql结果--count(*)将> 100000
select count(*) from table where timestamp < :t1
【问题讨论】:
为了提高性能,我需要一个sql来实现以下需求。
如果有一个表并且有以下列:
id timestamp value
当结果计数 > 100000 时,如何获取最小时间戳(例如:t1)?
那么下面的sql结果--count(*)将> 100000
select count(*) from table where timestamp < :t1
【问题讨论】:
我对你的问题的理解是:在表中找到至少有 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
我并不确定,但如果有重复的时间戳,这些结果可能会略有不同。
【讨论】:
这将为您提供最小值和最大值以及计数
select
count(t.*),
min(t.timestamp),
max(t.timestamp)
from table t
where ( select count(*) from table t where t.timestamp < :t1 ) > 10000
【讨论】:
WHERE 子句中不允许使用聚合函数。