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

RedShift中to_char(to_date)函数在JOIN查询中格式转换异常求助

Fixing the yyyyMMdd to yyyy-MM-dd Conversion Issue in RedShift JOIN Queries

Let's break down what's going wrong here and how to fix it quickly:

The Root Cause

In your JOIN query, you're using the wrong format mask for to_date()!

Your s.date column stores dates as yyyyMMdd strings (like 20150614), but you're telling RedShift to parse it as yyyy-MM-dd:

to_date(s.date, 'yyyy-MM-dd')

This misalignment causes RedShift to misinterpret the string, leading to that nonsensical 139496-03-09 date value. Your single-test query was correct because you used the right mask (yyyyMMdd), but you didn't carry that over to the JOIN.

Fixed Query

Just update the format mask in your JOIN query to match the actual storage format of s.date:

select 
  to_char(to_date(s.date, 'yyyyMMdd'),'yyyy-MM-dd') as SDate, 
  s.date, 
  e.code, 
  s.id 
from student as s 
join event as e on e.code >= s.id 
order by SDate asc 
limit 1

This should return the correct 2015-06-14 for SDate as expected.

Alternative: String Manipulation (No Date Conversion)

If you want to avoid date parsing entirely (which can be more efficient for fixed-length date strings), you can use string concatenation instead:

select 
  left(s.date, 4) || '-' || substring(s.date, 5, 2) || '-' || right(s.date, 2) as SDate,
  s.date,
  e.code,
  s.id
from student as s
join event as e on e.code >= s.id
order by SDate asc
limit 1

This works because your input is always 8 characters long:

  • left(s.date,4) grabs the year (2015)
  • substring(s.date,5,2) grabs the month (06)
  • right(s.date,2) grabs the day (14)
  • We just add the - separators to get the desired format.

Why the Weird Date Happened?

When RedShift gets a string that doesn't match the specified format mask, it falls back to "lenient parsing" which can produce unexpected results. In your case, trying to parse 20150614 as yyyy-MM-dd confuses the parser—it can't find the - separators, so it tries to interpret the string in unintended ways, leading to that absurdly large year value.

内容的提问来源于stack exchange,提问作者user036

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:49:13