1

I have the below SQL Server tables:

Asset Table

+---------+-----------+------------+
| AssetID | AssetName | LocationID |
+---------+-----------+------------+

Location Table

+-------------+---------------+------------------+
|  LocationID |  LocationName |  SubLocationName |
+-------------+---------------+------------------+

How can I return results where the Assets Table LocationID = Location Table LocationID but also append the corresponding LocationName and SubLocationName as extra columns?

Assets Table

+---------+-----------+------------+
| AssetID | AssetName | LocationID |
+---------+-----------+------------+
|       1 | Asset1    |        123 |
+---------+-----------+------------+

Location Table

+------------+--------------------+----------------------+
| LocationID | LocationName       | SubLocationName      |
+------------+--------------------+----------------------+
|        123 | Area1              | Sub1                 |
+------------+--------------------+----------------------+

would return:

+--------+-------+------+
| Asset1 | Area1 | Sub1 |
+--------+-------+------+

Thanks Paul.

1
  • Have you tried inner join? Commented Mar 26, 2019 at 5:16

2 Answers 2

1

You need to join the tables and query the columns you're interested in:

SELECT AssetName, LocationName, SubLocationName
FROM   Assets a
JOIN   Location l ON a.LocationId = l.LocationId
Sign up to request clarification or add additional context in comments.

2 Comments

Mureinik, thanks for the reply. If I use the query I get 'invalid column name SubLocationName'. If I remove SubLocationName from the query it runs but returns 0 rows?
that means you do not have data in your table which match the records or by mistake you have selected different database. please verify once
0
    SELECT a.AssetID,a.AssetName,l.LocationName, l.SubLocationName
    FROM   Assets a
    JOIN   Location l ON a.LocationId = l.LocationId

1 Comment

Thanks piraji. Your query is exactly what I required. Paul.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.