數據分組:sql
1.分組容許把數據分爲多個邏輯組,以便對每一個組進行聚合計算,GROUP BY子句必須出如今WHERE子句以後,ORDER BY子句以前code
過濾分組:排序
1.WHERE是在數據分組前進行過濾的,HAVING在數據分組後進行過濾的,可是WHERE子句和HAVING是能夠同時出現的it
2.要基於分組後的行進行過濾,WHERE子句無能爲力,由於過濾是基於分組聚合值的而不是特定行值的,HAVING子句來實現分組,HAVING支持全部的WHERE操做符class
SELECT cust_id, count(*) AS order_num FROM orders GROUP BY cust_id HAVING order_num >= 2;
分組和排序:數據
1.通常在使用GROUP BY子句時,應該也給出ORDER BY子句,可確保數據正確排序的惟一辦法ant
SELECT order_num, SUM(quantity*item_price) AS ordertotal FROM orderitems GROUP BY order_num HAVING ordertotal >= 50 ORDER BY ordertotal;
SELECT子句順序:co
SELECT -> FROM -> WHERE -> GROUP BY -> HAVING -> ORDER BY -> LIMIT