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
相关推荐
麦聪聊数据18 小时前
企业数据流通与敏捷API交付实战(五):异构数据跨库联邦与零代码发布
数据库·sql·低代码·restful
生瓜硬劈..20 小时前
SQL 调优全解:从 20 s 到 200 ms 的 6 步实战笔记
java·笔记·sql
颜颜yan_20 小时前
让数据库学会说“不“——金仓 SQL 防火墙深度解析
数据库·sql
霖霖总总20 小时前
[小技巧52]从 SQL 到结果:MySQL 8.0 查询执行全流程深度剖析
sql·mysql
輕華20 小时前
【零基础入门】SQL 核心语法精讲:外键约束与多表查询全解析(进阶篇)
数据库·sql
white-persist1 天前
【渗透测试 红队】Netcat(NC)渗透实战全指南详解
开发语言·数据库·python·sql·算法·web安全·网络安全
橘子编程1 天前
Hive大数据实战指南:从入门到精通
大数据·hive·hadoop
麦聪聊数据1 天前
企业数据流通与敏捷API交付实战(四):DaaS与SQL2API
数据库·sql·低代码·restful
仗剑_走天涯1 天前
hadoop 执行mr任务出现找不到主类或无法加载主类解决方案
hadoop·mr
lingggggaaaa1 天前
PHP原生开发篇&SQL注入&数据库监控&正则搜索&文件定位&静态分析
数据库·sql·安全·web安全·php