这是我的桌子的样子:
appl_db_srvr_xref_id secrty_ctl_id assmt_dt cmdb_id secrty_ctl_elemnt_impmtn_cd
180 43 1/1/2018 227 N
180 43 9/31/2018 227 Y
179 28 1/1/2018 710 N
179 29 2/2/2018 710 N
179 43 3/3/2018 710 N
我需要的是按日期分组(appl_db_srvr_xref_id,secrty_ctl_id和cmdb_id),然后返回最新行。因此,在这种情况下,我想返回:
180 43 227 Y
179 28 710 N
179 29 710 N
179 43 710 N
我正在尝试的是:
SELECT secrty_ctl_id,
appl_db_srvr_xref_id,
cmdb_id,
assmt_dt
FROM tablename
GROUP BY
secrty_ctl_id,
appl_db_srvr_xref_id,
cmdb_id
ORDER BY assmt_dt desc
答案 0 :(得分:1)
使用row_number()分析函数:
select
secrty_ctl_id,
appl_db_srvr_xref_id,
cmdb_id,
assmt_dt
from
(
SELECT secrty_ctl_id,
appl_db_srvr_xref_id,
cmdb_id,
assmt_dt,
row_number() over (partition by appl_db_srvr_xref_id, secrty_ctl_id, cmdb_id order by assmt_dt desc) rn
FROM tablename
)s
where rn=1;