2012-11-11 22 views
0

我有兩個查詢(返回正確的結果):增加,我基本上要計數,然後組結合兩個表的計數,然後組

Select profileID, 
Count(*) as numTotal from replies 
GROUP BY profileID; 

結果:

profileID: 1,2,3 
numTotal: 10,1,1 

Select postedByID, 
Count(*) as numTotal from WIRL_01.posts 
Group by postedByID 

結果:

postedByID: 1,2,3 
numTotal: 13,4,3 

在這種情況下,我想分組profileID = postedByID。我嘗試以下,但無濟於事:

Select profileID, 
Count(*) as numTotal 
from replies 
INNER JOIN posts ON replies.profileID = posts.postedByID 
Group by profileID 

結果:

postedByID: 1,2,3 
numTotal: 130,4,3 

任何指導,將不勝感激。

編輯:

這個查詢得到我一點點接近但是我怎麼組的結果通過配置文件ID?

Select profileID, Count(*) from WIRL_01.replies Group by profileID 
UNION ALL 
Select postedByID, Count(*) from WIRL_01.posts Group by postedByID 

給我...

配置文件ID:1,2,3,1,2,3 COUNT(*):10,1,1,13,4,3

我需要的是:

配置文件ID:1,2,3 COUNT(*):23,5,4

+1

有什麼錯你的連接查詢? –

+0

@AlainCollins我沒有得到預期的結果。看起來這兩個結果正在成倍增長。爲了清晰起見,我會用結果編輯我的帖子。 – Jason

回答

0

明白了! :)

Select profileID, sum(count) as totalNum from (Select profileID, Count(*) as count from replies Group by profileID 
UNION ALL 
Select postedByID, Count(*) as count from posts Group by postedByID) as numTotal 
group by profileID 

非常感謝喬Stafanelli:Selecting Sum of the Count From Tables in a DB

相關問題