根据列值分组、计数和排除
虽然我在 SQL 或 MySQL 方面并不是完全的新手,但我注意到还有很多东西需要学习。经过多次尝试、阅读和搜索后,我无法理解这个问题。如果您能给我任何指点,我将不胜感激。
我已将实际数据和表格简化如下。
有两个相关表:Staff 和 Work。它们包含各个项目的人员数据。
员工:
ID Name Unit
1 Smith Chicago
2 Clarke London
3 Hess Chicago
工作:
StaffID ProjectID
1 10
2 10
3 10
1 20
2 30
3 40
1 50
3 50
目标:
将所有有芝加哥员工的项目分组,并统计该项目中的所有员工数量。
预期结果:
Project Staff count
10 3
20 1
40 1
50 2
因此项目 30 未列出,因为其成员不是来自芝加哥。
我下面的查询显然是错误的。它只计算来自芝加哥的项目成员,而不计算整个项目工作人员。
SELECT
work.projectID as Project, COUNT(*) as "Staff count"
FROM
staff
JOIN
work ON staff.ID=work.staffID
WHERE
unit="Chicago"
GROUP BY
work.projectID;
Although I've not a complete newbie in SQL or MySQL I notice that there's still quite a bit to learn. I cannot get my head around this one, after much trying, reading and searching. If you can give any pointers, I'd be grateful.
I have simplified the actual data and tables to the following.
Two tables are relevant: Staff, and Work. They contain data on staff in various projects.
Staff:
ID Name Unit
1 Smith Chicago
2 Clarke London
3 Hess Chicago
Work:
StaffID ProjectID
1 10
2 10
3 10
1 20
2 30
3 40
1 50
3 50
Goal:
To get grouped all those projects where there are staff from Chicago, with the count of all staff in that project.
Expected result:
Project Staff count
10 3
20 1
40 1
50 2
So the project 30 is not listed because its member(s) are not from Chicago.
My query below is obviously wrong. It counts only those project members who are from Chicago, not the whole project staff.
SELECT
work.projectID as Project, COUNT(*) as "Staff count"
FROM
staff
JOIN
work ON staff.ID=work.staffID
WHERE
unit="Chicago"
GROUP BY
work.projectID;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会将芝加哥的测试放在子选择中。
或者,您可以使用自连接,但我发现子选择更容易理解。
I'd put the test for Chicago in a subselect.
Alternatively you can use a self-join, but I find the sub-select easier to understand.
删除 where 子句并添加having 子句,该子句检查至少一名员工来自芝加哥。
Remove the where clause and add a having clause which checks that at least one member of staff is from Chicago.
最后:结果。再次感谢@Johan 和@a'r 的帮助,并感谢@Johan 让我走上正轨(就我而言)。
我将子选择更改为派生表,并将其与 projectID 上的工作表进行内连接。
Finally: the result. Thanks again both @Johan and @a'r for your help, and @Johan for getting me on the right track (in my case).
I changed the sub-select to a derived table, and inner-joined this with the Work table on projectID.