[英]How to get latest date from previous month in MS SQL
I am trying to get the latest date from previous month and when I run this query:我正在尝试获取上个月的最新日期以及运行此查询时:
select max(me_date) from table1 having month(me_date) = Month(max(me_date)) - 1
This gives me the latest date for the current month instead of previous.这给了我当月的最新日期而不是之前的日期。 Any ideas?
有任何想法吗?
Your code would fail in almost any database, because of the use of non-aggregated functions in the having
clause.由于在
having
子句中使用了非聚合函数,您的代码几乎在任何数据库中都会失败。
In general, if you want to filter data, you should do so before aggregation.一般来说,如果你想过滤数据,你应该在聚合之前这样做。 In SQL Server, I would suggest:
在 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())));
The above is index and optimizer friendly.以上是索引和优化器友好的。 If you don't care about that, then a simpler formulation is:
如果您不关心这一点,那么一个更简单的公式是:
where datediff(month, me_date, getdate()) = 1
SELECT EOMONTH(GETDATE()-1) AS 'Last Month'; SELECT EOMONTH(GETDATE()-1) AS '上个月';
Click here for more info. 点击这里了解更多信息。
We can't use having without group by clause, hence the error.我们不能使用没有 group by 子句的 have,因此会出现错误。
I tested The following query;我测试了以下查询; it works fine in MySQL
它在 MySQL 中运行良好
Select distinct me_date from <table_name> where month(me_date) not in (select max(month(me_date)) from <table_name> ) order by me_date describe limit 1; Select distinct me_date from <table_name> where month(me_date) not in (select max(month(me_date)) from <table_name> ) 按 me_date 排序,描述限制 1;
Alternatives of month() function would be datepart(month, me_date) Or, Extract (month from me_date) Or, Strftime('%m', me_date) month() function 的替代方案是 datepart(month, me_date) 或 Extract (month from me_date) 或 Strftime('%m', me_date)
Regards!问候!
If you want to get the max(me_date) from previous month of max(me_date) of table1 then try this:如果您想从 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.