一、题目
现有用户账户表,包含日期、用户id、用户余额,其中用户余额发生了缺失,需要进行补全。补全规则:如果余额为空则取之前最近不为空值进行填补。如果截止到最早日期都为空则补0;
二、思路
题目要求使用当天之前的余额进行补全,需要明确一点不是取前面一天而是取前面最近的不为空的余额。所以首先需要知道前面第一个余额不为空的是哪一天,可以使用max开窗获取,取到以后再关联那天的余额进行补全。知识点:max() over()
三、解答
select
t11.user_id,
t11.busi_date,
coalesce(t11.amount, t12.amount, 0) amount_fix,
t11.amount,
max_date
from (
select
user_id,
busi_date,
amount,
-- 取每个用户当前日期 最接近的余额不为空的日期
max(if(amount is not null, busi_date, null)) over(partition by user_id order by busi_date rows between unbounded preceding and current row) max_date
from mst.user_account_info
) t11
left join (
-- 关联替代日期的余额
select
user_id,
busi_date,
amount
from mst.user_account_info
) t12
on t11.user_id = t12.user_id
and t11.max_date = t12.busi_date结果:

数据
# 建表
--建表语句
create table user_account_info(
busi_date string COMMENT '日期',
user_id bigint COMMENT '用户ID',
amount bigint COMMENT '用户余额'
) COMMENT '用户账户表'
stored as parquet
;
-- 数据插入
insert into user_account_info(busi_date,user_id,amount) values
('2024-06-01',001,null),
('2024-06-02',001,100),
('2024-06-03',001,80),
('2024-06-04',001,null),
('2024-06-05',001,50),
('2024-06-06',001,30),
('2024-06-01',002,80),
('2024-06-02',002,null),
('2024-06-03',002,null),
('2024-06-04',002,null),
('2024-06-05',002,50),
('2024-06-06',002,30);注:题目获取自网络
评论