如何在SQL中计算一个月的最后一天?

问题描述:

具体来说,MSSQL 2005。

Specifically MSSQL 2005.

这是一个解决方案,让您成为当月的最后一秒。您可以提取日期部分或修改它以返回只是一天。我在SQL Server 2005上测试了这个。

Here's a solution that gives you the last second of the current month. You can extract the date part or modify it to return just the day. I tested this on SQL Server 2005.

select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );

要了解它的工作原理,我们必须看看 dateadd() datediff()功能。

To understand how it works we have to look at the dateadd() and datediff() functions.

DATEADD(datepart, number, date)  
DATEDIFF(datepart, startdate, enddate)

如果你只运行最内部的对于datediff()的调用,你会得到从时间戳记0起的当前月份号。

If you run just the most inner call to datediff(), you get the current month number since timestamp 0.

select datediff(m, 0, getdate() );  
1327

下一部分将0个时间戳加上1个月,给出你是下一个日历月的起点。

The next part adds that number of months plus 1 to the 0 timestamp, giving you the starting point of the next calendar month.

select dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 );
2010-09-01 00:00:00.000

最后,外部的dateadd()只需从下个月的开始时间戳中减去一秒钟,即可获得当前月份的最后一秒。

Finally, the outer dateadd() just subtracts one second from the beginning timestamp of next month, giving you the last second of the current month.

select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
2010-08-31 23:59:59.000



这个旧答案(以下)有一个错误,它在一个月的最后一天不工作,比下个月多了几天。我将其留在这里作为警告给他人。

添加一个月到当前日期,然后减去应用的DAY函数返回的值使用函数DAY和DATEADD到当前日期。

Add one month to the current date, and then subtract the value returned by the DAY function applied to the current date using the functions DAY and DATEADD.

dateadd(day, -day(getdate()), dateadd(month, 1, getdate()))