使用rank / group by来重新获取oracle中的atest记录

时间:2016-01-05 03:55:05

标签: sql oracle group-by rank

我有以下查询,它给了我附上这篇文章的结果。我想只带最新状态更新的记录。请注意,没有日期列来标识更新后的状态。我们唯一的方法就是分组(IDK,IDFK,STATUS)。请注意,一个CODE可以更新次数。我希望更新最新状态(因此每个状态更新的每个代码基本上都是最大IDFK)。所以从下面的屏幕截图我应该得到三个记录(即我们的IDFK是1418853,1418939,1419017)

注意:IDK和IDFK可能/可能没有按顺序排列。

    SELECT ID.ISS_CD CODE,
         IF.ISS_DIM_KY IDK,
         IF.LOAD_TS,
         IE.ISS_FACT_DIM_KY IFDK,
         IE.SUSPN_STS
 FROM ccm_mi_rds_owner.iss_fact if
         INNER JOIN ccm_mi_rds_owner.iss_dim id ON (IF.ISS_DIM_KY = ID.ISS_DIM_KY)
         LEFT OUTER JOIN ccm_mi_rds_owner.iss_fact_ext ie ON (IF.ISS_FACT_DIM_KY = IE.ISS_FACT_DIM_KY)
   WHERE IF.SRC_DIM_KY = 20  
   and IE.SUSPN_STS is not null
   and iss_cd in ('C0000182087' , 'C0000182142','C0000182999')``

Result of the Query

1 个答案:

答案 0 :(得分:0)

Oracle的分析功能非常适合这种情况。 试试以下内容:

select
  *
from
(
    SELECT ID.ISS_CD CODE,
         IF.ISS_DIM_KY IDK,
         IF.LOAD_TS,
         IE.ISS_FACT_DIM_KY IFDK,
         IE.SUSPN_STS,
         row_number() over (partition by idk order by idfk desc ) as rn
 FROM ccm_mi_rds_owner.iss_fact if
         INNER JOIN ccm_mi_rds_owner.iss_dim id ON (IF.ISS_DIM_KY = ID.ISS_DIM_KY)
         LEFT OUTER JOIN ccm_mi_rds_owner.iss_fact_ext ie ON (IF.ISS_FACT_DIM_KY = IE.ISS_FACT_DIM_KY)
   WHERE IF.SRC_DIM_KY = 20  
   and IE.SUSPN_STS is not null
   and iss_cd in ('C0000182087' , 'C0000182142','C0000182999')
)
where
  rn = 1