我有一个表 test ,其中有一列 state_numbers
id state_numbers -- ------------ 1 scr:1.0043;smb:0;rsm:0 2 scr:1.12;smb:0;rsm:0.3 3 scr:0.083;smb:0.65;rsm:0 4 scr:1.021;smb:0;rsm:0.2 5 scr:0.77;smb:0;rsm:0
我创建了一个名为状态的表,看起来像
id scr smb rsm total ------ ------ ------ ------ ------ (null) (null) (null) (null) (null)
我需要一个能够读取 state_numbers 中的值的查询,根据关键字拆分表达式并将值放在Status表的相应列中。
我期待:
id scr smb rsm total ------ ------ ------ ------ ------ 1 1.0043 0 0 (null) 2 1.12 0 0.3 (null) 3 0.083 0.65 0 (null)
然后我将能够在每列中添加数据并在 total 列中更新。
最终输出:
id scr smb rsm total ------ ------ ------ ------ ------ 1 1.0043 0 0 1.0043 2 1.12 0 0.3 1.42 3 0.083 0.65 0 0.733
我将如何实现这一目标?帮助我拆分特定单元格并在不同的字段中插入数据。
提前致谢!!!
P.S:请提出这个问题的正确标题
答案 0 :(得分:1)
您可以使用MySQL split function by Federico Cargnelutti.
CREATE FUNCTION SPLIT_STR(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '');
select id,
scr,
smb,
rsm,
cast(scr as DECIMAL(10,5))+cast(rsm as DECIMAL(10,5))+cast(smb as DECIMAL(10,5)) as total
from (
select
id,
trim(replace(SPLIT_STR(state_numbers, ';', 1),'scr:','')) as scr,
trim(replace(SPLIT_STR(state_numbers, ';', 2),'smb:','')) as smb,
trim(replace(SPLIT_STR(state_numbers, ';', 3),'rsm:','')) as rsm
from test) as myTable;
答案 1 :(得分:1)
试试这个:
SELECT id, scr, smb, rsm,
(CAST(scr AS DECIMAL(18, 5)) + CAST(smb AS DECIMAL(18, 5)) + CAST(rsm AS DECIMAL(18, 5))) total
FROM (SELECT id, REPLACE(SUBSTRING_INDEX(state_numbers, ';', 1), 'scr:', '') scr,
REPLACE(SUBSTRING_INDEX(SUBSTRING_INDEX(state_numbers, ';', -2), ';', 1), 'smb:', '') smb,
REPLACE(SUBSTRING_INDEX(state_numbers, ';', -1), 'rsm:', '') rsm
FROM test
) AS A