需要获取最新日期的数据

Need to fetch data with latest date

我关注table,

----------------------------------------
|person_id   date        pstatus    px1 |
---------------------------------------- 
  1         29|6|2016     null      089E

  1         27|6|2016     Died      null

  2         29|6|2016     null      DFWE

  2         27|6|2016     null      WEWE

  3         29|6|2016     Died      null

根据上面的 table,我需要得到以下输出。如果 "pstatus" 不为空,我需要获取对应于每个 person_id 的记录,如果 pstatus 为空,则需要获取最新日期的记录。

----------------------------------------
|person_id   date        pstatus    px1 |
---------------------------------------- 

  1         27|6|2016     Died      null

  2         29|6|2016     null      DFWE

  3         29|6|2016     Died      null

您可以使用 row_number window 函数来枚举每个 person_id 和 select "last" 的记录 - 要么有一个 not-空 pstatus,或最新日期:

SELECT person_id, date, pstatus, px1
FROM   (SELECT person_id, date, pstatus, px1,
               ROW_NUMBER() OVER (PARTITION BY person_id
                                  ORDER BY CASE WHEN pstatus IS NOT NULL 
                                                THEN 0 
                                                ELSE 1 END ASC, 
                                           date DESC) AS rn
        FROM mytable) t
WHERE  rn = 1

您需要像这样使用 Row_Number() Over (Partition By ..) 来获取所需的数据

 with ss as (select 1 as pid , to_date('29.06.2016','dd.mm.yyyy') as dd,null as status, '089E' as px1 from dual union all
             select  1,to_date('27.06.2016','dd.mm.yyyy'),'Died',null from dual union all
             select  2,to_date('29.06.2016','dd.mm.yyyy'),null ,'DFWE' from dual union all
             select  2,to_date('27.06.2016','dd.mm.yyyy'),null ,'WEWE' from dual union all
             select  3,to_date('29.06.2016','dd.mm.yyyy'),'Died' ,null  from dual)
select * from (
select ss.*,
        Row_Number() Over (Partition By pid Order By status nulls last, dd desc) Rn
  from ss

  ) where Rn = 1

试试这个;)

select t1.*
from yourtable t1
join (
    select max(date) as "date", max(pstatus) as pstatus, person_id
    from yourtable
    group by person_id
) t2
on t1.person_id = t2.person_id
and ((t2.pstatus is not null and t1.pstatus = t2.pstatus) or t1.date = t2.date)