Need To select Data From One Table After Minus With One Value

北慕城南 提交于 2019-12-13 19:22:54

问题


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:


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


来源:https://stackoverflow.com/questions/17794932/need-to-select-data-from-one-table-after-minus-with-one-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!