mysql 聚合乘法_利用MySQL的GROUP_CONCAT函数实现聚合乘法

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 < cnt DO -- get multiple result. SET result = result * REVERSE(SUBSTRING_INDEX(REVERSE(SUBSTRING_INDEX(f_nums,',',i+1)),',',1)); SET i = i + 1; END WHILE; SET result = ROUND(result,2); RETURN result; END$$ DELIMITER ;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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值