Recursive Common Table Expression

2019-07-23 13:43发布

问题:

I know I am probably going about this the wrong way, but I am trying to understand Recursive CTE's.

I created a simple table

RowNum  Type    Amount
1       Anch    10
2       Amt     1
3       Amt     2
4       Amt     3
5       Amt     4

The idea was to anchor at the amount 10, the to recursively loop through and remove the amount from the total.

I came up with below

WITH cte_Rec (RowNum, [Type], Amount, Amount2, RT, RN)
     AS (SELECT RowNum,
                [Type],
                Amount,
                Amount,
                Amount,
                RowNum
         FROM   dbo.tbl_RecursiveCTE
         WHERE  [Type] = 'Anch'
         UNION ALL
         SELECT r.RowNum,
                r.[Type],
                r.Amount,
                ct.Amount,
                ct.Amount - r.Amount AS RT,
                ct.RowNum
         FROM   dbo.tbl_RecursiveCTE r
                INNER JOIN cte_Rec ct
                  ON ct.RowNum = r.RowNum - 1)
SELECT *
FROM   cte_Rec  

Which obv does not work.

Any ideas?

回答1:

Not sure what doesn't work for you and what exactly you really want .....

But something like this should work:

;WITH cte_Rec AS 
(
  SELECT RowNum, RowType, Amount AS 'Amount', Amount AS 'SumAmt'
  FROM dbo.tbl_RecursiveCTE
  WHERE RowType = 'Anch'

  UNION ALL 

  SELECT r.RowNum, r.RowType, r.Amount, CAST(ct.SumAmt - r.Amount AS DECIMAL(18,2))
  from dbo.tbl_RecursiveCTE r
  INNER JOIN cte_Rec ct on ct.RowNum = r.RowNum - 1
)
SELECT  *
FROM cte_Rec

I get an output of:

RowNum  RowType  Amount SumAmt
 1      Anch     10.00   10.00
 2      Amt       1.00    9.00
 3      Amt       2.00    7.00
 4      Amt       3.00    4.00
 5      Amt       4.00    0.00

The Amount row shows the amount for that specific row, while SumAmt starts with the 10.00 and then consecutively subtracts the other amounts - is that what you're looking for??