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

SQL Right Join未返回预期年份-编码全组合结果,求正确查询语句

正确生成全量年份-编码组合的SQL查询

问题背景

现有主数据表:

declare @table table(year int, code int, import decimal(5,2))
insert into @table values
(2019,390107,10.00),
(2021,390107,175.00),
(2022,390107,102.00),
(2022,470101,101.00),
(2022,53015101,140.00)

需要基于以下年份表和编码表,生成所有年份-编码组合的记录,无对应数据时import返回0:

declare @years table (year int)
insert into @years values
(2018),
(2019),
(2020),
(2021),
(2022)

declare @codes table (code int)
insert into @codes values
(390107),
(470101),
(470103),
(471103),
(53010101),
(53015101)

原查询尝试使用两次右连接,但无法生成全量30条(5年×6编码)的预期结果:

select 
    y.year,
    c.code,
    isnull(t.import,0)
from @table t
right join @years y on t.year = y.year
right join @codes c on t.code = c.code

正确查询语句

要生成全量组合,需先对年份表和编码表做笛卡尔积(交叉连接),得到所有可能的年份-编码配对,再左连接到主数据表获取对应import值:

select 
    y.year,
    c.code,
    ISNULL(t.import, 0.00) as import
from @years y
cross join @codes c
left join @table t 
    on y.year = t.year 
    and c.code = t.code
order by y.year, c.code

逻辑说明

  1. cross join:让@years和@codes做交叉连接,直接生成5×6=30条全量年份-编码组合,这是获取所有可能配对的核心。
  2. left join:以全量组合为基础,左连接主数据表@table,匹配对应的年份和编码,确保即使没有匹配数据,也能保留全量组合记录。
  3. ISNULL:将无匹配的import值替换为0.00,符合需求。
  4. order by:按年份和编码排序,与预期结果的顺序一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:06:45