SQL Server - 递归子行

时间:2017-11-07 08:28:10

标签: sql sql-server recursion

我有这个:

        C1       C2   C3
        100      20    1
        100      40    1

我想要这个:

                       C1           C2    C3
                       100          20    1
                       100-20       40    1 -> 80  40  1
                       100-20-40     0    1 -> 40   0  1

递归?

谢谢!

2 个答案:

答案 0 :(得分:0)

试试这个

    Create table #tmp1 (c1 int, c2 int, c3 int)
    insert into #tmp1 values(100,20,1)
    insert into #tmp1 values(100,40,1)


    select ROW_NUMBER() OVER (ORDER BY (SELECT 150)) as rn,  * 
    into #tmp2
    from #tmp1

    DECLARE @MaxRow INT = 0
    DECLARE @i INT=1
    SELECT @MaxRow= MAX(rn) from #tmp2

    Create table #tmp3 (c1 int, c2 int, c3 int)
    WHILE(@i<=@MaxRow+1)
    BEGIN

        DECLARe @j INT = @i-1

        DECLARE @C1 int=0
        DECLARE @C2 int
        DECLARE @C3 int

        IF(@i<=@MaxRow)
        BEGIN
            SELECT @c2=c2,@c3=c3 From #tmp2 where rn=@i
            SELECT @c1=c1 FROM #tmp2 where rn=1
        END
        ELSE
        BEGIN
            SELECT @c2=0,@c3=1 
            SELECT @c1=100 
        END

        IF(@i>1)
        BEGIN
            WHILE(@j>0)
            BEGIN   
                SELECT @c1=@C1-c2 FROM #tmp2 where rn=@j            
                SET @j=@j-1
            END
        END
        SET @i=@i+1

        INSERT INTO #tmp3 values(@c1,@c2,@c3)
    END


    SELECT * FROM #tmp3

    Drop table #tmp1
    DROP TABLE #tmp2

    DROP TABLE #tmp3

答案 1 :(得分:-1)

希望这有助于:

WITH CTE
AS
(
    SELECT
      SeqNo = ROW_NUMBER() OVER(ORDER BY C1),
      C1,
      C2,
      C3
    FROM T1
)
SELECT
  C1,
  C2,
  C3,
  C4 = ISNULL(C1 - (SELECT SUM(C2) FROM CTE WHERE SeqNo < C.SeqNo ),0)
  FROM CTE C