我正在尝试为特定的total sum of hours获取每个project_type的project_type,从而得到一个单独的行。
下面是我的SQL查询:
select SUM(total_hours) as hours, year(task_completion) as year
from task_details
group by project_type_id
having year = '2018' AND project_type_id = 10另外,下面是我的数据集的样子:
project_type_id | total_hours | task_completion
-------------------------------------------------------
10 | 5 | 2018-9-10
10 | 4 | 2018-9-11
10 | 10 | 2017-9-10
10 | 2 | 2016-9-10
11 | 9 | 2017-9-10
14 | 8 | 2017-9-11查询提供的输出如下:
hours | year
---------------
21 | 2018但我希望是9。
查询有什么问题?
发布于 2018-10-10 11:13:45
您的查询逻辑简单地关闭。GROUP BY在SELECT中使用不同的未聚合列。HAVING中有既不是聚合的也不是在GROUP BY中的列。MySQL扩展了它的语法以允许这样做。但是,查询(和结果)没有意义。
您的查询应该如下所示:
select sum(total_hours) as hours, year(task_completion) as year
from task_details
where project_type_id = 10
group by year
having year = 2018;有什么关系?注意:
project_type_id的比较是在聚合之前的WHERE子句中,而不是在聚合之后。GROUP BY子句包含来自SELECT的未聚合列。year是一个数字,所以比较是一个数字,而不是一个字符串。我建议您在聚合之前进行所有比较--因此不需要使用having子句:
select sum(total_hours) as hours,
year(task_completion) as year
from task_details
where project_type_id = 10 and
task_completion >= '2018-01-01' and
task_completion < '2019-01-01'
group by year;注意,此版本不使用year()。列上的函数可能会妨碍索引的使用。此版本可以在(project_type_id, task_completion)上使用索引。
发布于 2018-10-10 11:12:54
您需要在project_type_id中使用where和having的条件,否则它将对全年的值进行求和:
select project_type_id,
SUM(total_hours) as hours,
year(task_completion) as year_completion
from task_details
WHERE year(task_completion) = 2018
and project_type_id = 10
group by project_type_id https://stackoverflow.com/questions/52738904
复制相似问题