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

sweetriver 2007-04-04 08:10:22
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语句应该怎么写(不用存储过程和触发,简单语句即可,能在一条语句里面实现就更好了)
...全文
191 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
ydage 2007-04-04
  • 打赏
  • 举报
回复
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

sweetriver 2007-04-04
  • 打赏
  • 举报
回复
你好!谢谢


update a
set a.single_hours = b.single_hours , a.sum_hours = b.sum_hours
from a
left join
( select type_id, max(single_hours) single_hours , sum(single_hours ) sum_hours from b group by type_id) b on a.type_id = b.type_id

可以使用,但是我要的是用B表相同Type-ID的最后一条记录的single_hours去更新A表相同的Type-Id的singlehours而不是最大的一条Max(single_hours)记录,应该怎么写呢?
ydage 2007-04-04
  • 打赏
  • 举报
回复
create table a (Type_Id int,single_hours int,sum_hours int)
go
create table b (Bulb_id int identity,type_id int,single_hours int)
go
insert a select 1,3,10
union all select 2,5,8
union all select 3,4,9
go

insert b select 1,2
union all select 1,4
union all select 1,8
union all select 2,9
union all select 2,8
union all select 3,2
union all select 3,8
union all select 3,7
union all select 3,18
go

--执行
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

--结果
Type_Id single_hours sum_hours
1 8 14
2 8 17
3 18 35
47522341 2007-04-04
  • 打赏
  • 举报
回复
update a
set a.single_hours = b.single_hours , a.sum_hours = b.sum_hours
from a
left join
( select type_id, max(single_hours) single_hours , sum(single_hours ) sum_hours from b group by type_id) b on a.type_id = b.type_id

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧