Arsen Ivanov

Science and Technology Blog

Archive for the 'programming' Category

MySQL “SELECT … GROUP BY” statement

Let us say you have a table or times when people arrive at work. One column identifies a person by his or her name and second column records time when person arrived. How would “ask” MySQL for information on how often does each individual person come to work?

This is easily done with “SELECT … GROUP BY”.

Let’s assume that table is set up like so (pseudo-code, this is not actual MySQL code):

VARCHAR(20) name, TIMESTAMP time

So, to select all individuals and count how many times they arrived, do this:

SELECT name, COUNT(*) FROM tbl_your_table_here GROUP BY name;

So, we group rows by name, then count for each individual name! Voila! This is a bit counter-intuitive, but it works! You can also sort ascending or descending like this:

SELECT name, COUNT(*) FROM tbl_your_table_here GROUP BY name ORDER BY name DESC;

No comments