我有两张桌子:
City
表格 - 列CityID
,Name
,Period
Assets
表格 - 列AssetID
,Name
我必须更新Period
表格的City
列,其中AssetID
表的Assets
与City.Name=Assets.Name
的前1位匹配。 Assets
表具有相同的不同资产名称。
示例Assets
表:
AssetID Name
1 Asset1
2 Asset1
3 Asset2
4 Asset2
我该怎么做?我尝试了不同的查询,但我无法得到它。
答案 0 :(得分:13)
UPDATE City
SET Period = a.AssetID
FROM (SELECT TOP 1 AssetID, Name FROM Assets ORDER BY AssetID ASC) AS a
WHERE City.Name = a.Name;
答案 1 :(得分:0)
这应该有效:
update City
set Period = (
select top 1 a.AssetID
from Assets a
where City.Name = a.Name
order by a.AssetId asc)
要测试的示例代码:
create table #City (CityId varchar(20), [Name] varchar(20), Period varchar(20))
create table #Assets (AssetId varchar(20), [Name] varchar(20))
insert into #City values (1, 'Asset1', null)
insert into #City values (2, 'Asset2', null)
insert into #City values (3, 'Asset3', null)
insert into #Assets values (1, 'Asset1')
insert into #Assets values (2, 'Asset1')
insert into #Assets values (3, 'Asset1')
insert into #Assets values (4, 'Asset2')
insert into #Assets values (5, 'Asset2')
insert into #Assets values (6, 'Asset3')
insert into #Assets values (7, 'Asset3')
select * from #City
select * from #Assets
update #City
set Period = (
select top 1 a.AssetID
from #Assets a
where #City.Name = a.Name
order by a.AssetId asc)
select * from #City
drop table #City
drop table #Assets