星期五星期开始的周数

时间:2013-07-08 16:36:04

标签: sql sql-server

我正在尝试编写SQL来填充客户日历表,其中客户的营业周是星期五到星期四。我需要填写几个客户,每个客户都定义了不同的业务周。我正在尝试填充以下字段:

WeekBeginDate
WeekEndDate
WeekNo
WeekYear

这是结果集的一个示例:

Date      WeekBeginDate  WeekEndDate    DayofWeek   WeekNo   WeekYear
01/03/13  12/28/12       01/03/2013     Thursday    52       2012
01/04/13  01/04/13       01/10/2013     Friday  1    2013

2 个答案:

答案 0 :(得分:0)

我将假设您有一个日期范围,其中包含您需要避免循环的日期范围。然后,您可以利用SET DATEFIRST来改变一周的第一天:http://msdn.microsoft.com/en-us/library/ms181598(v=sql.105).aspx

然后,以下内容应返回正确的结果。以下是使用您的星期五示例。我还在列表中包含了“CustomerID”,以防您需要根据客户的不同而变化。

--Set the first day of the week as Friday.  For other customers with different week start days, vary this setting
set datefirst 5

select 
    1 AS CustomerID,  --or whatever you use as a customerid
    CalendarDate, 
    dateadd(dd, (-1 * datepart(dw, calendardate)) + 1, calendardate) as WeekBeginDate,
    dateadd(dd, (7 - datepart(dw, calendardate)), calendardate) as WeekEndDate,
    datename(dw, calendardate) as DayofWeek,
    datepart(wk, dateadd(dd, (-1 * datepart(dw, calendardate)) + 1, calendardate)) - 1 as Week No,
    datepart(yyyy, dateadd(dd, (-1 * datepart(dw, calendardate)) + 1, calendardate)) as WeekYear
FROM
    dates  --my dates table
where
    calendardate between '12/28/12' and '1/5/14'

答案 1 :(得分:0)

要获取播种的所有日期,您可以使用以下内容:

Select DateAdd (D, ROW_NUMBER() Over (Order By C1.Ordinal_Position), '12/31/1999') DateValue
From INFORMATION_SCHEMA.COLUMNS C1, INFORMATION_SCHEMA.COLUMNS C2

如果在列数太少的数据库中运行上述查询,则将FROM更改为。笛卡尔积FTW

From INFORMATION_SCHEMA.COLUMNS C1, INFORMATION_SCHEMA.COLUMNS C2, 
     INFORMATION_SCHEMA.COLUMNS C3, INFORMATION_SCHEMA.COLUMNS C4

现在,您需要将一周中的不同日期作为第一天。请阅读SET DATEFIRST。这使您可以将特定会话的第一天设置为TSQL。

然后,您可以使用DATEPART获取所需的其他列。

将三者结合起来得到答案。我将向您展示如何使其工作 - 您可以使用DATEADD查询以获取周开始和周末值,并使用DATEPART获取周年和年N-棕土

SET DATEFIRST 3 -- put your corresponding day here

;With AllDates AS
(
Select 
    DateAdd (D, ROW_NUMBER() Over (Order By C1.Ordinal_Position), '12/31/1999') DateValue
From INFORMATION_SCHEMA.COLUMNS C1
),
AllDatesWithWeekDayNumber AS
(
Select 
    DateValue, 
    DatePart (weekday, DateValue) WeekDayNumber
From AllDates
)
Select * From AllDatesWithWeekDayNumber