有一个简单粗暴的方法,把月份加一错开和原表left join 。你把table_yourtable换成你的表试一下。
select a.usedate,
case when a.demand_num is null then b.demand_num else a.demand_num end as new_demand_num
from
(select CONVERT(varchar(100), create_time, 112) usedate,demand_num from table_yourtable) a
left join
(select CONVERT(varchar(100), create_time, 112)+1 usedate,demand_num from table_yourtable) b on a.usedate=b.usedate
上面是不管跨年和一月份数据,如果一月份数据也要处理就用下面语句:
select a.usedate,
case when a.demand_num is null then b.demand_num else a.demand_num end as new_demand_num
from
(select CONVERT(varchar(100), create_time, 112) usedate,demand_num from table_yourtable) a
left join
(select case when month(create_time) = 12 then CONVERT(varchar(100),DATEADD(yy,DATEDIFF(yy,0,dateadd(year,-1,create_time)),0), 112)
else CONVERT(varchar(100), create_time, 112)+1 end as usedate,
demand_num from table_yourtable where month(create_time)<> 01 ) b on a.usedate=b.usedate