mysql - 在多个日期列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>
我怎样才能包含其他两个日期字段?
解决方案
您想为每一行考虑每一年一次。用于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
。
推荐阅读
- python - Fuzzywuzzy 过程 extractBests 的奇怪结果
- python - 用于duckduckgo的python selenium并找到url
- c++ - 在调用 sendto() 之前从 UDP 套接字修改 IP 标头
- javascript - 如何捕获注销确认“是”和“否”的事件
- javascript - 在 HTML 和 JavaScript 中使用检查隐藏某些内容以使其无法查看
- regex - htaccess 中带有斜杠数量的条件
- python - 我需要计算滞后 6 天 Pandas python 的每日价格回报的平均值
- css - 如何正确声明路径?
- python - 将 imshow 与底图一起使用:颜色和地图边界不匹配
- common-lisp - 使用双浮点数时,有没有办法在普通 lisp 中显示更少的数字?