Skip to content

Instantly share code, notes, and snippets.

@michaelminter
Created November 13, 2019 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelminter/b4387c81116a479d1db75ffb32dddcb4 to your computer and use it in GitHub Desktop.
Save michaelminter/b4387c81116a479d1db75ffb32dddcb4 to your computer and use it in GitHub Desktop.
Selecting data with group by comparing arrays
# @param [String] account_id
# @param [String] exclusions
def statement(account_id, exclusions = nil)
<<-STATEMENT
SELECT
JSON_AGG(profiles.id) id,
JSON_AGG(users.external_id) external_id
FROM profiles
LEFT JOIN users ON users.id = profiles.user_id
WHERE
profiles.role = 'Patient'
AND profiles.account_id = #{account_id}
GROUP BY
profiles.account_id,
profiles.location_id,
LOWER(users.last_name),
users.date_of_birth
HAVING
#{exclusions.present? ? "NOT(ARRAY[#{exclusions}] && ARRAY_AGG(users.external_id::TEXT)) AND " : ''}
COUNT(profiles.id) > 1;
STATEMENT
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment