sqlsql-serverdategetdate

SQL get previous month (in January too)


Hello I'm looking for simple way, how to get data from previous month. I get this code but it didn't work in January (result is 12 2021 and I need 12 2020)

select month(dateadd(month,-1,getdate())), year(getdate())

Solution

  • Try This

    select CASE WHEN month(getdate())>1 THEN  month(getdate())-1   ELSE 12   END ,
    

    CASE WHEN month(getdate())>1 THEN YEAR (getdate()) ELSE YEAR (getdate()) -1 END