SQL Server 2008 version of OVER(... Rows Unbounded Preceding) -
looking in converting sql server 2008 friendly can't work out. i've tried cross applies , inner joins (not saying did them right) no avail... suggestions?
what have table of stock , table of orders. , combine 2 show me pick once stock taken away (see previous question more details more details)
with advpick (select 'a' placea, placeb, case when picktime = '00:00' '07:00' else isnull(picktime, '12:00') end picktime, cast(product int) product, prd_description, -qty qty t_pick_orders union select 'a' placea, placeb, '0', cast(code int) product, null, stock t_pick_stock), stock_post_order (select *, sum(qty) on ( partition placeb, product order picktime rows unbounded preceding ) new_qty advpick) select *, case when new_qty > qty new_qty else qty end order_shortfall stock_post_order new_qty < 0 order placeb, picktime, product
now whole sum on partition order sql server 2012+ have 2 servers run on 2008 , need converted...
expected results:
+--------+--------+----------+---------+-----------+-------+---------+-----------------+ | placea | placeb | picktime | product | prd_descr | qty | new_qty | order_shortfall | +--------+--------+----------+---------+-----------+-------+---------+-----------------+ | bw | ames | 16:00 | 1356 | product | -1330 | -17 | -17 | | bw | ames | 16:00 | 17 | product b | -48 | -42 | -42 | | bw | ames | 17:00 | 1356 | product | -840 | -857 | -840 | | bw | ames | 18:00 | 1356 | product | -770 | -1627 | -770 | | bw | ames | 18:00 | 17 | product b | -528 | -570 | -528 | | bw | ames | 19:00 | 1356 | product | -700 | -2327 | -700 | | bw | ames | 20:00 | 1356 | product | -910 | -3237 | -910 | | bw | ames | 20:00 | 8009 | product c | -192 | -52 | -52 | | bw | ames | 20:00 | 897 | product d | -90 | -10 | -10 | +--------+--------+----------+---------+-----------+-------+---------+-----------------+
one straight-forward way use correlated sub-query in cross apply
.
if table more or less large, next question how make fast. index on placeb, product, picktime include (qty)
should help. but, if table large, cursor better.
with advpick ( select 'a' placea,placeb, case when picktime = '00:00' '07:00' else isnull(picktime,'12:00') end picktime, cast(product int) product, prd_description, -qty qty t_pick_orders union select 'a' placea,placeb, '0', cast(code int) product, null, stock t_pick_stock ) ,stock_post_order ( select * advpick main cross apply ( select sum(sub.qty) new_qty advpick sub sub.placeb = main.placeb , sub.product = main.product , t.picktime <= main.picktime ) ) select *, case when new_qty > qty new_qty else qty end order_shortfall stock_post_order new_qty < 0 order placeb, picktime, product;
oh, , if (placeb, product, picktime)
not unique, you'll different results original query sum() over
. if need same results, need use column (like id
) resolve ties.
Comments
Post a Comment