select 行,包含所有最小值和给定值的下一个最大值

select rows with all min values and next max value of given value

我需要从 postgresql 获取数据,我需要 select 行符合以下条件。

id  type  total_quantity created_dttm [desc]

1    1    12            27-Jun-2021
2    1    32            26-Jun-2021
3    1    52            25-Jun-2021

需要获取与查询中给定值匹配的所有行。如果我将值设为 24 ,那么我需要获取所有行 <= 24 和下一个最大值 24 ..order by created_dttm desc order

所以我只需要得到两行..

id  type  total_quantity created_dttm [desc]

1    1    12            27-Jun-2021
2    1    32            26-Jun-2021

我尝试了两列的总和,但这行不通,因为我正在寻找一个值范围之间的行,条件是 select 所有小于给定值的行 + select给定值的下一个最大值...对于给定类型...

编辑:- 查询必须根据 created_dttm desc

的类型和顺序获取

如果您的数量正在减少,则使用 lead():

select t.*
from (select t.*,
             lead(total_quantity) over (order by created_dttm) as next_total_quantity
      from t
     ) t
where next_total_quantity is null or
      next_total_quantity <= 24;

Here 是一个 db<>fiddle.

使用 MIN() window 函数,您可以获得每个 type 大于 24:

的最小值 total_quantity
SELECT id, type, total_quantity, created_dttm
FROM (
  SELECT *, MIN(total_quantity) FILTER (WHERE total_quantity > 24) OVER (PARTITION BY type) qty
  FROM tablename
) t
WHERE total_quantity <= qty

如果您只想要 type = 1 的结果:

SELECT id, type, total_quantity, created_dttm
FROM (
  SELECT *, MIN(total_quantity) FILTER (WHERE total_quantity > 24) OVER () qty
  FROM tablename
  WHERE type = 1
) t
WHERE total_quantity <= qty

或者:

SELECT *
FROM tablename
WHERE type = 1 
  AND total_quantity <= (SELECT MIN(total_quantity) FROM tablename WHERE total_quantity > 24)

参见demo