如何使用sql获取上个月的第一天和最后一个月

时间:2022-10-16 12:19:48

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

我想在上个月的第一天像2013年1月1日那样,我也希望得到上个月的最后一天,比如2013年1月31日。如果我们在三月,那么我想做同样的事情,如02/01/2013和02/28/2013等等....谢谢

4 个解决方案

#1


26  

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))

#2


0  

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))

#3


0  

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)))

#4


-1  

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);

#1


26  

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))

#2


0  

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))

#3


0  

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)))

#4


-1  

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);