haimen
haimen

Reputation: 2015

Expand the rows into multiple rows based on the count column in SQL

Suppose I have a table as below,

ID         word            count
1           A                 3
1           B                 2
1           C                 4
2           D                 2
2           E                 3

I want to expand the table into multiple rows based on the count column. If the count has 3 as value, then I want to create 3 rows. Similarly I want to do it for all of them. The output should be as follows,

ID         word            count
1           A                 3
1           A                 3
1           A                 3
1           B                 2
1           B                 2
1           C                 4
1           C                 4
1           C                 4
1           C                 4
2           D                 2
2           D                 2
2           E                 3
2           E                 3
2           E                 3

Can anybody help me in doing this is SQL?

Upvotes: 2

Views: 1364

Answers (1)

Pheelbert
Pheelbert

Reputation: 327

I used http://sqlfiddle.com to test this out. There must be a better way than having a table with numbers. I took the idea from a link that I forgot (sorry). Hope this gives you an idea to find a better solution.

EDIT: Here's the link where I got the idea from: SQL: Repeat a result row multiple times, and number the rows

enter image description here

enter image description here

Upvotes: 1

Related Questions