0
点赞
收藏
分享

微信扫一扫

MySQL数据库查询数据操作篇第20篇使用聚合函数查询


MySQL数据库查询数据操作篇第20篇使用聚合函数查询_mysql

MySQL数据库查询数据操作篇第20篇使用聚合函数查询_聚合函数_02

20.使用聚合函数查询(单独一篇)
mysql> select count(*) as cust_num
-> from customers;
+----------+
| cust_num |
+----------+
| 3 |
+----------+
1 row in set

mysql> select count(c_email) as email_num
-> from customers;
+-----------+
| email_num |
+-----------+
| 2 |
+-----------+
1 row in set

mysql> select f_name,count(f_id)
-> from fruits
-> group by f_name
-> ;
+--------+-------------+
| f_name | count(f_id) |
+--------+-------------+
| apple | 1 |
| banana | 1 |
| caomei | 1 |
+--------+-------------+
3 rows in set



mysql> create table orderitems
-> (
-> o_num int not null,
-> o_item int not null,
-> f_id char(10) not null,
-> quantity int not null,
-> item_price decimal(8,2) not null,
-> primary key (o_num,o_item)
-> );
Query OK, 0 rows affected
mysql> insert into orderitems
-> values(1001,1,"a1",10,5.2),
-> (1002,2,"b1",11,6.2),#逗号间隔不可少。
-> (1003,3,"c1",12,7.2);
Query OK, 3 rows affected
Records: 3 Duplicates: 0 Warnings: 0

mysql> select o_num,sum(quantity) as items_total
-> from orderitems
-> group by o_num;
+-------+-------------+
| o_num | items_total |
+-------+-------------+
| 1001 | 10 |
| 1002 | 11 |
| 1003 | 12 |
+-------+-------------+
3 rows in set

mysql> select avg(f_price) as avg_price
-> from fruits
-> where s_id = 103;
+-----------+
| avg_price |
+-----------+
| 7.2 |
+-----------+
1 row in set

mysql> select s_id,avg(f_price) as avg_price
-> from fruits
-> group by s_id;
+------+-----------+
| s_id | avg_price |
+------+-----------+
| 101 | 5.2 |
| 102 | 6.2 |
| 103 | 7.2 |
+------+-----------+
3 rows in set

mysql> select max(f_price) as max_price from fruits;
+-----------+
| max_price |
+-----------+
| 7.2 |
+-----------+
1 row in set

mysql> select s_id,max(f_price) as max_price
-> from fruits
-> group by s_id;
+------+-----------+
| s_id | max_price |
+------+-----------+
| 101 | 5.2 |
| 102 | 6.2 |
| 103 | 7.2 |
+------+-----------+
3 rows in set

mysql> select max(f_name) from fruits;
+-------------+
| max(f_name) |
+-------------+
| caomei |
+-------------+
1 row in set

mysql> select min(f_price) as min_price from fruits;
+-----------+
| min_price |
+-----------+
| 5.2 |
+-----------+
1 row in set

mysql> select s_id,min(f_price) as min_price
-> from fruits
-> group by s_id;
+------+-----------+
| s_id | min_price |
+------+-----------+
| 101 | 5.2 |
| 102 | 6.2 |
| 103 | 7.2 |
+------+-----------+
3 rows in set



举报

相关推荐

0 条评论