You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:12:15