在给定的日期范围中,我想获得月份的名称和月份的结束日期。根据给定的值,我将计算不同的计数并计算最终值。
我可以用CTE做到这一点,但我不知道如何完全使用CTE。
我更喜欢使用CTE的方式。
SQL 2008 R2版,2012。
我希望结果为我提供的完整日期范围。不是一个月
示例:我提供的输入是日期范围
Declare @Start datetime
Declare @End datetime
Select @Start = '2014-08-08'
Select @End = '2015-04-01'
需要输出:
Month End Date
August 2014-08-31 00:00:00.000
September 2014-09-30 00:00:00.000
October 2014-10-31 00:00:00.000
November 2014-11-30 00:00:00.000
December 2014-12-31 00:00:00.000
January 2015-01-31 00:00:00.000
February 2015-02-28 00:00:00.000
March 2015-03-31 00:00:00.000
答案 0 :(得分:2)
适用于SQL SERVER 2008 +
Declare @Start datetime Declare @End datetime
Select @Start = '2014-08-08' Select @End = '2015-04-01'
declare @day DATETIME = @Start
declare @tab TABLE(MONTH_NAME varchar(20),LAST_DAY_OF_MONTH DATETIME)
while @day <= @end
begin
INSERT INTO
@tab
SELECT
DATENAME(month, @day),
DATEADD(SECOND,-1,DATEADD(MONTH,1+ DATEDIFF(MONTH, 0, @day), 0))
set @day = DATEADD(MONTH,1,@day)
end
SELECT
*
FROM
@tab
答案 1 :(得分:1)
2012年或2012年 -
DECLARE @Start DATETIME = '2014-08-08',
@End DATETIME = '2015-04-01'
SELECT DATENAME(MONTH, DATEADD(MONTH, a.number, @Start)) AS NameOfMonth
,EOMONTH(DATEADD(MONTH, a.number, @Start)) AS EndOfMonthForSQL2012Plus
,DATEADD(DAY, -1, DATEADD(MONTH, 1 + DATEDIFF(MONTH, 0, DATEADD(MONTH, a.number, @Start)), 0)) AS EndOfMonthForSQL2012Minus
FROM master.dbo.spt_values a
WHERE a.type = 'P'
AND a.number <= DATEDIFF(MONTH, @Start, @End);
答案 2 :(得分:1)
答案 3 :(得分:0)
&#39>之前使用以下内容。它需要一个开始日期,但您需要自己的结束日期;
DECLARE @SeedDate DATETIME = '1 February 2015'
;WITH CalData AS (
SELECT DATENAME(MONTH, @SeedDate) AS Name,
@SeedDate As StartDate,
DATEADD(MONTH, ((YEAR(@SeedDate) - 1900) * 12) + MONTH(@SeedDate), -1) AS EndDate
UNION ALL
SELECT DATENAME(MONTH, DATEADD(MONTH, 1, StartDate)),
DATEADD(MONTH, 1, StartDate),
DATEADD(MONTH, ((YEAR(StartDate) - 1900) * 12) + (MONTH(StartDate) + 1), -1)
FROM CalData
) SELECT TOP 200 * FROM CalData
OPTION (MAXRECURSION 5000);