用于获取最大累积值的 MySQL 查询
要实现此目的,请使用聚合函数 COUNT(*) 和子查询。还使用了 GROUP BY。
让我们创建一个表格 -
mysql> create table demo23 −> ( −> id int not null auto_increment primary key, −> value1 int, −> value2 int −> ); Query OK, 0 rows affected (1.65 sec)
使用 insert 命令向表格中插入一些记录 -
mysql> insert into demo23(value1,value2) values(5,600); Query OK, 1 row affected (0.20 sec) mysql> insert into demo23(value1,value2) values(20,800); Query OK, 1 row affected (0.06 sec) mysql> insert into demo23(value1,value2) values(7,400); Query OK, 1 row affected (0.20 sec) mysql> insert into demo23(value1,value2) values(6,500); Query OK, 1 row affected (0.17 sec) mysql> insert into demo23(value1,value2) values(10,300); Query OK, 1 row affected (0.12 sec) mysql> insert into demo23(value1,value2) values(11,500); Query OK, 1 row affected (0.14 sec)
使用 select 语句从表格中显示记录 -
mysql> select *from demo23;
这将产生以下输出 -
+----+--------+--------+ | id | value1 | value2 | +----+--------+--------+ | 1 | 5 | 600 | | 2 | 20 | 800 | | 3 | 7 | 400 | | 4 | 6 | 500 | | 5 | 10 | 300 | | 6 | 11 | 500 | +----+--------+--------+ 6 rows in set (0.00 sec)
以下是最大累积值的查询 -
mysql> select total_value, count(*) as number_of_occurrences −> from ( −> select value1*value2 as total_value −> from demo23 −> ) t −> group by total_value −> order by total_value desc −> limit 1 ;
这将产生以下输出 -
+-------------+-----------------------+ | total_value | number_of_occurrences | +-------------+-----------------------+ | 16000 | 1 | +-------------+-----------------------+ 1 row in set (0.00 sec)
广告