Need To select Data From One Table After Minus Wit

2019-08-14 16:51发布

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

1条回答
beautiful°
2楼-- · 2019-08-14 17:16

The easiest way to do this would be to use a running aggregate. In your original example, you had two tables, and if this is the case, simply run a sum on that table like I am doing in the subselect and store that value in the variable I created @Sum.

The CTE calculates what the value would be as it is added together for each record, and is then added to the total calculated, and then keeps the ones that are positive.

I believe that this will fit your need.

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
查看更多
登录 后发表回答