2

Given a number of types and a number of occurrences per type, I would like to generate something like this in T-SQL:

Occurrence | Type
-----------------
         0 | A
         1 | A
         0 | B
         1 | B
         2 | B

Both the number of types and the number of occurrences per type are presented as values in different tables.

While I can do this with WHILE loops, I'm looking for a better solution.

Thanks!

3
  • 1
    Please share you Other table also. Commented Sep 25, 2014 at 12:56
  • 2
    Have you tried something before asking your question? Commented Sep 25, 2014 at 12:56
  • What have you tried? At the very least, post a data sample or (better) create a simple example in SQL fiddle Commented Sep 25, 2014 at 13:51

2 Answers 2

2

This works with a number-table which i would use.

SELECT Occurrence = ROW_NUMBER() OVER (PARTITION BY Type ORDER BY Type) - 1
     , Type
FROM Numbers num
INNER JOIN #temp1 t
ON num.n BETWEEN 1 AND t.Occurrence

Tested with this sample data:

create table #temp1(Type varchar(10),Occurrence int)
insert into  #temp1 VALUES('A',2)
insert into  #temp1 VALUES('B',3)

How to create a number-table? http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that worked. One minor thing though - ON n BETWEEN 1 and t.Occurrence should be: ON n.COLUMNAME BETWEEN 1 and T.Occurrence
@mo5470: : in my number-table n is the column-name. But you're right, that's a little bit confusing since the table alias was also n. I've channged that.
1

If you have a table with the columns type and num, you have two approaches. One way is to use recursive CTEs:

with CTE as (
      select type, 0 as occurrence, num
      from table t
      union all
      select type, 1 + occurrence, num
      from cte
      where occurrence + 1 < num
     )
select cte.*
from cte;

You may have to set the MAXRECURSION option, if the number exceeds 100.

The other way is to join in a numbers table. SQL Server uses spt_values for this purpose:

select s.number - 1 as occurrence, t.type
from table t join
     spt_values s
     on s.number <= t.num ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.