With the change of strategy, I made the SQL edition to calculate so:
If the months are different it makes two calculation of the month of entry and the month of exit.
If the months have differences of more months type month 05 until month 07 you could then take the middle and make a calculation in PHP code to find out type month 6 has 30 days equal is in SQL 1, 3, 5, 7, 8, 10, 12 has 31 days, month 2 depending on the year may have 28 or 29 days (take the ano % 2 == 0
if true, the expression has 29 days if not 28 days), and the other months have 30 days.
If the month reported belongs to the entry take the field DIFERENCA_MENTRADA
if the month given belongs to the month of departure take DIFERENCA_MSAIDA
.
SELECT IF(mentrada <> msaida,
(
CASE mentrada
WHEN (1 OR 3 OR 5 OR 7 OR 8 OR 10 OR 12) THEN
DATEDIFF(date_format(concat(yentrada,'-', mentrada,'-', 31), '%Y-%m-%d'), data_entrada)
WHEN (2) THEN
DATEDIFF(date_format(concat(yentrada,'-', mentrada,'-', IF(yentrada % 4 = 0,29,28)), '%Y-%m-%d'), data_entrada)
ELSE
DATEDIFF(date_format(concat(yentrada,'-', mentrada,'-', 30), '%Y-%m-%d'), data_entrada)
END
), DATEDIFF(data_saida, data_entrada)) as diferenca_mentrada,
IF (mentrada <> msaida,
DATEDIFF(data_saida, date_add(date_format(concat(ysaida,'-', msaida,'-1'), '%Y-%m-%d'), INTERVAL -1 DAY)),0) as diferenca_msaida,
id_funcionario,
data_entrada,
data_saida,
mentrada,yentrada,
msaida,ysaida
FROM (
SELECT
id_funcionario,
data_entrada,
data_saida,
month(data_entrada) mentrada,
year(data_entrada) yentrada,
month(data_saida) msaida,
year(data_saida) ysaida
FROM historico
) as historico WHERE (mentrada = 6 or msaida = 6) and yentrada = 2014 AND id_funcionario = 1
Online Example: Sqlfiddle
Month 5: Then take the difference
Month 6: Then take the difference
See if this issue, can help
– Papa Charlie
No :/, the problem is that I may have dates that the entry is in the month x, and the exit is in the month x+1. For example, Input 25/05/2014 and Output 03/06/2014, and precise days of the month 05 for example, the same problem is when it is different month, because if they were with equal month would serve perfectly.
– João Neto
From 25/05/2014 to 31/05/2014 are not 6 days difference?
– gmsantos