Skip to content
Advertisement

Query which outputs the number of athletes that voted for someone in the same athletePosition? [closed]

Like the title says, SQL query which outputs the number of athletes that voted for someone in the same athletePosition as himself.

I have 4 tables in my database right now, they consist of:

Here is some sample data for ATHLETE Table.

(3B, SS, 2B, 1B, etc. being the positions)

Here is some sample data for the Team table.

My expected query result should be 2.

So that means that 2 athletes voted for someone who plays the same position as themselves.

I was thinking the query’s top half should be something like:

I am not sure what the WHERE would be.

Any help would be much appreciated.

Advertisement

Answer

You could accomplish this using an inner join with the same table. In the proposed solution, I aliased one voter to represent those who casted votes and the other nominated for those who votes were cast for. The inner join was done on the athletePosition on both table aliases and voter.votesForId= nominated.athleteId before finding the total records.

It was difficult to replicate with the shared schema and data however, I believe the StackOverflow community has shared some valuable insights on how to proceed with these in the comments.

I have shared a db-fiddle that replicates your problem and the proposed solution.

Setup

Proposed Solution

Returns:

num_votes
2

db<>fiddle here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement