Search code examples
mysqljoinvoting

Getting winners from database per position - Voting system


So I have my data in the table in this format

Candidate Name      Position ID       Total Votes
_____________     _____________     _____________
Name 1                   1                 1
Name 2                   1                 3
Name 3                   2                 1
Name 4                   2                 4
Name 5                   3                 1
Name 6                   3                 5

How can I get the each winners per position. I try many queries but didnt get the right results. Any help would be appreciated.


Solution

  • Here's a possible solution which could be slightly naïve but I can't seem to be able to think of a better version.

    Let us consider a table with the details as follows:

    CREATE TABLE VOTING (Name TEXT, position integer, votes integer);
    INSERT INTO VOTING VALUES("Name 1", 1, 1);
    INSERT INTO VOTING VALUES("Name 2", 1, 3);
    INSERT INTO VOTING VALUES("Name 3", 2, 1);
    INSERT INTO VOTING VALUES("Name 4", 2, 4);
    INSERT INTO VOTING VALUES("Name 5", 3, 1);
    INSERT INTO VOTING VALUES("Name 6", 3, 5);
    

    Query is:

    SELECT name, 
           A.position, 
           votes 
    FROM   voting A, 
           (SELECT position, 
                   Max(votes) AS M 
            FROM   voting 
            WHERE  position IN (SELECT DISTINCT( position ) 
                                FROM   voting) 
            GROUP  BY position) B 
    WHERE  A.position = B.position 
           AND A.votes = B.m; 
    

    My thought process was as follows:

    • First select all possible distinct position values.
    • For each distinct position retrieve the max(votes) for that position.
    • Attach the max(votes) column to the original table where position values match, so that means for each row and position pair there is a max(votes) for that position available.
    • Filter this new table where position matches and original vote value matches the max(votes) value and you have the table. You can further order these however you want (ASC/DESC)

    The result is as follows:

    Name    position    votes
    ------  --------    -----
    Name 2  1           3
    Name 4  2           4
    Name 6  3           5
    

    Here's a link to a running sample: http://sqlfiddle.com/#!9/8d7ce6/54/0