获取昨天的记录,但每小时

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 个查询

Chr*_*ton 5

使用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)

  • 如果您想填写的结果(最上面的查询)中有空白,您可以添加一个从 generate_series 中选择的 UNION 语句,例如。`union all select hr from generate_series(0,23,1) hr` (2认同)