将右外连接中的空值替换为先前非空匹配的行

时间:2011-06-29 14:53:41

标签: sql sql-server-2005

我有这个查询

select a.WeekNumber
        ,a.filedate
        ,a.customer
        ,material
        ,Quantity
from zfmon zf right outer join zfmonTemp a
on zf.customer = a.customer
        and zf.filedate = a.filedate
        and zf.material =  'AD215BY'

返回以下内容

WeekNumber FileDate                 Customer Material Quantity
1          2010-03-19 00:00:00.000  1008777  NULL     NULL
2          2010-03-12 00:00:00.000  1008777  AD215XX  3

我想要的是当材料为null时将其替换为下一个非空值。在这种情况下,它将用AD215XX替换它

因此输出看起来像

WeekNumber FileDate                 Customer Material Quantity
1          2010-03-19 00:00:00.000  1008777  AD215XX  NULL
2          2010-03-12 00:00:00.000  1008777  AD215XX  3

这可能吗?任何人都可以帮忙。

谢谢, 利

2 个答案:

答案 0 :(得分:1)

select a.WeekNumber
        ,a.filedate
        ,a.customer
        ,isnull(material, (select top 1 material from zfmonTemp where weeknumber > zf.weeknumber and material is not null order by weeknumber)) material
        ,Quantity
from zfmon zf right outer join zfmonTemp a
on zf.customer = a.customer
        and zf.filedate = a.filedate
        and zf.material =  'AD215BY'

答案 1 :(得分:0)

set @material = 'AD215BY';
select a.WeekNumber
        ,a.filedate
        ,a.customer
        ,coalesce(zf.material, @material) as Material
        ,zf.Quantity
from zfmon zf right outer join zfmonTemp a
on zf.customer = a.customer
        and zf.filedate = a.filedate
        and zf.material = @material