2013-02-08 42 views
1

我下表甲骨文複雜的字符串替換

mytable 
type   | id  | name   | formula 
"simple"  | 1  | "COUNT"  | "<1>" 
"simple"  | 2  | "DISTINCT"  | "<2>" 
"simple"  | 3  | "mycol"  | "<3>" 
"complex" | 4  | null   | "<1>(<2> <3>)" 

現在我想閱讀此表,並添加一個附加列取代了公式字符串了。 對於ID 4我需要:"COUNT(DISTINCT mycol)"
任何想法我可以做到這一點?

+3

呃.... _why_你在幹什麼呢?請注意,您將無法'直接'運行以此方式重新構建的任何查詢;你至少需要一個存儲過程(在這一點上,在SP內部執行這個操作將會簡單得多)。通過在應用程序層中執行此操作,您可能擁有最簡單的時間。然而,**很少**是這種「靈活性」所需要的;你認爲你在解決什麼問題? – 2013-02-08 22:59:36

+0

這是http://en.wikipedia.org/wiki/Inner-platform_effect的例子嗎? – 2013-02-12 02:49:45

回答

1

在Oracle 11它可能看起來像這樣:

select 
    type, id, name, formula, value 
from 
    mytable 
    left join (
     select 
     id_complex, 
     listagg(decode(pos, 2, name, part)) within group (order by occ, pos) as value 
     from 
     (
      select 
       id_complex, occ, pos, 
       regexp_replace(pair, '^(.*?)(<.*?>)$', '\'||pos) as part 
      from 
       (
        select 
        id as id_complex, 
        occ, 
        regexp_substr(formula||'<>', '.*?<.*?>', 1, occ) as pair 
        from 
        (
         select level as occ from dual 
         connect by level <= (select max(length(formula)) from mytable) 
        ), 
        mytable 
        where type = 'complex' 
       ), 
       (select level as pos from dual connect by level <= 2) 
     ) 
     left join mytable on part = formula and type = 'simple' 
     group by id_complex 
    ) on id = id_complex 
order by id 

SQL Fiddle

+0

感謝您的輸入! – BaseBallBatBoy 2013-02-11 13:00:46