create table rcds (
pk_id serial primary key,
key varchar(20),
from_ts timestamp(0) not null,
thru_ts timestamp(0) not null
)
;
insert into rcds (key, from_ts, thru_ts) values
('abc', '2012-01-01 12:34', '2012-01-02 13:47'),
('abc', '2012-01-03 10:52', '2012-01-07 18:23')
;
with r as (
select sum(extract(epoch from thru_ts - from_ts)) * random() as r
from rcds
)
select
pk_id,
from_ts + (
((select r from r) - coalesce(lag(ts, 1) over (order by from_ts), 0))
::text || ' seconds'
)::interval as random_ts,
from_ts
from (
select
pk_id,
sum(extract(epoch from thru_ts - from_ts)) over (order by from_ts) as ts,
from_ts
from rcds
where key = 'abc'
) s
where (select r from r) <= ts
order by from_ts
limit 1
;
我假设时间戳是按 pk_id 排序的。如果不是,那么只需将排序更改为 from_ts 列。
将其更改为按 from_ts 列排序
新版本由于对问题的更好理解。