日期:2014-05-18  浏览次数:20564 次

更新求和数据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
------解决方案--------------------
SQL code

create table table_1
(
    f_key        int
,    f_IsSysSN    int
,    f_Qty        int
)
go
insert into table_1
select 1001,0,0 union all
select 1001,3,0 union all
select 1001,5,0    union all
select 1002,2,0    union all
select 1002,2,0
go


update table_1 set f_qty=(select sum(f_issyssn) from table_1 where f_key=1001 group by f_key )
where f_key=1001

update table_1 set f_qty=(select sum(f_issyssn) from table_1 where f_key=1002 group by f_key )
where f_key=1002

select * from table_1

f_key       f_IsSysSN   f_Qty
----------- ----------- -----------
1001        0           8
1001        3           8
1001        5           8
1002        2           4
1002        2           4

(5 行受影响)