当前位置: 代码迷 >> Sql Server >> 关于计算数据库平均值的有关问题
  详细解决方案

关于计算数据库平均值的有关问题

热度:66   发布时间:2016-04-27 14:38:08.0
关于计算数据库平均值的问题
现在数据库中有两张表
Table1 为主表
字段
tid(自增) avg_price(平均价格)  
1 0 
2 0
3 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


现在 希望用一句SQL 将table1中的avg_price 更新成 table2 对应的平均值
谢谢 在线等
 

------解决方案--------------------
SQL code
update Table1set avg_price=(select avg(price)               from Table2               where Table2=.ID=Table1.TID)
------解决方案--------------------
SQL code
update table1 set avg_price=t.avg_pricefrom(select tid,avg(price) as avg_price from table1 group by tid) twhere table1.tid=t.tid
------解决方案--------------------
SQL code
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
------解决方案--------------------
SQL code
--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           152           123           8(3 行受影响)
  相关解决方案