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
mydb=> 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 lottu02
connect by id = prior id
and prior dbms_random.value is not null
and level <= length(regexp_replace(names, '[^|]'))+1;
#或者
select id,regexp_substr(names,'[^|]+',1,level) as name from lottu02
connect by id = prior id
and prior dbms_random.value is not null
and level <= regexp_count(names, '\|')+1;
postgresql
 postgresql里面有分割函數--split_part;還是不能按照上面的寫法來改;因為目前的postgresql不支持 connect by語法;
不過沒關系;這並不妨礙寫法不能實現。
另外 postgresql針對這個有個正則函數--regexp_split_to_table;可以直接實現。
--借用with recursive的語法來替換 connect by的寫法。
mydb=> with recursive t(id,lv) as(
mydb(> select id,1 lv from lottu02
mydb(> union all
mydb(> select ts.id, t.lv+1 from t, lottu02 ts where t.id = ts.id and t.lv < length(ts.names)-length(replace(ts.names,'|','')) + 1
mydb(> )
mydb-> select t1.id,split_part(t1.names,'|',t2.lv) from lottu02 t1,t t2
mydb-> where t1.id = t2.id; 
  id  | split_part 
------+------------
 1001 | lottu
 1001 | xuan
 1001 | rax
 1002 | ak
 1002 | vincent

-- 借用regexp_split_to_table輕松實現。
mydb=> select id,regexp_split_to_table(names,'\|') from lottu02;
  id  | regexp_split_to_table 
------+-----------------------
 1001 | lottu
 1001 | xuan
 1001 | rax
 1002 | ak
 1002 | vincen

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM