22,209
社区成员
发帖
与我相关
我的任务
分享
update a set a.MatId=C.id
from #Sale a join #tbMat b on a.MatID=b.id
join (select ROW_NUMBER() over(partition by name order by id) as rn,* from #tbMat) c
on b.Name=c.Name and c.rn=1
--物料表
create table #tbMat(id int ,
Number varchar(10), Name varchar(10))
insert into #tbMat(id,Number,Name) values(1,'001','老干妈')
insert into #tbMat(id,Number,Name)values(2,'002','老干妈')
insert into #tbMat(id,Number,Name)values(3,'003','王老吉')
--销售表
create table #Sale(id int,MatID int,Many int)
insert into #Sale(id,MatID,Many) values(1,1,12)
insert into #Sale(id,MatID,Many)values(2,2,10)
insert into #Sale(id,MatID,Many)values(3,3,9)
go
update a set matID=(select min(id) from #tbMat where name=(select name from #tbMat where id=a.MatID)) from #sale a
go
select * from #sale
/*
id MatID Many
----------- ----------- -----------
1 1 12
2 1 10
3 3 9
(3 行受影响)
*/