简体   繁体   中英

How to use aggregate function in update in SQL server 2012

CREATE TABLE #TEMP
(
ID INT,
EmpID INT,
AMOUNT INT
)

INSERT INTO #TEMP VALUES(1,1,10)
INSERT INTO #TEMP VALUES(2,1,5)
INSERT INTO #TEMP VALUES(3,2,6)
INSERT INTO #TEMP VALUES(4,3,8)
INSERT INTO #TEMP VALUES(5,3,10)
.
.
.

SELECT * FROM #TEMP

ID EmpID    AMOUNT
1   1       10
2   1       5
3   2       6
4   3       8
5   4       10  

UPDATE #TEMP
SET AMOUNT = SUM(AMOUNT) - 11
Where EmpID = 1

Table consists of employeeID's along with amount assigned to Employee I need to subtract amount from amount filed depending on employee usage.表由员工 ID 以及分配给员工的金额组成,我需要根据员工使用情况从提交的金额中减去金额。 Amount "10" should be deducted from ID = 1 and amount "1" should be deducted from ID = 2.

Credits available for that particular employee depending on date.根据日期可用于该特定员工的积分。

So i need to reduce credits from table depending on condition first i need to subtract from old credits. In my condition i need to collect 11 rupees from empID = 1 so first i need to collect rupee from ID=1 and rupee from the next credit ie ID=2.卢比和从下一个信用(即 ID=2)收集卢比。 For this reason in my expected output for ID=1 the value is and final output should be like ,最终输出应该是这样的

ID EmpID    AMOUNT
1   1       0
2   1       4
3   2       6
4   3       8
5   4       10  

Need help to update records. Check error in my update statement.

I think you want the following: subtract amounts from 11 while remainder is positive. If this is true, here is a solution with recursive cte :

DECLARE @t TABLE ( id INT, amount INT )

INSERT  INTO @t VALUES  
( 1, 10 ),
( 2, 5 ),
( 3, 3 ),
( 4, 2 );

WITH    cte
          AS ( SELECT   * , 17 - amount AS remainder
               FROM     @t
               WHERE    id = 1
               UNION ALL
               SELECT   t.* , c.remainder - t.amount AS remainder
               FROM     @t t
                        CROSS JOIN cte c
               WHERE    t.id = c.id + 1 AND c.remainder > 0
             )
    UPDATE  t
    SET     amount = CASE WHEN c.remainder > 0 THEN 0
                          ELSE -remainder
                     END
    FROM    @t t
            JOIN cte c ON c.id = t.id

SELECT  * FROM    @t

Output:

id  amount
1   0
2   0
3   1
4   2

Here I use 17 as start remainder.

If you use sql server 2012+ then you can do it like:

WITH    cte
          AS ( SELECT   * ,
                        17 - SUM(amount) OVER ( ORDER BY id ) AS remainder
               FROM     @t
             )
    SELECT  id ,
            CASE WHEN remainder >= 0 THEN 0
                 WHEN remainder < 0
                      AND LAG(remainder) OVER ( ORDER BY id ) >= 0
                 THEN -remainder
                 ELSE amount
            END
    FROM    cte
Declare @Deduct int = -11, 
@CurrentDeduct int = 0 /*this represent the deduct per row */
update #TEMP 
        set   @CurrentDeduct = case when abs(@Deduct) >= AMOUNT then Amount else abs(@Deduct) end 
             , @Deduct = @Deduct + @CurrentDeduct
            ,AMOUNT = AMOUNT - @CurrentDeduct
    where EmpID= 1

First you should get a cumulative sum on amount:

select 
  id, 
  amount,
  sum(amount) over (order by id) running_sum 
from #TEMP;

From here we should put 0 on rows before running_sum exceeds the value 11. Update the row where the running sum exceeds 11 and do nothing to rows after precedent row.

select 
id,
amount
running_sum,
min(case when running_sum > 11 then id end) over () as decide
from (

    select 
      id, 
      amount,
      sum(amount) over (order by id) running_sum 
    from #TEMP

);

From here we can do the update:

merge into #TEMP t
using (    
    select 
      id,
      amount
      running_sum,
      min(case when running_sum > 11 then id end) over () as decide
    from (
        select 
          id, 
          amount,
          sum(amount) over (order by id) running_sum 
        from #TEMP
        )
    )a  on a.id=t.id
when matched then update set 
  t.amount = case when a.id = a.decide then a.running_sum - 11
                  when a.id < a.decide then 0
                  else a.amount 
             end;

See an SQLDFIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM