How to get first and last day of previous month (with timestamp) in SQL Server(如何在 SQL Server 中获取上个月的第一天和最后一天(带时间戳))
问题描述
我找不到给出上个月第一天和最后一天带时间戳的解决方案.希望这对其他人有帮助.如果已经有针对此问题的解决方案,我深表歉意.
I could not find the solution which gives first and last day of previous month with timestamp. Hope this helps others. If there is already a solution for this problem I apologize.
这是解决方案.
SELECT DATEADD(month, DATEDIFF(month, -1, getdate()) - 2, 0) as FirtDayPreviousMonthWithTimeStamp,
DATEADD(ss, -1, DATEADD(month, DATEDIFF(month, 0, getdate()), 0)) as LastDayPreviousMonthWithTimeStamp
如果 currentdate = '2012-7-31'
结果:2012-06-01 00:00:00.000 2012-06-30 23:59:59.000
如果 currentdate = '2012-1-1'
结果:2011-12-01 00:00:00.000 2011-12-31 23:59:59.000
推荐答案
select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) --First day of previous month
select DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) --Last Day of previous month
这篇关于如何在 SQL Server 中获取上个月的第一天和最后一天(带时间戳)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 SQL Server 中获取上个月的第一天和最后一天(带时间戳)


基础教程推荐
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01