我有如下表格
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 順序的最后或最近記錄。
所以我有以下查詢,但由于closure_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
uj5u.com熱心網友回復:
該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;
請參閱演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/362592.html
標籤:sql PostgreSQL的 where子句 独特的
