问题
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
+1in 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