...

Database Managment - MySql

Back to Course

Lesson Description


Lession - #1346 SQL GroupBy



SQL GROUP BY

The GROUP BY statement, for example, "identify the number of consumers in each country," groups rows with the same values into summary rows.
To group the result set by one or more columns, the GROUP BY statement is frequently used with aggregate functions (COUNT(>
, MAX(>
, MIN(>
, SUM(>
, AVG

Demo Database

Below is a selection from the "Customers" table is the sample database:

CustomerID CustomerName ContactName Address City PostalCode Country
1 Rahul Desai Rahul Green Street 57 México D.F. 12209 Germany
2 Raj Ahuja Raja Avda Constitución 2222 Berlin 05021 Mexico
3 Moreno Taquería Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Alwa Horn Thomas Thomas Mariiot Reforma Hotel London WA1 1DP UK
5 Soniya Fernandis Fernandis Icehotel, Jukkasjarvi Luleå S-958 22 Sweden

GROUP BY Syntax

SELECT column_name(s>
FROM table_name WHERE condition GROUP BY column_name(s>
ORDER BY column_name(s>
;



SQL GROUP BY Examples

The following SQL statement lists the number of customers in each country:

SELECT COUNT(CustomerID>
, Country FROM Customers GROUP BY Country;


Output:
CustomerID Country
1

Germany
2 Mexico
3 Mexico
4 UK
5 Sweden