SQL GROUP BY
ROUP BY clause is used to associate an aggregate function with groups of rows.
The SQL GROUP BY clause is used along with the SQL aggregate functions like SUM, COUNT, MAX, MIN, and AVG to provide means of grouping the result by refer to certain database table column.
The SQL syntax for GROUP BY is :
SELECT AGGREGATE FUNCTION ( [COLUMN NAME] )
FROM [TABLE NAME] GROUP BY[COLUMN NAME]
EXAMPLE (WITH SUM) :
We can use GROUP BY clause to calculate sum of the scores by Department.
Table GameScores
PlayerName | Department | Scores |
Jason | IT | 3000 |
Irene | IT | 1500 |
Jane | Marketing | 1000 |
David | Marketing | 2500 |
Paul | HR | 2000 |
James | HR | 2000 |
SQL statement :
SELECT Department, SUM(Scores)
FROM GameScores
GROUP BY Department
Result:
Department | SUM(Scores) |
HR | 4000 |
IT | 4500 |
Marketing | 3500 |
EXAMPLE (WITH COUNT) :
We can use GROUP BY clause to calculate the number of contestants by Department.
SQL statement :
SELECT Department, COUNT(*)
FROM GameScores
GROUP BY Department
Result:
Department | COUNT(*) |
HR | 2 |
IT | 2 |
Marketing | 2 |