Monday, January 4, 2021

SQL11 Generate Duplicate Data to Some specific count

We have given data in table, along with the count of quantity with respect to each order and item, we need to generate number of rows equal to the count of QTY given in table.

Assume, for first row 5 count is given, as a output we need to generate 1 row 5 time as duplicate row.

Data in Table 
orderid item qty
o1 A1 5
o2 A2 1
o3 A3 3



Output Needed
orderid item qty
o1 A1 1
o1 A1 2
o1 A1 3
o1 A1 4
o1 A1 5
o2 A2 1
o3 A3 1
o3 A3 2
o3 A3 3


SELECT *
INTO SQL11
FROM (
	SELECT 'o1' OrderID
		,'A1' Item
		,5 QTY
	
	UNION ALL
	
	SELECT 'o2'
		,'A2'
		,1
	
	UNION ALL
	
	SELECT 'o3'
		,'A3'
		,3
	) t1


Solution 1
WITH t
AS (
	SELECT orderid
		,item
		,qty
	FROM SQL11
	
	UNION ALL
	
	SELECT orderid
		,item
		,qty - 1
	FROM t
	WHERE qty > 1
	)
SELECT *
FROM t
ORDER BY 1
	,3
note* - abvove query can also be possible to execute in Oracle, before execute in oracle, change the with clause "with t (orderid, item, qty) as ("

Oracle Specific Query
SELECT OrderID
	,Item
	,1
FROM (
	SELECT DISTINCT OrderID
		,Item
		,LEVEL
	FROM SQL11 EO connect BY LEVEL <= (
			SELECT QTY
			FROM SQL11 EI
WHERE EO.OrderID = EI.OrderID ) ) ORDER BY 1 ,2 ,3;

No comments:

Post a Comment

web stats