如何根据两个不同的属性选择最新的行?

时间:2017-12-06 20:48:32

标签: sql database oracle

我需要为我的员工选择以下交易(109,154,982,745)的最新活动代码(A,V,W,J)。我需要知道我的员工上次交易(来自列表)有哪些活动代码。有2个表涉及员工ID的连接。 表1:

|Emp_id  |  STUFF
|  1     |  stuff
|  2     |  stuff
|  3     |  stuff

表2:

|Emp_id   |  date      | act_code   |  trans 
|   1     |  1/1/17    |   A        |    109
|   1     |  3/4/12    |   X        |    203
|   1     |  2/14/09   |   A        |    154
|   2     |  1/1/17    |   A        |    110
|   2     |  6/6/13    |   V        |    109
|   3     |  12/13/16  |   J        |    982
|   3     |  11/23/14  |   W        |    745
|   4     |  12/13/16  |   X        |    154
|   4     |  11/23/14  |   W        |    745

我想回来的是:

|Emp_id  |  STUFF  |  date      | act_code   |  trans 
|  1     |  stuff  |  1/1/17    |   A        |    109
|  3     |  stuff  |  12/13/16  |   J        |    982

不会选择Emp 2,因为最新的trans不是正确的值之一。不会选择Emp 4,因为最新的act_code不是正确的值之一。任何人都知道如何解决这个问题?提前谢谢。

2 个答案:

答案 0 :(得分:1)

这是一种方式。

使用ROW_NUMBER()emp_id对行进行分区,然后按date排序:

SELECT t2.emp_id, t1.stuff, t2.date, t2.act_code, t2.trans,
       ROW_NUMBER() over (PARTITION BY t2.emp_id ORDER BY t2.date DESC) RN
FROM Table1 t1
JOIN Table2 t2 on t1.emp_id = t2.emp_id;

然后将其过滤为仅包含外部选择列表中值的最新记录(RN = 1):

SELECT emp_id, stuff, date, act_code, trans
FROM (
    SELECT t2.emp_id, t1.stuff, t2.date, t2.act_code, t2.trans,
           ROW_NUMBER() over (PARTITION BY t2.emp_id ORDER BY t2.date DESC) RN
    FROM Table1 t1
    JOIN Table2 t2 on t1.emp_id = t2.emp_id
     ) A
WHERE RN = 1
AND trans IN (109, 154, 982, 745)
AND act_code IN ('A', 'V', 'W', 'J');

答案 1 :(得分:0)

使用first_value获取act_code,trans的最新值,然后检查它们是否在指定列表中。

select * from (
select distinct t1.emp_id,t1.stuff,
max(t2.date) over(partition by t2.emp_id) as latest_date,
first_value(t2.act_code) over(partition by t2.emp_id order by t2.date desc) as latest_act_code,
first_value(t2.trans) over(partition by t2.emp_id order by t2.date desc) as latest_trans
from tbl1 t1
join tbl2 t2 on t1.emp_id=t2.emp_id
) t 
where latest_act_code in ('A','V','W','J') and latest_trans in (109, 154, 982, 745)