Jump to content

Recommended Posts

Here's the situation. This database has about 150 different categories. This query is supposed to lump all the votes per category together and return the count. However, I'm thinking if someone voted for the same person in two categories, the vote might get lumped into the wrong category. What do you think?

 

SELECT *,COUNT(*) AS `mycount` FROM `table` GROUP BY `vote` HAVING `mycount` > 1 ORDER BY `category`,COUNT( * ) DESC

1) you can't use * with group by

2) the value of "category" will be meaningless

3) you're not using your column alias in your order by

 

The goal of the query is to report how may votes each item received in each category. It seems to be working since I added kickstart's suggestion. Here's the new query:

 

SELECT `category`,`vote`,COUNT(`vote`) AS `counti` FROM `table` GROUP BY `category`,`vote` HAVING `counti` > 3 ORDER BY `category`,`counti` DESC

 

1) SELECT * seems to be returning the results I expect. However, I modified the field query to have no *.

2) ORDER BY `category`keeps the `category` field together, making it easier to determine a winner without having to resort later.

3) yeah, I don't know why I missed this one. It has been remedied.

1) SELECT * seems to be returning the results I expect. However, I modified the field query to have no *.

 

MySQL is pretty tolerant of this, unlike most other flavours of SQL. However consider a table of first name and surname, and you want a count of each surname:-

 

FirstName, Surname

John, Smith

Andrew, Smith

Fred, Blogs

 

If you tried something like SELECT *, COUNT(*) FROM Names GROUP BY Surname, you would get the counts, but with the count of Smith what surname would be brought back?

 

All the best

 

Keith

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.