Labor Day Vs. Thanksgiving - sql-server

I am creating a calendar table for my warehouse. I will use this as a foreign key for all the date fields.
The code shown below creates the table and populates it. I was able to figure out how to find Memorial Day (last Monday of May) and Labor Day (first Monday of September).
SET NOCOUNT ON
DROP Table dbo.Calendar
GO
Create Table dbo.Calendar
(
CalendarId Integer NOT NULL,
DateValue Date NOT NULL,
DayNumberOfWeek Integer NOT NULL,
NameOfDay VarChar (10) NOT NULL,
NameOfMonth VarChar (10) NOT NULL,
WeekOfYear Integer NOT NULL,
JulianDay Integer NOT NULL,
USAIsBankHoliday Bit NOT NULL,
USADayName VarChar (100) NULL,
)
ALTER TABLE dbo.Calendar ADD CONSTRAINT
DF_Calendar_USAIsBankHoliday DEFAULT 0 FOR USAIsBankHoliday
GO
ALTER TABLE dbo.Calendar ADD CONSTRAINT
DF_Calendar_USADayName DEFAULT '' FOR USADayName
GO
Declare #StartDate DateTime = '01/01/2000'
Declare #EndDate DateTime = '01/01/2020'
While #StartDate < #EndDate
Begin
INSERT INTO dbo.Calendar
(
CalendarId,
DateValue,
WeekOfYear,
DayNumberOfWeek,
NameOfDay,
NameOfMonth,
JulianDay
)
Values
(
YEAR (#StartDate) * 10000 + MONTH (#StartDate) * 100 + Day (#StartDate), --CalendarId
#StartDate, -- DateValue
DATEPART (ww, #StartDate), -- WeekOfYear
DATEPART (dw, #StartDate), -- DayNumberOfWeek
DATENAME (dw, #StartDate), -- NameOfDay
DATENAME (M, #StartDate), -- NameOfMonth
DATEPART (dy, #StartDate) -- JulianDay
)
Set #StartDate += 1
End
--=========================== Weekends
-- saturday and sunday
UPDATE dbo.Calendar SET USAIsBankHoliday = 1, USADayName += 'Weekend, ' WHERE DayNumberOfWeek IN (1, 7)
--=========================== Bank Holidays
-- new years day
UPDATE dbo.Calendar SET USAIsBankHoliday = 1, USADayName += 'New Year''s Day, ' WHERE (CalendarId % 2000) IN (101)
-- memorial day (last Monday in May)
UPDATE dbo.Calendar
SET USAIsBankHoliday = 1,
USADayName += 'Memorial Day, '
WHERE 1=1
AND CalendarId IN
(
SELECT MAX (CalendarId)
FROM dbo.Calendar
WHERE MONTH (DateValue) = 5
AND DATEPART (DW, DateValue)=2
GROUP BY YEAR (datevalue)
)
-- independence day
UPDATE dbo.Calendar SET USAIsBankHoliday = 1, USADayName += 'Independence Day, ' WHERE (CalendarId % 2000) IN (704)
-- labor day (first Monday in September)
UPDATE dbo.Calendar
SET USAIsBankHoliday = 1,
USADayName += 'Labor Day, '
WHERE 1=1
AND CalendarId IN
(
SELECT MIN (CalendarId)
FROM dbo.Calendar
WHERE MONTH (DateValue) = 9
AND DATEPART (DW, DateValue)=2
GROUP BY YEAR (datevalue)
)
-- thanksgiving day (fourth Thursday in November)
UPDATE dbo.Calendar
SET USAIsBankHoliday = 1,
USADayName += 'Thanksgiving Day, '
WHERE 1=1
AND CalendarId IN
(
SELECT Max (CalendarId)
FROM dbo.Calendar
WHERE MONTH (DateValue) = 11
AND DATEPART (DW, DateValue)=5
GROUP BY YEAR (datevalue)
)
-- christmas
UPDATE dbo.Calendar SET USAIsBankHoliday = 1, USADayName += 'Christmas Day, ' WHERE (CalendarId % 2000) IN (1225)
--=========================== Other named days
-- new years eve
UPDATE dbo.Calendar SET USADayName += 'New Year''s Eve, ' WHERE (CalendarId % 2000) IN (1231)
-- christmas eve
UPDATE dbo.Calendar SET USADayName += 'Christmas Eve, ' WHERE (CalendarId % 2000) IN (1224)
-- boxing day
UPDATE dbo.Calendar SET USADayName += 'Boxing Day, ' WHERE (CalendarId % 2000) IN (1226)
--=========================== Remove trailing comma
UPDATE dbo.Calendar SET USADayName = SubString (USADayName, 1, LEN (USADayName) -1) WHERE LEN (USADayName) > 2
SELECT * FROM dbo.Calendar
I am stumped on figuring out Thanksgiving day (Thursday of the last FULL week of November).
Edit:
Correction based on comment by John Sauer
Thanksgiving is the fourth Thursday of November. However, upon checking several years, I find that it has turned out to also be the Thursday of the last full week of Nov.

I am stumped on figuring out Thanksgiving day (Thursday of the last FULL week of November).
Last Saturday of November - 2

Take the last Saturday of November, and subtract two days ;)

WITH cal AS
(
SELECT CAST('2009-30-11' AS DATETIME) AS cdate
UNION ALL
SELECT DATEADD(day, -1, cdate)
FROM cal
WHERE cdate >= '2009-01-11'
)
SELECT TOP 1 DATEADD(day, -2, cdate)
FROM cal
WHERE DATEPART(weekday, cdate) = 6
For the complex algorithms, it's sometimes better to find a matching date from a set than trying to construct an enormous single-value formula.
See this article in my blog for more detail:
Checking event dates

declare #thedate datetime
set #thedate = '11/24/2011'
select 1
where datepart(dw, #thedate) = 5 and datepart(m, #thedate) = 11 AND (datepart(dd, #thedate) - 21) between 0 and 6
Is the date a Thursday in November and is there less than a week remaining.

We use a neat Scalar-valued Function in our database that we can call to determine whether or not a date is a NonWorkDay. We manually add special dates for Observed Holidays.
Create Function:
CREATE FUNCTION [dbo].[NonWorkDay](#date as DATETIME)
RETURNS bit
AS
BEGIN
if #date is not null
begin
-- Weekends
if DATEPART(weekday, #date)=1 return 1 --Sunday
if DATEPART(weekday, #date)=7 return 1 --Saturday
-- JAN
if month(#date)=1 AND day(#date)=1 return 1 -- New Years Day
-- MAY
if month(#date)=5 and DATEPART(weekday, #date)=2 and day(#date)>24 and day(#date)<=31 return 1 --Memorial Day
-- JULY
if month(#date)=7 AND day(#date)=4 return 1 -- July 4th
-- SEP
if month(#date)=9 and DATEPART(weekday, #date)=2 and day(#date)<=7 return 1--Labor Day
-- NOV
if month(#date)=11 and DATEPART(weekday, #date)=5 and day(#date)>21 and day(#date)<=28 return 1--Thanksgiving
if month(#date)=11 and DATEPART(weekday, #date)=6 and day(#date)>22 and day(#date)<=29 return 1 -- Black Friday
-- DEC
if month(#date)=12 AND day(#date)=24 return 1 -- Christmas Eve
if month(#date)=12 AND day(#date)=25 return 1 -- Christmas
if month(#date)=12 AND day(#date)=31 return 1 -- NYE
-- Office Closed for Observed Holiday Dates
if month(#date)=7 AND day(#date)=5 AND year(#date)=2021 return 1 -- 4th of July Observed for 2021
if month(#date)=12 AND day(#date)=26 AND year(#date)=2022 return 1 -- Christmas Day observed for 2022
if month(#date)=1 AND day(#date)=2 AND year(#date)=2023 return 1 -- New Years Day observed for 2023
if month(#date)=7 AND day(#date)=3 AND year(#date)=2026 return 1 -- 4th of July Observed for 2026
if month(#date)=7 AND day(#date)=5 AND year(#date)=2027 return 1 -- 4th of July Observed for 2027
end
return 0
END
GO
Call Function:
IF [dbo].[NonWorkDay](Getdate())= 0 -- If (not a NonWorkDay -ie not Sat or Sun)

Related

Identify All Holiday Dates By Year using TSQL

I did a lot of searching for an easy solution to dynamically identify U.S. federal holidays by year. I wasn't able to find much information for the trickier holidays. Holidays like New Year's Day or Independence Day are easy to program as they are static. However, some are more difficult to identify programmatically such as Presidents' Day (3rd Monday in February) or Thanksgiving (4th Thursday in November).
I know this is an old question, but we have a sweet Scalar-valued Function that returns 1 if it's a holiday and 0 if it is not. We do have to manually add Observed Dates - We use the https://www.timeanddate.com/holidays/us/ to get the observed dates.
First, create the function:
USE [DATABASE]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[IsHoliday](#date as DATETIME)
RETURNS bit
AS
BEGIN
if #date is not null
begin
-- JAN
IF Month(#date)=1 AND day(#date)=1 return 1 -- New Years Day
IF Month(#date)=1 AND DATEPART(weekday, #date)=2 and day(#date)>14 and day(#date)<=21 return 1 -- Martin Luther King, Jr. Day
-- FEB
IF Month(#date)=2 AND DATEPART(weekday, #date)=1 and day(#date)<=7 return 1 -- Super Bowl Sunday
IF Month(#date)=2 AND day(#date)=14 return 1 -- Valentine's Day
IF Month(#date)=2 AND DATEPART(weekday, #date)=2 and day(#date)>14 and day(#date)<=21 return 1 -- Presidents' Day
-- MAR
IF Month(#date)=3 AND day(#date)=17 return 1 -- St Patrick's Day
-- MAY
IF Month(#date)=5 AND DATEPART(weekday, #date)=1 and day(#date)>7 and day(#date)<=14 return 1 -- Mother's day
IF Month(#date)=5 AND DATEPART(weekday, #date)=2 and day(#date)>24 and day(#date)<=31 return 1 --Memorial Day
-- JUN
IF Month(#date)=6 AND day(#date)=19 return 1 -- Juneteenth
IF Month(#date)=6 AND DATEPART(weekday, #date)=2 and day(#date)>14 and day(#date)<=21 return 1 --Father's Day
-- JUL
IF Month(#date)=7 AND day(#date)=4 return 1 -- July 4th
-- SEP
IF Month(#date)=9 AND DATEPART(weekday, #date)=2 and day(#date)<=7 return 1--Labor Day
-- OCT
IF Month(#date)=10 AND DATEPART(weekday, #date)=2 and day(#date)>7 and day(#date)<=14 return 1 --Columbus Day
IF Month(#date)=10 AND day(#date)=31 return 1 -- Halloween
-- NOV
IF Month(#date)=11 AND day(#date)=11 return 1 -- Veteran's Day
IF Month(#date)=11 AND DATEPART(weekday, #date)=5 and day(#date)>21 and day(#date)<=28 return 1 --Thanksgiving
-- DEC
IF Month(#date)=12 AND day(#date)=24 return 1 -- Christmas Eve
IF Month(#date)=12 AND day(#date)=25 return 1 -- Christmas Day
IF Month(#date)=12 AND day(#date)=31 return 1 -- NYE
-- Observed Dates
if month(#date)=1 AND day(#date)=2 AND year(#date)=2017 return 1 -- New Years Day observed for 2017
if month(#date)=11 AND day(#date)=10 AND year(#date)=2017 return 1 -- Veteran's Day observed for 2017
if month(#date)=11 AND day(#date)=12 AND year(#date)=2018 return 1 -- Veteran's Day observed for 2018
if month(#date)=7 AND day(#date)=3 AND year(#date)=2020 return 1 -- 4th of July Observed for 2021
if month(#date)=6 AND day(#date)=18 AND year(#date)=2021 return 1 -- Juneteenth observed for 2021
if month(#date)=7 AND day(#date)=5 AND year(#date)=2021 return 1 -- 4th of July Observed for 2021
if month(#date)=6 AND day(#date)=20 AND year(#date)=2022 return 1 -- Juneteenth observed for 2022
if month(#date)=12 AND day(#date)=26 AND year(#date)=2022 return 1 -- Christmas Day observed for 2022
if month(#date)=1 AND day(#date)=2 AND year(#date)=2023 return 1 -- New Years Day observed for 2023
if month(#date)=11 AND day(#date)=10 AND year(#date)=2023 return 1 -- Veteran's Day observed for 2023
if month(#date)=7 AND day(#date)=3 AND year(#date)=2026 return 1 -- 4th of July Observed for 2026
if month(#date)=6 AND day(#date)=18 AND year(#date)=2027 return 1 -- Juneteenth observed for 2027
if month(#date)=7 AND day(#date)=5 AND year(#date)=2027 return 1 -- 4th of July Observed for 2027
if month(#date)=11 AND day(#date)=10 AND year(#date)=2028 return 1 -- Veteran's Day observed for 2028
if month(#date)=11 AND day(#date)=12 AND year(#date)=2029 return 1 -- Veteran's Day observed for 2029
end
return 0
END
GO
Then call the function:
SELECT dbo.[IsHoliday](GETDATE())
SELECT dbo.[IsHoliday]('2021-07-05 09:20:51.270')
Here is the solution I came up with.
I created a table variable to store the entire years dates:
DECLARE #DateTable TABLE
(
dtDate DATE,
dtMonth VARCHAR(10),
dtDayName VARCHAR(10),
dtDayRank INT
);
Populated first 3 columns of the #DateTable:
DECLARE #Year CHAR(4), #CurrentDate DATE
SET #Year = '2018'
SET #CurrentDate = CAST(#Year + '0101' AS DATE)
WHILE #CurrentDate <= CAST(#Year + '1231' AS DATE)
BEGIN
INSERT INTO #DateTable (dtDate, dtMonth, dtDayName)
VALUES (#CurrentDate, DATENAME(mm, #CurrentDate), DATENAME(dw, #CurrentDate))
SET #CurrentDate = DATEADD(dd, 1, #CurrentDate)
END;
Once I had the table populated, I ranked the rows and updated the table:
UPDATE #DateTable
SET dtDayRank = rankdates.DayRank
FROM #DateTable datatable
INNER JOIN (
SELECT
dtDate,
DayRank = RANK() OVER (PARTITION BY dtMonth, dtDayName ORDER BY dtDate) -- rank each DayOfWeek in order
FROM #DateTable
) rankdates ON datatable.dtDate = rankdates.dtDate;
Sample Output from #DateTable
Once I had the #DateTable populated, I could use logic to identify specific days.
SELECT
HolidayName = 'Presidents'' Day',
ObservedDayOfWeek = dtDayName,
HolidayObservedDate = dtDate
FROM #DateTable
WHERE dtMonth = 'February'
AND dtDayName = 'Monday'
AND dtDayRank = 3
SELECT
HolidayName = 'Thanksgiving Day',
ObservedDayOfWeek = dtDayName,
HolidayObservedDate = dtDate
FROM #DateTable
WHERE dtMonth = 'November'
AND dtDayName = 'Thursday'
AND dtDayRank = 4
Output
I liked how this solution worked out because I can identify any date in the year by using a predicate equal to the month, day of the week and how many times this day of the week has occurred in this month. I made this into a stored procedure and table valued function so that I can run it by passing a year and it returns all holidays for that year.
Is this a good solution...is there an easier way?
There's some math you can use to make your SQL life easier e.g. 3rd Monday in February mathematically has to be between the 15th and the 21st (the earliest 3rd Monday has 14 days before it; the latest 3rd Monday can have no more than 20 days before it). If you have a tally table, it will be pretty easy to find all the dates. Here's how you can do it for president's day
with t1 as
(SELECT 1 num
FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1)) subTable(n)
),
TallyTable as
(
SELECT TOP 10000 ROW_NUMBER() OVER (ORDER BY (SELECT 1)) n
FROM t1 a
CROSS JOIN t1 b
CROSS JOIN t1 c
CROSS JOIN t1 d
CROSS JOIN t1 e
CROSS JOIN t1 f
),
DateTable as
(
SELECT DateAdd(day,n,'1/1/2018') DateValue
FROM TallyTable
)
SELECT *
FROM DateTable DT
WHERE DatePart(month,DT.DateValue) = 2 --February
AND DatePart(dw,DT.DateValue) = 2 --Monday
AND DatePart(day,DT.DateValue) BETWEEN 15 AND 21; --Day is between 15 and 21

Get date from week and year - date must be first day of the year - sql

I have a query that converts week and year to date.
But it returns the exact date.
But what i want is, I need the date to be such a day, that is same as the first day of the year.
dateadd (week, PromisedWeek-1, dateadd (year, PromisedYear-1900, 0)) - 4 -
datepart(dw, dateadd (week, PromisedWeek-1, dateadd (year, PromisedYear-1900, 0)) - 4) + 1
Hypothetical example.
My current query does is:
If week is 4 and year 2017, returns 26-Sun-2017
My need:
If week is 4 and year 2017 and January 1st was a Wednesday, its should return 29-Wednesday-2017.
Hoping that you guys get what I am trying to explain.
I need the query to return such a date which has the same day as that of the current year's 1st day.
Unless I'm reading this wrong, you're making things too hard on yourself. Just do this:
declare #year int; set #year = 2017;
declare #week int; set #week = 4;
select dateadd(week, #week, dateadd(year, #year - 1900, 0))
Result:
2017-01-29 00:00:00.000
The inner dateadd() gives you the first day of the requested year (Jan 1), regardless of weekday. If it's a Wednesday, you'll get a Wednesday. This year, it's Sunday. The outer dateadd() then adds full weeks to that, so you end up with the same day of the week, just like you asked.
If that's not what you want, please explain how it needs to be more complicated.
This is pretty easy if you have a calendar table. A calendar table is a table that contains every date and its parts for a given range. I created mine for 2010 to 2020 with this code:
declare #start_dt as date = '1/1/2010';
declare #end_dt as date = '1/1/2020';
declare #dates as table (
date_id date primary key,
date_year smallint,
date_month tinyint,
date_day tinyint,
weekday_id tinyint,
weekday_nm varchar(10),
month_nm varchar(10),
day_of_year smallint,
quarter_id tinyint,
first_day_of_month date,
last_day_of_month date,
start_dts datetime,
end_dts datetime
)
while #start_dt < #end_dt
begin
insert into #dates(
date_id, date_year, date_month, date_day,
weekday_id, weekday_nm, month_nm, day_of_year, quarter_id,
first_day_of_month, last_day_of_month,
start_dts, end_dts
)
values(
#start_dt, year(#start_dt), month(#start_dt), day(#start_dt),
datepart(weekday, #start_dt), datename(weekday, #start_dt), datename(month, #start_dt), datepart(dayofyear, #start_dt), datepart(quarter, #start_dt),
dateadd(day,-(day(#start_dt)-1),#start_dt), dateadd(day,-(day(dateadd(month,1,#start_dt))),dateadd(month,1,#start_dt)),
cast(#start_dt as datetime), dateadd(second,-1,cast(dateadd(day, 1, #start_dt) as datetime))
)
set #start_dt = dateadd(day, 1, #start_dt)
end
select *
into Calendar
from #dates
Once you have a calendar table you can query for the correct weekday in the PromisedWeek
declare #PromisedYear as numeric
declare #PromisedWeek as int
set #PromisedYear = 2017
set #PromisedWeek = 4
select concat(date_day, '-', weekday_nm, '-', #PromisedYear)
from Calendar as c
where
weekday_id =
(select weekday_ID
from Calendar
where date_year = #PromisedYear
and day_of_year = 1
)
and datepart(week, date_id) = #PromisedWeek
and date_year = #PromisedYear
Turns out that January 1st 2017 was a Sunday and the 4th Sunday in 2017 was January 22nd, so the return is 22-Sunday-2017

Creating a date from Week of month and Day of week in SQL server

I have to get/create date from the user input of week of month (week number in that month - 1st,2nd,3rd,4th and last) and day of week (sunday,monday..) in SQL server.
Examples:
4th Sunday of every month, Last Friday of every month, First Monday etc.
I was able to do it easily in .net but SQL server does seem limited in the date functions.
I am having to use lot of logic to get the date. To calculate the date using the above two parameters I had to use lot of datepart function.
Any suggestions on how to come up with the optimal SQL query for such a function?
I created a function other day for another OP GET Month, Quarter based on Work Week number
This function takes the current year as default it can be further modified to take Year as a parameter too.
an extension to that function can produce the results you are looking for ....
WITH X AS
(
SELECT TOP (CASE WHEN YEAR(GETDATE()) % 4 = 0 THEN 366 ELSE 365 END)-- to handle leap year
DATEADD(DAY
,ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1
, CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '0101' )
DayNumber
From master..spt_values
),DatesData AS(
SELECT DayNumber [Date]
,DATEPART(WEEKDAY,DayNumber) DayOfTheWeek
,DATEDIFF(WEEK,
DATEADD(WEEK,
DATEDIFF(WEEK, 0, DATEADD(MONTH,
DATEDIFF(MONTH, 0, DayNumber), 0)), 0)
, DayNumber- 1) + 1 WeekOfTheMonth
FROM X )
SELECT * FROM DatesData
WHERE DayOfTheWeek = 6 -- A function would expect these two parameters
AND WeekOfTheMonth = 4 -- #DayOfTheWeek and #WeekOfTheMonth
Here is a general formula:
declare #month as datetime --set to the first day of the month you wish to use
declare #week as int --1st, 2nd, 3rd...
declare #day as int --Day of the week (1=sunday, 2=monday...)
--Second monday in August 2015
set #month = '8/1/2015'
set #week = 2
set #day = 2
select dateadd(
day,
((7+#day) - datepart(weekday, #month)) % 7 + 7 * (#week-1),
#month
)
You can also find the last, 2nd to last... etc with this reverse formula:
--Second to last monday in August 2015
set #month = '8/1/2015'
set #week = 2
set #day = 2
select
dateadd(
day,
-((7+datepart(weekday, dateadd(month,1,#month)-1)-#day)) % 7 - 7 * (#week-1),
dateadd(month,1,#month)-1
)

Calendar table for Data Warehouse

For my data warehouse, I am creating a calendar table as follows:
SET NOCOUNT ON
DROP Table dbo.Calendar
GO
Create Table dbo.Calendar
(
CalendarId Integer NOT NULL,
DateValue Date NOT NULL,
DayNumberOfWeek Integer NOT NULL,
NameOfDay VarChar (10) NOT NULL,
NameOfMonth VarChar (10) NOT NULL,
WeekOfYear Integer NOT NULL,
JulianDay Integer NOT NULL,
USAIsBankHoliday Bit NOT NULL,
USADayName VarChar (100) NULL,
)
ALTER TABLE dbo.Calendar ADD CONSTRAINT
DF_Calendar_USAIsBankHoliday DEFAULT 0 FOR USAIsBankHoliday
GO
ALTER TABLE dbo.Calendar ADD CONSTRAINT
DF_Calendar_USADayName DEFAULT '' FOR USADayName
GO
Declare #StartDate DateTime = '01/01/2000'
Declare #EndDate DateTime = '01/01/2020'
While #StartDate < #EndDate
Begin
INSERT INTO dbo.Calendar
(
CalendarId,
DateValue,
WeekOfYear,
DayNumberOfWeek,
NameOfDay,
NameOfMonth,
JulianDay
)
Values
(
YEAR (#StartDate) * 10000 + MONTH (#StartDate) * 100 + Day (#StartDate), --CalendarId
#StartDate, -- DateValue
DATEPART (ww, #StartDate), -- WeekOfYear
DATEPART (dw, #StartDate), -- DayNumberOfWeek
DATENAME (dw, #StartDate), -- NameOfDay
DATENAME (M, #StartDate), -- NameOfMonth
DATEPART (dy, #StartDate) -- JulianDay
)
Set #StartDate += 1
End
--=========================== Weekends
-- saturday and sunday
UPDATE dbo.Calendar SET USAIsBankHoliday = 1, USADayName += 'Weekend, ' WHERE DayNumberOfWeek IN (1, 7)
--=========================== Bank Holidays
-- new years day
UPDATE dbo.Calendar SET USAIsBankHoliday = 1, USADayName += 'New Year''s Day, ' WHERE (CalendarId % 2000) IN (101)
-- memorial day (last Monday in May)
UPDATE dbo.Calendar
SET USAIsBankHoliday = 1,
USADayName += 'Memorial Day, '
WHERE 1=1
AND CalendarId IN
(
SELECT MAX (CalendarId)
FROM dbo.Calendar
WHERE MONTH (DateValue) = 5
AND DATEPART (DW, DateValue)=2
GROUP BY YEAR (datevalue)
)
-- independence day
UPDATE dbo.Calendar SET USAIsBankHoliday = 1, USADayName += 'Independence Day, ' WHERE (CalendarId % 2000) IN (704)
-- labor day (first Monday in September)
UPDATE dbo.Calendar
SET USAIsBankHoliday = 1,
USADayName += 'Labor Day, '
WHERE 1=1
AND CalendarId IN
(
SELECT MIN (CalendarId)
FROM dbo.Calendar
WHERE MONTH (DateValue) = 9
AND DATEPART (DW, DateValue)=2
GROUP BY YEAR (datevalue)
)
-- thanksgiving day (fourth Thursday in November)
UPDATE dbo.Calendar
SET USAIsBankHoliday = 1,
USADayName += 'Thanksgiving Day, '
WHERE 1=1
AND CalendarId IN
(
SELECT Max (CalendarId)-2
FROM dbo.Calendar
WHERE MONTH (DateValue) = 11
AND DATEPART (DW, DateValue)=7
GROUP BY YEAR (datevalue)
)
-- christmas
UPDATE dbo.Calendar SET USAIsBankHoliday = 1, USADayName += 'Christmas Day, ' WHERE (CalendarId % 2000) IN (1225)
--=========================== Other named days
-- new years eve
UPDATE dbo.Calendar SET USADayName += 'New Year''s Eve, ' WHERE (CalendarId % 2000) IN (1231)
-- black friday (day after thanksgiving day)
UPDATE dbo.Calendar SET USADayName += 'Black Friday, ' WHERE CalendarId IN (SELECT CalendarId+1 From dbo.Calendar Where USADayName like '%Thanksgiving%')
-- christmas eve
UPDATE dbo.Calendar SET USADayName += 'Christmas Eve, ' WHERE (CalendarId % 2000) IN (1224)
-- boxing day
UPDATE dbo.Calendar SET USADayName += 'Boxing Day, ' WHERE (CalendarId % 2000) IN (1226)
--=========================== Remove trailing comma
UPDATE dbo.Calendar SET USADayName = SubString (USADayName, 1, LEN (USADayName) -1) WHERE LEN (USADayName) > 2
SELECT * FROM dbo.Calendar
Here is the output of this command
I have seen similar structures implemented in various flavours by data architects.
My question is: What other data warehousing / dimension style useful information can I add to this table structure?
Quarter
Year
Financial/Accounting Year
Financial/Accounting Quarter
isWeekend
isWeekday
isWorkDay
WeekId (weeks since start of year)
isLastDayofMonth
DaysSince (e.g. days since 1/1/2000)
This is my list of possible columns in calendar dimension:
Key
Date
Is Yesterday
Is Today
Is Tomorrow
Day of Year
Day of Halfyear
Day of Quarter
Day of Month
Day of Week
Day of Week Short Name
Day of Week Short Name CS
Day of Week Long Name
Day of Week Long Name CS
Days in Week
Days in Month
Days in Quarter
Days in Halfyear
Days in Year
Reverse Day of Week
Reversse Day of Month
Reverse Day of Quarter
Reverse Day of Halfyear
Reverse Day of Year
Is Last 7 days
Is Last 14 days
Is Last 30 days
Is Last 90 Days
Is Last 180 Days
Is Last 365 Days
Is Weekday
Is Weekend
Workday of Week
Workday of Month
Workday of Quarter
Workday of Halfyear
Workday of Year
Reverse Workday of Week
Reverse Workday of Month
Reverse Workday of Quarter
Reverse Workday of Halfyear
Reverse Workday of Year
Workdays in Week
Workdays in Month
Workdays in Quarter
Workdays in Halfyear
Workdays in Year
Is Last Workday in Week
Is Last Workday in Month
Is Workday
Is Holiday
Is Future
Is Past
Is Previous Month
Is Current Month
Is Following Month
Is Month to Date
Is Beginning of Month
Is End of Month
Is Past Month
Beginning of Month
End of Month
Month Number
Month Name Long
Month Name Long CS
Month Name Short
Month Name Short CS
Month of Quarter
Month of Halfyear
Is Previous Week
Is Current Week
Is Following Week
Is Week to Date
Is Beginning of Week
Is End of Week
Is Past Week
Beginning of Week
End of Week
Week Number
Week Name Long
Week Name Short
Week of Month
Is Previous Quarter
Is Current Quarter
Is Following Quarter
Is Quarter to Date
Is Beginning of Quarter
Is End of Quarter
Is Past Quarter
Beginning of Quarter
End of Quarter
Quarter Number
Quarter Name Long
Quarter Name Long CS
Quarter Name Short
Is Previous Halfyear
Is Current Halfyear
Is Following Halfyear
Is Halfyear to Date
Is Beginning of Halfyear
Is End of Halfyear
Is Past Halfyear
Beginning of Halfyear
End of Halfyear
Halfyear Number
Halfyear Name Long
Halfyear Name Long CS
Halfyear Name Short
Is Previous Year
Is Current Year
Is Following Year
Is Year to Date
Is Beginning of Year
Is End of Year
Is Past Year
Beginning of Year
End of Year
Year Number
Year Name Long
Year Name Short
Year Quarter Text
Year Month Day
Year Halfyear
Year Quarter
Year Month
Year Day of Year
Is Leap Year
Distance in Days from Today
Distance in Working Days from Today
Distance in Calendar Weeks from Today
Distance in Calendar Months from Today
Distance in Calendar Quarters from Today
Distance in Calendar Halfyears from Today
Distance in Calendar Years from Today
Nth Day of Week in Month
Reverse Nth Day of Week in Month
I created interactive spreadsheet where you can create your own time dimension for PostgreSQL database.
Well Raj More, Its a nice Post and very helpful script for Creating a calender,
The Other fields which you can include in the same table may be-
1) QuateroftheYear
2) IsWeekend
3) IsWeekday
quarter of year
year_quarter (2013-3)
month of year
year_month (2013-08)
week of year
week of month
day of year
day of quarter
day of month
day of week

How do I take a day of the year and 'bucket it' into weeks of the year in Microsoft SQL? Used in manufacturing scenarios for material requirements

I have a need to create a gross requirements report that takes how much supply and demand of a item in inventory from a start date onwards and 'buckets' it into different weeks of the year so that material planners know when they will need a item and if they have enough stock in inventory at that time.
As an example, today’s date (report date) is 8/27/08. The first step is to find the date for the Monday of the week the report date falls in. In this case, Monday would be 8/25/08. This becomes the first day of the first bucket. All transactions that fall before that are assigned to week #0 and will be summarized as the beginning balance for the report. The remaining buckets are calculated from that point. For the eighth bucket, there is no ending date so any transactions after that 8th bucket start date are considered week #8.
WEEK# START DATE END DATE
0.......None..........8/24/08
1.......8/25/08.......8/31/08
2.......9/1/08.........9/7/08
3.......9/8/08.........9/14/08
4.......9/15/08.......9/21/08
5.......9/22/08.......9/28/08
6.......9/29/08.......10/5/08
7.......10/06/08.....10/12/08
8.......10/13/08......None
How do I get the week #, start date, end date for a given date?
I've always found it easiest and most efficient (for SQL Server) to construct a table with one row for every week into the future through your domain horizon; and join to that (with a "WHERE GETDATE() >= MONDATE AND NOT EXISTS (SELECT 1 FROM table WHERE MONDATE < GETDATE())".
Anything you try to do with UDF's will be much less efficient and I find more difficult to use.
You can get Monday for any given date in a week as:
DATEADD(d, 1 - DATEPART(dw, #date), #date)
and you can write a stored procedure with the following body
-- find Monday at that week
DECLARE #currentDate SMALLDATETIME
SELECT #currentDate = DATEADD(d, 1 - DATEPART(dw, #date), #date)
-- create a table and insert the first record
DECLARE #weekTable TABLE (Id INT, StartDate SMALLDATETIME, EndDate SMALLDATETIME)
INSERT INTO #weekTable VALUES (0, NULL, #currentDate)
-- increment the date
SELECT #currentDate = DATEADD(d, 1, #currentDate)
-- iterate for 7 more weeks
DECLARE #id INT
SET #id = 1
WHILE #id < 8
BEGIN
INSERT INTO #weekTable VALUES (#id, #currentDate, DATEADD(d, 6, #currentDate))
SELECT #currentDate = DATEADD(ww, 1, #currentDate)
SET #id = #id + 1
END
-- add the last record
INSERT INTO #weekTable VALUES (8, #currentDate, NULL)
-- select the values
SELECT Id 'Week #', StartDate 'Start Date', EndDate 'End Date'
FROM #weekTable
When I pass
#date = '20080827'
to this procedure, I get the following
Week # Start Date End Date
0 NULL 2008-08-24 00:00:00
1 2008-08-25 00:00:00 2008-08-31 00:00:00
2 2008-09-01 00:00:00 2008-09-07 00:00:00
3 2008-09-08 00:00:00 2008-09-14 00:00:00
4 2008-09-15 00:00:00 2008-09-21 00:00:00
5 2008-09-22 00:00:00 2008-09-28 00:00:00
6 2008-09-29 00:00:00 2008-10-05 00:00:00
7 2008-10-06 00:00:00 2008-10-12 00:00:00
8 2008-10-13 00:00:00 NULL
--SQL sets the first day of the week as sunday and for our purposes we want it to be Monday.
--This command does that.
SET DATEFIRST 1
DECLARE
#ReportDate DATETIME,
#Weekday INTEGER,
#NumDaysToMonday INTEGER,
#MondayStartPoint DATETIME,
#MondayStartPointWeek INTEGER,
#DateToProcess DATETIME,
#DateToProcessWeek INTEGER,
#Bucket VARCHAR(50),
#DaysDifference INTEGER,
#BucketNumber INTEGER,
#NumDaysToMondayOfDateToProcess INTEGER,
#WeekdayOfDateToProcess INTEGER,
#MondayOfDateToProcess DATETIME,
#SundayOfDateToProcess DATETIME
SET #ReportDate = '2009-01-01'
print #ReportDate
SET #DateToProcess = '2009-01-26'
--print #DateToProcess
SET #Weekday = (select DATEPART ( dw , #ReportDate ))
--print #Weekday
--print DATENAME(dw, #ReportDate)
SET #NumDaysToMonday =
(SELECT
CASE
WHEN #Weekday = 1 THEN 0
WHEN #Weekday = 2 THEN 1
WHEN #Weekday = 3 THEN 2
WHEN #Weekday = 4 THEN 3
WHEN #Weekday = 5 THEN 4
WHEN #Weekday = 6 THEN 5
WHEN #Weekday = 7 THEN 6
END)
--print #NumDaysToMonday
SET #MondayStartPoint = (SELECT DATEADD (d , -1*#NumDaysToMonday, #ReportDate))
--print #MondayStartPoint
SET #DaysDifference = DATEDIFF ( dd , #MondayStartPoint , #DateToProcess )
--PRINT #DaysDifference
SET #BucketNumber = #DaysDifference/7
--print #BucketNumber
----Calculate the start and end dates of this bucket------
PRINT 'Start Of New Calc'
print #DateToProcess
SET #WeekdayOfDateToProcess = (select DATEPART ( dw , #DateToProcess ))
print #WeekdayOfDateToProcess
SET #NumDaysToMondayOfDateToProcess=
(SELECT
CASE
WHEN #WeekdayOfDateToProcess = 1 THEN 0
WHEN #WeekdayOfDateToProcess = 2 THEN 1
WHEN #WeekdayOfDateToProcess = 3 THEN 2
WHEN #WeekdayOfDateToProcess = 4 THEN 3
WHEN #WeekdayOfDateToProcess = 5 THEN 4
WHEN #WeekdayOfDateToProcess = 6 THEN 5
WHEN #WeekdayOfDateToProcess = 7 THEN 6
END)
print #NumDaysToMondayOfDateToProcess
SET #MondayOfDateToProcess = (SELECT DATEADD (d , -1*#NumDaysToMondayOfDateToProcess, #DateToProcess))
print #MondayOfDateToProcess ---This is the start week
SET #SundayOfDateToProcess = (SELECT DATEADD (d , 6, #MondayOfDateToProcess))
PRINT #SundayOfDateToProcess
The problem I see with the one bucket at a time approach is that its hard to make it scale,
If you join into a user defined function you will get better performance, you could use this a a starting point
Why not use a combination of DATEPART(year, date-column) and DATEPART(week, date-column) and group by these values. This works if the week in DATEPART is aligned on Mondays as ISO 8601 requires. In outline:
SELECT DATEPART(year, date_column) AS yyyy,
DATEPART(week, date_column) AS ww,
...other material as required...
FROM SomeTableOrOther
WHERE ...appropriate filters...
GROUP BY yyyy, ww -- ...and other columns as necessary...

Resources