(+91) 7 999 01 02 03

Ungroup the Orders Table

Ayush Dixit
15 Posts

Problem Statement:-

You have an orders table with order details. You have to ungroup the data based on the order quantity.

The amount column in the output should be an amount of a single quantity. Assume that the product's amount will be the same regardless of the quantity ordered.


Write an SQL query to ungroup the orders table.

Sample Input:-


Expected Output:-


SQL Scripts:-

CREATE TABLE order_details(
order_id INT,
product VARCHAR(255),
quantity INT,
amount INT

INSERT INTO order_detail (order_id,product,quantity,amount) VALUES

My Solution:-

I have implemented the solution using Number Sequence and CROSS JOIN. First I have Generated the Number Sequence using RECURSIVE CTE and then CROSS JOIN this Number Sequence table with the Orders table based on the quantity in the Orders table.

Final Query:-

DECLARE @max_num int = (SELECT max(quantity) FROM order_details);
;WITH numbers (num) as
( SELECT 1 as num


SELECT num+1
FROM numbers
WHERE num< @max_num

SELECT order_id, product,
1 AS quantity, CAST(amount / quantity as DECIMAL(18,2)) AS amount
FROM order_details
CROSS JOIN  numbers
WHERE quantity>= num
ORDER BY order_id, product;


Thanks for reading. I hope you enjoyed this fun little case study - it was fun for me to create!. You can also share your approach to solve this problem.

Published By : Ayush Dixit
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.