Combine Records in SQL: GROUP BY & Aggregate
In SQL, aggregate functions and the GROUP BY statement can be used to consolidate multiple rows of data into one.
For instance, suppose there is a table containing students’ grades information, with each student possibly having multiple grade records. If we want to merge all grades for each student into one record, we can use the following SQL statement:
SELECT student_id, MAX(grade) AS max_grade, MIN(grade) AS min_grade, AVG(grade) AS avg_grade
FROM grades
GROUP BY student_id;
In this example, we utilized the MAX, MIN, and AVG aggregation functions to calculate the highest score, lowest score, and average score for each student. We then grouped the data by student ID using the GROUP BY statement, ultimately consolidating multiple grade records into a single record.