简体   繁体   English

不满足条件的查询计数为 1

[英]query make a count to 1 which does not satistfy the condition

i have a two table i want to know the number of person who are all assigned to project in each sector我有一张两张表我想知道每个部门都分配给项目的人数

CREATE TABLE first1( a int,projectname varchar(20));
INSERT INTO first1 VALUES
(1001,'crm'),
(1002,'iic'),
(1003,'abc'),
(1004,'sifty bank');

CREATE TABLE diff(b int,name varchar(20),p_id int );
INSERT INTO diff VALUES
(101,'priya',1001),
(102,'divya',1002),
(103,'sidhu',null),
(104,'shiva',null),
(105,'surya',1002);

Query:询问:

select first1.projectname,count(*) from first1  left join diff on first1.a=diff.p_id group by 
first1.projectname;

The output of this code is:该代码的output为:

abc|1
crm|1
iic|2
sifty bank|1

The expected output is:预期的 output 为:

abc|0
crm|1
iic|2
sifty bank|0

The problem is count(*) ;问题是count(*) it counts how many rows there are in each group - A project without any person assigned still counts as 1. Instead, you need to count() something from the left table, so null values are not taken into account:它计算每组中有多少行 - 没有分配任何人的项目仍计为 1。相反,您需要从左表中count()一些东西,因此不考虑null值:

select f.projectname, count(d.p_id) as cnt_diff
from first1 f
left join diff d on f.a = d.p_id 
group by f.projectname;

Note that you can get the same result with a subquery:请注意,您可以使用子查询获得相同的结果:

select f.projectname, 
    (select count(*) from diff d where d.p_id = f.a)  as cnt_diff
from first1 f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM