SQL Server创建缺少的条目

时间:2017-02-14 09:56:14

标签: sql-server

我想在临时表

中添加缺少的序列条目
Declare @tbl as  table
(
    orderid varchar(50),
    sequence int
)


insert into @tbl
select '1548756', 3
union
select '1878966',2

select * from @tbl

当前输出:

1548756 3
1878966 2

我想修改如下输出在临时表中添加缺失序列:

1548756 3
1548756 2
1548756 1
1878966 2
1878966 1

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用初始行作为锚点创建递归cte,并在每次递归时从序列中减去1,直到值为1:

DECLARE @tbl AS  TABLE
    (
      orderid VARCHAR(50) ,
      sequence INT
    );


INSERT  INTO @tbl
        SELECT  '1548756' ,
                3
        UNION
        SELECT  '1878966' ,
                2;

SELECT  *
FROM    @tbl;
WITH    cte
          AS ( SELECT   orderid ,
                        sequence
               FROM     @tbl
               UNION ALL
               SELECT   cte.orderid ,
                        CASE WHEN cte.sequence > 1 THEN cte.sequence - 1
                        END AS sequence
               FROM     cte
                        INNER JOIN @tbl t ON t.orderid = cte.orderid
               WHERE    cte.sequence > 1
             )
    SELECT  *
    FROM    cte
    ORDER BY orderid ,
            sequence desc

给你:

orderid sequence
1548756 3
1548756 2
1548756 1
1878966 2
1878966 1