How does MySQL group query results by a specific column?
In MySQL, to group query results by a specific column, you can use the GROUP BY clause. This clause is used to group query results by a specified column and then perform aggregate operations on each group.
Suppose there is a table named “students” with fields: id, name, age, gender, grade. To group the students by the “grade” column and count the number of students in each group, you can use the following query:
SELECT grade, COUNT(*) as num_students
FROM students
GROUP BY grade;
The mentioned query will group by the ‘grade’ column and count the number of students in each group. Using the COUNT(*) function in the SELECT clause allows for counting the number of rows in each group, and then using the AS keyword to give a name to the counted results. The GROUP BY clause specifies to group by the ‘grade’ column.
By using the GROUP BY clause, it is easy to group query results by a specific column and perform aggregate functions.