开发者

Expand row results based on a value in column (with iterator)

Need help from you all in writing up this query. Running SQL 2005 Standard edition.

I have a basic query that gets a subset of records from a table where the record_Count is greater then 1.

SELECT * 
    FROM Table_Records
    WHERE Record_Count > 1

This query gives me a result set of, say:

TableRecords_ID       Record_Desc               Record_Count
123                   XYZ                       3
456                   PQR                       2

The above query needs to be modified so that each record appears as many times as the Record_Count and has its iteration number with it, as a value. So the new query should return results as follows:

   TableRecords_ID   Record_Desc          Record_Count         开发者_如何学C   Rec_Iteration
   123                XYZ                      3                        1
   123                XYZ                      3                        2
   123                XYZ                      3                        3
    456                PQR                       2                        1
    456                PQR                       2                        2

Could anyone help we write this query up? appreciate the help.

Clarification: Rec_Iteration column is a sub representation of the Record_Count. Basically, since there are three Record_Count for XYZ description thus three rows were returned with the Rec_Iteration representing the Row one , two and three respectively.


You can use a recursive CTE for this query. Below I use a table variable @T instead of your table Table_Records.

declare @T table(TableRecords_ID int,Record_Desc varchar(3), Record_Count int)

insert into @T
select 123, 'XYZ', 3 union all
select 456, 'PQR', 2

;with cte as
(
  select TableRecords_ID,
         Record_Desc,
         Record_Count,
         1 as Rec_Iteration
  from @T
  where Record_Count > 1
  union all  
  select TableRecords_ID,
         Record_Desc,
         Record_Count,
         Rec_Iteration + 1
  from cte 
  where Rec_Iteration < Record_Count
)
select TableRecords_ID,
       Record_Desc,
       Record_Count,
       Rec_Iteration
from cte
order by TableRecords_ID,
         Rec_Iteration
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜