简体   繁体   中英

sql get previous month

我需要在输入时获取前一个月和一年。所以如果用户输入 201412 那么它应该返回 201411。如果他们输入 201501 那么它应该返回 201401。

A quick way to do this on a SQL Server database would be to create a date element out of your string, convert it to a date type, then use the function dateadd and add -1 month (subtract one month if you like)

Like this:

select DATEADD(MONTH,-1,CAST(LEFT(201401,4)+'-'+RIGHT(201401,2)+'-01' AS DATE))

The steps broken down:

  1. Get the year by selecting the 4 leftmost characters
  2. Get the month by selecting the 2 rightmost characters
  3. Add the separators '-' and 01 with the previous two elements to get a string with a valid format to be converted
  4. Convert the string to a datetype to enable date operations
  5. Use the dateadd function to add -1 month to the date element
  6. Fingers crossed for usable input that wont break your code

In SQL Server

 DECLARE @dateAsNumber VARCHAR(8);
SET @dateAsNumber = '198705';

DECLARE @DateConvertedFromNumber DATETIME; 
SELECT  @DateConvertedFromNumber = CONVERT (DATETIME, CONVERT(CHAR(8), @dateAsNumber
        + '01'))

SELECT  LEFT(CONVERT(VARCHAR,   DATEADD(YEAR, -1,
                                              @DateConvertedFromNumber), 112),
             6) AS 'Year Before'

SELECT  LEFT(CONVERT(VARCHAR,   DATEADD(MONTH, -1,
                                              @DateConvertedFromNumber), 112),
             6) AS 'Month Before'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM