当前位置: 代码迷 >> Sql Server >> 用相同值的记录填充为null的记录解决办法
  详细解决方案

用相同值的记录填充为null的记录解决办法

热度:42   发布时间:2016-04-27 14:45:11.0
用相同值的记录填充为null的记录
有如下表内容:

SQL code
cust_code    order             PN            nums        dateMTPZZ       026308-01    AFE4-1975-1A        20        2011-1-2MTPZZ       026308-02    AFE4-1975-1A        25        2011-5-2null        null         AFE4-1975-1A        32          nullCMPZZ       026557-01    AFE4-1235-1A        36        2011-4-10CMPZZ       026316-01    AFE4-1235-1A        100       2011-4-13null        null         AFE4-1235-1A        50          null........因上面的结果导致我无法根据 cust_code过滤出为空的 PN。故我想得到如下结果:cust_code    order             PN            nums        dateMTPZZ       026308-01    AFE4-1975-1A        20        2011-1-2MTPZZ       026308-02    AFE4-1975-1A        25        2011-5-2MTPZZ       null         AFE4-1975-1A        32          nullCMPZZ       026557-01    AFE4-1235-1A        36        2011-4-10CMPZZ       026316-01    AFE4-1235-1A        100       2011-4-13CMPZZ       null         AFE4-1235-1A        50          null........这样我就能用cust_code 过滤本来为空的记录了。根据 PN值相同的,将 cust_code 为空的记录,用PN值相同的记录对应的cust_code的值填充。请问SQL如何实现?另外,如果要将为null 的记录与相同PN值的记录相加又如何实现?要求null值要与日期最近的那条记录相加。


------解决方案--------------------
SQL code
select a.cust_code,a.[order],a.pn,    (case when a.px=1 then a.nums+isnull(b.nums,0) else a.nums end) nums,    a.datefrom (    select *,px=row_number() over (partition by pn order by date desc)    from tb) a left join (    select * from tb where cust_code is null) b on a.pn = b.pn
------解决方案--------------------
SQL code
select (case when cust_code is null then (select top 1 cust_code from tb where pn =t.pn) else cust_code end) cust_code,    [order],pn,nums,datefrom tb t
------解决方案--------------------
探讨

只能用select解决。不允许用update.
  相关解决方案