SQL日期维度,介绍如何在第二个星期二之后的第一个星期三编写

时间:2018-12-14 19:44:21

标签: sql-server tsql

在寻找创建日期维度的最佳方式之后,我终于找到了:https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/

作者作者:Aaron Bertrand(@AaronBertrand)

我能够使用他的查询来创建一个表,但是现在我的问题是,我希望能够使用该表来创建一个列,该列将容纳第二个星期二之后的第一个星期三的日期。我不知道该怎么写请帮忙!

示例:

Date        DayName     First Wednesday after Second Tuesday
1/1/2018    Monday          1/10/2018
1/2/2018    Tuesday         1/10/2018
1/3/2018    Wednesday       1/10/2018
1/4/2018    Thursday        1/10/2018
1/5/2018    Friday          1/10/2018
1/6/2018    Saturday        1/10/2018
1/7/2018    Sunday          1/10/2018
1/8/2018    Monday          1/10/2018
1/9/2018    Tuesday         1/10/2018
1/10/2018   Wednesday       1/10/2018
1/11/2018   Thursday        1/10/2018
1/12/2018   Friday          1/10/2018
1/13/2018   Saturday        1/10/2018
1/14/2018   Sunday          1/10/2018
1/15/2018   Monday          1/10/2018
1/16/2018   Tuesday         1/10/2018
1/17/2018   Wednesday       1/10/2018
1/18/2018   Thursday        1/10/2018
1/19/2018   Friday          1/10/2018
1/20/2018   Saturday        1/10/2018
1/21/2018   Sunday          1/10/2018
1/22/2018   Monday          1/10/2018
1/23/2018   Tuesday         1/10/2018
1/24/2018   Wednesday       1/10/2018
1/25/2018   Thursday        1/10/2018
1/26/2018   Friday          1/10/2018
1/27/2018   Saturday        1/10/2018
1/28/2018   Sunday          1/10/2018
1/29/2018   Monday          1/10/2018
1/30/2018   Tuesday         1/10/2018
1/31/2018   Wednesday       1/10/2018
2/1/2018    Thursday        2/14/2018
2/2/2018    Friday          2/14/2018
2/3/2018    Saturday        2/14/2018
2/4/2018    Sunday          2/14/2018
2/5/2018    Monday          2/14/2018

1 个答案:

答案 0 :(得分:0)

我将创建一个临时表来保存WeekNumber和CustomSortOrder并将其与您的日历表(Aaron Bertrand的文章中的一个)对接。您可以在查询中使用INSERT INTO作为SELECT位。必须使用“年”和“周”值才能按时间顺序排列自定义排序顺序。

DECLARE  @StartDate  DATETIME = GETDATE()
DECLARE @EndDate DATETIME = DATEADD(DAY,50,@StartDate)

DECLARE @CustomOrderTable TABLE (DayOfWeek INT, OrderInTable INT)
INSERT @CustomOrderTable VALUES (1,1),(2,2),(3,3),(4,5),(5,4),(6,6),(7,7)

;WITH DateRange AS  
(  
    SELECT  DATEADD(DAY,1,@StartDate) AS D, DayOfWeek = DATEPART(DW,@StartDate),Week = DATEPART(WEEK,@StartDate), Year =DATEPART(YEAR,@StartDate), DayName = DATENAME(WEEKDAY, @StartDate)
    UNION ALL  
    SELECT DATEADD(DAY,1, D), DayOfWeek = DATEPART(DW,D),Week = DATEPART(WEEK,D), Year =DATEPART(YEAR,D), DayName = DATENAME(WEEKDAY,D) FROM DateRange 
    WHERE D < @EndDate  
)

--INSERT INTO YourTable
SELECT 
    * 
FROM 
    DateRange DR
    INNER JOIN @CustomOrderTable CO ON CO.DayOfWeek=DR.DayOfWeek
ORDER BY
    DR.Year,
    DR.Week,
    CO.OrderInTable