Reputation: 1190
I have a data set that is loaded into the database every time the forecast for that particular date is changed. I need to be able to select the last load_dt for each fore_dt. An example data set is below:
load_dt, fore_dt, data,
1/1/2017, 1/14/2017, 5,
1/5/2017, 1/14/2017, 8,
1/5/2017, 1/15/2017, 9,
1/15/2017, 1/15/2017, 10,
1/17/2017, 1/16/2017, 5
Results should look like:
load_dt, fore_dt, data,
1/5/2017, 1/14/2017, 8,
1/15/2017, 1/15/2017, 10,
1/17/2017, 1/16/2017, 5
The actual data set is much more complex and has a lot of rows. In the query, I need to be able to select where fore_dt between date and date.
Upvotes: 0
Views: 106
Reputation: 13969
Are you looking at max()
select max(load_dt) as load_dt, fore_dt, max(data)
from yourtable
group by fore_dt
Upvotes: 0
Reputation: 39507
You can use window function row_number
to assign sequence number to row within each fore_dt in the order of decreasing load_dt and then select the first row using a simple where clause:
select *
from (
select t.*,
row_number() over (
partition by fore_dt order by load_dt desc nulls last
) as seqnum
from your_table t
) t
where seqnum = 1;
Upvotes: 1