SQL 如何使用sql获取上个月的第一天和最后一天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15144964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get the first day and the last of previous month using sql
提问by moe
I am trying to get the first day of last month like 01/01/2013, also i want to get the last day of previous month like 01/31/2013. If we are in March then i want to do the same thing like 02/01/2013 and 02/28/2013 and so on.... thanks
我想得到上个月的第一天,比如 01/01/2013,我也想得到上个月的最后一天,比如 01/31/2013。如果我们在三月,那么我想做同样的事情,比如 02/01/2013 和 02/28/2013 等等......谢谢
回答by Simon C
This should do it:
这应该这样做:
--First day of last month
SELECT DATEADD(m,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()), 0))
--Last day of last month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
回答by moe
here is my solution
这是我的解决方案
DECLARE @Today DATETIME
SELECT @Today = GETDATE()
update Test.dbo.DateTable
set StartDate = (
SELECT convert (varchar, DATEADD(dd,-(DAY(DATEADD(mm,1,@Today))-1),DATEADD(mm,-1,@Today)),101))
update Test.dbo.DateTable
set EndDate = (
SELECT convert(varchar, DATEADD(dd, -DAY(DATEADD(m,1,@Today)), DATEADD(m,0,@Today)),101))
回答by Pradeep atkari
First day of the last month
上个月的第一天
convert (date,DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0))
Last Day of the previous month
上个月的最后一天
convert (date,DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)))
回答by D Jaynes
The following query works to find the last day of the prior month in my older MySQL:
以下查询用于在我的旧 MySQL 中查找上个月的最后一天:
SELECT DATE_SUB(CURDATE(),INTERVAL Extract(DAY from now()) DAY);