Skip to content
Advertisement

How do I combine dateadd and convert?

I have a query that shows the month (converted from date of day):

DECLARE @Month varchar(6) = '202101'

SELECT
    [Month] = CONVERT(varchar(4), YEAR(Date)) + RIGHT('00' + CONVERT(varchar(2), MONTH(Date)), 2),
    Conversion_Rate, 
    ID
FROM 
    X
WHERE 
    CONVERT(varchar(4), YEAR(Date)) + RIGHT('00' + CONVERT(varchar(2), MONTH(Date)), 2) = @Month

Now I want it to show the previous month as well, counting 1 backwards from the declared month using DATEADD. How can I do this?

I’m using SQL Server Management Studio.

Thanks in advance

Advertisement

Answer

dateadd(month,-1,date) will do the trick. month is indicating that you want to add months to the date and adding -1 will give you the previous month:

DECLARE @Month varchar(6) = '202101'

SELECT
    [Month] = CONVERT(varchar(4), YEAR(Date)) + RIGHT('00' + CONVERT(varchar(2), MONTH(Date)), 2),
    [PreviousMonth] = CONVERT(varchar(4), YEAR(dateadd(month,-1,'Date'))) + RIGHT('00' + CONVERT(varchar(2), MONTH(dateadd(month,-1,'Date'))), 2),
    Conversion_Rate, 
    ID
FROM 
    X
WHERE 
    CONVERT(varchar(4), YEAR(Date)) + RIGHT('00' + CONVERT(varchar(2), MONTH(Date)), 2) = @Month
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement