2010-06-14 62 views
2

我有這2個表:SQL:2使用連接計數?

表:單位

UnitID | Title 
1  Unit 1 
2  Unit 2 
3  Unit 3 

表:一塊

PieceID | UnitID | Category 
1   1  A 
2   1  A 
3   1  B 
4   2  A 
5   3  B 

我需要做的是顯示包含有類件行總套數的計數A以及帶有類別A的塊錶行總數(不管單元大小)。因此,使用上面的數據,結果將是2單位,3件行。

我可以用兩個語句做到這一點,但我想要做到這一點。

任何建議從藝人比我更?

回答

2

篩選出具有正確類別的作品,然後計算單位明顯:

select count(distinct UnitId) as Units, count(*) as Pieces 
from Piece 
where Category = 'A' 
+0

這似乎工作 - 我從來沒有看到伯爵用這樣的獨特。謝謝您的幫助。 – Todd 2010-06-14 13:51:35

2

嘗試:

select count(distinct UnitID) total_units, count(*) total_rows 
from Piece 
where Cateory = 'A'; 
+0

這個答案的工作,以及(實際上是一回事)。謝謝馬克。 – Todd 2010-06-14 13:52:32