首页 > 解决方案 > 在多个日期列mysql上按年份分组

问题描述

我有如下表格:

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计算中。

为了进一步详细说明,应该考虑for year 2019、 row1和两者。1因此总小时数应该是123 + 234 = 357

而对于year 2018,行2 and 3

同样,对于year 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>

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

标签: mysqlsqlgroup-by

解决方案


您想为每一行考虑每一年一次。用于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;

如果您想在总和中考虑一年两次或三次的连续,然后更改UNIONUNION ALL


推荐阅读