SQL使用总和(天)

时间:2016-09-26 14:01:29

标签: sql

我的问题是关于使用函数sum(天)并在我的查询中重用它。

select
  new_client, 
  sum(days) as effort
from actuals
where week >='01/01/2016' 
  and type is null 
  and sum(days) = 0
group by new_client
order by effort desc

我知道这不起作用。我想知道如何做到这一点。

3 个答案:

答案 0 :(得分:3)

select new_client, sum(days) as effort
from actuals
where week >='01/01/2016' and type is null                          
group by new_client
having sum(days) = 0
order by effort desc

这样的东西应该有效吗?您不能在where子句中使用SUM()。这就是HAVING存在的原因。

问题是为什么你会想要选择那个SUM(天),因为如果有结果它总是会显示0。

答案 1 :(得分:1)

如果days永远不会消极,您也可以这样做:

select new_client, sum(days) as effort
from actuals
where week >= '2016-01-01' and type is null and days > 0
group by new_client
order by effort desc;

这更有效,因为它在聚合之前进行过滤。但@Jens的答案更为笼统。

答案 2 :(得分:1)

嗨,很好的问题
您可以使用以下查询

select new_client, sum(days) as effort
from actuals
where week >='01/01/2016' and type is null
group by new_client
having  sum(days) = 0
order by effort desc
  

Explination

WHERE子句在执行所有条件后执行HAVING子句时执行当前条件。即HAVING执行条件的结果,WHERE逐行执行或处理数据。简单来说,WHERE子句是预过滤器,HAVING子句是后置过滤器