主题:SQL更新语句
zwt
[专家分:1230] 发布于 2007-04-02 11:30:00
Table_A A_VAlue 平均值
A_Name A_Value A_Name AVG
1 12 1 11
2 4 2 7.5
3 7 3 6.5
1 10 4 10
4 6
2 11
3 6
4 14
求一条更新语句,更新Table_A中的A_Value字段为各自A_Name的平均值。最终如下表:
Table_A
A_Name A_Value
1 11
2 7.5
3 6.5
1 11
4 10
2 7.5
3 6.5
4 10
回复列表 (共4个回复)
沙发
lgt9732 [专家分:170] 发布于 2007-04-02 20:27:00
update Table_A set A_Value = AVG from A_VAlue where A_VAlue.A_Name = Table_A.A_Name
板凳
菜鸭 [专家分:5120] 发布于 2007-04-03 08:10:00
update Table_A set A_Value = AVG from Table_A,A_VAlue where Table_A.A_Name = A_VAlue.A_Name
3 楼
zwt [专家分:1230] 发布于 2007-04-04 09:58:00
哥们,A_Value不是一个表,是我为了讲清楚而写的,只有Table_A一个表。
4 楼
潇洒老乌龟 [专家分:1050] 发布于 2007-04-08 11:12:00
if object_id('pubs..tb') is not null
drop table tb
go
create table tb(A_Name int,A_Value decimal(18,1))
insert into tb(A_Name,A_Value) values(1, 12)
insert into tb(A_Name,A_Value) values(2, 4 )
insert into tb(A_Name,A_Value) values(3, 7 )
insert into tb(A_Name,A_Value) values(1, 10)
insert into tb(A_Name,A_Value) values(4, 6)
insert into tb(A_Name,A_Value) values(2, 11)
insert into tb(A_Name,A_Value) values(3, 6)
insert into tb(A_Name,A_Value) values(4, 14)
update tb
set a_value = t.a_value
from tb ,
(select a_name , avg(a_value) a_value from tb group by a_name) t
where tb.a_name = t.a_name
select * from tb
drop table tb
/*
A_Name A_Value
----------- --------------------
1 11.0
2 7.5
3 6.5
1 11.0
4 10.0
2 7.5
3 6.5
4 10.0
(所影响的行数为 8 行)
*/
我来回复