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

SQL左连接后结果周期范围不符问题排查

问题排查:左连接后结果周期范围异常

我需要通过client_key和period关联all_clients与data_db表,基于all_clients按客户和周期计算统计值。已知all_clients最小周期为2020/05,但最终结果表df2的最小周期却是2019/08,不符合预期。关联代码如下:

create table empl_df_bog as 
       with df1 as (select c.compinn
               ,c.client_key
               ,c.period
               ,max((case when nvl(s.dpd_max,0) > 90 then 1 else 0 end)) is_default 
               from all_clients c
               left join data_db s on c.client_key = s.client_key and 
               s.year_month between to_char(add_months(to_date(c.period,'YYYY/MM'), -12),'yyyy/mm') 
               and to_char(add_months(to_date(c.period,'YYYY/MM'), -1),'yyyy/mm')
               group by c.compinn, c.client_key, c.period)
,          df2 as(select compinn
              ,period
              ,avg(is_default) DR
              from df1
              group by compinn, period)
              select * from df2

错误原因分析

  1. 隐式关联逻辑变更:数据库执行计划优化时,可能将左连接逻辑转换为内连接或其他关联类型,导致data_db中更早的year_month反向引入了不符合预期的周期值。
  2. 源表脏数据:all_clients表中可能存在period早于2020/05的记录,只是之前的统计查询未覆盖到这些脏数据。

修正方案

方案1:强制过滤源表周期

在all_clients的查询中直接添加周期过滤条件,从源头上确保只处理符合要求的周期数据:

create table empl_df_bog as 
       with df1 as (select c.compinn
               ,c.client_key
               ,c.period
               ,max((case when nvl(s.dpd_max,0) > 90 then 1 else 0 end)) is_default 
               from all_clients c
               -- 限定all_clients周期不早于2020/05
               where c.period >= '2020/05'
               left join data_db s on c.client_key = s.client_key and 
               s.year_month between to_char(add_months(to_date(c.period,'YYYY/MM'), -12),'yyyy/mm') 
               and to_char(add_months(to_date(c.period,'YYYY/MM'), -1),'yyyy/mm')
               group by c.compinn, c.client_key, c.period)
,          df2 as(select compinn
              ,period
              ,avg(is_default) DR
              from df1
              group by compinn, period)
              select * from df2

方案2:验证源表数据

先执行以下查询确认all_clients表的实际周期范围,排查是否存在脏数据:

select min(period) as min_period, max(period) as max_period from all_clients;

如果查询结果显示min_period确实早于2020/05,需要先清理all_clients中的脏数据,再执行统计逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:48:46