group by子句和having子句都是select子句
返回供應商DLL01的總產品數
select count(*) as num_prods, vend_id
from products
where vend_id = 'DLL01';
用分組把數據分爲多個邏輯組,對每個組進行聚集計算
創建分組:select語句的group by子句
select vend_id, count(*) as num_prods
from products
group by vend_id;
group by指示DBMS按照vend_id分組數據,然後對每個組再聚集計算。
注意不用group by會報錯:
select vend_id, count(*) as num_prods
from products;
過濾分組:having子句
厲害了,
- having子句非常類似於where子句,目前學過的所有類型的where子句都可以用having替代
- having也是過濾,但是過濾的是分組,而where過濾的是行
示例1
select cust_id, count(*) as orders
from orders
group by cust_id
having count(*) >=2;
如果沒有having子句,則輸出如下,所以having子句確實過濾了3個分組。這裏的過濾是基於分組聚集值,而不是特定行的值
示例2:having和where一起用
select vend_id, count(*) as num_prods
from products
where prod_price >= 4
group by vend_id
having count(*) >= 2;
看看供應商和價格情況
select vend_id, prod_price
from products;
可以看到,where語句先過濾了價格小於4的,然後再根據行數大於2來聚集
分組的排序
使用group by應該也給出order by,不要只依賴group by
沒有用order by
select order_num, count(*) as items
from orderitems
group by order_num
having count(*) >= 3;
出來的順序不知道是什麼順序
給出order by,按照items數量先排序,items相同的再按照訂單號排序
select order_num, count(*) as items
from orderitems
group by order_num
having count(*) >= 3
order by items, order_num;
select子句的順序
終於要總結他們的順序了
總結
- 雖然having和where很相似,但是要記住,having一定要和group by一起用,是用於過濾分組;而where是用於普通的行級過濾
- 掌握好where和having的差異
- 掌握好order by 和group by 的差異
- 掌握好設了select子句的順序