34,594
社区成员
发帖
与我相关
我的任务
分享
/*表与字段说明
tb1 表1
tb2 表2
ls 序号
name 名字
bh 编号
mch 名称
*/
create table tb1(ls varchar(20),name varchar(20))
go
insert into tb1
select '001','五五' union all
select '001','田田' union all
select '001','七七' union all
select '002','方方' union all
select '003','红红' union all
select '003','花花' union all
select '004','牛牛' union all
select '004','丽丽'
select * from tb1
go
create table tb2(bh varchar(20),mch varchar(20))
go
insert into tb2
select '001','0' union all
select '002','0' union all
select '003','0' union all
select '004','0'
select * from tb2
go
/*现在需要一条更新语句,把tb2表中的mch字段更新成tb1表的name,
重点是提取tb1表中001这一组的第一条'五五'来更新,或者从001里面随机
提取一条更新.(随机或者只提第一条都可以)为方便演示更新效果,
下面的结果是提取每一组的第一条进行更新,更新完查询tb2效果如下
bh mch
---- -----
001 五五
002 方方
003 红红
004 牛牛
*/
-- MAX
update tb2 set mch = (select max(name) from tb1 where ls = bh)
go
-- 第一个
update tb2 set mch = (select top 1 name from tb1 where ls = bh)
go
-- 随机取
update tb2 set mch = (select top 1 name from tb1 where ls = bh order by NEWID())
go