Create a weekCount column in SQL Server 2012 -


i have data:

id    worked_date -----------------     1     2013-09-25 2     2013-09-26 3     2013-10-01 4     2013-10-04 5     2013-10-07 

i want add column called weekcount. based date 2013-09-25. data worked_date 2013-09-25 2013-10-01 have weekcount 1 , 2013-10-02 2013-10-8 have weekcount 2 , on. how can done?

thanks.

perhaps approach solve problem.

i compute in-memory table contains week's boundaries along monotonically increasing number (buildweeks). compare worked_date values date boundaries. based on comment @sgeddes, need reverse week number use dense_rank function calculate reverseweeknumber.

with bot(startdate) (     select cast('2013-09-25' date) ) , buildweeks (weeknumber, startofweek, endofweek) (     select          n.number weeknumber     ,   dateadd(week, n.number -1, b.startdate) startofweek     ,   dateadd(d, -1, dateadd(week, n.number, b.startdate)) endofweek             dbo.numbers n         cross apply           bot b ) select     m.* ,   bw.* ,   dense_rank() on (order bw.weeknumber desc) reverseweeknumber     dbo.mytable m     inner join         buildweeks bw         on m.worked_date between bw.startofweek , bw.endofweek ; 

sqlfiddle


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -