PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 23, 2022

[FIXED] How to update data from 1 table with subqueries

 October 23, 2022     database, sql, sql-update     No comments   

Issue

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:

  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


Answered By - Mostafa NZ
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing