如下是咱們常常要用的一些聚合函數,請謹慎使用,注意sql_mode 模式設置對查詢結果的影響,若是sql_mode=' ',那麼:
select create_time,test_name,max(moneys) from test_table group by test_name; 查詢不報錯,但可能與預想結果不同,時間與最大值不匹配,以前見有開發這樣寫過,若是sql_mode=‘only_full_group_by’,以上sql 會報錯。sql
avg() 求平均值
select test_name,avg(moneys) from test_table group by test_name; 按人名分組求平均金額
+-----------+---------------+
| test_name | avg(moneys) |
+-----------+---------------+
| 哈羅德 | 550000.175000 |
| 格溫 | 170015.130000 |
| 班尼 | 915016.630000 |
+-----------+---------------+ide
max() 求最大值
select test_name,max(moneys) from test_table group by test_name; 按人名分組求最大金額
+-----------+-------------+
| test_name | max(moneys) |
+-----------+-------------+
| 哈羅德 | 1000000.23 |
| 格溫 | 170030.13 |
| 班尼 | 1660003.13 |
+-----------+-------------+函數
min() 求最小值
select test_name,min(moneys) from test_table group by test_name; 按人名分組求最小金額
+-----------+-------------+
| test_name | min(moneys) |
+-----------+-------------+
| 哈羅德 | 100000.12 |
| 格溫 | 170000.13 |
| 班尼 | 170030.13 |
+-----------+-------------+開發
sum() 求和
select test_name,sum(moneys) from test_table group by test_name; 按人名分組求總金額
+-----------+-------------+
| test_name | sum(moneys) |
+-----------+-------------+
| 哈羅德 | 1100000.35 |
| 格溫 | 340030.26 |
| 班尼 | 1830033.26 |
+-----------+-------------+it
select test_name,count() from test_table group by test_name; 按人名分組求頻率
+-----------+----------+
| test_name | count() |
+-----------+----------+
| 哈羅德 | 2 |
| 格溫 | 2 |
| 班尼 | 2 |
+-----------+----------+table
select test_name,count(distinct test_name) from test_table group by test_name; 先去重,後按人名分組求頻率
+-----------+---------------------------+
| test_name | count(distinct test_name) |
+-----------+---------------------------+
| 哈羅德 | 1 |
| 格溫 | 1 |
| 班尼 | 1 |
+-----------+---------------------------+class
6.group_concat() 拼接數據
select test_name,group_concat(test_id),avg(moneys) from test_table group by test_name; 按人名分組拼接id
+-----------+-----------------------+---------------+
| test_name | group_concat(test_id) | avg(moneys) |
+-----------+-----------------------+---------------+
| 哈羅德 | 1,2 | 550000.175000 |
| 格溫 | 3,5 | 170015.130000 |
| 班尼 | 4,6 | 915016.630000 |
+-----------+-----------------------+---------------+test
7.計算每日訪問量
select * from t1;
+------+-------+------+
| year | month | day |
+------+-------+------+
| 2000 | 01 | 01 |
| 2000 | 01 | 20 |
| 2000 | 01 | 30 |
| 2000 | 02 | 02 |
| 2000 | 02 | 23 |
| 2000 | 02 | 23 |
+------+-------+------+select
SELECT year,month,BIT_COUNT(BIT_OR(1<<day)) AS days FROM t1
GROUP BY year,month;
+------+-------+------+
| year | month | days |
+------+-------+------+
| 2000 | 01 | 3 |
| 2000 | 02 | 2 |
+------+-------+------+im