我是SQL新手。我正在尝试编写一个与forcast-fulfillment-sql-query几乎相似的查询,但我的业务需要是根据req_qty
上运行的max_qty
来reserve_qty
STORE_ID_B
}
表格:1
STORE_ID_A req_qty max_qty shop_rnk
1002 3 5 1
1003 5 8 2
1004 1 5 3
1005 3 5 5
1006 3 5 6
1007 3 5 8
1008 3 5 9
1009 3 5 10
1010 2 5 11
1011 3 5 12
1012 2 5 13
表2:
STORE_ID_B reserve_qty rnk
500 10 1
501 9 2
预期输出:
STORE_ID_A STORE_ID_B release_qty
1002 500 3
1003 500 7
1004 501 1
1005 501 3
1006 501 5
对于第一行STORE_ID_B reserve_qty = 10和STORE_ID_A
req_qty
3和max_qty 5.。10不在3和5之间,所以我需要取req_qty
即3。
第二行,现在余额reserve_qty
是(10-3)= 7,它位于5到8之间,所以我需要max_qty
。发送数量将基于Store_ID_A和STORE_ID_B等级。
到目前为止,我已尝试过以下。但没有得到所需的输出。任何帮助都将受到高度赞赏。
WITH t1 AS (
select t1.*,
coalesce(sum( reserve_qty ) over ( order by rnk range between unbounded preceding and 1 preceding),0) As range_start,
sum( reserve_qty ) over ( order by rnk ) As range_end
from table1 t1
),
t2 As (
select t2.*,
coalesce(sum( req_qty ) over ( order by shop_rnk range between unbounded preceding and 1 preceding),0) As range_start,
sum( req_qty ) over ( order by shop_rnk ) As range_end
from table2 t2
)
select t1.*,t2.* , t1.req_qty - coalesce(sum(er_rtl_dm..least( from_loc_rec.range_end, to_loc_rec.range_end ) - greatest( from_loc_rec.range_start, to_loc_rec.range_start )) OVER (
PARTITION BY from_loc_rec.vpn,from_loc_rec.color,from_loc_rec.loc_CD ORDER BY to_loc_rec.rnk rows BETWEEN unbounded preceding
AND 1 preceding
), 0)
FROM t1
join t2
on not ( t1.range_end <= t2.range_start OR t1.range_start >= t2.range_end)