簡體   English   中英

如何在 postgresql 中使用另一個條件過濾選定的查詢

[英]how to filter selected query with another condition in postgresql

我有如下表

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

WHERE子句在DISTINCT ON之前應用,過濾掉所有帶有closing_stock = 0的行。
因此,如果對於product_idproduct_type_id的組合而言, closing_stock = 0的任何行是最新的,則此組合不會從結果中排除。

從查詢中刪除條件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() window function:

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;

請參閱演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM