SQL SELECT Previous MMYY as varchar(4)

后端 未结 3 584
滥情空心
滥情空心 2021-01-17 06:32

Dearest genius StackOverflow friends,

I\'m in the need of creating a view that will always give me data in the WHERE clause for \"Period\" looking for the previous M

相关标签:
3条回答
  • you can get what you want using

    TO_CHAR(add_months(sysdate,-1), 'MMYY')

    of course you can replace sysdate with timestamp, if necessary.

    0 讨论(0)
  • 2021-01-17 06:50

    Try this expression:

    SELECT STUFF(CONVERT(VARCHAR(10), DATEADD(MONTH, -1, GETDATE()), 101), 3, 6, '')
    
    0 讨论(0)
  • 2021-01-17 06:58

    Use this:

    ;WITH PrevMonth AS (
       SELECT LEFT(REPLACE(CONVERT(date, DATEADD(m, -1, getdate())), '-', ''), 6) AS YYYYMM
    )
    SELECT SUBSTRING(YYYYMM, 5, 2) + SUBSTRING(YYYYMM, 3, 2) AS MMYY 
    FROM PrevMonth  
    

    The CTE yields the date of previous month in YYYYMM format. Using SUBSTRING the format is rearranged to produce the required output.

    If you are using SQL Server 2012+ it's a lot easier to get the desired result using FORMAT:

    SELECT FORMAT(DATEADD(m, -1, getdate()), 'MMyy') AS MMYY
    
    0 讨论(0)
提交回复
热议问题