Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2016-07-19
6
Medium Priority
?
95 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 1000 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 1000 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
Use Case: Protecting a Hybrid Cloud Infrastructure

Microsoft Azure is rapidly becoming the norm in dynamic IT environments. This document describes the challenges that organizations face when protecting data in a hybrid cloud IT environment and presents a use case to demonstrate how Acronis Backup protects all data.

 
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

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

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

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.
This post looks at MongoDB and MySQL, and covers high-level MongoDB strengths, weaknesses, features, and uses from the perspective of an SQL user.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

704 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