[英]SQL Server query to get previous month name in string from another month in string
I need to get previous month name from given month name. 我需要从给定的月份名称中获取上一个月份的名称。
For example I need to get previous month as May for the given month June. 例如,对于给定的六月,我需要将上个月作为五月。 There is no date.
没有日期。
I tried select CAST(Monthname-1 AS Varchar(max)) from table
我尝试
select CAST(Monthname-1 AS Varchar(max)) from table
Because "There is no date." 因为“没有日期。”
You can convert an augmented string {month name} + ' 01, 1980'
to a date, and then perform the date calculation 您可以将扩展字符串
{month name} + ' 01, 1980'
转换为日期,然后执行日期计算
Example 例
Select datename(MONTH,dateadd(MONTH,-1,convert(date,'June'+' 01,1980')))
If 2012+ and potentially bogus data ... try_convert()
如果2012年以上且可能存在伪造数据...
try_convert()
Select datename(MONTH,dateadd(MONTH,-1,try_convert(date,'June'+' 01,1980')))
Returns 返回
May
在开始日期前加上-1个月,然后使用DATENAME(month)
来获取名称。
DATENAME(month, DATEADD(month, -1, <yourDateField>))
您可以尝试以下方法:
SELECT DATENAME(MM,CAST('1 June 2018' AS datetime)-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.