-1

我正在尝试编写 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
4

2 回答 2

0

我将假设您有一个 Dates 表,其中包含您需要避免循环的日期范围。然后,您可以利用 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'
于 2013-07-08T17:48:45.160 回答
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 来获取 Start-Of-Week 和 End-Of-Week 值,并使用 DATEPART 来获取 Week-Of-Year 和 YearN-琥珀色

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
于 2013-07-08T17:56:28.823 回答