现在数据库中有两张表
Table1 为主表
字段
tid(自增)   avg_price(平均价格)    
1           0 
2           0
3           0Table2 为详细信息表
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
现在 希望用一句SQL 将table1中的avg_price 更新成 table2 对应的平均值
谢谢 在线等
  

解决方案 »

  1.   

    update Table1
    set avg_price=(select avg(price)
                   from Table2
                   where Table2=.ID=Table1.TID)
      

  2.   

    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
      

  3.   

    update table1 set
      avg_price = (select avg(price) from table2 where table2.tid = table1.tid)
      

  4.   

    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
      

  5.   

    --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,table2tid         avg_price
    ----------- -----------
    1           15
    2           12
    3           8(3 行受影响)