【问题标题】:how to filter selected query with another condition in postgresql如何在postgresql中使用另一个条件过滤选定的查询
【发布时间】: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


【解决方案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;

请参阅demo。

【讨论】:

  • 简单直接的解决方案..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 2018-06-18
  • 2014-12-13
  • 1970-01-01
相关资源
最近更新 更多