Bora Çolakoğlu
Bora Çolakoğlu

Reputation: 69

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. 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. 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?

Upvotes: 0

Views: 869

Answers (3)

Mikhail Berlyant
Mikhail Berlyant

Reputation: 172993

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)

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

I would use RANK here along with a scalar subquery:

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:

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;

Upvotes: 1

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 31993

use 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

Upvotes: 0

Related Questions