Ivy Professional School
Rating
Learning/SQL Data Drill #18

Batch-wise Order Packaging Allocation

Last updated

Find which order was packaged from which batch and in what quantity using recursive CTEs and row-wise allocation logic.

SQLAdvancedRecursive CTEROW_NUMBERLEFT JOINGROUP BYAllocation LogicInventory Analysis

Your Objective

Find which order was packaged from which batch and in what quantity using recursive CTEs and row-wise allocation logic.

The Setup

Your dataset contains two packaging allocation tables: 1. A Batches table with batch IDs and available quantity in each batch 2. An Orders table with order numbers and required quantity for each order The packaging company uses batches sequentially. It starts from the first batch, and only after that batch is exhausted, it moves to the next batch.

Table Schema

Batches
ColumnTypeKey / Notes
batch_idVARCHAR(10)
quantityINT
Orders
ColumnTypeKey / Notes
order_numberVARCHAR(10)
quantityINT

Sample Data

Batches — 10 rows

batch_idquantity
BA10
BB12
BC10
BD16
BE15
BF13
BG19
BH10
BI14
BJ16

Orders — 20 rows

order_numberquantity
OA5
OB4
OC2
OD8
OE7
OF10
OG12
OH6
OI12
OJ10
OK8
OL16
OM8
ON5
OO3
OP4
OQ12
OR9
OS6
OT10

Your Task

Batch-wise Order Packaging Allocation: Which order was packaged from which batch and in what quantity? The final result table should have order_number, batch_id, and quantity columns.

Your output should look like this (partial example):

order_numberbatch_idquantity
OABA5
OBBA4
OCBA1
OCBB1

Before You Solve

  • →Use recursive CTEs to split each batch and each order into unit-level rows.
  • →Assign ROW_NUMBER() to batch units and order units to create a common sequence.
  • →Join order units to batch units by row number to simulate sequential allocation.
  • →Aggregate the unit-level matches back to order_number and batch_id.
  • →Use LEFT JOIN so any unfulfilled order units remain visible with a NULL batch_id.
Explore Enterprise Solutions