有记录,每条都有
pk_id serial primary key,
key varchar(20),
...
from_ts timestamp(0) not null,
thru_ts timestamp(0) not null,
希望从 from_ts
到 thru_ts
确定的间隔中选择随机时间
间隔两小时的记录被选择的机会应该是间隔一小时的记录的两倍。
具有相同键的记录是不相交的 - 没有重叠时间
希望选择pk_id
和随机时间戳。
select pk_id, ???
from rcds
where key = 'abc'
使用 postgres
,因此 ANSI 加上 interval
数据类型
最佳答案
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 列排序
由于对问题有了更好的理解而推出了新版本。
关于sql - 在sql中,如何从具有from和thru时间戳的记录中选择随机时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10796826/