sql - increase Row number based on the existing column -
i using following sql rownumber increased 1 one. have attached image show need. when rownumber null should take max number table , add 1 ,max can 12.
[![drop table #test123 create table #test123 ( monthname varchar(15), monthlycount int , totalcount int, rownumber int ) insert #test123 values ('jan', 1,1,1) ,('feb' ,3,4,2) ,('mar' ,null ,null,null) ,('apr', null,null,null) ,('may', null,null,null) ,('jun' ,null ,null,null),('jul', null,null,null) ,('aug', 6,10,3) ,('sep' ,null ,null,null) ,('oct', null,null,null) ,('nov', 2,12,4) ,('dec' ,null ,null,null) --select * #test123 ---i tried following sql select monthname,monthlycount,totalcount,case when rownumber null (select max(rownumber)+1 #test123) else rownumber end rownumber #test123][1]][1]
here... order looking for:
select [monthname] ,[monthlycount] ,[totalcount] ,[rownumber] ,row_number() over(order [rownum], [mnum]) [desired_output] (select * ,datepart(mm, [monthname] + ' 01 2017') [mnum] ,case when [rownumber] null 13 else [rownumber] end [rownum] #test123) m order [mnum];
it figures out month number [mnum] using datepart function dummy day , year ' 01 2017'
.
then figures out row number [rownum] based on existing [rownumber]. if null, slugs 13 in sorting purposes.
then in outer query, finds real row number [desired_output] grabbing row number of subquery ordered [rownum] , [mnum]. existing row numbers float top , 13's float bottom. having secondary sort of [mnum], 13's sorted month order.
then final order put whole list in month order.
monthname monthlycount totalcount rownumber desired_output jan 11 1 1 1 feb 3 4 2 2 mar null null null 5 apr null null null 6 may null null null 7 jun null null null 8 jul null null null 9 aug 6 10 3 3 sep null null null 10 oct null null null 11 nov 2 12 4 4 dec null null null 12
not complicated, works under parameters gave.
hope helps. :)
Comments
Post a Comment