求解一个数值更新问题
一个价格表
create table mon_price( monid int, price int)
insert into mon_price values(1,0)
insert into mon_price values(2,10)
insert into mon_price values(3,20)
insert into mon_price values(4,0)
insert into mon_price values(5,0)
insert into mon_price values(6,15)
insert into mon_price values(7,25)
insert into mon_price values(8,0)
逻辑:如果往后的月份,价格为0,则取上一个最近非0月份的价格
希望得到结果为
monid price
1 0
2 10
3 20
4 20 *
5 20 *
6 15
7 25
8 25 *
求SQL语句,先谢谢各位的热心解答了
------解决方案--------------------SELECT
monid,
price=ISNULL(NULLIF(price,0),ISNULL((SELECT TOP 1 price FROM mon_price WHERE monid<p.monid AND price>0 ORDER BY monid desc),0))
FROM mon_price p
------解决方案--------------------SELECT
monid,
price=case price
when 0 then (SELECT TOP 1 price FROM mon_price WHERE monid<p.monid AND price<>0 ORDER BY monid desc)
else price
end
FROM mon_price p