mysql - mysql 在多个日期列上按年分组

标签 mysql sql group-by

我有如下表格:

hours  | ... | task_assigned  | task_deadline  | task_completion
----------------------------------------------------------------
123    | ... | 2019-08-01     | -              | -
234    | ... | -              | 2018-08-01     | 2019-08-01
145    | ... | 2017-08-01     | 2017-08-01     | 2018-01-01

我想计算每年的总小时数,即按年分组。

目前我只考虑 task_completion 字段。

如果task_completion字段没有值,则该记录不包含在SUM计算中。

为了进一步详细说明,假设对于 2019 年,行 11 都应该被考虑。因此,总小时数应为 123 + 234 = 357

对于 2018 年,行 2 和 3

同样,对于 2017 年,行 3

SELECT YEAR(task_completion) as year, ROUND(SUM(total_hours), 2) as hours 
FROM task
GROUP BY year
HAVING year BETWEEN '$year_from' AND '$year_to'

结果集:

year  |  hours
--------------------
2017  |  <somevalue>
2018  |  <somevalue>
2019  |  <somevalue>

我怎样才能同时包含其他两个日期字段?

最佳答案

您想要在每一行的每一年考虑一次。使用 UNION 获取这些年份:

select year, round(sum(total_hours), 2) as hours
from
(
  select year(task_assigned) as year, total_hours from task
  union
  select year(task_deadline) as year, total_hours from task
  union
  select year(task_completion) as year, total_hours from task
) years_and_hours
group by year
having year between $year_from and $year_to
order by year;

如果你想在总和中考虑一年两次或三次的行,则将 UNION 更改为 UNION ALL

关于mysql - mysql 在多个日期列上按年分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55296674/

相关文章:

mysql - 如何使用 MySQL 将项目添加到列表框

php - MySQL 表 USERS 和 FLASHCARDS - 如何根据另一个修改一个?

PHP "Simple"查询需要大量时间

sql - 如何在oracle中实现多值属性?

php - MySQL查询排序/分组性能

mysql - 将多条sql更新语句合并为一条语句

php - 请将 SQL 查询与 PHP 帮助合并

python - 将数据从 MySQL 数据库导入到 Pandas 数据框中,包括列名

group-by - pyspark:聚合列中最常见的值

sql - 如何为每行添加具有相同值的列?