使用月份的日期差异

时间:2013-03-18 09:18:06

标签: mysql datediff

我的数据库中有月份名称,例如。 tomonthfrommonth。存储的数据类似于'JAN','FEB'等。

我需要做些什么来区分tomonthfrommonth

2 个答案:

答案 0 :(得分:0)

尝试以下查询

select (tomonth-frommonth) as monthdiff from
( SELECT case when `frommonth` = 'Jan' then 1 
   when frommonth = 'Feb' then 2  
   when frommonth = 'Mar' then 3 
   when frommonth = 'Apr' then 4  
   when frommonth = 'May' then 5  
   when frommonth = 'Jun' then 6  
   when frommonth = 'Jul' then 7  
   when frommonth = 'Aug' then 8  
   when frommonth = 'Sep' then 9  
   when frommonth = 'Oct' then 10  
   when frommonth = 'Nov' then 11  
   when frommonth = 'Dec' then 12 
   end frommonth, 
( case when tomonth = 'Jan' then 1
   when tomonth = 'Feb' then 2  
   when tomonth = 'Mar' then 3 
   when tomonth = 'Apr' then 4  
   when tomonth = 'May' then 5  
   when tomonth = 'Jun' then 6  
   when tomonth = 'Jul' then 7  
   when tomonth = 'Aug' then 8  
   when tomonth = 'Sep' then 9  
   when tomonth = 'Oct' then 10  
   when tomonth = 'Nov' then 11  
   when tomonth = 'Dec' then 12 
   end ) as tomonth from table) a

答案 1 :(得分:0)

您可以使用STR_TO_DATE:

SELECT
  MONTH(STR_TO_DATE(tomonth,'%b'))-MONTH(STR_TO_DATE(frommonth,'%b')) as montdiff
FROM
  yourtable