結(jié)構(gòu)化查詢(sql)的另一個(gè)強(qiáng)大的功能是分類匯總,也就是group子句;mysql當(dāng)然也提供這個(gè)功能?,F(xiàn)在還以我在《select查詢的應(yīng)用(二)join子句的用法》中的數(shù)據(jù)庫(kù)為例說(shuō)說(shuō)group子句的用法。
一、查詢每個(gè)客戶的交易次數(shù)。count()是一個(gè)與group子句一起使用的函數(shù),它的作用是計(jì)數(shù):
select customer,count(*) as sale_count from sales group by customer
返回的查詢可能結(jié)果為:
+----------+------------+
| customer | sale_count |
+----------+------------+
| 1 | 1 |
+----------+------------+
| 2 | 1 |
+----------+------------+
表示了代碼為1和2的兩個(gè)客戶分別有一次交易。
二、查詢每個(gè)客戶的交易總額。sum()是一個(gè)與group子句一起使用的函數(shù),它的作用是求和:
select customer,sum(price*amount) as total_price from sales group by customer
返回的查詢結(jié)果可能為:
+----------+-------------+
| customer | total_price |
+----------+-------------+
| 1 | 12000.00 |
+----------+-------------+
| 2 | 12000.00 |
+----------+-------------+
表示了代碼為1和2的兩個(gè)客戶各有12000元的交易額。其中sum(price*amount)表示先將price和amount即單價(jià)和數(shù)量相乘后再求和,亦即總價(jià)。
三、查詢每個(gè)客戶的平均每次交易額。avg()是求平均值的函數(shù):
select customer,avg(price*amount) as avg_price from sales group by customer
返回的查詢結(jié)果可能為:
+----------+-----------+
| customer | avg_price |
+----------+-----------+
| 1 | 12000.00 |
+----------+-----------+
| 2 | 12000.00 |
+----------+-----------+
表示了代碼為1和2的兩個(gè)客戶的平均每次交易的交易額都是12000元。由于我預(yù)設(shè)的數(shù)據(jù)量比較小,查詢的結(jié)果不甚明顯,請(qǐng)讀者諒解。可以隨意向sales表中添加一些數(shù)據(jù),數(shù)據(jù)量越大,結(jié)果越明顯。
四、查詢每個(gè)客戶最大的和最小的一筆成交額。max()和min()函數(shù)分別是取最大值和最小值的函數(shù):
select customer,max(price*amount) as max_price,min(price*amount) as min_price from sales group by customer
返回的查詢結(jié)果可能為:
+----------+-----------+-----------+
| customer | max_price | min_price |
+----------+-----------+-----------+
| 1 | 12000.00 | 12000.00 |
+----------+-----------+-----------+
| 2 | 12000.00 | 12000.00 |
+----------+-----------+-----------+
五、查詢每一種貨物售出的平均價(jià)格。
select good_code,avg(price) as avg_price from sales group by good_code
對(duì)么?不對(duì)!這樣查詢到的是每種貨物各條銷售記錄中價(jià)格的平均值,并不是實(shí)際售出的所有該貨物的平均價(jià)格;對(duì)我們來(lái)說(shuō),有用的是按照銷售數(shù)量加權(quán)平均的價(jià)格:
select good_code,sum(price*amount)/sum(amount) as avg_price from sales group by good_code
返回的查詢結(jié)果可能為:
+-----------+-----------+
| good_code | avg_price |
+-----------+-----------+
| a0001 | 1200.00 |
+-----------+-----------+
六、查詢售給不同客戶的每一種貨物售出的平均價(jià)格。只要在group子句中多加一個(gè)關(guān)鍵字:
select good_code,customer,sum(price*amount)/sum(amount) as avg_price from sales group by good_code,customer
返回的查詢結(jié)果可能為:
+-----------+----------+-----------+
| good_code | customer | avg_price |
+-----------+----------+-----------+
| a0001 | 1 | 1200.00 |
+-----------+----------+-----------+
| a0001 | 2 | 1200.00 |
+-----------+----------+-----------+
所有客戶和所售貨物兩項(xiàng)相同的記錄匯總到一起來(lái)求平均,就形成了售給不同客戶的每一種貨物售出的平均價(jià)格。
按月統(tǒng)計(jì):select convert(char(7),createtime,20) as time,sum(price*amount) as hits from sales
group by convert(char(7),createtime,20)
該文章在 2010/7/3 16:05:50 編輯過(guò)