1

我有如下表

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 顺序的最后或最近记录。

所以我有以下查询,但由于 close_stock 参数> 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
4

1 回答 1

1

WHERE子句在之前应用DISTINCT ON,过滤掉所有带有 的行closing_stock = 0
因此,如果任何行带有closing_stock = 0的组合是最新的,product_id并且product_type_id该组合不会被排除在结果之外。

从查询中删除条件closing_stock > 0并在获得结果后使用它:

select *
from (
  select distinct on(product_id, product_type_id) * 
  from daily_stock
  where product_id = 2 and product_type_id in (1, 2, 3)
  order by product_id, product_type_id, created_dttm desc
) t
where closing_stock > 0;

或者,使用row_number()窗口函数:

select *
from (
  select *, row_number() over (partition by product_id, product_type_id order by created_dttm desc) rn
  from daily_stock
  where product_id = 2
) t
where rn = 1 and closing_stock > 0;

请参阅演示

于 2021-11-21T17:04:57.273 回答