2016-05-12 68 views
1

我想使用ListAgg,然後在其上使用INSTR/REGEXPR來理解結果字符串是否包含字符串組合。在ListAGG上使用instr

appNumber Decision 
123   AB 
345   BC 
123   PA 
345   PA 
123   AM 

我希望他們在一起使用LISTAGG,然後把INSTR說如果列表AGG既有 「AB」 和 「AM」

結果將列出

Appnumber   MyResult 
123    1 
345    0 

有什麼建議嗎?

謝謝

+1

嗨, - 這並沒有多大意義。你是說,如果appNumber 123有決定字符串BA和MC,並且級聯是BAMC,那麼這個字符串是否有子字符串AM? (如果這不是你所說的,並且AM必須是Decision中的值或Decision列中值的子字符串,則可以獨立於LISTAGG進行測試)。如果實際上你想讓BAMC導致AM的匹配,那麼...... LISTAGG取決於聚合的順序,但是你沒有提到任何關於這一點的內容。 MCBA,這是另一種可能性,不包含子字符串AM。 – mathguy

+0

@mathguy你有一點,我給了我的例子。然而在現實生活中這不會發生。抱歉造成混淆。同樣使用LISTAGG,我會用逗號分隔它們。而且它不是該列的子字符串。這是它的一切:) – SeeWe

回答

0

我根本不打擾使用LISTAGG;一個簡單的總和+ GROUP BY和一對夫婦的情況下表現的做的工作一樣好:

with sample_data as (select 123 appnumber, 'AB' decision from dual union all 
        select 345 appnumber, 'BC' decision from dual union all 
        select 123 appnumber, 'PA' decision from dual union all 
        select 345 appnumber, 'PA' decision from dual union all 
        select 123 appnumber, 'AM' decision from dual) 
-- end of mimicking a table called "sample_data" that contains your data 
select appnumber, 
     case when sum(distinct case when decision = 'AB' then 1 
            when decision = 'AM' then 2 
            else 0 
           end) = 3 then 1 
       else 0 
     end myresult 
from  sample_data 
group by appnumber; 

APPNUMBER MYRESULT 
---------- ---------- 
     123   1 
     345   0 

這是通過分配每個您要搜索的2(1,2的冪​​的值決定的,4,8等),然後使用不同值的總和與所有這些值的總和進行比較。在你的情況下,你正在尋找2個字符串,所以你檢查的總和等於3(如果你正在檢查3個字符串的存在,它將是7(1 + 2 + 4),4個字符串將是15(1 + 2 + 4 + 8)等)。

這是否比Tim使用listagg的答案更有效率是任何人的猜測;我建議你測試兩個版本,看看哪一個最適合你的數據。

0

如果您不限制使用ListAgg,我可能會建議您使用沒有分析功能的其他解決方案。我使用集合來讓外部應用程序像字符串數組那樣傳遞狀態('AB','AM')。該函數將結果集作爲嵌套表返回。

初步類型聲明:

create or replace type t_test_states is varray(10) of varchar2(2); 
create or replace type t_test_appnumbers is table of number; 

創建一個函數(在現實生活中,你不會有一個子查詢「ample_data」塊):

create or replace function TEST_GET_ANSWER (p_states IN t_test_states) 
    return t_test_appnumbers 
    is 
    v_resultset t_test_appnumbers; 
    begin  
    with sample_data as (select 123 appnumber, 'AB' decision from dual union all 
         select 345 appnumber, 'BC' decision from dual union all 
         select 123 appnumber, 'PA' decision from dual union all 
         select 345 appnumber, 'PA' decision from dual union all 
         select 123 appnumber, 'AM' decision from dual) 

    select appnumber bulk collect into v_resultset 
     from (
      select appnumber 
       from sample_data 
      where decision in (select column_value from table(p_states)) 
      group 
       by appnumber 
       , decision  
      ) 
    group    
     by appnumber 
    --the next condition ensures that appnumber has exactly ALL states 
    having count(*) = (select count(column_value) from table(p_states)); 

    return v_resultset; 
end TEST_GET_ANSWER; 

使用該函數是這樣的:

​​
+0

這也是一個很好的解決方案。謝謝。 – SeeWe