2012-06-03 30 views
-5

我有一個簡單的查詢:如何在SQL或Java中創建所有可能組合的散列?

select key, name from cities 

這給了我價值觀,像這樣:

11 | Chicago 
21 | New York 
31 | Boston 

我需要什麼,能夠做的是創造一切可能的組合無論是在SQL或哈希在Java中爲了在最後收到這個結果:

11 | Chicago 
21 | New York 
31 | Boston 
32 | Chicago/New York 
42 | Chicago/Boston 
52 | New York/Boston 
63 | Chicago/New York/Boston 

任何想法?

+1

你爲何預期的產量與三座城市都不成?如果關鍵值的總和不是唯一的呢? –

+0

你說得對,我只是在三個城市中添加了最後一個結果。鑰匙將永遠是獨一無二的我知道。 – goe

+0

你是什麼意思的「創建一個哈希」?術語「哈希」具有多種含義(我責備Perl)取決於上下文,這裏不完全清楚... – thkala

回答

0

這不是完美的,但可能是一個開始:

首先我創建了一個功能:

create or replace function sum_string(str in varchar2) return number is 
    Result number; 
begin 
    execute immediate 'select ' || str || ' from dual' 
    into result; 
    return(Result); 
end sum_string; 
/

然後是查詢(your_table是你的表)

with jwt as (
    select t1.key k1, t1.name n1, t2.key k2, t2.name n2, t1.key + t2.key jkey 
    from your_table t1 
    left outer join (select key, name 
         from your_table 
        union all 
        select 0 "key", null "name" from dual) t2 on t1.key <> 
                    t2.key 
) 
select jkey, max(aaa.pth) 
    from (select sys_connect_by_path(t.n1, '/') pth, 
       sum_string(ltrim(sys_connect_by_path(t.k1, '+'), '+')) jkey 
      from jwt t 
     start with t.k2 = 0 
     connect by nocycle prior k1 = k2) aaa 
group by jkey;