Hive SQL如何改写查询以包含acquiring_date为空的交易数据?
数据表
client_id | acquiring_date | transaction | date ----------+----------------+-------------+------- 123 | 202305 | 200 | 202306 123 | 202305 | 200 | 202206 123 | 202305 | 200 | 202203 123 | 202305 | 200 | 202201 789 | | 20 | 202202 890 | | 310 | 202201
问题分析
原查询的where条件在acquiring_date为空时,涉及该字段的比较运算结果为null,Hive会将null视为false,因此这部分行被过滤。需要调整条件,同时覆盖两种场景:
acquiring_date不为空时,筛选其前12个月内的交易数据acquiring_date为空时,直接保留该行数据
改写后的Hive SQL语句
select * from df where (acquiring_date is not null and date >= add_months(to_date(acquiring_date, 'yyyyMM'), -12) and date < to_date(acquiring_date, 'yyyyMM')) or acquiring_date is null;
补充说明
- 用
to_date将字符串格式的日期(如202305)转换为Hive日期类型,再通过add_months计算前12个月的日期,比直接用数字减法(acquiring_date - 100)更严谨,能避免特殊月份的计算误差。 - 如果坚持使用原数字减法的逻辑,也可以改写为:
select * from df where (acquiring_date is not null and date >= acquiring_date - 100 and date < acquiring_date) or acquiring_date is null;
内容的提问来源于stack exchange,提问作者Maths12
相关产品推荐
相关产品推荐

