如何更新来自另一个表的TOP 1的列

时间:2011-08-05 06:25:53

标签: sql sql-server

我有两张桌子:

  • City表格 - 列CityIDNamePeriod
  • Assets表格 - 列AssetIDName

我必须更新Period表格的City列,其中AssetID表的AssetsCity.Name=Assets.Name的前1位匹配。 Assets表具有相同的不同资产名称。

示例Assets表:

AssetID  Name
1        Asset1
2        Asset1
3        Asset2
4        Asset2

我该怎么做?我尝试了不同的查询,但我无法得到它。

2 个答案:

答案 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