根据不同列中的计数重复行-SQL

时间:2019-01-28 15:07:22

标签: sql sql-server

我有一个表,其中包含ID和计数。我想重复计数中提到的次数。

我的桌子:

enter image description here

所需的输出:

enter image description here

我的代码:

    create table #temp1(CID int, CVID int, count int)
    insert #temp1
    values
    (9906,  4687,   4),
    (9906,  4693,   5)

    create table #temp2 (CID int,CVID int, count int,ro int)

    ;with t3 as (
    select c.CID,c.CVID, c.count, row_number() over (partition by c.CID order by c.CID) ro 
    from #temp1 c
    )
    insert #temp2 
    select CID,CVID,count,ro from t3 where ro <= count

我的代码缺少一些无法产生预期结果的东西。有帮助吗?!

4 个答案:

答案 0 :(得分:3)

您需要一个最大为count列最大值的数字表,然后该表可用于生成多行。可以使用递归cte完成此数字生成。

--Recursive CTE
with nums(n) as (select max(count) from #temp1
                 union all
                 select n-1 
                 from nums 
                 where n > 1
                )
--Query to generate multiple rows
select t.*,nums.n as ro
from #temp1 t
join nums on nums.n <= t.count

答案 1 :(得分:2)

另一种选择是临时提示表

示例

Select A.*
      ,Ro = B.N
 From  YourTable A 
 Join  ( Select Top 1000 N=Row_Number() Over (Order By (Select NULL)) 
          From  master..spt_values n1 ) B on B.N<=A.[Count]

返回

CID     CVID    COUNT   Ro
9906    4687    4       1
9906    4687    4       2
9906    4687    4       3
9906    4687    4       4
9906    4693    5       1
9906    4693    5       2
9906    4693    5       3
9906    4693    5       4
9906    4693    5       5

答案 2 :(得分:1)

我将使用递归CTE,但直接使用:

with cte as (
      select CID, CVID, count, 1 as ro
      from #temp1
      union all
      select CID, CVID, count, ro + 1
      from cte
      where cte.ro < cte.count
     )
select cte.*
from cte;

如果计数超过100,则需要使用option (maxrecursion 0)

答案 3 :(得分:0)

感谢所有建议。我使用以下查询解决了我的问题:

;with    cte(cid, cvid,count, i) as 
        (
        select  cid
        ,       cvid
        ,       count
        ,       1
        from    #temp1
        union all
        select  cid
        ,       cvid
        ,       count
        ,       i + 1
        from    cte
        where   cte.i < cte.count
        )
select  *
from    cte
order by
        cid,count