0

我想计算分配给每个员工的项目数量。但我也想包括那些目前没有从事任何项目的人的名字,显然这些人的计数值应该是空白或空。这是我到目前为止所做的:

Select
lname
, ssn
, COUNT(*) AS projectnum
FROM
employee LEFT OUTER JOIN works_on
ON essn=ssn
GROUP BY 
lname
ORDER BY
projectnum DESC

它工作得很好,除了在 projectnum 字段中,它为那些不从事任何项目的人设置了 1,而不是 null,我该如何解决这个问题?

4

1 回答 1

2

你算错了。说count(*)基本上计算返回的行,您将获得带有 NULL 项目的行(如预期的那样),但count(*)将它们视为行,因此您得到1. 如果没有项目,您需要计算一个为 NULL 的列,如果有,则为非 NULL:

select ..., count(c) as projectnum ....

c的一些非 NULL 列在哪里works_on


例如,我的 MySQL 沙箱中有这些表:

mysql> select * from posts;
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
+------+

mysql> select * from posts_tags;
+---------+--------+
| post_id | tag_id |
+---------+--------+
|       1 |      1 |
|       1 |      2 |
|       1 |      3 |
|       2 |      2 |
|       2 |      3 |
|       3 |      2 |
+---------+--------+

count(*)您可以看到和之间的区别count(tag_id)

mysql> select posts.id, count(*) from posts left join posts_tags on posts.id = posts_tags.post_id group by posts.id;
+------+----------+
| id   | count(*) |
+------+----------+
|    1 |        3 |
|    2 |        2 |
|    3 |        1 |
|    4 |        1 |
+------+----------+

mysql> select posts.id, count(tag_id) from posts left join posts_tags on posts.id = posts_tags.post_id group by posts.id;
+------+---------------+
| id   | count(tag_id) |
+------+---------------+
|    1 |             3 |
|    2 |             2 |
|    3 |             1 |
|    4 |             0 |
+------+---------------+

在第一个中做 acount(*)会让你迷路1id=4count(tag_id)在第二个中会给你预期的0.

于 2013-11-10T05:43:33.467 回答