利用MySQL的GROUP_CONCAT函数实现聚合乘法_MySQL
程序员文章站
2022-04-09 13:35:09
...
MySQL 聚合函数里面提供了加,平均数,最小,最大等,但是没有提供乘法,我们这里来利用MYSQL现有的GROUP_CONCAT函数实现聚合乘法。
CREATE TABLE `tb_seq` ( `num` int(10) NOT NULL, `seq_type` enum('yellow','green','red') NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `tb_seq`(`num`,`seq_type`) values (4,'green'),(1,'red'),(3,'green'), (1,'red'),(8,'red'),(4,'yellow'), (8,'red'),(7,'yellow'),(10,'red'), (1,'red'),(1,'red'),(1,'yellow'), (5,'green'),(9,'red'),(1,'yellow'), (6,'yellow');
DELIMITER $$ USE `t_girl`$$ DROP FUNCTION IF EXISTS `func_multiple`$$ CREATE DEFINER=`root`@`localhost` FUNCTION `func_multiple`( f_nums VARCHAR(1000) ) RETURNS DOUBLE(10,2) BEGIN -- Created by ytt 2014/10/21. DECLARE result DOUBLE(10,2) DEFAULT 1; DECLARE cnt,i INT DEFAULT 0; SET cnt = CHAR_LENGTH(f_nums) - CHAR_LENGTH(REPLACE(f_nums,',','')) + 1; WHILE i SELECT seq_type,func_multiple(GROUP_CONCAT(num ORDER BY num ASC SEPARATOR ',')) AS multiple_num FROM tb_seq WHERE 1 GROUP BY seq_type; +----------+--------------+ | seq_type | multiple_num | +----------+--------------+ | yellow | 168.00 | | green | 60.00 | | red | 5760.00 | +----------+--------------+ 3 rows in set (0.00 sec)
CREATE TABLE `tb_seq` ( `num` int(10) NOT NULL, `seq_type` enum('yellow','green','red') NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `tb_seq`(`num`,`seq_type`) values (4,'green'),(1,'red'),(3,'green'), (1,'red'),(8,'red'),(4,'yellow'), (8,'red'),(7,'yellow'),(10,'red'), (1,'red'),(1,'red'),(1,'yellow'), (5,'green'),(9,'red'),(1,'yellow'), (6,'yellow');
DELIMITER $$ USE `t_girl`$$ DROP FUNCTION IF EXISTS `func_multiple`$$ CREATE DEFINER=`root`@`localhost` FUNCTION `func_multiple`( f_nums VARCHAR(1000) ) RETURNS DOUBLE(10,2) BEGIN -- Created by ytt 2014/10/21. DECLARE result DOUBLE(10,2) DEFAULT 1; DECLARE cnt,i INT DEFAULT 0; SET cnt = CHAR_LENGTH(f_nums) - CHAR_LENGTH(REPLACE(f_nums,',','')) + 1; WHILE i SELECT seq_type,func_multiple(GROUP_CONCAT(num ORDER BY num ASC SEPARATOR ',')) AS multiple_num FROM tb_seq WHERE 1 GROUP BY seq_type; +----------+--------------+ | seq_type | multiple_num | +----------+--------------+ | yellow | 168.00 | | green | 60.00 | | red | 5760.00 | +----------+--------------+ 3 rows in set (0.00 sec)
上一篇: jQuery聚合函数实例_jquery
下一篇: 常用的检查函数
推荐阅读
-
PHP+MySQL实现海量数据导入导出的总结:is_numbric函数的坑
-
MySQL数据库中CAST与CONVERT函数实现类型转换的讲解
-
PHP利用MySQL保存session的实现思路及示例代码
-
MySQL中聚合函数count的使用和性能优化技巧
-
MySql 中聚合函数增加条件表达式的方法
-
详解利用Dockerfile构建mysql镜像并实现数据的初始化及权限设置
-
ms sql server中实现的unix时间戳函数(含生成和格式化,可以和mysql兼容)
-
php利用scws实现mysql全文搜索功能的方法
-
PHP+Mysql实现多关键字与多字段生成SQL语句的函数
-
MySQL数据库:聚合函数的使用