我有如下表格:
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 年
,行 1
和 1
都应该被考虑。因此,总小时数应为 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/