簡體   English   中英

如何在 MS SQL 中獲取上個月的最新日期

[英]How to get latest date from previous month in MS SQL

我正在嘗試獲取上個月的最新日期以及運行此查詢時:

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

這給了我當月的最新日期而不是之前的日期。 有任何想法嗎?

由於在having子句中使用了非聚合函數,您的代碼幾乎在任何數據庫中都會失敗。

一般來說,如果你想過濾數據,你應該在聚合之前這樣做。 在 SQL 服務器中,我建議:

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

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

點擊這里了解更多信息。

我們不能使用沒有 group by 子句的 have,因此會出現錯誤。

我測試了以下查詢; 它在 MySQL 中運行良好

Select distinct me_date from <table_name> where month(me_date) not in (select max(month(me_date)) from <table_name> ) 按 me_date 排序,描述限制 1;

month() function 的替代方案是 datepart(month, me_date) 或 Extract (month from me_date) 或 Strftime('%m', me_date)

問候!

如果您想從 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM