2

記録を持っており、それぞれが持っている

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

によって決定される間隔からランダムな時間を選択しfrom_tsたいthru_ts

2 時間間隔のレコードは、1 時間間隔のレコードよりも 2 倍の確率で選択されるはずです。

同じキーを持つレコードはばらばらです - 時間の重複はありません

pk_idとランダムなタイムスタンプを選択したい。

select pk_id, ???
from rcds
where key = 'abc'

を使用してpostgresいるため、ANSI プラスintervalデータ型

4

1 に答える 1

2
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列で並べ替えるように変更


質問の理解が深まったための新版。

于 2012-05-29T11:51:02.940 に答える