2013-05-31 46 views
1

我有一個查詢的問題,看我有兩個表,讓說:甲骨文比較兩個計數()不同的表

table a: 
progid  | name | type 
12   | john | b 
12   | anna | c 
13   | sara | b 
13   | ben | c 
14   | alan | b 
15   | george| b 

table b: 
progid  | name | type 
12   | john | b 
12   | anna | c 
13   | sara | b 
14   | alan | b 
15   | george| b 

表中獲取數

progid | count(*) 
12  | 2 
13  | 2 
14  | 1 
15  | 1 

B表得到

progid | count(*) 
12  | 2 
**13  | 1**<-this is what I want to find different count 
14  | 1 
15  | 1 

我想要的是找到表b中的哪個progid不在表格a中(因爲你可以看到prog ID在那裏,但是它們是s應該在那裏相同的時間!所以,本是走了,但進程id 13是存在的)

所以我希望得到的progid其中count表中的變化,我想:

select a.progid from 
(select progid ,count(*) total from tablea group by progid) a, 
(select progid ,count(*) total from tableb group by progid) b 
where 
a.progid=b.progid and a.total<>b.total; 

我得到b.total無效的標識符

if I use a.count(progid)<>b.count(progid) 

錯誤表示不能使用組功能,有什麼想法?我很絕望!


好,我覈對答案,這裏是原來的

select a.beneficiarioid from 
(select beneficiarioid,count(*) total from lmml_ejercicio_2012_3 where programaid=61 group by beneficiarioid order by beneficiarioid) a, 
(select beneficiarioid,count(*) total from ejercicio_2012_3 where programaid=61 group by beneficiarioid order by beneficiarioid) where 
a.beneficiarioid=b.beneficiarioid and a.total<>b.total; 

無論如何,我會嘗試你querys,並讓你知道!非常感謝你!! BTW它的Oracle 11g

+0

什麼版本的Oracle您使用的是?您的聲明在Oracle XE –

+0

上正常工作我嘗試了您的聲明,它對我來說運行良好。也許如果你可以把你的表的真實姓名和你的真正的SQL語句。 –

回答

3

您應該能夠使用子查詢來獲取每個計數,然後使用全外連接他們加入:

select coalesce(a.progId, b.progId) progid, 
    coalesce(a.atotal, 0) atotal, 
    coalesce(b.btotal, 0) btotal 
from 
(
    select progid, count(*) aTotal 
    from tablea 
    group by progId 
) a 
full outer join 
(
    select progid, count(*) bTotal 
    from tableb 
    group by progId 
) b 
    on a.progid = b.progid 
where coalesce(a.atotal, 0) <> coalesce(b.btotal, 0); 

SQL Fiddle with Demo。如果一個表中的行不在另一個表中,我使用了FULL OUTER JOIN。

+0

+1:對於非常大量的獨特progid,使用公用表表達式重寫可能會有所幫助。 –

1

即使您的查詢工作正常在我的數據庫,我寧願設置操作:

(select progid ,count(*) total from tablea group by progid) 
minus 
(select progid ,count(*) total from tableb group by progid) 
+0

但是如果在tableb上有沒有在tablea上對應的progid的寄存器,那就不會顯示它。我認爲@bluefeet FULL OUTER JOIN在這種情況下會更好。 –