-2

I have total value in table A and need to get row value in table B until reached value in table A.

Table A

ID Available
1 99
2 0

Table B

ID Rack RequiredQty
1 A 60
1 B 102
1 C 8
2 A 10

Expected Results

ID Rack RequiredQty FulfilledQty
1 A 60 60
1 B 102 39
1 C 8 0
2 A 10 0
4
  • You can find in this link , some ways to do it: sqlperformance.com/2021/12/t-sql-queries/…
    – Sabin B
    Commented Mar 9, 2022 at 7:42
  • is it possible to use cte to get the fullfilledqty breakdown?
    – Alice
    Commented Mar 9, 2022 at 8:18
  • 1
    In what order do you want to fulfill the quantities for a given ID?...by Rack alphabetically?
    – J.D.
    Commented Mar 9, 2022 at 12:45
  • Cumulative SUM in CTE by table 2, join table 1, compare, calculate additional column.
    – Akina
    Commented Mar 9, 2022 at 13:41

1 Answer 1

0

You can use a recursive CTE to produce a running total and subtract that from the required quantity:

;WITH CTE AS (
  SELECT ID, Rack, Required
    , ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Rack ASC) AS Rn
  FROM TableB
), CTE2 AS (
  SELECT b.ID
    , b.Rn
    , b.Rack
    , b.Required
    , CASE
        WHEN b.Required > a.Available THEN a.Available
        ELSE a.Available - (a.Available - b.Required) 
      END AS Fulfilled
    , CASE
        WHEN b.Required > a.Available THEN 0
        ELSE a.Available - (a.Available - (a.Available - b.Required))
      END AS Available
  FROM CTE b
  INNER JOIN TableA a ON a.ID = b.ID
  WHERE b.Rn = 1
  UNION ALL
  SELECT b.ID
    , b.Rn
    , b.Rack
    , b.Required
    , CASE
        WHEN b.Required > a.Available THEN a.Available
        ELSE a.Available - (a.Available - b.Required) 
      END AS Fulfilled
    , CASE
        WHEN b.Required > a.Available THEN 0
        ELSE a.Available - (a.Available - (a.Available - b.Required))
      END AS Available
  FROM CTE b
  INNER JOIN CTE2 a ON a.ID = b.ID AND a.Rn = b.Rn-1
  WHERE b.Rn > 1
)

SELECT ID
  , Required AS RequiredQty
  , Fulfilled AS FulfilledQty
FROM CTE2
ORDER BY ID, Rack

You can see a working example in this fiddle, which produces the below output:

ID Rack RequiredQty FulfilledQty
1 A 60 60
1 B 102 39
1 C 8 0
2 A 10 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.