Created
November 13, 2019 18:14
-
-
Save michaelminter/b4387c81116a479d1db75ffb32dddcb4 to your computer and use it in GitHub Desktop.
Selecting data with group by comparing arrays
This file contains hidden or 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
# @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