日期:2014-05-18 浏览次数:20617 次
update Table1
set avg_price=(select avg(price)
               from Table2
               where Table2=.ID=Table1.TID)
------解决方案--------------------
update table1 set avg_price=t.avg_price from (select tid,avg(price) as avg_price from table1 group by tid) t where table1.tid=t.tid
------解决方案--------------------
update table1 set avg_price = (select avg(price) from table2 where table2.tid = table1.tid)
------解决方案--------------------
update table1 set avg_price=t.avg_price
from
(select tid,avg(price) as avg_price from table1 group by tid) t
where table1.tid=t.tid
------解决方案--------------------
--Table1 为主表
--字段
--tid(自增) avg_price(平均价格)   
--1 0  
--2 0
--3 0
 create table table1(tid int identity(1,1) not null ,avg_price int)
 insert into table1 values(0),(0),(0)
--Table2 为详细信息表
--id(自增) tid(Table1中的id) price
--1 1 10
--2 1 15
--3 1 20
--4 2 10
--5 2 12
--6 2 14
--7 3 8
--8 4 10
--9 5 6
 create table table2(id int identity(1,1) not null ,tid int,price int)
 insert into table2 values(1,10),(1,15),(1,20),(2,10),(2,12),(2,14),(3,8),(4,10),(5,6)
 
--    现在 希望用一句SQL 将table1中的avg_price 更新成 table2 对应的平均值
--谢谢 在线等
update table1   set avg_price=(select AVG(price) from table2  where table1.tid=table2.tid) 
  select * from table1
 drop table table1,table2
tid         avg_price
----------- -----------
1           15
2           12
3           8
(3 行受影响)