根据最大序列号查询特定字段

时间:2016-12-06 19:39:21

标签: sql greatest-n-per-group

我有一个记录集,其中一些行是重复的。特别是,它们被复制到记录集的最后三行。在整个四行中,我想要的正确结果集包括第一行和最后一行。我希望这是因为对于特定的SARAPPD_TERM_CODE_ENTRY,所需的记录是SARAPPD_SEQ_NO值最大的记录。因此,第一行是因为对于该特定术语,序列号最多在一行和最后一行,因为序列号最大为六。图片和查询如下。

enter image description here

select ppd.sarappd_seq_no, ppd.sarappd_term_code_entry, ppd.sarappd_apdc_code, 
   dap. dap.saradap_term_code_entry, 
   spri.spriden_id, 
   t.sgbstdn_astd_code, t.* 
from sgbstdn t 
left join spriden spri on t.sgbstdn_pidm = spri.spriden_pidm
left join saradap dap on spri.spriden_pidm = dap.saradap_pidm
join sarappd ppd on dap.saradap_pidm = ppd.sarappd_pidm
where t.sgbstdn_astd_code not in ('AS', 'DS', 'WD', 'SU', 'LA') 
and t.sgbstdn_stst_code = 'AS'
and spri.spriden_change_ind is null
and spri.spriden_id = '123456789'
and (ppd.sarappd_apdc_code = 25 or ppd.sarappd_apdc_code = 30
or   ppd.sarappd_apdc_code =35)
and ppd.sarappd_term_code_entry = dap.saradap_term_code_entry

                      --where b.sarappd_term_code_entry = ppd.sarappd_term_code_entry)
order by ppd.sarappd_term_code_entry

我相信这是一个简单的"其中this =(select max())类型的查询,但我一直在尝试一些不同的东西,但没有任何工作。我没有得到我想要的结果。所以说,对此的任何帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER()

;WITH cte 
AS
(select 
   ROW_NUMBER() OVER (PARTITION BY SARAPPD_TERM_CODE_ENTRY ORDER BY SARAPPD_SEQ_NO DESC) AS RN
   ppd.sarappd_seq_no, 
   ppd.sarappd_term_code_entry, 
   ppd.sarappd_apdc_code, 
   dap. dap.saradap_term_code_entry, 
   spri.spriden_id, 
   t.sgbstdn_astd_code, t.* 
from sgbstdn t 
left join spriden spri on t.sgbstdn_pidm = spri.spriden_pidm
left join saradap dap on spri.spriden_pidm = dap.saradap_pidm
join sarappd ppd on dap.saradap_pidm = ppd.sarappd_pidm
where t.sgbstdn_astd_code not in ('AS', 'DS', 'WD', 'SU', 'LA') 
and t.sgbstdn_stst_code = 'AS'
and spri.spriden_change_ind is null
and spri.spriden_id = '123456789'
and (ppd.sarappd_apdc_code = 25 or ppd.sarappd_apdc_code = 30
or   ppd.sarappd_apdc_code =35)
and ppd.sarappd_term_code_entry = dap.saradap_term_code_entry
order by ppd.sarappd_term_code_entry) a


SELECT *
FROM cte WHERE rn = 1