Question

I have a table, with the following columns: id name vote

Each name is unique, and each vote is either null or contains a name.

I need a MySQL statement to return how many votes each person has, and who voted for each person.

I've been working on this for 3 hours, and I'm at a complete loss, so I honestly don't care how inefficient it is, or how you do it.

Was it helpful?

Solution

How many votes:

select 
 count(*) as numVotes, 
 vote
from
 voteTable
where
 vote IS NOT NULL
group by 
 vote
order by
 numVotes desc

Who voted for each:

Select
 name,
 vote
from
 voteTable

... unless I'm misreading something, it should be that simple

OTHER TIPS

SELECT name, count(*) as num_votes, GROUP_CONCAT(vote) as voted_by FROM table GROUP BY 1

select count(name), id from your_table where vote is not null group by (name) 

To get number of votes per person:

select vote, 
       count(*) as nbr_of_votes 
  from table 
 where vote is not null 
 group by vote 
 order by nbr_of_votes desc;

To get who voted for whom you basically has to select the entire table, leaving out the nulls

select vote, 
       name 
  from table
 where vote is not null 
 order by vote;
SELECT VOTE, COUNT(1) Number_Of_Votes,
GROUP_CONCAT(Name)
WHERE VOTE is Not NULL
GROUP BY VOTE
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top