I have these 2 tables:
Table: Unit
UnitID | Title
1 Unit 1
2 Unit 2
3 Unit 3
Table: Piece
PieceID | UnitID | Category
1 1 A
2 1 A
3 1 B
4 2 A
5 3 B
What I need to do is show a count of the total units containing Piece rows with Category A, as well as the total amount of Piece table rows with Category 开发者_如何学JAVAA (regardless of unitid). So using the data above, the result would be 2 units, 3 Piece rows.
I could do this with two statements, but I would like to do it one.
Any suggestions from craftier folks than I?
Filter out the pieces with the correct category, then count the units distinctly:
select count(distinct UnitId) as Units, count(*) as Pieces
from Piece
where Category = 'A'
Try:
select count(distinct UnitID) total_units, count(*) total_rows
from Piece
where Cateory = 'A';
精彩评论