Solved

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

Posted on 2016-07-19
6
91 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 49

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 13

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
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
LVL 49

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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

626 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