使select sum()不返回null

时间:2014-09-03 08:11:40

标签: mysql sql

我需要使用sum进行sql查询,这将只向我显示sum不为null的记录和!= 0.现在我有:

QUERY

SELECT SUM(time) AS sumToPay,
w.name, w.lname 
FROM `service` s 
JOIN worker w 
ON s.worker_id = w.id 
GROUP BY s.worker_id

它显示了我正确的时间总和,但是当一个工人没有时间时它会显示我0.如何强制查询只显示非空值?

2 个答案:

答案 0 :(得分:5)

您可以使用having子句

SELECT 
sum(time) as sumToPay, 
w.name, 
w.lname 
FROM `service` s 
join worker w on s.worker_id = w.id 
group by s.worker_id 
having sum(time) > 0

答案 1 :(得分:0)

我不完全清楚您是否希望完全省略SUM()出现为0的行,或者是否要查看所有非空值的SUM()。 Donal的答案给你前者,这应该给你后者:

SELECT SUM(time) AS sumToPay,
w.name, w.lname 
FROM `service` s 
JOIN worker w ON s.worker_id = w.id 
WHERE time IS NOT NULL
GROUP BY s.worker_id