where子句在sql查询中使用sum聚合

时间:2015-09-15 07:46:17

标签: mysql aggregate-functions mysql-workbench

我有一张桌子,我想只显示那些至少有一个注册用户的部门。我的查询如下:

SELECT departments.id as DepartmentID, 
       departments.depName as DepartmentName,
       SUM(IF(users.isDelete=0, 1, 0)) AS NumberOfUsers
FROM (myDB.departments) 
LEFT JOIN myDB.users ON departmentID=departments.id
AND `departments`.`isDelete` =  0
HAVING SUM(NumberOfUsers) >=0

HAVING SUM(NumberOfUsers) >=0根本不起作用。我想检查NumberOfUsers是否多于一个然后显示它,如果不是多于一个然后不显示它。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT departments.id as DepartmentID, 
       departments.depName as DepartmentName,
       (SELECT COUNT(u.id)
       FROM users u
       WHERE u.departmentID = d.id) as NumberOfUsers
FROM departments d
WHERE d.isdelete = 0
AND EXISTS
  (SELECT 'user'
  FROM users u
  WHERE u.departmentID = d.id)

这样,在主查询中不使用SUM(必须使用GROUP BY来显示其他标量字段,如departments.id和departments.depName。在My Sql中不是必需的GROUP BY)

EXISTS条款保证至少有一个用户在场。如果要显示所有部门(独立用户数,删除EXISTS子句)

答案 1 :(得分:1)

我认为您可以简化查询,因为您正在检查用户表中is_delete应该为0的条件,因此不需要左连接,您只需使用普通连接即可。在此之后,您将通过having子句删除那些没有记录的行,因此您可以将此条件简单地放在where子句中,如下所示 -

SELECT dpt.id AS DepartmentID, dpt.depName AS DepartmentName, 
COUNT(usr.id) AS NumberOfUsers
FROM myDB.departments AS dpt 
JOIN myDB.users AS usr ON usr.departmentID=dpt.id
WHERE dpt.`isDelete` =  0 AND usr.isDelete=0 

注意:假设用户表的主键为id,如果没有,则可以使用count函数中的任何其他列。

答案 2 :(得分:0)

在这种情况下,您还需要使用group by子句。

 SELECT departments.id as DepartmentID, 
        departments.depName as DepartmentName,
        SUM(IF(users.isDelete=0, 1, 0)) AS NumberOfUsers
 FROM (myDB.departments) 
 LEFT JOIN myDB.users ON departmentID=departments.id
     AND `departments`.`isDelete` =  0
 GROUP BY departments.id, departments.depName
 HAVING SUM(IF(users.isDelete=0, 1, 0)) >=0

但如果您想要更短的答案,可以使用JOIN代替LEFT JOIN并删除HAVING子句:

 SELECT departments.id as DepartmentID, 
        departments.depName as DepartmentName,
        SUM(IF(users.isDelete=0, 1, 0)) AS NumberOfUsers
 FROM (myDB.departments) 
 JOIN myDB.users ON departmentID=departments.id
     AND `departments`.`isDelete` =  0
 GROUP BY departments.id, departments.depName