在字段中选择每个值组合的最新记录

时间:2015-08-26 12:33:17

标签: sql db2 greatest-n-per-group

查询目标: 我试图总共选择80条记录(20个州 - 每条记录4条记录)。每个州有大约20000条记录。理想情况下,我只想为活动类型和生产者类型代码的4种组合中的每一种选择最新的(使用ACTIVITY_TSP)记录。

实施例

STATE| ACTIVITY_TYPE | PRODUCER_TYPE_CD | ...
-------------------------------------------------------
MI   |     1         |  '01'            | ...
MI   |     1         |  '02'            | ...
MI   |     2         |  '01'            | ...
MI   |     2         |  '02'            | ...

表1:

AGENT_KEY
STATE
ACTIVITY_TYPE
...
ACTIVITY_TSP

表2:

AGENT_KEY
PRODUCER_TYPE_CD

2 个答案:

答案 0 :(得分:0)

JOIN GROUP BY

select STATE, ACTIVITY_TYPE, PRODUCER_TYPE_CD, MAX(ACTIVITY_TSP)
from table1 t1
  join table2 t2 on t1.AGENT_KEY = t2.AGENT_KEY
group by STATE, ACTIVITY_TYPE, PRODUCER_TYPE_CD

或许您想要所有table1和table2列?

select *
from table1 t1
  join table2 t2 on t1.AGENT_KEY = t2.AGENT_KEY
where not exists (select 1 from table1 t1b
                  where t1b.STATE = t1.STATE
                    and t1b.ACTIVITY_TYPE = t1.ACTIVITY_TYPE
                    and t1b.PRODUCER_TYPE_CD = t1.PRODUCER_TYPE_CD
                    and t1b.ACTIVITY_TSP > t1.ACTIVITY_TSP)

答案 1 :(得分:0)

使用row_number()

select t.*
from (select t1.*, t2.producer_type_cd,
             row_number() over (partition by t1.state, t1.activity_type, t2.PRODUCER_TYPE_CD
                                order by t1.ACTIVITY_TSP desc) as seqnum
      from table1 t1 join
           table2 t2
           on t1.agent_key = t2.agent_key
     ) t
where seqnum = 1;