【发布时间】:2018-08-28 03:16:44
【问题描述】:
我正在尝试在 mssql 中创建一个 13 个周期的日历,但我有点卡住了。我不确定我的方法是否是实现这一目标的最佳方法。我有我的基本脚本,如下所示:
Set DateFirst 1
Declare @Date1 date = '20180101' --startdate should always be start of
financial year
Declare @Date2 date = '20181231' --enddate should always be start of
financial year
SELECT * INTO #CalendarTable
FROM dbo.CalendarTable(@Date1,@Date2,0,0,0)c
DECLARE @StartDate datetime,@EndDate datetime
SELECT @StartDate=MIN(CASE WHEN [Day]='Monday' THEN [Date] ELSE NULL END),
@EndDate=MAX([Date])
FROM #CalendarTable
;With Period_CTE(PeriodNo,Start,[End])
AS
(SELECT 1,@StartDate,DATEADD(wk,4,@StartDate) -1
UNION ALL
SELECT PeriodNo+1,DATEADD(wk,4,Start),DATEADD(wk,4,[End])
FROM Period_CTE
WHERE DATEADD(wk,4,[End])< =@EndDate
OR PeriodNo+1 <=13
)
select * from Period_CTE
这给了我这个:
PeriodNo Start End
1 2018-01-01 00:00:00.000 2018-01-28 00:00:00.000
2 2018-01-29 00:00:00.000 2018-02-25 00:00:00.000
3 2018-02-26 00:00:00.000 2018-03-25 00:00:00.000
4 2018-03-26 00:00:00.000 2018-04-22 00:00:00.000
5 2018-04-23 00:00:00.000 2018-05-20 00:00:00.000
6 2018-05-21 00:00:00.000 2018-06-17 00:00:00.000
7 2018-06-18 00:00:00.000 2018-07-15 00:00:00.000
8 2018-07-16 00:00:00.000 2018-08-12 00:00:00.000
9 2018-08-13 00:00:00.000 2018-09-09 00:00:00.000
10 2018-09-10 00:00:00.000 2018-10-07 00:00:00.000
11 2018-10-08 00:00:00.000 2018-11-04 00:00:00.000
12 2018-11-05 00:00:00.000 2018-12-02 00:00:00.000
13 2018-12-03 00:00:00.000 2018-12-30 00:00:00.000
即使我必须采取不同的方法我也不介意,只要结果与上述相同。
dbo.CalendarTable() 是一个返回以下结果的函数。如果需要,我可以分享代码。
【问题讨论】:
-
你走错了方向。从您的 DayOfWeek 列开始,然后使用函数/子选择来获取其他列。
-
我没有收到星期一的部分? dbo.CalendarTable 来自哪里?
-
我更新了帖子。 dbo.CalendarTable 是一个函数。
标签: sql-server date tsql datetime calendar