查询查找最后两个批准日期的记录

时间:2014-07-22 11:35:41

标签: sql sybase sybase-ase

我有两个表,PlanPlan_Log。它们的结构如下所示:

表:Plan

Id  PlanName  PlanApprovalDate         PlanStatus
--  --------  -----------------------  ----------
1   abc       18-04-2014 15:48:22.790  A
2   def       19-07-2014 15:48:22.790  A

表:Plan_Log

Id  PlanName  PlanApprovalDate
--  --------  -----------------------
1   abc       18-04-2014 15:48:22.790
2   abc       17-04-2014 15:48:22.790
3   abc       15-04-2014 15:48:22.790 
4   def       19-07-2014 15:48:22.790
5   def       18-07-2014 15:48:22.790
6   def       17-07-2014 15:48:22.790   

我希望从这些记录中检索每个计划及其最近的两个PlanApprovalDate记录。另外,我需要确保这些计划是活动的(PlanStatus)。所以我的最终列表应该检索:

ID  PlanName  PlanApprovalDate
--  --------  -----------------------
1   abc       18-04-2014 15:48:22.790
2   abc       17-04-2014 15:48:22.790
3   def       18-07-2014 15:48:22.790 
4   def       19-07-2014 15:48:22.790

如何实现这一结果?

我正在使用Sybase ASE 12.5.4

1 个答案:

答案 0 :(得分:0)

您可以非常轻松地使用row_number()执行此操作(某些版本的Sybase支持):

select id, plan_name, PlanApprovalDate
from (select pl.*,
             row_number() over (partition by plan_name order by PlanApprovalDate desc
                               ) as seqnum
      from plan_log pl
     ) pl
where seqnum <= 2;

没有Windows功能,您可以通过不同方式执行此操作。这是一个在where子句中使用相关子查询的方法:

select id, plan_name, PlanApprovalDate
from plan_log pl
where 2 >= (select count(*)
            from plan_log pl2
            where pl2.plan_name = pl.plan_name and
                  pl2.PlanApprovalDate >= pl.PlanApprovalDate
           );