选择具有最大日期的行以设置帐号

时间:2017-08-18 22:21:56

标签: sql db2

我有一个包含三列的表,ACCT_NUM,EFF_DATE和ACCT_NAME。唯一键是ACCT_NUM和EFF_DATE。

例如数据,

ACCT_NUM EFF_DATE ACCT_NAME 0000100200 2017-01-01 Account 1 0000100200 2017-03-10 Account A 0000100200 2017-08-22 Account Alpha 0000100230 2017-01-01 Account C 0000100230 2017-05-20 Account Charlie

以及更多帐户。

希望使用in子句为一组帐号获取基于Eff_date的最新帐户名称。

select * from ACCT_MASTER where acct_num in ('0000100200', '0000100230') order by eff_date fetch 1 row only; -- but this query returns only one account

喜欢获取以下数据,

ACCT_NUM ACCT_NAME 0000100200 Account Alpha 0000100230 Account Charlie

2 个答案:

答案 0 :(得分:1)

在标准SQL中,您可以执行

select t1.*
from your_table t1
join
(
    select acct_num, max(eff_date) as dt
    from your_table
    group by acct_num
) t2 on t1.acct_num = t2.acct_num
    and t1.eff_date = t2.dt

答案 1 :(得分:0)

您可以使用row_number()

select am.*
from (select am.*,
             row_number() over (partition by acct_num order by eff_date desc) as seqnum
      from ACCT_MASTER am
      where acct_num in ('0000100200', '0000100230') 
     ) am
where seqnum = 1
order by eff_date
fetch 1 row only