遇到这样的一个需求,需要实现根据一个字段统计数据,但是这个字段存储是多个字根据逗号分隔存储的,我要实现一行转多行的逻辑。
数据
转化后:
转化后的数据
使用的sql:
SELECT friendid,substr(a.friendname, instr(a.friendname, ',.', 1, levels.lvl) + 2, instr(a.friendname, ',.', 1, levels.lvl + 1) -(instr(a.friendname, ',.', 1, levels.lvl) + 1)-1) as friendname,sex
FROM
(SELECT friendid,',.' || friendname || ',.' AS friendname,sex,(length(friendname || ',.') - nvl(length(REPLACE(friendname, ',.')), 0))/2 AS cnt
FROM myfriendsTest) a,
(SELECT rownum AS lvl
FROM (SELECT (MAX(length(friendname || ',.') - nvl(length(REPLACE(friendname, ',.')), 0)))/2 max_len FROM myfriendsTest)
CONNECT BY LEVEL <= max_len) levels
WHERE levels.lvl <= a.cnt
ORDER BY friendid;
参考:
https://blog.csdn.net/qq_20481125/article/details/99550208
网友评论