GROUP BY

If we need to group rows with the same values into summary rows, we use GROUP BY.

GROUP BY is often used with aggregation functions (SUM, MIN, MAX, AVG, COUNT).

 

Structure:
SELECT column_name
FROM table_name
WHERE condition
GROUP BY column_name
ORDER BY column_name;

 

Example1:

We have a table Customer with this data:

CustomerID Name Hair Salary
1 Alechandro brown 100
2 Katerina blonde 150
3 Lucie blonde 30
4 Thomas black 40
5 Theodor black 120
6 Thomassino black 99
7 Knor brown 50
8 Thor blonde 10
9 Lucie pink 70

 

 

SELECT name, COUNT(salary) 
FROM Customer
GROUP BY name;

The result will be this:

NAME COUNT(SALARY)
Thomas 1
Knor 1
Katerina 1
Thor 1
Lucie 2
Thomassino 1
Alechandro 1
Theodor 1

 

Example2:

We have a table Customer with this data:

CustomerID Name Hair Salary
1 Alechandro brown 100
2 Katerina blonde 150
3 Lucie blonde 30
4 Thomas black 40
5 Theodor black 120
6 Thomassino black 99
7 Knor brown 50
8 Thor blonde 10
9 Lucie pink 70

 

 

SELECT name, COUNT(salary) 
FROM Customer
GROUP BY name
ORDER BY name;

The result will be this:

NAME COUNT(SALARY)
Alechandro 1
Katerina 1
Knor 1
Lucie 2
Theodor 1
Thomas 1
Thomassino 1
Thor 1

 

Leave a Comment

Your email address will not be published. Required fields are marked *