Q:

in sql, how to choose random time in from records having from and thru timestamp

have records, each having
pk_id  serial primary key,
key varchar(20),
...
from_ts timestamp(0) not null,
thru_ts timestamp(0) not null,

wish to choose random time from intervals as determined by from_ts to thru_ts
a record with a two hour interval should have twice as much chance of being selected as a record with a one hour interval.
records having the same key are disjoint - there are no overlapping times
wish to select the pk_id and the random timestamp.
select pk_id, ???
from rcds
where key = 'abc'

using postgres, so ANSI plus interval datatype

A:

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
;

I'm assuming the timestamps are ordered by the pk_id. If not then it is just a matter of changing the ordering to the from_ts column.

Changedt it to order by the from_ts  column

New edition due to a better understanding of the question.

