From 45f3af6ba527034100c3a28189668baf218f7eea Mon Sep 17 00:00:00 2001 From: bhiller Date: Sat, 24 Oct 2020 22:36:38 -0700 Subject: [PATCH] optimize distinct votes query --- src/data.js | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/data.js b/src/data.js index 26086aa..f1dc81d 100644 --- a/src/data.js +++ b/src/data.js @@ -102,16 +102,19 @@ export async function getContestResults(query) { let contestsToVotes = {}; if (query.candidate) { - const distinctVotes = await applyCandidateFilter( - knex('vote') - .count(knex.raw('DISTINCT(tabulator_id, batch_id, record_id)'), { - as: 'distinct_votes', - }) - .select('contest_id') - .where('election_id', electionId) - .groupBy('contest_id'), - query.candidate, - ); + const distinctVotes = await knex + .count() + .select('contest_id') + .from( + applyCandidateFilter( + knex('vote') + .distinct(['tabulator_id', 'batch_id', 'record_id']) + .select('contest_id') + .where('election_id', electionId), + query.candidate, + ).as('distinct_votes'), + ) + .groupBy('contest_id'); contestsToVotes = Object.fromEntries( distinctVotes.map((row) => [ row.contest_id.toString(),