Grouping Data: 03 Using the HAVING Clause 1
/*
mysql> Select * from StudentExam;
+-----------+------+------------+
| StudentID | Mark | Comments |
+-----------+------+------------+
| 10 | 76 | Java |
| 10 | 65 | C# |
| 10 | 79 | JavaScript |
| 11 | 66 | Java |
| 11 | 85 | C# |
| 11 | 69 | JavaScript |
+-----------+------+------------+
6 rows in set (0.00 sec)
mysql> /* Real command */
mysql> SELECT StudentID, AVG(Mark) AS AverageMark
-> FROM StudentExam
-> GROUP BY StudentID
-> HAVING AVG(Mark) < 50 OR AVG(Mark) > 70;
+-----------+-------------+
| StudentID | AverageMark |
+-----------+-------------+
| 10 | 73.3333 |
| 11 | 73.3333 |
+-----------+-------------+
2 rows in set (0.01 sec)
*/
/* Create table */
Drop TABLE StudentExam;
CREATE TABLE StudentExam (
StudentID INT NOT NULL,
Mark INT,
Comments VARCHAR(255)
)TYPE = InnoDB;
/* Insert data */
INSERT INTO StudentExam (StudentID,Mark,Comments) VALUES (10,76,'Java');
INSERT INTO StudentExam (StudentID,Mark,Comments) VALUES (10,65,'C#');
INSERT INTO StudentExam (StudentID,Mark,Comments) VALUES (10,79,'JavaScript');
INSERT INTO StudentExam (StudentID,Mark,Comments) VALUES (11,66,'Java');
INSERT INTO StudentExam (StudentID,Mark,Comments) VALUES (11,85,'C#');
INSERT INTO StudentExam (StudentID,Mark,Comments) VALUES (11,69,'JavaScript');
Select * from StudentExam;
/* Real command */
SELECT StudentID, AVG(Mark) AS AverageMark
FROM StudentExam
GROUP BY StudentID
HAVING AVG(Mark) < 50 OR AVG(Mark) > 70;
Related examples in the same category