[英]How to get min value at max date in sql?
I have a table with snapshot data.我有一个包含快照数据的表。 It has productid and date and quantity columns.
它具有 productid 和日期以及数量列。 I need to find min value in the max date.
我需要在最大日期中找到最小值。 Let's say, we have product X: X had the last snapshot at Y date but it has two snapshots at Y with 9 and 8 quantity values.
比方说,我们有产品 X:X 在 Y 日期有最后一个快照,但它在 Y 有两个快照,数量值分别为 9 和 8。 I need to get
我需要得到
product_id | date | quantity
X Y 8
So far I came up with this.到目前为止,我想出了这个。
select
productid
, max(snapshot_date) max_date
, min(quantity) min_quantity
from snapshot_table
group by 1
It works but I don't know why.它有效,但我不知道为什么。 Why this does not bring min value for each date?
为什么这不会为每个日期带来最小值?
I would use RANK
here along with a scalar subquery:我会在这里使用
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;
Note that this solution caters to the possibility that two or more records happened to be tied for having the lower quantity among those most recent records.请注意,此解决方案迎合了两条或更多条记录碰巧因最近的记录中数量较少而被绑定的可能性。
Edit: We could simplify by doing away with the CTE and instead using the QUALIFY
clause for the restriction on the RANK
:编辑:我们可以通过取消 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;
Consider also below approach还请考虑以下方法
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)
use row_number()使用 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.