Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update data from 1 table with subqueries

So, I have 3 columns: building_name, latitude, longitude.

Some of the lats and longs haven’t been filled in, however they have in other records. This means I can extract the latitude and longitude on other records matching the building name.

I need to do the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Get all records with lat and long that are not null and contain a building name
  2. Get all records with a null lat or long, but have a building name
  3. Update all records (lat and long fields) from 2 with all records from 1 that have a matching building name

What’s the best way to go about this?

>Solution :

Try this query. Because I didn’t have a sample table, I couldn’t test

WITH CTE1 AS 
    (SELECT building_name, latitude, longitude FROM TBL WHERE ISNULL(building_name ,'') <> '' AND ISNULL(latitude ,'') <> '' AND ISNULL(longitude ,'') <> '') , 
    
    CTE2 AS 
    (SELECT building_name, latitude, longitude FROM TBL WHERE ISNULL(building_name ,'') <> '' AND ISNULL(latitude ,'') = '' AND ISNULL(longitude ,'') = '')

    UPDATE CTE2 SET latitude = CTE1.latitude , longitude = CTE1.longitude FROM CTE2 INNER JOIN CTE1 ON CTE2.building_name = CTE1.building_name
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading