gpt4 book ai didi

mysql - having子句不过滤记录mysql

转载 作者:行者123 更新时间:2023-11-29 05:52:39 25 4
gpt4 key购买 nike

我正在尝试获取特定 year 的每个 project_typetotal sum of hours,因此结果是一行。

这是我的 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

查询有什么问题?

最佳答案

您的查询逻辑完全关闭。您有一个 GROUP BYSELECT 中使用不同的未聚合列。您在 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) 上使用索引。

关于mysql - having子句不过滤记录mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52738904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com