看結果,果斷搞懂group by || group by having
最終要的結果是:每個班年齡大於20歲的男性同學各是多少
create TABLE Table1
(ID int identity(1,1) primary key NOT NULL,
classid int,
sex varchar(10),
age int,
)
Insert into Table1 values(1,'男',20)
Insert into Table1 values(2,'女',22)
Insert into Table1 values(3,'男',23)
Insert into Table1 values(4,'男',22)
Insert into Table1 values(1,'男',24)
Insert into Table1 values(2,'女',19)
Insert into Table1 values(4,'男',26)
Insert into Table1 values(1,'男',24)
Insert into Table1 values(1,'男',20)
Insert into Table1 values(2,'女',22)
Insert into Table1 values(3,'男',23)
Insert into Table1 values(4,'男',22)
Insert into Table1 values(1,'男',24)
Insert into Table1 values(2,'女',19)
SELECT classid , COUNT(*)as renshu FROM Table1 WHEREsex='男' group by classid ,age HAVING age>20
執行結果 :
去掉age 再執行,就會報錯:HAVING 子句中的列 'Table1.age' 無效,因爲該列沒有包含在聚合函數或 GROUP BY 子句中
SELECT b.classid, SUM(b.renshu) FROM
(SELECT classid , COUNT(*)as renshu FROM Table1 WHERE sex='男' group by classid ,age HAVING age>20) b
GROUP BY b.classid