Group BY and having interpretation: the premise must understand a special function in the SQL language: aggregate function,
--such as Sum, COUNT, MAX, AVG, and so on. The fundamental difference between these functions and other functions is that they generally function on more than one record.
The--where keyword cannot be used when using aggregate functions, so the SET function is added to the function to test whether the query results match the condition.
Create TABLE Table1
(
ID int Identity (primary) key is not NULL,
ClassID int,
Sex varchar (10),
Age int,
)
--Add test data
Insert into Table1 values (1, ' Male ', 20)
Insert into Table1 values (2, ' female ', 22)
Insert into Table1 values (3, ' Male ', 23)
Insert into Table1 values (4, ' Male ', 22)
Insert into Table1 values (1, ' Male ', 24)
Insert into Table1 values (2, ' female ', 19)
Insert into Table1 values (4, ' Male ', 26)
Insert into Table1 values (1, ' Male ', 24)
Insert into Table1 values (1, ' Male ', 20)
Insert into Table1 values (2, ' female ', 22)
Insert into Table1 values (3, ' Male ', 23)
Insert into Table1 values (4, ' Male ', 22)
Insert into Table1 values (1, ' Male ', 24)
Insert into Table1 values (2, ' female ', 19
--For example: Query table tables for each class of age greater than 20, gender is the number of men
Select COUNT (*) as ' >20 years ', ClassID from Table1 where sex= ' Men ' GROUP by Classid,age have age>20
Note: When you include the WHERE clause, the GROUP BY clause, the HAVING clause, and the aggregation function, the order of execution is as follows:
--Executes the WHERE clause to find the data that meets the criteria;
--Use the GROUP BY clause to group the data, and the GROUP BY clause to run the aggregate function to calculate the value of each group, and finally remove the non-conforming group with the HAVING clause.
Each element in a--having clause must also appear in the select list. Some database exceptions, such as Oracle.
Both the--having clause and the WHERE clause can be used to set constraints so that the query results meet certain conditional limits.
The--having clause restricts the group, not the row. You cannot use the aggregate function in the WHERE clause, but you can in the HAVING clause.
Having in an SQL statement