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

B表改动后如何更新到A表中
A表  
Type_Id  
single_hours
sum_hours  

B表  
Bulb_Id(自动编号)  
Type_Id  
single_hours  

A表对应于B表的多条记录,两者的关系用Type_Id连接,
想实现的功能是:
从B表中将具有相同Type_id的single_hours求和,然后把求得的和将A表中的sum_hours更新,同时将B表相同Type_Id中的最后一条记录中的single_hours的值更新到具有相同Type_Id的A表的single_hours字段中,sql语句应该怎么写(不用存储过程和触发,简单语句即可,能在一条语句里面实现就更好了)


------解决方案--------------------
to sweetriver:但是我要的是用B表相同Type-ID的最后一条记录的single_hours去更新A表相同的Type-Id的singlehours
---------------------------------
--你测试下,已经实现了啊
update a
set single_hours = (select single_hours from b where bulb_id = t.bid),
sum_hours = t.hours
from a,
(select type_id,sum(single_hours) hours,max(bulb_id) bid from b group by type_id) t
where a.type_id = t.type_id