# UPDATE - 1:
After some corrections, the following query gave the exact result marked by you as expected:
SELECT DISTINCT
nombre,
fecha_de_inicio,
FLOOR(PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'), DATE_FORMAT(fecha_de_inicio, '%Y%m')) / 12) as years_employed,
PERIOD_DIFF(DATE_FORMAT(DATE_ADD((CASE WHEN DAY(NOW()) >= DAY(fecha_de_inicio) THEN NOW() ELSE DATE_ADD(NOW(), INTERVAL -1 MONTH) END), INTERVAL -(FLOOR(PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'), DATE_FORMAT(fecha_de_inicio, '%Y%m')) / 12)) YEAR), '%Y%m'), DATE_FORMAT(fecha_de_inicio, '%Y%m')) as months_employed,
DATEDIFF(NOW(), fecha_de_inicio) - DATEDIFF(DATE_ADD(CONVERT(CONCAT(DATE_FORMAT((CASE WHEN DAY(NOW()) >= DAY(fecha_de_inicio) THEN NOW() ELSE DATE_ADD(NOW(), INTERVAL -1 MONTH) END), '%Y-%m-'), RIGHT('0' + DAY(fecha_de_inicio), 2)), DATE), INTERVAL -1 DAY), fecha_de_inicio) as days_employed
FROM
cms_trabajadores
ORDER BY
years_employed desc,
months_employed desc,
days_employed desc
Column calculation description:
years_employed : FLOOR(PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'), DATE_FORMAT(fecha_de_inicio, '%Y%m')) / 12)
- difference in years between current date and employment date counted as difference in months divided by 12 and with remainder left out
months_employed : PERIOD_DIFF(DATE_FORMAT(DATE_ADD((CASE WHEN DAY(NOW()) >= DAY(fecha_de_inicio) THEN NOW() ELSE DATE_ADD(NOW(), INTERVAL -1 MONTH) END), INTERVAL -(FLOOR(PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'), DATE_FORMAT(fecha_de_inicio, '%Y%m')) / 12)) YEAR), '%Y%m'), DATE_FORMAT(fecha_de_inicio, '%Y%m'))
- here, using PERIOD_DIFF
function, difference in months is counted substracting first 1 month from NOW()
only if DAY(NOW()) < DAY(fecha_de_inicio)
, then substracting the difference in years and, after that, making a DATEDIFF
between the product of substraction and fecha_de_inicio
; this should get the months remainder
days_employed : DATEDIFF(NOW(), fecha_de_inicio) - DATEDIFF(DATE_ADD(CONVERT(CONCAT(DATE_FORMAT((CASE WHEN DAY(NOW()) >= DAY(fecha_de_inicio) THEN NOW() ELSE DATE_ADD(NOW(), INTERVAL -1 MONTH) END), '%Y-%m-'), RIGHT('0' + DAY(fecha_de_inicio), 2)), DATE), INTERVAL -1 DAY), fecha_de_inicio)
- this value is counted substracting first 1 month from NOW()
only if DAY(NOW()) < DAY(fecha_de_inicio)
, then the new date is built using DATE_FORMAT
taking Year and Month from NOW()
prepared in the first step (conditional -1 Month step) and with Day taken from fecha_de_inicio
substracted then by 1 DAY. Having such number of days which in fact is the difference in month between NOW()
and fecha_de_inicio
but converted to days, we substract this value from the DATEDIFF(NOW(), fecha_de_inicio)
strict difference in days between the two dates. This gives us a days remainder
I hope it may occur helpful. In case of doubts, please write.