LINUX.ORG.RU

legk@topaz /tmp ;) cat d.sql
DROP FUNCTION IF EXISTS month_diff;
delimiter //
CREATE FUNCTION month_diff(date_from DATE, date_to DATE) RETURNS INT DETERMINISTIC
BEGIN
  SET @m_diff = 12 * (YEAR(date_to) - YEAR(date_from)) +
                     MONTH(date_to) - MONTH(date_from);

  IF date_from < date_to THEN
    SET @d_diff = DAY(date_to) - DAY(date_from);
  ELSE
    SET @d_diff = DAY(date_from) - DAY(date_to);
  END IF;

  IF @d_diff < 0 THEN
    SET @m_diff = @m_diff - SIGN(@m_diff);
  END IF;

  RETURN @m_diff;
END;
//
delimiter ;

SELECT month_diff('2000-12-12', '2007-01-13');
SELECT month_diff('2007-01-13', '2000-12-12');
SELECT month_diff('2000-12-13', '2007-01-13');
SELECT month_diff('2007-01-13', '2000-12-13');
SELECT month_diff('2000-12-14', '2007-01-13');
SELECT month_diff('2007-01-13', '2000-12-14');

legk@topaz /tmp ;) mysql test < d.sql
month_diff('2000-12-12', '2007-01-13')
73
month_diff('2007-01-13', '2000-12-12')
-73
month_diff('2000-12-13', '2007-01-13')
73
month_diff('2007-01-13', '2000-12-13')
-73
month_diff('2000-12-14', '2007-01-13')
72
month_diff('2007-01-13', '2000-12-14')
-72

legk
()

Привести дату к формату YYYYMM и:
mysql> select period_diff('200701','200012');
+--------------------------------+
| period_diff('200701','200012') |
+--------------------------------+
|                             73 |
+--------------------------------+

Chumka ★★★
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.