Skip to content

Commit

Permalink
Simplify query
Browse files Browse the repository at this point in the history
We already have access to the claims in the cte, so don't need to rejoin
to the eligibilities
  • Loading branch information
rjlynch committed Dec 16, 2024
1 parent ff79ef8 commit 54d7f75
Showing 1 changed file with 7 additions and 16 deletions.
23 changes: 7 additions & 16 deletions app/models/admin/reports/duplicate_approved_claims.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,12 @@ def scope

def duplicates_by_eligibility
ActiveRecord::Base.connection.execute(
<<~SQL
WITH eligibilities AS (#{eligibilities_cte})
SELECT claims.id
FROM claims
JOIN eligibilities
ON claims.eligibility_id = eligibilities.id
WHERE claims.academic_year = '#{academic_year}'
SQL
Policies::POLICIES.map do |policy|
policy_with_claimable_policies(policy)
end.compact.join("\nUNION\n")
).map { |row| row["id"] }
end

def eligibilities_cte
Policies::POLICIES.map do |policy|
policy_with_claimable_policies(policy)
end.compact.join("\nUNION\n")
end

def policy_with_claimable_policies(policy)
left_table = policy::Eligibility.table_name

Expand All @@ -81,7 +70,7 @@ def policy_with_claimable_policies(policy)
)

<<~SQL
SELECT #{left_table}.id
SELECT claims.id
FROM #{left_table}
JOIN #{right_table} #{right_table_alias}
ON #{left_table}.id != #{right_table_alias}.id
Expand All @@ -90,7 +79,9 @@ def policy_with_claimable_policies(policy)
JOIN claims other_claims ON other_claims.eligibility_id = #{right_table_alias}.id
JOIN decisions ON claims.id = decisions.claim_id
JOIN decisions other_decisions ON other_claims.id = other_decisions.claim_id
WHERE decisions.result = 0
WHERE claims.academic_year = '#{academic_year}'
AND other_claims.academic_year = '#{academic_year}'
AND decisions.result = 0
AND other_decisions.result = 0
SQL
end.join("\nUNION\n")
Expand Down

0 comments on commit 54d7f75

Please sign in to comment.