我正在尝试将列字符串值拆分为单独的行,但到目前为止还没有运气。
这是我的数据集
990^275,987^280,988^278
我想得到每个逗号分隔数据集i.e. 990,987,988 etc
的第一个值。我试过了substring_index
但没有得到我想要的结果。这是我尝试过的 -
select
rooms_tariffs,
replace( rooms_tariffs,'^',','),
SUBSTRING_INDEX(replace( rooms_tariffs,'^',','), ',', 1) "First",
SUBSTRING_INDEX(SUBSTRING_INDEX(rooms_tariffs,'^',2),',', -1) "second"
from ewqhv_jomres_contracts
order by 1 desc;
输出 -
rooms_tariffs | rooms_tariffs | First | second
991^278,990^275 991,278,990,275 991 990
991^278,984^280 991,278,984,280 991 984
991^278 991,278 991 991^278
991^278 991,278 991 991^278
答案 0 :(得分:0)
你很近,我的朋友。试试这个:
SELECT `data`.`room_tariffs` AS `room_tariffs`,
SUBSTRING_INDEX(`data`.`room_tariffs`, ',', 1) AS `First`,
SUBSTRING_INDEX(SUBSTRING_INDEX(`data`.`room_tariffs`, ',', -4), ',', 1) AS `Second`,
SUBSTRING_INDEX(SUBSTRING_INDEX(`data`.`room_tariffs`, ',', -2), ',', 1) AS `Third`
FROM (
SELECT REPLACE(`room_tariffs`, '^', ',') AS `room_tariffs`
FROM `ewqhv_jomres_contracts`
ORDER BY 1 desc;
) AS `data`
输出:
room_tariffs First Second Third
990,275,987,280,988,278 990 987 988
答案 1 :(得分:0)
最后,我通过在下面创建一个简单的函数然后将其调用到我的查询脚本中来解决它。
CREATE FUNCTION `SPLIT_STR`( x VARCHAR(255), delim VARCHAR(12), pos INT) RETURNS varchar(255) CHARSET latin1 RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos), LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '');
我在我的SQL查询中调用了这个函数,如下所示 -
select room_no, split_str(room_no,',',1) "One", split_str(room_no,',',3) "Two", split_str( room_no,',',5) "Three" from room_view where tag=676648xx;