查询一个月的第一天和最后一天

时间:2013-04-01 11:29:10

标签: sql sql-server

如果我有月份的名称,我怎样才能在SQL中拥有该月的第一天和最后一天?

我有这个查询来返回月份名称:

DECLARE @StartDate  DATETIME,
        @EndDate    DATETIME;

SELECT   @StartDate = '20110501'        
        ,@EndDate   = '20110801';


SELECT  DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS MonthName
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'        
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate)

结果:

results

现在,我怎样才能获得那个月的第一天和最后一天?更改查询。

5 个答案:

答案 0 :(得分:5)

如果您想要更通用,更简单的解决方案:

DECLARE @startdate AS DATETIME = GETDATE()
SELECT      
DATEADD(MONTH, DATEDIFF(MONTH, 0, @startdate) , 0)   as startMonth,
DATEADD(SECOND, -1, DATEADD(MONTH, 1,  DATEADD(MONTH, DATEDIFF(MONTH, 0, @startdate) , 0) ) ) as endMonth

给出结果:

startMonth              endMonth
----------------------- -----------------------
2013-06-01 00:00:00.000 2013-06-30 23:59:59.000

答案 1 :(得分:3)

试试这个: -

DECLARE @StartDate  DATETIME,
        @EndDate    DATETIME;

SELECT   @StartDate = '20110501'        
        ,@EndDate   = '20110801';


SELECT  DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS MonthName,
CONVERT(VARCHAR(25),
DATEADD(dd,-(DAY(DATEADD(MONTH, x.number, @StartDate))-1),DATEADD(MONTH, x.number, @StartDate)),101) as FirstDay,
CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,DATEADD(MONTH, x.number, @StartDate)))),DATEADD(mm,1,DATEADD(MONTH, x.number, @StartDate))),101) as LastDay
FROM    master..spt_values x
WHERE   x.type = 'P'        
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate)

结果: -

 MonthName       FirstDay         LastDay   
  May           05/01/2011        05/31/2011    
 June           06/01/2011        06/30/2011    
 July           07/01/2011        07/31/2011    
 August         08/01/2011        08/31/2011    

获得this查询

的帮助后获得的结果

答案 2 :(得分:1)

此代码为您提供当月的第一个日期:

DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)

如果你知道月份的数字,那么:

SELECT      DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + @MonthNumber, 0)

同样适用于月结束日期

SELECT   DATEADD(MILLISECOND, -1,
         DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - @@MonthNumber+ 1, 0))

答案 3 :(得分:1)

根据您使用的SQL Server版本,您也可以使用EOMONTH()...我写了一个指南,在这里分解了各种SQL的选项:How to Find the Last Day of the Month in SQL, MySQL, PostgreSQL, and Teradata

答案 4 :(得分:0)

这是一篇关于在 SQLServer 中使用 EOMonth 函数的非常好的文章,它有很多很好的例子,并且以易于阅读的格式进行布局。

https://www.tutorialsrack.com/articles/60/how-to-get-first-and-last-day-of-a-month-in-sql-server-using-eomonth-function