日期:2014-05-16  浏览次数:20795 次

有个更新操作问题
我有个产品表
字段
产品ID 年 月 价格
1000 2012 5 9
1000 2012 6 10
1000 2012 7 11
1000 2012 5 null
1001 2012 6 20
1001 2012 7 23
...
1000 2012 8 null
1001 2012 8 null
现在录入8月份的数据,但是有些产品8月价录入价格为null,现想直接取前面几个月有值的一个价格,就是不一定是取上个月,只要前面这个产品哪个月有值就取那个价格的值填充到这个8月份的数据
希望通过一条SQL语句update之类,直接一次批量将8月NULL值替换前面某个月有值的价格。

------解决方案--------------------
SQL code
update product pa set price = (
select max(price) from product pb where pa.id = pb.id
) where price is null;

------解决方案--------------------
SQL code
update product pa set price = (
select max(price) from product pb where pa.id = pb.id
) where price is null and year=2012 and month=8;

------解决方案--------------------
如果要更新成最近一个价格不是空的月份的值,
SQL code
update product p set price = ( select price from
  (select id, mth, price, row_number() over (partition by id order by year desc, month desc) rn from product where price is not null) prc_list
where prc_list.id = p.id and prc_list.rn = 1)
where price is null and year=2012 and month=8;