SQL GROUP BY |
SQL Sample Code - SQL GROUP BY keyword. |
| SELECT column_name, aggregate_function(column_name) FROM table_name GROUP BY column_name; |
See the SQL samples section below for an explanation of the GROUP BY keyword.
What does SQL GROUP BY do? |
GROUP BY is used to organise aggregated data into groups by one or more specified database columns.
GROUP BY is used alongside ‘Aggregate Functions’. Go to the ‘Aggregate Functions’ section to learn more.
Sample 1 – SQL GROUP BY using SUM() function. |
In this example we will use the database table ‘tblCompany’.
| Company_ID | CompanyName | Address | Town | Sales |
| 1 | SQL Sample | 1 Sample St | Hamburg | 10000 |
| 2 | SQL Code Land | 2 Code Rd | Hamburg | 20000 |
| 3 | Sample Code World | 66 SQL St | Curry | 18000 |
| 4 | SQL Reference Ltd | 34 Reference St | Pisa | 17000 |
In this SQL sample we want to know the total SUM() for the Sales column in the tblCompany table for each Town.
Use the SELECT statement below:
| SELECT Town, SUM(Sales) FROM tblCompany GROUP BY Town; |
The table of results will look like this:
| Town | SUM(Sales |
| Hamburg | 30000 |
| Curry | 18000 |
| Pisa | 17000 |
Note: To learn more about the SUM() function go to the SUM() section.
Sample 2 – SQL GROUP BY using SUM() function and WHERE clause. |
In this SQL sample we will use the database table ‘tblCompany’.
| Company_ID | CompanyName | Address | Town | Sales |
| 1 | SQL Sample | 1 Sample St | Hamburg | 10000 |
| 2 | SQL Code Land | 2 Code Rd | Hamburg | 20000 |
| 3 | Sample Code World | 66 SQL St | Curry | 18000 |
| 4 | SQL Reference Ltd | 34 Reference St | Pisa | 17000 |
| 5 | MySQL Code Geeks | 5 Sample Ave | Las Vegas | 21000 |
| 6 | SQL Sample House | 32 Code Rd | Hamburg | 15500 |
| 7 | SQL Group Land | 5 Function St | Curry | 18125 |
In this SQL sample we want to know the total SUM() for the Sales column in the tblCompany table grouped by each Town where the Sales are greater than 15000.
Use the SELECT statement below:
| SELECT Town, SUM(Sales) FROM tblCompany WHERE SALES>15000 GROUP BY Town; |
The table of results will look like this:
| Town | SUM(Sales |
| Hamburg | 35500 |
| Curry | 36125 |
| Pisa | 17000 |
Note: To learn more about the WHERE clause go to the WHERE section.
Note: To learn more about the SUM() function go to the SUM() section
Related SQL Sample Code:
|
|