How to sort MonthName (varchar) in SQL Server? -
i got stuck while sorting month name in order in below query. here period alias user can choose if wants see result in daily, weekly, monthly or yearly. sorting working rest of cases except month. taking month string , if try convert month giving exception.
please have , guide me.
it begin return like:
april august december desired output:
january february march april december code:
declare @period char = 'm' declare @finaldateid int = 20170101; select period, sum(cast(totalamount bigint)) value (select case when @period = 'd' cast(d.datename varchar(50)) when @period = 'w' cast(d.weekofyear varchar(50)) when @period = 'm' cast(d.monthname varchar(50)) when @period = 'y' cast(d.calendaryear varchar(50)) end period, tr.totalamount revenue tr inner join dates d on tr.dateid = d.id (tr.dateid between case when @period = 'd' convert(varchar, convert(datetime, convert(char(8), @finaldateid)) - 30, 112) when @period = 'w' convert(varchar, convert(datetime, convert(char(8), @finaldateid)) - 364, 112) when @period = 'm' convert(varchar, convert(datetime, convert(char(8), @finaldateid)) - 365, 112) when @period = 'y' convert(varchar, convert(datetime, convert(char(8), @finaldateid)) - 3652, 112) end , @finaldateid) ) totalrevenue group period order case when @period = 'm' convert(month, period) end output returning without sort:
period value -------------------- april 4750 august 4750 december 187250 february 4000 january 12500 desired output after sorting month:
period value ----------------------- january 12500 february 4000 april 4750 august 4750 december 187250 shared sample data/table @ https://1drv.ms/u/s!ak02jpvbvozehy0hs2r8rxh6mhsr
don't mess around names of date's part!
any approach build full date using month's name , date fragment in order month's number fail, if executing system has got different language. if application might ever run in international environment, must find way deal without hacks.
if period real date somewhere, might extract year , month using year() , month() , order both of them. both come numeric index.
but solution seems simpler:
obviously using dates table (which thing!)
from posted example take, column [monthofyear] has got numeric month index. , you've got fiscalyear too. include these columns query , use order fiscalyear,monthofyear.
Comments
Post a Comment