每条数据都要最新一条有值的数据去重

现在我有三行数据,我想获取每个字段最新一条并且有值的数据,最后的结果应该是黄色的那一行

这种SQL该怎么去写呢?

案例数据如下

create table tbl1(
id varchar2(10),
name varchar2(10),
age varchar2(5),
address varchar2(10),
phone varchar2(20),
"date" varchar2(20)
);


insert into tbl1 values('1','lisa','16','','188xxxxxxxx','20230105');
insert into tbl1 values('1','lisa','17','CHINA','','20230106');
insert into tbl1 values('1','lisa','','','','20230107');

因为我们要的每个列的最新的一条“有值”的数据,并且把这三条聚合成一条数据。

那么就可以先根据主键进行分组,然后每一列去row_number()开窗,再加上一个限定条件不能为空,每一列换成一个子查询的方式来就可以解决这个问题了

办法SQL如下

 select 
       (select id 
       from (
            (select a.*,row_number() over(partition by id order by "date" desc) as idrn 
        from tbl1 a 
        where id is not null)
        )a where main.id = a.id 
        and idrn = 1)                                           as id,
        (select name 
       from (
            (select a.*,row_number() over(partition by id order by "date" desc) as namern 
        from tbl1 a 
        where name is not null)
        )b where main.id = b.id 
        and namern = 1)                                         as name,
         (select age 
       from (
            (select a.*,row_number() over(partition by id order by "date" desc) as agern 
        from tbl1 a 
        where age is not null)
        )b where main.id = b.id 
        and agern = 1)                                          as age,
        (select address 
       from (
            (select a.*,row_number() over(partition by id order by "date" desc) as addressrn 
        from tbl1 a 
        where address is not null)
        )b where main.id = b.id 
        and addressrn = 1)                                          as address,
         (select phone 
       from (
            (select a.*,row_number() over(partition by id order by "date" desc) as phonern 
        from tbl1 a 
        where phone is not null)
        )b where main.id = b.id 
        and phonern = 1)                                          as phone,
        (select "date" 
       from (
            (select a.*,row_number() over(partition by id order by "date" desc) as datern 
        from tbl1 a 
        where phone is not null)
        )b where main.id = b.id 
        and datern = 1)                                          as "date"
 from tbl1 main
 group by id

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值