mysql & php - How to calculate total year of experience from multiple date range?

岁酱吖の 提交于 2019-12-12 01:09:51

问题


I want to calculate total experience year and month of each particular user id. user_id can be multiple in the table like the following. Here for user_id 14, the total experience range will be from 2010-01-03 to 2013-11-30 and the expected result will be 3 year 11 month. How can I do it in either php or mysql?


回答1:


Comments are relevant but incomplete for your case.

If exp_to is not nullable:

select user_id, sum( datediff(exp_to, exp_from) +1 )
from experience
group by user_id;

Notes:

  • don't forget +1 in the sum, because for user 25 it would return 0, whereas we can decently consider the user worked 1 day
  • for user 14, based on your screenshot, the total is 880 days: you'll have to calculate the number of months (with PHP, for example).

If exp_to is nullable (which makes sense if user is still working at the same position):

select user_id, sum( datediff( ifnull(exp_to, now()), exp_from) +1 )
from experience
group by user_id;


来源:https://stackoverflow.com/questions/37151815/mysql-php-how-to-calculate-total-year-of-experience-from-multiple-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!