[英]How to subtract to previous year, but add months in MySQL?
I am new to procedural programming and mysql, but suppose I have a function PrevMonth(in_date date, in_mn_count int)
The first is a date and the second is an integer which is expected to be the number of months. 我是过程编程和mysql的新手,但假设我有一个函数
PrevMonth(in_date date, in_mn_count int)
,第一个是日期,第二个是整数,预期是月数。 The function returns a string with the format 'YYYY-MM'
which is the year and month, where the year in the first parameter is the previous year, and in_mn_count is added to in_date. 该函数返回格式为
'YYYY-MM'
的字符串,该字符串是年份和月份,其中第一个参数中的年份是上一年,并且in_date中添加了in_mn_count。
For example, a_testbed.PrevMonth('2012-05-19', 6)
returns '2011-11'
例如,
a_testbed.PrevMonth('2012-05-19', 6)
返回'2011-11'
This is what I have: 这就是我所拥有的:
set return_date := Date_format(DATE_ADD(in_date, INTERVAL -1 YEAR),
DATE_ADD(in_date, INTERVAL in_mn_count MONTH),'%Y %M');
You have several issues here, your format for DATE_FORMAT is wrong, and you are passing the date through DATE_ADD twice for some odd reason. 您这里有几个问题,您的DATE_FORMAT格式错误,并且出于某种奇怪的原因,您两次将日期通过DATE_ADD。
DATE_FORMAT(DATE_ADD(in_date, INTERVAL (in_mn_count-12) MONTH), '%Y-%m')
That would do the trick, because 12 months is 1 year. 那会成功的,因为12个月就是1年。
Note the small 'm' in '%Y-%m', that is actually what you want if you desire '2011-05' type of return value. 请注意,'%Y-%m'中的小'm'实际上是如果您希望返回类型为'2011-05'的返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.