SQL查询中的多个计数

The*_*TXI 2 t-sql group-by sql-server-2000

给出以下简单的表结构:

Departments
PK - DeptID    DeptName
--------------------------
1              Department 1
2              Department 2
3              Department 3
4              Department 4

Groups
PK - GroupdID    DeptID
--------------------------
1                1
2                1
3                3 
4                4
5                2
6                3
7                1
8                3

Inventory
PK - ItemID    GroupID
--------------------------
1              2
2              3
3              8
4              1
5              4
6              5
7              1
8              2
9              2
10             3
11             7
Run Code Online (Sandbox Code Playgroud)

有没有办法不使用子查询(这很容易),我可以获得部门列表,每个部门的组计数,以及每个部门的库存计数?

示例输出:

DeptID    DeptName          GroupCount      ItemCount
-----------------------------------------------------
1         Department 1      3               6
2         Department 2      1               1
3         Department 1      3               3
4         Department 4      1               1    
Run Code Online (Sandbox Code Playgroud)

我的直觉告诉我,让GROUP BY语句正确是一个简单的问题,但到目前为止,我正在画一个空白.如果它确实需要使用子查询,这不是问题.我只是想确认以备参考.

注意:使用SQL Server 2000来解决此特定问题

Qua*_*noi 11

SELECT  d.deptID,
        COUNT(DISTINCT g.GroupID) AS Groups,
        COUNT(DISTINCT i.ItemID) AS Items
FROM    Departments d
LEFT JOIN 
        Groups g
ON      g.deptID = d.deptID
LEFT JOIN
        Items i
ON      i.GroupID = g.GroupID
GROUP BY
        d.deptID
Run Code Online (Sandbox Code Playgroud)

产生的结果是:

deptID  Groups  Items
-----   ------  -----
1       3       6 
2       1       1
3       3       3
4       1       1
Run Code Online (Sandbox Code Playgroud)

这也将产生正确0的为Departments那些没有Groups或仅具有GroupsItems.