开发者

SQL: 2 Counts using joins?

开发者 https://www.devze.com 2023-01-03 14:54 出处:网络
I have these 2 tables: Table: Unit UnitID | Title 1Unit 1 2Unit 2 3Unit 3 Table: Piece PieceID | UnitID | Category

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';
0

精彩评论

暂无评论...
验证码 换一张
取 消