3

私の前の質問を参照して GROUP BY 句から生じる列を追加する

SELECT AcctId,Date,
   Sum(CASE
         WHEN DC = 'C' THEN TrnAmt
         ELSE 0
       END) AS C,
   Sum(CASE
         WHEN DC = 'D' THEN TrnAmt
         ELSE 0
       END) AS D
FROM   Table1 where AcctId = '51'
GROUP  BY AcctId,Date
ORDER  BY AcctId,Date

上記のクエリを実行し、目的の結果を得ました..

  AcctId       Date         C        D
    51       2012-12-04   15000      0
    51       2012-12-05   150000  160596
    51       2012-12-06    600        0

今、同じクエリで別の操作を行う必要があります。

私は結果がこのようになる必要があります

  AcctId   Date                                Result

    51       2012-12-04    (15000-0)->       15000  
    51       2012-12-05   (150000-160596) + (15000->The first value)  4404
    51       2012-12-06     600-0         +(4404 ->The calculated 2nd value) 5004

同じクエリで可能ですか??。

4

1 に答える 1

1

再帰 CTE を使用する

;WITH cte AS
 (
  SELECT AcctId, Date,
     Sum(CASE
           WHEN DC = 'C' THEN TrnAmt
           ELSE 0
         END) AS C,
     Sum(CASE
           WHEN DC = 'D' THEN TrnAmt
           ELSE 0
         END) AS D,
     ROW_NUMBER() OVER (ORDER BY AcctId, Date) AS Id 
  FROM   Table1 where AcctId = '51'
  GROUP  BY AcctId, Date
  ), cte2 AS
 (
  SELECT Id, AcctId, Date, C, D, (C - 0) AS Result
  FROM cte
  WHERE Id = 1
  UNION ALL
  SELECT c.Id, c.AcctId, c.Date, c.C, c.D, (c.C - c.D) + ct.Result
  FROM cte c JOIN cte2 ct ON c.Id = ct.Id + 1
  )
  SELECT *
  FROM cte2

SQLFiddle の簡単な例

于 2012-12-16T17:00:45.857 に答える