1

I have a table and a single value

Table 1                
SNo           Amount     
 1              100         
 2              500         
 3              400         
 4              100 


 Value:  800

Now I want the result from the table is Minus the value and finally

I would like to having rolling subtraction, that is subtract the Value 800 From Table 1's first Amount and then apply it to subsequent rows. Eg:

for type-1
800 - 100 (Record1) =  700
700 - 500 (record2) =  200
200 - 400 (record3) = -200 

The table records starts from record 3 with Balance Values Balance 200

Table-Output
SNo       Amount
 1         200
 2         100

that means if minus 800 in first table the first 2 records will be removed and in third record 200 is Balance

4

1 回答 1

2

最简单的方法是使用运行聚合。在您的原始示例中,您有两个表,如果是这种情况,只需像我在子选择中所做的那样对该表运行求和并将该值存储在我创建的变量@Sum 中。

CTE 计算将每条记录加在一起的值,然后将其添加到计算的总数中,然后保留正值。

我相信这将满足您的需求。

DECLARE @Sum INT;
SET @Sum = 800;

WITH    RunningTotals
          AS (
               SELECT   [SNo]
                      , [Amount]
                      , [Amount] + (
                                     SELECT ISNULL(SUM([Amount]), 0)
                                     FROM   [Table1] t2
                                     WHERE  t2.[SNo] < t.SNo
                                   ) [sums]
               FROM     [Table1] t
    ),
    option_sums
      AS (
           SELECT   ROW_NUMBER() OVER ( ORDER BY [SNo] ) [SNo]
                  , CASE WHEN ( [Sums] - @Sum ) > 0 THEN [Sums] - @Sum
                         ELSE [Amount]
                    END AS [Amount]
                  , sums
                  , [Amount] [OriginalAmount]
                  , [OriginalID] = [SNo]
           FROM     [RunningTotals] rt
           WHERE    ( [Sums] - @Sum ) > 0
         )
 SELECT [SNo]
      , CASE [SNo]
          WHEN 1 THEN [Amount]
          ELSE [OriginalAmount]
        END AS [Amount]
      , [OriginalID]
 FROM   option_sums 

SNo Amount  OriginalID
--- ------  ----------
1   200     3
2   100     4
3   100     5
4   500     6
5   400     7
6   100     8
7   200     9
于 2013-07-22T14:06:32.347 回答