【发布时间】:2021-11-21 16:11:41
【问题描述】:
我有如下表格
id | product_id | product_type_id | closing_stock | created_dttm
-------------------------------------------------------------------------
1 2 1 0 21-Nov-21
2 2 2 9 21-Nov-21
3 2 3 11 21-Nov-21
4 2 1 7 20-Nov-21
我需要通过 created_dttm desc 获取具有唯一 product_id 和 product_type_id 顺序的最后或最近记录。
所以我有以下查询,但由于关闭库存参数> 0,它没有获取最后或最近输入的数据。
select distinct on(product_id, product_type_id) *
from daily_stock
where product_id = 2
and product_type_id in (1, 2, 3)
and closing_stock > 0
order by product_id, product_type_id , created_dttm desc
id | product_id | product_type_id | closing_stock | created_dttm
-------------------------------------------------------------------------
1 2 2 9 21-Nov-21
2 2 3 11 21-Nov-21
3 2 1 7 20-Nov-21
但我期待以下结果
id | product_id | product_type_id | closing_stock | created_dttm
------------------------------------------------------------------------------------
2 2 2 9 21-Nov-21
3 2 3 11 21-Nov-21
【问题讨论】:
-
与您的问题无关,但是:Postgres 9.1 是no longer supported,您应该尽快计划升级。
-
你为什么不删除条件
closing_stock > 0? -
我需要收盘价 > 0 的行,所以我添加了那个条件
-
但在您的预期结果中,id=1 的行的 close_stock=0
-
是的,我只需要关闭库存> 0的最新记录
标签: sql postgresql where-clause distinct-on