Friday 10 February 2023

SQL - How to convert multiple rows into single rows with more columns?

 https://community.spiceworks.com/topic/973727-sql-how-to-convert-multiple-rows-into-single-rows-with-more-columns

SQL - How to convert multiple rows into single rows with more columns?

check
  • This is how I would get the result you want using the sample table and data you posted.

    SQL
    -- Create table for sample query
    Declare @Orders Table (OrderID int,
    	Product varchar(10),
    	Quantity int);
    
    -- Insert sample data
    Insert Into @Orders
    Values (100, 'Cup', 1),
    	(100, 'Plate', 2),
    	(101, 'Cup', 1),
    	(102, 'Cup', 2),
    	(103, 'Cup', 1),
    	(103, 'Plate', 2),
    	(103, 'Glass', 1);
    
    
    With Orders
    As (Select ROW_NUMBER() Over (Partition By OrderID Order By OrderID) As RowID,
    		*
    	From @Orders)
    Select OrderID As [Order#],
    	Min(Product1) As Product1,
    	Min(Quantity1) As Quantity1,
    	Min(Product2) As Product2,
    	Min(Quantity2) As Quantity2,
    	Min(Product3) As Product3,
    	Min(Quantity3) As Quantity3
    From (Select ROW_NUMBER() Over (Partition By OrderID Order By OrderID) As RowID,
    		OrderID,
    		'Product' + Cast(RowID as varchar) As ProductNum,
    		'Quantity' + Cast(RowID as varchar) As QuantityNum,
    		Product,
    		Quantity
    	From Orders) As Pvt
    Pivot (Min(Product)
    	For ProductNum In ([Product1], [Product2], [Product3])) As Pvt1
    Pivot (Min(Quantity)
    	For QuantityNum In ([Quantity1], [Quantity2], [Quantity3])) As Pvt2
    Group By OrderID;
  •  

    No comments:

    Post a Comment

    Note: only a member of this blog may post a comment.

    Blog Archive