Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

T-SQL – How to use results of a query to select multiple rows based on a count

Considering the below example Person table, I am looking for a way to return multiple rows based on an X value. So, if the BagsOut count is, say 3, I would want 3 copies of the row returned or if it was 2 then 2 copies should be returned, and so on:

ID      Name      BagsOut
1       Ken       1
2       Dave      3
3       Ben       2

Desired result:

ID      Name      BagsOut
1       Ken       1
2       Dave      3
2       Dave      3
2       Dave      3
3       Ben       2
3       Ben       2

Is it possible to write this into a single query? I am using T-SQL.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Many thanks in advance for looking.

>Solution :

you can use recursive CTE to achieve this.

declare @t table(ID int,      Name char(5),      BagsOut int)

insert into @t values
(1       ,'Ken',       1)
,(2       ,'Dave',     3)
,(3       ,'Ben',       2)

;with cte_bags as
(
select id, name, BagsOut,1 as currentRow from @t 
union all
select id, name, BagsOut, currentRow+1 
from cte_bags
where currentRow < BagsOut)
select id, name, BagsOut from cte_bags
order by id
id name BagsOut
1 Ken 1
2 Dave 3
2 Dave 3
2 Dave 3
3 Ben 2
3 Ben 2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading