SQL查询以获取最大日期的行

时间:2020-07-31 12:39:15

标签: sql oracle oracle-sqldeveloper

我有一个查询,该查询为我提供了多个日期不同的员工行-

PROCESSSTARTDATE  EMPLOYEENUMBER RUN_ACTION  CURRENTAMOUNT
10-JUL-2020          27             D           10
11-JUL-2020          27             C           10.3
12-JUL-2020          27             F           11.6

11-JUL-2020          28             C           2.8
12-JUL-2020          28             F           2
13-JUL-2020          28             G           11.6

用于上述输出的查询-

Select pa.processstartdate,
paam.assignment_number EMPLOYEENUMBER,
pr.RUN_ACTION RUN_ACTION,
pa.CURRENTAMOUNT
from
per_all_actions pa,
per_all_assignments_m paam,
per_run pr
where pa.action_id = pr.action_id
and paam.assignment_id = pr.assignment_id

我只想要输出中的最大PROCESSSTARTDATE行。即

PROCESSSTARTDATE  EMPLOYEENUMBER RUN_ACTION  CURRENTAMOUNT
12-JUL-2020          27             F           11.6
13-JUL-2020          28             G           11.6

该怎么做?

3 个答案:

答案 0 :(得分:0)

在Oracle中,可以将聚合与keep关键字一起使用:

Select max(pa.processstartdate) as processstartdate,
       paam.assignment_number as EMPLOYEENUMBER,
       max(pr.RUN_ACTION) keep (dense_rank first order by pa.processstartdate desc) as RUN_ACTION,
       max(pa.CURRENTAMOUNT) keep (dense_rank first order by pa.processstartdate desc) as current_amount
from per_all_actions pa join
     per_run pr
     on pa.action_id = pr.action_id join
     per_all_assignments_m paam
     on paam.assignment_id = pr.assignment_id
group by paam.assignment_number

答案 1 :(得分:0)

您可以使用rank获取每个员工的最新行。附带说明一下,隐式连接(from子句中有多个表)是一种过时的做法,您可能应该使用显式join子句:

SELECT processstartdate, employeenumber, run_action, currentamount
FROM   (SELECT pa.processstartdate AS processstartdate,
               paam.assignment_number AS employeenumber,
               pr.run_action AS run_action,
               pa.currentamount AS currentamount,
               RANK() OVER (PARTITION BY paam.assignment_number 
                            ORDER BY processstartdate DESC) AS rk
        FROM   per_all_actions pa
        JOIN   per_run pr ON pa.action_id = pr.action_id
        JOIN   per_all_assignments_m paam ON paam.assignment_id = pr.assignment_id) t
WHERE  rk = 1

答案 2 :(得分:0)

使用row_number窗口子句添加一个伪列,按员工分组,按日期降序。

然后将其包装在只看到row_number = 1的sub_query中。

类似:

select *
  from (select pa.processstartdate,
               paam.assignment_number EMPLOYEENUMBER,
               pr.RUN_ACTION RUN_ACTION,
               pa.CURRENTAMOUNT,
               row_number() over(partition by paam.assignment_number order by pa.processstartdate desc) as rn
          from per_all_actions pa, per_all_assignments_m paam, per_run pr
         where pa.action_id = pr.action_id
           and paam.assignment_id = pr.assignment_id) t
 where t.rn = 1