标签:时间 sql_mod select ble sql_mode 设置 影响 mysq 直接
以下是我们经常要用的一些聚合函数,请谨慎使用,注意sql_mode 模式设置对查询结果的影响,如果sql_mode=‘ ‘,那么:avg() 求平均值
select test_name,avg(moneys) from test_table group by test_name; 按人名分组求平均金额
+-----------+---------------+
| test_name | avg(moneys) |
+-----------+---------------+
| 哈罗德 | 550000.175000 |
| 格温 | 170015.130000 |
| 班尼 | 915016.630000 |
+-----------+---------------+
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 |
+-----------+-------------+
select test_name,count() from test_table group by test_name; 按人名分组求频率
+-----------+----------+
| test_name | count() |
+-----------+----------+
| 哈罗德 | 2 |
| 格温 | 2 |
| 班尼 | 2 |
+-----------+----------+
select test_name,count(distinct test_name) from test_table group by test_name; 先去重,后按人名分组求频率
+-----------+---------------------------+
| test_name | count(distinct test_name) |
+-----------+---------------------------+
| 哈罗德 | 1 |
| 格温 | 1 |
| 班尼 | 1 |
+-----------+---------------------------+
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 |
+-----------+-----------------------+---------------+
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 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 |
+------+-------+------+
标签:时间 sql_mod select ble sql_mode 设置 影响 mysq 直接
原文地址:http://blog.51cto.com/11103985/2327099