【问题标题】:SQL get previous month (in January too)SQL 获取上个月(1 月也是)
【发布时间】:2021-01-09 12:21:35
【问题描述】:

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

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

【问题讨论】:

  • 您需要某种日期列。过滤发生在WHERE 子句中,而不是SELECT 子句中。

标签: sql sql-server date getdate


【解决方案1】:

大概,你有某种日期列。

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

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

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

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))

【讨论】:

    【解决方案2】:

    试试这个

    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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          给你!

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

          结果:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-03
            • 2021-05-31
            • 1970-01-01
            • 2020-07-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多