SQL查询中的多重计数
给出以下简单的表结构:
<前><代码>部门 PK - 部门 ID 部门名称 -------------------------- 1 部门 1 2 部门 2 3 部门3 4 部门 4 团体 PK - GroupdID 部门 ID -------------------------- 1 1 2 1 3 3 4 4 5 2 6 3 7 1 8 3 存货 PK - 物品 ID 组 ID -------------------------- 1 2 2 3 3 8 4 1 5 4 6 5 7 1 8 2 9 2 10 3 11 7
有没有一种方法可以不使用子查询(这很简单),让我可以获得部门列表、每个部门中的组数以及每个部门中的库存计数?
示例输出:
DeptID DeptName GroupCount ItemCount
-----------------------------------------------------
1 Department 1 3 6
2 Department 2 1 1
3 Department 1 3 3
4 Department 4 1 1
我的直觉告诉我,这只是使 GROUP BY 语句正确的简单问题,但到目前为止我还是一片空白。 如果确实需要使用子查询,这不是问题。 我只是想确认一下,以供将来参考。
注意:使用 SQL Server 2000 解决此特定问题
Give the following simple table structure:
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
Is there a way without using subqueries (which is easy) where I could get a listing of the departments, the count of the groups in each department, and the count of the inventory in each department?
Example Output:
DeptID DeptName GroupCount ItemCount
-----------------------------------------------------
1 Department 1 3 6
2 Department 2 1 1
3 Department 1 3 3
4 Department 4 1 1
My gut is telling me it's just a simple matter of getting the GROUP BY statements correct, but so far I'm drawing a blank. If it does require the use of subqueries, this isn't a problem. I just wanted to confirm for future reference.
NOTE: Using SQL Server 2000 for this particular problem
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
生成的结果为:
对于没有
Groups
或仅具有Groups< 的
Departments
,这也会生成正确的0
。 /code> 没有Items
。The results produced are:
This will also produce correct
0
's for theDepartments
that have noGroups
, or having onlyGroups
withoutItems
.以下至少是获得结果的一种方法。
Following is at least one way to get the results.
这是我的尝试...
Here's my try...
抱歉,我没有坐在我的 SQL Server 前面。 这是您的第一次尝试。 我可能无法正确理解您想要的结果,但也许您可以以此为起点?
Sorry I am not sitting in front of my SQL Server. Here is a first attempt for you. I might not understand you desired result correctly but maybe you can use this as a starting point?