简体   繁体   English

SQL Server查询以从另一个字符串月份中获取字符串中的上个月名称

[英]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.

相关问题 在 sql 查询中获取上个月的数据 - Get the data from previous month in sql query SQL 如果下个月的列值不存在,则服务器查询以获取上个月的数据 - SQL Server query to get the data from previous month if the column value is not present in next month 从 SQL Server 中的字符串中提取月份名称和年份并以它们为中心 - Extract Month Name and Year from string in SQL server and pivot on them 查询以获取本月和上个月的销售额 - Query to get sales from this month and previous month SQL 服务器查询以获取一年中每个月的总计,并以日期格式而不是字符串格式返回年月 - SQL Server query to get total against each month of a year and return the year and month in date format not the string format 如何在SQL Server中获取月份(字符串)差异 - How to get month (in string) diff in sql server 如何在sql server中将此年份和月份与此字符串分开? - How to get year and month separately from this string in sql server? 如何从sql中的字符串中获取月份? - How to get the month from a string in sql? SQL查询Informix以获取上个月的所有记录 - SQL query for Informix to get all the records from previous month 如何从SQL Server中获取上个月的数据 - How to get data from the previous month result in SQL Server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM