You can use something like below. 1. The logic is to reset the values first, then delete 0 records, and then calculate the last non-zero value as row_num = 1.
- Then a turn follows to get the result.
Request below
create table t (timespan date,val1 int,val2 int,val3 int,val4 int,val5 int,val6 int,val7 int,val8 int,val9 int,val10 int); insert into t values ('10/09/2011', 0, 0,60,80,40, 0, 0,40,80, 0) ,('10/10/2011', 0,10,90,30,70,50,50,70,30,90) ,('10/11/2011',10, 0,20, 0, 0,60,60, 0, 0,20); select * from ( select value, Columns from ( select timespan, value, Columns, row_number() over(partition by Columns order by timespan desc) r from (select * from t)s unpivot ( value for Columns in ([val1],[val2],[val3],[val4],[val5],[val6],[val7],[val8],[val9],[val10]) )up where value<>0 ) t where r=1 )s pivot ( max(value) for Columns in ([val1],[val2],[val3],[val4],[val5],[val6],[val7],[val8],[val9],[val10]) )p
See a working demo