1

I would like to update a column that has missing data based on matches within the same table, for this example, no locations came through on 01/02/20, so based on matching the campaign and ID, update this data.

Sample table:

PersonID| date_serve | campagign | location
--------+----------+--------+---------+
1       | 01/01/2020 |  email    | Sydney   |    
1       | 01/02/2020 |  email    |          | 
2       | 01/01/2020 |  email    | London   | 
2       | 01/02/2020 |  email    |          | 
2       | 01/01/2020 |  text     | New York | 
2       | 01/02/2020 |  text     |          | 

Expected Output:

PersonID| date_serve | campagign | location
--------+----------+--------+---------+
1       | 01/01/2020 |  email    | Sydney   |    
1       | 01/02/2020 |  email    | Sydney   | 
2       | 01/01/2020 |  email    | London   | 
2       | 01/02/2020 |  email    | London   | 
2       | 01/01/2020 |  text     | New York | 
2       | 01/02/2020 |  text     | New York | 

Current script I've developed but returns locations for all IDs to become Sydney:

UPDATE Persons ps
SET location = ps2.location
FROM Persons ps1, Persons ps2
WHERE ps1.PersonID = ps2.PersonID AND ps1.location = '' 
AND ps1.campaign = ps2.campaign
RETURNING ps.PersonID, ps.location, ps.Date_served

Also, a SQL fiddle for the above. http://sqlfiddle.com/#!17/0feac/1

Thanks in advance,

2 Answers 2

2

You have too many references to the table:

UPDATE Persons ps
    SET location = ps2.location
    FROM Persons ps2
    WHERE ps.PersonID = ps2.PersonID AND
          ps.location = '' AND
          ps.campaign = ps2.campaign
    RETURNING ps.PersonID, ps.location, ps.Date_served;
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a subquery:

update persons p
set location = (
  select q.location
  from persons q 
  where q.personid = p.personid and q.date_server = '2020-01-01'
)
where date_serve = '2020-01-02'

Comments

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.