根据日期列选择最新数据

时间:2018-04-17 21:35:45

标签: sql db2-400

我有一张桌子ACCT,

COMPANY    ACCOUNT    EFFDT        NAME
25         1001       2015-12-01   ABC Ltd.
25         1001       2012-01-01   ABC Inc
30         1001       2012-01-01   ABC Inc
10         1001       2012-01-01   ABC Inc
10         3800       2011-05-01   RAC Corp
25         3800       2011-05-01   RAC Corp
30         3800       2011-05-01   RAC Corp

我正在尝试根据帐户的EFFDT列获取一组帐户的最后一条记录#

我正在寻找的结果是,

| 25  | 1001  | 2015-12-01   | ABC Ltd.
| 30  | 3800  | 2011-05-01   | RAC Corp

我尝试过使用,

select * 
  from acct t1 
    inner join (
        select account as a, max(effdt) as b, max(company) as c 
          from acct 
          where account in (1001, 3800) 
          group by account
        ) t2 
      on t1.account = t2.a 
        and t1.effdt = t2.b 
        and t1.company = t2.c;

但我得到了,

| 30  | 3800  | 2011-05-01   | RAC Corp

2 个答案:

答案 0 :(得分:2)

使用ROW_NUMBER

https://chartio.com/resources/tutorials/how-to-use-row_number-in-db2/

  SELECT
      company,
      account,
      effdt,
      name
    FROM (SELECT
      company,
      account,
      effdt,
      name,
      ROW_NUMBER() OVER (PARTITION BY account ORDER BY effdt DESC, company DESC) rn  
    FROM acct) x
    WHERE x.rn = 1

答案 1 :(得分:1)

这应该有效:

select max(a.company), a.account, a.effdt, a.name from acct a
join(select account, max(EFFDT) as m  
    from acct 
    group by account)
b on a.account = b.account and a.EFFDT = m  
group by a.account, a.effdt, a.name