HIVE SQL 根据主键去重并实现其余字段分组聚合

相同个人id下所有字段按时间顺序补位,取首个不为空值

c 复制代码
--数据建表
drop table if exists db.tb_name;
create table if not exists db.tb_name
( id string
	,name string
	,tele string
	,email string
	,`date` string
)
;
insert overwrite table db.tb_name
values 
("32001","张三","23456789",null,"2023-07-18")
,("32001",null,null,"23456789@163.com","2023-07-19")
,("32002","李四",null,"23456876@qq.com","2023-07-18")
,("32003","王二",null,null,"2023-07-18")
,("32003",null,"9876789",null,"2023-06-18")
,("32003",null,null,"9876789@gmail.com","2023-07-18")
,("32004","刘五","987456798",null,"2023-07-18")
,("32004","刘七","1987456798",null,"2023-07-20")
;
c 复制代码
--distribute by 分区排序:类似MR中partition,进行分区,结合sort by使用

drop table if exists db.tb_name_new;
create table if not exists db.tb_name_new as
select id 
	,collect_list(`name`)[0] as `name`
	,collect_list(`tele`)[0] as `tele`
	,collect_list(`email`)[0] as `email`
	,collect_list(`date`)[0] as `date`
from 
(
select id
	,name
	,tele
	,email
	,`date`
from 
db.tb_name
distribute by id 
sort by id,`date` desc
) t 
group by id
;

*注意:此处是取的首个不为空(即不为null)的字段,所以在实际使用过程中应提前将空字符串转为null值。

c 复制代码
--剔除字符串中的不可见字符,若该字段中均为不可见字符或该字段为空字符串,则转为空
case when length(regexp_replace(col_name,'[\\x00-\\x08\\x0B-\\x0C\\x0E-\\x1F]+|\\s+',''))>0 
	then regexp_replace(col_name,'[\\x00-\\x08\\x0B-\\x0C\\x0E-\\x1F]+|\\s+','')
	else null end as new_col_name
相关推荐
余槐i6 小时前
PostgreSQL 函数索引报错 must be immutable:3种绕法与代价
数据库·后端·sql·postgresql·性能优化
数据工匠老o14 小时前
一张 5 亿行的表按月分区后,清理历史数据从几小时变成了几秒
数据库·sql
hwscom14 小时前
几分钟开防护,SQL和XSS注入全被护卫神挡住
数据库·sql·xss
挖掘狂人15 小时前
SQL 注入:一行代码如何撬开整个数据库
后端·sql·数据分析
用户849137175471615 小时前
数据库迁移总出问题?学会这个工具,让团队协作效率翻倍!
数据库·sql
打工仔折腾 AI16 小时前
SQL 编辑器不是高级记事本:KStudio 与 KSQL Developer 的建表与增删改查手法
数据库·人工智能·后端·python·sql·编辑器·ai agent 实战
Data analyse45616 小时前
用户路径SQL按会话起止时间聚合的方法
大数据·服务器·前端·数据库·人工智能·sql·数据分析
zh731417 小时前
sqlforge一个SQL 格式化与方言转换工具
数据库·sql
其实防守也摸鱼17 小时前
CTF Web 6 题全解 Writeup
linux·sql·学习·算法·安全·ctf·xss
小小龙学IT17 小时前
PostgreSQL 服务端机制与 SQL 实战深度解析:从 MVCC 到查询优化器
数据库·sql·postgresql