Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update column coming from TOP 1 of another table

Tags:

sql

sql-server

I have 2 tables:

  • City table - columns CityID, Name, Period
  • Assets table - columns AssetID, Name

I have to update the Period column of the City table with AssetID of the Assets table matching with the top 1 where City.Name=Assets.Name. The Assets table have identical names for different assets.

Example Assets table:

AssetID  Name
1        Asset1
2        Asset1
3        Asset2
4        Asset2

How can I do this? I tried with different queries but I am not able to get it.

like image 474
Avinash Avatar asked Aug 05 '11 06:08

Avinash


People also ask

How do you update a column from one table to another table?

UPDATE table SET col = ( SELECT other_col FROM other_table WHERE other_table. table_id = table.id ); Perhaps an easier way is to specify multiple tables after the UPDATE clause. Only the SET expression will perform updates but listing additional tables will allow the tables to be included.

How do you update a specific column?

The UPDATE statement in SQL is used to update the data of an existing table in database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. UPDATE table_name SET column1 = value1, column2 = value2,...


1 Answers

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;
like image 80
bniwredyc Avatar answered Oct 16 '22 10:10

bniwredyc