Jump to content

Recommended Posts

Hey everyone, I am new to MySQL and I have been having a hard time understanding the GROUP BY clause. I have not been able to find a basic example that will let me grasp what it actually does. I am currently reading a MySQL book and here is the code from the book that uses the GROUP BY clause:

 

SELECT state, COUNT(*) AS count FROM president GROUP BY state ORDER BY count DESC;

 

And here is the output from that query:

 

+-------+-------+ 
| state | count |
+-------+-------+
| VA | 8 |
| OH | 7 | 
| MA | 4 | 
| NY | 4 | 
| NC | 2 | 
| VT | 2 | 
| TX | 2 | 
| SC | 1 | 
| NH | 1 | 
| PA | 1 | 
| KY | 1 | 
| NJ | 1 | 
| IA | 1 | 
| MO | 1 |
| CA | 1 | 
| NE | 1 | 
| GA | 1 | 
| IL | 1 | 
| AR | 1 | 
| CT | 1 | 
+-------+-------+

 

Any help explaining what the GROUP BY clause actually does and how it works would be great. I understand the rest of the code except for the GROUP BY part. Thanks in advance for the help.

 

 

Link to comment
https://forums.phpfreaks.com/topic/189493-group-by-clause-help/
Share on other sites

The best way to explain group by is it allows you to place records into groups based on values that are stored in the designed columns.

 

for example:

select gender, count(*) as ct from people group by gender

 

would allow you to group on the column gender, so you would expect to see something like

 

gender --- ct

M --- 50

F --- 40

 

50 records would have the gender value of M, 40 would have the value of F

 

All of your columns that you have in your select need to be in your group by also... and then in your select you can use math functions such as MAX, MIN, SUM, AVG, COUNT

 

mySQL has a good article on the usage of the group by function that you should take a look at if you haven't yet: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

 

I hope all of that makes sense,

Aaron

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.