Postgresql 求不同时间聚合的最大值

问题描述 投票:0回答:2

我有一张桌子,用于存储以下内容:

uuid, client_code, account, item, quantity, timestamp

每次在其他地方更新商品数量时,都会在此表中创建一条新记录,并且可以通过客户的帐户重复商品,因此我最终可能会为每个客户的同一商品或不同帐户提供多条记录,但数量不同。

我正在尝试提出一个查询,该查询将为我提供按客户和时间划分的最大聚合数量。举个例子:

时间戳 项目 数量 账户
2024-01-01T01:00:10 1245 10 a
2024-01-01T05:00:10 1245 300 a
2024-01-01T04:00:10 1245 20 b
2024-01-01T07:00:10 1111 30 a

对于此示例,需要返回项目

1245
的最高数量为 2024-01-01T05:00:10,其中 320、300 来自账户 a,20 来自账户 b,因为它是最新变动。 对于项目
1111
,最高数量是在2024-01-01T07:00:10,总数量为30。

我多次尝试解决这个问题,但没有结果。

有人可以帮忙看看如何实现这一点吗?谢谢!

尝试了几个查询、Windows 功能,但无法使其工作。

postgresql
2个回答
0
投票

您可以从相关的标量子查询中回顾。 db<>fiddle 的演示:

select *,(select sum(quantity)
          from(select distinct on (account) quantity
               from my_table t2
               where t1.item=t2.item
                 and t1.timestamp>=t2.timestamp
               order by account,timestamp desc)_)
from my_table t1
order by timestamp;
时间戳 项目 数量 账户 总和
2024-01-01 01:00:10 1245 10 a 10
2024-01-01 04:00:10 1245 20 b 30
2024-01-01 05:00:10 1245 300 a 320
2024-01-01 07:00:10 1111 30 a 30

在每一行中,它使用

distinct on
从每个帐户中获取同一商品的最新数量,然后将它们相加。


0
投票

我用另一种方式解决了这个问题,也许没有那么整齐,但更符合 ANSI 一点。

create table ItemQty (ts timestamp, item int, quantity int, account char(1));

insert into ItemQty (ts, item, quantity, account)
values
  ('2024-01-01 01:00:10',   1245,   10,     'a'),
  ('2024-01-01 05:00:10',   1245,   300,    'a'),
  ('2024-01-01 04:00:10',   1245,   20,     'b'),
  ('2024-01-01 07:00:10',   1111,   30,     'a')
;

select y.*,
    max(q) over(partition by item order by ts desc) as m,
    sum(quantity) over(partition by item, q) as s 
from
(
  select 
      x.*,
      case when r <= 2 then 1 else 0 end as q
  from
  (
      select 
          dense_rank() over(partition by item order by ts desc) r,
        *
      from ItemQty
  ) x
) y
order by ts desc
© www.soinside.com 2019 - 2024. All rights reserved.