更新具有相同ID和名称的行

时间:2016-09-17 01:27:09

标签: sql sqlite

这是表t1

id name amount close
1  jon   4000    0
1  jon   5000    0
1  jon   9000    0

我想要在关闭栏末尾的金额总和

id name amount close
1  jon   4000    0
1  jon   5000    0
1  jon   9000  18000

我尝试更新关闭

update t1 set close = (select sum(amount) from t1  where id = '1' group by id)

但是这个查询会像这样更新所有关闭行

id name amount close
1  jon   4000  18000  
1  jon   5000  18000
1  jon   9000  18000

3 个答案:

答案 0 :(得分:0)

我认为你想要一个相关的子查询:

update t1
    set close = (select sum(t11.amount)
                 from t1 t11
                 where t1.id = t11.id
                );

但是,这仍将更新所有行。你只想要最后一个。好吧,在SQL中,行是无序的,但SQLite提供rowid。这允许你这样做:

update t1
    set close = (select sum(t11.amount)
                 from t1 t11
                 where t1.id = t11.id
                )
    where rowid = (select max(rowid)
                   from t1 t11
                   where t1.id = t11.id
                  );

答案 1 :(得分:0)

尝试以下操作。

Update [Temp_Table]
      set [Temp_Table].[close] = (Select sum(amount) from [Temp_Table]  where id=1 group by ID)
      where amount = (Select max(amount) from [Temp_Table] group by id)

答案 2 :(得分:0)

你也可以试试这个:

UPDATE testing1 a
INNER JOIN (SELECT MAX(amount) maxi, 
            SUM(amount) tot FROM testing1) b ON b.maxi = a.amount
SET a.close = b.tot