这是我用来创建日历的语法。我遇到的问题是,由于Week1的开始日期是2012年,因此startdate显示为null。有没有办法让startdate(或其他实例中的enddate)填充,即使它在不同的年份? @变革之风 - - 这会添加一个开始日期和结束日期,之前它是null。但我所追求的是,例如,我需要我的日期范围来运行星期六 - 星期三。所以让我们在2013年的第53周。日期范围应该是12/28/2013 - 01/01/14。有没有办法修改压延机以这种格式显示?
CREATE TABLE dbo.Calendar (
CalendarYear INT NOT NULL,
CalendarWeek INT NOT NULL,
WeekStartDate VARCHAR(50),
WeekEndDate VARCHAR(50),
CONSTRAINT PK_Calendar PRIMARY KEY (
CalendarYear,
CalendarWeek
)
)
SET DATEFIRST 6
DECLARE @StartDate DATETIME,
@NumOfDays INT
SET @StartDate = '20130101'
SET @NumOfDays = 1000;
WITH calendar
AS (
SELECT TOP (@NumOfDays) dateadd(day, row_number() OVER (
ORDER BY sc1.column_id
) - 1, @StartDate) AS CalendarDate
FROM sys.columns sc1
CROSS JOIN sys.columns sc2
)
INSERT INTO dbo.Calendar (
CalendarYear,
CalendarWeek,
WeekStartDate,
WeekEndDate
)
SELECT DATEPART(year, c.CalendarDate) AS Year,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) AS Week, --DATEPART(week, c.CalendarDate) AS Week,
MAX(CASE DATEPART(WEEKDAY, c.CalendarDate)
WHEN 1
THEN convert(VARCHAR(50), c.CalendarDate, 101)
ELSE NULL
END) AS StartDate,
MAX(CASE DATEPART(WEEKDAY, c.CalendarDate)
WHEN 7
THEN convert(VARCHAR(50), c.CalendarDate, 101)
ELSE NULL
END) AS EndDate
FROM calendar c
GROUP BY DATEPART(year, c.CalendarDate),
DATEPART(Week, c.CalendarDate)
ORDER BY Year,
startdate,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) --Week
SELECT *
FROM dbo.Calendar
答案 0 :(得分:1)
所以你的问题是你按周和年分组,但是在年初或年末,年份在不同的一周开始/结束。因此,如果第一周从星期三开始,那一年只有3天的星期。
我有一个小小的修补程序,我已经让它工作,以便通过改变一切来显示一年中的第一天/最后一天作为一周的开始/结束日期。这是我的修改版本:
SELECT
DATEPART(year, c.CalendarDate) AS Year,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) AS Week, --DATEPART(week, c.CalendarDate) AS Week,
convert(VARCHAR(50), MIN(c.CalendarDate), 101) AS StartDate,
convert(VARCHAR(50), MAX(c.CalendarDate), 101) AS EndDate
FROM
calendar c
GROUP BY
DATEPART(year, c.CalendarDate),
DATEPART(Week, c.CalendarDate)
ORDER BY
Year,
startdate,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) --Week
希望这有帮助。
编辑:在回复您的评论/编辑时,请查看这些更新语句。插入后放入它们。
EDIT2:请勿使用上述插件以及更新。
update dbo.Calendar set WeekStartDate = convert(VARCHAR(50), dateadd(day, 1, dateadd(week, -1, cast(WeekEndDate as datetime))), 101)
where WeekStartdate is null
update dbo.Calendar set WeekEndDate = convert(VARCHAR(50), dateadd(day, -1, dateadd(week, 1, WeekStartDate)), 101)
where WeekEndDate is null