在Join中包含NULL(已使用左连接)

时间:2016-11-08 17:47:06

标签: sql sql-server

我有一张表@rpt_year_month,其中包含YYYYMM形式的最新6个月,没有其他内容(还有其他信息,但仅限于6个月的行;总共6行)。我试图加入一个表格,其中包含按月分类的信息,但有些"材料"几个月没有数据。我有一个例子,我想要拉下面看起来像一个特定的材料:

Correct Material Pull

但是,当我运行它而不是加入特定材料时(正如您将在我的代码中看到的那样)它不会返回任何空值。有没有办法复制上面的结果,以便每种材料都以这种方式显示?我的代码如下:

    With picard as (
Select c.client
,COALESCE(c.fiscal_year_month_key,r.cal_year_month) as cal_year_month
,c.material_nbr
,c.plant
,c.stock_qty
,c.stock_value from @rpt_year_month r

LEFT JOIN

@cmbnd_inv_period_qty c ON

r.cal_year_month = c.fiscal_year_month_key
AND material_nbr = '100000009428'
)
Select * into #worf from picard;

Select * from #worf
Drop Table #worf;

1 个答案:

答案 0 :(得分:0)

您需要生成所有行,然后使用left join。所以,我认为这就是你想要的:

Select c.client,
       coalesce(c.fiscal_year_month_key, r.cal_year_month) as cal_year_month,
       m.material_nbr, c.plant, c.stock_qty, c.stock_value
from (select distinct material_nbr from from @rpt_year_month r) m cross join
     @rpt_year_month r left join
     @cmbnd_inv_period_qty c 
     ON r.cal_year_month = c.fiscal_year_month_key ;
相关问题