Skip to content

Instantly share code, notes, and snippets.

@lhauspie
Created May 23, 2018 01:44
Show Gist options
  • Save lhauspie/9e086a9dfa75bc72a427bb9aa6fb4254 to your computer and use it in GitHub Desktop.
Save lhauspie/9e086a9dfa75bc72a427bb9aa6fb4254 to your computer and use it in GitHub Desktop.
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