SQL 获取上个月(也是一月)

SQL get previous month (in January too)

您好,我正在寻找简单的方法,如何获取上个月的数据。我得到了这个代码,但它在 1 月份不起作用(结果是 12 2021,我需要 12 2020)

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

使用此处给出的答案: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;

输出: 2020-12-01 00:00:00.000

我可以使用 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

据推测,您有某种日期列。

在SQL服务器中,您可以表达这个概念使用datediff():

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

但是,这不是“可搜索的”,这意味着它会阻止使用索引。所以,我会推荐:

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

如果你只是想要上个月的第一天,你可以使用:

dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))

给你!

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

结果:

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

您也可以使用 CONVERT()FORMAT() 函数来根据需要格式化日期。

试试这个

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