如何在 sql 中获取最大日期的最小值?

How to get min value at max date in sql?

我有一个带有快照数据的 table。它具有 productid 和日期以及数量列。我需要在最大日期中找到最小值。比方说,我们有产品 X:X 在 Y 日期有最后一个快照,但它在 Y 有两个快照,数量值分别为 9 和 8。我需要得到

product_id | date | quantity
     X        Y       8

到目前为止我想到了这个。

select 
  productid
  , max(snapshot_date) max_date
  , min(quantity) min_quantity
from snapshot_table
group by 1

它有效,但我不知道为什么。为什么这不会为每个日期带来最小值?

使用row_number()

  with cte as (select *, 
  row_number() over(partition by product_id order by date desc) rn 
 from table_name) select * from cte where rn=1

我会在这里使用 RANK 以及标量子查询:

WITH cte AS (
    SELECT *, RANK() OVER (ORDER BY quantity) rnk
    FROM snapshot_table
    WHERE snapshot_date = (SELECT MAX(snapshot_date) FROM snapshot_table)
)

SELECT productid, snapshot_date, quantity
FROM cte
WHERE rnk = 1;

请注意,此解决方案迎合了两条或更多条记录碰巧因最近的记录中数量较少而被绑定的可能性。

编辑: 我们可以通过取消 CTE 并使用 QUALIFY 子句来简化 RANK:

SELECT productid, snapshot_date, quantity
FROM snapshot_table
WHERE snapshot_date = (SELECT MAX(snapshot_date) FROM snapshot_table)
QUALIFY RANK() OVER (ORDER BY quantity) = 1;

同时考虑以下方法

select distinct product_id, 
  max(snapshot_date) over product as max_date,
  first_value(quantity) over(product order by snapshot_date desc, quantity) as min_quantity
from your_table
window product as (partition by product_id)