在group by 中使用HAVING篩選結果
【例31】查詢所有價格超過10美元的書的種類和平均價格。
use pubs
go
select type , avg(price) 'avg_price' from titles where price>$10 group by type
go
查詢結果如下:
Type avg_price
------------ ------------------
Business 17.3100
mod_cook 19.9900
popular_comp 21.4750
Psychology 17.5100
trad_cook 15.9633
(所影響的行數為 5 行)
【例32】在所有價格超過10美元的書中,查詢所有平均價格超過18美元的書的種類和平均價格。
use pubs
go
select type , avg(price) 'avg_price' from titles where price>10 group by type having avg(price)>$18
go
查詢的結果是:
Type avg_price
------------ ---------------------
mod_cook 19.9900
popular_comp 21.4750
(所影響的行數為 2 行)
WHERE子句在求平均值之前從表中選擇所需要的行,HAVING子句在進行統計計算後產生的結果中選擇所需要的行
指定組或彙總的搜尋條件。HAVING 通常與 GROUP BY 子句一起使用。如果不使用 GROUP BY 子句,HAVING 的行為與 WHERE 子句一樣。
文法: [HAVING <search_condition>]
參數: <search_condition>: 指定組或彙總應滿足的搜尋條件。當 HAVING 與 GROUP BY ALL 一起使用時,HAVING 子句替代 ALL。 在 HAVING 子句中不能使用 text、image 和 ntext 資料類型。