Skip to content

Commit

Permalink
optimize distinct votes query
Browse files Browse the repository at this point in the history
  • Loading branch information
benhiller committed Oct 25, 2020
1 parent 3fcbaea commit 45f3af6
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down

0 comments on commit 45f3af6

Please sign in to comment.