Created
May 23, 2018 01:44
-
-
Save lhauspie/9e086a9dfa75bc72a427bb9aa6fb4254 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WITH upd AS ( | |
UPDATE target t | |
SET counter = t.counter + s.counter, | |
FROM source s | |
WHERE t.id = s.id | |
RETURNING s.id | |
) | |
INSERT INTO target(id, counter) | |
SELECT id, sum(counter) | |
FROM source s LEFT JOIN upd t USING(id) | |
WHERE t.id IS NULL | |
GROUP BY s.id | |
RETURNING t.id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment