sql server - Deriving Dynamic Column in SQL -


i have table this:

store_id | week  ---------+--------    a1    | 201601    a1    | 201602    a1    | 201604    a1    | 201606    a1    | 201607    a2    | 201552    a2    | 201603    a2    | 201604    a2    | 201605    a2    | 201608 

i need derive dynamic week column next ideally looking this:

store_id | week   | dynamic_week ---------+--------+-------------    a1    | 201602 |    1    a1    | 201603 |    2    a1    | 201605 |    4    a1    | 201606 |    5    a1    | 201607 |    6    a2    | 201552 |    1    a2    | 201603 |    4    a2    | 201604 |    5    a2    | 201605 |    6    a2    | 201608 |    9 

the logic is: min(week) each store considered first week of sales corresponding store. preceding values in dynamic week incremented based on reference of first week of sales on each store.

i tried row_number(), rank(), dense_rank(), couldn't solution that's needed. 3 things didn't work.

can suggest me possible solution.

thanks in advance.

edit: made query dynamic handle set of years, not 1.

new restester sample

select d.* ,((d.week-m.min_w+1)   -(48*(cast(left(d.week,4) int)         - cast(left(min_w,4) int)         )    )  )as dynamic_week dynw d inner join (select store_id,min(week) min_w              dynw              group store_id            ) m on d.store_id=m.store_id order 1,2 

output more complex sample

+----------+--------+--------------+ | store_id |  week  | dynamic_week | +----------+--------+--------------+ | a1       | 201602 |            1 | | a1       | 201607 |            6 | | a2       | 201552 |            1 | | a2       | 201603 |            4 | | a2       | 201704 |           57 | | a3       | 201352 |            1 | | a3       | 201601 |          106 | +----------+--------+--------------+ 

previous: need. although sample data , expected data don't match, solution store_id spanning across 1 year. more that, have change query bit. sample have.

restester sample

select t1.*,        case            when (t1.week-t.week1+1)>=52             (t1.week-t.week1+1)-48            else (t1.week-t.week1+1)        end dynamic_week table1 t1 inner join   (select store_id,           min(week) week1    table1    group store_id) t  on t1.store_id=t.store_id 

output sample

+----------+--------+--------------+ | store_id |  week  | dynamic_week | +----------+--------+--------------+ | a1       | 201602 |            1 | | a1       | 201604 |            3 | | a1       | 201606 |            5 | | a1       | 201607 |            6 | | a2       | 201552 |            1 | | a2       | 201603 |            4 | | a2       | 201604 |            5 | | a2       | 201605 |            6 | | a2       | 201608 |            9 | +----------+--------+--------------+ 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -