【问题标题】:Postgres DB query to get the count, and first and last ids by date in a single queryPostgres DB查询以在单个查询中按日期获取计数以及第一个和最后一个ID
【发布时间】:2020-07-29 22:26:07
【问题描述】:

我有以下数据库结构。

table
-----
 id (uuids)
date (TIMESTAMP)

我想在 postgres 中编写一个查询(实际上是使用 postgres 引擎的 cockroachdb,所以 postgres 查询应该没问题)。

查询应返回 2 个日期之间的记录计数、日期最晚的记录 ID 和该范围内最早日期最晚的记录 ID。

所以查询应该返回以下内容: count, id(范围内最早记录), id(范围内最新记录)

谢谢。

【问题讨论】:

  • ID 是否与日期的顺序相同,或者我可以找到更大的 ID 和更早的日期?
  • Id 是 uuid,所以它们的顺序不会相同

标签: sql database postgresql date cockroachdb


【解决方案1】:

你可以使用row_number()两次,然后条件聚合:

select
    no_records,
    min(id) filter(where rn_asc = 1) first_id
    max(id) filter(where rn_desc = 1) last_id
from (
    select 
        id, 
        count(*) over() no_records
        row_number() over(order by date asc)  rn_asc, 
        row_number() over(order by date desc) rn_desc
    from mytable
    where date >= ? and date < ?
) t
where 1 in (rn_asc, rn_desc)

问号代表日期间隔的(包括)开始和(不包括)结束。

当然,如果ids一直在增加,简单的聚合就足够了:

select count(*), min(id) first_id, max(id) last_id
from mytable
where date >= ? and date < ?

【讨论】:

    【解决方案2】:

    不幸的是,Postgres 不支持 first_value() 作为聚合函数。一种方法是使用数组:

    select count(*),
           (array_agg(id order by date asc))[1] as first_id,
           (array_agg(id order by date desc))[1] as last_id
    from t
    where date >= ? and date <= ?
    

    【讨论】:

    • 不幸的是,我们使用的实际数据库是 cockroachdb,尽管基础引擎是 postgres。 CockroachDb 仍然不允许在聚合函数中排序。 github.com/cockroachdb/cockroach/issues/23620
    • @user7510999 。 . .那么 GMB 就有了正确的答案,你应该接受它。
    • 我还在尝试。我会接受,但我正在做一些柚木。
    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    相关资源
    最近更新 更多