sql server - Calculate Sum From Moving 4 Rows in SQL -
i've have following data.
wm_week pos_store_count pos_qty pos_sales pos_cost ------ --------------- ------ -------- -------- 201541 3965 77722 153904.67 102593.04 201542 3952 77866 154219.66 102783.12 201543 3951 70690 139967.06 94724.60 201544 3958 70773 140131.41 95543.55 201545 3958 76623 151739.31 103441.05 201546 3956 73236 145016.54 98868.60 201547 3939 64317 127368.62 86827.95 201548 3927 60762 120309.32 82028.70 i need write sql query last 4 weeks of data, , last 4 weeks summed each of following columns: pos_store_count,pos_qty,pos_sales, , pos_cost.
for example, if wanted 201548's data contain 201548, 201547, 201546, , 201545's.
the sum of 201547 contain 201547, 201546, 201545, , 201544.
the query should return 4 rows when ran successfully.
how formulate recursive query this? there easier recursive this?
edit: version azure sql dw version number 12.0.2000. edit2: 4 rows should returned have sum of columns , it's 3 earlier weeks.
for example, if wanted figures 201548 return following:
wm_week pos_store_count pos_qty pos_sales pos_cost ------ --------------- ------- -------- -------- 201548 15780 274938 544433.79 371166.3 which sum of 4 (non-identity) columns 201548, 201547, 201546, , 201545.
pretty sure want.. im using cross apply after ordering data apply sums
create table #weeklydata (wm_week int, pos_store_count int, pos_qty int, pos_sales money, pos_cost money) insert #weeklydata values (201541,3965,77722,153904.67,102593.04), (201542,3952,77866,154219.66,102783.12), (201543,3951,70690,139967.06,94724.6), (201544,3958,70773,140131.41,95543.55), (201545,3958,76623,151739.31,103441.05), (201546,3956,73236,145016.54,98868.6), (201547,3939,64317,127368.62,86827.95), (201548,3927,60762,120309.32,82028.7) declare @startweek int = 201548; cte ( select *, row_number() on (order [wm_week] desc) rn #weeklydata wm_week between @startweek - 9 , @startweek ) select * cte c1 cross apply (select sum(pos_store_count) pos_store_count_sum, sum(pos_qty) pos_qty_sum, sum(pos_sales) pos_sales_sum, sum(pos_cost) pos_cost_sum cte c2 c2.rn between c1.rn , (c1.rn + 3) ) ca c1.rn <= 4
Comments
Post a Comment