需要获取最新日期的数据

时间:2016-07-04 07:25:29

标签: oracle postgresql greatest-n-per-group amazon-redshift

我有下表,

----------------------------------------
|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

从上表中,我需要获得以下输出。如果" pstatus"不是null我需要获取与每个person_id相对应的记录,如果pstatus为null,则需要获取最新日期的记录。

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

  1         27|6|2016     Died      null

  2         29|6|2016     null      DFWE

  3         29|6|2016     Died      null

3 个答案:

答案 0 :(得分:0)

您可以使用row_number窗口函数枚举每个person_id的记录,并选择" last" one - 要么具有非空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

答案 1 :(得分:0)

你需要使用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

答案 2 :(得分:0)

试试这个;)

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)