在count中包含0不适用于extra where子句

时间:2017-05-29 10:32:05

标签: sql sql-server sql-server-2014

在我当前的项目中,我有分配了设施的用户组。我需要的是显示用户组的名称,它是部门,它是描述分配的设施数量它。我有点能够实现这一点,如下所示:

当前“成功”结果

Successful query of what I wanted

我现在面临的问题是当我添加一个where子句时,说明已删除的设施应包含 NOT 。下面是我的SQL语句,它产生上面的结果:

声明以实现上述结果

SELECT ug.usergroupname UserGroupName, dpt.deptname Department, ug.usergroupdesc UserGroupDesc, count(ugf.usergroupid) NumOFFacilities
FROM tblusergroup ug
LEFT JOIN tblusergroupfacilities ugf
ON ug.usergroupid = ugf.usergroupid
LEFT JOIN tbldepartment dpt
ON dpt.deptcode = ug.deptcode
LEFT JOIN tblfacility f
ON ugf.facilityid = f.facilityid
WHERE ug.isdeleted = 0
GROUP BY ug.usergroupname, dpt.deptname, ug.usergroupdesc

但是,当我将where子句添加到不包含已删除的工具时,它会产生另一个结果:

已编辑的声明

SELECT ug.usergroupname UserGroupName, dpt.deptname Department, ug.usergroupdesc UserGroupDesc, count(ugf.usergroupid) NumOFFacilities
FROM tblusergroup ug
LEFT JOIN tblusergroupfacilities ugf
ON ug.usergroupid = ugf.usergroupid
LEFT JOIN tbldepartment dpt
ON dpt.deptcode = ug.deptcode
LEFT JOIN tblfacility f
ON ugf.facilityid = f.facilityid
WHERE ug.isdeleted = 0
AND f.isdeleted = 0     //<-------added clause
GROUP BY ug.usergroupname, dpt.deptname, ug.usergroupdesc

更改结果

enter image description here

除了删除的设施外,有什么办法可以达到上述结果吗?任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:3)

关于如何在一个查询中执行此操作,我的头脑中没有任何内容,但使用C:\Program Files (x86)\Java\jre1.8.0_131\bin>keytool -exportcert -alias androiddebugkey -keystore C:\Users\siddhijambhale\.android\debug.keystore | "C:\Program Files (x86)\openssl-0.9.8k_X64\bin\openssl.exe" sha1 -binary | "C:\Program Files (x86)\openssl-0.9.8k_X64\bin\openssl.exe" base64 似乎很简单。单独运行以了解它们提供的内容:

UNION

答案 1 :(得分:0)

LEFT JOIN保留第一个表中的所有行以及第二个表中的匹配行。如果没有匹配项,则返回的值为NULLf.isdeleted上的条件会移除所有NULL值,将LEFT JOIN转换为INNER JOIN

解决方案是将条件放在ON子句中:

SELECT ug.usergroupname UserGroupName, dpt.deptname Department, ug.usergroupdesc UserGroupDesc, count(ugf.usergroupid) NumOFFacilities
FROM tblusergroup ug LEFT JOIN
     tblusergroupfacilities ugf
     ON ug.usergroupid = ugf.usergroupid LEFT JOIN
     tbldepartment dpt
     ON dpt.deptcode = ug.deptcode LEFT JOIN
     tblfacility f
     ON ugf.facilityid = f.facilityid AND f.isdeleted = 0
WHERE ug.isdeleted = 0
GROUP BY ug.usergroupname, dpt.deptname, ug.usergroupdesc;

请注意,第一个表中的条件属于WHERE子句。