Solved

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

Posted on 2016-07-19
6
50 Views
Last Modified: 2016-07-21
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
0
Comment
Question by:sqdperu
  • 3
  • 2
6 Comments
 
LVL 48

Assisted Solution

by:PortletPaul
PortletPaul earned 250 total points
ID: 41719916
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
 
LVL 12

Accepted Solution

by:
Dustin Saunders earned 250 total points
ID: 41719934
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
 

Author Comment

by:sqdperu
ID: 41720945
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 48

Expert Comment

by:PortletPaul
ID: 41721041
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
 

Author Comment

by:sqdperu
ID: 41723021
I'm just going to do it VB.net with looping.  Thanks for the help and awarding points for trying to help me.
0
 

Author Closing Comment

by:sqdperu
ID: 41723023
Thank
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now