How do I create duplicate rows in a table with a count? (SQL)

I have a table with a single row for each order.  It has an order#, tag, and quantity.  If it has a quantity greater than 1, I need to duplicate the rows (quantity - 1) number of times because the tag can be unique for each item of the quantity.

I use to have a table with the tags in it with number of rows equal to the quanity that I could join on to update the tags and create mulitiple records via the join.   The table is going away so now I have come up with a way to duplicate the rows, add a quantity count, and update the tags (by looking up order in a table and finding all the tags for the order and updating the field).

Example:

OrderTable
Order#      Tag      Qty      
1                               5
2                               1

I need it to look like this (will need to add a field for QtyCount)

OrderTable
Order#      Tag          Qty      QtyCount
1              Ace            5            1
1              Spd            5            2
1              Jack            5            3
1             King            5            4
1             Club            5            5
2             One             1            1


I don't know how to generate the extra rows for the ones with quantity greater than one and then how do I increment the QtyCount field (1 of 5, 2 of 5, etc.)

I'm using SQL Server 2008 R2.  

 Any ideas?

Thanks
sqdperuAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Dustin SaundersConnect With a Mentor Director of OperationsCommented:
If we can see the structure of the other table that would be helpful...  but to replicate I created the following table with (simply) order# and tag:
Table Name = ee_28958373
Order#      Tag
----------- --------------------------------------------------
1           Ace
1           Spd
1           Jack
1           King
1           Club
2           One
4           Two
4           Three

Open in new window


Then the following query:

CREATE TABLE #results ([Order#] INT, Tag VARCHAR(50), Qty INT, QtyCount INT)

DECLARE @thisOrder INT
DECLARE @lastOrder INT
DECLARE @thisQty INT
DECLARE @thisTotalQty INT

SET @thisOrder = (SELECT Min([Order#]) FROM ee_28958373)
SET @lastOrder = (SELECT Max([Order#]) FROM ee_28958373)

WHILE @thisOrder <= @lastOrder
BEGIN
CREATE TABLE #temp (Tag VARCHAR(50), RowNumb INT)
INSERT INTO #temp (Tag,RowNumb)
SELECT Tag, ROW_NUMBER() OVER (ORDER BY Tag) FROM ee_28958373 WHERE [Order#] = @thisOrder
SET @thisTotalQty = (SELECT Count(tag) FROM #temp)
SET @thisQty = 1
	WHILE @thisQty <= @thisTotalQty
	BEGIN
		INSERT INTO #results ([Order#],Tag,Qty,QtyCount)
		VALUES(@thisOrder,(SELECT tag FROM #temp WHERE RowNumb = @thisQty),@thisTotalQty,@thisQty)
		SET @thisQty = @thisQty + 1
	END
DROP TABLE #temp
SET @thisOrder = @thisOrder + 1
END
SELECT * FROM #results
DROP TABLE #results

Open in new window


Produces this result:
Order#      Tag                                                Qty         QtyCount
----------- -------------------------------------------------- ----------- -----------
1           Ace                                                5           1
1           Club                                               5           2
1           Jack                                               5           3
1           King                                               5           4
1           Spd                                                5           5
2           One                                                1           1
4           Three                                              2           1
4           Two                                                2           2

Open in new window

0
 
PaulConnect With a Mentor Commented:
by looking up order in a table and finding all the tags for the order
What is the query you use to do this bit? It is important to the solution. Also provide some sample data that support this query.

I don't a great deal of time right now but you just need a table of numbers, and you can use a CTE for this if you can't actually store the table.

e.g.  this quickly generates a set of integers that you can use to create the wanted rows

;WITH
  cteDigits AS (
      SELECT 0 AS digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
      SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
      )
, cteTally AS (
      SELECT
              [1s].digit
            + [10s].digit * 10
            + [100s].digit * 100  /* add more like this as needed */
            AS num
      FROM cteDigits [1s]
      CROSS JOIN cteDigits [10s]
      CROSS JOIN cteDigits [100s] /* add more like this as needed */
      )
select count(*)
from cteTally
0
 
sqdperuAuthor Commented:
I should have noted, I execute these queries from my VB.net app.   I know how to acheive my goal in vb.net with loops and inserts.   I just thought if there was simple slick way in SQL to do this I would.  I will probably just end up doing it in VB.  These solutions are more complex than my SQL knowledge.  

Paul,
To answer your question, there is a table that contains characteristics of the order.
For example:

Order#      Charc          CharVal
1                  This             red
1                  That            blue
1                  Tag              Ace
1                  Tag             Spd
1                  Tag             Jack
...

So I would query for Order# and Charc = 'Tag'.   Then pull the CharVal field for all of them.  But if 2 of the 5 had no Tag, then they would not get one.  Nothing I can really count on for the join.  Bummer.
Thanks
0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
PaulCommented:
I'm really not sure I follow the problem, but try this to see if it produces the rows you want
select
     d.OrderNo, d.Charc, d.CharVal, d.rn, d.Qty
from (
      select
           o.OrderNo, oc.Charc, oc.CharVal, o.Qty
        , row_number() over(partition by o.OrderNo order by ov.CharVal) as rn
      from OrderTable o
      inner join OrderCharacteristics o on o.OrderNo = oc.OrderNo
      where o.OrderNo = 1
      ) d
where d.rn <= d.qty

Open in new window

0
 
sqdperuAuthor Commented:
I'm just going to do it VB.net with looping.  Thanks for the help and awarding points for trying to help me.
0
 
sqdperuAuthor Commented:
Thank
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.