2011-12-13 43 views
3

我有以下兩個表:Oracle的組/數查詢

TableOne 
======== 
Id1|ColA1|ColB1|ColC1|ColD1|ColE1 
-------------------------------- 
    1| AFoo|BFoo |CFoo | DFoo| EFoo 
    2| AFoo|BBar |CFoo | DFoo| EFoo 

TableTwo 
======== 
Id2|ColA2|ColB2|ColC2 
--------------------- 
11| 1 |ABC |NOP | 
12| 1 |ABC |QRS | 
13| 1 |DEF |TUV | 
14| 1 |DEF |WXY | 
15| 1 |DEF |FGH | 
16| 2 |ABC |NOP | 

我運行下面的查詢:

select t1.*, t2.* 
from TableOne t1 
inner join TableTwo t2 on t2.ColA2=t1.Id1 
where t1.ColA1='AFoo' 

,並得到以下結果:

Result 
====== 
Id1|ColA1|ColB1|ColC1|ColD1|ColE1|Id2|ColA2|ColB2|ColC2 
------------------------------------------------------- 
    1| AFoo|BFoo |CFoo | DFoo| EFoo| 11| 1 | ABC | NOP 
    1| AFoo|BFoo |CFoo | DFoo| EFoo| 12| 1 | ABC | QRS 
    1| AFoo|BFoo |CFoo | DFoo| EFoo| 13| 1 | DEF | TUV 
    1| AFoo|BFoo |CFoo | DFoo| EFoo| 14| 1 | DEF | WXY 
    1| AFoo|BFoo |CFoo | DFoo| EFoo| 15| 1 | DEF | FGH 
    2| AFoo|BBar |CFoo | DFoo| EFoo| 16| 2 | ABC | NOP 

我真的想要返回的是:

Desired Result 
====== 
Id1|MaxDup 
---------------------------------------- 
    1| 3 (This is because there are 3 DEF records) 
    2| 1 (This is because there is 1 ABC record) 

所以,我試圖跟蹤出現在每個TableOne行ColB2出現的最大數量。在上面的例子中,1的ID1有兩個ABC記錄和三個與它關聯的DEF記錄。由於DEF記錄比ABC記錄更多,我想要返回DEF記錄的計數。

任何人都可以提供一個可以證明這一點的工作示例嗎?

回答

1

試試這一個(我沒有測試過):

with t2 as (
    select ColA2, ColB2, count(*) cnt 
    from TableTwo 
    group by ColA2, ColB2 
) 
select t1.Id1, 
( select max(cnt) MaxDup 
    from t2 
    where t2.ColA2=t1.Id1) 
from TableOne t1 
+0

是的,很棒!謝謝! – user973479

0

這是SQL Server代碼,但我認爲它可以被安全地轉移到甲骨文:

select id1,cola1,colb1,colc1,cold1,cole1,max(dup) as dup2 from (
     select t1.id1, t1.cola1, t1.colb1, t1.colc1,t1.cold1,t1.cole1, t2.colb2,count(*) as dup 
     from t1 
     inner join t2 on t2.cola2=t1.Id1 
     where t1.cola1='Afoo' 
     group by t1.id1, t1.cola1, t1.colb1, t1.colc1,t1.cold1,t1.cole1, t2.colb2) 
    tab 
    group by id1,cola1,colb1,colc1,cold1,cole1 

它的工作原理上的SQL服務器,並通過包含在子查詢中可以只提取id1和dup2。試圖擴大你的數據集,它的作品。

+0

如果您使用了OP給出的列名稱,那麼測試您是否會使用quesy會更容易。 – APC

+0

更正,作品。 –

0

這是根據您的測試數據得出的結果。

SQL> select  
     cola2 
     , cnt as maxDup 
from (  
     select  
       cola2 
       , colb2 
       , cnt 
       , rank() over (partition by cola2 order by cnt desc) cnt_rnk 
     from (
       select cola2 
         , colb2 
         , count(*) as cnt 
       from TableTwo 
       group by cola2, colb2 
     ) 
    )   
where  cnt_rnk = 1 
/
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
COLA  MAXDUP 
---- ---------- 
1    3 
2    1 

SQL> 

最裏面的查詢計數重複。中間查詢排列重複計數。最高計數組合的最外面的查詢過濾器:

0

也許這個?

SELECT t2.id2 id, count(t2.ColB2) MaxDup 
FROM TableTwo t2 
WHERE EXISTS(
     SELECT * FROM TableOne t1 
     WHERE t1.id1 = t2.id2 
     AND t1.ColA1='AFoo') 
AND rownum < 2 
GROUP BY t2.id2, t2.ColB2 
ORDER BY MaxDup desc;