sql—在mysql中,如何将count(*)显示为0,而不是完全不显示行?

cnh2zyt3  于 2021-06-25  发布在  Mysql
关注(0)|答案(4)|浏览(792)

下面是一个细分的声明,试图找出所有拥有p1,p2技能并且认证>10的员工。

SELECT name, COUNT(empNumber) 
FROM SKILL 
WHERE (certified > 10) AND name IN ('p1', 'p2') 
GROUP BY name;

在数据库中:p1有2名员工,p2有0名员工
但是,现在显示的是

name | count(empNumber)
P1   |       2
P2   |       0   <= this row doesn't show but would like if it does

只需使用select语句和NOJOIN。谢谢

nnt7mjpx

nnt7mjpx1#

也许是这边?

SELECT name, COUNT(empNumber) as empNum
FROM SKILL 
WHERE (certified > 10) AND name IN ('p1', 'p2') 
GROUP BY name
HAVING empNum > 0

祝你今天愉快:)

brjng4g3

brjng4g32#

移动 WHERE 计数逻辑:

SELECT
    name,
    COUNT(CASE WHEN certified > 10 THEN empNumber END)
FROM SKILL 
WHERE name IN ('p1', 'p2') 
GROUP BY name;

检查的问题 certifiedWHERE 子句的作用是,它过滤掉不匹配的记录,然后在 GROUP BY 发生。我上面的版本对所有记录进行聚合,然后使用条件聚合来获得匹配的计数。
你也可以用 SUM 在这里:

SELECT
    name,
    SUM(CASE WHEN certified > 10 THEN 1 ELSE 0 END)
FROM SKILL
...
ki1q1bka

ki1q1bka3#

mysql有一个方便的速记。根据您想要的结果,您可以表示为:

SELECT name, SUM(certified > 10) 
FROM SKILL 
WHERE name IN ('p1', 'p2') 
GROUP BY name;

这是计数技巧。要计算员工人数,我认为您需要:

SELECT name, COUNT(DISTINCT CASE WHEN certified > 10 THEN empnumber END) 
FROM SKILL 
WHERE name IN ('p1', 'p2') 
GROUP BY name;

如果两个名字都不存在 SKILL 如果你还想在结果集中看到它们,你需要一个 LEFT JOIN (或某种形式的结合):

SELECT n.name, COUNT(DISTINCT s.empnumber)  
FROM (SELECT 'p1' as name UNION ALL SELECT 'p2' as name
     ) n LEFT JOIN
     SKILL s
     ON n.name = s.name AND s.certified > 10
GROUP BY n.name;

请注意此查询的一些更改:
我可以把过滤条件移到 ON 因为 LEFT JOIN 将保留这两个名字。
我引入了表别名。
所有列引用都是限定的,因此很清楚它们来自哪些表。
最后,问题是:
试图找到技能为p1、p2且认证>10的员工总数
这是一个数字,不是每个员工的一行。我相信这回答了一个问题:

SELECT COUNT(*)
FROM (SELECT empnumber 
      FROM SKILL 
      HAVING SUM( name = 'p1' ) > 0 AND
             SUM( name = 'p2' ) > 0 AND
             SUM( certified > 10 ) > 0
      GROUP BY empnumber
     ) es;

子查询将查找具有这三个条件的所有员工。这个 SUM() 是每个员工符合给定条件的技能数。这个 > 0 表示特定条件匹配。

tuwxkamq

tuwxkamq4#

您可以使用此查询:

select name, count(certified)
from skill
where name in ('p1','p2')
      and certified > 10
group by name
union
select b.name, 0 
from
(
  select name, count(certified)
  from skill
  where name in ('p1','p2')
       and certified <=10
  group by name
) b;

插图:

select * from skill;
+-----------+------+-----------+
| empNumber | name | certified |
+-----------+------+-----------+
|       100 | p1   |        11 |
|       101 | p1   |        12 |
|       102 | p2   |         0 |
|       103 | p2   |         5 |
+-----------+------+-----------+

-- run the query
+------+------------------+
| name | count(certified) |
+------+------------------+
| p1   |                2 |
| p2   |                0 |
+------+------------------+

相关问题