星空网 > 软件开发 > 数据库

oracle VS postgresql系列

【需求】例如先有数据为
 id | name  ------+--------- 1001 | lottu 1001 | xuan 1001 | rax 1002 | ak 1002 | vincent现在需要转换为 id |   names   ------+---------------- 1001 | lottu|xuan|rax 1002 | ak|vincent反之;oracle,postgresql有如何对待

【列转行】
oracle 
对oracle;看到这样的需求;立刻想到vm_concat,listagg函数;这样sql就出来了
select id, vm_concat(name,'|')as names from lottu01 group by id;select id, listagg(name,'|') within group(order by null) as names from lottu01 group by id;

 postgresql
同理也有对应的函数string_agg
=> select id,string_agg(name,'|') from lottu01 group by id; id |  string_agg  ------+---------------- 1002 | ak|vincent 1001 | lottu|xuan|rax

【行转列】
oracle
  这个一看就要使用分割函数;对oracle目前是不存在split函数
分割函数这个可以查考--http://www.cnblogs.com/lottu/p/4013751.html
当然我们可以用其他函数来替代 正则函数 regexp_substr
select id,regexp_substr(names,'[^|]+',1,level) as name from lottu02connect by id = prior idand prior dbms_random.value is not nulland level <= length(regexp_replace(names, '[^|]'))+1;#或者select id,regexp_substr(names,'[^|]+',1,level) as name from lottu02connect by id = prior idand prior dbms_random.value is not nulland level <= regexp_count(names, '\|')+1;

postgresql
 postgresql里面有分割函数--split_part;还是不能按照上面的写法来改;因为目前的postgresql不支持 connect by语法
不过没关系;postgresql针对这个有个正则函数--regexp_split_to_table;可以直接实现。
=> select id,regexp_split_to_table(names,'\|') from lottu02; id | regexp_split_to_table ------+----------------------- 1001 | lottu 1001 | xuan 1001 | rax 1002 | ak 1002 | vincen









原标题:oracle VS postgresql系列

关键词:sql

sql
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流