我有一个数据集,每次更改特定日期的预测时都会加载到数据库中。我需要能够为每个fore_dt选择最后一个load_dt。下面是一个示例数据集:
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
结果应该如下:
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
实际数据集要复杂得多且行数很多。在查询中,我需要能够选择日期和日期之间的fore_dt。
答案 0 :(得分:2)
您可以使用窗口函数row_number
按减少load_dt的顺序将序列号分配给每个fore_dt中的行,然后使用简单的where子句选择第一行:
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;
答案 1 :(得分:0)
你在看max()
吗?select max(load_dt) as load_dt, fore_dt, max(data)
from yourtable
group by fore_dt