简体   繁体   中英

Select max date in one column based on unique dates in another

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.

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;

Are you looking at max()

select max(load_dt) as load_dt, fore_dt, max(data) 
    from yourtable
   group by fore_dt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM