获取上周数据时遇‘ERROR: invalid value for "YYYY"...’错误的解决方法
问题解决:invalid value for "YYYY" in source string 错误
这个错误和数据滞后无关,核心原因是**start_datetime字段中存在不符合YYYYMMDDHH24MISS格式的数据**,导致to_date函数无法正常解析。比如字段值长度不是14位、包含非数字字符、年份部分不是四位有效数字等。
第一步:排查脏数据
先找出不符合格式的记录,确认问题类型(以PostgreSQL为例):
select start_datetime from your_table -- 检查长度是否为14位(YYYYMMDDHH24MISS标准长度) where length(start_datetime) != 14 -- 检查是否全为数字 or not start_datetime ~ '^\d{14}$';
第二步:解决方案
方案1:清理脏数据
直接修正或删除不符合格式的记录,确保所有start_datetime值都是14位数字的合法日期格式。这是最彻底的解决方式。
方案2:容错处理(无法立即清理数据时)
如果暂时无法清理脏数据,使用数据库的容错日期解析函数跳过错误数据:
- 若使用Snowflake:用
try_to_date函数,解析失败时返回null,不会抛出错误:
where try_to_date(start_datetime, 'YYYYMMDDHH24MISS') >= date_trunc('week', current_date) - interval '7 days' and try_to_date(start_datetime, 'YYYYMMDDHH24MISS') < date_trunc('week', current_date)
- 若使用PostgreSQL:用
case语句先判断格式,再解析:
where case when start_datetime ~ '^\d{14}$' then to_date(start_datetime, 'YYYYMMDDHH24MISS') else null end >= date_trunc('week', current_date) - interval '7 days' and case when start_datetime ~ '^\d{14}$' then to_date(start_datetime, 'YYYYMMDDHH24MISS') else null end < date_trunc('week', current_date)
另外注意:原代码中date_trunc('week', current_date) -7的写法在部分数据库中可能不规范,建议改为date_trunc('week', current_date) - interval '7 days'确保兼容性。
内容的提问来源于stack exchange,提问作者Bertie Shaw
相关产品推荐
相关产品推荐

