I have tried desperately to get this to work and I am stuck. Any help is appreciated! I have two tables. Table 1 is customers and table 2 is the location and qty of inventory. The issue is I need the number of times a bin is recommended to be limited by the quantity so once it's recommended the entire quantity it stops recommending that bin...This is what stumps me.
Table 1
Customer | Item | Qty
1 | Item1 | 2
1 | Item2 | 1
2 | Item1 | 1
3 | Item1 | 1
4 | Item1 | 1
5 | Item1 | 1
6 | Item1 | 1
Table 2
Item | Bin | Qty
Item1 | A1 | 1
Item1 | A84 | 2
Item1 | C32 | 2
Item1 | D01 | 1
Output would would stop recommending the first match once the times matched hits the qty count... I am completely stuck...
The output would look like
Customer | Item | Bin
1 | Item1 | A1
1 | Item2 | A84
2 | Item1 | A84
3 | Item1 | C32
4 | Item1 | C32
5 | Item1 | D01
6 | Item1 | (since there is no other bin left)
The script so far with the help of Ponder is...
SELECT
CUST.CUSTOMER, CUST.ITEM, BIN
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY CUSTOMER, ITEM ORDER BY CUSTOMER ASC, ITEM ASC) AS RN,
CUSTOMER,
ITEM
FROM CUSTOMERS
) CUST
LEFT JOIN (
SELECT
ITEM,
BIN,
LAG(Q2, 1, 0) OVER (PARTITION BY ITEM, BIN ORDER BY ITEM ASC, BIN ASC) Q1,
Q2
FROM (
SELECT
ITEM,
BIN,
SUM(QTY) OVER (PARTITION BY ITEM, BIN ORDER BY ITEM ASC, BIN ASC) Q2
FROM INVENTORY I
)
) INV ON Q1 < RN AND Q2 <= RN AND CUST.ITEM = INV.ITEM
Number rows in table customers. Make cumulative sum of quantities in table locations. Assign rows from customers to locations using left join and defined ranges. You did not specify what RDBM you use, so here is Oracle solution, but it uses standard functions which should work in most databases, or at least you can easily apply this logic:
select customer, item, bin
from (select row_number() over (order by customer) as rn, customer, item
from customers)
left join (
select bin, lag(q2, 1, 0) over (order by bin) q1, q2
from (select bin, sum(qty) over (order by bin) q2 from locations))
on q1 < rn and rn <= q2
Seems that item
is not used to join rows (in your example you have no Item2 in locations). In case you need it, use partition by
in analytic functions and use item
in join condition.