Jun*_*ooq 2 postgresql postgresql-9.3
我目前正在从我的数据库中获取昨天的所有数据,但我想获取每小时的数据。这是我的查询:
select
camera_id,
count(*) as snapshot_count
from snapshots
where created_at >= TIMESTAMP 'yesterday'
and created_at < TIMESTAMP 'today'
group by camera_id
Run Code Online (Sandbox Code Playgroud)
它给了我昨天的所有记录,但是怎么可能从昨天获取记录但每个小时?
PS:我想在一个查询中运行它,而不是 24 个查询
使用date_part
让您的时间戳的小时部分,然后将其添加到您的GROUP BY
条款。
select
camera_id,
count(*) as snapshot_count,
date_part('hour', created_at) as hr
from snapshots
where created_at >= TIMESTAMP 'yesterday' AND created_at < TIMESTAMP 'today'
group by camera_id, hr
Run Code Online (Sandbox Code Playgroud)
我生成了一个示例表:
CREATE TABLE ex.snapshots
(
camera_id integer NOT NULL,
created_at timestamp with time zone NOT NULL,
)
Run Code Online (Sandbox Code Playgroud)
并用一些测试数据填充它:
INSERT INTO ex.snapshots (camera_id,created_at) (
SELECT
(random() * 6)::integer,
now() - (((random() * 2000)::integer)::text || ' minutes')::interval
FROM generate_series(1,20000)
);
Run Code Online (Sandbox Code Playgroud)
添加排序子句后,这是输出的前几行:
camera_id | snapshot_count | hr
-----------+----------------+----
0 | 39 | 0
0 | 46 | 1
0 | 59 | 2
0 | 46 | 3
0 | 49 | 4
0 | 48 | 5
0 | 56 | 6
0 | 43 | 7
Run Code Online (Sandbox Code Playgroud)