これがまさにあなたが探しているものかどうかはわかりませんが、適応の基礎として役立つかもしれません. 私はエポック時間を使用していませんが、時間の経過とともに要約データを生成する必要があることが多いため、私が思いついたよりも値を操作するより良い方法があるかもしれません。
テスト テーブルの作成と入力
create table epoch_t(etime numeric);
insert into epoch_t
select extract(epoch from generate_series(now(),now() - interval '6 hours',interval '-10 minutes'));
時間を期間バケットに分割するには:
select generate_series(to_char(now(),'yyyy-mm-dd hh24:00:00')::timestamptz,
to_char(now(),'yyyy-mm-dd hh24:00:00')::timestamptz - interval '4 hours',
interval '-1 hour');
エポック時間を postgres タイムスタンプに変換します。
select timestamptz 'epoch' + etime * '1 second'::interval from epoch_t;
次に、 hour に切り捨てます。
select to_char(timestamptz 'epoch' + etime * '1 second'::interval,
'yyyy-mm-dd hh24:00:00')::timestamptz from epoch_t
時間ごとの要約情報を提供するには:
select to_char(timestamptz 'epoch' + etime * '1 second'::interval,
'yyyy-mm-dd hh24:00:00')::timestamptz,
count(*)
from epoch_t
group by 1
order by 1 desc;
データにギャップがある可能性があるが、ゼロの結果を報告する必要がある場合は、generate_series を使用して期間バケットを作成し、データ テーブルに左結合します。この場合、6 時間ではなく 9 時間以上のデータ ポピュレーションの前にサンプル時間バケットを作成し、エポック時間から時間に切り捨てられたタイムスタンプへの変換に参加します。
select per.sample_hour,
sum(case etime is null when true then 0 else 1 end) as etcount
from (select generate_series(to_char(now(),
'yyyy-mm-dd hh24:00:00')::timestamptz,
to_char(now(),'yyyy-mm-dd hh24:00:00')::timestamptz - interval '9 hours',
interval '-1 hour') as sample_hour) as per
left join epoch_t on to_char(timestamptz 'epoch' + etime * '1 second'::interval,
'yyyy-mm-dd hh24:00:00')::timestamptz = per.sample_hour
group by per.sample_hour
order by per.sample_hour desc;