更新求和数据sql
一个表3个字段,想根据f_key group by
求和数据更新到Qty字段上
Table_1
f_key(int) f_IsSysSN(int) f_Qty(int)
1001 0 0
1001 3 0
1001 5 0
1002 2 0
1002 2 0
select sum(f_IsSysSN),f_key from Table_1
group by f_key
用sql语句更新
最后想更新数据后是下面这效果
Table_1
f_key(int) f_IsSysSN(int) f_Qty(int)
1001 0 8
1001 3 8
1001 5 8
1002 2 4
1002 2 4
[解决办法]
update a
set f_Qty = b.sum_qty
from Table_1 a ,(select sum(f_IsSysSN) as sum_qty,f_key from Table_1 where f_key=a.f_key) b
where a.f_key=b.f_key
[解决办法]
create table table_1( f_key int, f_IsSysSN int, f_Qty int)goinsert into table_1select 1001,0,0 union allselect 1001,3,0 union allselect 1001,5,0 union allselect 1002,2,0 union allselect 1002,2,0goupdate table_1 set f_qty=(select sum(f_issyssn) from table_1 where f_key=1001 group by f_key )where f_key=1001update table_1 set f_qty=(select sum(f_issyssn) from table_1 where f_key=1002 group by f_key )where f_key=1002select * from table_1f_key f_IsSysSN f_Qty----------- ----------- -----------1001 0 81001 3 81001 5 81002 2 41002 2 4(5 行受影响)