Mysql SUM左连接强制显示结果,总和为零结果

时间:2017-07-27 09:24:13

标签: mysql left-join

所以我现在正在努力解决这个问题。

员工只需在表clocktimes

上添加开始和结束时间

我只想在所有日期间隔中包括所有员工的结果,包括ZERO(未显示的那些)。我也尝试使用COALESCE而没有预期的结果。

regular字段是已经以单位为单位的时间量示例:3.5。

我的问题是显示结果为0(零)的那些,该任务中没有小时。

使用的查询:

SELECT
employees.employeeid,
employees.emp_external_id,
employees.status_id,
employees.firstname,
employees.middlename,
employees.lastname,
IFNULL(SUM(clocktimes.Regular), 0) AS sumoftime
FROM
employees
LEFT JOIN clocktimes ON employees.emp_external_id  = clocktimes.EmployeeGUID
WHERE
employees.status_id <> 3 AND
date(clocktimes.StartDate) BETWEEN '2017-07-01' AND '2017-07-15'
GROUP BY
employees.employeeid
ORDER BY
employees.firstname ASC 

http://sqlfiddle.com/#!9/d89534/1

1 个答案:

答案 0 :(得分:1)

SELECT
employees.employeeid, 
employees.emp_external_id,
employees.status_id,
employees.firstname,
employees.middlename,
employees.lastname, 
IFNULL(SUM(clocktimes.Regular), 0) AS sumoftime
FROM
employees
LEFT JOIN clocktimes ON employees.emp_external_id = clocktimes.EmployeeGUID
WHERE
employees.status_id <> 3 AND
(date(clocktimes.StartDate) BETWEEN '2017-07-01' AND '2017-07-15') or date(clocktimes.StartDate) is null )
GROUP BY
employees.employeeid
ORDER BY
employees.firstname ASC

这里的haapening是,因为您通过日期过滤,所以空列被过滤掉了。 检查where子句