【问题标题】:How to get latest date from previous month in MS SQL如何在 MS SQL 中获取上个月的最新日期
【发布时间】:2021-03-29 10:41:00
【问题描述】:

我正在尝试获取上个月的最新日期以及运行此查询时:

select max(me_date) from table1 having month(me_date) = Month(max(me_date)) - 1

这给了我当前月份的最新日期,而不是之前的日期。有什么想法吗?

【问题讨论】:

  • 我根据标题添加了“sql-server”标签。但是,该代码应该会在 SQL Server 中生成语法错误。

标签: sql sql-server


【解决方案1】:

由于在having 子句中使用了非聚合函数,您的代码在几乎任何数据库中都会失败。

一般来说,如果你想过滤数据,你应该在聚合之前这样做。在 SQL Server 中,我建议:

select max(me_date)
from table1
where me_date < dateadd(day, (1 - day(getdate())), convert(date, getdate())) and
      me_date >= dateadd(month, -1, dateadd(day, (1 - day(getdate())), convert(date, getdate())));

以上是索引和优化器友好的。如果你不关心这个,那么一个更简单的公式是:

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

【讨论】:

    【解决方案2】:

    SELECT EOMONTH(GETDATE()-1) AS '上个月';

    Click here 了解更多信息。

    【讨论】:

      【解决方案3】:

      如果没有 group by 子句,我们不能使用 have,因此会出现错误。

      我测试了以下查询;它在 MySQL 中运行良好

      Select distinct me_date from where month(me_date) not in (select max(month(me_date)) from ) order by me_date describe limit 1;

      month() 函数的替代方法是 datepart(month, me_date) 或者, 提取(从 me_date 开始的月份) 或者, strftime('%m', me_date)

      问候!

      【讨论】:

        【解决方案4】:

        如果您想从 table1 的 max(me_date) 的上个月获取 max(me_date),请尝试以下操作:

            select max(me_date)
            from table1
            where datediff(month, me_date, (select max(me_date) from table1)) = 1;
        

        【讨论】:

        • 为什么你复制了答案。 Gordon linoff 发布了相同的答案
        • 感谢@B.Muthamizhselvi。在回答时它不在那里。但是我已经删除了重复的答案,因为 Linoff 的答案要好得多。
        猜你喜欢
        • 2017-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        相关资源
        最近更新 更多