我想要满足数量要求的送货单物品的ID.这些项目必须按特定的顺序排序,如先进先出后进先出

示例表:

CREATE TABLE delivery_note_item (id BIGINT PRIMARY KEY, stock_item_id BIGINT, quantity BIGINT, received TIMESTAMP);
INSERT INTO delivery_note_item (id, stock_item_id, quantity, received) 
VALUES 
(1, 1, 5, '2023-08-01 00:00:00'),
(2, 1, 3, '2023-08-02 00:00:00'),
(3, 1, 9, '2023-08-03 00:00:00'), 
(4, 1, 8, '2023-08-04 00:00:00');

因此,如果FIFO(按接收到的ASC排序)需要10个STOCK_ITEM(id=1),则查询应该返回1,2,3. 如果我需要10个HIFO的STOCK_Items,那么输出应该是4,3.

有谁能帮我找到解决这个问题的办法吗?

我不确定是使用While循环还是使用CTE或REQURSIVE CTE更好? 谢谢

推荐答案

要根据数量检索x行,请使用sum()窗口函数计算运行总数,然后减go 数量:

select *
from (
  select *, sum(quantity) over (partition by stock_item_id order by received) - quantity as FIFO_running,
            sum(quantity) over (partition by stock_item_id order by received DESC) - quantity as LIFO_running
  from delivery_note_item
) as s
where stock_item_id = 1 and fifo_running <= 10

Demo here

Postgresql相关问答推荐

转换失败:(—122.763091,49.04676)转换为地理(位置)""

横向联接返回的行数太多

Select 所有数组类型和维度

无法继承BYPASSRLS

Postgres从spark触发post-write

在插入时创建一个触发器,在PostgreSQL中的另一个表上创建另一个触发器

supabase 中的交易

EF Core和npgsql连接池已被耗尽

TimescaleDB 连续聚合:如何存储连续聚合结果

UPDATE implies move across partitions

如何更改几何列的 SRID?

如何从 WSL 连接到 windows postgres 数据库

如何检索 PostgreSQL 数据库的 comments ?

如何将 DELETE 的返回值插入到 postgresql 中的 INSERT 中?

PostgreSQL:将时间戳转换为时间 - 或仅从时间戳列中检索时间

将属性添加到 Sequelize FindOne 返回的对象

你如何在postgresql中做mysqldump?

解释结果中的Recheck Cond是什么意思?

在 Postgres 中显示关系、序列和函数的默认访问权限

postgresql 删除级联