我有一个包含部门名称的表,但如果某个部门不属于另一个表中的计数部分,那么我就不会得到部门名称。
如何才能获得不属于CSEReduxResponses的部门的名称,以便在'branchtotalstarsgiven'为0的输出中显示?
以下是一些测试数据以及让我了解部门数量的查询。
create table CSEReduxDepts (csedept_id int, csedept_name varchar(25));
insert into CSEReduxDepts (csedept_id, csedept_name)
values (1,'one'),
(2,'two'),
(3,'three'),
(4,'four');
create table CSEReduxResponses (execoffice_status int, submitterdept int);
insert into CSEReduxResponses (execoffice_status,submitterdept)
values (1,1),
(1,1),
(1,1),
(1,1),
(1,2),
(1,2);
------------------------------------------------------------------
SELECT submitterdept,csedept_name, COUNT(*) as 'branchtotalstarsgiven'
FROM CSEReduxResponses c
join CSEReduxDepts d on
c.submitterdept= d.csedept_id
WHERE execoffice_status = 1
GROUP BY execoffice_status, submitterdept, csedept_name
答案 0 :(得分:1)
要获得预期结果,实施的更改很少:
JOIN
从INNER
更改为LEFT/RIGHT
WHERE
条件,以便它不会删除不在CSEReduxResponses
COUNT
,以便当部门不在CSEReduxResponses
结果查询是
SELECT submitterdept
, csedept_name
, COUNT(execoffice_status) as 'branchtotalstarsgiven'
FROM CSEReduxDepts d
LEFT JOIN CSEReduxResponses c on d.csedept_id = c.submitterdept
WHERE COALESCE(execoffice_status, 1) = 1
GROUP BY execoffice_status, submitterdept, csedept_name
更改的部分以粗体显示,COUNT
使用execoffice_status作为参数,因为COUNT(*)
计算每一行,但COUNT(field)
仅计算非空的行。
答案 1 :(得分:0)
据我了解,您需要在第二个表中没有显示的部门名称:
SELECT csedept_id, csedept_name FROM CSEReduxDepts
WHERE csedept_id NOT IN (SELECT distinct submitterdept FROM CSEReduxResponses)
答案 2 :(得分:0)
将内连接更改为外连接应该有效。像这样:
from CSEReduxDepts d left join SEReduxResponses c
on c.submitterdept= d.csedept_id
and execoffice_status = 1