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,
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;
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.