计算SQL Server中给定时间段的最后几天

时间:2013-12-24 09:01:52

标签: sql sql-server-2008

是否可以在SQL中执行:例如,我有句点where @s_date = '20130101' and @e_date = '20130601',我想在此期间选择所有月份的所有最后几天。

这是结果的例子:

20130131
20130228
20130331
20130430
20130531

感谢。

5 个答案:

答案 0 :(得分:1)

最简单的选择是拥有calendar table,其中包含月份的最后一天标记,因此您的查询只会是:

SELECT  *
FROM    dbo.Calendar
WHERE   Date >= @StartDate
AND     Date <= @EndDate
AND     EndOfMonth = 1;

当然假设您没有日历表,您可以动态生成日期列表:'

DECLARE @s_date DATE = '20130101',
        @e_date DATE = '20130601';

SELECT  Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY Object_ID) - 1, @s_date)
FROM    sys.all_objects;

然后,一旦你有了你的日期,你就可以将它们限制在这个月的最后一天(加上一天使它成为本月的第一天)的地方:

DECLARE @s_date DATE = '20130101',
        @e_date DATE = '20130601';

WITH Dates AS
(   SELECT  Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY Object_ID) - 1, @s_date)
    FROM    sys.all_objects
)
SELECT  *
FROM    Dates
WHERE   Date <= @e_Date
AND     DATEPART(DAY, DATEADD(DAY, 1, Date)) = 1;

<强> Example on SQL Fiddle

答案 1 :(得分:0)

您可以运行以下查询,然后使用表格详细信息进行调整:

declare @s_date as datetime= '20130101'
declare @e_date as datetime= '20131020'


SELECT DateAdd(m, number, '1990-01-31')
FROM master.dbo.spt_values
WHERE  'P' = type
AND DateAdd(m, number, @s_date) < @e_date

答案 2 :(得分:0)

20130101的示例:

select  CONVERT(VARCHAR(8), 
            dateadd(day, -1, dateadd(month, 1, 
                  convert(datetime, '20130101',112))), 112)

结果:

20130131

答案 3 :(得分:0)

尝试此查询

WITH sample 
     AS (SELECT Cast('2013-04-01' AS DATETIME) Date 
         UNION ALL 
         SELECT Dateadd(day, 1, date) dt 
         FROM   sample 
         WHERE  date < Cast('2013-05-05' AS DATETIME)) 
SELECT * 
FROM   sample 

Fiddle

答案 4 :(得分:0)

EOMONTH(@date)是您需要的功能。 这是帮助页面https://docs.microsoft.com/en-us/sql/t-sql/functions/eomonth-transact-sql?view=sql-server-2017

此查询获得las 50 End Of Months。 用作示例的原始查询来自此处。

https://dba.stackexchange.com/a/186829

WITH cte AS
(
  SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) - 1 AS [Incrementor]
  FROM   [master].[sys].[columns] sc1
  CROSS JOIN [master].[sys].[columns] sc2
)
SELECT top 50 EOMONTH(DATEADD(Month, -1 * cte.[Incrementor], GETDATE()))
FROM   cte
WHERE  EOMONTH(DATEADD(Month, -1 * cte.[Incrementor], GETDATE())) < GETDATE();