Duplicating rows based on another table

  • Hi,

    I have some data in table a which has a unique identifier called column nd. I have another table, table b, which has that unique identifier, again called nd and another column called j which is a number between 10-20.

    How can I return the results on table a, but I want a row for each nd times the result in column j where nd is the same in both tables.

    For example, if nd is equal to small, and j is equal 10 the results from that query would be 10 rows of the word small.

    Hope that makes sense.

    Thanks

  • Hi and welcome to SSC. It is somewhat difficult to help here because you did not provide very much information. We like to see ddl, sample data and desired output. Since your a brand new around here I went ahead and created it for you this time. Please take a few minutes to read the first link in my signature for best practices when posting questions for your future posts.

    if OBJECT_ID('tempdb..#Table1') is not null

    drop table #Table1

    if OBJECT_ID('tempdb..#Table2') is not null

    drop table #Table2

    create table #Table1

    (

    SomeID uniqueidentifier,

    ValueToDisplay char(5)

    )

    create table #Table2

    (

    SomeID uniqueidentifier,

    SomeNumber int

    )

    insert #Table1

    select NEWID(), 'small'

    insert #Table2

    select SomeID, 10

    from #Table1

    select t1.ValueToDisplay

    from #Table1 t1

    join #Table2 t2 on t2.SomeID = t1.SomeID

    join Tally t on t.N <= t2.SomeNumber

    Now this will likely not work on your system because you probably don't have a tally table. You can read about what a tally table is by following this link. http://www.sqlservercentral.com/articles/T-SQL/62867/[/url] The article will also show you how to create your own. 😉

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply