For Those Who Do Not Know GROUP BY
The GROUP BY clause groups duplicate values in a column. For example, if we have categorical nominal values like marital status (Married, Single, Divorced), and a table named person consisting of id, name, marital_status:
- GROUP BY
- COUNT
- AVG
- marital status
The GROUP BY clause groups duplicate values in a column. For example, if we have categorical nominal values like marital status (Married, Single, Divorced), and a table named person consisting of id, name, marital_status:
If we want to count the repeated names—that is, everyone named Ahmed, Mostafa, Omar, Yousry, Mohamed—to know how many people are named Mohamed, how many are named Mostafa, and so on, we write:
SELECT name, COUNT(*) AS count
FROM person
GROUP BY nameThe output will be:
I could have written COUNT(Name) instead of COUNT(*), but it wouldn't make a difference because I am aggregating one thing (counting rows), so it won't affect the output.
And if we want, for example, to count the number of people whose marital status is single, married, etc., we write:
SELECT martial_status, COUNT(*) AS count
FROM person
GROUP BY martial_statusThe output will be:
And if we want to calculate the average age for each marital status, we write:
SELECT martial_status, AVG(age) AS avg
FROM person
GROUP BY martial_statusThe output will be:
Notice that I wrote inside the AVG function the name of the column I want to calculate, because I am sure GROUP BY will group the repeated marital statuses and the function will sum the values and divide by their count to calculate the average.
Here is also a simple and easy explanation by Coach @Saud_Alrshoud: https://macdiscussions.udacity.com/t/group-by/89343