Summing a comma separated column in MySQL 4 (not 5)(在 MySQL 4(不是 5)中总结逗号分隔的列)
问题描述
我正在编写一个查询,从一个表中选择数据到另一个表中,需要移动的列之一是 DECIMAL 列.由于我无法控制的原因,源列有时可以是逗号分隔的数字列表.有没有优雅的 sql 唯一方法来做到这一点?
I'm writing a query that selects data from one table into another, one of the columns that needs to be moved is a DECIMAL column. For reasons beyond my control, the source column can sometimes be a comma separated list of numbers. Is there an elegant sql only way to do this?
例如:
源列
10.2
5,2.1
4
应该产生一个目标列
10.2
7.1
4
顺便说一句,我使用的是 MySQL 4.
I'm using MySQL 4, btw.
推荐答案
要进行这种非平凡的字符串操作,您需要使用存储过程,对于 MySQL,它在 6 年前才出现在 5.0 版本中.
To do this kind of non trivial string manipulations, you need to use stored procedures, which, for MySQL, only appeared 6 years ago, in version 5.0.
MySQL 4 现在很老了,分支 4.1 的最新版本是 4.1.25,在 2008 年.不再支持.大多数 Linux 发行版不再提供它.是时候升级了.
MySQL 4 is now very old, the latest version from branch 4.1 was 4.1.25, in 2008. It is not supported anymore. Most Linux distributions don't provide it anymore. It's really time to upgrade.
这是适用于 MySQL 5.0+ 的解决方案:
Here is a solution that works for MySQL 5.0+:
DELIMITER //
CREATE FUNCTION SUM_OF_LIST(s TEXT)
RETURNS DOUBLE
DETERMINISTIC
NO SQL
BEGIN
DECLARE res DOUBLE DEFAULT 0;
WHILE INSTR(s, ",") > 0 DO
SET res = res + SUBSTRING_INDEX(s, ",", 1);
SET s = MID(s, INSTR(s, ",") + 1);
END WHILE;
RETURN res + s;
END //
DELIMITER ;
示例:
mysql> SELECT SUM_OF_LIST("5,2.1") AS Result;
+--------+
| Result |
+--------+
| 7.1 |
+--------+
这篇关于在 MySQL 4(不是 5)中总结逗号分隔的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 MySQL 4(不是 5)中总结逗号分隔的列
基础教程推荐
- 带更新的 sqlite CTE 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
