Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn value into singular row

Current

Name   Quantity
---------------
Stella       2
Jennifer     2
Greg         3 

Requested result

Name    Quantity 
---------------
Stella       1
Stella       1
Jennifer     1
Jennifer     1
Greg         1
Greg         1 
Greg         1 

How should I do it?

declare @T table  
(  
  Name varchar(50),  
  Sales int  
)  
insert into @T values  
('Stella',   '2'),  
('Jennifer', '2'), 
('Greg',     '3')
like image 735
What'sUP Avatar asked Mar 22 '12 21:03

What'sUP


People also ask

How do I convert multiple row data to single row?

To merge two or more rows into one, here's what you need to do: Select the range of cells where you want to merge rows. Go to the Ablebits Data tab > Merge group, click the Merge Cells arrow, and then click Merge Rows into One.

How do I convert columns to single rows?

In Excel, to convert any Columns to Rows, first select the column which we want to switch and copy the selected cells or columns. To proceed further, go to the cell where we want to paste the data, then from the Paste option, which is under the Home menu tab, select the Transpose option.

How do I convert a column value to a row value in Excel?

Here's how you can transpose cell content: Copy the cell range. Select the empty cells where you want to paste the transposed data. On the Home tab, click the Paste icon, and select Paste Transpose.


2 Answers

If the maximum value in the quantity column is known to be less than 32,767, you can use Recursion to generate numbers and join the Numbers to achieve your result.

/*******************************************
  Max Recursion Count in SQL Server is 32767
  Limitation of 32767 Numbers!
 ******************************************/
;WITH Numbers (Number) AS 
(
    SELECT 1 
    UNION ALL
    SELECT 1 + Number FROM Numbers WHERE Number < 100
)
SELECT  m.Name,
        Quantity = 1
  FROM  MyTable m 
        JOIN @numbers n ON m.Quantity <= n.Number
OPTION (MAXRECURSION  32767);
like image 157
Akhil Avatar answered Oct 19 '22 03:10

Akhil


Using recursion and borrowing Michael Fredrickson's setup code:

declare @T table (  
  Name varchar(50),  
  Sales int  
)

insert into @T values ('Stella',   '2')  
insert into @T values ('Jennifer', '2') 
insert into @T values ('Greg',     '3')

-- Recursive verion
;with People (Name, Sales) as
(
    select Name, Sales
    from @T
    union all
    select Name, Sales - 1
    from People
    where Sales - 1 > 0
)
select Name, 1 as Quantity
from People
option (maxrecursion 0) -- Recurse without limit

This seems to run faster on my box (5x faster than Michael Fredrickson's according to query plan, but with many more logical reads), not that it matters much.

like image 23
Tim Lehner Avatar answered Oct 19 '22 02:10

Tim Lehner