1

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())
a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843
sql-rookie
  • 13
  • 2

5 Answers5

1

Presumably, you have some sort of date column.

In SQL Server, you can express this concept using datediff():

where datediff(month, datecol, getdate()) = 1

However, that is not "sargable", meaning that it prevents the use of indexes. So, I would instead recommend:

where datecol < datefromparts(year(getdate()), month(getdate()), 1) and
      datecol >= dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))

If you simply want the first day of the previous month, you can use:

dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))
Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709
0

Using the answer given here: How can I select the first day of a month in SQL?

SELECT dateadd(month,-1,DATEADD(month, DATEDIFF(month, 0, getdate()), 0)) as previousmonth;

output: 2020-12-01 00:00:00.000

Slava Rozhnev
  • 8,085
  • 6
  • 21
  • 35
Luuk
  • 9,042
  • 4
  • 20
  • 28
0

I can provide next query using FORMAT function:

SELECT 
    -- get current day in previous month
    FORMAT(dateadd(month, -1, getdate()), 'yyyy-MM-dd') as current_previousmonth,
    -- get first of previous month
    FORMAT(dateadd(month, -1, getdate()), 'yyyy-MM-01') as first_previousmonth,
    -- previous month without date
    FORMAT(dateadd(month, -1, getdate()), 'yyyy-MM') as previousmonth;

test T-SQL here

Slava Rozhnev
  • 8,085
  • 6
  • 21
  • 35
0

Here you go!

select dateadd(mm,-1,eomonth(getdate())) as [Previous Month]

Result:

Previous Month
--------------
2020-12-31

You could also use CONVERT() or FORMAT() functions to format the date as you desire.

0

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