1. 程式人生 > >MYSQL 學習筆記2

MYSQL 學習筆記2

5、資料彙總

聚集函式:執行在組上,計算和返回單個值的函式

avg count max min sum

select avg(prod_price) as avg_price from products;

好處:不再顯示所有的資料,節省傳輸頻寬

max min也可用於文字,表示最後(前)行

select avg(distinct prod_price) as avg_price from products where vend_id = 1003;

使用disctinct,只計算其中不同值的平均值

組合使用:

select count(*) as num_items,

          min(prod_price) as price_min,

          max(prod_price) as price_max,

from products;

6、資料分組

select vend_id,count(*) as num_prods from products group by vend_id;

以vend_id,分組求和

group by 位置在where之後 order by之前

select vend_id,count(*) as num_prods

from products

where prod_price >= 10

group by vend_id

having count(*) >= 2;

統計price 大於等於10的,並按id計數,最終顯示計數大於等於2的

where用於前過濾,having用於後過濾