Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a SQL Server stored procedure to get the following output?

Tags:

I have a SourceTable like this with 2 column names:

  Col 1  | Col 2
------------------
  A      |   2
  B      |   3
  C      |   4
  D      |   2
  E      |   1
  F      |   0

The first column has some letter, and the second column carries its frequency.

We need to write a stored procedure and get the output in a TargetTable like this.

We CAN NOT use any loop, or iteration for this.

Col 1
-----
  A
  A
  B
  B
  B
  C
  C
  C
  C 
  D
  D
  E
like image 694
Code Fearer Avatar asked Jan 06 '17 12:01

Code Fearer


1 Answers

How about a recursive CTE?

with x as (
      select col1, 1 as i, col2 as lim
      from t
      where col2 > 0
      union all
      select col1, i + 1, lim
      from x
      where i + 1 <= lim
     )
select col1
from x
order by col1;
like image 199
Gordon Linoff Avatar answered Sep 23 '22 09:09

Gordon Linoff